mqtt_broker_node.go 3.7 KB

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