Network guard and pairing#

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.

ids_core.h#

Source: main/ids_core.h

ids_core: the network guard's pure rules (OpenCarMind EdgeOS AI service "ids", ESP-Mosaico). No IDF: host-tested in
tests/host/test_ids.c. The firmware glue (the radio hooks, the service step, the consumers) is ids_svc.c.

Three heads, one 5 s window at a time (carmind-ml experiments/net_ids: DESIGN.md section 6, UNSUPERVISED.md):
  scan  the BLE adverts the scan sees: ids_model.h's rotation detector (single-use new transmitters, churn, adverts per
        address; static prior + learnt robust z, 3 of 6 windows, poisoning guard). It blocks.
  link  the car link's response time (mean ELM round trip per window): frugal median and MAD of this board's normal,
        one-sided robust z over IDS_LINK_Z, 3 of 6 windows. Advisory only (relay timing found +80 % reliably, +40 %
        partly, from 1.5 h of data): it marks rows and shows a note, it never blocks.
  wifi  per Wi-Fi scan in a clock round: the same rotation detector, static prior only (a round gives a few windows,
        so it could never learn), its persistence reset at every round; plus the deauth rule: IDS_DEAUTH_K or more
        deauth or disassoc disconnects in one round. Either blocks the round.

Verdict and states (what the Health app shows):
  learning  no head has seen a window yet
  shadow    the first IDS_SHADOW_WIN windows (2 h) the guard runs: heads learn and score, nothing is acted on; a block
            they would raise is logged as "would block"
  watching  after the shadow, no block
  blocking  a head blocks and the user's "Network guard: blocking" setting is on. With the setting off the heads still
            run and the "would block" events are logged.
A block lifts by itself IDS_HOLD_WIN windows (10 min) after the head's last anomalous window, or at once with the
user's Clear (the learnt baselines are kept). What blocking does is the consumers' business (ids_svc.h): no pairing
prompts or re-pair requests, the scan narrowed to the paired adapter, the Wi-Fi round stopped with the clock kept.
Never: cut the paired link, transmit, pair, change the clock. Addresses never leave the hooks: only bitmap bits and a
16-bit hash prefix of the window's pattern.

Function

Comment in the header

void ids_init(ids_t *g);

uint32_t ids_step(ids_t *g, const ids_in_t *in);

IDS_CH_* bits

bool ids_shadow(const ids_t *g);

uint32_t ids_block_left_s(const ids_t *g);

while blocking: until it lifts by itself

const char *ids_reason_text(uint8_t r);

“radio flood nearby”, “Wi-Fi beacon flood”, “Wi-Fi deauth attack”

const char *ids_state_name(uint8_t st);

static inline bool ids_wifi_scan_scored(bool have_prev)

a finished Wi-Fi scan is scored only against the scan before it: the first scan after boot (or after the slot ring lost the one before) has nothing to compare with, so every network would look new (290 of 256 right after boot, V21). It is only kept as the next scan’s “before”. Each clock round makes one scan (wifi_sync.c sync_once), so a round’s scan is compared with the previous round’s.

static inline bool ids_deauth_rule(uint16_t deauth_round)

the deauth rule alone, for the Wi-Fi task’s inline check before the clock is set

int32_t ids_link_score(const ids_link_t *l, int32_t x);

the link head on one window’s mean latency (1/16 ms): the score (Q8), and the note’s start (true once)

bool ids_link_step(ids_link_t *l, int32_t x, bool *ended);

ids_svc.h#

Source: main/ids_svc.h

ids_svc: the network guard as an OpenCarMind EdgeOS AI service (CONFIG_OCM_IDS, ESP-Mosaico only). The rules are
ids_core.h, the hook data ids_hooks.h. This header is included by the radio code on both boards: without
CONFIG_OCM_IDS (the S3) every hook and consumer is an empty inline, so the S3 image does not change.

