Getting Started
7 Lessons
Section
















In domains ranging from security analytics to industrial process and device health monitoring, a common pattern is the continuous real-time analysis of streaming data to generate discrete events or alarms when meaningful changes occur.
In security video analytics, the metadata stream could be object detections; for example, the position and speed of all vehicles in the view. Let's say we want to monitor if a vehicle has been in a particular area of the view for a specific amount of time. This would be processed by comparing the object positions to a polygon describing the area we want to monitor, and filtering out those that are outside of it. Objects that pass through this first filter would then be tracked over time to trigger an event if they remain in the area for too long. This event is meaningful and actionable, but also a discrete data point. It changes at a single point in time from inactive (no vehicle exceeds the dwell-time threshold) to active (a vehicle has exceeded the threshold).
In industrial manufacturing, the data stream might be the position of objects on a conveyor belt. These positions could be captured using a deep learning model running on the device (read more about YOLOv5 integration here) or using the FixedIT QR Code Decoder edge app if the objects to track have been equipped with a QR code each. To verify correct positioning, the data stream can be compared against two boundaries: the left and right edges of the conveyor belt. If an object is detected outside these limits, an alert is triggered. Once again, while the data stream is sampled continuously at regular intervals, the alert itself is emitted only once when the alarming condition is met.
For device health monitoring, some examples of continuous data streams are samples of the device's CPU usage or disk space. An actionable event may be triggered if CPU usage exceeds a threshold for over 10 seconds, indicating that the camera might be too heavily loaded.
The monitored signal might be continuous, but in a strict mathematical sense, the metadata stream consists of discrete samples of this continuous signal. In many cases, these samples might be sampled at a regular interval. For example, with a deep-learning based object detector, these observations might be delivered at 10 frames per second (FPS). In the same way, CPU utilization might be sampled once per second. In contrast, triggered events and alarms are typically less regular and impossible to predict, since they depend on external factors; sometimes, days might pass without a single event being triggered, while other times there might be multiple alarms in an hour.
Generally, we can say that individual events provide very valuable information, since their existence indicate that something important happened. By comparison, raw data streams are always present, and while they contain important information, it is often buried within a large volume of low-value data.
Data streams used as Telegraf inputs in the FixedIT Data Agent fall into one of two categories: pulled or triggered.
In the case of pulled data streams, Telegraf pulls data from the source at fixed intervals and processes it into metrics. One example of this is how we request the current occupancy level from the AXIS Object Analytics API in the "Extending the Dashboards with Your Own Data" section of the Pattern: Using the FixedIT Data Agent with InfluxDB and Grafana to Create Dashboards article. Another example is how we use the [[inputs.cpu]] plugin in the default bundled configuration files to sample the current CPU usage. These are both pull-based an executed by Telegraf. Typically, these are sampled at an even interval based on the interval parameter in the configuration file, but this interval might be subject to (intentional) random jitter by setting the collection_jitter parameter. This is typically done to avoid the "Thundering herd problem".
For trigger-based data sources, the data is pushed to Telegraf when specific triggering actions occur. Some examples of this are the inputs.tail plugin when used with the inotify mode which reacts on data being written to a file, the inputs.socket_listener plugin that reacts to data being written to a socket or the inputs.mqtt_consumer plugin that reacts on messages sent to a specific topic. These input sources are constantly waiting for data, and when they receive it, the input will process the data into a metric directly.
This means that a data stream that might be experienced as "continuous" doesn't even need to happen at a fixed interval. This blurs the line between what's considered a "data stream" and an "event". MQTT is a great example of this, as it's a transport protocol that could be used to push a continuous stream of data (object observations) or to only send alerts when an alarm triggers. It's therefore up to you to define the difference between an overwhelming data stream and actionable events in your specific use case and domain.
To put these concepts into practice, we're going to go over an example where we simulate an industrial monitoring process. In this scenario, we will monitor that objects are correctly positioned. This could, for example, be the lateral position of an object on a conveyor belt:

