sub_dev.go 5.4 KB

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