An end-to-end IoT telemetry architecture engineered to surpass the consumer 4-to-7 concurrent BLE GATT connection limit. Battery-powered ESP32 sensors buffer 30 days of 8-byte binary readings in flash, broadcast live status via MAC-staggered advertising packets, offload history one device at a time with ISO-HDLC CRC-32 verification to Flutter or Python Bleak gateways, and stream into a containerized Django + NATS JetStream + QuestDB hub.
Consumer smartphones and BLE controllers reliably sustain only 4 to 7 active GATT connections. Rather than keeping permanent connections open, this platform decouples live monitoring from bulk historical retrieval:
logs_pending into a 16-byte scan response.200 ms to 500 ms in 20 ms steps using the last byte of
the sensor's hardware MAC.CMD_CLEAR
(0x02), and push Unix epoch time via CMD_SET_TIME (0x03).200/201 confirms backend receipt.
Both gateways upload to POST /api/telemetry with Bearer/Knox authentication, seamlessly
targeting either deployment tier:
UNIQUE (sensor_id, timestamp) idempotency against gateway retries.Click any screenshot to inspect in fullscreen with zoom, pan, and keyboard navigation (18 captures).
Interactive MapLibre GL JS facility and sensor beacon map with live KPI counters and latest cached telemetry status.
Real-time temperature and humidity comparison curves paired with server-side DataTables and AJAX refresh.
Per-sensor time-series Chart.js plots backed by paginated QuestDB SQL queries and inactivity status tracking.
Server-side DataTables view built for thousands of BLE nodes with instant search, sorting, and live status badges.
Geolocated facility overview showing coordinate inheritance, manager assignments, and all sensors stationed on-site.
Searchable directory of monitored warehouses and sites with per-place timeout policies and device counts.
Async searchable dropdowns for Place assignment, custom coordinates, and per-device inactivity timeout overrides.
Configure geolocation coordinates, place managers, and default inactivity timeout thresholds inherited by site sensors.
Account preferences with English/Spanish localization and hashed django-rest-knox bearer token management.
Administrative oversight for users, roles, Knox tokens, places, and registered BLE sensor nodes.
Dark-themed django-allauth login screen protecting multi-tenant sensor fleets and telemetry APIs.
Self-service operator signup workflow supporting multi-user facility permissions and language selection.
Live scan-response discovery via flutter_blue_plus
followed by sequential CRC-32 verified GATT flash dumps.
When backend connectivity fails, offloaded telemetry stays safely persisted in local SQLite until HTTP 200/201 confirmation.
Inspect locally discovered BLE nodes and buffered readings stored
in sqflite prior to cloud synchronization.
Browse remote facilities synchronized from the Django REST API with Knox bearer authentication.
Live status, latest cached temperature/humidity, and online/unknown health indicators synced from PostgreSQL.
Paginated historical temperature and humidity readings queried directly from the hub's QuestDB time-series endpoint.
Every reading flows through a strictly verified pipeline: 8-byte little-endian flash storage on the ESP32, CRC-32 verified one-at-a-time GATT offload, durable local gateway buffering, NATS JetStream decoupling, and batched QuestDB time-series persistence.
+----------------------------------------------------------------------------------------------------+
| EDGE LAYER (ESP32 BLE SENSORS) |
| [MicroPython / Arduino Node #1..N] |
| - Wake every 5 min -> Append 8-byte record (<Ihh) to logs.bin (30-day ring: 8,640 records) |
| - Primary Adv: 128-bit Service UUID (iOS background wake) | Scan Resp: 16-byte live telemetry |
| - MAC-staggered interval (200-500 ms, 20 ms step) | 20 s connectable window -> Deep Sleep 5 min |
+--------------------------------------------------+-------------------------------------------------+
| BLE Adv (live) + GATT Dump (CRC-32)
v
+----------------------------------------------------------------------------------------------------+
| GATEWAY LAYER (1 ACTIVE BLE CONNECTION MAX) |
| [Desktop Gateway: Python + Bleak + CSV] | [Mobile App: Flutter + flutter_blue_plus] |
| - Passive scan queues live readings; connects sequentially to sensors with logs_pending == True |
| - 0x01 (CMD_DUMP) -> 5 ms paced notify -> 0xFE end frame (count + CRC-32) |
| - On CRC pass: 0x02 (CMD_CLEAR) + 0x03 (CMD_SET_TIME Unix epoch) -> Disconnect |
| - Uploads 250-row batches to POST /api/telemetry; clears local SQLite ONLY on HTTP 200 / 201 |
+--------------------------------------------------+-------------------------------------------------+
| HTTPS POST /api/telemetry (Bearer / Knox)
v
+----------------------------------------------------------------------------------------------------+
| BACKEND HUB (DOCKER COMPOSE) |
| [Django + DRF + Knox + allauth] <---> [(PostgreSQL: Users, Places, Devices, Latest Cache)] |
| | |
| | Background thread publish -> subject: sensor.<id>.telemetry (instant HTTP 201) |
| v |
| [[NATS JetStream: Durable Stream SENSOR_TELEMETRY]] |
| | Push Queue Group Subscription (horizontal worker scaling) |
| v |
| [Telemetry Worker Group: Python + nats-py + asyncpg] |
| | Batched INSERT (BATCH_SIZE=50 or 0.5 s flush via PG Wire) |
| v |
| [(QuestDB: sensor_telemetry partitioned by day)] |
+--------------------------------------------------+-------------------------------------------------+
|
+------------------------+------------------------+
v v
[Web Dashboard: Bootstrap 5 Dark, [Mobile App Views:
MapLibre GL JS, Chart.js, DataTables] Places, Devices, History]
| Module / Directory | Primary Technology | Core Responsibility | Reliability & Scale Safeguards |
|---|---|---|---|
| protocol/frame.py | Pure Python / MicroPython | Shared 8-byte record packer, scan response builder, CRC-32 ISO-HDLC, and commands. | Zero host-only imports; validated against identical golden byte vectors in C++, Python, and Dart. |
| firmware/micropython/ & arduino/ | ESP32, MicroPython, C++ | 5-min deep sleep cycle, append-only flash store, MAC-staggered BLE adv, GATT notify stream. | 8,640-record 30-day ring buffer; 5 ms notify pacing; never clears flash without explicit CMD_CLEAR. |
| gateway/ble_gateway/ | Python, Bleak, AsyncIO | Cross-platform desktop/Raspberry Pi BLE scanner, sequential offloader, and HTTP uploader. | Strictly 1 active BLE connection at a time; verifies CRC-32 & count; syncs sensor RTC via CMD_SET_TIME. |
| mobile/ | Flutter, Dart, sqflite | Android/iOS field technician gateway, foreground scan service, and remote fleet viewer. | 250-row batched uploads; retains local SQLite queue across network outages until HTTP 200/201. |
| server/ | FastAPI, Uvicorn, Nginx, SQLite | Lightweight single-node telemetry ingest server sharing the exact POST /api/telemetry API. |
UNIQUE (sensor_id, timestamp) idempotency prevents duplicate rows from gateway retries. |
| backend/ | Django, DRF, Knox, allauth | Multi-user web dashboard, REST API, MapLibre maps, Chart.js graphs, DataTables, and i18n. | DAL Select2 async dropdowns; cascading inactivity timeouts (Device → Place → default 3600 s). |
| NATS JetStream | NATS 2.x, nats-py | Durable streaming broker decoupling HTTP ingest bursts from time-series storage writes. | Instant HTTP 201 response even on 5,000-row offline mobile dumps; replayable durable streams. |
| telemetry_worker/ | Python, nats-py, asyncpg | Independent microservice consuming sensor.*.telemetry via push queue-group. |
Horizontal replica load-balancing; memory batching (50 rows or 0.5 s flush) into QuestDB. |
| QuestDB & PostgreSQL | QuestDB, PostgreSQL | Hybrid storage: relational fleet metadata in Postgres, partitioned time-series in QuestDB. | Day-partitioned sensor_telemetry table serving paginated SQL history to web & mobile. |
Key source excerpts from the shared wire protocol, ESP32 CRC-32 streamer, sequential Bleak & Flutter gateways, and NATS-to-QuestDB batch worker.
_RECORD = _Struct("<Ihh") # uint32 timestamp, int16 temp_centi, int16 humid_centi
_MFR_PAYLOAD = _Struct("<6sBhhHB") # 6-byte MAC ID, seq, temp, humid, log_count, flags
_END = _Struct("<BHI") # 0xFE marker, uint16 count, uint32 crc32
_SET_TIME = _Struct("<BI") # 0x03 command, uint32 unix timestamp
def adv_interval_ms(sensor_id):
last_byte = sensor_id_to_bytes(sensor_id)[-1]
ms = ADV_INTERVAL_BASE_MS + (last_byte % 16) * ADV_INTERVAL_STEP_MS
return 500 if ms > 500 else ms
def build_adv():
"""Connectable advertising: flags + 128-bit service UUID (required for iOS background scan)."""
uuid = uuid128_le(SERVICE_UUID)
return bytes((0x02, 0x01, 0x06, len(uuid) + 1, 0x07)) + uuid
def build_scan_response(sensor_id, seq, temp_c, humid, log_count):
body = pack_mfr_ad(sensor_id, seq, temp_c, humid, log_count)
return bytes((len(body) + 1, 0xFF)) + body
def _stream(self):
if self.conn is None:
return
blob = self.store.read_all()
crc = frame.crc32_update(0xFFFFFFFF, b"")
count = 0
offset = 0
while offset + frame.RECORD_SIZE <= len(blob):
record = blob[offset : offset + frame.RECORD_SIZE]
if not self._notify(record):
return
crc = frame.crc32_update(crc, record)
count += 1
offset += frame.RECORD_SIZE
time.sleep_ms(frame.NOTIFY_GAP_MS)
end = frame.pack_end(count, frame.crc32_finish(crc))
self._notify(end)
async def offload_address(address, timeout=45, idle=3):
from bleak import BleakClient
session = OffloadSession()
def on_notify(_sender, data):
session.feed(bytes(data))
async with BleakClient(address, timeout=20) as client:
await client.start_notify(frame.STREAM_UUID, on_notify)
await client.write_gatt_char(frame.COMMAND_UUID, bytes((frame.CMD_DUMP,)), response=True)
# ... wait for 0xFE end frame or idle timeout ...
await client.stop_notify(frame.STREAM_UUID)
if session.ok:
await client.write_gatt_char(frame.COMMAND_UUID, bytes((frame.CMD_CLEAR,)), response=True)
await asyncio.sleep(0.2)
await client.write_gatt_char(
frame.COMMAND_UUID, frame.pack_set_time(int(time.time())), response=True
)
return session
# ble_multiple_devices/backend/apps/telemetry/nats_producer.py
for record in records:
sensor_id = record.get('sensor_id', 0)
subject = f"{settings.NATS_SUBJECT_PREFIX}.{sensor_id}.telemetry"
payload = json.dumps(record).encode('utf-8')
await js.publish(subject, payload)
# ble_multiple_devices/telemetry_worker/worker_group.py
async with self._lock:
self.batch_queue.append((sensor_id, temp, humid, dt))
if len(self.batch_queue) >= BATCH_SIZE:
await self._flush_batch_locked()
await msg.ack()