sub_dev.go 6.2 KB

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