OpenTelemetry at the edge: Getting environmental sensor data out of IoT devices
A sensor reading is a metric. Send it through the pipeline your fleet already has.

Most IoT monitoring stops at the device. CPU, memory, disk, uptime. That tells you the device is healthy. It doesn't tell you whether the cold room it sits in is still cold.
IoT is ultimately about sensors. The temperature, humidity and pressure readings are the reason the device exists, and it's tempting to build a second pipeline just for them.
You don't have to. A sensor reading is a metric. This tutorial shows you how to get environmental readings off the sensor and into Dynatrace as OpenTelemetry metrics, through the same Bindplane-managed pipeline as the rest of your fleet.
The device was covered. What it measures wasn't.
This is part 2 of a series. Part 1, OpenTelemetry at the edge: observability for IoT fleets with Bindplane and Dynatrace, built the telemetry pipeline for an IoT fleet. Even though this post stands on its own, part 1 is worth a read if you want the full picture of the pipeline it plugs into.
Here's what part 1 set up.
- Edge collectors on capable devices gather host metrics, journald logs and application files, and do little processing.
- Gateway collectors on site hardware handle filtering, site and asset enrichment, batching and egress.
- Bindplane manages both tiers over OpAMP, from a single
IoT-devicesconfiguration. - Dynatrace receives the logs and metrics, next to application traces.
Both collector tiers run the Bindplane Distro for OpenTelemetry (BDOT).
Part 1 covered the device itself. This post covers what the device measures.
You treat the sensor like any other application. Instrument the code that reads the sensor with the OpenTelemetry SDK, send OTLP to the local edge collector, and let the existing pipeline do the rest.
By the end you'll have a metric model for the readings, a small Python exporter running under systemd, one new OTLP source in Bindplane, and a Dynatrace dashboard on top.
I'm using the Raspberry Pi Sense HAT as the reference board. It carries the same class of digital environmental sensors you'll find in commercial cold-chain loggers, building-management nodes and comms-cabinet monitors, so the patterns carry over directly.
What we're building
One new component runs on each device. It's a small exporter that reads the sensors and sends OTLP to the edge collector on localhost. Everything downstream is the existing fleet pipeline, unchanged.

