Battery#

Every function each header declares, with the comment the header gives it. The header’s own opening comment is shown as written in the source.

bat_est_core.h#

Source: main/bat_est_core.h

bat_est_core: the battery SoC/SoH estimator's math (EdgeOS AI service "bat", ESP-Mosaico). No IDF, float only:
host-tested in tests/host/test_bat_est.c and checked to 1e-4 against the research agent's test_vectors.csv.
The numbers come from bat_model.h (its contract is at the top of that file).

The filter is the research agent's reference step (carmind-ml experiments/battery_soc: ref_estimator.py and its
float32 port bat_est_host.c), line for line, so the vectors match. With c = I / Q (C-rate, + = charge), z = SoC:
    predict   z  += eta c_avg dt / (3600 soh)                       (coulomb counting; soh = capacity / nominal)
              v1  = a v1 + (1 - a) r1 f(T) c_avg,  a = exp(-dt / tau)   (the RC branch, exact for c constant in dt)
              P   = F P F^T + Q dt,  F = diag(1, a)
    measure   V   = OCV(z) + v1 + r0 f(T) c_inst                      (r0 = r0c charging, r0d discharging)
    correct   H = [dOCV/dz, 1], S = H P H^T + r_v, K = P H^T / S, x += K (V - V_hat), P -= K S K^T
and an optional ridge correction on the output only (never fed back): z_corr = clamp(z + w . (f - mu) inv_sd + b).
soc_user maps z_corr onto the device window [z_lo, z_hi].

The firmware's additions run after the filter step, only with learn on (the vector check runs with learn off):
  mode      from c: rest |c| < BAT_REST_C_RATE, discharge, charge, CV taper (charging at V >= BAT_FULL_V - 30 mV)
  anchors   rest for BAT_REST_MIN_S: z = OCV^-1(V); the end of a CV taper (V >= BAT_FULL_V, c <= BAT_FULL_C_RATE):
            z = 1. Until the first anchor the estimate is "learning".
  capacity  two anchors at least BAT_SOH_MIN_DZ apart: soh sample = Ah counted between them / (dz Q); at least
            BAT_FULL_DZ apart it is also the full-ends count (soh_full, n_full), which bat_soh.h prefers to its model
  DCIR      a current step of at least BAT_DCIR_MIN_DC within one sample: dV / dc (V per C), smoothed; its trend is
            DCIR / the first DCIR this cell gave, and BAT_SOH_RMAP_A + B x trend is the resistance-based SoH flag

Function

Comment in the header

void bat_est_init(bat_est_t *e, float z0, float p0_z, float p0_v, float soh, bool learn);

bat_init of the reference; learn = false for the vector check

void bat_est_boot(bat_est_t *e, const bat_persist_t *saved, float v, float i);

a boot: from the saved values when valid, else z from the OCV of the first sample (v volts, i amps)

void bat_est_step(bat_est_t *e, const bat_in_t *in);

float bat_ocv_v(float z);

float bat_ocv_inv(float v);

z 0..1

uint8_t bat_mode(float c, float v);

c = I / Q

const char *bat_mode_name(uint8_t mode);

“rest”, “discharge”, “charge”, “CV taper”

float bat_soh_pct(const bat_est_t *e);

capacity-based, %

float bat_dcir_ratio(const bat_est_t *e);

DCIR / the first DCIR, 1 before two samples

float bat_soh_r_pct(const bat_est_t *e);

the resistance-based flag, % (BAT_SOH_RMAP)

void bat_est_persist(const bat_est_t *e, bat_persist_t *out);

bool bat_persist_valid(const bat_persist_t *p);

bool bat_model_placeholder(void);

the model, for the glue and the tests

const char *bat_model_id(void);

float bat_model_qnom_ah(void);

float bat_model_p0_z(void);

float bat_model_p0_v(void);

float bat_model_rest_min_s(void);

void bat_model_circuit(float *r0c, float *r0d, float *r1, float *tau_s);

void bat_model_set_ridge(bool on);

the test vectors’ use_ridge column

void bat_model_set_qnom_ah(float ah);

the firmware’s CONFIG_OCM_BAT_NOMINAL_MAH (the vectors keep the header’s)

bat_est.h#

Source: main/bat_est.h

bat_est: the battery SoC/SoH estimator as an OpenCarMind EdgeOS AI service (CONFIG_OCM_BAT_EST). The math is bat_est_core.c;
this is the glue: the gauge sample in (read-only, the board task's existing 2 s poll), the result out for the UI,
the learnt values in NVS ("ocm_bat"/"est", at most every 10 minutes and on the safe-shutdown path), and the battery
log for training data (CONFIG_OCM_BAT_LOG). The gauge is never written: no data flash, no control commands.
2.1.0: the SoH regressor's charge features (bat_soh.h) run in the same step; its reference cycles and the full-ends
count are kept in NVS ("ocm_bat"/"soh") with the same 10-minute rule.

Function

Comment in the header

const ai_svc_def_t *bat_est_service(void);

bool bat_est_read(bat_est_out_t *out);

any task, lock-free; false before the first step

bool bat_est_filter(bat_filt_t *out);

any task, lock-free; false before the first step

bool bat_log_name_valid(const char *name);

the battery log’s file names, bNNNNNN.csv (the USB door’s LIST and GET)

bat_soh.h#

Source: main/bat_soh.h

bat_soh: the battery's state of health from partial charge cycles (OpenCarMind EdgeOS, part of the "bat" AI service on
the ESP-Mosaico). No IDF, no heap: host-tested in tests/host/test_bat_soh.c. The model is the research agent's ridge
regressor (bat_soh_model.h, carmind-ml experiments/battery_soc: p3_soh.py, gen_p3.py); this file computes its eight
features online from the samples bat_est already has, one sample at a time, in fixed memory.

One cycle = a charge and the rest or discharge after it, until the next charge starts. Its features:
  dq_chg_win   Ah charged between 3.9 V and 4.1 V during the constant-current part, over the nominal capacity
  ica_chg_v    the voltage of the dQ/dV peak during that part: Q(V) on a 10 mV grid from 3.60 to 4.15 V (56 floats,
               the charge recorded where the voltage crosses each grid line, linear between two samples), its
               gradient (np.gradient: central differences, one-sided at the ends), a 5-point moving mean, the largest
               |dQ/dV| inside the trimmed grid
  ica_chg_h    the height of that peak (per volt, Q in units of the nominal capacity)
  cv_dur_h     the constant-voltage part's duration (charging at V >= BAT_FULL_V - 30 mV), hours
  cv_tau_h     the CV current's decay constant: least squares of ln(I) on t over the CV samples with I > 0.0067 C,
               tau = -1 / slope, hours
  dcir         the first rest -> load step after the charge (rest |c| < 0.0067 C, then c <= -BAT_SOH_DCIR_C):
               (V_rest - V_120s - (OCV(z_rest) - OCV(z_120s))) / -c_120s, volts per C, 120 s into the load
  T_avg        the mean cell temperature over the cycle
  ekf_ratio    on a discharge that starts full: Ah discharged / Q_nom / (1 - z_EKF) at the first z_EKF <= 0.3
The model takes five of them relative to the cell's own reference: the median of each over the first BAT_SOH_NREF
(10) usable cycles this firmware sees, learnt on the board and kept in NVS by bat_est.c. Until then the source is
"learning (n of 10)". A cycle is usable when all eight features exist: the charge must start at or below 3.60 V and
reach the CV part, so a top-up charge gives no SoH sample (it is counted, not used).

The full-ends coulomb count wins when it exists (0.08 % error in the research, against 1.45 % for the model): a capacity
sample from two anchors at least BAT_SOH_FULL_DZ apart (bat_est_core.c anchor(): rest OCV or full), so a nearly
empty-to-full charge. bat_est_core keeps that count; bat_soh_source() picks.

UNVERIFIED: the model was fitted on lab cells (3 Ah, CC 0.5 C) and its NASA cross-cell test failed; on this 65 mAh cell
its output is a relative figure (the capacity against the first learnt cycles), not an absolute SoH.

Function

Comment in the header

void bat_soh_init(bat_soh_t *s, float qnom_ah, const soh_ref_t *saved);

saved NULL or invalid: learn from scratch

bool bat_soh_ref_valid(const soh_ref_t *r);

bool bat_soh_step(bat_soh_t *s, const soh_in_t *in);

