peat-btle 0.3.2

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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
# Android Platform Integration Guide

This guide covers integrating `peat-btle` into Android applications using JNI bindings.

## Requirements

| Requirement | Minimum | Recommended |
|-------------|---------|-------------|
| Android API | 23 (6.0) | 26+ (8.0) |
| BLE 5.0 features | API 26 | API 26+ |
| Coded PHY | API 26 | API 26+ |

### Permissions

Add to `AndroidManifest.xml`:

```xml
<!-- BLE permissions -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />

<!-- Location required for BLE scanning on Android 6-11 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

<!-- Declare BLE hardware support -->
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true" />
```

**Permission Notes:**
- Android 12+ (API 31): Use new granular permissions (`BLUETOOTH_SCAN`, `BLUETOOTH_CONNECT`, `BLUETOOTH_ADVERTISE`)
- Android 6-11: Location permission required for BLE scanning
- Android 10+: `ACCESS_BACKGROUND_LOCATION` for background scanning

## Architecture

```
┌─────────────────────────────────────────┐
│        Kotlin/Java Application          │
├─────────────────────────────────────────┤
│           JNI Bridge (native)           │
├─────────────────────────────────────────┤
│         AndroidAdapter (Rust)           │
├─────────────────────────────────────────┤
│  BluetoothAdapter │ BluetoothLeScanner  │
│  BluetoothGatt    │ BluetoothGattServer │
└─────────────────────────────────────────┘
```

## Project Setup

### 1. Configure Cargo.toml

```toml
[lib]
crate-type = ["cdylib"]

[dependencies]
peat-btle = { version = "0.1", features = ["android"] }
jni = "0.21"
log = "0.4"
android_logger = "0.13"
```

### 2. Create JNI Library

Create `src/lib.rs`:

