mqtt_broker_node.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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. fmt.Printf("进入初始化:%s\r\n", config)
  52. if config != "" {
  53. c := new(MQTTBrokerNodeCfg)
  54. err := json.Unmarshal([]byte(config), c)
  55. if err != nil {
  56. return err
  57. }
  58. M.config = c
  59. }
  60. if M.config.Timeout == 0 {
  61. M.config.Timeout = defaultTimeout
  62. }
  63. var opt MQTT.ClientOptions
  64. opt.ClientID = "MQTT_NODE_" + guid.S()
  65. opt.CleanSession = M.config.ClearSession
  66. opt.KeepAlive = time.Second * 30
  67. opt.ConnectTimeout = time.Duration(M.config.Timeout) * time.Second
  68. switch M.config.Credentials {
  69. case "Basic":
  70. opt.Username = M.config.UserName
  71. opt.Password = M.config.Password
  72. default:
  73. }
  74. if M.config.ClientId != "" {
  75. opt.ClientID = M.config.ClientId
  76. }
  77. opt.AutoReconnect = true
  78. opt.MaxReconnectInterval = 10
  79. opt.AddBroker(fmt.Sprintf("tcp://%s:%d", M.config.Host, M.config.Port))
  80. c := MQTT.NewClient(&opt)
  81. M.mqttClient = c
  82. fmt.Printf("M.mqttClient = c:%v\r\n", 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. }