mqtt.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. // Copyright 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 mqtt
  15. import (
  16. "crypto/tls"
  17. "fmt"
  18. MQTT "github.com/eclipse/paho.mqtt.golang"
  19. "github.com/google/uuid"
  20. "github.com/lf-edge/ekuiper/internal/conf"
  21. "github.com/lf-edge/ekuiper/internal/pkg/cert"
  22. "github.com/lf-edge/ekuiper/pkg/cast"
  23. "github.com/lf-edge/ekuiper/pkg/errorx"
  24. "strings"
  25. )
  26. type MQTTConnectionConfig struct {
  27. Server string `json:"server"`
  28. PVersion string `json:"protocolVersion"`
  29. ClientId string `json:"clientid"`
  30. Uname string `json:"username"`
  31. Password string `json:"password"`
  32. Certification string `json:"certificationPath"`
  33. PrivateKPath string `json:"privateKeyPath"`
  34. RootCaPath string `json:"rootCaPath"`
  35. InsecureSkipVerify bool `json:"insecureSkipVerify"`
  36. }
  37. type MQTTClient struct {
  38. srv string
  39. clientid string
  40. pVersion uint
  41. uName string
  42. password string
  43. tls *tls.Config
  44. conn MQTT.Client
  45. }
  46. func (ms *MQTTClient) CfgValidate(props map[string]interface{}) error {
  47. cfg := MQTTConnectionConfig{}
  48. err := cast.MapToStruct(props, &cfg)
  49. if err != nil {
  50. return fmt.Errorf("failed to get config, the error is %s", err)
  51. }
  52. if cfg.Server != "" {
  53. ms.srv = cfg.Server
  54. } else {
  55. return fmt.Errorf("missing server property")
  56. }
  57. if cfg.ClientId == "" {
  58. if newUUID, err := uuid.NewUUID(); err != nil {
  59. return fmt.Errorf("failed to get uuid, the error is %s", err)
  60. } else {
  61. ms.clientid = newUUID.String()
  62. }
  63. } else {
  64. ms.clientid = cfg.ClientId
  65. }
  66. ms.pVersion = 3
  67. if cfg.PVersion == "3.1.1" {
  68. ms.pVersion = 4
  69. }
  70. tlsOpts := cert.TlsConfigurationOptions{
  71. SkipCertVerify: cfg.InsecureSkipVerify,
  72. CertFile: cfg.Certification,
  73. KeyFile: cfg.PrivateKPath,
  74. CaFile: cfg.RootCaPath,
  75. }
  76. conf.Log.Infof("Connect MQTT broker %s with TLS configs: %v.", ms.srv, tlsOpts)
  77. tlscfg, err := cert.GenerateTLSForClient(tlsOpts)
  78. if err != nil {
  79. return err
  80. }
  81. ms.tls = tlscfg
  82. ms.uName = cfg.Uname
  83. ms.password = strings.Trim(cfg.Password, " ")
  84. return nil
  85. }
  86. func (ms *MQTTClient) Connect(connHandler MQTT.OnConnectHandler, lostHandler MQTT.ConnectionLostHandler) error {
  87. opts := MQTT.NewClientOptions().AddBroker(ms.srv).SetProtocolVersion(ms.pVersion)
  88. opts = opts.SetTLSConfig(ms.tls)
  89. if ms.uName != "" {
  90. opts = opts.SetUsername(ms.uName)
  91. }
  92. if ms.password != "" {
  93. opts = opts.SetPassword(ms.password)
  94. }
  95. opts = opts.SetClientID(ms.clientid)
  96. opts = opts.SetAutoReconnect(true)
  97. opts.OnConnect = connHandler
  98. opts.OnConnectionLost = lostHandler
  99. c := MQTT.NewClient(opts)
  100. if token := c.Connect(); token.Wait() && token.Error() != nil {
  101. conf.Log.Errorf("The connection to mqtt broker %s failed : %s ", ms.srv, token.Error())
  102. return fmt.Errorf("found error when connecting for %s: %s", ms.srv, token.Error())
  103. }
  104. conf.Log.Infof("The connection to mqtt broker is established successfully for %s.", ms.srv)
  105. ms.conn = c
  106. return nil
  107. }
  108. func (ms *MQTTClient) Subscribe(topic string, qos byte, handler MQTT.MessageHandler) error {
  109. if token := ms.conn.Subscribe(topic, qos, handler); token.Wait() && token.Error() != nil {
  110. return fmt.Errorf("%s: %s", errorx.IOErr, token.Error())
  111. }
  112. return nil
  113. }
  114. func (ms *MQTTClient) Publish(topic string, qos byte, retained bool, message []byte) error {
  115. if token := ms.conn.Publish(topic, qos, retained, message); token.Wait() && token.Error() != nil {
  116. return fmt.Errorf("%s: %s", errorx.IOErr, token.Error())
  117. }
  118. return nil
  119. }
  120. func (ms *MQTTClient) Disconnect() error {
  121. conf.Log.Infof("Closing the connection to mqtt broker for %s", ms.srv)
  122. if ms.conn != nil && ms.conn.IsConnected() {
  123. ms.conn.Disconnect(5000)
  124. }
  125. return nil
  126. }