Skip to content

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 learn_one(x) and score_one(x) (or predict_one(x) when output="predict").

required
in_topic str

topic to read.

required
out_topic str

topic where the score or the prediction is published, as JSON {"value": v}.

required
names Sequence[str] | None

names of the channels, needed when the payload is a bare number.

None
output str

"score" (default) uses score_one; "predict" uses predict_one.

'score'
allow_command bool

False (default) never sends a command.

False
command_topic str | None

topic of the device, required with allow_command.

None
limits tuple[float, float] | None

(low, high) the command is clipped to, required with allow_command.

None
min_interval_s float

minimum seconds between two commands, default 1.0.

1.0
client Any

an MQTT client with publish and subscribe. None (default) builds a paho client; connect then needs host.

None
clock Callable[[], float]

function that returns seconds, default time.monotonic.

monotonic

Raises:

Type Description
ValueError

if allow_command is set without command_topic or limits, if limits has low > high, or if output is not "score" or "predict".

Source code in dense_armor/bridges/mqtt.py
def __init__(
    self,
    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,
) -> None:
    if output not in ("score", "predict"):
        raise ValueError("output must be 'score' or 'predict'")
    if allow_command:
        if command_topic is None or limits is None:
            raise ValueError("allow_command needs command_topic and limits")
        if limits[0] > limits[1]:
            raise ValueError("limits must be (low, high) with low <= high")
    self.model = model
    self.in_topic = in_topic
    self.out_topic = out_topic
    self.names = list(names) if names is not None else None
    self.output = output
    self.allow_command = allow_command
    self.command_topic = command_topic
    self.limits = tuple(limits) if limits is not None else None
    self.min_interval_s = float(min_interval_s)
    self._clock = clock
    self._last_command = None
    self.client = client if client is not None else _paho.Client(_paho.CallbackAPIVersion.VERSION2)
    self.client.on_message = self._on_message

connect

connect(host='localhost', port=1883)

Connect to the broker and subscribe to in_topic.

Source code in dense_armor/bridges/mqtt.py
def connect(self, host="localhost", port=1883):
    """Connect to the broker and subscribe to ``in_topic``."""
    self.client.connect(host, port)
    self.client.subscribe(self.in_topic)

run

run()

Block and serve messages until the connection is closed.

Source code in dense_armor/bridges/mqtt.py
def run(self):
    """Block and serve messages until the connection is closed."""
    self.client.loop_forever()

handle

handle(payload)

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
def handle(self, payload):
    """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.
    """
    try:
        x = self._sample(payload)
    except (ValueError, TypeError):
        return None
    fn = self.model.score_one if self.output == "score" else self.model.predict_one
    value = fn(x)
    self.model.learn_one(x)
    if value is None:
        return None
    self.client.publish(self.out_topic, json.dumps({"value": value}, default=float))
    if self.allow_command:
        self._command(value)
    return value

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.