OFFLINE-FIRST BLE TELEMETRY ESP32 MICROPYTHON & ARDUINO FLUTTER, NATS JETSTREAM & QUESTDB

BLE Multi-Sensor Telemetry: Scalable Offline-First IoT Platform

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.

1 Conn
Max Concurrent BLE Session
8 Bytes
Binary Wire Record Contract
8,640 Recs
30-Day Flash Ring Buffer
CRC-32
Verified Offload Before Clear

Breaking the 4-Device BLE Ceiling

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:

  • Connectionless Live Broadcasts: Sensors place the 128-bit Service UUID in primary advertising (for iOS background wakeups) and pack live temperature, humidity, and logs_pending into a 16-byte scan response.
  • MAC-Staggered Anti-Collision: Advertising intervals are deterministically spaced from 200 ms to 500 ms in 20 ms steps using the last byte of the sensor's hardware MAC.
  • One-at-a-Time Verified Offload: Gateways connect sequentially to sensors with pending logs, verify every byte with ISO-HDLC CRC-32 before sending CMD_CLEAR (0x02), and push Unix epoch time via CMD_SET_TIME (0x03).
  • Zero Silent Data Loss: Flash is never cleared until CRC-32 passes; mobile SQLite queues are never cleared until HTTP 200/201 confirms backend receipt.
Golden Cross-Language Byte Vector:
• Input: MAC a4cf12345601, seq 7, 23.45°C, 55.10%, 3 logs
• Hex: ffffa4cf123456010729098615030001
• Verified in: Arduino C++, MicroPython, Python pytest, Dart flutter test

Two Backend Tiers, One API Contract

Both gateways upload to POST /api/telemetry with Bearer/Knox authentication, seamlessly targeting either deployment tier:

Option A: Lightweight Edge Ingest (FastAPI + SQLite)
Single-node Uvicorn + Nginx service storing readings with UNIQUE (sensor_id, timestamp) idempotency against gateway retries.
Option B: Scalable Hub (Django + NATS JetStream + QuestDB)
Django updates PostgreSQL metadata and publishes batches to NATS JetStream asynchronously; horizontal worker replicas batch-flush into QuestDB every 50 rows or 0.5 s.
Fleet-Scale Web & Mobile Visibility
MapLibre GL JS geolocation beacons, Chart.js time-series graphs, server-side DataTables over QuestDB, DAL Select2 dropdowns, and cascading inactivity timeouts.

System Topology & End-to-End Data Flow

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]

System Components & Architecture Matrix

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.

Core Implementation Walkthrough

Key source excerpts from the shared wire protocol, ESP32 CRC-32 streamer, sequential Bleak & Flutter gateways, and NATS-to-QuestDB batch worker.

1. Shared 8-Byte Wire Contract & MAC-Staggered Advertising (protocol/frame.py)
Python / MicroPython
_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
2. ESP32 Paced GATT Notification Stream & Running CRC-32 (firmware/micropython/node.py)
MicroPython
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)
3. Sequential One-at-a-Time Offload, Flash Clear & Clock Sync (gateway/ble_gateway/radio.py)
Python / Bleak
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
4. NATS JetStream Queue-Group Consumer & QuestDB Batch Flusher (telemetry_worker/worker_group.py)
Python / asyncpg
# 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()