sub_dev.go 6.2 KB

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