sub_dev.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. }
  18. type ConnectMsg struct {
  19. Username string `json:"username"`
  20. Ts int64 `json:"ts"`
  21. Sockport int `json:"sockport"`
  22. ProtoVer int `json:"proto_ver"`
  23. ProtoName string `json:"proto_name"`
  24. Keepalive int `json:"keepalive"`
  25. Ipaddress string `json:"ipaddress"`
  26. ExpiryInterval int `json:"expiry_interval"`
  27. ConnectedAt int64 `json:"connected_at"`
  28. Connack int `json:"connack"`
  29. Clientid string `json:"clientid"`
  30. Reason string `json:"reason"`
  31. CleanStart bool `json:"clean_start"`
  32. }
  33. type Handle func(ctx context.Context) DevSubHandle
  34. type DevSubHandle interface {
  35. Message(topic string, payload []byte) error
  36. Connected(status *protocol.DevConnectStatus) error
  37. Disconnected(status *protocol.DevConnectStatus) error
  38. }
  39. type MqttClient struct {
  40. client *client.MqttClient
  41. handlePool *grpool.Pool
  42. }
  43. const (
  44. ShareSubTopicPrefix = "$share/sparrow.agent/"
  45. TopicConnectStatus = ShareSubTopicPrefix + "$SYS/brokers/+/clients/#"
  46. TopicThing = ShareSubTopicPrefix + protocol.TopicHeadThing + "/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. handlePool: grpool.New(1000),
  65. }, nil
  66. }
  67. func (d *MqttClient) SubDevMsg(handle Handle) error {
  68. err := d.subDevMsg(nil, handle)
  69. if err != nil {
  70. return err
  71. }
  72. client.SetMqttSetOnConnectHandler(func(cli mqtt.Client) {
  73. err := d.subDevMsg(cli, handle)
  74. if err != nil {
  75. server.Log.Errorf("mqttSetOnConnectHandler.subDevMsg err:%v", err)
  76. }
  77. })
  78. return nil
  79. }
  80. func (d *MqttClient) subDevMsg(cli mqtt.Client, handle Handle) error {
  81. err := d.subscribeWithFunc(cli, TopicConnectStatus, d.subConnectStatus(handle))
  82. if err != nil {
  83. return err
  84. }
  85. err = d.subscribeWithFunc(cli, TopicThing, func(ctx context.Context, topic string, payload []byte) error {
  86. return handle(ctx).Message(topic, payload)
  87. })
  88. if err != nil {
  89. return err
  90. }
  91. err = d.subscribeWithFunc(cli, TopicConfig, 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, TopicOta, 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, TopicExt, 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, TopicShadow, 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, TopicGateway, 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, TopicSDKLog, 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. return nil
  128. }
  129. func (d *MqttClient) subConnectStatus(handle Handle) func(ctx context.Context, topic string, payload []byte) error {
  130. return func(ctx context.Context, topic string, payload []byte) error {
  131. var (
  132. msg ConnectMsg
  133. err error
  134. )
  135. err = json.Unmarshal(payload, &msg)
  136. if err != nil {
  137. server.Log.Errorf("json.Unmarshal err :%s, topic :%v", err, topic)
  138. return err
  139. }
  140. status := protocol.DevConnectStatus{
  141. DeviceCode: msg.Username,
  142. DeviceId: msg.Clientid,
  143. ClientIp: msg.Ipaddress,
  144. }
  145. if strings.HasSuffix(topic, "/connected") {
  146. status.Action = "LOGIN"
  147. return handle(ctx).Connected(&status)
  148. } else {
  149. status.Action = "LOGOUT"
  150. status.Reason = msg.Reason
  151. return handle(ctx).Disconnected(&status)
  152. }
  153. }
  154. }
  155. func (d *MqttClient) subscribeWithFunc(cli mqtt.Client, topic string,
  156. handle func(ctx context.Context, topic string, payload []byte) error) error {
  157. return d.client.Subscribe(cli, topic, 1, func(c mqtt.Client, message mqtt.Message) {
  158. _ = d.handlePool.Add(func() {
  159. go func() {
  160. ctx, cancel := context.WithTimeout(context.Background(), 50*time.Second)
  161. defer cancel()
  162. Recover(ctx)
  163. err := handle(ctx, message.Topic(), message.Payload())
  164. if err != nil {
  165. server.Log.Errorf("handle failure err :%s, topic :%v", err, topic)
  166. }
  167. }()
  168. })
  169. })
  170. }
  171. func Recover(ctx context.Context) {
  172. if p := recover(); p != nil {
  173. HandleThrow(ctx, p)
  174. }
  175. }
  176. func HandleThrow(ctx context.Context, p any) {
  177. pc := make([]uintptr, 1)
  178. runtime.Callers(3, pc)
  179. f := runtime.FuncForPC(pc[0])
  180. server.Log.Errorf("HandleThrow|func=%s|error=%#v|stack=%s\n", f, p, string(debug.Stack()))
  181. //os.Exit(-1)
  182. }