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
55 changes: 43 additions & 12 deletions ShimmerBluetooth/ShimmerBluetooth/PressureTempSensor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ public class PressureTempSensor: Sensor , SensorProcessing{
/// nil (not yet known) keeps the BMP390 path on a Shimmer3R.
public var pressureSensorType: PressureSensorType? = nil

/// True once a Shimmer3R's BMP390 coefficients have been parsed. Until then its
/// pressure and temperature are reported as not calibrated (NaN).
public private(set) var hasBmp390Coefficients = false

/// BMP581 oversampling settings, indexed by the 3-bit pressure resolution field.
public static let ListOfPressureResolutionBMP581 = ["Lowest Power", "Low", "Standard", "High", "High Res", "Very High Res", "Ultra High Res", "Highest Res"]

Expand Down Expand Up @@ -168,8 +172,12 @@ public class PressureTempSensor: Sensor , SensorProcessing{
return objectCluster
}

let (compPress, tLin) = calibratePressure390(UP: Double(rawP),
UT: Double(rawT))
// No coefficients: none received yet, an all-0x00/0xFF block, or a BMP390 assumed from
// the SR number. The BMP390 has no published defaults, so report the values as not
// calibrated rather than invent them, as the Java driver does (DEV-1125).
let (compPress, tLin) = hasBmp390Coefficients
? calibratePressure390(UP: Double(rawP), UT: Double(rawT))
: (Double.nan, Double.nan)

let temperatureC = tLin
let pressurekPa = compPress / 1000.0
Expand Down Expand Up @@ -249,6 +257,13 @@ public class PressureTempSensor: Sensor , SensorProcessing{
// Drop the first 2 header bytes (length + chipId), keep next 21
let b = Array(pressureResoRes.dropFirst(2).prefix(21))

// As CalibDetailsBmp390.parseCalParamByteArray: an all-0x00 or all-0xFF block
// holds no coefficients, so keep none and leave the values uncalibrated
guard b.count == 21, !b.allSatisfy({ $0 == 0x00 }), !b.allSatisfy({ $0 == 0xFF }) else {
print("No BMP390 coefficients in the reply, pressure and temperature are not calibrated")
return
}

func u16(_ i: Int) -> UInt16 {
// ConcatenateBytes(high, low) style
return (UInt16(b[i+1]) << 8) | UInt16(b[i])
Expand Down Expand Up @@ -325,6 +340,7 @@ public class PressureTempSensor: Sensor , SensorProcessing{
print("par_P10 = \(par_P10)")
print("par_P11 = \(par_P11)")

hasBmp390Coefficients = true
return
return
} else {
Expand Down Expand Up @@ -364,6 +380,13 @@ public class PressureTempSensor: Sensor , SensorProcessing{
print("Invalid pressure calibration response: \(payload.map{ String(format: "%02X", $0) }.joined(separator: " "))")
return false
}
// A Shimmer3R carries a BMP390 or BMP581. Any other ID is refused, leaving the
// SR-number rule to decide, as the Java driver does.
if HardwareVersion == Shimmer3Protocol.HardwareType.Shimmer3R.rawValue
&& decoded.sensorType != .BMP390 && decoded.sensorType != .BMP581 {
print("Pressure calibration response refused: a Shimmer3R carries a BMP390 or BMP581, not a \(decoded.sensorType)")
return false
}
pressureSensorType = decoded.sensorType
print("Pressure sensor: \(decoded.sensorType)")
if decoded.sensorType == .BMP390 {
Expand Down Expand Up @@ -396,16 +419,24 @@ public class PressureTempSensor: Sensor , SensorProcessing{

/// True for LogAndStream v1.01.006 onwards, the first firmware that can drive a BMP581.
public static func isBmp581SupportedByFirmware(firmwareIdentifier: Int, major: Int, minor: Int, internalVersion: Int) -> Bool {
if firmwareIdentifier != PressureTempSensor.FW_ID_LOGANDSTREAM {
return false
}
if major != 1 {
return major > 1
}
if minor != 1 {
return minor > 1
}
return internalVersion >= 6
return isLogAndStreamAtLeast(firmwareIdentifier: firmwareIdentifier, major: major, minor: minor, internalVersion: internalVersion, atLeast: (1, 1, 6))
}

/// Whether to ask a Shimmer3R for its pressure sensor with 0xA7, as the Java driver's
/// ShimmerBluetooth.readPressureCalibrationCoefficients() decides. LogAndStream v1.01.007
/// onwards answers with the sensor ID ([A6][01][03] on a BMP581). v1.01.006 is the one
/// version that NACKs it on a BMP581, so it is not asked there and the SR-number rule
/// stands. isBmp581PerSrNumber includes the >= v1.01.006 guard, so "BMP581 by SR number
/// and below v1.01.007" is exactly v1.01.006.
public static func readsPressureCalibrationCoefficients(isBmp581PerSrNumber: Bool, firmwareIdentifier: Int, major: Int, minor: Int, internalVersion: Int) -> Bool {
return !isBmp581PerSrNumber
|| isLogAndStreamAtLeast(firmwareIdentifier: firmwareIdentifier, major: major, minor: minor, internalVersion: internalVersion, atLeast: (1, 1, 7))
}

/// True for LogAndStream firmware at or above the given version.
static func isLogAndStreamAtLeast(firmwareIdentifier: Int, major: Int, minor: Int, internalVersion: Int, atLeast version: (Int, Int, Int)) -> Bool {
return firmwareIdentifier == PressureTempSensor.FW_ID_LOGANDSTREAM
&& (major, minor, internalVersion) >= version
}

/// BMP581 conversion: pressure is unsigned, Pa = raw / 64; temperature is signed, degC = raw / 65536.
Expand Down
25 changes: 19 additions & 6 deletions ShimmerBluetooth/ShimmerBluetooth/Shimmer3Protocol.swift
Original file line number Diff line number Diff line change
Expand Up @@ -361,13 +361,16 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol {
if (REV_HW_MAJOR==HardwareType.Shimmer3.rawValue){
await sendBMP280PressureCalibCoefficientsCommand()
} else if (REV_HW_MAJOR==HardwareType.Shimmer3R.rawValue){
let pressureSensorIdReceived = await sendPressureCalibCoefficientsCommand() ?? false
// As the Java driver: v1.01.006 is the one firmware that NACKs 0xA7 on a
// BMP581, so it is not asked there.
var pressureSensorIdReceived = false
if (readsPressureCalibrationCoefficients()){
pressureSensorIdReceived = await sendPressureCalibCoefficientsCommand() ?? false
}
if (!pressureSensorIdReceived){
// No usable 0xA6 reply: v1.01.006 refuses 0xA7 on a BMP581, so
// fall back to the board SR number and firmware version.
// Also taken for a malformed reply. A NACK only reaches here once
// NACK handling resumes the command with a failure; until then it
// leaves this await suspended.
// No usable 0xA6 reply: not asked (v1.01.006 with a BMP581), refused
// with a NACK, or malformed or refused by applyPressureCalibrationResponse.
// Fall back to the board SR number and firmware version.
let sensorType = isShimmer3RwithBmp581() ? PressureTempSensor.PressureSensorType.BMP581 : PressureTempSensor.PressureSensorType.BMP390
pressureTempSensor.pressureSensorType = sensorType
print("Pressure sensor from SR number: \(sensorType)")
Expand Down Expand Up @@ -397,6 +400,16 @@ public class Shimmer3Protocol : NSObject, ShimmerProtocol {
internalVersion: REV_FW_INTERNAL)
}

/// Whether connect() asks a Shimmer3R for its pressure sensor with 0xA7
/// (see PressureTempSensor.readsPressureCalibrationCoefficients).
public func readsPressureCalibrationCoefficients() -> Bool {
return PressureTempSensor.readsPressureCalibrationCoefficients(isBmp581PerSrNumber: isShimmer3RwithBmp581(),
firmwareIdentifier: REV_FW_IDENTIFIER,
major: REV_FW_MAJOR,
minor: REV_FW_MINOR,
internalVersion: REV_FW_INTERNAL)
}

func parseCalibrationDump(_ bytes:[UInt8]){
let length = Int(bytes[0]) + (Int(bytes[1])<<8)
var calibrationBytes = Array(bytes.prefix(length+2))
Expand Down
79 changes: 79 additions & 0 deletions ShimmerBluetooth/ShimmerBluetoothTests/SensorTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,85 @@ class SensorTest: XCTestCase {
let (referencePressure, referenceTemperature) = reference.calibratePressure390(UP: 6400000, UT: 8400000)
XCTAssertEqual(pressure, referencePressure, "Failed BMP390 pressure")
XCTAssertEqual(temperature, referenceTemperature, "Failed BMP390 temperature")

// A Shimmer3R carries a BMP390 or BMP581: a BMP180 or BMP280 ID is refused, as the Java driver does
pressTempSensor = PressureTempSensor(hwid: Shimmer3Protocol.HardwareType.Shimmer3R.rawValue)
XCTAssertFalse(pressTempSensor.applyPressureCalibrationResponse([0x17, 0x00] + [UInt8](repeating: 0x11, count: 22)), "A Shimmer3R accepted a BMP180")
XCTAssertFalse(pressTempSensor.applyPressureCalibrationResponse([0x19, 0x01] + [UInt8](repeating: 0x11, count: 24)), "A Shimmer3R accepted a BMP280")
XCTAssertNil(pressTempSensor.pressureSensorType, "A refused reply set the sensor type")
}

// As the Java driver's readPressureCalibrationCoefficients(): v1.01.006 NACKs 0xA7 on a BMP581, so it is not asked there
func testReadsPressureCalibrationCoefficients(){
let cases: [(Bool, Int, Int, Int, Int, Bool)] = [
// (BMP581 by SR number, firmware identifier, major, minor, internal, sends 0xA7)
(true, 3, 1, 1, 6, false),
(true, 3, 1, 1, 7, true),
(true, 3, 1, 2, 0, true),
(true, 3, 2, 0, 0, true),
(false, 3, 1, 1, 6, true),
(false, 3, 1, 1, 5, true),
(false, 3, 0, 16, 0, true),
(false, 1, 1, 1, 6, true)
]
for (isBmp581, firmwareIdentifier, major, minor, internalVersion, expected) in cases {
XCTAssertEqual(PressureTempSensor.readsPressureCalibrationCoefficients(isBmp581PerSrNumber: isBmp581, firmwareIdentifier: firmwareIdentifier, major: major, minor: minor, internalVersion: internalVersion), expected, "BMP581 \(isBmp581), firmware \(firmwareIdentifier) v\(major).\(minor).\(internalVersion)")
}
}

// DEV-1125 in the Java driver: a BMP390 without coefficients reports NaN rather than invented values
func testBMP390WithoutCoefficients(){
let pressureName = [PressureTempSensor.PRESSURE, Sensor.SensorFormats.Calibrated.rawValue, Sensor.SensorUnits.kpascal.rawValue].joined(separator: "_")
let temperatureName = [PressureTempSensor.TEMPERATURE, Sensor.SensorFormats.Calibrated.rawValue, Sensor.SensorUnits.degreescelcius.rawValue].joined(separator: "_")
let rawPressureName = [PressureTempSensor.PRESSURE, Sensor.SensorFormats.Raw.rawValue, Sensor.SensorUnits.noUnit.rawValue].joined(separator: "_")
// Channel order [0x1B pressure, 0x1A temperature], each 3 bytes little-endian: P 6400000, T 8400000
let packet: [UInt8] = [0x00, 0xA8, 0x61, 0x80, 0x2C, 0x80]
func calibrated(_ sensor: PressureTempSensor) -> (Double, Double, Double) {
let objectCluster = sensor.processData(sensorPacket: packet, objectCluster: ObjectCluster(deviceName: "test"))
return (objectCluster.SignalData[objectCluster.SignalNames.firstIndex(of: pressureName)!],
objectCluster.SignalData[objectCluster.SignalNames.firstIndex(of: temperatureName)!],
objectCluster.SignalData[objectCluster.SignalNames.firstIndex(of: rawPressureName)!])
}
func newSensor() -> PressureTempSensor {
let sensor = PressureTempSensor(hwid: Shimmer3Protocol.HardwareType.Shimmer3R.rawValue)
sensor.packetIndexPressure = 0
sensor.packetIndexTemp = 3
return sensor
}

// Sampled before any 0xA6 reply
var pressTempSensor = newSensor()
var (pressure, temperature, rawPressure) = calibrated(pressTempSensor)
XCTAssertTrue(pressure.isNaN, "Calibrated pressure without coefficients")
XCTAssertTrue(temperature.isNaN, "Calibrated temperature without coefficients")
XCTAssertEqual(rawPressure, 6400000.0, "Raw pressure lost without coefficients")

// A BMP390 assumed from the SR number after 0xA7 got no usable reply
pressTempSensor.pressureSensorType = PressureTempSensor.PressureSensorType.BMP390
(pressure, temperature, _) = calibrated(pressTempSensor)
XCTAssertTrue(pressure.isNaN && temperature.isNaN, "Calibrated a BMP390 assumed from the SR number")

// An all-0x00 or all-0xFF block is a valid reply that holds no coefficients
for fill: UInt8 in [0x00, 0xFF] {
pressTempSensor = newSensor()
XCTAssertTrue(pressTempSensor.applyPressureCalibrationResponse([0x16, 0x02] + [UInt8](repeating: fill, count: 21)), "Rejected a BMP390 reply")
XCTAssertEqual(pressTempSensor.pressureSensorType, PressureTempSensor.PressureSensorType.BMP390, "Failed to set BMP390")
XCTAssertFalse(pressTempSensor.hasBmp390Coefficients, "Kept an all-\(fill) block as coefficients")
(pressure, temperature, _) = calibrated(pressTempSensor)
XCTAssertTrue(pressure.isNaN && temperature.isNaN, "Calibrated from an all-\(fill) block")
}

// Real coefficients calibrate exactly as calibratePressure390
let bmp390Payload: [UInt8] = [0x16, 0x02, 0x6B, 0x6A, 0x8E, 0x49, 0xF8, 0x7F, 0xF5, 0xA2, 0x05, 0x19, 0x05, 0x68, 0x44, 0x36, 0x61, 0xFC, 0x07, 0x3A, 0xF3, 0xB8, 0x0E]
pressTempSensor = newSensor()
XCTAssertTrue(pressTempSensor.applyPressureCalibrationResponse(bmp390Payload), "Rejected a BMP390 reply")
XCTAssertTrue(pressTempSensor.hasBmp390Coefficients, "Failed to keep the BMP390 coefficients")
(pressure, temperature, _) = calibrated(pressTempSensor)
let reference = newSensor()
reference.parseCalParamByteArray(pressureResoRes: bmp390Payload)
let (referencePressure, referenceTemperature) = reference.calibratePressure390(UP: 6400000, UT: 8400000)
XCTAssertEqual(pressure, referencePressure / 1000.0, "Failed BMP390 pressure")
XCTAssertEqual(temperature, referenceTemperature, "Failed BMP390 temperature")
}

// Cases copied from the firmware's test_bmp581_gate (log-and-stream-common Test/host/test_boards.c)
Expand Down
Loading