Connecting Custom Data Sources#

This guide shows how to connect Fusion Graphs to data sources that MuFASA doesn’t support out of the box, with a focus on live data from sensors and other external systems. Which approach fits depends on where your data comes from:

Your data comes from …

Approach

a file or a list you already have in Python

No new node: convert it and use a LocationInput or MapInput

a recorded format MuFASA doesn’t know

An InputNode that returns all items at once, see For Recorded Sources

a library you ask for the next message (pull client)

A StreamingInputNode whose items() yields the messages, see For Pull Clients

a library that calls you back with each message (push client)

A StreamingInputNode that ingest()s the messages, see For Push Clients

For real messaging systems such as MQTT or ROS 2, see Going Live.

For Recorded Sources#

Recorded data is the simple case: subclass an InputNode (that is not a StreamingInputNode) and return all your data at once from items(). CsvInput in Writing a Node shows a complete example that reads a CSV file.

You don’t need a new node!

Just read and convert the data beforehand and pass it in via a LocationInput or MapInput node.

The rest of this guide covers live data.

You don’t need a new node!

Implementing a new node might just be overkill in some situations. The same goals might be achieved by some boilerplate preparation code. In the spirit of rapid prototyping, these boxes highlight how to use your custom data with existing core inputs.

Implementing a dedicated node has some advantages, too:

  • It gives you a coherent unit of code that you can share with others, for example by contributing it back to MuFASA.

  • It allows you to serialize and re-import your Fusion Graph (see JSON Serialization).

  • It makes your extensions explicit in the Fusion Graph and visible at a glance.

Simulating a Live Sensor#

Throughout this guide, we simulate a live sensor by a TCP server that sends detections as GeoJSON Features over each connection, one per line with a random few seconds delay in between. The demo server and client code is largely based on Python’s official socketserver examples[1].

Sensor simulation TCP server

# FeatureSendingRequestHandler

import json
import socketserver
import time

SEP = b"\r\n"

with open("sensor_b.geojson") as features_file:
    features = json.load(features_file)["features"]

features_bin = [json.dumps(f).encode() + SEP for f in features]

class FeatureSendingRequestHandler(socketserver.BaseRequestHandler):
    """Simulates a sensor that is sending GeoJSON Feature lines"""

    def handle(self):
        for feature in features_bin:
            self.request.sendall(feature)
            time.sleep(.1 + .1 * random.random())


# server_thread

import contextlib
import threading

ADDRESS = "localhost", 8765

# Allow reusing the same port immediately after server shutdown (for repeated calls)
socketserver.ThreadingTCPServer.allow_reuse_address = True

@contextlib.contextmanager
def on_bg_thread(target, *args, **kwargs):
    t = threading.Thread(target=target, args=args, kwargs=kwargs)
    t.start()
    try:
        yield
    finally:
        t.join()

@contextlib.contextmanager
def server_thread(address: tuple[str, int], handler: socketserver.BaseRequestHandler):
    """Starts a sensor server on a separate thread on enter and shuts it down on exit"""
    with (
        socketserver.ThreadingTCPServer(address, handler) as server,
        on_bg_thread(server.serve_forever),
    ):
        try:
            yield
        finally:
            server.shutdown()

Note

For this tutorial, we use a context manager for starting and stopping the server that you wrap your fusion code with like so:

with server_thread(ADDRESS, FeatureSendingRequestHandler):  # Demo only!
    graph.run()

In a real-world scenario, you don’t need something equivalent! You certainly have an externally managed sensor. Within the fusion code, you’d take it for granted that the system is up and running.

Integration Basics#

To use that demo sensor in fusion systems, we extend MuFASA with a custom InputNode subclass. They are responsible for connecting to the data streams of external systems and for converting them to MuFASA’s own data models. And since it is a live sensor – and we want continuous updates to our outputs[2] – we implement a streaming one derived from StreamingInputNode.

Here’s a quick checklist that applies to every input node:

☑

Ref

Requirement

Notes

☑

#1

Derives from InputNode.

