MQTT#

This example sends input and output data over MQTT[1] for a more realistic scenario. We will use the Paho[2] MQTT client library, so install it with:

pip install paho-mqtt

Subscriber for Inputs#

Since Paho offers a push client, the input node is similar to the one defined in For Push Clients. The most notable difference is that we need to disconnect the client#D when we want to truly stop receiving data or else it will stay subscribed to the topic forever.

def bg_thread(...):

import contextlib
import threading

@contextlib.contextmanager
def bg_thread(target, *args, **kwargs):
    t = threading.Thread(target=target, args=args, kwargs=kwargs)
    t.start()
    try:
        yield
    finally:
        t.join()
from typing import Callable

from mufasa import Observation
from mufasa.io.inputs import ObservationStreamingInput

from paho.mqtt import client as mqtt
from paho.mqtt import subscribe

DECODER = Callable[[bytes], Observation]


class MqttInput(ObservationStreamingInput):  #1  #2
    def __init__(self, host: str, port: int, topic: str, decoder: DECODER):
        super().__init__()
        self.host = host
        self.port = port
        self.topic = topic
        self.decode = decoder

    def items(self):  #4a
        with bg_thread(
            subscribe.callback,
            self.paho_ingest_message,
            self.topic,
            0,
            None,
            self.host,
            self.port,
            "mqtt_input_" + self.topic,
        ):  #A
            yield from super().items()  #B

    def paho_ingest_message(self, client: mqtt.Client, _, msg: mqtt.MQTTMessage):
        content = msg.payload
        if content == b"END":  #C - Application-specific termination condition!
            self.stop()
            # Disconnect the client so that the subscriber thread finishes
            client.disconnect()  #D
        else:
            self.ingest(self.decode(content))  #3 #4b

Note that the message conversion is left out in the node above and delegated to a decoder function. This is because MQTT specifies the transport, but not the structure of the message payload – That is specific to your setup! As a consequence, the node’s config (that would need to include the decoder Python function) isn’t JSON-serializable, and we don’t add it to the NODE_REGISTRY.

In this example, we assume that the payload is a GeoJSON Feature and use the following decoder function:

import json
import time

from shapely.geometry.geo import shape

_start_time = time.monotonic()


def feat_to_obs(
    raw: str | bytes, ts_k: str = "timestamp", conf_k: str = "confidence", **dfs,
) -> Observation:
    """Converts a GeoJSON Feature to a MuFASA Observation"""
    feature = json.loads(raw)
    geom = shape(feature["geometry"])
    props = dfs | feature.get("properties", {})
    # Utilize upscaled arrival timestamp for demo purposes!
    ts = props.pop(ts_k, 10 * (time.monotonic() - _start_time))
    conf = props.pop(conf_k, Observation.confidence)
    return Observation(geom, ts, props, conf)

Publisher for Outputs#

The MqttOutput node publishes every Location it gets via process(). This implementation initializes the MQTT client only when the first message is to be published. This allows us to construct and plot a graph without having the broker running already, but you could also do it in __init__(). The connection will be closed in save() since it is called after all processing finished.

The Location encoder defaults to simply using its string representation, and we will stick to that in this example.

from mufasa import Location
from mufasa.io.outputs import OutputNode

ENCODER = Callable[[Location], str]


class MqttOutput(OutputNode):
    _input_types = {Location}

    def __init__(self, host: str, port: int, topic: str, encoder: ENCODER = str):
        super().__init__()
        self.host = host
        self.port = port
        self.topic = topic
        self.encode = encoder
        self.client = None
        self.msgs = set()

    def process(self, loc: Location) -> None:
        """Publishes the given location over MQTT"""
        if self.client is None:
            # Connect to the broker only here so it's part of graph.run()
            self.client = mqtt.Client(
                mqtt.CallbackAPIVersion.VERSION2, "mqtt_output_" + self.topic
            )
            self.client.connect(self.host, self.port)
            self.client.loop_start()
        self.msgs.add(self.client.publish(self.topic, self.encode(loc)))

    def save(self) -> None:
        """Disconnect from the MQTT broker"""
        if self.client is not None:
            for msg in self.msgs:
                msg.wait_for_publish()
            self.client.disconnect()
            self.client.loop_stop()  # join thread

    def get_config(self):
        raise TypeError("Not JSON-serializable!")  # Due to encoder function

Running the Example#

To run this example, start a MQTT broker running in the background, for example Eclipse Mosquitto via Docker[3]:

docker run -p 1883:1883 eclipse-mosquitto

To simulate a sensor, we use a simple script publishing detections as GeoJSON Features from a file.

