forked from Blendman974/faceclaw
Refactor Kotlin for iOS commonality
This commit is contained in:
1 parent
587364e5e6
commit
c3a0ba9f56
31 files changed
+2780
-964
No files matched your search
+2
-2
@@ -19,7 +19,7 @@ object FirmwareImage {
|
||||
const val TOC_ENTRY_SIZE = 16
|
||||
const val SUBHEADER_SIZE = 128
|
||||
const val NAME_OFFSET = 48
|
||||
const val NAME_MAX = 80
|
||||
const val NAME_LENGTH = 80
|
||||
|
||||
// Firmware 2.2.4 has 5 components; 2.2.6 has 6.
|
||||
const val MIN_SEGMENTS = 5
|
||||
@@ -107,7 +107,7 @@ object FirmwareImage {
|
||||
if (psLong <= 0 || off + SUBHEADER_SIZE + psLong > img.size) {
|
||||
throw IllegalStateException("segment $i payload is truncated")
|
||||
}
|
||||
val name = readCString(img, off + NAME_OFFSET, NAME_MAX)
|
||||
val name = readCString(img, off + NAME_OFFSET, NAME_LENGTH)
|
||||
val seg = Segment(off, psLong.toInt(), crc, name)
|
||||
for (other in segs) {
|
||||
if (seg.off < other.end && other.off < seg.end) {
|
||||
|
||||
+46
@@ -32,6 +32,10 @@ class GlassesSessionCore(
|
||||
companion object {
|
||||
const val TAG = "FaceclawComm"
|
||||
|
||||
/** Relay-frame signature ('A','N') checked by [rawFrameTap]. */
|
||||
internal const val RELAY_TAG_A: Byte = 0x41
|
||||
internal const val RELAY_TAG_N: Byte = 0x4e
|
||||
|
||||
// Local metadata for custom-command bookkeeping, not an EvenHub container.
|
||||
// Submitted frames supply pixel geometry; the stock layout only captures input.
|
||||
internal val DASHBOARD_TILE: BleProtocol.ImageTileOptions =
|
||||
@@ -102,6 +106,14 @@ class GlassesSessionCore(
|
||||
internal val ringAddress: String = ringAddress?.trim() ?: ""
|
||||
|
||||
@Volatile internal var listener: FaceclawBleCommunicatorListener? = null
|
||||
|
||||
/**
|
||||
* Optional tap for relay frames the session does not interpret: notifications on the
|
||||
* right arm's data characteristic whose first two bytes are 'A','N' (the iOS ANCS
|
||||
* notification relay, consumed by the phone-side ANCS client). Unset (Android) they
|
||||
* fall through to the normal frame parser exactly as before. Called on the BLE thread.
|
||||
*/
|
||||
@Volatile internal var rawFrameTap: ((ByteArray) -> Unit)? = null
|
||||
internal val imuListeners = CopyOnWriteList<FaceclawImuListener>(platform)
|
||||
/** A compass subscriber plus the dispatcher it registered from (see addCompassListener). */
|
||||
internal class CompassSubscription(
|
||||
@@ -309,6 +321,33 @@ class GlassesSessionCore(
|
||||
// ---------------------------------------------------------------------
|
||||
// Lifecycle
|
||||
|
||||
/** See [rawFrameTap]; null restores the default (frames parsed by the session). */
|
||||
fun setRawFrameTap(tap: ((ByteArray) -> Unit)?) {
|
||||
rawFrameTap = tap
|
||||
}
|
||||
|
||||
/**
|
||||
* Write one already-framed packet to an arm outside the message scheduler (the ANCS
|
||||
* relay client builds its own packets). Blocks like any link write; false when the
|
||||
* arm is unknown, the link rejects the write, or the session is not running.
|
||||
*/
|
||||
fun writeRawPacket(arm: String, packet: ByteArray): Boolean {
|
||||
val address = when (arm.uppercase()) {
|
||||
"R", "RIGHT" -> rightAddress
|
||||
"L", "LEFT" -> leftAddress
|
||||
else -> return false
|
||||
}
|
||||
val active = monitor.withLock { running }
|
||||
if (!active) return false
|
||||
return try {
|
||||
link.writeFrames(address, BleProtocol.WRITE_CHAR_UUID, listOf(packet), ConnectionOptions.WRITE_MODE,
|
||||
ConnectionOptions.WRITE_TIMEOUT_MS)
|
||||
} catch (t: Throwable) {
|
||||
logLine("raw packet write failed: " + safeMessage(t))
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fun setListener(listener: FaceclawBleCommunicatorListener?) {
|
||||
this.listener = listener
|
||||
emitState()
|
||||
@@ -1308,6 +1347,13 @@ class GlassesSessionCore(
|
||||
interruptibleSleep.interrupt()
|
||||
return
|
||||
}
|
||||
val tap = rawFrameTap
|
||||
if (tap != null && data.size >= 2 && data[0] == RELAY_TAG_A && data[1] == RELAY_TAG_N
|
||||
&& address.equals(rightAddress, ignoreCase = true)) {
|
||||
monitor.withLock { lastIncomingAtMs = now() }
|
||||
tap(data.copyOf())
|
||||
return
|
||||
}
|
||||
logDebug("onNotification: address=" + address + " characteristicUuid=" + characteristicUuid + " data.length=" + data.size)
|
||||
val frame = BleProtocol.parseFrame(data)
|
||||
val decodedWearState = BleProtocol.parseWearState(frame)
|
||||
|
||||
+9
-4
@@ -132,7 +132,8 @@ class RemoteInputSession(
|
||||
fun randomSecret(): String = BinaryEncoding.bytesToHex(random.nextBytes(32))
|
||||
|
||||
private fun notifyRequestReady(id: Long) {
|
||||
// Called with the condition held; dispatching keeps JS off the socket thread and outside the lock.
|
||||
// Called WITHOUT the condition held (ProtocolCondition is not reentrant on iOS, and a
|
||||
// dispatcher may run the closure inline); the closure re-checks the request under the lock.
|
||||
dispatch {
|
||||
val callback = condition.withLock {
|
||||
if (requestId != id || pending == null || wallClock() >= deadline) null else requestListener
|
||||
@@ -150,14 +151,18 @@ class RemoteInputSession(
|
||||
client = connection
|
||||
}
|
||||
val text = readFrame(connection) ?: continue
|
||||
val response: String = condition.withLock {
|
||||
val id = condition.withLock {
|
||||
if (server !== listener) return
|
||||
requestId = ++nextId
|
||||
deadline = wallClock() + requestTimeoutMs
|
||||
reply = null
|
||||
pending = Json.write(linkedMapOf("id" to requestId, "expiresAt" to deadline, "body" to text))
|
||||
notifyRequestReady(requestId)
|
||||
while (reply == null && server === listener && wallClock() < deadline) {
|
||||
requestId
|
||||
}
|
||||
notifyRequestReady(id)
|
||||
val response: String = condition.withLock {
|
||||
if (server !== listener) return
|
||||
while (reply == null && requestId == id && server === listener && wallClock() < deadline) {
|
||||
condition.awaitMs(maxOf(1L, deadline - wallClock()))
|
||||
}
|
||||
val result = reply ?: TIMEOUT_RESPONSE
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
import platform.Foundation.NSDocumentDirectory
|
||||
import platform.Foundation.NSSearchPathForDirectoriesInDomains
|
||||
import platform.Foundation.NSUserDomainMask
|
||||
|
||||
/**
|
||||
* iOS facade over the shared [FrameTimingsCore] with the Android FrameTimings method set.
|
||||
* [startExport] enables the export thread that sweeps timed-out frames every 5 s and writes
|
||||
* <Documents>/frame-timings.txt every 15 s while dirty (the app's Documents folder is
|
||||
* visible in Finder/Files when UIFileSharingEnabled is on).
|
||||
*/
|
||||
class IosFrameTimings internal constructor(platform: ProtocolPlatform) {
|
||||
constructor() : this(IosProtocolPlatform)
|
||||
|
||||
val core = FrameTimingsCore(platform)
|
||||
private val lock = platform.createLock()
|
||||
private var exportDir: String? = null
|
||||
private var exporting = false
|
||||
|
||||
/** Idempotent; enables filesystem export into [directory] (default: Documents). */
|
||||
fun startExport(directory: String?) {
|
||||
lock.withLock {
|
||||
exportDir = directory ?: documentsDirectory()
|
||||
if (exporting) return
|
||||
exporting = true
|
||||
}
|
||||
startThread("FrameTimingsExport", true) { exportLoop() }
|
||||
}
|
||||
|
||||
fun startFrame(reason: String?): Int = core.startFrame(reason)
|
||||
|
||||
fun startFrame(reason: String?, parentFrameId: Int): Int = core.startFrame(reason, parentFrameId)
|
||||
|
||||
fun annotate(frameId: Int, text: String?) = core.annotate(frameId, text)
|
||||
|
||||
fun log(frameId: Int, message: String?) = core.log(frameId, message)
|
||||
|
||||
fun spanStart(frameId: Int, name: String) = core.spanStart(frameId, name)
|
||||
|
||||
fun spanEnd(frameId: Int, name: String) = core.spanEnd(frameId, name)
|
||||
|
||||
fun finishFrame(frameId: Int, outcome: String?) = core.finishFrame(frameId, outcome)
|
||||
|
||||
fun statsSummary(): String = core.statsSummary()
|
||||
|
||||
/** Writes the export now (if anything changed); returns the file path or null. */
|
||||
fun exportNow(): String? {
|
||||
val dir = lock.withLock { exportDir } ?: return null
|
||||
val content = core.takeExport() ?: return null
|
||||
val target = "$dir/$EXPORT_FILE_NAME"
|
||||
val temp = "$target.tmp"
|
||||
return try {
|
||||
writeFileData(temp, content.encodeToByteArray())
|
||||
if (renameFile(temp, target)) target else {
|
||||
PlatformLog.w(TAG, "failed to rename $temp to $target")
|
||||
null
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
PlatformLog.w(TAG, "failed to export frame timings: ${t.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun exportLoop() {
|
||||
var lastExportAtMs = 0L
|
||||
while (true) {
|
||||
sleepMs(FrameTimingsCore.SWEEP_INTERVAL_MS)
|
||||
try {
|
||||
core.sweepTimedOut()
|
||||
val now = IosProtocolPlatform.elapsedRealtimeMs()
|
||||
if (core.isExportDirty && now - lastExportAtMs >= FrameTimingsCore.EXPORT_INTERVAL_MS) {
|
||||
lastExportAtMs = now
|
||||
exportNow()
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
PlatformLog.w(TAG, "export loop error: ${t.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = FrameTimingsCore.TAG
|
||||
const val EXPORT_FILE_NAME = "frame-timings.txt"
|
||||
val shared: IosFrameTimings by lazy { IosFrameTimings() }
|
||||
|
||||
fun documentsDirectory(): String =
|
||||
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true).firstOrNull() as? String ?: "."
|
||||
}
|
||||
}
|
||||
@@ -63,12 +63,16 @@ actual fun formatLocalTime(epochMs: Long, pattern: String): String {
|
||||
}
|
||||
|
||||
actual object PlatformLog {
|
||||
actual fun i(tag: String, message: String) = NSLog("%@", "$tag: $message")
|
||||
// NSLog's vararg bridge cannot take a Kotlin String (it segfaults), so the message becomes
|
||||
// the format string itself with '%' escaped.
|
||||
private fun emit(text: String) = NSLog(text.replace("%", "%%"))
|
||||
|
||||
actual fun w(tag: String, message: String) = NSLog("%@", "$tag: [warn] $message")
|
||||
actual fun i(tag: String, message: String) = emit("$tag: $message")
|
||||
|
||||
actual fun w(tag: String, message: String) = emit("$tag: [warn] $message")
|
||||
|
||||
actual fun e(tag: String, message: String, error: Throwable?) =
|
||||
NSLog("%@", "$tag: [error] $message" + (error?.let { " (${it.message})" } ?: ""))
|
||||
emit("$tag: [error] $message" + (error?.let { " (${it.message})" } ?: ""))
|
||||
}
|
||||
|
||||
actual fun startThread(name: String, daemon: Boolean, body: () -> Unit) {
|
||||
|
||||
@@ -0,0 +1,718 @@
|
||||
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class, kotlinx.cinterop.BetaInteropApi::class)
|
||||
|
||||
package com.faceclaw.app
|
||||
|
||||
import kotlin.concurrent.Volatile
|
||||
import kotlinx.cinterop.ObjCSignatureOverride
|
||||
import platform.CoreBluetooth.CBAdvertisementDataIsConnectable
|
||||
import platform.CoreBluetooth.CBAdvertisementDataLocalNameKey
|
||||
import platform.CoreBluetooth.CBAdvertisementDataManufacturerDataKey
|
||||
import platform.CoreBluetooth.CBCentralManager
|
||||
import platform.CoreBluetooth.CBCentralManagerDelegateProtocol
|
||||
import platform.CoreBluetooth.CBCentralManagerScanOptionAllowDuplicatesKey
|
||||
import platform.CoreBluetooth.CBCharacteristic
|
||||
import platform.CoreBluetooth.CBCharacteristicPropertyIndicate
|
||||
import platform.CoreBluetooth.CBCharacteristicPropertyNotify
|
||||
import platform.CoreBluetooth.CBCharacteristicPropertyWrite
|
||||
import platform.CoreBluetooth.CBCharacteristicPropertyWriteWithoutResponse
|
||||
import platform.CoreBluetooth.CBCharacteristicWriteType
|
||||
import platform.CoreBluetooth.CBCharacteristicWriteWithResponse
|
||||
import platform.CoreBluetooth.CBCharacteristicWriteWithoutResponse
|
||||
import platform.CoreBluetooth.CBConnectPeripheralOptionRequiresANCS
|
||||
import platform.CoreBluetooth.CBManager
|
||||
import platform.CoreBluetooth.CBManagerStatePoweredOff
|
||||
import platform.CoreBluetooth.CBManagerStatePoweredOn
|
||||
import platform.CoreBluetooth.CBManagerStateUnauthorized
|
||||
import platform.CoreBluetooth.CBManagerStateUnsupported
|
||||
import platform.CoreBluetooth.CBPeripheral
|
||||
import platform.CoreBluetooth.CBPeripheralDelegateProtocol
|
||||
import platform.CoreBluetooth.CBPeripheralStateConnected
|
||||
import platform.CoreBluetooth.CBPeripheralStateDisconnected
|
||||
import platform.CoreBluetooth.CBService
|
||||
import platform.Foundation.NSData
|
||||
import platform.Foundation.NSError
|
||||
import platform.Foundation.NSNumber
|
||||
import platform.Foundation.NSUUID
|
||||
import platform.darwin.NSObject
|
||||
import platform.darwin.dispatch_async
|
||||
import platform.darwin.dispatch_get_main_queue
|
||||
import platform.darwin.dispatch_queue_create
|
||||
import platform.darwin.dispatch_sync
|
||||
|
||||
/** Scan/state events for the phone-side device picker; delivered on the main queue. */
|
||||
interface IosBleScanListener {
|
||||
/** CBManagerState raw value and CBManagerAuthorization raw value. */
|
||||
fun onBluetoothState(state: Int, authorization: Int)
|
||||
|
||||
fun onAdvertisement(identifier: String, name: String, manufacturerDataHex: String, rssi: Int, connectable: Boolean)
|
||||
}
|
||||
|
||||
/** ANCS authorization changes for a connected peripheral; delivered on the BLE queue. */
|
||||
fun interface IosAncsAuthorizationListener {
|
||||
fun onAncsAuthorization(identifier: String, authorized: Boolean)
|
||||
}
|
||||
|
||||
/**
|
||||
* CoreBluetooth central used by the shared session and stock-firmware flows on iOS. It is
|
||||
* the iOS counterpart of Android's FaceclawBleManager: every [SessionLink]/[StockLink] call
|
||||
* blocks the calling (worker) thread until the delegate reports completion or the timeout
|
||||
* elapses. CoreBluetooth runs on a private serial queue; the calling thread hands it work
|
||||
* with dispatch_sync and waits on a condition the delegate signals. Addresses are peripheral
|
||||
* identifier UUID strings (case-insensitive). Inbound notifications and connection-state
|
||||
* changes go to the registered listeners on the BLE queue; scan events go to the main queue.
|
||||
*
|
||||
* Locking: [cond] (non-reentrant) guards all peer state. It is never held across a
|
||||
* dispatch_sync or a listener callback.
|
||||
*/
|
||||
class IosBleCentral(private val platform: ProtocolPlatform = IosProtocolPlatform) : SessionLink, StockLink {
|
||||
companion object {
|
||||
const val TAG = "FaceclawBle"
|
||||
const val ADVERTISEMENT_CACHE = 512
|
||||
private const val READY_TIMEOUT_MS = 30_000
|
||||
private const val DEFAULT_ATT_MTU = 23
|
||||
private const val MAX_ATT_MTU = 517
|
||||
}
|
||||
|
||||
private class Peer(val peripheral: CBPeripheral) {
|
||||
val identifier: String = peripheral.identifier.UUIDString.uppercase()
|
||||
val characteristics = HashMap<String, CBCharacteristic>()
|
||||
var connectPending = false
|
||||
var connected = false
|
||||
var failure: String? = null
|
||||
var discoverPending = false
|
||||
var pendingServices = 0
|
||||
var notifyPending: String? = null
|
||||
var notifyResult: Boolean? = null
|
||||
var writePending = false
|
||||
var writeError: String? = null
|
||||
var readyForWriteWithoutResponse = false
|
||||
var requiresAncs = false
|
||||
var reportedConnected = false
|
||||
}
|
||||
|
||||
private class Advertisement(var name: String, var manufacturerDataHex: String)
|
||||
|
||||
private val queue = dispatch_queue_create("com.faceclaw.ble", null)
|
||||
private val cond: ProtocolCondition = platform.createCondition()
|
||||
private val peers = HashMap<String, Peer>()
|
||||
private val advertisements = LinkedHashMap<String, Advertisement>()
|
||||
private val delegate = Delegate(this)
|
||||
private var central: CBCentralManager? = null
|
||||
|
||||
@Volatile private var bluetoothState: Long = 0
|
||||
@Volatile private var scanRequested = false
|
||||
@Volatile private var scanListener: IosBleScanListener? = null
|
||||
@Volatile private var ancsListener: IosAncsAuthorizationListener? = null
|
||||
@Volatile private var sessionListener: FaceclawBleListener? = null
|
||||
@Volatile private var stockListener: StockLinkListener? = null
|
||||
@Volatile private var closed = false
|
||||
|
||||
// ----- listeners ------------------------------------------------------------------
|
||||
|
||||
/** The session core (a FaceclawBleListener); called on the BLE queue. */
|
||||
fun setSessionListener(listener: FaceclawBleListener?) {
|
||||
sessionListener = listener
|
||||
}
|
||||
|
||||
override fun setListener(listener: StockLinkListener?) {
|
||||
stockListener = listener
|
||||
}
|
||||
|
||||
fun setAncsAuthorizationListener(listener: IosAncsAuthorizationListener?) {
|
||||
ancsListener = listener
|
||||
}
|
||||
|
||||
/** Connect [identifier] with CBConnectPeripheralOptionRequiresANCS (the right arm relays iPhone notifications). */
|
||||
fun setRequiresAncs(identifier: String, required: Boolean) {
|
||||
val key = identifier.uppercase()
|
||||
cond.withLock { peers[key]?.requiresAncs = required }
|
||||
pendingAncs[key] = required
|
||||
}
|
||||
|
||||
private val pendingAncs = HashMap<String, Boolean>()
|
||||
|
||||
/** Whether the OS granted ANCS for the peripheral (false when unknown or disconnected). */
|
||||
fun isAncsAuthorized(identifier: String): Boolean =
|
||||
cond.withLock { peers[identifier.uppercase()]?.peripheral?.ancsAuthorized ?: false }
|
||||
|
||||
// ----- readiness and scanning -----------------------------------------------------------
|
||||
|
||||
/** Current CBManagerState raw value (0 until the central reports). */
|
||||
fun bluetoothState(): Int = bluetoothState.toInt()
|
||||
|
||||
fun authorization(): Int = CBManager.authorization.toInt()
|
||||
|
||||
/**
|
||||
* Creates the central (which triggers the permission prompt on first use) and waits for
|
||||
* it to power on. Returns null when ready or a user-facing message (the same texts the
|
||||
* TypeScript transport used).
|
||||
*/
|
||||
fun waitForPoweredOn(timeoutMs: Int = READY_TIMEOUT_MS): String? {
|
||||
ensureCentral()
|
||||
val deadline = platform.elapsedRealtimeMs() + timeoutMs
|
||||
cond.lock()
|
||||
try {
|
||||
while (true) {
|
||||
when (bluetoothState) {
|
||||
CBManagerStatePoweredOn -> return null
|
||||
CBManagerStateUnsupported -> return "Bluetooth is unavailable on this device. Use the physical iPhone."
|
||||
CBManagerStateUnauthorized -> return "Allow Faceclaw to use Bluetooth in iPhone Settings."
|
||||
CBManagerStatePoweredOff -> return "Turn on Bluetooth, then try again."
|
||||
}
|
||||
val left = deadline - platform.elapsedRealtimeMs()
|
||||
if (left <= 0) return "Waiting for Bluetooth permission timed out. Try again after allowing Bluetooth."
|
||||
cond.awaitMs(left)
|
||||
}
|
||||
} finally {
|
||||
cond.unlock()
|
||||
}
|
||||
}
|
||||
|
||||
private fun ensureCentral() {
|
||||
if (central != null) {
|
||||
// Re-report the current state so a fresh listener learns it.
|
||||
val listener = scanListener
|
||||
if (listener != null) {
|
||||
val state = bluetoothState.toInt()
|
||||
val authorization = authorization()
|
||||
dispatch_async(dispatch_get_main_queue()) { listener.onBluetoothState(state, authorization) }
|
||||
}
|
||||
return
|
||||
}
|
||||
central = CBCentralManager(delegate = delegate, queue = queue)
|
||||
}
|
||||
|
||||
fun setScanListener(listener: IosBleScanListener?) {
|
||||
scanListener = listener
|
||||
}
|
||||
|
||||
/** Starts (or keeps) scanning for all peripherals with duplicates; events reach the scan listener on main. */
|
||||
fun startScan() {
|
||||
scanRequested = true
|
||||
ensureCentral()
|
||||
dispatch_sync(queue) {
|
||||
val manager = central ?: return@dispatch_sync
|
||||
if (manager.state == CBManagerStatePoweredOn) beginScan(manager)
|
||||
}
|
||||
}
|
||||
|
||||
fun stopScan() {
|
||||
scanRequested = false
|
||||
dispatch_sync(queue) { central?.stopScan() }
|
||||
}
|
||||
|
||||
private fun beginScan(manager: CBCentralManager) {
|
||||
manager.scanForPeripheralsWithServices(null, mapOf(CBCentralManagerScanOptionAllowDuplicatesKey to true))
|
||||
}
|
||||
|
||||
/** Known peripheral identifiers from this process's scans/retrievals (uppercase). */
|
||||
fun knownIdentifiers(): List<String> = cond.withLock { peers.keys.toList() }
|
||||
|
||||
// ----- SessionLink / StockLink ----------------------------------------------------------
|
||||
|
||||
override fun connect(address: String, timeoutMs: Int): Boolean {
|
||||
val identifier = address.uppercase()
|
||||
val deadline = platform.elapsedRealtimeMs() + timeoutMs
|
||||
val ready = waitForPoweredOn(minOf(timeoutMs, READY_TIMEOUT_MS))
|
||||
if (ready != null) {
|
||||
log("connect $identifier: $ready")
|
||||
return false
|
||||
}
|
||||
val peer = findOrDiscover(identifier, deadline) ?: run {
|
||||
log("connect $identifier: peripheral not found")
|
||||
return false
|
||||
}
|
||||
val requiresAncs = cond.withLock {
|
||||
if (peer.connected || peer.connectPending) {
|
||||
log("connect $identifier: already connecting or connected")
|
||||
return peer.connected
|
||||
}
|
||||
peer.characteristics.clear()
|
||||
peer.failure = null
|
||||
peer.connectPending = true
|
||||
peer.reportedConnected = false
|
||||
peer.requiresAncs || (pendingAncs[identifier] ?: false)
|
||||
}
|
||||
dispatch_sync(queue) {
|
||||
val manager = central ?: return@dispatch_sync
|
||||
manager.connectPeripheral(
|
||||
peer.peripheral,
|
||||
if (requiresAncs) mapOf(CBConnectPeripheralOptionRequiresANCS to true) else null,
|
||||
)
|
||||
}
|
||||
val connected = cond.withLock {
|
||||
while (peer.connectPending) {
|
||||
val left = deadline - platform.elapsedRealtimeMs()
|
||||
if (left <= 0) break
|
||||
cond.awaitMs(left)
|
||||
}
|
||||
val ok = peer.connected
|
||||
if (!ok) peer.connectPending = false
|
||||
ok
|
||||
}
|
||||
if (!connected) {
|
||||
log("connect $identifier failed: " + (cond.withLock { peer.failure } ?: "timeout"))
|
||||
dispatch_sync(queue) { central?.cancelPeripheralConnection(peer.peripheral) }
|
||||
}
|
||||
return connected
|
||||
}
|
||||
|
||||
private fun findOrDiscover(identifier: String, deadline: Long): Peer? {
|
||||
cond.withLock { peers[identifier] }?.let { return it }
|
||||
var retrieved: CBPeripheral? = null
|
||||
dispatch_sync(queue) {
|
||||
val manager = central ?: return@dispatch_sync
|
||||
val uuid = NSUUID(uUIDString = identifier) ?: return@dispatch_sync
|
||||
retrieved = manager.retrievePeripheralsWithIdentifiers(listOf(uuid)).firstOrNull() as? CBPeripheral
|
||||
}
|
||||
retrieved?.let { return remember(it) }
|
||||
// Not known to the system: scan until the identifier shows up.
|
||||
val wasScanning = scanRequested
|
||||
startScan()
|
||||
try {
|
||||
cond.lock()
|
||||
try {
|
||||
while (true) {
|
||||
peers[identifier]?.let { return it }
|
||||
val left = deadline - platform.elapsedRealtimeMs()
|
||||
if (left <= 0) return null
|
||||
cond.awaitMs(left)
|
||||
}
|
||||
} finally {
|
||||
cond.unlock()
|
||||
}
|
||||
} finally {
|
||||
if (!wasScanning) stopScan()
|
||||
}
|
||||
}
|
||||
|
||||
override fun requestHighPriority(address: String) {}
|
||||
|
||||
override fun requestMtu(address: String, mtu: Int, timeoutMs: Int): Boolean = true
|
||||
|
||||
override fun prepareLink(address: String, desiredMtu: Int, timeoutMs: Int) {}
|
||||
|
||||
override fun negotiatedMtu(address: String): Int {
|
||||
val peer = cond.withLock { peers[address.uppercase()] } ?: return DEFAULT_ATT_MTU
|
||||
// CoreBluetooth reports the ATT payload; Android reports the ATT MTU (payload + 3).
|
||||
val payload = peer.peripheral.maximumWriteValueLengthForType(CBCharacteristicWriteWithoutResponse).toInt()
|
||||
return (payload + 3).coerceIn(DEFAULT_ATT_MTU, MAX_ATT_MTU)
|
||||
}
|
||||
|
||||
override fun discoverServices(address: String, timeoutMs: Int): Boolean {
|
||||
val peer = connectedPeer(address) ?: return false
|
||||
val deadline = platform.elapsedRealtimeMs() + timeoutMs
|
||||
cond.withLock {
|
||||
peer.discoverPending = true
|
||||
peer.pendingServices = 0
|
||||
peer.characteristics.clear()
|
||||
}
|
||||
dispatch_sync(queue) { peer.peripheral.discoverServices(null) }
|
||||
return cond.withLock {
|
||||
while (peer.discoverPending && peer.connected) {
|
||||
val left = deadline - platform.elapsedRealtimeMs()
|
||||
if (left <= 0) break
|
||||
cond.awaitMs(left)
|
||||
}
|
||||
!peer.discoverPending && peer.connected && peer.characteristics.isNotEmpty()
|
||||
}
|
||||
}
|
||||
|
||||
override fun enableNotifications(address: String, characteristicUuid: String, timeoutMs: Int): Boolean =
|
||||
enableNotifications(address, characteristicUuid, true, timeoutMs)
|
||||
|
||||
override fun enableNotifications(address: String, characteristicUuid: String, enable: Boolean, timeoutMs: Int): Boolean {
|
||||
val peer = connectedPeer(address) ?: return false
|
||||
val key = characteristicUuid.lowercase()
|
||||
val characteristic = cond.withLock { peer.characteristics[key] } ?: run {
|
||||
log("notifications $key: characteristic unavailable")
|
||||
return false
|
||||
}
|
||||
val notifiable = (characteristic.properties and (CBCharacteristicPropertyNotify or CBCharacteristicPropertyIndicate)) != 0uL
|
||||
if (!notifiable) {
|
||||
log("notifications $key: not notifiable")
|
||||
return false
|
||||
}
|
||||
if (characteristic.isNotifying == enable) return true
|
||||
val deadline = platform.elapsedRealtimeMs() + timeoutMs
|
||||
cond.withLock {
|
||||
peer.notifyPending = key
|
||||
peer.notifyResult = null
|
||||
}
|
||||
dispatch_sync(queue) { peer.peripheral.setNotifyValue(enable, characteristic) }
|
||||
return cond.withLock {
|
||||
while (peer.notifyPending == key && peer.connected) {
|
||||
val left = deadline - platform.elapsedRealtimeMs()
|
||||
if (left <= 0) break
|
||||
cond.awaitMs(left)
|
||||
}
|
||||
val result = peer.notifyResult == true && peer.connected
|
||||
if (peer.notifyPending == key) peer.notifyPending = null
|
||||
result || (!enable && peer.connected)
|
||||
}
|
||||
}
|
||||
|
||||
override fun writeFrames(
|
||||
address: String,
|
||||
characteristicUuid: String,
|
||||
frames: List<ByteArray>,
|
||||
mode: GattWriteMode,
|
||||
timeoutMs: Int,
|
||||
): Boolean {
|
||||
val peer = connectedPeer(address) ?: return false
|
||||
val key = characteristicUuid.lowercase()
|
||||
val characteristic = cond.withLock { peer.characteristics[key] } ?: run {
|
||||
log("write $key: characteristic unavailable")
|
||||
return false
|
||||
}
|
||||
val writable = (characteristic.properties and (CBCharacteristicPropertyWrite or CBCharacteristicPropertyWriteWithoutResponse)) != 0uL
|
||||
if (!writable) return false
|
||||
val withoutResponseSupported = (characteristic.properties and CBCharacteristicPropertyWriteWithoutResponse) != 0uL
|
||||
val type: CBCharacteristicWriteType =
|
||||
if (mode == GattWriteMode.WITHOUT_RESPONSE && withoutResponseSupported) CBCharacteristicWriteWithoutResponse
|
||||
else CBCharacteristicWriteWithResponse
|
||||
val limit = peer.peripheral.maximumWriteValueLengthForType(type).toInt()
|
||||
val deadline = platform.elapsedRealtimeMs() + timeoutMs
|
||||
for (frame in frames) {
|
||||
if (frame.size > limit) {
|
||||
log("write $key: ${frame.size} bytes exceeds the ${limit}-byte limit")
|
||||
return false
|
||||
}
|
||||
val data = frame.data()
|
||||
if (type == CBCharacteristicWriteWithResponse) {
|
||||
cond.withLock {
|
||||
peer.writePending = true
|
||||
peer.writeError = null
|
||||
}
|
||||
dispatch_sync(queue) { peer.peripheral.writeValue(data, characteristic, type) }
|
||||
val ok = cond.withLock {
|
||||
while (peer.writePending && peer.connected) {
|
||||
val left = deadline - platform.elapsedRealtimeMs()
|
||||
if (left <= 0) break
|
||||
cond.awaitMs(left)
|
||||
}
|
||||
val done = !peer.writePending && peer.writeError == null && peer.connected
|
||||
peer.writePending = false
|
||||
done
|
||||
}
|
||||
if (!ok) {
|
||||
log("write $key failed: " + (cond.withLock { peer.writeError } ?: "timeout"))
|
||||
return false
|
||||
}
|
||||
IosBleTraffic.recordWrite(frame.size)
|
||||
} else {
|
||||
while (true) {
|
||||
var sent = false
|
||||
var connected = true
|
||||
dispatch_sync(queue) {
|
||||
if (peer.peripheral.state != CBPeripheralStateConnected) {
|
||||
connected = false
|
||||
} else if (peer.peripheral.canSendWriteWithoutResponse) {
|
||||
peer.peripheral.writeValue(data, characteristic, type)
|
||||
sent = true
|
||||
}
|
||||
}
|
||||
if (!connected) return false
|
||||
if (sent) {
|
||||
IosBleTraffic.recordWrite(frame.size)
|
||||
break
|
||||
}
|
||||
// Pace on the controller's buffer: wait for peripheralIsReadyToSendWriteWithoutResponse.
|
||||
val ready = cond.withLock {
|
||||
peer.readyForWriteWithoutResponse = false
|
||||
while (!peer.readyForWriteWithoutResponse && peer.connected) {
|
||||
val left = deadline - platform.elapsedRealtimeMs()
|
||||
if (left <= 0) break
|
||||
cond.awaitMs(minOf(left, 50))
|
||||
// canSendWriteWithoutResponse may flip without a callback; re-check.
|
||||
if (peer.peripheral.canSendWriteWithoutResponse) break
|
||||
}
|
||||
peer.connected && (peer.readyForWriteWithoutResponse || peer.peripheral.canSendWriteWithoutResponse)
|
||||
}
|
||||
if (!ready) {
|
||||
if (platform.elapsedRealtimeMs() >= deadline) {
|
||||
log("write $key: timed out waiting for the write buffer")
|
||||
return false
|
||||
}
|
||||
if (!cond.withLock { peer.connected }) return false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
override fun isConnected(address: String): Boolean =
|
||||
cond.withLock { peers[address.uppercase()]?.connected ?: false }
|
||||
|
||||
override fun bondState(address: String): BondState = BondState.UNKNOWN
|
||||
|
||||
override fun isBonded(address: String): Boolean = true
|
||||
|
||||
override fun prepareBenchmarkLink(address: String, mode: Int) {}
|
||||
|
||||
override fun recordDisplayFrameSent() {
|
||||
IosBleTraffic.recordDisplayFrame()
|
||||
}
|
||||
|
||||
override fun disconnect(address: String) {
|
||||
val peer = cond.withLock { peers[address.uppercase()] } ?: return
|
||||
dispatch_sync(queue) {
|
||||
if (peer.peripheral.state != CBPeripheralStateDisconnected) central?.cancelPeripheralConnection(peer.peripheral)
|
||||
}
|
||||
failPeer(peer, "Disconnected", notifyListeners = false)
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
closed = true
|
||||
scanRequested = false
|
||||
val all = cond.withLock { peers.values.toList() }
|
||||
dispatch_sync(queue) {
|
||||
central?.stopScan()
|
||||
for (peer in all) if (peer.peripheral.state != CBPeripheralStateDisconnected) central?.cancelPeripheralConnection(peer.peripheral)
|
||||
}
|
||||
for (peer in all) failPeer(peer, "Closed", notifyListeners = false)
|
||||
}
|
||||
|
||||
// ----- internals ------------------------------------------------------------------
|
||||
|
||||
private fun connectedPeer(address: String): Peer? {
|
||||
val peer = cond.withLock { peers[address.uppercase()]?.takeIf { it.connected } }
|
||||
if (peer == null) log("$address is not connected")
|
||||
return peer
|
||||
}
|
||||
|
||||
private fun remember(peripheral: CBPeripheral): Peer {
|
||||
val identifier = peripheral.identifier.UUIDString.uppercase()
|
||||
return cond.withLock {
|
||||
peers.getOrPut(identifier) {
|
||||
peripheral.delegate = delegate
|
||||
Peer(peripheral).also { it.requiresAncs = pendingAncs[identifier] ?: false }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Marks the peer disconnected, wakes every waiter and (optionally) tells the listeners. */
|
||||
private fun failPeer(peer: Peer, reason: String, notifyListeners: Boolean) {
|
||||
val wasReported = cond.withLock {
|
||||
val reported = peer.reportedConnected
|
||||
peer.failure = reason
|
||||
peer.connectPending = false
|
||||
peer.connected = false
|
||||
peer.reportedConnected = false
|
||||
peer.discoverPending = false
|
||||
peer.notifyPending = null
|
||||
peer.writePending = false
|
||||
peer.readyForWriteWithoutResponse = false
|
||||
peer.characteristics.clear()
|
||||
cond.signalAll()
|
||||
reported
|
||||
}
|
||||
if (notifyListeners && wasReported) emitConnectionState(peer.identifier, false)
|
||||
}
|
||||
|
||||
private fun emitConnectionState(identifier: String, connected: Boolean) {
|
||||
sessionListener?.onConnectionStateChange(identifier, connected)
|
||||
stockListener?.onConnectionStateChange(identifier, connected)
|
||||
}
|
||||
|
||||
private fun log(message: String) = PlatformLog.i(TAG, message)
|
||||
|
||||
// ----- delegate callbacks (BLE queue) ----------------------------------------------------
|
||||
|
||||
private fun onStateUpdated(manager: CBCentralManager) {
|
||||
val state = manager.state
|
||||
bluetoothState = state
|
||||
cond.withLock { cond.signalAll() }
|
||||
val listener = scanListener
|
||||
if (listener != null) {
|
||||
val authorization = authorization()
|
||||
dispatch_async(dispatch_get_main_queue()) { listener.onBluetoothState(state.toInt(), authorization) }
|
||||
}
|
||||
if (state != CBManagerStatePoweredOn) {
|
||||
val all = cond.withLock { peers.values.toList() }
|
||||
for (peer in all) failPeer(peer, "Bluetooth is unavailable", notifyListeners = true)
|
||||
} else if (scanRequested) {
|
||||
beginScan(manager)
|
||||
}
|
||||
}
|
||||
|
||||
private fun onDiscovered(peripheral: CBPeripheral, advertisementData: Map<Any?, *>, rssi: NSNumber) {
|
||||
val peer = remember(peripheral)
|
||||
cond.withLock { cond.signalAll() } // findOrDiscover may be waiting for this identifier
|
||||
val listener = scanListener ?: return
|
||||
val manufacturer = (advertisementData[CBAdvertisementDataManufacturerDataKey] as? NSData)?.byteArray()
|
||||
val advertisedName = advertisementData[CBAdvertisementDataLocalNameKey] as? String
|
||||
val connectable = (advertisementData[CBAdvertisementDataIsConnectable] as? NSNumber)?.boolValue ?: true
|
||||
val merged = cond.withLock {
|
||||
val previous = advertisements.remove(peer.identifier)
|
||||
val name = advertisedName ?: peripheral.name ?: previous?.name ?: ""
|
||||
val hex = if (manufacturer != null) BinaryEncoding.bytesToHex(manufacturer) else previous?.manufacturerDataHex ?: ""
|
||||
if (advertisements.size >= ADVERTISEMENT_CACHE) advertisements.remove(advertisements.keys.first())
|
||||
Advertisement(name, hex).also { advertisements[peer.identifier] = it }
|
||||
}
|
||||
val identifier = peer.identifier
|
||||
val level = rssi.intValue
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
listener.onAdvertisement(identifier, merged.name, merged.manufacturerDataHex, level, connectable)
|
||||
}
|
||||
}
|
||||
|
||||
private fun onConnected(peripheral: CBPeripheral) {
|
||||
val peer = remember(peripheral)
|
||||
cond.withLock {
|
||||
peer.connected = true
|
||||
peer.connectPending = false
|
||||
peer.failure = null
|
||||
peer.reportedConnected = true
|
||||
cond.signalAll()
|
||||
}
|
||||
emitConnectionState(peer.identifier, true)
|
||||
}
|
||||
|
||||
private fun onDisconnected(peripheral: CBPeripheral, error: NSError?) {
|
||||
val peer = remember(peripheral)
|
||||
failPeer(peer, error?.localizedDescription ?: "Disconnected", notifyListeners = true)
|
||||
}
|
||||
|
||||
private fun onServicesDiscovered(peripheral: CBPeripheral, error: NSError?) {
|
||||
val peer = remember(peripheral)
|
||||
val services = peripheral.services?.mapNotNull { it as? CBService } ?: emptyList()
|
||||
if (error != null || services.isEmpty()) {
|
||||
cond.withLock {
|
||||
peer.discoverPending = false
|
||||
cond.signalAll()
|
||||
}
|
||||
return
|
||||
}
|
||||
cond.withLock { peer.pendingServices = services.size }
|
||||
for (service in services) peripheral.discoverCharacteristics(null, service)
|
||||
}
|
||||
|
||||
private fun onCharacteristicsDiscovered(peripheral: CBPeripheral, service: CBService, error: NSError?) {
|
||||
val peer = remember(peripheral)
|
||||
cond.withLock {
|
||||
if (error == null) {
|
||||
for (item in service.characteristics ?: emptyList<Any?>()) {
|
||||
val characteristic = item as? CBCharacteristic ?: continue
|
||||
peer.characteristics[characteristic.UUID.UUIDString.lowercase()] = characteristic
|
||||
}
|
||||
}
|
||||
peer.pendingServices--
|
||||
if (peer.pendingServices <= 0) peer.discoverPending = false
|
||||
cond.signalAll()
|
||||
}
|
||||
}
|
||||
|
||||
private fun onNotificationState(peripheral: CBPeripheral, characteristic: CBCharacteristic, error: NSError?) {
|
||||
val peer = remember(peripheral)
|
||||
val key = characteristic.UUID.UUIDString.lowercase()
|
||||
cond.withLock {
|
||||
if (peer.notifyPending == key) {
|
||||
peer.notifyResult = error == null && characteristic.isNotifying
|
||||
peer.notifyPending = null
|
||||
}
|
||||
cond.signalAll()
|
||||
}
|
||||
}
|
||||
|
||||
private fun onValue(peripheral: CBPeripheral, characteristic: CBCharacteristic, error: NSError?) {
|
||||
if (error != null) {
|
||||
log("notification error: " + error.localizedDescription)
|
||||
return
|
||||
}
|
||||
val data = characteristic.value?.byteArray() ?: return
|
||||
val identifier = peripheral.identifier.UUIDString.uppercase()
|
||||
val uuid = characteristic.UUID.UUIDString.lowercase()
|
||||
IosBleTraffic.recordRead(data.size)
|
||||
sessionListener?.onNotification(identifier, uuid, data)
|
||||
stockListener?.onNotification(identifier, uuid, data)
|
||||
}
|
||||
|
||||
private fun onWrote(peripheral: CBPeripheral, error: NSError?) {
|
||||
val peer = remember(peripheral)
|
||||
cond.withLock {
|
||||
peer.writeError = error?.localizedDescription
|
||||
peer.writePending = false
|
||||
cond.signalAll()
|
||||
}
|
||||
}
|
||||
|
||||
private fun onReadyForWriteWithoutResponse(peripheral: CBPeripheral) {
|
||||
val peer = remember(peripheral)
|
||||
cond.withLock {
|
||||
peer.readyForWriteWithoutResponse = true
|
||||
cond.signalAll()
|
||||
}
|
||||
}
|
||||
|
||||
private fun onAncsAuthorization(peripheral: CBPeripheral) {
|
||||
val identifier = peripheral.identifier.UUIDString.uppercase()
|
||||
ancsListener?.onAncsAuthorization(identifier, peripheral.ancsAuthorized)
|
||||
}
|
||||
|
||||
private class Delegate(private val owner: IosBleCentral) : NSObject(), CBCentralManagerDelegateProtocol, CBPeripheralDelegateProtocol {
|
||||
override fun centralManagerDidUpdateState(central: CBCentralManager) = owner.onStateUpdated(central)
|
||||
|
||||
override fun centralManager(central: CBCentralManager, didDiscoverPeripheral: CBPeripheral, advertisementData: Map<Any?, *>, RSSI: NSNumber) =
|
||||
owner.onDiscovered(didDiscoverPeripheral, advertisementData, RSSI)
|
||||
|
||||
@ObjCSignatureOverride
|
||||
override fun centralManager(central: CBCentralManager, didConnectPeripheral: CBPeripheral) = owner.onConnected(didConnectPeripheral)
|
||||
|
||||
@ObjCSignatureOverride
|
||||
override fun centralManager(central: CBCentralManager, didFailToConnectPeripheral: CBPeripheral, error: NSError?) =
|
||||
owner.onDisconnected(didFailToConnectPeripheral, error)
|
||||
|
||||
@ObjCSignatureOverride
|
||||
override fun centralManager(central: CBCentralManager, didDisconnectPeripheral: CBPeripheral, error: NSError?) =
|
||||
owner.onDisconnected(didDisconnectPeripheral, error)
|
||||
|
||||
@ObjCSignatureOverride
|
||||
override fun centralManager(central: CBCentralManager, didUpdateANCSAuthorizationForPeripheral: CBPeripheral) =
|
||||
owner.onAncsAuthorization(didUpdateANCSAuthorizationForPeripheral)
|
||||
|
||||
override fun peripheral(peripheral: CBPeripheral, didDiscoverServices: NSError?) = owner.onServicesDiscovered(peripheral, didDiscoverServices)
|
||||
|
||||
@ObjCSignatureOverride
|
||||
override fun peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService: CBService, error: NSError?) =
|
||||
owner.onCharacteristicsDiscovered(peripheral, didDiscoverCharacteristicsForService, error)
|
||||
|
||||
@ObjCSignatureOverride
|
||||
override fun peripheral(peripheral: CBPeripheral, didUpdateNotificationStateForCharacteristic: CBCharacteristic, error: NSError?) =
|
||||
owner.onNotificationState(peripheral, didUpdateNotificationStateForCharacteristic, error)
|
||||
|
||||
@ObjCSignatureOverride
|
||||
override fun peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic: CBCharacteristic, error: NSError?) =
|
||||
owner.onValue(peripheral, didUpdateValueForCharacteristic, error)
|
||||
|
||||
@ObjCSignatureOverride
|
||||
override fun peripheral(peripheral: CBPeripheral, didWriteValueForCharacteristic: CBCharacteristic, error: NSError?) =
|
||||
owner.onWrote(peripheral, error)
|
||||
|
||||
override fun peripheralIsReadyToSendWriteWithoutResponse(peripheral: CBPeripheral) = owner.onReadyForWriteWithoutResponse(peripheral)
|
||||
}
|
||||
}
|
||||
|
||||
/** Process-wide BLE traffic counters (the TypeScript ios-ble-traffic counters' successor). */
|
||||
object IosBleTraffic {
|
||||
private val lock = IosProtocolPlatform.createLock()
|
||||
private var bytesWritten = 0L
|
||||
private var bytesRead = 0L
|
||||
private var displayFrames = 0L
|
||||
|
||||
fun recordWrite(bytes: Int) = lock.withLock { bytesWritten += bytes }
|
||||
|
||||
fun recordRead(bytes: Int) = lock.withLock { bytesRead += bytes }
|
||||
|
||||
fun recordDisplayFrame() = lock.withLock { displayFrames++ }
|
||||
|
||||
/** [bytesWritten, bytesRead, displayFrames] and resets the counters. */
|
||||
fun sample(): LongArray = lock.withLock {
|
||||
val out = longArrayOf(bytesWritten, bytesRead, displayFrames)
|
||||
bytesWritten = 0
|
||||
bytesRead = 0
|
||||
displayFrames = 0
|
||||
out
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
|
||||
|
||||
package com.faceclaw.app
|
||||
|
||||
import platform.Foundation.NSData
|
||||
import platform.darwin.dispatch_async
|
||||
import platform.darwin.dispatch_get_main_queue
|
||||
import platform.darwin.dispatch_queue_create
|
||||
|
||||
/** iPhone-notification relay hooks; both callbacks are delivered on the main queue. */
|
||||
interface IosAncsListener {
|
||||
fun onAncsAuthorization(authorized: Boolean)
|
||||
|
||||
/** A relay frame ('A','N',...) received on the right arm's data characteristic. */
|
||||
fun onRelayFrame(data: NSData)
|
||||
}
|
||||
|
||||
/**
|
||||
* ObjC-facing facade over the shared [GlassesSessionCore] for the NativeScript app: the iOS
|
||||
* counterpart of Android's FaceclawBleCommunicator with the same method names. GATT goes
|
||||
* through [IosBleCentral], side effects through [IosSessionHost]; every listener the
|
||||
* TypeScript side installs is invoked on the main queue. Binary crossings use NSData.
|
||||
*/
|
||||
class IosGlassesSession internal constructor(
|
||||
link: SessionLink,
|
||||
private val central: IosBleCentral?,
|
||||
private val host: SessionHost,
|
||||
rightAddress: String,
|
||||
leftAddress: String,
|
||||
ringAddress: String,
|
||||
platform: ProtocolPlatform,
|
||||
) {
|
||||
/** Production constructor: CoreBluetooth link + main-queue host. Addresses are peripheral identifiers. */
|
||||
constructor(rightAddress: String, leftAddress: String, ringAddress: String) : this(
|
||||
IosBleCentral(),
|
||||
rightAddress,
|
||||
leftAddress,
|
||||
ringAddress,
|
||||
)
|
||||
|
||||
private constructor(central: IosBleCentral, rightAddress: String, leftAddress: String, ringAddress: String) : this(
|
||||
central,
|
||||
central,
|
||||
IosSessionHost(),
|
||||
rightAddress,
|
||||
leftAddress,
|
||||
ringAddress,
|
||||
IosProtocolPlatform,
|
||||
)
|
||||
|
||||
companion object {
|
||||
const val TAG = GlassesSessionCore.TAG
|
||||
}
|
||||
|
||||
private val frameTimings = IosFrameTimings.shared.core
|
||||
private val core = GlassesSessionCore(link, host, frameTimings, platform, rightAddress, leftAddress, ringAddress)
|
||||
private val rawQueue = dispatch_queue_create("com.faceclaw.session.raw", null)
|
||||
private val rightIdentifier = rightAddress.uppercase()
|
||||
|
||||
init {
|
||||
central?.setSessionListener(core)
|
||||
}
|
||||
|
||||
// ----- lifecycle ------------------------------------------------------------------
|
||||
|
||||
fun setListener(listener: FaceclawBleCommunicatorListener?) = core.setListener(listener)
|
||||
|
||||
fun start(): Boolean = core.start()
|
||||
|
||||
fun disconnect() = core.disconnect()
|
||||
|
||||
fun close() = core.close()
|
||||
|
||||
fun onPhoneLockSignal() = core.onPhoneLockSignal()
|
||||
|
||||
fun isSessionReady(): Boolean = core.isSessionReady()
|
||||
|
||||
// ----- iPhone notification relay (ANCS) -------------------------------------------------
|
||||
|
||||
/** Ask CoreBluetooth for ANCS on the right arm's next connection (call before start()). */
|
||||
fun setRequiresAncs(required: Boolean) {
|
||||
central?.setRequiresAncs(rightIdentifier, required)
|
||||
}
|
||||
|
||||
fun isAncsAuthorized(): Boolean = central?.isAncsAuthorized(rightIdentifier) ?: false
|
||||
|
||||
fun setAncsListener(listener: IosAncsListener?) {
|
||||
if (listener == null) {
|
||||
core.setRawFrameTap(null)
|
||||
central?.setAncsAuthorizationListener(null)
|
||||
return
|
||||
}
|
||||
core.setRawFrameTap { bytes ->
|
||||
val data = bytes.data()
|
||||
dispatch_async(dispatch_get_main_queue()) { listener.onRelayFrame(data) }
|
||||
}
|
||||
central?.setAncsAuthorizationListener { _, authorized ->
|
||||
dispatch_async(dispatch_get_main_queue()) { listener.onAncsAuthorization(authorized) }
|
||||
}
|
||||
}
|
||||
|
||||
/** Queue one relay packet for the right arm; never blocks the caller (writes run on a serial queue). */
|
||||
fun writeRawToRight(packet: NSData) {
|
||||
val bytes = packet.byteArray()
|
||||
dispatch_async(rawQueue) {
|
||||
if (!core.writeRawPacket("R", bytes)) PlatformLog.w(TAG, "relay packet dropped (${bytes.size} bytes)")
|
||||
}
|
||||
}
|
||||
|
||||
// ----- controls -------------------------------------------------------------------
|
||||
|
||||
fun setG2ScreenOn(screenOn: Boolean) = core.setG2ScreenOn(screenOn)
|
||||
|
||||
fun setFirmwareDebugFlags(enabled: Boolean) = core.setFirmwareDebugFlags(enabled)
|
||||
|
||||
/** The packet listener is invoked on the main queue (the core delivers on the BLE queue). */
|
||||
fun startG2AudioCapture(listener: FaceclawAudioPacketListener?): Boolean =
|
||||
core.startG2AudioCapture(listener?.let { MainQueueAudioListener(it) })
|
||||
|
||||
fun stopG2AudioCapture() = core.stopG2AudioCapture()
|
||||
|
||||
fun isAudioCaptureActive(): Boolean = core.isAudioCaptureActive()
|
||||
|
||||
fun setFaceclawWakeLeaseEnabled(enabled: Boolean): Boolean = core.setFaceclawWakeLeaseEnabled(enabled)
|
||||
|
||||
fun awaitEvenHubSessionReady(timeoutMs: Int): Boolean = core.awaitEvenHubSessionReady(timeoutMs)
|
||||
|
||||
fun setImuReportEnabled(enable: Boolean, reportFrq: Int) = core.setImuReportEnabled(enable, reportFrq)
|
||||
|
||||
fun setCompassEnabled(enable: Boolean) = core.setCompassEnabled(enable)
|
||||
|
||||
fun setCompassEnabledForOwner(owner: String?, enable: Boolean) = core.setCompassEnabled(owner, enable)
|
||||
|
||||
fun setBrightness(autoAdjust: Boolean, brightnessLevel: Int) = core.setBrightness(autoAdjust, brightnessLevel)
|
||||
|
||||
fun enableWearDetectionAndRequestState() = core.enableWearDetectionAndRequestState()
|
||||
|
||||
fun startBandwidthBenchmark(messageSize: Int, windowSize: Int, durationMs: Int): Boolean =
|
||||
core.startBandwidthBenchmark(messageSize, windowSize, durationMs)
|
||||
|
||||
fun startBandwidthBenchmarkWithLinkMode(messageSize: Int, windowSize: Int, durationMs: Int, linkMode: Int): Boolean =
|
||||
core.startBandwidthBenchmarkWithLinkMode(messageSize, windowSize, durationMs, linkMode)
|
||||
|
||||
fun cancelBandwidthBenchmark() = core.cancelBandwidthBenchmark()
|
||||
|
||||
fun getBandwidthBenchmarkStatus(): String = core.getBandwidthBenchmarkStatus()
|
||||
|
||||
fun addImuListener(listener: FaceclawImuListener?) = core.addImuListener(listener)
|
||||
|
||||
fun removeImuListener(listener: FaceclawImuListener?) = core.removeImuListener(listener)
|
||||
|
||||
fun addAmbientLightListener(listener: FaceclawAmbientLightListener?) = core.addAmbientLightListener(listener)
|
||||
|
||||
fun removeAmbientLightListener(listener: FaceclawAmbientLightListener?) = core.removeAmbientLightListener(listener)
|
||||
|
||||
fun queryAmbientLight() = core.queryAmbientLight()
|
||||
|
||||
fun setAmbientLightPolling(enable: Boolean, intervalMs: Int, minDelta: Int, heartbeatMs: Int, bindToLease: Boolean) =
|
||||
core.setAmbientLightPolling(enable, intervalMs, minDelta, heartbeatMs, bindToLease)
|
||||
|
||||
fun addMicStatusListener(listener: FaceclawMicStatusListener?) = core.addMicStatusListener(listener)
|
||||
|
||||
fun removeMicStatusListener(listener: FaceclawMicStatusListener?) = core.removeMicStatusListener(listener)
|
||||
|
||||
fun sendFaceclawMicControl(record: NSData?, label: String, rightTemple: Boolean, leftTemple: Boolean) =
|
||||
core.sendFaceclawMicControl(record?.byteArray(), label, rightTemple, leftTemple)
|
||||
|
||||
fun startG2AudioForwarding(listener: FaceclawAudioPacketListener?): Boolean =
|
||||
core.startG2AudioForwarding(listener?.let { MainQueueAudioListener(it) })
|
||||
|
||||
fun stopG2AudioForwarding() = core.stopG2AudioForwarding()
|
||||
|
||||
/** Compass events are delivered on the queue of the thread that adds the listener (main for TypeScript). */
|
||||
fun addCompassListener(listener: FaceclawCompassListener?) = core.addCompassListener(listener)
|
||||
|
||||
fun removeCompassListener(listener: FaceclawCompassListener?) = core.removeCompassListener(listener)
|
||||
|
||||
fun sendShutdown(exitMode: Int): Boolean = core.sendShutdown(exitMode)
|
||||
|
||||
fun sendCfwCleanup(): Boolean = core.sendCfwCleanup()
|
||||
|
||||
fun suspendEvenHubSession(): Boolean = core.suspendEvenHubSession()
|
||||
|
||||
fun resumeEvenHubSession(): Boolean = core.resumeEvenHubSession()
|
||||
|
||||
fun playBuzzerSequence(payload: NSData?) = core.playBuzzerSequence(payload?.byteArray())
|
||||
|
||||
// ----- surfaces -------------------------------------------------------------------
|
||||
|
||||
/** Set the compositor's output frame size. Call before configuring surfaces. */
|
||||
fun configureCompositorScreen(width: Int, height: Int) = core.configureCompositorScreen(width, height)
|
||||
|
||||
fun setSurfaceVisible(id: String, visible: Boolean) = core.setSurfaceVisible(id, visible)
|
||||
|
||||
fun setScreenBlanked(blanked: Boolean) = core.setScreenBlanked(blanked)
|
||||
|
||||
fun configureSurface(id: String, x: Int, y: Int, width: Int, height: Int, zOrder: Int, transparency: Int) =
|
||||
core.configureSurface(id, x, y, width, height, zOrder, transparency)
|
||||
|
||||
fun removeSurface(id: String) = core.removeSurface(id)
|
||||
|
||||
fun submitShellScene(bytes: NSData, paintMs: Int, frameId: Int) = core.submitShellScene(IosByteReader(bytes), paintMs, frameId)
|
||||
|
||||
fun setUnderlayDim(belowZOrder: Int, factor256: Int) = core.setUnderlayDim(belowZOrder, factor256)
|
||||
|
||||
fun submitSurfaceFrame(
|
||||
pixels8bpp: NSData,
|
||||
surfaceId: String,
|
||||
rectX: Int,
|
||||
rectY: Int,
|
||||
rectWidth: Int,
|
||||
rectHeight: Int,
|
||||
contentFingerprint: String?,
|
||||
paintMs: Int,
|
||||
frameId: Int,
|
||||
glyphs: NSData?,
|
||||
) = core.submitSurfaceFrame(
|
||||
IosByteReader(pixels8bpp), surfaceId, rectX, rectY, rectWidth, rectHeight, contentFingerprint, paintMs, frameId,
|
||||
glyphs?.let { IosByteReader(it) },
|
||||
)
|
||||
|
||||
/** The current composited screen (gray, 8bpp) or null before any surface was configured. */
|
||||
fun previewComposite(): IosTextureFrame? = core.previewComposite()?.let { IosTextureFrame(it) }
|
||||
|
||||
fun compositeWidth(): Int = core.previewComposite()?.width ?: 0
|
||||
|
||||
fun compositeHeight(): Int = core.previewComposite()?.height ?: 0
|
||||
|
||||
/** The current composite as a 4-bit grayscale PNG, or null. */
|
||||
fun screenshotPng(): NSData? {
|
||||
val composite = core.previewComposite() ?: return null
|
||||
return SharedScreenshots.encode4BitGrayPng(composite.gray, composite.width, composite.height).data()
|
||||
}
|
||||
|
||||
/** Frame-timings export text (see FrameTimingsCore), for the phone-side debug page. */
|
||||
fun frameTimingsExport(): String = frameTimings.buildExport()
|
||||
|
||||
internal fun coreForTests(): GlassesSessionCore = core
|
||||
|
||||
private class MainQueueAudioListener(private val delegate: FaceclawAudioPacketListener) : FaceclawAudioPacketListener {
|
||||
override fun onAudioPacket(data: ByteArray?, arm: String?, arrivalMs: Long) {
|
||||
dispatch_async(dispatch_get_main_queue()) { delegate.onAudioPacket(data, arm, arrivalMs) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
|
||||
|
||||
package com.faceclaw.app
|
||||
|
||||
import kotlin.concurrent.Volatile
|
||||
import platform.Foundation.NSBundle
|
||||
import platform.Foundation.NSNotificationCenter
|
||||
import platform.Foundation.NSOperationQueue
|
||||
import platform.Foundation.NSThread
|
||||
import platform.UIKit.UIApplication
|
||||
import platform.UIKit.UIApplicationProtectedDataDidBecomeAvailable
|
||||
import platform.UIKit.UIApplicationProtectedDataWillBecomeUnavailable
|
||||
import platform.darwin.dispatch_async
|
||||
import platform.darwin.dispatch_get_main_queue
|
||||
import platform.darwin.dispatch_queue_create
|
||||
|
||||
/**
|
||||
* iOS [SessionHost]: listener callbacks go to the main queue (NativeScript's JavaScript
|
||||
* thread), the session worker is an NSThread, the "glasses screen on" wake lock maps to the
|
||||
* idle timer, and "phone locked" tracks protected-data availability (data protection kicks
|
||||
* in shortly after the passcode lock engages), observed on the main queue so the worker
|
||||
* never has to block on the main thread. There is no Even-app conflict on iOS.
|
||||
*/
|
||||
class IosSessionHost(private val platform: ProtocolPlatform = IosProtocolPlatform, private val threadName: String = "FaceclawBleCommunicator") : SessionHost {
|
||||
private val mainDispatcher = SessionDispatcher { action -> dispatch_async(dispatch_get_main_queue()) { action() } }
|
||||
|
||||
@Volatile private var phoneLocked = false
|
||||
|
||||
@Volatile private var workerDone: Latch? = null
|
||||
|
||||
/** UIApplication exists only inside a UIKit app; the Kotlin test executable has no bundle type. */
|
||||
private val uiApplicationAvailable: Boolean =
|
||||
NSBundle.mainBundle.infoDictionary?.get("CFBundlePackageType") == "APPL"
|
||||
|
||||
init {
|
||||
if (uiApplicationAvailable) {
|
||||
val center = NSNotificationCenter.defaultCenter
|
||||
center.addObserverForName(UIApplicationProtectedDataWillBecomeUnavailable, null, NSOperationQueue.mainQueue) { phoneLocked = true }
|
||||
center.addObserverForName(UIApplicationProtectedDataDidBecomeAvailable, null, NSOperationQueue.mainQueue) { phoneLocked = false }
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
phoneLocked = !UIApplication.sharedApplication.protectedDataAvailable
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun postToMain(action: () -> Unit) {
|
||||
dispatch_async(dispatch_get_main_queue()) { action() }
|
||||
}
|
||||
|
||||
override fun currentThreadDispatcher(): SessionDispatcher {
|
||||
if (NSThread.isMainThread) return mainDispatcher
|
||||
val queue = dispatch_queue_create("com.faceclaw.session.subscriber", null)
|
||||
return SessionDispatcher { action -> dispatch_async(queue) { action() } }
|
||||
}
|
||||
|
||||
override fun isPhoneLocked(): Boolean = phoneLocked
|
||||
|
||||
override fun setScreenWakeLock(on: Boolean) {
|
||||
if (!uiApplicationAvailable) return
|
||||
dispatch_async(dispatch_get_main_queue()) { UIApplication.sharedApplication.idleTimerDisabled = on }
|
||||
}
|
||||
|
||||
override fun isEvenAppActive(): Boolean = false
|
||||
|
||||
override fun startWorker(body: () -> Unit) {
|
||||
val latch = Latch(1, platform)
|
||||
workerDone = latch
|
||||
val thread = NSThread {
|
||||
try {
|
||||
body()
|
||||
} finally {
|
||||
latch.countDown()
|
||||
}
|
||||
}
|
||||
thread.name = threadName
|
||||
thread.start()
|
||||
}
|
||||
|
||||
override fun joinWorker(timeoutMs: Long) {
|
||||
// Kotlin/Native threads cannot be interrupted; the core wakes its own sleeper before joining.
|
||||
workerDone?.await(timeoutMs)
|
||||
workerDone = null
|
||||
}
|
||||
|
||||
override fun log(level: SessionLogLevel, tag: String, message: String, error: Throwable?) {
|
||||
when (level) {
|
||||
SessionLogLevel.DEBUG, SessionLogLevel.INFO -> PlatformLog.i(tag, message)
|
||||
SessionLogLevel.WARN -> PlatformLog.w(tag, if (error != null) "$message (${error.message})" else message)
|
||||
SessionLogLevel.ERROR -> PlatformLog.e(tag, message, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
|
||||
|
||||
package com.faceclaw.app
|
||||
|
||||
import platform.Foundation.NSThread
|
||||
import platform.darwin.dispatch_async
|
||||
import platform.darwin.dispatch_get_main_queue
|
||||
|
||||
private fun main(action: () -> Unit) {
|
||||
dispatch_async(dispatch_get_main_queue()) { action() }
|
||||
}
|
||||
|
||||
private fun runOnThread(name: String, body: () -> Unit) {
|
||||
val thread = NSThread { body() }
|
||||
thread.name = name
|
||||
thread.start()
|
||||
}
|
||||
|
||||
/**
|
||||
* iOS host for the shared [DeviceInfoProbeFlow]: owns a CoreBluetooth link, runs the flow on
|
||||
* its own NSThread and delivers listener callbacks on the main queue. Same surface as
|
||||
* Android's FaceclawDeviceInfoProbe. Addresses are peripheral identifiers.
|
||||
*/
|
||||
class IosDeviceInfoProbe(rightAddress: String, leftAddress: String) {
|
||||
private val link = IosBleCentral()
|
||||
private val lock = IosProtocolPlatform.createLock()
|
||||
private var started = false
|
||||
private var listener: FaceclawDeviceInfoProbeListener? = null
|
||||
|
||||
private val flow = DeviceInfoProbeFlow(
|
||||
link,
|
||||
rightAddress,
|
||||
leftAddress,
|
||||
object : FaceclawDeviceInfoProbeListener {
|
||||
override fun onLog(line: String?) {
|
||||
PlatformLog.i(DeviceInfoProbeFlow.TAG, line ?: "")
|
||||
post { it.onLog(line) }
|
||||
}
|
||||
|
||||
override fun onState(state: String?, detail: String?) = post { it.onState(state, detail ?: "") }
|
||||
|
||||
override fun onResult(leftVersion: String?, rightVersion: String?, extension: String?) =
|
||||
post { it.onResult(leftVersion, rightVersion, extension) }
|
||||
|
||||
override fun onError(message: String?) = post { it.onError(message ?: "") }
|
||||
},
|
||||
)
|
||||
|
||||
fun setListener(listener: FaceclawDeviceInfoProbeListener?) {
|
||||
lock.withLock { this.listener = listener }
|
||||
}
|
||||
|
||||
fun start() {
|
||||
lock.withLock {
|
||||
if (started) return
|
||||
started = true
|
||||
}
|
||||
runOnThread("faceclaw-device-info") { flow.run() }
|
||||
}
|
||||
|
||||
fun cancel() = flow.cancel()
|
||||
|
||||
fun close() {
|
||||
cancel()
|
||||
runCatching { link.close() }
|
||||
}
|
||||
|
||||
private fun post(action: (FaceclawDeviceInfoProbeListener) -> Unit) = main {
|
||||
lock.withLock { listener }?.let(action)
|
||||
}
|
||||
}
|
||||
|
||||
/** iOS host for the shared [FlashPromptFlow] (the on-glasses Yes/No confirmation before flashing). */
|
||||
class IosFlashPrompt(rightAddress: String, leftAddress: String, warningText: String, skipPrompt: Boolean) {
|
||||
private val link = IosBleCentral()
|
||||
private val lock = IosProtocolPlatform.createLock()
|
||||
private var started = false
|
||||
private var listener: FaceclawFlashPromptListener? = null
|
||||
|
||||
private val flow = FlashPromptFlow(
|
||||
link,
|
||||
rightAddress,
|
||||
leftAddress,
|
||||
warningText,
|
||||
skipPrompt,
|
||||
object : FaceclawFlashPromptListener {
|
||||
override fun onLog(line: String?) {
|
||||
PlatformLog.i(FlashPromptFlow.TAG, line ?: "")
|
||||
post { it.onLog(line) }
|
||||
}
|
||||
|
||||
override fun onState(state: String?, detail: String?) = post { it.onState(state, detail ?: "") }
|
||||
|
||||
override fun onBattery(rightPercent: Int, leftPercent: Int) = post { it.onBattery(rightPercent, leftPercent) }
|
||||
|
||||
override fun onResult(approved: Boolean) = post { it.onResult(approved) }
|
||||
},
|
||||
)
|
||||
|
||||
fun setListener(listener: FaceclawFlashPromptListener?) {
|
||||
lock.withLock { this.listener = listener }
|
||||
}
|
||||
|
||||
fun start() {
|
||||
lock.withLock {
|
||||
if (started) return
|
||||
started = true
|
||||
}
|
||||
runOnThread("faceclaw-flash-prompt") { flow.run() }
|
||||
}
|
||||
|
||||
fun cancel() = flow.cancel()
|
||||
|
||||
fun close() {
|
||||
cancel()
|
||||
runCatching { link.close() }
|
||||
}
|
||||
|
||||
private fun post(action: (FaceclawFlashPromptListener) -> Unit) = main {
|
||||
lock.withLock { listener }?.let(action)
|
||||
}
|
||||
}
|
||||
|
||||
/** iOS host for the shared [OtaFlashFlow] (custom-firmware OTA over the stock protocol). */
|
||||
class IosFirmwareFlasher(rightAddress: String, leftAddress: String, firmwarePath: String) {
|
||||
private val link = IosBleCentral()
|
||||
private val lock = IosProtocolPlatform.createLock()
|
||||
private var started = false
|
||||
private var listener: FaceclawFirmwareFlasherListener? = null
|
||||
|
||||
private val flow = OtaFlashFlow(
|
||||
link,
|
||||
rightAddress,
|
||||
leftAddress,
|
||||
firmwarePath,
|
||||
object : FaceclawFirmwareFlasherListener {
|
||||
override fun onLog(line: String?) {
|
||||
PlatformLog.i(OtaFlashFlow.TAG, line ?: "")
|
||||
post { it.onLog(line) }
|
||||
}
|
||||
|
||||
override fun onProgress(lens: String?, componentIndex: Int, componentCount: Int, blockIndex: Int, blockCount: Int, bytesSent: Long, bytesTotal: Long) =
|
||||
post { it.onProgress(lens, componentIndex, componentCount, blockIndex, blockCount, bytesSent, bytesTotal) }
|
||||
|
||||
override fun onState(state: String?, detail: String?) = post { it.onState(state, detail ?: "") }
|
||||
|
||||
override fun onComplete(success: Boolean, detail: String?) = post { it.onComplete(success, detail ?: "") }
|
||||
},
|
||||
)
|
||||
|
||||
fun setListener(listener: FaceclawFirmwareFlasherListener?) {
|
||||
lock.withLock { this.listener = listener }
|
||||
}
|
||||
|
||||
fun start() {
|
||||
lock.withLock {
|
||||
if (started) return
|
||||
started = true
|
||||
}
|
||||
runOnThread("faceclaw-flasher") { flow.run() }
|
||||
}
|
||||
|
||||
fun cancel() = flow.cancel()
|
||||
|
||||
fun close() {
|
||||
cancel()
|
||||
runCatching { link.close() }
|
||||
}
|
||||
|
||||
private fun post(action: (FaceclawFirmwareFlasherListener) -> Unit) = main {
|
||||
lock.withLock { listener }?.let(action)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
|
||||
|
||||
package com.faceclaw.app
|
||||
|
||||
import kotlin.concurrent.Volatile
|
||||
|
||||
import kotlinx.cinterop.addressOf
|
||||
import kotlinx.cinterop.convert
|
||||
import kotlinx.cinterop.usePinned
|
||||
import platform.Foundation.NSData
|
||||
import platform.Foundation.NSError
|
||||
import platform.Foundation.NSFileManager
|
||||
import platform.Foundation.NSHTTPURLResponse
|
||||
import platform.Foundation.NSURLResponse
|
||||
import platform.Foundation.NSURLSession
|
||||
import platform.Foundation.NSURLSessionConfiguration
|
||||
import platform.Foundation.NSURLSessionDataDelegateProtocol
|
||||
import platform.Foundation.NSURLSessionDataTask
|
||||
import platform.Foundation.NSURLSessionResponseAllow
|
||||
import platform.Foundation.NSURLSessionResponseDisposition
|
||||
import platform.Foundation.NSURLSessionTask
|
||||
import platform.darwin.NSObject
|
||||
import platform.posix.fclose
|
||||
import platform.posix.fopen
|
||||
import platform.posix.fread
|
||||
import platform.posix.fwrite
|
||||
|
||||
/**
|
||||
* iOS twin of the Android FaceclawModelDownloader: NSURLSession transport and POSIX
|
||||
* storage under the shared [ResumableDownload], run on its own thread with listener
|
||||
* callbacks on the main queue. Same constructor/start/cancel shape as Android.
|
||||
*/
|
||||
class IosModelDownloader internal constructor(
|
||||
url: String,
|
||||
destPath: String,
|
||||
expectedSha256: String?,
|
||||
expectedTotalBytes: Long,
|
||||
listener: FaceclawModelDownloaderListener,
|
||||
dispatch: (() -> Unit) -> Unit,
|
||||
) {
|
||||
constructor(url: String, destPath: String, expectedSha256: String?, expectedTotalBytes: Long, listener: FaceclawModelDownloaderListener) :
|
||||
this(url, destPath, expectedSha256, expectedTotalBytes, listener, ::dispatchToMain)
|
||||
|
||||
private val transport = IosDownloadTransport()
|
||||
private val download: ResumableDownload
|
||||
|
||||
init {
|
||||
val posted = object : FaceclawModelDownloaderListener {
|
||||
override fun onProgress(bytesDownloaded: Long, totalBytes: Long) = dispatch { listener.onProgress(bytesDownloaded, totalBytes) }
|
||||
|
||||
override fun onDone(path: String?) = dispatch { listener.onDone(path) }
|
||||
|
||||
override fun onError(message: String?) = dispatch { listener.onError(message) }
|
||||
}
|
||||
download = ResumableDownload(url, destPath, expectedSha256, expectedTotalBytes, transport, IosDownloadStorage, posted)
|
||||
}
|
||||
|
||||
fun start() = startThread("FaceclawModelDl", true) { download.run() }
|
||||
|
||||
/** Stops the download but keeps the .part file so a later start() resumes. */
|
||||
fun cancel() {
|
||||
download.cancel()
|
||||
transport.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Blocking-read view of an NSURLSession data task: the delegate queues body chunks and the
|
||||
* reader drains them, suspending the task while too much is buffered.
|
||||
*/
|
||||
internal class IosDownloadTransport : DownloadTransport {
|
||||
@Volatile
|
||||
private var current: Session? = null
|
||||
|
||||
fun cancel() {
|
||||
current?.close()
|
||||
}
|
||||
|
||||
override fun open(url: String, rangeFrom: Long): DownloadResponse {
|
||||
val target = parseUrl(url) ?: error("Invalid download URL")
|
||||
val headers = if (rangeFrom > 0) listOf("Range" to "bytes=$rangeFrom-") else emptyList()
|
||||
val request = buildRequest(target, "GET", null, headers)
|
||||
val configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration
|
||||
configuration.timeoutIntervalForRequest = 60.0
|
||||
configuration.timeoutIntervalForResource = 7 * 24 * 3600.0
|
||||
val session = Session()
|
||||
current = session
|
||||
session.start(configuration, request)
|
||||
if (!session.responded.await(30_000)) {
|
||||
session.close()
|
||||
error("download timed out waiting for the server")
|
||||
}
|
||||
session.failure?.let { session.close(); error(it) }
|
||||
return session
|
||||
}
|
||||
|
||||
/** Body reader; NSURLSession callbacks arrive through [Delegate] on the session's queue. */
|
||||
private class Session : DownloadResponse {
|
||||
private val platform = IosProtocolPlatform
|
||||
val responded = Latch(1, platform)
|
||||
private val chunks = BlockingQueue<ByteArray>(platform)
|
||||
private val lock = platform.createLock()
|
||||
private var queuedBytes = 0L
|
||||
private var suspended = false
|
||||
private var pending: ByteArray? = null
|
||||
private var pendingOffset = 0
|
||||
private var ended = false
|
||||
|
||||
@Volatile
|
||||
var failure: String? = null
|
||||
private var session: NSURLSession? = null
|
||||
private var task: NSURLSessionDataTask? = null
|
||||
|
||||
override var code: Int = 0
|
||||
private set
|
||||
|
||||
override var contentLength: Long = -1
|
||||
private set
|
||||
|
||||
fun start(configuration: NSURLSessionConfiguration, request: platform.Foundation.NSURLRequest) {
|
||||
val created = NSURLSession.sessionWithConfiguration(configuration, Delegate(this), delegateQueue = null)
|
||||
session = created
|
||||
task = created.dataTaskWithRequest(request).also { it.resume() }
|
||||
}
|
||||
|
||||
fun onResponse(response: NSURLResponse) {
|
||||
code = (response as? NSHTTPURLResponse)?.statusCode?.toInt() ?: 0
|
||||
contentLength = response.expectedContentLength
|
||||
responded.countDown()
|
||||
}
|
||||
|
||||
fun onData(data: NSData, dataTask: NSURLSessionDataTask) {
|
||||
val bytes = data.byteArray()
|
||||
if (bytes.isEmpty()) return
|
||||
chunks.put(bytes)
|
||||
lock.withLock {
|
||||
queuedBytes += bytes.size
|
||||
if (queuedBytes > HIGH_WATER && !suspended) {
|
||||
suspended = true
|
||||
dataTask.suspend()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun onFinished(error: NSError?) {
|
||||
if (error != null) failure = error.localizedDescription
|
||||
responded.countDown()
|
||||
chunks.put(END)
|
||||
}
|
||||
|
||||
override fun read(buffer: ByteArray): Int {
|
||||
var source = pending
|
||||
if (source == null) {
|
||||
if (ended) return -1
|
||||
val next = chunks.poll(60_000) ?: error("download stalled")
|
||||
if (next === END) {
|
||||
ended = true
|
||||
failure?.let { error(it) }
|
||||
return -1
|
||||
}
|
||||
source = next
|
||||
pendingOffset = 0
|
||||
}
|
||||
val count = minOf(buffer.size, source.size - pendingOffset)
|
||||
source.copyInto(buffer, 0, pendingOffset, pendingOffset + count)
|
||||
pendingOffset += count
|
||||
if (pendingOffset >= source.size) {
|
||||
pending = null
|
||||
lock.withLock {
|
||||
queuedBytes -= source.size
|
||||
if (suspended && queuedBytes < LOW_WATER) {
|
||||
suspended = false
|
||||
task?.resume()
|
||||
}
|
||||
}
|
||||
} else pending = source
|
||||
return count
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
session?.invalidateAndCancel()
|
||||
session = null
|
||||
chunks.put(END)
|
||||
}
|
||||
}
|
||||
|
||||
private class Delegate(private val owner: Session) : NSObject(), NSURLSessionDataDelegateProtocol {
|
||||
override fun URLSession(
|
||||
session: NSURLSession,
|
||||
dataTask: NSURLSessionDataTask,
|
||||
didReceiveResponse: NSURLResponse,
|
||||
completionHandler: (NSURLSessionResponseDisposition) -> Unit,
|
||||
) {
|
||||
owner.onResponse(didReceiveResponse)
|
||||
completionHandler(NSURLSessionResponseAllow)
|
||||
}
|
||||
|
||||
override fun URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData: NSData) =
|
||||
owner.onData(didReceiveData, dataTask)
|
||||
|
||||
override fun URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError: NSError?) {
|
||||
owner.onFinished(didCompleteWithError)
|
||||
session.finishTasksAndInvalidate()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val END = ByteArray(0)
|
||||
private const val HIGH_WATER = 4L * 1024 * 1024
|
||||
private const val LOW_WATER = 1L * 1024 * 1024
|
||||
|
||||
/** POSIX file storage for downloads; multi-GB files stream through fixed buffers. */
|
||||
internal object IosDownloadStorage : DownloadStorage {
|
||||
override fun length(path: String): Long = fileLength(path)
|
||||
|
||||
override fun prepareParent(path: String) {
|
||||
val parent = path.substringBeforeLast('/', "")
|
||||
if (parent.isNotEmpty()) NSFileManager.defaultManager.createDirectoryAtPath(parent, true, null, null)
|
||||
}
|
||||
|
||||
override fun openWrite(path: String, append: Boolean): FileSink {
|
||||
val file = fopen(path, if (append) "ab" else "wb") ?: error("Cannot write $path")
|
||||
return object : FileSink {
|
||||
override fun write(bytes: ByteArray, offset: Int, length: Int) {
|
||||
if (length <= 0) return
|
||||
bytes.usePinned {
|
||||
check(fwrite(it.addressOf(offset), 1u, length.convert(), file) == length.convert<platform.posix.size_t>()) { "Short write to $path" }
|
||||
}
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
fclose(file)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun readAll(path: String, consumer: (ByteArray, Int) -> Boolean): Long {
|
||||
val file = fopen(path, "rb") ?: return 0
|
||||
var consumed = 0L
|
||||
try {
|
||||
val buffer = ByteArray(1 shl 16)
|
||||
while (true) {
|
||||
val read = buffer.usePinned { fread(it.addressOf(0), 1u, buffer.size.convert(), file) }.toInt()
|
||||
if (read <= 0) break
|
||||
if (!consumer(buffer, read)) break
|
||||
consumed += read
|
||||
}
|
||||
} finally {
|
||||
fclose(file)
|
||||
}
|
||||
return consumed
|
||||
}
|
||||
|
||||
override fun rename(from: String, to: String): Boolean = renameFile(from, to)
|
||||
|
||||
override fun delete(path: String): Boolean = deleteFile(path)
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
|
||||
|
||||
package com.faceclaw.app
|
||||
|
||||
import kotlin.concurrent.Volatile
|
||||
|
||||
import kotlinx.cinterop.ByteVar
|
||||
import kotlinx.cinterop.CPointer
|
||||
import kotlinx.cinterop.IntVar
|
||||
import kotlinx.cinterop.addressOf
|
||||
import kotlinx.cinterop.alloc
|
||||
import kotlinx.cinterop.allocArray
|
||||
import kotlinx.cinterop.allocPointerTo
|
||||
import kotlinx.cinterop.CFunction
|
||||
import kotlinx.cinterop.COpaquePointer
|
||||
import kotlinx.cinterop.COpaquePointerVar
|
||||
import kotlinx.cinterop.UIntVar
|
||||
import kotlinx.cinterop.invoke
|
||||
import kotlinx.cinterop.plus
|
||||
import kotlinx.cinterop.convert
|
||||
import kotlinx.cinterop.memScoped
|
||||
import kotlinx.cinterop.pointed
|
||||
import kotlinx.cinterop.ptr
|
||||
import kotlinx.cinterop.reinterpret
|
||||
import kotlinx.cinterop.sizeOf
|
||||
import kotlinx.cinterop.toKString
|
||||
import kotlinx.cinterop.usePinned
|
||||
import kotlinx.cinterop.value
|
||||
import platform.Security.SecRandomCopyBytes
|
||||
import platform.Security.kSecRandomDefault
|
||||
import platform.posix.AF_INET
|
||||
import platform.posix.AF_INET6
|
||||
import platform.posix.AI_NUMERICHOST
|
||||
import platform.posix.AI_NUMERICSERV
|
||||
import platform.posix.IFF_LOOPBACK
|
||||
import platform.posix.IFF_POINTOPOINT
|
||||
import platform.posix.IFF_UP
|
||||
import platform.posix.IPPROTO_TCP
|
||||
import platform.posix.NI_MAXHOST
|
||||
import platform.posix.NI_NUMERICHOST
|
||||
import platform.posix.POLLIN
|
||||
import platform.posix.SHUT_RDWR
|
||||
import platform.posix.SOCK_STREAM
|
||||
import platform.posix.SOL_SOCKET
|
||||
import platform.posix.SO_NOSIGPIPE
|
||||
import platform.posix.SO_REUSEADDR
|
||||
import platform.posix.TCP_NODELAY
|
||||
import platform.posix.accept
|
||||
import platform.posix.addrinfo
|
||||
import platform.posix.bind
|
||||
import platform.posix.close
|
||||
import platform.posix.dlopen
|
||||
import platform.posix.dlsym
|
||||
import platform.posix.RTLD_NOW
|
||||
import platform.posix.freeaddrinfo
|
||||
import platform.posix.getaddrinfo
|
||||
import platform.posix.getnameinfo
|
||||
import platform.posix.listen
|
||||
import platform.posix.poll
|
||||
import platform.posix.pollfd
|
||||
import platform.posix.recv
|
||||
import platform.posix.send
|
||||
import platform.posix.setsockopt
|
||||
import platform.posix.shutdown
|
||||
import platform.posix.sockaddr
|
||||
import platform.posix.socket
|
||||
|
||||
/** Numeric host text of a socket address, or null when it is not IPv4/IPv6. */
|
||||
private fun numericHost(address: CPointer<sockaddr>?): String? {
|
||||
if (address == null) return null
|
||||
val family = address.pointed.sa_family.toInt()
|
||||
if (family != AF_INET && family != AF_INET6) return null
|
||||
return memScoped {
|
||||
val host = allocArray<ByteVar>(NI_MAXHOST)
|
||||
val status = getnameinfo(address, address.pointed.sa_len.convert(), host, NI_MAXHOST.convert(), null, 0u, NI_NUMERICHOST)
|
||||
if (status != 0) null else host.toKString()
|
||||
}
|
||||
}
|
||||
|
||||
// Kotlin/Native's POSIX library for iOS does not bind <ifaddrs.h>, so the two functions are
|
||||
// resolved from libSystem at runtime and `struct ifaddrs` is read by its fixed 64-bit layout:
|
||||
// ifa_next @0, ifa_name @8, ifa_flags @16, ifa_addr @24 (netmask @32, dstaddr @40, data @48).
|
||||
private typealias GetIfAddrs = CFunction<(CPointer<COpaquePointerVar>) -> Int>
|
||||
private typealias FreeIfAddrs = CFunction<(COpaquePointer?) -> Unit>
|
||||
|
||||
private val libSystem: COpaquePointer? by lazy { dlopen(null, RTLD_NOW) }
|
||||
|
||||
private fun CPointer<*>.pointerField(offset: Int): COpaquePointer? =
|
||||
(this.reinterpret<ByteVar>() + offset)!!.reinterpret<COpaquePointerVar>().pointed.value
|
||||
|
||||
private fun CPointer<*>.uintField(offset: Int): UInt =
|
||||
(this.reinterpret<ByteVar>() + offset)!!.reinterpret<UIntVar>().pointed.value
|
||||
|
||||
/** Every address assigned to a local interface, as the shared session's [InterfaceAddress]. */
|
||||
fun iosInterfaceAddresses(): List<InterfaceAddress> {
|
||||
val result = ArrayList<InterfaceAddress>()
|
||||
val getifaddrs = dlsym(libSystem, "getifaddrs")?.reinterpret<GetIfAddrs>() ?: return result
|
||||
val freeifaddrs = dlsym(libSystem, "freeifaddrs")?.reinterpret<FreeIfAddrs>() ?: return result
|
||||
memScoped {
|
||||
val list = alloc<COpaquePointerVar>()
|
||||
if (getifaddrs(list.ptr) != 0) return result
|
||||
try {
|
||||
var item: COpaquePointer? = list.value
|
||||
while (item != null) {
|
||||
val host = numericHost(item.pointerField(24)?.reinterpret())
|
||||
if (host != null) {
|
||||
val flags = item.uintField(16).toInt()
|
||||
val bare = host.substringBefore('%')
|
||||
val loopbackFlag = flags and IFF_LOOPBACK != 0
|
||||
result.add(InterfaceAddress(
|
||||
interfaceName = item.pointerField(8)?.reinterpret<ByteVar>()?.toKString() ?: "",
|
||||
address = host,
|
||||
up = flags and IFF_UP != 0,
|
||||
pointToPoint = flags and IFF_POINTOPOINT != 0,
|
||||
loopback = loopbackFlag || bare.startsWith("127.") || bare == "::1",
|
||||
linkLocal = bare.startsWith("169.254.") || bare.lowercase().startsWith("fe80:"),
|
||||
anyLocal = bare == "0.0.0.0" || bare == "::",
|
||||
))
|
||||
}
|
||||
item = item.pointerField(0)
|
||||
}
|
||||
} finally {
|
||||
freeifaddrs(list.value)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private fun setIntOption(fd: Int, level: Int, option: Int, value: Int) {
|
||||
memScoped {
|
||||
val holder = alloc<IntVar>()
|
||||
holder.value = value
|
||||
setsockopt(fd, level, option, holder.ptr, sizeOf<IntVar>().convert())
|
||||
}
|
||||
}
|
||||
|
||||
/** Canonical numeric text of a literal address, or null when it is not a literal. */
|
||||
private fun canonicalAddress(address: String): String? =
|
||||
memScoped {
|
||||
val hints = alloc<addrinfo>()
|
||||
hints.ai_flags = AI_NUMERICHOST
|
||||
hints.ai_socktype = SOCK_STREAM
|
||||
val resolved = allocPointerTo<addrinfo>()
|
||||
if (getaddrinfo(address, null, hints.ptr, resolved.ptr) != 0) return null
|
||||
try {
|
||||
numericHost(resolved.value?.pointed?.ai_addr)
|
||||
} finally {
|
||||
freeaddrinfo(resolved.value)
|
||||
}
|
||||
}
|
||||
|
||||
/** POSIX sockets for the shared [RemoteInputSession]. */
|
||||
object IosLocalServerPort : LocalServerPort {
|
||||
override fun isLocalUnicastAddress(address: String): Boolean {
|
||||
val canonical = canonicalAddress(address) ?: return false
|
||||
// Wildcard and multicast addresses are never assigned to an interface.
|
||||
return iosInterfaceAddresses().any { it.address == canonical || it.address.substringBefore('%') == canonical }
|
||||
}
|
||||
|
||||
override fun bind(address: String, port: Int): RemoteInputListener {
|
||||
val fd = memScoped {
|
||||
val hints = alloc<addrinfo>()
|
||||
hints.ai_flags = AI_NUMERICHOST or AI_NUMERICSERV
|
||||
hints.ai_socktype = SOCK_STREAM
|
||||
val resolved = allocPointerTo<addrinfo>()
|
||||
if (getaddrinfo(address, port.toString(), hints.ptr, resolved.ptr) != 0) error("Invalid address")
|
||||
try {
|
||||
val info = resolved.value!!.pointed
|
||||
val socketFd = socket(info.ai_family, SOCK_STREAM, 0)
|
||||
if (socketFd < 0) error("socket failed")
|
||||
setIntOption(socketFd, SOL_SOCKET, SO_REUSEADDR, 1)
|
||||
if (bind(socketFd, info.ai_addr, info.ai_addrlen) != 0 || listen(socketFd, 8) != 0) {
|
||||
close(socketFd)
|
||||
error("bind failed")
|
||||
}
|
||||
socketFd
|
||||
} finally {
|
||||
freeaddrinfo(resolved.value)
|
||||
}
|
||||
}
|
||||
return PosixListener(fd)
|
||||
}
|
||||
}
|
||||
|
||||
private class PosixListener(private val fd: Int) : RemoteInputListener {
|
||||
@Volatile
|
||||
private var closed = false
|
||||
|
||||
override val isClosed: Boolean
|
||||
get() = closed
|
||||
|
||||
override fun accept(): RemoteInputConnection? {
|
||||
while (!closed) {
|
||||
// Polling also guarantees close() is observed where shutdown does not wake accept.
|
||||
val ready = memScoped {
|
||||
val request = alloc<pollfd>()
|
||||
request.fd = fd
|
||||
request.events = POLLIN.toShort()
|
||||
poll(request.ptr, 1u, 250)
|
||||
}
|
||||
if (closed) return null
|
||||
if (ready <= 0) continue
|
||||
val client = accept(fd, null, null)
|
||||
if (client < 0) return null
|
||||
setIntOption(client, SOL_SOCKET, SO_NOSIGPIPE, 1)
|
||||
setIntOption(client, IPPROTO_TCP, TCP_NODELAY, 1)
|
||||
return PosixConnection(client)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
if (closed) return
|
||||
closed = true
|
||||
shutdown(fd, SHUT_RDWR)
|
||||
close(fd)
|
||||
}
|
||||
}
|
||||
|
||||
private class PosixConnection(private val fd: Int) : RemoteInputConnection {
|
||||
@Volatile
|
||||
private var closed = false
|
||||
|
||||
override fun readByte(timeoutMs: Long): Int {
|
||||
if (closed) return -1
|
||||
return memScoped {
|
||||
val request = alloc<pollfd>()
|
||||
request.fd = fd
|
||||
request.events = POLLIN.toShort()
|
||||
if (poll(request.ptr, 1u, timeoutMs.coerceIn(0L, Int.MAX_VALUE.toLong()).toInt()) <= 0) return -1
|
||||
val byte = alloc<ByteVar>()
|
||||
if (recv(fd, byte.ptr, 1u, 0) != 1L) -1 else byte.value.toInt() and 0xff
|
||||
}
|
||||
}
|
||||
|
||||
override fun write(bytes: ByteArray) {
|
||||
if (bytes.isEmpty() || closed) return
|
||||
bytes.usePinned { pinned ->
|
||||
var offset = 0
|
||||
while (offset < bytes.size) {
|
||||
val sent = send(fd, pinned.addressOf(offset), (bytes.size - offset).convert(), 0)
|
||||
if (sent <= 0L) error("send failed")
|
||||
offset += sent.toInt()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
if (closed) return
|
||||
closed = true
|
||||
shutdown(fd, SHUT_RDWR)
|
||||
close(fd)
|
||||
}
|
||||
}
|
||||
|
||||
/** Cryptographically secure bytes from the Security framework. */
|
||||
object IosSecureRandom : RandomSource {
|
||||
override fun nextBytes(count: Int): ByteArray {
|
||||
val bytes = ByteArray(count)
|
||||
if (count == 0) return bytes
|
||||
val status = bytes.usePinned { SecRandomCopyBytes(kSecRandomDefault, count.convert(), it.addressOf(0)) }
|
||||
check(status == 0) { "SecRandomCopyBytes failed: $status" }
|
||||
return bytes
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
import platform.darwin.dispatch_async
|
||||
import platform.darwin.dispatch_get_main_queue
|
||||
|
||||
/** Runs [action] on the main queue, where NativeScript's JavaScript lives. */
|
||||
internal fun dispatchToMain(action: () -> Unit) {
|
||||
dispatch_async(dispatch_get_main_queue()) { action() }
|
||||
}
|
||||
|
||||
/**
|
||||
* iOS facade over the shared [RemoteInputSession] for the TypeScript side
|
||||
* (app/native/remote-input.ios.ts): POSIX sockets, Security-framework randomness and
|
||||
* main-queue request notifications. Mirrors the Android FaceclawRemoteInput API.
|
||||
*/
|
||||
class IosRemoteInput internal constructor(
|
||||
dispatch: (() -> Unit) -> Unit,
|
||||
requestTimeoutMs: Long,
|
||||
) {
|
||||
constructor() : this(::dispatchToMain, RemoteInputSession.REQUEST_TIMEOUT_MS)
|
||||
|
||||
private val session = RemoteInputSession(
|
||||
port = IosLocalServerPort,
|
||||
random = IosSecureRandom,
|
||||
dispatch = dispatch,
|
||||
platform = IosProtocolPlatform,
|
||||
requestTimeoutMs = requestTimeoutMs,
|
||||
)
|
||||
|
||||
/** Called (on the main queue) whenever a request is waiting in [nextRequest]. */
|
||||
fun setRequestListener(listener: (() -> Unit)?) = session.setRequestListener(listener)
|
||||
|
||||
fun start(port: Int): String = startAddress(port, "127.0.0.1")
|
||||
|
||||
/** Returns "" on success or a user-facing error. */
|
||||
fun startAddress(port: Int, address: String): String = session.start(port, address)
|
||||
|
||||
fun stop() = session.stop()
|
||||
|
||||
fun nextRequest(): String? = session.nextRequest()
|
||||
|
||||
fun complete(id: Long, value: String?) = session.complete(id, value)
|
||||
|
||||
fun randomSecret(): String = session.randomSecret()
|
||||
|
||||
fun tokenDigest(value: String): String = RemoteInputSession.tokenHash(value)
|
||||
|
||||
/** JSON array of {name, address, pointToPoint} for the reachable local interfaces. */
|
||||
fun interfaces(): String = RemoteInputSession.interfacesJson(iosInterfaceAddresses())
|
||||
|
||||
companion object {
|
||||
val shared: IosRemoteInput by lazy { IosRemoteInput() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
import kotlin.concurrent.Volatile
|
||||
|
||||
import platform.Foundation.NSRecursiveLock
|
||||
import platform.UIKit.UIApplication
|
||||
import platform.UIKit.UIBackgroundTaskIdentifier
|
||||
import platform.UIKit.UIBackgroundTaskInvalid
|
||||
|
||||
/**
|
||||
* iOS twin of the Android FaceclawSseRequest for app/native/sse.ios.ts: starts a streaming
|
||||
* POST immediately and pushes the shared [SseStream] events to [listener] on the main queue,
|
||||
* in order. A UIKit background task keeps the stream alive while the app is backgrounded.
|
||||
* headersJson is a JSON object of header name to value.
|
||||
*/
|
||||
class IosSseRequest internal constructor(
|
||||
url: String,
|
||||
body: String,
|
||||
headersJson: String?,
|
||||
private val listener: FaceclawSseListener,
|
||||
private val dispatch: (() -> Unit) -> Unit,
|
||||
keepAliveInBackground: Boolean,
|
||||
) {
|
||||
constructor(url: String, body: String, headersJson: String?, listener: FaceclawSseListener) :
|
||||
this(url, body, headersJson, listener, ::dispatchToMain, true)
|
||||
|
||||
private val stream = SseStream()
|
||||
private val lock = NSRecursiveLock()
|
||||
private var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
|
||||
private var keepAlive = keepAliveInBackground
|
||||
|
||||
@Volatile
|
||||
private var cancelled = false
|
||||
private val transfer: Cancellable
|
||||
|
||||
init {
|
||||
val headers = ArrayList<Pair<String, String>>()
|
||||
if (!headersJson.isNullOrBlank()) {
|
||||
runCatching { Json.parse(headersJson).asObject() }.getOrNull()?.forEach { (name, value) ->
|
||||
val text = value.asString()
|
||||
if (name.isNotEmpty() && text != null) headers.add(name to text)
|
||||
}
|
||||
}
|
||||
if (keepAlive) dispatchToMain { beginBackgroundTask() }
|
||||
val sink = object : ChunkSink {
|
||||
override fun onStatus(code: Int) = stream.onStatus(code)
|
||||
|
||||
override fun onChunk(bytes: ByteArray, offset: Int, length: Int) {
|
||||
stream.onChunk(bytes, offset, length)
|
||||
drain()
|
||||
}
|
||||
|
||||
override fun onComplete() {
|
||||
stream.onComplete()
|
||||
drain()
|
||||
}
|
||||
|
||||
override fun onFailure(message: String) {
|
||||
stream.onFailure(message)
|
||||
drain()
|
||||
}
|
||||
}
|
||||
transfer = IosStreamingHttp.post(url.trim(), body, headers, sink)
|
||||
}
|
||||
|
||||
fun cancel() {
|
||||
cancelled = true
|
||||
stream.cancel()
|
||||
transfer.cancel()
|
||||
if (keepAlive) dispatchToMain { endBackgroundTask() }
|
||||
}
|
||||
|
||||
/** Hands every queued event to the listener on the main queue, in order. */
|
||||
private fun drain() {
|
||||
val events = stream.takeEvents()
|
||||
if (events.isEmpty()) return
|
||||
dispatch {
|
||||
for (event in events) {
|
||||
if (cancelled) return@dispatch
|
||||
try {
|
||||
SseStream.deliver(event, listener)
|
||||
} catch (t: Throwable) {
|
||||
PlatformLog.w(TAG, "listener callback failed: ${t.message}")
|
||||
}
|
||||
}
|
||||
if (stream.isFinished && keepAlive) endBackgroundTask()
|
||||
}
|
||||
}
|
||||
|
||||
// Main queue only.
|
||||
private fun beginBackgroundTask() {
|
||||
lock.lock()
|
||||
try {
|
||||
if (cancelled || stream.isFinished || backgroundTask != UIBackgroundTaskInvalid) return
|
||||
backgroundTask = UIApplication.sharedApplication.beginBackgroundTaskWithName("Assistant response") {
|
||||
stream.onFailure("iOS background time expired. Open Faceclaw and retry.")
|
||||
drain()
|
||||
endBackgroundTask()
|
||||
}
|
||||
} finally {
|
||||
lock.unlock()
|
||||
}
|
||||
}
|
||||
|
||||
private fun endBackgroundTask() {
|
||||
lock.lock()
|
||||
try {
|
||||
if (backgroundTask == UIBackgroundTaskInvalid) return
|
||||
UIApplication.sharedApplication.endBackgroundTask(backgroundTask)
|
||||
backgroundTask = UIBackgroundTaskInvalid
|
||||
} finally {
|
||||
lock.unlock()
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "FaceclawSseRequest"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
|
||||
|
||||
package com.faceclaw.app
|
||||
|
||||
import kotlin.concurrent.Volatile
|
||||
|
||||
import platform.Foundation.NSData
|
||||
import platform.Foundation.NSError
|
||||
import platform.Foundation.NSHTTPURLResponse
|
||||
import platform.Foundation.NSMutableURLRequest
|
||||
import platform.Foundation.NSString
|
||||
import platform.Foundation.NSURL
|
||||
import platform.Foundation.NSURLRequest
|
||||
import platform.Foundation.NSURLResponse
|
||||
import platform.Foundation.NSURLSession
|
||||
import platform.Foundation.NSURLSessionConfiguration
|
||||
import platform.Foundation.NSURLSessionDataDelegateProtocol
|
||||
import platform.Foundation.NSURLSessionDataTask
|
||||
import platform.Foundation.NSURLSessionResponseAllow
|
||||
import platform.Foundation.NSURLSessionResponseDisposition
|
||||
import platform.Foundation.NSURLSessionTask
|
||||
import platform.Foundation.NSUTF8StringEncoding
|
||||
import platform.Foundation.create
|
||||
import platform.Foundation.dataUsingEncoding
|
||||
import platform.Foundation.setHTTPBody
|
||||
import platform.Foundation.setHTTPMethod
|
||||
import platform.Foundation.setValue
|
||||
import platform.darwin.NSObject
|
||||
|
||||
/** Builds an NSURLRequest with the shared User-Agent unless the caller supplied one. */
|
||||
internal fun buildRequest(url: NSURL, method: String, body: String?, headers: List<Pair<String, String>>): NSMutableURLRequest {
|
||||
val request = NSMutableURLRequest.requestWithURL(url)
|
||||
request.setHTTPMethod(method)
|
||||
if (body != null) request.setHTTPBody((body as NSString).dataUsingEncoding(NSUTF8StringEncoding))
|
||||
var hasUserAgent = false
|
||||
for ((name, value) in headers) {
|
||||
if (name.equals("User-Agent", ignoreCase = true)) hasUserAgent = true
|
||||
request.setValue(value, forHTTPHeaderField = name)
|
||||
}
|
||||
if (!hasUserAgent) request.setValue(HttpIdentity.getUserAgent(), forHTTPHeaderField = "User-Agent")
|
||||
return request
|
||||
}
|
||||
|
||||
internal fun parseUrl(url: String): NSURL? {
|
||||
val target = NSURL.URLWithString(url) ?: return null
|
||||
val scheme = target.scheme?.lowercase() ?: return null
|
||||
return if (scheme == "https" || scheme == "http") target else null
|
||||
}
|
||||
|
||||
/**
|
||||
* Streaming POST over NSURLSession for the shared [SseStream]. Redirects are refused so
|
||||
* provider credentials in the headers are never forwarded; a 3xx reaches the sink as a
|
||||
* status with an (empty) body. Delegate callbacks arrive on NSURLSession's own queue.
|
||||
*/
|
||||
internal object IosStreamingHttp : StreamingHttp {
|
||||
override fun post(url: String, body: String, headers: List<Pair<String, String>>, sink: ChunkSink): Cancellable {
|
||||
val target = parseUrl(url)
|
||||
if (target == null) {
|
||||
sink.onFailure("Invalid streaming URL")
|
||||
return object : Cancellable { override fun cancel() {} }
|
||||
}
|
||||
val request = buildRequest(target, "POST", body, listOf("Content-Type" to "application/json; charset=utf-8", "Accept" to "text/event-stream") + headers)
|
||||
val configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration
|
||||
configuration.timeoutIntervalForRequest = 180.0
|
||||
configuration.timeoutIntervalForResource = 180.0
|
||||
val delegate = StreamingDelegate(sink)
|
||||
val session = NSURLSession.sessionWithConfiguration(configuration, delegate, delegateQueue = null)
|
||||
val task = session.dataTaskWithRequest(request)
|
||||
task.resume()
|
||||
return object : Cancellable {
|
||||
override fun cancel() {
|
||||
delegate.cancelled = true
|
||||
session.invalidateAndCancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class StreamingDelegate(private val sink: ChunkSink) : NSObject(), NSURLSessionDataDelegateProtocol {
|
||||
@Volatile
|
||||
var cancelled = false
|
||||
|
||||
override fun URLSession(
|
||||
session: NSURLSession,
|
||||
dataTask: NSURLSessionDataTask,
|
||||
didReceiveResponse: NSURLResponse,
|
||||
completionHandler: (NSURLSessionResponseDisposition) -> Unit,
|
||||
) {
|
||||
val code = (didReceiveResponse as? NSHTTPURLResponse)?.statusCode?.toInt() ?: 0
|
||||
if (!cancelled) sink.onStatus(code)
|
||||
completionHandler(NSURLSessionResponseAllow)
|
||||
}
|
||||
|
||||
override fun URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData: NSData) {
|
||||
if (cancelled) return
|
||||
val bytes = didReceiveData.byteArray()
|
||||
sink.onChunk(bytes, 0, bytes.size)
|
||||
}
|
||||
|
||||
override fun URLSession(
|
||||
session: NSURLSession,
|
||||
task: NSURLSessionTask,
|
||||
willPerformHTTPRedirection: NSHTTPURLResponse,
|
||||
newRequest: NSURLRequest,
|
||||
completionHandler: (NSURLRequest?) -> Unit,
|
||||
) {
|
||||
// Never forward provider credentials to a redirected endpoint.
|
||||
completionHandler(null)
|
||||
}
|
||||
|
||||
override fun URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError: NSError?) {
|
||||
if (cancelled) return
|
||||
if (didCompleteWithError != null) sink.onFailure(didCompleteWithError.localizedDescription)
|
||||
else sink.onComplete()
|
||||
session.finishTasksAndInvalidate()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user