peat-btle 0.3.3

Bluetooth Low Energy mesh transport for Peat Protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
# Apple Platform Integration Guide (iOS/macOS)

This guide covers integrating `peat-btle` into iOS and macOS applications using CoreBluetooth.

## Requirements

| Platform | Minimum Version |
|----------|-----------------|
| iOS | 13.0 |
| macOS | 10.15 (Catalina) |
| Xcode | 15.0+ |

### Hardware Requirements

- iPhone 8 or newer for best BLE 5.0 support
- Any modern Mac with Bluetooth

## Architecture

```
┌─────────────────────────────────────────┐
│       SwiftUI / UIKit Application       │
├─────────────────────────────────────────┤
│         UniFFI Swift Bindings           │
├─────────────────────────────────────────┤
│      CoreBluetoothAdapter (Rust)        │
├─────────────────────────────────────────┤
│  CentralManager    │  PeripheralManager │
│   (scanning,       │   (advertising,    │
│    connecting)     │    GATT server)    │
├─────────────────────────────────────────┤
│           Objective-C Delegates          │
├─────────────────────────────────────────┤
│           CoreBluetooth Framework        │
└─────────────────────────────────────────┘
```

## Project Setup

### Option 1: Pure Swift with Native BLE

For simpler integration, use Swift's CoreBluetooth directly and call Rust for mesh logic only.

### Option 2: Full Rust Integration (UniFFI)

Use UniFFI to expose the entire Rust API to Swift.

---

## Info.plist Configuration

Add required permissions:

```xml
<!-- Bluetooth usage description -->
<key>NSBluetoothAlwaysUsageDescription</key>
<string>Peat uses Bluetooth to sync data with nearby devices</string>

<!-- For iOS 13+ -->
<key>NSBluetoothPeripheralUsageDescription</key>
<string>Peat uses Bluetooth to sync data with nearby devices</string>

<!-- Background modes (iOS) -->
<key>UIBackgroundModes</key>
<array>
    <string>bluetooth-central</string>
    <string>bluetooth-peripheral</string>
</array>
```

### macOS Sandbox Entitlements

For sandboxed Mac apps, add to `*.entitlements`:

```xml
<key>com.apple.security.device.bluetooth</key>
<true/>
```

## Swift Implementation

### PeatManager Class

