mqtt_source.go 4.4 KB

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