Skip to main content
Ctrl+K
OpenCarMind documentation, home OpenCarMind documentation, home

OpenCarMind

  • Get started
  • User guides
  • Concepts
  • Hardware
    • Reference
    • Research
    • Release notes
    • Contributing
ESP32-S3 2.5.1 ESP32-S3 beta 2.5.1b OpenCarMind EdgeOS 2.1.0 OpenCarMind EdgeOS 2.0.0 (older)
  • GitHub
  • Releases
  • Get started
  • User guides
  • Concepts
  • Hardware
  • Reference
  • Research
  • Release notes
  • Contributing
ESP32-S3 2.5.1 ESP32-S3 beta 2.5.1b OpenCarMind EdgeOS 2.1.0 OpenCarMind EdgeOS 2.0.0 (older)
  • GitHub
  • Releases

Section Navigation

  • Messages
  • Settings
  • Configuration
  • The on-board models: CarMind E.V and CarMind R.E.V
  • USB door protocol
  • Host tools
  • C API of the firmware modules
    • Operating-system layer
    • AI services
    • Battery
    • Network guard and pairing
    • Models and learning
    • Car link and logging
    • USB, Wi-Fi and version
  • Reference
  • C API of the firmware modules
  • Car link and logging

Car link and logging#

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.

obd_ble.h#

Source: main/obd_ble.h

Function

Comment in the header

esp_err_t obd_ble_start(void);

bool obd_ble_connected(void);

void obd_ble_set_paused(bool paused);

Pause scanning (an existing link is never dropped); while paused, obd_ble_probe(ms) scans once for ms.

void obd_ble_probe(uint32_t ms);

void obd_ble_forget_adapter(void);

Erase the saved adapter address and go back to name/service discovery.

bool obd_ble_adapter_confirmed(void);

Called by elm327.c once the device answered the ELM327 reset. True: it is the paired adapter, go on. False: a new adapter (the link is being dropped and the user asked, obd_ble_pair_*) or no link: send nothing more.

void obd_ble_adapter_rejected(const char *why);

Called by elm327.c when the device never answered like an ELM327: drops it, and skips it for a while if unsaved.

int obd_ble_write(const uint8_t *data, size_t len);

Transport write used by elm327.c; splits to the ATT MTU; returns 0 on success.

void obd_ble_explore(bool user);

Connection search. user = true (Find OBD, the BOOT double-click): clears the failure skip list and the unanswered questions and, for 90 s, lets a different adapter be offered next to the saved one. user = false (the automatic search): changes nothing, so it never replaces or bypasses a saved adapter. A new device must look like an OBD adapter and have a strong signal (CONFIG_OBD_BLE_PAIR_MIN_RSSI), and is saved only after the user’s yes.

bool obd_ble_pair_offer(char *name, size_t n, const char **strength, int *secs_left);

The pairing question (obd_pair.h). offer: true while one is open (name, “strong”/”good”, seconds left; any may be NULL). seq: +1 for every new question. answer: the user’s yes (“Use this adapter”) or no (“Not this one”); a late answer is ignored. poll: once a second, closes a question whose time ran out (not saved). answer and poll may write NVS: call them from a task with an internal-RAM stack.

uint32_t obd_ble_pair_seq(void);

void obd_ble_pair_answer(bool yes);

void obd_ble_pair_poll(void);

void obd_ble_guard_elm(const char *ati, const char *at1);

Pairing safety on the ESP-Mosaico (adapter_guard.h: R1 the adapter fingerprint, R2 no silent re-pair). elm: elm327.c hands over the paired adapter’s ATI and AT@1 replies; the fingerprint is checked (or learned on the first link after the yes) and the verdict logged. May write NVS: the obd task (internal-RAM stack). protocol: the ATDPN reply, a soft field (noted, never a mismatch). changed: this link’s adapter looks different or its re-pair was refused, so its rows are marked and the learner gets none of them. meta: the obd task, every row: writes the session’s “adapter_check” when it changed. offer/answer: the guard question for the screen (one at a time, the pairing sheet’s style); seq tells a late answer apart; answer may write NVS (the board task).

