mqtt_source.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. package extensions
  2. import (
  3. "crypto/tls"
  4. "encoding/json"
  5. "fmt"
  6. MQTT "github.com/eclipse/paho.mqtt.golang"
  7. "github.com/emqx/kuiper/common"
  8. "github.com/emqx/kuiper/xsql"
  9. "github.com/emqx/kuiper/xstream/api"
  10. "github.com/google/uuid"
  11. "strconv"
  12. "strings"
  13. )
  14. type MQTTSource struct {
  15. srv string
  16. tpc string
  17. clientid string
  18. pVersion uint
  19. uName string
  20. password string
  21. certPath string
  22. pkeyPath string
  23. schema map[string]interface{}
  24. conn MQTT.Client
  25. }
  26. type MQTTConfig struct {
  27. Qos int `json:"qos"`
  28. Sharedsubscription bool `json:"sharedSubscription"`
  29. Servers []string `json:"servers"`
  30. Clientid string `json:"clientid"`
  31. PVersion string `json:"protocolVersion"`
  32. Uname string `json:"username"`
  33. Password string `json:"password"`
  34. Certification string `json:"certificationPath"`
  35. PrivateKPath string `json:"privateKeyPath"`
  36. }
  37. func (ms *MQTTSource) WithSchema(schema string) *MQTTSource {
  38. return ms
  39. }
  40. func (ms *MQTTSource) Configure(topic string, props map[string]interface{}) error {
  41. cfg := &MQTTConfig{}
  42. err := common.MapToStruct(props, cfg)
  43. if err != nil {
  44. return fmt.Errorf("read properties %v fail with error: %v", props, err)
  45. }
  46. ms.tpc = topic
  47. if srvs := cfg.Servers; srvs != nil && len(srvs) > 0 {
  48. ms.srv = srvs[0]
  49. } else {
  50. return fmt.Errorf("missing server property")
  51. }
  52. ms.clientid = cfg.Clientid
  53. ms.pVersion = 3
  54. if cfg.PVersion == "3.1.1" {
  55. ms.pVersion = 4
  56. }
  57. ms.uName = cfg.Uname
  58. ms.password = strings.Trim(cfg.Password, " ")
  59. ms.certPath = cfg.Certification
  60. ms.pkeyPath = cfg.PrivateKPath
  61. return nil
  62. }
  63. func (ms *MQTTSource) Open(ctx api.StreamContext, consumer chan<- api.SourceTuple, errCh chan<- error) {
  64. log := ctx.GetLogger()
  65. opts := MQTT.NewClientOptions().AddBroker(ms.srv).SetProtocolVersion(ms.pVersion)
  66. if ms.clientid == "" {
  67. if uuid, err := uuid.NewUUID(); err != nil {
  68. errCh <- fmt.Errorf("failed to get uuid, the error is %s", err)
  69. } else {
  70. ms.clientid = uuid.String()
  71. opts.SetClientID(uuid.String())
  72. }
  73. } else {
  74. opts.SetClientID(ms.clientid)
  75. }
  76. if ms.certPath != "" || ms.pkeyPath != "" {
  77. log.Infof("Connect MQTT broker with certification and keys.")
  78. if cp, err := common.ProcessPath(ms.certPath); err == nil {
  79. log.Infof("The certification file is %s.", cp)
  80. if kp, err1 := common.ProcessPath(ms.pkeyPath); err1 == nil {
  81. log.Infof("The private key file is %s.", kp)
  82. if cer, err2 := tls.LoadX509KeyPair(cp, kp); err2 != nil {
  83. errCh <- err2
  84. } else {
  85. opts.SetTLSConfig(&tls.Config{Certificates: []tls.Certificate{cer}})
  86. }
  87. } else {
  88. errCh <- err1
  89. }
  90. } else {
  91. errCh <- err
  92. }
  93. } else {
  94. log.Infof("Connect MQTT broker with username and password.")
  95. if ms.uName != "" {
  96. opts = opts.SetUsername(ms.uName)
  97. } else {
  98. log.Infof("The username is empty.")
  99. }
  100. if ms.password != "" {
  101. opts = opts.SetPassword(ms.password)
  102. } else {
  103. log.Infof("The password is empty.")
  104. }
  105. }
  106. opts.SetAutoReconnect(true)
  107. var reconn = false
  108. opts.SetConnectionLostHandler(func(client MQTT.Client, e error) {
  109. log.Errorf("The connection %s is disconnected due to error %s, will try to re-connect later.", ms.srv+": "+ms.clientid, e)
  110. reconn = true
  111. subscribe(ms.tpc, client, ctx, consumer)
  112. })
  113. opts.SetOnConnectHandler(func(client MQTT.Client) {
  114. if reconn {
  115. log.Infof("The connection is %s re-established successfully.", ms.srv+": "+ms.clientid)
  116. }
  117. })
  118. c := MQTT.NewClient(opts)
  119. if token := c.Connect(); token.Wait() && token.Error() != nil {
  120. errCh <- fmt.Errorf("found error when connecting to %s: %s", ms.srv, token.Error())
  121. }
  122. log.Infof("The connection to server %s was established successfully", ms.srv)
  123. ms.conn = c
  124. subscribe(ms.tpc, c, ctx, consumer)
  125. log.Infof("Successfully subscribe to topic %s", ms.srv+": "+ms.clientid)
  126. }
  127. func subscribe(topic string, client MQTT.Client, ctx api.StreamContext, consumer chan<- api.SourceTuple) {
  128. log := ctx.GetLogger()
  129. h := func(client MQTT.Client, msg MQTT.Message) {
  130. log.Debugf("instance %d received %s", ctx.GetInstanceId(), msg.Payload())
  131. result := make(map[string]interface{})
  132. //The unmarshal type can only be bool, float64, string, []interface{}, map[string]interface{}, nil
  133. if e := json.Unmarshal(msg.Payload(), &result); e != nil {
  134. log.Errorf("Invalid data format, cannot convert %s into JSON with error %s", string(msg.Payload()), e)
  135. return
  136. }
  137. //Convert the keys to lowercase
  138. result = xsql.LowercaseKeyMap(result)
  139. meta := make(map[string]interface{})
  140. meta["topic"] = msg.Topic()
  141. meta["messageid"] = strconv.Itoa(int(msg.MessageID()))
  142. select {
  143. case consumer <- api.NewDefaultSourceTuple(result, meta):
  144. log.Debugf("send data to source node")
  145. case <-ctx.Done():
  146. return
  147. }
  148. }
  149. if token := client.Subscribe(topic, 0, h); token.Wait() && token.Error() != nil {
  150. log.Errorf("Found error: %s", token.Error())
  151. } else {
  152. log.Infof("Successfully subscribe to topic %s", topic)
  153. }
  154. }
  155. func (ms *MQTTSource) Close(ctx api.StreamContext) error {
  156. ctx.GetLogger().Infof("Mqtt Source instance %d Done", ctx.GetInstanceId())
  157. if ms.conn != nil && ms.conn.IsConnected() {
  158. ms.conn.Disconnect(5000)
  159. }
  160. return nil
  161. }