diff --git a/README.md b/README.md index 1f53a0e5..d0eeaeee 100644 --- a/README.md +++ b/README.md @@ -91,6 +91,7 @@ calibration offsets. - **Blood pressure calibration** (Settings → Calibration) — enter reference systolic/diastolic values from a cuff to apply an offset. 56ff/Jring only. - **Blood sugar calibration** (Settings → Calibration) — enter a reference glucose reading from lab work or a glucometer to calibrate the ring's profile-derived blood sugar estimates. 56ff/Jring only. - **Privacy & Data** (Settings → Privacy & Data) — demo-data controls (reseed/clear) and the anonymized diagnostics export for bug reports. +- **MQTT** (Settings → MQTT) — publishes real ring vitals, daily activity, sleep stages, and live workout streaming (~5 s throttle) to any MQTT broker with configurable topics, auto-discovery payloads, and background sync intervals. See [docs/mqtt.md](docs/mqtt.md) for topic formats, capability-based sensor selection, and example payloads. ### Simplified Ring Management - **Forget ring** — removes the ring from the app in one tap. The unbind command is sent to the ring to release it for pairing with other apps. diff --git a/app/src/main/java/com/pulseloop/data/dao/Daos.kt b/app/src/main/java/com/pulseloop/data/dao/Daos.kt index c1b363ce..ad73ae52 100644 --- a/app/src/main/java/com/pulseloop/data/dao/Daos.kt +++ b/app/src/main/java/com/pulseloop/data/dao/Daos.kt @@ -54,6 +54,10 @@ interface MeasurementDao { @Query("SELECT value FROM measurements WHERE kindRaw = :kind AND timestamp <= :before ORDER BY timestamp DESC LIMIT 1") suspend fun latest(kind: String, before: Long = System.currentTimeMillis()): Double? + /** Latest real (non-demo/mock) measurement of [kind], for exports (MQTT) that must never surface seeded demo data. */ + @Query("SELECT * FROM measurements WHERE kindRaw = :kind AND sourceRaw NOT IN ('demo','mock') ORDER BY timestamp DESC LIMIT 1") + suspend fun latestReal(kind: String): MeasurementEntity? + /** Newest measurement of any kind — iOS `latestMeasurementTimestamp()`, the live-data leg of * the coach check-in's hasRecentData freshness fallback. */ @Query("SELECT MAX(timestamp) FROM measurements") diff --git a/app/src/main/java/com/pulseloop/mqtt/MqttClient.kt b/app/src/main/java/com/pulseloop/mqtt/MqttClient.kt new file mode 100644 index 00000000..7acf2fef --- /dev/null +++ b/app/src/main/java/com/pulseloop/mqtt/MqttClient.kt @@ -0,0 +1,413 @@ +package com.pulseloop.mqtt + +import java.io.BufferedInputStream +import java.io.BufferedOutputStream +import java.io.Closeable +import java.io.IOException +import java.net.InetSocketAddress +import java.net.Socket +import java.util.concurrent.locks.ReentrantLock +import javax.net.ssl.SSLSocket +import javax.net.ssl.SSLSocketFactory +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/** + * A single outbound MQTT message. + */ +data class MqttMessage( + val topic: String, + val payload: ByteArray, + val qos: Int = 1, + val retain: Boolean = false, +) { + constructor( + topic: String, + payload: String, + qos: Int = 1, + retain: Boolean = false, + ) : this(topic, payload.toByteArray(Charsets.UTF_8), qos, retain) + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is MqttMessage) return false + return topic == other.topic && + payload.contentEquals(other.payload) && + qos == other.qos && + retain == other.retain + } + + override fun hashCode(): Int { + var result = topic.hashCode() + result = 31 * result + payload.contentHashCode() + result = 31 * result + qos + result = 31 * result + retain.hashCode() + return result + } +} + +/** + * Connection parameters for an MQTT broker endpoint. + */ +data class MqttEndpointConfig( + val host: String, + val port: Int, + val useTls: Boolean = false, + val transport: MqttTransport = MqttTransport.TCP, + val wsPath: String = "/mqtt", + val username: String = "", + val password: String = "", + val clientId: String, + val keepAliveSeconds: Int = 60, + val connectTimeoutMs: Int = 10_000, + val readTimeoutMs: Int = 10_000, +) + +/** + * Raised for any MQTT protocol or transport failure. + */ +class MqttException(message: String, cause: Throwable? = null) : IOException(message, cause) + +/** + * A live MQTT connection over a (possibly TLS-wrapped) socket. + * Not thread-safe on its own; callers must serialize access. + */ +internal class MqttConnection( + private val socket: Socket, + private val input: BufferedInputStream, + private val output: BufferedOutputStream, + private var nextPacketId: Int = 1, +) : Closeable { + + companion object { + /** + * Opens a new connection to [config], performing the MQTT CONNECT/CONNACK handshake. + * On any failure the underlying socket is closed before the exception propagates. + */ + fun open(config: MqttEndpointConfig): MqttConnection { + val host = config.host.trim() + if (host.isBlank()) { + throw MqttException("MQTT host must not be blank") + } + if (config.port !in 1..65535) { + throw MqttException("MQTT port must be in 1..65535, was: ${config.port}") + } + + var socket: Socket? = null + try { + val plain = Socket() + socket = plain + plain.connect(InetSocketAddress(host, config.port), config.connectTimeoutMs) + plain.soTimeout = config.readTimeoutMs + + var liveSocket: Socket = plain + if (config.useTls) { + val factory = SSLSocketFactory.getDefault() as SSLSocketFactory + val ssl = factory.createSocket(plain, host, config.port, true) as SSLSocket + ssl.sslParameters = ssl.sslParameters.apply { + endpointIdentificationAlgorithm = "HTTPS" + } + ssl.startHandshake() + liveSocket = ssl + } + + val rawInput = BufferedInputStream(liveSocket.getInputStream()) + val rawOutput = BufferedOutputStream(liveSocket.getOutputStream()) + val (input, output) = if (config.transport == MqttTransport.WEBSOCKET) { + val (wsIn, wsOut) = MqttWebSocket.upgrade( + host = host, + port = config.port, + useTls = config.useTls, + path = config.wsPath, + rawInput = rawInput, + rawOutput = rawOutput, + ) + BufferedInputStream(wsIn) to BufferedOutputStream(wsOut) + } else { + rawInput to rawOutput + } + val connection = MqttConnection(liveSocket, input, output) + + output.write( + MqttProtocol.encodeConnect( + clientId = config.clientId, + username = config.username.ifEmpty { null }, + password = if (config.username.isNotEmpty() && config.password.isNotEmpty()) { + config.password + } else { + null + }, + keepAliveSeconds = config.keepAliveSeconds, + cleanSession = true, + ) + ) + output.flush() + + val packet = connection.readPacket() + val ack = MqttProtocol.decodeConnAck(packet) + if (ack.returnCode != MqttProtocol.CONNACK_ACCEPTED) { + throw MqttException( + "MQTT connect rejected: ${MqttProtocol.connAckDescription(ack.returnCode)}" + ) + } + return connection + } catch (e: IOException) { + runCatching { socket?.close() } + if (e is MqttException) throw e + throw MqttException("MQTT connect failed: ${e.message}", e) + } catch (e: RuntimeException) { + runCatching { socket?.close() } + throw e + } + } + } + + val isClosed: Boolean + get() = socket.isClosed || !socket.isConnected + + /** + * Publishes all messages. QoS 0 messages are fire-and-forget; QoS 1 messages + * wait for a matching PUBACK before proceeding. + */ + fun publishAll(messages: List) { + for (msg in messages) { + when (msg.qos) { + 0 -> output.write( + MqttProtocol.encodePublish( + msg.topic, + msg.payload, + qos = 0, + retain = msg.retain, + ) + ) + 1 -> { + val packetId = allocatePacketId() + output.write( + MqttProtocol.encodePublish( + msg.topic, + msg.payload, + qos = 1, + retain = msg.retain, + packetId = packetId, + ) + ) + output.flush() + awaitPubAck(packetId) + } + else -> throw MqttException("Unsupported MQTT QoS level: ${msg.qos}") + } + } + output.flush() + } + + /** + * Sends a PINGREQ and waits for the PINGRESP. + */ + fun ping() { + output.write(MqttProtocol.encodePingReq()) + output.flush() + val packet = readPacket() + if (packet.packetType != MqttProtocol.PACKET_PINGRESP) { + throw MqttException( + "Unexpected MQTT packet while awaiting PINGRESP: type=${packet.packetType}" + ) + } + } + + /** + * Best-effort graceful disconnect followed by close. Never throws. + */ + fun disconnectAndClose() { + runCatching { + output.write(MqttProtocol.encodeDisconnect()) + output.flush() + } + runCatching { close() } + } + + override fun close() { + runCatching { input.close() } + runCatching { output.close() } + runCatching { socket.close() } + } + + private fun readPacket(): MqttProtocol.MqttPacket = + MqttProtocol.readPacket(input) + + private fun allocatePacketId(): Int { + val id = nextPacketId + nextPacketId = if (nextPacketId >= 65535) 1 else nextPacketId + 1 + return id + } + + private fun awaitPubAck(packetId: Int) { + while (true) { + val packet = readPacket() + when (packet.packetType) { + MqttProtocol.PACKET_PUBACK -> { + val ackId = MqttProtocol.decodePubAckPacketId(packet) + if (ackId == packetId) return + throw MqttException( + "MQTT PUBACK packetId mismatch: expected $packetId, got $ackId" + ) + } + MqttProtocol.PACKET_PINGRESP -> continue + else -> throw MqttException( + "Unexpected MQTT packet while awaiting PUBACK: type=${packet.packetType}" + ) + } + } + } +} + +/** + * One-shot MQTT publishing API. + */ +object MqttClient { + + /** + * Publishes [messages] to [config] on a fresh connection, then disconnects cleanly. + */ + suspend fun publishAll(config: MqttEndpointConfig, messages: List) { + withContext(Dispatchers.IO) { + if (messages.isEmpty()) return@withContext + var connection: MqttConnection? = null + try { + connection = MqttConnection.open(config) + connection.publishAll(messages) + } catch (e: MqttException) { + throw e + } catch (e: IOException) { + throw MqttException("MQTT publish failed: ${e.message}", e) + } finally { + connection?.disconnectAndClose() + } + } + } + + /** + * Verifies the broker is reachable by connecting and performing a PINGREQ/PINGRESP. + */ + suspend fun testConnection(config: MqttEndpointConfig) { + withContext(Dispatchers.IO) { + var connection: MqttConnection? = null + try { + connection = MqttConnection.open(config) + connection.ping() + connection.disconnectAndClose() + connection = null + } catch (e: MqttException) { + throw e + } catch (e: IOException) { + throw MqttException("MQTT connection test failed: ${e.message}", e) + } finally { + connection?.disconnectAndClose() + } + } + } +} + +/** + * Keeps at most one idle MQTT connection alive for [idleTtlMs] to amortize + * connect/handshake cost across publishes targeting the same endpoint. + * + * Mutual exclusion is provided by a [ReentrantLock] acquired on the IO + * dispatcher; the critical section performs only blocking socket I/O and + * contains no suspension points, so holding the lock across it is safe. + */ +class MqttSessionPool( + private val idleTtlMs: Long = 30_000L, + private val clockMs: () -> Long = { System.currentTimeMillis() }, +) { + + private val lock = ReentrantLock() + private var connection: MqttConnection? = null + private var activeConfig: MqttEndpointConfig? = null + private var lastUsedMs: Long = 0L + + /** + * Publishes [messages], reusing the cached connection when it is still open, + * configured for the same endpoint, and within the idle TTL. A reused + * connection that fails with a plain IOException (stale socket) triggers + * exactly one reconnect-and-retry. On any failure the cached connection + * is discarded so the next call starts fresh. + */ + suspend fun publish(config: MqttEndpointConfig, messages: List) { + if (messages.isEmpty()) return + withContext(Dispatchers.IO) { + lock.lock() + try { + try { + var reused = false + val existing = connection + val conn: MqttConnection + if (existing != null && + !existing.isClosed && + activeConfig == config && + (clockMs() - lastUsedMs) <= idleTtlMs + ) { + conn = existing + reused = true + } else { + conn = openFreshLocked(config) + } + + try { + conn.publishAll(messages) + } catch (e: IOException) { + if (reused && e !is MqttException) { + // Stale reused socket: reconnect once and retry. + val fresh = openFreshLocked(config) + fresh.publishAll(messages) + } else { + throw e + } + } + + lastUsedMs = clockMs() + } catch (e: MqttException) { + closeAndClearLocked() + throw e + } catch (e: IOException) { + closeAndClearLocked() + throw MqttException("MQTT publish failed: ${e.message}", e) + } + } finally { + lock.unlock() + } + } + } + + /** + * Closes any cached connection and resets pool state. + */ + suspend fun close() { + withContext(Dispatchers.IO) { + lock.lock() + try { + closeAndClearLocked() + } finally { + lock.unlock() + } + } + } + + private fun openFreshLocked(config: MqttEndpointConfig): MqttConnection { + closeAndClearLocked() + val fresh = MqttConnection.open(config) + connection = fresh + activeConfig = config + return fresh + } + + private fun closeAndClearLocked() { + connection?.disconnectAndClose() + connection = null + activeConfig = null + lastUsedMs = 0L + } + + companion object { + val shared: MqttSessionPool = MqttSessionPool() + } +} diff --git a/app/src/main/java/com/pulseloop/mqtt/MqttDiscovery.kt b/app/src/main/java/com/pulseloop/mqtt/MqttDiscovery.kt new file mode 100644 index 00000000..88999626 --- /dev/null +++ b/app/src/main/java/com/pulseloop/mqtt/MqttDiscovery.kt @@ -0,0 +1,657 @@ +package com.pulseloop.mqtt + +import com.pulseloop.data.entity.DeviceEntity +import com.pulseloop.ring.MeasurementKind +import com.pulseloop.ring.RingDeviceType +import com.pulseloop.ring.WearableCapability +import com.pulseloop.ring.ringModelLabel +import com.pulseloop.wearables.WearableModel +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put + +/** + * Pure-Kotlin MQTT state and auto-discovery payload generation. + * + * No Android dependencies: safe to run directly in JVM unit tests. + */ +data class DeviceIdentity( + val uniquePrefix: String, + val slug: String, + val displayName: String, + val manufacturer: String, + val model: String, + val swVersion: String?, + val macAddress: String?, +) + +data class SensorDescriptor( + val key: String, + val component: String = "sensor", + val name: String, + val jsonField: String, + val unit: String? = null, + val deviceClass: String? = null, + val stateClass: String? = null, + val icon: String? = null, + val entityCategory: String? = null, + val suggestedDisplayPrecision: Int? = null, + val payloadOn: String? = null, + val payloadOff: String? = null, + val valueTemplate: String? = null, +) + +data class MqttDataSnapshot( + val batteryPercent: Int? = null, + val heartRateBpm: Int? = null, + val restingHeartRateBpm: Int? = null, + val spo2Percent: Int? = null, + val hrvMs: Double? = null, + val stressScore: Int? = null, + val temperatureCelsius: Double? = null, + val steps: Int? = null, + val caloriesKcal: Double? = null, + val distanceMeters: Int? = null, + val activeMinutes: Int? = null, + val sleepTotalMinutes: Int? = null, + val sleepScore: Int? = null, + val sleepDeepMinutes: Int? = null, + val sleepLightMinutes: Int? = null, + val sleepRemMinutes: Int? = null, + val sleepAwakeMinutes: Int? = null, + val bpSystolicMmhg: Int? = null, + val bpDiastolicMmhg: Int? = null, + val bloodSugarMmol: Double? = null, + val respiratoryRateBrpm: Double? = null, + val vo2Max: Double? = null, + val workoutActive: Boolean = false, + val workoutType: String? = null, + val workoutDurationSeconds: Int? = null, + val lastSyncIso: String? = null, + val availableKinds: Set = emptySet(), +) + +object MqttDiscovery { + + private val MAC_REGEX = Regex("^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$") + private val NON_SLUG_CHARS = Regex("[^a-z0-9]+") + + // ------------------------------------------------------------------ + // Slug / identity helpers + // ------------------------------------------------------------------ + + fun sanitizeSlug(raw: String): String { + val cleaned = raw.lowercase() + .replace(NON_SLUG_CHARS, "_") + .trim('_') + return cleaned.ifEmpty { "ring" } + } + + fun resolveDeviceIdentity(device: DeviceEntity, prefs: MqttPrefs): DeviceIdentity { + val model = WearableModel.model(device.wearableModelID)?.displayName + ?: ringModelLabel(device.name, device.deviceType) + + val manufacturer = when (device.deviceType) { + RingDeviceType.COLMI_R02, + RingDeviceType.COLMI_SMART_HEALTH, + RingDeviceType.CRP -> "Colmi" + RingDeviceType.YCBT -> "YCBT" + RingDeviceType.RWFIT -> "RWfit" + else -> "Smart Ring" + } + + val rawIdentifier = (device.peripheralIdentifier ?: device.bleAddressHint ?: device.id).trim() + val idDigits = rawIdentifier.lowercase().replace(Regex("[^a-z0-9]"), "") + .ifEmpty { device.id.lowercase().replace(Regex("[^a-z0-9]"), "") } + + val uniquePrefix = "pulseloop_$idDigits" + val shortSuffix = idDigits.takeLast(4).ifEmpty { "ring" } + + val overrideName = prefs.deviceNameOverride.trim() + val displayName = overrideName.ifEmpty { + device.name.trim().ifEmpty { + device.advertisedName?.trim().orEmpty().ifEmpty { model } + } + } + + val slug = if (overrideName.isNotEmpty()) { + sanitizeSlug(overrideName) + } else { + sanitizeSlug("${displayName}_$shortSuffix") + } + + val macAddress = (device.peripheralIdentifier ?: device.bleAddressHint) + ?.trim() + ?.takeIf { MAC_REGEX.matches(it) } + + val swVersion = device.firmwareVersion?.trim()?.takeIf { it.isNotEmpty() } + + return DeviceIdentity( + uniquePrefix = uniquePrefix, + slug = slug, + displayName = displayName, + manufacturer = manufacturer, + model = model, + swVersion = swVersion, + macAddress = macAddress, + ) + } + + // ------------------------------------------------------------------ + // Topic helpers + // ------------------------------------------------------------------ + + fun stateTopic(baseTopic: String, identity: DeviceIdentity): String = + "${baseTopic.trim().trim('/').ifEmpty { "pulseloop" }}/${identity.slug}/state" + + fun discoveryTopic(discoveryPrefix: String, descriptor: SensorDescriptor, identity: DeviceIdentity): String = + "${discoveryPrefix.trim().trim('/').ifEmpty { "homeassistant" }}/" + + "${descriptor.component}/${identity.uniquePrefix}/${descriptor.key}/config" + + /** Maps a stored sensor key back to its discovery component prefix. */ + fun componentForKey(key: String): String = + if (key == "workout_active") "binary_sensor" else "sensor" + + // ------------------------------------------------------------------ + // Sensor descriptors (strict capability + data gating) + // ------------------------------------------------------------------ + + fun sensorsFor(device: DeviceEntity, snapshot: MqttDataSnapshot): List { + val caps = device.capabilities + val sensors = mutableListOf() + + val workoutRelevant = WearableCapability.HEART_RATE in caps || + snapshot.workoutActive || + snapshot.workoutType != null + + if (WearableCapability.BATTERY in caps) { + sensors += SensorDescriptor( + key = "battery", + name = "Battery", + jsonField = "battery", + unit = "%", + deviceClass = "battery", + stateClass = "measurement", + icon = "mdi:battery", + ) + } + + if (WearableCapability.HEART_RATE in caps || WearableCapability.MANUAL_HEART_RATE in caps) { + sensors += SensorDescriptor( + key = "heart_rate", + name = "Heart Rate", + jsonField = "heart_rate", + unit = "bpm", + stateClass = "measurement", + icon = "mdi:heart-pulse", + ) + } + + if ((WearableCapability.HEART_RATE in caps || WearableCapability.MANUAL_HEART_RATE in caps) && + snapshot.restingHeartRateBpm != null + ) { + sensors += SensorDescriptor( + key = "resting_heart_rate", + name = "Resting Heart Rate", + jsonField = "resting_heart_rate", + unit = "bpm", + stateClass = "measurement", + icon = "mdi:heart-outline", + ) + } + + if (WearableCapability.SPO2 in caps || + WearableCapability.SPO2_HISTORY in caps || + WearableCapability.MANUAL_SPO2 in caps + ) { + sensors += SensorDescriptor( + key = "spo2", + name = "Blood Oxygen", + jsonField = "spo2", + unit = "%", + stateClass = "measurement", + icon = "mdi:water-percent", + ) + } + + if (WearableCapability.HRV in caps || WearableCapability.MANUAL_HRV in caps) { + sensors += SensorDescriptor( + key = "hrv", + name = "HRV", + jsonField = "hrv", + unit = "ms", + stateClass = "measurement", + icon = "mdi:heart-flash", + suggestedDisplayPrecision = 1, + ) + } + + // CRITICAL (#67): only expose stress when real hardware stress readings exist. + if ((WearableCapability.STRESS in caps || WearableCapability.MANUAL_STRESS in caps) && + MeasurementKind.STRESS.name in snapshot.availableKinds + ) { + sensors += SensorDescriptor( + key = "stress", + name = "Stress", + jsonField = "stress", + stateClass = "measurement", + icon = "mdi:emoticon-neutral-outline", + ) + } + + if (WearableCapability.TEMPERATURE in caps || WearableCapability.MANUAL_TEMPERATURE in caps) { + sensors += SensorDescriptor( + key = "temperature", + name = "Skin Temperature", + jsonField = "temperature", + unit = "°C", + deviceClass = "temperature", + stateClass = "measurement", + suggestedDisplayPrecision = 1, + ) + } + + if (WearableCapability.STEPS in caps) { + sensors += SensorDescriptor( + key = "steps", + name = "Steps", + jsonField = "steps", + unit = "steps", + stateClass = "total_increasing", + icon = "mdi:walk", + ) + sensors += SensorDescriptor( + key = "calories", + name = "Calories", + jsonField = "calories", + unit = "kcal", + stateClass = "total_increasing", + icon = "mdi:fire", + suggestedDisplayPrecision = 0, + ) + sensors += SensorDescriptor( + key = "distance", + name = "Distance", + jsonField = "distance", + unit = "m", + deviceClass = "distance", + stateClass = "total_increasing", + icon = "mdi:map-marker-distance", + ) + sensors += SensorDescriptor( + key = "active_minutes", + name = "Active Minutes", + jsonField = "active_minutes", + unit = "min", + deviceClass = "duration", + stateClass = "total_increasing", + icon = "mdi:run", + ) + } + + if (WearableCapability.SLEEP in caps) { + sensors += SensorDescriptor( + key = "sleep_duration", + name = "Sleep Duration", + jsonField = "sleep_duration", + unit = "min", + deviceClass = "duration", + stateClass = "measurement", + icon = "mdi:sleep", + ) + sensors += SensorDescriptor( + key = "sleep_score", + name = "Sleep Score", + jsonField = "sleep_score", + stateClass = "measurement", + icon = "mdi:star-circle-outline", + ) + sensors += SensorDescriptor( + key = "sleep_deep", + name = "Deep Sleep", + jsonField = "sleep_deep", + unit = "min", + deviceClass = "duration", + stateClass = "measurement", + icon = "mdi:power-sleep", + ) + sensors += SensorDescriptor( + key = "sleep_light", + name = "Light Sleep", + jsonField = "sleep_light", + unit = "min", + deviceClass = "duration", + stateClass = "measurement", + icon = "mdi:weather-night", + ) + if (WearableCapability.REM_SLEEP in caps) { + sensors += SensorDescriptor( + key = "sleep_rem", + name = "REM Sleep", + jsonField = "sleep_rem", + unit = "min", + deviceClass = "duration", + stateClass = "measurement", + icon = "mdi:eye-outline", + ) + } + sensors += SensorDescriptor( + key = "sleep_awake", + name = "Awake Sleep", + jsonField = "sleep_awake", + unit = "min", + deviceClass = "duration", + stateClass = "measurement", + icon = "mdi:sleep-off", + ) + } + + if (WearableCapability.BLOOD_PRESSURE in caps || WearableCapability.MANUAL_BLOOD_PRESSURE in caps) { + sensors += SensorDescriptor( + key = "blood_pressure_systolic", + name = "Blood Pressure Systolic", + jsonField = "blood_pressure_systolic", + unit = "mmHg", + stateClass = "measurement", + icon = "mdi:blood-bag", + ) + sensors += SensorDescriptor( + key = "blood_pressure_diastolic", + name = "Blood Pressure Diastolic", + jsonField = "blood_pressure_diastolic", + unit = "mmHg", + stateClass = "measurement", + icon = "mdi:blood-bag", + ) + } + + if (WearableCapability.BLOOD_SUGAR in caps) { + sensors += SensorDescriptor( + key = "blood_sugar", + name = "Blood Glucose", + jsonField = "blood_sugar", + unit = MeasurementKind.BLOOD_SUGAR.unit, + deviceClass = "blood_glucose_concentration", + stateClass = "measurement", + suggestedDisplayPrecision = 1, + ) + } + + // Only if real respiratory-rate readings exist (e.g. YCBT). + if (MeasurementKind.RESPIRATORY_RATE.name in snapshot.availableKinds) { + sensors += SensorDescriptor( + key = "respiratory_rate", + name = "Respiratory Rate", + jsonField = "respiratory_rate", + unit = "breaths/min", + stateClass = "measurement", + icon = "mdi:lungs", + suggestedDisplayPrecision = 1, + ) + } + + if (WearableCapability.VO2MAX in caps) { + sensors += SensorDescriptor( + key = "vo2_max", + name = "VO2 Max", + jsonField = "vo2_max", + unit = "mL/kg/min", + stateClass = "measurement", + icon = "mdi:lungs", + suggestedDisplayPrecision = 1, + ) + } + + if (workoutRelevant) { + sensors += SensorDescriptor( + component = "binary_sensor", + key = "workout_active", + name = "Workout Active", + jsonField = "workout_active", + deviceClass = "running", + icon = "mdi:run-fast", + payloadOn = "ON", + payloadOff = "OFF", + valueTemplate = "{{ 'ON' if value_json.get('workout_active') else 'OFF' }}", + ) + sensors += SensorDescriptor( + key = "workout_type", + name = "Workout Type", + jsonField = "workout_type", + icon = "mdi:dumbbell", + ) + sensors += SensorDescriptor( + key = "workout_duration", + name = "Workout Duration", + jsonField = "workout_duration", + unit = "s", + deviceClass = "duration", + stateClass = "measurement", + icon = "mdi:timer-outline", + ) + } + + // Always included: diagnostic sync timestamp. + sensors += SensorDescriptor( + key = "last_sync", + name = "Last Sync", + jsonField = "last_sync", + deviceClass = "timestamp", + entityCategory = "diagnostic", + icon = "mdi:sync", + ) + + return sensors + } + + // ------------------------------------------------------------------ + // Discovery payload construction + // ------------------------------------------------------------------ + + private fun discoveryJson( + descriptor: SensorDescriptor, + identity: DeviceIdentity, + baseTopic: String, + ): JsonObject = buildJsonObject { + put("name", descriptor.name) + put("unique_id", "${identity.uniquePrefix}_${descriptor.key}") + put("object_id", "${identity.slug}_${descriptor.key}") + put("state_topic", stateTopic(baseTopic, identity)) + put( + "value_template", + descriptor.valueTemplate ?: "{{ value_json.get('${descriptor.jsonField}') }}", + ) + descriptor.unit?.let { put("unit_of_measurement", it) } + descriptor.deviceClass?.let { put("device_class", it) } + descriptor.stateClass?.let { put("state_class", it) } + descriptor.icon?.let { put("icon", it) } + descriptor.entityCategory?.let { put("entity_category", it) } + descriptor.suggestedDisplayPrecision?.let { put("suggested_display_precision", it) } + descriptor.payloadOn?.let { put("payload_on", it) } + descriptor.payloadOff?.let { put("payload_off", it) } + put("device", buildJsonObject { + put("identifiers", JsonArray(listOf(JsonPrimitive(identity.uniquePrefix)))) + put("name", identity.displayName) + put("manufacturer", identity.manufacturer) + put("model", identity.model) + identity.swVersion?.let { put("sw_version", it) } + identity.macAddress?.let { mac -> + put( + "connections", + JsonArray( + listOf( + JsonArray( + listOf(JsonPrimitive("mac"), JsonPrimitive(mac.lowercase())) + ) + ) + ), + ) + } + }) + } + + fun buildDiscoveryMessages( + identity: DeviceIdentity, + sensors: List, + prefs: MqttPrefs, + ): List { + val baseTopic = prefs.normalizedBaseTopic + val discoveryPrefix = prefs.normalizedDiscoveryPrefix + return sensors.map { descriptor -> + MqttMessage( + topic = discoveryTopic(discoveryPrefix, descriptor, identity), + payload = discoveryJson(descriptor, identity, baseTopic).toString(), + qos = 1, + retain = true, + ) + } + } + + fun buildRemovalMessages( + discoveryPrefix: String, + uniquePrefix: String, + sensorDescriptorsOrKeys: Iterable, + ): List { + val prefix = discoveryPrefix.trim().trim('/').ifEmpty { "homeassistant" } + return sensorDescriptorsOrKeys.map { key -> + MqttMessage( + topic = "$prefix/${componentForKey(key)}/$uniquePrefix/$key/config", + payload = ByteArray(0), + qos = 1, + retain = true, + ) + } + } + + // ------------------------------------------------------------------ + // State payload construction + // ------------------------------------------------------------------ + + fun buildStateJson(snapshot: MqttDataSnapshot, activeSensors: List): String { + val activeFields = activeSensors.map { it.jsonField }.toSet() + return buildJsonObject { + if ("battery" in activeFields) { + snapshot.batteryPercent?.let { put("battery", it) } + } + if ("heart_rate" in activeFields) { + snapshot.heartRateBpm?.let { put("heart_rate", it) } + } + if ("resting_heart_rate" in activeFields) { + snapshot.restingHeartRateBpm?.let { put("resting_heart_rate", it) } + } + if ("spo2" in activeFields) { + snapshot.spo2Percent?.let { put("spo2", it) } + } + if ("hrv" in activeFields) { + snapshot.hrvMs?.let { put("hrv", it) } + } + if ("stress" in activeFields) { + snapshot.stressScore?.let { put("stress", it) } + } + if ("temperature" in activeFields) { + snapshot.temperatureCelsius?.let { put("temperature", it) } + } + if ("steps" in activeFields) { + snapshot.steps?.let { put("steps", it) } + } + if ("calories" in activeFields) { + snapshot.caloriesKcal?.let { put("calories", it) } + } + if ("distance" in activeFields) { + snapshot.distanceMeters?.let { put("distance", it) } + } + if ("active_minutes" in activeFields) { + snapshot.activeMinutes?.let { put("active_minutes", it) } + } + if ("sleep_duration" in activeFields) { + snapshot.sleepTotalMinutes?.let { put("sleep_duration", it) } + } + if ("sleep_score" in activeFields) { + snapshot.sleepScore?.let { put("sleep_score", it) } + } + if ("sleep_deep" in activeFields) { + snapshot.sleepDeepMinutes?.let { put("sleep_deep", it) } + } + if ("sleep_light" in activeFields) { + snapshot.sleepLightMinutes?.let { put("sleep_light", it) } + } + if ("sleep_rem" in activeFields) { + snapshot.sleepRemMinutes?.let { put("sleep_rem", it) } + } + if ("sleep_awake" in activeFields) { + snapshot.sleepAwakeMinutes?.let { put("sleep_awake", it) } + } + if ("blood_pressure_systolic" in activeFields) { + snapshot.bpSystolicMmhg?.let { put("blood_pressure_systolic", it) } + } + if ("blood_pressure_diastolic" in activeFields) { + snapshot.bpDiastolicMmhg?.let { put("blood_pressure_diastolic", it) } + } + if ("blood_sugar" in activeFields) { + snapshot.bloodSugarMmol?.let { put("blood_sugar", it) } + } + if ("respiratory_rate" in activeFields) { + snapshot.respiratoryRateBrpm?.let { put("respiratory_rate", it) } + } + if ("vo2_max" in activeFields) { + snapshot.vo2Max?.let { put("vo2_max", it) } + } + if ("workout_active" in activeFields) { + put("workout_active", snapshot.workoutActive) + } + if ("workout_type" in activeFields) { + snapshot.workoutType?.let { put("workout_type", it) } + } + if ("workout_duration" in activeFields) { + snapshot.workoutDurationSeconds?.let { put("workout_duration", it) } + } + if ("last_sync" in activeFields) { + snapshot.lastSyncIso?.let { put("last_sync", it) } + } + }.toString() + } + + // ------------------------------------------------------------------ + // Combined message builder + // ------------------------------------------------------------------ + + fun buildMqttMessages( + device: DeviceEntity, + snapshot: MqttDataSnapshot, + prefs: MqttPrefs, + forceDiscovery: Boolean = false, + ): Pair, Set> { + val identity = resolveDeviceIdentity(device, prefs) + val sensors = sensorsFor(device, snapshot) + val sensorKeys = sensors.map { it.key }.toSet() + + val messages = mutableListOf() + + val needsDiscovery = forceDiscovery || + sensorKeys != prefs.discoveredSensorKeys || + identity.slug != prefs.lastDiscoveredDeviceSlug + + if (needsDiscovery) { + val staleKeys = prefs.discoveredSensorKeys - sensorKeys + if (staleKeys.isNotEmpty()) { + messages += buildRemovalMessages( + prefs.normalizedDiscoveryPrefix, + identity.uniquePrefix, + staleKeys, + ) + } + messages += buildDiscoveryMessages(identity, sensors, prefs) + } + + messages += MqttMessage( + topic = stateTopic(prefs.normalizedBaseTopic, identity), + payload = buildStateJson(snapshot, sensors), + qos = 1, + retain = true, + ) + + return messages to sensorKeys + } +} diff --git a/app/src/main/java/com/pulseloop/mqtt/MqttExportWorker.kt b/app/src/main/java/com/pulseloop/mqtt/MqttExportWorker.kt new file mode 100644 index 00000000..82e06bc6 --- /dev/null +++ b/app/src/main/java/com/pulseloop/mqtt/MqttExportWorker.kt @@ -0,0 +1,55 @@ +package com.pulseloop.mqtt + +import android.content.Context +import androidx.work.CoroutineWorker +import androidx.work.ExistingWorkPolicy +import androidx.work.NetworkType +import androidx.work.OneTimeWorkRequestBuilder +import androidx.work.WorkManager +import androidx.work.WorkerParameters +import androidx.work.Constraints +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import java.util.concurrent.TimeUnit + +class MqttExportWorker( + appContext: Context, + params: WorkerParameters, +) : CoroutineWorker(appContext, params) { + + override suspend fun doWork(): Result { + val prefs = MqttPrefsStore.get(applicationContext).current + if (!prefs.isConfigured) { + return Result.success() + } + + return passMutex.withLock { + when (MqttExporter.run(applicationContext, isLive = false)) { + is MqttExporter.Result.Failure -> + if (runAttemptCount < 3) Result.retry() else Result.success() + else -> Result.success() + } + } + } + + companion object { + private const val WORK_NAME = "pulseloop.mqtt.export" + private val passMutex = Mutex() + + fun enqueue(context: Context) { + if (!MqttPrefsStore.get(context).current.isConfigured) return + + val request = OneTimeWorkRequestBuilder() + .setConstraints( + Constraints.Builder() + .setRequiredNetworkType(NetworkType.CONNECTED) + .build() + ) + .setInitialDelay(10, TimeUnit.SECONDS) + .build() + + WorkManager.getInstance(context.applicationContext) + .enqueueUniqueWork(WORK_NAME, ExistingWorkPolicy.REPLACE, request) + } + } +} diff --git a/app/src/main/java/com/pulseloop/mqtt/MqttExporter.kt b/app/src/main/java/com/pulseloop/mqtt/MqttExporter.kt new file mode 100644 index 00000000..3cb3db41 --- /dev/null +++ b/app/src/main/java/com/pulseloop/mqtt/MqttExporter.kt @@ -0,0 +1,387 @@ +package com.pulseloop.mqtt + +import android.content.Context +import com.pulseloop.AppServices +import com.pulseloop.data.PulseLoopDatabase +import com.pulseloop.data.entity.DeviceEntity +import com.pulseloop.ring.MeasurementKind +import com.pulseloop.service.DailyCalorieEstimator +import com.pulseloop.service.SleepScore +import com.pulseloop.service.awakeMinutes +import com.pulseloop.util.TimeUtil +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.time.Instant +import kotlin.math.round +import kotlin.math.roundToInt + +object MqttExporter { + + sealed class Result { + data class Success( + val messageCount: Int, + val sensorCount: Int, + val isLive: Boolean + ) : Result() + + data object Skipped : Result() + + data class Failure( + val reason: String, + val error: Throwable? = null + ) : Result() + } + + private val DEMO_SOURCES = setOf("demo", "mock") + + /** + * Collects the current health snapshot from the local database and publishes it + * to the configured MQTT broker, including discovery and state messages. + */ + suspend fun run( + context: Context, + isLive: Boolean = false, + forceDiscovery: Boolean = false + ): Result = withContext(Dispatchers.IO) { + val store = MqttPrefsStore.get(context) + val prefs = store.current + if (!prefs.isConfigured) { + return@withContext Result.Skipped + } + if (isLive && !prefs.liveStreamingEnabled) { + return@withContext Result.Skipped + } + val db = PulseLoopDatabase.getInstance(context) + val device = db.deviceDao().currentReal() ?: return@withContext Result.Skipped + publishInternal(context, store, prefs, device, isLive, forceDiscovery) + } + + /** + * Validates the broker settings and attempts a bare connection. + * Never swallows [CancellationException]. + */ + suspend fun testConnection(context: Context): Result = withContext(Dispatchers.IO) { + val store = MqttPrefsStore.get(context) + val prefs = store.current + if (prefs.host.isBlank() || prefs.port !in 1..65535) { + return@withContext Result.Failure("Broker host and port are required") + } + val db = PulseLoopDatabase.getInstance(context) + val deviceId = db.deviceDao().currentReal()?.id ?: "android" + val config = buildEndpointConfig(prefs, store, deviceId) + try { + MqttClient.testConnection(config) + store.update { it.copy(lastError = null) } + Result.Success(0, 0, false) + } catch (ce: CancellationException) { + throw ce + } catch (t: Throwable) { + val message = t.message ?: t.javaClass.simpleName + store.update { it.copy(lastError = message) } + Result.Failure("Connection failed: $message", t) + } + } + + /** + * Forces a full publish (including discovery) using a one-shot connection. + */ + suspend fun publishNow(context: Context): Result = withContext(Dispatchers.IO) { + val store = MqttPrefsStore.get(context) + val prefs = store.current + if (prefs.host.isBlank() || prefs.port !in 1..65535) { + return@withContext Result.Failure("Broker host and port are required") + } + val db = PulseLoopDatabase.getInstance(context) + val device = db.deviceDao().currentReal() + ?: return@withContext Result.Failure("No paired ring found") + publishInternal(context, store, prefs, device, isLive = false, forceDiscovery = true) + } + + /** + * Publishes zero-byte tombstones for all retained discovery and state topics + * and clears the local discovery bookkeeping. + */ + suspend fun clearRetainedTopics(context: Context): Result = withContext(Dispatchers.IO) { + val store = MqttPrefsStore.get(context) + val prefs = store.current + if (prefs.host.isBlank() || prefs.port !in 1..65535) { + return@withContext Result.Failure("Broker host and port are required") + } + val db = PulseLoopDatabase.getInstance(context) + val device = db.deviceDao().currentReal() + val identity = device?.let { MqttDiscovery.resolveDeviceIdentity(it, prefs) } + val keys = buildSet { + addAll(prefs.discoveredSensorKeys) + if (device != null) { + addAll(MqttDiscovery.sensorsFor(device, MqttDataSnapshot()).map { it.key }) + } + } + + var messageCount = 0 + if (identity != null && keys.isNotEmpty()) { + val messages = MqttDiscovery.buildRemovalMessages( + prefs.normalizedDiscoveryPrefix, + identity.uniquePrefix, + keys + ).toMutableList() + val stateTopic = MqttDiscovery.stateTopic(prefs.normalizedBaseTopic, identity) + messages.add( + MqttMessage( + topic = stateTopic, + payload = ByteArray(0), + qos = 1, + retain = true + ) + ) + val config = buildEndpointConfig(prefs, store, device?.id ?: "android") + try { + MqttClient.publishAll(config, messages) + messageCount = messages.size + } catch (ce: CancellationException) { + throw ce + } catch (t: Throwable) { + store.update { it.copy(lastError = t.message ?: t.javaClass.simpleName) } + return@withContext Result.Failure( + t.message ?: "Failed to clear retained MQTT topics", + t + ) + } + } + + store.update { + it.copy( + discoveredSensorKeys = emptySet(), + lastDiscoveredDeviceSlug = null, + lastPublishAt = null, + lastPublishSummary = null, + lastError = null + ) + } + Result.Success(messageCount, keys.size, false) + } + + // ------------------------------------------------------------------ + // Internal + // ------------------------------------------------------------------ + + private suspend fun publishInternal( + context: Context, + store: MqttPrefsStore, + prefs: MqttPrefs, + device: DeviceEntity, + isLive: Boolean, + forceDiscovery: Boolean + ): Result { + val db = PulseLoopDatabase.getInstance(context) + val identity = MqttDiscovery.resolveDeviceIdentity(device, prefs) + val snapshot = collectSnapshot(db, device) + val (messages, discoveredKeys) = MqttDiscovery.buildMqttMessages( + device, + snapshot, + prefs, + forceDiscovery + ) + if (messages.isEmpty()) { + return Result.Skipped + } + val config = buildEndpointConfig(prefs, store, device.id) + return try { + if (isLive) { + MqttSessionPool.shared.publish(config, messages) + } else { + MqttClient.publishAll(config, messages) + } + val now = System.currentTimeMillis() + store.update { + it.copy( + discoveredSensorKeys = discoveredKeys, + lastDiscoveredDeviceSlug = identity.slug, + lastPublishAt = now, + lastPublishSummary = "${messages.size} message(s), ${discoveredKeys.size} sensor(s)" + + if (isLive) " (live)" else "", + lastError = null + ) + } + Result.Success(messages.size, discoveredKeys.size, isLive) + } catch (ce: CancellationException) { + throw ce + } catch (t: Throwable) { + store.update { it.copy(lastError = t.message ?: t.javaClass.simpleName) } + Result.Failure(t.message ?: "MQTT publish failed", t) + } + } + + private fun buildEndpointConfig( + prefs: MqttPrefs, + store: MqttPrefsStore, + deviceId: String + ): MqttEndpointConfig = MqttEndpointConfig( + host = prefs.host, + port = prefs.port, + useTls = prefs.useTls, + transport = prefs.transport, + wsPath = prefs.normalizedWsPath, + username = prefs.username, + password = store.getPassword(), + clientId = buildClientId(deviceId) + ) + + /** + * Deterministic MQTT client id, guaranteed to be at most 23 characters: + * "pl_" (3) + up to 12 hex-ish chars = at most 15 characters. + */ + private fun buildClientId(deviceId: String): String = + ("pl_" + deviceId.replace("-", "").takeLast(12)).take(23) + + internal suspend fun collectSnapshot( + db: PulseLoopDatabase, + device: DeviceEntity + ): MqttDataSnapshot { + val measurementDao = db.measurementDao() + + val availableKinds = buildSet { + for (kind in MeasurementKind.entries) { + if (measurementDao.hasReal(kind.name)) { + add(kind.name) + } + } + } + + suspend fun latest(kind: MeasurementKind): Double? = measurementDao.latestReal(kind.name)?.value + + var heartRateBpm = latest(MeasurementKind.HEART_RATE)?.roundToInt() + var spo2Percent = latest(MeasurementKind.SPO2)?.roundToInt() + val hrvMs = latest(MeasurementKind.HRV)?.let { roundTo1Decimal(it) } + val stressScore = if (MeasurementKind.STRESS.name in availableKinds) { + latest(MeasurementKind.STRESS)?.roundToInt() + } else { + null + } + val temperatureCelsius = latest(MeasurementKind.TEMPERATURE)?.let { roundTo1Decimal(it) } + val bpSystolicMmhg = latest(MeasurementKind.BLOOD_PRESSURE_SYSTOLIC)?.roundToInt() + val bpDiastolicMmhg = latest(MeasurementKind.BLOOD_PRESSURE_DIASTOLIC)?.roundToInt() + val bloodSugarMmol = latest(MeasurementKind.BLOOD_SUGAR)?.let { roundTo1Decimal(it) } + val respiratoryRateBrpm = if (MeasurementKind.RESPIRATORY_RATE.name in availableKinds) { + latest(MeasurementKind.RESPIRATORY_RATE)?.let { roundTo1Decimal(it) } + } else { + null + } + val vo2Max = latest(MeasurementKind.VO2MAX)?.let { roundTo1Decimal(it) } + + val profile = db.userProfileDao().get() + val restingHeartRateBpm = profile?.hrRestingBaseline?.roundToInt() + + // Today's real activity + val todayRow = db.activityDailyDao() + .byDay(TimeUtil.startOfTodayLocal()) + ?.takeIf { it.source !in DEMO_SOURCES } + val steps = todayRow?.steps + val caloriesKcal = todayRow?.let { + DailyCalorieEstimator.effectiveCalories( + it, + DailyCalorieEstimator.Profile( + profile?.sex, + profile?.age, + profile?.weightKg, + profile?.heightCm + ), + System.currentTimeMillis() + )?.roundToInt()?.toDouble() + } + val distanceMeters = todayRow?.distanceMeters?.roundToInt() + val activeMinutes = todayRow?.activeMinutes + + // Last night's real sleep + val sleepSession = db.sleepSessionDao() + .ringAllByDay(TimeUtil.referenceNightLocal()) + .filter { it.sourceRaw !in DEMO_SOURCES && it.totalMinutes > 0 } + .maxByOrNull { it.totalMinutes } + val sleepBlocks = sleepSession + ?.let { db.sleepStageBlockDao().forSession(it.id) } + .orEmpty() + val sleepTotalMinutes = sleepSession?.totalMinutes + val sleepScore = sleepSession?.let { SleepScore.calculate(it, sleepBlocks).score } + val sleepDeepMinutes = if (sleepSession != null) { + sleepBlocks + .filter { it.stageRaw.equals("DEEP", ignoreCase = true) } + .sumOf { it.durationMinutes } + } else { + null + } + val sleepLightMinutes = if (sleepSession != null) { + sleepBlocks + .filter { it.stageRaw.equals("LIGHT", ignoreCase = true) } + .sumOf { it.durationMinutes } + } else { + null + } + val sleepRemMinutes = if (sleepSession != null) { + sleepBlocks + .filter { it.stageRaw.equals("REM", ignoreCase = true) } + .sumOf { it.durationMinutes } + } else { + null + } + val sleepAwakeMinutes = sleepSession?.let { awakeMinutes(sleepBlocks) } + + // Live workout + val workoutState = AppServices.peek()?.liveWorkout?.state?.value + val activeSession = if (workoutState?.isRecording == true) { + workoutState.activeSession + } else { + db.activitySessionDao().active() + } + val workoutActive = (workoutState?.isRecording == true) || activeSession != null + heartRateBpm = workoutState?.takeIf { it.isRecording }?.latestHeartRate ?: heartRateBpm + spo2Percent = workoutState?.takeIf { it.isRecording }?.latestSpO2 ?: spo2Percent + val workoutType = activeSession?.type + ?.replace('_', ' ') + ?.lowercase() + ?.replaceFirstChar { it.uppercaseChar() } + val workoutDurationSeconds = when { + workoutState?.isRecording == true -> workoutState.elapsedSeconds + activeSession != null -> ((System.currentTimeMillis() - activeSession.startedAt) / 1000L) + .toInt() + .coerceAtLeast(0) + else -> null + } + + val lastSyncIso = listOfNotNull(device.lastSyncAt, device.lastFullSyncAt) + .maxOrNull() + ?.let { Instant.ofEpochMilli(it).toString() } + + return MqttDataSnapshot( + availableKinds = availableKinds, + heartRateBpm = heartRateBpm, + spo2Percent = spo2Percent, + hrvMs = hrvMs, + stressScore = stressScore, + temperatureCelsius = temperatureCelsius, + bpSystolicMmhg = bpSystolicMmhg, + bpDiastolicMmhg = bpDiastolicMmhg, + bloodSugarMmol = bloodSugarMmol, + respiratoryRateBrpm = respiratoryRateBrpm, + vo2Max = vo2Max, + restingHeartRateBpm = restingHeartRateBpm, + steps = steps, + caloriesKcal = caloriesKcal, + distanceMeters = distanceMeters, + activeMinutes = activeMinutes, + sleepTotalMinutes = sleepTotalMinutes, + sleepScore = sleepScore, + sleepDeepMinutes = sleepDeepMinutes, + sleepLightMinutes = sleepLightMinutes, + sleepRemMinutes = sleepRemMinutes, + sleepAwakeMinutes = sleepAwakeMinutes, + workoutActive = workoutActive, + workoutType = workoutType, + workoutDurationSeconds = workoutDurationSeconds, + lastSyncIso = lastSyncIso, + batteryPercent = device.batteryPercent + ) + } + + private fun roundTo1Decimal(value: Double): Double = + round(value * 10.0) / 10.0 +} diff --git a/app/src/main/java/com/pulseloop/mqtt/MqttLivePublisher.kt b/app/src/main/java/com/pulseloop/mqtt/MqttLivePublisher.kt new file mode 100644 index 00000000..0817b16c --- /dev/null +++ b/app/src/main/java/com/pulseloop/mqtt/MqttLivePublisher.kt @@ -0,0 +1,85 @@ +package com.pulseloop.mqtt + +import android.content.Context +import android.util.Log +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +object MqttLivePublisher { + + private const val THROTTLE_MS = 5_000L + private const val TAG = "MqttLivePublisher" + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + private val publishMutex = Mutex() + private val lock = Any() + + private var lastDispatchMs = 0L + private var pendingJob: Job? = null + + fun publishLive(context: Context) { + val prefs = MqttPrefsStore.get(context).current + if (!prefs.isConfigured || !prefs.liveStreamingEnabled) return + + val appContext = context.applicationContext + synchronized(lock) { + if (pendingJob?.isActive == true) return + val now = System.currentTimeMillis() + val waitMs = (lastDispatchMs + THROTTLE_MS - now).coerceAtLeast(0L) + pendingJob = scope.launch { + if (waitMs > 0L) delay(waitMs) + synchronized(lock) { + pendingJob = null + lastDispatchMs = System.currentTimeMillis() + } + val latestPrefs = MqttPrefsStore.get(appContext).current + if (!latestPrefs.isConfigured || !latestPrefs.liveStreamingEnabled) return@launch + try { + publishMutex.withLock { + MqttExporter.run(appContext, isLive = true) + } + } catch (t: Throwable) { + if (t is CancellationException) throw t + Log.w(TAG, "Live publish failed", t) + } + } + } + } + + fun onWorkoutFinished(context: Context) { + val prefs = MqttPrefsStore.get(context).current + if (!prefs.isConfigured) return + + val appContext = context.applicationContext + synchronized(lock) { + pendingJob?.cancel() + pendingJob = null + lastDispatchMs = System.currentTimeMillis() + } + scope.launch { + try { + publishMutex.withLock { + val useLive = MqttPrefsStore.get(appContext).current.liveStreamingEnabled + MqttExporter.run(appContext, isLive = useLive) + MqttSessionPool.shared.close() + } + } catch (t: Throwable) { + if (t is CancellationException) throw t + Log.w(TAG, "Workout finish publish failed", t) + } + } + } + + fun resetPool() { + scope.launch { + runCatching { MqttSessionPool.shared.close() } + } + } +} diff --git a/app/src/main/java/com/pulseloop/mqtt/MqttPrefsStore.kt b/app/src/main/java/com/pulseloop/mqtt/MqttPrefsStore.kt new file mode 100644 index 00000000..cf22364d --- /dev/null +++ b/app/src/main/java/com/pulseloop/mqtt/MqttPrefsStore.kt @@ -0,0 +1,212 @@ +package com.pulseloop.mqtt + +import android.content.Context +import android.content.SharedPreferences +import android.util.Log +import androidx.security.crypto.EncryptedSharedPreferences +import androidx.security.crypto.MasterKeys +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.Json + +/** + * Network transport used to reach the MQTT broker. + */ +@Serializable +enum class MqttTransport { + TCP, + WEBSOCKET, +} + +/** + * Serializable MQTT integration preferences for PulseLoop. + */ +@Serializable +data class MqttPrefs( + val enabled: Boolean = false, + val host: String = "", + val port: Int = 1883, + val useTls: Boolean = false, + val transport: MqttTransport = MqttTransport.TCP, + val wsPath: String = "/mqtt", + val username: String = "", + val discoveryPrefix: String = "homeassistant", + val baseTopic: String = "pulseloop", + val deviceNameOverride: String = "", + val syncIntervalMinutes: Int = 30, + val liveStreamingEnabled: Boolean = true, + val lastPublishAt: Long? = null, + val lastPublishSummary: String? = null, + val lastError: String? = null, + val discoveredSensorKeys: Set = emptySet(), + val lastDiscoveredDeviceSlug: String? = null, +) { + /** Discovery prefix with surrounding whitespace/slashes removed, falling back to the default. */ + val normalizedDiscoveryPrefix: String + get() = discoveryPrefix.trim().trim('/').ifEmpty { "homeassistant" } + + /** Base topic with surrounding whitespace/slashes removed, falling back to the default. */ + val normalizedBaseTopic: String + get() = baseTopic.trim().trim('/').ifEmpty { "pulseloop" } + + /** WebSocket endpoint path normalized with a leading slash, defaulting to `/mqtt`. */ + val normalizedWsPath: String + get() = MqttWebSocket.normalizePath(wsPath) + + /** True when the broker connection settings are complete and valid. */ + val isConfigured: Boolean + get() = enabled && host.trim().isNotEmpty() && port in 1..65535 + + /** Sync interval clamped to the supported range [15, 720] minutes. */ + val effectiveSyncIntervalMinutes: Int + get() = syncIntervalMinutes.coerceIn(15, 720) +} + +/** + * Thread-safe store persisting [MqttPrefs] to plain [SharedPreferences] and the broker + * password to [EncryptedSharedPreferences]. + * + * The constructor is [internal] so tests can build instances with fake preferences. + */ +class MqttPrefsStore internal constructor( + private val prefs: SharedPreferences, + private val securePrefs: SharedPreferences?, +) { + + private val json = Json { + ignoreUnknownKeys = true + encodeDefaults = true + } + + private val writeLock = Any() + + private val _state = MutableStateFlow(loadPrefs()) + + /** Current preferences as a [StateFlow]. */ + val state: StateFlow = _state.asStateFlow() + + /** Current preferences snapshot. */ + val current: MqttPrefs + get() = _state.value + + /** + * Atomically applies [transform] to the current state, persists the result, and returns it. + */ + fun update(transform: (MqttPrefs) -> MqttPrefs): MqttPrefs = synchronized(writeLock) { + val next = transform(_state.value) + prefs.edit().putString(KEY_PREFS, json.encodeToString(next)).apply() + _state.value = next + next + } + + /** + * Re-reads preferences from disk, publishes them to [state], and returns them. + */ + fun reload(): MqttPrefs = synchronized(writeLock) { + val loaded = loadPrefs() + _state.value = loaded + loaded + } + + /** + * Reads the broker password from encrypted storage; returns an empty string on any failure. + */ + fun getPassword(): String = synchronized(writeLock) { + try { + securePrefs?.getString(KEY_PASSWORD, "") ?: "" + } catch (e: Exception) { + Log.w(TAG, "Failed to read MQTT password", e) + "" + } + } + + /** + * Stores the broker password in encrypted storage, or removes it when [password] is empty. + * Never stores the password in plain preferences; a no-op if secure storage is unavailable. + */ + fun setPassword(password: String) { + synchronized(writeLock) { + val secure = securePrefs ?: return + try { + if (password.isEmpty()) { + secure.edit().remove(KEY_PASSWORD).apply() + } else { + secure.edit().putString(KEY_PASSWORD, password).apply() + } + } catch (e: Exception) { + Log.w(TAG, "Failed to store MQTT password", e) + } + } + } + + /** True when a broker password is set. */ + fun hasPassword(): Boolean = getPassword().isNotEmpty() + + private fun loadPrefs(): MqttPrefs { + val raw = prefs.getString(KEY_PREFS, null) ?: return MqttPrefs() + return try { + json.decodeFromString(raw) + } catch (e: SerializationException) { + Log.w(TAG, "Malformed MQTT prefs JSON; using defaults", e) + MqttPrefs() + } catch (e: IllegalArgumentException) { + Log.w(TAG, "Malformed MQTT prefs JSON; using defaults", e) + MqttPrefs() + } catch (e: Exception) { + Log.w(TAG, "Failed to load MQTT prefs; using defaults", e) + MqttPrefs() + } + } + + companion object { + private const val TAG = "MqttPrefsStore" + private const val PREF_FILE = "pulseloop_prefs" + private const val SECURE_PREF_FILE = "pulseloop_secure" + internal const val KEY_PREFS = "pulseloop.mqtt.v1" + internal const val KEY_PASSWORD = "mqtt_password" + + @Volatile + private var instance: MqttPrefsStore? = null + + /** + * Returns the process-wide singleton [MqttPrefsStore], creating it on first use. + */ + fun get(context: Context): MqttPrefsStore { + val existing = instance + if (existing != null) return existing + return synchronized(this) { + val cached = instance + if (cached != null) { + cached + } else { + val appContext = context.applicationContext + val prefs = appContext.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE) + val store = MqttPrefsStore(prefs, createSecurePrefs(appContext)) + instance = store + store + } + } + } + + /** + * Creates [EncryptedSharedPreferences] for credential storage, or null on failure. + */ + private fun createSecurePrefs(appContext: Context): SharedPreferences? = try { + val masterKey = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC) + EncryptedSharedPreferences.create( + SECURE_PREF_FILE, + masterKey, + appContext, + EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, + EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM, + ) + } catch (e: Exception) { + Log.w(TAG, "Failed to create encrypted preferences; password storage disabled", e) + null + } + } +} diff --git a/app/src/main/java/com/pulseloop/mqtt/MqttProtocol.kt b/app/src/main/java/com/pulseloop/mqtt/MqttProtocol.kt new file mode 100644 index 00000000..d315d354 --- /dev/null +++ b/app/src/main/java/com/pulseloop/mqtt/MqttProtocol.kt @@ -0,0 +1,355 @@ +package com.pulseloop.mqtt + +import java.io.ByteArrayOutputStream +import java.io.EOFException +import java.io.IOException +import java.io.InputStream + +/** + * Pure-Kotlin implementation of the MQTT 3.1.1 wire protocol subset used by PulseLoop. + * + * Supports encoding/decoding of CONNECT, CONNACK, PUBLISH, PUBACK, PINGREQ, PINGRESP + * and DISCONNECT packets. Contains no Android dependencies so it can be unit-tested + * directly on the JVM. + */ +internal object MqttProtocol { + + // ------------------------------------------------------------------ + // Packet type constants (MQTT 3.1.1 section 2.2.1) + // ------------------------------------------------------------------ + const val PACKET_CONNECT = 1 + const val PACKET_CONNACK = 2 + const val PACKET_PUBLISH = 3 + const val PACKET_PUBACK = 4 + const val PACKET_PINGREQ = 12 + const val PACKET_PINGRESP = 13 + const val PACKET_DISCONNECT = 14 + + /** CONNACK return code: connection accepted. */ + const val CONNACK_ACCEPTED = 0 + + /** Maximum value representable by the MQTT variable-length remaining length field. */ + private const val MAX_REMAINING_LENGTH = 268_435_455 // 0xFF,0xFF,0xFF,0x7F + + /** Maximum length of an MQTT UTF-8 string (2-byte unsigned length prefix). */ + private const val MAX_STRING_LENGTH = 65_535 + + // ------------------------------------------------------------------ + // Data classes + // ------------------------------------------------------------------ + + /** + * A decoded MQTT packet: the fixed-header type and flags plus the raw body + * (everything after the remaining-length field). + */ + data class MqttPacket( + val packetType: Int, + val flags: Int, + val body: ByteArray, + ) { + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is MqttPacket) return false + return packetType == other.packetType && + flags == other.flags && + body.contentEquals(other.body) + } + + override fun hashCode(): Int { + var result = packetType + result = 31 * result + flags + result = 31 * result + body.contentHashCode() + return result + } + } + + /** Decoded contents of a CONNACK packet. */ + data class ConnAck( + val sessionPresent: Boolean, + val returnCode: Int, + ) + + // ------------------------------------------------------------------ + // Remaining length helpers (MQTT 3.1.1 section 2.2.3) + // ------------------------------------------------------------------ + + /** + * Encodes [length] using the MQTT variable-length encoding and appends the + * resulting bytes to [out]. + * + * @throws IllegalArgumentException if [length] is outside 0..268_435_455. + */ + fun encodeRemainingLength(length: Int, out: ByteArrayOutputStream) { + require(length in 0..MAX_REMAINING_LENGTH) { + "Remaining length out of range: $length (must be 0..$MAX_REMAINING_LENGTH)" + } + var value = length + do { + var byte = value % 128 + value /= 128 + if (value > 0) { + byte = byte or 0x80 + } + out.write(byte) + } while (value > 0) + } + + /** + * Decodes an MQTT variable-length remaining length field from [input], + * consuming 1..4 bytes. + * + * @throws EOFException if the stream ends before the field is complete. + * @throws IOException if the continuation bit is still set on the 4th byte. + */ + fun decodeRemainingLength(input: InputStream): Int { + var multiplier = 1 + var value = 0 + var byte: Int + do { + byte = input.read() + if (byte < 0) { + throw EOFException("Premature EOF while reading MQTT remaining length") + } + value += (byte and 0x7F) * multiplier + if ((byte and 0x80) != 0 && multiplier >= 128 * 128 * 128) { + // Continuation bit set on the 4th byte -> malformed. + throw IOException("Malformed MQTT remaining length") + } + multiplier *= 128 + } while (byte and 0x80 != 0) + return value + } + + // ------------------------------------------------------------------ + // UTF-8 string helper + // ------------------------------------------------------------------ + + /** + * Writes [value] as an MQTT UTF-8 string: a 2-byte big-endian length prefix + * followed by the UTF-8 encoded bytes. + * + * @throws IllegalArgumentException if the UTF-8 encoding exceeds 65_535 bytes. + */ + fun writeMqttString(out: ByteArrayOutputStream, value: String) { + val bytes = value.toByteArray(Charsets.UTF_8) + if (bytes.size > MAX_STRING_LENGTH) { + throw IllegalArgumentException( + "MQTT string exceeds 65535 bytes: ${bytes.size}" + ) + } + out.write((bytes.size ushr 8) and 0xFF) + out.write(bytes.size and 0xFF) + out.write(bytes) + } + + // ------------------------------------------------------------------ + // Packet encoders + // ------------------------------------------------------------------ + + /** + * Encodes an MQTT CONNECT packet. + * + * @throws IllegalArgumentException if a password is supplied without a username, + * or if the clientId UTF-8 encoding exceeds 65_535 bytes. + */ + fun encodeConnect( + clientId: String, + username: String? = null, + password: String? = null, + keepAliveSeconds: Int = 60, + cleanSession: Boolean = true, + ): ByteArray { + require(!(password != null && username == null)) { + "Password provided without a username" + } + val clientIdBytes = clientId.toByteArray(Charsets.UTF_8) + require(clientIdBytes.size <= MAX_STRING_LENGTH) { + "Client id UTF-8 length exceeds 65535 bytes: ${clientIdBytes.size}" + } + + val body = ByteArrayOutputStream() + + // Variable header: protocol name "MQTT", level 4. + writeMqttString(body, "MQTT") + body.write(0x04) // protocol level + + // Connect flags. + var connectFlags = 0 + if (cleanSession) connectFlags = connectFlags or 0x02 + if (username != null) connectFlags = connectFlags or 0x80 + if (password != null) connectFlags = connectFlags or 0x40 + body.write(connectFlags) + + // Keep alive: big-endian uint16. + val keepAlive = keepAliveSeconds and 0xFFFF + body.write((keepAlive ushr 8) and 0xFF) + body.write(keepAlive and 0xFF) + + // Payload. + writeMqttString(body, clientId) + if (username != null) writeMqttString(body, username) + if (password != null) writeMqttString(body, password) + + val payload = body.toByteArray() + val header = ByteArrayOutputStream() + header.write(0x10) // CONNECT fixed header type + encodeRemainingLength(payload.size, header) + + return header.toByteArray() + payload + } + + /** + * Encodes an MQTT PUBLISH packet. + * + * @throws IllegalArgumentException if the topic is empty, the QoS is not 0 or 1, + * or (for QoS 1) the packet id is outside 1..65535. + */ + fun encodePublish( + topic: String, + payload: ByteArray, + qos: Int = 1, + retain: Boolean = false, + dup: Boolean = false, + packetId: Int = 1, + ): ByteArray { + require(topic.isNotEmpty()) { "Topic must not be empty" } + require(qos in 0..1) { "QoS must be 0 or 1, got: $qos" } + if (qos == 1) { + require(packetId in 1..65_535) { + "Packet id must be in 1..65535 for QoS 1, got: $packetId" + } + } + + val body = ByteArrayOutputStream() + writeMqttString(body, topic) + if (qos == 1) { + body.write((packetId ushr 8) and 0xFF) + body.write(packetId and 0xFF) + } + body.write(payload) + + val fixedHeader: Int = + 0x30 or + (if (dup && qos > 0) 0x08 else 0) or + ((qos and 0x03) shl 1) or + (if (retain) 0x01 else 0) + + val header = ByteArrayOutputStream() + header.write(fixedHeader) + encodeRemainingLength(body.size(), header) + + return header.toByteArray() + body.toByteArray() + } + + /** + * Encodes an MQTT PUBACK packet (4 bytes). + * + * @throws IllegalArgumentException if [packetId] is outside 1..65535. + */ + fun encodePubAck(packetId: Int): ByteArray { + require(packetId in 1..65_535) { + "Packet id must be in 1..65535, got: $packetId" + } + return byteArrayOf( + 0x40, + 0x02, + ((packetId ushr 8) and 0xFF).toByte(), + (packetId and 0xFF).toByte(), + ) + } + + /** Encodes an MQTT PINGREQ packet. */ + fun encodePingReq(): ByteArray = byteArrayOf(0xC0.toByte(), 0x00) + + /** Encodes an MQTT DISCONNECT packet. */ + fun encodeDisconnect(): ByteArray = byteArrayOf(0xE0.toByte(), 0x00) + + // ------------------------------------------------------------------ + // Packet decoders + // ------------------------------------------------------------------ + + /** + * Reads a complete MQTT packet from [input]: the fixed header byte, the + * variable-length remaining length, and exactly that many body bytes. + * + * @throws EOFException if the stream ends before the packet is complete. + */ + fun readPacket(input: InputStream): MqttPacket { + val firstByte = input.read() + if (firstByte < 0) { + throw EOFException("Premature EOF while reading MQTT fixed header") + } + val packetType = (firstByte ushr 4) and 0x0F + val flags = firstByte and 0x0F + val remainingLength = decodeRemainingLength(input) + + val body = ByteArray(remainingLength) + var offset = 0 + while (offset < remainingLength) { + val read = input.read(body, offset, remainingLength - offset) + if (read < 0) { + throw EOFException( + "Premature EOF while reading MQTT packet body " + + "(expected $remainingLength bytes, got $offset)" + ) + } + offset += read + } + return MqttPacket(packetType, flags, body) + } + + /** + * Decodes a CONNACK packet. + * + * @throws IOException if the packet is not a CONNACK or the body is not 2 bytes. + */ + fun decodeConnAck(packet: MqttPacket): ConnAck { + if (packet.packetType != PACKET_CONNACK) { + throw IOException( + "Expected CONNACK packet (type $PACKET_CONNACK), got type ${packet.packetType}" + ) + } + if (packet.body.size != 2) { + throw IOException( + "Malformed CONNACK: body must be 2 bytes, got ${packet.body.size}" + ) + } + val sessionPresent = (packet.body[0].toInt() and 0x01) != 0 + val returnCode = packet.body[1].toInt() and 0xFF + return ConnAck(sessionPresent, returnCode) + } + + /** + * Extracts the unsigned 16-bit packet id from a PUBACK packet. + * + * @throws IOException if the packet is not a PUBACK or the body is not 2 bytes. + */ + fun decodePubAckPacketId(packet: MqttPacket): Int { + if (packet.packetType != PACKET_PUBACK) { + throw IOException( + "Expected PUBACK packet (type $PACKET_PUBACK), got type ${packet.packetType}" + ) + } + if (packet.body.size != 2) { + throw IOException( + "Malformed PUBACK: body must be 2 bytes, got ${packet.body.size}" + ) + } + val high = packet.body[0].toInt() and 0xFF + val low = packet.body[1].toInt() and 0xFF + return (high shl 8) or low + } + + /** + * Returns a concise human-readable description of a CONNACK return code. + */ + fun connAckDescription(returnCode: Int): String = when (returnCode) { + 0 -> "Accepted" + 1 -> "Unacceptable protocol version" + 2 -> "Identifier rejected" + 3 -> "Server unavailable" + 4 -> "Bad username or password" + 5 -> "Not authorized" + else -> "Unknown error ($returnCode)" + } +} diff --git a/app/src/main/java/com/pulseloop/mqtt/MqttWebSocket.kt b/app/src/main/java/com/pulseloop/mqtt/MqttWebSocket.kt new file mode 100644 index 00000000..85ba16d6 --- /dev/null +++ b/app/src/main/java/com/pulseloop/mqtt/MqttWebSocket.kt @@ -0,0 +1,418 @@ +package com.pulseloop.mqtt + +import java.io.ByteArrayOutputStream +import java.io.EOFException +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream +import java.security.MessageDigest +import java.security.SecureRandom + +/** + * Pure-Kotlin RFC 6455 WebSocket client framing (`ws://` / `wss://`) for MQTT 3.1.1. + * + * Performs the HTTP/1.1 `Upgrade: websocket` handshake (`Sec-WebSocket-Protocol: mqtt`) + * on an already-connected [InputStream]/[OutputStream] pair (plain or TLS [SSLSocket]) + * and exposes masked binary frame streams compatible with [MqttProtocol]. + */ +internal object MqttWebSocket { + + private const val WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + private const val MAX_HEADER_LINES = 128 + private const val MAX_LINE_BYTES = 8192 + private const val MAX_FRAME_PAYLOAD_BYTES = 16 * 1024 * 1024 // 16 MiB safety cap + + private const val OPCODE_CONTINUATION = 0x0 + private const val OPCODE_TEXT = 0x1 + private const val OPCODE_BINARY = 0x2 + private const val OPCODE_CLOSE = 0x8 + private const val OPCODE_PING = 0x9 + private const val OPCODE_PONG = 0xA + + /** + * Normalizes a WebSocket endpoint path to always start with `/` (defaulting to `/mqtt`). + */ + fun normalizePath(path: String): String { + val trimmed = path.trim() + if (trimmed.isEmpty()) return "/mqtt" + return if (trimmed.startsWith("/")) trimmed else "/$trimmed" + } + + /** + * Performs the RFC 6455 HTTP/1.1 Upgrade handshake and returns wrapped `(input, output)` streams. + */ + fun upgrade( + host: String, + port: Int, + useTls: Boolean, + path: String, + rawInput: InputStream, + rawOutput: OutputStream, + random: SecureRandom = SecureRandom(), + ): Pair { + val normalizedPath = normalizePath(path) + val hostHeader = if ((useTls && port == 443) || (!useTls && port == 80)) { + host + } else { + "$host:$port" + } + + val nonce = ByteArray(16).also { random.nextBytes(it) } + val wsKey = base64Encode(nonce) + val expectedAccept = computeAcceptKey(wsKey) + + val request = buildString { + append("GET ").append(normalizedPath).append(" HTTP/1.1\r\n") + append("Host: ").append(hostHeader).append("\r\n") + append("Upgrade: websocket\r\n") + append("Connection: Upgrade\r\n") + append("Sec-WebSocket-Key: ").append(wsKey).append("\r\n") + append("Sec-WebSocket-Version: 13\r\n") + append("Sec-WebSocket-Protocol: mqtt\r\n") + append("\r\n") + } + rawOutput.write(request.toByteArray(Charsets.US_ASCII)) + rawOutput.flush() + + val statusLine = readHttpLine(rawInput) + ?: throw MqttException("WebSocket handshake failed: unexpected EOF reading HTTP status") + if (!statusLine.startsWith("HTTP/1.1 101") && !statusLine.startsWith("HTTP/1.0 101")) { + throw MqttException("WebSocket handshake rejected: $statusLine") + } + + val headers = LinkedHashMap() + var lineCount = 0 + while (true) { + val line = readHttpLine(rawInput) + ?: throw MqttException("WebSocket handshake failed: unexpected EOF reading headers") + if (line.isEmpty()) break + if (++lineCount > MAX_HEADER_LINES) { + throw MqttException("WebSocket handshake failed: too many HTTP response headers") + } + val colon = line.indexOf(':') + if (colon > 0) { + val name = line.substring(0, colon).trim().lowercase() + val value = line.substring(colon + 1).trim() + headers[name] = value + } + } + + val upgradeHeader = headers["upgrade"]?.lowercase() + if (upgradeHeader != "websocket") { + throw MqttException("WebSocket handshake failed: missing/invalid Upgrade header ($upgradeHeader)") + } + + val connectionTokens = headers["connection"] + ?.lowercase() + ?.split(',') + ?.map { it.trim() } + .orEmpty() + if ("upgrade" !in connectionTokens) { + throw MqttException("WebSocket handshake failed: missing Connection: Upgrade header") + } + + val acceptHeader = headers["sec-websocket-accept"] + if (acceptHeader != expectedAccept) { + throw MqttException("WebSocket handshake failed: invalid Sec-WebSocket-Accept") + } + + val subprotocol = headers["sec-websocket-protocol"]?.trim()?.lowercase() + if (subprotocol != null && subprotocol != "mqtt") { + throw MqttException("WebSocket handshake failed: unsupported subprotocol '$subprotocol'") + } + + val writeLock = Any() + val wsInput = WebSocketInputStream(rawInput, rawOutput, random, writeLock) + val wsOutput = WebSocketOutputStream(rawOutput, random, writeLock) + return wsInput to wsOutput + } + + internal fun computeAcceptKey(clientKey: String): String { + val digest = MessageDigest.getInstance("SHA-1") + .digest((clientKey + WS_GUID).toByteArray(Charsets.US_ASCII)) + return base64Encode(digest) + } + + private fun readHttpLine(input: InputStream): String? { + val buf = ByteArrayOutputStream(128) + while (true) { + val b = input.read() + if (b == -1) { + return if (buf.size() == 0) null else buf.toString(Charsets.US_ASCII.name()) + } + if (b == '\n'.code) { + val bytes = buf.toByteArray() + val len = if (bytes.isNotEmpty() && bytes[bytes.size - 1] == '\r'.code.toByte()) { + bytes.size - 1 + } else { + bytes.size + } + return String(bytes, 0, len, Charsets.US_ASCII) + } + if (buf.size() >= MAX_LINE_BYTES) { + throw MqttException("WebSocket HTTP header line exceeded $MAX_LINE_BYTES bytes") + } + buf.write(b) + } + } + + private fun writeClientFrame( + rawOutput: OutputStream, + opcode: Int, + payload: ByteArray, + offset: Int, + length: Int, + random: SecureRandom, + writeLock: Any, + ) { + val mask = ByteArray(4).also { random.nextBytes(it) } + val header = ByteArrayOutputStream(14) + header.write(0x80 or (opcode and 0x0F)) // FIN = 1 + when { + length <= 125 -> header.write(0x80 or length) + length <= 0xFFFF -> { + header.write(0x80 or 126) + header.write((length ushr 8) and 0xFF) + header.write(length and 0xFF) + } + else -> { + header.write(0x80 or 127) + val len64 = length.toLong() + for (shift in 56 downTo 0 step 8) { + header.write(((len64 ushr shift) and 0xFFL).toInt()) + } + } + } + header.write(mask) + + val maskedPayload = ByteArray(length) + for (i in 0 until length) { + maskedPayload[i] = (payload[offset + i].toInt() xor mask[i and 3].toInt()).toByte() + } + + synchronized(writeLock) { + rawOutput.write(header.toByteArray()) + if (length > 0) { + rawOutput.write(maskedPayload) + } + rawOutput.flush() + } + } + + private class WebSocketInputStream( + private val rawInput: InputStream, + private val rawOutput: OutputStream, + private val random: SecureRandom, + private val writeLock: Any, + ) : InputStream() { + + private var currentFrame: ByteArray = ByteArray(0) + private var framePos: Int = 0 + private var closedByPeer: Boolean = false + + override fun read(): Int { + val one = ByteArray(1) + val n = read(one, 0, 1) + return if (n == -1) -1 else one[0].toInt() and 0xFF + } + + override fun read(b: ByteArray, off: Int, len: Int): Int { + if (len == 0) return 0 + while (framePos >= currentFrame.size) { + if (closedByPeer) return -1 + if (!readNextDataFrame()) return -1 + } + val available = currentFrame.size - framePos + val toCopy = minOf(len, available) + System.arraycopy(currentFrame, framePos, b, off, toCopy) + framePos += toCopy + return toCopy + } + + private fun readNextDataFrame(): Boolean { + while (true) { + val b0 = rawInput.read() + if (b0 == -1) { + closedByPeer = true + return false + } + val b1 = rawInput.read() + if (b1 == -1) throw EOFException("Unexpected EOF in WebSocket frame header") + + val opcode = b0 and 0x0F + val masked = (b1 and 0x80) != 0 + val len7 = b1 and 0x7F + + val payloadLenLong: Long = when (len7) { + 126 -> { + val hi = readByteOrEof() + val lo = readByteOrEof() + ((hi shl 8) or lo).toLong() + } + 127 -> { + var acc = 0L + repeat(8) { + acc = (acc shl 8) or readByteOrEof().toLong() + } + acc + } + else -> len7.toLong() + } + if (payloadLenLong < 0 || payloadLenLong > MAX_FRAME_PAYLOAD_BYTES) { + throw MqttException("WebSocket frame too large: $payloadLenLong bytes") + } + val payloadLen = payloadLenLong.toInt() + + val mask = if (masked) ByteArray(4).also { readFully(it) } else null + val payload = ByteArray(payloadLen) + if (payloadLen > 0) { + readFully(payload) + if (mask != null) { + for (i in 0 until payloadLen) { + payload[i] = (payload[i].toInt() xor mask[i and 3].toInt()).toByte() + } + } + } + + when (opcode) { + OPCODE_BINARY, OPCODE_CONTINUATION -> { + if (payloadLen > 0) { + currentFrame = payload + framePos = 0 + return true + } + // Empty binary/continuation frame: read next frame. + } + OPCODE_PING -> { + // RFC 6455 §5.5.3: reply with masked Pong containing identical application data. + runCatching { + writeClientFrame( + rawOutput = rawOutput, + opcode = OPCODE_PONG, + payload = payload, + offset = 0, + length = payload.size.coerceAtMost(125), + random = random, + writeLock = writeLock, + ) + } + } + OPCODE_PONG -> { + // Unsolicited or keepalive Pong; ignore. + } + OPCODE_CLOSE -> { + closedByPeer = true + runCatching { + writeClientFrame( + rawOutput = rawOutput, + opcode = OPCODE_CLOSE, + payload = ByteArray(0), + offset = 0, + length = 0, + random = random, + writeLock = writeLock, + ) + } + return false + } + OPCODE_TEXT -> throw MqttException("Unexpected WebSocket text frame (expected binary)") + else -> throw MqttException("Unsupported WebSocket opcode: 0x${opcode.toString(16)}") + } + } + } + + private fun readByteOrEof(): Int { + val b = rawInput.read() + if (b == -1) throw EOFException("Unexpected EOF reading WebSocket frame") + return b + } + + private fun readFully(dest: ByteArray) { + var off = 0 + while (off < dest.size) { + val n = rawInput.read(dest, off, dest.size - off) + if (n == -1) throw EOFException("Unexpected EOF reading WebSocket frame payload") + off += n + } + } + } + + private class WebSocketOutputStream( + private val rawOutput: OutputStream, + private val random: SecureRandom, + private val writeLock: Any, + ) : OutputStream() { + + private val buffer = ByteArrayOutputStream(256) + private var closed = false + + override fun write(b: Int) { + if (closed) throw IOException("WebSocket output stream is closed") + buffer.write(b) + } + + override fun write(b: ByteArray, off: Int, len: Int) { + if (closed) throw IOException("WebSocket output stream is closed") + buffer.write(b, off, len) + } + + override fun flush() { + if (buffer.size() > 0) { + val bytes = buffer.toByteArray() + buffer.reset() + writeClientFrame( + rawOutput = rawOutput, + opcode = OPCODE_BINARY, + payload = bytes, + offset = 0, + length = bytes.size, + random = random, + writeLock = writeLock, + ) + } else { + synchronized(writeLock) { rawOutput.flush() } + } + } + + override fun close() { + if (closed) return + closed = true + runCatching { flush() } + runCatching { + writeClientFrame( + rawOutput = rawOutput, + opcode = OPCODE_CLOSE, + payload = ByteArray(0), + offset = 0, + length = 0, + random = random, + writeLock = writeLock, + ) + } + } + } + + private const val BASE64_ALPHABET = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" + + internal fun base64Encode(data: ByteArray): String { + if (data.isEmpty()) return "" + val out = StringBuilder(((data.size + 2) / 3) * 4) + var i = 0 + while (i < data.size) { + val b0 = data[i].toInt() and 0xFF + val hasB1 = i + 1 < data.size + val hasB2 = i + 2 < data.size + val b1 = if (hasB1) data[i + 1].toInt() and 0xFF else 0 + val b2 = if (hasB2) data[i + 2].toInt() and 0xFF else 0 + val triple = (b0 shl 16) or (b1 shl 8) or b2 + + out.append(BASE64_ALPHABET[(triple ushr 18) and 0x3F]) + out.append(BASE64_ALPHABET[(triple ushr 12) and 0x3F]) + out.append(if (hasB1) BASE64_ALPHABET[(triple ushr 6) and 0x3F] else '=') + out.append(if (hasB2) BASE64_ALPHABET[triple and 0x3F] else '=') + i += 3 + } + return out.toString() + } +} diff --git a/app/src/main/java/com/pulseloop/service/EventPersistenceSubscriber.kt b/app/src/main/java/com/pulseloop/service/EventPersistenceSubscriber.kt index 581bb51e..15e18e8b 100644 --- a/app/src/main/java/com/pulseloop/service/EventPersistenceSubscriber.kt +++ b/app/src/main/java/com/pulseloop/service/EventPersistenceSubscriber.kt @@ -301,6 +301,7 @@ class EventPersistenceSubscriber( updatedAt = now, )) recordBatterySample(event.percent, now) + com.pulseloop.mqtt.MqttLivePublisher.publishLive(context) } is PulseEvent.LiveSampleGate -> { if (event.closed) closedGates.add(event.kind) else closedGates.remove(event.kind) @@ -312,6 +313,7 @@ class EventPersistenceSubscriber( event.timestamp.toEpochMilli(), awaitsRingsCopy(event.spot, event.ringWillLogIt), sourceRaw = event.sourceRaw, ) + com.pulseloop.mqtt.MqttLivePublisher.publishLive(context) } is PulseEvent.Spo2Result -> { if (!event.spot && MeasurementKind.SPO2 in closedGates) return @@ -320,6 +322,7 @@ class EventPersistenceSubscriber( event.timestamp.toEpochMilli(), awaitsRingsCopy(event.spot, event.ringWillLogIt), sourceRaw = event.sourceRaw, ) + com.pulseloop.mqtt.MqttLivePublisher.publishLive(context) } is PulseEvent.HistoryMeasurement -> { val at = event.timestamp.toEpochMilli() @@ -348,7 +351,10 @@ class EventPersistenceSubscriber( sourceRaw = "colmi", ) if (event.isHistory) upsertUnlessDeleted(measurement) - else db.measurementDao().insert(measurement) + else { + db.measurementDao().insert(measurement) + com.pulseloop.mqtt.MqttLivePublisher.publishLive(context) + } } is PulseEvent.HrvSample -> { db.measurementDao().insert(MeasurementEntity( @@ -357,6 +363,7 @@ class EventPersistenceSubscriber( timestamp = event.timestamp.toEpochMilli(), sourceRaw = "live", )) + com.pulseloop.mqtt.MqttLivePublisher.publishLive(context) } is PulseEvent.BloodPressureSample -> { db.withTransaction { @@ -390,6 +397,7 @@ class EventPersistenceSubscriber( db.measurementDao().insert(diastolic) } } + if (!event.isHistory) com.pulseloop.mqtt.MqttLivePublisher.publishLive(context) } is PulseEvent.BloodSugarSample -> { db.measurementDao().insert(MeasurementEntity( @@ -399,6 +407,7 @@ class EventPersistenceSubscriber( timestamp = event.timestamp.toEpochMilli(), sourceRaw = "live", )) + com.pulseloop.mqtt.MqttLivePublisher.publishLive(context) } is PulseEvent.TemperatureSample -> { val measurement = MeasurementEntity( @@ -413,13 +422,17 @@ class EventPersistenceSubscriber( sourceRaw = "live", ) if (event.isHistory) upsertUnlessDeleted(measurement) - else db.measurementDao().insert(measurement) + else { + db.measurementDao().insert(measurement) + com.pulseloop.mqtt.MqttLivePublisher.publishLive(context) + } } is PulseEvent.ActivityUpdate -> { // The ring always writes its own totals, in every mode. Under Path B the phone's // count lives in `phoneSteps`, so there is no ownership conflict to gate on — the // read path picks which column to show at display time. upsertActivityDaily(event.timestamp.toEpochMilli(), event.steps, event.calories, event.distanceMeters) + com.pulseloop.mqtt.MqttLivePublisher.publishLive(context) } is PulseEvent.ActivityBucket -> { // Per-slice ring history: upserted by timestamp + the day total recomputed as the @@ -462,6 +475,7 @@ class EventPersistenceSubscriber( // moment new measurements can have landed. Debounced 15 s + REPLACE in the // worker, so this is cheap to fire on every done. HealthConnectExportWorker.enqueue(context) + com.pulseloop.mqtt.MqttExportWorker.enqueue(context) } } is PulseEvent.HeartRateComplete -> {} diff --git a/app/src/main/java/com/pulseloop/service/LiveWorkoutManager.kt b/app/src/main/java/com/pulseloop/service/LiveWorkoutManager.kt index bde30987..ae68cae9 100644 --- a/app/src/main/java/com/pulseloop/service/LiveWorkoutManager.kt +++ b/app/src/main/java/com/pulseloop/service/LiveWorkoutManager.kt @@ -87,6 +87,7 @@ class LiveWorkoutManager( startTick(session) // Fresh state (not copy): clears any previous workout's finishedSessionId/paused flags. _state.value = WorkoutState(isRecording = true, activeSession = session) + com.pulseloop.mqtt.MqttLivePublisher.publishLive(context) return session } @@ -117,6 +118,7 @@ class LiveWorkoutManager( polling.pause() tickJob?.cancel() _state.value = _state.value.copy(isPaused = true, activeSession = updated) + com.pulseloop.mqtt.MqttLivePublisher.publishLive(context) refreshNotification() } @@ -140,6 +142,7 @@ class LiveWorkoutManager( polling.resume() startTick(updated) _state.value = _state.value.copy(isPaused = false, activeSession = updated) + com.pulseloop.mqtt.MqttLivePublisher.publishLive(context) refreshNotification() } @@ -166,6 +169,7 @@ class LiveWorkoutManager( coordinator.stopWorkoutHeartRate() finishForegroundService(summarized) _state.value = WorkoutState(finishedSessionId = summarized.id) + com.pulseloop.mqtt.MqttLivePublisher.onWorkoutFinished(context) uploadToStravaIfConnected() } @@ -197,6 +201,7 @@ class LiveWorkoutManager( )) coordinator.stopWorkoutHeartRate() _state.value = WorkoutState() + com.pulseloop.mqtt.MqttLivePublisher.onWorkoutFinished(context) } // MARK: - Tick loop @@ -222,7 +227,10 @@ class LiveWorkoutManager( hrZone = zone, ) - if (elapsed % 5 == 0) refreshNotification() + if (elapsed % 5 == 0) { + refreshNotification() + com.pulseloop.mqtt.MqttLivePublisher.publishLive(context) + } delay(1000) } } diff --git a/app/src/main/java/com/pulseloop/service/RingSyncWorker.kt b/app/src/main/java/com/pulseloop/service/RingSyncWorker.kt index 4e74a053..24c5b5bd 100644 --- a/app/src/main/java/com/pulseloop/service/RingSyncWorker.kt +++ b/app/src/main/java/com/pulseloop/service/RingSyncWorker.kt @@ -36,11 +36,20 @@ class RingSyncWorker( var isSyncing: Boolean = false internal set - /** Schedule periodic background ring sync. Call from MainActivity. */ - fun schedule(context: Context) { + /** Schedule periodic background ring sync. Call from MainActivity or settings. */ + fun schedule( + context: Context, + intervalMinutes: Int? = null, + policy: ExistingPeriodicWorkPolicy = ExistingPeriodicWorkPolicy.KEEP, + ) { + val interval = (intervalMinutes + ?: com.pulseloop.mqtt.MqttPrefsStore.get(context).current.effectiveSyncIntervalMinutes) + .coerceIn(15, 720) + .toLong() + val flex = (interval / 2L).coerceAtLeast(5L) val request = PeriodicWorkRequestBuilder( - 30, TimeUnit.MINUTES, // repeat interval - 15, TimeUnit.MINUTES, // flex interval + interval, TimeUnit.MINUTES, // repeat interval + flex, TimeUnit.MINUTES, // flex interval ) .setConstraints( Constraints.Builder() @@ -56,7 +65,7 @@ class RingSyncWorker( WorkManager.getInstance(context).enqueueUniquePeriodicWork( WORK_NAME, - ExistingPeriodicWorkPolicy.KEEP, + policy, request, ) } @@ -137,6 +146,7 @@ class RingSyncWorker( // data — run the (debounced) export pass. The foreground path triggers the same // worker via the SyncProgress("done") event, so both sync owners cover it. HealthConnectExportWorker.enqueue(applicationContext) + com.pulseloop.mqtt.MqttExportWorker.enqueue(applicationContext) Result.success() } diff --git a/app/src/main/java/com/pulseloop/service/ScheduledSpo2Worker.kt b/app/src/main/java/com/pulseloop/service/ScheduledSpo2Worker.kt index 200c78a7..e594f98a 100644 --- a/app/src/main/java/com/pulseloop/service/ScheduledSpo2Worker.kt +++ b/app/src/main/java/com/pulseloop/service/ScheduledSpo2Worker.kt @@ -260,6 +260,7 @@ class ScheduledSpo2Worker( Log.i(TAG, "Scheduled SpO2: ${value ?: "no reading"}") // The stop frame is only enqueued; let it reach the ring before the link closes. client.awaitOpsFlushed() + com.pulseloop.mqtt.MqttExportWorker.enqueue(applicationContext) return true } finally { withContext(NonCancellable) { diff --git a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt index 3411f6fa..db70b578 100644 --- a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt +++ b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt @@ -644,6 +644,9 @@ fun PulseLoopApp() { paddedComposable("settings/health-connect") { HealthConnectSettingsScreen(onBack = { navController.popBackStack() }) } + paddedComposable("settings/mqtt") { + com.pulseloop.ui.screens.MqttSettingsScreen(onBack = { navController.popBackStack() }) + } paddedComposable("settings/nutrition") { NutritionSettingsScreen( onBack = { navController.popBackStack() }, diff --git a/app/src/main/java/com/pulseloop/ui/screens/MqttSettingsScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/MqttSettingsScreen.kt new file mode 100644 index 00000000..fc7a3446 --- /dev/null +++ b/app/src/main/java/com/pulseloop/ui/screens/MqttSettingsScreen.kt @@ -0,0 +1,570 @@ +package com.pulseloop.ui.screens + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Visibility +import androidx.compose.material.icons.filled.VisibilityOff +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.FilterChip +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.text.input.VisualTransformation +import androidx.compose.ui.unit.dp +import androidx.work.ExistingPeriodicWorkPolicy +import com.pulseloop.R +import com.pulseloop.coach.local.LocalEndpoint +import com.pulseloop.data.PulseLoopDatabase +import com.pulseloop.data.entity.DeviceEntity +import com.pulseloop.mqtt.MqttDiscovery +import com.pulseloop.mqtt.MqttExporter +import com.pulseloop.mqtt.MqttLivePublisher +import com.pulseloop.mqtt.MqttPrefsStore +import com.pulseloop.mqtt.MqttTransport +import com.pulseloop.service.RingSyncWorker +import com.pulseloop.ui.components.DeviceHeroStatus +import com.pulseloop.ui.theme.PulseColors +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +private const val DEFAULT_PLAIN_PORT = "1883" +private const val DEFAULT_TLS_PORT = "8883" +private const val DEFAULT_WS_PLAIN_PORT = "80" +private const val DEFAULT_WS_TLS_PORT = "443" + +private fun defaultPortFor(transport: MqttTransport, useTls: Boolean): String = when (transport) { + MqttTransport.TCP -> if (useTls) DEFAULT_TLS_PORT else DEFAULT_PLAIN_PORT + MqttTransport.WEBSOCKET -> if (useTls) DEFAULT_WS_TLS_PORT else DEFAULT_WS_PLAIN_PORT +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +fun MqttSettingsScreen(onBack: () -> Unit) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + val store = remember { MqttPrefsStore.get(context) } + val initialPrefs = remember { store.current } + val prefs by store.state.collectAsState() + + var host by remember { mutableStateOf(initialPrefs.host) } + var portText by remember { mutableStateOf(initialPrefs.port.toString()) } + var useTls by remember { mutableStateOf(initialPrefs.useTls) } + var transport by remember { mutableStateOf(initialPrefs.transport) } + var wsPath by remember { mutableStateOf(initialPrefs.wsPath) } + var username by remember { mutableStateOf(initialPrefs.username) } + var password by remember { mutableStateOf("") } + var savedPassword by remember { mutableStateOf("") } + var passwordVisible by remember { mutableStateOf(false) } + var discoveryPrefix by remember { mutableStateOf(initialPrefs.discoveryPrefix) } + var baseTopic by remember { mutableStateOf(initialPrefs.baseTopic) } + var deviceNameOverride by remember { mutableStateOf(initialPrefs.deviceNameOverride) } + + var pairedDevice by remember { mutableStateOf(null) } + var busy by remember { mutableStateOf(false) } + var feedback by remember { mutableStateOf?>(null) } + var showRemoveDialog by remember { mutableStateOf(false) } + + LaunchedEffect(Unit) { + val loadedPassword = withContext(Dispatchers.IO) { store.getPassword() } + password = loadedPassword + savedPassword = loadedPassword + pairedDevice = withContext(Dispatchers.IO) { + PulseLoopDatabase.getInstance(context).deviceDao().currentReal() + } + } + + fun draftPort(): Int = (portText.toIntOrNull() ?: defaultPortFor(transport, useTls).toInt()).coerceIn(1, 65535) + + fun draftValid(): Boolean { + val parsedPort = portText.toIntOrNull() ?: return false + return host.trim().isNotEmpty() && parsedPort in 1..65535 + } + + fun saveDraftPrefs() { + val port = draftPort() + portText = port.toString() + val trimmedHost = host.trim() + val trimmedWsPath = wsPath.trim().ifEmpty { "/mqtt" } + wsPath = trimmedWsPath + val trimmedUser = username.trim() + val trimmedPrefix = discoveryPrefix.trim() + val trimmedBase = baseTopic.trim() + val trimmedDevice = deviceNameOverride.trim() + val connectionChanged = prefs.host != trimmedHost || + prefs.port != port || + prefs.useTls != useTls || + prefs.transport != transport || + prefs.wsPath != trimmedWsPath || + prefs.username != trimmedUser || + savedPassword != password + + store.update { + it.copy( + host = trimmedHost, + port = port, + useTls = useTls, + transport = transport, + wsPath = trimmedWsPath, + username = trimmedUser, + discoveryPrefix = trimmedPrefix, + baseTopic = trimmedBase, + deviceNameOverride = trimmedDevice, + ) + } + store.setPassword(password) + savedPassword = password + if (connectionChanged) MqttLivePublisher.resetPool() + } + + fun launchAction(saveFirst: Boolean = true, block: suspend () -> Pair) { + if (saveFirst) saveDraftPrefs() + scope.launch { + busy = true + feedback = null + feedback = try { + withContext(Dispatchers.IO) { block() } + } finally { + busy = false + } + } + } + + val draftPrefs = prefs.copy( + discoveryPrefix = discoveryPrefix, + baseTopic = baseTopic, + deviceNameOverride = deviceNameOverride, + ) + val topicPreview = pairedDevice?.let { device -> + MqttDiscovery.stateTopic( + draftPrefs.normalizedBaseTopic, + MqttDiscovery.resolveDeviceIdentity(device, draftPrefs), + ) + } ?: "${draftPrefs.normalizedBaseTopic}/${MqttDiscovery.sanitizeSlug(deviceNameOverride.ifBlank { "ring" })}/state" + + val hasDraftChanges = host.trim() != prefs.host || + draftPort() != prefs.port || + useTls != prefs.useTls || + transport != prefs.transport || + wsPath.trim().ifEmpty { "/mqtt" } != prefs.wsPath || + username.trim() != prefs.username || + password != savedPassword || + discoveryPrefix.trim() != prefs.discoveryPrefix || + baseTopic.trim() != prefs.baseTopic || + deviceNameOverride.trim() != prefs.deviceNameOverride + + SettingsSubScreen(title = stringResource(R.string.mqtt_title), onBack = onBack) { + Text( + text = stringResource(R.string.mqtt_subtitle), + style = MaterialTheme.typography.bodyMedium, + color = PulseColors.textSecondary, + ) + + Card(modifier = Modifier.fillMaxWidth()) { + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = stringResource(R.string.mqtt_enable_title), + style = MaterialTheme.typography.titleMedium, + ) + Switch( + checked = prefs.enabled, + onCheckedChange = { enable -> + if (enable && draftValid()) saveDraftPrefs() + store.update { it.copy(enabled = enable) } + if (!enable) MqttLivePublisher.resetPool() + }, + ) + } + val isReady = prefs.enabled && draftValid() + Text( + text = stringResource( + when { + isReady -> R.string.mqtt_status_enabled + prefs.enabled -> R.string.mqtt_status_incomplete + else -> R.string.mqtt_status_disabled + } + ), + style = MaterialTheme.typography.bodySmall, + color = when { + isReady -> PulseColors.success + prefs.enabled -> PulseColors.warning + else -> PulseColors.textSecondary + }, + ) + } + } + + Card(modifier = Modifier.fillMaxWidth()) { + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text( + text = stringResource(R.string.mqtt_broker_section), + style = MaterialTheme.typography.titleMedium, + ) + OutlinedTextField( + value = host, + onValueChange = { host = it }, + label = { Text(stringResource(R.string.mqtt_host_label)) }, + placeholder = { Text(stringResource(R.string.mqtt_host_placeholder)) }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + if (!useTls && host.trim().isNotBlank() && !LocalEndpoint.isPrivateHost(host.trim())) { + Text( + text = stringResource(R.string.mqtt_cleartext_warning), + style = MaterialTheme.typography.bodySmall, + color = PulseColors.warning, + ) + } + Text( + text = stringResource(R.string.mqtt_transport_label), + style = MaterialTheme.typography.bodyMedium, + ) + FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + MqttTransport.entries.forEach { option -> + FilterChip( + selected = transport == option, + onClick = { + if (transport != option) { + val oldDefault = defaultPortFor(transport, useTls) + val nextDefault = defaultPortFor(option, useTls) + transport = option + if (portText == oldDefault || portText.isBlank()) { + portText = nextDefault + } + } + }, + label = { + Text( + stringResource( + when (option) { + MqttTransport.TCP -> R.string.mqtt_transport_tcp + MqttTransport.WEBSOCKET -> R.string.mqtt_transport_ws + } + ) + ) + }, + ) + } + } + OutlinedTextField( + value = portText, + onValueChange = { portText = it.filter(Char::isDigit).take(5) }, + label = { Text(stringResource(R.string.mqtt_port_label)) }, + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + modifier = Modifier.fillMaxWidth(), + ) + if (transport == MqttTransport.WEBSOCKET) { + OutlinedTextField( + value = wsPath, + onValueChange = { wsPath = it }, + label = { Text(stringResource(R.string.mqtt_ws_path_label)) }, + placeholder = { Text(stringResource(R.string.mqtt_ws_path_placeholder)) }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + } + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Text(stringResource(R.string.mqtt_tls_label)) + Switch( + checked = useTls, + onCheckedChange = { next -> + val oldDefault = defaultPortFor(transport, useTls) + val nextDefault = defaultPortFor(transport, next) + useTls = next + if (portText == oldDefault || portText.isBlank()) { + portText = nextDefault + } + }, + ) + } + OutlinedTextField( + value = username, + onValueChange = { username = it }, + label = { Text(stringResource(R.string.mqtt_username_label)) }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + OutlinedTextField( + value = password, + onValueChange = { password = it }, + label = { Text(stringResource(R.string.mqtt_password_label)) }, + singleLine = true, + visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), + trailingIcon = { + IconButton(onClick = { passwordVisible = !passwordVisible }) { + Icon( + imageVector = if (passwordVisible) Icons.Filled.VisibilityOff else Icons.Filled.Visibility, + contentDescription = stringResource(R.string.action_toggle_visibility), + ) + } + }, + modifier = Modifier.fillMaxWidth(), + ) + OutlinedTextField( + value = discoveryPrefix, + onValueChange = { discoveryPrefix = it }, + label = { Text(stringResource(R.string.mqtt_discovery_prefix_label)) }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + OutlinedTextField( + value = baseTopic, + onValueChange = { baseTopic = it }, + label = { Text(stringResource(R.string.mqtt_base_topic_label)) }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + OutlinedTextField( + value = deviceNameOverride, + onValueChange = { deviceNameOverride = it }, + label = { Text(stringResource(R.string.mqtt_device_name_label)) }, + placeholder = { Text(stringResource(R.string.mqtt_device_name_placeholder)) }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + Text( + text = stringResource(R.string.mqtt_topic_preview, topicPreview), + style = MaterialTheme.typography.bodySmall, + color = PulseColors.textSecondary, + ) + Button( + onClick = { + saveDraftPrefs() + feedback = context.getString(R.string.mqtt_saved_feedback) to false + }, + enabled = !busy && hasDraftChanges, + modifier = Modifier.fillMaxWidth(), + ) { + Text(stringResource(R.string.mqtt_save_button)) + } + } + } + + Card(modifier = Modifier.fillMaxWidth()) { + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text( + text = stringResource(R.string.mqtt_sync_section), + style = MaterialTheme.typography.titleMedium, + ) + Text( + text = stringResource(R.string.mqtt_sync_interval_label), + style = MaterialTheme.typography.bodyMedium, + ) + FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + listOf(15, 30, 60, 120).forEach { mins -> + FilterChip( + selected = prefs.syncIntervalMinutes == mins, + onClick = { + store.update { it.copy(syncIntervalMinutes = mins) } + RingSyncWorker.schedule(context, mins, ExistingPeriodicWorkPolicy.UPDATE) + }, + label = { + Text( + stringResource( + when (mins) { + 15 -> R.string.mqtt_interval_15m + 30 -> R.string.mqtt_interval_30m + 60 -> R.string.mqtt_interval_1h + else -> R.string.mqtt_interval_2h + } + ) + ) + }, + ) + } + } + Text( + text = stringResource(R.string.mqtt_sync_interval_hint), + style = MaterialTheme.typography.bodySmall, + color = PulseColors.textSecondary, + ) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f).padding(end = 12.dp)) { + Text( + text = stringResource(R.string.mqtt_live_streaming_title), + style = MaterialTheme.typography.bodyMedium, + ) + Text( + text = stringResource(R.string.mqtt_live_streaming_desc), + style = MaterialTheme.typography.bodySmall, + color = PulseColors.textSecondary, + ) + } + Switch( + checked = prefs.liveStreamingEnabled, + onCheckedChange = { next -> + store.update { it.copy(liveStreamingEnabled = next) } + if (!next) MqttLivePublisher.resetPool() + }, + ) + } + } + } + + Card(modifier = Modifier.fillMaxWidth()) { + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text( + text = stringResource(R.string.mqtt_actions_section), + style = MaterialTheme.typography.titleMedium, + ) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Button( + onClick = { + launchAction { + when (val res = MqttExporter.testConnection(context)) { + is MqttExporter.Result.Success -> + context.getString(R.string.mqtt_test_success) to false + is MqttExporter.Result.Failure -> + res.reason to true + is MqttExporter.Result.Skipped -> + context.getString(R.string.mqtt_status_incomplete) to true + } + } + }, + enabled = !busy && draftValid(), + modifier = Modifier.weight(1f), + ) { + Text(stringResource(R.string.mqtt_test_connection)) + } + OutlinedButton( + onClick = { + launchAction { + when (val res = MqttExporter.publishNow(context)) { + is MqttExporter.Result.Success -> + context.getString(R.string.mqtt_publish_success, res.sensorCount) to false + is MqttExporter.Result.Failure -> + res.reason to true + is MqttExporter.Result.Skipped -> + context.getString(R.string.mqtt_status_incomplete) to true + } + } + }, + enabled = !busy && draftValid(), + modifier = Modifier.weight(1f), + ) { + Text(stringResource(R.string.mqtt_publish_now)) + } + } + OutlinedButton( + onClick = { showRemoveDialog = true }, + enabled = !busy && draftValid(), + modifier = Modifier.fillMaxWidth(), + ) { + Text(stringResource(R.string.mqtt_remove_ha)) + } + if (busy) { + Text( + text = stringResource(R.string.mqtt_testing_progress), + style = MaterialTheme.typography.bodySmall, + color = PulseColors.textSecondary, + ) + } + feedback?.let { (message, isError) -> + Text( + text = message, + style = MaterialTheme.typography.bodySmall, + color = if (isError) PulseColors.danger else PulseColors.success, + ) + } + val lastPublishAt = prefs.lastPublishAt + if (lastPublishAt != null) { + Text( + text = stringResource( + R.string.mqtt_last_publish, + DeviceHeroStatus.relativeShort(lastPublishAt, System.currentTimeMillis()), + prefs.lastPublishSummary ?: "", + ), + style = MaterialTheme.typography.bodySmall, + color = PulseColors.textSecondary, + ) + } + val lastError = prefs.lastError + if (lastError != null) { + Text( + text = stringResource(R.string.mqtt_last_error, lastError), + style = MaterialTheme.typography.bodySmall, + color = PulseColors.danger, + ) + } + } + } + + Spacer(Modifier.height(16.dp)) + } + + if (showRemoveDialog) { + AlertDialog( + onDismissRequest = { showRemoveDialog = false }, + title = { Text(stringResource(R.string.mqtt_remove_confirm_title)) }, + text = { Text(stringResource(R.string.mqtt_remove_confirm_body)) }, + confirmButton = { + TextButton( + onClick = { + showRemoveDialog = false + launchAction(saveFirst = false) { + when (val res = MqttExporter.clearRetainedTopics(context)) { + is MqttExporter.Result.Failure -> res.reason to true + else -> context.getString(R.string.mqtt_removed_feedback) to false + } + } + }, + ) { + Text(stringResource(R.string.mqtt_remove_confirm_action)) + } + }, + dismissButton = { + TextButton(onClick = { showRemoveDialog = false }) { + Text(stringResource(R.string.mqtt_cancel)) + } + }, + ) + } +} diff --git a/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt index de3deeb5..90ac18ce 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt @@ -311,6 +311,9 @@ fun SettingsScreen( add(SettingsRowItem(Icons.Filled.Sync, PulseColors.success, "Health Connect") { navigate("settings/health-connect") }) + add(SettingsRowItem(Icons.Filled.Hub, PulseColors.info, stringResource(R.string.mqtt_row_title)) { + navigate("settings/mqtt") + }) add(SettingsRowItem(Icons.Filled.Info, PulseColors.textMuted, stringResource(R.string.settings_about_app)) { navigate("settings/about") }) diff --git a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt index 1b268ccb..f1921b99 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt @@ -104,7 +104,7 @@ import kotlinx.coroutines.launch /** Pushed-screen chrome shared by every settings detail screen: back arrow + title + scroll column. */ @OptIn(ExperimentalMaterial3Api::class) @Composable -private fun SettingsSubScreen( +internal fun SettingsSubScreen( title: String, onBack: () -> Unit, bottomOverlay: (@Composable BoxScope.() -> Unit)? = null, diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index c3347eab..b587c08a 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1303,4 +1303,55 @@ Чтобы выключить кольцо, PulseLoop должен быть к нему подключён. Дождитесь подключения и попробуйте снова. Не удаётся выключить это кольцо Это кольцо нельзя выключить из PulseLoop. Перезапустите его через родное приложение или на зарядке. + + MQTT + MQTT + Публикация показателей кольца, сна, тренировок и топиков автообнаружения в брокер MQTT. + Включить экспорт MQTT + Активно + Выключено + Укажите адрес брокера + Подключение к брокеру + Хост брокера + 192.168.1.50 + Порт + Транспорт + TCP + WebSocket (WS / WSS) + Путь WebSocket + /mqtt + Использовать TLS (MQTTS / WSS) + Нешифрованный MQTT на внешний хост передаёт данные и пароль в открытом виде. Включите TLS для удалённых брокеров. + Имя пользователя (необязательно) + Пароль (необязательно) + Префикс автообнаружения + Базовый топик + Имя устройства (необязательно) + Авто по кольцу + Сохранить настройки + Настройки MQTT сохранены + Синхронизация и прямой эфир + Фоновая синхронизация кольца + 15 мин + 30 мин + 1 ч + 2 ч + Задаёт частоту фоновой синхронизации кольца и отправки обновлений в MQTT. + Потоковая передача тренировок + Отправка пульса и метрик тренировки каждые ~5 с во время активных тренировок и разовых замеров. + Действия и статус + Проверить соединение + Опубликовать сейчас + Подключение… + Соединение с брокером успешно + Опубликовано датчиков в брокер MQTT: %1$d + Топик состояния: %1$s + Последняя отправка %1$s — %2$s + Последняя ошибка: %1$s + Очистить сохранённые топики + Очистить сохранённые топики MQTT? + Будут очищены сохранённые конфигурации автообнаружения и топик состояния MQTT на брокере для привязанного кольца. + Очистить + Отмена + Сохранённые топики MQTT очищены diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 9f2b8b6b..0c52ec06 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1259,4 +1259,55 @@ PulseLoop needs to be connected to your ring to turn it off. Wait for it to connect and try again. Can\'t turn this ring off This ring can\'t be turned off from PulseLoop. Restart it from its own app or its charger. + + MQTT + MQTT + Publish ring vitals, sleep, workouts, and discovery topics to your MQTT broker. + Enable MQTT export + Active + Disabled + Broker host required + Broker Connection + Broker Host + 192.168.1.50 + Port + Transport + TCP + WebSocket (WS / WSS) + WebSocket Path + /mqtt + Use TLS (MQTTS / WSS) + Unencrypted MQTT to a non-local host sends traffic and credentials in plaintext. Enable TLS for remote brokers. + Username (optional) + Password (optional) + Discovery Prefix + Base Topic + Device Name Override (optional) + Auto from ring + Save Settings + MQTT settings saved + Sync & Live Streaming + Background Ring Sync + 15 min + 30 min + 1 hr + 2 hr + Controls how often the ring syncs in the background and publishes MQTT updates. + Live workout streaming + Stream heart rate and workout metrics every ~5s during active workouts and spot measurements. + Actions & Status + Test Connection + Publish Now + Connecting… + Broker handshake succeeded + Published %1$d sensors to MQTT broker + State topic: %1$s + Last publish %1$s — %2$s + Last error: %1$s + Clear Retained Topics + Clear retained MQTT topics? + This clears retained MQTT discovery configs and state topics on the broker for your paired ring. + Clear + Cancel + Cleared retained MQTT topics diff --git a/app/src/test/java/com/pulseloop/mqtt/LiveMosquittoBrokerTest.kt b/app/src/test/java/com/pulseloop/mqtt/LiveMosquittoBrokerTest.kt new file mode 100644 index 00000000..6f78ba30 --- /dev/null +++ b/app/src/test/java/com/pulseloop/mqtt/LiveMosquittoBrokerTest.kt @@ -0,0 +1,246 @@ +package com.pulseloop.mqtt + +import com.pulseloop.data.entity.DeviceEntity +import com.pulseloop.ring.MeasurementKind +import com.pulseloop.ring.RingDeviceType +import com.pulseloop.ring.WearableCapability +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Assume.assumeTrue +import org.junit.Test + +/** + * Integration tests exercised against a real local Mosquitto broker (OrbStack / localhost:1883). + * + * Skipped during offline CI runs unless either `-Dpulseloop.test.liveBroker=true` or + * `PULSELOOP_LIVE_BROKER=true` is supplied. + */ +class LiveMosquittoBrokerTest { + + private fun isLiveEnabled(): Boolean = + System.getProperty("pulseloop.test.liveBroker") == "true" || + System.getenv("PULSELOOP_LIVE_BROKER") == "true" + + private fun phase(): String = System.getenv("PULSELOOP_LIVE_PHASE") ?: "all" + + private fun sampleRing() = DeviceEntity( + id = "live-ring-01", + name = "Colmi R11", + advertisedName = "R11_A1B2", + peripheralIdentifier = "AA:BB:CC:DD:A1:B2", + bleAddressHint = null, + batteryPercent = 87, + stateRaw = "CONNECTED", + deviceTypeRaw = RingDeviceType.COLMI_R02.name, + wearableModelID = "colmi-r11", + capabilitiesRaw = listOf( + WearableCapability.BATTERY, + WearableCapability.HEART_RATE, + WearableCapability.SPO2, + WearableCapability.STEPS, + WearableCapability.SLEEP, + WearableCapability.STRESS, + WearableCapability.HRV, + WearableCapability.TEMPERATURE, + ).joinToString(",") { it.key }, + lastConnectedAt = 1_763_190_000_000L, + lastDisconnectedAt = null, + lastSyncAt = 1_763_190_100_000L, + lastFullSyncAt = 1_763_190_100_000L, + firmwareVersion = "2.1.4", + createdAt = 1_763_190_000_000L, + updatedAt = 1_763_190_100_000L, + ) + + private fun anonConfig(clientId: String = "pl_live_test") = MqttEndpointConfig( + host = System.getenv("PULSELOOP_MQTT_HOST") ?: "127.0.0.1", + port = System.getenv("PULSELOOP_MQTT_PORT")?.toIntOrNull() ?: 1883, + useTls = false, + username = "", + password = "", + clientId = clientId, + ) + + @Test + fun liveBroker_handshakePublishAndSessionPool() = runBlocking { + assumeTrue("Live Mosquitto test skipped (set PULSELOOP_LIVE_BROKER=true)", isLiveEnabled()) + val mode = phase() + assumeTrue("Auth-only phase", mode == "all" || mode == "publish" || mode == "remove") + + val ring = sampleRing() + val prefs = MqttPrefs( + enabled = true, + host = "127.0.0.1", + port = 1883, + discoveryPrefix = "homeassistant", + baseTopic = "pulseloop", + ) + val identity = MqttDiscovery.resolveDeviceIdentity(ring, prefs) + + if (mode == "all" || mode == "publish") { + // 1. Handshake & PINGREQ/PINGRESP test + MqttClient.testConnection(anonConfig("pl_ping_test")) + + // 2. Full HA discovery + state publish + val initialSnapshot = MqttDataSnapshot( + batteryPercent = 87, + heartRateBpm = 72, + spo2Percent = 98, + hrvMs = 46.5, + stressScore = 31, + temperatureCelsius = 36.4, + steps = 4320, + caloriesKcal = 1840.0, + distanceMeters = 3150, + activeMinutes = 42, + sleepTotalMinutes = 435, + sleepScore = 84, + sleepDeepMinutes = 110, + sleepLightMinutes = 290, + sleepAwakeMinutes = 35, + workoutActive = false, + lastSyncIso = "2026-11-15T07:50:00Z", + availableKinds = setOf(MeasurementKind.STRESS.name), + ) + val (discoveryMsgs, keys) = MqttDiscovery.buildMqttMessages( + device = ring, + snapshot = initialSnapshot, + prefs = prefs, + forceDiscovery = true, + ) + assertTrue(keys.size >= 15) + MqttClient.publishAll(anonConfig("pl_pub_test"), discoveryMsgs) + + // 3. Consecutive pooled live workout updates over a single warm TCP session + val pool = MqttSessionPool() + try { + val sensors = MqttDiscovery.sensorsFor(ring, initialSnapshot) + assertTrue(sensors.any { it.key == "stress" }) + val updatedPrefs = prefs.copy( + discoveredSensorKeys = keys, + lastDiscoveredDeviceSlug = identity.slug, + ) + val liveTick1 = initialSnapshot.copy( + heartRateBpm = 142, + workoutActive = true, + workoutType = "Indoor Cross Trainer", + workoutDurationSeconds = 120, + ) + val liveTick2 = liveTick1.copy( + heartRateBpm = 148, + workoutDurationSeconds = 125, + ) + val (msgs1, _) = MqttDiscovery.buildMqttMessages(ring, liveTick1, updatedPrefs) + val (msgs2, _) = MqttDiscovery.buildMqttMessages(ring, liveTick2, updatedPrefs) + assertEquals(1, msgs1.size) + assertEquals(1, msgs2.size) + + val poolCfg = anonConfig("pl_pool_live") + pool.publish(poolCfg, msgs1) + pool.publish(poolCfg, msgs2) + } finally { + pool.close() + } + } + + if (mode == "all" || mode == "remove") { + val allKeys = MqttDiscovery.sensorsFor( + ring, + MqttDataSnapshot(availableKinds = setOf(MeasurementKind.STRESS.name)), + ).map { it.key } + val removalMsgs = MqttDiscovery.buildRemovalMessages( + prefs.normalizedDiscoveryPrefix, + identity.uniquePrefix, + allKeys, + ) + MqttMessage( + topic = MqttDiscovery.stateTopic(prefs.normalizedBaseTopic, identity), + payload = ByteArray(0), + qos = 1, + retain = true, + ) + MqttClient.publishAll(anonConfig("pl_remove_test"), removalMsgs) + } + } + + @Test + fun liveBroker_usernamePasswordAuthAcceptedAndBadPasswordRejected() = runBlocking { + assumeTrue("Live Mosquitto auth test skipped", isLiveEnabled() && phase() == "auth") + + val validCfg = MqttEndpointConfig( + host = "127.0.0.1", + port = 1883, + useTls = false, + username = "pulseloop", + password = "secret_password_123", + clientId = "pl_auth_ok", + ) + MqttClient.testConnection(validCfg) + MqttClient.publishAll( + validCfg, + listOf(MqttMessage("pulseloop/auth_test", """{"ok":true}""", qos = 1, retain = false)), + ) + + val badCfg = validCfg.copy(password = "wrong_password", clientId = "pl_auth_bad") + try { + MqttClient.testConnection(badCfg) + fail("Expected MqttException when Mosquitto rejects wrong password") + } catch (e: MqttException) { + assertTrue( + "Expected CONNACK rejection message, got: ${e.message}", + e.message?.contains("rejected", ignoreCase = true) == true || + e.message?.contains("username or password", ignoreCase = true) == true || + e.message?.contains("authorized", ignoreCase = true) == true, + ) + } + } + + @Test + fun liveBroker_webSocketHandshakeAndPublish() = runBlocking { + assumeTrue( + "Live Mosquitto WS test skipped", + isLiveEnabled() && (phase() == "ws" || phase() == "all"), + ) + + val wsCfg = MqttEndpointConfig( + host = System.getenv("PULSELOOP_MQTT_HOST") ?: "127.0.0.1", + port = System.getenv("PULSELOOP_MQTT_WS_PORT")?.toIntOrNull() ?: 9001, + useTls = false, + transport = MqttTransport.WEBSOCKET, + wsPath = "/mqtt", + username = "", + password = "", + clientId = "pl_ws_live", + ) + MqttClient.testConnection(wsCfg) + + val pool = MqttSessionPool() + try { + pool.publish( + wsCfg, + listOf( + MqttMessage( + topic = "pulseloop/ws_test/state", + payload = """{"heart_rate":75,"transport":"ws"}""", + qos = 1, + retain = true, + ) + ), + ) + pool.publish( + wsCfg, + listOf( + MqttMessage( + topic = "pulseloop/ws_test/state", + payload = """{"heart_rate":78,"transport":"ws"}""", + qos = 1, + retain = true, + ) + ), + ) + } finally { + pool.close() + } + } +} diff --git a/app/src/test/java/com/pulseloop/mqtt/MqttDiscoveryTest.kt b/app/src/test/java/com/pulseloop/mqtt/MqttDiscoveryTest.kt new file mode 100644 index 00000000..3ff6aaee --- /dev/null +++ b/app/src/test/java/com/pulseloop/mqtt/MqttDiscoveryTest.kt @@ -0,0 +1,367 @@ +package com.pulseloop.mqtt + +import com.pulseloop.data.entity.DeviceEntity +import com.pulseloop.ring.MeasurementKind +import com.pulseloop.ring.RingDeviceType +import com.pulseloop.ring.WearableCapability +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.boolean +import kotlinx.serialization.json.int +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class MqttDiscoveryTest { + + private val colmiCaps = listOf( + WearableCapability.BATTERY, + WearableCapability.HEART_RATE, + WearableCapability.SPO2, + WearableCapability.STEPS, + WearableCapability.SLEEP, + ) + + private fun testRing( + mac: String = "AA:BB:CC:DD:EE:FF", + name: String = "Colmi R02", + type: RingDeviceType = RingDeviceType.COLMI_R02, + caps: List = colmiCaps, + ) = DeviceEntity( + id = "device-${mac.lowercase().replace(":", "")}", + name = name, + advertisedName = null, + peripheralIdentifier = mac, + bleAddressHint = null, + batteryPercent = 82, + stateRaw = "CONNECTED", + deviceTypeRaw = type.name, + wearableModelID = null, + capabilitiesRaw = caps.joinToString(",") { it.key }, + lastConnectedAt = 1_700_000_000_000L, + lastDisconnectedAt = null, + lastSyncAt = 1_700_000_100_000L, + lastFullSyncAt = null, + firmwareVersion = "1.0.0", + createdAt = 1_700_000_000_000L, + updatedAt = 1_700_000_100_000L, + ) + + private fun keys(device: DeviceEntity, snapshot: MqttDataSnapshot = MqttDataSnapshot()): Set = + MqttDiscovery.sensorsFor(device, snapshot).map { it.key }.toSet() + + // ------------------------------------------------------------------ + // 1. Capability gating on a Colmi R02-like ring + // ------------------------------------------------------------------ + + @Test + fun `colmi ring exposes supported sensors`() { + val device = testRing() + val sensorKeys = keys(device) + + assertTrue("battery" in sensorKeys) + assertTrue("heart_rate" in sensorKeys) + assertTrue("spo2" in sensorKeys) + + assertTrue("steps" in sensorKeys) + assertTrue("calories" in sensorKeys) + assertTrue("distance" in sensorKeys) + assertTrue("active_minutes" in sensorKeys) + + assertTrue("sleep_duration" in sensorKeys) + assertTrue("sleep_score" in sensorKeys) + assertTrue("sleep_deep" in sensorKeys) + assertTrue("sleep_light" in sensorKeys) + assertTrue("sleep_awake" in sensorKeys) + + assertTrue("workout_active" in sensorKeys) + assertTrue("workout_type" in sensorKeys) + assertTrue("workout_duration" in sensorKeys) + + assertTrue("last_sync" in sensorKeys) + } + + @Test + fun `colmi ring omits unsupported sensors`() { + val device = testRing() + val sensorKeys = keys(device) + + val unsupported = setOf( + "resting_heart_rate", + "temperature", + "hrv", + "stress", + "sleep_rem", + "blood_pressure_systolic", + "blood_pressure_diastolic", + "blood_sugar", + "respiratory_rate", + "vo2_max", + ) + unsupported.forEach { key -> + assertFalse("Expected '$key' to be absent", key in sensorKeys) + } + } + + // ------------------------------------------------------------------ + // 2. Derived stress #67 guard + // ------------------------------------------------------------------ + + @Test + fun `stress capability without stress measurement kind omits stress sensor`() { + val device = testRing(caps = colmiCaps + WearableCapability.STRESS) + val sensorKeys = keys(device, MqttDataSnapshot(availableKinds = emptySet())) + assertFalse("stress" in sensorKeys) + } + + @Test + fun `stress capability with stress measurement kind includes stress sensor`() { + val device = testRing(caps = colmiCaps + WearableCapability.STRESS) + val sensorKeys = keys( + device, + MqttDataSnapshot(availableKinds = setOf(MeasurementKind.STRESS.name), stressScore = 38), + ) + assertTrue("stress" in sensorKeys) + } + + // ------------------------------------------------------------------ + // 3. Respiratory rate guard + // ------------------------------------------------------------------ + + @Test + fun `ycbt ring without respiratory measurement kind omits respiratory_rate`() { + val device = testRing( + mac = "11:22:33:44:55:66", + name = "YCBT Ring", + type = RingDeviceType.YCBT, + ) + val sensorKeys = keys(device, MqttDataSnapshot(availableKinds = emptySet())) + assertFalse("respiratory_rate" in sensorKeys) + } + + @Test + fun `ycbt ring with respiratory measurement kind includes respiratory_rate`() { + val device = testRing( + mac = "11:22:33:44:55:66", + name = "YCBT Ring", + type = RingDeviceType.YCBT, + ) + val sensorKeys = keys( + device, + MqttDataSnapshot( + availableKinds = setOf(MeasurementKind.RESPIRATORY_RATE.name), + respiratoryRateBrpm = 15.2, + ), + ) + assertTrue("respiratory_rate" in sensorKeys) + } + + // ------------------------------------------------------------------ + // 4. Multi-device isolation + // ------------------------------------------------------------------ + + @Test + fun `two rings with same name produce distinct identities and topics`() { + val prefs = MqttPrefs(enabled = true, host = "192.168.1.50") + val ringA = testRing(mac = "AA:BB:CC:DD:EE:01", name = "Colmi R11") + val ringB = testRing(mac = "AA:BB:CC:DD:EE:02", name = "Colmi R11") + + val idA = MqttDiscovery.resolveDeviceIdentity(ringA, prefs) + val idB = MqttDiscovery.resolveDeviceIdentity(ringB, prefs) + + assertNotEquals(idA.uniquePrefix, idB.uniquePrefix) + assertNotEquals(idA.slug, idB.slug) + + val stateTopicA = MqttDiscovery.stateTopic(prefs.normalizedBaseTopic, idA) + val stateTopicB = MqttDiscovery.stateTopic(prefs.normalizedBaseTopic, idB) + assertNotEquals(stateTopicA, stateTopicB) + + val sample = MqttDiscovery.sensorsFor(ringA, MqttDataSnapshot()).first() + val configTopicA = MqttDiscovery.discoveryTopic(prefs.normalizedDiscoveryPrefix, sample, idA) + val configTopicB = MqttDiscovery.discoveryTopic(prefs.normalizedDiscoveryPrefix, sample, idB) + assertNotEquals(configTopicA, configTopicB) + } + + @Test + fun `deviceNameOverride changes displayName and slug but keeps uniquePrefix`() { + val ring = testRing(mac = "AA:BB:CC:DD:EE:03", name = "Colmi R11") + + val base = MqttDiscovery.resolveDeviceIdentity(ring, MqttPrefs()) + val overridden = MqttDiscovery.resolveDeviceIdentity( + ring, + MqttPrefs(deviceNameOverride = "Bedroom Ring"), + ) + + assertEquals(base.uniquePrefix, overridden.uniquePrefix) + assertNotEquals(base.slug, overridden.slug) + assertEquals("Bedroom Ring", overridden.displayName) + assertEquals("bedroom_ring", overridden.slug) + } + + // ------------------------------------------------------------------ + // 5. Discovery JSON & state JSON structure + // ------------------------------------------------------------------ + + @Test + fun `discovery payload has required HA fields`() { + val prefs = MqttPrefs(enabled = true, host = "192.168.1.50") + val ring = testRing() + val identity = MqttDiscovery.resolveDeviceIdentity(ring, prefs) + val sensors = MqttDiscovery.sensorsFor(ring, MqttDataSnapshot()) + + val discoveryMessages = MqttDiscovery.buildDiscoveryMessages(identity, sensors, prefs) + val batteryIdx = sensors.indexOfFirst { it.key == "battery" } + val batteryMsg = discoveryMessages[batteryIdx] + assertTrue(batteryMsg.retain) + assertEquals(1, batteryMsg.qos) + + val payload: JsonObject = Json.parseToJsonElement(batteryMsg.payload.decodeToString()).jsonObject + assertEquals("${identity.uniquePrefix}_battery", payload["unique_id"]?.jsonPrimitive?.content) + assertEquals("${identity.slug}_battery", payload["object_id"]?.jsonPrimitive?.content) + assertEquals( + MqttDiscovery.stateTopic(prefs.normalizedBaseTopic, identity), + payload["state_topic"]?.jsonPrimitive?.content, + ) + + val deviceJson = payload["device"]?.jsonObject + assertNotNull(deviceJson) + val identifiers = deviceJson?.get("identifiers")?.jsonArray + assertEquals(listOf(identity.uniquePrefix), identifiers?.map { it.jsonPrimitive.content }) + + val connections = deviceJson?.get("connections")?.jsonArray + val firstConnection = connections?.firstOrNull() as? JsonArray + assertNotNull(firstConnection) + assertEquals("mac", (firstConnection?.getOrNull(0) as? JsonPrimitive)?.content) + assertEquals("aa:bb:cc:dd:ee:ff", (firstConnection?.getOrNull(1) as? JsonPrimitive)?.content) + } + + @Test + fun `workout_active uses binary_sensor topic with ON-OFF payloads`() { + val prefs = MqttPrefs(enabled = true, host = "192.168.1.50") + val ring = testRing() + val identity = MqttDiscovery.resolveDeviceIdentity(ring, prefs) + val sensors = MqttDiscovery.sensorsFor(ring, MqttDataSnapshot()) + + val workout = sensors.first { it.key == "workout_active" } + val topic = MqttDiscovery.discoveryTopic(prefs.normalizedDiscoveryPrefix, workout, identity) + assertTrue(topic.startsWith("homeassistant/binary_sensor/${identity.uniquePrefix}/workout_active/config")) + + val messages = MqttDiscovery.buildDiscoveryMessages(identity, listOf(workout), prefs) + val payload = Json.parseToJsonElement(messages.single().payload.decodeToString()).jsonObject + assertEquals("ON", payload["payload_on"]?.jsonPrimitive?.content) + assertEquals("OFF", payload["payload_off"]?.jsonPrimitive?.content) + assertEquals("running", payload["device_class"]?.jsonPrimitive?.content) + } + + @Test + fun `state json serializes present fields and omits nulls`() { + val ring = testRing() + val snapshot = MqttDataSnapshot( + batteryPercent = 82, + heartRateBpm = 71, + steps = 5432, + workoutActive = false, + lastSyncIso = "2026-11-15T07:00:00Z", + ) + val sensors = MqttDiscovery.sensorsFor(ring, snapshot) + + val json = MqttDiscovery.buildStateJson(snapshot, sensors) + val obj = Json.parseToJsonElement(json).jsonObject + + assertEquals(82, obj["battery"]?.jsonPrimitive?.int) + assertEquals(71, obj["heart_rate"]?.jsonPrimitive?.int) + assertEquals(5432, obj["steps"]?.jsonPrimitive?.int) + assertEquals(false, obj["workout_active"]?.jsonPrimitive?.boolean) + assertEquals("2026-11-15T07:00:00Z", obj["last_sync"]?.jsonPrimitive?.content) + + // Null fields must be omitted entirely + assertFalse(obj.containsKey("spo2")) + assertFalse(obj.containsKey("temperature")) + assertFalse(obj.containsKey("workout_type")) + assertFalse(obj.containsKey("workout_duration")) + } + + // ------------------------------------------------------------------ + // 6. Incremental discovery & stale sensor cleanup + // ------------------------------------------------------------------ + + @Test + fun `incremental build with matching discovered keys and slug emits only one state message`() { + val ring = testRing() + val snapshot = MqttDataSnapshot(batteryPercent = 82) + val basePrefs = MqttPrefs(enabled = true, host = "192.168.1.50") + val identity = MqttDiscovery.resolveDeviceIdentity(ring, basePrefs) + val sensors = MqttDiscovery.sensorsFor(ring, snapshot) + val prefs = basePrefs.copy( + discoveredSensorKeys = sensors.map { it.key }.toSet(), + lastDiscoveredDeviceSlug = identity.slug, + ) + + val (messages, keys) = MqttDiscovery.buildMqttMessages( + device = ring, + snapshot = snapshot, + prefs = prefs, + forceDiscovery = false, + ) + + assertEquals(sensors.map { it.key }.toSet(), keys) + assertEquals(1, messages.size) + assertTrue(messages[0].retain) + assertEquals( + MqttDiscovery.stateTopic(prefs.normalizedBaseTopic, identity), + messages[0].topic, + ) + assertTrue(messages[0].payload.isNotEmpty()) + } + + @Test + fun `stale discovered key triggers removal message plus discovery and state updates`() { + val ring = testRing() + val snapshot = MqttDataSnapshot(batteryPercent = 82) + val basePrefs = MqttPrefs(enabled = true, host = "192.168.1.50") + val identity = MqttDiscovery.resolveDeviceIdentity(ring, basePrefs) + val sensors = MqttDiscovery.sensorsFor(ring, snapshot) + val prefs = basePrefs.copy( + discoveredSensorKeys = sensors.map { it.key }.toSet() + "removed_sensor", + lastDiscoveredDeviceSlug = identity.slug, + ) + + val (messages, _) = MqttDiscovery.buildMqttMessages( + device = ring, + snapshot = snapshot, + prefs = prefs, + forceDiscovery = false, + ) + + val staleConfigTopic = "homeassistant/sensor/${identity.uniquePrefix}/removed_sensor/config" + val removalMessages = messages.filter { it.topic == staleConfigTopic } + assertEquals(1, removalMessages.size) + assertTrue(removalMessages[0].retain) + assertTrue(removalMessages[0].payload.isEmpty()) + + val messageTopics = messages.map { it.topic }.toSet() + sensors.forEach { sensor -> + val expectedTopic = MqttDiscovery.discoveryTopic( + prefs.normalizedDiscoveryPrefix, + sensor, + identity, + ) + assertTrue("Missing discovery message for ${sensor.key}", expectedTopic in messageTopics) + } + + val stateMessages = messages.filter { + it.topic == MqttDiscovery.stateTopic(prefs.normalizedBaseTopic, identity) + } + assertEquals(1, stateMessages.size) + assertTrue(stateMessages[0].retain) + assertTrue(stateMessages[0].payload.isNotEmpty()) + } +} diff --git a/app/src/test/java/com/pulseloop/mqtt/MqttPrefsStoreTest.kt b/app/src/test/java/com/pulseloop/mqtt/MqttPrefsStoreTest.kt new file mode 100644 index 00000000..55a70dd7 --- /dev/null +++ b/app/src/test/java/com/pulseloop/mqtt/MqttPrefsStoreTest.kt @@ -0,0 +1,311 @@ +package com.pulseloop.mqtt + +import android.content.SharedPreferences +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class MqttPrefsStoreTest { + + // --------------------------------------------------------------------- + // Minimal fake SharedPreferences (no Mockito/MockK/Robolectric) + // --------------------------------------------------------------------- + + private class FakeSharedPreferences : SharedPreferences { + val map = HashMap() + private val listeners = mutableListOf() + + val editor = object : SharedPreferences.Editor { + private val pending = HashMap() + private val removals = HashSet() + private var cleared = false + + override fun putString(key: String?, value: String?): SharedPreferences.Editor { + if (key != null) { + if (value == null) removals.add(key) else { pending[key] = value; removals.remove(key) } + } + return this + } + + override fun putStringSet(key: String?, values: MutableSet?): SharedPreferences.Editor { + if (key != null) { + if (values == null) removals.add(key) else { pending[key] = HashSet(values); removals.remove(key) } + } + return this + } + + override fun putInt(key: String?, value: Int): SharedPreferences.Editor { + if (key != null) { pending[key] = value; removals.remove(key) } + return this + } + + override fun putLong(key: String?, value: Long): SharedPreferences.Editor { + if (key != null) { pending[key] = value; removals.remove(key) } + return this + } + + override fun putFloat(key: String?, value: Float): SharedPreferences.Editor { + if (key != null) { pending[key] = value; removals.remove(key) } + return this + } + + override fun putBoolean(key: String?, value: Boolean): SharedPreferences.Editor { + if (key != null) { pending[key] = value; removals.remove(key) } + return this + } + + override fun remove(key: String?): SharedPreferences.Editor { + if (key != null) { removals.add(key); pending.remove(key) } + return this + } + + override fun clear(): SharedPreferences.Editor { + cleared = true + return this + } + + override fun commit(): Boolean { + apply() + return true + } + + override fun apply() { + if (cleared) { + map.clear() + cleared = false + } + removals.forEach { map.remove(it) } + removals.clear() + pending.forEach { (k, v) -> map[k] = v } + pending.clear() + } + } + + override fun edit(): SharedPreferences.Editor = editor + + override fun getAll(): MutableMap = HashMap(map) + + override fun getString(key: String?, defValue: String?): String? = + if (map.containsKey(key)) map[key] as? String ?: defValue else defValue + + @Suppress("UNCHECKED_CAST") + override fun getStringSet(key: String?, defValues: MutableSet?): MutableSet? = + if (map.containsKey(key)) map[key] as? MutableSet ?: defValues else defValues + + override fun getInt(key: String?, defValue: Int): Int = + if (map.containsKey(key)) map[key] as Int else defValue + + override fun getLong(key: String?, defValue: Long): Long = + if (map.containsKey(key)) map[key] as Long else defValue + + override fun getFloat(key: String?, defValue: Float): Float = + if (map.containsKey(key)) map[key] as Float else defValue + + override fun getBoolean(key: String?, defValue: Boolean): Boolean = + if (map.containsKey(key)) map[key] as Boolean else defValue + + override fun contains(key: String?): Boolean = map.containsKey(key) + + override fun registerOnSharedPreferenceChangeListener( + listener: SharedPreferences.OnSharedPreferenceChangeListener? + ) { + if (listener != null) listeners.add(listener) + } + + override fun unregisterOnSharedPreferenceChangeListener( + listener: SharedPreferences.OnSharedPreferenceChangeListener? + ) { + listeners.remove(listener) + } + } + + // --------------------------------------------------------------------- + // Tests + // --------------------------------------------------------------------- + + @Test + fun freshEmptyPrefsReturnDefaults() { + val store = MqttPrefsStore(FakeSharedPreferences(), null) + + val prefs = store.state.value + assertFalse(prefs.enabled) + assertEquals("", prefs.host) + assertEquals(1883, prefs.port) + assertFalse(prefs.useTls) + assertEquals("homeassistant", prefs.discoveryPrefix) + assertEquals("pulseloop", prefs.baseTopic) + assertEquals(30, prefs.syncIntervalMinutes) + assertTrue(prefs.liveStreamingEnabled) + assertFalse(prefs.isConfigured) + + assertEquals(prefs, store.current) + } + + @Test + fun updateRoundTripsPersistsAndSurvivesSecondStore() { + val fake = FakeSharedPreferences() + val store = MqttPrefsStore(fake, null) + + val updated = store.update { + it.copy( + enabled = true, + host = "mqtt.example.com", + port = 8883, + useTls = true, + discoveryPrefix = "ha", + baseTopic = "pulseloop/rings", + syncIntervalMinutes = 60, + liveStreamingEnabled = false, + ) + } + assertTrue(updated.isConfigured) + + assertEquals(updated, store.state.value) + assertEquals(updated, store.current) + assertTrue(fake.map.containsKey(MqttPrefsStore.KEY_PREFS)) + + val second = MqttPrefsStore(fake, null) + assertEquals(updated, second.state.value) + assertEquals(updated, second.current) + } + + @Test + fun normalizedHelpersTrimAndFallback() { + val fake = FakeSharedPreferences() + val store = MqttPrefsStore(fake, null) + + store.update { + it.copy( + discoveryPrefix = " /homeassistant/ ", + baseTopic = " pulseloop/rings/ ", + ) + } + assertEquals("homeassistant", store.current.normalizedDiscoveryPrefix) + assertEquals("pulseloop/rings", store.current.normalizedBaseTopic) + + store.update { it.copy(discoveryPrefix = " ", baseTopic = "") } + assertEquals("homeassistant", store.current.normalizedDiscoveryPrefix) + assertEquals("pulseloop", store.current.normalizedBaseTopic) + } + + @Test + fun effectiveSyncIntervalCoercesOutOfRangeValues() { + val fake = FakeSharedPreferences() + val store = MqttPrefsStore(fake, null) + + store.update { it.copy(syncIntervalMinutes = 5) } + assertEquals(15, store.current.effectiveSyncIntervalMinutes) + + store.update { it.copy(syncIntervalMinutes = 100_000) } + assertEquals(720, store.current.effectiveSyncIntervalMinutes) + + store.update { it.copy(syncIntervalMinutes = 30) } + assertEquals(30, store.current.effectiveSyncIntervalMinutes) + } + + @Test + fun forwardCompatibleJsonWithUnknownFieldLoadsCleanly() { + val fake = FakeSharedPreferences() + val json = """ + { + "enabled": true, + "host": "mqtt.example.com", + "port": 8883, + "useTls": true, + "discoveryPrefix": "ha", + "baseTopic": "pulseloop/rings", + "syncIntervalMinutes": 45, + "liveStreamingEnabled": false, + "future_flag": true + } + """.trimIndent() + fake.edit().putString(MqttPrefsStore.KEY_PREFS, json).commit() + + val store = MqttPrefsStore(fake, null) + val prefs = store.state.value + assertTrue(prefs.enabled) + assertEquals("mqtt.example.com", prefs.host) + assertEquals(8883, prefs.port) + assertTrue(prefs.useTls) + assertEquals("ha", prefs.discoveryPrefix) + assertEquals("pulseloop/rings", prefs.baseTopic) + assertEquals(45, prefs.syncIntervalMinutes) + assertFalse(prefs.liveStreamingEnabled) + assertTrue(prefs.isConfigured) + } + + @Test + fun corruptJsonFallsBackToDefaults() { + val fake = FakeSharedPreferences() + fake.edit().putString(MqttPrefsStore.KEY_PREFS, "{not valid json!!!").commit() + + val store = MqttPrefsStore(fake, null) + assertEquals(MqttPrefs(), store.state.value) + assertEquals(MqttPrefs(), store.current) + } + + @Test + fun passwordIsolatedToSecurePrefs() { + val plain = FakeSharedPreferences() + val secure = FakeSharedPreferences() + val store = MqttPrefsStore(plain, secure) + + store.setPassword("s3cr3t") + + assertEquals("s3cr3t", secure.map[MqttPrefsStore.KEY_PASSWORD]) + assertFalse(plain.map.containsKey(MqttPrefsStore.KEY_PASSWORD)) + assertEquals("s3cr3t", store.getPassword()) + assertTrue(store.hasPassword()) + + store.setPassword("") + assertFalse(secure.map.containsKey(MqttPrefsStore.KEY_PASSWORD)) + assertEquals("", store.getPassword()) + assertFalse(store.hasPassword()) + } + + @Test + fun nullSecurePrefsHandlesPasswordCallsWithoutThrowing() { + val store = MqttPrefsStore(FakeSharedPreferences(), null) + + store.setPassword("whatever") + assertEquals("", store.getPassword()) + assertFalse(store.hasPassword()) + } + + @Test + fun legacyJsonWithoutTransportDeserializesToTcpDefaults() { + val fake = FakeSharedPreferences() + fake.edit().putString( + MqttPrefsStore.KEY_PREFS, + """{"enabled":true,"host":"192.168.1.50","port":1883,"useTls":false}""", + ).commit() + + val store = MqttPrefsStore(fake, null) + assertEquals(MqttTransport.TCP, store.current.transport) + assertEquals("/mqtt", store.current.normalizedWsPath) + } + + @Test + fun persistsWebSocketTransportAndPath() { + val fake = FakeSharedPreferences() + val store1 = MqttPrefsStore(fake, null) + store1.update { + it.copy( + enabled = true, + host = "mqtt.example.com", + port = 443, + useTls = true, + transport = MqttTransport.WEBSOCKET, + wsPath = "ws/ha", + ) + } + + val store2 = MqttPrefsStore(fake, null) + assertEquals(MqttTransport.WEBSOCKET, store2.current.transport) + assertEquals("/ws/ha", store2.current.normalizedWsPath) + assertEquals(443, store2.current.port) + assertTrue(store2.current.useTls) + } +} diff --git a/app/src/test/java/com/pulseloop/mqtt/MqttProtocolTest.kt b/app/src/test/java/com/pulseloop/mqtt/MqttProtocolTest.kt new file mode 100644 index 00000000..3852c8a5 --- /dev/null +++ b/app/src/test/java/com/pulseloop/mqtt/MqttProtocolTest.kt @@ -0,0 +1,513 @@ +package com.pulseloop.mqtt + +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.DataInputStream +import java.io.EOFException +import java.io.IOException +import java.io.OutputStream +import java.net.InetAddress +import java.net.ServerSocket +import java.net.Socket +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger + +/** + * Tests for [MqttProtocol], [MqttClient], and [MqttSessionPool]. + * Uses a real in-process TCP broker on 127.0.0.1 for end-to-end coverage. + */ +class MqttProtocolTest { + + private val timeoutMs = 2000 + + // ------------------------------------------------------------------ + // 1. Remaining length round-trip boundaries + // ------------------------------------------------------------------ + + @Test + fun remainingLength_oneByteBoundaries() { + for (value in intArrayOf(0, 127)) { + val encoded = encodeRemainingLengthBytes(value) + assertEquals("value=$value", 1, encoded.size) + assertEquals(value, MqttProtocol.decodeRemainingLength(ByteArrayInputStream(encoded))) + } + } + + @Test + fun remainingLength_twoByteBoundaries() { + for (value in intArrayOf(128, 16383)) { + val encoded = encodeRemainingLengthBytes(value) + assertEquals("value=$value", 2, encoded.size) + assertEquals(value, MqttProtocol.decodeRemainingLength(ByteArrayInputStream(encoded))) + } + } + + @Test + fun remainingLength_threeByteBoundaries() { + for (value in intArrayOf(16384, 2097151)) { + val encoded = encodeRemainingLengthBytes(value) + assertEquals("value=$value", 3, encoded.size) + assertEquals(value, MqttProtocol.decodeRemainingLength(ByteArrayInputStream(encoded))) + } + } + + @Test + fun remainingLength_fourByteBoundaries() { + for (value in intArrayOf(2097152, 268435455)) { + val encoded = encodeRemainingLengthBytes(value) + assertEquals("value=$value", 4, encoded.size) + assertEquals(value, MqttProtocol.decodeRemainingLength(ByteArrayInputStream(encoded))) + } + assertArrayEquals( + byteArrayOf(0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0x7F), + encodeRemainingLengthBytes(268435455), + ) + } + + @Test + fun remainingLength_overLimit_throws() { + val bytes = byteArrayOf(0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0x80.toByte()) + try { + MqttProtocol.decodeRemainingLength(ByteArrayInputStream(bytes)) + fail("Expected IOException for over-limit remaining length") + } catch (_: IOException) { + // expected + } + } + + @Test + fun remainingLength_prematureEof_throwsEofException() { + val truncated = byteArrayOf(0x80.toByte(), 0x81.toByte()) + try { + MqttProtocol.decodeRemainingLength(ByteArrayInputStream(truncated)) + fail("Expected EOFException for truncated remaining length") + } catch (_: EOFException) { + // expected + } + } + + private fun encodeRemainingLengthBytes(length: Int): ByteArray = + ByteArrayOutputStream().also { MqttProtocol.encodeRemainingLength(length, it) }.toByteArray() + + // ------------------------------------------------------------------ + // 2. CONNECT encoding + // ------------------------------------------------------------------ + + @Test + fun connectEncoding_withUsernameAndPassword() { + val packet = MqttProtocol.encodeConnect( + clientId = "pulse-loop-client", + username = "alice", + password = "secret123", + keepAliveSeconds = 60, + cleanSession = true, + ) + + assertEquals(0x10, packet[0].toInt() and 0xFF) + var offset = 1 + decodeVarintWidth(packet, 1) + + offset = assertUtf8String(packet, offset, "MQTT") + assertEquals(0x04, packet[offset].toInt()) + val flags = packet[offset + 1].toInt() and 0xFF + assertEquals(0x02, flags and 0x02) // clean session + assertEquals(0x80, flags and 0x80) // username flag + assertEquals(0x40, flags and 0x40) // password flag + val keepAlive = ((packet[offset + 2].toInt() and 0xFF) shl 8) or (packet[offset + 3].toInt() and 0xFF) + assertEquals(60, keepAlive) + + var payloadOffset = offset + 4 + payloadOffset = assertUtf8String(packet, payloadOffset, "pulse-loop-client") + payloadOffset = assertUtf8String(packet, payloadOffset, "alice") + payloadOffset = assertUtf8String(packet, payloadOffset, "secret123") + assertEquals(packet.size, payloadOffset) + } + + @Test + fun connectEncoding_usernameNullPasswordNonNull_throws() { + try { + MqttProtocol.encodeConnect( + clientId = "client", + username = null, + password = "orphan", + keepAliveSeconds = 30, + cleanSession = true, + ) + fail("Expected IllegalArgumentException when password set without username") + } catch (_: IllegalArgumentException) { + // expected + } + } + + private fun decodeVarintWidth(packet: ByteArray, start: Int): Int { + var i = start + while (true) { + val byte = packet[i].toInt() and 0xFF + i++ + if (byte and 0x80 == 0) break + } + return i - start + } + + private fun assertUtf8String(packet: ByteArray, offset: Int, expected: String): Int { + val len = ((packet[offset].toInt() and 0xFF) shl 8) or (packet[offset + 1].toInt() and 0xFF) + assertEquals(expected, String(packet, offset + 2, len, Charsets.UTF_8)) + return offset + 2 + len + } + + // ------------------------------------------------------------------ + // 3. PUBLISH / PUBACK + // ------------------------------------------------------------------ + + @Test + fun publishQos0_noPacketId_retainFlag() { + val packet = MqttProtocol.encodePublish( + topic = "sensors/heart-rate", + payload = "72".toByteArray(Charsets.UTF_8), + qos = 0, + retain = true, + dup = false, + packetId = 1, + ) + val fixedHeader = packet[0].toInt() and 0xFF + assertEquals(0x30, fixedHeader and 0xF0) // PUBLISH type + assertEquals(0x01, fixedHeader and 0x01) // retain = true + assertEquals(0x00, fixedHeader and 0x08) // dup = false (QoS 0) + assertEquals(0x00, fixedHeader and 0x06) // QoS 0 + + var offset = 1 + decodeVarintWidth(packet, 1) + offset = assertUtf8String(packet, offset, "sensors/heart-rate") + assertEquals("72", String(packet, offset, packet.size - offset, Charsets.UTF_8)) + } + + @Test + fun publishQos1_hasPacketId_dupFlag() { + val packet = MqttProtocol.encodePublish( + topic = "sensors/spo2", + payload = "98".toByteArray(Charsets.UTF_8), + qos = 1, + retain = false, + dup = true, + packetId = 0x1234, + ) + val fixedHeader = packet[0].toInt() and 0xFF + assertEquals(0x08, fixedHeader and 0x08) // dup = true + assertEquals(0x02, fixedHeader and 0x06) // QoS 1 + assertEquals(0x00, fixedHeader and 0x01) // retain = false + + var offset = 1 + decodeVarintWidth(packet, 1) + offset = assertUtf8String(packet, offset, "sensors/spo2") + val packetId = ((packet[offset].toInt() and 0xFF) shl 8) or (packet[offset + 1].toInt() and 0xFF) + assertEquals(0x1234, packetId) + assertEquals("98", String(packet, offset + 2, packet.size - offset - 2, Charsets.UTF_8)) + } + + @Test + fun pubAck_roundTrip() { + val encoded = MqttProtocol.encodePubAck(0xBEEF) + assertEquals(4, encoded.size) + assertEquals(0x40, encoded[0].toInt() and 0xFF) + assertEquals(2, encoded[1].toInt()) + val packet = MqttProtocol.readPacket(ByteArrayInputStream(encoded)) + assertEquals(MqttProtocol.PACKET_PUBACK, packet.packetType) + assertEquals(0xBEEF, MqttProtocol.decodePubAckPacketId(packet)) + } + + // ------------------------------------------------------------------ + // 4. CONNACK decoding + // ------------------------------------------------------------------ + + @Test + fun connAckDecoding_allReturnCodes() { + for (code in 0..5) { + val raw = byteArrayOf( + 0x20, + 0x02, + if (code == 0) 0x01 else 0x00, + code.toByte(), + ) + val packet = MqttProtocol.readPacket(ByteArrayInputStream(raw)) + val connAck = MqttProtocol.decodeConnAck(packet) + assertEquals(code == 0, connAck.sessionPresent) + assertEquals(code, connAck.returnCode) + assertTrue(MqttProtocol.connAckDescription(code).isNotBlank()) + } + } + + // ------------------------------------------------------------------ + // 5. End-to-end loopback broker tests + // ------------------------------------------------------------------ + + private class BrokerMessage( + val topic: String, + val payload: ByteArray, + val retain: Boolean, + val packetId: Int?, + ) + + private class MockBroker(private val serverSocket: ServerSocket) { + val acceptCount = AtomicInteger(0) + val connectUsernames = CopyOnWriteArrayList() + val messages = CopyOnWriteArrayList() + val sawDisconnect = CountDownLatch(1) + @Volatile var connAckReturnCode: Int = 0 + @Volatile var closeSocketAfterFirstPublish = false + + fun serve() { + val executor = Executors.newCachedThreadPool() + try { + while (!serverSocket.isClosed) { + val socket = try { + serverSocket.accept() + } catch (_: Exception) { + break + } + acceptCount.incrementAndGet() + executor.submit { handle(socket) } + } + } finally { + executor.shutdownNow() + } + } + + private fun handle(socket: Socket) { + socket.soTimeout = 3000 + try { + socket.use { s -> + val input = DataInputStream(s.getInputStream()) + val output = s.getOutputStream() + if (!readConnectAndReply(input, output)) return + while (true) { + val first = input.read() + if (first == -1) return + val remaining = MqttProtocol.decodeRemainingLength(input) + val body = ByteArray(remaining) + input.readFully(body) + when ((first ushr 4) and 0x0F) { + MqttProtocol.PACKET_PUBLISH -> handlePublish(first, body, output) + MqttProtocol.PACKET_PINGREQ -> output.write(byteArrayOf(0xD0.toByte(), 0x00)) + MqttProtocol.PACKET_DISCONNECT -> { + sawDisconnect.countDown() + return + } + } + output.flush() + } + } + } catch (_: Exception) { + // Socket closed cleanly or simulated disconnect. + } + } + + private fun readConnectAndReply(input: DataInputStream, output: OutputStream): Boolean { + val first = input.read() + if (first == -1) return false + val remaining = MqttProtocol.decodeRemainingLength(input) + val body = ByteArray(remaining) + input.readFully(body) + + // Variable header: protocolName(2+len) + level(1) + flags(1) + keepAlive(2) + val protoLen = ((body[0].toInt() and 0xFF) shl 8) or (body[1].toInt() and 0xFF) + var offset = 2 + protoLen + 1 + val connectFlags = body[offset].toInt() and 0xFF + offset += 1 + 2 // skip flags + keepAlive + + val clientIdLen = ((body[offset].toInt() and 0xFF) shl 8) or (body[offset + 1].toInt() and 0xFF) + offset += 2 + clientIdLen + + var username: String? = null + if (connectFlags and 0x80 != 0) { + val uLen = ((body[offset].toInt() and 0xFF) shl 8) or (body[offset + 1].toInt() and 0xFF) + username = String(body, offset + 2, uLen, Charsets.UTF_8) + offset += 2 + uLen + } + connectUsernames.add(username) + + output.write(byteArrayOf(0x20, 0x02, 0x00, connAckReturnCode.toByte())) + output.flush() + return connAckReturnCode == 0 + } + + private fun handlePublish(firstByte: Int, body: ByteArray, output: OutputStream) { + var offset = 0 + val topicLen = ((body[offset].toInt() and 0xFF) shl 8) or (body[offset + 1].toInt() and 0xFF) + offset += 2 + val topic = String(body, offset, topicLen, Charsets.UTF_8) + offset += topicLen + val qos = (firstByte and 0x06) ushr 1 + val retain = (firstByte and 0x01) != 0 + var packetId: Int? = null + if (qos >= 1) { + packetId = ((body[offset].toInt() and 0xFF) shl 8) or (body[offset + 1].toInt() and 0xFF) + offset += 2 + } + val payload = body.copyOfRange(offset, body.size) + messages.add(BrokerMessage(topic, payload, retain, packetId)) + if (qos == 1 && packetId != null) { + output.write(MqttProtocol.encodePubAck(packetId)) + output.flush() + } + if (closeSocketAfterFirstPublish && messages.size == 1) { + throw IOException("simulated idle disconnect after first publish") + } + } + } + + private fun startBroker(configure: (MockBroker) -> Unit = {}): Triple { + val serverSocket = ServerSocket(0, 4, InetAddress.getByName("127.0.0.1")) + val broker = MockBroker(serverSocket).apply(configure) + val thread = Thread { broker.serve() }.apply { + isDaemon = true + start() + } + return Triple(serverSocket, broker, thread) + } + + private fun stopBroker(serverSocket: ServerSocket, thread: Thread) { + runCatching { serverSocket.close() } + thread.join(1000) + } + + private fun configFor(port: Int, clientId: String, username: String = "", password: String = "") = + MqttEndpointConfig( + host = "127.0.0.1", + port = port, + useTls = false, + username = username, + password = password, + clientId = clientId, + connectTimeoutMs = timeoutMs, + readTimeoutMs = timeoutMs, + ) + + @Test + fun publishAll_sendsConnectPublishesAndDisconnect() = runBlocking { + val (serverSocket, broker, thread) = startBroker() + try { + MqttClient.publishAll( + configFor(serverSocket.localPort, "e2e-publisher", "user", "pass"), + listOf( + MqttMessage("pulse/hr", "72", qos = 1, retain = true), + MqttMessage("pulse/spo2", "98", qos = 1, retain = true), + MqttMessage("pulse/steps", "10453", qos = 1, retain = false), + ), + ) + + assertTrue(broker.sawDisconnect.await(2, TimeUnit.SECONDS)) + assertEquals(listOf("user"), broker.connectUsernames.toList()) + assertEquals(3, broker.messages.size) + assertEquals("pulse/hr", broker.messages[0].topic) + assertEquals("72", String(broker.messages[0].payload, Charsets.UTF_8)) + assertTrue(broker.messages[0].retain) + assertEquals("pulse/spo2", broker.messages[1].topic) + assertEquals("98", String(broker.messages[1].payload, Charsets.UTF_8)) + assertEquals("pulse/steps", broker.messages[2].topic) + assertEquals("10453", String(broker.messages[2].payload, Charsets.UTF_8)) + assertTrue(broker.messages.all { it.packetId != null }) + } finally { + stopBroker(serverSocket, thread) + } + } + + @Test + fun publishAll_throwsMqttException_whenConnAckRejects() = runBlocking { + val (serverSocket, broker, thread) = startBroker { it.connAckReturnCode = 4 } + try { + try { + MqttClient.publishAll( + configFor(serverSocket.localPort, "bad-creds", "wrong", "creds"), + listOf(MqttMessage("pulse/hr", "72", qos = 1, retain = false)), + ) + fail("Expected MqttException for CONNACK return code 4") + } catch (_: MqttException) { + // expected + } + assertEquals(0, broker.messages.size) + } finally { + stopBroker(serverSocket, thread) + } + } + + @Test + fun testConnection_pingReqPingRespDisconnect() = runBlocking { + val (serverSocket, broker, thread) = startBroker() + try { + MqttClient.testConnection(configFor(serverSocket.localPort, "ping-test")) + assertTrue(broker.sawDisconnect.await(2, TimeUnit.SECONDS)) + assertEquals(1, broker.acceptCount.get()) + } finally { + stopBroker(serverSocket, thread) + } + } + + @Test + fun sessionPool_reusesConnectionWithinIdleTtl() = runBlocking { + val (serverSocket, broker, thread) = startBroker() + try { + var nowMs = 1_000L + val pool = MqttSessionPool(idleTtlMs = 10_000L, clockMs = { nowMs }) + val cfg = configFor(serverSocket.localPort, "pool-test", "user", "pass") + try { + pool.publish(cfg, listOf(MqttMessage("pulse/hr", "72", qos = 1, retain = false))) + nowMs += 4_000L + pool.publish(cfg, listOf(MqttMessage("pulse/hr", "75", qos = 1, retain = false))) + } finally { + pool.close() + } + assertEquals(1, broker.acceptCount.get()) + assertEquals(2, broker.messages.size) + assertEquals("72", String(broker.messages[0].payload, Charsets.UTF_8)) + assertEquals("75", String(broker.messages[1].payload, Charsets.UTF_8)) + } finally { + stopBroker(serverSocket, thread) + } + } + + @Test + fun sessionPool_reconnectsWhenBrokerClosesSocket() = runBlocking { + val (serverSocket, broker, thread) = startBroker { it.closeSocketAfterFirstPublish = true } + try { + val pool = MqttSessionPool(idleTtlMs = 10_000L) + val cfg = configFor(serverSocket.localPort, "reconnect-test", "user", "pass") + try { + pool.publish(cfg, listOf(MqttMessage("pulse/hr", "72", qos = 1, retain = false))) + pool.publish(cfg, listOf(MqttMessage("pulse/hr", "75", qos = 1, retain = false))) + } finally { + pool.close() + } + assertEquals(2, broker.acceptCount.get()) + assertEquals(2, broker.messages.size) + } finally { + stopBroker(serverSocket, thread) + } + } + + @Test + fun sessionPool_reconnectsAfterIdleTtlElapses() = runBlocking { + val (serverSocket, broker, thread) = startBroker() + try { + var nowMs = 1_000L + val pool = MqttSessionPool(idleTtlMs = 5_000L, clockMs = { nowMs }) + val cfg = configFor(serverSocket.localPort, "ttl-test", "user", "pass") + try { + pool.publish(cfg, listOf(MqttMessage("pulse/hr", "72", qos = 1, retain = false))) + nowMs += 6_000L + pool.publish(cfg, listOf(MqttMessage("pulse/hr", "75", qos = 1, retain = false))) + } finally { + pool.close() + } + assertEquals(2, broker.acceptCount.get()) + assertEquals(2, broker.messages.size) + } finally { + stopBroker(serverSocket, thread) + } + } +} diff --git a/app/src/test/java/com/pulseloop/mqtt/MqttWebSocketTest.kt b/app/src/test/java/com/pulseloop/mqtt/MqttWebSocketTest.kt new file mode 100644 index 00000000..c44a791b --- /dev/null +++ b/app/src/test/java/com/pulseloop/mqtt/MqttWebSocketTest.kt @@ -0,0 +1,263 @@ +package com.pulseloop.mqtt + +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.EOFException +import java.io.InputStream +import java.io.OutputStream +import java.net.ServerSocket +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.Executors +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test + +class MqttWebSocketTest { + + @Test + fun computeAcceptKey_matchesRfc6455Vector() { + assertEquals( + "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", + MqttWebSocket.computeAcceptKey("dGhlIHNhbXBsZSBub25jZQ=="), + ) + } + + @Test + fun normalizePath_addsLeadingSlashOrDefaultsToMqtt() { + assertEquals("/mqtt", MqttWebSocket.normalizePath("")) + assertEquals("/mqtt", MqttWebSocket.normalizePath(" ")) + assertEquals("/mqtt", MqttWebSocket.normalizePath("/mqtt")) + assertEquals("/ws", MqttWebSocket.normalizePath("ws")) + assertEquals("/mqtt/v1", MqttWebSocket.normalizePath(" /mqtt/v1 ")) + } + + @Test + fun upgrade_rejectsNon101AndInvalidAcceptKey() { + val badStatus = "HTTP/1.1 404 Not Found\r\n\r\n".toByteArray(Charsets.US_ASCII) + try { + MqttWebSocket.upgrade( + host = "mqtt.example.com", + port = 443, + useTls = true, + path = "/mqtt", + rawInput = ByteArrayInputStream(badStatus), + rawOutput = ByteArrayOutputStream(), + ) + fail("Expected MqttException on HTTP 404") + } catch (e: MqttException) { + assertTrue(e.message!!.contains("404")) + } + + val badAccept = ( + "HTTP/1.1 101 Switching Protocols\r\n" + + "Upgrade: websocket\r\n" + + "Connection: Upgrade\r\n" + + "Sec-WebSocket-Accept: wrongkey==\r\n\r\n" + ).toByteArray(Charsets.US_ASCII) + try { + MqttWebSocket.upgrade( + host = "mqtt.example.com", + port = 443, + useTls = true, + path = "/mqtt", + rawInput = ByteArrayInputStream(badAccept), + rawOutput = ByteArrayOutputStream(), + ) + fail("Expected MqttException on invalid Sec-WebSocket-Accept") + } catch (e: MqttException) { + assertTrue(e.message!!.contains("Sec-WebSocket-Accept")) + } + } + + @Test + fun loopbackMockWsBroker_handlesHandshakeQos1PublishPingAndLargePayload() = runBlocking { + val capturedRequestLines = CopyOnWriteArrayList() + val capturedMqttPayloads = CopyOnWriteArrayList() + val receivedPong = CopyOnWriteArrayList() + val sawClose = java.util.concurrent.atomic.AtomicBoolean(false) + + val server = ServerSocket(0) + val executor = Executors.newSingleThreadExecutor() + val serverFuture = executor.submit { + server.use { srv -> + srv.accept().use { client -> + val input = client.getInputStream() + val output = client.getOutputStream() + + // Read HTTP Upgrade request + var key = "" + while (true) { + val line = readAsciiLine(input) + if (line.isEmpty()) break + capturedRequestLines.add(line) + if (line.lowercase().startsWith("sec-websocket-key:")) { + key = line.substringAfter(':').trim() + } + } + + val accept = MqttWebSocket.computeAcceptKey(key) + val response = ( + "HTTP/1.1 101 Switching Protocols\r\n" + + "Upgrade: websocket\r\n" + + "Connection: Upgrade\r\n" + + "Sec-WebSocket-Accept: $accept\r\n" + + "Sec-WebSocket-Protocol: mqtt\r\n" + + "\r\n" + ).toByteArray(Charsets.US_ASCII) + output.write(response) + output.flush() + + // Read MQTT packets wrapped in masked client WebSocket frames + while (true) { + val (opcode, payload) = readWsFrame(input) ?: break + when (opcode) { + 0x8 -> { + sawClose.set(true) + break + } + 0xA -> { + receivedPong.add(payload) + } + 0x2 -> { + capturedMqttPayloads.add(payload) + val packetType = (payload[0].toInt() ushr 4) and 0x0F + when (packetType) { + MqttProtocol.PACKET_CONNECT -> { + // Send WS Ping first to verify client auto-replies with Pong before CONNACK + writeUnmaskedWsFrame(output, 0x9, "hi".toByteArray()) + writeUnmaskedWsFrame( + output, + 0x2, + byteArrayOf(0x20, 0x02, 0x00, 0x00), // CONNACK 0 + ) + } + MqttProtocol.PACKET_PUBLISH -> { + val qos = (payload[0].toInt() ushr 1) and 0x03 + if (qos == 1) { + // Extract packetId after remaining length + topic + var idx = 1 + while ((payload[idx].toInt() and 0x80) != 0) idx++ + idx++ + val topicLen = ((payload[idx].toInt() and 0xFF) shl 8) or + (payload[idx + 1].toInt() and 0xFF) + val pidIdx = idx + 2 + topicLen + val hi = payload[pidIdx] + val lo = payload[pidIdx + 1] + writeUnmaskedWsFrame( + output, + 0x2, + byteArrayOf(0x40, 0x02, hi, lo), // PUBACK + ) + } + } + MqttProtocol.PACKET_PINGREQ -> { + writeUnmaskedWsFrame( + output, + 0x2, + byteArrayOf(0xD0.toByte(), 0x00), // PINGRESP + ) + } + MqttProtocol.PACKET_DISCONNECT -> { + // Client will follow with WS Close + } + } + } + } + } + } + } + } + + val largeJson = """{"payload":"${"x".repeat(400)}"}""" + val config = MqttEndpointConfig( + host = "127.0.0.1", + port = server.localPort, + useTls = false, + transport = MqttTransport.WEBSOCKET, + wsPath = "ws/mqtt", + username = "u", + password = "p", + clientId = "pl_ws_test", + ) + MqttClient.publishAll( + config, + listOf( + MqttMessage("pulseloop/test/state", largeJson, qos = 1, retain = true), + ), + ) + serverFuture.get() + executor.shutdown() + + assertTrue(capturedRequestLines.first().startsWith("GET /ws/mqtt HTTP/1.1")) + assertTrue(capturedRequestLines.any { it.equals("Host: 127.0.0.1:${server.localPort}", ignoreCase = true) }) + assertTrue(capturedRequestLines.any { it.equals("Sec-WebSocket-Protocol: mqtt", ignoreCase = true) }) + assertEquals(1, receivedPong.size) + assertEquals("hi", receivedPong.first().toString(Charsets.UTF_8)) + assertTrue(capturedMqttPayloads.size >= 3) // CONNECT, PUBLISH, DISCONNECT + assertTrue(sawClose.get()) + } + + private fun readAsciiLine(input: InputStream): String { + val buf = ByteArrayOutputStream() + while (true) { + val b = input.read() + if (b == -1) throw EOFException() + if (b == '\n'.code) { + val arr = buf.toByteArray() + val len = if (arr.isNotEmpty() && arr.last() == '\r'.code.toByte()) arr.size - 1 else arr.size + return String(arr, 0, len, Charsets.US_ASCII) + } + buf.write(b) + } + } + + private fun readWsFrame(input: InputStream): Pair? { + val b0 = input.read() + if (b0 == -1) return null + val b1 = input.read() + if (b1 == -1) throw EOFException() + val opcode = b0 and 0x0F + val masked = (b1 and 0x80) != 0 + assertTrue("Client WebSocket frames must be masked per RFC 6455", masked) + var len = b1 and 0x7F + if (len == 126) { + len = (input.read() shl 8) or input.read() + } else if (len == 127) { + var acc = 0L + repeat(8) { acc = (acc shl 8) or input.read().toLong() } + len = acc.toInt() + } + val mask = ByteArray(4) + readFully(input, mask) + val payload = ByteArray(len) + readFully(input, payload) + for (i in 0 until len) { + payload[i] = (payload[i].toInt() xor mask[i and 3].toInt()).toByte() + } + return opcode to payload + } + + private fun readFully(input: InputStream, dest: ByteArray) { + var off = 0 + while (off < dest.size) { + val n = input.read(dest, off, dest.size - off) + if (n == -1) throw EOFException() + off += n + } + } + + private fun writeUnmaskedWsFrame(output: OutputStream, opcode: Int, payload: ByteArray) { + output.write(0x80 or opcode) + if (payload.size <= 125) { + output.write(payload.size) + } else { + output.write(126) + output.write((payload.size ushr 8) and 0xFF) + output.write(payload.size and 0xFF) + } + output.write(payload) + output.flush() + } +} diff --git a/docs/mqtt.md b/docs/mqtt.md new file mode 100644 index 00000000..241abf5c --- /dev/null +++ b/docs/mqtt.md @@ -0,0 +1,162 @@ +# MQTT Integration + +PulseLoop Android can publish your synced ring health metrics directly to any local or remote MQTT broker using a consolidated JSON state topic paired with standard MQTT auto-discovery config payloads. + +> **Real ring data only:** Demo / seeded rows (`source` in `demo` / `mock`) are excluded from MQTT export. Only measurements, activity, sleep, and workout sessions recorded from a paired real ring are published. + +--- + +## Configuration (`Settings → MQTT`) + +| Setting | Default | Notes | +|---|---|---| +| **Enable MQTT export** | Off | Turns background and live publishing on or off. | +| **Broker Host** | _(empty)_ | Hostname or IP of your MQTT broker (for example `192.168.1.50` or `mqtt.example.com`). Plain TCP/WS is intended for private/local addresses; enable TLS for public hosts. | +| **Transport** | `TCP` | Choose `TCP` (`mqtt://` / `mqtts://`) or `WebSocket (WS / WSS)` (`ws://` / `wss://`, for example behind a reverse proxy on port `443`). | +| **Port** | `1883` (`8883` TLS) / `80` (`443` WSS) | TCP port (`1`–`65535`). Auto-switches defaults when toggling Transport or TLS. | +| **WebSocket Path** | `/mqtt` | Endpoint path sent in the HTTP Upgrade request when **Transport** is `WebSocket` (for example `/mqtt` or `/ws`). | +| **Use TLS (MQTTS / WSS)** | Off | Uses Android's default TLS socket factory with `HTTPS` hostname verification (supports `mqtts://` and `wss://`). | +| **Username / Password** | _(optional)_ | Sent on `CONNECT`; password is stored separately in `EncryptedSharedPreferences` (`pulseloop_secure`). | +| **Discovery Prefix** | `homeassistant` | Root topic used when publishing MQTT auto-discovery entity definitions. | +| **Base Topic** | `pulseloop` | Root topic used for consolidated state payloads. | +| **Device Name Override** | _(optional)_ | Replaces the ring's default display name and topic slug (`//state`). | +| **Background Ring Sync** | `30 min` | Controls how often `RingSyncWorker` wakes in the background (`15 min`, `30 min`, `1 hr`, `2 hr`, clamped to `15`–`720 min`) and queues an MQTT export. | +| **Live workout streaming** | On | Streams throttled updates (~`5 s`) over a pooled MQTT connection (`MqttSessionPool`) during active workouts and live spot measurements. | + +--- + +## Topic Layout + +Every message is published with **QoS 1** and **retain = true**. + +### 1. Discovery Config Topics + +```text +////config +``` + +- ``: normalized discovery prefix (default `homeassistant`, compatible with MQTT auto-discovery consumers). +- ``: `binary_sensor` for `workout_active`, `sensor` for all other metrics. +- ``: `pulseloop_` (for example `pulseloop_aabbccdde1f2`). +- ``: metric key listed in the table below (for example `heart_rate`, `steps`, `sleep_score`). + +### 2. Consolidated State Topic + +```text +//state +``` + +- ``: normalized base topic (default `pulseloop`). +- ``: `_` (for example `colmi_r11_e1f2`) or `` when an override is set. +- Payload is a single flat JSON object read by subscribers or via auto-discovery `value_template` (for example `{{ value_json.get('heart_rate') }}`). + +--- + +## Exported Data & Sensor Selection + +Exported sensors are automatically selected based on the paired ring's reported capabilities and recorded measurements (unsupported metrics are not advertised or emitted). Sleep uses the current reference waking night; daily activity uses today's local day; vitals use the latest real reading. + +### Vitals + +| Sensor Key | Component | JSON Field | Unit | Device / State Class | Selection Requirement | +|---|---|---|---|---|---| +| `battery` | `sensor` | `battery` | `%` | `battery` / `measurement` | `BATTERY` capability | +| `heart_rate` | `sensor` | `heart_rate` | `bpm` | — / `measurement` | `HEART_RATE` or `MANUAL_HEART_RATE` (uses live HR when workout streaming is active) | +| `resting_heart_rate` | `sensor` | `resting_heart_rate` | `bpm` | — / `measurement` | `HEART_RATE` or `MANUAL_HEART_RATE` **and** computed resting baseline present | +| `spo2` | `sensor` | `spo2` | `%` | — / `measurement` | `SPO2`, `SPO2_HISTORY`, or `MANUAL_SPO2` | +| `hrv` | `sensor` | `hrv` | `ms` | — / `measurement` | `HRV` or `MANUAL_HRV` | +| `stress` | `sensor` | `stress` | — | — / `measurement` | `STRESS` or `MANUAL_STRESS` **and** real hardware `STRESS` rows present (derived stress is never exported) | +| `temperature` | `sensor` | `temperature` | `°C` | `temperature` / `measurement` | `TEMPERATURE` or `MANUAL_TEMPERATURE` | +| `blood_pressure_systolic` | `sensor` | `blood_pressure_systolic` | `mmHg` | — / `measurement` | `BLOOD_PRESSURE` or `MANUAL_BLOOD_PRESSURE` | +| `blood_pressure_diastolic` | `sensor` | `blood_pressure_diastolic` | `mmHg` | — / `measurement` | `BLOOD_PRESSURE` or `MANUAL_BLOOD_PRESSURE` | +| `blood_sugar` | `sensor` | `blood_sugar` | `mg/dL` | `blood_glucose_concentration` / `measurement` | `BLOOD_SUGAR` | +| `respiratory_rate` | `sensor` | `respiratory_rate` | `breaths/min` | — / `measurement` | Real `RESPIRATORY_RATE` measurement rows present | +| `vo2_max` | `sensor` | `vo2_max` | `mL/kg/min` | — / `measurement` | `VO2MAX` | + +### Daily Activity & Sleep + +| Sensor Key | Component | JSON Field | Unit | Device / State Class | Selection Requirement | +|---|---|---|---|---|---| +| `steps` | `sensor` | `steps` | `steps` | — / `total_increasing` | `STEPS` capability | +| `calories` | `sensor` | `calories` | `kcal` | — / `total_increasing` | `STEPS` capability | +| `distance` | `sensor` | `distance` | `m` | `distance` / `total_increasing` | `STEPS` capability | +| `active_minutes` | `sensor` | `active_minutes` | `min` | `duration` / `total_increasing` | `STEPS` capability | +| `sleep_duration` | `sensor` | `sleep_duration` | `min` | `duration` / `measurement` | `SLEEP` capability | +| `sleep_score` | `sensor` | `sleep_score` | — | — / `measurement` | `SLEEP` capability | +| `sleep_deep` | `sensor` | `sleep_deep` | `min` | `duration` / `measurement` | `SLEEP` capability | +| `sleep_light` | `sensor` | `sleep_light` | `min` | `duration` / `measurement` | `SLEEP` capability | +| `sleep_rem` | `sensor` | `sleep_rem` | `min` | `duration` / `measurement` | `SLEEP` and `REM_SLEEP` capabilities | +| `sleep_awake` | `sensor` | `sleep_awake` | `min` | `duration` / `measurement` | `SLEEP` capability | + +### Live Workout & Diagnostics + +| Sensor Key | Component | JSON Field | Unit | Device / State Class / Category | Selection Requirement | +|---|---|---|---|---|---| +| `workout_active` | `binary_sensor` | `workout_active` | `ON`/`OFF` | `running` (binary sensor) | `HEART_RATE` capability or active/recorded workout (`payload_on: "ON"`, `payload_off: "OFF"`) | +| `workout_type` | `sensor` | `workout_type` | — | — | Same as `workout_active` (omitted from state JSON when no workout is active) | +| `workout_duration` | `sensor` | `workout_duration` | `s` | `duration` / `measurement` | Same as `workout_active` (omitted from state JSON when no workout is active) | +| `last_sync` | `sensor` | `last_sync` | ISO-8601 UTC | `timestamp` / `diagnostic` | Always included | + +--- + +## Example Payloads + +### Discovery Config (`homeassistant/sensor/pulseloop_aabbccdde1f2/heart_rate/config`) + +```json +{ + "name": "Heart Rate", + "unique_id": "pulseloop_aabbccdde1f2_heart_rate", + "object_id": "colmi_r11_e1f2_heart_rate", + "state_topic": "pulseloop/colmi_r11_e1f2/state", + "value_template": "{{ value_json.get('heart_rate') }}", + "unit_of_measurement": "bpm", + "state_class": "measurement", + "icon": "mdi:heart-pulse", + "device": { + "identifiers": ["pulseloop_aabbccdde1f2"], + "name": "Colmi R11", + "manufacturer": "Colmi", + "model": "Colmi R11", + "sw_version": "1.00.38", + "connections": [["mac", "aa:bb:cc:dd:e1:f2"]] + } +} +``` + +### State Topic (`pulseloop/colmi_r11_e1f2/state`) + +```json +{ + "battery": 84, + "heart_rate": 72, + "resting_heart_rate": 58, + "spo2": 98, + "hrv": 46.5, + "stress": 31, + "temperature": 36.4, + "steps": 6840, + "calories": 428.0, + "distance": 4925, + "active_minutes": 34, + "sleep_duration": 450, + "sleep_score": 70, + "sleep_deep": 115, + "sleep_light": 245, + "sleep_rem": 90, + "sleep_awake": 25, + "blood_pressure_systolic": 118, + "blood_pressure_diastolic": 76, + "blood_sugar": 94.0, + "workout_active": false, + "last_sync": "2026-11-15T08:06:12Z" +} +``` + +> Null metrics and inactive workout fields (`workout_type`, `workout_duration`) are omitted from the JSON object rather than emitted as `null`. + +--- + +## Clearing Retained Topics + +Tapping **Clear Retained Topics** on `Settings → MQTT` publishes zero-byte retained payloads (QoS 1) to all previously published `////config` topics and `//state`, then resets local discovery bookkeeping.