mqtt_source.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. package extensions
  2. import (
  3. "context"
  4. "encoding/json"
  5. "engine/common"
  6. "engine/xsql"
  7. "fmt"
  8. MQTT "github.com/eclipse/paho.mqtt.golang"
  9. "github.com/go-yaml/yaml"
  10. "github.com/google/uuid"
  11. "os"
  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. outs map[string]chan<- interface{}
  25. conn MQTT.Client
  26. name string
  27. //ctx context.Context
  28. }
  29. type MQTTConfig struct {
  30. Qos string `yaml:"qos"`
  31. Sharedsubscription string `yaml:"sharedsubscription"`
  32. Servers []string `yaml:"servers"`
  33. Clientid string `yaml:"clientid"`
  34. PVersion string `yaml:"protocolVersion"`
  35. Uname string `yaml:"username"`
  36. Password string `yaml:"password"`
  37. }
  38. const confName string = "mqtt_source.yaml"
  39. func NewWithName(name string, topic string, confKey string) (*MQTTSource, error) {
  40. b := common.LoadConf(confName)
  41. var cfg map[string]MQTTConfig
  42. if err := yaml.Unmarshal(b, &cfg); err != nil {
  43. return nil, err
  44. }
  45. ms := &MQTTSource{tpc: topic, name: name}
  46. ms.outs = make(map[string]chan<- interface{})
  47. if srvs := cfg[confKey].Servers; srvs != nil && len(srvs) > 1 {
  48. return nil, fmt.Errorf("It only support one server in %s section.", confKey)
  49. } else if srvs == nil {
  50. srvs = cfg["default"].Servers
  51. if srvs != nil && len(srvs) == 1 {
  52. ms.srv = srvs[0]
  53. } else {
  54. return nil, fmt.Errorf("Wrong configuration in default section!")
  55. }
  56. } else {
  57. ms.srv = srvs[0]
  58. }
  59. if cid := cfg[confKey].Clientid; cid != "" {
  60. ms.clientid = cid
  61. } else {
  62. ms.clientid = cfg["default"].Clientid
  63. }
  64. var pversion uint = 3
  65. if pv := cfg[confKey].PVersion; pv != "" {
  66. if pv == "3.1.1" {
  67. pversion = 4
  68. }
  69. }
  70. ms.pVersion = pversion
  71. if uname := cfg[confKey].Uname; uname != "" {
  72. ms.uName = strings.Trim(uname, " ")
  73. }
  74. if password := cfg[confKey].Password; password != "" {
  75. ms.password = strings.Trim(password, " ")
  76. }
  77. return ms, nil
  78. }
  79. func fileExists(filename string) bool {
  80. info, err := os.Stat(filename)
  81. if os.IsNotExist(err) {
  82. return false
  83. }
  84. return !info.IsDir()
  85. }
  86. func (ms *MQTTSource) WithSchema(schema string) *MQTTSource {
  87. return ms
  88. }
  89. func (ms *MQTTSource) GetName() string {
  90. return ms.name
  91. }
  92. func (ms *MQTTSource) AddOutput(output chan<- interface{}, name string) {
  93. if _, ok := ms.outs[name]; !ok{
  94. ms.outs[name] = output
  95. }else{
  96. common.Log.Warnf("fail to add output %s, operator %s already has an output of the same name", name, ms.name)
  97. }
  98. }
  99. func (ms *MQTTSource) Open(ctx context.Context) error {
  100. log := common.GetLogger(ctx)
  101. go func() {
  102. exeCtx, cancel := context.WithCancel(ctx)
  103. opts := MQTT.NewClientOptions().AddBroker(ms.srv).SetProtocolVersion(ms.pVersion)
  104. if ms.clientid == "" {
  105. if uuid, err := uuid.NewUUID(); err != nil {
  106. log.Printf("Failed to get uuid, the error is %s", err)
  107. cancel()
  108. return
  109. } else {
  110. opts.SetClientID(uuid.String())
  111. }
  112. } else {
  113. opts.SetClientID(ms.clientid)
  114. }
  115. if ms.uName != "" {
  116. opts.SetUsername(ms.uName)
  117. }
  118. if ms.password != "" {
  119. opts.SetPassword(ms.password)
  120. }
  121. h := func(client MQTT.Client, msg MQTT.Message) {
  122. log.Infof("received %s", msg.Payload())
  123. result := make(map[string]interface{})
  124. //The unmarshal type can only be bool, float64, string, []interface{}, map[string]interface{}, nil
  125. if e := json.Unmarshal(msg.Payload(), &result); e != nil {
  126. log.Errorf("Invalid data format, cannot convert %s into JSON with error %s", string(msg.Payload()), e)
  127. return
  128. }
  129. //Convert the keys to lowercase
  130. result = xsql.LowercaseKeyMap(result)
  131. meta := make(map[string]interface{})
  132. meta[xsql.INTERNAL_MQTT_TOPIC_KEY] = msg.Topic()
  133. meta[xsql.INTERNAL_MQTT_MSG_ID_KEY] = strconv.Itoa(int(msg.MessageID()))
  134. tuple := &xsql.Tuple{Emitter: ms.tpc, Message:result, Timestamp: common.TimeToUnixMilli(time.Now()), Metadata:meta}
  135. for _, out := range ms.outs{
  136. out <- tuple
  137. }
  138. }
  139. opts.SetDefaultPublishHandler(h)
  140. c := MQTT.NewClient(opts)
  141. if token := c.Connect(); token.Wait() && token.Error() != nil {
  142. log.Printf("Found error when connecting to %s for %s: %s", ms.srv, ms.name, token.Error())
  143. cancel()
  144. return
  145. }
  146. log.Printf("The connection to server %s was established successfully", ms.srv)
  147. ms.conn = c
  148. if token := c.Subscribe(ms.tpc, 0, nil); token.Wait() && token.Error() != nil {
  149. log.Printf("Found error: %s", token.Error())
  150. cancel()
  151. return
  152. }
  153. log.Printf("Successfully subscribe to topic %s", ms.tpc)
  154. select {
  155. case <-exeCtx.Done():
  156. log.Println("Mqtt Source Done")
  157. ms.conn.Disconnect(5000)
  158. cancel()
  159. }
  160. }()
  161. return nil
  162. }