Thread sensor joined through a border router
An ESP32-H2 or ESP32-C5 joins an existing Thread network as a Minimal Thread Device and sends SHT45 readings over UDP, through an OpenThread Border Router, to a collector on the LAN.
| Board | Espressif ESP32-H2-DevKitM-1 (or ESP32-C5-DevKitC-1 v1.2) |
|---|---|
| Time | about 4 hours |
| Stack | esp-idf, python |
| Extra parts | ESP32-H2-DevKitM-1 or ESP32-C5-DevKitC-1 v1.2, SHT45 breakout (Sensirion SHT45-AD1B) for 3.3 V, OpenThread Border Router (Linux host with an RCP radio) or Home Assistant with the OpenThread Border Router app |
This project builds a Thread sensor: an ESP32-H2 or ESP32-C5 that joins an existing Thread network and sends temperature and humidity readings to a computer on your ordinary LAN. The border router does the work in the middle. It is for makers who already run a Thread border router (or want to set one up) and want their own device on it, and for product teams who want to see the minimum a Thread end device needs. There is no Matter layer here. The sensor talks plain IPv6 and UDP (User Datagram Protocol), which makes the network path easy to see.
What you will build
- Firmware in ESP-IDF v6.1.1 that starts OpenThread as an MTD (Minimal Thread Device, an end device that never routes), loads the network’s active operational dataset, attaches, and sends one JSON (JavaScript Object Notation) datagram every 60 s.
- The same source building for two chips: the ESP32-H2 (Bluetooth LE and 802.15.4 only) and the ESP32-C5 (which adds dual-band Wi-Fi 6).
- A border router, either the OpenThread Border Router (OTBR) in Docker on a Linux host with an RCP (radio co-processor), or Home Assistant’s OpenThread Border Router app.
- A Python collector that listens on UDP port 47011 on every IPv6 address of a LAN computer and writes a CSV (comma-separated values) file.
A datagram looks like this (the shape is fixed by the firmware, the values are from the collector’s test):
{"seq":0,"t_c":22.41,"rh":51.3,"role":"child"}
What you need
| Part | Why | Reference |
|---|---|---|
| ESP32-H2-DevKitM-1 or ESP32-C5-DevKitC-1 v1.2 | Thread end device with an on-chip 802.15.4 radio | H2 user guide |
| SHT45 breakout for 3.3 V | Same sensor and driver as the battery sensor project | SHT4x datasheet v7.3 |
| A border router (one of the three below) | Joins the Thread network to your Wi-Fi or Ethernet LAN | See “Back end” |
| A computer on the same LAN | Runs collector.py |
Python 3.12 |
The ESP32-H2-DevKitM-1 uses the ESP32-H2-MINI-1 module. Espressif lists the N4S variant with 4 MB flash and marks the older N4 variant as not recommended for new designs. On v1.3 boards the 32.768 kHz crystal is fitted, so GPIO13 and GPIO14 are not free. The firmware uses GPIO10 and GPIO11 instead.
| SHT45 | ESP32-H2-DevKitM-1 | ESP32-C5-DevKitC-1 v1.2 |
|---|---|---|
| VDD | 3V3 (J1 pin 1) | 3V3 (J1 pin 1) |
| GND | G | G |
| SDA | GPIO10 (J3 pin 4) | GPIO23 (J3 pin 5) |
| SCL | GPIO11 (J3 pin 5) | GPIO24 (J3 pin 4) |
The pins are Kconfig defaults chosen per target, so the same idf.py build picks the right pair.
Design
Four design choices shape the firmware.
- The sensor does not form a network. It loads a dataset you copy from the border router and calls
esp_openthread_auto_start()with it. The dataset holds the channel, PAN ID, network name and network key, so it is a credential. It goes in the gitignoredmain/secrets.h, never insdkconfig.defaults. - MTD, not FTD. A Full Thread Device can act as a router and leader. A sensor has no reason to route traffic for others, so
CONFIG_OPENTHREAD_MTD=ybuilds it as a device that can only be an end device. - Plain sockets. ESP-IDF glues OpenThread to lwIP, so the report task uses an ordinary IPv6 UDP socket. Only the calls into OpenThread itself (reading the device role) take the OpenThread lock.
- Send only when attached. The task checks the role before each reading. While detached it logs “not attached yet” and tries again next period instead of queueing data.
How the datagram reaches the collector depends on the prefixes the border router advertises. The OpenThread codelab describes an OMR (off-mesh-routable) prefix, which gives Thread devices addresses the Wi-Fi or Ethernet side can reach, and an on-link prefix that OTBR creates when the LAN has no IPv6 of its own. Set COLLECTOR_ADDR to an address of the collector computer in a prefix the border router advertises a route for. sudo ot-ctl netdata show on an OTBR lists those routes. On Linux, the codelab also sets net.ipv6.conf.wlan0.accept_ra_rt_info_max_plen=64 so the computer accepts the route back to the Thread network, which you need for replies and ping.
Firmware
The firmware is in examples/thread-sensor-border-router/firmware/. It shares sht4x.c with the battery sensor project. The start-up follows ESP-IDF’s ot_sleepy_device example:
// target: esp32h2,esp32c5 sdk: esp-idf tier: 1
// ...
void app_main(void)
{
esp_vfs_eventfd_config_t eventfd_config = {.max_fds = 3}; // netif, OT task queue, radio driver
ESP_ERROR_CHECK(nvs_flash_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_vfs_eventfd_register(&eventfd_config));
static esp_openthread_config_t config = {
.netif_config = ESP_NETIF_DEFAULT_OPENTHREAD(),
.platform_config = {
.radio_config = {.radio_mode = RADIO_MODE_NATIVE},
.host_config = {.host_connection_mode = HOST_CONNECTION_MODE_NONE},
.port_config = {.storage_partition_name = "nvs", .netif_queue_size = 10, .task_queue_size = 10},
},
};
ESP_ERROR_CHECK(esp_openthread_start(&config));
esp_netif_set_default_netif(esp_openthread_get_netif());
static otOperationalDatasetTlvs tlvs;
if (hex_to_tlvs(THREAD_DATASET_HEX, &tlvs) != 0) {
ESP_LOGE(TAG, "THREAD_DATASET_HEX is not valid hex");
return;
}
esp_openthread_lock_acquire(portMAX_DELAY);
otInstance *ot = esp_openthread_get_instance();
otSetStateChangedCallback(ot, on_state, NULL);
ESP_ERROR_CHECK(esp_openthread_auto_start(&tlvs));
esp_openthread_lock_release();
xTaskCreate(report_task, "report", 4096, NULL, 5, NULL);
}
The report task reads the sensor and sends one datagram per period while the device is attached:
// target: esp32h2,esp32c5 sdk: esp-idf tier: 1
// ...
static void report_task(void *arg)
{
i2c_master_bus_config_t bus_cfg = {
.i2c_port = -1,
.sda_io_num = CONFIG_FG_I2C_SDA_GPIO,
.scl_io_num = CONFIG_FG_I2C_SCL_GPIO,
.clk_source = I2C_CLK_SRC_DEFAULT,
.glitch_ignore_cnt = 7,
.flags.enable_internal_pullup = true,
};
i2c_master_bus_handle_t bus;
ESP_ERROR_CHECK(i2c_new_master_bus(&bus_cfg, &bus));
i2c_device_config_t dev_cfg = {.dev_addr_length = I2C_ADDR_BIT_LEN_7, .device_address = SHT4X_ADDR, .scl_speed_hz = 100000};
i2c_master_dev_handle_t dev;
ESP_ERROR_CHECK(i2c_master_bus_add_device(bus, &dev_cfg, &dev));
struct sockaddr_in6 dst = {.sin6_family = AF_INET6, .sin6_port = htons(CONFIG_FG_COLLECTOR_PORT)};
if (inet_pton(AF_INET6, COLLECTOR_ADDR, &dst.sin6_addr) != 1) {
ESP_LOGE(TAG, "COLLECTOR_ADDR is not an IPv6 address: %s", COLLECTOR_ADDR);
vTaskDelete(NULL);
}
int sock = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
uint32_t seq = 0;
for (;;) {
otDeviceRole role = current_role();
if (role == OT_DEVICE_ROLE_CHILD || role == OT_DEVICE_ROLE_ROUTER || role == OT_DEVICE_ROLE_LEADER) {
float t = 0, rh = 0;
esp_err_t err = read_sht45(dev, &t, &rh);
char msg[160];
int n;
if (err == ESP_OK) {
n = snprintf(msg, sizeof msg, "{\"seq\":%lu,\"t_c\":%.2f,\"rh\":%.1f,\"role\":\"%s\"}",
(unsigned long)seq, t, rh, otThreadDeviceRoleToString(role));
} else {
n = snprintf(msg, sizeof msg, "{\"seq\":%lu,\"error\":\"%s\",\"role\":\"%s\"}",
(unsigned long)seq, esp_err_to_name(err), otThreadDeviceRoleToString(role));
}
int sent = sendto(sock, msg, n, 0, (struct sockaddr *)&dst, sizeof dst);
ESP_LOGI(TAG, "%s %s", sent == n ? "sent" : "send FAILED", msg);
seq++;
} else {
ESP_LOGI(TAG, "not attached yet (role %s)", otThreadDeviceRoleToString(role));
}
vTaskDelay(pdMS_TO_TICKS(CONFIG_FG_REPORT_SECONDS * 1000));
}
}
main/secrets.h.example shows what to fill in:
// snippet: copy to secrets.h (gitignored) and fill in. Never commit secrets.h.
#pragma once
// Active operational dataset of your Thread network as hex TLVs.
// On an OpenThread Border Router run: sudo ot-ctl dataset active -x
// It contains the network key: treat it like a Wi-Fi password.
#define THREAD_DATASET_HEX "0e080000000000010000000300000f35060004001fffe0..."
// IPv6 address of the computer running host/collector.py, as seen from the Thread network
// (an address in the on-link or global prefix the border router advertises).
#define COLLECTOR_ADDR "fd11:22::1"
The OpenThread settings in sdkconfig.defaults come from ESP-IDF’s ot_cli example, with the console off and the device type set to MTD:
# Based on ESP-IDF v6.1.1 examples/openthread/ot_cli/sdkconfig.defaults
CONFIG_PARTITION_TABLE_CUSTOM=y
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
CONFIG_PARTITION_TABLE_FILENAME="partitions.csv"
CONFIG_PARTITION_TABLE_OFFSET=0x8000
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
CONFIG_MBEDTLS_SSL_PROTO_DTLS=y
CONFIG_MBEDTLS_KEY_EXCHANGE_ECJPAKE=y
CONFIG_MBEDTLS_ECJPAKE_C=y
CONFIG_OPENTHREAD_ENABLED=y
# A sensor never needs to route: Minimal Thread Device (end device only)
CONFIG_OPENTHREAD_MTD=y
CONFIG_OPENTHREAD_BORDER_ROUTER=n
CONFIG_OPENTHREAD_DNS64_CLIENT=y
CONFIG_OPENTHREAD_CONSOLE_ENABLE=n
CONFIG_OPENTHREAD_TASK_SIZE=10240
CONFIG_LWIP_TCPIP_TASK_STACK_SIZE=4096
Back end
Pick one of three border routers. We have not yet run any of them with this sensor. Each is described from its maker’s documentation.
1. OpenThread Border Router in Docker. OpenThread’s guide runs OTBR as the openthread/border-router image on a Linux host such as a Raspberry Pi, after a setup-host script that enables IP forwarding (set INFRA_IF_NAME if your LAN interface is not wlan0). The radio is an RCP: an 802.15.4 chip that runs only the lowest layers while OpenThread runs on the host. The guide’s example uses a Nordic nRF52840 dongle. ESP-IDF’s ot_rcp example turns an ESP32-H2 or ESP32-C5 into an RCP on UART0 at 460800 baud, so with an ESP32-H2-DevKitM-1 as the radio, change uart-baudrate to 460800. The environment file from the guide:
# Environment file for the openthread/border-router Docker image (OpenThread Border Router guide).
# The RCP is a USB radio running RCP firmware; the device path differs between systems.
OT_RCP_DEVICE=spinel+hdlc+uart:///dev/ttyACM0?uart-baudrate=1000000
OT_INFRA_IF=wlan0
OT_THREAD_IF=wpan0
OT_LOG_LEVEL=7
Form a network on the OTBR as its guide describes, then export the active dataset for secrets.h:
sudo ot-ctl dataset active -x
2. Home Assistant’s OpenThread Border Router app. Home Assistant installs the OTBR integration with the app (formerly called an add-on). Its documentation names Home Assistant Yellow, Connect ZBT-1 and Connect ZBT-2 as the radios. Exporting the dataset is the awkward part. As of November 2026 the Thread integration’s “Network information” view shows the channel and PAN ID, and its page does not describe exporting the dataset as hex. The app runs OTBR, whose REST API returns the active dataset as hex from GET /node/dataset/active with Accept: text/plain. Home Assistant gives http://<IP>:8081 as the usual address for a standalone border router. Whether that port is reachable from your LAN depends on the app’s configuration, so check its Documentation tab before you rely on it.
curl -H 'Accept: text/plain' http://<border-router-ip>:8081/node/dataset/active
3. Espressif’s Thread border router board. An Espressif codelab on openthread.io pairs an ESP32-S3 (running the border router) with an ESP32-H2 (running RCP firmware) on one board, built from the esp-thread-br SDK. The codelab shows the board’s CLI commands for creating a dataset and printing its values.
On the LAN computer, start the collector:
# target: host sdk: python tier: 2
"""Receive the Thread sensor's UDP datagrams and append them to a CSV file.
Run on a computer on the same LAN as the border router:
python examples/thread-sensor-border-router/host/collector.py --csv thread.csv
It listens on all IPv6 addresses ([::]) on UDP port 47011 (CONFIG_FG_COLLECTOR_PORT in the firmware).
"""
from __future__ import annotations
import argparse
import csv
import json
import socket
import time
from pathlib import Path
FIELDS = ["received_utc", "src", "seq", "t_c", "rh", "role", "error"]
def parse(data: bytes, src: str) -> dict | None:
"""One datagram -> one CSV row, or None if it is not a sensor report."""
try:
msg = json.loads(data)
except ValueError:
return None
if not isinstance(msg, dict) or "seq" not in msg:
return None
row = {k: msg.get(k, "") for k in FIELDS}
row.update(received_utc=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), src=src)
return row
def open_socket(bind: str, port: int) -> socket.socket:
s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((bind, port))
return s
def serve(sock: socket.socket, csv_path: Path, max_rows: int | None = None) -> int:
new = not csv_path.exists()
n = 0
with csv_path.open("a", newline="") as fh:
w = csv.DictWriter(fh, fieldnames=FIELDS)
if new:
w.writeheader()
while max_rows is None or n < max_rows:
data, addr = sock.recvfrom(512)
row = parse(data, addr[0])
if row is None:
continue
w.writerow(row)
fh.flush()
n += 1
print(f"{row['src']} seq {row['seq']}: {row['t_c']} °C {row['rh']} %RH ({row['role']})")
return n
Enclosure
If the sensor is an ESP32-C5-DevKitC-1 v1.2, it fits the vented DevKit enclosure, which is drawn from Espressif’s v1.2 dimension drawing and keeps 15 mm of clearance around the PCB antenna. The ESP32-H2-DevKitM-1 has a different outline, and its dimensions are published only as a drawing we have not checked against that design, so do not assume it fits. An H2 variant is a request to the Build backlog. In either case, put the SHT45 at the vent end, away from the board’s regulator.
Build and flash
cd examples/thread-sensor-border-router/firmware
cp main/secrets.h.example main/secrets.h # paste the dataset hex and the collector address
idf.py set-target esp32h2 # or esp32c5
idf.py build flash monitor
Without secrets.h the build uses the placeholder dataset, which is not valid hex, so the device logs “THREAD_DATASET_HEX is not valid hex” and stops. That is deliberate.
Test
What working looks like on the sensor’s console (values in angle brackets are your board’s):
I (<ms>) fg_thread: role -> child
I (<ms>) fg_thread: sent {"seq":<n>,"t_c":<t>,"rh":<rh>,"role":"child"}
The collector prints one line per datagram with the sensor’s IPv6 source address.
- Tier 1 (builds in CI): passes for both
esp32h2andesp32c5inespressif/idf:v6.1.1. - Tier 2 (runs in CI):
host/collector_test.pyruns the collector on the IPv6 loopback, sends a non-JSON datagram and two firmware-shaped reports, and checks the CSV rows. - Tier 3 (tested on hardware): waiting for the owner’s bench run, which needs a running border router and
secrets.hfilled in on the bench host:
python tools/bench/bench.py flash --port <port> --example thread-sensor-border-router --target esp32h2
python tools/bench/bench.py capture --port <port> --seconds 120 --reset --expect examples/thread-sensor-border-router/bench/expect.txt --board-rev "ESP32-H2-DevKitM-1 v1.3" --example thread-sensor-border-router --target esp32h2 --meta border_router=<model and firmware>
The same pair with --target esp32c5 and --board-rev "ESP32-C5-DevKitC-1 v1.2" covers the C5. The page shows tier 1 until those logs are committed.
For makers
If you already run Home Assistant with a ZBT-1 or ZBT-2, use its border router and solve the dataset export once. Otherwise a Raspberry Pi with OTBR in Docker and a spare ESP32-H2 as the RCP is the cheapest bench setup. Keep the collector on wired Ethernet or the same Wi-Fi as the border router.
For product teams
A product would not ship a dataset in firmware. It would join through Thread commissioning, or through Matter commissioning, which hands over the dataset. Plan for border routers from several vendors on one network, IPv6 prefixes that change, and devices that must keep working while the LAN has no IPv6. ESP-IDF v6.1 disabled ECDSA Secure Boot V2 on the ESP32-H2 and ESP32-C5 because of a vulnerability, so settle the secure boot scheme early.
Things to try
- Sleepy end device. ESP-IDF’s
ot_sleepy_device/deep_sleepexample (ESP32-C6 and ESP32-H2) sets a poll period and enters deep sleep once attached as a child. Merge it with this sensor for battery use. - SRP (Service Registration Protocol). OTBR provides SRP on the Thread side and mDNS on the LAN. Let the sensor register a service so the collector can find it by name.
- NAT64. OTBR can translate to IPv4, which lets the sensor reach an IPv4-only collector or broker.
- Matter over Thread. The ESP32-C5 runs Matter over Thread too. See the Matter light project for the esp-matter settings.
Summary
- The sensor is a Minimal Thread Device that loads the border router’s dataset from a gitignored file and sends UDP datagrams while attached.
- One source builds for the ESP32-H2 and the ESP32-C5 with ESP-IDF v6.1.1, with per-target I²C pins in Kconfig.
- OTBR exports the dataset with
ot-ctl dataset active -xor its REST API. Home Assistant’s own pages do not yet describe a hex export. - The collector is tested on the IPv6 loopback. A hardware run with a named border router is still to come.