mqtt_source.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. // Copyright 2021-2023 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package mqtt
  15. import (
  16. "fmt"
  17. pahoMqtt "github.com/eclipse/paho.mqtt.golang"
  18. "github.com/lf-edge/ekuiper/internal/compressor"
  19. "github.com/lf-edge/ekuiper/internal/conf"
  20. "github.com/lf-edge/ekuiper/internal/topo/connection/clients"
  21. "github.com/lf-edge/ekuiper/internal/xsql"
  22. "github.com/lf-edge/ekuiper/pkg/api"
  23. "github.com/lf-edge/ekuiper/pkg/cast"
  24. "github.com/lf-edge/ekuiper/pkg/message"
  25. "path"
  26. "strconv"
  27. )
  28. type MQTTSource struct {
  29. qos int
  30. format string
  31. tpc string
  32. buflen int
  33. config map[string]interface{}
  34. model modelVersion
  35. schema map[string]interface{}
  36. cli api.MessageClient
  37. decompressor message.Decompressor
  38. }
  39. type MQTTConfig struct {
  40. Format string `json:"format"`
  41. Qos int `json:"qos"`
  42. BufferLen int `json:"bufferLength"`
  43. KubeedgeModelFile string `json:"kubeedgeModelFile"`
  44. KubeedgeVersion string `json:"kubeedgeVersion"`
  45. Decompression string `json:"decompression"`
  46. }
  47. func (ms *MQTTSource) WithSchema(_ string) *MQTTSource {
  48. return ms
  49. }
  50. func (ms *MQTTSource) Configure(topic string, props map[string]interface{}) error {
  51. cfg := &MQTTConfig{
  52. BufferLen: 1024,
  53. }
  54. err := cast.MapToStruct(props, cfg)
  55. if err != nil {
  56. return fmt.Errorf("read properties %v fail with error: %v", props, err)
  57. }
  58. if cfg.BufferLen <= 0 {
  59. cfg.BufferLen = 1024
  60. }
  61. ms.buflen = cfg.BufferLen
  62. ms.tpc = topic
  63. ms.format = cfg.Format
  64. ms.qos = cfg.Qos
  65. ms.config = props
  66. if cfg.Decompression != "" {
  67. dc, err := compressor.GetDecompressor(cfg.Decompression)
  68. if err != nil {
  69. return fmt.Errorf("get decompressor %s fail with error: %v", cfg.Decompression, err)
  70. }
  71. ms.decompressor = dc
  72. }
  73. if 0 != len(cfg.KubeedgeModelFile) {
  74. p := path.Join("sources", cfg.KubeedgeModelFile)
  75. ms.model = modelFactory(cfg.KubeedgeVersion)
  76. err = conf.LoadConfigFromPath(p, ms.model)
  77. if err != nil {
  78. return err
  79. }
  80. }
  81. cli, err := clients.GetClient("mqtt", ms.config)
  82. if err != nil {
  83. return err
  84. }
  85. ms.cli = cli
  86. return nil
  87. }
  88. func (ms *MQTTSource) Open(ctx api.StreamContext, consumer chan<- api.SourceTuple, errCh chan<- error) {
  89. err := subscribe(ms, ctx, consumer)
  90. if err != nil {
  91. errCh <- err
  92. }
  93. }
  94. // should only return fatal error
  95. func subscribe(ms *MQTTSource, ctx api.StreamContext, consumer chan<- api.SourceTuple) error {
  96. log := ctx.GetLogger()
  97. messages := make(chan interface{}, ms.buflen)
  98. topics := []api.TopicChannel{{Topic: ms.tpc, Messages: messages}}
  99. err := make(chan error, len(topics))
  100. para := map[string]interface{}{
  101. "qos": byte(ms.qos),
  102. }
  103. if e := ms.cli.Subscribe(ctx, topics, err, para); e != nil {
  104. log.Errorf("Failed to subscribe to mqtt topic %s, error %s\n", ms.tpc, e.Error())
  105. return e
  106. } else {
  107. log.Infof("Successfully subscribed to topic %s.", ms.tpc)
  108. var t api.SourceTuple
  109. for {
  110. select {
  111. case <-ctx.Done():
  112. log.Infof("Exit subscription to mqtt messagebus topic %s.", ms.tpc)
  113. return nil
  114. case e1 := <-err:
  115. t = &xsql.ErrorSourceTuple{
  116. Error: fmt.Errorf("the subscription to mqtt topic %s have error %s.\n", ms.tpc, e1.Error()),
  117. }
  118. case env, ok := <-messages:
  119. if !ok { // the source is closed
  120. log.Infof("Exit subscription to mqtt messagebus topic %s.", ms.tpc)
  121. return nil
  122. }
  123. t = getTuple(ctx, ms, env)
  124. }
  125. select {
  126. case consumer <- t:
  127. log.Debugf("send data to source node")
  128. case <-ctx.Done():
  129. return nil
  130. }
  131. }
  132. }
  133. }
  134. func getTuple(ctx api.StreamContext, ms *MQTTSource, env interface{}) api.SourceTuple {
  135. msg, ok := env.(pahoMqtt.Message)
  136. if !ok { // should never happen
  137. return &xsql.ErrorSourceTuple{
  138. Error: fmt.Errorf("can not convert interface data to mqtt message %v.", env),
  139. }
  140. }
  141. payload := msg.Payload()
  142. var err error
  143. if ms.decompressor != nil {
  144. payload, err = ms.decompressor.Decompress(payload)
  145. if err != nil {
  146. return &xsql.ErrorSourceTuple{
  147. Error: fmt.Errorf("can not decompress mqtt message %v.", err),
  148. }
  149. }
  150. }
  151. result, e := ctx.Decode(payload)
  152. //The unmarshal type can only be bool, float64, string, []interface{}, map[string]interface{}, nil
  153. if e != nil {
  154. return &xsql.ErrorSourceTuple{
  155. Error: fmt.Errorf("Invalid data format, cannot decode %s with error %s", string(msg.Payload()), e),
  156. }
  157. }
  158. meta := make(map[string]interface{})
  159. meta["topic"] = msg.Topic()
  160. meta["messageid"] = strconv.Itoa(int(msg.MessageID()))
  161. if nil != ms.model {
  162. sliErr := ms.model.checkType(result, msg.Topic())
  163. for _, v := range sliErr {
  164. ctx.GetLogger().Errorf(v)
  165. }
  166. }
  167. return api.NewDefaultSourceTuple(result, meta)
  168. }
  169. func (ms *MQTTSource) Close(ctx api.StreamContext) error {
  170. ctx.GetLogger().Infof("Mqtt Source instance %d Done", ctx.GetInstanceId())
  171. if ms.cli != nil {
  172. clients.ReleaseClient(ctx, ms.cli)
  173. }
  174. return nil
  175. }