In a simulated use case, we might want to observe the lateral position (side-to-side position) of an object on a conveyor belt and trigger an alert if any object goes too close to the side of the conveyor belt.
In a simple scenario, it might be enough to define a fixed position as the edge of the conveyor belt. In other cases, this might be a variable position. This could be either due to it being calculated as a function of the objects position (non-axis aligned conveyor belt), or it could be because the whole conveyor belt is actually moving from side to side.
For this simulated use case, we will have three different continuous input signals:
The upper limit of the envelope
The lower limit of the envelope
The observed position of the object
The envelope is simply stating the upper and lower value in the lateral position, i.e. the two edges of the belt.
The purpose of the implementation is to analyze those in real time and trigger an actionable alert whenever the observed position is not within the allowed range (the envelope).
Let's start with generating some simulated input data using the inputs.mock plugin. This will serve as the simulated data that we would get from the monitoring system looking at the conveyor belt in a real scenario. The example below creates a continuous signal for the envelope limits and its midway point, and samples it at 10 Hz. If you want to follow along and test this example, you can copy the content below into a file called input_simulate_envelope.conf:
# Simulate operating envelope signals.
#
# Emits the "position_monitoring" measurement with three fields:
# - upper_process_limit (UPL): upper bound of the safe operating corridor
# - lower_process_limit (LPL): lower bound of the safe operating corridor
# - setpoint (SP): commanded reference trajectory
#
# All three are slow sine waves. UPL and LPL are phase-shifted from each other
# so the corridor width breathes slightly over time.
#
# In a real system, these could be read from an external system or computer
# vision application running in the same camera device. Here, we instead
# use the mock input plugin to simulate these signals.
[[inputs.mock]]
metric_name = "position_monitoring"
# Send a sample 10 times per second.
interval = "0.1s"
# Upper Process Limit: sine wave offset upward from centre.
[[inputs.mock.sine_wave]]
name = "upper_process_limit"
amplitude = 0.6 # corridor half-width contribution
period = 0.005 # 2/0.005 = 400 ticks meaning ~40 s per cycle
phase = 0.0 # No phase shift
base_line = 0.5 # vertical offset above centre line
# Lower Process Limit: same wave, phase-shifted for asymmetric corridor.
[[inputs.mock.sine_wave]]
name = "lower_process_limit"
amplitude = 0.6
period = 0.005
phase = 8.0 # Add a bit of a phase shift.
base_line = -0.5
# Setpoint: reference trajectory, amplitude kept midway inside the envelope.
[[inputs.mock.sine_wave]]
name = "setpoint"
amplitude = 0.5
period = 0.005
phase = 4.0 # midway between UPL (0) and LPL (8)
base_line = 0.0Now, let's simulate an observed position that will in most cases be within this envelope. We can do this by creating a signal with the mock input, then using a Starlark processor (which is a Python-like language) to create a slow moving random value. This value is then added to the setpoint to create a signal that is most often within the envelope, but sometimes outside of it. Add the following content to a file called input_simulate_observed_signal.conf:
# Simulate observed signal computation
#
# Generates raw process disturbance and derives the Process Variable (PV):
# PV = setpoint + mean(disturbance window)
#
# The Starlark processor maintains a global sliding window of raw disturbance
# samples. Each tick, the window mean is added to the setpoint to produce PV.
#
# This simulates a physical process where the actual position drifts slowly
# away from the commanded setpoint due to real-world effects. In reality, this
# would be received from e.g. a computer vision application running in the
# same camera device.
[[inputs.mock]]
metric_name = "disturbance"
# Send a new random disturbance value 10 times per second.
interval = "0.1s"
# Uniform random noise: wide range so the 2-second mean drifts enough
# to push PV outside the operating envelope occasionally.
[[inputs.mock.random]]
name = "raw_disturbance"
min = -2.0
max = 2.0
[[processors.starlark]]
namepass = ["position_monitoring", "disturbance"]
source = '''
# To convert the random noise into a slowly drifting offset, we use an
# exponential moving average (EMA) with a window size of 20 samples, i.e.
# approximately 2 seconds when sampling at 0.1 seconds.
ALPHA = 0.095 # 2 / (N + 1) where N = 20 samples
# We use the global state variable to store the exponential moving average
# (EMA) of the raw disturbance values between ticks.
state = {"ema": 0.0}
# The apply function is called for each metric received.
def apply(metric):
# Disturbance metric: update EMA and discard (not forwarded to outputs)
if metric.name == "disturbance":
d = float(metric.fields.get("raw_disturbance", 0.0))
state["ema"] = state["ema"] * (1.0 - ALPHA) + d * ALPHA
return None
# Position monitoring metric: add a new field for the process variable
# which is calculated as the setpoint plus the smoothed disturbance offset.
if metric.name == "position_monitoring":
sp = float(metric.fields.get("setpoint", 0.0))
metric.fields["process_variable"] = sp + state["ema"]
return metric
'''If the FixedIT Data Agent is connected to an InfluxDB instance (as described in this guide), we can send these metrics to the database and visualize them as a time series in real time. If you don't have it connected to the database, remove the [[outputs.influxdb_v2]] outputs and only keep the [[output.file]] outputs. Add the following content to a file called output_debugging.conf:
# Pipeline outputs for debugging
#
# Receives the "position_monitoring" metrics that include the process variable
# (PV) and the envelope signals (UPL, LPL, SP). For debugging purposes, we will
# send those both to InfluxDB v2 and write them to stdout for logging.
# Send to InfluxDB v2 for visualization.
[[outputs.influxdb_v2]]
# Send only the "position_monitoring" metrics.
namepass = ["position_monitoring"]
# Send each metric immediately without batching for low latency.
metric_batch_size = 1
# Use the environment variables set by the FixedIT Data Agent settings.
urls = ["${INFLUXDB_URL}"]
token = "${INFLUXDB_TOKEN}"
organization = "${INFLUXDB_ORG}"
bucket = "${INFLUXDB_BUCKET}"
# Write metrics to stdout so that they are visible in the "Logs" tab of the FixedIT Data Agent.
[[outputs.file]]
namepass = ["position_monitoring"]
fieldpass = ["process_variable", "setpoint", "upper_process_limit", "lower_process_limit"]
metric_batch_size = 1
files = ["stdout"]
data_format = "template"
template = "pv={{ .Field \"process_variable\" }} sp={{ .Field \"setpoint\" }} upl={{ .Field \"upper_process_limit\" }} lpl={{ .Field \"lower_process_limit\" }}\n"To test these files, upload them to the FixedIT Data Agent and enable them. Note that you have to enable input_simulate_envelope.conf before you enable input_simulate_observed_signal.conf, since the second one has a processor that is consuming the position_monitoring metric from the first file. This order is indicated by the 1 on the first file and the 2 on the second file in the image:

