package `in`.caresoft.carepulse.connect.ble import android.annotation.SuppressLint import android.bluetooth.* import android.bluetooth.le.ScanCallback import android.bluetooth.le.ScanFilter import android.bluetooth.le.ScanResult import android.bluetooth.le.ScanSettings import android.content.Context import android.os.Build import android.os.Handler import android.os.Looper import android.os.ParcelUuid import android.util.Log import `in`.caresoft.carepulse.connect.Prefs import `in`.caresoft.carepulse.connect.data.ReadingQueue import `in`.caresoft.carepulse.connect.work.UploadWorker import org.json.JSONArray import org.json.JSONObject import java.util.ArrayDeque import java.util.UUID /** * Scans for Bluetooth LE health devices (standard SIG profiles), connects, subscribes to measurement * characteristics, syncs glucose memory with RACP, reads battery / device info, and queues readings. * * Typical flow: patient presses "Take reading" (or auto-listen is on) → measures on the device → * the device advertises → we connect → it sends the stored measurement(s) → we queue + upload. * * Permissions (BLUETOOTH_SCAN / BLUETOOTH_CONNECT) are checked by the UI before start(). */ @SuppressLint("MissingPermission") class BleCollector(private val ctx: Context, private val listener: Listener) { interface Listener { fun onStatus(text: String) fun onReadings(deviceName: String, readings: List) } private val tag = "CarePulseBLE" private val adapter: BluetoothAdapter? = (ctx.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter private val main = Handler(Looper.getMainLooper()) private val queue = ReadingQueue(ctx) private val prefs = Prefs.get(ctx) private val busy = mutableSetOf() // MACs we are connected to private var scanning = false /** Known device-name prefixes of vendor devices that do not advertise the standard service UUID. */ private val namePrefixes: List by lazy { val out = mutableListOf() val models = prefs.config?.optJSONArray("device_models") ?: JSONArray() for (i in 0 until models.length()) models.optJSONObject(i)?.optString("name_prefix")?.takeIf { it.isNotBlank() && it != "null" }?.let { out += it } out } val isBluetoothOn get() = adapter?.isEnabled == true fun start(timeoutMs: Long? = 90_000) { val scanner = adapter?.bluetoothLeScanner ?: run { listener.onStatus("Bluetooth is off"); return } if (scanning) return val filters = GattParsers.HEALTH_SERVICES.map { ScanFilter.Builder().setServiceUuid(ParcelUuid(it)).build() }.toMutableList() namePrefixes.forEach { filters += ScanFilter.Builder().setDeviceName(it).build() } val settings = ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build() scanner.startScan(filters, settings, scanCb) scanning = true listener.onStatus("Listening for your device… take your measurement now") timeoutMs?.let { main.postDelayed({ stop() }, it) } } fun stop() { if (!scanning) return runCatching { adapter?.bluetoothLeScanner?.stopScan(scanCb) } scanning = false listener.onStatus("Stopped listening") } private val scanCb = object : ScanCallback() { override fun onScanResult(callbackType: Int, result: ScanResult) { val dev = result.device if (dev.address in busy) return busy += dev.address val name = result.scanRecord?.deviceName ?: dev.name ?: "Health device" val svc = result.scanRecord?.serviceUuids?.map { it.uuid }?.firstOrNull { it in GattParsers.HEALTH_SERVICES } listener.onStatus("Found $name – connecting…") Session(dev, name, svc).connect() } override fun onScanFailed(errorCode: Int) { scanning = false; listener.onStatus("Scan failed ($errorCode). Turn Bluetooth off and on.") } } /** One connection to one device, with a serial queue of GATT operations (Android allows one at a time). */ private inner class Session(val dev: BluetoothDevice, val name: String, var service: UUID?) { private val ops = ArrayDeque<() -> Unit>() private var opRunning = false private var gatt: BluetoothGatt? = null private val collected = mutableListOf() private val contexts = mutableMapOf() private var battery: Int? = null private val info = mutableMapOf() private var flushScheduled = false fun connect() { gatt = if (Build.VERSION.SDK_INT >= 23) dev.connectGatt(ctx, false, cb, BluetoothDevice.TRANSPORT_LE) else dev.connectGatt(ctx, false, cb) main.postDelayed({ finish("timeout") }, 120_000) } private fun enqueue(op: () -> Unit) { ops.add(op); if (!opRunning) next() } private fun next() { val op = ops.poll() if (op == null) { opRunning = false; return } opRunning = true main.post { runCatching { op() }.onFailure { Log.w(tag, "op failed", it); next() } } } private fun subscribe(g: BluetoothGatt, ch: BluetoothGattCharacteristic, indicate: Boolean) = enqueue { g.setCharacteristicNotification(ch, true) val d = ch.getDescriptor(GattParsers.CCCD) ?: return@enqueue next() val v = if (indicate) BluetoothGattDescriptor.ENABLE_INDICATION_VALUE else BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE if (Build.VERSION.SDK_INT >= 33) g.writeDescriptor(d, v) else @Suppress("DEPRECATION") run { d.value = v; g.writeDescriptor(d) } } private fun read(g: BluetoothGatt, ch: BluetoothGattCharacteristic) = enqueue { if (!g.readCharacteristic(ch)) next() } private fun write(g: BluetoothGatt, ch: BluetoothGattCharacteristic, value: ByteArray) = enqueue { if (Build.VERSION.SDK_INT >= 33) g.writeCharacteristic(ch, value, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT) else @Suppress("DEPRECATION") run { ch.value = value; ch.writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT; g.writeCharacteristic(ch) } } private val cb = object : BluetoothGattCallback() { override fun onConnectionStateChange(g: BluetoothGatt, status: Int, newState: Int) { if (newState == BluetoothProfile.STATE_CONNECTED) main.post { g.discoverServices() } else if (newState == BluetoothProfile.STATE_DISCONNECTED) finish("disconnected") } override fun onServicesDiscovered(g: BluetoothGatt, status: Int) { if (status != BluetoothGatt.GATT_SUCCESS) { finish("discovery failed"); return } // Device information + battery first (read), then subscriptions g.getService(GattParsers.SVC_DEVICE_INFO)?.let { s -> listOf(GattParsers.CH_SERIAL, GattParsers.CH_MANUFACTURER, GattParsers.CH_MODEL, GattParsers.CH_FIRMWARE).forEach { c -> s.getCharacteristic(c)?.let { read(g, it) } } } g.getService(GattParsers.SVC_BATTERY)?.getCharacteristic(GattParsers.CH_BATTERY_LEVEL)?.let { read(g, it) } for (s in g.services) { if (s.uuid in GattParsers.HEALTH_SERVICES && service == null) service = s.uuid for (ch in s.characteristics) { GattParsers.MEASUREMENT_CHARS[ch.uuid]?.let { ind -> subscribe(g, ch, ind) } if (ch.uuid == GattParsers.CH_GLUCOSE_CONTEXT) subscribe(g, ch, false) } } // Glucose meters keep readings in memory: ask for records newer than the last one we synced g.getService(GattParsers.SVC_GLUCOSE)?.getCharacteristic(GattParsers.CH_RACP)?.let { racp -> val last = prefs.glucoseSeq(dev.address) write(g, racp, GattParsers.racpReport(last?.plus(1))) } } override fun onDescriptorWrite(g: BluetoothGatt, d: BluetoothGattDescriptor, status: Int) { if (status == BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION || status == 5 || status == 15) { // Device needs pairing (bonding) – Android shows the pairing prompt; retry after bond if (dev.bondState == BluetoothDevice.BOND_NONE) dev.createBond() listener.onStatus("Pair $name when asked (PIN is usually on the device screen or 000000)") } next() } override fun onCharacteristicWrite(g: BluetoothGatt, ch: BluetoothGattCharacteristic, status: Int) { next() } @Deprecated("Deprecated in Java") override fun onCharacteristicRead(g: BluetoothGatt, ch: BluetoothGattCharacteristic, status: Int) { @Suppress("DEPRECATION") onRead(ch, ch.value ?: ByteArray(0)); next() } override fun onCharacteristicRead(g: BluetoothGatt, ch: BluetoothGattCharacteristic, value: ByteArray, status: Int) { onRead(ch, value); next() } @Deprecated("Deprecated in Java") override fun onCharacteristicChanged(g: BluetoothGatt, ch: BluetoothGattCharacteristic) { @Suppress("DEPRECATION") onValue(ch.uuid, ch.value ?: ByteArray(0)) } override fun onCharacteristicChanged(g: BluetoothGatt, ch: BluetoothGattCharacteristic, value: ByteArray) { onValue(ch.uuid, value) } } private fun onRead(ch: BluetoothGattCharacteristic, v: ByteArray) { when (ch.uuid) { GattParsers.CH_BATTERY_LEVEL -> battery = v.firstOrNull()?.toInt()?.and(0xFF) GattParsers.CH_SERIAL -> info["serial"] = String(v).trim() GattParsers.CH_MANUFACTURER -> info["manufacturer"] = String(v).trim() GattParsers.CH_MODEL -> info["model"] = String(v).trim() GattParsers.CH_FIRMWARE -> info["firmware"] = String(v).trim() } } private fun onValue(ch: UUID, v: ByteArray) { when (ch) { GattParsers.CH_RACP -> { scheduleFlush(1500); return } // "records sent" response GattParsers.CH_GLUCOSE_CONTEXT -> { GattParsers.glucoseContext(v)?.let { contexts[it.first] = it.second }; return } } val rs = GattParsers.parse(ch, v) if (rs.isEmpty()) return synchronized(collected) { collected += rs } // Continuous oximeters/HR straps stream: flush every 30 s; spot devices: flush shortly after the last value scheduleFlush(if (ch == GattParsers.CH_PLX_CONTINUOUS || ch == GattParsers.CH_HEART_RATE) 30_000 else 3_000) } private fun scheduleFlush(delay: Long) { if (flushScheduled) return flushScheduled = true main.postDelayed({ flushScheduled = false; flush() }, delay) } @Synchronized private fun flush() { val items: List synchronized(collected) { items = collected.toList(); collected.clear() } if (items.isEmpty()) return // Continuous streams: keep one value per parameter per minute val reduced = items.groupBy { it.param to it.measuredAt / 60_000 }.map { (_, v) -> v.last() } val arr = JSONArray() reduced.forEach { r -> arr.put(JSONObject().put("param", r.param).put("value", r.value).put("unit", r.unit).put("measured_at", r.measuredAt) .apply { (r.context ?: r.sequence?.let { contexts[it] })?.let { put("context", it) } }) } val device = JSONObject().put("mac", dev.address).put("name", name) service?.let { device.put("ble_service", GattParsers.shortCode(it)) } battery?.let { device.put("battery", it) } info.forEach { (k, v) -> device.put(if (k == "model") "model" else k, v) } val batch = JSONObject().put("batch_id", "${dev.address.replace(":", "")}-${System.currentTimeMillis()}").put("device", device).put("readings", arr) prefs.wardUhid?.takeIf { it.isNotBlank() }?.let { batch.put("patient", JSONObject().put("uhid", it)) } // ward mode: patient chosen on screen val summary = describe(reduced) queue.add(batch, summary) queue.log("$name: $summary") reduced.mapNotNull { it.sequence }.maxOrNull()?.let { prefs.setGlucoseSeq(dev.address, it) } listener.onReadings(name, reduced) UploadWorker.now(ctx) } fun finish(why: String) { flush() runCatching { gatt?.close() } gatt = null busy -= dev.address Log.d(tag, "session ${dev.address} closed: $why") } } companion object { fun describe(rs: List): String { val m = rs.associateBy { it.param } val parts = mutableListOf() if (m["bp_sys"] != null && m["bp_dia"] != null) parts += "BP ${m["bp_sys"]!!.value.toInt()}/${m["bp_dia"]!!.value.toInt()}" m["pulse"]?.let { parts += "Pulse ${it.value.toInt()}" } m["spo2"]?.let { parts += "SpO₂ ${it.value.toInt()}%" } m["temp"]?.let { parts += "Temp ${"%.1f".format(it.value)}${if (it.unit == "Cel") "°C" else "°F"}" } rs.filter { it.param == "glucose" }.lastOrNull()?.let { parts += "Sugar ${it.value} ${it.unit}" + if (rs.count { r -> r.param == "glucose" } > 1) " (+${rs.count { r -> r.param == "glucose" } - 1} from memory)" else "" } m["weight"]?.let { parts += "Weight ${"%.1f".format(it.value)} ${if (it.unit == "kg") "kg" else "lb"}" } m["hr"]?.let { parts += "HR ${it.value.toInt()}" } return parts.joinToString(" · ").ifEmpty { "${rs.size} values" } } } }