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
1[ESP32 Device]2 ↓ BLE (peripheral)3[iOS App — central]4 ↓ Wi-Fi when available5[Firebase Realtime DB + Cloud Storage]6 ↓ sync queue7[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:
unpairedScanningpairingpaired(connected)paired-disconnected(cached)firmwareUpdatingerror(reachable from every state)
Each transition means 2-3 race conditions to resolve in iOS CBCentralManager callbacks:
didDisconnect+didFailToConnectoverlap — UUID-based dedupscanForPeripheralsbackground restoration — setCBCentralManagerOptionRestoreIdentifierKey- On the Bluetooth state transition
.poweredOff→.poweredOn, scanning doesn't auto-resume — explicit re-call toscanForPeripherals
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:
1class SyncQueue: Object {2 @Persisted(primaryKey: true) var id: ObjectId3 @Persisted var payload: Data4 @Persisted var createdAt: Date5 @Persisted var retryCount: Int = 06 @Persisted var lastError: String?7}Sync worker:
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 += 116 item.lastError = error.localizedDescription17 }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:
@MainActoractor (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
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