Hooks (radio callbacks, each in its own writer task; they only count and set bitmap bits):
  ids_hook_ble_adv      obd_ble.c BLE_GAP_EVENT_DISC, every advert           NimBLE host task
  ids_hook_link         obd_ble.c CONNECT (up) and DISCONNECT (down)        NimBLE host task
  ids_hook_link_rtt     elm327.c, each mode 01 request's round trip          OBD task
  ids_hook_wifi_disc    wifi_sync.c STA_DISCONNECTED, its reason            esp_event task
  ids_hook_wifi_round / _scan_begin / _ap / _scan_done / _leave              Wi-Fi task (wifi_sync.c sync_once)
Consumers (poll the verdict, never wait; the IDS calls none of them):
  ids_ble_blocking      obd_ble.c: no pairing offers and no re-pair, the scan narrowed to the paired adapter
  ids_wifi_refuse       wifi_sync.c: before connecting and before settimeofday (the round stops, the clock is kept)
  ids_rows_suspect      obd_ble_adapter_changed(): the learners skip rows while the link head flags or a block runs

Function

Comment in the header

const ai_svc_def_t *ids_service(void);

bool ids_read(ids_result_t *out);

any task, lock-free

void ids_events(char ev[][64], int32_t *age_s, int n);

the last guard events (board task writes, any task reads lock-free): newest first, ages in s, “” for none

void ids_hook_ble_adv(const uint8_t addr[6], uint8_t type);

void ids_hook_link(bool up);

void ids_hook_link_rtt(uint32_t us);

void ids_hook_wifi_disc(int reason);

void ids_hook_wifi_round(void);

void ids_hook_wifi_scan_begin(void);

void ids_hook_wifi_ap(const uint8_t bssid[6]);

void ids_hook_wifi_scan_done(void);

void ids_hook_wifi_leave(void);

bool ids_ble_blocking(void);

bool ids_wifi_refuse(const char **why);

bool ids_rows_suspect(void);

adapter_guard.h#

Source: main/adapter_guard.h

adapter_guard: the pure rules that keep the saved OBD adapter honest on the ESP-Mosaico (pairing safety, R1 and R2 of
the net_ids design study). No IDF, no heap, no clock of its own: host-tested in tests/host/test_adapter_guard.c.
obd_ble.c builds the fingerprint, keeps the state under its lock and does what these rules return.

R1, the adapter fingerprint. The saved adapter used to be known by its address alone, and a device that copies the
address could connect with no question. The fingerprint is one 32-bit FNV-1a hash per field below. Raw strings are
never kept: NVS holds the hashes, the log shows at most the 8-hex id (afp_id). The VIN is not a field (it names the car,
not the adapter, and must never be stored or logged), so no VIN can reach the record.

  field        source                                         rule
  addr type    the advert (public or random)                  core: must match
  adv name     the advertised name in an advert (ADV_IND)     hard, compared only when both packets carried it
  adv uuids    the advertised service UUIDs, sorted, no dups  hard, as above
  adv mfg      the manufacturer data's company id (2 bytes)   hard, as above; the bytes after it are not used
  rsp name     the same three from a scan response            hard, compared only with a scan response's
  rsp uuids
  rsp mfg
  gatt         service, notify and write UUIDs of the serial  core: must match
               line adapter_choose() picked
  ati          the ATI reply, upper case, A-Z 0-9 . ? only    core: must match
  at@1         the AT@1 reply, same cleaning ("?" counts)     hard, skipped when the adapter gave no reply
  protocol     ATDPN, the leading "A" (auto) dropped          soft: a difference is noted, never a mismatch

