All Articles
CategoryiOS
Reading Time
13 min read
Published
2026-05-13
Word Count
819words

Grab a coffee — this one is a deep dive!

ESP-Point: An Offline-First Architecture for IoT Hardware + iOS Sync

Summary

Architecture design notes from ESP-Point, my own side project: bidirectional ESP32 device ↔ iOS app sync, BLE handshake + Firebase + Realm offline cache. A 50ms handshake target, 3-day offline endurance, OTA firmware updates. BLE state machine fragmentation is the real story.

  • Targets: a 50ms BLE handshake median and a connection drop rate below 1% (industry 4-6%)
  • Three-day offline endurance is designed around a Realm sync queue + Firebase
  • OTA firmware update over 244-byte chunks, targeting above 99% success, takes 4-6 minutes
  • Without CBCentralManagerOptionRestoreIdentifierKey, the connection is lost after the app is killed
ESP-Point: An Offline-First Architecture for IoT Hardware + iOS Sync
ESP-Point is my own side project: a small ESP32-based IoT device and its iOS app, still in development. The figures below are not measured product results; they are the architecture decisions and design targets.

Problem: Bidirectional realtime sync between an ESP32 microcontroller (DIY IoT device) and an iOS app: the device uploads sensor data, and the app sends commands + firmware updates to the device. Offline-first is mandatory — the device will be used in locations without internet access.

Design targets: a 50ms BLE handshake median, 3-day offline endurance (local cache + delayed sync), and a success rate above 99% for OTA firmware updates. All three are targets, not measured results.

1. Architecture

swift
1[ESP32 Device]
2 ↓ BLE (peripheral)
3[iOS App — central]
4 ↓ Wi-Fi when available
5[Firebase Realtime DB + Cloud Storage]
6 ↓ sync queue
7[Web Dashboard for fleet ops]

The iOS app acts as a proxy / router: a BLE \<-\> Cloud bridge.

2. BLE State Machine: The Real Issue

BLE doesn't have just one "easy demo." State machine fragmentation is the real production issue:

States:

  • unpairedScanning
  • pairing
  • paired (connected)
  • paired-disconnected (cached)
  • firmwareUpdating
  • error (reachable from every state)

Each transition means 2-3 race conditions to resolve in iOS CBCentralManager callbacks:

  1. didDisconnect + didFailToConnect overlap — UUID-based dedup
  2. scanForPeripherals background restoration — set CBCentralManagerOptionRestoreIdentifierKey
  3. On the Bluetooth state transition .poweredOff → .poweredOn, scanning doesn't auto-resume — explicit re-call to scanForPeripherals

Target: a 50ms handshake median and a connection drop rate below 1% (industry standard 4-6%).

3. Offline Storage: Realm + Sync Queue

3-day offline target. Every sensor reading (hourly) is written to device storage, then pushed to a sync queue in Realm:

swift
1class SyncQueue: Object {
2 @Persisted(primaryKey: true) var id: ObjectId
3 @Persisted var payload: Data
4 @Persisted var createdAt: Date
5 @Persisted var retryCount: Int = 0
6 @Persisted var lastError: String?
7}

Sync worker:

swift
1final class SyncWorker {
2 func runOnce() async {
3 let realm = try await Realm()
4 let pending = realm.objects(SyncQueue.self)
5 .where { $0.retryCount < 5 }
6 .sorted(by: \.createdAt)
7 .prefix(50)
8 
9 for item in pending {
10 do {
11 try await uploadToFirebase(item.payload)
12 try realm.write { realm.delete(item) }
13 } catch {
14 try realm.write {
15 item.retryCount += 1
16 item.lastError = error.localizedDescription
17 }
18 }
19 }
20 }
21}

The sync worker is triggered via NWPathMonitor network reachability. In the background, the app retries via BGAppRefreshTask starting day 1.

4. OTA Firmware Update

8-12MB binary blob transfer over BLE:

  • Bluetooth chunk size: 244 bytes (BLE 5 max safe)
  • Sequence number + CRC32 per chunk
  • Acknowledgment per 10-chunk batch
  • Total transfer: 4-6 minutes (for 10MB firmware)
  • Resume on disconnect support

Target success rate: above 99%. The failure modes that eat into that budget:

  • connection drop right before the last chunk (the most common case)
  • device flash corruption (recoverable by re-upload)
  • power loss at a critical moment (manual recovery required)

The OTA UI matters — progress bar + "do not close app" warning + battery indicator. Without those three, the OTA screen generates negative App Store reviews on its own.

5. Test Strategy

  • Unit tests: Sync queue state machine, BLE manager state transitions (mocked CBCentralManager)
  • Integration tests: Realm migration, sync conflict resolution
  • Device farm plan: 6 physical ESP32 units + 4 iPhone devices (iOS 16-18) — physical testing in the CI pipeline
  • Snapshot tests: UI state for each BLE state

Coverage targets: domain layer 90%+, BLE manager 75%+, UI around 65%.

6. iOS App Architecture

  • SwiftUI iOS 16+
  • BLEManager: @MainActor actor (Bluetooth callbacks run on the main thread)
  • DataLayer: Realm primary + Firebase secondary (offline-first)
  • Sync orchestrator: BG task + foreground refresh

Memory budget: 105MB baseline, peaking at 220MB during OTA (firmware buffer).

7. Lessons

1. Physical BLE testing is mandatory. The simulator cannot simulate BLE, so a physical device in CI is a must.

2. CBCentralManagerOptionRestoreIdentifierKey is critical for background relaunch — without it, the connection is lost after the app is killed.

3. State machine documentation. In a 6-state machine every transition has to be logged for production debugging.

4. Realm migration can empty the sync queue on schema changes — without a migration test, that turns into silent data loss on the user's side.

5. Don't give users an OTA "abort" button — risk of flash corruption. Pause/resume only.

6. Firebase rules can throttle offline write throughput — requireAuth: false write rule + custom token validation.

7. Battery profiling is required: constant BLE scanning drops the phone to the 8-hour band. The connection-on-demand pattern saves around 35% on that line item.

Result: IoT + iOS sync is far harder than the "happy path" demos suggest. State machine + offline storage + OTA is technical debt measured in months if it isn't planned upfront.

Tags

#case study#IoT#BLE#Bluetooth#offline-first#Realm#Firebase
Muhittin Camdali

Muhittin Çamdalı

Senior Mobile Engineer

Senior Mobile Engineer with 12+ years of experience. I build mobile products with iOS, Flutter and React Native, working full-stack and AI-native.

iOS Development News

Weekly Swift tips, SwiftUI tricks and iOS best practices. No spam, only valuable content.

Your subscription starts when you open the link in the confirmation email and press “Confirm my subscription”. The newsletter keeps open/click statistics; you can unsubscribe anytime with one click. Privacy

Share