```swift
import CoreBluetooth
import Combine

class PeatManager: NSObject, ObservableObject {
    // Published state
    @Published var peers: [PeatPeer] = []
    @Published var isScanning = false
    @Published var isAdvertising = false
    @Published var emergencyActive = false

    // CoreBluetooth managers
    private var centralManager: CBCentralManager!
    private var peripheralManager: CBPeripheralManager!

    // Peat UUIDs
    private let peatServiceUUID = CBUUID(string: "F47AC10B-58CC-4372-A567-0E02B2C3D479")
    private let documentCharUUID = CBUUID(string: "F47AC10B-58CC-4372-A567-0E02B2C30003")

    // Connections
    private var connectedPeripherals: [UUID: CBPeripheral] = [:]
    private var documentCharacteristics: [UUID: CBCharacteristic] = [:]

    // Rust bridge
    private var meshBridge: PeatMeshBridge?

    override init() {
        super.init()
        centralManager = CBCentralManager(delegate: self, queue: nil)
        peripheralManager = CBPeripheralManager(delegate: self, queue: nil)

        // Initialize Rust mesh
        initializeMesh()
    }

    private func initializeMesh() {
        let nodeId = generateNodeId()
        meshBridge = PeatMeshBridge(
            nodeId: nodeId,
            callsign: "IOS-\(UIDevice.current.name.prefix(4))",
            meshId: "DEMO"
        )
    }

    private func generateNodeId() -> UInt32 {
        // Use a stable identifier derived from device
        let id = UIDevice.current.identifierForVendor ?? UUID()
        let bytes = id.uuid
        return UInt32(bytes.12) << 24 |
               UInt32(bytes.13) << 16 |
               UInt32(bytes.14) << 8 |
               UInt32(bytes.15)
    }

    // MARK: - Public API

    func startScanning() {
        guard centralManager.state == .poweredOn else { return }
        centralManager.scanForPeripherals(
            withServices: [peatServiceUUID],
            options: [CBCentralManagerScanOptionAllowDuplicatesKey: false]
        )
        isScanning = true
    }

    func stopScanning() {
        centralManager.stopScan()
        isScanning = false
    }

    func startAdvertising() {
        guard peripheralManager.state == .poweredOn else { return }

        let advertisementData: [String: Any] = [
            CBAdvertisementDataServiceUUIDsKey: [peatServiceUUID],
            CBAdvertisementDataLocalNameKey: meshBridge?.deviceName ?? "Peat"
        ]

        peripheralManager.startAdvertising(advertisementData)
        isAdvertising = true
    }

    func stopAdvertising() {
        peripheralManager.stopAdvertising()
        isAdvertising = false
    }

    func sendEmergency() {
        guard let data = meshBridge?.sendEmergency() else { return }
        broadcastToAllPeers(data: data)
        emergencyActive = true
    }

    func sendAck() {
        guard let data = meshBridge?.sendAck() else { return }
        broadcastToAllPeers(data: data)
    }

    func clearEmergency() {
        meshBridge?.clearEvent()
        emergencyActive = false
    }

    private func broadcastToAllPeers(data: Data) {
        for (uuid, char) in documentCharacteristics {
            if let peripheral = connectedPeripherals[uuid] {
                peripheral.writeValue(data, for: char, type: .withResponse)
            }
        }
    }

    func tick() {
        if let data = meshBridge?.tick() {
            broadcastToAllPeers(data: data)
        }
    }
}

// MARK: - CBCentralManagerDelegate

extension PeatManager: CBCentralManagerDelegate {
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state {
        case .poweredOn:
            startScanning()
            setupGattService()
        case .poweredOff:
            isScanning = false
            isAdvertising = false
        default:
            break
        }
    }

    func centralManager(_ central: CBCentralManager,
                        didDiscover peripheral: CBPeripheral,
                        advertisementData: [String: Any],
                        rssi RSSI: NSNumber) {
        let name = advertisementData[CBAdvertisementDataLocalNameKey] as? String

        // Parse mesh ID from name
        var meshId: String?
        if let name = name, name.hasPrefix("PEAT_") {
            let parts = name.dropFirst(5).split(separator: "-")
            if parts.count >= 1 {
                meshId = String(parts[0])
            }
        }

        // Notify Rust layer
        if let nodeId = meshBridge?.onDiscovered(
            identifier: peripheral.identifier.uuidString,
            name: name,
            rssi: RSSI.int8Value,
            meshId: meshId
        ) {
            // Add to peers list
            let peer = PeatPeer(
                nodeId: nodeId,
                name: name ?? "Unknown",
                rssi: RSSI.intValue
            )

            if !peers.contains(where: { $0.nodeId == nodeId }) {
                DispatchQueue.main.async {
                    self.peers.append(peer)
                }
            }

            // Connect if not already
            if connectedPeripherals[peripheral.identifier] == nil {
                central.connect(peripheral, options: nil)
            }
        }
    }

    func centralManager(_ central: CBCentralManager,
                        didConnect peripheral: CBPeripheral) {
        connectedPeripherals[peripheral.identifier] = peripheral
        peripheral.delegate = self
        peripheral.discoverServices([peatServiceUUID])

        meshBridge?.onConnected(identifier: peripheral.identifier.uuidString)
    }

    func centralManager(_ central: CBCentralManager,
                        didDisconnectPeripheral peripheral: CBPeripheral,
                        error: Error?) {
        connectedPeripherals.removeValue(forKey: peripheral.identifier)
        documentCharacteristics.removeValue(forKey: peripheral.identifier)

        meshBridge?.onDisconnected(identifier: peripheral.identifier.uuidString)

        // Reconnect
        central.connect(peripheral, options: nil)
    }
}

// MARK: - CBPeripheralDelegate

extension PeatManager: CBPeripheralDelegate {
    func peripheral(_ peripheral: CBPeripheral,
                    didDiscoverServices error: Error?) {
        guard let services = peripheral.services else { return }

        for service in services {
            if service.uuid == peatServiceUUID {
                peripheral.discoverCharacteristics([documentCharUUID], for: service)
            }
        }
    }

    func peripheral(_ peripheral: CBPeripheral,
                    didDiscoverCharacteristicsFor service: CBService,
                    error: Error?) {
        guard let characteristics = service.characteristics else { return }

        for char in characteristics {
            if char.uuid == documentCharUUID {
                documentCharacteristics[peripheral.identifier] = char

                // Enable notifications
                peripheral.setNotifyValue(true, for: char)

                // Initial read
                peripheral.readValue(for: char)
            }
        }
    }

    func peripheral(_ peripheral: CBPeripheral,
                    didUpdateValueFor characteristic: CBCharacteristic,
                    error: Error?) {
        guard let data = characteristic.value else { return }

        if let result = meshBridge?.onDataReceived(
            identifier: peripheral.identifier.uuidString,
            data: data
        ) {
            if result.isEmergency {
                DispatchQueue.main.async {
                    self.emergencyActive = true
                    self.triggerHapticFeedback()
                }
            }
        }
    }

    private func triggerHapticFeedback() {
        #if os(iOS)
        let generator = UINotificationFeedbackGenerator()
        generator.notificationOccurred(.warning)
        #endif
    }
}

// MARK: - CBPeripheralManagerDelegate

extension PeatManager: CBPeripheralManagerDelegate {
    func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
        if peripheral.state == .poweredOn {
            setupGattService()
            startAdvertising()
        }
    }

    private func setupGattService() {
        let characteristic = CBMutableCharacteristic(
            type: documentCharUUID,
            properties: [.read, .write, .notify],
            value: nil,
            permissions: [.readable, .writeable]
        )

        let service = CBMutableService(type: peatServiceUUID, primary: true)
        service.characteristics = [characteristic]

        peripheralManager.add(service)
    }

    func peripheralManager(_ peripheral: CBPeripheralManager,
                           didReceiveRead request: CBATTRequest) {
        if request.characteristic.uuid == documentCharUUID {
            if let data = meshBridge?.buildDocument() {
                request.value = data
                peripheral.respond(to: request, withResult: .success)
            } else {
                peripheral.respond(to: request, withResult: .attributeNotFound)
            }
        }
    }

    func peripheralManager(_ peripheral: CBPeripheralManager,
                           didReceiveWrite requests: [CBATTRequest]) {
        for request in requests {
            if request.characteristic.uuid == documentCharUUID,
               let data = request.value {
                meshBridge?.onDataReceived(
                    identifier: request.central.identifier.uuidString,
                    data: data
                )
            }
        }

        if let first = requests.first {
            peripheral.respond(to: first, withResult: .success)
        }
    }
}
```