The exporter knows nothing about the gateway, Dynatrace or credentials. Bindplane configures both collector tiers over OpAMP, so a routing or processing change is a config rollout, not a device deploy.
Step 1: Know what the sensors report
The environmental readings come from two STMicroelectronics (ST) MEMS chips on the Sense HAT, both on the device's I²C bus.
Datasheet figures come from the ST product pages.
Both chips are factory-calibrated and have an embedded ADC, so you read finished values over I²C rather than sampling analogue signals. That's typical of the digital sensors in modern IoT hardware, and it's why the collection code is short.
Two details shape how you export the data.
- Each chip has its own temperature sensor. The HTS221 and LPS25H report slightly different temperatures. Export both, tagged by source chip. Don't pick one.
- Board placement affects temperature. On a HAT mounted over the processor, both temperature readings include heat from the SoC. Export the SoC temperature too, so you can correct the offset and recalibrate it over time.
Both chips are now marked obsolete by ST, which recommends the Sensirion SHT40 and the LPS25HB as replacements. The pattern here doesn't depend on the chip. Only the function that reads the sensor changes.
The Sense HAT also carries an accelerometer, a gyroscope, a magnetometer and, on v2 boards, a colour and light sensor. They export the same way. I'm focusing on the environmental readings.
Step 2: Decide the metric model before you write code
The metric model is much harder to change once dashboards and alerts depend on it, so settle it first. Every environmental reading is a gauge, a value sampled at a point in time, not a running total.
Four conventions sit behind that table.
- One metric per physical quantity, attributes for the variant. Two temperature chips are one metric with a
sensorattribute, not two metrics. Dashboards can split or filter by the attribute, and the metric list stays short. - UCUM units.
Cel,%andhParender correctly in Dynatrace and make units explicit to anyone reading the data later. - A clear namespace. OpenTelemetry has no stable semantic conventions for ambient environmental readings yet, so a device-family prefix keeps these metrics distinct from host metrics.
- Observable instruments. The SDK calls back for the latest value at collection time, so the export interval doesn't depend on how often you read the hardware.
Identity goes in resource attributes, not metric attributes. The device sets what only it knows, which is service.name, host.name and device.model.name. The gateway's enrichment processors from part 1 add site and asset identity, so they're consistent across every signal from that site and you never configure them per device.
Step 3: Write the exporter around one rule
One thread touches the hardware. OpenTelemetry only ever reads from a cache. That's the rule. I²C reads can stall or fail transiently, and the SDK's collection callbacks should never block on hardware.
- A sampler thread reads the sensors every second and writes the values into a lock-protected cache.
- Observable gauges return the latest cached value when the SDK collects.
- A periodic reader exports over OTLP/HTTP to the edge collector every 60 seconds.
Install the SDK in a virtual environment that can still see the OS-packaged sense_hat library:
1python3 -m venv --system-site-packages /opt/env-sensors/venv
2/opt/env-sensors/venv/bin/pip install opentelemetry-sdk opentelemetry-exporter-otlp-proto-httpSave the exporter as /opt/env-sensors/env_sensors.py:
1import os, signal, socket, threading
2
3from sense_hat import SenseHat
4from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
5from opentelemetry.metrics import CallbackOptions, Observation
6from opentelemetry.sdk.metrics import MeterProvider
7from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
8from opentelemetry.sdk.resources import Resource
9
10SAMPLE_SECONDS = float(os.getenv("SENSEHAT_SAMPLE_SECONDS", "1"))
11EXPORT_SECONDS = float(os.getenv("SENSEHAT_EXPORT_SECONDS", "60"))
12TEMP_FACTOR = float(os.getenv("SENSEHAT_TEMP_FACTOR", "1.5"))
13SOC_TEMP_PATH = "/sys/class/thermal/thermal_zone0/temp"
14
15
16class SensorCache:
17 """Latest readings: written by the sampler, read by OTel callbacks."""
18
19 def __init__(self):
20 self._lock = threading.Lock()
21 self._values = {}
22
23 def update(self, values):
24 with self._lock:
25 self._values.update(values)
26
27 def get(self, key):
28 with self._lock:
29 return self._values.get(key)
30
31
32def read_soc_temp():
33 with open(SOC_TEMP_PATH) as f:
34 return int(f.read().strip()) / 1000.0
35
36
37class Sampler(threading.Thread):
38 """The only thread that touches the sensor hardware."""
39
40 def __init__(self, sense, cache):
41 super().__init__(daemon=True, name="sampler")
42 self.sense, self.cache = sense, cache
43 self.stopped = threading.Event()
44
45 def sample(self):
46 s = self.sense
47 t_hts = s.get_temperature_from_humidity()
48 soc = read_soc_temp()
49 values = {
50 "temp.hts221": t_hts,
51 "humidity": s.get_humidity(),
52 "soc_temp": soc,
53 # correct for heat conducted from the SoC below the board
54 "temp.compensated": t_hts - (soc - t_hts) / TEMP_FACTOR,
55 }
56 pressure = s.get_pressure()
57 if pressure: # the LPS25H returns 0 until its first conversion
58 values["pressure"] = pressure
59 values["temp.lps25h"] = s.get_temperature_from_pressure()
60 self.cache.update(values)
61
62 def run(self):
63 while not self.stopped.is_set():
64 try:
65 self.sample()
66 except Exception as exc: # keep sampling through transient I2C errors
67 print(f"sensor read failed: {exc}", flush=True)
68 self.stopped.wait(SAMPLE_SECONDS)
69
70
71def gauge_of(cache, key):
72 def callback(options: CallbackOptions):
73 value = cache.get(key)
74 if value is not None:
75 yield Observation(value)
76 return callback
77
78
79def temperatures(cache):
80 def callback(options: CallbackOptions):
81 for sensor in ("hts221", "lps25h"):
82 value = cache.get(f"temp.{sensor}")
83 if value is not None:
84 yield Observation(value, {"sensor": sensor})
85 return callback
86
87
88def main():
89 os.environ.setdefault("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4318")
90 resource = Resource.create({
91 "service.name": os.getenv("OTEL_SERVICE_NAME", "env-sensors"),
92 "host.name": socket.gethostname(),
93 "device.model.name": "Raspberry Pi Sense HAT",
94 })
95 reader = PeriodicExportingMetricReader(
96 OTLPMetricExporter(), export_interval_millis=int(EXPORT_SECONDS * 1000)
97 )
98 provider = MeterProvider(resource=resource, metric_readers=[reader])
99 meter = provider.get_meter("env-sensors", "1.0.0")
100
101 cache = SensorCache()
102 meter.create_observable_gauge(
103 "sensehat.temperature", [temperatures(cache)], unit="Cel",
104 description="Temperature reported by each on-board sensor chip")
105 meter.create_observable_gauge(
106 "sensehat.temperature.compensated", [gauge_of(cache, "temp.compensated")],
107 unit="Cel", description="Ambient temperature corrected for SoC heat")
108 meter.create_observable_gauge(
109 "sensehat.humidity", [gauge_of(cache, "humidity")], unit="%",
110 description="Relative humidity")
111 meter.create_observable_gauge(
112 "sensehat.pressure", [gauge_of(cache, "pressure")], unit="hPa",
113 description="Absolute barometric pressure")
114 meter.create_observable_gauge(
115 "rpi.cpu.temperature", [gauge_of(cache, "soc_temp")], unit="Cel",
116 description="SoC temperature, used for compensation")
117
118 sampler = Sampler(SenseHat(), cache)
119 sampler.start()
120
121 stop = threading.Event()
122 signal.signal(signal.SIGTERM, lambda *_: stop.set())
123 signal.signal(signal.SIGINT, lambda *_: stop.set())
124 stop.wait()
125
126 sampler.stopped.set()
127 provider.shutdown() # flushes the final export
128
129
130if __name__ == "__main__":
131 main()Everything device-specific lives in Sampler.sample(). For a different sensor, such as an SHT40 or a Modbus temperature probe, you replace that one function, and the metric names, resource attributes and export path stay the same.
Step 4: Run the exporter as a locked-down service
Run the exporter under systemd as an unprivileged service account with access to the I²C bus and nothing else. All tuning is in environment variables, so the same file deploys to every device and the differences live in configuration management.
Create the service account:
1sudo useradd --system --no-create-home --groups i2c env-sensorsCreate the unit file at /etc/systemd/system/env-sensors.service:
1[Unit]
2Description=Environmental sensor OpenTelemetry exporter
3After=network-online.target
4Wants=network-online.target
5
6[Service]
7Type=simple
8User=env-sensors
9Group=env-sensors
10SupplementaryGroups=i2c
11WorkingDirectory=/opt/env-sensors
12StateDirectory=env-sensors
13Environment=HOME=/var/lib/env-sensors
14Environment=OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
15Environment=OTEL_SERVICE_NAME=env-sensors
16Environment=OTEL_RESOURCE_ATTRIBUTES=deployment.environment=production
17Environment=OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=delta
18Environment=SENSEHAT_SAMPLE_SECONDS=1
19Environment=SENSEHAT_EXPORT_SECONDS=60
20Environment=SENSEHAT_TEMP_FACTOR=1.5
21ExecStart=/opt/env-sensors/venv/bin/python /opt/env-sensors/env_sensors.py
22Restart=always
23RestartSec=10
24NoNewPrivileges=true
25ProtectSystem=strict
26ProtectHome=true
27PrivateTmp=true
28
29[Install]
30WantedBy=multi-user.targetEnable the service and tail its logs:
1sudo systemctl daemon-reload
2sudo systemctl enable --now env-sensors
3journalctl -u env-sensors -fThe hardening directives keep the exporter read-only on the filesystem. The only writable path is its state directory, where the Sense HAT library keeps its settings file. Beyond that it needs only /dev/i2c-1, the SoC thermal zone in /sys and the loopback network.

