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