```rust
use jni::JNIEnv;
use jni::objects::{JClass, JObject, JString};
use jni::sys::{jlong, jbyteArray, jint};

use peat_btle::{PeatMesh, PeatMeshConfig, NodeId};
use peat_btle::observer::DisconnectReason;

use std::sync::Arc;
use std::panic;

// Store mesh instance pointer
static mut MESH: Option<Arc<PeatMesh>> = None;

#[no_mangle]
pub extern "C" fn Java_com_example_hive_PeatBridge_init(
    mut env: JNIEnv,
    _class: JClass,
    node_id: jlong,
    callsign: JString,
    mesh_id: JString,
) -> jint {
    // Initialize logging
    android_logger::init_once(
        android_logger::Config::default()
            .with_max_level(log::LevelFilter::Debug)
            .with_tag("peat-btle"),
    );

    panic::catch_unwind(|| {
        let callsign: String = env.get_string(&callsign)
            .expect("Invalid callsign")
            .into();
        let mesh_id: String = env.get_string(&mesh_id)
            .expect("Invalid mesh_id")
            .into();

        let config = PeatMeshConfig::new(
            NodeId::new(node_id as u32),
            &callsign,
            &mesh_id,
        );

        let mesh = PeatMesh::new(config);

        unsafe {
            MESH = Some(Arc::new(mesh));
        }

        0 // Success
    }).unwrap_or(-1)
}

#[no_mangle]
pub extern "C" fn Java_com_example_hive_PeatBridge_onDiscovered(
    mut env: JNIEnv,
    _class: JClass,
    identifier: JString,
    name: JString,
    rssi: jint,
    mesh_id: JString,
    now_ms: jlong,
) -> jlong {
    let mesh = unsafe {
        match &MESH {
            Some(m) => m.clone(),
            None => return -1,
        }
    };

    let identifier: String = env.get_string(&identifier)
        .unwrap_or_default().into();
    let name: Option<String> = env.get_string(&name).ok().map(|s| s.into());
    let mesh_id: Option<String> = env.get_string(&mesh_id).ok().map(|s| s.into());

    match mesh.on_ble_discovered(
        &identifier,
        name.as_deref(),
        rssi as i8,
        mesh_id.as_deref(),
        now_ms as u64,
    ) {
        Some(peer) => peer.node_id.as_u32() as jlong,
        None => 0,
    }
}

#[no_mangle]
pub extern "C" fn Java_com_example_hive_PeatBridge_onConnected(
    mut env: JNIEnv,
    _class: JClass,
    identifier: JString,
    now_ms: jlong,
) -> jlong {
    let mesh = unsafe {
        match &MESH {
            Some(m) => m.clone(),
            None => return -1,
        }
    };

    let identifier: String = env.get_string(&identifier)
        .unwrap_or_default().into();

    match mesh.on_ble_connected(&identifier, now_ms as u64) {
        Some(node_id) => node_id.as_u32() as jlong,
        None => 0,
    }
}

#[no_mangle]
pub extern "C" fn Java_com_example_hive_PeatBridge_onDisconnected(
    mut env: JNIEnv,
    _class: JClass,
    identifier: JString,
    reason: jint,
) -> jlong {
    let mesh = unsafe {
        match &MESH {
            Some(m) => m.clone(),
            None => return -1,
        }
    };

    let identifier: String = env.get_string(&identifier)
        .unwrap_or_default().into();

    let reason = match reason {
        0 => DisconnectReason::LocalRequest,
        1 => DisconnectReason::RemoteRequest,
        2 => DisconnectReason::Timeout,
        3 => DisconnectReason::LinkLoss,
        _ => DisconnectReason::Unknown,
    };

    match mesh.on_ble_disconnected(&identifier, reason) {
        Some(node_id) => node_id.as_u32() as jlong,
        None => 0,
    }
}

#[no_mangle]
pub extern "C" fn Java_com_example_hive_PeatBridge_onDataReceived(
    mut env: JNIEnv,
    _class: JClass,
    identifier: JString,
    data: jbyteArray,
    now_ms: jlong,
) -> jint {
    let mesh = unsafe {
        match &MESH {
            Some(m) => m.clone(),
            None => return -1,
        }
    };

    let identifier: String = env.get_string(&identifier)
        .unwrap_or_default().into();

    let data = match env.convert_byte_array(data) {
        Ok(d) => d,
        Err(_) => return -2,
    };

    match mesh.on_ble_data_received(&identifier, &data, now_ms as u64) {
        Some(result) => {
            if result.is_emergency { 1 }
            else if result.is_ack { 2 }
            else { 0 }
        }
        None => -3,
    }
}

#[no_mangle]
pub extern "C" fn Java_com_example_hive_PeatBridge_sendEmergency(
    env: JNIEnv,
    _class: JClass,
    timestamp: jlong,
) -> jbyteArray {
    let mesh = unsafe {
        match &MESH {
            Some(m) => m.clone(),
            None => return std::ptr::null_mut(),
        }
    };

    let doc = mesh.send_emergency(timestamp as u64);

    env.byte_array_from_slice(&doc)
        .unwrap_or_else(|_| std::ptr::null_mut())
}

#[no_mangle]
pub extern "C" fn Java_com_example_hive_PeatBridge_sendAck(
    env: JNIEnv,
    _class: JClass,
    timestamp: jlong,
) -> jbyteArray {
    let mesh = unsafe {
        match &MESH {
            Some(m) => m.clone(),
            None => return std::ptr::null_mut(),
        }
    };

    let doc = mesh.send_ack(timestamp as u64);

    env.byte_array_from_slice(&doc)
        .unwrap_or_else(|_| std::ptr::null_mut())
}

#[no_mangle]
pub extern "C" fn Java_com_example_hive_PeatBridge_tick(
    env: JNIEnv,
    _class: JClass,
    now_ms: jlong,
) -> jbyteArray {
    let mesh = unsafe {
        match &MESH {
            Some(m) => m.clone(),
            None => return std::ptr::null_mut(),
        }
    };

    match mesh.tick(now_ms as u64) {
        Some(doc) => env.byte_array_from_slice(&doc)
            .unwrap_or_else(|_| std::ptr::null_mut()),
        None => std::ptr::null_mut(),
    }
}

#[no_mangle]
pub extern "C" fn Java_com_example_hive_PeatBridge_buildDocument(
    env: JNIEnv,
    _class: JClass,
) -> jbyteArray {
    let mesh = unsafe {
        match &MESH {
            Some(m) => m.clone(),
            None => return std::ptr::null_mut(),
        }
    };

    let doc = mesh.build_document();

    env.byte_array_from_slice(&doc)
        .unwrap_or_else(|_| std::ptr::null_mut())
}
```

### 3. Create Kotlin Bridge Class

