Skip to content
Open
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
22 changes: 20 additions & 2 deletions ShimmerBluetooth/ShimmerBluetooth/BattVoltageSensor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,36 @@

import Foundation

/// The battery voltage, channel 0x03 (VBATT), on a Shimmer3 and a Shimmer3R.
///
/// Where it sits in the packet depends on what else is on: on a Shimmer3 it follows the
/// low-noise accelerometer when that is enabled, and on a Shimmer3R it is the last channel. So
/// it is read at `packetIndex`, which interpretDataPacketFormat sets from the inquiry response's
/// channel list.
public class BattVoltageSensor: Sensor , SensorProcessing{
public static let BATTERY = "Battery"
public static let BATTERY_PERCENTAGE = "Battery Percentage"

public var packetIndex: Int = -1

/// A raw battery reading in mV: the 12-bit ADC value at a 3 V reference, times 2 for the
/// divider. The same on a Shimmer3 and a Shimmer3R, as in the Java and C# APIs.
public static func calibrate(raw: Double) -> Double {
return ((raw - 0) * ((3000/1)/4095)) * 2
}

public func processData(sensorPacket: [UInt8], objectCluster: ObjectCluster) -> ObjectCluster {
let battery = Array(sensorPacket[3..<5])
// No index yet (the inquiry response has not been read), or a packet too short for it
guard packetIndex >= 0, packetIndex + 2 <= sensorPacket.count else {
return objectCluster
}
let battery = Array(sensorPacket[packetIndex..<packetIndex+2])
let rawBattery = Double(ShimmerUtilities.parseSensorData(sensorData: battery, dataType: SensorDataType.i16)!)

objectCluster.addData(sensorName: BattVoltageSensor.BATTERY, formatName: SensorFormats.Raw.rawValue, unitName: SensorUnits.noUnit.rawValue, value: Double(rawBattery))
if (calibrationEnabled){

let calBattery = ((rawBattery - 0) * ((3000/1)/4095)) * 2
let calBattery = BattVoltageSensor.calibrate(raw: rawBattery)
objectCluster.addData(sensorName: BattVoltageSensor.BATTERY, formatName: SensorFormats.Calibrated.rawValue, unitName: SensorUnits.milliVolts.rawValue, value: Double(calBattery))
var battVoltage = calBattery/1000
//equations are only valid when: 3.2 < x < 4.167. Leaving a 0.2v either side just incase
Expand Down
7 changes: 7 additions & 0 deletions ShimmerBluetooth/ShimmerBluetooth/Shimmer3Protocol.swift
Original file line number Diff line number Diff line change
Expand Up @@ -463,6 +463,7 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol {
altMagSensor = AltMagSensor(hwid: REV_HW_MAJOR)
pressureTempSensor = PressureTempSensor(hwid: REV_HW_MAJOR)
highGAccelSensor = HighGAccelSensor(hwid: REV_HW_MAJOR)
battVoltageSensor = BattVoltageSensor()
}
}

Expand Down Expand Up @@ -502,6 +503,7 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol {
adcExternalA0Sensor.sensorEnabled = false
adcExternalA1Sensor.sensorEnabled = false
adcExternalA2Sensor.sensorEnabled = false
battVoltageSensor.sensorEnabled = false
}
}

Expand Down Expand Up @@ -541,6 +543,7 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol {
adcExternalA0Sensor.setInfoMem(infomem: infoMem)
adcExternalA1Sensor.setInfoMem(infomem: infoMem)
adcExternalA2Sensor.setInfoMem(infomem: infoMem)
battVoltageSensor.setInfoMom(infomem: infoMem)
}
}

