kpetremann / mqtt-exporter

Simple generic MQTT Prometheus exporter for IoT working out of the box
https://hub.docker.com/r/kpetrem/mqtt-exporter
MIT License
103 stars 29 forks source link

Handle plain state value string in raw_payload #83

Closed mortenlj closed 3 months ago

mortenlj commented 3 months ago

Fixes/Implement: #82

Description:

When parsing a message, check if it is one of the defined STATE_VALUES, and in that case, use that value instead of trying to parse using JSON.

Before the commit:

See the linked issue.

After the commit:

topic: freezer_open_detector/binary_sensor/freezer_open/state
payload: OFF

## Debug ##

parsed to: freezer_open_detector_binary_sensor {'state': 0}
INFO:mqtt-exporter:creating prometheus metric: PromMetricId(name='mqtt_state', labels=())

## Result ##

# HELP mqtt_state metric generated from MQTT message.
# TYPE mqtt_state gauge
mqtt_state{topic="freezer_open_detector_binary_sensor"} 0.0
mortenlj commented 3 months ago

Should be a fairly safe change.

json.loads normally does the decode from bytes to string, but by moving that out it was possible to compare with the keys in STATE_VALUES, and pick a value directly from there instead of trying to parse it using json.loads.

Strictly speaking, it is sort of random luck that this works for numeric values, because esphome doesn't actually consider the payload to be JSON. It just happens that the textual representation of numeric values is exactly the representation JSON uses for numeric values. Still, it works, so I didn't think there was any point in changing how that works.

kpetremann commented 3 months ago

thanks for the contribution :)