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 |
|---|---|
|
|
|
|
|
Pause scanning (an existing link is never dropped); while paused, obd_ble_probe(ms) scans once for ms. |
|
|
|
Erase the saved adapter address and go back to name/service discovery. |
|
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. |
|
Called by elm327.c when the device never answered like an ELM327: drops it, and skips it for a while if unsaved. |
|
Transport write used by elm327.c; splits to the ATT MTU; returns 0 on success. |
|
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. |
|
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. |
|
|
|
|
|
|
|
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). |
|
|
|
|
|
|
|
|
|
|
|
the Health app (plain reads) |
|
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 |
|---|---|
|
Transport hooks implemented by obd_ble.c |
|
Called by the transport |
|
A drive is being set up or logged (poll lists built from the selected model): no model switch now. |
|
from BLE notifications |
|
link up = subscribed and ready |
|
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. |
|
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. |
|
|
|
|
|
Stop logging (stop_core.h): on = no polling and no new drive until elm_user_stop(false); elm_resume() cannot undo it. |
|
|
|
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”). |
|
|
|
|
|
|
|
esp_timer ms when the current link came up, -1 when down |
|
+1 at every adapter link-up: the automatic search runs once per connection |
|
“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 |
|---|---|
|
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. |
|
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. |
|
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 |
|---|---|
|
Convert raw DTC bytes (pairs) into “P0300 P0171”. Returns number of codes. |
|
Forget which codes have been seen (call at session start). |
|
Analyse the three space-separated code lists. Any may be NULL or empty. |
|
“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 |
|---|---|
|
Units from a two-letter country code (as broadcast by a Wi-Fi access point). -1 when the code says nothing. |
|
Units from a POSIX TZ string. Only the UK is unambiguous (North American zones are shared with Canada); -1 otherwise. |
|
“metric”, “us”, “uk” -> units; “auto” or anything else -> -1. |
|
|
|
“km/L” or “mpg” |
|
“km” or “mi” |
|
“”, “pid”, “maf”, “model”, “phys”, “learned” |
|
Model, physics or learned: a figure the board worked out, shown in amber. |
|
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. |
|
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. |
|
|
|
|
|
One row: speed in km/h, fuel rate in L/h (negative = unknown, the row is skipped), seconds since the last row. |
|
Trip economy in km/L; negative until at least 0.5 km and 0.02 L are counted. |
|
Instant economy in km/L at this row; negative when stopped, slow or unknown. |
|
km/L converted to the display unit (km/L, mpg US, mpg UK). Negative stays negative. |
|
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 |
|---|---|
|
Parse CONFIG path; returns number loaded (0 if the file is missing). Writes an example file if none exists. |
|
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 |
|---|---|
|
“…/obd/sessions” of the drive store |
|
“…/obd/drives.csv” of the drive store |
|
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). |
|
Full path of drive-log file name: the first directory that has it (true), else where a new one goes (false). |
|
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. |
|
|
|
|
|
|
|
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. |
|
since the last row or file write, INT64_MAX before any |
|
Flush everything to the card now and raise “Safe to turn off” (the car link dropped, or a periodic save). |
|
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. |
|
Ends the current drive: everything is saved and the session files are closed. No-op when nothing was logged yet. |
|
Opens a new session if the last drive was ended. Called when the next drive starts without a reboot. |
|
|
|
Append one CSV row built from the current OBD values. |
|
Rewrite the session metadata JSON. Any argument may be NULL to keep the previous value. |
|
|
|
Which model ran this drive (“ev”, “rev”) and the fill-up calibration factor at its start. |
|
|
|
|
|
ESP-Mosaico: the clock was set by hand (meta “clock”:”manual”, started_epoch_ms, clock.txt) |
|
|
|
|
|
|
|
Sets (or replaces) one top-level key of the session JSON to a JSON value given as text; invalid JSON is ignored. |
|
Raw hex of a supported PID the firmware does not decode: appended to sNNNNNN.raw as “uptime_ms,01XX,HEX”. |
|
Pattern layer files: one line per closed window in sNNNNNN.pat; the k-means model in /sdcard/obd/patterns.json. |
|
|
|
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 |
|
|
|
|
|
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). |
|
Delete drive logs (every sNNNNNN. |
|
|
|
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. |
|
Flush and unmount before deep sleep. |
|
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. |
|
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. |
|
|
|
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. |
|
|
|
|
|
|
|
sdlog_ms_since_write() or the last background write, the newer |
|
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 |
|---|---|
|
|
|
nand_store.h#
Source: main/nand_store.h
Function |
Comment in the header |
|---|---|
|
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. |
|
|
|
|
|
|
|
Settings > Format storage: erase every good block (Dhara map cleared), make the FAT, mount. ~15 s. |
|
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. |
|
Deep sleep: unmount and sync (the logger closed its files first). |
|
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 |
|---|---|
|
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). |
|
One sector of each FAT copy (the same index i). first = sector 0 of the FAT (holds entries 0 and 1). |
|
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. |