diff --git a/ShimmerBluetooth/ShimmerBluetooth/BleByteRadio.swift b/ShimmerBluetooth/ShimmerBluetooth/BleByteRadio.swift index afdb54e..6617290 100644 --- a/ShimmerBluetooth/ShimmerBluetooth/BleByteRadio.swift +++ b/ShimmerBluetooth/ShimmerBluetooth/BleByteRadio.swift @@ -60,7 +60,11 @@ public class BleByteRadio : NSObject, ByteCommunication { public func connect() async -> Bool? { - await self.bluetoothManager!.connect(activePeripheral: activePeripheral!) + // A connect CoreBluetooth failed or gave up on never reaches service discovery: return now + // instead of waiting for characteristics that will not come. + guard await self.bluetoothManager!.connect(activePeripheral: activePeripheral!) == true else { + return false + } /* if self.centralManager.state != .poweredOn { diff --git a/ShimmerBluetooth/ShimmerBluetooth/BluetoothManager.swift b/ShimmerBluetooth/ShimmerBluetooth/BluetoothManager.swift index fe79042..38bd7ec 100644 --- a/ShimmerBluetooth/ShimmerBluetooth/BluetoothManager.swift +++ b/ShimmerBluetooth/ShimmerBluetooth/BluetoothManager.swift @@ -110,10 +110,10 @@ public class BluetoothManager: NSObject { self.centralManager.connect(activePeripheral, options: [CBConnectPeripheralOptionNotifyOnDisconnectionKey : NSNumber(value: true)]) return await withCheckedContinuation { continuation in - if self.continuation == nil { - // 2 - self.continuation = continuation - } + // A connect that never completed (CoreBluetooth never times one out) is given up on + // here, so it cannot take this attempt's didConnect. + self.continuation?.resume(returning: false) + self.continuation = continuation } } @@ -185,6 +185,8 @@ extension BluetoothManager: CBCentralManagerDelegate { }*/ public func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { print("[ERROR] Could not connecto to peripheral \(peripheral.identifier.uuidString)") + self.continuation?.resume(returning: false) + self.continuation = nil let pname = peripheral.name delegates![pname!]!?.isDisconnected() } diff --git a/ShimmerBluetooth/ShimmerBluetooth/Shimmer3Protocol.swift b/ShimmerBluetooth/ShimmerBluetooth/Shimmer3Protocol.swift index c2cf34d..bdbc467 100644 --- a/ShimmerBluetooth/ShimmerBluetooth/Shimmer3Protocol.swift +++ b/ShimmerBluetooth/ShimmerBluetooth/Shimmer3Protocol.swift @@ -26,7 +26,8 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol { } var startTime = Date() - var numberOfPackets = 0 + /// Packets received since streaming started; the numerator of the trial PRR. + public private(set) var numberOfPackets = 0 public var REV_HW_MAJOR: Int = -1 public var REV_HW_MINOR: Int = -1 @@ -44,6 +45,10 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol { public var EXPANSION_BOARD_REV: Int = -1 public var EXPANSION_BOARD_REV_SPECIAL: Int = -1 + /// The Bluetooth radio's own version string, as sendReadBtFwVersionCommand() read it, e.g. + /// "RN4678 V1.23 06/30/2021 (c)Microchip Technology Inc" or "CYW20820 app=v01.04.16.16". + /// Empty until read. ShimmerUtilities.btModuleDisplayName gives the short form. + public private(set) var btModuleVersion: String = "" public var internalExpPower:Int = -1 public var lnAccelSensor: LNAccelSensor = LNAccelSensor(hwid: HardwareType.UNKNOWN.rawValue) public var wrAccelSensor: WRAccelSensor = WRAccelSensor(hwid: HardwareType.UNKNOWN.rawValue) @@ -683,10 +688,14 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol { // Start the processing loop func startProcessing() { - self.receivedBytes.removeAll() + queue.sync(flags: .barrier) { self.receivedBytes.removeAll() } self.processing = true processingQueue.async { while self.processing { + // Each pass holds `queue` exclusively, as processData's append does, so the buffer + // is never read here while it is being appended to on the Bluetooth thread. + // Unsynchronized, the two corrupted the array (SIGABRT mid-stream). + self.queue.sync(flags: .barrier) { if (self.processStatusPushAtHead()){ /* An unsolicited status push, consumed if it has all arrived and otherwise * held until it has. It is neither a reply nor a data packet, so neither @@ -734,7 +743,10 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol { if (self.commandSent==PacketTypeShimmer.getCalibDumpCommand){ if (self.receivedBytes.count > 1 && self.receivedBytes[1] == PacketTypeShimmer.calibDumpResponse.rawValue) { - Thread.sleep(forTimeInterval: 0.5) + // Not all here yet: end this pass and look again on the next. A sleep + // here would hold `queue`, so the rest could never arrive. + guard self.receivedBytes.count >= 3, + self.receivedBytes.count >= Int(self.receivedBytes[2]) + 3 + 2 + Int(self.CRCMode.rawValue) else { return } var received = self.receivedBytes print("\(received.count) data: \(received)") let length = received[2] @@ -768,7 +780,9 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol { if (self.commandSent==PacketTypeShimmer.getInfoMem){ if (self.receivedBytes.count > 1 && self.receivedBytes[1] == PacketTypeShimmer.getInfoMemResponse.rawValue) { - Thread.sleep(forTimeInterval: 0.5) + // Not all here yet: end this pass and look again on the next (see calib dump). + guard self.receivedBytes.count >= 3, + self.receivedBytes.count >= Int(self.receivedBytes[2]) + 3 + Int(self.CRCMode.rawValue) else { return } //print(self.receivedBytes) var received = self.receivedBytes //print(received) @@ -799,6 +813,8 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol { } if (self.commandSent==PacketTypeShimmer.setCRCCommand){ + // The ACK's CRC can arrive in a later notification: wait for it. + guard self.receivedBytes.count >= 1+Int(self.CRCMode.rawValue) else { return } let received = Array(self.receivedBytes.prefix(1+Int(self.CRCMode.rawValue))) self.receivedBytes.removeFirst(1+Int(self.CRCMode.rawValue)) var crcresult = true @@ -817,6 +833,8 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol { } print("Command ACK Received and Processed: \(self.commandSent!)") } else if(self.commandSent == PacketTypeShimmer.setInfoMem){ + // The ACK's CRC can arrive in a later notification: wait for it. + guard self.receivedBytes.count >= 1+Int(self.CRCMode.rawValue) else { return } let received = Array(self.receivedBytes.prefix(1+Int(self.CRCMode.rawValue))) self.receivedBytes.removeFirst(1+Int(self.CRCMode.rawValue)) var crcresult = true @@ -882,9 +900,11 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol { } } else if (self.commandSent==PacketTypeShimmer.getShimmerVersionCommand){ - if (self.receivedBytes[1] == PacketTypeShimmer.getShimmerVersionResponse.rawValue) + if (self.receivedBytes.count > 1 && self.receivedBytes[1] == PacketTypeShimmer.getShimmerVersionResponse.rawValue) { var length = 1 + 1 + 1 + Int(self.CRCMode.rawValue)//ack + response byte + 1 + // Not all here yet: end this pass and look again on the next (see calib dump). + guard self.receivedBytes.count >= length else { return } var received = Array(self.receivedBytes.prefix(length)) self.receivedBytes.removeFirst(length) var crcresult = true @@ -910,11 +930,14 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol { } } else if (self.commandSent==PacketTypeShimmer.getDaughterCardIDCommand){ - if (self.receivedBytes[1] == PacketTypeShimmer.daughterCardIDResponse.rawValue) + if (self.receivedBytes.count > 1 && self.receivedBytes[1] == PacketTypeShimmer.daughterCardIDResponse.rawValue) { + // Not all here yet: end this pass and look again on the next (see calib dump). + guard self.receivedBytes.count > 2 else { return } var len = Int(self.receivedBytes[2]); var length = 1 + 1 + 1 + len + Int(self.CRCMode.rawValue)//ack + response byte + 1 (length) + guard self.receivedBytes.count >= length else { return } var received = Array(self.receivedBytes.prefix(length)) self.receivedBytes.removeFirst(length) var crcresult = true @@ -944,9 +967,11 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol { } } else if (self.commandSent==PacketTypeShimmer.getFWVersionCommand){ - if (self.receivedBytes[1] == PacketTypeShimmer.fwVersionResponse.rawValue) + if (self.receivedBytes.count > 1 && self.receivedBytes[1] == PacketTypeShimmer.fwVersionResponse.rawValue) { var length = 1 + 1 + 6 + Int(self.CRCMode.rawValue)//ack + response byte + 1 + // Not all here yet: end this pass and look again on the next (see calib dump). + guard self.receivedBytes.count >= length else { return } var received = Array(self.receivedBytes.prefix(length)) self.receivedBytes.removeFirst(length) var crcresult = true @@ -978,6 +1003,8 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol { }else if (self.commandSent==PacketTypeShimmer.startStreamingCommand){ print("Start Streaming ACK Received") + // The ACK's CRC can arrive in a later notification: wait for it. + guard self.receivedBytes.count >= 1+Int(self.CRCMode.rawValue) else { return } let received = Array(self.receivedBytes.prefix(1+Int(self.CRCMode.rawValue))) self.receivedBytes.removeFirst(1+Int(self.CRCMode.rawValue)) print(received) @@ -997,10 +1024,11 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol { } } else if (self.commandSent==PacketTypeShimmer.getBmp280CalibrationCoefficientsCommand){ - if (self.receivedBytes[1] == PacketTypeShimmer.bmp280CalibrationCoefficientsResponse.rawValue) + if (self.receivedBytes.count > 1 && self.receivedBytes[1] == PacketTypeShimmer.bmp280CalibrationCoefficientsResponse.rawValue) { print("Get Bmp280 Calib Coefficient ACK Received") - Thread.sleep(forTimeInterval: 0.5) + // Not all here yet: end this pass and look again on the next (see calib dump). + guard self.receivedBytes.count >= 1 + 1 + 24 + Int(self.CRCMode.rawValue) else { return } var length = 1 + 1 + 24 //ack + response byte + 24 @@ -1032,6 +1060,8 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol { }else if (self.commandSent==PacketTypeShimmer.setSamplingRateCommand){ print("Set Sampling Rate Command ACK Received") + // The ACK's CRC can arrive in a later notification: wait for it. + guard self.receivedBytes.count >= 1+Int(self.CRCMode.rawValue) else { return } let received = Array(self.receivedBytes.prefix(1+Int(self.CRCMode.rawValue))) self.receivedBytes.removeFirst(1+Int(self.CRCMode.rawValue)) var crcresult = true @@ -1056,6 +1086,8 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol { }else if (self.commandSent==PacketTypeShimmer.setExgRegsCommand){ print("Set Exg Regs Command ACK Received") + // The ACK's CRC can arrive in a later notification: wait for it. + guard self.receivedBytes.count >= 1+Int(self.CRCMode.rawValue) else { return } let received = Array(self.receivedBytes.prefix(1+Int(self.CRCMode.rawValue))) self.receivedBytes.removeFirst(1+Int(self.CRCMode.rawValue)) var crcresult = true @@ -1100,9 +1132,34 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol { } } } + else if (self.commandSent == PacketTypeShimmer.getBtFwVersionStrCommand) { + if self.receivedBytes.count > 2 && self.receivedBytes[1] == PacketTypeShimmer.btFwVersionStrResponse.rawValue { + // [ACK][0xA2][len][len bytes of version text][CRC]. Longer than one BLE + // notification, so wait for all of it. + let length = 1 + 1 + 1 + Int(self.receivedBytes[2]) + Int(self.CRCMode.rawValue) + if self.receivedBytes.count >= length { + let received = Array(self.receivedBytes.prefix(length)) + self.receivedBytes.removeFirst(length) + var crcresult = true + if self.CRCMode != BTCRCMode.OFF { + crcresult = self.checkCrc(received, received.count - Int(self.CRCMode.rawValue)) + } + if crcresult { + self.btModuleVersion = String(decoding: received[3..<(length - Int(self.CRCMode.rawValue))], as: UTF8.self) + print("BT module version: \(self.btModuleVersion)") + } else { + print("[CRC ERROR] : \(self.commandSent!)") + } + self.continuation?.resume(returning: crcresult) + self.continuation = nil + } + } + } else if (self.commandSent == PacketTypeShimmer.setSensorsCommand) { print("Set Sensors Command ACK Received") + // The ACK's CRC can arrive in a later notification: wait for it. + guard self.receivedBytes.count >= 1+Int(self.CRCMode.rawValue) else { return } let received = Array(self.receivedBytes.prefix(1 + Int(self.CRCMode.rawValue))) self.receivedBytes.removeFirst(1 + Int(self.CRCMode.rawValue)) @@ -1127,6 +1184,8 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol { else if (self.commandSent == PacketTypeShimmer.setInternalEXPPowerEnableCommand) { print("Set EXP Power ACK Received") + // The ACK's CRC can arrive in a later notification: wait for it. + guard self.receivedBytes.count >= 1+Int(self.CRCMode.rawValue) else { return } let received = Array(self.receivedBytes.prefix(1 + Int(self.CRCMode.rawValue))) self.receivedBytes.removeFirst(1 + Int(self.CRCMode.rawValue)) @@ -1150,9 +1209,10 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol { } } } - - - + } + + + /* self.queue.sync { if self.receivedBytes.count>0{ @@ -1671,6 +1731,12 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol { return true } + /// The sampling rate (Hz) the PRR expectation is calculated from. + public var currentSamplingRate: Double { return CurrentSamplingRate } + /// Streaming packet length in bytes on the wire: start byte, payload and CRC. + /// Zero until sensors have been initialised. + public var packetSizeBytes: Int { return PacketSize + 1 } + private func sendCRCCommand(crcMode:BTCRCMode) async ->Bool?{ // Refused rather than sent when this firmware cannot carry it (strongestSafeCRCMode). let strongestSafe = strongestSafeCRCModeForDevice() @@ -1802,6 +1868,21 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol { } } + /// Reads the Bluetooth radio's version string into btModuleVersion (0xA1, reply 0xA2). + /// Supported from Shimmer3 LogAndStream v0.13.7 and on every Shimmer3R; older firmware NACKs. + public func sendReadBtFwVersionCommand() async -> Bool?{ + let bytes: [UInt8] = [PacketTypeShimmer.getBtFwVersionStrCommand.rawValue] + guard self.continuation == nil, let radio = radio else { + print("Cannot send command: another command is already awaiting an ACK") + return false + } + commandSent = PacketTypeShimmer.getBtFwVersionStrCommand + return await withCheckedContinuation { continuation in + self.continuation = continuation // stored before the write so a fast reply finds it + radio.writeBytes(bytes: bytes) + } + } + private func sendPressureCalibCoefficientsCommand() async -> Bool?{ let bytes: [UInt8] = [PacketTypeShimmer.getpressureCalibrationCoefficientsCommand.rawValue] commandSent = PacketTypeShimmer.getpressureCalibrationCoefficientsCommand @@ -2324,6 +2405,8 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol { case bmp280CalibrationCoefficientsResponse = 0x9F case getpressureCalibrationCoefficientsCommand = 0xA7 case pressureCalibrationCoefficientsResponse = 0xA6 + case getBtFwVersionStrCommand = 0xA1 + case btFwVersionStrResponse = 0xA2 case setExgRegsCommand = 0x61 case exgRegsResponse = 0x62 case getExgRegsCommand = 0x63 diff --git a/ShimmerBluetooth/ShimmerBluetooth/ShimmerUtilities.swift b/ShimmerBluetooth/ShimmerBluetooth/ShimmerUtilities.swift index 1d7988b..849733a 100644 --- a/ShimmerBluetooth/ShimmerBluetooth/ShimmerUtilities.swift +++ b/ShimmerBluetooth/ShimmerBluetooth/ShimmerUtilities.swift @@ -214,6 +214,27 @@ public class ShimmerUtilities{ return crcCalcArray } + /// The short radio name the BLE-Throughput wiki uses, from the Bluetooth module's version + /// string (Shimmer3Protocol.btModuleVersion). An unrecognised string is returned trimmed. + /// "RN4678 V1.23 06/30/2021 (c)Microchip Technology Inc" -> "RN4678 v1.23" + /// "CYW20820 app=v01.04.16.16" -> "IF820 v01.04.16.16" + /// The IF820 module is built on the CYW20820. Java's BluetoothModuleVersionDetails maps the + /// same strings by table, with two slips (V1.22 -> "v1.23", V1.13.5 -> "v1.15.5"); this + /// takes the version from the string itself. + public static func btModuleDisplayName(_ version: String) -> String { + let s = version.trimmingCharacters(in: .whitespacesAndNewlines.union(.controlCharacters)) + let words = s.split(separator: " ") + // Only the version's digits and dots: the IF820 follows it with a comma. + func versionDigits(_ w: Substring) -> Substring { w.prefix(while: { $0.isNumber || $0 == "." }) } + if words.count >= 2, words[0] == "RN4678", words[1].hasPrefix("V") { + return "RN4678 v\(versionDigits(words[1].dropFirst()))" + } + if words.count >= 2, words[0] == "CYW20820", words[1].hasPrefix("app=v") { + return "IF820 v\(versionDigits(words[1].dropFirst("app=v".count)))" + } + return s + } + static func shimmerUartCrcByte(_ crc: Int, _ b: UInt8) -> Int { var crcValue = crc & 0xFFFF crcValue = (crcValue >> 8) | (crcValue << 8) diff --git a/ShimmerBluetooth/ShimmerBluetoothTests/ShimmerUtilitiesTest.swift b/ShimmerBluetooth/ShimmerBluetoothTests/ShimmerUtilitiesTest.swift index fd216d9..c98bcb5 100644 --- a/ShimmerBluetooth/ShimmerBluetoothTests/ShimmerUtilitiesTest.swift +++ b/ShimmerBluetooth/ShimmerBluetoothTests/ShimmerUtilitiesTest.swift @@ -289,4 +289,18 @@ class ShimmerUtilitiesTest: XCTestCase { XCTAssertEqual(ShimmerUtilities.shimmerUartCrcCalc([0xFF, 0x8A, 0x71, 0x52, 0xAA], 4), [0x00, 0xE6], "only the first len bytes count") } + func testBtModuleDisplayName() { + // Full strings from the Java API's BluetoothModuleVersionDetails + XCTAssertEqual(ShimmerUtilities.btModuleDisplayName("RN4678 V1.23 06/30/2021 (c)Microchip Technology Inc"), "RN4678 v1.23") + XCTAssertEqual(ShimmerUtilities.btModuleDisplayName("RN4678 V1.22 12/08/2020 (c)Microchip Technology Inc "), "RN4678 v1.22") + XCTAssertEqual(ShimmerUtilities.btModuleDisplayName("RN4678 V1.00.5 11/15/2016 (c)Microchip Technology Inc"), "RN4678 v1.00.5") + XCTAssertEqual(ShimmerUtilities.btModuleDisplayName("CYW20820 app=v01.04.16.16"), "IF820 v01.04.16.16") + XCTAssertEqual(ShimmerUtilities.btModuleDisplayName("CYW20820 app=v01.04.18.18\r\n"), "IF820 v01.04.18.18", "trailing CR LF") + XCTAssertEqual(ShimmerUtilities.btModuleDisplayName("CYW20820 app=v01.04.16.16, stack=v2.0"), "IF820 v01.04.16.16", + "a comma after the version, as a Shimmer3R v1.01.025 sends; kept, it split the CSV field") + XCTAssertEqual(ShimmerUtilities.btModuleDisplayName("RN4678 V1.23, 06/30/2021"), "RN4678 v1.23") + XCTAssertEqual(ShimmerUtilities.btModuleDisplayName("Ver 6.15 04/26/2013\r\n(c) Roving Networks"), "Ver 6.15 04/26/2013\r\n(c) Roving Networks", "unknown: kept") + XCTAssertEqual(ShimmerUtilities.btModuleDisplayName(""), "") + } + } diff --git a/TestApp/TestApp.xcodeproj/project.pbxproj b/TestApp/TestApp.xcodeproj/project.pbxproj index d0392c6..3e669f8 100644 --- a/TestApp/TestApp.xcodeproj/project.pbxproj +++ b/TestApp/TestApp.xcodeproj/project.pbxproj @@ -15,6 +15,8 @@ 3A780CCB2AE12CC500EAF050 /* TestAppUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A780CCA2AE12CC500EAF050 /* TestAppUITests.swift */; }; 3A780CCD2AE12CC500EAF050 /* TestAppUITestsLaunchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A780CCC2AE12CC500EAF050 /* TestAppUITestsLaunchTests.swift */; }; 3A780CDC2AE12F2C00EAF050 /* ViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A780CDB2AE12F2C00EAF050 /* ViewModel.swift */; }; + 3A780CDE2AE1300000EAF050 /* ThroughputRunner.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A780CDF2AE1300000EAF050 /* ThroughputRunner.swift */; }; + 3A780CE02AE1300000EAF050 /* ThroughputView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A780CE12AE1300000EAF050 /* ThroughputView.swift */; }; 3AD18D8A2AE1436800AE7475 /* ShimmerBluetooth.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3AD18D892AE1436800AE7475 /* ShimmerBluetooth.framework */; }; 3AD18D8B2AE1436800AE7475 /* ShimmerBluetooth.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 3AD18D892AE1436800AE7475 /* ShimmerBluetooth.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; /* End PBXBuildFile section */ @@ -65,6 +67,8 @@ 3A780CCA2AE12CC500EAF050 /* TestAppUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestAppUITests.swift; sourceTree = ""; }; 3A780CCC2AE12CC500EAF050 /* TestAppUITestsLaunchTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestAppUITestsLaunchTests.swift; sourceTree = ""; }; 3A780CDB2AE12F2C00EAF050 /* ViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewModel.swift; sourceTree = ""; }; + 3A780CDF2AE1300000EAF050 /* ThroughputRunner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ThroughputRunner.swift; sourceTree = ""; }; + 3A780CE12AE1300000EAF050 /* ThroughputView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ThroughputView.swift; sourceTree = ""; }; 3AD18D892AE1436800AE7475 /* ShimmerBluetooth.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; path = ShimmerBluetooth.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ @@ -121,6 +125,8 @@ 3A7712932AE2BAF9006213A8 /* Info.plist */, 3A7712922AE2B5C9006213A8 /* TestAppDebug.entitlements */, 3A780CDB2AE12F2C00EAF050 /* ViewModel.swift */, + 3A780CDF2AE1300000EAF050 /* ThroughputRunner.swift */, + 3A780CE12AE1300000EAF050 /* ThroughputView.swift */, 3A780CAE2AE12CC400EAF050 /* TestAppApp.swift */, 3A780CB02AE12CC400EAF050 /* ContentView.swift */, 3A780CB22AE12CC500EAF050 /* Assets.xcassets */, @@ -296,6 +302,8 @@ files = ( 3A780CB12AE12CC400EAF050 /* ContentView.swift in Sources */, 3A780CDC2AE12F2C00EAF050 /* ViewModel.swift in Sources */, + 3A780CDE2AE1300000EAF050 /* ThroughputRunner.swift in Sources */, + 3A780CE02AE1300000EAF050 /* ThroughputView.swift in Sources */, 3A780CAF2AE12CC400EAF050 /* TestAppApp.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -467,6 +475,8 @@ INFOPLIST_FILE = TestApp/Info.plist; INFOPLIST_KEY_LSApplicationCategoryType = ""; INFOPLIST_KEY_NSBluetoothAlwaysUsageDescription = "Allow for Bluetooth use"; + INFOPLIST_KEY_LSSupportsOpeningDocumentsInPlace = YES; + INFOPLIST_KEY_UIFileSharingEnabled = YES; INFOPLIST_KEY_NSBluetoothPeripheralUsageDescription = "Please allow using Blueooth for discovering peripherals"; INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES; @@ -518,6 +528,8 @@ INFOPLIST_FILE = TestApp/Info.plist; INFOPLIST_KEY_LSApplicationCategoryType = ""; INFOPLIST_KEY_NSBluetoothAlwaysUsageDescription = "Allow for Bluetooth use"; + INFOPLIST_KEY_LSSupportsOpeningDocumentsInPlace = YES; + INFOPLIST_KEY_UIFileSharingEnabled = YES; INFOPLIST_KEY_NSBluetoothPeripheralUsageDescription = "Please allow using Blueooth for discovering peripherals"; INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES; diff --git a/TestApp/TestApp/ContentView.swift b/TestApp/TestApp/ContentView.swift index dfe68b7..3ad4f24 100644 --- a/TestApp/TestApp/ContentView.swift +++ b/TestApp/TestApp/ContentView.swift @@ -9,7 +9,8 @@ import SwiftUI struct ContentView: View { @StateObject var viewModel = ViewModel() - + @State private var showThroughput = false + var body: some View { VStack { Image(systemName: "globe") @@ -19,8 +20,9 @@ struct ContentView: View { } .padding() - - + + Button("Throughput Test", action: { showThroughput = true }) + .sheet(isPresented: $showThroughput) { ThroughputView() } Button("Scan Veri",action: { viewModel.test()}) Button("Connect Dev1",action: { Task { do { diff --git a/TestApp/TestApp/ThroughputRunner.swift b/TestApp/TestApp/ThroughputRunner.swift new file mode 100644 index 0000000..5e82aac --- /dev/null +++ b/TestApp/TestApp/ThroughputRunner.swift @@ -0,0 +1,317 @@ +// +// ThroughputRunner.swift +// TestApp +// +// Not yet run against a Shimmer. See docs/THROUGHPUT_AUTOMATION.md. +// +// Runs the BLE-Throughput wiki matrix against one or more Shimmer3 / Shimmer3R, found by name, one +// device after another: scan, connect, record versions, then for each config set CRC -> rate -> +// sensors, stream, count, stop. Writes the wiki table as CSV for tools/throughput/update_wiki.py. +// +import Foundation +import CoreBluetooth +import ShimmerBluetooth + +struct ThroughputConfig { + let label: String // "LN Accel, GSR, PPG" + let sensorBitmap: UInt32 // for sendSetSensorsCommand + let payloadBytes: Int // sensor bytes excluding start byte, timestamp and CRC (the check) + let rateHz: Double + let crc: Shimmer3Protocol.BTCRCMode + let seconds: Int + let repeats: Int +} + +struct ThroughputRow { + var device = "", fw = "", hw = "", radio = "", expBoard = "", ios = "", app = "", phone = "" + var config = "", crc = 0, rateHz = 0.0, seconds = 0, run = 0 + var attempts = 0 // 1 if the first try was ok; up to 1 + maxRetries + var packetBytes = 0, expectedPacketBytes = 0 + var received = 0, expected = 0 + var prrApi = 0.0 // the API's own trial PRR, clamped to 100 + var prrRaw = 0.0 // received / expected, NOT clamped, so >100% is visible + var wallSeconds = 0.0 + var status = "ok" // ok | connect-failed | config-failed | size-mismatch | stalled | disconnected | device-stopped | stop-timeout | stop-failed +} + +/// Whichever of an operation and its timer finishes first resumes; the other does nothing. +@MainActor +private final class TimeoutOnce { var done = false } + +@MainActor +final class ThroughputRunner: NSObject, ShimmerProtocolDelegate, BluetoothManagerDelegate { + private let central = CBCentralManager() + private lazy var manager = BluetoothManager(centralmanager: central) + private var radio: BleByteRadio? + private var proto: Shimmer3Protocol? + private var scanContinuation: CheckedContinuation? + /// False once the link drops or a command goes unanswered; the next run reconnects first. + /// Shimmer3Protocol has no command timeout, so a reply that never comes leaves its pending + /// command suspended and refuses every later one on that instance. + private var linkUp = false + private var deviceStreaming = false // false once the device reports it left STREAMING + /// Called with a one-line status as the run moves on (device, config, run number). + var onProgress: ((String) -> Void)? + /// A run that is not ok is tried again up to this many times; only the last try is recorded. + var maxRetries = 3 + + // MARK: matrix (mirrors wiki Test Results 3 and 4) + static func wikiMatrix() -> [ThroughputConfig] { + let bitmap = Shimmer3Protocol.SensorBitmapShimmer3.SENSOR_LN_ACCEL.rawValue + | Shimmer3Protocol.SensorBitmapShimmer3.SENSOR_GSR.rawValue + | Shimmer3Protocol.SensorBitmapShimmer3.SENSOR_INT_A1.rawValue // PPG (A13) - VERIFY bit + // 6 accel + 2 GSR + 2 PPG = 10 payload bytes (the wiki's 15 / 16 bytes = 1 start + 3 ts + 10 + CRC) + return [Shimmer3Protocol.BTCRCMode.ONE_BYTE, Shimmer3Protocol.BTCRCMode.TWO_BYTE].map { + ThroughputConfig(label: "LN Accel, GSR, PPG", sensorBitmap: bitmap, payloadBytes: 10, + rateHz: 128, crc: $0, seconds: 60, repeats: 1) // one ok run each; failures are retried + } + } + + // MARK: scan for every Shimmer in range + /// Names of the Shimmers advertising within `seconds`, sorted. Empty if Bluetooth is off. + func scanShimmers(seconds: Double = 8) async -> [String] { + manager.delegate = self + guard manager.startScanning(timeout: seconds) else { return [] } + await withCheckedContinuation { scanContinuation = $0 } // resumed by scanCompleted() + let names = manager.getDiscoveredPeripherals().compactMap { $0.name }.filter { $0.hasPrefix("Shimmer") } + return Array(Set(names)).sorted() + } + + // MARK: connect by name + func connect(deviceName: String, scanSeconds: Double = 15) async -> Bool { + manager.delegate = self + guard manager.startScanning(deviceName: deviceName, timeout: scanSeconds) else { return false } + await withCheckedContinuation { scanContinuation = $0 } // resumed by scanCompleted() + guard let peripheral = manager.getPeripheral(deviceName: deviceName) else { return false } + let radio = BleByteRadio(deviceName: deviceName, cbperipheral: peripheral, bluetoothManager: manager) + let proto = Shimmer3Protocol(radio: radio) + proto.delegate = self + self.radio = radio; self.proto = proto + linkUp = await withTimeout(45) { await proto.connect() } ?? false + return linkUp + } + func disconnect() async { + if linkUp, let p = proto { _ = await withTimeout(10) { await p.disconnect() } } + else { _ = await radio?.disconnect() } // drop the link without waiting for any reply + linkUp = false + } + + /// `op`'s result, or nil if it has not finished within `seconds`. Swift cannot cancel a + /// suspended continuation, so on timeout `op` is left suspended and the link is marked down. + private func withTimeout(_ seconds: Double, _ op: @escaping @MainActor () async -> T) async -> T? { + let once = TimeoutOnce() + let result: T? = await withCheckedContinuation { c in + Task { @MainActor in + let v = await op() + if !once.done { once.done = true; c.resume(returning: v) } + } + Task { @MainActor in + try? await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000)) + if !once.done { once.done = true; c.resume(returning: nil) } + } + } + if result == nil { linkUp = false } + return result + } + + // MARK: run + /// Runs the matrix on each device in turn. A device that fails to connect gives one + /// connect-failed row and the run moves on to the next. + func run(deviceNames: [String], matrix: [ThroughputConfig], appVersion: String, ios: String, phone: String) async -> [ThroughputRow] { + var rows: [ThroughputRow] = [] + for name in deviceNames { + rows += await run(deviceName: name, matrix: matrix, appVersion: appVersion, ios: ios, phone: phone) + } + return rows + } + + func run(deviceName: String, matrix: [ThroughputConfig], appVersion: String, ios: String, phone: String) async -> [ThroughputRow] { + var rows: [ThroughputRow] = [] + var base = ThroughputRow(); base.device = deviceName; base.ios = ios; base.app = appVersion; base.phone = phone + var connected = false + onProgress?("\(deviceName): connecting") + for attempt in 0..<2 where !connected { // one retry + if attempt > 0 { + await disconnect() // drop the first attempt, or the retry finds the peripheral half-connected + try? await Task.sleep(nanoseconds: 3_000_000_000) + } + connected = await connect(deviceName: deviceName) + } + guard connected, var p = proto else { + onProgress?("\(deviceName): connect failed") + base.status = "connect-failed"; return [base] + } + base.fw = "\(p.REV_FW_MAJOR).\(p.REV_FW_MINOR).\(p.REV_FW_INTERNAL)" + base.hw = p.REV_HW_MAJOR == Shimmer3Protocol.HardwareType.Shimmer3R.rawValue ? "Shimmer3R" : "Shimmer3" + base.expBoard = "SR\(p.EXPANSION_BOARD_ID)-\(p.EXPANSION_BOARD_REV).\(p.EXPANSION_BOARD_REV_SPECIAL)" + if await withTimeout(10, { await p.sendReadBtFwVersionCommand() == true }) == true { + base.radio = ShimmerUtilities.btModuleDisplayName(p.btModuleVersion) + } + onProgress?("\(deviceName): \(base.hw) FW \(base.fw), radio \(base.radio.isEmpty ? "not read" : base.radio)") + + for cfg in matrix { + for run in 1...cfg.repeats { + var template = base + template.config = cfg.label; template.crc = Int(cfg.crc.rawValue); template.rateHz = cfg.rateHz + template.seconds = cfg.seconds; template.run = run + var r = template + for attempt in 1...(1 + maxRetries) { + r = template + r.attempts = attempt + let tryLabel = attempt == 1 ? "" : " (retry \(attempt - 1)/\(maxRetries))" + if !linkUp { + onProgress?("\(deviceName): link lost, reconnecting") + await disconnect() + try? await Task.sleep(nanoseconds: 3_000_000_000) + guard await connect(deviceName: deviceName), let p2 = proto else { + onProgress?("\(deviceName): reconnect failed\(tryLabel)") + r.status = "connect-failed" + continue + } + p = p2 + } + onProgress?("\(deviceName): \(cfg.crc.rawValue)-byte CRC, run \(run)/\(cfg.repeats), \(cfg.seconds) s\(tryLabel)") + r = await runOne(p, cfg, r) + onProgress?("\(deviceName): \(r.status), PRR \(String(format: "%.1f", r.prrApi))%") + if r.status == "ok" { break } + } + rows.append(r) // the ok try, or the last failure if every try failed + if r.status == "connect-failed" { + onProgress?("\(deviceName): unreachable, skipping the rest of this device") + await disconnect() + return rows + } + } + } + await disconnect() + return rows + } + + private func runOne(_ p: Shimmer3Protocol, _ cfg: ThroughputConfig, _ rowIn: ThroughputRow) async -> ThroughputRow { + var r = rowIn + // Order matters: PacketSize is fixed at inquiry and includes the CRC, so the CRC goes first + // and the sensor command (which re-runs inquiry) goes last. + guard await withTimeout(15, { await p.setCRCMode(cfg.crc) }) == true, + await withTimeout(15, { await p.sendSetSamplingRateCommand(samplingRate: cfg.rateHz) == true }) == true, + await withTimeout(15, { await p.sendSetSensorsCommand(sensorBitmap: cfg.sensorBitmap) }) == true else { + r.status = linkUp ? "config-failed" : "disconnected"; return r + } + // Accuracy gate: the packet on the wire must be the size the config implies. + r.expectedPacketBytes = 1 + p.TimeStampPacketByteSize + cfg.payloadBytes + Int(cfg.crc.rawValue) + r.packetBytes = p.packetSizeBytes + guard r.packetBytes == r.expectedPacketBytes, p.getCRCMode() == cfg.crc, + p.currentSamplingRate == cfg.rateHz else { + r.status = "size-mismatch"; return r // wrong sensors enabled: do not report a PRR + } + + let t0 = Date() + guard await withTimeout(15, { await p.sendStartStreamingCommand() == true }) == true else { + r.status = linkUp ? "config-failed" : "disconnected"; return r + } + deviceStreaming = true + // One-second steps so a dropped link, or the device ending the stream, ends the run now. + while linkUp && deviceStreaming && Date().timeIntervalSince(t0) < Double(cfg.seconds) { + try? await Task.sleep(nanoseconds: 1_000_000_000) + } + r.wallSeconds = Date().timeIntervalSince(t0) + r.received = p.numberOfPackets + r.prrApi = p.packetReceptionRateOverall + if !linkUp { + r.status = "disconnected" // counts so far are kept, but the row is not a result + } else if !deviceStreaming { + r.status = "device-stopped" // docked, button, low battery: a partial run, not a result + } else { + switch await withTimeout(10, { await p.sendStopStreamingCommand() }) { + case nil: r.status = "stop-timeout" // the stream ran its full time, but the stop was never ACKed + case .some(.some(true)): break + default: // refused: the device may still be streaming + r.status = "stop-failed"; linkUp = false // reconnect before the next run + } + } + + // Same expectation the API uses (device timestamps), but kept unclamped. + r.expected = Int(Double(cfg.seconds) * cfg.rateHz) + r.prrRaw = r.expected > 0 ? Double(r.received) / Double(r.expected) * 100 : 0 + if r.received == 0 && r.status == "ok" { r.status = "stalled" } + try? await Task.sleep(nanoseconds: 2_000_000_000) // settle between runs + return r + } + + // MARK: output + /// The wiki's BLE-Throughput columns, in its order. One row per device and setting. + static let wikiColumns = ["Equipment", "Shimmer Device", "FW Version", "Radio Type", "Sensors Enabled", + "CRC Bytes", "Number of Bytes", "Sampling Rate", "Streaming Duration", + "Packet Reception Rate", "OS Version", "Distance between devices (approximate)"] + + /// The wiki table as CSV. Each setting's runs become one row: Packet Reception Rate is the + /// API PRR of the ok run (the median if there are several), otherwise "failed after n tries" or the + /// failure, so a setting that did not finish can never pass for a result. + static func csv(_ rows: [ThroughputRow], distance: String) -> String { + var order: [String] = [] + var groups: [String: [ThroughputRow]] = [:] + for r in rows { + let key = "\(r.device)|\(r.config)|\(r.crc)|\(r.rateHz)|\(r.seconds)" + if groups[key] == nil { order.append(key) } + groups[key, default: []].append(r) + } + let lines = order.map { key -> String in + let g = groups[key]!, first = g[0] + let ok = g.filter { $0.status == "ok" } + let prr: String + if first.status == "connect-failed" && g.count == 1 && first.config.isEmpty { + prr = "connect failed" + } else if ok.count == g.count { + let v = ok.map(\.prrApi).sorted() + let median = v.count % 2 == 1 ? v[v.count / 2] : (v[v.count / 2 - 1] + v[v.count / 2]) / 2 + prr = "\(Int(median.rounded()))%" + } else { + let reasons = Set(g.map(\.status)).subtracting(["ok"]).sorted().joined(separator: ", ") + prr = g.count == 1 ? "failed after \(first.attempts) tries: \(reasons)" + : "incomplete (\(ok.count)/\(g.count) ok: \(reasons))" + } + let bytes = (ok.first ?? first).packetBytes + let cells = [ + first.phone, + first.hw.isEmpty ? first.device : first.hw, + fwCell(hw: first.hw, fw: first.fw), + first.radio, + first.config, + first.crc == 0 ? "" : "\(first.crc) byte\(first.crc == 1 ? "" : "s")", + bytes == 0 ? "" : "\(bytes) bytes", + first.rateHz == 0 ? "" : "\(Int(first.rateHz)) Hz", + first.seconds == 0 ? "" : "\(first.seconds) s", + prr, + first.ios, + distance, + ] + return cells.map(quote).joined(separator: ",") + } + return ([wikiColumns.map(quote).joined(separator: ",")] + lines).joined(separator: "\n") + } + + /// "1.1.9" on a Shimmer3 -> "L&S Shimmer3 v1.01.009", as the wiki writes it. + private static func fwCell(hw: String, fw: String) -> String { + let n = fw.split(separator: ".").compactMap { Int($0) } + guard n.count == 3 else { return fw } + return "L&S \(hw) v\(n[0]).\(String(format: "%02d", n[1])).\(String(format: "%03d", n[2]))" + } + + private static func quote(_ s: String) -> String { "\"" + s.replacingOccurrences(of: "\"", with: "\"\"") + "\"" } + + // MARK: delegates + // nonisolated: Shimmer3Protocol calls these from its background processing queue, not the + // main thread, so they must not touch main-actor state directly. + nonisolated func scanCompleted() { + Task { @MainActor in self.scanContinuation?.resume(); self.scanContinuation = nil } + } + nonisolated func isConnected() {} + nonisolated func isDisconnected() {} + nonisolated func shimmerProtocolNewMessage(message: String) {} + nonisolated func shimmerProtocolNewObjectCluster(message: ObjectCluster) {} + nonisolated func shimmerBTStateChange(message: Shimmer3Protocol.Shimmer3BTState) { + Task { @MainActor in + if message == .DISCONNECTED { self.linkUp = false } + if message != .STREAMING { self.deviceStreaming = false } // e.g. a status push ended the stream + } + } +} diff --git a/TestApp/TestApp/ThroughputView.swift b/TestApp/TestApp/ThroughputView.swift new file mode 100644 index 0000000..124489a --- /dev/null +++ b/TestApp/TestApp/ThroughputView.swift @@ -0,0 +1,189 @@ +// +// ThroughputView.swift +// TestApp +// +// Scan for Shimmers, tick the ones to test, run the BLE-Throughput matrix on each in turn, and +// save one CSV to the app's Documents folder (visible in Finder and the Files app). +// +import SwiftUI +#if os(iOS) +import UIKit +#endif + +@MainActor +struct ThroughputView: View { + @State private var runner = ThroughputRunner() + @State private var found: [String] = [] + @State private var selected: Set = [] + @State private var scanning = false + @State private var running = false + @State private var quick = true + @State private var distance = "2.5 m" + @State private var log: [String] = [] + @State private var status = "" + @State private var statusSince = Date() + @State private var csvURL: URL? + + var body: some View { + NavigationView { + List { + if running { + Section { + // Ticks every second so a 60 s run visibly moves. + TimelineView(.periodic(from: .now, by: 1)) { context in + VStack(alignment: .leading, spacing: 4) { + Text(status).font(.headline) + Text("\(Int(context.date.timeIntervalSince(statusSince))) s").monospacedDigit() + } + } + } header: { Text("Now") } + } + Section { + Button(scanning ? "Scanning..." : "Scan for Shimmers") { Task { await scan() } } + .disabled(scanning || running) + ForEach(found, id: \.self) { name in + Button { + if selected.contains(name) { selected.remove(name) } else { selected.insert(name) } + } label: { + HStack { + Text(name) + Spacer() + if selected.contains(name) { Image(systemName: "checkmark") } + } + } + .disabled(running) + } + } header: { Text("Devices") } + + Section { + Toggle("Quick check (10 s, 1 run)", isOn: $quick).disabled(running) + HStack { + Text("Distance") + TextField("2.5 m", text: $distance).multilineTextAlignment(.trailing).disabled(running) + } + Button(running ? "Running..." : "Run on \(selected.count) device(s)") { Task { await run() } } + .disabled(selected.isEmpty || running || scanning) + if let csvURL { + Text(csvURL.lastPathComponent).font(.footnote) + if #available(iOS 16.0, macOS 13.0, *) { + ShareLink(item: csvURL) { Label("Share CSV", systemImage: "square.and.arrow.up") } + } + } + } header: { Text("Run") } footer: { + Text(quick ? "Quick check: a smoke test, not wiki results." + : "Full: 1 run x 60 s per CRC mode, retried if it fails, about 3 min per device.") + } + + Section { ForEach(Array(log.enumerated().reversed()), id: \.offset) { Text($0.element).font(.footnote) } } + header: { Text("Log (newest first)") } + } + .navigationTitle("Throughput") + } + // Swiping the sheet away mid-run would leave the run going unseen, the phone kept awake, + // and a second Run able to start against the same devices. + .interactiveDismissDisabled(running) + } + + private func scan() async { + scanning = true + found = await runner.scanShimmers() + selected = selected.intersection(found) + log.append(found.isEmpty ? "No Shimmers found. Is Bluetooth on and the device powered?" + : "Found \(found.count): \(found.joined(separator: ", "))") + scanning = false + } + + private func run() async { + running = true + csvURL = nil + setIdleTimerDisabled(true) // a locked phone stops the run + runner.onProgress = { line in + log.append("\(Self.clock.string(from: Date())) \(line)") + status = line + statusSince = Date() + } + + var matrix = ThroughputRunner.wikiMatrix() + if quick { + matrix = matrix.map { + ThroughputConfig(label: $0.label, sensorBitmap: $0.sensorBitmap, payloadBytes: $0.payloadBytes, + rateHz: $0.rateHz, crc: $0.crc, seconds: 10, repeats: 1) + } + } + let app = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "?" + let rows = await runner.run(deviceNames: selected.sorted(), matrix: matrix, + appVersion: app, ios: osVersion(), phone: Self.phoneModel()) + csvURL = save(ThroughputRunner.csv(rows, distance: distance)) + log.append(csvURL.map { "Saved \($0.lastPathComponent)" } ?? "Could not save the CSV") + + setIdleTimerDisabled(false) + running = false + } + + private static let clock: DateFormatter = { + let f = DateFormatter() + f.dateFormat = "HH:mm:ss" + return f + }() + + private func save(_ csv: String) -> URL? { + let stamp = DateFormatter() + stamp.dateFormat = "yyyyMMdd_HHmmss" + guard let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return nil } + let url = docs.appendingPathComponent("throughput_\(stamp.string(from: Date()))\(quick ? "_quick" : "").csv") + return (try? csv.write(to: url, atomically: true, encoding: .utf8)) == nil ? nil : url + } + + /// As the wiki writes it, e.g. "iOS 16.7.1". + private func osVersion() -> String { + #if os(iOS) + return "iOS \(UIDevice.current.systemVersion)" + #else + let v = ProcessInfo.processInfo.operatingSystemVersion + return "macOS \(v.majorVersion).\(v.minorVersion).\(v.patchVersion)" + #endif + } + + /// The wiki's Equipment cell, e.g. "iPhone X". A model not in the table below is written as its + /// raw identifier (e.g. "iPhone18,3"), which is still exact: add it to the table when seen. + static func phoneModel() -> String { + let id = modelIdentifier() + return phoneNames[id] ?? id + } + + private static func modelIdentifier() -> String { + if let sim = ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] { return sim } + #if os(iOS) + var sys = utsname() + uname(&sys) + return withUnsafeBytes(of: &sys.machine) { String(decoding: $0.prefix { $0 != 0 }, as: UTF8.self) } + #else + var size = 0 + sysctlbyname("hw.model", nil, &size, nil, 0) + var model = [CChar](repeating: 0, count: max(size, 1)) + sysctlbyname("hw.model", &model, &size, nil, 0) + return String(cString: model) // e.g. "Mac14,3" + #endif + } + + private static let phoneNames: [String: String] = [ + "iPhone10,1": "iPhone 8", "iPhone10,4": "iPhone 8", "iPhone10,2": "iPhone 8 Plus", "iPhone10,5": "iPhone 8 Plus", + "iPhone10,3": "iPhone X", "iPhone10,6": "iPhone X", + "iPhone11,2": "iPhone XS", "iPhone11,4": "iPhone XS Max", "iPhone11,6": "iPhone XS Max", "iPhone11,8": "iPhone XR", + "iPhone12,1": "iPhone 11", "iPhone12,3": "iPhone 11 Pro", "iPhone12,5": "iPhone 11 Pro Max", + "iPhone12,8": "iPhone SE (2nd gen)", + "iPhone13,1": "iPhone 12 mini", "iPhone13,2": "iPhone 12", "iPhone13,3": "iPhone 12 Pro", "iPhone13,4": "iPhone 12 Pro Max", + "iPhone14,4": "iPhone 13 mini", "iPhone14,5": "iPhone 13", "iPhone14,2": "iPhone 13 Pro", "iPhone14,3": "iPhone 13 Pro Max", + "iPhone14,6": "iPhone SE (3rd gen)", "iPhone14,7": "iPhone 14", "iPhone14,8": "iPhone 14 Plus", + "iPhone15,2": "iPhone 14 Pro", "iPhone15,3": "iPhone 14 Pro Max", + "iPhone15,4": "iPhone 15", "iPhone15,5": "iPhone 15 Plus", "iPhone16,1": "iPhone 15 Pro", "iPhone16,2": "iPhone 15 Pro Max", + "iPhone17,3": "iPhone 16", "iPhone17,4": "iPhone 16 Plus", "iPhone17,1": "iPhone 16 Pro", "iPhone17,2": "iPhone 16 Pro Max", + "iPhone17,5": "iPhone 16e", + ] + + private func setIdleTimerDisabled(_ disabled: Bool) { + #if os(iOS) + UIApplication.shared.isIdleTimerDisabled = disabled + #endif + } +} diff --git a/TestApp/TestApp/ViewModel.swift b/TestApp/TestApp/ViewModel.swift index 3974544..3697cca 100644 --- a/TestApp/TestApp/ViewModel.swift +++ b/TestApp/TestApp/ViewModel.swift @@ -86,7 +86,7 @@ class ViewModel: NSObject, ObservableObject { } func sendStopStreamingCommandDev2() async { - shimmer3Protocol!.sendStopStreamingCommand() + await shimmer3Protocol!.sendStopStreamingCommand() } func sendInfoMemIMU() async{ diff --git a/docs/THROUGHPUT_AUTOMATION.md b/docs/THROUGHPUT_AUTOMATION.md new file mode 100644 index 0000000..e7884b3 --- /dev/null +++ b/docs/THROUGHPUT_AUTOMATION.md @@ -0,0 +1,111 @@ +# BLE throughput test automation + +Fills the wiki's [BLE-Throughput](https://github.com/ShimmerResearch/SwiftAPI/wiki/BLE-Throughput) +page from a run of TestApp on an iPhone. Status: run on an iPhone X (iOS 16.7.16) against a +Shimmer3 (L&S v1.01.009, RN4678) and a Shimmer3R (L&S v1.01.025, IF820), 2026-11-04 and -05. + +## Steps +1. **Build:** open `Shimmer.xcworkspace`, pick the **TestApp** scheme and the iPhone, set a team + under Signing & Capabilities (do not commit it), and press Run (Cmd+R). Tap Allow on the + Bluetooth prompt, once per install. +2. **Devices:** flash the firmware under test, power the boards on, and put them about 2.5 m from the + phone. +3. **Run:** in TestApp tap **Throughput Test**, **Scan for Shimmers**, tick the devices, turn + **Quick check** off, set **Distance** if it is not 2.5 m, and tap **Run** (about 3 min per + device). Keep the app open; the phone stays awake by itself. +4. **CSV:** tap **Share CSV** and AirDrop it to the Mac (it lands in `~/Downloads`). Every PRR cell + should be a percentage; a cell saying `failed after n tries` means that setting never passed, so + re-run that device before publishing. +5. **Publish:** from the repo root, + ``` + python3 tools/throughput/update_wiki.py ~/Downloads/throughput__