diff --git a/App_Resources/iOS/src/FaceclawBluetooth.h b/App_Resources/iOS/src/FaceclawBluetooth.h deleted file mode 100644 index e59bf88c..00000000 --- a/App_Resources/iOS/src/FaceclawBluetooth.h +++ /dev/null @@ -1,14 +0,0 @@ -#import -#import - -/** Main-queue CoreBluetooth adapter. Protocol and MAC matching live in TS. */ -@interface FaceclawBluetooth : NSObject -@property (nonatomic, copy) void (^eventHandler)(NSString *json); -- (void)initializeBluetooth; -- (void)scan:(BOOL)enabled; -- (void)connect:(NSString *)identifier requestId:(NSInteger)requestId; -- (void)connect:(NSString *)identifier requiresANCS:(BOOL)requiresANCS requestId:(NSInteger)requestId; -- (void)subscribe:(NSString *)identifier characteristic:(NSString *)uuid requestId:(NSInteger)requestId; -- (void)write:(NSString *)identifier characteristic:(NSString *)uuid data:(NSData *)data requestId:(NSInteger)requestId; -- (void)disconnect:(NSString *)identifier; -@end diff --git a/App_Resources/iOS/src/FaceclawBluetooth.m b/App_Resources/iOS/src/FaceclawBluetooth.m deleted file mode 100644 index 6ba03e75..00000000 --- a/App_Resources/iOS/src/FaceclawBluetooth.m +++ /dev/null @@ -1,197 +0,0 @@ -#import "FaceclawBluetooth.h" - -@interface FCBPeripheral : NSObject -@property (nonatomic, strong) CBPeripheral *peripheral; -@property (nonatomic, strong) NSMutableDictionary *characteristics; -@property (nonatomic, strong) NSMutableDictionary *subscriptions; -@property (nonatomic, strong) NSMutableArray *writes; -@property (nonatomic, strong) NSNumber *connectRequest; -@property (nonatomic) NSInteger pendingServices; -@property (nonatomic) BOOL awaitingWriteResponse; -@end -@implementation FCBPeripheral -- (instancetype)init { - if ((self = [super init])) { - _characteristics = [NSMutableDictionary new]; _subscriptions = [NSMutableDictionary new]; - _writes = [NSMutableArray new]; - } - return self; -} -@end - -@interface FaceclawBluetooth () -@property (nonatomic, strong) CBCentralManager *central; -@property (nonatomic, strong) NSMutableDictionary *peers; -@property (nonatomic) BOOL scanRequested; -@end - -@implementation FaceclawBluetooth -- (instancetype)init { if ((self = [super init])) _peers = [NSMutableDictionary new]; return self; } -- (void)emit:(NSDictionary *)event { - if (!self.eventHandler) return; - NSData *data = [NSJSONSerialization dataWithJSONObject:event options:0 error:nil]; - if (data) self.eventHandler([[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); -} -- (void)complete:(NSNumber *)request error:(NSString *)error details:(NSDictionary *)details { - if (!request) return; - NSMutableDictionary *event = [@{ @"kind": @"completion", @"id": request } mutableCopy]; - if (error) event[@"error"] = error; - if (details) event[@"details"] = details; - [self emit:event]; -} -- (void)initializeBluetooth { - if (!self.central) self.central = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()]; - else [self centralManagerDidUpdateState:self.central]; -} -- (void)scan:(BOOL)enabled { - self.scanRequested = enabled; - if (!enabled) { [self.central stopScan]; return; } - [self initializeBluetooth]; - if (self.central.state == CBManagerStatePoweredOn) - [self.central scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey: @YES}]; -} -- (void)centralManagerDidUpdateState:(CBCentralManager *)central { - [self emit:@{@"kind": @"state", @"state": @(central.state), @"authorization": @(CBManager.authorization)}]; - if (central.state != CBManagerStatePoweredOn) { - for (FCBPeripheral *peer in self.peers.allValues) [self failPeer:peer reason:@"Bluetooth is unavailable"]; - } else if (self.scanRequested) { - [central scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey: @YES}]; - } -} -- (FCBPeripheral *)remember:(CBPeripheral *)peripheral { - NSString *identifier = peripheral.identifier.UUIDString; - FCBPeripheral *peer = self.peers[identifier]; - if (!peer) { peer = [FCBPeripheral new]; peer.peripheral = peripheral; self.peers[identifier] = peer; } - peripheral.delegate = self; - return peer; -} -- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisement RSSI:(NSNumber *)RSSI { - [self remember:peripheral]; - NSData *data = advertisement[CBAdvertisementDataManufacturerDataKey]; - NSMutableString *hex = [NSMutableString new]; - const uint8_t *bytes = data.bytes; - for (NSUInteger i = 0; i < data.length; i++) [hex appendFormat:@"%02x", bytes[i]]; - [self emit:@{@"kind": @"advertisement", @"identifier": peripheral.identifier.UUIDString, - @"name": advertisement[CBAdvertisementDataLocalNameKey] ?: peripheral.name ?: @"", - @"manufacturerData": hex, @"rssi": RSSI, - @"connectable": advertisement[CBAdvertisementDataIsConnectable] ?: @YES}]; -} -- (void)connect:(NSString *)identifier requestId:(NSInteger)requestId { - [self connect:identifier requiresANCS:NO requestId:requestId]; -} -- (void)connect:(NSString *)identifier requiresANCS:(BOOL)requiresANCS requestId:(NSInteger)requestId { - if (self.central.state != CBManagerStatePoweredOn) { [self complete:@(requestId) error:@"Bluetooth is not ready" details:nil]; return; } - FCBPeripheral *peer = self.peers[identifier.uppercaseString]; - if (!peer) { - NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:identifier]; - CBPeripheral *peripheral = uuid ? [self.central retrievePeripheralsWithIdentifiers:@[uuid]].firstObject : nil; - if (peripheral) peer = [self remember:peripheral]; - } - if (!peer) { [self complete:@(requestId) error:@"Peripheral is unknown; scan for the device first" details:nil]; return; } - if (peer.connectRequest || peer.peripheral.state != CBPeripheralStateDisconnected) { - [self complete:@(requestId) error:@"Peripheral is already connecting or connected" details:nil]; return; - } - [peer.characteristics removeAllObjects]; peer.connectRequest = @(requestId); - [self.central connectPeripheral:peer.peripheral options:requiresANCS ? @{CBConnectPeripheralOptionRequiresANCS: @YES} : nil]; -} -- (void)centralManager:(CBCentralManager *)central didUpdateANCSAuthorizationForPeripheral:(CBPeripheral *)peripheral { - [self emit:@{@"kind": @"ancs-authorization", @"identifier": peripheral.identifier.UUIDString, - @"authorized": @(peripheral.ancsAuthorized)}]; -} -- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral { - [peripheral discoverServices:nil]; -} -- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error { - [self failPeer:[self remember:peripheral] reason:error.localizedDescription ?: @"Connection failed"]; -} -- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error { - [self failPeer:[self remember:peripheral] reason:error.localizedDescription ?: @"Disconnected"]; -} -- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error { - FCBPeripheral *peer = [self remember:peripheral]; - if (error || !peripheral.services.count) { [self failPeer:peer reason:error.localizedDescription ?: @"No services found"]; return; } - peer.pendingServices = peripheral.services.count; - for (CBService *service in peripheral.services) [peripheral discoverCharacteristics:nil forService:service]; -} -- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error { - FCBPeripheral *peer = [self remember:peripheral]; - if (!peer.connectRequest) return; - if (error) { [self failPeer:peer reason:error.localizedDescription]; return; } - for (CBCharacteristic *characteristic in service.characteristics) peer.characteristics[characteristic.UUID.UUIDString.lowercaseString] = characteristic; - if (--peer.pendingServices == 0) { - NSNumber *request = peer.connectRequest; peer.connectRequest = nil; - [self complete:request error:nil details:@{@"characteristics": peer.characteristics.allKeys, - @"maxWrite": @([peripheral maximumWriteValueLengthForType:CBCharacteristicWriteWithoutResponse])}]; - } -} -- (void)subscribe:(NSString *)identifier characteristic:(NSString *)uuid requestId:(NSInteger)requestId { - FCBPeripheral *peer = self.peers[identifier.uppercaseString]; - CBCharacteristic *characteristic = peer.characteristics[uuid.lowercaseString]; - if (!characteristic || !(characteristic.properties & (CBCharacteristicPropertyNotify | CBCharacteristicPropertyIndicate))) { - [self complete:@(requestId) error:@"Notification characteristic is unavailable" details:nil]; return; - } - if (characteristic.isNotifying) { [self complete:@(requestId) error:nil details:nil]; return; } - if (peer.subscriptions[uuid.lowercaseString]) { [self complete:@(requestId) error:@"Subscription already pending" details:nil]; return; } - peer.subscriptions[uuid.lowercaseString] = @(requestId); - [peer.peripheral setNotifyValue:YES forCharacteristic:characteristic]; -} -- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error { - FCBPeripheral *peer = [self remember:peripheral]; NSString *key = characteristic.UUID.UUIDString.lowercaseString; - NSNumber *request = peer.subscriptions[key]; [peer.subscriptions removeObjectForKey:key]; - [self complete:request error:error.localizedDescription ?: (characteristic.isNotifying ? nil : @"Notifications not enabled") details:nil]; -} -- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error { - if (error) { [self emit:@{@"kind": @"error", @"message": error.localizedDescription}]; return; } - NSMutableString *hex = [NSMutableString new]; NSData *data = characteristic.value; const uint8_t *bytes = data.bytes; - for (NSUInteger i = 0; i < data.length; i++) [hex appendFormat:@"%02x", bytes[i]]; - [self emit:@{@"kind": @"notification", @"identifier": peripheral.identifier.UUIDString, - @"characteristic": characteristic.UUID.UUIDString.lowercaseString, @"data": hex}]; -} -- (void)write:(NSString *)identifier characteristic:(NSString *)uuid data:(NSData *)data requestId:(NSInteger)requestId { - FCBPeripheral *peer = self.peers[identifier.uppercaseString]; - CBCharacteristic *characteristic = peer.characteristics[uuid.lowercaseString]; - if (!characteristic || peer.peripheral.state != CBPeripheralStateConnected) { - [self complete:@(requestId) error:@"Write characteristic is disconnected or unavailable" details:nil]; return; - } - CBCharacteristicWriteType type = (characteristic.properties & CBCharacteristicPropertyWriteWithoutResponse) - ? CBCharacteristicWriteWithoutResponse : CBCharacteristicWriteWithResponse; - if (!(characteristic.properties & (CBCharacteristicPropertyWriteWithoutResponse | CBCharacteristicPropertyWrite)) || - data.length > [peer.peripheral maximumWriteValueLengthForType:type]) { - [self complete:@(requestId) error:@"Write exceeds the negotiated BLE payload size or is unsupported" details:nil]; return; - } - if (peer.writes.count >= 256) { [self complete:@(requestId) error:@"Bluetooth write queue is full" details:nil]; return; } - [peer.writes addObject:@{@"id": @(requestId), @"characteristic": characteristic, @"data": [data copy], @"type": @(type)}]; - [self drain:peer]; -} -- (void)drain:(FCBPeripheral *)peer { - while (peer.writes.count && !peer.awaitingWriteResponse && peer.peripheral.state == CBPeripheralStateConnected) { - NSDictionary *write = peer.writes.firstObject; - CBCharacteristicWriteType type = [write[@"type"] integerValue]; - if (type == CBCharacteristicWriteWithoutResponse && !peer.peripheral.canSendWriteWithoutResponse) return; - if (type == CBCharacteristicWriteWithResponse) peer.awaitingWriteResponse = YES; - [peer.peripheral writeValue:write[@"data"] forCharacteristic:write[@"characteristic"] type:type]; - if (peer.awaitingWriteResponse) return; - [peer.writes removeObjectAtIndex:0]; [self complete:write[@"id"] error:nil details:nil]; - } -} -- (void)peripheralIsReadyToSendWriteWithoutResponse:(CBPeripheral *)peripheral { [self drain:[self remember:peripheral]]; } -- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error { - FCBPeripheral *peer = [self remember:peripheral]; - if (!peer.awaitingWriteResponse || !peer.writes.count) return; - NSDictionary *write = peer.writes.firstObject; [peer.writes removeObjectAtIndex:0]; peer.awaitingWriteResponse = NO; - [self complete:write[@"id"] error:error.localizedDescription details:nil]; [self drain:peer]; -} -- (void)failPeer:(FCBPeripheral *)peer reason:(NSString *)reason { - if (!peer) return; - NSNumber *connect = peer.connectRequest; peer.connectRequest = nil; - [self complete:connect error:reason details:nil]; - NSArray *subscriptions = peer.subscriptions.allValues; [peer.subscriptions removeAllObjects]; - NSArray *writes = [peer.writes copy]; [peer.writes removeAllObjects]; peer.awaitingWriteResponse = NO; - for (NSNumber *request in subscriptions) [self complete:request error:reason details:nil]; - for (NSDictionary *write in writes) [self complete:write[@"id"] error:reason details:nil]; - [peer.characteristics removeAllObjects]; - if (peer.peripheral.state != CBPeripheralStateDisconnected) [self.central cancelPeripheralConnection:peer.peripheral]; - [self emit:@{@"kind": @"disconnected", @"identifier": peer.peripheral.identifier.UUIDString, @"message": reason}]; -} -- (void)disconnect:(NSString *)identifier { [self failPeer:self.peers[identifier.uppercaseString] reason:@"Disconnected"]; } -@end diff --git a/App_Resources/iOS/src/FaceclawRemoteInput.h b/App_Resources/iOS/src/FaceclawRemoteInput.h deleted file mode 100644 index 4a5708f4..00000000 --- a/App_Resources/iOS/src/FaceclawRemoteInput.h +++ /dev/null @@ -1,13 +0,0 @@ -#import -@interface FaceclawRemoteInput : NSObject -+ (instancetype)shared; -+ (NSString *)interfaces; -- (NSString *)start:(int)port; -- (NSString *)start:(int)port address:(NSString *)address; -- (void)stop; -- (void)setRequestListener:(void (^)(void))listener; -- (NSString *)nextRequest; -- (void)complete:(long long)identifier response:(NSString *)response; -- (NSString *)randomSecret; -- (NSString *)tokenDigest:(NSString *)value; -@end diff --git a/App_Resources/iOS/src/FaceclawRemoteInput.m b/App_Resources/iOS/src/FaceclawRemoteInput.m deleted file mode 100644 index b7e73446..00000000 --- a/App_Resources/iOS/src/FaceclawRemoteInput.m +++ /dev/null @@ -1,166 +0,0 @@ -#import "FaceclawRemoteInput.h" -#import "FaceclawCrypto.h" -#import -#import -#import -#import -#import -#import -#import -#import -#import - -@implementation FaceclawRemoteInput { - NSCondition *_condition; - int _server, _client; - NSUInteger _generation; - long long _nextId, _requestId; - NSTimeInterval _deadline; - NSString *_pending, *_reply; - void (^_requestListener)(void); -} -+ (instancetype)shared { - static FaceclawRemoteInput *instance; static dispatch_once_t once; - dispatch_once(&once, ^{ instance = [self new]; }); return instance; -} -- (instancetype)init { - if ((self = [super init])) { _condition = [NSCondition new]; _server = _client = -1; } - return self; -} -- (NSString *)start:(int)port { return [self start:port address:@"127.0.0.1"]; } -- (NSString *)start:(int)port address:(NSString *)address { - [_condition lock]; - if (_server >= 0) { [_condition unlock]; return @""; } - struct addrinfo hints = {0}, *resolved = NULL; - hints.ai_flags = AI_NUMERICHOST; hints.ai_socktype = SOCK_STREAM; - NSString *service = [NSString stringWithFormat:@"%d", port]; - if (getaddrinfo(address.UTF8String, service.UTF8String, &hints, &resolved) != 0) { - [_condition unlock]; return @"Invalid local address."; - } - BOOL wildcard = resolved->ai_family == AF_INET ? - ((struct sockaddr_in *)resolved->ai_addr)->sin_addr.s_addr == INADDR_ANY : - IN6_IS_ADDR_UNSPECIFIED(&((struct sockaddr_in6 *)resolved->ai_addr)->sin6_addr); - if (wildcard) { freeaddrinfo(resolved); [_condition unlock]; return @"Wildcard addresses are not allowed."; } - int fd = socket(resolved->ai_family, SOCK_STREAM, 0), yes = 1; - setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)); - int result = fd < 0 ? -1 : bind(fd, resolved->ai_addr, (socklen_t)resolved->ai_addrlen); - freeaddrinfo(resolved); - if (result || listen(fd, 8)) { - if (fd >= 0) close(fd); [_condition unlock]; return @"Could not open input port on this address."; - } - _server = fd; NSUInteger generation = ++_generation; - [_condition unlock]; - dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{ [self serve:fd generation:generation]; }); - return @""; -} -- (void)stop { - [_condition lock]; ++_generation; - // The serving thread owns close(); shutdown interrupts its blocking I/O. - if (_server >= 0) shutdown(_server, SHUT_RDWR); - if (_client >= 0) shutdown(_client, SHUT_RDWR); - _server = _client = -1; _requestId = 0; _pending = _reply = nil; - [_condition broadcast]; [_condition unlock]; -} -- (NSString *)nextRequest { - [_condition lock]; - NSString *result = NSDate.date.timeIntervalSince1970 < _deadline ? _pending : nil; - _pending = nil; [_condition unlock]; return result; -} -- (void)setRequestListener:(void (^)(void))listener { - [_condition lock]; _requestListener = [listener copy]; [_condition unlock]; -} -- (void)notifyRequestReady:(long long)identifier { - // Dispatch from under the condition lock; invoke JS only on the main thread, - // outside the lock, and discard notifications invalidated by stop/timeout. - dispatch_async(dispatch_get_main_queue(), ^{ - [self->_condition lock]; - void (^callback)(void) = self->_requestId == identifier && self->_pending && - NSDate.date.timeIntervalSince1970 < self->_deadline ? self->_requestListener : nil; - [self->_condition unlock]; - if (callback) callback(); - }); -} -- (void)complete:(long long)identifier response:(NSString *)response { - [_condition lock]; - if (_requestId == identifier && NSDate.date.timeIntervalSince1970 < _deadline) { _reply = response; [_condition signal]; } - [_condition unlock]; -} -- (void)serve:(int)listener generation:(NSUInteger)generation { - for (;;) { - [_condition lock]; BOOL current = generation == _generation; [_condition unlock]; - if (!current) break; - // Poll also guarantees stop is observed on platforms where shutdown does not wake accept. - struct pollfd p = { .fd = listener, .events = POLLIN }; - if (poll(&p, 1, 250) <= 0) continue; - int client = accept(listener, NULL, NULL); - if (client < 0) break; - @autoreleasepool { - [_condition lock]; current = generation == _generation; - if (current) _client = client; - [_condition unlock]; - if (!current) { close(client); break; } - struct timeval timeout = {5, 0}; int yes = 1; - setsockopt(client, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); - setsockopt(client, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)); - setsockopt(client, SOL_SOCKET, SO_NOSIGPIPE, &yes, sizeof(yes)); - NSTimeInterval readDeadline = NSDate.date.timeIntervalSince1970 + 5; - NSMutableData *body = [NSMutableData new]; unsigned char byte; BOOL complete = NO; - while (body.length <= 65536) { - NSTimeInterval remaining = readDeadline - NSDate.date.timeIntervalSince1970; - struct pollfd input = { .fd = client, .events = POLLIN }; - if (remaining <= 0 || poll(&input, 1, (int)(remaining * 1000)) <= 0 || recv(client, &byte, 1, 0) != 1) break; - if (byte == '\n') { complete = YES; break; } - [body appendBytes:&byte length:1]; - } - NSString *text = complete ? [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding] : nil; - if (text) { - [_condition lock]; - if (generation == _generation) { - _requestId = ++_nextId; _deadline = NSDate.date.timeIntervalSince1970 + 5; _reply = nil; - NSData *json = [NSJSONSerialization dataWithJSONObject:@{@"id":@(_requestId), @"expiresAt":@(_deadline * 1000), @"body":text} options:0 error:nil]; - _pending = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding]; - [self notifyRequestReady:_requestId]; - while (!_reply && generation == _generation && NSDate.date.timeIntervalSince1970 < _deadline) - [_condition waitUntilDate:[NSDate dateWithTimeIntervalSince1970:_deadline]]; - NSString *reply = _reply ?: @"{\"ok\":false,\"error\":\"timeout\",\"message\":\"Faceclaw did not respond in time.\"}"; - if (generation == _generation) { _pending = _reply = nil; _requestId = 0; } - [_condition unlock]; - NSData *data = [[reply stringByAppendingString:@"\n"] dataUsingEncoding:NSUTF8StringEncoding]; - NSUInteger offset = 0; - while (offset < data.length) { - ssize_t n = send(client, (const char *)data.bytes + offset, data.length - offset, 0); - if (n <= 0) break; offset += n; - } - } else [_condition unlock]; - } - [_condition lock]; if (generation == _generation) _client = -1; [_condition unlock]; - close(client); - } - } - close(listener); - [_condition lock]; if (generation == _generation) _server = -1; [_condition unlock]; -} -+ (NSString *)interfaces { - NSMutableArray *result = [NSMutableArray new]; struct ifaddrs *interfaces = NULL; - if (getifaddrs(&interfaces) == 0) { - for (struct ifaddrs *item = interfaces; item; item = item->ifa_next) { - if (!item->ifa_addr || !(item->ifa_flags & IFF_UP) || (item->ifa_flags & IFF_LOOPBACK)) continue; - int family = item->ifa_addr->sa_family; - if (family != AF_INET && family != AF_INET6) continue; - char address[NI_MAXHOST]; - if (getnameinfo(item->ifa_addr, item->ifa_addr->sa_len, address, sizeof(address), NULL, 0, NI_NUMERICHOST)) continue; - [result addObject:@{@"name":@(item->ifa_name), @"address":@(address), @"pointToPoint":@((item->ifa_flags & IFF_POINTOPOINT) != 0)}]; - } - freeifaddrs(interfaces); - } - return [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:result options:0 error:nil] encoding:NSUTF8StringEncoding]; -} -- (NSString *)randomSecret { - unsigned char bytes[32]; - if (SecRandomCopyBytes(kSecRandomDefault, sizeof(bytes), bytes) != errSecSuccess) return @""; - NSMutableString *hex = [NSMutableString new]; - for (NSUInteger i = 0; i < sizeof(bytes); i++) [hex appendFormat:@"%02x", bytes[i]]; - return hex; -} -- (NSString *)tokenDigest:(NSString *)value { return [FaceclawCrypto sha256:[value dataUsingEncoding:NSUTF8StringEncoding]]; } -@end diff --git a/App_Resources/iOS/src/FaceclawSseRequest.h b/App_Resources/iOS/src/FaceclawSseRequest.h deleted file mode 100644 index 3177e20b..00000000 --- a/App_Resources/iOS/src/FaceclawSseRequest.h +++ /dev/null @@ -1,8 +0,0 @@ -#import - -/** Streaming POST. Events are polled by the owning JS isolate, including workers. */ -@interface FaceclawSseRequest : NSObject -- (instancetype)initWithURL:(NSString *)url body:(NSString *)body headers:(NSString *)headersJson; -- (NSString *)takeEvents; -- (void)cancel; -@end diff --git a/App_Resources/iOS/src/FaceclawSseRequest.m b/App_Resources/iOS/src/FaceclawSseRequest.m deleted file mode 100644 index 7e793257..00000000 --- a/App_Resources/iOS/src/FaceclawSseRequest.m +++ /dev/null @@ -1,153 +0,0 @@ -#import "FaceclawSseRequest.h" -#import -#if TARGET_OS_IOS -#import -#endif - -@interface FaceclawSseRequest () -@property(nonatomic, strong) NSURLSession *session; -@property(nonatomic, strong) NSURLSessionDataTask *task; -@property(nonatomic, strong) NSMutableData *buffer; -@property(nonatomic, strong) NSMutableArray *events; -@property(nonatomic) NSUInteger queuedBytes; -@property(nonatomic) NSInteger status; -@property(nonatomic) BOOL finished; -@property(nonatomic) BOOL cancelled; -@property(nonatomic) BOOL firstLine; -#if TARGET_OS_IOS -@property(nonatomic) UIBackgroundTaskIdentifier backgroundTask; -#endif -@end - -@implementation FaceclawSseRequest -- (instancetype)initWithURL:(NSString *)url body:(NSString *)body headers:(NSString *)headersJson { - if ((self = [super init])) { - _buffer = [NSMutableData new]; _events = [NSMutableArray new]; _firstLine = YES; -#if TARGET_OS_IOS - _backgroundTask = UIBackgroundTaskInvalid; - dispatch_async(dispatch_get_main_queue(), ^{ - @synchronized(self) { - if (self.cancelled || self.finished) return; - self.backgroundTask = [UIApplication.sharedApplication beginBackgroundTaskWithName:@"Assistant response" expirationHandler:^{ - [self finish:@{@"kind": @"failure", @"text": @"iOS background time expired. Open Faceclaw and retry."}]; - [self endBackgroundTask]; - }]; - } - }); -#endif - NSURL *target = [NSURL URLWithString:url]; - if (!target || ![@[@"https", @"http"] containsObject:target.scheme.lowercaseString]) { - [self finish:@{@"kind": @"failure", @"text": @"Invalid streaming URL"}]; return self; - } - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:target]; - request.HTTPMethod = @"POST"; - request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding]; - [request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; - [request setValue:@"text/event-stream" forHTTPHeaderField:@"Accept"]; - NSDictionary *headers = [NSJSONSerialization JSONObjectWithData:[headersJson dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]; - if ([headers isKindOfClass:NSDictionary.class]) for (NSString *name in headers) { - if ([headers[name] isKindOfClass:NSString.class]) [request setValue:headers[name] forHTTPHeaderField:name]; - } - NSURLSessionConfiguration *config = NSURLSessionConfiguration.ephemeralSessionConfiguration; - config.timeoutIntervalForRequest = 180; - config.timeoutIntervalForResource = 180; - _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil]; - _task = [_session dataTaskWithRequest:request]; - [_task resume]; - } - return self; -} -- (void)endBackgroundTask { -#if TARGET_OS_IOS - dispatch_async(dispatch_get_main_queue(), ^{ - @synchronized(self) { - if (self.backgroundTask == UIBackgroundTaskInvalid) return; - [UIApplication.sharedApplication endBackgroundTask:self.backgroundTask]; - self.backgroundTask = UIBackgroundTaskInvalid; - } - }); -#endif -} -- (void)finish:(NSDictionary *)event { - @synchronized(self) { - if (_finished || _cancelled) return; - _finished = YES; [_events addObject:event]; - [_session invalidateAndCancel]; _session = nil; _task = nil; - [_buffer setLength:0]; - } -} -- (NSString *)takeEvents { - @synchronized(self) { - NSData *data = [NSJSONSerialization dataWithJSONObject:_events options:0 error:nil]; - [_events removeAllObjects]; _queuedBytes = 0; - if (_finished) [self endBackgroundTask]; - return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ?: @"[]"; - } -} -- (void)cancel { - @synchronized(self) { - _cancelled = YES; - [_events removeAllObjects]; [_buffer setLength:0]; _queuedBytes = 0; - [_session invalidateAndCancel]; _session = nil; _task = nil; - [self endBackgroundTask]; - } -} -- (void)line:(NSData *)data { - NSString *line = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; - if (!line) { [self finish:@{@"kind": @"failure", @"text": @"Invalid UTF-8 in streaming response"}]; return; } - if (_firstLine && [line hasPrefix:@"\uFEFF"]) line = [line substringFromIndex:1]; - _firstLine = NO; - _queuedBytes += data.length; - if (_queuedBytes > 8 * 1024 * 1024 || _events.count >= 16384) { - [_events removeAllObjects]; - [self finish:@{@"kind": @"failure", @"text": @"Streaming response queue overflow"}]; return; - } - [_events addObject:@{@"kind": @"line", @"text": line}]; -} -- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler { - @synchronized(self) { _status = [(NSHTTPURLResponse *)response statusCode]; } - completionHandler(NSURLSessionResponseAllow); -} -- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler { - // Never forward provider credentials to a redirected endpoint. - completionHandler(nil); -} -- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveData:(NSData *)data { - @synchronized(self) { - if (_finished || _cancelled) return; - if (_status < 200 || _status >= 300) { - NSUInteger remaining = 65536 - _buffer.length; - [_buffer appendData:[data subdataWithRange:NSMakeRange(0, MIN(remaining, data.length))]]; - return; - } - [_buffer appendData:data]; - NSUInteger start = 0; - const uint8_t *bytes = _buffer.bytes; - for (NSUInteger i = 0; i < _buffer.length; i++) { - if (bytes[i] != '\r' && bytes[i] != '\n') continue; - if (bytes[i] == '\r' && i + 1 == _buffer.length) break; - [self line:[_buffer subdataWithRange:NSMakeRange(start, i - start)]]; - if (_finished) return; - if (bytes[i] == '\r' && bytes[i + 1] == '\n') i++; - start = i + 1; - } - if (start) [_buffer replaceBytesInRange:NSMakeRange(0, start) withBytes:NULL length:0]; - if (_buffer.length > 2 * 1024 * 1024) [self finish:@{@"kind": @"failure", @"text": @"Streaming response line too large"}]; - } -} -- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { - @synchronized(self) { - if (_finished || _cancelled) return; - if (error) { [self finish:@{@"kind": @"failure", @"text": error.localizedDescription}]; return; } - if (_status < 200 || _status >= 300) { - NSString *body = [[NSString alloc] initWithData:_buffer encoding:NSUTF8StringEncoding] ?: @""; - [self finish:@{@"kind": @"http-error", @"code": @(_status), @"text": body}]; return; - } - if (_buffer.length) { - if (((const uint8_t *)_buffer.bytes)[_buffer.length - 1] == '\r') [_buffer setLength:_buffer.length - 1]; - [self line:_buffer]; - } - [self finish:@{@"kind": @"complete"}]; - } -} -@end diff --git a/app/g2/firmware-ota.ts b/app/g2/firmware-ota.ts deleted file mode 100644 index 78cc4701..00000000 --- a/app/g2/firmware-ota.ts +++ /dev/null @@ -1,91 +0,0 @@ -/** Stock EVENOTA validation and transfer, matching Android's flasher/g2flash.py. */ -import { StockConnection, OTA_WRITE, OTA_NOTIFY } from './stock-connection' -import { concat } from './ble-protocol' -import type { FlashProgress } from './firmware-types' - -export type FirmwareSegment = { offset: number; size: number; name: string } -const CRC_TABLE = Array.from({ length: 256 }, (_, b) => { - let c = b << 24 - for (let i = 0; i < 8; i++) c = c & 0x80000000 ? (c << 1) ^ 0x1edc6f41 : c << 1 - return c >>> 0 -}) -export function firmwareCrc(data: Uint8Array): number { - let crc = 0 - for (const byte of data) crc = (crc << 8) ^ CRC_TABLE[((crc >>> 24) ^ byte) & 255] - return crc >>> 0 -} -export function validateFirmware(image: Uint8Array): FirmwareSegment[] { - const u32 = (offset: number) => { - if (offset < 0 || offset + 4 > image.length) throw new Error('Firmware header is truncated.') - return new DataView(image.buffer, image.byteOffset, image.byteLength).getUint32(offset, true) - } - if (image.length < 0x40) throw new Error('File is too small to be a firmware image.') - const count = u32(8) - if (count < 5 || count > 6 || 0x40 + count * 16 > image.length) throw new Error('Expected 5–6 firmware components.') - const segments: FirmwareSegment[] = [] - for (let i = 0; i < count; i++) { - const toc = 0x40 + i * 16, offset = u32(toc + 4) - if (offset < 0x40 + count * 16 || offset + 128 > image.length) throw new Error('Firmware component header is out of bounds.') - const size = u32(offset + 8), end = offset + 128 + size - if (!size || end > image.length) throw new Error('Firmware component payload is truncated.') - if (segments.some(s => offset < s.offset + 128 + s.size && s.offset < end)) throw new Error('Firmware components overlap.') - const nameBytes = image.subarray(offset + 48, offset + 128) - const name = String.fromCharCode(...nameBytes.subarray(0, nameBytes.indexOf(0) < 0 ? 80 : nameBytes.indexOf(0))) - const crc = firmwareCrc(image.subarray(offset + 128, end)) - if (crc !== u32(toc + 12) || crc !== u32(offset + 12)) throw new Error(`Component ${name} CRC32C is stale (image not checksum-fixed).`) - segments.push({ offset, size, name }) - } - const mains = segments.filter(s => s.name === 'ota/s200_firmware_ota.bin') - if (mains.length !== 1) throw new Error('Required main firmware component is missing or duplicated.') - const main = mains[0], payload = main.offset + 128 - if (main.size < 32 || u32(payload + 0x14) !== 0x00438000 || (u32(payload) & 0xffffff) !== main.size) - throw new Error('Main-app preamble load address or length is invalid.') - if (0x00438000 + main.size - 32 > 0x007f0000) throw new Error('Main-app exceeds the safe MRAM ceiling — refusing to flash.') - return segments -} - -export async function flashLensImage(link: StockConnection, role: string, image: Uint8Array, segments: FirmwareSegment[], - progress: (value: FlashProgress) => void, log: (line: string) => void, - delay: (ms: number) => Promise): Promise { - let sequence = 0 - const ctrl = async (op: number, payload = new Uint8Array(), data?: Uint8Array): Promise => { - sequence = (sequence + 1) & 255 - const message = await link.exchange(role, 0xc0, concat(new Uint8Array([op]), payload), - message => message.command === op, data ? 4000 : 8000, OTA_WRITE, OTA_NOTIFY, 0, sequence, data) - return message.payload[1] - } - const accepted = (status: number) => [0, 8, 9].includes(status) - const begin = await ctrl(0) - if (!accepted(begin)) throw new Error(`OTA BEGIN rejected (status ${begin}).`) - const total = segments.reduce((sum, segment) => sum + segment.size, 0) - let before = 0 - for (const [index, segment] of segments.entries()) { - let verified = false, failure: unknown - for (let attempt = 0; attempt < 3; attempt++) { - link.check() - if (attempt) { log(`${segment.name}: re-flash attempt ${attempt + 1}/3`); await delay(1500) } - try { - const status = await ctrl(1, image.slice(segment.offset, segment.offset + 128)) - if (status !== 0) throw new Error(`FILE_CHECK rejected (status ${status}).`) - const blocks = Math.ceil(segment.size / 4096) - for (let block = 0; block < blocks; block++) { - const start = segment.offset + 128 + block * 4096 - const data = image.slice(start, Math.min(start + 4096, segment.offset + 128 + segment.size)) - let ok = false - for (let retry = 0; retry < 3; retry++) { - if (await ctrl(2, new Uint8Array(), data) === 0) { ok = true; break } - } - if (!ok) throw new Error(`Block ${block + 1} rejected three times.`) - if (block % 20 === 0 || block === blocks - 1) - progress({ lens: role, componentIndex: index + 1, componentCount: segments.length, blockIndex: block + 1, - blockCount: blocks, bytesSent: before + Math.min((block + 1) * 4096, segment.size), bytesTotal: total }) - } - const end = await ctrl(3) - if (!accepted(end)) throw new Error(`END verification failed (status ${end}).`) - log(`${role} ${segment.name}: END verify OK (status ${end})`); verified = true; break - } catch (error) { link.check(); failure = error } - } - if (!verified) throw new Error(`Component ${segment.name} failed after 3 attempts: ${failure}`) - before += segment.size - } -} diff --git a/app/g2/flash-prompt-protocol.ts b/app/g2/flash-prompt-protocol.ts deleted file mode 100644 index d4e166e4..00000000 --- a/app/g2/flash-prompt-protocol.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { bytes, concat, integer, readBytes, readInteger, readString, type ProtocolMessage } from './ble-protocol' -const text = (field: number, value: string) => bytes(field, new Uint8Array(Array.from(value, ch => ch.charCodeAt(0)))) -export function createFlashPrompt(magic: number, warning: string): Uint8Array { - const geometry = (y: number, height: number, id: number, name: string) => concat( - integer(1, 0), integer(2, y), integer(3, 280), integer(4, height), integer(9, id), text(10, name)) - const list = concat(geometry(150, 120, 2, 'flashmenu'), bytes(11, concat(integer(1, 2), integer(3, 1), text(4, 'No, cancel'), text(4, 'Yes, flash'))), integer(12, 1)) - const label = concat(geometry(0, 130, 1, 'flashwarn'), text(12, warning)) - return concat(integer(1, 0), integer(2, magic), bytes(3, concat(integer(1, 2), bytes(2, list), bytes(3, label), integer(5, 10000)))) -} -export function flashPromptSelection(message: ProtocolMessage): boolean | null { - if (message.sid !== 0xe0 || ![1, 6].includes(message.flag)) return null - const event = readBytes(message.payload, 13), list = event && readBytes(event, 1) - if (!list || readString(list, 2) !== 'flashmenu' || readInteger(list, 5, 0) !== 0) return null - const index = readInteger(list, 4, -1), name = readString(list, 3).toLowerCase() - if (index === 1 || name.startsWith('yes')) return true - if (index === 0 || name.startsWith('no')) return false - return null -} diff --git a/app/g2/stock-connection.ts b/app/g2/stock-connection.ts deleted file mode 100644 index edce1b4f..00000000 --- a/app/g2/stock-connection.ts +++ /dev/null @@ -1,152 +0,0 @@ -import * as p from './ble-protocol' -import type { SessionTransport, SessionAddresses, TransportEvent } from './glasses-session' -import { hexToBytes } from '../util/hex-util' - -declare function setTimeout(callback: () => void, ms: number): number -declare function clearTimeout(id: number): void - -export const OTA_WRITE = '00002760-08c2-11e1-9073-0e8ac72e0001' -export const OTA_NOTIFY = '00002760-08c2-11e1-9073-0e8ac72e0002' -export class StockTimeout extends Error {} -type Waiter = { role: string; characteristic: string; match: (message: p.ProtocolMessage) => boolean; - resolve: (message: p.ProtocolMessage) => void; reject: (error: Error) => void; timer: ReturnType | null } - -/** Exclusive, short-lived stock-protocol connection for onboarding/OTA. No display pump. */ -export class StockConnection { - ids: Record = {} - private limits: Record = {} - private receiver = new p.MessageReceiver() - private waiters = new Set() - private listeners = new Set<(role: string, message: p.ProtocolMessage) => void>() - private lost = new Set() - private writes = new Map>() - private closed = false - private magic = 0x60 - private sequence = 0 - private off: () => void - constructor(private transport: SessionTransport, private log: (line: string) => void = () => {}) { - this.off = transport.onEvent(event => this.receive(event)) - } - check(): void { if (this.closed) throw new Error('Cancelled.') } - isConnected(role: string): boolean { return !this.closed && !!this.limits[role] && !this.lost.has(role) } - async resolve(addresses: SessionAddresses): Promise { - this.ids = await this.transport.resolveDevices(addresses); this.check() - } - async connect(role: string, ota = false): Promise { - this.check(); this.lost.delete(role) - const id = this.ids[role] - if (!id) throw new Error(`No ${role} lens configured.`) - const details = await this.transport.connect(id) - if (this.closed) { this.transport.disconnect(id); this.check() } - this.limits[role] = details.maxWrite - for (const characteristic of [p.G2_WRITE, p.G2_NOTIFY, ...(ota ? [OTA_WRITE, OTA_NOTIFY] : [])]) - if (!details.characteristics.includes(characteristic)) throw new Error(`${role} lens is missing ${ota ? 'firmware update' : 'G2'} characteristics.`) - await this.transport.subscribe(id, p.G2_NOTIFY); this.check() - if (ota) { await this.transport.subscribe(id, OTA_NOTIFY); this.check() } - } - nextMagic(): number { this.magic = this.magic >= 0x7f ? 0x60 : this.magic + 1; return this.magic } - async authenticate(role: string): Promise { - for (let attempt = 0; attempt < 2; attempt++) { - const magic = this.nextMagic() - try { - await this.exchange(role, p.SID.auth, p.authentication(magic), - message => p.authenticationSucceeded(message, magic), 30_000, p.G2_WRITE, p.G2_NOTIFY, 0) - this.log(`Security authentication complete: ${role} lens`); return - } catch (error) { this.check(); if (!(error instanceof StockTimeout) || attempt === 1) throw error } - } - } - request(role: string, sid: number, build: (magic: number) => Uint8Array, timeout = 3500, fixedMagic?: number): Promise { - const magic = fixedMagic ?? this.nextMagic() - return this.exchange(role, sid, build(magic), message => message.sid === sid && message.magic === magic && ![1, 6].includes(message.flag), timeout) - } - write(role: string, sid: number, payload: Uint8Array, characteristic = p.G2_WRITE, flag = 0x20, sequence = ++this.sequence): Promise { - // Keep a fragmented control message together when the prompt heartbeat - // overlaps a settings request or shutdown. - const pending = (this.writes.get(role) ?? Promise.resolve()).catch(() => {}).then(async () => { - this.check() - for (const frame of p.frameMessage(payload, sid, flag, sequence, this.limits[role])) { - this.check() - if (this.lost.has(role)) throw new Error(`Lost connection to the ${role} lens.`) - await this.transport.write(this.ids[role], characteristic, frame) - } - this.check() - if (this.lost.has(role)) throw new Error(`Lost connection to the ${role} lens.`) - }) - this.writes.set(role, pending) - return pending - } - exchange(role: string, sid: number, payload: Uint8Array, match: Waiter['match'], timeout: number, - write = p.G2_WRITE, notify = p.G2_NOTIFY, flag = 0x20, sequence?: number, data?: Uint8Array): Promise { - this.check() - return new Promise((resolve, reject) => { - let written = false, reply: p.ProtocolMessage | null = null - const waiter: Waiter = { role, characteristic: notify, match, - resolve: message => { reply = message; if (written) resolve(message) }, reject, - timer: null } - this.waiters.add(waiter) - void (async () => { - await this.write(role, sid, payload, write, flag, sequence) - if (data) await this.write(role, 0xc1, data, write, flag, sequence) - this.check() - if (!reply && !this.waiters.has(waiter)) return - written = true - if (reply) resolve(reply) - else waiter.timer = setTimeout(() => { - this.waiters.delete(waiter) - reject(new StockTimeout(`No response from the ${role} lens (0x${sid.toString(16)}).`)) - }, timeout) - })().catch(error => { this.waiters.delete(waiter); if (waiter.timer !== null) clearTimeout(waiter.timer); reject(error) }) - }) - } - - onMessage(listener: (role: string, message: p.ProtocolMessage) => void): () => void { - this.listeners.add(listener); return () => this.listeners.delete(listener) - } - private receive(event: TransportEvent): void { - if (this.closed) return - const role = Object.keys(this.ids).find(role => this.ids[role] === event.identifier) - if (!role) return - if (event.kind === 'disconnected') { - this.lost.add(role) - for (const waiter of [...this.waiters]) if (waiter.role === role) { - this.waiters.delete(waiter); if (waiter.timer !== null) clearTimeout(waiter.timer); waiter.reject(new Error(`Lost connection to the ${role} lens.`)) - } - return - } - if (event.kind !== 'notification' || !event.data || ![p.G2_NOTIFY, OTA_NOTIFY].includes(event.characteristic!)) return - try { - const data = hexToBytes(event.data) - const messages = event.characteristic === OTA_NOTIFY ? decodeOtaAcks(data) : this.receiver.receive(event.identifier!, data) - for (const message of messages) { - for (const waiter of [...this.waiters]) if (waiter.role === role && waiter.characteristic === event.characteristic && waiter.match(message)) { - this.waiters.delete(waiter); if (waiter.timer !== null) clearTimeout(waiter.timer); waiter.resolve(message) - } - if (event.characteristic === p.G2_NOTIFY) for (const listener of this.listeners) listener(role, message) - } - } catch (error) { this.log(`Ignored malformed onboarding notification: ${error}`) } - } - disconnect(role: string): void { this.lost.add(role); if (this.ids[role]) this.transport.disconnect(this.ids[role]); this.receiver.clear() } - close(): void { - if (this.closed) return - this.closed = true; this.off(); this.transport.stopScan() - for (const waiter of this.waiters) { if (waiter.timer !== null) clearTimeout(waiter.timer); waiter.reject(new Error('Cancelled.')) } - this.waiters.clear(); this.listeners.clear() - for (const role of Object.keys(this.ids)) this.disconnect(role) - } -} - -/** OTA ACKs are raw opcode/status bytes, not protobuf; validate the aa21 CRC envelope. */ -export function decodeOtaAcks(data: Uint8Array): p.ProtocolMessage[] { - const messages: p.ProtocolMessage[] = [] - for (let offset = 0; offset + 8 <= data.length;) { - const n = data[offset + 3], end = offset + 8 + n - if (end > data.length) break - if (data[offset] === 0xaa && [0x12, 0x21].includes(data[offset + 1]) && data[offset + 4] === 1 && data[offset + 5] === 1 && n >= 4) { - const payload = data.slice(offset + 8, end - 2) - if (p.crc16(payload) === (data[end - 2] | data[end - 1] << 8)) - messages.push({ sid: data[offset + 6], flag: data[offset + 7], payload, command: payload[0], magic: -1 }) - } - offset = end - } - return messages -} diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/FirmwareImage.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/FirmwareImage.kt index a1c62bce..c8c7a4d5 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/FirmwareImage.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/FirmwareImage.kt @@ -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) { diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionCore.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionCore.kt index 8175ccf9..fb85df35 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionCore.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/g2protocol/session/GlassesSessionCore.kt @@ -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(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) diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/net/RemoteInputSession.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/net/RemoteInputSession.kt index 40d9bbe0..cc27aa64 100644 --- a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/net/RemoteInputSession.kt +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/net/RemoteInputSession.kt @@ -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 diff --git a/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/IosFrameTimings.kt b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/IosFrameTimings.kt new file mode 100644 index 00000000..1fb23767 --- /dev/null +++ b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/IosFrameTimings.kt @@ -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 + * /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 ?: "." + } +} diff --git a/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/PlatformUtil.ios.kt b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/PlatformUtil.ios.kt index 27f43702..185bdfcb 100644 --- a/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/PlatformUtil.ios.kt +++ b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/PlatformUtil.ios.kt @@ -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) { diff --git a/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/ble/IosBleCentral.kt b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/ble/IosBleCentral.kt new file mode 100644 index 00000000..aec8d2e0 --- /dev/null +++ b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/ble/IosBleCentral.kt @@ -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() + 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() + private val advertisements = LinkedHashMap() + 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() + + /** 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 = 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, + 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, 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()) { + 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, 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 + } +} diff --git a/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/ble/IosGlassesSession.kt b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/ble/IosGlassesSession.kt new file mode 100644 index 00000000..37900640 --- /dev/null +++ b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/ble/IosGlassesSession.kt @@ -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) } + } + } +} diff --git a/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/ble/IosSessionHost.kt b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/ble/IosSessionHost.kt new file mode 100644 index 00000000..1e03e786 --- /dev/null +++ b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/ble/IosSessionHost.kt @@ -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) + } + } +} diff --git a/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/ble/IosStockFlows.kt b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/ble/IosStockFlows.kt new file mode 100644 index 00000000..a8146eba --- /dev/null +++ b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/ble/IosStockFlows.kt @@ -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) + } +} diff --git a/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/net/IosModelDownloader.kt b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/net/IosModelDownloader.kt new file mode 100644 index 00000000..20919c7c --- /dev/null +++ b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/net/IosModelDownloader.kt @@ -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(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()) { "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) +} diff --git a/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/net/IosPosixSockets.kt b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/net/IosPosixSockets.kt new file mode 100644 index 00000000..0091d193 --- /dev/null +++ b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/net/IosPosixSockets.kt @@ -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?): 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(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 , 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) -> 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() + offset)!!.reinterpret().pointed.value + +private fun CPointer<*>.uintField(offset: Int): UInt = + (this.reinterpret() + offset)!!.reinterpret().pointed.value + +/** Every address assigned to a local interface, as the shared session's [InterfaceAddress]. */ +fun iosInterfaceAddresses(): List { + val result = ArrayList() + val getifaddrs = dlsym(libSystem, "getifaddrs")?.reinterpret() ?: return result + val freeifaddrs = dlsym(libSystem, "freeifaddrs")?.reinterpret() ?: return result + memScoped { + val list = alloc() + 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()?.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() + holder.value = value + setsockopt(fd, level, option, holder.ptr, sizeOf().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() + hints.ai_flags = AI_NUMERICHOST + hints.ai_socktype = SOCK_STREAM + val resolved = allocPointerTo() + 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() + hints.ai_flags = AI_NUMERICHOST or AI_NUMERICSERV + hints.ai_socktype = SOCK_STREAM + val resolved = allocPointerTo() + 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() + 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() + 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() + 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 + } +} diff --git a/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/net/IosRemoteInput.kt b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/net/IosRemoteInput.kt new file mode 100644 index 00000000..1fc1034b --- /dev/null +++ b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/net/IosRemoteInput.kt @@ -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() } + } +} diff --git a/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/net/IosSseRequest.kt b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/net/IosSseRequest.kt new file mode 100644 index 00000000..b64f303b --- /dev/null +++ b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/net/IosSseRequest.kt @@ -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>() + 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" + } +} diff --git a/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/net/IosStreamingHttp.kt b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/net/IosStreamingHttp.kt new file mode 100644 index 00000000..91a32f72 --- /dev/null +++ b/native/kotlin/shared/src/iosMain/kotlin/com/faceclaw/app/net/IosStreamingHttp.kt @@ -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>): 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>, 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() + } + } +} diff --git a/package.json b/package.json index 12869539..96173ab8 100644 --- a/package.json +++ b/package.json @@ -18,7 +18,8 @@ "release": "scripts/release.sh", "clean": "rm -rf platforms", "test": "tsc -p tests/tsconfig.json && node --test tests/*.test.cjs", - "test:kotlin:ios": "bash scripts/test-kotlin.sh iosSimulatorArm64Test compileKotlinIosArm64" + "test:kotlin:ios": "bash scripts/test-kotlin.sh iosSimulatorArm64Test compileKotlinIosArm64", + "postinstall": "node scripts/install-hooks.cjs" }, "dependencies": { "@evenrealities/pretext": "^0.1.4", diff --git a/scripts/before_build.sh b/scripts/before_build.sh index 9a1c34f0..9692ea5f 100644 --- a/scripts/before_build.sh +++ b/scripts/before_build.sh @@ -5,3 +5,5 @@ else cp build_paths.sh.template build_paths.sh fi +# Restore the Kotlin prepare hook if a package install removed it. +node "$(dirname "${BASH_SOURCE[0]}")/install-hooks.cjs" diff --git a/scripts/hooks/faceclaw-kotlin.before-prepare.js b/scripts/hooks/faceclaw-kotlin.before-prepare.js new file mode 100644 index 00000000..435b315f --- /dev/null +++ b/scripts/hooks/faceclaw-kotlin.before-prepare.js @@ -0,0 +1,8 @@ +const { buildKotlin, checkAndroidRuntime } = require('../../scripts/kotlin-build.cjs'); + +module.exports = function (hookArgs) { + // NativeScript parses hooks with an older JavaScript parser; avoid optional chaining. + const { platform, release } = hookArgs.prepareData; + if (platform === 'android') checkAndroidRuntime(); + return buildKotlin(platform, release ? 'release' : 'debug'); +}; diff --git a/scripts/install-hooks.cjs b/scripts/install-hooks.cjs new file mode 100644 index 00000000..a0aebec6 --- /dev/null +++ b/scripts/install-hooks.cjs @@ -0,0 +1,31 @@ +// NativeScript runs hooks//*.js, but that directory is also managed by +// @nativescript/hook on package (re)installs and has been observed to lose our +// custom hook. The tracked copy under scripts/hooks/ is the source of truth; +// this restores it on `npm install` and before every build. +const fs = require('node:fs'); +const path = require('node:path'); + +const root = path.resolve(__dirname, '..'); +const hooks = [ + { source: 'scripts/hooks/faceclaw-kotlin.before-prepare.js', target: 'hooks/before-prepare/faceclaw-kotlin.js' }, +]; + +function installHooks() { + const restored = []; + for (const { source, target } of hooks) { + const from = path.join(root, source); + const to = path.join(root, target); + const content = fs.readFileSync(from); + if (fs.existsSync(to) && fs.readFileSync(to).equals(content)) continue; + fs.mkdirSync(path.dirname(to), { recursive: true }); + fs.writeFileSync(to, content); + restored.push(target); + } + return restored; +} + +module.exports = { installHooks }; +if (require.main === module) { + const restored = installHooks(); + if (restored.length) console.log(`[hooks] restored ${restored.join(', ')}`); +} diff --git a/scripts/ios.sh b/scripts/ios.sh index e86bc302..e5e9f0d5 100755 --- a/scripts/ios.sh +++ b/scripts/ios.sh @@ -19,4 +19,5 @@ if command -v ruby >/dev/null 2>&1; then export PATH="$gem_bin:$PATH" fi +node scripts/install-hooks.cjs exec ns "$@" diff --git a/tests/ios-onboarding-ota.test.cjs b/tests/ios-onboarding-ota.test.cjs deleted file mode 100644 index 029b386d..00000000 --- a/tests/ios-onboarding-ota.test.cjs +++ /dev/null @@ -1,142 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); -const p = require('../.test-build/app/g2/ble-protocol.js'); -const { StockConnection, OTA_WRITE, OTA_NOTIFY, decodeOtaAcks } = require('../.test-build/app/g2/stock-connection.js'); -const { firmwareCrc, validateFirmware, flashLensImage } = require('../.test-build/app/g2/firmware-ota.js'); -const { createFlashPrompt, flashPromptSelection } = require('../.test-build/app/g2/flash-prompt-protocol.js'); -const hex = bytes => Buffer.from(bytes).toString('hex'); -function fixture() { - const sizes = [9000, 20, 20, 20, 20], image = new Uint8Array(0x40 + 5 * 16 + sizes.reduce((n, size) => n + size + 128, 0)); - const view = new DataView(image.buffer), u32 = (off, value) => view.setUint32(off, value, true); - u32(8, 5); let offset = 0x40 + 5 * 16; - sizes.forEach((size, index) => { - u32(0x40 + index * 16 + 4, offset); u32(offset + 8, size); - image.set(Buffer.from(index ? `ota/part${index}.bin` : 'ota/s200_firmware_ota.bin'), offset + 48); - image.fill(index + 1, offset + 128, offset + 128 + size); - if (!index) { u32(offset + 128, size); u32(offset + 128 + 0x14, 0x00438000); } - const crc = firmwareCrc(image.subarray(offset + 128, offset + 128 + size)); - u32(offset + 12, crc); u32(0x40 + index * 16 + 12, crc); offset += size + 128; - }); - return image; -} -class Transport { - listeners = new Set(); writes = []; messages = []; chunks = []; seq = 0; held = false; respond = null; closed = []; - onEvent(fn) { this.listeners.add(fn); return () => this.listeners.delete(fn); } - emit(event) { for (const fn of this.listeners) fn(event); } - async resolveDevices() { return { left: 'L', right: 'R' }; } - async connect() { return { characteristics: [p.G2_WRITE, p.G2_NOTIFY, OTA_WRITE, OTA_NOTIFY], maxWrite: 60 }; } - async subscribe() {} - stopScan() {} - disconnect(id) { this.closed.push(id); this.emit({ kind: 'disconnected', identifier: id }); } - notify(id, sid, payload, characteristic = p.G2_NOTIFY, flag = 0) { - this.emit({ kind: 'notification', identifier: id, characteristic, data: hex(p.concat(...p.frameMessage(payload, sid, flag, 10))) }); - } - async write(id, characteristic, bytes) { - this.writes.push({ id, characteristic, bytes }); - if (bytes[5] === 1) this.chunks = []; - this.chunks.push(bytes.subarray(8)); - if (bytes[5] !== bytes[4]) return; - const all = p.concat(...this.chunks), payload = all.slice(0, -2); - assert.equal(p.crc16(payload), all.at(-2) | all.at(-1) << 8); - const message = { id, characteristic, sid: bytes[6], seq: bytes[2], payload }; - this.messages.push(message); - if (this.respond) return this.respond(message); - if (this.held) return; - if (characteristic === OTA_WRITE) { - if (message.sid === 0xc0 && payload[0] === 2) { this.seq = message.seq; return; } - if (message.sid === 0xc1) assert.equal(message.seq, this.seq, 'marker/data sequence must match'); - this.notify(id, 0xc0, new Uint8Array([message.sid === 0xc1 ? 2 : payload[0], 0]), OTA_NOTIFY); - } else { - this.notify(id, message.sid, p.concat(p.integer(1, p.readInteger(payload, 1)), p.integer(2, p.readInteger(payload, 2)), p.bytes(3, new Uint8Array()))); - } - } -} -async function connection(t, transport = new Transport()) { - const link = new StockConnection(transport); t.after(() => link.close()); - await link.resolve({ left: 'a', right: 'b', ring: '' }); await link.connect('left', true); - return { link, transport }; -} - -test('OTA validator checks CRCs, bounds, overlap and the main-app preamble before transfer', () => { - const image = fixture(), segments = validateFirmware(image); - assert.equal(segments.length, 5); - const corrupt = image.slice(); corrupt[segments[0].offset + 200] ^= 1; - assert.throws(() => validateFirmware(corrupt), /CRC32C/); - assert.throws(() => validateFirmware(image.slice(0, -1)), /truncated/); - const bad = image.slice(), view = new DataView(bad.buffer); - view.setUint32(0x44, 0xfffffff0, true); assert.throws(() => validateFirmware(bad), /bounds/); - const overlap = image.slice(); new DataView(overlap.buffer).setUint32(0x54, segments[0].offset, true); - assert.throws(() => validateFirmware(overlap), /overlap/); - const wrongLoad = image.slice(), w = new DataView(wrongLoad.buffer), main = segments[0]; - w.setUint32(main.offset + 128 + 0x14, 0, true); - const crc = firmwareCrc(wrongLoad.subarray(main.offset + 128, main.offset + 128 + main.size)); - w.setUint32(main.offset + 12, crc, true); w.setUint32(0x4c, crc, true); - assert.throws(() => validateFirmware(wrongLoad), /preamble/); -}); - -test('OTA framing streams every verified byte in 4KB blocks with shared marker/data sequences', async t => { - const { link, transport } = await connection(t); await link.authenticate('left'); - const image = fixture(), segments = validateFirmware(image), progress = []; - await flashLensImage(link, 'left', image, segments, value => progress.push(value), () => {}, async () => {}); - const controls = transport.messages.filter(m => m.sid === 0xc0); - assert.equal(controls[0].payload[0], 0); - assert.equal(controls.filter(m => m.payload[0] === 1).length, 5); - assert.equal(controls.filter(m => m.payload[0] === 3).length, 5); - const streamed = p.concat(...transport.messages.filter(m => m.sid === 0xc1).map(m => m.payload)); - assert.deepEqual(streamed, p.concat(...segments.map(s => image.slice(s.offset + 128, s.offset + 128 + s.size)))); - assert.equal(progress.at(-1).bytesSent, progress.at(-1).bytesTotal); - assert.ok(transport.writes.every(w => w.bytes.length <= 60)); -}); - -test('OTA retries NAKed blocks and failed END verification, but never accepts a rejected FILE_CHECK', async () => { - const image = fixture(), segments = validateFirmware(image); let blockAttempts = 0, endAttempts = 0, checks = 0; - const fake = { check() {}, async exchange(_role, _sid, payload, _match, _timeout, _write, _notify, _flag, _seq, data) { - const op = payload[0]; let status = 0; - if (op === 1) checks++; - if (op === 2 && ++blockAttempts === 1) status = 1; - if (op === 3 && ++endAttempts === 1) status = 2; - return { payload: new Uint8Array([op, status]) }; - } }; - await flashLensImage(fake, 'left', image, segments, () => {}, () => {}, async () => {}); - assert.equal(checks, 6); assert.equal(blockAttempts, 11); - let dataWrites = 0; - fake.exchange = async (_role, _sid, payload, ...args) => { if (args.at(-1)) dataWrites++; return { payload: new Uint8Array([payload[0], payload[0] === 1 ? 4 : 0]) }; }; - await assert.rejects(flashLensImage(fake, 'left', image, segments, () => {}, () => {}, async () => {}), /failed after 3 attempts/); - assert.equal(dataWrites, 0); -}); - -test('onboarding requests ignore wrong peers, magic and pre-encryption authentication failures', async t => { - const { link, transport } = await connection(t); let resolved = false; - transport.respond = message => { - const magic = p.readInteger(message.payload, 2); - const good = p.concat(p.integer(1, 4), p.integer(2, magic), p.bytes(3, new Uint8Array())); - transport.notify('stranger', p.SID.auth, good); - transport.notify('R', p.SID.auth, good); - transport.notify('L', p.SID.auth, p.concat(p.integer(1, 4), p.integer(2, magic), p.bytes(3, p.integer(1, 1)))); - transport.notify('L', p.SID.auth, p.concat(p.integer(1, 4), p.integer(2, magic + 1), p.bytes(3, new Uint8Array()))); - setImmediate(() => { assert.equal(resolved, false); transport.notify('L', p.SID.auth, good); }); - }; - await link.authenticate('left'); resolved = true; -}); - -test('OTA ACK parsing rejects bad CRC and truncation; cancellation rejects an outstanding transaction', async t => { - const { link, transport } = await connection(t); transport.held = true; - const payload = new Uint8Array([2, 0]), packet = p.frameMessage(payload, 0xc0, 0, 1)[0]; - assert.equal(decodeOtaAcks(packet)[0].payload[1], 0); - assert.deepEqual(decodeOtaAcks(packet.slice(0, -1)), []); - packet[8] ^= 1; assert.deepEqual(decodeOtaAcks(packet), []); - const pending = link.exchange('left', 0xc0, new Uint8Array([0]), m => m.command === 0, 8000, OTA_WRITE, OTA_NOTIFY, 0); - link.close(); await assert.rejects(pending, /Cancelled/); - assert.equal(transport.listeners.size, 0); -}); - -test('stock confirmation keeps No first and accepts only a confirmed flashmenu selection', () => { - const page = createFlashPrompt(42, 'Warning'); const body = p.readBytes(page, 3); - const list = p.readBytes(body, 2), label = p.readBytes(body, 3); - assert.equal(p.readInteger(list, 3), 280); assert.equal(p.readInteger(label, 4), 130); - assert.equal(p.readString(list, 10), 'flashmenu'); assert.equal(p.readString(label, 12), 'Warning'); - const event = (index, type = 0, name = 'flashmenu') => ({ sid: 0xe0, flag: 1, - payload: p.bytes(13, p.bytes(1, p.concat(p.bytes(2, new Uint8Array(Buffer.from(name))), p.integer(4, index), p.integer(5, type)))) }); - assert.equal(flashPromptSelection(event(0)), false); assert.equal(flashPromptSelection(event(1)), true); - assert.equal(flashPromptSelection(event(1, 1)), null); assert.equal(flashPromptSelection(event(1, 0, 'other')), null); -}); diff --git a/tests/kotlin/src/iosTest/kotlin/com/faceclaw/app/IosNetworkingTest.kt b/tests/kotlin/src/iosTest/kotlin/com/faceclaw/app/IosNetworkingTest.kt new file mode 100644 index 00000000..fea48103 --- /dev/null +++ b/tests/kotlin/src/iosTest/kotlin/com/faceclaw/app/IosNetworkingTest.kt @@ -0,0 +1,314 @@ +@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class) + +package com.faceclaw.app + +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlinx.cinterop.ByteVar +import kotlinx.cinterop.addressOf +import kotlinx.cinterop.alloc +import kotlinx.cinterop.allocPointerTo +import kotlinx.cinterop.memScoped +import kotlinx.cinterop.pointed +import kotlinx.cinterop.ptr +import kotlinx.cinterop.usePinned +import kotlinx.cinterop.value +import platform.Foundation.NSTemporaryDirectory +import platform.posix.AI_NUMERICHOST +import platform.posix.AI_NUMERICSERV +import platform.posix.SOCK_STREAM +import platform.posix.addrinfo +import platform.posix.close +import platform.posix.connect +import platform.posix.freeaddrinfo +import platform.posix.getaddrinfo +import platform.posix.recv +import platform.posix.send +import platform.posix.socket + +private var nextPort = 43000 + (currentTimeMillis() % 9000).toInt() + +/** Binds the next free loopback port; returns the listener and its port. */ +private fun bindFreePort(): Pair { + repeat(50) { + val port = nextPort++ + val listener = runCatching { IosLocalServerPort.bind("127.0.0.1", port) }.getOrNull() ?: return@repeat + return listener to port + } + error("no free loopback port") +} + +/** Blocking POSIX client: connects to loopback, sends [request], reads until the peer closes. */ +private fun loopbackExchange(port: Int, request: ByteArray, readTimeoutMs: Int = 8000): ByteArray = memScoped { + val hints = alloc() + hints.ai_flags = AI_NUMERICHOST or AI_NUMERICSERV + hints.ai_socktype = SOCK_STREAM + val resolved = allocPointerTo() + check(getaddrinfo("127.0.0.1", port.toString(), hints.ptr, resolved.ptr) == 0) + val info = resolved.value!!.pointed + val fd = socket(info.ai_family, SOCK_STREAM, 0) + check(fd >= 0) + try { + check(connect(fd, info.ai_addr, info.ai_addrlen) == 0) { "connect failed" } + request.usePinned { check(send(fd, it.addressOf(0), request.size.toULong(), 0) == request.size.toLong()) } + val out = ByteSink() + val buffer = ByteArray(4096) + val deadline = IosProtocolPlatform.elapsedRealtimeMs() + readTimeoutMs + while (IosProtocolPlatform.elapsedRealtimeMs() < deadline) { + val n = buffer.usePinned { recv(fd, it.addressOf(0), buffer.size.toULong(), 0) } + if (n <= 0L) break + out.write(buffer, 0, n.toInt()) + if (out.toByteArray().last() == '\n'.code.toByte()) break + } + out.toByteArray() + } finally { + freeaddrinfo(resolved.value) + close(fd) + } +} + +/** Minimal loopback HTTP/1.1 server for the NSURLSession facades; one request per connection. */ +private class LoopbackHttpServer(private val handler: (path: String, headers: Map) -> Reply) { + class Reply(val status: Int, val headers: List>, val pieces: List, val pieceDelayMs: Long = 0) + + private val listener: RemoteInputListener + val port: Int + val requests = ArrayList>() + private val lock = IosProtocolPlatform.createLock() + + init { + val bound = bindFreePort() + listener = bound.first + port = bound.second + startThread("loopback-http", true) { + while (!listener.isClosed) { + val connection = listener.accept() ?: continue + startThread("loopback-http-conn", true) { serve(connection) } + } + } + } + + fun url(path: String) = "http://127.0.0.1:$port$path" + + fun close() = listener.close() + + fun requestsFor(path: String): List> = lock.withLock { requests.filter { it["path"] == path } } + + private fun serve(connection: RemoteInputConnection) { + try { + val head = ByteSink() + while (true) { + val b = connection.readByte(5000) + if (b < 0) return + head.write(b) + val bytes = head.toByteArray() + val n = bytes.size + if (n >= 4 && bytes[n - 4] == '\r'.code.toByte() && bytes[n - 3] == '\n'.code.toByte() && + bytes[n - 2] == '\r'.code.toByte() && bytes[n - 1] == '\n'.code.toByte()) break + } + val lines = head.toByteArray().decodeToString().split("\r\n").filter { it.isNotEmpty() } + val path = lines.first().split(' ')[1] + val headers = lines.drop(1).associate { it.substringBefore(':').trim().lowercase() to it.substringAfter(':').trim() } + val bodyLength = headers["content-length"]?.toIntOrNull() ?: 0 + repeat(bodyLength) { connection.readByte(5000) } + lock.withLock { requests.add(headers + ("path" to path)) } + val reply = handler(path, headers) + val total = reply.pieces.sumOf { it.size } + val response = buildString { + append("HTTP/1.1 ${reply.status} X\r\n") + for ((name, value) in reply.headers) append("$name: $value\r\n") + append("Content-Length: $total\r\nConnection: close\r\n\r\n") + } + connection.write(response.encodeToByteArray()) + for (piece in reply.pieces) { + connection.write(piece) + if (reply.pieceDelayMs > 0) sleepMs(reply.pieceDelayMs) + } + } catch (ignored: Exception) { + } finally { + connection.close() + } + } +} + +private fun waitUntil(timeoutMs: Long, condition: () -> Boolean): Boolean { + val deadline = IosProtocolPlatform.elapsedRealtimeMs() + timeoutMs + while (IosProtocolPlatform.elapsedRealtimeMs() < deadline) { + if (condition()) return true + sleepMs(20) + } + return condition() +} + +private class RecordingSseListener : FaceclawSseListener { + private val lock = IosProtocolPlatform.createLock() + val lines = ArrayList() + var httpError: Pair? = null + var failure: String? = null + var completed = false + val finished: Boolean get() = lock.withLock { completed || httpError != null || failure != null } + + override fun onLine(line: String?) { lock.withLock { lines.add(line ?: "") } } + override fun onHttpError(code: Int, body: String?) { lock.withLock { httpError = code to (body ?: "") } } + override fun onComplete() { lock.withLock { completed = true } } + override fun onFailure(message: String?) { lock.withLock { failure = message ?: "" } } +} + +private class RecordingDownloadListener : FaceclawModelDownloaderListener { + private val lock = IosProtocolPlatform.createLock() + var progress = 0 + var done: String? = null + var error: String? = null + val finished: Boolean get() = lock.withLock { done != null || error != null } + + override fun onProgress(bytesDownloaded: Long, totalBytes: Long) { lock.withLock { progress++ } } + override fun onDone(path: String?) { lock.withLock { done = path } } + override fun onError(message: String?) { lock.withLock { error = message } } +} + +class IosNetworkingTest { + private val immediate: (() -> Unit) -> Unit = { it() } + + /** Like the main queue: never runs on the caller's thread, so the session's lock is not re-entered. */ + private val hop: (() -> Unit) -> Unit = { action -> startThread("test-dispatch", true, action) } + + @Test + fun remoteInputRoundTripsOverLoopbackAndTimesOut() { + val (probe, port) = bindFreePort() + probe.close() + val remote = IosRemoteInput(hop, requestTimeoutMs = 1200) + val ready = BlockingQueue(IosProtocolPlatform) + remote.setRequestListener { ready.put("ready") } + assertEquals("Invalid local address.", remote.startAddress(port, "example.com")) + assertEquals("Address is not assigned to a local interface.", remote.startAddress(port, "0.0.0.0")) + assertEquals("", remote.startAddress(port, "127.0.0.1")) + try { + val replies = BlockingQueue(IosProtocolPlatform) + startThread("remote-client", true) { replies.put(loopbackExchange(port, "hello world\n".encodeToByteArray())) } + assertEquals("ready", ready.poll(5000)) + val request = Json.parseObject(assertNotNull(remote.nextRequest())) + assertEquals("hello world", request["body"].asString()) + assertNull(remote.nextRequest()) + remote.complete(request["id"].asLong()!!, "{\"ok\":true}") + assertEquals("{\"ok\":true}\n", assertNotNull(replies.poll(5000)).decodeToString()) + + startThread("remote-client-2", true) { replies.put(loopbackExchange(port, "later\n".encodeToByteArray())) } + assertEquals("ready", ready.poll(5000)) + assertNotNull(remote.nextRequest()) + assertEquals(RemoteInputSession.TIMEOUT_RESPONSE + "\n", assertNotNull(replies.poll(8000)).decodeToString()) + + assertEquals(64, remote.randomSecret().length) + assertEquals(RemoteInputSession.tokenHash("abc"), remote.tokenDigest("abc")) + val all = iosInterfaceAddresses() + assertTrue(all.any { it.loopback && it.address == "127.0.0.1" }, all.toString()) + assertTrue(Json.parseArray(remote.interfaces()).none { it.asObject()!!["address"].asString() == "127.0.0.1" }) + assertTrue(IosLocalServerPort.isLocalUnicastAddress("::1")) + assertFalse(IosLocalServerPort.isLocalUnicastAddress("224.0.0.1")) + } finally { + remote.stop() + } + } + + @Test + fun sseStreamsLinesRefusesRedirectsAndReportsErrors() { + val body = "event: a\r\ndata: one\n\ndata: two\r\n".encodeToByteArray() + val server = LoopbackHttpServer { path, _ -> + when (path) { + "/sse" -> LoopbackHttpServer.Reply(200, listOf("Content-Type" to "text/event-stream"), + listOf(body.copyOfRange(0, 13), body.copyOfRange(13, body.size)), pieceDelayMs = 50) + "/limited" -> LoopbackHttpServer.Reply(429, listOf("Content-Type" to "text/plain"), listOf("slow down".encodeToByteArray())) + else -> LoopbackHttpServer.Reply(302, listOf("Location" to "http://127.0.0.1:1/never"), listOf(ByteArray(0))) + } + } + try { + val ok = RecordingSseListener() + IosSseRequest(server.url("/sse"), "{\"q\":1}", "{\"X-Test\":\"yes\"}", ok, immediate, false) + assertTrue(waitUntil(10_000) { ok.finished }, "sse did not finish: ${ok.failure}") + assertEquals(listOf("event: a", "data: one", "", "data: two"), ok.lines) + assertTrue(ok.completed) + val request = server.requestsFor("/sse").single() + assertEquals("yes", request["x-test"]) + assertEquals("text/event-stream", request["accept"]) + assertTrue(request["user-agent"]!!.isNotEmpty()) + + val limited = RecordingSseListener() + IosSseRequest(server.url("/limited"), "{}", null, limited, immediate, false) + assertTrue(waitUntil(10_000) { limited.finished }) + assertEquals(429 to "slow down", limited.httpError) + + val redirected = RecordingSseListener() + IosSseRequest(server.url("/moved"), "{}", "{}", redirected, immediate, false) + assertTrue(waitUntil(10_000) { redirected.finished }) + assertEquals(302, redirected.httpError?.first) + assertTrue(server.requestsFor("/never").isEmpty()) + } finally { + server.close() + } + } + + @Test + fun downloaderFetchesAndResumesWithRange() { + val payload = ByteArray(200_000) { (it * 31 + it / 977).toByte() } + val sha = sha256Hex(payload) + val server = LoopbackHttpServer { _, headers -> + val range = headers["range"] + if (range != null && range.startsWith("bytes=")) { + val from = range.removePrefix("bytes=").removeSuffix("-").toInt() + LoopbackHttpServer.Reply(206, listOf("Content-Range" to "bytes $from-${payload.size - 1}/${payload.size}"), + listOf(payload.copyOfRange(from, payload.size))) + } else LoopbackHttpServer.Reply(200, emptyList(), listOf(payload.copyOfRange(0, 70_000), payload.copyOfRange(70_000, payload.size)), pieceDelayMs = 30) + } + val dir = NSTemporaryDirectory().trimEnd('/') + "/faceclaw-dl-" + currentTimeMillis() + val dest = "$dir/model.bin" + try { + val first = RecordingDownloadListener() + IosModelDownloader(server.url("/model.bin"), dest, sha, payload.size.toLong(), first, immediate).start() + assertTrue(waitUntil(20_000) { first.finished }, "download did not finish: ${first.error}") + assertEquals(dest, first.done, first.error) + assertContentEquals(payload, readFileData(dest)) + assertTrue(first.progress >= 1) + assertNull(server.requestsFor("/model.bin").single()["range"]) + + deleteFile(dest) + writeFileData("$dest.part", payload.copyOfRange(0, 50_000)) + val second = RecordingDownloadListener() + IosModelDownloader(server.url("/model.bin"), dest, sha, payload.size.toLong(), second, immediate).start() + assertTrue(waitUntil(20_000) { second.finished }, "resume did not finish: ${second.error}") + assertEquals(dest, second.done, second.error) + assertContentEquals(payload, readFileData(dest)) + assertEquals("bytes=50000-", server.requestsFor("/model.bin").last()["range"]) + assertEquals(-1L, fileLength("$dest.part")) + } finally { + server.close() + deleteFile(dest) + deleteFile("$dest.part") + } + } + + @Test + fun frameTimingsExportsToAFile() { + val dir = NSTemporaryDirectory().trimEnd('/') + "/faceclaw-ft-" + currentTimeMillis() + platform.Foundation.NSFileManager.defaultManager.createDirectoryAtPath(dir, true, null, null) + val timings = IosFrameTimings(IosProtocolPlatform) + assertNull(timings.exportNow()) + timings.startExport(dir) + val frame = timings.startFrame("test:frame") + timings.spanStart(frame, "work") + timings.log(frame, "hello") + timings.spanEnd(frame, "work") + timings.finishFrame(frame, "sent") + val path = assertNotNull(timings.exportNow()) + assertEquals("$dir/${IosFrameTimings.EXPORT_FILE_NAME}", path) + val text = readFileData(path).decodeToString() + assertTrue(text.contains("test:frame"), text) + assertTrue(text.contains("hello"), text) + assertNull(timings.exportNow()) + assertTrue(timings.statsSummary().isNotEmpty()) + deleteFile(path) + } +} diff --git a/tests/kotlin/src/iosTest/kotlin/com/faceclaw/app/IosSessionFacadeTest.kt b/tests/kotlin/src/iosTest/kotlin/com/faceclaw/app/IosSessionFacadeTest.kt new file mode 100644 index 00000000..6067bfc8 --- /dev/null +++ b/tests/kotlin/src/iosTest/kotlin/com/faceclaw/app/IosSessionFacadeTest.kt @@ -0,0 +1,228 @@ +package com.faceclaw.app + +import kotlin.concurrent.Volatile +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertTrue +import platform.Foundation.NSDate +import platform.Foundation.NSDefaultRunLoopMode +import platform.Foundation.NSRunLoop +import platform.Foundation.NSThread +import platform.Foundation.dateWithTimeIntervalSinceNow +import platform.Foundation.runMode + +private const val RIGHT = "11111111-2222-3333-4444-555555555501" +private const val LEFT = "11111111-2222-3333-4444-555555555502" + +/** Pump the main run loop (which drains the main dispatch queue) until [condition] or timeout. */ +private fun pumpMainUntil(timeoutMs: Long, condition: () -> Boolean): Boolean { + val deadline = IosProtocolPlatform.elapsedRealtimeMs() + timeoutMs + while (IosProtocolPlatform.elapsedRealtimeMs() < deadline) { + if (condition()) return true + NSRunLoop.mainRunLoop.runMode(NSDefaultRunLoopMode, NSDate.dateWithTimeIntervalSinceNow(0.02)) + } + return condition() +} + +/** A GATT link that acks EvenHub/settings/auth requests and CFW stream messages like the firmware. */ +private class FakeIosLink : SessionLink { + lateinit var core: GlassesSessionCore + private val lock = IosProtocolPlatform.createLock() + val connected = HashSet() + val disconnected = ArrayList() + @Volatile var closed = false + @Volatile var writes = 0 + private var seq = 0 + + override fun connect(address: String, timeoutMs: Int): Boolean { + connected.add(address) + return true + } + + override fun requestHighPriority(address: String) {} + + override fun requestMtu(address: String, mtu: Int, timeoutMs: Int): Boolean = true + + override fun negotiatedMtu(address: String): Int = 247 + + override fun discoverServices(address: String, timeoutMs: Int): Boolean = true + + override fun enableNotifications(address: String, characteristicUuid: String, enable: Boolean, timeoutMs: Int): Boolean = true + + override fun writeFrames(address: String, characteristicUuid: String, frames: List, mode: GattWriteMode, timeoutMs: Int): Boolean { + writes++ + val sid = frames[0][6].toInt() and 255 + val magic = if (sid == CfwTransport.SID) frames[0][2].toInt() and 255 else BleProtocol.parseFrame(frames[0]).msgSeq + val inFlight = core.monitor.withLock { core.inFlightMessages.firstOrNull { it.sid == sid && it.magic == magic && magic != 0 } } + if (inFlight != null) { + if (sid == CfwTransport.SID) { + for (lens in 1..2) core.onNotification(address, BleProtocol.NOTIFY_CHAR_UUID, cfwAck(magic, lens, inFlight.message.size, inFlight.cfwChecksum)) + } else { + val joined = frames.flatMap { frame -> frame.slice(8 until 8 + (frame[3].toInt() and 255)) }.toByteArray() + val pb = joined.copyOf(maxOf(0, joined.size - 2)) + core.onNotification(address, BleProtocol.NOTIFY_CHAR_UUID, ackFrame(sid, magic, pb)) + } + } + return true + } + + private fun ackFrame(sid: Int, magic: Int, request: ByteArray): ByteArray { + val body = if (sid == BleProtocol.SID_SECURITY_AUTH) + BleProtocol.encodeVarintField(1, 4) + BleProtocol.encodeVarintField(2, magic) + byteArrayOf(0x1a, 0x00) + else + BleProtocol.encodeVarintField(1, 1) + BleProtocol.encodeVarintField(2, magic) + return lock.withLock { BleProtocol.framePb(body, sid, 0x00, seq++)[0] } + } + + private fun cfwAck(streamId: Int, lens: Int, size: Int, checksum: Int): ByteArray { + val packet = ByteArray(19) + packet[0] = 0xaa.toByte() + packet[1] = 0x12 + packet[3] = 11 + packet[4] = 1 + packet[5] = 1 + packet[6] = CfwTransport.SID.toByte() + packet[8] = 1 + packet[9] = streamId.toByte() + packet[12] = lens.toByte() + packet[13] = size.toByte() + packet[14] = (size ushr 8).toByte() + packet[15] = checksum.toByte() + packet[16] = (checksum ushr 8).toByte() + val crc = CfwTransport.crc(packet.copyOfRange(8, 17)) + packet[17] = crc.toByte() + packet[18] = (crc ushr 8).toByte() + return packet + } + + override fun disconnect(address: String) { + disconnected.add(address) + connected.remove(address) + } + + override fun close() { + closed = true + } + + override fun isBonded(address: String): Boolean = true + + override fun prepareBenchmarkLink(address: String, mode: Int) {} + + override fun recordDisplayFrameSent() {} +} + +private class MainThreadListener : FaceclawBleCommunicatorListener { + val phases = ArrayList() + var offMainCallbacks = 0 + + private fun record(phase: String) { + if (!NSThread.isMainThread) offMainCallbacks++ + phases.add(phase) + } + + override fun onStateChange(phase: String?, status: String?) = record(phase ?: "") + + override fun onRingEvent(kind: String?, containerName: String?, eventType: Int, eventSource: Int, systemExitReasonCode: Int, frameId: Int, ringTick: Long, ringType: Int, ringAux: Int, ringSpeed: Int) {} + + override fun onBatteryState(headsetBattery: Int, headsetCharging: Int, ringBattery: Int, ringCharging: Int) { + if (!NSThread.isMainThread) offMainCallbacks++ + } + + override fun onSilentMode(silent: Boolean) {} + + override fun onWearState(wearing: Boolean) {} + + override fun onPhoneLockState(locked: Boolean) {} + + override fun onEvenAppConflict(message: String?) {} + + override fun onFrameMetrics(paintMs: Int, transmitMs: Int, tileCount: Int) {} + + override fun onFrameFinished(frameId: Int, outcome: String?) {} + + override fun onFirmwareInfo(leftVersion: String?, rightVersion: String?, extension: String?) {} +} + +class IosSessionFacadeTest { + @Test + fun facadeSessionConnectsOverAnInjectedLinkAndReportsOnTheMainQueue() { + assertTrue(NSThread.isMainThread, "tests drive the main run loop") + val link = FakeIosLink() + val host = IosSessionHost(threadName = "test-session") + val session = IosGlassesSession(link, null, host, RIGHT, LEFT, "", IosProtocolPlatform) + link.core = session.coreForTests() + val listener = MainThreadListener() + session.setListener(listener) + assertTrue(session.start()) + assertFalse(session.start(), "already running") + assertTrue(pumpMainUntil(5_000) { listener.phases.contains("connected") }, "phases=${listener.phases}") + assertTrue(session.isSessionReady()) + assertEquals(0, listener.offMainCallbacks, "listener callbacks must arrive on the main queue") + assertTrue(pumpMainUntil(5_000) { link.writes > 3 }, "auth, prelude, settings and layout writes (saw ${link.writes})") + session.disconnect() + assertTrue(pumpMainUntil(2_000) { listener.phases.lastOrNull() == "disconnected" }, "phases=${listener.phases}") + assertFalse(session.isSessionReady()) + assertTrue(link.closed) + assertEquals(listOf(RIGHT, LEFT), link.disconnected.takeLast(2)) + assertEquals(0, listener.offMainCallbacks) + } + + @Test + fun relayFramesReachTheAncsListenerOnMainAndOtherFramesDoNot() { + val link = FakeIosLink() + val host = IosSessionHost(threadName = "test-session-ancs") + val session = IosGlassesSession(link, null, host, RIGHT, LEFT, "", IosProtocolPlatform) + val core = session.coreForTests() + link.core = core + val relayed = ArrayList() + var offMain = 0 + session.setAncsListener(object : IosAncsListener { + override fun onAncsAuthorization(authorized: Boolean) {} + + override fun onRelayFrame(data: platform.Foundation.NSData) { + if (!NSThread.isMainThread) offMain++ + relayed.add(data.byteArray()) + } + }) + val relay = byteArrayOf(65, 78, 1, 0, 9, 9, 9, 9, 0, 0, 0) + core.onNotification(RIGHT, BleProtocol.NOTIFY_CHAR_UUID, relay) + core.onNotification(LEFT, BleProtocol.NOTIFY_CHAR_UUID, relay) // wrong arm: ignored by the tap + assertTrue(pumpMainUntil(2_000) { relayed.size == 1 }) + assertEquals(relay.toList(), relayed[0].toList()) + assertEquals(0, offMain) + session.setAncsListener(null) + core.onNotification(RIGHT, BleProtocol.NOTIFY_CHAR_UUID, relay) + assertFalse(pumpMainUntil(200) { relayed.size > 1 }) + } + + @Test + fun hostDispatchesToTheCallingQueueAndRunsTheWorker() { + val host = IosSessionHost(threadName = "test-host") + var onMain = false + host.currentThreadDispatcher().post { onMain = NSThread.isMainThread } + assertTrue(pumpMainUntil(1_000) { onMain }) + var workerThread = "" + host.startWorker { workerThread = NSThread.currentThread.name ?: "" } + host.joinWorker(2_000) + assertEquals("test-host", workerThread) + var posted = false + host.postToMain { posted = NSThread.isMainThread } + assertTrue(pumpMainUntil(1_000) { posted }) + assertFalse(host.isEvenAppActive()) + } + + @Test + fun stockFlowFacadesConstructWithoutBluetooth() { + // No CoreBluetooth on the simulator; construction and cancel/close must still be safe. + val probe = IosDeviceInfoProbe(RIGHT, LEFT) + probe.setListener(null) + probe.close() + val prompt = IosFlashPrompt(RIGHT, LEFT, "warn", true) + prompt.close() + val flasher = IosFirmwareFlasher(RIGHT, LEFT, "/nonexistent.bin") + flasher.close() + assertNotNull(IosFrameTimings.shared.core.buildExport()) + } +}