sub_dev.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. server.Log.Infof("subDevMsg")
  89. if err != nil {
  90. server.Log.Infof("subDevMsg err:%v", err)
  91. return err
  92. }
  93. err = d.subscribeWithFunc(cli, TopicThing, func(ctx context.Context, topic string, payload []byte) error {
  94. return handle(ctx).Message(topic, payload)
  95. })
  96. if err != nil {
  97. return err
  98. }
  99. //err = d.subscribeWithFunc(cli, TopicConfig, func(ctx context.Context, topic string, payload []byte) error {
  100. // return handle(ctx).Message(topic, payload)
  101. //})
  102. //if err != nil {
  103. // return err
  104. //}
  105. err = d.subscribeWithFunc(cli, TopicOta, func(ctx context.Context, topic string, payload []byte) error {
  106. return handle(ctx).Message(topic, payload)
  107. })
  108. if err != nil {
  109. return err
  110. }
  111. //err = d.subscribeWithFunc(cli, TopicExt, func(ctx context.Context, topic string, payload []byte) error {
  112. // return handle(ctx).Message(topic, payload)
  113. //})
  114. //if err != nil {
  115. // return err
  116. //}
  117. //err = d.subscribeWithFunc(cli, TopicShadow, func(ctx context.Context, topic string, payload []byte) error {
  118. // return handle(ctx).Message(topic, payload)
  119. //})
  120. //
  121. //if err != nil {
  122. // return err
  123. //}
  124. //err = d.subscribeWithFunc(cli, TopicGateway, func(ctx context.Context, topic string, payload []byte) error {
  125. // return handle(ctx).Message(topic, payload)
  126. //})
  127. //if err != nil {
  128. // return err
  129. //}
  130. //err = d.subscribeWithFunc(cli, TopicSDKLog, func(ctx context.Context, topic string, payload []byte) error {
  131. // return handle(ctx).Message(topic, payload)
  132. //})
  133. //if err != nil {
  134. // return err
  135. //}
  136. err = d.subscribeWithFunc(cli, TopicEvent, func(ctx context.Context, topic string, payload []byte) error {
  137. return handle(ctx).Message(topic, payload)
  138. })
  139. if err != nil {
  140. return err
  141. }
  142. return nil
  143. }
  144. func (d *MqttClient) subConnectStatus(handle Handle) func(ctx context.Context, topic string, payload []byte) error {
  145. return func(ctx context.Context, topic string, payload []byte) error {
  146. var (
  147. msg ConnectMsg
  148. err error
  149. )
  150. err = json.Unmarshal(payload, &msg)
  151. if err != nil {
  152. server.Log.Errorf("json.Unmarshal err :%s, topic :%v", err, topic)
  153. return err
  154. }
  155. status := protocol.DevConnectStatus{
  156. DeviceCode: msg.Username,
  157. DeviceId: msg.Clientid,
  158. ClientIp: msg.Ipaddress,
  159. }
  160. if strings.HasSuffix(topic, "/connected") || strings.HasSuffix(topic, "/subscribed") {
  161. status.Action = "LOGIN"
  162. return handle(ctx).Connected(&status)
  163. } else {
  164. status.Action = "LOGOUT"
  165. status.Reason = msg.Reason
  166. return handle(ctx).Disconnected(&status)
  167. }
  168. }
  169. }
  170. func (d *MqttClient) subscribeWithFunc(cli mqtt.Client, topic string,
  171. handle func(ctx context.Context, topic string, payload []byte) error) error {
  172. return d.client.Subscribe(cli, topic, 1, func(c mqtt.Client, message mqtt.Message) {
  173. _ = d.handlePool.Add(func() {
  174. go func() {
  175. ctx, cancel := context.WithTimeout(context.Background(), 50*time.Second)
  176. defer cancel()
  177. Recover(ctx)
  178. err := handle(ctx, message.Topic(), message.Payload())
  179. if err != nil {
  180. server.Log.Errorf("handle failure err :%s, topic :%v", err, topic)
  181. }
  182. }()
  183. })
  184. })
  185. }
  186. func Recover(ctx context.Context) {
  187. if p := recover(); p != nil {
  188. HandleThrow(ctx, p)
  189. }
  190. }
  191. func HandleThrow(ctx context.Context, p any) {
  192. pc := make([]uintptr, 1)
  193. runtime.Callers(3, pc)
  194. f := runtime.FuncForPC(pc[0])
  195. server.Log.Errorf("HandleThrow|func=%s|error=%#v|stack=%s\n", f, p, string(debug.Stack()))
  196. //os.Exit(-1)
  197. }