If you have ever built an Internet of Things (IoT) prototype with Bluetooth Low Energy (BLE)—the low-power wireless protocol designed for short-range, battery-friendly communication—you have probably hit the same wall I did. Everything works beautifully with one sensor on your desk. Two sensors? Still great. Four sensors? Things start getting flaky. By the time you try to keep six, ten, or fifty sensors connected to a single smartphone or Raspberry Pi, connections start dropping, radio buffers overflow, and batteries drain far faster than expected.
That ceiling isn't a bug in your code; it is a practical reality of how consumer BLE controllers and mobile operating systems (Android and iOS) manage simultaneous active connections. Most phones reliably sustain only about 4 to 7 concurrent GATT connections—where GATT (Generic Attribute Profile) is the standard BLE layer used to read, write, and subscribe to structured data characteristics once two devices are connected.
This project started with a straightforward question: Can we surpass that ~4-device BLE limit cleanly, collect reliable historical data from dozens or hundreds of battery-powered sensors, and build an end-to-end platform that works even when the network goes down?
Here is how we designed and built the solution—from an 8-byte binary wire contract on an ESP32 all the way to a mobile gateway, a streaming message broker, a time-series database, and a live web dashboard.
00.The Core Idea: Don't Stay Connected
Instead of fighting the BLE stack by holding permanent connections to every sensor, we flipped the model around:
- Broadcast live readings without connecting. Sensors wake up, take a measurement, save it to local flash storage, and broadcast their latest temperature, humidity, and pending-log count inside BLE advertising and scan-response packets (short, connectionless radio broadcasts that any nearby scanner can hear without opening a connection).
- Connect to one sensor at a time, briefly. When a gateway hears a sensor advertising
logs_pending = true, it queues that sensor, connects to one device at a time, pulls the entire binary history over GATT notifications, verifies its integrity, tells the sensor to clear flash, syncs the sensor's clock, and disconnects. - Sleep almost all the time. After a 20-second connectable window (or immediately after a gateway finishes offloading), the sensor goes into deep sleep for 5 minutes.
Scaling Past the Radio Ceiling
With this pattern, a single gateway can easily harvest data from dozens or hundreds of sensors without ever holding more than one active BLE connection at a time.
Other Goals We Set Out to Solve
Overcoming the connection ceiling was only the beginning. To make the system genuinely useful in the field, we also aimed for:
- Zero silent data loss: Never delete records from a sensor until every single byte has been verified end-to-end with a checksum.
- 30 days of offline resilience on the sensor: Each sensor buffers up to 8,640 records (30 days at 5-minute intervals) in local flash, dropping the oldest only when full.
- RF collision avoidance: When dozens of sensors share the same wake interval, staggered advertising intervals keep them from stepping on each other's broadcasts.
- Offline-first gateways: Both desktop and mobile gateways cache offloaded telemetry locally and only delete their local queue once the backend confirms receipt.
- Clock drift recovery: Cheap microcontrollers lose track of wall-clock time without Wi-Fi/NTP. Gateways push the current Unix timestamp back to each sensor after every successful offload.
- Scalable ingestion & visibility: Support both a lightweight single-container ingest server and a full production-style hub with user management, geolocation maps, live charts, paginated tables, and a time-series database.
01.Designing a Tiny, Shared Binary Wire Protocol
Everything in this repository—firmware, desktop gateway, mobile app, and automated tests—agrees on a single byte-level contract documented in protocol/SPEC.md and implemented in protocol/frame.py.
We deliberately kept protocol/frame.py free of host-only Python libraries like asyncio or typing so the exact same file can be copied straight onto MicroPython boards—a lean, efficient implementation of Python 3 built specifically to run on microcontrollers.
Every stored reading is packed into just 8 bytes (little-endian): a 4-byte Unix timestamp, a 2-byte signed integer for temperature in centidegrees (23.45 °C → 2345), and a 2-byte signed integer for humidity in centipercent (55.10 % → 5510).
# ble_multiple_devices/protocol/frame.py
_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
Avoiding Advertising Collisions & Supporting iOS Background Wake
Two subtle BLE details made a huge difference in reliability:
- Splitting Advertising and Scan Response packets: iOS requires the 128-bit Service UUID to appear in the primary advertising packet for background wakeups. So we put flags + our 128-bit Service UUID in the primary advertising packet, and place our 16-byte manufacturer telemetry payload in the scan response.
- Staggered advertising intervals: Every sensor derives its advertising interval deterministically from the last byte of its 6-byte hardware MAC address, spacing sensors between
200 msand500 msin20 mssteps.
# ble_multiple_devices/protocol/frame.py
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
if ms > 500:
return 500
return 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
To guarantee that our C firmware (for Arduino), MicroPython firmware, Python gateway, and Dart mobile app never drift apart, every implementation is validated against the same golden byte vectors—for example, sensor a4cf12345601, sequence 7, 23.45 °C, 55.10 %, 3 stored records must serialize to ffffa4cf123456010729098615030001.
02.The Edge Node: ESP32 Firmware with Deep Sleep & CRC-32 Offload
The sensor nodes target the ESP32—a low-cost, low-power system-on-a-chip microcontroller from Espressif with built-in BLE and Wi-Fi radios. We maintain both a MicroPython node (firmware/micropython/) and an Arduino C/C++ sketch (firmware/arduino/ble_sensor/) sharing the exact same wire format.
Each wake cycle in firmware/micropython/main.py is intentionally minimal:
# ble_multiple_devices/firmware/micropython/main.py
def run():
node = SensorNode(SENSOR_ID)
node.bind_sensor_id()
node.sample_and_log()
node.start()
connected_once = False
started = time.ticks_ms()
while True:
node.poll()
if node.connected:
connected_once = True
elif connected_once:
break
elif time.ticks_diff(time.ticks_ms(), started) >= WINDOW_MS:
break
time.sleep_ms(50)
node.stop()
machine.deepsleep(SLEEP_MS)
Notice the power-saving exit condition: if no gateway connects within the advertising window, the ESP32 shuts off the BLE radio and enters deep sleep for 5 minutes (300000 ms). If a gateway does connect, the node stays awake for as long as the transfer takes, and the moment the gateway disconnects, it goes straight back to deep sleep.
Streaming History Safely with CRC-32
When a gateway writes command byte 0x01 (CMD_DUMP) to the command characteristic, the sensor streams every 8-byte record from its append-only logs.bin file over GATT notifications, pacing notifications by 5 ms so the BLE controller's transmit queue never overflows. As it streams, it computes a running CRC-32 (ISO-HDLC)—the same polynomial used by zlib—that detects even a single flipped or dropped bit during wireless transmission:
# ble_multiple_devices/firmware/micropython/node.py
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)
Crucially, the sensor never clears its own flash after streaming. It waits for an explicit 0x02 (CMD_CLEAR) from the gateway. If the radio drops halfway through, the gateway never receives a matching end frame, never sends 0x02, and the sensor's flash remains completely intact for the next wake window.
03.Gateways: One Connection at a Time (Desktop & Mobile)
To make data collection flexible, we built two interchangeable gateways that speak the exact same BLE and HTTP contracts.
Desktop / Edge Computer Gateway (Python + Bleak)
For laptops, mini-PCs, or Raspberry Pis, gateway/ble_gateway/ uses Bleak—a cross-platform, asynchronous Python library for communicating with BLE devices across macOS, Linux (BlueZ), and Windows.
In radio.py, offload_all scans for sensors advertising our SERVICE_UUID, skips any sensor with logs_pending == False, and loops through the rest sequentially—never opening two BLE connections at once:
# ble_multiple_devices/gateway/ble_gateway/radio.py
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 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
Right after session.ok passes the CRC-32 and record-count check in OffloadSession, the gateway sends CMD_CLEAR (0x02) followed immediately by CMD_SET_TIME (0x03 + 4-byte Unix epoch) to keep the sensor's real-time clock accurate.
Mobile Gateway App (Flutter + Offline-First Sync)
For field technicians walking through a warehouse or facility with a phone in their pocket, we built a cross-platform mobile app in mobile/ using Flutter—Google's open-source UI toolkit for compiling natively rendered Android and iOS apps from a single Dart codebase.
- flutter_blue_plus: Wraps native Android and iOS BLE APIs for scanning, connecting, and GATT characteristic notifications.
- sqflite: Embeds SQLite directly inside the phone's local storage as a durable offline queue.
- flutter_background_service: Runs periodic BLE scan-and-offload cycles in an Android foreground service even when the screen is off.
Just like the Python gateway, mobile/lib/src/cycle.dart scans, records every live advertised reading into the local SQLite pending queue, and then offloads sensors with pending flash logs one by one:
// ble_multiple_devices/mobile/lib/src/cycle.dart
for (final sensor in sensors) {
if (shouldStop?.call() == true) break;
if (sensor.reading != null && !sensor.reading!.logsPending) {
continue;
}
final sensorId = sensor.reading?.sensorId ??
sensor.device.remoteId.str.replaceAll(':', '').toLowerCase();
final count = await _offload(sensor.device, sensorId, logs, say);
stored += count;
}
When uploading to the server (mobile/lib/src/sync.dart), the app batches records (250 at a time) and only removes rows from the local SQLite queue after receiving an HTTP 200/201 response. If the phone is underground or offline, every offloaded record stays safely stored locally until connectivity returns. Users only configure the base server URL (e.g., http://192.168.1.50:8000) in Remote Server Settings, and ServerConfig appends /api/telemetry, /api/auth/..., /api/devices/, and /api/telemetry/history/ internally.
04.Two Backend Tiers: Lightweight Ingest vs. Scalable Telemetry Hub
Different deployments have different needs, so the repository provides two backend implementations that share the exact same POST /api/telemetry contract:
Option A: Lightweight Single-Node Ingest (server/)
For simple setups or edge servers, server/app/main.py is built with FastAPI—served by Uvicorn behind Nginx. It stores rows directly in SQLite with a UNIQUE (sensor_id, timestamp) constraint so duplicate retries from gateways are safely ignored.
Option B: Full Scalable Telemetry Hub (backend/ + telemetry_worker/)
For multi-user, multi-site deployments with thousands of devices and millions of readings, we built a containerized multi-service stack orchestrated with Docker and Docker Compose:
- Django & Django REST Framework (DRF): Handles the web UI, ORM, permissions, internationalization (English/Spanish), and JSON APIs.
- django-rest-knox & django-allauth: Provides hashed per-device bearer tokens for mobile and gateway API authentication, plus web login, signup, and password management.
- PostgreSQL: Stores users, places/facilities, device metadata, geolocation coordinates, and cached latest readings.
- NATS & NATS JetStream (
nats-py): Ultra-lightweight cloud-native messaging with durable, replayable message streams. - QuestDB (
asyncpg/psycopg2): High-performance time-series database designed for fast ingestion and analytical SQL queries over timestamped sensor data.
Why put NATS JetStream between Django and QuestDB? Because when a mobile gateway walks back into Wi-Fi range and dumps 5,000 buffered readings at once, the HTTP ingest endpoint shouldn't block on heavy time-series writes. Instead, TelemetryIngestAPIView validates the batch, updates each device's latest status and cached reading in PostgreSQL, and hands the batch to NATS JetStream in a background thread so the HTTP 201 Created response returns immediately:
# 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)
On the other side of the stream, telemetry_worker/worker_group.py runs as an independent microservice with a durable NATS JetStream push queue-group subscription (allowing multiple worker replicas to load-balance messages automatically). It accumulates records in memory and flushes them into QuestDB in batches—either when BATCH_SIZE (50) is reached or every 0.5 seconds:
# 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()
Rich Web Dashboard Built for Thousands of Devices
The Django web interface is styled with Bootstrap 5 and a custom dark theme, enhanced with:
- MapLibre GL JS: Displays every Place and Sensor beacon on an interactive map (with coordinate inheritance from Place to Device).
- Chart.js: Renders live temperature/humidity comparisons and per-sensor time-series histories.
- DataTables (
django-datatable-view): Server-side pagination, search, sorting, and one-click AJAX data refresh—covering/devices/, the dashboard, place details, and QuestDB-backed telemetry history on/devices/<device_id>/. - django-autocomplete-light (DAL / Select2): Async searchable dropdowns for ForeignKey fields (like Places and Place Managers) so forms stay fast even with thousands of records.
- Automatic Inactivity Detection: If a device stops reporting for longer than its configured timeout (cascading from Device → Place →
DEFAULT_DEVICE_TIMEOUT_SECONDS, defaulting to 3600 s), it is automatically markedUNKNOWN.
05.Full Solution Architecture & End-to-End Lifecycle
Here is how all components fit together from the BLE radio at the edge to the time-series storage and dashboards:
+-----------------------------------------------------------------------------------------+
| EDGE LAYER (BLE SENSORS) |
| [ESP32 Sensor #1..N] (MicroPython / Arduino) |
| - Wake 5 min -> Append 8-byte record to logs.bin (30-day ring: 8,640 recs) |
| - Primary Adv: 128-bit Service UUID (iOS wake) | Scan Resp: Live temp/humid/pending |
| - MAC-staggered adv interval (200-500 ms) | 20 s window -> Deep Sleep 5 min |
+-------------------------------------------+---------------------------------------------+
| BLE Adv (live) + GATT Dump (CRC-32)
v
+-----------------------------------------------------------------------------------------+
| GATEWAY LAYER (1 BLE CONNECTION AT A TIME) |
| [Desktop Gateway: Python + Bleak + CSV] | [Mobile App: Flutter + SQLite + BG Svc] |
| - Passive scan queues live adv readings; connects sequentially to logs_pending=True |
| - CMD_DUMP (0x01) -> verify CRC-32 + count -> CMD_CLEAR (0x02) -> CMD_SET_TIME (0x03) |
| - Batches 250 records; deletes local SQLite queue ONLY on HTTP 200 / 201 |
+-------------------------------------------+---------------------------------------------+
| HTTPS POST /api/telemetry (Knox Bearer)
v
+-----------------------------------------------------------------------------------------+
| BACKEND HUB (DOCKER COMPOSE) |
| [Django + DRF + Knox] <---> [(PostgreSQL: Users, Places, Devices, Latest Cache)] |
| | |
| | Publish sensor.<id>.telemetry (background thread -> instant HTTP 201) |
| v |
| [[NATS JetStream: Stream SENSOR_TELEMETRY]] |
| | Durable Push Queue Group (horizontal scaling) |
| v |
| [Telemetry Worker Group: Python + nats-py + asyncpg] |
| | Batched INSERT (50 rows or 0.5 s flush via PG Wire) |
| v |
| [(QuestDB: sensor_telemetry partitioned by day)] |
+-------------------------------------------+---------------------------------------------+
|
+-----------------------+-----------------------+
v v
[Web Dashboard: MapLibre GL JS, [Mobile App Views:
Chart.js, Server-Side DataTables] Places, Devices, History]
End-to-End Data Lifecycle
- Sense & Buffer: Each ESP32 wakes every 5 minutes, appends an 8-byte binary record to flash (
logs.bin), and advertises its live reading pluslogs_pendingflag for 20 seconds using a MAC-staggered interval. - Scan & Offload: A desktop or mobile gateway scans passively, queues live readings locally, and connects to pending sensors one at a time. It sends
0x01(dump), collects 8-byte notifications until the0xFEend frame, validates count + CRC-32, then sends0x02(clear) and0x03(clock sync). - Offline-Safe Upload: Gateways upload batches to
POST /api/telemetrywith a Bearer/Knox token. Local SQLite/pending rows are cleared only upon HTTP200/201. - Decoupled Persistence: Django updates device metadata in PostgreSQL and publishes records to NATS JetStream (
sensor.<id>.telemetry). Thetelemetry_workermicroservice consumes the stream and batch-inserts rows into QuestDB (sensor_telemetry, partitioned by day). - Query & Visualize: Both the web dashboard (MapLibre, Chart.js, server-side DataTables) and the mobile app query PostgreSQL for device/place metadata and QuestDB for paginated historical time series.
Verification Without Radios
One design principle we stuck to throughout was keeping every layer testable on a laptop without needing physical ESP32 hardware attached. Our test script (./scripts/check.sh) compiles the C packer, runs pytest across the protocol, firmware store, gateway, and FastAPI server; Django's test suite verifies models, permissions, timeouts, DAL autocomplete, and DataTables; and flutter test validates the exact same golden byte vectors, offline queue behavior, and UI components in Dart.
06.Closing Thoughts
Trying to hold dozens of simultaneous BLE connections is a losing battle against radio physics and mobile OS limits. By embracing BLE's strengths—connectionless advertising for live status, short one-at-a-time GATT sessions for bulk CRC-verified offloads, and deep sleep in between—we ended up with a system that scales cleanly, protects every byte against RF drops and offline blackouts, and feeds smoothly into a modern event-driven time-series backend.
07.References & Documentation
Félix Pupo Pérez
Over 20 years of experience building bare-metal firmware, BLE/IoT telemetry networks, distributed cloud microservices, and grounded AI systems.