package `in`.caresoft.carepulse.connect.ble import java.util.Calendar import java.util.TimeZone import java.util.UUID import kotlin.math.pow /** One normalised reading, using CarePulse parameter codes (see /api/v1/parameters). */ data class Reading( val param: String, val value: Double, val unit: String, val measuredAt: Long, // epoch millis val context: String? = null, val sequence: Int? = null // glucose record number (for incremental memory sync) ) /** * Parsers for Bluetooth SIG standard health profiles (GATT Specification Supplement). * Pure Kotlin, no Android dependencies, so they are unit-testable (see GattParsersTest). */ object GattParsers { fun uuid16(short: String): UUID = UUID.fromString("0000${short.lowercase()}-0000-1000-8000-00805f9b34fb") // Services val SVC_BLOOD_PRESSURE = uuid16("1810") val SVC_HEALTH_THERMOMETER = uuid16("1809") val SVC_GLUCOSE = uuid16("1808") val SVC_PULSE_OXIMETER = uuid16("1822") val SVC_WEIGHT_SCALE = uuid16("181D") val SVC_BODY_COMPOSITION = uuid16("181B") val SVC_HEART_RATE = uuid16("180D") val SVC_BATTERY = uuid16("180F") val SVC_DEVICE_INFO = uuid16("180A") // Characteristics val CH_BP_MEASUREMENT = uuid16("2A35") val CH_TEMPERATURE = uuid16("2A1C") val CH_GLUCOSE = uuid16("2A18") val CH_GLUCOSE_CONTEXT = uuid16("2A34") val CH_RACP = uuid16("2A52") val CH_PLX_SPOT = uuid16("2A5E") val CH_PLX_CONTINUOUS = uuid16("2A5F") val CH_WEIGHT = uuid16("2A9D") val CH_BODY_COMPOSITION = uuid16("2A9C") val CH_HEART_RATE = uuid16("2A37") val CH_BATTERY_LEVEL = uuid16("2A19") val CH_SERIAL = uuid16("2A25") val CH_MANUFACTURER = uuid16("2A29") val CH_MODEL = uuid16("2A24") val CH_FIRMWARE = uuid16("2A26") val CCCD: UUID = uuid16("2902") val HEALTH_SERVICES = listOf(SVC_BLOOD_PRESSURE, SVC_HEALTH_THERMOMETER, SVC_GLUCOSE, SVC_PULSE_OXIMETER, SVC_WEIGHT_SCALE, SVC_BODY_COMPOSITION, SVC_HEART_RATE) /** Characteristics we subscribe to, with true = indication, false = notification. */ val MEASUREMENT_CHARS = mapOf( CH_BP_MEASUREMENT to true, CH_TEMPERATURE to true, CH_GLUCOSE to false, CH_RACP to true, CH_PLX_SPOT to true, CH_PLX_CONTINUOUS to false, CH_WEIGHT to true, CH_BODY_COMPOSITION to true, CH_HEART_RATE to false ) /** Accept the device clock only if it is within 2 days of the phone clock (many devices are never set). */ private const val MAX_SKEW_MS = 2L * 24 * 3600 * 1000 // ------------------------------------------------------------------ number formats fun u8(b: ByteArray, o: Int) = b[o].toInt() and 0xFF fun u16(b: ByteArray, o: Int) = (b[o].toInt() and 0xFF) or ((b[o + 1].toInt() and 0xFF) shl 8) fun s16(b: ByteArray, o: Int) = u16(b, o).toShort().toInt() /** IEEE-11073 16-bit SFLOAT. Returns null for NaN / NRes / ±INF / reserved. */ fun sfloat(b: ByteArray, o: Int): Double? { val raw = u16(b, o) if (raw == 0x07FF || raw == 0x0800 || raw == 0x07FE || raw == 0x0802 || raw == 0x0801) return null var mantissa = raw and 0x0FFF var exponent = raw shr 12 if (mantissa >= 0x0800) mantissa -= 0x1000 if (exponent >= 0x0008) exponent -= 0x0010 return mantissa * 10.0.pow(exponent) } /** IEEE-11073 32-bit FLOAT. */ fun float32(b: ByteArray, o: Int): Double? { val raw = (b[o].toLong() and 0xFF) or ((b[o + 1].toLong() and 0xFF) shl 8) or ((b[o + 2].toLong() and 0xFF) shl 16) if (raw == 0x7FFFFFL || raw == 0x800000L || raw == 0x7FFFFEL || raw == 0x800002L || raw == 0x800001L) return null val mantissa = if (raw >= 0x800000) raw - 0x1000000 else raw val exponent = b[o + 3].toInt() return mantissa * 10.0.pow(exponent) } /** 7-byte Date Time (year u16, month, day, h, m, s) in the phone's time zone. Returns null if unset/invalid. */ fun dateTime(b: ByteArray, o: Int, tz: TimeZone = TimeZone.getDefault()): Long? { val year = u16(b, o); val month = u8(b, o + 2); val day = u8(b, o + 3) if (year < 2000 || month !in 1..12 || day !in 1..31) return null val c = Calendar.getInstance(tz) c.clear() c.set(year, month - 1, day, u8(b, o + 4), u8(b, o + 5), u8(b, o + 6)) return c.timeInMillis } private fun pickTime(deviceTime: Long?, now: Long, trustDevice: Boolean = false): Long = if (deviceTime != null && (trustDevice || kotlin.math.abs(deviceTime - now) < MAX_SKEW_MS) && deviceTime <= now + 300_000) deviceTime else now // ------------------------------------------------------------------ Blood Pressure Measurement 0x2A35 fun bloodPressure(b: ByteArray, now: Long = System.currentTimeMillis()): List { val flags = u8(b, 0) val kPa = flags and 0x01 != 0 var o = 1 val sys = sfloat(b, o); val dia = sfloat(b, o + 2); val map = sfloat(b, o + 4); o += 6 var t: Long? = null if (flags and 0x02 != 0) { t = dateTime(b, o); o += 7 } var pulse: Double? = null if (flags and 0x04 != 0 && b.size >= o + 2) { pulse = sfloat(b, o); o += 2 } val ts = pickTime(t, now) val unit = if (kPa) "kPa" else "mmHg" return listOfNotNull( sys?.let { Reading("bp_sys", it, unit, ts) }, dia?.let { Reading("bp_dia", it, unit, ts) }, map?.let { Reading("bp_map", it, unit, ts) }, pulse?.let { Reading("pulse", it, "/min", ts) } ) } // ------------------------------------------------------------------ Temperature Measurement 0x2A1C fun temperature(b: ByteArray, now: Long = System.currentTimeMillis()): List { val flags = u8(b, 0) val f = flags and 0x01 != 0 val v = float32(b, 1) ?: return emptyList() var t: Long? = null if (flags and 0x02 != 0 && b.size >= 12) t = dateTime(b, 5) return listOf(Reading("temp", v, if (f) "[degF]" else "Cel", pickTime(t, now))) } // ------------------------------------------------------------------ Glucose Measurement 0x2A18 fun glucose(b: ByteArray, now: Long = System.currentTimeMillis()): List { val flags = u8(b, 0) var o = 1 val seq = u16(b, o); o += 2 var base = dateTime(b, o); o += 7 if (flags and 0x01 != 0) { val offMin = s16(b, o); o += 2; base = base?.plus(offMin * 60_000L) } if (flags and 0x02 == 0) return emptyList() val conc = sfloat(b, o) ?: return emptyList(); o += 2 val molPerL = flags and 0x04 != 0 // kg/L -> mg/dL (x100000); mol/L -> mmol/L (x1000) val (value, unit) = if (molPerL) Pair(conc * 1000.0, "mmol/L") else Pair(conc * 100000.0, "mg/dL") // Glucose meters keep a real clock for their memory; trust it for record sync return listOf(Reading("glucose", Math.round(value * 10) / 10.0, unit, pickTime(base, now, trustDevice = true), sequence = seq)) } /** Glucose Measurement Context 0x2A34 → meal context for a sequence number. */ fun glucoseContext(b: ByteArray): Pair? { if (b.size < 3) return null val flags = u8(b, 0) val seq = u16(b, 1) var o = 3 if (flags and 0x80 != 0) o += 1 // extended flags if (flags and 0x01 != 0) o += 3 // carbohydrate id + kg if (flags and 0x02 != 0 && b.size > o) { // meal return seq to when (u8(b, o)) { 1 -> "pre_meal"; 2 -> "post_meal"; 3 -> "fasting"; 4 -> "random"; 5 -> "bedtime"; else -> null } } return seq to null } /** RACP command: report stored records (all, or with sequence number >= fromSeq). */ fun racpReport(fromSeq: Int?): ByteArray = if (fromSeq == null) byteArrayOf(0x01, 0x01) else byteArrayOf(0x01, 0x03, 0x01, (fromSeq and 0xFF).toByte(), ((fromSeq shr 8) and 0xFF).toByte()) // ------------------------------------------------------------------ PLX Spot-check 0x2A5E / Continuous 0x2A5F fun plxSpot(b: ByteArray, now: Long = System.currentTimeMillis()): List { val flags = u8(b, 0) val spo2 = sfloat(b, 1); val pr = sfloat(b, 3) var o = 5 var t: Long? = null if (flags and 0x01 != 0) { t = dateTime(b, o); o += 7 } if (flags and 0x02 != 0) o += 2 if (flags and 0x04 != 0) o += 3 val pai = if (flags and 0x08 != 0 && b.size >= o + 2) sfloat(b, o) else null val ts = pickTime(t, now) return listOfNotNull(spo2?.let { Reading("spo2", it, "%", ts) }, pr?.let { Reading("pulse", it, "/min", ts) }, pai?.let { Reading("pi", it, "%", ts) }) } fun plxContinuous(b: ByteArray, now: Long = System.currentTimeMillis()): List { val flags = u8(b, 0) val spo2 = sfloat(b, 1); val pr = sfloat(b, 3) var o = 5 if (flags and 0x01 != 0) o += 4 if (flags and 0x02 != 0) o += 4 if (flags and 0x04 != 0) o += 2 if (flags and 0x08 != 0) o += 3 val pai = if (flags and 0x10 != 0 && b.size >= o + 2) sfloat(b, o) else null return listOfNotNull(spo2?.let { Reading("spo2", it, "%", now) }, pr?.let { Reading("pulse", it, "/min", now) }, pai?.let { Reading("pi", it, "%", now) }) } // ------------------------------------------------------------------ Weight Measurement 0x2A9D fun weight(b: ByteArray, now: Long = System.currentTimeMillis()): List { val flags = u8(b, 0) val imperial = flags and 0x01 != 0 val raw = u16(b, 1) if (raw == 0xFFFF) return emptyList() // measurement unsuccessful val w = if (imperial) raw * 0.01 else raw * 0.005 var o = 3 var t: Long? = null if (flags and 0x02 != 0) { t = dateTime(b, o); o += 7 } if (flags and 0x04 != 0) o += 1 var bmi: Double? = null if (flags and 0x08 != 0 && b.size >= o + 4) bmi = u16(b, o) * 0.1 val ts = pickTime(t, now) return listOfNotNull( Reading("weight", Math.round(w * 100) / 100.0, if (imperial) "[lb_av]" else "kg", ts), bmi?.let { Reading("bmi", Math.round(it * 10) / 10.0, "kg/m2", ts) } ) } // ------------------------------------------------------------------ Body Composition Measurement 0x2A9C fun bodyComposition(b: ByteArray, now: Long = System.currentTimeMillis()): List { val flags = u16(b, 0) val imperial = flags and 0x0001 != 0 val fatRaw = u16(b, 2) var o = 4 var t: Long? = null if (flags and 0x0002 != 0) { t = dateTime(b, o); o += 7 } if (flags and 0x0004 != 0) o += 1 for (bit in listOf(0x0008, 0x0010, 0x0020, 0x0040, 0x0080, 0x0100, 0x0200)) if (flags and bit != 0) o += 2 var w: Double? = null if (flags and 0x0400 != 0 && b.size >= o + 2) w = u16(b, o) * (if (imperial) 0.01 else 0.005) val ts = pickTime(t, now) return listOfNotNull( if (fatRaw != 0xFFFF) Reading("body_fat", fatRaw * 0.1, "%", ts) else null, w?.let { Reading("weight", Math.round(it * 100) / 100.0, if (imperial) "[lb_av]" else "kg", ts) } ) } // ------------------------------------------------------------------ Heart Rate Measurement 0x2A37 fun heartRate(b: ByteArray, now: Long = System.currentTimeMillis()): List { val flags = u8(b, 0) val hr = if (flags and 0x01 != 0) u16(b, 1) else u8(b, 1) return if (hr in 20..300) listOf(Reading("hr", hr.toDouble(), "/min", now)) else emptyList() } /** Route a characteristic value to its parser. */ fun parse(characteristic: UUID, value: ByteArray, now: Long = System.currentTimeMillis()): List = try { when (characteristic) { CH_BP_MEASUREMENT -> bloodPressure(value, now) CH_TEMPERATURE -> temperature(value, now) CH_GLUCOSE -> glucose(value, now) CH_PLX_SPOT -> plxSpot(value, now) CH_PLX_CONTINUOUS -> plxContinuous(value, now) CH_WEIGHT -> weight(value, now) CH_BODY_COMPOSITION -> bodyComposition(value, now) CH_HEART_RATE -> heartRate(value, now) else -> emptyList() } } catch (e: IndexOutOfBoundsException) { emptyList() // malformed packet from device - ignore } /** 16-bit service short code for the API (e.g. "1810"). */ fun shortCode(u: UUID): String = u.toString().substring(4, 8).uppercase() }