Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

Wake when PC is nearby: the phone finds the PC's Bluetooth beacon

Bee7598ddead494
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/companion/PcCompanion.kt b/android/app/src/main/kotlin/app/nectarlink/android/companion/PcCompanion.kt
index 383ef9b..851accc 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/companion/PcCompanion.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/companion/PcCompanion.kt
@@ -29,28 +29,43 @@ object PcCompanion {
1,
)
+ /** z-base-32, as device IDs are written (`core/nectarlink-protocol/src/id.rs`). */
+ private const val ZBASE32 = "ybndrfg8ejkmcpqxot1uwisza345h769"
+
/**
- * Builds the manufacturer-specific BLE beacon payload:
- * 5-byte `NCTR\x01` magic followed by the first 8 bytes of the decoded
- * hex device ID (13 bytes total), or just the 5-byte magic if [deviceIdHex]
- * does not contain at least 8 valid hex bytes.
+ * The bytes of a z-base-32 string, most significant bit first, or null if it
+ * has a character outside the alphabet. Trailing bits that don't make a whole
+ * byte are dropped, as the encoder pads with them.
*/
- fun buildBeaconPayload(deviceIdHex: String?): ByteArray {
- val clean = deviceIdHex
- ?.filter { it in '0'..'9' || it in 'a'..'f' || it in 'A'..'F' }
- .orEmpty()
- if (clean.length < 16) {
- return BEACON_MAGIC.copyOf()
+ fun decodeZBase32(text: String): ByteArray? {
+ val out = java.io.ByteArrayOutputStream()
+ var buffer = 0
+ var bits = 0
+ for (c in text.trim().lowercase()) {
+ val value = ZBASE32.indexOf(c)
+ if (value < 0) return null
+ buffer = (buffer shl 5) or value
+ bits += 5
+ if (bits >= 8) {
+ bits -= 8
+ out.write((buffer shr bits) and 0xFF)
+ }
}
- val out = ByteArray(BEACON_MAGIC.size + 8)
- BEACON_MAGIC.copyInto(out, 0)
- for (i in 0 until 8) {
- val hi = Character.digit(clean[i * 2], 16)
- val lo = Character.digit(clean[i * 2 + 1], 16)
- if (hi < 0 || lo < 0) return BEACON_MAGIC.copyOf()
- out[BEACON_MAGIC.size + i] = ((hi shl 4) or lo).toByte()
+ return out.toByteArray()
+ }
+
+ /**
+ * Builds the manufacturer-specific BLE beacon payload a PC broadcasts
+ * (`desktop/app/src/win/ble_beacon.rs`): the 5-byte `NCTR\x01` magic followed
+ * by the first 8 bytes of the PC's 32-byte device ID (13 bytes in all), or
+ * just the magic when [deviceId] isn't a valid device ID.
+ */
+ fun buildBeaconPayload(deviceId: String?): ByteArray {
+ val id = deviceId?.let(::decodeZBase32)
+ if (id == null || id.size != 32) {
+ return BEACON_MAGIC.copyOf()
}
- return out
+ return BEACON_MAGIC + id.copyOfRange(0, 8)
}
/**
@@ -98,7 +113,7 @@ object PcCompanion {
fun requestAssociation(
activity: Activity,
pcName: String,
- pcDeviceIdHex: String? = null,
+ pcDeviceId: String? = null,
onResult: (Boolean) -> Unit = {},
onLauncherFallback: (IntentSender) -> Unit,
) {
@@ -107,7 +122,7 @@ object PcCompanion {
onResult(false)
return
}
- val payload = buildBeaconPayload(pcDeviceIdHex)
+ val payload = buildBeaconPayload(pcDeviceId)
val mask = buildBeaconMask(payload.size == 13)
val scanFilter = ScanFilter.Builder()
.setManufacturerData(MANUFACTURER_ID, payload, mask)
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt
index 55907cb..b271cd3 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt
@@ -1180,7 +1180,7 @@ private fun CompanionWakeAccess(
PcCompanion.requestAssociation(
activity = activity,
pcName = primaryPc?.name ?: "PC",
- pcDeviceIdHex = primaryPc?.id,
+ pcDeviceId = primaryPc?.id,
onResult = { onAccessChanged() },
onLauncherFallback = { sender ->
runCatching {
diff --git a/android/app/src/test/kotlin/app/nectarlink/android/CompanionAndMigrationTest.kt b/android/app/src/test/kotlin/app/nectarlink/android/CompanionAndMigrationTest.kt
index 3f9c33c..ed1a867 100644
--- a/android/app/src/test/kotlin/app/nectarlink/android/CompanionAndMigrationTest.kt
+++ b/android/app/src/test/kotlin/app/nectarlink/android/CompanionAndMigrationTest.kt
@@ -14,37 +14,41 @@ import org.junit.Test
class CompanionAndMigrationTest {
@Test
- fun `PcCompanion buildBeaconPayload and buildBeaconMask encode 5-byte magic and 8-byte device ID prefix`() {
- val hexId = "0123456789abcdef-fedcba9876543210"
- val payload = PcCompanion.buildBeaconPayload(hexId)
- assertEquals(13, payload.size)
+ fun `z-base-32 decodes like the core encodes device IDs`() {
+ // The z-base-32 specification's own example.
assertArrayEquals(
- byteArrayOf(
- 'N'.code.toByte(),
- 'C'.code.toByte(),
- 'T'.code.toByte(),
- 'R'.code.toByte(),
- 1,
- 0x01,
- 0x23,
- 0x45,
- 0x67,
- 0x89.toByte(),
- 0xAB.toByte(),
- 0xCD.toByte(),
- 0xEF.toByte(),
- ),
- payload,
+ byteArrayOf(0xF0.toByte(), 0xBF.toByte(), 0xC7.toByte()),
+ PcCompanion.decodeZBase32("6n9hq"),
)
+ // The device ID whose 32 bytes are 0, 1, 2 ... 31, as the core writes it
+ // (pinned on the Rust side in core/nectarlink-protocol/src/id.rs).
+ assertArrayEquals(
+ ByteArray(32) { it.toByte() },
+ PcCompanion.decodeZBase32("yyyoryarywdyqnyjbefoadeqbhebnrounoktcfaadrpbs8y7daxo"),
+ )
+ assertEquals(null, PcCompanion.decodeZBase32("not-an-id"))
+ }
+
+ @Test
+ fun `the scan filter matches the beacon a PC broadcasts for its device ID`() {
+ // What desktop/app/src/win/ble_beacon.rs broadcasts: the magic, then the
+ // ID's first 8 bytes, here A5 3C 00 FF 12 34 56 78, which no hex reading of
+ // the ID could produce.
+ val id = "ww6yb9a1gtm8tgw4ukpjigw4ukpjigw4ukpjigw4ukpjigw4ukpy"
+ val broadcast = PcCompanion.BEACON_MAGIC + byteArrayOf(
+ 0xA5.toByte(), 0x3C, 0x00, 0xFF.toByte(), 0x12, 0x34, 0x56, 0x78,
+ )
+ assertArrayEquals(broadcast, PcCompanion.buildBeaconPayload(id))
+ assertArrayEquals(broadcast, PcCompanion.buildBeaconPayload(id.uppercase()))
val maskWithId = PcCompanion.buildBeaconMask(hasDeviceId = true)
assertEquals(13, maskWithId.size)
assertTrue(maskWithId.all { it == 0xFF.toByte() })
- val shortPayload = PcCompanion.buildBeaconPayload("abcd")
- assertArrayEquals(PcCompanion.BEACON_MAGIC, shortPayload)
+ // Not a device ID: match any NectarLink PC.
+ assertArrayEquals(PcCompanion.BEACON_MAGIC, PcCompanion.buildBeaconPayload("abcd"))
+ assertArrayEquals(PcCompanion.BEACON_MAGIC, PcCompanion.buildBeaconPayload("0123456789abcdef-fedcba9876543210"))
assertArrayEquals(PcCompanion.BEACON_MAGIC, PcCompanion.buildBeaconPayload(null))
-
val maskWithoutId = PcCompanion.buildBeaconMask(hasDeviceId = false)
assertEquals(5, maskWithoutId.size)
assertTrue(maskWithoutId.all { it == 0xFF.toByte() })
diff --git a/core/nectarlink-protocol/src/id.rs b/core/nectarlink-protocol/src/id.rs
index 9297d08..764de9b 100644
--- a/core/nectarlink-protocol/src/id.rs
+++ b/core/nectarlink-protocol/src/id.rs
@@ -92,6 +92,11 @@ mod tests {
fn zbase32_matches_reference_vector() {
// From the z-base-32 specification: 0xF0 0xBF 0xC7 -> "6n9hq".
assert_eq!(ZBASE32.encode(&[0xF0, 0xBF, 0xC7]), "6n9hq");
+ // The Android app decodes IDs itself for its Bluetooth scan filter;
+ // its test uses this same ID (CompanionAndMigrationTest.kt).
+ let mut bytes = [0u8; 32];
+ bytes.iter_mut().enumerate().for_each(|(i, b)| *b = i as u8);
+ assert_eq!(DeviceId(bytes).to_string(), "yyyoryarywdyqnyjbefoadeqbhebnrounoktcfaadrpbs8y7daxo");
}
#[test]
diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rs
index 5e32713..793c0f1 100644
--- a/desktop/app/src/main.rs
+++ b/desktop/app/src/main.rs
@@ -567,9 +567,13 @@ fn main() -> ExitCode {
tracing::error!(error = %e, "can't start the core runtime");
return ExitCode::FAILURE;
}
- if let Some(node) = core_host::node() {
- win::ble_beacon::start(node.device_id());
- }
+ // The node starts in the background, so wait for it: the beacon carries
+ // its device ID.
+ core_host::spawn(async {
+ if let Some(node) = core_host::wait_for_node().await {
+ win::ble_beacon::start(node.device_id());
+ }
+ });
core_host::host().hub.update(|s| {
notification_store::load(&data_dir, s);
state::Changes::APPS | state::Changes::HISTORY
diff --git a/desktop/app/src/win/ble_beacon.rs b/desktop/app/src/win/ble_beacon.rs
index 4fafcc1..5da5b37 100644
--- a/desktop/app/src/win/ble_beacon.rs
+++ b/desktop/app/src/win/ble_beacon.rs
@@ -14,7 +14,8 @@ use std::{
use nectarlink_core::DeviceId;
use windows::{
Devices::Bluetooth::Advertisement::{
- BluetoothLEAdvertisementPublisher, BluetoothLEAdvertisementReceivedEventArgs,
+ BluetoothLEAdvertisementPublisher, BluetoothLEAdvertisementPublisherStatus,
+ BluetoothLEAdvertisementPublisherStatusChangedEventArgs, BluetoothLEAdvertisementReceivedEventArgs,
BluetoothLEAdvertisementWatcher, BluetoothLEManufacturerData,
},
Foundation::TypedEventHandler,
@@ -98,14 +99,14 @@ pub fn build_manufacturer_payload(device_id: &DeviceId) -> [u8; 13] {
out
}
-/// Starts advertising the NectarLink BLE proximity beacon for `device_id` and
-/// watching for paired phone BLE proximity frames for RSSI walk-away ranging.
+/// Starts advertising the NectarLink BLE proximity beacon for `device_id`.
+///
+/// The RSSI watcher (`try_start_watcher`) stays off: phones don't broadcast a
+/// beacon yet, so it would scan all the time and only ever hear other PCs.
pub fn start(device_id: DeviceId) {
+ // Phones find this PC by it ("Wake when PC is nearby"), so say when it can't run.
if let Err(e) = try_start(&device_id) {
- tracing::debug!(error = %e, "BLE beacon advertising unavailable on this PC");
- }
- if let Err(e) = try_start_watcher(device_id) {
- tracing::debug!(error = %e, "BLE proximity RSSI watcher unavailable on this PC");
+ tracing::warn!(error = %e, "this PC can't broadcast its Bluetooth beacon");
}
}
@@ -132,6 +133,19 @@ fn try_start(device_id: &DeviceId) -> windows::core::Result<()> {
let mfg_data = BluetoothLEManufacturerData::Create(COMPANY_ID, &buffer)?;
let publisher = BluetoothLEAdvertisementPublisher::new()?;
publisher.Advertisement()?.ManufacturerData()?.Append(&mfg_data)?;
+ // Windows can accept Start and stop a moment later (an adapter that can't
+ // advertise, Bluetooth turned off), so log why it stops.
+ publisher.StatusChanged(&TypedEventHandler::<
+ BluetoothLEAdvertisementPublisher,
+ BluetoothLEAdvertisementPublisherStatusChangedEventArgs,
+ >::new(|_, args| {
+ if let Some(args) = args.as_ref()
+ && args.Status()? == BluetoothLEAdvertisementPublisherStatus::Aborted
+ {
+ tracing::warn!(error = ?args.Error()?, "the Bluetooth beacon stopped");
+ }
+ Ok(())
+ }))?;
publisher.Start()?;
if let Ok(mut guard) = publisher_slot().lock()
@@ -139,7 +153,7 @@ fn try_start(device_id: &DeviceId) -> windows::core::Result<()> {
{
let _ = prev.Stop();
}
- tracing::debug!("started PC BLE proximity beacon");
+ tracing::info!("broadcasting the Bluetooth beacon");
Ok(())
}