Fix an issue where iOS couldn't reconnect to a G2 arm because it already had an ANCS connection open to it
This commit is contained in:
1 parent
ab692741f7
commit
d1e424b7e1
6 files changed
+164
-6
No files matched your search
@@ -68,6 +68,23 @@ export function extractG2Mac(mfg: Uint8Array): string | null {
|
||||
return humanReadableAddressFromWireBytes(mfg.subarray(16, 22));
|
||||
}
|
||||
|
||||
/**
|
||||
* G2 manufacturer data (hex) carrying `serial` and `address`, for an arm known
|
||||
* only from a saved pairing: what `extractG2Serial` and `extractG2Mac` read
|
||||
* back, with the serial zero-padded and no flag byte. Null when the serial is
|
||||
* not up to 14 printable ASCII characters or the address is not a MAC.
|
||||
*/
|
||||
export function g2ManufacturerData(serial: string, address: string): string | null {
|
||||
const wire = wireBytesFromHumanReadableAddress(address);
|
||||
if (!wire || !/^[\x20-\x7e]{1,14}$/.test(serial)) return null;
|
||||
const bytes = new Uint8Array(22);
|
||||
bytes[0] = 0x45;
|
||||
bytes[1] = 0x52;
|
||||
for (let i = 0; i < serial.length; i++) bytes[2 + i] = serial.charCodeAt(i);
|
||||
bytes.set(wire, 16);
|
||||
return bytesToHex(bytes);
|
||||
}
|
||||
|
||||
/** Preserve the final G2 manufacturer-data byte without guessing its meaning. */
|
||||
export function extractG2AdvertisementFlag(mfg: Uint8Array): number | null {
|
||||
if (mfg.length < 23 || !hasEvenManufacturerSignature(mfg)) return null;
|
||||
|
||||
@@ -3,11 +3,18 @@ import type { DiscoveryEvents } from './device-discovery'
|
||||
import type { RawAdvertisement } from '../g2/even-advertisement'
|
||||
export { buildAddressSet } from './device-discovery-common'
|
||||
|
||||
/**
|
||||
* How often a scan re-reads which arms the system is connected to. Each read refreshes
|
||||
* their rows, which age out like advertisements once the link drops and they go quiet.
|
||||
*/
|
||||
const CONNECTED_ARMS_POLL_MS = 2000
|
||||
|
||||
export class DeviceDiscoveryBridge {
|
||||
private ble = iosBluetooth()
|
||||
private off: (() => void) | null = null
|
||||
private generation = 0
|
||||
private cancelCollection: (() => void) | null = null
|
||||
private connectedArmsTimer: ReturnType<typeof setInterval> | null = null
|
||||
get bluetoothEnabled(): boolean { return this.ble.state === 5 }
|
||||
get scanning(): boolean { return !!this.off && this.ble.scanning }
|
||||
startScan(events: DiscoveryEvents): boolean {
|
||||
@@ -21,16 +28,27 @@ export class DeviceDiscoveryBridge {
|
||||
void this.ble.startScan(24 * 60 * 60 * 1000).catch(error => {
|
||||
if (generation === this.generation) events.onScanFailed?.(-1, String(error.message ?? error))
|
||||
})
|
||||
// A connected arm doesn't advertise (iOS holds the right arm's ANCS link open after a
|
||||
// session ends), so the scan alone would show those glasses one-armed.
|
||||
const reportConnectedArms = () => { for (const device of this.ble.systemConnectedDevices()) events.onAdvertisement(device) }
|
||||
reportConnectedArms()
|
||||
this.connectedArmsTimer = setInterval(reportConnectedArms, CONNECTED_ARMS_POLL_MS)
|
||||
return true
|
||||
}
|
||||
stopScan(): void {
|
||||
++this.generation; this.cancelCollection?.()
|
||||
if (this.connectedArmsTimer) { clearInterval(this.connectedArmsTimer); this.connectedArmsTimer = null }
|
||||
if (this.off) { this.off(); this.off = null; this.ble.stopScan() }
|
||||
}
|
||||
// CoreBluetooth does not expose the phone's bond list. Fresh advertisements
|
||||
// supply both identity and the UUID mapping that iOS needs for connections.
|
||||
// supply both identity and the UUID mapping that iOS needs for connections;
|
||||
// startScan() reports the arms the system is connected to.
|
||||
emitBondedDevices(): void {}
|
||||
async getBondedCandidates(): Promise<RawAdvertisement[]> { return [...this.ble.devices.values()] }
|
||||
async getBondedCandidates(): Promise<RawAdvertisement[]> {
|
||||
const devices = new Map(this.ble.devices)
|
||||
for (const device of this.ble.systemConnectedDevices()) if (!devices.has(device.address)) devices.set(device.address, device)
|
||||
return [...devices.values()]
|
||||
}
|
||||
async scanCandidates(timeoutMs = 6000): Promise<RawAdvertisement[]> {
|
||||
const generation = this.generation
|
||||
await this.ble.ensureReady()
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { ApplicationSettings } from '@nativescript/core'
|
||||
import { loadPairedGlassesIdentity } from '../g2/device-addresses'
|
||||
import { g2ManufacturerData } from '../g2/even-advertisement'
|
||||
import { serialKey } from '../g2/glasses-hardware-identity'
|
||||
import { identifyIosPeripheral, type IosAdvertisement, type IosDevice } from '../g2/ios-peripheral-identity'
|
||||
import { hexToBytes } from '../util/hex-util'
|
||||
import { kotlinListener } from './kotlin-listener.ios'
|
||||
@@ -10,6 +13,13 @@ export const BLE_STATE_UNSUPPORTED = 2, BLE_STATE_UNAUTHORIZED = 3, BLE_STATE_PO
|
||||
/** CBManagerAuthorization.allowedAlways. */
|
||||
const BLE_AUTHORIZATION_ALLOWED = 3
|
||||
|
||||
/**
|
||||
* Per address, the peripheral identifier and side last heard there and (since 2026-11-16)
|
||||
* the advertisement itself, from which an arm that has stopped advertising is rebuilt.
|
||||
*/
|
||||
const PERIPHERAL_KEY_PREFIX = 'ios.ble.peripheral.'
|
||||
type RememberedPeripheral = { identifier: string; role: string; name?: string; manufacturerData?: string }
|
||||
|
||||
export type BluetoothEvent =
|
||||
| { kind: 'state'; state: number; authorization: number }
|
||||
| { kind: 'advertisement'; identifier: string; name: string; manufacturerData: string; rssi: number; connectable: boolean }
|
||||
@@ -28,6 +38,8 @@ export class IosBluetooth {
|
||||
private readonly native = FaceclawKitIosBleCentral.alloc().initWithPlatform(FaceclawKitIosProtocolPlatform.shared)
|
||||
private readonly listeners = new Set<(event: BluetoothEvent) => void>()
|
||||
readonly devices = new Map<string, IosDevice>()
|
||||
/** The record last written per settings key, so repeated advertisements don't rewrite it. */
|
||||
private readonly rememberedValues = new Map<string, string>()
|
||||
private scanTimer: ReturnType<typeof setTimeout> | null = null
|
||||
private scanGeneration = 0
|
||||
private readonly scanListener: object
|
||||
@@ -47,12 +59,68 @@ export class IosBluetooth {
|
||||
const device = identifyIosPeripheral(raw)
|
||||
if (device) {
|
||||
this.devices.set(device.address, device)
|
||||
ApplicationSettings.setString(`ios.ble.peripheral.${device.address}`, JSON.stringify({ identifier: device.identifier, role: device.role }))
|
||||
this.remember(device)
|
||||
this.emit({ kind: 'device', device })
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
/** Persists what `device` advertised; skips the write when nothing changed (scans report duplicates). */
|
||||
private remember(device: IosDevice): void {
|
||||
const key = `${PERIPHERAL_KEY_PREFIX}${device.address}`
|
||||
const record: RememberedPeripheral = { identifier: device.identifier, role: device.role, name: device.name, manufacturerData: device.manufacturerData }
|
||||
const value = JSON.stringify(record)
|
||||
if (this.rememberedValues.get(key) === value) return
|
||||
this.rememberedValues.set(key, value)
|
||||
ApplicationSettings.setString(key, value)
|
||||
}
|
||||
/**
|
||||
* Even arms the system is connected to, rebuilt from what they last advertised here. A
|
||||
* connected arm doesn't advertise, and iOS keeps the right arm's ANCS link open after a
|
||||
* session ends (even after pairing other glasses), so a scan alone hears only the left
|
||||
* arm. An arm this phone has never heard advertise can't be rebuilt: its MAC and the
|
||||
* pair's serial come only from the advertisement. The device has no signal strength.
|
||||
*/
|
||||
systemConnectedDevices(): IosDevice[] {
|
||||
if (this.state !== BLE_STATE_POWERED_ON) return []
|
||||
let connected: any
|
||||
try {
|
||||
connected = this.native.systemConnectedG2Arms()
|
||||
} catch (error) {
|
||||
// Scanning still works without this; don't let it take the pairing page down.
|
||||
console.log(`[IosBluetooth] systemConnectedG2Arms failed: ${error}`)
|
||||
return []
|
||||
}
|
||||
if (!connected?.count) return []
|
||||
const records = new Map<string, { address: string; record: RememberedPeripheral }>()
|
||||
for (const key of ApplicationSettings.getAllKeys()) {
|
||||
if (!key.startsWith(PERIPHERAL_KEY_PREFIX)) continue
|
||||
try {
|
||||
const record = JSON.parse(ApplicationSettings.getString(key, '{}')) as RememberedPeripheral
|
||||
if (typeof record.identifier === 'string') records.set(record.identifier.toUpperCase(), { address: key.slice(PERIPHERAL_KEY_PREFIX.length), record })
|
||||
} catch { /* Malformed: a fresh advertisement rewrites it. */ }
|
||||
}
|
||||
const identity = loadPairedGlassesIdentity()
|
||||
const devices: IosDevice[] = []
|
||||
for (let i = 0; i < connected.count; i++) {
|
||||
const peripheral = connected.objectAtIndex(i)
|
||||
const identifier = String(peripheral.identifier)
|
||||
const remembered = records.get(identifier)
|
||||
if (!remembered) continue
|
||||
const { address, record } = remembered
|
||||
let name = record.name ?? ''
|
||||
let manufacturerData = record.manufacturerData ?? ''
|
||||
if (!manufacturerData && identity && (address === identity.leftAddress || address === identity.rightAddress)) {
|
||||
// Remembered before advertisements were: the saved pairing supplies the serial.
|
||||
const side = address === identity.leftAddress ? 'left' : 'right'
|
||||
name ||= side === 'left' ? identity.leftName : identity.rightName
|
||||
manufacturerData = g2ManufacturerData(serialKey(identity.serial) ?? '', address) ?? ''
|
||||
}
|
||||
const device = identifyIosPeripheral({ identifier, name: name || String(peripheral.name ?? ''), manufacturerData, rssi: 0, connectable: true })
|
||||
if (device?.address === address && device.role === record.role) devices.push({ ...device, rssi: null, source: 'paired' })
|
||||
}
|
||||
return devices
|
||||
}
|
||||
onEvent(listener: (event: BluetoothEvent) => void): () => void {
|
||||
this.listeners.add(listener); return () => { this.listeners.delete(listener) }
|
||||
}
|
||||
@@ -111,7 +179,7 @@ export class IosBluetooth {
|
||||
const live = this.devices.get(address)
|
||||
if (live && live.role !== role) throw new Error(`${address} advertises as ${live.role}, not ${role}. Check Configure devices.`)
|
||||
try {
|
||||
const saved = JSON.parse(ApplicationSettings.getString(`ios.ble.peripheral.${address}`, '{}'))
|
||||
const saved = JSON.parse(ApplicationSettings.getString(`${PERIPHERAL_KEY_PREFIX}${address}`, '{}'))
|
||||
if (saved.role === role && typeof saved.identifier === 'string') result[role] = saved.identifier
|
||||
} catch { /* A fresh scan can recover malformed settings. */ }
|
||||
}
|
||||
@@ -138,13 +206,15 @@ export class IosBluetooth {
|
||||
/** The peripheral last heard at this address, if it was on this side. */
|
||||
peripheralIdentifier(address: string, role: string): string | null {
|
||||
try {
|
||||
const saved = JSON.parse(ApplicationSettings.getString(`ios.ble.peripheral.${address}`, '{}'))
|
||||
const saved = JSON.parse(ApplicationSettings.getString(`${PERIPHERAL_KEY_PREFIX}${address}`, '{}'))
|
||||
return saved.role === role && typeof saved.identifier === 'string' ? saved.identifier : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
forget(address: string): void { ApplicationSettings.remove(`ios.ble.peripheral.${address}`); this.devices.delete(address) }
|
||||
forget(address: string): void {
|
||||
ApplicationSettings.remove(`${PERIPHERAL_KEY_PREFIX}${address}`); this.rememberedValues.delete(`${PERIPHERAL_KEY_PREFIX}${address}`); this.devices.delete(address)
|
||||
}
|
||||
}
|
||||
let instance: IosBluetooth | null = null
|
||||
export function iosBluetooth(): IosBluetooth { return instance ??= new IosBluetooth() }
|
||||
|
||||
@@ -12,6 +12,12 @@ import kotlin.jvm.JvmStatic
|
||||
*/
|
||||
class BleProtocol {
|
||||
companion object {
|
||||
/** The service holding [WRITE_CHAR_UUID] and [NOTIFY_CHAR_UUID]. */
|
||||
const val PROTOCOL_SERVICE_UUID: String = "00002760-08c2-11e1-9073-0e8ac72e5450"
|
||||
|
||||
/** The service holding [RENDER_NOTIFY_UUID]. */
|
||||
const val RENDER_SERVICE_UUID: String = "00002760-08c2-11e1-9073-0e8ac72e6450"
|
||||
|
||||
const val WRITE_CHAR_UUID: String = "00002760-08c2-11e1-9073-0e8ac72e5401"
|
||||
|
||||
const val NOTIFY_CHAR_UUID: String = "00002760-08c2-11e1-9073-0e8ac72e5402"
|
||||
|
||||
@@ -29,6 +29,7 @@ import platform.CoreBluetooth.CBPeripheralDelegateProtocol
|
||||
import platform.CoreBluetooth.CBPeripheralStateConnected
|
||||
import platform.CoreBluetooth.CBPeripheralStateDisconnected
|
||||
import platform.CoreBluetooth.CBService
|
||||
import platform.CoreBluetooth.CBUUID
|
||||
import platform.Foundation.NSData
|
||||
import platform.Foundation.NSError
|
||||
import platform.Foundation.NSNumber
|
||||
@@ -47,6 +48,9 @@ interface IosBleScanListener {
|
||||
fun onAdvertisement(identifier: String, name: String, manufacturerDataHex: String, rssi: Int, connectable: Boolean)
|
||||
}
|
||||
|
||||
/** A peripheral the system holds a connection to; see [IosBleCentral.systemConnectedG2Arms]. */
|
||||
class IosConnectedPeripheral(val identifier: String, val name: String)
|
||||
|
||||
/** ANCS authorization changes for a connected peripheral; delivered on the BLE queue. */
|
||||
fun interface IosAncsAuthorizationListener {
|
||||
fun onAncsAuthorization(identifier: String, authorized: Boolean)
|
||||
@@ -214,6 +218,25 @@ class IosBleCentral(private val platform: ProtocolPlatform = IosProtocolPlatform
|
||||
manager.scanForPeripheralsWithServices(null, mapOf(CBCentralManagerScanOptionAllowDuplicatesKey to true))
|
||||
}
|
||||
|
||||
/**
|
||||
* G2 arms the system is connected to, through this app, another app or iOS itself. A
|
||||
* connected arm stops advertising, and iOS keeps the right arm's ANCS link open after a
|
||||
* session ends, so a scan alone never hears it. Empty until Bluetooth is powered on.
|
||||
*/
|
||||
fun systemConnectedG2Arms(): List<IosConnectedPeripheral> {
|
||||
val found = ArrayList<IosConnectedPeripheral>()
|
||||
dispatch_sync(queue) {
|
||||
val manager = central ?: return@dispatch_sync
|
||||
if (manager.state != CBManagerStatePoweredOn) return@dispatch_sync
|
||||
val services = listOf(BleProtocol.PROTOCOL_SERVICE_UUID, BleProtocol.RENDER_SERVICE_UUID).map { CBUUID.UUIDWithString(it) }
|
||||
for (item in manager.retrieveConnectedPeripheralsWithServices(services)) {
|
||||
val peripheral = item as? CBPeripheral ?: continue
|
||||
found.add(IosConnectedPeripheral(peripheral.identifier.UUIDString.uppercase(), peripheral.name ?: ""))
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
/** Known peripheral identifiers from this process's scans/retrievals (uppercase). */
|
||||
fun knownIdentifiers(): List<String> = cond.withLock { peers.keys.toList() }
|
||||
|
||||
|
||||
@@ -275,3 +275,27 @@ test("names that only look like a G1 are not admitted", () => {
|
||||
assert.equal(classifyAdvertisement(g1Raw(name, "")), null, name);
|
||||
}
|
||||
});
|
||||
|
||||
test("an iOS arm rebuilt from a saved pairing joins its advertising other arm", () => {
|
||||
const { g2ManufacturerData } = require("../.test-build/app/g2/even-advertisement.js");
|
||||
const { identifyIosPeripheral } = require("../.test-build/app/g2/ios-peripheral-identity.js");
|
||||
const { DiscoveryAggregator } = require("../.test-build/app/g2/pairing-candidates.js");
|
||||
const mfg = g2ManufacturerData("S211GBBC180304", "E0:12:14:B6:EC:E1");
|
||||
assert.equal(extractG2Serial(hexToBytes(mfg)), "S211GBBC180304");
|
||||
assert.equal(extractG2Mac(hexToBytes(mfg)), "E0:12:14:B6:EC:E1");
|
||||
const right = identifyIosPeripheral({ identifier: "14b99254-0798-d1a8-3eec-b141bdabfae8", name: "Even G2_32_R_B6ECE1",
|
||||
manufacturerData: mfg, rssi: 0, connectable: true });
|
||||
assert.equal(right.address, "E0:12:14:B6:EC:E1");
|
||||
assert.equal(right.role, "right");
|
||||
assert.equal(right.note, null);
|
||||
const aggregator = new DiscoveryAggregator();
|
||||
aggregator.ingest(raw({}));
|
||||
aggregator.ingest({ ...right, rssi: null, source: "paired" });
|
||||
const [pair] = aggregator.pairs();
|
||||
assert.equal(pair.completeness, "complete");
|
||||
assert.equal(pair.rssi, -55);
|
||||
|
||||
assert.equal(g2ManufacturerData("S211GBBC180304XX", "E0:12:14:B6:EC:E1"), null);
|
||||
assert.equal(g2ManufacturerData("", "E0:12:14:B6:EC:E1"), null);
|
||||
assert.equal(g2ManufacturerData("S211GBBC180304", "not a mac"), null);
|
||||
});
|
||||
Reference in new issue
Block a user