```kotlin
package com.example.hive

class PeatBridge {
    companion object {
        init {
            System.loadLibrary("hive_android")
        }

        @JvmStatic
        external fun init(nodeId: Long, callsign: String, meshId: String): Int

        @JvmStatic
        external fun onDiscovered(
            identifier: String,
            name: String?,
            rssi: Int,
            meshId: String?,
            nowMs: Long
        ): Long

        @JvmStatic
        external fun onConnected(identifier: String, nowMs: Long): Long

        @JvmStatic
        external fun onDisconnected(identifier: String, reason: Int): Long

        @JvmStatic
        external fun onDataReceived(
            identifier: String,
            data: ByteArray,
            nowMs: Long
        ): Int

        @JvmStatic
        external fun sendEmergency(timestamp: Long): ByteArray?

        @JvmStatic
        external fun sendAck(timestamp: Long): ByteArray?

        @JvmStatic
        external fun tick(nowMs: Long): ByteArray?

        @JvmStatic
        external fun buildDocument(): ByteArray?
    }
}
```

### 4. Build Script

Create `build-android.sh`:

```bash
#!/bin/bash
set -e

# Ensure NDK is set
if [ -z "$ANDROID_NDK_HOME" ]; then
    echo "Error: ANDROID_NDK_HOME not set"
    exit 1
fi

# Add Android targets
rustup target add aarch64-linux-android armv7-linux-androideabi x86_64-linux-android

# Build for each architecture
TARGETS=(
    "aarch64-linux-android"
    "armv7-linux-androideabi"
    "x86_64-linux-android"
)

for TARGET in "${TARGETS[@]}"; do
    echo "Building for $TARGET..."
    cargo build --release --target $TARGET
done

# Copy libraries to Android project
mkdir -p app/src/main/jniLibs/{arm64-v8a,armeabi-v7a,x86_64}

cp target/aarch64-linux-android/release/libpeat_android.so \
   app/src/main/jniLibs/arm64-v8a/

cp target/armv7-linux-androideabi/release/libpeat_android.so \
   app/src/main/jniLibs/armeabi-v7a/

cp target/x86_64-linux-android/release/libpeat_android.so \
   app/src/main/jniLibs/x86_64/

echo "Done! Libraries copied to app/src/main/jniLibs/"
```

## Android BLE Integration

### BLE Scanner Implementation

```kotlin
class PeatBleManager(private val context: Context) {
    private val bluetoothAdapter: BluetoothAdapter? by lazy {
        (context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter
    }

    private val scanner: BluetoothLeScanner?
        get() = bluetoothAdapter?.bluetoothLeScanner

    private val peatServiceUuid = ParcelUuid.fromString("f47ac10b-58cc-4372-a567-0e02b2c3d479")

    private val scanCallback = object : ScanCallback() {
        override fun onScanResult(callbackType: Int, result: ScanResult) {
            val device = result.device
            val name = result.scanRecord?.deviceName
            val rssi = result.rssi

            // Parse mesh ID from device name (PEAT_MESHID-NODEID)
            val meshId = name?.let {
                if (it.startsWith("PEAT_")) {
                    it.substringAfter("PEAT_").substringBefore("-")
                } else null
            }

            // Notify Rust layer
            PeatBridge.onDiscovered(
                device.address,
                name,
                rssi,
                meshId,
                System.currentTimeMillis()
            )
        }

        override fun onScanFailed(errorCode: Int) {
            Log.e("PeatBLE", "Scan failed: $errorCode")
        }
    }

    fun startScan() {
        val settings = ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
            .build()

        val filters = listOf(
            ScanFilter.Builder()
                .setServiceUuid(peatServiceUuid)
                .build()
        )

        scanner?.startScan(filters, settings, scanCallback)
    }

    fun stopScan() {
        scanner?.stopScan(scanCallback)
    }
}
```

### GATT Client Implementation

