mqtt_source.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. package extensions
  2. import (
  3. "context"
  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. "time"
  15. )
  16. type MQTTSource struct {
  17. srv string
  18. tpc string
  19. clientid string
  20. pVersion uint
  21. uName string
  22. password string
  23. schema map[string]interface{}
  24. conn MQTT.Client
  25. }
  26. type MQTTConfig struct {
  27. Qos string `yaml:"qos"`
  28. Sharedsubscription string `yaml:"sharedsubscription"`
  29. Servers []string `yaml:"servers"`
  30. Clientid string `yaml:"clientid"`
  31. PVersion string `yaml:"protocolVersion"`
  32. Uname string `yaml:"username"`
  33. Password string `yaml:"password"`
  34. }
  35. const confName string = "mqtt_source.yaml"
  36. func NewMQTTSource(topic string, confKey string) (*MQTTSource, error) {
  37. b := common.LoadConf(confName)
  38. var cfg map[string]MQTTConfig
  39. if err := yaml.Unmarshal(b, &cfg); err != nil {
  40. return nil, err
  41. }
  42. ms := &MQTTSource{tpc: topic}
  43. if srvs := cfg[confKey].Servers; srvs != nil && len(srvs) > 1 {
  44. return nil, fmt.Errorf("It only support one server in %s section.", confKey)
  45. } else if srvs == nil {
  46. srvs = cfg["default"].Servers
  47. if srvs != nil && len(srvs) == 1 {
  48. ms.srv = srvs[0]
  49. } else {
  50. return nil, fmt.Errorf("Wrong configuration in default section!")
  51. }
  52. } else {
  53. ms.srv = srvs[0]
  54. }
  55. if cid := cfg[confKey].Clientid; cid != "" {
  56. ms.clientid = cid
  57. } else {
  58. ms.clientid = cfg["default"].Clientid
  59. }
  60. var pversion uint = 3
  61. if pv := cfg[confKey].PVersion; pv != "" {
  62. if pv == "3.1.1" {
  63. pversion = 4
  64. }
  65. }
  66. ms.pVersion = pversion
  67. if uname := cfg[confKey].Uname; uname != "" {
  68. ms.uName = strings.Trim(uname, " ")
  69. }
  70. if password := cfg[confKey].Password; password != "" {
  71. ms.password = strings.Trim(password, " ")
  72. }
  73. return ms, nil
  74. }
  75. func (ms *MQTTSource) WithSchema(schema string) *MQTTSource {
  76. return ms
  77. }
  78. func (ms *MQTTSource) Open(ctx api.StreamContext, consume api.ConsumeFunc) error {
  79. log := ctx.GetLogger()
  80. go func() {
  81. exeCtx, cancel := context.WithCancel(ctx.GetContext())
  82. opts := MQTT.NewClientOptions().AddBroker(ms.srv).SetProtocolVersion(ms.pVersion)
  83. if ms.clientid == "" {
  84. if uuid, err := uuid.NewUUID(); err != nil {
  85. log.Printf("Failed to get uuid, the error is %s", err)
  86. cancel()
  87. return
  88. } else {
  89. opts.SetClientID(uuid.String())
  90. }
  91. } else {
  92. opts.SetClientID(ms.clientid)
  93. }
  94. if ms.uName != "" {
  95. opts.SetUsername(ms.uName)
  96. }
  97. if ms.password != "" {
  98. opts.SetPassword(ms.password)
  99. }
  100. h := func(client MQTT.Client, msg MQTT.Message) {
  101. log.Infof("received %s", msg.Payload())
  102. result := make(map[string]interface{})
  103. //The unmarshal type can only be bool, float64, string, []interface{}, map[string]interface{}, nil
  104. if e := json.Unmarshal(msg.Payload(), &result); e != nil {
  105. log.Errorf("Invalid data format, cannot convert %s into JSON with error %s", string(msg.Payload()), e)
  106. return
  107. }
  108. //Convert the keys to lowercase
  109. result = xsql.LowercaseKeyMap(result)
  110. meta := make(map[string]interface{})
  111. meta[xsql.INTERNAL_MQTT_TOPIC_KEY] = msg.Topic()
  112. meta[xsql.INTERNAL_MQTT_MSG_ID_KEY] = strconv.Itoa(int(msg.MessageID()))
  113. tuple := &xsql.Tuple{Emitter: ms.tpc, Message:result, Timestamp: common.TimeToUnixMilli(time.Now()), Metadata:meta}
  114. consume(tuple)
  115. }
  116. opts.SetDefaultPublishHandler(h)
  117. c := MQTT.NewClient(opts)
  118. if token := c.Connect(); token.Wait() && token.Error() != nil {
  119. log.Printf("Found error when connecting to %s: %s", ms.srv, token.Error())
  120. cancel()
  121. return
  122. }
  123. log.Printf("The connection to server %s was established successfully", ms.srv)
  124. ms.conn = c
  125. if token := c.Subscribe(ms.tpc, 0, nil); token.Wait() && token.Error() != nil {
  126. log.Printf("Found error: %s", token.Error())
  127. cancel()
  128. return
  129. }
  130. log.Printf("Successfully subscribe to topic %s", ms.tpc)
  131. select {
  132. case <-exeCtx.Done():
  133. log.Println("Mqtt Source Done")
  134. ms.conn.Disconnect(5000)
  135. cancel()
  136. }
  137. }()
  138. return nil
  139. }