### SwiftUI View

```swift
import SwiftUI

struct ContentView: View {
    @StateObject private var peatManager = PeatManager()

    var body: some View {
        NavigationView {
            VStack(spacing: 20) {
                // Status
                HStack {
                    StatusIndicator(
                        label: "Scanning",
                        active: peatManager.isScanning
                    )
                    StatusIndicator(
                        label: "Advertising",
                        active: peatManager.isAdvertising
                    )
                }

                // Peer list
                List(peatManager.peers) { peer in
                    PeerRow(peer: peer)
                }

                // Action buttons
                HStack(spacing: 20) {
                    Button("EMERGENCY") {
                        peatManager.sendEmergency()
                    }
                    .buttonStyle(EmergencyButtonStyle())

                    Button("ACK") {
                        peatManager.sendAck()
                    }
                    .buttonStyle(AckButtonStyle())

                    Button("RESET") {
                        peatManager.clearEmergency()
                    }
                    .buttonStyle(ResetButtonStyle())
                }
            }
            .navigationTitle("Peat Mesh")
            .onAppear {
                // Start tick timer
                Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
                    peatManager.tick()
                }
            }
        }
    }
}
```

## UniFFI Integration (Optional)

For full Rust API exposure, use UniFFI bindings.

### 1. Create FFI Crate

```toml
# peat-apple-ffi/Cargo.toml
[package]
name = "peat-apple-ffi"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["staticlib", "cdylib"]
name = "peat_apple_ffi"

[dependencies]
peat-btle = { path = ".." }
uniffi = "0.25"

[build-dependencies]
uniffi = { version = "0.25", features = ["build"] }
```