void obd_ble_guard_protocol(const char *dpn);

bool obd_ble_adapter_changed(void);

void obd_ble_guard_meta(void);

bool obd_ble_guard_offer(const char **text, const char **yes, const char **no, const char **note, int *secs_left, uint32_t *seq);

void obd_ble_guard_answer(uint32_t seq, bool yes);

void obd_ble_guard_counts(uint32_t *fp_checks, uint32_t *repair_refused);

the Health app (plain reads)

bool obd_ble_adapter_mismatch(void);

ESP-Mosaico: the adapter looks different and the user has not said “Use it”

elm327.h#

Source: main/elm327.h

ELM327 command/response layer and OBD-II polling loop, transport-agnostic.

Function

Comment in the header

int obd_ble_write(const uint8_t *data, size_t len);

Transport hooks implemented by obd_ble.c

void elm_init(void);

Called by the transport

bool elm_drive_active(void);

A drive is being set up or logged (poll lists built from the selected model): no model switch now.

void elm_rx_bytes(const uint8_t *data, size_t len);

from BLE notifications

void elm_link_changed(bool up);

link up = subscribed and ready

int elm_transact(const char *cmd, char *resp, size_t resp_sz, uint32_t timeout_ms);

Send a command (without CR) and wait for the ‘>’ prompt. Returns response length, -1 on timeout, -2 if the link is down. The response has echo, CR/LF and the prompt removed.

void elm_request_stop(void);

Power-off support. elm_request_stop() stops polling at once and no new drive starts; elm_wait_stopped() also waits up to timeout_ms for the poll loop to save and close the drive, and returns true when it has. elm_resume() undoes the stop.

bool elm_wait_stopped(uint32_t timeout_ms);

void elm_resume(void);

void elm_user_stop(bool on);

Stop logging (stop_core.h): on = no polling and no new drive until elm_user_stop(false); elm_resume() cannot undo it.

bool elm_user_stopped(void);

void elm_explore(void);

Connection search: elm_explore() is the user’s (Find OBD, a BOOT double-click), elm_explore_auto() the automatic one (after a minute without engine data). With no adapter linked, the user’s search lets a new adapter be offered for 90 s (obd_ble_explore(true)); the automatic one never looks past a saved adapter. With an adapter linked both stop the current attempt and, read-only, tries every protocol, lists the computers that answer (broadcast request with headers, plus each 11-bit physical address 7E0..7E7), asks each for RPM on its own address and keeps the engine for this boot (checked again at the next connect). The result is shown on screen and saved in the session JSON (“search”).

void elm_explore_auto(void);

bool elm_exploring(void);

bool elm_link_is_up(void);

int64_t elm_link_up_ms(void);

esp_timer ms when the current link came up, -1 when down

uint32_t elm_link_epoch(void);

+1 at every adapter link-up: the automatic search runs once per connection

void elm_link_summary(char *out, size_t n);

“Link OK: polling 7E0” for the double-click status line

obd_fields.h#

Source: main/obd_fields.h

Every decoded SAE J1979 mode-01 field OpenCarMind collects.
One X-macro drives the enum, the decode table, the CSV header and the schema document.
  X(ident, csv_name, unit, pid, byte_offset, kind, scale, offset, fast)
  value = raw(kind at byte_offset) * scale + offset
Formulas follow SAE J1979 / ISO 15031-5 Annex B (as tabulated on the OBD-II PIDs reference).

ecu_select.h#

Source: main/ecu_select.h

Which computer to poll when several answer, and the connection-search summary. Pure C, no ESP-IDF, covered by
tests/host. On CAN, more than one computer can answer a broadcast request (engine and transmission, hybrid systems), in
either order; reading the first reply then gives the wrong supported-PID list. These helpers parse the replies to
0100 sent with headers on and pick the engine, so the logger can address it directly (ISO 15765-4: 11-bit request id
= reply id - 8; 29-bit 18DAxxF1).

Function

Comment in the header

int ecu_parse_replies(const char *resp, bool ext29, ecu_t *out, int max);

Parses the reply to a broadcast 0100 sent with ATH1 ATS0 on CAN: one line per computer, 11-bit “7E8064100BE3EA813” (id, length byte, data) or 29-bit “18DAF110064100BE3EA813”. Ids outside 7E8..7EF / 18DAF1xx are skipped. Sorted by id, no duplicates. Returns the number written to out.

int ecu_pick_engine(const ecu_t *e, int n);

The engine among them: 7E8 (11-bit) or 18DAF110 (29-bit) whenever it answers, the usual engine ids across Japanese and US makes; otherwise the computer that lists RPM (PID 0C) with the most supported PIDs, lowest id on a tie. Listing RPM and speed alone is not enough: a transmission can list both. The caller confirms the pick with 010C on its address. Returns the index, or -1 when none qualifies.

size_t ecu_search_summary(const char *proto, const ecu_t *e, const bool *rpm_ok, int n, int pick, char *out, size_t cap);

One line for the screen: protocol, each computer and whether it answered RPM on its own address, the address used. Example “A6: 7E8 rpm, 7E9 -; use 7E0”. pick < 0 = none. Returns the length.

fault_engine.h#

Source: main/fault_engine.h

Rule-based diagnostic trouble code (DTC) analysis: decodes, describes, ranks and groups
faults so the Faults screen can present the most important ones first.
Pure C, no ESP-IDF dependencies: unit-tested on the host (tests/host).

Function

Comment in the header

int dtc_bytes_to_string(const uint8_t *b, int n, char *out, size_t out_sz);

Convert raw DTC bytes (pairs) into “P0300 P0171”. Returns number of codes.

void fault_engine_reset(void);

Forget which codes have been seen (call at session start).

void fault_engine_analyse(const char *stored, const char *pending, const char *permanent, bool mil_on, fault_report_t *out);

Analyse the three space-separated code lists. Any may be NULL or empty.

const char *fault_severity_name(uint8_t sev);

“LOW” .. “CRITICAL”

econ.h#

Source: main/econ.h

Fuel use, fuel economy and display units. Pure C, no ESP-IDF, so the host tests cover it.

Fuel rate comes from PID 0x5E when the car reports it. Otherwise it is worked out from the mass air flow (PID 0x10):
  fuel (g/s) = MAF / (AFR_stoich * lambda),   L/h = g/s * 3600 / density
with lambda the commanded equivalence ratio (PID 0x44) when present. A commanded ratio of 0 is decel fuel cut (no fuel).
Economy is distance over fuel: km/L, mpg (US gallon) or mpg (imperial gallon).

Function

Comment in the header

int units_from_country(const char *cc);

Units from a two-letter country code (as broadcast by a Wi-Fi access point). -1 when the code says nothing.

int units_from_timezone(const char *tz);

Units from a POSIX TZ string. Only the UK is unambiguous (North American zones are shared with Canada); -1 otherwise.

int units_parse(const char *s);

“metric”, “us”, “uk” -> units; “auto” or anything else -> -1.

const char *units_name(units_t u);

const char *units_econ_label(units_t u);

“km/L” or “mpg”

const char *units_dist_label(units_t u);

“km” or “mi”

const char *fuel_src_name(fuel_src_t s);

“”, “pid”, “maf”, “model”, “phys”, “learned”

bool econ_src_is_estimate(fuel_src_t s);

Model, physics or learned: a figure the board worked out, shown in amber.

float econ_fuel_lph(bool rate_ok, float rate_lph, bool maf_ok, float maf_gps, bool lambda_ok, float lambda, int fuel_type, bool model_ok, float model_lph, fuel_src_t *src);

Fuel rate in L/h from the best source available, or a negative value with FUEL_NONE. fuel_type is PID 0x51 (0 unknown). The caller decides whether a commanded 0 (fuel cut) is still current: PID 0x44 is polled slowly. model_lph is the on-board model’s estimate (an estimate, not a measurement), used only when the car gives neither.

float econ_maf_lph(float maf_gps, bool lambda_ok, float lambda, int fuel_type);

Fuel L/h from an airflow in g/s, with the commanded ratio when known (0 = decel fuel cut) and the fuel type: the MAF formula.

