MQTT bridge: how do I read a sensor from an MQTT broker and publish a score, or a command, from a Dense-Armor model?¶
MQTT is the messaging of Home Assistant, Zigbee2MQTT, Tasmota and ESPHome: a device publishes a reading on a topic, and anyone who subscribes to the topic receives it. MQTTBridge subscribes to one topic, gives each reading to a Dense-Armor model, and publishes the answer on another topic.
By default the bridge only reads and reports. It sends a command to a device only when you ask for it, with limits.
1. A fridge sensor in, an anomaly score out¶
The payload of a reading is a JSON object, {"t": 4.0}, or a bare number when names has one name. The bridge asks the model first and learns after, so a reading is never scored with itself. The model below is HampelScorer; the broker is a small class with a publish method, so the example needs no network.
import json
from dense_armor.bridges.mqtt import MQTTBridge
from dense_armor.core.online.anomaly.filters import HampelScorer
class Broker:
def __init__(self):
self.sent = []
def publish(self, topic, payload):
self.sent.append((topic, payload))
c = Broker()
b = MQTTBridge(HampelScorer(), "cucina/frigo/temp", "cucina/frigo/anomalia", client=c)
for t in [4.0, 4.1, 3.9, 4.0, 4.2, 4.0, 3.9, 4.1, 4.0, 9.5]:
b.handle(json.dumps({"t": t}))
for topic, p in c.sent[-3:]:
print(topic, p)
cucina/frigo/anomalia {"value": 0.6744914027217203}
cucina/frigo/anomalia {"value": 0.0}
cucina/frigo/anomalia {"value": 37.097027149694746}
The last reading, 9.5 degrees, scores 37; the usual ones score under 1. With a real broker you do not pass client: b.connect("localhost", 1883) subscribes to the topic and b.run() serves the messages.
A payload that is not valid JSON, or has a value that is not a number, is dropped: nothing is published and the model does not learn it.
2. A command to a device¶
A model can also drive a device, for example a target temperature. That is off by default: allow_command=True needs command_topic and limits.
b = MQTTBridge(
model, "casa/sensore", "casa/previsione", output="predict",
allow_command=True, command_topic="casa/caldaia/set", limits=(15.0, 24.0), min_interval_s=60.0,
)
The value is clipped to limits, so a model that says 99 sends 24. It is not sent at all when it is None, nan or infinite. And it is sent at most once every min_interval_s seconds. The report on out_topic is published for every reading, the command only when these three conditions hold.
3. Matter and CoAP¶
The bridge speaks MQTT only. Matter devices reach MQTT through Home Assistant, and CoAP through a gateway; neither needs a bridge of its own here.
The parameters¶
MQTTBridge ¶
MQTTBridge(
model: Any,
in_topic: str,
out_topic: str,
names: Sequence[str] | None = None,
output: str = "score",
allow_command: bool = False,
command_topic: str | None = None,
limits: tuple[float, float] | None = None,
min_interval_s: float = 1.0,
client: Any = None,
clock: Callable[[], float] = time.monotonic,
)
Connect a Dense-Armor model to an MQTT broker.
Each message on in_topic is one sample. The payload is a JSON object
{"name": value, ...}, or a single number (then names must have one
name). The model sees the sample as a dict. The bridge asks the model first
and learns after, so the answer is never made with the sample it has just
learned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Any
|
any object with |
required |
in_topic
|
str
|
topic to read. |
required |
out_topic
|
str
|
topic where the score or the prediction is published, as
JSON |
required |
names
|
Sequence[str] | None
|
names of the channels, needed when the payload is a bare number. |
None
|
output
|
str
|
|
'score'
|
allow_command
|
bool
|
|
False
|
command_topic
|
str | None
|
topic of the device, required with |
None
|
limits
|
tuple[float, float] | None
|
|
None
|
min_interval_s
|
float
|
minimum seconds between two commands, default 1.0. |
1.0
|
client
|
Any
|
an MQTT client with |
None
|
clock
|
Callable[[], float]
|
function that returns seconds, default |
monotonic
|
Raises:
| Type | Description |
|---|---|
ValueError
|
if |
Source code in dense_armor/bridges/mqtt.py
connect ¶
run ¶
handle ¶
Process one payload. Returns the value published, or None.
A payload that is not valid JSON or has a non-numeric value is
dropped: it returns None and publishes nothing.
Source code in dense_armor/bridges/mqtt.py
Details¶
The bridge needs pip install dense-armor[mqtt], which installs paho-mqtt 2 or later. A score of inf, which HampelScorer gives on a flat window, is published as Infinity, which a strict JSON parser rejects.