Extending StreamingInputNode signals to the Graph that the node will do blocking calls to wait for new messages.

☑

#2

Specifies its _output_type.

In this example, we equivalently could have subclassed ObservationStreamingInput to inherit producing Observation.

☑

#3

Converts to its output type.

We provide a helper function in this example that we will use later in concrete subclasses.

☐

#4a

Yields its data from items().

This will depend on the type of input node and be implemented in subclasses in the following sections.

☐

#4b

Or ingest()s data items.

For StreamingInputNodes only!

☑

#5a

Exports its parameters in get_config().

☐

#5b

Registers with the NODE_REGISTRY for imports.

Needs to be done for each concrete subclass separately.

Checked items are covered by GeoJsonObservationStreamingInput implemented below that serves as a base in the following concrete sections. The #N references annotate respective lines in code samples and their explanations.

from mufasa.location import Observation
from mufasa.io.inputs import StreamingInputNode
from shapely.geometry.geo import shape

_start_time = time.monotonic()

class GeoJsonObservationStreamingInput(StreamingInputNode):  #1
    _output_type = Observation  #2

    def __init__(
            self,
            address: tuple[str, int],
            ts_col: str = "timestamp",
            conf_col: str = "confidence",
            props_default: dict[str, "Any"] | None = None,
    ):
        super().__init__()
        self.address = address
        self.ts_col = ts_col
        self.conf_col = conf_col
        self.props_default = props_default if props_default is not None else {}

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

    def get_config(self) -> dict:  #5a
        return {
            "address": self.address,
            "ts_col": self.ts_col,
            "conf_col": self.conf_col,
            "props_default": self.props_default
        }

For Pull Clients#

Pull clients provide either a function that blocks to wait for a single message or a generator function that does so repeatedly, yielding the messages. We go for a generator function in this example. You can easily replace it with a receiver function called in a loop.

Sensor simulation TCP pull client

import random
import socket

def sock_recv_lines(address: tuple[str, int]):
    """Yields lines of text received from a socket connected to the given address"""
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.connect(address)
        yield from sock.makefile()

Pull client usage outside MuFASA

with server_thread(ADDRESS, FeatureSendingRequestHandler):
    for line in sock_recv_lines(ADDRESS):
            print(f"[client] received data:", line)
[client] received data: {"type": "Feature", "geometry": {"type": "Point", "coordinates": [16.426643559839174, 48.268408685767966]}, "properties": {"confidence": 0.9433776719597745}}

[client] received data: {"type": "Feature", "geometry": {"type": "Point", "coordinates": [16.426838778147946, 48.26916496293138]}, "properties": {"confidence": 0.5543464775591364, "headquarters": true}}
[client] received data: {"type": "Feature", "geometry": {"type": "Point", "coordinates": [16.427123796877638, 48.26961976340052]}, "properties": {"confidence": 0.7896239763630372}}

To integrate it, we overwrite items()#4a so that it yields the messages from the generator after conversion#3. We derive the node from the one developed in Integration Basics#1 to inherit output type, conversion and config logic and also register the node for later imports#5b.

from mufasa.registry import NODE_REGISTRY

class GeoJsonObservationPullInput(GeoJsonObservationStreamingInput):  #1
    def items(self):  #4a
        for line in sock_recv_lines(self.address):
            yield self.feature_to_observation(line)  #3

NODE_REGISTRY[GeoJsonObservationPullInput.__name__] = GeoJsonObservationPullInput  #5b

Usage:

from mufasa import Graph
from mufasa.io.outputs import LocationOutput

pull_a = GeoJsonObservationPullInput(ADDRESS, props_default={"track": "A"})
pull_b = GeoJsonObservationPullInput(ADDRESS, props_default={"track": "B"})
pull_out = LocationOutput()(pull_a, pull_b)
pull_graph = Graph([pull_a, pull_b], [pull_out])

pull_graph.plot_graph()
/tmp/ipykernel_206/3619763805.py:7: 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.
  pull_graph = Graph([pull_a, pull_b], [pull_out])
