add shelly MQTT exporter
This commit is contained in:
commit
5577bf224d
8 changed files with 575 additions and 0 deletions
46
Readme.md
Normal file
46
Readme.md
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
# Shelly Prometheus Exporter
|
||||
|
||||
Subscribes to the MQTT topics of Shelly Gen2+ devices and exposes their status as Prometheus metrics on `/metrics`.
|
||||
|
||||
## Configuration
|
||||
|
||||
All configuration is done via environment variables.
|
||||
|
||||
| Variable | Default | Description |
|
||||
|-----------------------|------------------------------|-----------------------------------------------------------------------------|
|
||||
| `MQTT_BROKER` | *(required)* | Broker URL, e.g. `tcp://192.168.1.10:1883` or `ssl://broker:8883` |
|
||||
| `MQTT_USERNAME` | | Username; leave empty for brokers without authentication |
|
||||
| `MQTT_PASSWORD` | | Password |
|
||||
| `MQTT_CLIENT_ID` | `shelly-prometheus-exporter` | MQTT client ID |
|
||||
| `MQTT_QOS` | `0` | Subscription QoS (0, 1 or 2) |
|
||||
| `MQTT_TOPICS` | | Comma-separated device topic prefixes, e.g. `shellyplussmoke-halle-2,shellyplussmoke-funkzentrale` |
|
||||
| `MQTT_WILDCARD_TOPIC` | | Topic prefix with MQTT wildcard, e.g. `+` (all root-level devices) or `shellies/+` |
|
||||
| `LISTEN_ADDRESS` | `:9784` | HTTP listen address for the metrics endpoint |
|
||||
| `LOG_LEVEL` | `INFO` | `ERROR`, `WARN`, `INFO` or `DEBUG` |
|
||||
| `LOG_FOLDER` | | If set, logs are additionally written to `<LOG_FOLDER>/application.log` |
|
||||
|
||||
At least one of `MQTT_TOPICS` or `MQTT_WILDCARD_TOPIC` must be set. For each prefix the exporter subscribes to
|
||||
`<prefix>/online`, `<prefix>/status/+` and `<prefix>/events/rpc`. The `device` label is the last segment of the prefix.
|
||||
|
||||
## Metrics
|
||||
|
||||
| Metric | Labels | Source |
|
||||
|-----------------------------------------|----------------|----------------------------------------|
|
||||
| `shelly_online` | `device` | `<device>/online` |
|
||||
| `shelly_cloud_connected` | `device` | `status/cloud` → `connected` |
|
||||
| `shelly_mqtt_connected` | `device` | `status/mqtt` → `connected` |
|
||||
| `shelly_smoke_alarm` | `device`, `id` | `status/smoke:<id>` → `alarm` |
|
||||
| `shelly_smoke_mute` | `device`, `id` | `status/smoke:<id>` → `mute` |
|
||||
| `shelly_battery_voltage_volts` | `device`, `id` | `status/devicepower:<id>` → `battery.V` |
|
||||
| `shelly_battery_percent` | `device`, `id` | `status/devicepower:<id>` → `battery.percent` |
|
||||
| `shelly_last_message_timestamp_seconds` | `device` | Time of the last message from the device |
|
||||
|
||||
`NotifyStatus` events on `<device>/events/rpc` are applied too, so e.g. a smoke alarm shows up immediately.
|
||||
|
||||
To export more values, add an entry to the `mappings` table in [metrics.go](metrics.go).
|
||||
|
||||
## Example
|
||||
|
||||
```sh
|
||||
MQTT_BROKER=tcp://192.168.1.10:1883 MQTT_WILDCARD_TOPIC=+ go run .
|
||||
```
|
||||
72
config.go
Normal file
72
config.go
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"jonasled.dev/jonasled/go-libs/config"
|
||||
"jonasled.dev/jonasled/go-libs/log"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
ListenAddress string
|
||||
|
||||
MQTTBroker string
|
||||
MQTTClientID string
|
||||
MQTTUsername string
|
||||
MQTTPassword string
|
||||
MQTTQoS byte
|
||||
|
||||
// Topics are explicit device topic prefixes, e.g. "shellyplussmoke-halle-2".
|
||||
Topics []string
|
||||
// WildcardTopic is a topic prefix containing MQTT wildcards, e.g. "+" or "shellies/+".
|
||||
WildcardTopic string
|
||||
}
|
||||
|
||||
func loadConfig() Config {
|
||||
cfg := Config{
|
||||
ListenAddress: config.GetOrDefault("LISTEN_ADDRESS", ":9784"),
|
||||
MQTTBroker: config.GetOrFatal("MQTT_BROKER"),
|
||||
MQTTClientID: config.GetOrDefault("MQTT_CLIENT_ID", "shelly-prometheus-exporter"),
|
||||
MQTTUsername: config.GetOrDefault("MQTT_USERNAME", ""),
|
||||
MQTTPassword: config.GetOrDefault("MQTT_PASSWORD", ""),
|
||||
WildcardTopic: strings.Trim(config.GetOrDefault("MQTT_WILDCARD_TOPIC", ""), "/ "),
|
||||
}
|
||||
|
||||
qos, err := strconv.Atoi(config.GetOrDefault("MQTT_QOS", "0"))
|
||||
if err != nil || qos < 0 || qos > 2 {
|
||||
log.Log.Fatal("MQTT_QOS must be 0, 1 or 2")
|
||||
}
|
||||
cfg.MQTTQoS = byte(qos)
|
||||
|
||||
for _, topic := range strings.Split(config.GetOrDefault("MQTT_TOPICS", ""), ",") {
|
||||
topic = strings.Trim(topic, "/ ")
|
||||
if topic != "" {
|
||||
cfg.Topics = append(cfg.Topics, topic)
|
||||
}
|
||||
}
|
||||
|
||||
if len(cfg.Topics) == 0 && cfg.WildcardTopic == "" {
|
||||
log.Log.Fatal("At least one of MQTT_TOPICS or MQTT_WILDCARD_TOPIC must be set")
|
||||
}
|
||||
|
||||
return cfg
|
||||
}
|
||||
|
||||
// subscriptions returns all MQTT topic filters for the configured device prefixes.
|
||||
func (c Config) subscriptions() []string {
|
||||
prefixes := append([]string{}, c.Topics...)
|
||||
if c.WildcardTopic != "" {
|
||||
prefixes = append(prefixes, c.WildcardTopic)
|
||||
}
|
||||
|
||||
var subs []string
|
||||
for _, prefix := range prefixes {
|
||||
subs = append(subs,
|
||||
prefix+"/online",
|
||||
prefix+"/status/+",
|
||||
prefix+"/events/rpc",
|
||||
)
|
||||
}
|
||||
return subs
|
||||
}
|
||||
27
go.mod
Normal file
27
go.mod
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
module jonasled.dev/jonasled/shelly-prometheus-exporter
|
||||
|
||||
go 1.27.1
|
||||
|
||||
require (
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1
|
||||
github.com/joho/godotenv v1.5.1
|
||||
github.com/prometheus/client_golang v1.25.0
|
||||
jonasled.dev/jonasled/go-libs v0.0.4
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/kylelemons/godebug v1.1.0 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/prometheus/client_model v0.6.3 // indirect
|
||||
github.com/prometheus/common v0.72.0 // indirect
|
||||
github.com/prometheus/procfs v0.22.0 // indirect
|
||||
github.com/sirupsen/logrus v1.10.2 // indirect
|
||||
golang.org/x/net v0.59.0 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
google.golang.org/protobuf v1.36.12 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||
)
|
||||
48
go.sum
Normal file
48
go.sum
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1 h1:/VSOv3oDLlpqR2Epjn1Q7b2bSTplJIeV2ISgCl2W7nE=
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1/go.mod h1:1/yJCneuyOoCOzKSsOTUc0AJfpsItBGWvYpBLimhArU=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ=
|
||||
github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0=
|
||||
github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk=
|
||||
github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo=
|
||||
github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM=
|
||||
github.com/prometheus/common v0.72.0 h1:tAYsE+sPJxIncDAobm4H5aQjmox9ZxEIIqPbiffa8G4=
|
||||
github.com/prometheus/common v0.72.0/go.mod h1:77NWqAQ2tXT7BIK40qjJdw5Acrsrg1TlHAnsQi3i6mk=
|
||||
github.com/prometheus/procfs v0.22.0 h1:6q9+/JL9IKAPbCmBrv9n5O5Ty3NKnciV5X7YGw0oics=
|
||||
github.com/prometheus/procfs v0.22.0/go.mod h1:CvmFr/GVhIjIvWJZW3tgkODBQMRIf0EyWMQLHCHab58=
|
||||
github.com/sirupsen/logrus v1.10.2 h1:G2SED73/qrAu6YwbdxOD6peLkCBI3z7L+ykJFTXJBBo=
|
||||
github.com/sirupsen/logrus v1.10.2/go.mod h1:SLEg8TqYulVKKfIGHldVp2K2aYz2DKSVBq4g/H5bR7Q=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
|
||||
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
|
||||
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
|
||||
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
|
||||
jonasled.dev/jonasled/go-libs v0.0.4 h1:TGqAkzH7WrE/nZjWAUz7sb46rjxUewH/EmDrEr2ANzk=
|
||||
jonasled.dev/jonasled/go-libs v0.0.4/go.mod h1:y08q76iX3hMY+tt+fnfy9r4nyATONtSsaJ/oSDH/Aqw=
|
||||
36
main.go
Normal file
36
main.go
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
_ "github.com/joho/godotenv/autoload"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
"jonasled.dev/jonasled/go-libs/log"
|
||||
)
|
||||
|
||||
func main() {
|
||||
log.Init()
|
||||
cfg := loadConfig()
|
||||
|
||||
registerMetrics(prometheus.DefaultRegisterer)
|
||||
|
||||
client := connectMQTT(cfg)
|
||||
defer client.Disconnect(250)
|
||||
|
||||
http.Handle("/metrics", promhttp.Handler())
|
||||
go func() {
|
||||
log.Log.Infof("Serving metrics on %s/metrics", cfg.ListenAddress)
|
||||
if err := http.ListenAndServe(cfg.ListenAddress, nil); err != nil {
|
||||
log.Log.Fatalf("HTTP server failed: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
stop := make(chan os.Signal, 1)
|
||||
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
|
||||
<-stop
|
||||
log.Log.Info("Shutting down")
|
||||
}
|
||||
148
metrics.go
Normal file
148
metrics.go
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
)
|
||||
|
||||
// fieldMapping maps a single value inside a Shelly component status to a Prometheus gauge.
|
||||
type fieldMapping struct {
|
||||
// Component is the Shelly component type, e.g. "cloud" or "smoke".
|
||||
// Indexed components (e.g. "smoke:0") get an additional "id" label.
|
||||
Component string
|
||||
Indexed bool
|
||||
// Path is the JSON path inside the component status, e.g. ["battery", "V"].
|
||||
Path []string
|
||||
Gauge *prometheus.GaugeVec
|
||||
}
|
||||
|
||||
var (
|
||||
deviceLabels = []string{"device"}
|
||||
indexedLabels = []string{"device", "id"}
|
||||
|
||||
onlineGauge = prometheus.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Name: "shelly_online",
|
||||
Help: "Whether the device is online (1) or offline (0), as reported on the <device>/online topic.",
|
||||
}, deviceLabels)
|
||||
|
||||
lastSeenGauge = prometheus.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Name: "shelly_last_message_timestamp_seconds",
|
||||
Help: "Unix timestamp of the last MQTT message received from the device.",
|
||||
}, deviceLabels)
|
||||
|
||||
// mappings defines which status values get exported. Add new entries here to export more data.
|
||||
mappings = []fieldMapping{
|
||||
{
|
||||
Component: "cloud",
|
||||
Path: []string{"connected"},
|
||||
Gauge: prometheus.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Name: "shelly_cloud_connected",
|
||||
Help: "Whether the device is connected to the Shelly cloud.",
|
||||
}, deviceLabels),
|
||||
},
|
||||
{
|
||||
Component: "mqtt",
|
||||
Path: []string{"connected"},
|
||||
Gauge: prometheus.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Name: "shelly_mqtt_connected",
|
||||
Help: "Whether the device is connected to the MQTT broker.",
|
||||
}, deviceLabels),
|
||||
},
|
||||
{
|
||||
Component: "smoke",
|
||||
Indexed: true,
|
||||
Path: []string{"alarm"},
|
||||
Gauge: prometheus.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Name: "shelly_smoke_alarm",
|
||||
Help: "Whether the smoke alarm is active.",
|
||||
}, indexedLabels),
|
||||
},
|
||||
{
|
||||
Component: "smoke",
|
||||
Indexed: true,
|
||||
Path: []string{"mute"},
|
||||
Gauge: prometheus.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Name: "shelly_smoke_mute",
|
||||
Help: "Whether the smoke alarm is muted.",
|
||||
}, indexedLabels),
|
||||
},
|
||||
{
|
||||
Component: "devicepower",
|
||||
Indexed: true,
|
||||
Path: []string{"battery", "V"},
|
||||
Gauge: prometheus.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Name: "shelly_battery_voltage_volts",
|
||||
Help: "Battery voltage in volts.",
|
||||
}, indexedLabels),
|
||||
},
|
||||
{
|
||||
Component: "devicepower",
|
||||
Indexed: true,
|
||||
Path: []string{"battery", "percent"},
|
||||
Gauge: prometheus.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Name: "shelly_battery_percent",
|
||||
Help: "Battery charge in percent.",
|
||||
}, indexedLabels),
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
func registerMetrics(reg prometheus.Registerer) {
|
||||
reg.MustRegister(onlineGauge, lastSeenGauge)
|
||||
for _, m := range mappings {
|
||||
reg.MustRegister(m.Gauge)
|
||||
}
|
||||
}
|
||||
|
||||
// applyComponentStatus updates all gauges mapped to the given component.
|
||||
// key is the Shelly component key, e.g. "cloud" or "smoke:0". Missing fields are
|
||||
// ignored, so partial updates (NotifyStatus events) only touch the values they contain.
|
||||
func applyComponentStatus(device, key string, status map[string]any) {
|
||||
component, id, indexed := strings.Cut(key, ":")
|
||||
|
||||
for _, m := range mappings {
|
||||
if m.Component != component || m.Indexed != indexed {
|
||||
continue
|
||||
}
|
||||
value, ok := lookupNumber(status, m.Path)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if m.Indexed {
|
||||
m.Gauge.WithLabelValues(device, id).Set(value)
|
||||
} else {
|
||||
m.Gauge.WithLabelValues(device).Set(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// lookupNumber walks path inside data and converts the found value to a float.
|
||||
func lookupNumber(data map[string]any, path []string) (float64, bool) {
|
||||
var current any = data
|
||||
for _, key := range path {
|
||||
obj, ok := current.(map[string]any)
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
current, ok = obj[key]
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
return toFloat(current)
|
||||
}
|
||||
|
||||
func toFloat(v any) (float64, bool) {
|
||||
switch val := v.(type) {
|
||||
case float64:
|
||||
return val, true
|
||||
case bool:
|
||||
if val {
|
||||
return 1, true
|
||||
}
|
||||
return 0, true
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
122
mqtt.go
Normal file
122
mqtt.go
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
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()
|
||||
}
|
||||
76
mqtt_test.go
Normal file
76
mqtt_test.go
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus/testutil"
|
||||
)
|
||||
|
||||
type fakeMsg struct {
|
||||
topic string
|
||||
payload string
|
||||
}
|
||||
|
||||
func (m fakeMsg) Duplicate() bool { return false }
|
||||
func (m fakeMsg) Qos() byte { return 0 }
|
||||
func (m fakeMsg) Retained() bool { return false }
|
||||
func (m fakeMsg) Topic() string { return m.topic }
|
||||
func (m fakeMsg) MessageID() uint16 { return 0 }
|
||||
func (m fakeMsg) Payload() []byte { return []byte(m.payload) }
|
||||
func (m fakeMsg) Ack() {}
|
||||
|
||||
func gauge(t *testing.T, name string, labels ...string) float64 {
|
||||
t.Helper()
|
||||
if name == "shelly_online" {
|
||||
return testutil.ToFloat64(onlineGauge.WithLabelValues(labels...))
|
||||
}
|
||||
for _, m := range mappings {
|
||||
if testutil.CollectAndCount(m.Gauge, name) > 0 {
|
||||
return testutil.ToFloat64(m.Gauge.WithLabelValues(labels...))
|
||||
}
|
||||
}
|
||||
t.Fatalf("metric %s not found", name)
|
||||
return 0
|
||||
}
|
||||
|
||||
func TestHandleMessage(t *testing.T) {
|
||||
const dev = "shellyplussmoke-halle-2"
|
||||
for _, m := range []fakeMsg{
|
||||
{dev + "/online", "false"},
|
||||
{dev + "/status/cloud", `{"connected":true}`},
|
||||
{dev + "/status/mqtt", `{"connected":true}`},
|
||||
{dev + "/status/smoke:0", `{"id":0,"alarm":false, "mute":false}`},
|
||||
{dev + "/status/devicepower:0", `{"id": 0,"battery":{"V":2.98, "percent":95}}`},
|
||||
} {
|
||||
handleMessage(nil, m)
|
||||
}
|
||||
|
||||
checks := []struct {
|
||||
name string
|
||||
labels []string
|
||||
want float64
|
||||
}{
|
||||
{"shelly_online", []string{dev}, 0},
|
||||
{"shelly_cloud_connected", []string{dev}, 1},
|
||||
{"shelly_mqtt_connected", []string{dev}, 1},
|
||||
{"shelly_smoke_alarm", []string{dev, "0"}, 0},
|
||||
{"shelly_smoke_mute", []string{dev, "0"}, 0},
|
||||
{"shelly_battery_voltage_volts", []string{dev, "0"}, 2.98},
|
||||
{"shelly_battery_percent", []string{dev, "0"}, 95},
|
||||
}
|
||||
for _, c := range checks {
|
||||
if got := gauge(t, c.name, c.labels...); got != c.want {
|
||||
t.Errorf("%s = %v, want %v", c.name, got, c.want)
|
||||
}
|
||||
}
|
||||
|
||||
// A NotifyStatus event only updates the fields it contains.
|
||||
handleMessage(nil, fakeMsg{dev + "/events/rpc",
|
||||
`{"src":"x","method":"NotifyStatus","params":{"ts":1.5,"smoke:0":{"alarm":true}}}`})
|
||||
if got := gauge(t, "shelly_smoke_alarm", dev, "0"); got != 1 {
|
||||
t.Errorf("alarm after event = %v, want 1", got)
|
||||
}
|
||||
if got := gauge(t, "shelly_battery_percent", dev, "0"); got != 95 {
|
||||
t.Errorf("battery changed by unrelated event: %v", got)
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue