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:
Ashin Walpola
2026-10-28 16:48:18 +01:00
parent d0fcb45a55
commit 9f77f9f0e4
28 changed files with 955 additions and 31 deletions
+37
View File
@@ -5,6 +5,43 @@ Engineering to-do list. The reviewer-facing open items live in
## Waiting on hardware ## Waiting on hardware
### XIAO ESP32-C5 battery: voltage, low-battery warning, shutdown (added 2026-10-05)
The production board is now a Seeed XIAO ESP32-C5 on COM10 (8 MB flash), on a LiPo with no protection
board. Firmware reads the cell (GPIO6 behind the GPIO26 load switch) every 5 s, puts it in STATUS
(octets 103-105), warns below 3.50 V and deep-sleeps below 3.30 V when no phone is on USB; the app shows
voltage, percentage and the warning. Details: `obu-firmware/FLASHING.md`, "Battery and pins".
Host tests (`make battery`, 6 groups) and the app's 116 unit tests pass; the production image was
flashed to COM10 on 2026-10-05 and `tools/station_status_watch.py COM10` showed 106-octet STATUS with
3998 mV, stable over 18 s. Backup of what COM10 held before: `firmware-backups/COM10-xiao-before-obu-firmware-2026-10-05.bin`.
Needs the XIAO, the cell and a multimeter (shutdown test: also the phone, or just the PC script):
- [ ] **Is the reading right?** (3998 mV before the cell was soldered, 4078 then 4104 mV after, rising as USB charges it.) Measure the cell at the BAT pads with the multimeter while the board runs and
compare with `py -3.11 tools/station_status_watch.py COM10`. Off by more than ~2 %: set
`CONFIG_MICROBU_BATTERY_SCALE_PERMILLE` = 1000 x multimeter / reading (the divider is 2 x 100 k into
the ADC, so a high source impedance can read low). Unplug USB first to see the cell alone: with USB
the charger holds the pin above the cell voltage.
- [x] **Low-voltage shutdown and wake (done 2026-10-05 on COM10, cell soldered):** with the bench image the flags were 0x03 at once, the board stayed up for 85 s while the script talked, then slept 87 s after the script stopped (its port close resets the board, so that is 60 s grace + 30 s) and woke every 30 s, measured 4078 mV < 4100 and went straight back to sleep. A RESET press recovers it. Production image reflashed afterwards (c13c389-dirty, IDF v6.0.2, 4104 mV, flags 0). Original steps. Build with
`CONFIG_MICROBU_BATTERY_WARN_MV=4150`, `SHUTDOWN_MV=4100`, `RESUME_MV=4100`, `SLEEP_S=30` (edit a
copy of `sdkconfig`, `idf.py -B <dir> -DSDKCONFIG=<copy> build`), flash it, then expect:
`station_status_watch.py` shows flags 0x01 (low) at once and 0x03 (critical); the board does NOT
shut down while the script keeps talking; stop the script, wait about 2 minutes (60 s uptime + 30 s
+ sampling): COM10 disappears (deep sleep); it reappears about every 30 s for a moment and goes
away again while the cell reads below RESUME_MV. Then flash the production image again.
- [ ] **App** (BLE checked 2026-10-05 on the Pixel: the card shows "Battery 4.12 V · about 90 %"; USB and the low/critical look still to do): with the phone on the XIAO (USB, then BLE), Settings > Connection > ESP32-C5 shows
"Battery 3.xx V · about N %"; with a bench image whose WARN_MV is above the cell the card turns amber
with "Low battery" and the top bar shows the battery-alert icon.
- [ ] **Does the ADC read disturb the radio, or the radio the reading?** Connect the phone, transmit CAMs
(radio on), and check the STATUS voltage does not jump by more than ~50 mV during TX bursts and
that `radio_failed` stays 0 (the C5's ADC power is shared with the Wi-Fi PHY's power detector).
- [ ] **Charge current and charge time.** The XIAO wiki gives no figure for the SGM40567. Measure the
current into the cell with USB plugged in (multimeter in series in the cell's + wire), and note how
the cell voltage rises. A 5000 mAh cell charged at ~100 mA takes days.
- [ ] **Idle current from the cell** with the radio off (before Connect) and on, to estimate runtime.
- [ ] Decide whether the cell needs a protection board before it goes anywhere but the bench: nothing
protects it from a short, an over-current or a charge outside 0-45 degC.
### On-air check of the V2X data logger (added 2026-10-02) ### On-air check of the V2X data logger (added 2026-10-02)
Needs the phone, a second station sending (the simulated car works) and, for the CiT One part, the OBU. Needs the phone, a second station sending (the simulated car works) and, for the CiT One part, the OBU.
@@ -93,6 +93,7 @@ class MainActivity : AppCompatActivity() {
val useCaseEnabledMap by mqttViewModel.useCaseEnabledMap.collectAsState() val useCaseEnabledMap by mqttViewModel.useCaseEnabledMap.collectAsState()
val obuHardware by mqttViewModel.obuHardware.collectAsState() val obuHardware by mqttViewModel.obuHardware.collectAsState()
val esp32LinkState by mqttViewModel.esp32LinkState.collectAsState() val esp32LinkState by mqttViewModel.esp32LinkState.collectAsState()
val stationStatus by mqttViewModel.stationStatus.collectAsState()
val esp32Transport by mqttViewModel.esp32Transport.collectAsState() val esp32Transport by mqttViewModel.esp32Transport.collectAsState()
val outgoingMessage by mqttViewModel.outgoingMessage.collectAsState() val outgoingMessage by mqttViewModel.outgoingMessage.collectAsState()
val signOutgoing by mqttViewModel.signOutgoing.collectAsState() val signOutgoing by mqttViewModel.signOutgoing.collectAsState()
@@ -163,6 +164,8 @@ class MainActivity : AppCompatActivity() {
isEsp32 = obuHardware == ObuHardware.ESP32_C5, isEsp32 = obuHardware == ObuHardware.ESP32_C5,
esp32LinkState = esp32LinkState, esp32LinkState = esp32LinkState,
esp32Bluetooth = esp32Transport == Esp32Transport.BLE, 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 private const val SCAN_TIMEOUT_MS = 15_000L
/** Long enough for the user to find and type the passkey in the system dialog. */ /** 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 BOND_TIMEOUT_MS = 60_000L
private const val KEY_LAST_ADDRESS = "last_address"
private const val GATT_OP_TIMEOUT_MS = 5_000L private const val GATT_OP_TIMEOUT_MS = 5_000L
/** After a working link dropped: try again soon. */ /** After a working link dropped: try again soon. */
private const val RECONNECT_DELAY_MS = 1_000L 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 scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private val bluetoothManager = context.getSystemService(BluetoothManager::class.java) 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) private val _state = MutableStateFlow(Esp32LinkState.DISCONNECTED)
val state: StateFlow<Esp32LinkState> = _state.asStateFlow() val state: StateFlow<Esp32LinkState> = _state.asStateFlow()
@@ -223,7 +238,10 @@ class BleLinkTransport @Inject constructor(
_state.value = Esp32LinkState.DEVICE_ATTACHED _state.value = Esp32LinkState.DEVICE_ATTACHED
// A bonded micrOBU is reused without scanning: its address is stable (public address), and // A bonded micrOBU is reused without scanning: its address is stable (public address), and
// this is what makes a reconnect after a dropout fast. // 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?)") ?: scan() ?: return fail("No micrOBU advertising nearby (is the phone on its USB port?)")
deviceName = device.name deviceName = device.name
_detail.value = null _detail.value = null
@@ -232,6 +250,7 @@ class BleLinkTransport @Inject constructor(
connected = CompletableDeferred() connected = CompletableDeferred()
gatt = device.connectGatt(context, false, callback, BluetoothDevice.TRANSPORT_LE) gatt = device.connectGatt(context, false, callback, BluetoothDevice.TRANSPORT_LE)
if (withTimeoutOrNull(GATT_OP_TIMEOUT_MS * 2) { connected!!.await() } != true) { if (withTimeoutOrNull(GATT_OP_TIMEOUT_MS * 2) { connected!!.await() } != true) {
if (bonded.size > 1) connectAttempt++
return fail("Could not connect to ${device.name}") 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") if (!enableNotifications(g, uuid)) return fail("Could not subscribe to ${device.name} notifications")
} }
_state.value = Esp32LinkState.CONNECTED _state.value = Esp32LinkState.CONNECTED
connectAttempt = 0
prefs.edit().putString(KEY_LAST_ADDRESS, device.address).apply()
Log.i(TAG, "BLE station link ready: ${device.name}") Log.i(TAG, "BLE station link ready: ${device.name}")
// Wait until the link drops (callback completes `connected` anew with false). // Wait until the link drops (callback completes `connected` anew with false).
val dropped = CompletableDeferred<Boolean>() 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( data class StationStatus(
val uptimeMs: Long, val uptimeMs: Long,
val configured: Boolean, val configured: Boolean,
@@ -235,7 +239,18 @@ data class StationStatus(
val linkMalformed: Long, val linkMalformed: Long,
val potiUpdates: Long, val potiUpdates: Long,
val itsTimeMs: 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. */ /** Signing refusals of every kind: no usable ticket, a pending id change, or a missing permission. */
val signRefused: Long get() = refusedNoTicket + refusedChangePending + refusedPermission + signFailed val signRefused: Long get() = refusedNoTicket + refusedChangePending + refusedPermission + signFailed
@@ -244,10 +259,35 @@ data class StationStatus(
override fun hashCode(): Int = toString().hashCode() override fun hashCode(): Int = toString().hashCode()
companion object { companion object {
/** Octets of the colleague's STATUS body. */
const val SIZE = 103 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? { 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 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 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)) } 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 // c + 56: link_rx_frames
linkCrcErrors = u32(c + 60), linkMalformed = u32(c + 64), potiUpdates = u32(c + 68), linkCrcErrors = u32(c + 60), linkMalformed = u32(c + 64), potiUpdates = u32(c + 68),
itsTimeMs = u64(95), 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.layout.width
import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons 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.GpsFixed
import androidx.compose.material.icons.filled.GpsOff import androidx.compose.material.icons.filled.GpsOff
import androidx.compose.material.icons.filled.Sensors 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.draw.clip
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.hawhamburg.micr0bu.R
import com.hawhamburg.micr0bu.data.mqtt.MqttConnectionState import com.hawhamburg.micr0bu.data.mqtt.MqttConnectionState
import com.hawhamburg.micr0bu.data.transport.Esp32LinkState import com.hawhamburg.micr0bu.data.transport.Esp32LinkState
import com.hawhamburg.micr0bu.viewmodel.SensorUiState import com.hawhamburg.micr0bu.viewmodel.SensorUiState
@@ -58,6 +61,9 @@ fun StatusTopBar(
esp32LinkState: Esp32LinkState = Esp32LinkState.DISCONNECTED, esp32LinkState: Esp32LinkState = Esp32LinkState.DISCONNECTED,
/** The ESP32-C5 is reached over BLE rather than its USB port (Settings). */ /** The ESP32-C5 is reached over BLE rather than its USB port (Settings). */
esp32Bluetooth: Boolean = false, esp32Bluetooth: Boolean = false,
/** The connected ESP32-C5 reports a low cell (amber) or a critical one (red). */
obuBatteryLow: Boolean = false,
obuBatteryCritical: Boolean = false,
) { ) {
TopAppBar( TopAppBar(
title = { title = {
@@ -97,6 +103,17 @@ fun StatusTopBar(
) )
Spacer(Modifier.width(8.dp)) 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) ObuStatusIcon(mqttConnectionState, isEsp32, esp32LinkState, esp32Bluetooth = esp32Bluetooth)
} }
}, },
@@ -15,6 +15,8 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CheckCircle 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.Link
import androidx.compose.material.icons.filled.LinkOff import androidx.compose.material.icons.filled.LinkOff
import androidx.compose.material.icons.filled.Usb import androidx.compose.material.icons.filled.Usb
@@ -313,6 +315,39 @@ fun ConnectionSetupScreen(
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, 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,
)
}
}
} }
} }
+5
View File
@@ -330,6 +330,11 @@
<string name="conn_esp32_via_ble">über Bluetooth (Passkey 123456 beim ersten Koppeln)</string> <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_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_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_on">an</string>
<string name="conn_esp32_signing_off">aus</string> <string name="conn_esp32_signing_off">aus</string>
<string name="v2xlog_title">V2X-Datenlogger</string> <string name="v2xlog_title">V2X-Datenlogger</string>
+5
View File
@@ -337,6 +337,11 @@
<string name="conn_esp32_via_ble">via Bluetooth (passkey 123456 on first pairing)</string> <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_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_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_on">on</string>
<string name="conn_esp32_signing_off">off</string> <string name="conn_esp32_signing_off">off</string>
<string name="v2xlog_title">V2X data logger</string> <string name="v2xlog_title">V2X data logger</string>
@@ -12,6 +12,7 @@ import com.hawhamburg.micr0bu.data.transport.StationStatus
import com.hawhamburg.micr0bu.data.transport.credentialsSegment import com.hawhamburg.micr0bu.data.transport.credentialsSegment
import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue import org.junit.Assert.assertTrue
@@ -107,6 +108,83 @@ class StationLinkTest {
@Test @Test
fun `a STATUS of the wrong length is refused, as the Python decoder does`() { fun `a STATUS of the wrong length is refused, as the Python decoder does`() {
assertNull(StationStatus.decode(ByteArray(StationStatus.SIZE + 1))) assertNull(StationStatus.decode(ByteArray(StationStatus.SIZE + 1)))
assertNull(StationStatus.decode(ByteArray(StationStatus.SIZE + 2)))
assertNull(StationStatus.decode(ByteArray(StationStatus.SIZE - 1)))
}
/** The STATUS body of the Python-encoder test above, without its 4-octet message header. */
private val legacyStatusBody = (
"40e20100010800021122334455b80b49387a4c12eb00010b0000000c0000000d0000000e000000" +
"0f000000100000001100000012000000130000001400000015000000160000001700000018000000" +
"190000001a0000001b0000001c000000fbb2b7ffa6000000"
).hexToBytes()
@Test
fun `a 103 octet STATUS from an older board has no battery`() {
val legacy = legacyStatusBody
assertEquals(StationStatus.SIZE, legacy.size)
val status = StationStatus.decode(legacy)!!
assertEquals(0, status.batteryMv)
assertNull(status.batteryPercent)
assertFalse(status.batteryLow)
assertFalse(status.batteryCritical)
assertEquals(28L, status.potiUpdates)
}
@Test
fun `the battery fields after the 103 octets are decoded`() {
// 3871 mV = 0x0F1F, flags: low
val body = legacyStatusBody + "1f0f01".hexToBytes()
assertEquals(StationStatus.SIZE_WITH_BATTERY, body.size)
val status = StationStatus.decode(body)!!
assertEquals(3871, status.batteryMv)
assertEquals(StationStatus.BATTERY_FLAG_LOW, status.batteryFlags)
assertTrue(status.batteryLow)
assertFalse(status.batteryCritical)
assertEquals(60, status.batteryPercent)
assertEquals(28L, status.potiUpdates)
assertEquals(717_254_800_123L, status.itsTimeMs)
}
@Test
fun `critical flag, and octets of a later extension are tolerated`() {
// 3290 mV = 0x0CDA, flags: low + critical, then two octets of a later extension
val body = legacyStatusBody + "da0c03aabb".hexToBytes()
val status = StationStatus.decode(body)!!
assertEquals(3290, status.batteryMv)
assertTrue(status.batteryLow)
assertTrue(status.batteryCritical)
assertEquals(0, status.batteryPercent)
}
@Test
fun `half a battery field is malformed`() {
assertNull(StationStatus.decode(legacyStatusBody + "1f".hexToBytes()))
assertNull(StationStatus.decode(legacyStatusBody + "1f0f".hexToBytes()))
}
@Test
fun `battery flags are ignored while no voltage is reported`() {
val body = legacyStatusBody + "000003".hexToBytes()
val status = StationStatus.decode(body)!!
assertFalse(status.batteryLow)
assertFalse(status.batteryCritical)
assertNull(status.batteryPercent)
}
@Test
fun `LiPo percent is monotonic, clamped and anchored`() {
assertEquals(0, StationStatus.lipoPercent(3000))
assertEquals(0, StationStatus.lipoPercent(3300))
assertEquals(5, StationStatus.lipoPercent(3500))
assertEquals(100, StationStatus.lipoPercent(4200))
assertEquals(100, StationStatus.lipoPercent(4300))
var last = -1
for (mv in 3000..4300 step 10) {
val p = StationStatus.lipoPercent(mv)
assertTrue("$mv mV -> $p% went down", p >= last)
last = p
}
} }
@Test @Test
+7 -1
View File
@@ -53,7 +53,13 @@ Main changes against the colleague's firmware:
`V2X_RX` (0x85), whose body is the old `SERIAL_MSG_V2X_RX` payload. `V2X_RX` (0x85), whose body is the old `SERIAL_MSG_V2X_RX` payload.
- **Unsigned sending kept.** The colleague's station refuses unsecured requests; here they go out - **Unsigned sending kept.** The colleague's station refuses unsecured requests; here they go out
with the previous firmware's `geonet.c` header. with the previous firmware's `geonet.c` header.
- **Console on UART0** (CH343, COM3 on the bench); the native USB port carries only link frames. - **Console on UART0** (GPIO11/12; the earlier two-port bench board had a CH343 bridge there, COM3);
the native USB port carries only link frames. The production board is now a **Seeed XIAO ESP32-C5**
(8 MB flash, a single native USB-C port, COM10 on the bench) running from a LiPo on its BAT pads.
- **Battery:** the XIAO's own divider (GPIO6, enabled by GPIO26) is read every 5 s and sent in STATUS
(`battery_mv`, `battery_flags`, octets 103-105); the app shows the voltage, a rough percentage and a
low/critical warning on the ESP32-C5 card and in the top bar. Below 3.30 V with no phone on USB the
board deep-sleeps, because the prototype cell has no protection board. See `obu-firmware/FLASHING.md`.
- **BLE pauses advertising while USB is in use** (BLE and ITS-G5 share one RF front end). - **BLE pauses advertising while USB is in use** (BLE and ITS-G5 share one RF front end).
- **NVS 80 KB instead of 24 KB**, app at 0x20000. At 24 KB the BLE bond could not be stored and the - **NVS 80 KB instead of 24 KB**, app at 0x20000. At 24 KB the BLE bond could not be stored and the
phone had to pair on every connection. phone had to pair on every connection.
+76 -9
View File
@@ -1,5 +1,12 @@
# obu-firmware — setup & flashing notes # obu-firmware — setup & flashing notes
**Board (since 2026-10-05): Seeed XIAO ESP32-C5.** One USB-C port, which is the chip's native USB
Serial/JTAG (VID/PID 0x303A/0x1001); no UART bridge, no second port. 8 MB flash (`esptool flash-id`),
so `sdkconfig.defaults` sets `FLASHSIZE_8MB` (the earlier CH343 bench board had 16 MB). The same
port flashes the board *and* carries the phone's station link, so the PC and the phone take turns on
it. Pin map and what is wired: "Battery and pins" below. The sections that still say "UART-bridge
port" or "COM3" describe the earlier two-port bench board.
## Two toolchains - use a dedicated terminal for each ## Two toolchains - use a dedicated terminal for each
Since 2026-09-23 this project builds against ESP-IDF **6.0.2** exactly Since 2026-09-23 this project builds against ESP-IDF **6.0.2** exactly
@@ -36,18 +43,25 @@ idf.py --version # v6.0.2
## Build & flash ## Build & flash
Flash over the board's **UART-bridge port** (CH343; COM3 for the production OBU The XIAO flashes over its one USB-C port (COM10 on the bench; Device Manager → Ports shows it as
on the bench), not the native port the phone uses. "USB Serial Device"). esptool resets it into the bootloader by itself; no BOOT button is needed
unless the running firmware has crashed the USB peripheral, then hold BOOT while plugging in.
```powershell ```powershell
cd C:\Users\Ashin\AndroidStudioProjects\MicrOBU\obu-firmware cd C:\Users\Ashin\AndroidStudioProjects\MicrOBU\obu-firmware
idf.py set-target esp32c5 # only needed once per clean build folder idf.py set-target esp32c5 # only needed once per clean build folder
idf.py build idf.py build
idf.py -p COM3 -b 921600 flash monitor idf.py -p COM10 -b 921600 flash
``` ```
Swap `COM3` for whatever port the ESP32-C5's bridge enumerates as (Device Manager → There is **no console on this port**: ESP_LOG stays on UART0 (GPIO11/GPIO12 = pads D6/D7), which a
Ports). `monitor` opens the serial console after flashing — `Ctrl+]` to exit. bare XIAO does not route to USB, and `idf.py monitor` would only see the link frames. To read the
log, put a 3.3 V USB-UART adapter on D6 (TX) / D7 (RX), or set `CONFIG_MICROBU_LOG_OVER_LINK=y`
(LOG frames of type 0x7F on the link; the Android app has not been checked against them). To read
what the board says over the link, use `tools/station_status_watch.py COM10`.
The earlier two-port board flashed through its CH343 bridge port (COM3) with
`idf.py -p COM3 -b 921600 flash monitor`; its console was on that port.
Use `flash` (bootloader + partition table + app), not `app-flash`, whenever the Use `flash` (bootloader + partition table + app), not `app-flash`, whenever the
partition table may differ from what the board has. partition table may differ from what the board has.
@@ -58,8 +72,8 @@ The partition table changed with the port (NVS 24 KB → 80 KB, app 0x10000 →
behind. Erase the whole new NVS range once, then do a full flash: behind. Erase the whole new NVS range once, then do a full flash:
```powershell ```powershell
python -m esptool --chip esp32c5 -p COM3 -b 921600 erase-region 0x9000 0x15000 python -m esptool --chip esp32c5 -p COM10 -b 921600 erase-region 0x9000 0x15000
idf.py -p COM3 -b 921600 flash idf.py -p COM10 -b 921600 flash
``` ```
Without the erase, the board cannot store the BLE bond and the phone has to pair Without the erase, the board cannot store the BLE bond and the phone has to pair
@@ -103,9 +117,14 @@ can come back two ways. The app detects it and falls back to its protocol.
idf.py build idf.py build
``` ```
## Connecting the phone (ESP32-C5-WIFI6-KIT) ## Connecting the phone (XIAO ESP32-C5)
The board has two USB-C ports — use the right one: The XIAO has a single USB-C port, the native USB Serial/JTAG one: the phone plugs into it via
USB-OTG, the station link runs over it (below), and unplugging the phone and plugging the PC in
is how it is flashed. Over BLE the phone does not need the cable at all (the board runs on its cell).
The rest of this section describes the earlier **ESP32-C5-WIFI6-KIT** bench board with two USB-C
ports — use the right one:
- **Native USB-C port** (labeled for JTAG/native USB, up to 12 Mbps) — this - **Native USB-C port** (labeled for JTAG/native USB, up to 12 Mbps) — this
is where the phone plugs in via USB-OTG. The station link is where the phone plugs in via USB-OTG. The station link
@@ -168,6 +187,54 @@ the first time: passkey **123456** (fixed in `simple_ble.cpp`). The bond is kept
on both sides; the board keeps one bond, so pairing a second phone or a PC on both sides; the board keeps one bond, so pairing a second phone or a PC
replaces the first. Log lines on the console start with `cits_ble:`. replaces the first. Log lines on the console start with `cits_ble:`.
## Battery and pins (XIAO ESP32-C5)
The prototype runs on the 3.7 V LiPo of an Intenso XS5000 power bank (5000 mAh), on the XIAO's BAT
pads: cell `+` through a slide switch to **BAT+**, cell `−` to **BAT−**. The board's SGM40567 charger
charges it from USB (the phone, or the PC). Check the polarity with a multimeter before connecting:
reversed, the cell destroys the board. **The cell has no protection board** (the power bank's own
circuit board did that job), so nothing but the firmware stops an over-discharge, and nothing at all
stops a short.
| Pin | GPIO | Used for |
|---|---|---|
| (back pad) | GPIO6 | `BAT_VOLT_PIN`: the cell through two 100 kΩ resistors (ADC1) |
| (back pad) | GPIO26 | `BAT_VOLT_PIN_EN`: load switch that powers that divider, high only while measuring |
| D6 / D7 | GPIO11 / GPIO12 | UART0 (console) |
| native USB | GPIO13 / GPIO14 | USB D− / D+ (the phone link) |
| — | GPIO27 | the yellow user LED, active low; `CONFIG_MICROBU_TX_LED_GPIO=27` turns the activity LED on |
(Pin names from Seeed's XIAO ESP32-C5 wiki; GPIO13/14 and the LED are the chip's defaults, not
re-checked against the schematic.) The cell's two extra wires (temperature / ID) are not used.
What the firmware does with it (`battery.cpp`, `battery_monitor.hpp`):
- Every 5 s it enables the divider, takes the median of 16 samples, disables it, and smooths the
result. The cell voltage (twice the pin voltage) goes into the STATUS message the board sends
every second over USB and BLE: `battery_mv` u16 at octet 103 (0: no cell or no sensor) and
`battery_flags` u8 at 105 (bit 0 low, bit 1 critical). STATUS grew from 103 to 106 octets; the
app and the firmware both accept 103 (older board) or 106 and more. The colleague's Python
`Status.decode` requires exactly 103, so their `phone_emulator` rejects this board's STATUS.
- **Low** below 3.50 V (cleared at 3.60 V): the app shows an amber battery icon in the top bar and a
warning on the ESP32-C5 card. **Critical** below 3.30 V: red.
- **Shutdown:** when the smoothed voltage has stayed below 3.30 V for 30 s (6 samples), more than
60 s after boot, and **no phone has sent a frame over USB in the last 10 s**, the board sends a
last STATUS with the critical flag and goes into deep sleep. A phone on USB powers the board, so
the cell is not the reason it would stop and no shutdown happens. In deep sleep the board wakes
every 300 s, measures, and sleeps again until the cell reads 3.60 V (charged over USB); a reset
or power-cycle starts it normally and the rule applies again.
- The battery percentage in the app is a LiPo open-circuit-voltage table (`StationStatus.lipoPercent`):
an indicator, not a fuel gauge. It sags under TX and rises while charging.
All thresholds are `CONFIG_MICROBU_BATTERY_*` in `main/Kconfig.projbuild`. If the app's voltage
differs from a multimeter on the cell, set `CONFIG_MICROBU_BATTERY_SCALE_PERMILLE` to
1000 × multimeter ÷ reading. Check it with `py -3.11 tools/station_status_watch.py COM10`: it
requests STATUS once a second and prints the battery fields.
Not measured yet: the charge current of the XIAO's charger (the wiki does not give it; a 5000 mAh
cell on a trickle charge takes days), whether the ADC reading is disturbed while the radio is
transmitting, and the board's own idle current from the cell. See TODO.md.
## Notes ## Notes
- No `git submodule update` needed here — obu-firmware has no pinned - No `git submodule update` needed here — obu-firmware has no pinned
+10 -4
View File
@@ -27,9 +27,10 @@ Changed or added for this project (search for `MicrOBU:` in the sources):
Here a request with GN security profile 1 goes out with the previous firmware's `geonet.c` header Here a request with GN security profile 1 goes out with the previous firmware's `geonet.c` header
and the position of the last PoTi (`Station::unsecured_request`); the app's "Sign outgoing and the position of the last PoTi (`Station::unsecured_request`); the app's "Sign outgoing
messages" setting decides per message. messages" setting decides per message.
- **Console on UART0.** ESP_LOG stays on the CH343 bridge port (COM3 on the bench); the native port - **Console on UART0.** ESP_LOG stays on UART0 (GPIO11/12, pads D6/D7 on the XIAO); the native port
carries only link frames. The colleague's single-port board routes the log into LOG frames there carries only link frames. The earlier bench board had a CH343 bridge on UART0 (COM3); the XIAO has
(`CONFIG_MICROBU_LOG_OVER_LINK`, off here). none, so its log is invisible unless a UART adapter is attached. The colleague's single-port board
routes the log into LOG frames on the native port (`CONFIG_MICROBU_LOG_OVER_LINK`, off here).
- **BLE pauses while USB is in use** (`CONFIG_MICROBU_BLE_USB_IDLE_MS`, 3 s): BLE and ITS-G5 share - **BLE pauses while USB is in use** (`CONFIG_MICROBU_BLE_USB_IDLE_MS`, 3 s): BLE and ITS-G5 share
the C5's one RF front end. Whether a live BLE connection disturbs 5.9 GHz is still unmeasured the C5's one RF front end. Whether a live BLE connection disturbs 5.9 GHz is still unmeasured
(TODO.md). (TODO.md).
@@ -38,7 +39,12 @@ Changed or added for this project (search for `MicrOBU:` in the sources):
- The Wi-Fi RX callback's 2.4 KB capture buffer is static rather than on the driver task's stack - The Wi-Fi RX callback's 2.4 KB capture buffer is static rather than on the driver task's stack
(the previous firmware's commit 04b0076 fixed the same risk). (the previous firmware's commit 04b0076 fixed the same risk).
- Manual country policy and the TX-power read-back from the previous firmware's radio bring-up. - Manual country policy and the TX-power read-back from the previous firmware's radio bring-up.
- The activity LED (GPIO27 on the colleague's XIAO board) is off unless configured. - The activity LED (GPIO27 on the XIAO) is off unless configured (`CONFIG_MICROBU_TX_LED_GPIO`).
- **Production board is the XIAO ESP32-C5 (2026-10-05):** 8 MB flash, one native USB-C port, flashed
on COM10 on the bench. Battery: STATUS carries `battery_mv`/`battery_flags` (octets 103-105, a
MicrOBU extension; decoders accept 103 or >= 106 octets) and the board deep-sleeps below 3.30 V
when no phone is on USB, to protect a cell with no protection board. Details and thresholds:
FLASHING.md, "Battery and pins".
Credentials: the app ships `assets/demo-chain.vcr`, a throwaway chain generated 2026-09-23 with the Credentials: the app ships `assets/demo-chain.vcr`, a throwaway chain generated 2026-09-23 with the
colleague's `vidf_issue` (root `6E7D0374FB021901`, AA `B3312F29844299E0`, AT `B80B49387A4C12EB` colleague's `vidf_issue` (root `6E7D0374FB021901`, AA `B3312F29844299E0`, AT `B80B49387A4C12EB`
+2 -2
View File
@@ -12,11 +12,11 @@
# Still compiled by the host tests in test/host. # Still compiled by the host tests in test/host.
# tx_custom.c/.h - previous copy of the OpenTrafficMap raw TX; otm_tx_custom.c replaces it. # tx_custom.c/.h - previous copy of the OpenTrafficMap raw TX; otm_tx_custom.c replaces it.
# denm.c/.h, cam.c/.h, wifi_patches.c - reference only, as before. # denm.c/.h, cam.c/.h, wifi_patches.c - reference only, as before.
idf_component_register(SRCS "app_main.cpp" "board_controls.cpp" "simple_ble.cpp" "c5_radio.cpp" "otm_tx_custom.c" idf_component_register(SRCS "app_main.cpp" "board_controls.cpp" "battery.cpp" "simple_ble.cpp" "c5_radio.cpp" "otm_tx_custom.c"
"link_protocol.cpp" "serial_link.cpp" "station.cpp" "station_test.cpp" "link_protocol.cpp" "serial_link.cpp" "station.cpp" "station_test.cpp"
"link_service.cpp" "test_channel.cpp" "link_service.cpp" "test_channel.cpp"
"gn_unwrap.c" "geonet.c" "gn_unwrap.c" "geonet.c"
INCLUDE_DIRS "." INCLUDE_DIRS "."
LDFRAGMENTS "linker.lf" LDFRAGMENTS "linker.lf"
REQUIRES vanetza-idf esp_wifi esp_phy esp_event bt esp_driver_gpio esp_driver_usb_serial_jtag nvs_flash esp_timer) REQUIRES vanetza-idf esp_wifi esp_phy esp_event bt esp_driver_gpio esp_adc esp_driver_usb_serial_jtag nvs_flash esp_timer)
target_compile_features(${COMPONENT_LIB} PRIVATE cxx_std_17) target_compile_features(${COMPONENT_LIB} PRIVATE cxx_std_17)
+40
View File
@@ -36,4 +36,44 @@ config MICROBU_TX_LED_BLINK_MS
config MICROBU_LED_INVERTED_RX config MICROBU_LED_INVERTED_RX
bool "Inverted LED mode for receiver/bridge (normally ON, blink OFF on packet)" bool "Inverted LED mode for receiver/bridge (normally ON, blink OFF on packet)"
default n default n
config MICROBU_BATTERY_ADC_GPIO
int "Battery voltage ADC GPIO (-1: no battery monitoring)"
range -1 6
default 6
help
The XIAO ESP32-C5 reads its battery on GPIO6 (BAT_VOLT_PIN) through two 100 k resistors.
config MICROBU_BATTERY_EN_GPIO
int "Battery divider enable GPIO"
range 0 28
default 26
help
XIAO ESP32-C5: GPIO26 (BAT_VOLT_PIN_EN) switches the divider on for the reading.
config MICROBU_BATTERY_SCALE_PERMILLE
int "Battery reading trim (1000 = none)"
range 800 1200
default 1000
help
Multiplies the reading. Compare the STATUS battery voltage with a multimeter on the cell
and set this to 1000 * multimeter / reading if the divider or ADC is off.
config MICROBU_BATTERY_WARN_MV
int "Low-battery warning below this cell voltage (mV)"
range 3000 4200
default 3500
config MICROBU_BATTERY_SHUTDOWN_MV
int "Shutdown below this cell voltage (mV), see battery_monitor.hpp"
range 3000 4200
default 3300
help
There is no protection board on the prototype cell, so this is the only guard against
over-discharge. The board shuts down (deep sleep) once the smoothed voltage has stayed below
this for 30 s and no phone is talking over USB; it checks the cell again every
MICROBU_BATTERY_SLEEP_S and runs again from 3600 mV.
config MICROBU_BATTERY_RESUME_MV
int "After a shutdown, run again at or above this cell voltage (mV)"
range 3300 4200
default 3600
config MICROBU_BATTERY_SLEEP_S
int "Seconds between cell checks while shut down"
range 30 3600
default 300
endmenu endmenu
+53
View File
@@ -3,6 +3,8 @@
// enqueues frames. Link messages: implementation/station-link/README.md. // enqueues frames. Link messages: implementation/station-link/README.md.
#include "link_protocol.hpp" #include "link_protocol.hpp"
#include "link_service.hpp" #include "link_service.hpp"
#include "battery.hpp"
#include "battery_monitor.hpp"
#include "board_controls.hpp" #include "board_controls.hpp"
#include "simple_ble.hpp" #include "simple_ble.hpp"
#include "serial_link.hpp" #include "serial_link.hpp"
@@ -30,6 +32,9 @@ struct Incoming {
microbu::serial::Frame frame; microbu::serial::Frame frame;
}; };
constexpr std::int64_t battery_interval_us = 5000000; // one cell sample every 5 s
constexpr std::uint32_t battery_usb_window_ms = 10000; // a USB frame this recently means a phone powers the board
QueueHandle_t frames = nullptr; // FIFO of Incoming* (8 bytes each); frame bytes never enter the queue itself QueueHandle_t frames = nullptr; // FIFO of Incoming* (8 bytes each); frame bytes never enter the queue itself
/// @brief Attempts to heap-allocate an Incoming so it can be pushed onto the frames queue. /// @brief Attempts to heap-allocate an Incoming so it can be pushed onto the frames queue.
@@ -74,6 +79,36 @@ void pause_ble_while_usb_in_use() {
microbu::ble::set_advertising_allowed(!usb_in_use); microbu::ble::set_advertising_allowed(!usb_in_use);
} }
/// @brief MicrOBU: the battery policy with this build's Kconfig thresholds.
microbu::BatteryConfig battery_config() {
microbu::BatteryConfig config;
config.warn_mv = CONFIG_MICROBU_BATTERY_WARN_MV;
config.warn_clear_mv = CONFIG_MICROBU_BATTERY_WARN_MV + 100; // 100 mV of hysteresis
config.shutdown_mv = CONFIG_MICROBU_BATTERY_SHUTDOWN_MV;
config.resume_mv = CONFIG_MICROBU_BATTERY_RESUME_MV;
return config;
}
/// @brief MicrOBU: samples the cell, publishes it in STATUS and powers the board down before the
/// unprotected cell is over-discharged. A phone on USB powers the board itself, so the cell does not
/// force a shutdown while one is talking (see BatteryMonitor::update).
void check_battery(microbu::Battery& battery, microbu::BatteryMonitor& monitor, microbu::LinkService& link) {
const auto now_ms = static_cast<std::uint32_t>(esp_timer_get_time() / 1000);
const auto last_usb = microbu::serial::last_frame_ms();
const bool usb_active = last_usb != 0 && now_ms - last_usb < battery_usb_window_ms;
monitor.update(battery.measure(), usb_active, now_ms);
std::uint8_t flags = 0;
if (monitor.low()) flags |= microbu::link::battery_flag_low;
if (monitor.critical()) flags |= microbu::link::battery_flag_critical;
link.set_battery(monitor.millivolts(), flags);
if (monitor.shutdown_due()) {
ESP_LOGW(TAG, "cell at %u mV and no phone on USB: shutting down", unsigned(monitor.millivolts()));
link.send_status_now(); // the phone sees the critical flag before the link goes away
vTaskDelay(pdMS_TO_TICKS(500));
microbu::Battery::deep_sleep();
}
}
/// @brief FreeRTOS task body: owns the station, link service and board controls. Drains the incoming queue. /// @brief FreeRTOS task body: owns the station, link service and board controls. Drains the incoming queue.
void station_task(void*) { void station_task(void*) {
microbu::Station station; microbu::Station station;
@@ -81,6 +116,9 @@ void station_task(void*) {
microbu::BoardControls controls; microbu::BoardControls controls;
station.on_disseminated([&controls] { controls.blink(); }); station.on_disseminated([&controls] { controls.blink(); });
station.on_received([&controls] { controls.blink(); }); station.on_received([&controls] { controls.blink(); });
microbu::Battery battery;
microbu::BatteryMonitor monitor(battery_config());
std::int64_t next_battery_us = 0;
ESP_LOGI(TAG, "station task ready; the phone/PC configures the station over BLE or USB Serial-JTAG"); ESP_LOGI(TAG, "station task ready; the phone/PC configures the station over BLE or USB Serial-JTAG");
for (;;) { /// main loop: drain the incoming queue, tick the station and link service, tick the controls for (;;) { /// main loop: drain the incoming queue, tick the station and link service, tick the controls
Incoming* incoming = nullptr; Incoming* incoming = nullptr;
@@ -95,12 +133,27 @@ void station_task(void*) {
link.tick(); link.tick();
controls.tick(); controls.tick();
pause_ble_while_usb_in_use(); pause_ble_while_usb_in_use();
if (esp_timer_get_time() >= next_battery_us) {
next_battery_us = esp_timer_get_time() + battery_interval_us;
check_battery(battery, monitor, link);
}
} }
} }
} }
/// @brief Firmware entry point: initializes NVS, watchdog, serial/BLE transports, and starts the station task. /// @brief Firmware entry point: initializes NVS, watchdog, serial/BLE transports, and starts the station task.
extern "C" void app_main() { extern "C" void app_main() {
// MicrOBU: woken from a low-battery shutdown. Judge the cell before anything else starts, and
// go back to sleep unless it has recovered (charged over USB).
if (microbu::Battery::woke_from_battery_sleep()) {
microbu::Battery battery;
const auto millivolts = battery.measure();
if (!microbu::BatteryMonitor(battery_config()).resume_ok(millivolts)) {
ESP_LOGW(TAG, "cell still at %u mV, back to sleep", unsigned(millivolts));
microbu::Battery::deep_sleep();
}
ESP_LOGI(TAG, "cell at %u mV, starting", unsigned(millivolts));
}
// NVS: the credential store (and the Wi-Fi driver's calibration data) // NVS: the credential store (and the Wi-Fi driver's calibration data)
esp_err_t nvs = nvs_flash_init(); esp_err_t nvs = nvs_flash_init();
if (nvs == ESP_ERR_NVS_NO_FREE_PAGES || nvs == ESP_ERR_NVS_NEW_VERSION_FOUND) { if (nvs == ESP_ERR_NVS_NO_FREE_PAGES || nvs == ESP_ERR_NVS_NEW_VERSION_FOUND) {
+100
View File
@@ -0,0 +1,100 @@
#include "battery.hpp"
#include "sdkconfig.h"
#include <algorithm>
#include <driver/gpio.h>
#include <esp_adc/adc_cali.h>
#include <esp_adc/adc_cali_scheme.h>
#include <esp_adc/adc_oneshot.h>
#include <esp_log.h>
#include <esp_rom_sys.h>
#include <esp_sleep.h>
namespace microbu {
namespace {
const char* TAG = "battery";
constexpr int samples = 16;
constexpr std::uint32_t settle_us = 2000; // the load switch and the divider's RC settle in well under this
constexpr int divider = 2; // two equal 100 k resistors on the XIAO ESP32-C5
}
Battery::Battery() {
#if CONFIG_MICROBU_BATTERY_ADC_GPIO < 0
ESP_LOGI(TAG, "battery monitoring disabled");
return;
#endif
gpio_config_t enable = {};
enable.pin_bit_mask = 1ULL << CONFIG_MICROBU_BATTERY_EN_GPIO;
enable.mode = GPIO_MODE_OUTPUT;
if (gpio_config(&enable) != ESP_OK) { ESP_LOGE(TAG, "enable GPIO %d unusable", CONFIG_MICROBU_BATTERY_EN_GPIO); return; }
gpio_set_level(static_cast<gpio_num_t>(CONFIG_MICROBU_BATTERY_EN_GPIO), 0);
adc_unit_t unit;
adc_channel_t channel;
if (adc_oneshot_io_to_channel(CONFIG_MICROBU_BATTERY_ADC_GPIO, &unit, &channel) != ESP_OK) {
ESP_LOGE(TAG, "GPIO %d is not an ADC pin", CONFIG_MICROBU_BATTERY_ADC_GPIO);
return;
}
adc_oneshot_unit_init_cfg_t unit_config = {};
unit_config.unit_id = unit;
adc_oneshot_unit_handle_t adc = nullptr;
if (adc_oneshot_new_unit(&unit_config, &adc) != ESP_OK) { ESP_LOGE(TAG, "ADC unit init failed"); return; }
adc_oneshot_chan_cfg_t channel_config = {};
channel_config.atten = ADC_ATTEN_DB_12; // the divided cell is at most about 2.1 V
channel_config.bitwidth = ADC_BITWIDTH_DEFAULT;
if (adc_oneshot_config_channel(adc, channel, &channel_config) != ESP_OK) {
ESP_LOGE(TAG, "ADC channel config failed");
adc_oneshot_del_unit(adc);
return;
}
#if ADC_CALI_SCHEME_CURVE_FITTING_SUPPORTED
adc_cali_curve_fitting_config_t cali_config = {};
cali_config.unit_id = unit;
cali_config.chan = channel;
cali_config.atten = ADC_ATTEN_DB_12;
cali_config.bitwidth = ADC_BITWIDTH_DEFAULT;
adc_cali_handle_t cali = nullptr;
if (adc_cali_create_scheme_curve_fitting(&cali_config, &cali) == ESP_OK) cali_ = cali;
#endif
if (!cali_) ESP_LOGW(TAG, "no ADC calibration: readings are approximate");
adc_ = adc;
channel_ = static_cast<int>(channel);
}
std::uint16_t Battery::measure() {
if (!adc_) return 0;
auto* adc = static_cast<adc_oneshot_unit_handle_t>(adc_);
gpio_set_level(static_cast<gpio_num_t>(CONFIG_MICROBU_BATTERY_EN_GPIO), 1);
esp_rom_delay_us(settle_us);
int values[samples];
int count = 0;
for (int i = 0; i < samples; ++i) {
int raw = 0;
if (adc_oneshot_read(adc, static_cast<adc_channel_t>(channel_), &raw) != ESP_OK) continue;
int millivolts = 0;
if (cali_) {
if (adc_cali_raw_to_voltage(static_cast<adc_cali_handle_t>(cali_), raw, &millivolts) != ESP_OK) continue;
} else {
millivolts = raw * 3100 / 4095; // uncalibrated 12 dB full scale, roughly
}
values[count++] = millivolts;
}
gpio_set_level(static_cast<gpio_num_t>(CONFIG_MICROBU_BATTERY_EN_GPIO), 0);
if (count < samples / 2) return 0;
std::sort(values, values + count);
const int median = values[count / 2];
const long cell_mv = static_cast<long>(median) * divider * CONFIG_MICROBU_BATTERY_SCALE_PERMILLE / 1000;
return static_cast<std::uint16_t>(std::clamp(cell_mv, 0L, 65535L));
}
void Battery::deep_sleep() {
ESP_LOGW(TAG, "deep sleep for %d s", CONFIG_MICROBU_BATTERY_SLEEP_S);
esp_sleep_enable_timer_wakeup(static_cast<std::uint64_t>(CONFIG_MICROBU_BATTERY_SLEEP_S) * 1000000ULL);
esp_deep_sleep_start();
}
bool Battery::woke_from_battery_sleep() {
return esp_sleep_get_wakeup_cause() == ESP_SLEEP_WAKEUP_TIMER;
}
} // namespace microbu
+28
View File
@@ -0,0 +1,28 @@
#pragma once
// Cell voltage of the XIAO ESP32-C5's battery, read through the board's own divider: GPIO6 (ADC1)
// behind two 100 k resistors, switched on by GPIO26 (a load switch that keeps the divider from
// draining the cell between readings). The policy (warning, shutdown) is in battery_monitor.hpp.
#include <cstdint>
namespace microbu {
class Battery {
public:
/// @brief Configures the enable GPIO and the ADC channel. On failure measure() returns 0.
Battery();
/// @brief Takes one measurement: enables the divider, samples, disables it again. Blocks for a few ms.
/// @return Cell voltage in millivolts, or 0 if the ADC could not be set up or read.
std::uint16_t measure();
/// @brief Puts the board into deep sleep and wakes it after CONFIG_MICROBU_BATTERY_SLEEP_S seconds.
/// Does not return.
[[noreturn]] static void deep_sleep();
/// @return true if this boot is the end of such a sleep (the only timer wake-up the firmware arms).
static bool woke_from_battery_sleep();
private:
void* adc_ = nullptr; // adc_oneshot_unit_handle_t
void* cali_ = nullptr; // adc_cali_handle_t, null when the chip has no calibration
int channel_ = -1;
};
} // namespace microbu
+70
View File
@@ -0,0 +1,70 @@
#pragma once
// Cell-voltage policy for the XIAO ESP32-C5's LiPo: smoothing, the low-battery warning with
// hysteresis, and the decision to shut down. Pure logic with no ESP-IDF dependency, so the host
// tests (test/host/test_battery.cpp) compile this header unmodified.
#include <cstdint>
namespace microbu {
/// @brief Thresholds and timing of the battery policy. Millivolts at the cell, not at the ADC pin.
struct BatteryConfig {
std::uint16_t warn_mv = 3500; ///< low-battery warning below this
std::uint16_t warn_clear_mv = 3600;///< ... and cleared again at or above this (hysteresis)
std::uint16_t shutdown_mv = 3300; ///< shut down below this ...
unsigned shutdown_samples = 6; ///< ... for this many consecutive samples (6 x 5 s = 30 s: rides out TX sag)
std::uint32_t grace_ms = 60000; ///< no shutdown in the first minute after boot
std::uint16_t resume_mv = 3600; ///< after a shutdown the board only runs again at or above this
std::uint16_t valid_min_mv = 2500; ///< a reading outside valid_min..valid_max is "no cell / no sensor"
std::uint16_t valid_max_mv = 4500;
};
/// @brief Turns raw cell-voltage samples into a smoothed value, a warning flag and a shutdown decision.
class BatteryMonitor {
public:
/// @param config Thresholds; the defaults suit a single LiPo cell.
explicit BatteryMonitor(BatteryConfig config = {}) : config_(config) {}
/// @brief Feeds one sample, taken every few seconds.
/// @param mv Cell voltage in millivolts, or 0 when the measurement failed.
/// @param usb_active A phone is talking over USB, so the board is powered from the phone and
/// the cell cannot be the reason it would stop.
/// @param uptime_ms Milliseconds since boot.
void update(std::uint16_t mv, bool usb_active, std::uint32_t uptime_ms) {
if (mv < config_.valid_min_mv || mv > config_.valid_max_mv) {
// No cell (or no sensor): report "not measured" and never shut down on it.
valid_ = false; ema_ = 0; low_ = false; below_ = 0;
return;
}
if (!valid_) { valid_ = true; ema_ = mv; } // first sample after a gap: no ramp from zero
else ema_ = static_cast<std::uint16_t>(ema_ + (static_cast<int>(mv) - static_cast<int>(ema_)) / 4);
if (ema_ < config_.warn_mv) low_ = true;
else if (ema_ >= config_.warn_clear_mv) low_ = false;
if (ema_ < config_.shutdown_mv && !usb_active && uptime_ms >= config_.grace_ms) ++below_;
else below_ = 0;
}
/// @return Smoothed cell voltage in millivolts, 0 while there is no valid reading.
std::uint16_t millivolts() const { return valid_ ? ema_ : 0; }
/// @return true once the cell fell below the warning threshold, until it is back above the clear threshold.
bool low() const { return low_; }
/// @return true while the smoothed voltage is below the shutdown threshold (not yet sustained).
bool critical() const { return valid_ && ema_ < config_.shutdown_mv; }
/// @return true once the cell has stayed below the shutdown threshold with no USB link for long enough.
bool shutdown_due() const { return below_ >= config_.shutdown_samples; }
/// @param mv A single reading taken right after a wake-up.
/// @return true if the board may run: the cell recovered, or there is no valid reading to judge by.
bool resume_ok(std::uint16_t mv) const {
if (mv < config_.valid_min_mv || mv > config_.valid_max_mv) return true;
return mv >= config_.resume_mv;
}
private:
BatteryConfig config_;
std::uint16_t ema_ = 0;
bool valid_ = false;
bool low_ = false;
unsigned below_ = 0;
};
} // namespace microbu
+6 -1
View File
@@ -157,9 +157,11 @@ Bytes encode(const Status& s) {
w.u32(s.radio_submitted); w.u32(s.radio_failed); w.u32(s.radio_received); w.u32(s.radio_dropped); w.u32(s.radio_submitted); w.u32(s.radio_failed); w.u32(s.radio_received); w.u32(s.radio_dropped);
w.u32(s.link_rx_frames); w.u32(s.link_crc_errors); w.u32(s.link_malformed); w.u32(s.poti_updates); w.u32(s.link_rx_frames); w.u32(s.link_crc_errors); w.u32(s.link_malformed); w.u32(s.poti_updates);
w.u64(s.its_time_ms); w.u64(s.its_time_ms);
w.u16(s.battery_mv); w.u8(s.battery_flags);
return w.out; return w.out;
} }
bool decode(const Bytes& body, Status& s) { bool decode(const Bytes& body, Status& s) {
if (body.size() != status_size_base && body.size() < status_size_battery) return false;
Reader r(body); Reader r(body);
s.uptime_ms = r.u32(); s.configured = r.u8(); r.bytes(s.gn_address, 8); r.bytes(s.identifier, 8); s.change_pending = r.u8(); s.tickets = r.u8(); s.uptime_ms = r.u32(); s.configured = r.u8(); r.bytes(s.gn_address, 8); r.bytes(s.identifier, 8); s.change_pending = r.u8(); s.tickets = r.u8();
s.signed_messages = r.u32(); s.refused_no_ticket = r.u32(); s.refused_change_pending = r.u32(); s.refused_permission = r.u32(); s.signed_messages = r.u32(); s.refused_no_ticket = r.u32(); s.refused_change_pending = r.u32(); s.refused_permission = r.u32();
@@ -168,7 +170,10 @@ bool decode(const Bytes& body, Status& s) {
s.radio_submitted = r.u32(); s.radio_failed = r.u32(); s.radio_received = r.u32(); s.radio_dropped = r.u32(); s.radio_submitted = r.u32(); s.radio_failed = r.u32(); s.radio_received = r.u32(); s.radio_dropped = r.u32();
s.link_rx_frames = r.u32(); s.link_crc_errors = r.u32(); s.link_malformed = r.u32(); s.poti_updates = r.u32(); s.link_rx_frames = r.u32(); s.link_crc_errors = r.u32(); s.link_malformed = r.u32(); s.poti_updates = r.u32();
s.its_time_ms = r.u64(); s.its_time_ms = r.u64();
return r.done(); if (!r.ok()) return false;
s.battery_mv = 0; s.battery_flags = 0;
if (r.remaining() >= 3) { s.battery_mv = r.u16(); s.battery_flags = r.u8(); }
return r.ok(); // octets beyond the known fields belong to a later extension
} }
// RESULT // RESULT
+14 -1
View File
@@ -292,9 +292,22 @@ struct Status {
std::uint32_t radio_submitted = 0, radio_failed = 0, radio_received = 0, radio_dropped = 0; std::uint32_t radio_submitted = 0, radio_failed = 0, radio_received = 0, radio_dropped = 0;
std::uint32_t link_rx_frames = 0, link_crc_errors = 0, link_malformed = 0, poti_updates = 0; std::uint32_t link_rx_frames = 0, link_crc_errors = 0, link_malformed = 0, poti_updates = 0;
std::uint64_t its_time_ms = 0; std::uint64_t its_time_ms = 0;
// MicrOBU extension, appended after the colleague's 103 octets: [103] battery_mv u16 (0: not
// measured, no cell or no sensor), [105] battery_flags u8. A 103-octet body (the colleague's
// layout, and this firmware before the battery) still decodes, with these two left at 0.
std::uint16_t battery_mv = 0;
std::uint8_t battery_flags = 0;
}; };
/// battery_flags bits of Status.
constexpr std::uint8_t battery_flag_low = 0x01; ///< cell below the warning threshold
constexpr std::uint8_t battery_flag_critical = 0x02; ///< cell below the shutdown threshold: the board powers down unless a phone is on USB
/// Octets of the STATUS body without / with the MicrOBU battery extension.
constexpr std::size_t status_size_base = 103;
constexpr std::size_t status_size_battery = 106;
/// @param body Raw message body bytes. /// @param body Raw message body bytes.
/// @param out Receives the decoded status. /// @param out Receives the decoded status. Accepts the 103-octet base body and any body of at
/// least 106 octets (trailing octets after the known fields are ignored, so a later
/// extension does not break this decoder); 104 or 105 octets are malformed.
/// @return false if malformed. /// @return false if malformed.
bool decode(const Bytes& body, Status& out); bool decode(const Bytes& body, Status& out);
/// @param value Status to encode. /// @param value Status to encode.
+12
View File
@@ -47,6 +47,8 @@ link::Status LinkService::status() {
value.link_rx_frames = serial_counters.frames + ble_counters.rx_messages; value.link_rx_frames = serial_counters.frames + ble_counters.rx_messages;
value.link_crc_errors = serial_counters.crc_errors; value.link_crc_errors = serial_counters.crc_errors;
value.link_malformed += ble_counters.malformed; value.link_malformed += ble_counters.malformed;
value.battery_mv = battery_mv_;
value.battery_flags = battery_flags_;
return value; return value;
} }
@@ -149,6 +151,16 @@ void LinkService::handle(const link::Bytes& octets, LinkTransport origin) {
} }
} }
void LinkService::set_battery(std::uint16_t millivolts, std::uint8_t flags) {
battery_mv_ = millivolts;
battery_flags_ = flags;
}
void LinkService::send_status_now() {
last_status_us_ = esp_timer_get_time();
broadcast(link::Opcode::STATUS, ++own_sequence_, link::encode(status()));
}
void LinkService::tick() { void LinkService::tick() {
const auto now = esp_timer_get_time(); const auto now = esp_timer_get_time();
if (now - last_status_us_ < 1000000) return; if (now - last_status_us_ < 1000000) return;
+8
View File
@@ -20,6 +20,12 @@ public:
void handle(const link::Bytes& message, LinkTransport origin); void handle(const link::Bytes& message, LinkTransport origin);
/// @brief Periodic work: broadcasts STATUS once a second. /// @brief Periodic work: broadcasts STATUS once a second.
void tick(); void tick();
/// @brief Sets the battery fields of every following STATUS.
/// @param millivolts Cell voltage, 0 if not measured.
/// @param flags link::battery_flag_* bits.
void set_battery(std::uint16_t millivolts, std::uint8_t flags);
/// @brief Broadcasts a STATUS now instead of waiting for the next second.
void send_status_now();
private: private:
/// @brief Encodes and writes one message on the given transport. /// @brief Encodes and writes one message on the given transport.
/// @param transport Transport to write to. /// @param transport Transport to write to.
@@ -46,6 +52,8 @@ private:
link::Bytes bundle_; // credentials being provisioned link::Bytes bundle_; // credentials being provisioned
std::uint16_t bundle_total_ = 0; std::uint16_t bundle_total_ = 0;
std::int64_t last_status_us_ = 0; std::int64_t last_status_us_ = 0;
std::uint16_t battery_mv_ = 0;
std::uint8_t battery_flags_ = 0;
}; };
} // namespace microbu } // namespace microbu
+1 -1
View File
@@ -1,5 +1,5 @@
# Name, Type, SubType, Offset, Size, Flags # Name, Type, SubType, Offset, Size, Flags
# MicrOBU: NVS 80 KB instead of the colleague's 24 KB (their board has 4 MB of flash, this one 16 MB). # MicrOBU: NVS 80 KB instead of the colleague's 24 KB (their board has 4 MB of flash, ours 8 MB: the XIAO ESP32-C5; the earlier bench board had 16 MB).
# NVS holds the BLE bond, the credential bundle and PHY calibration; at 24 KB, with Wi-Fi settings the # NVS holds the BLE bond, the credential bundle and PHY calibration; at 24 KB, with Wi-Fi settings the
# previous firmware had left in it, there was no room for the bond, so the board forgot the phone # previous firmware had left in it, there was no room for the bond, so the board forgot the phone
# after every connection. The app therefore moves from 0x10000 to 0x20000 (64 KB aligned). # after every connection. The app therefore moves from 0x10000 to 0x20000 (64 KB aligned).
1 # Name, Type, SubType, Offset, Size, Flags
2 # MicrOBU: NVS 80 KB instead of the colleague's 24 KB (their board has 4 MB of flash, this one 16 MB). # MicrOBU: NVS 80 KB instead of the colleague's 24 KB (their board has 4 MB of flash, ours 8 MB: the XIAO ESP32-C5; the earlier bench board had 16 MB).
3 # NVS holds the BLE bond, the credential bundle and PHY calibration; at 24 KB, with Wi-Fi settings the
4 # previous firmware had left in it, there was no room for the bond, so the board forgot the phone
5 # after every connection. The app therefore moves from 0x10000 to 0x20000 (64 KB aligned).
+28 -3
View File
@@ -1142,13 +1142,13 @@ CONFIG_ESPTOOLPY_FLASHFREQ="80m"
# CONFIG_ESPTOOLPY_FLASHSIZE_1MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_1MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_2MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_2MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_4MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_4MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_8MB is not set CONFIG_ESPTOOLPY_FLASHSIZE_8MB=y
CONFIG_ESPTOOLPY_FLASHSIZE_16MB=y # CONFIG_ESPTOOLPY_FLASHSIZE_16MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_32MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_32MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_64MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_64MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_128MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_128MB is not set
# default: # default:
CONFIG_ESPTOOLPY_FLASHSIZE="16MB" CONFIG_ESPTOOLPY_FLASHSIZE="8MB"
# default: # default:
# CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE is not set # CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE is not set
# default: # default:
@@ -1199,6 +1199,20 @@ CONFIG_MICROBU_TX_LED_GPIO=-1
CONFIG_MICROBU_TX_LED_BLINK_MS=100 CONFIG_MICROBU_TX_LED_BLINK_MS=100
# default: # default:
# CONFIG_MICROBU_LED_INVERTED_RX is not set # CONFIG_MICROBU_LED_INVERTED_RX is not set
# default:
CONFIG_MICROBU_BATTERY_ADC_GPIO=6
# default:
CONFIG_MICROBU_BATTERY_EN_GPIO=26
# default:
CONFIG_MICROBU_BATTERY_SCALE_PERMILLE=1000
# default:
CONFIG_MICROBU_BATTERY_WARN_MV=3500
# default:
CONFIG_MICROBU_BATTERY_SHUTDOWN_MV=3300
# default:
CONFIG_MICROBU_BATTERY_RESUME_MV=3600
# default:
CONFIG_MICROBU_BATTERY_SLEEP_S=300
# end of micrOBU firmware # end of micrOBU firmware
# #
@@ -1927,6 +1941,17 @@ CONFIG_BT_LE_DFT_CH39_TX_POWER_LEVEL_DBM_EFF=0
CONFIG_EFUSE_MAX_BLK_LEN=256 CONFIG_EFUSE_MAX_BLK_LEN=256
# end of eFuse Bit Manager # end of eFuse Bit Manager
#
# ADC and ADC Calibration
#
# default:
# CONFIG_ADC_ONESHOT_CTRL_FUNC_IN_IRAM is not set
# default:
# CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE is not set
# default:
# CONFIG_ADC_ENABLE_DEBUG_LOG is not set
# end of ADC and ADC Calibration
# #
# Wireless Coexistence # Wireless Coexistence
# #
+3 -3
View File
@@ -5,9 +5,9 @@ CONFIG_COMPILER_CXX_EXCEPTIONS=y
CONFIG_COMPILER_CXX_RTTI=y CONFIG_COMPILER_CXX_RTTI=y
CONFIG_COMPILER_OPTIMIZATION_SIZE=y CONFIG_COMPILER_OPTIMIZATION_SIZE=y
CONFIG_ESP_MAIN_TASK_STACK_SIZE=8192 CONFIG_ESP_MAIN_TASK_STACK_SIZE=8192
# MicrOBU: the production board has 16 MB of flash (esptool reports it); the partition table # MicrOBU: the production board is a Seeed XIAO ESP32-C5 with 8 MB of flash (esptool flash-id reports
# only uses the first 4 MB. # it); the partition table only uses the first 4 MB. The earlier CH343 bench board had 16 MB.
CONFIG_ESPTOOLPY_FLASHSIZE_16MB=y CONFIG_ESPTOOLPY_FLASHSIZE_8MB=y
CONFIG_PARTITION_TABLE_CUSTOM=y CONFIG_PARTITION_TABLE_CUSTOM=y
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
# Network profile: BTP + GeoNetworking, no facilities codecs (the phone builds CAM/VAM) # Network profile: BTP + GeoNetworking, no facilities codecs (the phone builds CAM/VAM)
+13 -3
View File
@@ -2,13 +2,14 @@
# asn1tools under `py -3.11` for the replay check. # asn1tools under `py -3.11` for the replay check.
# #
# make build and run everything: chain, replay, fuzz # make build and run everything: chain, replay, fuzz
# make chain | replay | fuzz one of them # make chain | replay | fuzz | battery one of them
# make fuzz FUZZ_ITER=50000000 FUZZ_SEED=7 a longer or different fuzz run # make fuzz FUZZ_ITER=50000000 FUZZ_SEED=7 a longer or different fuzz run
# make clean remove build/ # make clean remove build/
# #
# The firmware sources are compiled straight from ../../main, never copied. # The firmware sources are compiled straight from ../../main, never copied.
CC = gcc CC = gcc
CXX = g++
PYTHON = python PYTHON = python
PYTHON_ASN1 = py -3.11 PYTHON_ASN1 = py -3.11
FW = ../../main FW = ../../main
@@ -26,11 +27,11 @@ CFLAGS = -std=c11 -O2 -g -Wall -Wextra -Wpedantic -Werror -I$(FW) \
FW_SRCS = $(FW)/geonet.c $(FW)/dot11p.c $(FW)/gn_unwrap.c FW_SRCS = $(FW)/geonet.c $(FW)/dot11p.c $(FW)/gn_unwrap.c
DEPS = test_util.c test_util.h $(FW_SRCS) $(wildcard $(FW)/*.h) DEPS = test_util.c test_util.h $(FW_SRCS) $(wildcard $(FW)/*.h)
.PHONY: all check chain replay fuzz clean .PHONY: all check chain replay fuzz battery clean
all: check all: check
check: chain replay fuzz check: chain replay fuzz battery
$(BUILD): $(BUILD):
mkdir -p $@ mkdir -p $@
@@ -54,5 +55,14 @@ endif
fuzz: $(BUILD)/fuzz_gn_unwrap$(EXE) fuzz: $(BUILD)/fuzz_gn_unwrap$(EXE)
$(BUILD)/fuzz_gn_unwrap$(EXE) $(FUZZ_ITER) $(FUZZ_SEED) $(RECORDINGS) $(BUILD)/fuzz_gn_unwrap$(EXE) $(FUZZ_ITER) $(FUZZ_SEED) $(RECORDINGS)
# Battery policy and the STATUS battery fields: C++17, so its own flags.
CXXFLAGS = -std=c++17 -O2 -g -Wall -Wextra -Wpedantic -Werror -I$(FW)
$(BUILD)/test_battery$(EXE): test_battery.cpp $(FW)/battery_monitor.hpp $(FW)/link_protocol.cpp $(FW)/link_protocol.hpp | $(BUILD)
$(CXX) $(CXXFLAGS) -o $@ test_battery.cpp $(FW)/link_protocol.cpp
battery: $(BUILD)/test_battery$(EXE)
$(BUILD)/test_battery$(EXE)
clean: clean:
rm -rf $(BUILD) rm -rf $(BUILD)
+151
View File
@@ -0,0 +1,151 @@
// Host tests for the battery policy (battery_monitor.hpp) and the STATUS battery extension
// (link_protocol.cpp). No ESP-IDF involved: both sources compile unmodified on the PC.
#include "battery_monitor.hpp"
#include "link_protocol.hpp"
#include <cstdio>
#include <cstdlib>
using namespace microbu;
static int failures = 0;
#define CHECK(cond) do { if (!(cond)) { std::printf("FAIL %s:%d %s\n", __FILE__, __LINE__, #cond); ++failures; } } while (0)
// Feeds the same sample n times, 5 s apart, starting at t_ms.
static void feed(BatteryMonitor& m, std::uint16_t mv, int n, bool usb, std::uint32_t& t_ms) {
for (int i = 0; i < n; ++i) { m.update(mv, usb, t_ms); t_ms += 5000; }
}
static void test_smoothing_and_validity() {
BatteryMonitor m;
CHECK(m.millivolts() == 0); // nothing measured yet
m.update(4100, false, 0);
CHECK(m.millivolts() == 4100); // first sample taken as is, no ramp from zero
m.update(4000, false, 5000);
CHECK(m.millivolts() == 4075); // 1/4 of the step
m.update(0, false, 10000); // failed measurement
CHECK(m.millivolts() == 0 && !m.low() && !m.critical() && !m.shutdown_due());
m.update(4100, false, 15000);
CHECK(m.millivolts() == 4100); // restarts from the new reading
m.update(5200, false, 20000); // implausible: no cell connected
CHECK(m.millivolts() == 0);
}
static void test_warning_hysteresis() {
BatteryMonitor m;
std::uint32_t t = 0;
feed(m, 3700, 3, false, t);
CHECK(!m.low());
feed(m, 3450, 20, false, t);
CHECK(m.low());
feed(m, 3550, 20, false, t); // above the warning threshold but below the clear threshold
CHECK(m.low());
feed(m, 3650, 20, false, t);
CHECK(!m.low());
}
static void test_shutdown_rules() {
{ // sustained low, no USB, after the grace period
BatteryMonitor m;
std::uint32_t t = 120000;
feed(m, 3250, 5, false, t);
CHECK(m.critical() && !m.shutdown_due()); // five samples are not enough
feed(m, 3250, 1, false, t);
CHECK(m.shutdown_due());
}
{ // a phone on USB powers the board: never shut down, and the count restarts
BatteryMonitor m;
std::uint32_t t = 120000;
feed(m, 3250, 5, false, t);
feed(m, 3250, 1, true, t);
CHECK(!m.shutdown_due());
feed(m, 3250, 5, false, t);
CHECK(!m.shutdown_due());
feed(m, 3250, 1, false, t);
CHECK(m.shutdown_due());
}
{ // not within the first minute after boot
BatteryMonitor m;
std::uint32_t t = 0;
feed(m, 3250, 11, false, t); // 0..50 s
CHECK(!m.shutdown_due());
feed(m, 3250, 7, false, t); // 55..85 s: six of them at or past the 60 s grace period
CHECK(m.shutdown_due());
}
{ // a dip that recovers (TX sag) does not count
BatteryMonitor m;
std::uint32_t t = 120000;
feed(m, 3250, 4, false, t);
feed(m, 3900, 10, false, t);
feed(m, 3250, 4, false, t);
CHECK(!m.shutdown_due());
}
{ // a normal cell never trips it
BatteryMonitor m;
std::uint32_t t = 120000;
feed(m, 3800, 100, false, t);
CHECK(!m.shutdown_due() && !m.low() && !m.critical());
}
{ // no cell / no sensor: no shutdown
BatteryMonitor m;
std::uint32_t t = 120000;
feed(m, 0, 100, false, t);
CHECK(!m.shutdown_due());
}
}
static void test_resume() {
BatteryMonitor m;
CHECK(!m.resume_ok(3300));
CHECK(!m.resume_ok(3599));
CHECK(m.resume_ok(3600));
CHECK(m.resume_ok(4100));
CHECK(m.resume_ok(0)); // cannot judge: run
}
static link::Status sample_status() {
link::Status s;
s.uptime_ms = 123456; s.configured = 1; s.tickets = 7; s.signed_messages = 42; s.poti_updates = 9;
s.its_time_ms = 0x0102030405060708ULL;
s.battery_mv = 3871; s.battery_flags = link::battery_flag_low;
return s;
}
static void test_status_protocol() {
const auto body = link::encode(sample_status());
CHECK(body.size() == link::status_size_battery);
CHECK(body.size() == 106);
link::Status d;
CHECK(link::decode(body, d));
CHECK(d.battery_mv == 3871 && d.battery_flags == link::battery_flag_low);
CHECK(d.uptime_ms == 123456 && d.tickets == 7 && d.its_time_ms == 0x0102030405060708ULL);
// the 103-octet layout of the colleague's station (and of this firmware before the battery)
link::Bytes legacy(body.begin(), body.begin() + link::status_size_base);
link::Status l;
l.battery_mv = 999; l.battery_flags = 0xFF;
CHECK(link::decode(legacy, l));
CHECK(l.battery_mv == 0 && l.battery_flags == 0);
CHECK(l.uptime_ms == 123456 && l.its_time_ms == 0x0102030405060708ULL);
// trailing octets of a later extension are ignored; half a field is malformed
link::Bytes longer = body;
longer.push_back(0xEE); longer.push_back(0xEE);
link::Status x;
CHECK(link::decode(longer, x) && x.battery_mv == 3871);
CHECK(!link::decode(link::Bytes(body.begin(), body.begin() + 104), x));
CHECK(!link::decode(link::Bytes(body.begin(), body.begin() + 105), x));
CHECK(!link::decode(link::Bytes(body.begin(), body.begin() + 102), x));
CHECK(!link::decode(link::Bytes(), x));
}
int main() {
test_smoothing_and_validity();
test_warning_hysteresis();
test_shutdown_rules();
test_resume();
test_status_protocol();
if (failures) { std::printf("%d check(s) failed\n", failures); return EXIT_FAILURE; }
std::printf("battery: all checks passed\n");
return EXIT_SUCCESS;
}
+87
View File
@@ -0,0 +1,87 @@
"""Print the micrOBU's STATUS (incl. the battery fields) from its native USB Serial/JTAG port.
py -3.11 tools/station_status_watch.py COM10 [seconds]
Speaks the station-link framing of obu-firmware (0xAA55, type, u16 length, payload, CRC-16/CCITT-FALSE
over type..payload, little endian; frame type 0x10 = LINK) and asks for STATUS once a second. The
board also broadcasts STATUS itself every second. Opening the port resets the board (DTR/RTS), so
the first frames come after the boot. Needs pyserial (the ESP-IDF python env has it).
"""
import struct
import sys
import time
import serial
LINK = 0x10
STATUS_REQUEST = 0x0C
STATUS = 0x84
def crc16(data: bytes) -> int:
crc = 0xFFFF
for b in data:
crc ^= b << 8
for _ in range(8):
crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
return crc
def frame(type_: int, payload: bytes) -> bytes:
head = bytes([type_]) + struct.pack('<H', len(payload)) + payload
return b'\xaa\x55' + head + struct.pack('<H', crc16(head))
def parse(buffer: bytearray):
"""Yield (type, payload) for each complete, CRC-valid frame; consumes the buffer."""
while True:
i = buffer.find(b'\xaa\x55')
if i < 0 or len(buffer) < i + 5:
if i > 0:
del buffer[:i]
return
length = buffer[i + 3] | (buffer[i + 4] << 8)
end = i + 5 + length + 2
if len(buffer) < end:
if i > 0:
del buffer[:i]
return
head, crc = bytes(buffer[i + 2:end - 2]), buffer[end - 2] | (buffer[end - 1] << 8)
del buffer[:end if crc16(head) == crc else i + 2]
if crc16(head) == crc:
yield head[0], head[3:]
def describe(body: bytes) -> str:
uptime, configured = struct.unpack_from('<IB', body, 0)
text = f"len {len(body)} uptime {uptime / 1000:.1f}s configured {configured}"
if len(body) >= 106:
mv, flags = struct.unpack_from('<HB', body, 103)
text += f" battery {mv} mV flags 0x{flags:02x}" + (" LOW" if flags & 1 else "") + (" CRITICAL" if flags & 2 else "")
else:
text += " (no battery fields)"
return text
def main():
port = sys.argv[1] if len(sys.argv) > 1 else 'COM10'
seconds = float(sys.argv[2]) if len(sys.argv) > 2 else 15
buffer = bytearray()
sequence = 0
with serial.Serial(port, 115200, timeout=0.2) as s:
s.dtr = True # a CDC host asserts DTR; the firmware may gate TX on it
end = time.time() + seconds
next_request = 0.0
while time.time() < end:
if time.time() >= next_request:
sequence += 1
s.write(frame(LINK, bytes([STATUS_REQUEST, 0]) + struct.pack('<H', sequence)))
next_request = time.time() + 1.0
buffer += s.read(512)
for type_, payload in parse(buffer):
if type_ == LINK and len(payload) >= 4 and payload[0] == STATUS:
print(time.strftime('%H:%M:%S'), describe(payload[4:]), flush=True)
if __name__ == '__main__':
main()