Step 5: Add an OTLP source and roll it out
The exporter knows only localhost:4318. Routing, credentials, buffering and enrichment all stay in the existing collector tier, so adding sensor data is one change to the fleet configuration.
Add an OTLP source to IoT-devices
Open the IoT-devices configuration in Bindplane.
- Add an OpenTelemetry (OTLP) source with the HTTP listener on
localhost:4318. Binding to loopback keeps the receiver off the site network. - Leave the existing destination unchanged. The sensor metrics join host metrics and logs on the path to the gateway.
- Roll the configuration out. Bindplane pushes it to every collector using this configuration over OpAMP, and the exporter needs no change.
To confirm the receiver is listening on a device:
1ss -ltn | grep ':4318'
Leave the gateway alone
The gateway needs no change. Its existing processors attach site and asset identity, batch, and export through the Dynatrace destination, whose API token needs the metrics.ingest scope. The persistent queue on that exporter also covers sensor readings during a WAN outage.
Step 6: Query and chart the readings in Dynatrace
The metrics land in Grail under the names the SDK gave them, with metric and resource attributes as dimensions. There's no extension or schema to define first.
Confirm the shape of the data in a Notebook with the DQL timeseries command:
1timeseries avg(sensehat.temperature), by:{host.name, sensor}The dashboard uses a $Host variable populated from the data itself, so a device appears in the selector as soon as it starts reporting:
1timeseries avg(sensehat.humidity), by:{host.name}
2| fields host.nameCurrent-value tiles take the last non-null point in the timeframe:
1timeseries v = avg(sensehat.temperature.compensated), filter: host.name == $Host
2| fieldsAdd value = arrayLast(arrayRemoveNulls(v))
3| fields valueThe temperature chart overlays the compensated ambient value, both chip readings and the SoC temperature. It makes the heat offset visible, which is what you need when recalibrating the compensation factor:
1timeseries ambient = avg(sensehat.temperature.compensated), filter: host.name == $Host
2| append [timeseries raw = avg(sensehat.temperature), by:{sensor}, filter: host.name == $Host]
3| append [timeseries soc = avg(rpi.cpu.temperature), filter: host.name == $Host]Humidity and pressure are single series:
1timeseries humidity = avg(sensehat.humidity), filter: host.name == $Host
2timeseries pressure = avg(sensehat.pressure), filter: host.name == $HostTo compare devices across a site, drop the host filter and split by host instead:
1timeseries temp = avg(sensehat.temperature.compensated), by:{host.name}Put together, the dashboard has three rows.
Because these are ordinary Dynatrace metrics, the same queries drive alerting. A humidity threshold for a cold room or comms cabinet uses the same alerting and notification workflows as any application metric.