Expand Down Expand Up @@ -1289,6 +1292,10 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol {
packetSize += 2
enabledSensors |= Int(SensorBitmapShimmer3.SENSOR_LN_ACCEL.rawValue)
case ChannelContentsShimmer3.VBatt.rawValue:
// Not at a fixed place: after the low-noise accel on a Shimmer3 when that is on,
// and the last channel on a Shimmer3R
battVoltageSensor.sensorEnabled = true
battVoltageSensor.packetIndex = packetSize
packetSize += 2
enabledSensors |= Int(SensorBitmapShimmer3.SENSOR_VBATT.rawValue)
case ChannelContentsShimmer3.XWRAccel.rawValue:
Expand Down
84 changes: 84 additions & 0 deletions ShimmerBluetooth/ShimmerBluetoothTests/SensorTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,90 @@ class SensorTest: XCTestCase {

}

// MARK: Battery (VBATT, channel 0x03)

// DEV-1449: the battery was read from bytes 3-4 whatever its place in the packet, and is now
// read at the packet index interpretDataPacketFormat gives it.

private func batterySignal(_ objectCluster: ObjectCluster, _ name: String, _ format: Sensor.SensorFormats, _ unit: Sensor.SensorUnits) -> Double? {
let signal = [name, format.rawValue, unit.rawValue].joined(separator: "_")
guard let i = objectCluster.SignalNames.firstIndex(of: signal) else { return nil }
return objectCluster.SignalData[i]
}

private func batteryCluster(packet: [UInt8], packetIndex: Int, calibrationEnabled: Bool = true) -> ObjectCluster {
let sensor = BattVoltageSensor()
sensor.calibrationEnabled = calibrationEnabled
sensor.packetIndex = packetIndex
return sensor.processData(sensorPacket: packet, objectCluster: ObjectCluster(deviceName: "test"))
}

/// U12 at a 3 V reference, times 2, as the Java driver and the C# API do on both generations.
func testBatteryCalibration(){
XCTAssertEqual(BattVoltageSensor.calibrate(raw: 0), 0.0)
XCTAssertEqual(BattVoltageSensor.calibrate(raw: 4095), 6000.0, accuracy: 1e-9)
XCTAssertEqual(BattVoltageSensor.calibrate(raw: 2847), 4171.428571428572, accuracy: 1e-9)
XCTAssertEqual(BattVoltageSensor.calibrate(raw: 2048), 3000.7326007326005, accuracy: 1e-9)
}

/// The battery is read at its packet index, not at the first channel after the timestamp.
func testBatteryDecodesAtItsIndex(){
// Timestamp, then 0x002E (46) where the old code read, then 0x0B1F (2847)
let packet: [UInt8] = [0xE3, 0x85, 0x22, 0x2E, 0x00, 0x1F, 0x0B]
let battery = batteryCluster(packet: packet, packetIndex: 5)
XCTAssertEqual(batterySignal(battery, BattVoltageSensor.BATTERY, .Raw, .noUnit), 2847)
XCTAssertEqual(batterySignal(battery, BattVoltageSensor.BATTERY, .Calibrated, .milliVolts)!, 4171.428571428572, accuracy: 1e-9)

let uncalibrated = batteryCluster(packet: packet, packetIndex: 5, calibrationEnabled: false)
XCTAssertEqual(batterySignal(uncalibrated, BattVoltageSensor.BATTERY, .Raw, .noUnit), 2847)
XCTAssertNil(batterySignal(uncalibrated, BattVoltageSensor.BATTERY, .Calibrated, .milliVolts))
XCTAssertNil(batterySignal(uncalibrated, BattVoltageSensor.BATTERY_PERCENTAGE, .Calibrated, .percent))
}

/// Without an index from the inquiry response, or with one past the end of the packet, the
/// sensor adds nothing rather than reading the wrong bytes or out of range.
func testBatteryWithoutAUsableIndexAddsNothing(){
let packet: [UInt8] = [0xE3, 0x85, 0x22, 0x2E, 0x00, 0x1F, 0x0B]
for packetIndex in [-1, 6, 7] {
let cluster = batteryCluster(packet: packet, packetIndex: packetIndex)
XCTAssertTrue(cluster.SignalNames.isEmpty, "index \(packetIndex)")
}
}

/// Packets a Shimmer3R streamed, as buildMsg gets them: without the packet type byte. The
/// battery is the last channel, and bytes 3-4 hold the magnetometer.
func testBatteryFromShimmer3RPackets(){
func hex(_ s: String) -> [UInt8] {
var out: [UInt8] = []
var i = s.startIndex
while i < s.endIndex {
let j = s.index(i, offsetBy: 2)
out.append(UInt8(s[i..<j], radix: 16)!)
i = j
}
return out
}
// (packet, battery index, raw, mV). 1024 Hz with every sensor: timestamp (3), mag, gyro,
// low-noise accel (6 each), pressure and temperature (3 each), high-g accel, wide-range
// accel, alt mag (6 each), sound level, GSR, then the battery at 49. 512 Hz: timestamp (3),
// mag, gyro, low-noise accel (6 each), sound level, then the battery at 23.
let cases: [(String, Int, Double, Double)] = [
("3c49a82e004c0010fdc9ff2f00010097f3e13cb4ef009d5e00848001200040ffe0ccc408f1fcf200000000000000807c0a330b", 49, 2867, 4200.7326007326),
("5c49a82b004d0012fdabff2000150077f3f83c85ef009d5e0084800140fff00020b8c400f128f30000000000004d137f0a380b", 49, 2872, 4208.058608058608),
("e3852226004d0019fdbbff310012007ef3e83c8def00801f0b", 23, 2847, 4171.428571428572),
("23862226004d0019fdb0ff1f00190073f3f43c8eef54232d0b", 23, 2861, 4191.941391941392),
]
for (packetHex, packetIndex, raw, milliVolts) in cases {
let packet = hex(packetHex)
XCTAssertEqual(packet.count, packetIndex + 2, "the battery is the last channel")
let cluster = batteryCluster(packet: packet, packetIndex: packetIndex)
XCTAssertEqual(batterySignal(cluster, BattVoltageSensor.BATTERY, .Raw, .noUnit), raw)
XCTAssertEqual(batterySignal(cluster, BattVoltageSensor.BATTERY, .Calibrated, .milliVolts)!, milliVolts, accuracy: 1e-9)
// At these voltages the charge fit comes out over 100 %, and is held at 100
XCTAssertEqual(batterySignal(cluster, BattVoltageSensor.BATTERY_PERCENTAGE, .Calibrated, .percent), 100.0)
}
}

// DEV-1070: a GSR code below the range-3 open-circuit limit, 683, puts the amplifier output under
// its 0.5 V reference, which no skin resistance can do, so the electrodes are open, on every range.
// In auto-range ranges 0-2 see such codes as the device climbs after the electrodes come off, and
Expand Down
Loading