mqtt_broker_node.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. package nodes
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. MQTT "github.com/eclipse/paho.mqtt.golang"
  6. "github.com/gogf/gf/util/guid"
  7. "html/template"
  8. "sparrow/pkg/protocol"
  9. "sparrow/pkg/ruleEngine"
  10. "sparrow/pkg/server"
  11. "strings"
  12. "time"
  13. )
  14. const defaultTopicTemp = "/device_message/{{.VendorId}}/{{.DeviceId}}/{{.SubDeviceId}}"
  15. const defaultTimeout = 5
  16. // MQTTBrokerNode Publish incoming message payload to the topic of the configured MQTT broker with QoS AT_LEAST_ONCE.
  17. // In case of successful message publishing, original Message will be passed to the next nodes via Success chain,
  18. // otherwise Failure chain is used.
  19. type MQTTBrokerNode struct {
  20. mqttClient MQTT.Client
  21. config *MQTTBrokerNodeCfg
  22. }
  23. type MQTTBrokerNodeCfg struct {
  24. // can be a static string, or pattern that is resolved using Message Metadata properties. .
  25. // default topic device_message/{{.VendorId}}/{{.DeviceId}}
  26. TopicPattern string `json:"topic_pattern"`
  27. // MQTT broker host.
  28. Host string `json:"host"`
  29. // MQTT broker port.
  30. Port int `json:"port"`
  31. // timeout in seconds for connecting to MQTT broker.
  32. Timeout int `json:"timeout"`
  33. // optional client identifier used for connecting to MQTT broker. If not specified, default generated clientId will be used.
  34. ClientId string `json:"client_id"`
  35. // establishes a non persistent connection with the broker when enabled.
  36. ClearSession bool `json:"clear_session"`
  37. // enable/disable secure communication.
  38. SSLEnable bool `json:"ssl_enable"`
  39. // MQTT connection credentials. Can be either Anonymous, Basic or PEM.
  40. Credentials string `json:"credentials"` // Anonymous, Basic, PEM
  41. /*
  42. If PEM credentials type is selected, the following configuration should be provided:
  43. CA certificate file
  44. Certificate file
  45. Private key file
  46. Private key password
  47. */
  48. UserName string `json:"user_name"`
  49. Password string `json:"password"`
  50. }
  51. func (M *MQTTBrokerNode) Init(ctx ruleEngine.Context, config string) error {
  52. if config != "" {
  53. c := new(MQTTBrokerNodeCfg)
  54. err := json.Unmarshal([]byte(config), c)
  55. if err != nil {
  56. server.Log.Errorf("初始化失败:%s", err.Error())
  57. return err
  58. }
  59. M.config = c
  60. }
  61. if M.config.Timeout == 0 {
  62. M.config.Timeout = defaultTimeout
  63. }
  64. var opt MQTT.ClientOptions
  65. opt.ClientID = "MQTT_NODE_" + guid.S()
  66. opt.CleanSession = M.config.ClearSession
  67. opt.KeepAlive = 120
  68. opt.ConnectTimeout = time.Duration(M.config.Timeout) * time.Second
  69. switch M.config.Credentials {
  70. case "Basic":
  71. opt.Username = M.config.UserName
  72. opt.Password = M.config.Password
  73. default:
  74. }
  75. if M.config.ClientId != "" {
  76. opt.ClientID = M.config.ClientId
  77. }
  78. opt.AutoReconnect = true
  79. opt.MaxReconnectInterval = 10
  80. opt.AddBroker(fmt.Sprintf("tcp://%s:%d", M.config.Host, M.config.Port))
  81. c := MQTT.NewClient(&opt)
  82. M.mqttClient = c
  83. go func() {
  84. if token := c.Connect(); token.Wait() && token.Error() != nil {
  85. return
  86. }
  87. }()
  88. return nil
  89. }
  90. type MeteData struct {
  91. VendorId string
  92. DeviceId string
  93. SubDeviceId string
  94. }
  95. func (M *MQTTBrokerNode) OnMessage(ctx ruleEngine.Context, message *protocol.Message) error {
  96. var meteData MeteData
  97. if v, ok := message.MetaData["vendor_id"]; ok {
  98. meteData.VendorId = v.(string)
  99. }
  100. if v, ok := message.MetaData["device_id"]; ok {
  101. meteData.DeviceId = v.(string)
  102. }
  103. if v, ok := message.MetaData["sub_device_id"]; ok {
  104. meteData.SubDeviceId = v.(string)
  105. }
  106. tpl, err := template.New("topic").Parse(defaultTopicTemp)
  107. if err != nil {
  108. return err
  109. }
  110. stringBuf := new(strings.Builder)
  111. if err = tpl.Execute(stringBuf, &meteData); err != nil {
  112. return nil
  113. }
  114. topic := stringBuf.String()
  115. if M.mqttClient != nil {
  116. token := M.mqttClient.Publish(topic, 0, false, message.Data)
  117. if token.Error() != nil {
  118. ctx.TellNext(message, protocol.Failure)
  119. } else {
  120. ctx.TellNext(message, protocol.Success)
  121. }
  122. }
  123. return nil
  124. }