one sample; true when a cycle ended with a new model output (s->ref.last_soh) or a new reference entry

float bat_soh_q_between(const float grid[BAT_SOH_GRID_N], float v1, float v2);

the pure pieces, for the host test against p3_soh.py (q_between, ica_peak) Ah, from the grid

void bat_soh_ica_peak(const float grid_q[BAT_SOH_GRID_N], float *h, float *v);

grid_q in units of Q_nom

float bat_soh_median(const float *x, int n);

np.median of n values

float bat_soh_predict_rel(const soh_ref_t *r, const float raw[BAT_SOH_NRAW], float x_out[BAT_SOH_NRAW]);

uint8_t bat_soh_source(const bat_soh_t *s, uint32_t n_full);

full: the full-ends count exists (n_full > 0)

bat_anom_core.h#

Source: main/bat_anom_core.h

bat_anom_core: the unsupervised battery anomaly detector (OpenCarMind EdgeOS AI service "banom", ESP-Mosaico).
Ported from the research reference (carmind-ml experiments/battery_soc: anom_host.c, ref_anom.py; parameters in
bat_anom_model.h). No IDF, float32, fixed cost, no allocation: host-tested in tests/host/test_bat_anom.c against
anom_vectors.csv to 1e-4.

Per sample it accumulates window statistics; every window (60 samples at 1 Hz in the reference, 60 s of samples on
the board) it forms AN_NF features and scores them three ways:
  robust z     |f - median| / (1.4826 MAD), frugal streaming median and MAD (Ma, Muthukrishnan, Sandler 2013)
  Gaussian     |f - mean| / sd, EWMA mean and variance
  autoencoder  9-4-9 tanh, trained offline on normal windows; input = the Gaussian z clipped to +-5; score = the mean
               squared reconstruction error over the valid features
Only the autoencoder can raise the user-facing alarm (BAT_ANOM_ALARM_MASK = 4): on the held-out benign data it gave
0.0026 false alarms per hour, robust z 0.245 and the Gaussian 0.126, so those two are diagnostics only. An alarm needs
k_consec windows in a row over the threshold, after a warm-up of warmup_win windows (24 h).
Poisoning guard: the statistics are updated only on windows that score below upd_frac of the thresholds, never while
an alarm is active (during the warm-up every window updates, 4x faster).
Firmware additions, which leave the reference's numbers unchanged when samp_s = 1: the sample period (the board's gauge
gives a sample every 2 s, so a 60 s window is 30 samples and the count limits scale with it), and the per-feature
reconstruction error for the alarm's fault class. The detector only raises flags; it never acts on power.

Function

Comment in the header

void an_init(const an_params_t *p, an_state_t *s, float samp_s);

samp_s: the nominal sample period in seconds (1 = the reference)

void an_step(const an_params_t *p, an_state_t *s, float v, float i, float t_c, float dt, int valid, float innov, float ocv_z, float v1, an_out_t *o);

inputs: voltage, current (A, + charge), temperature, dt, valid flag, and the SoC filter’s innovation, OCV(z) and v1

const char *an_class_name(const an_out_t *o);

the fault class of an alarm window: its largest reconstruction error

bat_anom.h#

Source: main/bat_anom.h

bat_anom: the battery anomaly detector as an OpenCarMind EdgeOS AI service (CONFIG_OCM_BAT_ANOM, ESP-Mosaico). The
math is bat_anom_core.c with bat_anom_model.h; this is the glue. Input: the estimator's newest sample and filter
outputs (bat_est_filter, a single-writer snapshot). Output: a lock-free result for the Health app. On an alarm (the
autoencoder, 3 windows in a row after the 24 h warm-up) the board task writes an event; the Health monitor
(health_view.c) shows the banner in plain words. The detector never acts on power. Its statistics are kept in NVS ("ocm_bat"/"anom") every 10 minutes and on the safe-shutdown
path, so the warm-up and the learnt normal survive a restart.

Function

Comment in the header

const ai_svc_def_t *bat_anom_service(void);

bool bat_anom_read(bat_anom_out_t *out);

any task, lock-free

void bat_anom_last_event(char *text, int n, int32_t *age_s);

the last battery event (board task writes it): “” for none, age in s