Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

62 rindas
1.8 KiB

  1. package bridge
  2. import (
  3. "fmt"
  4. "log/slog"
  5. "github.com/AFASystems/presence/internal/pkg/config"
  6. mqtt "github.com/eclipse/paho.mqtt.golang"
  7. "github.com/google/uuid"
  8. )
  9. const defaultMQTTPort = 1883
  10. const subscribeTopic = "publish_out/#"
  11. const disconnectQuiesceMs = 250
  12. // MQTTClient wraps paho MQTT client and options.
  13. type MQTTClient struct {
  14. Client mqtt.Client
  15. }
  16. // NewMQTTClient creates and connects an MQTT client. Returns error instead of panic on connect failure.
  17. func NewMQTTClient(cfg *config.Config, publishHandler func(mqtt.Message)) (*MQTTClient, error) {
  18. opts := mqtt.NewClientOptions()
  19. opts.AddBroker(fmt.Sprintf("tcp://%s:%d", cfg.MQTTHost, defaultMQTTPort))
  20. opts.SetClientID(fmt.Sprintf("bridge-%s", uuid.New().String()))
  21. opts.SetAutoReconnect(true)
  22. opts.SetConnectRetry(true)
  23. opts.SetConnectRetryInterval(config.SMALL_TICKER_INTERVAL)
  24. opts.SetMaxReconnectInterval(config.LARGE_TICKER_INTERVAL)
  25. opts.SetCleanSession(false)
  26. opts.SetDefaultPublishHandler(func(c mqtt.Client, m mqtt.Message) {
  27. publishHandler(m)
  28. })
  29. opts.OnConnect = func(client mqtt.Client) {
  30. slog.Info("MQTT connected")
  31. }
  32. opts.OnConnectionLost = func(client mqtt.Client, err error) {
  33. slog.Error("MQTT connection lost", "err", err)
  34. }
  35. client := mqtt.NewClient(opts)
  36. token := client.Connect()
  37. token.Wait()
  38. if err := token.Error(); err != nil {
  39. return nil, fmt.Errorf("mqtt connect: %w", err)
  40. }
  41. return &MQTTClient{Client: client}, nil
  42. }
  43. // Subscribe subscribes to the default bridge topic.
  44. func (m *MQTTClient) Subscribe() {
  45. token := m.Client.Subscribe(subscribeTopic, 1, nil)
  46. token.Wait()
  47. slog.Info("MQTT subscribed", "topic", subscribeTopic)
  48. }
  49. // Disconnect disconnects the client with quiesce.
  50. func (m *MQTTClient) Disconnect() {
  51. m.Client.Disconnect(disconnectQuiesceMs)
  52. slog.Info("MQTT disconnected")
  53. }