sub_dev.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. package main
  2. import (
  3. "context"
  4. "encoding/json"
  5. mqtt "github.com/eclipse/paho.mqtt.golang"
  6. "github.com/gogf/gf/os/grpool"
  7. "runtime"
  8. "runtime/debug"
  9. "sparrow/pkg/protocol"
  10. "sparrow/pkg/server"
  11. "sparrow/services/emqx-agent/client"
  12. "strings"
  13. "time"
  14. )
  15. type SubDev interface {
  16. SubDevMsg(handle Handle) error
  17. PublishToMsgToDev(topic string, payload []byte) error
  18. }
  19. type ConnectMsg struct {
  20. Username string `json:"username"`
  21. Ts int64 `json:"ts"`
  22. Sockport int `json:"sockport"`
  23. ProtoVer int `json:"proto_ver"`
  24. ProtoName string `json:"proto_name"`
  25. Keepalive int `json:"keepalive"`
  26. Ipaddress string `json:"ipaddress"`
  27. ExpiryInterval int `json:"expiry_interval"`
  28. ConnectedAt int64 `json:"connected_at"`
  29. Connack int `json:"connack"`
  30. Clientid string `json:"clientid"`
  31. Reason string `json:"reason"`
  32. CleanStart bool `json:"clean_start"`
  33. }
  34. type Handle func(ctx context.Context) DevSubHandle
  35. type DevSubHandle interface {
  36. Message(topic string, payload []byte) error
  37. Connected(status *protocol.DevConnectStatus) error
  38. Disconnected(status *protocol.DevConnectStatus) error
  39. }
  40. type MqttClient struct {
  41. client *client.MqttClient
  42. handlePool *grpool.Pool
  43. lockDevices map[string]*Device
  44. }
  45. func (d *MqttClient) PublishToMsgToDev(topic string, payload []byte) error {
  46. return d.client.Publish(topic, 1, false, payload)
  47. }
  48. const (
  49. ShareSubTopicPrefix = "$share/sparrow.agent/"
  50. TopicConnectStatus = ShareSubTopicPrefix + "$SYS/brokers/+/clients/#"
  51. TopicThing = ShareSubTopicPrefix + protocol.TopicHeadThing + "/up/#"
  52. TopicOta = ShareSubTopicPrefix + protocol.TopicHeadOta + "/up/#"
  53. TopicConfig = ShareSubTopicPrefix + protocol.TopicHeadConfig + "/up/#"
  54. TopicSDKLog = ShareSubTopicPrefix + protocol.TopicHeadLog + "/up/#"
  55. TopicShadow = ShareSubTopicPrefix + protocol.TopicHeadShadow + "/up/#"
  56. TopicGateway = ShareSubTopicPrefix + protocol.TopicHeadGateway + "/up/#"
  57. TopicExt = ShareSubTopicPrefix + protocol.TopicHeadExt + "/up/#"
  58. TopicEvent = ShareSubTopicPrefix + protocol.TopicHeadEvent + "/up/#"
  59. )
  60. func NewSubDev(conf *client.MqttConfig) (SubDev, error) {
  61. return newEmqClient(conf)
  62. }
  63. func newEmqClient(conf *client.MqttConfig) (SubDev, error) {
  64. mc, err := client.NewMqttClient(conf)
  65. if err != nil {
  66. return nil, err
  67. }
  68. return &MqttClient{
  69. client: mc,
  70. handlePool: grpool.New(1000),
  71. }, nil
  72. }
  73. func (d *MqttClient) SubDevMsg(handle Handle) error {
  74. err := d.subDevMsg(nil, handle)
  75. if err != nil {
  76. return err
  77. }
  78. client.SetMqttSetOnConnectHandler(func(cli mqtt.Client) {
  79. err := d.subDevMsg(cli, handle)
  80. if err != nil {
  81. server.Log.Errorf("mqttSetOnConnectHandler.subDevMsg err:%v", err)
  82. }
  83. })
  84. return nil
  85. }
  86. func (d *MqttClient) subDevMsg(cli mqtt.Client, handle Handle) error {
  87. err := d.subscribeWithFunc(cli, TopicConnectStatus, d.subConnectStatus(handle))
  88. if err != nil {
  89. server.Log.Infof("subDevMsg err:%v", err)
  90. return err
  91. }
  92. err = d.subscribeWithFunc(cli, TopicThing, func(ctx context.Context, topic string, payload []byte) error {
  93. return handle(ctx).Message(topic, payload)
  94. })
  95. if err != nil {
  96. return err
  97. }
  98. //err = d.subscribeWithFunc(cli, TopicConfig, func(ctx context.Context, topic string, payload []byte) error {
  99. // return handle(ctx).Message(topic, payload)
  100. //})
  101. //if err != nil {
  102. // return err
  103. //}
  104. err = d.subscribeWithFunc(cli, TopicOta, func(ctx context.Context, topic string, payload []byte) error {
  105. return handle(ctx).Message(topic, payload)
  106. })
  107. if err != nil {
  108. return err
  109. }
  110. //err = d.subscribeWithFunc(cli, TopicExt, func(ctx context.Context, topic string, payload []byte) error {
  111. // return handle(ctx).Message(topic, payload)
  112. //})
  113. //if err != nil {
  114. // return err
  115. //}
  116. //err = d.subscribeWithFunc(cli, TopicShadow, func(ctx context.Context, topic string, payload []byte) error {
  117. // return handle(ctx).Message(topic, payload)
  118. //})
  119. //
  120. //if err != nil {
  121. // return err
  122. //}
  123. //err = d.subscribeWithFunc(cli, TopicGateway, func(ctx context.Context, topic string, payload []byte) error {
  124. // return handle(ctx).Message(topic, payload)
  125. //})
  126. //if err != nil {
  127. // return err
  128. //}
  129. //err = d.subscribeWithFunc(cli, TopicSDKLog, func(ctx context.Context, topic string, payload []byte) error {
  130. // return handle(ctx).Message(topic, payload)
  131. //})
  132. //if err != nil {
  133. // return err
  134. //}
  135. err = d.subscribeWithFunc(cli, TopicEvent, func(ctx context.Context, topic string, payload []byte) error {
  136. return handle(ctx).Message(topic, payload)
  137. })
  138. if err != nil {
  139. return err
  140. }
  141. return nil
  142. }
  143. func (d *MqttClient) subConnectStatus(handle Handle) func(ctx context.Context, topic string, payload []byte) error {
  144. return func(ctx context.Context, topic string, payload []byte) error {
  145. var (
  146. msg ConnectMsg
  147. err error
  148. )
  149. err = json.Unmarshal(payload, &msg)
  150. if err != nil {
  151. server.Log.Errorf("json.Unmarshal err :%s, topic :%v", err, topic)
  152. return err
  153. }
  154. status := protocol.DevConnectStatus{
  155. DeviceCode: msg.Username,
  156. DeviceId: msg.Clientid,
  157. ClientIp: msg.Ipaddress,
  158. }
  159. if strings.HasSuffix(topic, "/connected") || strings.HasSuffix(topic, "/subscribed") {
  160. status.Action = "LOGIN"
  161. return handle(ctx).Connected(&status)
  162. } else {
  163. status.Action = "LOGOUT"
  164. status.Reason = msg.Reason
  165. return handle(ctx).Disconnected(&status)
  166. }
  167. }
  168. }
  169. func (d *MqttClient) subscribeWithFunc(cli mqtt.Client, topic string,
  170. handle func(ctx context.Context, topic string, payload []byte) error) error {
  171. return d.client.Subscribe(cli, topic, 1, func(c mqtt.Client, message mqtt.Message) {
  172. _ = d.handlePool.Add(func() {
  173. go func() {
  174. ctx, cancel := context.WithTimeout(context.Background(), 50*time.Second)
  175. defer cancel()
  176. Recover(ctx)
  177. err := handle(ctx, message.Topic(), message.Payload())
  178. if err != nil {
  179. server.Log.Errorf("handle failure err :%s, topic :%v", err, topic)
  180. }
  181. }()
  182. })
  183. })
  184. }
  185. func Recover(ctx context.Context) {
  186. if p := recover(); p != nil {
  187. HandleThrow(ctx, p)
  188. }
  189. }
  190. func HandleThrow(ctx context.Context, p any) {
  191. pc := make([]uintptr, 1)
  192. runtime.Callers(3, pc)
  193. f := runtime.FuncForPC(pc[0])
  194. server.Log.Errorf("HandleThrow|func=%s|error=%#v|stack=%s\n", f, p, string(debug.Stack()))
  195. //os.Exit(-1)
  196. }