mqtt_source.go 3.8 KB

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