mqtt_source.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. package extensions
  2. import (
  3. "crypto/tls"
  4. "encoding/json"
  5. "engine/common"
  6. "engine/xsql"
  7. "engine/xstream/api"
  8. "fmt"
  9. MQTT "github.com/eclipse/paho.mqtt.golang"
  10. "github.com/go-yaml/yaml"
  11. "github.com/google/uuid"
  12. "strconv"
  13. "strings"
  14. )
  15. type MQTTSource struct {
  16. srv string
  17. tpc string
  18. clientid string
  19. pVersion uint
  20. uName string
  21. password string
  22. certPath string
  23. pkeyPath string
  24. schema map[string]interface{}
  25. conn MQTT.Client
  26. }
  27. type MQTTConfig struct {
  28. Qos string `yaml:"qos"`
  29. Sharedsubscription string `yaml:"sharedSubscription"`
  30. Servers []string `yaml:"servers"`
  31. Clientid string `yaml:"clientid"`
  32. PVersion string `yaml:"protocolVersion"`
  33. Uname string `yaml:"username"`
  34. Password string `yaml:"password"`
  35. Certification string `yaml:"certificationPath"`
  36. PrivateKPath string `yaml:"privateKeyPath"`
  37. }
  38. const confName string = "mqtt_source.yaml"
  39. func NewMQTTSource(topic string, confKey string) (*MQTTSource, error) {
  40. b, err := common.LoadConf(confName)
  41. if err != nil {
  42. common.Log.Fatal(err)
  43. }
  44. var cfg map[string]MQTTConfig
  45. if err := yaml.Unmarshal(b, &cfg); err != nil {
  46. return nil, err
  47. }
  48. ms := &MQTTSource{tpc: topic}
  49. if srvs := cfg[confKey].Servers; srvs != nil && len(srvs) > 1 {
  50. return nil, fmt.Errorf("It only support one server in %s section.", confKey)
  51. } else if srvs == nil {
  52. srvs = cfg["default"].Servers
  53. if srvs != nil && len(srvs) == 1 {
  54. ms.srv = srvs[0]
  55. } else {
  56. return nil, fmt.Errorf("Wrong configuration in default section!")
  57. }
  58. } else {
  59. ms.srv = srvs[0]
  60. }
  61. if cid := cfg[confKey].Clientid; cid != "" {
  62. ms.clientid = cid
  63. } else {
  64. ms.clientid = cfg["default"].Clientid
  65. }
  66. var pversion uint = 3
  67. if pv := cfg[confKey].PVersion; pv != "" {
  68. if pv == "3.1.1" {
  69. pversion = 4
  70. }
  71. } else {
  72. pv = cfg["default"].PVersion
  73. if pv == "3.1.1" {
  74. pversion = 4
  75. }
  76. }
  77. ms.pVersion = pversion
  78. if uname := cfg[confKey].Uname; uname != "" {
  79. ms.uName = strings.Trim(uname, " ")
  80. } else {
  81. ms.uName = cfg["default"].Uname
  82. }
  83. if password := cfg[confKey].Password; password != "" {
  84. ms.password = strings.Trim(password, " ")
  85. } else {
  86. ms.password = cfg["default"].Password
  87. }
  88. if cpath := cfg[confKey].Certification; cpath != "" {
  89. ms.certPath = cpath
  90. } else {
  91. ms.certPath = cfg["default"].Certification
  92. }
  93. if pkpath := cfg[confKey].PrivateKPath; pkpath != "" {
  94. ms.pkeyPath = pkpath
  95. } else {
  96. ms.pkeyPath = cfg["default"].PrivateKPath
  97. }
  98. return ms, nil
  99. }
  100. func (ms *MQTTSource) WithSchema(schema string) *MQTTSource {
  101. return ms
  102. }
  103. func (ms *MQTTSource) Configure(topic string, props map[string]interface{}) error {
  104. return nil
  105. }
  106. func (ms *MQTTSource) Open(ctx api.StreamContext, consume api.ConsumeFunc) error {
  107. log := ctx.GetLogger()
  108. opts := MQTT.NewClientOptions().AddBroker(ms.srv).SetProtocolVersion(ms.pVersion)
  109. if ms.clientid == "" {
  110. if uuid, err := uuid.NewUUID(); err != nil {
  111. return fmt.Errorf("failed to get uuid, the error is %s", err)
  112. } else {
  113. opts.SetClientID(uuid.String())
  114. }
  115. } else {
  116. opts.SetClientID(ms.clientid)
  117. }
  118. if ms.certPath != "" || ms.pkeyPath != "" {
  119. log.Infof("Connect MQTT broker with certification and keys.")
  120. if cp, err := common.ProcessPath(ms.certPath); err == nil {
  121. log.Infof("The certification file is %s.", cp)
  122. if kp, err1 := common.ProcessPath(ms.pkeyPath); err1 == nil {
  123. log.Infof("The private key file is %s.", kp)
  124. if cer, err2 := tls.LoadX509KeyPair(cp, kp); err2 != nil {
  125. return err2
  126. } else {
  127. opts.SetTLSConfig(&tls.Config{Certificates: []tls.Certificate{cer}})
  128. }
  129. } else {
  130. return err1
  131. }
  132. } else {
  133. return err
  134. }
  135. } else {
  136. log.Infof("Connect MQTT broker with username and password.")
  137. if ms.uName != "" {
  138. opts = opts.SetUsername(ms.uName)
  139. }
  140. if ms.password != "" {
  141. opts = opts.SetPassword(ms.password)
  142. }
  143. }
  144. h := func(client MQTT.Client, msg MQTT.Message) {
  145. log.Infof("received %s", msg.Payload())
  146. result := make(map[string]interface{})
  147. //The unmarshal type can only be bool, float64, string, []interface{}, map[string]interface{}, nil
  148. if e := json.Unmarshal(msg.Payload(), &result); e != nil {
  149. log.Errorf("Invalid data format, cannot convert %s into JSON with error %s", string(msg.Payload()), e)
  150. return
  151. }
  152. //Convert the keys to lowercase
  153. result = xsql.LowercaseKeyMap(result)
  154. meta := make(map[string]interface{})
  155. meta[xsql.INTERNAL_MQTT_TOPIC_KEY] = msg.Topic()
  156. meta[xsql.INTERNAL_MQTT_MSG_ID_KEY] = strconv.Itoa(int(msg.MessageID()))
  157. consume(result, meta)
  158. }
  159. //TODO error listener?
  160. opts.SetDefaultPublishHandler(h)
  161. c := MQTT.NewClient(opts)
  162. if token := c.Connect(); token.Wait() && token.Error() != nil {
  163. return fmt.Errorf("found error when connecting to %s: %s", ms.srv, token.Error())
  164. }
  165. log.Printf("The connection to server %s was established successfully", ms.srv)
  166. ms.conn = c
  167. if token := c.Subscribe(ms.tpc, 0, nil); token.Wait() && token.Error() != nil {
  168. return fmt.Errorf("Found error: %s", token.Error())
  169. }
  170. log.Printf("Successfully subscribe to topic %s", ms.tpc)
  171. return nil
  172. }
  173. func (ms *MQTTSource) Close(ctx api.StreamContext) error{
  174. ctx.GetLogger().Println("Mqtt Source Done")
  175. if ms.conn != nil && ms.conn.IsConnected() {
  176. ms.conn.Disconnect(5000)
  177. }
  178. return nil
  179. }