shelly-prometheus-exporter/mqtt.go

122 lines
3.3 KiB
Go

package main
import (
"encoding/json"
"strings"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
"jonasled.dev/jonasled/go-libs/log"
)
type rpcEvent struct {
Method string `json:"method"`
Params map[string]json.RawMessage `json:"params"`
}
func connectMQTT(cfg Config) mqtt.Client {
opts := mqtt.NewClientOptions().
AddBroker(cfg.MQTTBroker).
SetClientID(cfg.MQTTClientID).
SetAutoReconnect(true).
SetConnectRetry(true).
SetConnectRetryInterval(5 * time.Second).
SetMaxReconnectInterval(time.Minute)
if cfg.MQTTUsername != "" {
opts.SetUsername(cfg.MQTTUsername)
opts.SetPassword(cfg.MQTTPassword)
}
subs := cfg.subscriptions()
opts.SetOnConnectHandler(func(c mqtt.Client) {
log.Log.Infof("Connected to MQTT broker %s", cfg.MQTTBroker)
filters := make(map[string]byte, len(subs))
for _, sub := range subs {
filters[sub] = cfg.MQTTQoS
log.Log.Debugf("Subscribing to %s", sub)
}
token := c.SubscribeMultiple(filters, handleMessage)
token.Wait()
if err := token.Error(); err != nil {
log.Log.Errorf("Failed to subscribe: %v", err)
}
})
opts.SetConnectionLostHandler(func(_ mqtt.Client, err error) {
log.Log.Warnf("Connection to MQTT broker lost: %v", err)
})
client := mqtt.NewClient(opts)
client.Connect() // retries in the background thanks to SetConnectRetry
return client
}
func handleMessage(_ mqtt.Client, msg mqtt.Message) {
topic := msg.Topic()
payload := msg.Payload()
log.Log.Debugf("Received %s: %s", topic, payload)
switch {
case strings.HasSuffix(topic, "/online"):
device := deviceName(strings.TrimSuffix(topic, "/online"))
value, ok := toFloat(strings.TrimSpace(string(payload)) == "true")
if ok {
onlineGauge.WithLabelValues(device).Set(value)
}
touch(device)
case strings.HasSuffix(topic, "/events/rpc"):
device := deviceName(strings.TrimSuffix(topic, "/events/rpc"))
handleEvent(device, payload)
touch(device)
default:
idx := strings.LastIndex(topic, "/status/")
if idx < 0 {
return
}
device := deviceName(topic[:idx])
key := topic[idx+len("/status/"):]
var status map[string]any
if err := json.Unmarshal(payload, &status); err != nil {
log.Log.Warnf("Invalid status payload on %s: %v", topic, err)
return
}
applyComponentStatus(device, key, status)
touch(device)
}
}
// handleEvent processes NotifyStatus / NotifyFullStatus RPC events, which carry
// (partial) component status updates, e.g. when a smoke alarm is triggered.
func handleEvent(device string, payload []byte) {
var event rpcEvent
if err := json.Unmarshal(payload, &event); err != nil {
log.Log.Warnf("Invalid event payload from %s: %v", device, err)
return
}
if event.Method != "NotifyStatus" && event.Method != "NotifyFullStatus" {
return
}
for key, raw := range event.Params {
var status map[string]any
if err := json.Unmarshal(raw, &status); err != nil {
continue // e.g. "ts" is a number, not a component
}
applyComponentStatus(device, key, status)
}
}
// deviceName returns the last segment of the topic prefix, e.g. "shellies/foo" -> "foo".
func deviceName(prefix string) string {
if idx := strings.LastIndex(prefix, "/"); idx >= 0 {
return prefix[idx+1:]
}
return prefix
}
func touch(device string) {
lastSeenGauge.WithLabelValues(device).SetToCurrentTime()
}