Publisher simulating a sensor

import random


def sim_pub_mqtt(host: str, port: int, topic: str, file: str):
    """Publishes GeoJSON Features from a file over MQTT to simulate a server"""
    time.sleep(2)  # Startup delay (demo only)

    with open(file) as f:
        geojson = json.load(f)

    features = [json.dumps(f).encode() for f in geojson["features"]]

    client = mqtt.Client( mqtt.CallbackAPIVersion.VERSION2, "sim_pub_" + topic)
    client.connect(host, port)
    client.loop_start()
    try:
        try:
            time.sleep(2)
            for feature in features:
                client.publish(topic, feature)
                time.sleep(.1 + .1 * random.random())
            client.publish(topic, b"END")
        finally:
            client.disconnect()
    finally:
        client.loop_stop()  # Join thread

To see the results, we need a subscriber for the output topic:

Subscriber to fusion results

def sniff_sub_cb(client: mqtt.Client, userdata, message: mqtt.MQTTMessage):
    print("Topic", message.topic, "received message", message.payload)
    userdata["count"] -= 1
    if userdata["count"] == 0:
        client.disconnect()

Define a Fusion Graph.

from functools import partial

from mufasa import Graph

HOST = "localhost"
PORT = 1883

mqtt_a = MqttInput(HOST, PORT, "sensor/a", partial(feat_to_obs, track="A"))
mqtt_b = MqttInput(HOST, PORT, "sensor/b", partial(feat_to_obs, track="B"))
mqtt_out = MqttOutput(HOST, PORT, "mufasa")(mqtt_a, mqtt_b)
mqtt_graph = Graph([mqtt_a, mqtt_b], [mqtt_out])

mqtt_graph.plot_graph()
/tmp/ipykernel_253/899355525.py:11: UserWarning: No CRS specified. Ensure all input data is already in a Cartesian coordinate system with units of metres (e.g. a UTM projection). Using geographic coordinates (WGS84 degrees) will produce incorrect distances and unexpected behaviour.
  mqtt_graph = Graph([mqtt_a, mqtt_b], [mqtt_out])
MIMqttInputLocation family: ObservationObservationMIMqttInputLocation family: ObservationObservationMOMqttOutputLocation family: LocationLocation

Finally, start the sensor simulation publishers for both sensor_a.geojson and sensor_b.geojson and the results sniffer, then run the graph.

# Sensor and sniffer threads for demo only!
with (
    bg_thread(subscribe.callback, sniff_sub_cb, "mufasa", 0, {"count": 6}, HOST, PORT, "sniffer"),
    bg_thread(sim_pub_mqtt, HOST, PORT, "sensor/a", "sensor_a.geojson"),
    bg_thread(sim_pub_mqtt, HOST, PORT, "sensor/b", "sensor_b.geojson"),
):
    mqtt_graph.run()
Topic mufasa received message b"Observation(geometry=<POLYGON ((16.427 48.27, 16.427 48.27, 16.428 48.269, 16.428 48.27, 16.427 4...>, timestamp=40.76523096999992, properties={'track': 'A'}, confidence=0.2467114797992355)"
Topic mufasa received message b"Observation(geometry=<POINT (16.427 48.268)>, timestamp=40.768223620000015, properties={'track': 'B'}, confidence=0.9433776719597745)"
Topic mufasa received message b"Observation(geometry=<POINT (16.427 48.269)>, timestamp=41.96897973999995, properties={'track': 'B', 'headquarters': True}, confidence=0.5543464775591364)"
Topic mufasa received message b"Observation(geometry=<POLYGON ((16.427 48.269, 16.427 48.269, 16.428 48.269, 16.428 48.269, 16.42...>, timestamp=42.202495539999916, properties={'track': 'A', 'headquarters': True}, confidence=0.8718633463627452)"
Client is not connected. Socket: None). Last known Connection State: MQTT_CS_DISCONNECTED
Client is not connected. Socket: None). Last known Connection State: MQTT_CS_DISCONNECTED
Client is not connected. Socket: None). Last known Connection State: MQTT_CS_DISCONNECTED
Topic mufasa received message b"Observation(geometry=<POLYGON ((16.427 48.269, 16.427 48.268, 16.427 48.268, 16.428 48.268, 16.42...>, timestamp=43.41291241999997, properties={'track': 'A'}, confidence=0.6814251738380194)"
Topic mufasa received message b"Observation(geometry=<POINT (16.427 48.27)>, timestamp=43.735993760000014, properties={'track': 'B'}, confidence=0.7896239763630372)"