GJOGeoJsonObservationPullInputLocation family: ObservationObservationGJOGeoJsonObservationPullInputLocation family: ObservationObservationLOLocationOutputLocation family: LocationLocation
with server_thread(ADDRESS, FeatureSendingRequestHandler):  # Demo only!
    pull_graph.run()

pull_out.result
[Observation(geometry=<POINT (16.427 48.268)>, timestamp=5.919861100000077, properties={'track': 'A'}, confidence=0.9433776719597745),
 Observation(geometry=<POINT (16.427 48.268)>, timestamp=5.922791320000016, properties={'track': 'B'}, confidence=0.9433776719597745),
 Observation(geometry=<POINT (16.427 48.269)>, timestamp=6.9637558000000865, properties={'track': 'A', 'headquarters': True}, confidence=0.5543464775591364),
 Observation(geometry=<POINT (16.427 48.269)>, timestamp=7.873165200000045, properties={'track': 'B', 'headquarters': True}, confidence=0.5543464775591364),
 Observation(geometry=<POINT (16.427 48.27)>, timestamp=8.391380540000029, properties={'track': 'A'}, confidence=0.7896239763630372),
 Observation(geometry=<POINT (16.427 48.27)>, timestamp=9.758352900000062, properties={'track': 'B'}, confidence=0.7896239763630372)]

For Push Clients#

Push clients have their own blocking event loops that push each message received to a user-supplied callback function.

Sensor simulation TCP push client

def sock_recv_loop(address: tuple[str, int], callback, end_msg):
    """Pulls lines of text from a socket connected to address and pushes them to callback"""
    for line in sock_recv_lines(address):
        callback(line)
    callback(end_msg)

Push client usage outside MuFASA

def cb(msg):
    if msg == "END":
        print("-- END --")
    else:
        print(f"[client] received data:", line)

with server_thread(ADDRESS, FeatureSendingRequestHandler):
    sock_recv_loop(ADDRESS, cb, "END")
[client] received data: {"type": "Feature", "geometry": {"type": "Point", "coordinates": [16.427123796877638, 48.26961976340052]}, "properties": {"confidence": 0.7896239763630372}}

[client] received data: {"type": "Feature", "geometry": {"type": "Point", "coordinates": [16.427123796877638, 48.26961976340052]}, "properties": {"confidence": 0.7896239763630372}}
[client] received data: {"type": "Feature", "geometry": {"type": "Point", "coordinates": [16.427123796877638, 48.26961976340052]}, "properties": {"confidence": 0.7896239763630372}}

-- END --

To integrate them, we overwrite items()#4a to run the loop on a background thread#A. Yield from its superclass implementation#B to forward ingested data! The callback function uses ingest()#4b to pass the converted data on (Internally, there’s a queue connecting those two). This example uses a dedicated end message to stop()#C what indicates the data stream’s end. You have to have some end condition or else graph.run() will go forever – even though sensor data streams are typically endless. Finally, we derive this node from the one developed in Integration Basics#1 to inherit output type, conversion and config logic and also register the node for imports#5b.

class GeoJsonObservationPushInput(GeoJsonObservationStreamingInput):  #1
    END_MSG = "END"

    def items(self):  #4a
        with on_bg_thread(sock_recv_loop, self.address, self.ingest_message, self.END_MSG):  #A
            yield from super().items() #B

    def ingest_message(self, msg: str) -> None:
        if msg == self.END_MSG:  #C
            self.stop()
        else:
            self.ingest(self.feature_to_observation(msg))  #3 #4b

NODE_REGISTRY[GeoJsonObservationPushInput.__name__] = GeoJsonObservationPushInput  #5b

Usage:

push_a = GeoJsonObservationPushInput(ADDRESS, props_default={"track": "A"})
push_b = GeoJsonObservationPushInput(ADDRESS, props_default={"track": "B"})
push_out = LocationOutput()(push_a, push_b)
push_graph = Graph([push_a, push_b], [push_out])

push_graph.plot_graph()
/tmp/ipykernel_206/892259989.py:4: 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.
  push_graph = Graph([push_a, push_b], [push_out])