Tolerance, and why:
  - RSSI, the advert flags, TX power, the interval, service data and the manufacturer bytes after the company id are
    not used: they change from packet to packet or carry state (battery, counters).
  - Adverts and scan responses often carry different fields (the name only in the scan response, for example), and
    the board connects on the first packet it sees. So each kind is compared only with the same kind, and a field
    the packet did not carry is unknown, not a mismatch.
  - The order of the UUIDs in a packet does not matter (sorted set).
  - Upper/lower case, spaces and line ends in the ELM replies do not matter (cleaned before hashing).
  - AT@1: some clones never answer it; no reply is unknown. A "?" (not supported) is a stable answer and is compared.
  - The protocol is the car's, not the adapter's: moving the adapter to another car is a legitimate change.
  - A core field the saved record has but this link did not give (an ATI with no reply) counts as a mismatch, so a
    copy cannot pass by staying silent.
  - This is not cryptography: a device that copies every field passes. It stops the cheap clone that copies the address
    and the name. A hash is used for compact storage and so that no raw reply sits in NVS or the log.

R1 decision (ag_r1_decide):
  no saved record          -> LEARN (the first link after the user's yes; also an adapter paired before this check)
  all compared fields same -> USE
  a mismatch, parked       -> ASK  "This adapter looks different. Use it?"; its rows are marked, the learner gets none
  a mismatch, driving      -> FLAG the link is never cut; rows marked, no learner; the question waits until parked

R2, pairing again. NimBLE as a central (IDF 6.1) re-pairs by itself when the encryption with the saved bond fails with
"PIN or key missing" (BLE_RESTART_PAIR is 1 in esp_nimble_cfg.h, with no Kconfig), and the event
BLE_GAP_EVENT_REPEAT_PAIRING only comes for a pairing request, which a central never receives. obd_ble.c therefore
keeps a copy of the saved bond at connect and compares it after each encryption: a new key for the saved adapter
is a re-pair. The event handler uses the same table, in case another stack version sends it.
  user allowed it (Allow, within AG_ALLOW_MS) -> ALLOW  keep the new bond
  driving                                     -> REFUSE the old bond is put back, the link is kept but marked
  another question is open                    -> REFUSE as above
  parked                                      -> ASK    "The adapter asks to pair again. Allow?"; the link is held
                                                        (no subscribe, no data) until the answer

Function

Comment in the header

uint32_t afp_fnv1a(uint32_t h, const void *p, size_t n);

void afp_init(adapter_fp_t *fp);

void afp_set_addr_type(adapter_fp_t *fp, uint8_t type);

void afp_set_adv(adapter_fp_t *fp, bool scan_rsp, const afp_adv_t *a);

void afp_set_gatt(adapter_fp_t *fp, const uint8_t svc[16], const uint8_t ntf[16], const uint8_t wr[16]);

bool afp_set_elm(adapter_fp_t *fp, afp_field_t f, const char *reply);

f = AFP_ATI or AFP_AT1; reply NULL or empty after cleaning: the field stays unknown (false)

bool afp_set_proto(adapter_fp_t *fp, const char *dpn);

bool afp_valid(const adapter_fp_t *fp);

a record from NVS: right version and every core field known

uint32_t afp_id(const adapter_fp_t *fp);

one hash over the known fields: the only form that is logged

bool afp_same(const adapter_fp_t *stored, const adapter_fp_t *now, uint16_t *diff);

true when the records match under the rules above. diff (may be NULL): the fields that differ, soft ones included

const char *afp_field_name(afp_field_t f);

“name”, “services”, “ATI”, … for the event line

afp_field_t afp_first(uint16_t mask);

lowest field in mask, AFP_N if none

ag_r1_t ag_r1_decide(const adapter_fp_t *stored, const adapter_fp_t *now, bool driving, uint16_t *diff);

ag_r2_t ag_r2_decide(bool driving, bool user_allowed, bool question_open);

void ag_q_init(ag_q_t *q);

bool ag_q_open(ag_q_t *q, ag_q_kind_t k, int64_t now_ms, uint32_t ask_ms);

false: one is open already

ag_q_kind_t ag_q_answer(ag_q_t *q, uint32_t seq, int64_t now_ms);

the kind answered; NONE when late or stale

ag_q_kind_t ag_q_tick(ag_q_t *q, int64_t now_ms);

the kind whose time ran out, else NONE

void ag_q_close(ag_q_t *q);

bool ag_q_offer(const ag_q_t *q, int64_t now_ms, ag_q_kind_t *k, int *secs_left, uint32_t *seq);

const char *ag_q_text(ag_q_kind_t k);

const char *ag_q_yes(ag_q_kind_t k);

const char *ag_q_no(ag_q_kind_t k);

adapter_match.h#

Source: main/adapter_match.h

Decides whether a Bluetooth LE device is an OBD-II adapter and which of its characteristics carry the serial line.
   Pure C with no Bluetooth stack dependency, so the host tests cover it.

Function

Comment in the header

bool adapter_name_matches(const char *name, size_t len, const char *prefixes);

True when ‘name’ (not NUL-terminated, ‘len’ bytes) starts with any entry of the comma-separated list, ignoring case. Entries are trimmed and empty entries are skipped.

bool adapter_name_looks_obd(const char *name, size_t len);

True when the name contains a word that OBD-II adapters put in their names (“obd”, “elm327”, “vgate”, “vlink”, “veepeak”, “carista”, “kiwi”, …), anywhere and in any case.

bool adapter_uuid_parse(const char *s, adapter_uuid_t *out);

Parses 4 or 8 hex digits (on the Bluetooth base UUID) or a full 32-digit UUID; dashes and spaces are ignored.

adapter_uuid_t adapter_uuid16(uint16_t v);

bool adapter_uuid_eq(const adapter_uuid_t *a, const adapter_uuid_t *b);

bool adapter_service_is_obd(const adapter_uuid_t *u);

True when an advertised service UUID is one that OBD adapters use for their serial line. FFE0 (the HM-10 module’s) and the Nordic UART service are left out because many other gadgets carry them; those still match by name.

bool adapter_choose(const adapter_chr_t *c, size_t n, const char *cfg_svc, const char *cfg_ntf, const char *cfg_wr, int *notify_idx, int *write_idx, int *profile);

Picks the notify and write characteristics. Known profiles are tried first (the configured one, then the table), then the first non-standard service with a subscribable and a writable characteristic. Returns false when the device has no serial line. *profile is the matched table index, or -1 for the generic fallback.

const char *adapter_profile_name(int profile);

Name of a table profile for logs (“FFF0”, “Vgate E7810A71”, …); “configured” for -2, “generic” for -1.

obd_pair.h#

Source: main/obd_pair.h

obd_pair: the pure rules for choosing and pairing a Bluetooth LE OBD adapter (owner, 2026-11-11: "ask + strong signal").
No IDF, no heap, no clock of its own: host-tested in tests/host/test_obd_pair.c. obd_ble.c keeps one obd_pair_t under a
lock and does what these rules return (connect, drop the link, write NVS, delete a bond).

Choosing a device from one advert (obd_pair_pick):
  - the saved adapter is a candidate down to the link floor (CONFIG_OBD_BLE_MIN_RSSI, -90 dBm), so a paired adapter still
    works at the edge of range, and it needs no question;
  - any other device is only ever OFFERED for pairing, and only when all of these hold: no adapter is saved, or the user
    started Find OBD (the automatic search never looks past a saved adapter); it looks like an OBD adapter (name or
    serial service); its signal is at or above the pairing floor (CONFIG_OBD_BLE_PAIR_MIN_RSSI, -70 dBm); it is not
    skipped; and no other offer is open (one question at a time).

Pairing a new device (one at a time):
  IDLE -> PROBING   connected to it: the serial line and the ELM327 reset are tried. Nothing is logged or saved.
  PROBING -> ASKING it answered the reset like an ELM327: the caller drops the link at once and the user is asked.
  PROBING -> IDLE   it did not answer like an adapter (the caller's failure skip list takes it).
  ASKING -> IDLE    "Use this adapter" (OBD_ANS_YES) before the ask time ends: SAVE, the only path that saves.
                    "Not this one" (OBD_ANS_NO): skipped for this boot.
                    no answer within the ask time: not saved, skipped until the user's next Find OBD (or the next boot).
A skipped device is never offered again while it is skipped. The skip list holds OBD_PAIR_NSKIP devices; when it is full
the oldest entry is replaced.

Function

Comment in the header

void obd_pair_init(obd_pair_t *p);

obd_pick_t obd_pair_pick(const obd_pair_t *p, const obd_adv_t *a, int link_min_dbm, int pair_min_dbm);

bool obd_pair_skipped(const obd_pair_t *p, const uint8_t *key);

void obd_pair_probe(obd_pair_t *p, const uint8_t *key, const char *name, int rssi);

connected to an offered device: PROBING. The name is kept printable ASCII only (the screen fonts have nothing else).

bool obd_pair_is_probing(const obd_pair_t *p, const uint8_t *key);

void obd_pair_probe_failed(obd_pair_t *p);

bool obd_pair_probe_answered(obd_pair_t *p, int64_t now_ms, uint32_t ask_ms);

the probed device answered the ELM327 reset: ASKING until now + ask_ms. False (no change) unless it was PROBING.

obd_pair_result_t obd_pair_answer(obd_pair_t *p, obd_answer_t a, int64_t now_ms);

obd_pair_result_t obd_pair_tick(obd_pair_t *p, int64_t now_ms);

the ask time ran out: EXPIRED

void obd_pair_user_search(obd_pair_t *p);

the user’s Find OBD: expired devices may come back

bool obd_pair_offer(const obd_pair_t *p, int64_t now_ms, char *name, size_t n, const char **strength, int *secs_left);

the open question for the screen: false when none. Any out pointer may be NULL.

const char *obd_pair_strength(int rssi);

“strong” or “good”

clock_set.h#

Source: main/clock_set.h

Setting the clock by hand (ESP-Mosaico Settings > Clock): the pure parts, host-tested (tests/host `make clock`).

Clock source priority, highest first:
  Wi-Fi        the HTTPS time sync (wifi_sync.c, g_status.time_synced). Always wins when it syncs, also over a time
               set by hand, because a by-hand set clears time_synced and the sync task then keeps trying.
  set by hand  Settings > Clock > Set clock (shown in the normal colour)
  estimated    resumed from the last save on the storage after a power cut (sdlog.c, g_status.clock_estimated, amber)
  none         "no clock yet"

Function

Comment in the header

clock_src_t clock_source(const clock_flags_t *f);

const char *clock_source_name(clock_src_t s);

“Wi-Fi”, “set by hand”, “estimated”, “none”

void clock_on_manual(clock_flags_t *f);

transitions: a by-hand set, a Wi-Fi sync, and the boot after a software reset (the RTC kept the time and app_main marked it synced; rtc_manual = the RTC-memory note says the last source was a by-hand set)

void clock_on_wifi(clock_flags_t *f);

void clock_on_boot(clock_flags_t *f, bool rtc_manual);

clock_jump_t clock_jump_check(clock_src_t src, int64_t now_s, int64_t new_s);

bool clock_leap(int year);

int clock_days_in_month(int year, int month);

month 1..12; 0 for a bad month

bool clock_fields_ok(int year, int month, int day, int hour, int minute);

int clock_tz_count(void);

const clock_tz_t *clock_tz(int i);

int clock_tz_find(const char *tz);

index of an exact match, -1 if the string is not in the list

bool clock_local_to_epoch(const char *tz, int year, int month, int day, int hour, int minute, int64_t *epoch);

local date and time in zone tz -> Unix seconds. Sets TZ for the conversion and puts the caller’s TZ back. False when the fields or the zone are not valid or the result is outside harden_epoch_plausible(). A time inside a spring-forward gap comes back moved by the gap (mktime’s normalisation).