mqtt_source.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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/conf"
  19. "github.com/lf-edge/ekuiper/internal/topo/connection/clients"
  20. "github.com/lf-edge/ekuiper/internal/xsql"
  21. "github.com/lf-edge/ekuiper/pkg/api"
  22. "github.com/lf-edge/ekuiper/pkg/cast"
  23. "path"
  24. "strconv"
  25. )
  26. type MQTTSource struct {
  27. qos int
  28. format string
  29. tpc string
  30. buflen int
  31. config map[string]interface{}
  32. model modelVersion
  33. schema map[string]interface{}
  34. cli api.MessageClient
  35. }
  36. type MQTTConfig struct {
  37. Format string `json:"format"`
  38. Qos int `json:"qos"`
  39. BufferLen int `json:"bufferLength"`
  40. KubeedgeModelFile string `json:"kubeedgeModelFile"`
  41. KubeedgeVersion string `json:"kubeedgeVersion"`
  42. }
  43. func (ms *MQTTSource) WithSchema(_ string) *MQTTSource {
  44. return ms
  45. }
  46. func (ms *MQTTSource) Configure(topic string, props map[string]interface{}) error {
  47. cfg := &MQTTConfig{
  48. BufferLen: 1024,
  49. }
  50. err := cast.MapToStruct(props, cfg)
  51. if err != nil {
  52. return fmt.Errorf("read properties %v fail with error: %v", props, err)
  53. }
  54. if cfg.BufferLen <= 0 {
  55. cfg.BufferLen = 1024
  56. }
  57. ms.buflen = cfg.BufferLen
  58. ms.tpc = topic
  59. ms.format = cfg.Format
  60. ms.qos = cfg.Qos
  61. ms.config = props
  62. if 0 != len(cfg.KubeedgeModelFile) {
  63. p := path.Join("sources", cfg.KubeedgeModelFile)
  64. ms.model = modelFactory(cfg.KubeedgeVersion)
  65. err = conf.LoadConfigFromPath(p, ms.model)
  66. if err != nil {
  67. return err
  68. }
  69. }
  70. cli, err := clients.GetClient("mqtt", ms.config)
  71. if err != nil {
  72. return err
  73. }
  74. ms.cli = cli
  75. return nil
  76. }
  77. func (ms *MQTTSource) Open(ctx api.StreamContext, consumer chan<- api.SourceTuple, errCh chan<- error) {
  78. err := subscribe(ms, ctx, consumer)
  79. if err != nil {
  80. errCh <- err
  81. }
  82. }
  83. // should only return fatal error
  84. func subscribe(ms *MQTTSource, ctx api.StreamContext, consumer chan<- api.SourceTuple) error {
  85. log := ctx.GetLogger()
  86. messages := make(chan interface{}, ms.buflen)
  87. topics := []api.TopicChannel{{Topic: ms.tpc, Messages: messages}}
  88. err := make(chan error, len(topics))
  89. para := map[string]interface{}{
  90. "qos": byte(ms.qos),
  91. }
  92. if e := ms.cli.Subscribe(ctx, topics, err, para); e != nil {
  93. log.Errorf("Failed to subscribe to mqtt topic %s, error %s\n", ms.tpc, e.Error())
  94. return e
  95. } else {
  96. log.Infof("Successfully subscribed to topic %s.", ms.tpc)
  97. var t api.SourceTuple
  98. for {
  99. select {
  100. case <-ctx.Done():
  101. log.Infof("Exit subscription to mqtt messagebus topic %s.", ms.tpc)
  102. return nil
  103. case e1 := <-err:
  104. t = &xsql.ErrorSourceTuple{
  105. Error: fmt.Errorf("the subscription to mqtt topic %s have error %s.\n", ms.tpc, e1.Error()),
  106. }
  107. case env, ok := <-messages:
  108. if !ok { // the source is closed
  109. log.Infof("Exit subscription to mqtt messagebus topic %s.", ms.tpc)
  110. return nil
  111. }
  112. t = getTuple(ctx, ms, env)
  113. }
  114. select {
  115. case consumer <- t:
  116. log.Debugf("send data to source node")
  117. case <-ctx.Done():
  118. return nil
  119. }
  120. }
  121. }
  122. }
  123. func getTuple(ctx api.StreamContext, ms *MQTTSource, env interface{}) api.SourceTuple {
  124. msg, ok := env.(pahoMqtt.Message)
  125. if !ok { // should never happen
  126. return &xsql.ErrorSourceTuple{
  127. Error: fmt.Errorf("can not convert interface data to mqtt message %v.", env),
  128. }
  129. }
  130. result, e := ctx.Decode(msg.Payload())
  131. //The unmarshal type can only be bool, float64, string, []interface{}, map[string]interface{}, nil
  132. if e != nil {
  133. return &xsql.ErrorSourceTuple{
  134. Error: fmt.Errorf("Invalid data format, cannot decode %s with error %s", string(msg.Payload()), e),
  135. }
  136. }
  137. meta := make(map[string]interface{})
  138. meta["topic"] = msg.Topic()
  139. meta["messageid"] = strconv.Itoa(int(msg.MessageID()))
  140. if nil != ms.model {
  141. sliErr := ms.model.checkType(result, msg.Topic())
  142. for _, v := range sliErr {
  143. ctx.GetLogger().Errorf(v)
  144. }
  145. }
  146. return api.NewDefaultSourceTuple(result, meta)
  147. }
  148. func (ms *MQTTSource) Close(ctx api.StreamContext) error {
  149. ctx.GetLogger().Infof("Mqtt Source instance %d Done", ctx.GetInstanceId())
  150. if ms.cli != nil {
  151. clients.ReleaseClient(ctx, ms.cli)
  152. }
  153. return nil
  154. }