Monitor the XIAO's battery and make the XIAO the production board
The production OBU is now a Seeed XIAO ESP32-C5 (8 MB flash, one native USB-C port) on a LiPo with no protection board. The firmware reads the cell on GPIO6 (divider switched by GPIO26) every 5 s, sends it in STATUS (battery_mv and battery_flags, octets 103-105; decoders accept 103 or >= 106 octets), warns below 3.50 V and deep-sleeps below 3.30 V when no phone is on USB, waking every 5 min to check the cell again. Thresholds are in Kconfig; host test `make battery`. The app shows voltage, a rough percentage and the low/critical state on the ESP32-C5 card and in the top bar. With several bonded micrOBUs (a replaced board stays bonded), the BLE link tries the one that last connected first and moves on to the next after each failure. tools/station_status_watch.py reads STATUS from the native port.
This commit is contained in:
@@ -93,6 +93,7 @@ class MainActivity : AppCompatActivity() {
|
||||
val useCaseEnabledMap by mqttViewModel.useCaseEnabledMap.collectAsState()
|
||||
val obuHardware by mqttViewModel.obuHardware.collectAsState()
|
||||
val esp32LinkState by mqttViewModel.esp32LinkState.collectAsState()
|
||||
val stationStatus by mqttViewModel.stationStatus.collectAsState()
|
||||
val esp32Transport by mqttViewModel.esp32Transport.collectAsState()
|
||||
val outgoingMessage by mqttViewModel.outgoingMessage.collectAsState()
|
||||
val signOutgoing by mqttViewModel.signOutgoing.collectAsState()
|
||||
@@ -163,6 +164,8 @@ class MainActivity : AppCompatActivity() {
|
||||
isEsp32 = obuHardware == ObuHardware.ESP32_C5,
|
||||
esp32LinkState = esp32LinkState,
|
||||
esp32Bluetooth = esp32Transport == Esp32Transport.BLE,
|
||||
obuBatteryLow = esp32LinkState == Esp32LinkState.CONNECTED && stationStatus?.batteryLow == true,
|
||||
obuBatteryCritical = esp32LinkState == Esp32LinkState.CONNECTED && stationStatus?.batteryCritical == true,
|
||||
)
|
||||
}
|
||||
},
|
||||
|
||||
@@ -94,6 +94,7 @@ class BleLinkTransport @Inject constructor(
|
||||
private const val SCAN_TIMEOUT_MS = 15_000L
|
||||
/** Long enough for the user to find and type the passkey in the system dialog. */
|
||||
private const val BOND_TIMEOUT_MS = 60_000L
|
||||
private const val KEY_LAST_ADDRESS = "last_address"
|
||||
private const val GATT_OP_TIMEOUT_MS = 5_000L
|
||||
/** After a working link dropped: try again soon. */
|
||||
private const val RECONNECT_DELAY_MS = 1_000L
|
||||
@@ -114,6 +115,20 @@ class BleLinkTransport @Inject constructor(
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
private val bluetoothManager = context.getSystemService(BluetoothManager::class.java)
|
||||
private val prefs = context.getSharedPreferences("ble_link", Context.MODE_PRIVATE)
|
||||
/** Failed connections since the last good one, with several bonded micrOBUs; picks which one is next. */
|
||||
private var connectAttempt = 0
|
||||
|
||||
/**
|
||||
* Of the bonded micrOBUs, the one to try now: the address that last reached CONNECTED first, then
|
||||
* the others in turn after each failed connection. Null when none is bonded.
|
||||
*/
|
||||
private fun pickBonded(bonded: List<BluetoothDevice>): BluetoothDevice? {
|
||||
if (bonded.isEmpty()) return null
|
||||
val last = prefs.getString(KEY_LAST_ADDRESS, null)
|
||||
val ordered = bonded.sortedBy { if (it.address == last) 0 else 1 }
|
||||
return ordered[connectAttempt % ordered.size]
|
||||
}
|
||||
|
||||
private val _state = MutableStateFlow(Esp32LinkState.DISCONNECTED)
|
||||
val state: StateFlow<Esp32LinkState> = _state.asStateFlow()
|
||||
@@ -223,7 +238,10 @@ class BleLinkTransport @Inject constructor(
|
||||
_state.value = Esp32LinkState.DEVICE_ATTACHED
|
||||
// A bonded micrOBU is reused without scanning: its address is stable (public address), and
|
||||
// this is what makes a reconnect after a dropout fast.
|
||||
val device = adapter.bondedDevices.firstOrNull { it.name?.startsWith(NAME_PREFIX) == true }
|
||||
// Android may hold several bonded micrOBUs (a replaced board stays bonded): the one that
|
||||
// worked last goes first, and each failed connection moves on to the next.
|
||||
val bonded = adapter.bondedDevices.filter { it.name?.startsWith(NAME_PREFIX) == true }
|
||||
val device = pickBonded(bonded)
|
||||
?: scan() ?: return fail("No micrOBU advertising nearby (is the phone on its USB port?)")
|
||||
deviceName = device.name
|
||||
_detail.value = null
|
||||
@@ -232,6 +250,7 @@ class BleLinkTransport @Inject constructor(
|
||||
connected = CompletableDeferred()
|
||||
gatt = device.connectGatt(context, false, callback, BluetoothDevice.TRANSPORT_LE)
|
||||
if (withTimeoutOrNull(GATT_OP_TIMEOUT_MS * 2) { connected!!.await() } != true) {
|
||||
if (bonded.size > 1) connectAttempt++
|
||||
return fail("Could not connect to ${device.name}")
|
||||
}
|
||||
|
||||
@@ -277,6 +296,8 @@ class BleLinkTransport @Inject constructor(
|
||||
if (!enableNotifications(g, uuid)) return fail("Could not subscribe to ${device.name} notifications")
|
||||
}
|
||||
_state.value = Esp32LinkState.CONNECTED
|
||||
connectAttempt = 0
|
||||
prefs.edit().putString(KEY_LAST_ADDRESS, device.address).apply()
|
||||
Log.i(TAG, "BLE station link ready: ${device.name}")
|
||||
// Wait until the link drops (callback completes `connected` anew with false).
|
||||
val dropped = CompletableDeferred<Boolean>()
|
||||
|
||||
@@ -212,7 +212,11 @@ data class LinkResult(val code: Int, val detail: ByteArray) {
|
||||
}
|
||||
}
|
||||
|
||||
/** STATUS body (103 octets), sent by the micrOBU every second. Counters are since the last configure. */
|
||||
/**
|
||||
* STATUS body, sent by the micrOBU every second. Counters are since the last configure. 103 octets in
|
||||
* the colleague's layout; this firmware appends [batteryMv] and [batteryFlags] (106 octets), and a
|
||||
* 103-octet body from an older board still decodes, with the battery left at "not measured".
|
||||
*/
|
||||
data class StationStatus(
|
||||
val uptimeMs: Long,
|
||||
val configured: Boolean,
|
||||
@@ -235,7 +239,18 @@ data class StationStatus(
|
||||
val linkMalformed: Long,
|
||||
val potiUpdates: Long,
|
||||
val itsTimeMs: Long,
|
||||
/** Cell voltage in millivolts; 0 when the board does not report one (older firmware, no cell, no sensor). */
|
||||
val batteryMv: Int = 0,
|
||||
/** BATTERY_FLAG_* bits. */
|
||||
val batteryFlags: Int = 0,
|
||||
) {
|
||||
/** The cell is below the firmware's warning threshold. */
|
||||
val batteryLow: Boolean get() = batteryMv > 0 && (batteryFlags and BATTERY_FLAG_LOW) != 0
|
||||
/** The cell is below the shutdown threshold: the board powers down unless this phone keeps it on USB. */
|
||||
val batteryCritical: Boolean get() = batteryMv > 0 && (batteryFlags and BATTERY_FLAG_CRITICAL) != 0
|
||||
/** Rough charge of a LiPo cell from its voltage, or null when not measured. An indicator, not a fuel gauge. */
|
||||
val batteryPercent: Int? get() = if (batteryMv > 0) lipoPercent(batteryMv) else null
|
||||
|
||||
/** Signing refusals of every kind: no usable ticket, a pending id change, or a missing permission. */
|
||||
val signRefused: Long get() = refusedNoTicket + refusedChangePending + refusedPermission + signFailed
|
||||
|
||||
@@ -244,10 +259,35 @@ data class StationStatus(
|
||||
override fun hashCode(): Int = toString().hashCode()
|
||||
|
||||
companion object {
|
||||
/** Octets of the colleague's STATUS body. */
|
||||
const val SIZE = 103
|
||||
/** Octets with the MicrOBU battery fields appended. */
|
||||
const val SIZE_WITH_BATTERY = 106
|
||||
const val BATTERY_FLAG_LOW = 0x01
|
||||
const val BATTERY_FLAG_CRITICAL = 0x02
|
||||
|
||||
/** Open-circuit voltage (mV) to charge (%) of a single LiPo cell, interpolated linearly. */
|
||||
private val LIPO_CURVE = arrayOf(
|
||||
3300 to 0, 3500 to 5, 3690 to 10, 3730 to 20, 3770 to 30, 3800 to 40,
|
||||
3840 to 50, 3870 to 60, 3950 to 70, 4020 to 80, 4110 to 90, 4200 to 100,
|
||||
)
|
||||
|
||||
fun lipoPercent(millivolts: Int): Int {
|
||||
if (millivolts <= LIPO_CURVE.first().first) return 0
|
||||
if (millivolts >= LIPO_CURVE.last().first) return 100
|
||||
for (i in 1 until LIPO_CURVE.size) {
|
||||
val (v1, p1) = LIPO_CURVE[i]
|
||||
if (millivolts <= v1) {
|
||||
val (v0, p0) = LIPO_CURVE[i - 1]
|
||||
return p0 + (p1 - p0) * (millivolts - v0) / (v1 - v0)
|
||||
}
|
||||
}
|
||||
return 100
|
||||
}
|
||||
|
||||
/** Accepts the 103-octet body and any body of at least 106 octets; 104 or 105 are malformed. */
|
||||
fun decode(body: ByteArray): StationStatus? {
|
||||
if (body.size != SIZE) return null
|
||||
if (body.size != SIZE && body.size < SIZE_WITH_BATTERY) return null
|
||||
fun u8(i: Int) = body[i].toInt() and 0xFF
|
||||
fun u32(i: Int) = (0 until 4).fold(0L) { acc, k -> acc or ((body[i + k].toLong() and 0xFF) shl (8 * k)) }
|
||||
fun u64(i: Int) = (0 until 8).fold(0L) { acc, k -> acc or ((body[i + k].toLong() and 0xFF) shl (8 * k)) }
|
||||
@@ -268,6 +308,8 @@ data class StationStatus(
|
||||
// c + 56: link_rx_frames
|
||||
linkCrcErrors = u32(c + 60), linkMalformed = u32(c + 64), potiUpdates = u32(c + 68),
|
||||
itsTimeMs = u64(95),
|
||||
batteryMv = if (body.size >= SIZE_WITH_BATTERY) u8(103) or (u8(104) shl 8) else 0,
|
||||
batteryFlags = if (body.size >= SIZE_WITH_BATTERY) u8(105) else 0,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.BatteryAlert
|
||||
import androidx.compose.material.icons.filled.GpsFixed
|
||||
import androidx.compose.material.icons.filled.GpsOff
|
||||
import androidx.compose.material.icons.filled.Sensors
|
||||
@@ -38,8 +39,10 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.hawhamburg.micr0bu.R
|
||||
import com.hawhamburg.micr0bu.data.mqtt.MqttConnectionState
|
||||
import com.hawhamburg.micr0bu.data.transport.Esp32LinkState
|
||||
import com.hawhamburg.micr0bu.viewmodel.SensorUiState
|
||||
@@ -58,6 +61,9 @@ fun StatusTopBar(
|
||||
esp32LinkState: Esp32LinkState = Esp32LinkState.DISCONNECTED,
|
||||
/** The ESP32-C5 is reached over BLE rather than its USB port (Settings). */
|
||||
esp32Bluetooth: Boolean = false,
|
||||
/** The connected ESP32-C5 reports a low cell (amber) or a critical one (red). */
|
||||
obuBatteryLow: Boolean = false,
|
||||
obuBatteryCritical: Boolean = false,
|
||||
) {
|
||||
TopAppBar(
|
||||
title = {
|
||||
@@ -97,6 +103,17 @@ fun StatusTopBar(
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
|
||||
if (isEsp32 && (obuBatteryLow || obuBatteryCritical)) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.BatteryAlert,
|
||||
contentDescription = stringResource(
|
||||
if (obuBatteryCritical) R.string.status_battery_critical else R.string.status_battery_low,
|
||||
),
|
||||
tint = if (obuBatteryCritical) ErrorRed else AmberAcquiring,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
}
|
||||
ObuStatusIcon(mqttConnectionState, isEsp32, esp32LinkState, esp32Bluetooth = esp32Bluetooth)
|
||||
}
|
||||
},
|
||||
|
||||
@@ -15,6 +15,8 @@ import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.BatteryAlert
|
||||
import androidx.compose.material.icons.filled.BatteryFull
|
||||
import androidx.compose.material.icons.filled.Link
|
||||
import androidx.compose.material.icons.filled.LinkOff
|
||||
import androidx.compose.material.icons.filled.Usb
|
||||
@@ -313,6 +315,39 @@ fun ConnectionSetupScreen(
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
// The OBU's own cell (XIAO ESP32-C5 on its battery); absent from older firmware.
|
||||
s.batteryPercent?.let { percent ->
|
||||
val batteryColor = when {
|
||||
s.batteryCritical -> Color(0xFFFF5252)
|
||||
s.batteryLow -> UsbAmber
|
||||
else -> MaterialTheme.colorScheme.onSurfaceVariant
|
||||
}
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
Icon(
|
||||
if (s.batteryLow || s.batteryCritical) Icons.Default.BatteryAlert else Icons.Default.BatteryFull,
|
||||
null,
|
||||
tint = batteryColor,
|
||||
modifier = Modifier.size(14.dp),
|
||||
)
|
||||
Text(
|
||||
stringResource(R.string.conn_esp32_battery, s.batteryMv / 1000.0, percent),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = batteryColor,
|
||||
)
|
||||
}
|
||||
if (s.batteryLow || s.batteryCritical) {
|
||||
Text(
|
||||
stringResource(
|
||||
if (s.batteryCritical) R.string.conn_esp32_battery_critical else R.string.conn_esp32_battery_low,
|
||||
),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = batteryColor,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -330,6 +330,11 @@
|
||||
<string name="conn_esp32_via_ble">über Bluetooth (Passkey 123456 beim ersten Koppeln)</string>
|
||||
<string name="conn_esp32_cancel">Abbrechen</string>
|
||||
<string name="conn_esp32_signing">Signieren %1$s · Tickets %2$d · signiert %3$d · abgelehnt %4$d · gesendet %5$d</string>
|
||||
<string name="conn_esp32_battery">Akku %1$.2f V · etwa %2$d %%</string>
|
||||
<string name="conn_esp32_battery_low">Akku schwach: OBU bald laden.</string>
|
||||
<string name="conn_esp32_battery_critical">Akku kritisch: Das OBU schaltet sich ab, sofern es nicht per USB versorgt wird.</string>
|
||||
<string name="status_battery_low">OBU-Akku schwach</string>
|
||||
<string name="status_battery_critical">OBU-Akku kritisch</string>
|
||||
<string name="conn_esp32_signing_on">an</string>
|
||||
<string name="conn_esp32_signing_off">aus</string>
|
||||
<string name="v2xlog_title">V2X-Datenlogger</string>
|
||||
|
||||
@@ -337,6 +337,11 @@
|
||||
<string name="conn_esp32_via_ble">via Bluetooth (passkey 123456 on first pairing)</string>
|
||||
<string name="conn_esp32_cancel">Cancel</string>
|
||||
<string name="conn_esp32_signing">Signing %1$s · tickets %2$d · signed %3$d · refused %4$d · on air %5$d</string>
|
||||
<string name="conn_esp32_battery">Battery %1$.2f V · about %2$d %%</string>
|
||||
<string name="conn_esp32_battery_low">Low battery: charge the OBU soon.</string>
|
||||
<string name="conn_esp32_battery_critical">Battery critical: the OBU shuts down unless it stays on USB.</string>
|
||||
<string name="status_battery_low">OBU battery low</string>
|
||||
<string name="status_battery_critical">OBU battery critical</string>
|
||||
<string name="conn_esp32_signing_on">on</string>
|
||||
<string name="conn_esp32_signing_off">off</string>
|
||||
<string name="v2xlog_title">V2X data logger</string>
|
||||
|
||||
Reference in New Issue
Block a user