### 2. Define UDL Interface

```udl
// peat-apple-ffi/src/peat.udl
namespace peat_apple_ffi {
    PeatMeshBridge create_mesh(u32 node_id, string callsign, string mesh_id);
};

interface PeatMeshBridge {
    constructor(u32 node_id, string callsign, string mesh_id);

    string device_name();

    u32? on_discovered(string identifier, string? name, i8 rssi, string? mesh_id);
    u32? on_connected(string identifier);
    void on_disconnected(string identifier);

    DataResult? on_data_received(string identifier, bytes data);

    bytes send_emergency();
    bytes send_ack();
    void clear_event();

    bytes? tick();
    bytes build_document();
};

dictionary DataResult {
    u32 source_node;
    boolean is_emergency;
    boolean is_ack;
};
```

### 3. Build Script

```bash
#!/bin/bash
# build-apple.sh

set -e

# Build for all Apple platforms
for TARGET in \
    aarch64-apple-ios \
    aarch64-apple-ios-sim \
    x86_64-apple-ios \
    aarch64-apple-darwin \
    x86_64-apple-darwin
do
    echo "Building for $TARGET..."
    cargo build --release --target $TARGET
done

# Create XCFramework
mkdir -p build

# Generate Swift bindings
cargo run --bin uniffi-bindgen generate \
    src/peat.udl --language swift --out-dir build/

# Create fat libraries
lipo -create \
    target/aarch64-apple-ios-sim/release/libpeat_apple_ffi.a \
    target/x86_64-apple-ios/release/libpeat_apple_ffi.a \
    -output build/libpeat_apple_ffi_sim.a

# Create XCFramework
xcodebuild -create-xcframework \
    -library target/aarch64-apple-ios/release/libpeat_apple_ffi.a \
    -headers build/ \
    -library build/libpeat_apple_ffi_sim.a \
    -headers build/ \
    -library target/aarch64-apple-darwin/release/libpeat_apple_ffi.a \
    -headers build/ \
    -output build/PeatFFI.xcframework

echo "XCFramework created at build/PeatFFI.xcframework"
```

## Background Execution

### iOS Background Handling

```swift
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        // Check if launched from BLE event
        if let centralOptions = launchOptions?[.bluetoothCentrals] as? [String] {
            // Restore central manager state
        }
        if let peripheralOptions = launchOptions?[.bluetoothPeripherals] as? [String] {
            // Restore peripheral manager state
        }
        return true
    }
}
```

### State Restoration

```swift
// In PeatManager init
centralManager = CBCentralManager(
    delegate: self,
    queue: nil,
    options: [CBCentralManagerOptionRestoreIdentifierKey: "PeatCentral"]
)

peripheralManager = CBPeripheralManager(
    delegate: self,
    queue: nil,
    options: [CBPeripheralManagerOptionRestoreIdentifierKey: "PeatPeripheral"]
)

// Handle restoration
func centralManager(_ central: CBCentralManager,
                    willRestoreState dict: [String: Any]) {
    if let peripherals = dict[CBCentralManagerRestoredStatePeripheralsKey] as? [CBPeripheral] {
        for peripheral in peripherals {
            connectedPeripherals[peripheral.identifier] = peripheral
            peripheral.delegate = self
        }
    }
}
```

## Troubleshooting

### Common Issues

| Issue | Cause | Solution |
|-------|-------|----------|
| Scan returns nothing | No BLE permission | Check Info.plist |
| Background stops | Missing background mode | Add UIBackgroundModes |
| Mac sandbox error | Missing entitlement | Add bluetooth entitlement |
| Discovery fails | Wrong UUID format | Use uppercase UUID |

### Debug Logging

```swift
// Enable CoreBluetooth debug logging
// Add to scheme environment variables:
// CBUUID_DEBUG=1
```

## References

- [CoreBluetooth Programming Guide]https://developer.apple.com/library/archive/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/
- [WWDC: What's New in Core Bluetooth]https://developer.apple.com/videos/play/wwdc2019/901/
- [UniFFI Swift Bindings]https://mozilla.github.io/uniffi-rs/swift/overview.html
- [Background Execution]https://developer.apple.com/documentation/corebluetooth/cbcentralmanager/1518696-restoredstate