mqtt_source.go 4.4 KB

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