GJOGeoJsonObservationPushInputLocation family: ObservationObservationGJOGeoJsonObservationPushInputLocation family: ObservationObservationLOLocationOutputLocation family: LocationLocation
with server_thread(ADDRESS, FeatureSendingRequestHandler):  # Demo only!
    push_graph.run()

push_out.result
[Observation(geometry=<POINT (16.427 48.268)>, timestamp=21.260781590000022, properties={'track': 'A'}, confidence=0.9433776719597745),
 Observation(geometry=<POINT (16.427 48.268)>, timestamp=21.26449012000009, properties={'track': 'B'}, confidence=0.9433776719597745),
 Observation(geometry=<POINT (16.427 48.269)>, timestamp=22.659236150000055, properties={'track': 'A', 'headquarters': True}, confidence=0.5543464775591364),
 Observation(geometry=<POINT (16.427 48.269)>, timestamp=23.093807640000108, properties={'track': 'B', 'headquarters': True}, confidence=0.5543464775591364),
 Observation(geometry=<POINT (16.427 48.27)>, timestamp=24.657258140000096, properties={'track': 'A'}, confidence=0.7896239763630372),
 Observation(geometry=<POINT (16.427 48.27)>, timestamp=24.95757544, properties={'track': 'B'}, confidence=0.7896239763630372)]

You don’t need a new node!

Use a plain ObservationStreamingInput node (or similar as appropriate to your use case). Write a new callback function that you pass to your client library. Integrate your conversion logic there and make it call ingest() of your plain node instance.

Alternative core node + boilerplate code

from mufasa.io.inputs import ObservationStreamingInput
from functools import partial

alt_a = ObservationStreamingInput()
alt_b = ObservationStreamingInput()
alt_out = LocationOutput()(alt_a, alt_b)
alt_graph = Graph([alt_a, alt_b], [alt_out])

def push_cb(node: ObservationStreamingInput, props_default: dict, msg: str):
    if msg == "END":
        node.stop()
    else:
        # Conversion logic and ingest() inside callback
        feature = json.loads(msg)
        geom = shape(feature["geometry"])
        props = props_default | feature.get("properties", {})
        # Utilize upscaled arrival timestamp for demo purposes!
        ts = props.pop("timestamp", 10 * (time.monotonic() - _start_time))
        conf = props.pop("confidence", Observation.confidence)
        node.ingest(Observation(geom, ts, props, conf))

with (
    server_thread(ADDRESS, FeatureSendingRequestHandler),  # Demo only!
    # Start reception loops outside MuFASA and pass callbacks that ingest()
    on_bg_thread(sock_recv_loop, ADDRESS, partial(push_cb, alt_a, {"track": "A"}), "END"),
    on_bg_thread(sock_recv_loop, ADDRESS, partial(push_cb, alt_b, {"track": "B"}), "END"),
):
    alt_graph.run()

alt_out.result
/tmp/ipykernel_206/3389171579.py:7: 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.
  alt_graph = Graph([alt_a, alt_b], [alt_out])
[Observation(geometry=<POINT (16.427 48.268)>, timestamp=31.38362917000009, properties={'track': 'A'}, confidence=0.9433776719597745),
 Observation(geometry=<POINT (16.427 48.268)>, timestamp=31.38653540000007, properties={'track': 'B'}, confidence=0.9433776719597745),
 Observation(geometry=<POINT (16.427 48.269)>, timestamp=32.60594906999998, properties={'track': 'A', 'headquarters': True}, confidence=0.5543464775591364),
 Observation(geometry=<POINT (16.427 48.269)>, timestamp=32.986516890000104, properties={'track': 'B', 'headquarters': True}, confidence=0.5543464775591364),
 Observation(geometry=<POINT (16.427 48.27)>, timestamp=33.89971692000003, properties={'track': 'A'}, confidence=0.7896239763630372),
 Observation(geometry=<POINT (16.427 48.27)>, timestamp=34.40065557000011, properties={'track': 'B'}, confidence=0.7896239763630372)]