mqtt_broker_node.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. package nodes
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. MQTT "git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang.git"
  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 = time.Second * 30
  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. fmt.Printf("M.mqttClient = c:%v\r\n", c)
  84. go func() {
  85. if token := c.Connect(); token.Wait() && token.Error() != nil {
  86. return
  87. }
  88. }()
  89. return nil
  90. }
  91. type MeteData struct {
  92. VendorId string
  93. DeviceId string
  94. SubDeviceId string
  95. }
  96. func (M *MQTTBrokerNode) OnMessage(ctx ruleEngine.Context, message *protocol.Message) error {
  97. var meteData MeteData
  98. if v, ok := message.MetaData["vendor_id"]; ok {
  99. meteData.VendorId = v.(string)
  100. }
  101. if v, ok := message.MetaData["device_id"]; ok {
  102. meteData.DeviceId = v.(string)
  103. }
  104. if v, ok := message.MetaData["sub_device_id"]; ok {
  105. meteData.SubDeviceId = v.(string)
  106. }
  107. tpl, err := template.New("topic").Parse(defaultTopicTemp)
  108. if err != nil {
  109. return err
  110. }
  111. stringBuf := new(strings.Builder)
  112. if err = tpl.Execute(stringBuf, &meteData); err != nil {
  113. return nil
  114. }
  115. topic := stringBuf.String()
  116. if M.mqttClient != nil {
  117. token := M.mqttClient.Publish(topic, 0, false, message.Data)
  118. if token.Error() != nil {
  119. ctx.TellNext(message, protocol.Failure)
  120. } else {
  121. ctx.TellNext(message, protocol.Success)
  122. }
  123. }
  124. return nil
  125. }