float econ_fuel_pick(const econ_in_t *in, fuel_src_t *src);

void econ_reset(econ_trip_t *t);

void econ_step(econ_trip_t *t, float kph, float lph, float dt_s);

One row: speed in km/h, fuel rate in L/h (negative = unknown, the row is skipped), seconds since the last row.

float econ_trip_kpl(const econ_trip_t *t);

Trip economy in km/L; negative until at least 0.5 km and 0.02 L are counted.

float econ_instant_kpl(float kph, float lph);

Instant economy in km/L at this row; negative when stopped, slow or unknown.

float econ_to_unit(float kpl, units_t u);

km/L converted to the display unit (km/L, mpg US, mpg UK). Negative stays negative.

double econ_dist_to_unit(double km, units_t u);

km converted to the display distance unit.

custom_pids.h#

Source: main/custom_pids.h

User-defined PIDs loaded from the SD card (EngineLink/Torque-style CSV).

Function

Comment in the header

size_t custom_pids_load(const char *path, custom_pid_t *out, size_t max);

Parse CONFIG path; returns number loaded (0 if the file is missing). Writes an example file if none exists.

bool custom_pid_eval(const char *formula, const uint8_t *bytes, int n, float *result);

Evaluate formula against the data bytes. Returns false on a syntax error or missing byte.

sdlog.h#

Source: main/sdlog.h

Function

Comment in the header

const char *sdlog_drive_dir(void);

“…/obd/sessions” of the drive store

const char *sdlog_drives_csv(void);

“…/obd/drives.csv” of the drive store

int sdlog_drive_dirs(const char *dirs[2]);

The directories that can hold drive logs, the drive store first: the NAND, then the flash FAT (drives not moved yet). Returns how many (1 or 2).

bool sdlog_drive_file(const char *name, char *path, size_t n);

Full path of drive-log file name: the first directory that has it (true), else where a new one goes (false).

bool sdlog_move_lock(void);

log_move.c: the logger’s lock for one step of the move to the NAND; false (lock not held) once a reset is coming.

void sdlog_move_unlock(void);

esp_err_t sdlog_init(void);

bool sdlog_ok(void);

bool sdlog_saved(void);

True when everything written so far is on the card, so the power can be cut now. False between a write and the next save (at most SDLOG_SYNC_PERIOD_S seconds) and when there is no card. Reads one flag: safe to call from the display.

int64_t sdlog_ms_since_write(void);

since the last row or file write, INT64_MAX before any

void sdlog_sync_now(void);

Flush everything to the card now and raise “Safe to turn off” (the car link dropped, or a periodic save).

void sdlog_quiet(bool on);

While on, the periodic save waits and nothing is flushed on the side: each SD transfer needs a 4 KB DMA bounce buffer in internal RAM, which the Wi-Fi driver holds while it runs (wifi_sync.c). Writes stay buffered.

void sdlog_end_drive(void);

Ends the current drive: everything is saved and the session files are closed. No-op when nothing was logged yet.

void sdlog_begin_drive(void);

Opens a new session if the last drive was ended. Called when the next drive starts without a reboot.

uint32_t sdlog_session_id(void);

void sdlog_write_row(const obd_values_t *v);

Append one CSV row built from the current OBD values.

void sdlog_meta_set_adapter(const char *name, const char *addr, const char *ati, const char *batch);

Rewrite the session metadata JSON. Any argument may be NULL to keep the previous value.

void sdlog_meta_set_vehicle(const char *vin, const char *protocol);

void sdlog_meta_set_ml(const char *model_key, float fuel_cal);

Which model ran this drive (“ev”, “rev”) and the fill-up calibration factor at its start.

void sdlog_meta_set_supported(const char *pid_cmd, const char *bitmap_hex);

void sdlog_meta_set_time_sync(int64_t epoch_ms, int64_t uptime_ms);

void sdlog_meta_set_clock_manual(int64_t epoch_ms, int64_t uptime_ms);

ESP-Mosaico: the clock was set by hand (meta “clock”:”manual”, started_epoch_ms, clock.txt)