```kotlin
class PeatGattClient(
    private val context: Context,
    private val onDataReceived: (ByteArray) -> Unit
) {
    private var gatt: BluetoothGatt? = null
    private var documentCharacteristic: BluetoothGattCharacteristic? = null

    private val peatServiceUuid = UUID.fromString("f47ac10b-58cc-4372-a567-0e02b2c3d479")
    private val documentCharUuid = UUID.fromString("f47ac10b-58cc-4372-a567-0e02b2c3d479")

    private val gattCallback = object : BluetoothGattCallback() {
        override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
            when (newState) {
                BluetoothProfile.STATE_CONNECTED -> {
                    PeatBridge.onConnected(gatt.device.address, System.currentTimeMillis())
                    gatt.discoverServices()
                }
                BluetoothProfile.STATE_DISCONNECTED -> {
                    PeatBridge.onDisconnected(gatt.device.address, 1)
                }
            }
        }

        override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                val service = gatt.getService(peatServiceUuid)
                documentCharacteristic = service?.getCharacteristic(documentCharUuid)

                // Enable notifications
                documentCharacteristic?.let { char ->
                    gatt.setCharacteristicNotification(char, true)
                    val descriptor = char.getDescriptor(
                        UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")
                    )
                    descriptor?.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
                    gatt.writeDescriptor(descriptor)
                }
            }
        }

        override fun onCharacteristicChanged(
            gatt: BluetoothGatt,
            characteristic: BluetoothGattCharacteristic
        ) {
            if (characteristic.uuid == documentCharUuid) {
                val data = characteristic.value
                PeatBridge.onDataReceived(
                    gatt.device.address,
                    data,
                    System.currentTimeMillis()
                )
                onDataReceived(data)
            }
        }
    }

    fun connect(device: BluetoothDevice) {
        gatt = device.connectGatt(context, false, gattCallback)
    }

    fun disconnect() {
        gatt?.disconnect()
        gatt?.close()
        gatt = null
    }

    fun writeDocument(data: ByteArray) {
        documentCharacteristic?.let { char ->
            char.value = data
            gatt?.writeCharacteristic(char)
        }
    }
}
```

## Encryption Setup

```kotlin
// Generate or load 32-byte encryption secret
val encryptionSecret = ByteArray(32).also {
    SecureRandom().nextBytes(it)
}

// Initialize with encryption
PeatBridge.initWithEncryption(
    nodeId = getNodeId(),
    callsign = "ALPHA-1",
    meshId = "DEMO",
    encryptionSecret = encryptionSecret
)
```

## Lifecycle Integration

```kotlin
class PeatService : Service() {
    private lateinit var bleManager: PeatBleManager

    override fun onCreate() {
        super.onCreate()

        // Initialize Peat
        val nodeId = generateNodeId()
        PeatBridge.init(nodeId, "ANDROID-1", "DEMO")

        bleManager = PeatBleManager(this)

        // Start periodic tick
        handler.postDelayed(tickRunnable, 1000)
    }

    private val tickRunnable = object : Runnable {
        override fun run() {
            PeatBridge.tick(System.currentTimeMillis())?.let { doc ->
                // Broadcast to connected peers
                broadcastDocument(doc)
            }
            handler.postDelayed(this, 1000)
        }
    }

    private fun generateNodeId(): Long {
        // Use last 4 bytes of Bluetooth MAC address
        val btAddress = BluetoothAdapter.getDefaultAdapter()?.address
        return btAddress?.let {
            val bytes = it.split(":").map { b -> b.toInt(16).toByte() }
            ((bytes[2].toLong() and 0xFF) shl 24) or
            ((bytes[3].toLong() and 0xFF) shl 16) or
            ((bytes[4].toLong() and 0xFF) shl 8) or
            (bytes[5].toLong() and 0xFF)
        } ?: System.currentTimeMillis()
    }
}
```

## Testing

### Unit Testing

```kotlin
@Test
fun testPeatBridgeInit() {
    val result = PeatBridge.init(0x12345678, "TEST-1", "TEST")
    assertEquals(0, result)
}

@Test
fun testBuildDocument() {
    PeatBridge.init(0x12345678, "TEST-1", "TEST")
    val doc = PeatBridge.buildDocument()
    assertNotNull(doc)
    assertTrue(doc.isNotEmpty())
}
```

### Integration Testing

Use Android Emulator with BLE support or real devices:

1. Install app on two devices
2. Ensure both are on same mesh ID
3. Trigger emergency on device A
4. Verify device B receives emergency event

## Troubleshooting

### Common Issues

| Issue | Cause | Solution |
|-------|-------|----------|
| Scan returns no results | Missing permissions | Request runtime permissions |
| Connection fails | Device out of range | Move devices closer |
| Data not syncing | Wrong service UUID | Verify UUID matches PEAT_SERVICE_UUID |
| Library load error | Missing .so file | Check jniLibs directory structure |

### Debug Logging

Enable native logging:

```kotlin
// In Application.onCreate()
android_logger.init_once(
    android_logger.Config.default()
        .with_max_level(log.LevelFilter.Debug)
        .with_tag("peat-btle"),
)
```

View logs:
```bash
adb logcat -s peat-btle
```

## References

- [Android BLE Guide]https://developer.android.com/guide/topics/connectivity/bluetooth/ble-overview
- [JNI Reference]https://docs.oracle.com/javase/8/docs/technotes/guides/jni/
- [rust-android-gradle]https://github.com/aspect-build/aspect-workflows/tree/main/rust-android