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 |
a recorded format MuFASA doesn’t know |
An |
a library you ask for the next message (pull client) |
A |
a library that calls you back with each message (push client) |
A |
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].
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 |
Extending |
☑ |
#2 |
Specifies its |
In this example, we equivalently could have subclassed |
☑ |
#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 |
This will depend on the type of input node and be implemented in subclasses in the following sections. |
☐ |
#4b |
Or |
For |
☑ |
#5a |
Exports its parameters in |
|
☐ |
#5b |
Registers with the |
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.
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])
with server_thread(ADDRESS, FeatureSendingRequestHandler): # Demo only!
pull_graph.run()
pull_out.result
[Observation(geometry=<POINT (16.427 48.268)>, timestamp=5.601496069999996, properties={'track': 'A'}, confidence=0.9433776719597745),
Observation(geometry=<POINT (16.427 48.268)>, timestamp=5.602808489999944, properties={'track': 'B'}, confidence=0.9433776719597745),
Observation(geometry=<POINT (16.427 48.269)>, timestamp=6.918856310000052, properties={'track': 'A', 'headquarters': True}, confidence=0.5543464775591364),
Observation(geometry=<POINT (16.427 48.269)>, timestamp=7.064221039999978, properties={'track': 'B', 'headquarters': True}, confidence=0.5543464775591364),
Observation(geometry=<POINT (16.427 48.27)>, timestamp=8.475042440000067, properties={'track': 'A'}, confidence=0.7896239763630372),
Observation(geometry=<POINT (16.427 48.27)>, timestamp=8.489063399999992, 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.
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])
with server_thread(ADDRESS, FeatureSendingRequestHandler): # Demo only!
push_graph.run()
push_out.result
[Observation(geometry=<POINT (16.427 48.268)>, timestamp=15.833395549999949, properties={'track': 'B'}, confidence=0.9433776719597745),
Observation(geometry=<POINT (16.427 48.268)>, timestamp=15.834337619999985, properties={'track': 'A'}, confidence=0.9433776719597745),
Observation(geometry=<POINT (16.427 48.269)>, timestamp=17.418075690000023, properties={'track': 'B', 'headquarters': True}, confidence=0.5543464775591364),
Observation(geometry=<POINT (16.427 48.269)>, timestamp=17.808929939999985, properties={'track': 'A', 'headquarters': True}, confidence=0.5543464775591364),
Observation(geometry=<POINT (16.427 48.27)>, timestamp=18.927099579999975, properties={'track': 'B'}, confidence=0.7896239763630372),
Observation(geometry=<POINT (16.427 48.27)>, timestamp=19.248516119999977, properties={'track': 'A'}, 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.