void sdlog_meta_add_dtcs(int64_t uptime_ms, const char *dtcs);

void sdlog_meta_set_faults(const char *insight, const char *ranked_codes, uint8_t max_severity);

void sdlog_meta_set_custom(size_t idx, const char *cmd, const char *name, const char *unit, const char *formula, const char *header);

void sdlog_meta_set_json(const char *key, const char *json);

Sets (or replaces) one top-level key of the session JSON to a JSON value given as text; invalid JSON is ignored.

void sdlog_write_raw(uint8_t pid, const char *hex);

Raw hex of a supported PID the firmware does not decode: appended to sNNNNNN.raw as “uptime_ms,01XX,HEX”.

void sdlog_write_pattern_window(uint32_t window_seq, int64_t start_ms, int64_t end_ms, uint16_t samples, int pattern_id, float dist, float novelty, bool spawned, const char *sax_rpm, const char *sax_speed, const float *features, int nfeatures);

Pattern layer files: one line per closed window in sNNNNNN.pat; the k-means model in /sdcard/obd/patterns.json.

void sdlog_set_window_seq(uint32_t seq);

void sdlog_write_ml_line(const char *header, const char *line);

On-board model outputs: one line per window in sNNNNNN.ml.csv; header is written when the file is first opened. value written into the CSV window_seq column

bool sdlog_load_text(const char *path, char *buf, size_t n);

bool sdlog_save_text_atomic(const char *path, const char *text);

bool session_name_valid(const char *name);

Drive-log file name: “s” + 6 digits + a suffix the logger writes (.csv, .ml.csv, .pat, .raw, .json, and .sum.json on the ESP-Mosaico).

int sdlog_delete_session(uint32_t id);

Delete drive logs (every sNNNNNN. file in SDLOG_SESSIONS_DIR, nothing else) under the logger’s own lock, so a delete never races a save. The current session is refused. Each delete is a sys_event. Returns the number of files removed, -1 when refused (current session, no storage). sdlog_delete_all_sessions keeps the current session.

int sdlog_delete_all_sessions(int *sessions_out);

esp_err_t sdlog_format_storage(uint32_t *free_kb, int *kept_files, char *why, size_t why_n);

Boards with the log in a flash FAT (ESP-Mosaico): format it under the logger’s lock. Every plain file directly in SDLOG_DIR (learned R.E.V state, clock.txt, config.json, wifi.csv, …; at most 512 KB in all) is copied to PSRAM first and written back; drive logs (sessions/) and drives.csv are erased. Refused while a session is open for rows. Returns ESP_OK and the free KB after, or an error with the reason in why.

void sdlog_prepare_sleep(void);

Flush and unmount before deep sleep.

void sdlog_quiesce_for_reset(void);

Before a software reset: flush the logger’s files and hold the file system’s lock so no flash sector is half written when the reset hits. Never returns the lock; the caller resets right after. Not for the panic handler.

bool sdlog_session_open(void);

Stop logging (stop_core.h, OpenCarMind EdgeOS 2.1.1): the open session’s files flushed, synced and closed, waiting at most timeout_ms for the logger’s lock (false: busy, try again). A session with no rows is closed and its header-only files removed. True when no session is open afterwards.

bool sdlog_stop_close(uint32_t timeout_ms);

void sdlog_writers_hold(bool on);

Background writers (the battery log): sdlog_writer_enter() is false while a stop holds them; a true needs a matching sdlog_writer_exit(). sdlog_writers_idle(): held and none inside a write.

bool sdlog_writers_idle(void);

bool sdlog_writer_enter(void);

void sdlog_writer_exit(void);

int64_t sdlog_ms_since_any_write(void);

sdlog_ms_since_write() or the last background write, the newer

int sdlog_flash_health(uint16_t *repairs, bool *audit_warn);

mossREV OS boot health: the flash FAT’s state (1 mounted, 0 not, -1 damaged), FAT sectors repaired, audit warning

events.h#

Source: main/events.h

System event log: a small ring of recent internal errors and notable events shown on the
System page and, for warnings and errors, as a short pop-up banner on any page.

