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:
@@ -1,5 +1,12 @@
|
||||
# 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
|
||||
|
||||
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
|
||||
|
||||
Flash over the board's **UART-bridge port** (CH343; COM3 for the production OBU
|
||||
on the bench), not the native port the phone uses.
|
||||
The XIAO flashes over its one USB-C port (COM10 on the bench; Device Manager → Ports shows it as
|
||||
"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
|
||||
cd C:\Users\Ashin\AndroidStudioProjects\MicrOBU\obu-firmware
|
||||
idf.py set-target esp32c5 # only needed once per clean build folder
|
||||
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 →
|
||||
Ports). `monitor` opens the serial console after flashing — `Ctrl+]` to exit.
|
||||
There is **no console on this port**: ESP_LOG stays on UART0 (GPIO11/GPIO12 = pads D6/D7), which a
|
||||
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
|
||||
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:
|
||||
|
||||
```powershell
|
||||
python -m esptool --chip esp32c5 -p COM3 -b 921600 erase-region 0x9000 0x15000
|
||||
idf.py -p COM3 -b 921600 flash
|
||||
python -m esptool --chip esp32c5 -p COM10 -b 921600 erase-region 0x9000 0x15000
|
||||
idf.py -p COM10 -b 921600 flash
|
||||
```
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
## 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
|
||||
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
|
||||
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
|
||||
|
||||
- No `git submodule update` needed here — obu-firmware has no pinned
|
||||
|
||||
+10
-4
@@ -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
|
||||
and the position of the last PoTi (`Station::unsecured_request`); the app's "Sign outgoing
|
||||
messages" setting decides per message.
|
||||
- **Console on UART0.** ESP_LOG stays on the CH343 bridge port (COM3 on the bench); the native port
|
||||
carries only link frames. The colleague's single-port board routes the log into LOG frames there
|
||||
(`CONFIG_MICROBU_LOG_OVER_LINK`, off here).
|
||||
- **Console on UART0.** ESP_LOG stays on UART0 (GPIO11/12, pads D6/D7 on the XIAO); the native port
|
||||
carries only link frames. The earlier bench board had a CH343 bridge on UART0 (COM3); the XIAO has
|
||||
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
|
||||
the C5's one RF front end. Whether a live BLE connection disturbs 5.9 GHz is still unmeasured
|
||||
(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 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.
|
||||
- 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
|
||||
colleague's `vidf_issue` (root `6E7D0374FB021901`, AA `B3312F29844299E0`, AT `B80B49387A4C12EB`
|
||||
|
||||
@@ -12,11 +12,11 @@
|
||||
# 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.
|
||||
# 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_service.cpp" "test_channel.cpp"
|
||||
"gn_unwrap.c" "geonet.c"
|
||||
INCLUDE_DIRS "."
|
||||
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)
|
||||
|
||||
@@ -36,4 +36,44 @@ config MICROBU_TX_LED_BLINK_MS
|
||||
config MICROBU_LED_INVERTED_RX
|
||||
bool "Inverted LED mode for receiver/bridge (normally ON, blink OFF on packet)"
|
||||
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
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
// enqueues frames. Link messages: implementation/station-link/README.md.
|
||||
#include "link_protocol.hpp"
|
||||
#include "link_service.hpp"
|
||||
#include "battery.hpp"
|
||||
#include "battery_monitor.hpp"
|
||||
#include "board_controls.hpp"
|
||||
#include "simple_ble.hpp"
|
||||
#include "serial_link.hpp"
|
||||
@@ -30,6 +32,9 @@ struct Incoming {
|
||||
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
|
||||
|
||||
/// @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);
|
||||
}
|
||||
|
||||
/// @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.
|
||||
void station_task(void*) {
|
||||
microbu::Station station;
|
||||
@@ -81,6 +116,9 @@ void station_task(void*) {
|
||||
microbu::BoardControls controls;
|
||||
station.on_disseminated([&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");
|
||||
for (;;) { /// main loop: drain the incoming queue, tick the station and link service, tick the controls
|
||||
Incoming* incoming = nullptr;
|
||||
@@ -95,12 +133,27 @@ void station_task(void*) {
|
||||
link.tick();
|
||||
controls.tick();
|
||||
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.
|
||||
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)
|
||||
esp_err_t nvs = nvs_flash_init();
|
||||
if (nvs == ESP_ERR_NVS_NO_FREE_PAGES || nvs == ESP_ERR_NVS_NEW_VERSION_FOUND) {
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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.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.u16(s.battery_mv); w.u8(s.battery_flags);
|
||||
return w.out;
|
||||
}
|
||||
bool decode(const Bytes& body, Status& s) {
|
||||
if (body.size() != status_size_base && body.size() < status_size_battery) return false;
|
||||
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.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.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();
|
||||
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
|
||||
|
||||
@@ -292,9 +292,22 @@ struct Status {
|
||||
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::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 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.
|
||||
bool decode(const Bytes& body, Status& out);
|
||||
/// @param value Status to encode.
|
||||
|
||||
@@ -47,6 +47,8 @@ link::Status LinkService::status() {
|
||||
value.link_rx_frames = serial_counters.frames + ble_counters.rx_messages;
|
||||
value.link_crc_errors = serial_counters.crc_errors;
|
||||
value.link_malformed += ble_counters.malformed;
|
||||
value.battery_mv = battery_mv_;
|
||||
value.battery_flags = battery_flags_;
|
||||
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() {
|
||||
const auto now = esp_timer_get_time();
|
||||
if (now - last_status_us_ < 1000000) return;
|
||||
|
||||
@@ -20,6 +20,12 @@ public:
|
||||
void handle(const link::Bytes& message, LinkTransport origin);
|
||||
/// @brief Periodic work: broadcasts STATUS once a second.
|
||||
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:
|
||||
/// @brief Encodes and writes one message on the given transport.
|
||||
/// @param transport Transport to write to.
|
||||
@@ -46,6 +52,8 @@ private:
|
||||
link::Bytes bundle_; // credentials being provisioned
|
||||
std::uint16_t bundle_total_ = 0;
|
||||
std::int64_t last_status_us_ = 0;
|
||||
std::uint16_t battery_mv_ = 0;
|
||||
std::uint8_t battery_flags_ = 0;
|
||||
};
|
||||
|
||||
} // namespace microbu
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# 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
|
||||
# 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).
|
||||
|
||||
|
+28
-3
@@ -1142,13 +1142,13 @@ CONFIG_ESPTOOLPY_FLASHFREQ="80m"
|
||||
# CONFIG_ESPTOOLPY_FLASHSIZE_1MB is not set
|
||||
# CONFIG_ESPTOOLPY_FLASHSIZE_2MB is not set
|
||||
# CONFIG_ESPTOOLPY_FLASHSIZE_4MB is not set
|
||||
# CONFIG_ESPTOOLPY_FLASHSIZE_8MB is not set
|
||||
CONFIG_ESPTOOLPY_FLASHSIZE_16MB=y
|
||||
CONFIG_ESPTOOLPY_FLASHSIZE_8MB=y
|
||||
# CONFIG_ESPTOOLPY_FLASHSIZE_16MB is not set
|
||||
# CONFIG_ESPTOOLPY_FLASHSIZE_32MB is not set
|
||||
# CONFIG_ESPTOOLPY_FLASHSIZE_64MB is not set
|
||||
# CONFIG_ESPTOOLPY_FLASHSIZE_128MB is not set
|
||||
# default:
|
||||
CONFIG_ESPTOOLPY_FLASHSIZE="16MB"
|
||||
CONFIG_ESPTOOLPY_FLASHSIZE="8MB"
|
||||
# default:
|
||||
# CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE is not set
|
||||
# default:
|
||||
@@ -1199,6 +1199,20 @@ CONFIG_MICROBU_TX_LED_GPIO=-1
|
||||
CONFIG_MICROBU_TX_LED_BLINK_MS=100
|
||||
# default:
|
||||
# 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
|
||||
|
||||
#
|
||||
@@ -1927,6 +1941,17 @@ CONFIG_BT_LE_DFT_CH39_TX_POWER_LEVEL_DBM_EFF=0
|
||||
CONFIG_EFUSE_MAX_BLK_LEN=256
|
||||
# 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
|
||||
#
|
||||
|
||||
@@ -5,9 +5,9 @@ CONFIG_COMPILER_CXX_EXCEPTIONS=y
|
||||
CONFIG_COMPILER_CXX_RTTI=y
|
||||
CONFIG_COMPILER_OPTIMIZATION_SIZE=y
|
||||
CONFIG_ESP_MAIN_TASK_STACK_SIZE=8192
|
||||
# MicrOBU: the production board has 16 MB of flash (esptool reports it); the partition table
|
||||
# only uses the first 4 MB.
|
||||
CONFIG_ESPTOOLPY_FLASHSIZE_16MB=y
|
||||
# MicrOBU: the production board is a Seeed XIAO ESP32-C5 with 8 MB of flash (esptool flash-id reports
|
||||
# it); the partition table only uses the first 4 MB. The earlier CH343 bench board had 16 MB.
|
||||
CONFIG_ESPTOOLPY_FLASHSIZE_8MB=y
|
||||
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
|
||||
# Network profile: BTP + GeoNetworking, no facilities codecs (the phone builds CAM/VAM)
|
||||
|
||||
@@ -2,13 +2,14 @@
|
||||
# asn1tools under `py -3.11` for the replay check.
|
||||
#
|
||||
# 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 clean remove build/
|
||||
#
|
||||
# The firmware sources are compiled straight from ../../main, never copied.
|
||||
|
||||
CC = gcc
|
||||
CXX = g++
|
||||
PYTHON = python
|
||||
PYTHON_ASN1 = py -3.11
|
||||
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
|
||||
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
|
||||
|
||||
check: chain replay fuzz
|
||||
check: chain replay fuzz battery
|
||||
|
||||
$(BUILD):
|
||||
mkdir -p $@
|
||||
@@ -54,5 +55,14 @@ endif
|
||||
fuzz: $(BUILD)/fuzz_gn_unwrap$(EXE)
|
||||
$(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:
|
||||
rm -rf $(BUILD)
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
Reference in New Issue
Block a user