You can now open InfluxDB as described in the guide linked above. Use the InfluxDB Data Explorer to preview the live data stream:

In this image we can see the upper and lower limits of the envelope, the setpoint in the middle and the noisy observed (simulated) position signal. We have circled the occurrences where the observed value is outside the envelope, where we want to trigger alarms.
The next step is to start analyzing these signals as if they were real data. We can do this using a Starlark script. Copy the following content into a file called analyze_signals.star:
# Monitors the process_variable (PV) against the operating envelope (UPL / LPL).
# Emits an "alerting_state" metric with a boolean "active" field on every state
# transition:
# - inside → outside: active = true
# - outside → inside: active = false
# Global state variable to track the current state of the alarming
# state between ticks.
state = {"outside": False}
# The apply function is called for each metric received.
def apply(metric):
# Get the process variable (PV) from the metric.
pv = float(metric.fields["process_variable"])
# Get the upper process limit (UPL) and lower process limit (LPL) from the metric.
upl = float(metric.fields["upper_process_limit"])
lpl = float(metric.fields["lower_process_limit"])
# Check if the process variable is outside the operating envelope.
is_outside = pv > upl or pv < lpl
# If the alarming state has not changed, return only the original metric
# to let that through.
if is_outside == state["outside"]:
return metric
# Otherwise, update the alarming state.
state["outside"] = is_outside
# Build the alerting metric from a copy of the current metric so that
# timestamp, fields, and tags are preserved.
alert = deepcopy(metric)
alert.name = "alerting_state"
alert.fields["active"] = is_outside
# Return both the original metric and the new alerting metric.
return [metric, alert]This script can be run as a processor using the config file below. Name this file processor_analyze_signals.conf:
# Run the signal analysis script that produces the "alerting_state" metric
# whenever the process variable (PV) goes outside or inside the operating envelope.
[[processors.starlark]]
namepass = ["position_monitoring"]
script = "${HELPER_FILES_DIR}/analyze_signals.star"We can now extend the outputs_debugging.conf file with the following lines at the end, so that we also log an easy-to-spot line to the logs when the alert triggers:
# Existing content...
# Write human-readable alarm line on every state transition. The alarm metric
# is only emitted by the analyze-signals.star script when the alarm state changes.
# When this happens, we write an easy-to-find line to the logs to grab attention.
[[outputs.file]]
namepass = ["alerting_state"]
metric_batch_size = 1
files = ["stdout"]
data_format = "template"
template = "{{ if .Field \"active\" }}!!! ALARM ACTIVATED !!!{{ else }} --- ALARM DEACTIVATED ---{{ end }}\n"After uploading and enabling all files, it should look like this:

Going to the Logs tab of the FixedIT Data Agent, you can now see live updates:

A new sample is written 10 times per second. When the alarm state changes, a message saying "!!! ALARM ACTIVATED !!!" is logged. A message is also logged when the alarm is deactivated.
When the observed signal goes outside the envelope, the Starlark script sends a metric called signal_alarm. This is the discrete alarm that we can set to trigger an Axis-styled or ONVIF-styled event, which can be used in the Axis cameras' rule engine (or consumed in a VMS using the RTSP event stream).
Add the following content to a file called output_events.conf:
[[outputs.execd]]
# Only consume the 'alerting_state' metrics
namepass = ["alerting_state"]
# The binary expects JSON formatted metrics
data_format = "json"
# Command to run the binary, event structure is
# provided through GKeyFile-formatted input.
command = [
"${EXECUTABLES_DIR}/event_handler", "--produce", "--config-inline",
"""[topics]
namespace = tnsaxis
nice_name = FixedIT Unexpected Position Event
topic_0 = CameraApplicationPlatform
topic_1 = FixedITDataAgent
topic_2 = PositionOutsideEnvelope
[settings]
stateful = true
[item.active]
kind = data
data_type = bool
default_value = false
"""
]
# Process one metric at a time for immediate response.
# This ensures each event gets sent immediately.
# Higher values would batch multiple changes (undesirable).
metric_batch_size = 1Once this file is uploaded and enabled, there should be a new event source called FixedIT Unexpected Position Event in the camera's rule engine:

An example of how the PV alarm event can be used to trigger an overlay text in the camera's live view.
In this guide, we covered the common pattern of using the FixedIT Data Agent to transform continuous, low-value data streams into actionable events that signal important changes.
A complete example of processing a continuous object detection stream into alarming events is available in our time-in-area project in our open-source repo. You can also read more about it in this blog post.