Function

Comment in the header

void sys_event(event_level_t level, const char *fmt, ...) __attribute__((format(printf, 2, 3)));

void sys_event_net(event_level_t level, const char *name, const char *fmt, ...) __attribute__((format(printf, 3, 4)));

nand_store.h#

Source: main/nand_store.h

Function

Comment in the header

esp_err_t nand_store_init(void);

SPI3 bus, chip, FAT checks (fat_mirror, as on the flash FAT), mount. A blank chip (every good block’s first page unused) is formatted (2 FATs, 16 KB clusters); a chip that holds data and does not mount is never formatted here.

nand_state_t nand_store_state(void);

static inline bool nand_store_mounted(void)

bool nand_store_info(uint64_t *total, uint64_t *free_b);

esp_err_t nand_store_format(char *why, size_t why_n);

Settings > Format storage: erase every good block (Dhara map cleared), make the FAT, mount. ~15 s.

void nand_store_quiesce(void);

Before a reset (sdlog_quiesce_for_reset, after the logger flushed its files): wait for a mount or format in progress, take FatFs’s lock of the NAND volume and keep it, then a Dhara sync, so everything written so far is durable.

void nand_store_unmount(void);

Deep sleep: unmount and sync (the logger closed its files first).

const char *nand_store_describe(void);

One line for the console and the storage card: “GD5F1GM7 C8/91, 1024 blocks, 0 bad, SIO 20 MHz”

fat_mirror.h#

Source: main/fat_mirror.h

Function

Comment in the header

bool fat_geom_parse(const uint8_t *sec0, size_t n, bool (*read_sector)(uint32_t lba, uint8_t *buf, void *ctx), void *ctx, uint8_t *scratch, fat_geom_t *g);

Boot sector (VBR at sector 0, or an MBR whose first partition holds it) -> geometry. sec0 is sector 0 of the medium; read_sector reads another sector when the volume sits in a partition (may be NULL: then only a VBR at 0 is accepted).

fat_verdict_t fat_mirror_compare(const uint8_t *fat1, const uint8_t *fat2, size_t n, bool first, uint8_t media);

One sector of each FAT copy (the same index i). first = sector 0 of the FAT (holds entries 0 and 1).

int fat_reclaim(const fat_geom_t *g, uint8_t *fat, bool (*read_sector)(uint32_t lba, uint8_t *buf, void *ctx), bool (*write_sector)(uint32_t lba, const uint8_t *buf, void *ctx), void *ctx, uint8_t *secbuf, uint8_t *mark, int *scrubbed);

Orphan reclaim (a minimal fsck for FAT12/16). A file’s clusters reach the FAT before its directory entry records its first cluster (FatFs writes the entry at f_sync/f_close), so a reset while a new file is written leaves a chain that no directory entry reaches; nothing ever frees it. This walks the directory tree, marks every cluster a directory or file chain reaches, and clears allocated entries that nothing reaches. A directory sector torn by a reset (erased, or programmed only part way) holds entries whose name starts with 0xFF, which no real name does. With write_sector those entries are rewritten as deleted entries (0xE5, so FatFs keeps reading the entries after them) and *scrubbed counts them; their files are gone, and their chains are freed with the orphans. Without write_sector such a sector stops the walk. fat: the whole first FAT (fat_sectors * sector_size bytes), changed in place. Returns the number of clusters freed, or -1 when the tree is not clean enough to touch (then fat is unchanged): a read or write error, a torn directory sector without write_sector, a chain that leaves the cluster range or runs into a free or bad cluster, two chains that share a cluster, or a tree deeper than 16.

previous

Models and learning

next

USB, Wi-Fi and version

On this page
  • obd_ble.h
  • elm327.h
  • obd_fields.h
  • ecu_select.h
  • fault_engine.h
  • econ.h
  • custom_pids.h
  • sdlog.h
  • events.h
  • nand_store.h
  • fat_mirror.h
Edit on GitHub

© Copyright 2026 Alve Rahman Akash, MIT licence.

Created using Sphinx 9.2.0.

Built with the PyData Sphinx Theme 0.24.0.