Six things to know before production
Sample fast, export at the backend's resolution. Dynatrace stores metrics at one-minute resolution, so exporting more often than every 60 seconds sends points that are rolled up anyway. Reading the sensors every second still matters. It keeps the cache fresh and lets the sampler smooth or aggregate locally if needed.
A gauge is a snapshot. At a 60-second export, each point is the latest reading at export time. That's fine for environmental values, which change over minutes. For fast-changing signals, compute min, max and mean in the sampler over the interval and export those as separate gauges.
Expect an occasional empty minute. The periodic reader drifts by a few milliseconds per cycle, so an export occasionally lands in the following minute. An export interval of 55 seconds avoids empty buckets at the cost of an occasional second point, which Dynatrace averages.
Calibrate per installation. The compensation factor depends on enclosure, airflow and mounting. Keep exporting the raw chip readings and the SoC temperature alongside the compensated value, so you can recalibrate the factor against a reference instrument from history, without redeploying.
Use delta temporality for counters. Every metric here is a gauge, so temporality doesn't apply. If you add counters, for example door-open events or threshold breaches, set OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=delta or add the cumulativetodelta processor at the gateway. Dynatrace accepts only delta sums.
Keep the receiver local. The OTLP receiver has no authentication by default. Binding it to loopback means only processes on the device can write to it, and the gateway link carries the TLS.
Where this applies
The pattern doesn't depend on the sensor. Swap the Sense HAT for an SHT40, a Modbus probe or a BLE beacon reader and only the sampling function changes. The metric model, the pipeline and the dashboards stay the same.
Sensor data doesn't need its own pipeline
A sensor reading looks like a special case. It isn't. Read the hardware on one thread, model each reading as an OpenTelemetry gauge with clear units and attributes, and send OTLP to the edge collector that's already there. Bindplane rolls the change out across the fleet, the gateway enriches and forwards it, and Dynatrace treats it like any other metric.
You don't need a second agent. You don't need a second protocol. You need one more OTLP source.
Want to roll that source out to a whole fleet without touching a device? Try Bindplane.
Then pick one sensor and start there.


