mqtt_source.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. "path"
  18. "strconv"
  19. pahoMqtt "github.com/eclipse/paho.mqtt.golang"
  20. "github.com/lf-edge/ekuiper/internal/compressor"
  21. "github.com/lf-edge/ekuiper/internal/conf"
  22. "github.com/lf-edge/ekuiper/internal/io"
  23. "github.com/lf-edge/ekuiper/internal/topo/connection/clients"
  24. "github.com/lf-edge/ekuiper/internal/xsql"
  25. "github.com/lf-edge/ekuiper/pkg/api"
  26. "github.com/lf-edge/ekuiper/pkg/cast"
  27. "github.com/lf-edge/ekuiper/pkg/message"
  28. )
  29. type MQTTSource struct {
  30. qos int
  31. format string
  32. tpc string
  33. buflen int
  34. config map[string]interface{}
  35. model modelVersion
  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 tuples []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. tuples = []api.SourceTuple{
  116. &xsql.ErrorSourceTuple{
  117. Error: fmt.Errorf("the subscription to mqtt topic %s have error %s.\n", ms.tpc, e1.Error()),
  118. },
  119. }
  120. case env, ok := <-messages:
  121. if !ok { // the source is closed
  122. log.Infof("Exit subscription to mqtt messagebus topic %s.", ms.tpc)
  123. return nil
  124. }
  125. tuples = getTuples(ctx, ms, env)
  126. }
  127. io.ReceiveTuples(ctx, consumer, tuples)
  128. }
  129. }
  130. }
  131. func getTuples(ctx api.StreamContext, ms *MQTTSource, env interface{}) []api.SourceTuple {
  132. rcvTime := conf.GetNow()
  133. msg, ok := env.(pahoMqtt.Message)
  134. if !ok { // should never happen
  135. return []api.SourceTuple{
  136. &xsql.ErrorSourceTuple{
  137. Error: fmt.Errorf("can not convert interface data to mqtt message %v.", env),
  138. },
  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 []api.SourceTuple{
  147. &xsql.ErrorSourceTuple{
  148. Error: fmt.Errorf("can not decompress mqtt message %v.", err),
  149. },
  150. }
  151. }
  152. }
  153. results, e := ctx.DecodeIntoList(payload)
  154. // The unmarshal type can only be bool, float64, string, []interface{}, map[string]interface{}, nil
  155. if e != nil {
  156. return []api.SourceTuple{
  157. &xsql.ErrorSourceTuple{
  158. Error: fmt.Errorf("Invalid data format, cannot decode %s with error %s", string(msg.Payload()), e),
  159. },
  160. }
  161. }
  162. meta := make(map[string]interface{})
  163. meta["topic"] = msg.Topic()
  164. meta["messageid"] = strconv.Itoa(int(msg.MessageID()))
  165. tuples := make([]api.SourceTuple, 0, len(results))
  166. for _, result := range results {
  167. if nil != ms.model {
  168. sliErr := ms.model.checkType(result, msg.Topic())
  169. for _, v := range sliErr {
  170. ctx.GetLogger().Errorf(v)
  171. }
  172. }
  173. tuples = append(tuples, api.NewDefaultSourceTupleWithTime(result, meta, rcvTime))
  174. }
  175. return tuples
  176. }
  177. func (ms *MQTTSource) Close(ctx api.StreamContext) error {
  178. ctx.GetLogger().Infof("Mqtt Source instance %d Done", ctx.GetInstanceId())
  179. if ms.cli != nil {
  180. clients.ReleaseClient(ctx, ms.cli)
  181. }
  182. return nil
  183. }