Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 62 additions & 11 deletions ShimmerBluetooth/ShimmerBluetooth/Shimmer3Protocol.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Expand Down Expand Up @@ -1380,7 +1412,7 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol {
}
if (result!){
print("StartStreaming!")
numberOfPackets = 0
resetPacketReceptionRates()
self.changeState(btState:Shimmer3BTState.STREAMING)
}
return result
Expand Down Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions ShimmerExamplePlot/ShimmerExamplePlot/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,16 @@ struct ContentView: View {
viewModel.protocolShimmer3 = protocolSelection
}

Picker("CRC Mode", selection: $viewModel.crcModeIndex) {
ForEach(0..<viewModel.crcModes.count, id: \.self) { index in
Text(viewModel.crcModes[index])
}
}
.disabled(viewModel.stateText == "Streaming" || viewModel.isSensorCommandInFlight)

Text("BT State: \(viewModel.stateText)")
Text("Active CRC Mode: \(viewModel.currentCRCModeText)")
Text("PRR: \(viewModel.packetReceptionRate >= 0 ? "\(viewModel.packetReceptionRate)%" : "-")")
Button("Connect Shimmer3",action: {Task {
do {
viewModel.delegate = self
Expand All @@ -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()
Expand Down
26 changes: 26 additions & 0 deletions ShimmerExamplePlot/ShimmerExamplePlot/ViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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!)
Expand All @@ -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()
Expand Down Expand Up @@ -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
Expand Down
Loading