sub_dev.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. }
  44. func (d *MqttClient) PublishToMsgToDev(topic string, payload []byte) error {
  45. return d.client.Publish(topic, 1, false, payload)
  46. }
  47. const (
  48. ShareSubTopicPrefix = "$share/sparrow.agent/"
  49. TopicConnectStatus = ShareSubTopicPrefix + "$SYS/brokers/+/clients/#"
  50. TopicThing = ShareSubTopicPrefix + protocol.TopicHeadThing + "/up/#"
  51. TopicOta = ShareSubTopicPrefix + protocol.TopicHeadOta + "/up/#"
  52. TopicConfig = ShareSubTopicPrefix + protocol.TopicHeadConfig + "/up/#"
  53. TopicSDKLog = ShareSubTopicPrefix + protocol.TopicHeadLog + "/up/#"
  54. TopicShadow = ShareSubTopicPrefix + protocol.TopicHeadShadow + "/up/#"
  55. TopicGateway = ShareSubTopicPrefix + protocol.TopicHeadGateway + "/up/#"
  56. TopicExt = ShareSubTopicPrefix + protocol.TopicHeadExt + "/up/#"
  57. )
  58. func NewSubDev(conf *client.MqttConfig) (SubDev, error) {
  59. return newEmqClient(conf)
  60. }
  61. func newEmqClient(conf *client.MqttConfig) (SubDev, error) {
  62. mc, err := client.NewMqttClient(conf)
  63. if err != nil {
  64. return nil, err
  65. }
  66. return &MqttClient{
  67. client: mc,
  68. handlePool: grpool.New(1000),
  69. }, nil
  70. }
  71. func (d *MqttClient) SubDevMsg(handle Handle) error {
  72. err := d.subDevMsg(nil, handle)
  73. if err != nil {
  74. return err
  75. }
  76. client.SetMqttSetOnConnectHandler(func(cli mqtt.Client) {
  77. err := d.subDevMsg(cli, handle)
  78. if err != nil {
  79. server.Log.Errorf("mqttSetOnConnectHandler.subDevMsg err:%v", err)
  80. }
  81. })
  82. return nil
  83. }
  84. func (d *MqttClient) subDevMsg(cli mqtt.Client, handle Handle) error {
  85. err := d.subscribeWithFunc(cli, TopicConnectStatus, d.subConnectStatus(handle))
  86. if err != nil {
  87. return err
  88. }
  89. err = d.subscribeWithFunc(cli, TopicThing, func(ctx context.Context, topic string, payload []byte) error {
  90. return handle(ctx).Message(topic, payload)
  91. })
  92. if err != nil {
  93. return err
  94. }
  95. err = d.subscribeWithFunc(cli, TopicConfig, func(ctx context.Context, topic string, payload []byte) error {
  96. return handle(ctx).Message(topic, payload)
  97. })
  98. if err != nil {
  99. return err
  100. }
  101. err = d.subscribeWithFunc(cli, TopicOta, func(ctx context.Context, topic string, payload []byte) error {
  102. return handle(ctx).Message(topic, payload)
  103. })
  104. if err != nil {
  105. return err
  106. }
  107. err = d.subscribeWithFunc(cli, TopicExt, func(ctx context.Context, topic string, payload []byte) error {
  108. return handle(ctx).Message(topic, payload)
  109. })
  110. if err != nil {
  111. return err
  112. }
  113. err = d.subscribeWithFunc(cli, TopicShadow, func(ctx context.Context, topic string, payload []byte) error {
  114. return handle(ctx).Message(topic, payload)
  115. })
  116. if err != nil {
  117. return err
  118. }
  119. err = d.subscribeWithFunc(cli, TopicGateway, func(ctx context.Context, topic string, payload []byte) error {
  120. return handle(ctx).Message(topic, payload)
  121. })
  122. if err != nil {
  123. return err
  124. }
  125. err = d.subscribeWithFunc(cli, TopicSDKLog, func(ctx context.Context, topic string, payload []byte) error {
  126. return handle(ctx).Message(topic, payload)
  127. })
  128. if err != nil {
  129. return err
  130. }
  131. return nil
  132. }
  133. func (d *MqttClient) subConnectStatus(handle Handle) func(ctx context.Context, topic string, payload []byte) error {
  134. return func(ctx context.Context, topic string, payload []byte) error {
  135. var (
  136. msg ConnectMsg
  137. err error
  138. )
  139. err = json.Unmarshal(payload, &msg)
  140. if err != nil {
  141. server.Log.Errorf("json.Unmarshal err :%s, topic :%v", err, topic)
  142. return err
  143. }
  144. status := protocol.DevConnectStatus{
  145. DeviceCode: msg.Username,
  146. DeviceId: msg.Clientid,
  147. ClientIp: msg.Ipaddress,
  148. }
  149. if strings.HasSuffix(topic, "/connected") {
  150. status.Action = "LOGIN"
  151. return handle(ctx).Connected(&status)
  152. } else {
  153. status.Action = "LOGOUT"
  154. status.Reason = msg.Reason
  155. return handle(ctx).Disconnected(&status)
  156. }
  157. }
  158. }
  159. func (d *MqttClient) subscribeWithFunc(cli mqtt.Client, topic string,
  160. handle func(ctx context.Context, topic string, payload []byte) error) error {
  161. return d.client.Subscribe(cli, topic, 1, func(c mqtt.Client, message mqtt.Message) {
  162. _ = d.handlePool.Add(func() {
  163. go func() {
  164. ctx, cancel := context.WithTimeout(context.Background(), 50*time.Second)
  165. defer cancel()
  166. Recover(ctx)
  167. err := handle(ctx, message.Topic(), message.Payload())
  168. if err != nil {
  169. server.Log.Errorf("handle failure err :%s, topic :%v", err, topic)
  170. }
  171. }()
  172. })
  173. })
  174. }
  175. func Recover(ctx context.Context) {
  176. if p := recover(); p != nil {
  177. HandleThrow(ctx, p)
  178. }
  179. }
  180. func HandleThrow(ctx context.Context, p any) {
  181. pc := make([]uintptr, 1)
  182. runtime.Callers(3, pc)
  183. f := runtime.FuncForPC(pc[0])
  184. server.Log.Errorf("HandleThrow|func=%s|error=%#v|stack=%s\n", f, p, string(debug.Stack()))
  185. //os.Exit(-1)
  186. }