From 57fc6d686f09c72f2a69d2cb5d61bbad26c62de2 Mon Sep 17 00:00:00 2001 From: Harith Jamadi Date: Thu, 1 Oct 2026 16:16:34 +0800 Subject: [PATCH] add crc and PRR UI --- .../ShimmerBluetooth/Shimmer3Protocol.swift | 73 ++++++++++++++++--- .../ShimmerExamplePlot/ContentView.swift | 15 ++++ .../ShimmerExamplePlot/ViewModel.swift | 26 +++++++ 3 files changed, 103 insertions(+), 11 deletions(-) diff --git a/ShimmerBluetooth/ShimmerBluetooth/Shimmer3Protocol.swift b/ShimmerBluetooth/ShimmerBluetooth/Shimmer3Protocol.swift index 0e5481e..182fb35 100644 --- a/ShimmerBluetooth/ShimmerBluetooth/Shimmer3Protocol.swift +++ b/ShimmerBluetooth/ShimmerBluetooth/Shimmer3Protocol.swift @@ -570,20 +570,52 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol { } if (numberOfPackets==0){ startTime = Date() + prrCurrentWindowStart = startTime + prrTrialStartTimeStampMs = timeSensor.LastReceivedTimeStamp / 32768 * 1000 } numberOfPackets+=1 - let endTime = Date() - var elapsedTime = endTime.timeIntervalSince(self.startTime) - if (elapsedTime == 0){ - elapsedTime = 1 + prrCurrentPacketCount+=1 + calculatePacketReceptionRates() + ojc.addData(sensorName: Shimmer3Protocol.PACKET_RECEPTION_RATE_CURRENT, formatName: Sensor.SensorFormats.Calibrated.rawValue, unitName: Sensor.SensorUnits.percent.rawValue, value: packetReceptionRateCurrent) + ojc.addData(sensorName: Shimmer3Protocol.PACKET_RECEPTION_RATE_OVERALL, formatName: Sensor.SensorFormats.Calibrated.rawValue, unitName: Sensor.SensorUnits.percent.rawValue, value: packetReceptionRateOverall) + ojc.PacketReceptionRate = Int(packetReceptionRateOverall) + print("Number of packets: \(numberOfPackets) ; Packet Reception Rate Current(%): \(packetReceptionRateCurrent) ; Trial(%): \(packetReceptionRateOverall)") + return ojc + } + + // Packet reception rate, following the Shimmer Java/Android API (ShimmerDevice / SensorShimmerClock) + public static let PACKET_RECEPTION_RATE_CURRENT = "Packet_Reception_Rate_Current" + public static let PACKET_RECEPTION_RATE_OVERALL = "Packet_Reception_Rate_Trial" + static let PACKET_RECEPTION_RATE_CURRENT_INTERVAL_S: TimeInterval = 1 // mCalcReceptionRateMs in ShimmerBluetoothManager + public private(set) var packetReceptionRateCurrent: Double = 0 + public private(set) var packetReceptionRateOverall: Double = 0 + private var prrCurrentPacketCount = 0 + private var prrCurrentWindowStart = Date() + private var prrTrialStartTimeStampMs: Double = 0 + + func resetPacketReceptionRates() { + numberOfPackets = 0 + prrCurrentPacketCount = 0 + packetReceptionRateCurrent = 0 + packetReceptionRateOverall = 0 + } + + private func calculatePacketReceptionRates() { + // Trial: packets received vs packets expected from the device timestamps since streaming started + let timeDifferenceMs = timeSensor.LastReceivedTimeStamp / 32768 * 1000 - prrTrialStartTimeStampMs + let packetExpectedCount = Int(timeDifferenceMs / ((1 / CurrentSamplingRate) * 1000)) + if packetExpectedCount > 0 { + packetReceptionRateOverall = min(max(Double(numberOfPackets) / Double(packetExpectedCount) * 100, 0), 100) } - var PRR = Int((((Double)(numberOfPackets)/self.CurrentSamplingRate)/elapsedTime)*100) - if (PRR>100){ - PRR=100 + // Current: packets received over each interval vs packets expected for that interval + let now = Date() + let intervalS = now.timeIntervalSince(prrCurrentWindowStart) + if intervalS >= Shimmer3Protocol.PACKET_RECEPTION_RATE_CURRENT_INTERVAL_S { + let numPacketsShouldHaveReceived = intervalS * CurrentSamplingRate + packetReceptionRateCurrent = min(max(Double(prrCurrentPacketCount) / numPacketsShouldHaveReceived * 100, 0), 100) + prrCurrentPacketCount = 0 + prrCurrentWindowStart = now } - ojc.PacketReceptionRate = PRR - print("Elapsed time: \(elapsedTime) seconds ; Number of packets: \(numberOfPackets) ; Packet Reception Rate(%): \(PRR)") - return ojc } private var radio: BleByteRadio? @@ -1380,7 +1412,7 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol { } if (result!){ print("StartStreaming!") - numberOfPackets = 0 + resetPacketReceptionRates() self.changeState(btState:Shimmer3BTState.STREAMING) } return result @@ -1452,6 +1484,25 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol { return false } + public func getCRCMode() -> BTCRCMode { + return CRCMode + } + + /// Changes the CRC mode while connected (not while streaming). Re-sends the inquiry command + /// afterwards so the streaming packet size accounts for the new number of CRC bytes. + public func setCRCMode(_ crcMode:BTCRCMode) async -> Bool { + guard BTState == Shimmer3BTState.CONNECTED else { + print("Cannot set CRC mode: device must be connected and not streaming") + return false + } + let res = await sendCRCCommand(crcMode: crcMode) + guard res == true else { + return false + } + await sendInquiryCommand() + return true + } + private func sendCRCCommand(crcMode:BTCRCMode) async ->Bool?{ let bytes:[UInt8] = [PacketTypeShimmer.setCRCCommand.rawValue,crcMode.rawValue] commandSent = PacketTypeShimmer.setCRCCommand diff --git a/ShimmerExamplePlot/ShimmerExamplePlot/ContentView.swift b/ShimmerExamplePlot/ShimmerExamplePlot/ContentView.swift index ad319ba..c857930 100644 --- a/ShimmerExamplePlot/ShimmerExamplePlot/ContentView.swift +++ b/ShimmerExamplePlot/ShimmerExamplePlot/ContentView.swift @@ -160,7 +160,16 @@ struct ContentView: View { viewModel.protocolShimmer3 = protocolSelection } + Picker("CRC Mode", selection: $viewModel.crcModeIndex) { + ForEach(0..= 0 ? "\(viewModel.packetReceptionRate)%" : "-")") Button("Connect Shimmer3",action: {Task { do { viewModel.delegate = self @@ -182,6 +191,12 @@ struct ContentView: View { }) .disabled(viewModel.stateText == "Disconnected" || viewModel.stateText == "Configuring") + Button("Set CRC Mode Shimmer3",action:{ Task { + await viewModel.setCRCModeDev2() + } + }) + .disabled(viewModel.stateText != "Connected" || viewModel.isSensorCommandInFlight || viewModel.protocolShimmer3 != 0) + Button("StartStreaming Shimmer3",action:{ Task { do { await viewModel.sendStartStreamingCommandDev2() diff --git a/ShimmerExamplePlot/ShimmerExamplePlot/ViewModel.swift b/ShimmerExamplePlot/ShimmerExamplePlot/ViewModel.swift index a91240d..7191d29 100644 --- a/ShimmerExamplePlot/ShimmerExamplePlot/ViewModel.swift +++ b/ShimmerExamplePlot/ShimmerExamplePlot/ViewModel.swift @@ -52,6 +52,10 @@ class ViewModel: NSObject, ObservableObject { @Published var pressResolution = ["LOW", "STANDARD", "HIGH", "ULTRAHIGH"] @Published var samplingRate = ["1Hz", "10.2Hz", "51.2Hz", "102.4Hz", "204.8Hz", "256Hz", "512Hz", "1024Hz"] @Published var stateText = "Disconnected" + @Published var crcModes = ["Off", "1 Byte", "2 Byte"] + @Published var crcModeIndex = 2 // Initial value, matches the API default (TWO_BYTE) + @Published var currentCRCModeText = "-" + @Published var packetReceptionRate = -1 @Published var ppgInputOptions = PPGInputOption.allCases.map(\.rawValue) @Published var ppgInputSelectionIndex = 0 @Published var lnAccelEnabled = false @@ -158,6 +162,7 @@ class ViewModel: NSObject, ObservableObject { shimmer3Protocol = Shimmer3Protocol(radio: self.radio!) shimmer3Protocol?.delegate = self await shimmer3Protocol?.connect() + refreshCRCModeText() refreshUISettings() } else { shimmer3SpeedTestProtocol = Shimmer3SpeedTestProtocol(radio: self.radio!) @@ -167,6 +172,26 @@ class ViewModel: NSObject, ObservableObject { } } + private func selectedCRCMode() -> Shimmer3Protocol.BTCRCMode { + return Shimmer3Protocol.BTCRCMode(rawValue: UInt8(crcModeIndex)) ?? .TWO_BYTE + } + + func refreshCRCModeText() { + guard let mode = shimmer3Protocol?.getCRCMode() else { + currentCRCModeText = "-" + return + } + currentCRCModeText = crcModes[Int(mode.rawValue)] + } + + func setCRCModeDev2() async { + isSensorCommandInFlight = true + let ok = await shimmer3Protocol?.setCRCMode(selectedCRCMode()) ?? false + print("Set CRC mode \(selectedCRCMode()) result: \(ok)") + refreshCRCModeText() + isSensorCommandInFlight = false + } + func disconnectDev2() async{ if (shimmer3Protocol==nil){ await shimmer3SpeedTestProtocol!.disconnect() @@ -577,6 +602,7 @@ extension ViewModel : ShimmerProtocolDelegate { func shimmerProtocolNewObjectCluster(message: ShimmerBluetooth.ObjectCluster) { DispatchQueue.main.async { print(message) + self.packetReceptionRate = message.PacketReceptionRate if (!self.updatedPicker) { self.pickerData = message.SignalNames