Operating-system layer#

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.

os_core.h#

Source: main/os_core.h

os_core: the pure rules of the mossREV OS layer (ESP-Mosaico, mossREV 2.0.0). No IDF, no heap, no globals that
change: host-tested in tests/host/test_os.c. The firmware glue that acts on these rules is os.c (S31 only).

1. Resets. Every reset somebody or something asks for goes through sys_reset(reason) (os.h). The plan for a reason
   is a fixed sequence, always in this order:
     a. wait pre_ms, so a reply or a log line gets out (0 where the caller already waited),
     b. write the marker: "asked for" (the next boot does not count it toward safe mode) or nothing (a crash path:
        the stall guard and the monitor's restart must count),
     c. quiesce storage: the NOR FAT, then the NAND (sdlog_quiesce_for_reset),
     d. wait post_us (busy wait: the door runs in an esp_timer callback),
     e. reset with the reason's method.
   The marker comes first so that a hang inside the quiesce, which the task watchdog then resets, still reads as
   the reset that was asked for.

2. Runlevels (after PebbleOS's runlevel service). A runlevel is a condition the board is in: Boot (app_main has not
   finished), Safe (3 abnormal resets in a row), Driving (a drive is recorded or the car's computer answers over the
   adapter: os_rl_link_input; owner 2026-11-11, scanning and connecting keep Parked), Saving (the
   UPS state: USB power lost, CONFIG_OCM_UPS), Update (a reset, a door entry or a storage format is running), and
   Parked when none of these holds. Each service has an enable mask over the runlevels. Several conditions can hold
   at once (safe mode while driving), so a service runs only if every active runlevel enables it: each active
   runlevel acts like a circuit breaker. A service never asks which runlevel is in force, it asks os_allows(svc).
   The runlevel shown on the Board page and in the log is the active one highest in the order
   Update > Saving > Driving > Safe > Boot > Parked.

3. Boot health. About a minute after boot (after sched_mon's first summary) the OS combines the model self-test,
   the flash FAT preflight and audit, the NAND mount, the first UI tick, the touch probe and the scheduler summary
   into one verdict. Bad means this firmware image is not fit to keep: no UI tick at all, or safe mode (three
   crashes in a row). Degraded means something works less well than it should but the image runs: a model
   self-test that differs or did not run, a repaired or damaged store, no NAND, touch failing, deadline misses or
   stalls, a failed response-time analysis, a slow first frame. Good is everything else. A damaged store is not
   Bad: older firmware would not repair the data, so it is no reason to go back to it.
   The Wi-Fi boot hold: the boot window is the internal-RAM low point (R11b: 57.7 KB lowest while the Wi-Fi driver
   started at boot), so the board starts no Wi-Fi at boot. The automatic start (the Wi-Fi task and its first clock
   round) waits for the verdict and goes ahead on Good or Degraded, the verdicts that also confirm an A/B image (the
   image runs); Pending and Bad hold it for this boot. The owner's own start (Sync clock now, the Wi-Fi app's search
   and join) is never held.

4. Model admission by response-time analysis. Fixed-priority tasks i with worst-case CPU time C_i, period T_i and
   deadline D_i on one core. Task i's worst-case response time R_i is the smallest fixed point of
       R = C_i + sum over higher-priority tasks j on the same core of ceil(R / T_j) * C_j
   (Joseph and Pandya 1986), found by iterating from R = C_i. Task i is schedulable when R_i <= D_i. The sum counts
   how many times each higher-priority task can be released inside a window of length R and charges its full C_j for
   each release: the critical instant, all tasks released together. Equal priorities do not interfere here, as in
   sched_mon.c. A model is admitted on a switch or a load only if every task on its core still meets its deadline when
   the model's C is its measured self-test run times OS_ADMIT_FACTOR_PM / 1000. The factor is a safety margin: one
   measured run is not a worst case (cache state, PSRAM contention). The recurrence assumes D_i <= T_i or, for a
   job with a longer deadline (the R.E.V learner, D 30 s, T 1 s), that its R_i stays below T_i, which the log shows.

5. AI service contract. Every model and learner declares, in one table (os_ai_contract): its period, deadline and
   stall limit (sched_mon), its CPU reservation (sched_mon's token bucket: share per mille of a core, burst ms; 0 =
   none, a model is admitted by the analysis instead), its self-test, its fallback model and the runlevel service
   whose mask decides when it may run. The firmware registers the jobs from the table (os_ai_apply), the admission
   takes its period, deadline, priority and core from it, and ml_init falls back along it.

6. UPS power state (CONFIG_OCM_UPS, default n until measured on the board). The board runs from the car's USB and
   has a 65 mAh cell. USB loss is seen in the gauge's current: the BQ27220 reports discharge as a negative current
   (TI's sign convention; on this board UNVERIFIED until measured). The HUSB320 Type-C controller is not on I2C0 in
   the board's user guide (no address listed) and has no VBUS line to a GPIO, so VBUS_DET is not used. States:
     USB      on car power.
     GRACE    the current has been below -discharge_ma for two samples in a row: flush the logs, dim the screen, and
              wait grace_ms, because cranking the engine drops the USB rail for a few seconds. USB back (current
              above -5 mA) returns to USB and restores the screen.
     OFF      grace ran out on battery: sys_reset(POWER_OFF) quiesces storage and pulls GPIO57 (the SAM8108
              POWER_SWITCH request, documented as open-drain low = shutdown) or, without that, deep sleep.
   A hard floor: at or below floor_mv on battery the board goes to OFF at once, from any state, before a brownout
   can tear a write. GRACE is the Saving runlevel.

7. Degradation ladder (mixed-criticality style). Every 10 s the OS reads the ml job's deadline misses, and the misses
   of the jobs that only the AI services' rung answers (the UI, the AI worker and its services: ai_svc.c). A window
   with a new ml miss climbs one rung; a window with only AI-side misses climbs to rung 1 at most. Six clean windows
   in a row (a minute) step one rung down, so the rungs come back in reverse order:
     0 normal,
     1 the AI services slowed: every ai_svc service runs at period x10 and their learned heads are off (the battery
       estimator's ridge correction); built, not yet checked on the board,
     2 the UI refresh period goes from 16 to 33 ms (half the frames, LVGL's own timer); the AI services pause,
     3 the R.E.V learner's CPU reservation drops to 1 per mille (it pauses, its learned values stay),
     4 the model's inference pauses (windows are skipped, the same model stays loaded).
   The ladder never changes which model is loaded: no model switch while driving is the owner's rule, and a switch
   while parked stays the owner's own action. Rung 4 is left only when parked, so the model does not go on and off
   during one drive.

8. Battery safety. The charger (TP4057) has no enable pin and no thermistor input, and its supply (VCHG) comes from
   VBUS and the module 5 V through diodes (core schematic V1.2.1, Power page), so the firmware cannot stop or limit
   charging. It can only watch the gauge (BQ27220: no thermistor ball on this board, so Temperature() is the gauge's
   own sensor next to the cell, not the cell itself) and lower the board's own heat, and stop cleanly. Every 2 s:
     HOT      at or above warn_dc while on USB for `confirm` samples: shed load (the Saving runlevel stops Wi-Fi
              and the learner and refuses changes, the screen dims, the CPU clock drops if power management is
              built in), a warning. Back to OK at or below clear_dc (warn minus the hysteresis) for `confirm`
              samples.
     CRIT     at or above crit_dc, on USB or not, for `confirm` samples: a safe stop (logs flushed and storage
              quiesced, the Saving runlevel held, the screen off; power off through sys_reset when the GPIO57
              power-off is enabled). Ends with a restart once it is back at or below crit_dc minus the hysteresis
              for `cool_n` samples.
     OVERVOLT the cell at or above ov_mv (the charger's 4.2 V plus tolerance) for `confirm` samples: the same safe
              stop, logged as a charger fault. It ends only with a restart by the owner.
   A reading outside -40..100 C, or 0 mV, is a glitch: it neither counts toward nor resets a confirmation.

Function

Comment in the header

const os_reset_plan_t *os_reset_plan(sys_reset_reason_t r);

NULL for an unknown reason

int os_reset_steps(sys_reset_reason_t r, uint8_t steps[5]);

The steps in execution order (OS_STEP_*), steps that do nothing left out. Returns the count (<= 5).

uint8_t os_rl_active(const os_rl_in_t *in);

bit r set: runlevel r is active (Parked alone if none)

os_runlevel_t os_rl_primary(uint8_t active);

the one to show

bool os_rl_allows(uint8_t active, os_svc_t svc);

every active runlevel enables svc

os_runlevel_t os_rl_blocker(uint8_t active, os_svc_t svc);

the highest active runlevel that refuses, or OS_RL_N

uint8_t os_svc_mask(os_svc_t svc);

bit r: svc runs in runlevel r

const char *os_rl_name(os_runlevel_t r);

“Parked”, “Driving”, …

const char *os_rl_phrase(os_runlevel_t r, const os_rl_in_t *in);

a short phrase for a refusal by runlevel r: “a drive is running”, “the car link is up” (Driving without a drive), “safe mode is on”, “the board is starting”, “the board is saving power”, “an update or format is running”

const char *os_svc_name(os_svc_t svc);

bool os_rl_link_input(ble_state_t ble);

the car-link input of the runlevels from the Bluetooth state: true only when the adapter is linked AND the car’s computer answered (BLE_ST_LOGGING: elm327.c sets it after the first valid 0100 answer and the PID lists). Scanning, connecting, reading services, the adapter’s start-up with a silent computer (ignition off) and a locked adapter keep Parked. Read by sys_mode.c on the ESP-Mosaico; the masks are unchanged.

uint8_t os_health_verdict(const os_health_in_t *in, uint16_t *flags);

OS_H_GOOD / DEGRADED / BAD and why

uint8_t os_rollback_decision(bool pending_verify, uint8_t verdict);

bool os_wifi_may_start(uint8_t verdict, bool owner);

The Wi-Fi boot hold: may Wi-Fi start now? owner = the owner asked from the screen (Settings, the Wi-Fi app).

const char *os_health_name(uint8_t verdict);

“pending”, “good”, “degraded”, “bad”

int os_health_text(uint8_t verdict, uint16_t flags, char *buf, size_t n);

“good” or “degraded: model self-test differs, NAND not mounted” (truncated to n)

int os_rta(const os_rt_task_t *t, int n, int core, uint32_t *r_us);

R_i for every task on ‘core’ (OS_RTA_MISS when it passes D_i or does not converge; 0 for tasks elsewhere). Returns the number of tasks on that core that miss.

bool os_admit(const os_rt_task_t *set, int n, const os_rt_task_t *cand, uint32_t measured_us, uint32_t factor_pm, os_admit_t *out);

The set without the candidate’s old entry, plus the candidate with C = measured_us x factor_pm / 1000.

const os_ai_contract_t *os_ai_contract(int id);

NULL for an unknown id

int os_ai_check(const os_ai_contract_t *t, int n, char *why, size_t why_n);

The table’s rules (host-tested): sane times, a reservation with a burst, fallbacks to models only and without a cycle, models that share a job declare the same timing. Returns the number of broken rules (why: the first).

uint8_t os_ups_step(os_ups_t *u, const os_ups_cfg_t *c, bool ok, int16_t ma, uint16_t mv, uint32_t now_ms);

One gauge sample (every 2 s). ok = false: the gauge did not answer, nothing changes. Returns OS_UPS_A_* to do now.

const char *os_ups_name(uint8_t state);

uint8_t os_ladder_step(os_ladder_t *l, uint32_t ml_misses, uint32_t ai_misses, bool driving);

one 10 s window: ml_misses = the ml job’s miss counter so far, ai_misses = the AI-side counter so far (0 without AI services). Returns the level now.

const char *os_ladder_name(uint8_t level);

uint8_t os_bat_step(os_bat_t *b, const os_bat_cfg_t *c, bool ok, int16_t temp_dc, uint16_t mv, bool on_usb);

one gauge sample: temp in 0.1 C, the cell voltage, whether USB powers the board. Returns OS_BAT_A_* to do now.

const char *os_bat_name(uint8_t state);

uint8_t os_bq_checksum(uint16_t addr, const uint8_t *data, int n);

the data-memory block checksum: 0xFF minus the 8-bit sum of the two address bytes and the data bytes

uint16_t os_bq_design_energy(uint16_t mah, uint16_t nominal_mv);

mWh = mAh x V

bool os_bq_cal_ok(uint16_t dm_cap, uint16_t std_cap, uint16_t dm_energy, uint16_t target_mah);

the pre-write checks: the data-memory Design Capacity read must equal the standard command’s DesignCapacity(), and the stored Design Energy must be 3.4 to 4.0 times it (a 3.6-3.85 V cell), else the addresses are not the ones the code assumes and nothing is written. target 20..5000 mAh.

os.h#

Source: main/os.h

os: the mossREV OS layer on the ESP-Mosaico (S31 only; the rules are in os_core.h, host-tested).

It adds no task. Its functions run in the task that calls them (the board task, the LVGL task, the door, sched_mon)
and its state is a few words of internal RAM plus RTC words that survive a reset.

Function

Comment in the header

void sys_reset(sys_reset_reason_t reason, const char *detail) __attribute__((noreturn));

The one reset path: marker, storage quiesce (NOR then NAND), reset, in that order (os_core.h). Never returns. detail: a short note for the next boot’s log line (may be NULL).

void os_boot_done(void);

app_main, once the boot sequence is done: ends the Boot runlevel, logs the reset the previous run asked for.

bool os_allows(os_svc_t svc);

Runlevels (os_core.h). os_allows: every active runlevel enables svc. os_refusal: NULL when allowed, else the phrase for the runlevel that refuses (“a drive is running”, …). os_runlevel: the one to show (Board page, log).

const char *os_refusal(os_svc_t svc);

os_runlevel_t os_blocker(os_svc_t svc);

the runlevel that refuses svc, OS_RL_N if none (texts only)

os_runlevel_t os_runlevel(void);

void os_update_begin(void);

Update runlevel while a format runs (the board task brackets it). sys_reset enters it by itself.

void os_update_end(void);

void os_tick(void);

the board task, every 2 s: logs runlevel changes, forms the boot health verdict at OS_H_VERDICT_MS

uint8_t os_health(uint16_t *flags);

the boot health verdict (os_core.h): OS_H_PENDING until it is formed; flags = the reasons

bool os_admit_model(int ai_id, uint32_t measured_us, char *why, size_t why_n);

Model admission (os_core.h section 4): the jobs sched_mon measured plus the model’s job with C = its self-test run x 2, response-time analysis on its core. Logs every job’s R and the margin. false (why filled) when a deadline would fail.

void os_power_sample(bool ok, int ma, int mv);

The UPS state (CONFIG_OCM_UPS, os_core.h section 6): the board task’s gauge sample every 2 s

uint8_t os_ui_request(void);

void os_battery_sample(bool ok, int temp_dc, int mv, bool on_usb);

Battery safety (CONFIG_OCM_BATSAFE, os_core.h section 8): the board task’s gauge sample every 2 s (temperature in 0.1 C). os_battery_state: OS_BAT_* for the Board page.

uint8_t os_battery_state(void);

bool os_ml_paused(void);

The degradation ladder’s last rung (os_core.h section 7): the ml task skips its windows while this is true

int os_ai_register(int ai_id, bool watchdog);

The AI service contract (os_core.h section 5): register the service’s sched_mon job from its table entry, with its stall limit and CPU reservation. Returns the job.

os_hooks.h#

Source: main/os_hooks.h

os_hooks: how files shared with the car board (S3) call the mossREV OS layer (S31 only).

On the ESP-Mosaico these macros call the OS (os.h). On the S3 each expands to the statement or expression that the
site had before, on the same line, so the S3 objects do not change (the S3 build is compared byte for byte).
  OCM_SYS_RESET(reason, s3)    the one reset path, sys_reset(reason) (S3: the old statement s3)
  OCM_REFUSED(svc, s3)         true when the runlevels refuse svc (S3: the old check s3)
  OCM_WIFI_BOOT_START(s3)      app_main's Wi-Fi start: the S31 holds Wi-Fi until the boot health verdict
                               (wifi_sync_start_held, os_core.h section 3); S3: the old call s3

sched_mon.h#

Source: main/sched_mon.h

Soft real-time job monitor.

Every periodic activity on the board (OBD poll cycle, ML inference) is a "job" with a period and a
deadline. A job brackets each run with sched_begin() / sched_end(). The monitor records, per job:
  - response time (wall clock from begin to end: mean, max),
  - CPU time (the runner task's FreeRTOS run-time counter over the run: mean, max), which is the C in the
    schedulability analysis, as opposed to time spent blocked on BLE, SD or the network,
  - deadline misses, and stalls (an expected job that has not run for 3 periods).
Once a minute it logs a summary plus, per core, the utilisation U = sum(C_max / T) against the rate-monotonic bound
n(2^(1/n) - 1) (Liu and Layland 1973) and the worst-case response time of each job from response-time analysis
R = C_i + sum over higher-priority jobs on the same core of ceil(R / T_j) * C_j (Joseph and Pandya 1986).

Hang handling, without deadlocks:
  - Jobs with watchdog=true are subscribed to the ESP-IDF task watchdog only while a run is in progress. Long runs
    made of bounded steps (each ELM transaction is at most CONFIG_OBD_ELM_TIMEOUT_MS) call sched_kick() after each
    step, so the watchdog fires on a step that never returns, not on a slow but healthy cycle.
  - I/O jobs (watchdog=false) that stay running past SCHED_RESTART_FACTOR x deadline get a logged, orderly restart.
  - Reset reasons are kept across reboots. After SCHED_BOOTLOOP_LIMIT abnormal resets in a row the board boots in
    safe mode (sched_safe_mode() is true) and optional components, such as the model, stay off.
  - Locks: the monitor's lock is a leaf. Nothing is called while holding it that takes another lock (events are
    raised after it is released) and every take is bounded, so it cannot be part of a lock-order cycle.

Priorities follow rate-monotonic order per core: the shorter the period, the higher the priority (see sched_mon.c).

Function

Comment in the header

void sched_mon_start(void);

sched_job_t sched_register(const char *name, uint32_t period_ms, uint32_t deadline_ms, bool watchdog);

void sched_begin(sched_job_t job);

void sched_end(sched_job_t job);

void sched_kick(void);

Feed the task watchdog from inside a run, after each bounded step. No-op if the caller is not running a job.

void sched_set_expected(sched_job_t job, bool expected);

Whether the job should currently be running periodically (e.g. the OBD poll only while an adapter is logging).

void sched_set_stall_ms(sched_job_t job, uint32_t stall_ms);

Override the stall limit (default STALL_PERIODS periods). For jobs paced by something slower than their period.

int sched_get_stats(sched_stats_t *out, int max);

void sched_set_cpu_share(sched_job_t job, uint16_t share_permille, uint32_t burst_ms);

CPU reservation, a token bucket over CPU time in the spirit of a constant bandwidth server: the calling task earns share_permille/1000 us of CPU per us of wall time, up to burst_ms, and spends the CPU it actually uses (its FreeRTOS run-time counter). Aperiodic background work checks sched_cpu_available() before each bounded step and stops when it returns false, so it can never take more than its share however much work is queued.

bool sched_cpu_available(sched_job_t job);

void sched_get_system(sched_system_t *out);

void sched_boot_check(void);

Call first thing in app_main: reads the reset reason, counts boot loops, decides safe mode.

bool sched_safe_mode(void);

void sched_mark_intentional_reset(void);

ESP-Mosaico: call just before a reset somebody asked for (download door, REBOOT, restart after a format), so the next boot does not count it toward safe mode (see reset_class.h)

sys_mode.h#

Source: main/sys_mode.h

System modes: what the board is doing.

  SEEK   no drive: BLE scans for the adapter or waits for a quiet ECU, the model is loaded and ready. Wi-Fi may run its short clock sync.
  DRIVE  the ECU is answering and rows are logged, or (car board only) connecting to the adapter: the OBD poll and the model run. Wi-Fi scans and connects are held off so
         the shared 2.4 GHz radio and core 0 belong to the OBD link.

DRIVE always wins: logging is the board's job, the clock sync can wait.

Function

Comment in the header

void sys_mode_start(void);

sys_mode_t sys_mode_get(void);

const char *sys_mode_name(sys_mode_t m);

reset_class.h#

Source: main/reset_class.h

Function

Comment in the header

bool reset_is_abnormal(reset_kind_t kind, bool monitor_asked, bool intentional);

monitor_asked: the scheduler monitor left a reason before its esp_restart(); intentional: the RTC marker was set