sub_dev.go 5.4 KB

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