Reverse lights on DO0, Sport + Vehicle screens, per-DDE live data, ECU identification
Firmware / build (push) Successful in 10m49s
Firmware / build (push) Successful in 10m49s
- ReverseLight: isolated output DO0 (CH422G OC0 -> PC817 -> NPN sink) drives the reverse-lamp relay while the lever is in R on a live bus with ignition on; 10 Hz decision confirmed over 200 ms, written through the panel library's expander object so the backlight cannot undo it; `reverse status|on|off|force` console, default ON (NVS `revlight_en`). Wiki page reverse-lights-output with the wiring. - Sport screen: BMW-style power + torque gauges (lv_meter on a dial-face image, image needle); PNG sources in assets/, tools/png2lvgl.py converter. - Vehicle: final drive ratio + tyre circumference -> road speed, hp from torque; Settings > Vehicle page; `vehicle` console. - Bench simulation (`sim` console) overlays torque / rpm / shaft on the snapshot. - EcuIdent: KWP 1A 86 / 1A 80 read once, stored in NVS, shown on Settings > Vehicle, passive ECU CHANGED? check; `ecu` console. - Ignition fallback from the 0x1D2 lever byte on buses without 0x3B4 (Patrol 2). - Engine data: per-DDE `2C 10` identifier profiles (Patrol 1 vs Patrol 2 rail 00C2 / boost 003A / battery 002F); DiagProbe liveConfigure(). - Wiki: Patrol 2 captures, vehicles page, obd identifier table per DDE, logs.
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* Bench Simulation Module Implementation - see bench_sim.h
|
||||
*/
|
||||
|
||||
#include "bench_sim.h"
|
||||
#include "serial_lock.h"
|
||||
#include "vehicle.h"
|
||||
|
||||
namespace BenchSim {
|
||||
|
||||
// ============================================================================
|
||||
// PRIVATE MODULE STATE
|
||||
// ============================================================================
|
||||
|
||||
static volatile bool g_active = false;
|
||||
static volatile int16_t g_torque_x10 = 0;
|
||||
static volatile uint16_t g_rpm = 0;
|
||||
static volatile uint16_t g_shaft_raw = 0;
|
||||
|
||||
static void print(const char* fmt, ...) {
|
||||
char buf[200];
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
vsnprintf(buf, sizeof(buf), fmt, ap);
|
||||
va_end(ap);
|
||||
SerialLock::lock();
|
||||
Serial.println(buf);
|
||||
SerialLock::unlock();
|
||||
}
|
||||
|
||||
static void status() {
|
||||
if (!g_active) { print("[sim] off - screens show the CAN bus"); return; }
|
||||
uint16_t shaft_rpm = can_output_shaft_rpm(g_shaft_raw);
|
||||
uint16_t hp = Vehicle::powerHpX10(g_torque_x10, g_rpm);
|
||||
uint16_t kmh = Vehicle::speedKmhX10(g_shaft_raw);
|
||||
print("[sim] ON: torque %d.%d Nm, engine %u rpm -> %u.%u hp; output shaft %u rpm (raw %u) -> %u.%u km/h (not saved)",
|
||||
g_torque_x10 / 10, abs(g_torque_x10 % 10), g_rpm, hp / 10, hp % 10,
|
||||
shaft_rpm, g_shaft_raw, kmh / 10, kmh % 10);
|
||||
}
|
||||
|
||||
static void help() {
|
||||
print("sim torque <Nm> [rpm <n>] [shaft <rpm>] bench values for the Sport / Driveline screens");
|
||||
print("sim rpm <n> engine speed (power = torque x rpm)");
|
||||
print("sim shaft <rpm> output shaft speed (road speed on screen)");
|
||||
print("sim status");
|
||||
print("sim off back to the CAN bus (also at every boot)");
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// PUBLIC API
|
||||
// ============================================================================
|
||||
|
||||
bool isActive() { return g_active; }
|
||||
|
||||
void apply(driveline_t& dl) {
|
||||
if (!g_active) return;
|
||||
dl.engine_torque_x10 = g_torque_x10;
|
||||
dl.engine_rpm = g_rpm;
|
||||
dl.output_shaft_raw = g_shaft_raw;
|
||||
dl.ignition_on = true;
|
||||
dl.engine_run_state = ENGINE_RUN_RUNNING;
|
||||
}
|
||||
|
||||
bool handleCommand(const char* line) {
|
||||
if (strncmp(line, "sim", 3) != 0 || (line[3] != 0 && line[3] != ' ')) return false;
|
||||
char buf[96];
|
||||
snprintf(buf, sizeof(buf), "%s", line);
|
||||
char* argv[8];
|
||||
int argc = 0;
|
||||
for (char* t = strtok(buf, " \t"); t && argc < 8; t = strtok(NULL, " \t")) argv[argc++] = t;
|
||||
|
||||
if (argc == 1 || !strcmp(argv[1], "help")) { help(); return true; }
|
||||
if (!strcmp(argv[1], "status")) { status(); return true; }
|
||||
if (!strcmp(argv[1], "off")) {
|
||||
g_active = false;
|
||||
g_torque_x10 = 0; g_rpm = 0; g_shaft_raw = 0;
|
||||
print("[sim] off");
|
||||
return true;
|
||||
}
|
||||
|
||||
// any number of "<name> <value>" pairs
|
||||
bool ok = argc >= 3 && (argc % 2) == 1;
|
||||
for (int i = 1; ok && i + 1 < argc; i += 2) {
|
||||
long v = strtol(argv[i + 1], NULL, 0);
|
||||
if (!strcmp(argv[i], "torque")) g_torque_x10 = (int16_t)constrain(v, -3000, 3000) * 10;
|
||||
else if (!strcmp(argv[i], "rpm")) g_rpm = (uint16_t)constrain(v, 0, 10000);
|
||||
else if (!strcmp(argv[i], "shaft")) g_shaft_raw = (uint16_t)constrain((v * OUTPUT_SHAFT_RPM_DEN) / OUTPUT_SHAFT_RPM_NUM, 0, 65535);
|
||||
else ok = false;
|
||||
}
|
||||
if (!ok) { help(); return true; }
|
||||
g_active = true;
|
||||
status();
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace BenchSim
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Bench Simulation Module (`sim` console)
|
||||
*
|
||||
* Feeds made-up torque / engine rpm / output shaft values into the driveline
|
||||
* snapshot so the Sport screen, the Driveline and the Vehicle page can be
|
||||
* looked at on the bench without a CAN bus. While active, the snapshot also
|
||||
* reads ignition on + engine running, so the screens treat it as live.
|
||||
*
|
||||
* Bench tool only: never saved, off at every boot, nothing is transmitted,
|
||||
* and the Inst. Cluster is not affected (that side has `cfg override`).
|
||||
* The screens say "SIM" while it is on so a simulated number is never
|
||||
* mistaken for the car's.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include "drivers/can_driver.h"
|
||||
|
||||
namespace BenchSim {
|
||||
|
||||
/** True while a simulation is active (`sim ...` until `sim off`). */
|
||||
bool isActive();
|
||||
|
||||
/** Overlay the simulated fields onto a driveline snapshot. No-op when off. */
|
||||
void apply(driveline_t& dl);
|
||||
|
||||
/** `sim torque <Nm> | rpm <n> | shaft <rpm> | status | off` (several pairs per line). */
|
||||
bool handleCommand(const char* line);
|
||||
|
||||
} // namespace BenchSim
|
||||
+108
-12
@@ -81,8 +81,11 @@ static uint32_t g_tx_fail_at_send = 0; // CANDriver tx_failures when the reque
|
||||
static bool g_last_req_unacked = false;
|
||||
|
||||
// live engine data (Engine data screen) - liveStop() is public, declared in the header
|
||||
static const uint16_t LIVE_IDS[LIVE_COUNT] = {0x00DF, 0x0091, 0x16A8, 0x0093};
|
||||
static const uint16_t LIVE_DEFINE_ID = 0x15E0; // the Launch sends `2C 10 15 E0` once on connect
|
||||
// Which `2C 10 <id>` identifiers to ask is PER DDE SOFTWARE (Patrol 1's set
|
||||
// returned junk on Patrol 2, 2026-10-18): the Engine data screen picks a set
|
||||
// from its per-ECU profile table and installs it with liveConfigure(). Until
|
||||
// then nothing is asked. 0 = no identifier for that slot (never requested).
|
||||
static live_set_t g_live_set = {0, {0, 0, 0, 0}};
|
||||
static const uint32_t LIVE_GAP_MS = 80; // between requests (plus the loop's 100 ms tick)
|
||||
static const uint32_t LIVE_KEEPALIVE_MS = 1500; // stop this long after the screen stops asking
|
||||
static const uint8_t LIVE_NO_ANSWER_AFTER = 4; // consecutive timeouts
|
||||
@@ -97,6 +100,16 @@ static bool g_live_req = false; // the request in flight is a l
|
||||
static int8_t g_live_req_index = -1; // -1 = the define request
|
||||
static struct { bool valid; uint16_t raw; uint32_t at_ms; uint8_t nrc; } g_live_vals[LIVE_COUNT];
|
||||
|
||||
// ECU identification: handler + a passive reassembler for OTHER testers' `1A xx`
|
||||
// replies on 0x612 (we see the DDE's frames whoever asked; the asker sends the
|
||||
// flow control). CAN-task only, so no lock.
|
||||
static const size_t IDENT_MAX = 96; // `1A 80` is 31-37 bytes, `1A 86` 65
|
||||
static ident_cb_t g_ident_cb = NULL;
|
||||
static uint8_t g_pid_buf[IDENT_MAX];
|
||||
static size_t g_pid_len = 0, g_pid_exp = 0;
|
||||
static uint8_t g_pid_seq = 0;
|
||||
static bool g_pid_active = false;
|
||||
|
||||
// ============================================================================
|
||||
// HELPERS
|
||||
// ============================================================================
|
||||
@@ -421,6 +434,10 @@ static void handleReply(uint32_t id, const uint8_t* p, size_t n) {
|
||||
as[k] = 0;
|
||||
print("[diag] +%03u %-48s |%s|", (unsigned)(i - 1), hx, as);
|
||||
}
|
||||
// our own identification read: hand the block to EcuIdent
|
||||
if (g_req_mode == 0x1A && g_bmw_target == BMW_ADDR_DDE && n >= 2 && g_ident_cb) {
|
||||
g_ident_cb(p[1], p, n, true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -471,10 +488,46 @@ static void handleReply(uint32_t id, const uint8_t* p, size_t n) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reassemble a `5A xx` identification reply the DDE sends to ANOTHER tester
|
||||
* (our own request's reply goes through handleReply). Extended addressing:
|
||||
* byte 0 = 0xF1 (the tester), then the ISO-TP PCI.
|
||||
*/
|
||||
static void passiveIdent(const twai_message_t& m) {
|
||||
const uint8_t* d = m.data;
|
||||
uint8_t dlc = m.data_length_code;
|
||||
if (dlc < 3 || d[0] != 0xF1) return;
|
||||
if (g_state == ST_WAITING && g_bmw && g_bmw_target == BMW_ADDR_DDE) return; // ours: handled elsewhere
|
||||
|
||||
uint8_t pci = d[1] >> 4;
|
||||
if (pci == 0x1) { // first frame: F1 1L LL 5A xx ...
|
||||
if (dlc < 5 || d[3] != 0x5A) { g_pid_active = false; return; }
|
||||
g_pid_exp = ((size_t)(d[1] & 0x0F) << 8) | d[2];
|
||||
if (g_pid_exp > IDENT_MAX) g_pid_exp = IDENT_MAX;
|
||||
g_pid_len = 0;
|
||||
for (uint8_t i = 3; i < dlc && g_pid_len < g_pid_exp; i++) g_pid_buf[g_pid_len++] = d[i];
|
||||
g_pid_seq = 1;
|
||||
g_pid_active = true;
|
||||
} else if (pci == 0x2) { // consecutive frame: F1 2N ...
|
||||
if (!g_pid_active || (d[1] & 0x0F) != (g_pid_seq & 0x0F)) return;
|
||||
for (uint8_t i = 2; i < dlc && g_pid_len < g_pid_exp; i++) g_pid_buf[g_pid_len++] = d[i];
|
||||
g_pid_seq++;
|
||||
if (g_pid_len >= g_pid_exp) {
|
||||
g_pid_active = false;
|
||||
if (g_pid_len >= 2) g_ident_cb(g_pid_buf[1], g_pid_buf, g_pid_len, false);
|
||||
}
|
||||
} else if (pci == 0x0) { // single frame (not seen from a DDE, but cheap)
|
||||
size_t len = d[1] & 0x0F;
|
||||
if (len >= 2 && 2 + len <= dlc && d[2] == 0x5A) g_ident_cb(d[3], d + 2, len, false);
|
||||
}
|
||||
}
|
||||
|
||||
void onFrame(const twai_message_t& m) {
|
||||
if (m.extd) return;
|
||||
uint32_t id = m.identifier;
|
||||
|
||||
if (id == BMW_RX_BASE + BMW_ADDR_DDE && g_ident_cb) passiveIdent(m);
|
||||
|
||||
// Foreign tester activity: our own frames are not looped back in NORMAL mode,
|
||||
// so anything on these IDs is somebody else's request.
|
||||
if (id == OBD_FUNCTIONAL_ID || (id >= OBD_REQ_FIRST && id <= OBD_REQ_LAST) || id == BMW_TESTER_ID) {
|
||||
@@ -581,7 +634,7 @@ static void printScanSummary() {
|
||||
|
||||
/** One fixed `2C 10 <id>` request to the DDE for the live poll. Caller checked the guards. */
|
||||
static void sendLive(int8_t index) {
|
||||
uint16_t vid = index < 0 ? LIVE_DEFINE_ID : LIVE_IDS[index];
|
||||
uint16_t vid = index < 0 ? g_live_set.define_id : g_live_set.ids[index];
|
||||
uint8_t f[8];
|
||||
memset(f, PAD_BYTE, sizeof(f));
|
||||
f[0] = BMW_ADDR_DDE;
|
||||
@@ -627,11 +680,17 @@ static void liveTick() {
|
||||
g_live_last_tx = now;
|
||||
if (!g_live_defined) {
|
||||
g_live_defined = true;
|
||||
sendLive(-1);
|
||||
} else {
|
||||
sendLive((int8_t)g_live_next);
|
||||
g_live_next = (g_live_next + 1) % LIVE_COUNT;
|
||||
if (g_live_set.define_id) { sendLive(-1); return; }
|
||||
}
|
||||
// next slot that has an identifier on this DDE (at most one full turn)
|
||||
for (int i = 0; i < LIVE_COUNT; i++) {
|
||||
uint8_t slot = (uint8_t)((g_live_next + i) % LIVE_COUNT);
|
||||
if (g_live_set.ids[slot] == 0) continue;
|
||||
g_live_next = (uint8_t)((slot + 1) % LIVE_COUNT);
|
||||
sendLive((int8_t)slot);
|
||||
return;
|
||||
}
|
||||
// no identifiers at all: nothing to ask (the screen says so)
|
||||
}
|
||||
|
||||
void tick() {
|
||||
@@ -829,19 +888,33 @@ void init() {
|
||||
// Live engine data
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
void liveKeepAlive() {
|
||||
g_live_keep_ms = millis();
|
||||
if (g_live) return;
|
||||
static void liveRestart() {
|
||||
lock();
|
||||
memset(g_live_vals, 0, sizeof(g_live_vals));
|
||||
unlock();
|
||||
g_live = true;
|
||||
g_live_defined = false;
|
||||
g_live_next = 0;
|
||||
g_live_misses = 0;
|
||||
g_live_last_tx = 0;
|
||||
g_live_state = LIVE_RUNNING;
|
||||
print("[diag] live engine data ON: polling the DDE (2C 10 00DF/0091/16A8/0093)");
|
||||
}
|
||||
|
||||
void liveConfigure(const live_set_t* set) {
|
||||
live_set_t s = set ? *set : live_set_t{0, {0, 0, 0, 0}};
|
||||
if (memcmp(&s, &g_live_set, sizeof(s)) == 0) return;
|
||||
g_live_set = s;
|
||||
if (g_live) liveRestart(); // old values belong to the old identifiers
|
||||
print("[diag] live engine data identifiers: define %04X, rail %04X, boost %04X, air temp %04X, battery %04X (0 = not asked)",
|
||||
s.define_id, s.ids[LIVE_RAIL], s.ids[LIVE_BOOST], s.ids[LIVE_AIR_TEMP], s.ids[LIVE_BATTERY]);
|
||||
}
|
||||
|
||||
void liveKeepAlive() {
|
||||
g_live_keep_ms = millis();
|
||||
if (g_live) return;
|
||||
g_live = true;
|
||||
liveRestart();
|
||||
print("[diag] live engine data ON: polling the DDE (2C 10 %04X/%04X/%04X/%04X, 0 = not asked)",
|
||||
g_live_set.ids[LIVE_RAIL], g_live_set.ids[LIVE_BOOST], g_live_set.ids[LIVE_AIR_TEMP], g_live_set.ids[LIVE_BATTERY]);
|
||||
}
|
||||
|
||||
void liveStop() {
|
||||
@@ -867,4 +940,27 @@ live_value_t liveValue(live_id_t id) {
|
||||
return out;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// ECU identification
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
bool canSendNow() {
|
||||
if (!CANDriver::isActive()) return false;
|
||||
uint32_t now = millis();
|
||||
lock();
|
||||
bool busy = (g_state != ST_IDLE);
|
||||
bool tester = (g_last_tester_ms != 0) && (now - g_last_tester_ms < TESTER_GUARD_MS);
|
||||
unlock();
|
||||
return !busy && !tester;
|
||||
}
|
||||
|
||||
bool requestIdent(uint8_t sub) {
|
||||
uint8_t req[2] = {0x1A, sub};
|
||||
return sendBmwRequest(BMW_ADDR_DDE, req, sizeof(req));
|
||||
}
|
||||
|
||||
void setIdentHandler(ident_cb_t cb) {
|
||||
g_ident_cb = cb;
|
||||
}
|
||||
|
||||
} // namespace DiagProbe
|
||||
|
||||
@@ -29,12 +29,15 @@
|
||||
* 21/22 (read data) — never session control, resets, or writes.
|
||||
*
|
||||
* Live engine data (Engine data screen, 2026-10-07): while the screen keeps
|
||||
* calling liveKeepAlive(), the probe polls four DDE values with the same
|
||||
* KWP `2C 10 <id>` requests the Launch uses (one-time `2C 10 15 E0`, then
|
||||
* rail 00DF, boost 0091, charge-air temp 16A8, battery 0093 in turn, one
|
||||
* request in flight, ~100 ms apart). Quiet on the console, pauses while
|
||||
* another tester is on the bus, stops 1.5 s after the last keep-alive.
|
||||
* `2C` is NOT allowed from the console - only these fixed frames.
|
||||
* calling liveKeepAlive(), the probe polls up to four DDE values with the
|
||||
* same KWP `2C 10 <id>` requests the Launch uses (an optional one-time
|
||||
* define, then the slot identifiers in turn, one request in flight, ~100 ms
|
||||
* apart). The identifiers are installed by the screen per identified DDE
|
||||
* (liveConfigure(); Patrol 1: define 15E0, rail 00DF, boost 0091, charge-air
|
||||
* temp 16A8, battery 0093; Patrol 2: rail 00C2, boost 003A, battery 002F).
|
||||
* Quiet on the console,
|
||||
* pauses while another tester is on the bus, stops 1.5 s after the last
|
||||
* keep-alive. `2C` is NOT allowed from the console - only these frames.
|
||||
*
|
||||
* Every frame we send is echoed on the console as
|
||||
* CANTX,<ts_ms>,<id_hex>,0,<dlc>,<data_hex>
|
||||
@@ -85,6 +88,22 @@ typedef struct {
|
||||
uint8_t nrc; // last negative-response code (0 = none)
|
||||
} live_value_t;
|
||||
|
||||
/**
|
||||
* The `2C 10 <id>` identifiers to poll, one per live_id_t slot, 0 = none known
|
||||
* for this DDE (that slot is never requested, liveValue() stays invalid), plus
|
||||
* the one-time define id sent first (0 = none). THE IDENTIFIERS DIFFER PER DDE
|
||||
* SOFTWARE: Patrol 1's set read junk on Patrol 2 (2026-10-18), so the Engine
|
||||
* data screen installs the set that matches the identified ECU (`EcuIdent`).
|
||||
* Nothing is asked until a set with at least one identifier is installed.
|
||||
*/
|
||||
typedef struct {
|
||||
uint16_t define_id;
|
||||
uint16_t ids[LIVE_COUNT];
|
||||
} live_set_t;
|
||||
|
||||
/** Install the identifier set (NULL = none). Restarts the values if polling. */
|
||||
void liveConfigure(const live_set_t* set);
|
||||
|
||||
/** Keep the live poll running; starts it if needed. Call from loop() while the screen is shown. */
|
||||
void liveKeepAlive();
|
||||
|
||||
@@ -94,4 +113,27 @@ void liveStop();
|
||||
live_state_t liveState();
|
||||
live_value_t liveValue(live_id_t id);
|
||||
|
||||
// ---- ECU identification (EcuIdent module) ----------------------------------
|
||||
|
||||
/**
|
||||
* True when a request could go out right now: CAN running, nothing in flight,
|
||||
* no foreign tester for TESTER_GUARD_MS. Prints nothing (unlike a refused send).
|
||||
*/
|
||||
bool canSendNow();
|
||||
|
||||
/**
|
||||
* One KWP `1A <sub>` identification request to the DDE on 0x6F1 (sub 0x86 or
|
||||
* 0x80), console-echoed like `diag ident`. Returns false if refused.
|
||||
*/
|
||||
bool requestIdent(uint8_t sub);
|
||||
|
||||
/**
|
||||
* Handler for every complete `5A <sub> ...` identification payload the DDE puts
|
||||
* on 0x612: the reply to our own request (ours = true), or to another tester's
|
||||
* (ours = false - the Launch re-reads `1A 80` every cycle, so a connected scan
|
||||
* tool identifies the ECU for free). Runs in the CAN task: copy and return.
|
||||
*/
|
||||
typedef void (*ident_cb_t)(uint8_t sub, const uint8_t* payload, size_t n, bool ours);
|
||||
void setIdentHandler(ident_cb_t cb);
|
||||
|
||||
} // namespace DiagProbe
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
namespace DisplayInit {
|
||||
|
||||
static Backlight* g_backlight = nullptr;
|
||||
static esp_expander::Base* g_expander = nullptr;
|
||||
|
||||
/**
|
||||
* Firmware version, bottom-right on every screen. Lives on lv_layer_top(), which
|
||||
@@ -25,6 +26,8 @@ static void createVersionLabel() {
|
||||
lv_obj_align(lbl, LV_ALIGN_BOTTOM_RIGHT, -8, -4);
|
||||
}
|
||||
|
||||
esp_expander::Base* expander() { return g_expander; }
|
||||
|
||||
void setBacklight(bool on) {
|
||||
if (g_backlight == nullptr) return;
|
||||
if (on) g_backlight->on();
|
||||
@@ -117,6 +120,7 @@ DisplayObjects init() {
|
||||
|
||||
// Return board and backlight objects for later use
|
||||
g_backlight = backlight;
|
||||
g_expander = board->getIO_Expander() ? board->getIO_Expander()->getBase() : nullptr;
|
||||
return {board, backlight};
|
||||
}
|
||||
|
||||
|
||||
@@ -46,4 +46,13 @@ DisplayObjects init();
|
||||
/** Backlight on/off after init() (e.g. dark during OTA flash writes, which flicker the panel). */
|
||||
void setBacklight(bool on);
|
||||
|
||||
/**
|
||||
* The board's CH422G IO expander (panel library object), after init(). Modules
|
||||
* that drive its OC pins (ReverseLight: OC0 = DO0) must go through this object,
|
||||
* never raw I2C, so the library's cached output register stays right - the
|
||||
* backlight writes that cache back to the chip on every on/off. NULL if the
|
||||
* board has no expander.
|
||||
*/
|
||||
esp_expander::Base* expander();
|
||||
|
||||
} // namespace DisplayInit
|
||||
|
||||
@@ -12,6 +12,9 @@
|
||||
#include "settings_screen.h"
|
||||
#include "diff_locks.h"
|
||||
#include "engine_screen.h"
|
||||
#include "sport_screen.h"
|
||||
#include "vehicle.h"
|
||||
#include "bench_sim.h"
|
||||
#include "ui_kit.h"
|
||||
#include "esp_log.h"
|
||||
|
||||
@@ -49,6 +52,7 @@ static lv_obj_t* g_rpm_lbl = NULL;
|
||||
static lv_obj_t* g_torque_lbl = NULL;
|
||||
static lv_obj_t* g_pedal_lbl = NULL;
|
||||
static lv_obj_t* g_shaft_lbl = NULL;
|
||||
static lv_obj_t* g_speed_lbl = NULL;
|
||||
static lv_obj_t* g_ign_chip = NULL;
|
||||
static lv_obj_t* g_eng_chip = NULL;
|
||||
static lv_obj_t* g_clutch_chip = NULL;
|
||||
@@ -331,6 +335,11 @@ static void onEngineData(lv_event_t* e) {
|
||||
EngineScreen::show();
|
||||
}
|
||||
|
||||
static void onSport(lv_event_t* e) {
|
||||
(void)e;
|
||||
SportScreen::show();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Build the screen. Idempotent — returns immediately if already built.
|
||||
*/
|
||||
@@ -397,6 +406,11 @@ static void build() {
|
||||
UiKit::BTN_SECONDARY, onEngineData, NULL);
|
||||
lv_obj_align(eng, LV_ALIGN_TOP_RIGHT, -16 - DL_BOX_W - 16, 60);
|
||||
|
||||
// Sport displays (torque + power gauges), left of the Engine data button.
|
||||
lv_obj_t* sport = UiKit::button(g_screen, "Sport", 150, 56,
|
||||
UiKit::BTN_SECONDARY, onSport, NULL);
|
||||
lv_obj_align(sport, LV_ALIGN_TOP_RIGHT, -16 - DL_BOX_W - 16 - 200 - 12, 60);
|
||||
|
||||
// ---- gear hero -------------------------------------------------------
|
||||
g_gear_ring = lv_obj_create(g_screen);
|
||||
lv_obj_set_size(g_gear_ring, 220, 220);
|
||||
@@ -444,23 +458,27 @@ static void build() {
|
||||
lv_obj_set_style_text_color(g_rpm_lbl, COL_TEXT, 0);
|
||||
lv_obj_align(g_rpm_lbl, LV_ALIGN_CENTER, 330, 108);
|
||||
|
||||
// ---- bottom row: torque | pedal | output shaft -----------------------
|
||||
// ---- bottom row: torque | pedal | output shaft | speed ---------------
|
||||
// Turbine speed is intentionally NOT shown: it's a diagnostic (engagement
|
||||
// proof), not a driver number. Still decoded in the driver.
|
||||
g_torque_lbl = makeStat(g_screen, "TORQUE (Nm)", &lv_font_montserrat_30,
|
||||
LV_ALIGN_BOTTOM_MID, -340, -34);
|
||||
LV_ALIGN_BOTTOM_MID, -390, -34);
|
||||
g_pedal_lbl = makeStat(g_screen, "PEDAL (%)", &lv_font_montserrat_30,
|
||||
LV_ALIGN_BOTTOM_MID, 0, -34);
|
||||
LV_ALIGN_BOTTOM_MID, -130, -34);
|
||||
// Output shaft in rpm via a PROVISIONAL factor (one Launch point). The label
|
||||
// carries "~" so the screen doesn't present an unlocked scaling as exact.
|
||||
g_shaft_lbl = makeStat(g_screen, "OUTPUT (~rpm)", &lv_font_montserrat_30,
|
||||
LV_ALIGN_BOTTOM_MID, 340, -34);
|
||||
LV_ALIGN_BOTTOM_MID, 130, -34);
|
||||
// Road speed = output shaft / final drive x tyre circumference (Settings >
|
||||
// Vehicle). Inherits the "~" of the shaft factor.
|
||||
g_speed_lbl = makeStat(g_screen, "SPEED (~km/h)", &lv_font_montserrat_30,
|
||||
LV_ALIGN_BOTTOM_MID, 390, -34);
|
||||
|
||||
lv_obj_t* hint = lv_label_create(g_screen);
|
||||
lv_label_set_text(hint, LV_SYMBOL_LEFT " swipe left: Settings | swipe right: Gauge tuning " LV_SYMBOL_RIGHT);
|
||||
lv_obj_set_style_text_font(hint, &lv_font_montserrat_14, 0);
|
||||
lv_obj_set_style_text_color(hint, COL_MUTED, 0);
|
||||
lv_obj_align(hint, LV_ALIGN_BOTTOM_LEFT, 24, -14);
|
||||
lv_obj_align(hint, LV_ALIGN_BOTTOM_LEFT, 24, -8);
|
||||
|
||||
ESP_LOGI("Driveline", "Driveline screen built");
|
||||
}
|
||||
@@ -484,7 +502,7 @@ void tick() {
|
||||
if (millis() - last_refresh < 100) return;
|
||||
last_refresh = millis();
|
||||
|
||||
bool can_up = CANDriver::isActive();
|
||||
bool can_up = CANDriver::isActive() || BenchSim::isActive(); // `sim` console counts as a live bus
|
||||
driveline_t dl = CANDriver::getDriveline();
|
||||
|
||||
// Snapshot the shared struct under its own mutex, briefly.
|
||||
@@ -512,7 +530,8 @@ void tick() {
|
||||
// Blank every readout when there's nothing live to show: CAN off, or the key
|
||||
// is off. The user asked for a full reset on ignition-off so the screen goes
|
||||
// quiet with the car rather than freezing the last frame. 0x3B4 sends its
|
||||
// ignition nibble on-change, so this reset is effectively instant.
|
||||
// ignition nibble on-change, and the 0x1D2 lever fallback (buses without
|
||||
// 0x3B4) flips within one 200 ms frame, so this reset is effectively instant.
|
||||
if (!can_up || !dl.ignition_on) {
|
||||
setText(g_gear_lbl, "--");
|
||||
setText(g_coolant_lbl, "--");
|
||||
@@ -521,6 +540,7 @@ void tick() {
|
||||
setText(g_torque_lbl, "--");
|
||||
setText(g_pedal_lbl, "--");
|
||||
setText(g_shaft_lbl, "--");
|
||||
setText(g_speed_lbl, "--");
|
||||
lv_bar_set_value(g_rpm_bar, 0, LV_ANIM_OFF);
|
||||
setRing(COL_ACCENT);
|
||||
setColour(g_gear_lbl, COL_TEXT);
|
||||
@@ -576,8 +596,13 @@ void tick() {
|
||||
lv_bar_set_value(g_rpm_bar, dl.engine_rpm > RPM_MAX ? RPM_MAX : dl.engine_rpm, LV_ANIM_OFF);
|
||||
|
||||
// Torque is signed (negative under overrun/braking); one decimal, matching
|
||||
// the 0.5 Nm resolution of the field.
|
||||
snprintf(buf, sizeof(buf), "%d.%d", dl.engine_torque_x10 / 10, abs(dl.engine_torque_x10 % 10));
|
||||
// the 0.5 Nm resolution of the field. Engine off: the field holds a junk
|
||||
// value (812 Nm on Patrol 2, 245 on Patrol 1), so show nothing.
|
||||
if (dl.engine_run_state == ENGINE_RUN_RUNNING) {
|
||||
snprintf(buf, sizeof(buf), "%d.%d", dl.engine_torque_x10 / 10, abs(dl.engine_torque_x10 % 10));
|
||||
} else {
|
||||
snprintf(buf, sizeof(buf), "--");
|
||||
}
|
||||
setText(g_torque_lbl, buf);
|
||||
|
||||
snprintf(buf, sizeof(buf), "%u", dl.pedal_percent);
|
||||
@@ -587,9 +612,15 @@ void tick() {
|
||||
snprintf(buf, sizeof(buf), "%u", can_output_shaft_rpm(dl.output_shaft_raw));
|
||||
setText(g_shaft_lbl, buf);
|
||||
|
||||
// Road speed from the same shaft reading and the Settings > Vehicle numbers.
|
||||
uint16_t kmh_x10 = Vehicle::speedKmhX10(dl.output_shaft_raw);
|
||||
snprintf(buf, sizeof(buf), "%u", kmh_x10 / 10);
|
||||
setText(g_speed_lbl, buf);
|
||||
|
||||
// ---- status chips ----------------------------------------------------
|
||||
setChip(g_ign_chip, dl.ignition_on ? "IGN ON" : "IGN OFF",
|
||||
dl.ignition_on ? COL_OK : COL_MUTED);
|
||||
if (BenchSim::isActive()) setChip(g_ign_chip, "IGN SIM", COL_AMBER); // bench numbers, not the car's
|
||||
else setChip(g_ign_chip, dl.ignition_on ? "IGN ON" : "IGN OFF",
|
||||
dl.ignition_on ? COL_OK : COL_MUTED);
|
||||
|
||||
switch (dl.engine_run_state) {
|
||||
case ENGINE_RUN_RUNNING: setChip(g_eng_chip, "ENG RUN", COL_OK); break;
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
/*
|
||||
* ECU Identification Module Implementation - see ecu_ident.h
|
||||
*
|
||||
* Threading: onIdent() runs in the CAN task and only parks the payload;
|
||||
* everything else (sequencing, NVS, console) runs in loop() via tick().
|
||||
*/
|
||||
|
||||
#include "ecu_ident.h"
|
||||
#include "diag_probe.h"
|
||||
#include "bench_sim.h"
|
||||
#include "serial_lock.h"
|
||||
#include "drivers/can_driver.h"
|
||||
#include <Preferences.h>
|
||||
|
||||
namespace EcuIdent {
|
||||
|
||||
// ============================================================================
|
||||
// CONSTANTS
|
||||
// ============================================================================
|
||||
|
||||
static const char* NVS_NAMESPACE = "settings";
|
||||
static const char* NVS_KEY_86 = "ecu_id86";
|
||||
static const char* NVS_KEY_80 = "ecu_id80";
|
||||
static const size_t BLOCK_MAX = 96;
|
||||
|
||||
static const uint8_t SUB_86 = 0x86, SUB_80 = 0x80;
|
||||
static const uint8_t ATTEMPTS_PER_SUB = 3; // per boot, while nothing is stored
|
||||
static const uint32_t RETRY_GAP_MS = 10000; // between attempts
|
||||
static const uint32_t SETTLE_MS = 5000; // ignition on this long before the first ask
|
||||
static const uint32_t ANSWER_WAIT_MS = 1500; // DiagProbe's own timeout is 500 ms + linger
|
||||
|
||||
// ============================================================================
|
||||
// STATE
|
||||
// ============================================================================
|
||||
|
||||
typedef struct {
|
||||
uint8_t sub;
|
||||
uint8_t len; // 0 = empty
|
||||
uint8_t raw[BLOCK_MAX];
|
||||
} block_t;
|
||||
|
||||
static block_t g_blk[2] = {{SUB_86, 0, {0}}, {SUB_80, 0, {0}}}; // [0] = 1A 86, [1] = 1A 80
|
||||
|
||||
// CAN task -> loop handoff (single writer, single reader)
|
||||
static volatile bool g_pending = false;
|
||||
static block_t g_pending_blk;
|
||||
static bool g_pending_ours = false;
|
||||
|
||||
// one-shot read sequencing
|
||||
static bool g_read_session = false; // true while this boot is allowed to transmit
|
||||
static uint8_t g_attempts[2] = {0, 0};
|
||||
static uint32_t g_last_try_ms = 0;
|
||||
static uint32_t g_ign_since_ms = 0; // first tick with ignition on (0 = not yet)
|
||||
static bool g_waiting = false; // a request of ours is out
|
||||
static bool g_gave_up_printed = false;
|
||||
|
||||
// passive check
|
||||
static bool g_changed = false;
|
||||
static char g_bus_part[12] = ""; // part number of the differing 1A 80 block seen on the bus
|
||||
|
||||
// ============================================================================
|
||||
// HELPERS
|
||||
// ============================================================================
|
||||
|
||||
static void print(const char* fmt, ...) {
|
||||
char buf[200];
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
vsnprintf(buf, sizeof(buf), fmt, ap);
|
||||
va_end(ap);
|
||||
SerialLock::lock();
|
||||
Serial.println(buf);
|
||||
SerialLock::unlock();
|
||||
}
|
||||
|
||||
static block_t* blockFor(uint8_t sub) {
|
||||
if (sub == SUB_86) return &g_blk[0];
|
||||
if (sub == SUB_80) return &g_blk[1];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static block_t* primary() {
|
||||
if (g_blk[0].len) return &g_blk[0];
|
||||
if (g_blk[1].len) return &g_blk[1];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/** BCD bytes -> decimal string without leading zeros ("" if any nibble > 9). */
|
||||
static bool bcd(const uint8_t* p, size_t n, char* out, size_t out_sz) {
|
||||
size_t w = 0;
|
||||
bool started = false;
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
uint8_t hi = p[i] >> 4, lo = p[i] & 0x0F;
|
||||
if (hi > 9 || lo > 9) { out[0] = 0; return false; }
|
||||
if (started || hi) { if (w + 1 < out_sz) out[w++] = (char)('0' + hi); started = true; }
|
||||
if (started || lo) { if (w + 1 < out_sz) out[w++] = (char)('0' + lo); started = true; }
|
||||
}
|
||||
if (!started && w + 1 < out_sz) out[w++] = '0';
|
||||
out[w] = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** The part number this block carries (observed offsets), "" if it does not fit. */
|
||||
static void partOf(const block_t* b, char* out, size_t out_sz) {
|
||||
out[0] = 0;
|
||||
if (!b || !b->len) return;
|
||||
// 1A 86: 5A 86 "@B892524 " 06 03 07 00 00 [07 79 97 64] ... (Patrol 1, 2026-09-23)
|
||||
// 1A 80: 5A 80 00 00 [07 79 49 04] 10 00 00 10 35 39 20 04 01 21 ... (Patrol 2, 2026-10-18)
|
||||
if (b->sub == SUB_86 && b->len >= 20) bcd(b->raw + 16, 4, out, out_sz);
|
||||
else if (b->sub == SUB_80 && b->len >= 8) bcd(b->raw + 4, 4, out, out_sz);
|
||||
}
|
||||
|
||||
/** "20YY-MM-DD" from the block's BCD date, "" if absent or implausible. */
|
||||
static void dateOf(const block_t* b, char* out, size_t out_sz) {
|
||||
out[0] = 0;
|
||||
if (!b || !b->len) return;
|
||||
const uint8_t* d = NULL;
|
||||
if (b->sub == SUB_86 && b->len >= 14) d = b->raw + 11; // after the 9-char "@B892524 "
|
||||
else if (b->sub == SUB_80 && b->len >= 18) d = b->raw + 15;
|
||||
if (!d) return;
|
||||
char y[4], m[4], dd[4];
|
||||
if (!bcd(d, 1, y, sizeof(y)) || !bcd(d + 1, 1, m, sizeof(m)) || !bcd(d + 2, 1, dd, sizeof(dd))) return;
|
||||
int mi = atoi(m), di = atoi(dd);
|
||||
if (mi < 1 || mi > 12 || di < 1 || di > 31) return;
|
||||
snprintf(out, out_sz, "20%02d-%02d-%02d", atoi(y), mi, di);
|
||||
}
|
||||
|
||||
/** The VIN prefix the 1A 86 block ends with ("" otherwise). */
|
||||
static void vinOf(const block_t* b, char* out, size_t out_sz) {
|
||||
out[0] = 0;
|
||||
if (!b || b->sub != SUB_86 || b->len < 63) return;
|
||||
size_t w = 0;
|
||||
for (size_t i = 53; i < 63 && w + 1 < out_sz; i++) {
|
||||
char c = (char)b->raw[i];
|
||||
if (c < 0x20 || c >= 0x7F) { out[0] = 0; return; }
|
||||
out[w++] = c;
|
||||
}
|
||||
out[w] = 0;
|
||||
}
|
||||
|
||||
static void save(const block_t* b) {
|
||||
Preferences prefs;
|
||||
prefs.begin(NVS_NAMESPACE, false);
|
||||
const char* key = (b->sub == SUB_86) ? NVS_KEY_86 : NVS_KEY_80;
|
||||
if (b->len) prefs.putBytes(key, b->raw, b->len);
|
||||
else prefs.remove(key);
|
||||
prefs.end();
|
||||
}
|
||||
|
||||
static void load(block_t* b) {
|
||||
Preferences prefs;
|
||||
prefs.begin(NVS_NAMESPACE, true);
|
||||
const char* key = (b->sub == SUB_86) ? NVS_KEY_86 : NVS_KEY_80;
|
||||
size_t n = prefs.getBytesLength(key);
|
||||
if (n > 0 && n <= BLOCK_MAX) {
|
||||
prefs.getBytes(key, b->raw, n);
|
||||
b->len = (uint8_t)n;
|
||||
} else {
|
||||
b->len = 0;
|
||||
}
|
||||
prefs.end();
|
||||
}
|
||||
|
||||
static void describeBlock(const block_t* b, char* buf, size_t n) {
|
||||
char part[12], date[12];
|
||||
partOf(b, part, sizeof(part));
|
||||
dateOf(b, date, sizeof(date));
|
||||
if (part[0] && date[0]) snprintf(buf, n, "DDE %s - %s", part, date);
|
||||
else if (part[0]) snprintf(buf, n, "DDE %s", part);
|
||||
else snprintf(buf, n, "DDE ident 1A %02X, %u bytes", b->sub, b->len);
|
||||
if (b->sub == SUB_80 && !g_blk[0].len) {
|
||||
size_t l = strlen(buf);
|
||||
snprintf(buf + l, n - l, " (1A 80)");
|
||||
}
|
||||
}
|
||||
|
||||
/** CAN task: park the payload for tick(). A second one before it is taken is dropped. */
|
||||
static void onIdent(uint8_t sub, const uint8_t* payload, size_t n, bool ours) {
|
||||
if (g_pending || n < 2 || n > BLOCK_MAX) return;
|
||||
if (sub != SUB_86 && sub != SUB_80) return;
|
||||
g_pending_blk.sub = sub;
|
||||
g_pending_blk.len = (uint8_t)n;
|
||||
memcpy(g_pending_blk.raw, payload, n);
|
||||
g_pending_ours = ours;
|
||||
g_pending = true;
|
||||
}
|
||||
|
||||
/** loop(): a block arrived - store it, or compare it with what is stored. */
|
||||
static void takePending() {
|
||||
block_t in = g_pending_blk;
|
||||
bool ours = g_pending_ours;
|
||||
g_pending = false;
|
||||
g_waiting = false;
|
||||
|
||||
block_t* b = blockFor(in.sub);
|
||||
if (!b) return;
|
||||
char desc[64];
|
||||
if (b->len == 0) {
|
||||
*b = in;
|
||||
save(b);
|
||||
describeBlock(b, desc, sizeof(desc));
|
||||
print("[ecu] stored 1A %02X (%u bytes, %s): %s", in.sub, in.len, ours ? "our read" : "seen on the bus", desc);
|
||||
if (in.sub == SUB_80) { g_changed = false; g_bus_part[0] = 0; }
|
||||
return;
|
||||
}
|
||||
bool same = (b->len == in.len) && memcmp(b->raw, in.raw, in.len) == 0;
|
||||
if (in.sub == SUB_80) {
|
||||
if (same) {
|
||||
if (g_changed) print("[ecu] 1A 80 on the bus matches the stored block again");
|
||||
g_changed = false;
|
||||
g_bus_part[0] = 0;
|
||||
} else {
|
||||
char stored[12];
|
||||
partOf(&in, g_bus_part, sizeof(g_bus_part));
|
||||
partOf(b, stored, sizeof(stored));
|
||||
if (!g_changed) {
|
||||
print("[ecu] ECU CHANGED? the 1A 80 block on the bus (%s) differs from the stored one (%s) - `ecu forget` or Re-read ECU",
|
||||
g_bus_part[0] ? g_bus_part : "?", stored[0] ? stored : "?");
|
||||
}
|
||||
g_changed = true;
|
||||
}
|
||||
} else if (!same) {
|
||||
print("[ecu] note: a 1A 86 block on the bus differs from the stored one");
|
||||
}
|
||||
}
|
||||
|
||||
/** loop(): send the next identification request when every condition holds. */
|
||||
static void readTick() {
|
||||
if (!g_read_session || g_waiting) return;
|
||||
if (g_blk[0].len && g_blk[1].len) { g_read_session = false; return; } // both in hand
|
||||
|
||||
// the sub-function still missing with attempts left: 86 first, then 80
|
||||
int idx = -1;
|
||||
for (int i = 0; i < 2; i++) {
|
||||
if (!g_blk[i].len && g_attempts[i] < ATTEMPTS_PER_SUB) { idx = i; break; }
|
||||
}
|
||||
if (idx < 0) {
|
||||
g_read_session = false;
|
||||
if (!known() && !g_gave_up_printed) {
|
||||
g_gave_up_printed = true;
|
||||
print("[ecu] no identification answer after %u tries - UNKNOWN ECU, will try again next boot",
|
||||
(unsigned)(2 * ATTEMPTS_PER_SUB));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
uint32_t now = millis();
|
||||
if (!CANDriver::isActive() || BenchSim::isActive()) { g_ign_since_ms = 0; return; }
|
||||
driveline_t dl = CANDriver::getDriveline();
|
||||
if (!dl.ignition_on) { g_ign_since_ms = 0; return; }
|
||||
if (g_ign_since_ms == 0) g_ign_since_ms = now;
|
||||
if (now - g_ign_since_ms < SETTLE_MS) return;
|
||||
if (g_last_try_ms != 0 && now - g_last_try_ms < RETRY_GAP_MS) return;
|
||||
if (!DiagProbe::canSendNow()) return;
|
||||
|
||||
g_attempts[idx]++;
|
||||
g_last_try_ms = now;
|
||||
print("[ecu] reading the DDE identification (1A %02X, try %u of %u)", g_blk[idx].sub,
|
||||
g_attempts[idx], ATTEMPTS_PER_SUB);
|
||||
if (DiagProbe::requestIdent(g_blk[idx].sub)) g_waiting = true;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// PUBLIC API
|
||||
// ============================================================================
|
||||
|
||||
void init() {
|
||||
load(&g_blk[0]);
|
||||
load(&g_blk[1]);
|
||||
DiagProbe::setIdentHandler(onIdent);
|
||||
g_read_session = !known(); // stored = never ask again
|
||||
char desc[64];
|
||||
describe(desc, sizeof(desc));
|
||||
print("[ecu] %s%s", desc, g_read_session ? " - will read it once the bus is up with the key on" : "");
|
||||
}
|
||||
|
||||
void tick() {
|
||||
if (g_pending) takePending();
|
||||
if (g_waiting && millis() - g_last_try_ms > ANSWER_WAIT_MS) g_waiting = false; // no answer: next try later
|
||||
readTick();
|
||||
}
|
||||
|
||||
bool known() { return g_blk[0].len != 0 || g_blk[1].len != 0; }
|
||||
bool changed() { return g_changed; }
|
||||
|
||||
void describe(char* buf, size_t n) {
|
||||
if (g_changed) {
|
||||
char stored[12];
|
||||
partOf(&g_blk[1], stored, sizeof(stored));
|
||||
snprintf(buf, n, "ECU CHANGED? bus %s, stored %s", g_bus_part[0] ? g_bus_part : "?", stored[0] ? stored : "?");
|
||||
return;
|
||||
}
|
||||
block_t* p = primary();
|
||||
if (!p) { snprintf(buf, n, "UNKNOWN ECU"); return; }
|
||||
describeBlock(p, buf, n);
|
||||
}
|
||||
|
||||
bool hasPart(const char* part) {
|
||||
if (!part || !part[0]) return false;
|
||||
if (g_changed) return strcmp(g_bus_part, part) == 0; // the unit actually on the bus
|
||||
char p[12];
|
||||
for (int i = 0; i < 2; i++) {
|
||||
if (!g_blk[i].len) continue;
|
||||
partOf(&g_blk[i], p, sizeof(p));
|
||||
if (p[0] && strcmp(p, part) == 0) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void forget() {
|
||||
for (int i = 0; i < 2; i++) {
|
||||
g_blk[i].len = 0;
|
||||
save(&g_blk[i]);
|
||||
g_attempts[i] = 0;
|
||||
}
|
||||
g_changed = false;
|
||||
g_bus_part[0] = 0;
|
||||
g_gave_up_printed = false;
|
||||
g_last_try_ms = 0;
|
||||
g_waiting = false;
|
||||
g_read_session = true;
|
||||
print("[ecu] forgotten - UNKNOWN ECU; reading again once the bus is up with the key on");
|
||||
}
|
||||
|
||||
static void show() {
|
||||
char desc[64];
|
||||
describe(desc, sizeof(desc));
|
||||
print("[ecu] %s", desc);
|
||||
for (int i = 0; i < 2; i++) {
|
||||
block_t* b = &g_blk[i];
|
||||
if (!b->len) {
|
||||
print("[ecu] 1A %02X: not stored%s", b->sub,
|
||||
g_read_session ? (g_attempts[i] ? " (tried, no answer yet)" : " (will ask)") : "");
|
||||
continue;
|
||||
}
|
||||
char part[12], date[12], vin[12];
|
||||
partOf(b, part, sizeof(part));
|
||||
dateOf(b, date, sizeof(date));
|
||||
vinOf(b, vin, sizeof(vin));
|
||||
print("[ecu] 1A %02X: %u bytes, part %s, date %s%s%s", b->sub, b->len,
|
||||
part[0] ? part : "?", date[0] ? date : "?", vin[0] ? ", VIN prefix " : "", vin);
|
||||
}
|
||||
print("[ecu] %s", g_read_session ? "read pending: asks once CAN is on, ignition on 5 s, no scan tool"
|
||||
: "stored: never asked again (`ecu forget` to re-read)");
|
||||
}
|
||||
|
||||
static void dump() {
|
||||
for (int i = 0; i < 2; i++) {
|
||||
block_t* b = &g_blk[i];
|
||||
if (!b->len) { print("[ecu] 1A %02X: empty", b->sub); continue; }
|
||||
print("[ecu] 1A %02X (%u bytes):", b->sub, b->len);
|
||||
for (size_t o = 0; o < b->len; o += 16) {
|
||||
char hx[3 * 16 + 1];
|
||||
size_t w = 0, k = (b->len - o < 16) ? (b->len - o) : 16;
|
||||
for (size_t j = 0; j < k; j++) w += snprintf(hx + w, sizeof(hx) - w, "%02X ", b->raw[o + j]);
|
||||
if (w) hx[w - 1] = 0;
|
||||
char as[17];
|
||||
for (size_t j = 0; j < k; j++) as[j] = (b->raw[o + j] >= 0x20 && b->raw[o + j] < 0x7F) ? (char)b->raw[o + j] : '.';
|
||||
as[k] = 0;
|
||||
print("[ecu] +%03u %-48s |%s|", (unsigned)o, hx, as);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void help() {
|
||||
print("ecu show which engine ECU this board remembers (read once, never re-asked)");
|
||||
print("ecu dump the stored identification blocks in hex");
|
||||
print("ecu forget drop them - UNKNOWN ECU until read again (board moved to another car)");
|
||||
}
|
||||
|
||||
bool handleCommand(const char* line) {
|
||||
if (strncmp(line, "ecu", 3) != 0 || (line[3] != 0 && line[3] != ' ')) return false;
|
||||
const char* arg = line + 3;
|
||||
while (*arg == ' ') arg++;
|
||||
if (*arg == 0 || !strcmp(arg, "show")) { show(); return true; }
|
||||
if (!strcmp(arg, "dump")) { dump(); return true; }
|
||||
if (!strcmp(arg, "forget")) { forget(); return true; }
|
||||
help();
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace EcuIdent
|
||||
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
* ECU Identification Module
|
||||
*
|
||||
* Which engine ECU (DDE) is this board bolted to? Read ONCE and remembered.
|
||||
*
|
||||
* Two Patrols with "the same" M57N DDE turned out to carry different units
|
||||
* (part number 7796678 / 2006 vs 7794904 / 2004, captures 2026-10-18), and a
|
||||
* third setup is coming. The identity is a LABEL - every broadcast frame the
|
||||
* firmware decodes was identical on both - so it is stored for the record
|
||||
* (captures, wiki, Settings > Vehicle) and no broadcast decoding depends on it.
|
||||
* The one exception is the Engine data screen: the KWP `2C` live-data
|
||||
* identifiers are per DDE software (hasPart() selects its profile).
|
||||
*
|
||||
* Rules (user, 2026-10-18):
|
||||
* - While nothing is stored: read the identification the first time it is
|
||||
* possible (CAN on, ignition on for a few seconds, no scan tool on the bus,
|
||||
* not the bench simulation), a few spaced attempts per boot. Until then the
|
||||
* screen says UNKNOWN ECU.
|
||||
* - Once stored: NEVER ask again. A board moved to another car keeps the old
|
||||
* answer until "Re-read ECU" (Settings > Vehicle) or `ecu forget`.
|
||||
* - Free passive check: a connected Launch re-reads `1A 80` every cycle, and
|
||||
* we see the DDE's reply without transmitting. If it differs from the stored
|
||||
* `1A 80` block the screen says ECU CHANGED?.
|
||||
*
|
||||
* Two KWP identification blocks are kept, each as its raw payload (NVS blobs
|
||||
* `ecu_id86`, `ecu_id80` in the "settings" namespace):
|
||||
* `1A 86` - 65 bytes on Patrol 1 (verified 2026-09-23 from this board): ASCII
|
||||
* "@B892524 " (bytes 2-10), BCD date YY MM DD at bytes 11-13, three
|
||||
* BCD part numbers from byte 16 (7799764 / 7799765 / 7793887, six
|
||||
* bytes each), VIN prefix "WBANC92090" at bytes 53-62. Tried first
|
||||
* because this board's own `1A 80` went unanswered that day.
|
||||
* `1A 80` - what the Launch asks (answered on both Patrols, 31 / 37 bytes):
|
||||
* BCD part number at bytes 4-7, BCD date YY MM DD at bytes 15-17.
|
||||
* Second in the sequence; also what the passive check compares.
|
||||
* Field offsets are the ones observed on these two DDEs (wiki vehicles page);
|
||||
* a block that does not fit them is still stored and shown by length.
|
||||
*
|
||||
* Transmits through DiagProbe only (its guards: one request in flight, single
|
||||
* shot, refused for 3 s after any foreign tester frame).
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
namespace EcuIdent {
|
||||
|
||||
/** Load the stored blocks and hook DiagProbe. Call after DiagProbe::init(). */
|
||||
void init();
|
||||
|
||||
/** One-shot read sequencing and the deferred NVS write. Call from loop(). */
|
||||
void tick();
|
||||
|
||||
/** At least one identification block is stored. */
|
||||
bool known();
|
||||
|
||||
/** A `1A 80` block seen on the bus (another tester's read) differs from the stored one. */
|
||||
bool changed();
|
||||
|
||||
/**
|
||||
* One line for the screens: "DDE 7799764 - 2006-03-07", "UNKNOWN ECU",
|
||||
* "ECU CHANGED? bus 7796678, stored 7794904", ...
|
||||
*/
|
||||
void describe(char* buf, size_t n);
|
||||
|
||||
/**
|
||||
* The ECU in front of us carries this part number: the differing `1A 80` block
|
||||
* seen on the bus when changed() is set, otherwise any stored block's number
|
||||
* ("7796678", "7799764", ...). The Engine data screen keys its per-DDE
|
||||
* live-data identifiers on it - the one place behaviour follows the label,
|
||||
* because the `2C` identifiers are addresses inside each DDE's own software.
|
||||
*/
|
||||
bool hasPart(const char* part);
|
||||
|
||||
/** Drop the stored blocks; UNKNOWN ECU until the next successful read. */
|
||||
void forget();
|
||||
|
||||
/** `ecu show | dump | forget`. */
|
||||
bool handleCommand(const char* line);
|
||||
|
||||
} // namespace EcuIdent
|
||||
+122
-33
@@ -5,6 +5,7 @@
|
||||
#include "engine_screen.h"
|
||||
#include "ui_kit.h"
|
||||
#include "diag_probe.h"
|
||||
#include "ecu_ident.h"
|
||||
#include "driveline_screen.h"
|
||||
#include "display/lvgl_v8_port.h"
|
||||
|
||||
@@ -23,20 +24,61 @@ typedef struct {
|
||||
float factor;
|
||||
float offset;
|
||||
int decimals;
|
||||
bool provisional; // fitted to a single Launch reading
|
||||
} channel_t;
|
||||
|
||||
static const channel_t CHANNELS[DiagProbe::LIVE_COUNT] = {
|
||||
// verified 2026-09-23 against the Launch at two operating points
|
||||
{DiagProbe::LIVE_RAIL, "Rail pressure", "bar", 0.03f, 0.0f, 1, false},
|
||||
// verified 2026-09-23 against the Launch at two operating points (Patrol 1)
|
||||
{DiagProbe::LIVE_RAIL, "Rail pressure", "bar", 0.03f, 0.0f, 1},
|
||||
// 8271 raw <-> ~1028-1034 mbar engine off (2026-10-07): 1/8 mbar per count
|
||||
{DiagProbe::LIVE_BOOST, "Boost (absolute)", "mbar", 0.125f, 0.0f, 0, true},
|
||||
{DiagProbe::LIVE_BOOST, "Boost (absolute)", "mbar", 0.125f, 0.0f, 0},
|
||||
// 5295..5301 raw <-> Launch 36-38 C engine off (2026-10-07)
|
||||
{DiagProbe::LIVE_AIR_TEMP, "Charge-air temp", "\xC2\xB0" "C", 0.01f, -15.0f, 1, true},
|
||||
{DiagProbe::LIVE_AIR_TEMP, "Charge-air temp", "\xC2\xB0" "C", 0.01f, -15.0f, 1},
|
||||
// 4998 raw <-> 12.27 V engine off (2026-10-07, from the capture's file name)
|
||||
{DiagProbe::LIVE_BATTERY, "Battery", "V", 0.002455f, 0.0f, 2, true},
|
||||
{DiagProbe::LIVE_BATTERY, "Battery", "V", 0.002455f, 0.0f, 2},
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// PER-DDE PROFILES
|
||||
// ============================================================================
|
||||
//
|
||||
// The `2C 10 <id>` identifiers are addresses inside each DDE's own software:
|
||||
// Patrol 1's set, asked on Patrol 2's unit, returned a refused rail read, a
|
||||
// flat "2800 mbar" boost and a ">300 C" air temperature (user, 2026-10-18).
|
||||
// The Launch itself reads `1A 80` every cycle to choose its data set, and on
|
||||
// Patrol 2 it polled `00C2` for rail pressure. So the identifiers follow the
|
||||
// ECU identity (`EcuIdent`): the first profile whose part number the stored
|
||||
// identification carries wins. A slot with identifier 0 is never requested and
|
||||
// its card says so. No identified ECU, or an ECU with no profile = no polling.
|
||||
//
|
||||
// Adding a car: capture the Launch on each value (wiki obd-diagnostic-polling,
|
||||
// "decode recipe"), then add a row - part numbers from `ecu show`.
|
||||
|
||||
typedef struct {
|
||||
const char* name; // for the status line
|
||||
const char* parts[4]; // any part number (1A 80 or 1A 86) of this DDE, NULL-terminated
|
||||
DiagProbe::live_set_t set; // define id + one identifier per live_id_t slot (0 = unknown)
|
||||
uint8_t provisional_mask; // bit per slot: scaling fitted to a single Launch reading
|
||||
} profile_t;
|
||||
|
||||
static const profile_t PROFILES[] = {
|
||||
// Patrol 1: DDE 7796678 (1A 80, 2006-02) / 7799764, 7799765, 7793887 (1A 86, 2006-03)
|
||||
{"DDE 7796678 (Patrol 1)", {"7796678", "7799764", "7799765", "7793887"},
|
||||
{0x15E0, {0x00DF, 0x0091, 0x16A8, 0x0093}},
|
||||
(1 << DiagProbe::LIVE_BOOST) | (1 << DiagProbe::LIVE_AIR_TEMP) | (1 << DiagProbe::LIVE_BATTERY)},
|
||||
// Patrol 2: DDE 7794904 (1A 80, 2004-01) = 7796156 / 7796157 / 7789877
|
||||
// (1A 86, 2006-05-17, VIN prefix WBAGM21070 = E65 7-series; both blocks
|
||||
// read by this board on 2026-10-18, `ecu dump` in the wiki). Every
|
||||
// identifier differs from Patrol 1's, the scalings look the same: rail
|
||||
// `00C2` (~330 bar at idle), boost `003A` (1018 mbar idle, 1186 on a blip),
|
||||
// battery `002F` (14.0 V running, 12.7 V engine off) - all from Launch
|
||||
// captures on 2026-10-18 without the Launch's own readings noted, so all
|
||||
// provisional. No define seen. Charge-air temperature: not captured yet.
|
||||
{"DDE 7794904 (Patrol 2)", {"7794904", "7796156", "7796157", "7789877"},
|
||||
{0, {0x00C2, 0x003A, 0, 0x002F}},
|
||||
(1 << DiagProbe::LIVE_RAIL) | (1 << DiagProbe::LIVE_BOOST) | (1 << DiagProbe::LIVE_BATTERY)},
|
||||
};
|
||||
static const int PROFILE_COUNT = sizeof(PROFILES) / sizeof(PROFILES[0]);
|
||||
|
||||
static const uint32_t STALE_MS = 3000; // value older than this shows "--"
|
||||
|
||||
// ============================================================================
|
||||
@@ -47,6 +89,34 @@ static lv_obj_t* g_screen = NULL;
|
||||
static lv_obj_t* g_status = NULL;
|
||||
static lv_obj_t* g_value[DiagProbe::LIVE_COUNT];
|
||||
static lv_obj_t* g_raw[DiagProbe::LIVE_COUNT];
|
||||
static lv_obj_t* g_tag[DiagProbe::LIVE_COUNT];
|
||||
static const profile_t* g_profile = NULL; // the one in use (NULL = none)
|
||||
static bool g_profile_known = false; // g_profile has been evaluated at least once
|
||||
|
||||
/** The profile for the identified ECU, NULL when unknown or not in the table. */
|
||||
static const profile_t* findProfile() {
|
||||
if (!EcuIdent::known()) return NULL;
|
||||
for (int i = 0; i < PROFILE_COUNT; i++)
|
||||
for (int k = 0; k < 4 && PROFILES[i].parts[k]; k++)
|
||||
if (EcuIdent::hasPart(PROFILES[i].parts[k])) return &PROFILES[i];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/** Re-evaluate the profile; install its identifier set on change. */
|
||||
static void applyProfile() {
|
||||
const profile_t* p = findProfile();
|
||||
if (g_profile_known && p == g_profile) return;
|
||||
g_profile_known = true;
|
||||
g_profile = p;
|
||||
DiagProbe::liveConfigure(p ? &p->set : NULL);
|
||||
if (!p) DiagProbe::liveStop();
|
||||
for (int i = 0; i < DiagProbe::LIVE_COUNT; i++) {
|
||||
if (!g_tag[i]) continue;
|
||||
bool prov = p && (p->provisional_mask & (1 << i));
|
||||
if (prov) lv_obj_clear_flag(g_tag[i], LV_OBJ_FLAG_HIDDEN);
|
||||
else lv_obj_add_flag(g_tag[i], LV_OBJ_FLAG_HIDDEN);
|
||||
}
|
||||
}
|
||||
|
||||
static void onBack(lv_event_t* e) {
|
||||
(void)e;
|
||||
@@ -75,14 +145,14 @@ static void makeCard(lv_obj_t* parent, int i) {
|
||||
lv_obj_set_size(top, LV_PCT(100), LV_SIZE_CONTENT);
|
||||
lv_obj_set_flex_align(top, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
|
||||
label(top, ch.title, &lv_font_montserrat_24, UI_COL_MUTED);
|
||||
if (ch.provisional) {
|
||||
lv_obj_t* tag = label(top, "provisional", &lv_font_montserrat_14, UI_COL_AMBER);
|
||||
lv_obj_set_style_border_color(tag, UI_COL_AMBER, 0);
|
||||
lv_obj_set_style_border_width(tag, 1, 0);
|
||||
lv_obj_set_style_radius(tag, 6, 0);
|
||||
lv_obj_set_style_pad_hor(tag, 8, 0);
|
||||
lv_obj_set_style_pad_ver(tag, 3, 0);
|
||||
}
|
||||
lv_obj_t* tag = label(top, "provisional", &lv_font_montserrat_14, UI_COL_AMBER);
|
||||
lv_obj_set_style_border_color(tag, UI_COL_AMBER, 0);
|
||||
lv_obj_set_style_border_width(tag, 1, 0);
|
||||
lv_obj_set_style_radius(tag, 6, 0);
|
||||
lv_obj_set_style_pad_hor(tag, 8, 0);
|
||||
lv_obj_set_style_pad_ver(tag, 3, 0);
|
||||
lv_obj_add_flag(tag, LV_OBJ_FLAG_HIDDEN); // shown per profile
|
||||
g_tag[i] = tag;
|
||||
|
||||
lv_obj_t* row = box(c, LV_FLEX_FLOW_ROW);
|
||||
lv_obj_set_size(row, LV_PCT(100), LV_SIZE_CONTENT);
|
||||
@@ -113,36 +183,53 @@ static void build() {
|
||||
}
|
||||
|
||||
static void refresh() {
|
||||
const char* st;
|
||||
char st[160];
|
||||
lv_color_t col = UI_COL_MUTED;
|
||||
switch (DiagProbe::liveState()) {
|
||||
case DiagProbe::LIVE_RUNNING:
|
||||
st = LV_SYMBOL_OK " Live from the engine ECU (DDE)"; col = UI_COL_OK; break;
|
||||
case DiagProbe::LIVE_PAUSED_TESTER:
|
||||
st = LV_SYMBOL_PAUSE " Paused: another diagnostic tester is connected (e.g. the Launch)"; col = UI_COL_AMBER; break;
|
||||
case DiagProbe::LIVE_CAN_OFF:
|
||||
st = LV_SYMBOL_WARNING " CAN bus is off - turn it on in Settings > System"; col = UI_COL_WARN; break;
|
||||
case DiagProbe::LIVE_NO_ANSWER:
|
||||
st = LV_SYMBOL_WARNING " No answer from the engine ECU - is the ignition on?"; col = UI_COL_WARN; break;
|
||||
default:
|
||||
st = "Starting..."; break;
|
||||
if (!g_profile) {
|
||||
if (!EcuIdent::known()) {
|
||||
snprintf(st, sizeof(st), LV_SYMBOL_WARNING " Engine ECU not identified yet - no live data until it is read (key on, see Settings > Vehicle)");
|
||||
} else {
|
||||
char ecu[64];
|
||||
EcuIdent::describe(ecu, sizeof(ecu));
|
||||
snprintf(st, sizeof(st), LV_SYMBOL_WARNING " %s - no live-data identifiers known for this ECU yet (capture it with the Launch)", ecu);
|
||||
}
|
||||
col = UI_COL_AMBER;
|
||||
} else {
|
||||
switch (DiagProbe::liveState()) {
|
||||
case DiagProbe::LIVE_RUNNING:
|
||||
snprintf(st, sizeof(st), LV_SYMBOL_OK " Live from the engine ECU, %s", g_profile->name); col = UI_COL_OK; break;
|
||||
case DiagProbe::LIVE_PAUSED_TESTER:
|
||||
snprintf(st, sizeof(st), LV_SYMBOL_PAUSE " Paused: another diagnostic tester is connected (e.g. the Launch)"); col = UI_COL_AMBER; break;
|
||||
case DiagProbe::LIVE_CAN_OFF:
|
||||
snprintf(st, sizeof(st), LV_SYMBOL_WARNING " CAN bus is off - turn it on in Settings > System"); col = UI_COL_WARN; break;
|
||||
case DiagProbe::LIVE_NO_ANSWER:
|
||||
snprintf(st, sizeof(st), LV_SYMBOL_WARNING " No answer from the engine ECU - is the ignition on?"); col = UI_COL_WARN; break;
|
||||
default:
|
||||
snprintf(st, sizeof(st), "Starting..."); break;
|
||||
}
|
||||
}
|
||||
setText(g_status, st);
|
||||
setTextColor(g_status, col);
|
||||
|
||||
char buf[48];
|
||||
char buf[64];
|
||||
for (int i = 0; i < DiagProbe::LIVE_COUNT; i++) {
|
||||
const channel_t& ch = CHANNELS[i];
|
||||
uint16_t vid = g_profile ? g_profile->set.ids[ch.id] : 0;
|
||||
if (vid == 0) {
|
||||
setText(g_value[i], "--");
|
||||
setText(g_raw[i], g_profile ? "identifier not known for this ECU yet" : "no ECU profile");
|
||||
continue;
|
||||
}
|
||||
DiagProbe::live_value_t v = DiagProbe::liveValue(ch.id);
|
||||
if (v.valid && v.age_ms < STALE_MS) {
|
||||
snprintf(buf, sizeof(buf), "%.*f", ch.decimals, v.raw * ch.factor + ch.offset);
|
||||
setText(g_value[i], buf);
|
||||
snprintf(buf, sizeof(buf), "raw %u (0x%04X)", v.raw, v.raw);
|
||||
snprintf(buf, sizeof(buf), "raw %u (0x%04X) id %04X", v.raw, v.raw, vid);
|
||||
} else {
|
||||
setText(g_value[i], "--");
|
||||
if (v.nrc) snprintf(buf, sizeof(buf), "refused by the ECU (NRC 0x%02X)", v.nrc);
|
||||
else if (v.valid) snprintf(buf, sizeof(buf), "raw %u (stale)", v.raw);
|
||||
else snprintf(buf, sizeof(buf), "raw --");
|
||||
if (v.nrc) snprintf(buf, sizeof(buf), "refused by the ECU (NRC 0x%02X) id %04X", v.nrc, vid);
|
||||
else if (v.valid) snprintf(buf, sizeof(buf), "raw %u (stale) id %04X", v.raw, vid);
|
||||
else snprintf(buf, sizeof(buf), "raw -- id %04X", vid);
|
||||
}
|
||||
setText(g_raw[i], buf);
|
||||
}
|
||||
@@ -150,18 +237,20 @@ static void refresh() {
|
||||
|
||||
void show() {
|
||||
build();
|
||||
DiagProbe::liveKeepAlive();
|
||||
applyProfile();
|
||||
if (g_profile) DiagProbe::liveKeepAlive();
|
||||
refresh();
|
||||
lv_scr_load_anim(g_screen, LV_SCR_LOAD_ANIM_NONE, 0, 0, false); // instant: fades stutter at 1024x600
|
||||
}
|
||||
|
||||
void tick() {
|
||||
if (g_screen == NULL || lv_scr_act() != g_screen) return;
|
||||
DiagProbe::liveKeepAlive(); // polling stops ~1.5 s after the screen is left
|
||||
static uint32_t last = 0;
|
||||
if (millis() - last < 250) return;
|
||||
last = millis();
|
||||
lvgl_port_lock(-1);
|
||||
applyProfile(); // the ECU may get identified while we watch
|
||||
if (g_profile) DiagProbe::liveKeepAlive(); // polling stops ~1.5 s after the screen is left
|
||||
refresh();
|
||||
lvgl_port_unlock();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
/*
|
||||
* Reverse lights on DO0 - see reverse_light.h
|
||||
*/
|
||||
|
||||
#include "reverse_light.h"
|
||||
#include "settings_manager.h"
|
||||
#include "drivers/can_driver.h"
|
||||
#include "display/lvgl_v8_port.h"
|
||||
#include "serial_lock.h"
|
||||
#include <esp_display_panel.hpp>
|
||||
#include <stdarg.h>
|
||||
|
||||
namespace ReverseLight {
|
||||
|
||||
// CH422G pins in the ESP32_IO_Expander numbering: IO0-7 = 0-7, OC0-3 = 8-11.
|
||||
// OC0 is OD0 on the schematic -> PC817 T1 -> power transistor T2 -> DOUT0.
|
||||
static const uint8_t OC0_PIN = 8;
|
||||
static const uint32_t POLL_MS = 100;
|
||||
static const uint8_t CONFIRM = 2; // equal decisions before the output moves (200 ms)
|
||||
static const uint8_t FAULT_AFTER = 3; // failed writes in a row before we say so
|
||||
static const uint32_t FORCE_MAX_MS = 60000; // a forgotten `reverse force on` ends itself
|
||||
|
||||
enum force_t : uint8_t { FORCE_AUTO = 0, FORCE_ON, FORCE_OFF };
|
||||
|
||||
static esp_expander::Base* g_expander = nullptr;
|
||||
static bool g_enabled = true;
|
||||
static force_t g_force = FORCE_AUTO;
|
||||
static uint32_t g_force_since = 0;
|
||||
|
||||
static bool g_output = false; // what the chip was last told successfully
|
||||
static bool g_output_known = false; // false until the first successful write
|
||||
static bool g_decided = false; // the current (confirmed) decision
|
||||
static bool g_candidate = false; // the decision being confirmed
|
||||
static uint8_t g_candidate_ticks = 0;
|
||||
static uint8_t g_fail_run = 0;
|
||||
static uint32_t g_writes = 0, g_fails = 0, g_switches = 0;
|
||||
static uint32_t g_last_poll = 0;
|
||||
|
||||
static void print(const char* fmt, ...) {
|
||||
char buf[160];
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
vsnprintf(buf, sizeof(buf), fmt, ap);
|
||||
va_end(ap);
|
||||
SerialLock::lock();
|
||||
Serial.println(buf);
|
||||
SerialLock::unlock();
|
||||
}
|
||||
|
||||
/** One write to OC0. OC0 LOW lights the opto LED, which turns the output on. */
|
||||
static bool drive(bool on) {
|
||||
if (g_expander == nullptr) return false;
|
||||
if (!lvgl_port_lock(100)) return false; // UI busy: retried next tick
|
||||
bool ok = g_expander->digitalWrite(OC0_PIN, on ? 0 : 1);
|
||||
lvgl_port_unlock();
|
||||
g_writes++;
|
||||
if (!ok) {
|
||||
g_fails++;
|
||||
if (g_fail_run < 255) g_fail_run++;
|
||||
if (g_fail_run == FAULT_AFTER) print("[reverse] CH422G write failing - DO0 state unknown");
|
||||
return false;
|
||||
}
|
||||
if (g_fail_run >= FAULT_AFTER) print("[reverse] CH422G writes OK again");
|
||||
g_fail_run = 0;
|
||||
g_output = on;
|
||||
g_output_known = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
void init(bool enabled, esp_expander::Base* expander) {
|
||||
g_enabled = enabled;
|
||||
g_expander = expander;
|
||||
if (g_expander == nullptr) {
|
||||
print("[reverse] no IO expander - DO0 cannot be driven");
|
||||
return;
|
||||
}
|
||||
drive(false); // known state, whatever the chip held before this boot
|
||||
print("[reverse] %s (DO0 follows the lever in R)%s", enabled ? "ON" : "OFF - 'reverse on' to enable",
|
||||
g_output_known ? "" : " - first write failed, will retry");
|
||||
}
|
||||
|
||||
void setEnabled(bool enabled) {
|
||||
if (enabled == g_enabled) return;
|
||||
g_enabled = enabled;
|
||||
SettingsManager::saveReverseLightState(enabled);
|
||||
}
|
||||
|
||||
bool isEnabled() { return g_enabled; }
|
||||
bool isOn() { return g_output_known && g_output; }
|
||||
|
||||
/** The lights should be on: lever in R, on a live bus, key on. */
|
||||
static bool wanted() {
|
||||
if (g_force == FORCE_ON) return true;
|
||||
if (g_force == FORCE_OFF) return false;
|
||||
if (!g_enabled || !CANDriver::isActive()) return false;
|
||||
driveline_t dl = CANDriver::getDriveline(); // cleared by the driver after 2 s of silence
|
||||
return dl.ignition_on && dl.lever == GEAR_REVERSE;
|
||||
}
|
||||
|
||||
void tick() {
|
||||
if (millis() - g_last_poll < POLL_MS) return;
|
||||
g_last_poll = millis();
|
||||
|
||||
if (g_force != FORCE_AUTO && millis() - g_force_since > FORCE_MAX_MS) {
|
||||
g_force = FORCE_AUTO;
|
||||
print("[reverse] force ended after 60 s - back to the lever");
|
||||
}
|
||||
|
||||
bool want = wanted();
|
||||
if (want != g_candidate) {
|
||||
g_candidate = want;
|
||||
g_candidate_ticks = 0;
|
||||
}
|
||||
if (g_candidate_ticks < 255) g_candidate_ticks++;
|
||||
if (g_candidate_ticks >= CONFIRM && want != g_decided) {
|
||||
g_decided = want;
|
||||
g_switches++;
|
||||
print("[reverse] lights %s (%s)", want ? "ON" : "off",
|
||||
g_force == FORCE_ON ? "forced" : g_force == FORCE_OFF ? "forced off" : want ? "lever R" : "lever left R");
|
||||
}
|
||||
|
||||
// Apply when the chip disagrees with the decision; a failed write is retried every tick.
|
||||
if (!g_output_known || g_output != g_decided) drive(g_decided);
|
||||
}
|
||||
|
||||
bool handleCommand(const char* line) {
|
||||
if (strncmp(line, "reverse", 7) != 0 || (line[7] != 0 && line[7] != ' ')) return false;
|
||||
const char* a = line + 7;
|
||||
while (*a == ' ') a++;
|
||||
|
||||
if (!strcmp(a, "on")) { setEnabled(true); print("[reverse] ON (saved)"); return true; }
|
||||
if (!strcmp(a, "off")) { setEnabled(false); print("[reverse] OFF (saved) - DO0 stays off"); return true; }
|
||||
if (!strcmp(a, "force on")) { g_force = FORCE_ON; g_force_since = millis(); print("[reverse] FORCED ON for up to 60 s (not saved)"); return true; }
|
||||
if (!strcmp(a, "force off")) { g_force = FORCE_OFF; g_force_since = millis(); print("[reverse] FORCED OFF for up to 60 s (not saved)"); return true; }
|
||||
if (!strcmp(a, "force auto")) { g_force = FORCE_AUTO; print("[reverse] back to the lever"); return true; }
|
||||
if (!*a || !strcmp(a, "status")) {
|
||||
driveline_t dl = CANDriver::getDriveline();
|
||||
print("[reverse] %s | DO0 %s | lever %c, ignition %s, CAN %s | force %s | %lu writes, %lu failed, %lu switches%s",
|
||||
g_enabled ? "enabled" : "DISABLED",
|
||||
!g_output_known ? "unknown" : g_output ? "ON (relay energised)" : "off",
|
||||
gear_lever_char(dl.lever), dl.ignition_on ? "on" : "off", CANDriver::isActive() ? "on" : "off",
|
||||
g_force == FORCE_ON ? "ON" : g_force == FORCE_OFF ? "OFF" : "auto",
|
||||
(unsigned long)g_writes, (unsigned long)g_fails, (unsigned long)g_switches,
|
||||
g_fail_run >= FAULT_AFTER ? " | WRITE FAULT" : "");
|
||||
return true;
|
||||
}
|
||||
print("[reverse] usage: reverse status | on | off | force on|off|auto (DO0 = reverse-light relay)");
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace ReverseLight
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Reverse lights - the isolated output DO0 follows the gear lever in R
|
||||
*
|
||||
* The Patrol's reverse lamps are switched by a 12 V relay whose coil hangs
|
||||
* between +12 V and the board's DO0 terminal (flyback diode across the coil).
|
||||
* DO0 is the collector of an NPN power transistor (450 mA sink, emitter on the
|
||||
* board's GND) driven through a PC817 optocoupler from the CH422G's OC0 pin
|
||||
* (schematic: OC0 -> R24 100R -> PC817 LED, anode 510R to 3V3; so OC0 LOW =
|
||||
* LED on = transistor on = relay on). The CH422G comes up with OC0 high and
|
||||
* the panel library rewrites that default at every display init, so the
|
||||
* lights are off from reset until this module says otherwise.
|
||||
*
|
||||
* Decision, every 100 ms: lever == R (0x1D2 byte 0) with CAN running and the
|
||||
* ignition on - the same snapshot the Driveline screen shows, so the lights
|
||||
* never disagree with the big letter. The CAN driver forgets the lever after
|
||||
* 2 s of bus silence and on key-off, which turns the lights off as well. A
|
||||
* change is applied after two equal decisions (200 ms) so a one-frame glitch
|
||||
* cannot chatter the relay. `reverse force on|off` overrides for wiring tests
|
||||
* (never saved, back to auto after 60 s or `reverse force auto`).
|
||||
*
|
||||
* The output is written through the panel library's expander object (not raw
|
||||
* I2C like the diff-lock reads) so the library's cached OC register stays
|
||||
* right: the backlight writes that cache back to the chip on every on/off.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
namespace esp_expander { class Base; }
|
||||
|
||||
namespace ReverseLight {
|
||||
|
||||
/** Call once after DisplayInit (the expander belongs to the panel library). Drives DO0 off. */
|
||||
void init(bool enabled, esp_expander::Base* expander);
|
||||
|
||||
/** `reverse on|off`, saved to NVS (SettingsManager). Default ON. */
|
||||
void setEnabled(bool enabled);
|
||||
bool isEnabled();
|
||||
|
||||
/** Decide + drive DO0 (10 Hz, two equal decisions before a change). Call from loop(). */
|
||||
void tick();
|
||||
|
||||
/** What DO0 is being driven to right now (true = relay on). */
|
||||
bool isOn();
|
||||
|
||||
/** `reverse status | on | off | force on|off|auto`. Returns true if the line was ours. */
|
||||
bool handleCommand(const char* line);
|
||||
|
||||
} // namespace ReverseLight
|
||||
@@ -21,6 +21,7 @@ static const char* NVS_KEY_DEBUG_ENABLED = "debug_en";
|
||||
static const char* NVS_KEY_CAN_ENABLED = "can_en";
|
||||
static const char* NVS_KEY_DIFFLOCK_ENABLED = "difflock_en";
|
||||
static const char* NVS_KEY_DIFFLOCK_INVERT = "difflock_inv";
|
||||
static const char* NVS_KEY_REVLIGHT_ENABLED = "revlight_en";
|
||||
|
||||
// ============================================================================
|
||||
// PUBLIC API IMPLEMENTATION
|
||||
@@ -119,4 +120,18 @@ bool loadDiffLockInvert() {
|
||||
return inverted;
|
||||
}
|
||||
|
||||
void saveReverseLightState(bool enabled) {
|
||||
preferences.begin(NVS_NAMESPACE, false); // read-write mode
|
||||
preferences.putBool(NVS_KEY_REVLIGHT_ENABLED, enabled);
|
||||
preferences.end();
|
||||
Serial.printf("[SettingsManager] Saved ReverseLight state = %s\n", enabled ? "ON" : "OFF");
|
||||
}
|
||||
|
||||
bool loadReverseLightState() {
|
||||
preferences.begin(NVS_NAMESPACE, true); // read-only mode
|
||||
bool enabled = preferences.getBool(NVS_KEY_REVLIGHT_ENABLED, true); // default: ON (an unwired DO0 is harmless)
|
||||
preferences.end();
|
||||
return enabled;
|
||||
}
|
||||
|
||||
} // namespace SettingsManager
|
||||
|
||||
@@ -74,4 +74,8 @@ bool loadDiffLockState();
|
||||
void saveDiffLockInvert(bool inverted);
|
||||
bool loadDiffLockInvert();
|
||||
|
||||
/** Reverse-light relay on DO0 follows the lever in R (ReverseLight). Default ON. */
|
||||
void saveReverseLightState(bool enabled);
|
||||
bool loadReverseLightState();
|
||||
|
||||
} // namespace SettingsManager
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
#include "ota_update.h"
|
||||
#include "link_peer.h"
|
||||
#include "diff_locks.h"
|
||||
#include "vehicle.h"
|
||||
#include "ecu_ident.h"
|
||||
#include "bench_sim.h"
|
||||
#include "uart_manager.h"
|
||||
#include "espnow_link.h"
|
||||
#include "settings_manager.h"
|
||||
@@ -31,7 +34,7 @@ static const lv_coord_t NAV_X = 16, NAV_W = 240, NAV_H = 100;
|
||||
static const lv_coord_t TOP_Y = 88;
|
||||
static const lv_coord_t PAGE_X = 272, PAGE_W = 736, PAGE_H = 600 - TOP_Y - 28; // version label below
|
||||
|
||||
typedef enum { PAGE_WIFI, PAGE_UPDATES, PAGE_SYSTEM, PAGE_COUNT } page_t;
|
||||
typedef enum { PAGE_WIFI, PAGE_UPDATES, PAGE_SYSTEM, PAGE_VEHICLE, PAGE_COUNT } page_t;
|
||||
|
||||
// ============================================================================
|
||||
// MODULE STATE
|
||||
@@ -88,6 +91,14 @@ static lv_obj_t* g_sys_diff_inv = NULL; // polarity: no current = locked
|
||||
static lv_obj_t* g_sys_diff_sub = NULL; // sub-line of the diff-lock row: live state
|
||||
static lv_obj_t* g_sys_info = NULL; // values column; keys are static
|
||||
|
||||
// Vehicle page
|
||||
static lv_obj_t* g_veh_final_lbl = NULL;
|
||||
static lv_obj_t* g_veh_tyre_lbl = NULL;
|
||||
static lv_obj_t* g_veh_live = NULL;
|
||||
static lv_obj_t* g_veh_ecu = NULL; // "Engine ECU: DDE 7799764 - 2006-03-07" / UNKNOWN ECU / ECU CHANGED?
|
||||
static lv_obj_t* g_veh_save = NULL;
|
||||
static uint16_t g_repeats = 0; // long-press repeat count of the -/+ button being held
|
||||
|
||||
static void refresh(bool force);
|
||||
|
||||
// ============================================================================
|
||||
@@ -112,6 +123,7 @@ static void onNav(lv_event_t* e) {
|
||||
|
||||
static void onBack(lv_event_t* e) {
|
||||
(void)e;
|
||||
Vehicle::flush(); // write pending Vehicle edits now rather than after the idle delay
|
||||
DrivelineScreen::show();
|
||||
}
|
||||
|
||||
@@ -120,6 +132,7 @@ static void onGesture(lv_event_t* e) {
|
||||
if (g_pw && !lv_obj_has_flag(g_pw, LV_OBJ_FLAG_HIDDEN)) return; // typing a password
|
||||
if (lv_indev_get_gesture_dir(lv_indev_get_act()) == LV_DIR_RIGHT) {
|
||||
lv_indev_wait_release(lv_indev_get_act());
|
||||
Vehicle::flush();
|
||||
DrivelineScreen::show();
|
||||
}
|
||||
}
|
||||
@@ -861,6 +874,171 @@ static void buildSystemPage(lv_obj_t* page) {
|
||||
lv_obj_set_style_text_line_space(g_sys_info, 6, 0);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// VEHICLE PAGE - road speed = output shaft rpm / final drive x tyre circumference
|
||||
// ============================================================================
|
||||
|
||||
typedef enum { VEH_FINAL, VEH_TYRE } veh_field_t;
|
||||
typedef struct { veh_field_t field; int dir; } veh_step_t;
|
||||
static veh_step_t g_veh_step[2][2] = {{{VEH_FINAL, -1}, {VEH_FINAL, +1}}, {{VEH_TYRE, -1}, {VEH_TYRE, +1}}};
|
||||
|
||||
/** 1x for taps and the first second of a hold, then 5x, then 10x (as on the Tuning screen). */
|
||||
static int32_t holdMultiplier(lv_event_code_t code) {
|
||||
if (code == LV_EVENT_PRESSED) { g_repeats = 0; return 0; }
|
||||
if (code == LV_EVENT_LONG_PRESSED_REPEAT) {
|
||||
g_repeats++;
|
||||
return g_repeats > 25 ? 10 : g_repeats > 10 ? 5 : 1;
|
||||
}
|
||||
return 1; // CLICKED
|
||||
}
|
||||
|
||||
static void onVehicleStep(lv_event_t* e) {
|
||||
lv_event_code_t code = lv_event_get_code(e);
|
||||
int32_t mult = holdMultiplier(code);
|
||||
if (mult == 0) return;
|
||||
if (code == LV_EVENT_CLICKED && g_repeats > 0) return; // end of a hold, already applied
|
||||
veh_step_t* st = (veh_step_t*)lv_event_get_user_data(e);
|
||||
if (st->field == VEH_FINAL) {
|
||||
int32_t v = (int32_t)Vehicle::finalDriveX100() + st->dir * 1 * mult; // 0.01 per step
|
||||
Vehicle::setFinalDriveX100((uint16_t)constrain(v, Vehicle::FINAL_DRIVE_MIN_X100, Vehicle::FINAL_DRIVE_MAX_X100));
|
||||
} else {
|
||||
int32_t v = (int32_t)Vehicle::tyreMm() + st->dir * 10 * mult; // 10 mm per step
|
||||
Vehicle::setTyreMm((uint16_t)constrain(v, Vehicle::TYRE_MM_MIN, Vehicle::TYRE_MM_MAX));
|
||||
}
|
||||
refresh(true);
|
||||
}
|
||||
|
||||
static void onVehicleResetConfirmed(bool ok, void* user) {
|
||||
(void)user;
|
||||
if (!ok) return;
|
||||
Vehicle::resetDefaults();
|
||||
refresh(true);
|
||||
}
|
||||
|
||||
static void onVehicleReset(lv_event_t* e) {
|
||||
(void)e;
|
||||
confirm("Reset vehicle settings?", "Final drive back to 4.11:1 and tyre circumference to 2440 mm.",
|
||||
"Reset", onVehicleResetConfirmed, NULL);
|
||||
}
|
||||
|
||||
static void onEcuRereadConfirmed(bool ok, void* user) {
|
||||
(void)user;
|
||||
if (!ok) return;
|
||||
EcuIdent::forget();
|
||||
refresh(true);
|
||||
}
|
||||
|
||||
static void onEcuReread(lv_event_t* e) {
|
||||
(void)e;
|
||||
confirm("Re-read the engine ECU?",
|
||||
"Forgets the stored identification. It is read again, once, the next time the bus is up "
|
||||
"with the key on and no scan tool connected. Use it when this board moves to another car.",
|
||||
"Re-read", onEcuRereadConfirmed, NULL);
|
||||
}
|
||||
|
||||
static lv_obj_t* makeStepBtn(lv_obj_t* parent, const char* txt, void* ctx) {
|
||||
lv_obj_t* b = button(parent, txt, 76, 56, BTN_SECONDARY, NULL, NULL);
|
||||
lv_obj_set_style_text_font(lv_obj_get_child(b, 0), &lv_font_montserrat_24, 0);
|
||||
lv_obj_add_event_cb(b, onVehicleStep, LV_EVENT_PRESSED, ctx);
|
||||
lv_obj_add_event_cb(b, onVehicleStep, LV_EVENT_CLICKED, ctx);
|
||||
lv_obj_add_event_cb(b, onVehicleStep, LV_EVENT_LONG_PRESSED_REPEAT, ctx);
|
||||
return b;
|
||||
}
|
||||
|
||||
/** [name / hint] ... [-] value [+] - returns the value label. */
|
||||
static lv_obj_t* makeVehicleRow(lv_obj_t* parent, const char* name, const char* hint, veh_step_t* steps) {
|
||||
lv_obj_t* row = box(parent, LV_FLEX_FLOW_ROW);
|
||||
lv_obj_set_size(row, LV_PCT(100), 64);
|
||||
lv_obj_set_flex_align(row, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
|
||||
lv_obj_set_style_pad_column(row, 12, 0);
|
||||
|
||||
lv_obj_t* txt = box(row, LV_FLEX_FLOW_COLUMN);
|
||||
lv_obj_set_height(txt, LV_SIZE_CONTENT);
|
||||
lv_obj_set_flex_grow(txt, 1);
|
||||
lv_obj_set_style_pad_row(txt, 2, 0);
|
||||
label(txt, name, &lv_font_montserrat_24, UI_COL_TEXT);
|
||||
label(txt, hint, &lv_font_montserrat_14, UI_COL_MUTED);
|
||||
|
||||
makeStepBtn(row, LV_SYMBOL_MINUS, &steps[0]);
|
||||
lv_obj_t* v = label(row, "--", &lv_font_montserrat_30, UI_COL_TEXT);
|
||||
lv_obj_set_style_text_align(v, LV_TEXT_ALIGN_CENTER, 0);
|
||||
lv_obj_set_width(v, 170);
|
||||
makeStepBtn(row, LV_SYMBOL_PLUS, &steps[1]);
|
||||
return v;
|
||||
}
|
||||
|
||||
static void refreshVehicle() {
|
||||
char buf[160];
|
||||
uint16_t fd = Vehicle::finalDriveX100();
|
||||
snprintf(buf, sizeof(buf), "%u.%02u : 1", fd / 100, fd % 100);
|
||||
setText(g_veh_final_lbl, buf);
|
||||
snprintf(buf, sizeof(buf), "%u mm", Vehicle::tyreMm());
|
||||
setText(g_veh_tyre_lbl, buf);
|
||||
|
||||
// live preview: the real shaft reading when the bus is up, a worked example otherwise
|
||||
driveline_t dl = CANDriver::getDriveline();
|
||||
if ((CANDriver::isActive() || BenchSim::isActive()) && dl.ignition_on) {
|
||||
uint16_t rpm = can_output_shaft_rpm(dl.output_shaft_raw);
|
||||
uint16_t v = Vehicle::speedKmhX10FromRpm(rpm);
|
||||
snprintf(buf, sizeof(buf), "Now: output shaft %u rpm = %u.%u km/h", rpm, v / 10, v % 10);
|
||||
} else {
|
||||
uint16_t v = Vehicle::speedKmhX10FromRpm(1000);
|
||||
snprintf(buf, sizeof(buf), "With these values 1000 output shaft rpm = %u.%u km/h", v / 10, v % 10);
|
||||
}
|
||||
setText(g_veh_live, buf);
|
||||
|
||||
// which DDE this board remembers (read once; see EcuIdent)
|
||||
char ecu[80];
|
||||
EcuIdent::describe(ecu, sizeof(ecu));
|
||||
snprintf(buf, sizeof(buf), "Engine ECU: %s%s", ecu,
|
||||
EcuIdent::known() ? "" : " - read once from the bus when the key is on");
|
||||
static uint8_t ecu_state = 0xFF;
|
||||
uint8_t st = EcuIdent::changed() ? 2 : EcuIdent::known() ? 1 : 0;
|
||||
setText(g_veh_ecu, buf);
|
||||
if (st != ecu_state) {
|
||||
ecu_state = st;
|
||||
setTextColor(g_veh_ecu, st == 2 ? UI_COL_AMBER : st == 1 ? UI_COL_TEXT : UI_COL_MUTED);
|
||||
}
|
||||
|
||||
if (Vehicle::isDirty()) { setText(g_veh_save, "Saving..."); setTextColor(g_veh_save, UI_COL_MUTED); }
|
||||
else { setText(g_veh_save, LV_SYMBOL_OK " All changes saved"); setTextColor(g_veh_save, UI_COL_OK); }
|
||||
}
|
||||
|
||||
static void buildVehiclePage(lv_obj_t* page) {
|
||||
lv_obj_t* c = card(page);
|
||||
lv_obj_set_size(c, LV_PCT(100), LV_SIZE_CONTENT);
|
||||
lv_obj_set_flex_flow(c, LV_FLEX_FLOW_COLUMN);
|
||||
lv_obj_set_style_pad_row(c, 10, 0);
|
||||
g_veh_final_lbl = makeVehicleRow(c, "Final drive ratio", "Differential ratio - 4.11:1 on this Patrol", g_veh_step[0]);
|
||||
g_veh_tyre_lbl = makeVehicleRow(c, "Tyre circumference", "Rolling circumference in mm - a 265/70 R16 is about 2440", g_veh_step[1]);
|
||||
|
||||
lv_obj_t* info = card(page);
|
||||
lv_obj_set_size(info, LV_PCT(100), LV_SIZE_CONTENT);
|
||||
lv_obj_set_flex_flow(info, LV_FLEX_FLOW_COLUMN);
|
||||
lv_obj_set_style_pad_row(info, 8, 0);
|
||||
lv_obj_t* f = label(info, "Speed = output shaft rpm (0x0BA, from the gearbox) / final drive x tyre circumference. "
|
||||
"The shaft factor itself is still provisional, hence the ~ on the screens.",
|
||||
&lv_font_montserrat_20, UI_COL_MUTED);
|
||||
lv_label_set_long_mode(f, LV_LABEL_LONG_WRAP);
|
||||
lv_obj_set_width(f, LV_PCT(100));
|
||||
g_veh_live = label(info, "", &lv_font_montserrat_20, UI_COL_TEXT);
|
||||
lv_label_set_long_mode(g_veh_live, LV_LABEL_LONG_WRAP);
|
||||
lv_obj_set_width(g_veh_live, LV_PCT(100));
|
||||
g_veh_ecu = label(info, "", &lv_font_montserrat_20, UI_COL_MUTED);
|
||||
lv_label_set_long_mode(g_veh_ecu, LV_LABEL_LONG_WRAP);
|
||||
lv_obj_set_width(g_veh_ecu, LV_PCT(100));
|
||||
|
||||
lv_obj_t* foot = box(page, LV_FLEX_FLOW_ROW);
|
||||
lv_obj_set_size(foot, LV_PCT(100), LV_SIZE_CONTENT);
|
||||
lv_obj_set_flex_align(foot, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
|
||||
g_veh_save = label(foot, "", &lv_font_montserrat_20, UI_COL_MUTED);
|
||||
lv_obj_t* btns = box(foot, LV_FLEX_FLOW_ROW);
|
||||
lv_obj_set_size(btns, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
|
||||
lv_obj_set_style_pad_column(btns, 12, 0);
|
||||
button(btns, LV_SYMBOL_DOWNLOAD " Re-read ECU", 200, 56, BTN_SECONDARY, onEcuReread, NULL);
|
||||
button(btns, LV_SYMBOL_REFRESH " Reset", 160, 56, BTN_SECONDARY, onVehicleReset, NULL);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// BUILD / REFRESH
|
||||
// ============================================================================
|
||||
@@ -875,11 +1053,13 @@ static void build() {
|
||||
g_nav[PAGE_WIFI] = makeNav(g_screen, PAGE_WIFI, "Wi-Fi");
|
||||
g_nav[PAGE_UPDATES] = makeNav(g_screen, PAGE_UPDATES, "Updates");
|
||||
g_nav[PAGE_SYSTEM] = makeNav(g_screen, PAGE_SYSTEM, "System");
|
||||
g_nav[PAGE_VEHICLE] = makeNav(g_screen, PAGE_VEHICLE, "Vehicle");
|
||||
|
||||
for (int i = 0; i < PAGE_COUNT; i++) g_page[i] = makePage(g_screen);
|
||||
buildWifiPage(g_page[PAGE_WIFI]);
|
||||
buildUpdatesPage(g_page[PAGE_UPDATES]);
|
||||
buildSystemPage(g_page[PAGE_SYSTEM]);
|
||||
buildVehiclePage(g_page[PAGE_VEHICLE]);
|
||||
buildPasswordOverlay();
|
||||
|
||||
ESP_LOGI("Settings", "Settings screen built");
|
||||
@@ -903,6 +1083,11 @@ static void refreshNav() {
|
||||
snprintf(sys, sizeof(sys), "CAN %s \xE2\x80\xA2 Link %s", CANDriver::isActive() ? "on" : "off",
|
||||
UARTManager::getState() != UARTManager::UART_STATE_OFF ? "on" : "off");
|
||||
setText(g_nav_sub[PAGE_SYSTEM], sys);
|
||||
|
||||
char veh[40];
|
||||
uint16_t fd = Vehicle::finalDriveX100();
|
||||
snprintf(veh, sizeof(veh), "%u.%02u:1 \xE2\x80\xA2 %u mm", fd / 100, fd % 100, Vehicle::tyreMm());
|
||||
setText(g_nav_sub[PAGE_VEHICLE], veh);
|
||||
}
|
||||
|
||||
/** Caller holds the LVGL lock. */
|
||||
@@ -913,6 +1098,7 @@ static void refresh(bool force) {
|
||||
case PAGE_WIFI: refreshWifi(); break;
|
||||
case PAGE_UPDATES: refreshUpdates(); break;
|
||||
case PAGE_SYSTEM: refreshSystem(force); break;
|
||||
case PAGE_VEHICLE: refreshVehicle(); break;
|
||||
default: break;
|
||||
}
|
||||
g_refreshing = false;
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
/*
|
||||
* Sport Screen Module Implementation - see sport_screen.h
|
||||
*
|
||||
* Drawn after the BMW iDrive "Sport displays" (user's photo, 2026-10-13):
|
||||
* a wide dark-red band graded to bright orange at its inner edge, thin radial
|
||||
* dividers cutting it into segments, white numbers inside the band, a thin red
|
||||
* needle from the centre with no hub, the unit large in the middle and the
|
||||
* gauge's name underneath. No digital readout in the original; a small one is
|
||||
* kept under the unit because the bench has no other way to read the value.
|
||||
*
|
||||
* Each gauge is a dial-face IMAGE (assets/dial.png 420x420, rebuilt layer by
|
||||
* layer in PhotoCraft from the photo, source assets/dial.pcraft: cells ring
|
||||
* with a radial gradient and 15 dark gaps, dark ruler ring with 81 rungs, two
|
||||
* bright lines, rim with a halo, 5 light spokes; sweep 230 degrees from 155)
|
||||
* with an lv_meter on top that draws ONLY the numbers and the needle: its ticks
|
||||
* are zero-width. The needle is an image
|
||||
* (assets/needle.png, drawn in PhotoCraft 2026-10-13: tapered red body, lit
|
||||
* orange-white tip with a soft glow, transparent for the first 70 px so it
|
||||
* starts away from the pivot), rotated by lv_meter around its pivot at
|
||||
* (0, 24): x = radius from the dial centre, the tip at 212 = the rim.
|
||||
*/
|
||||
|
||||
#include "sport_screen.h"
|
||||
#include "ui_kit.h"
|
||||
#include "vehicle.h"
|
||||
#include "bench_sim.h"
|
||||
#include "driveline_screen.h"
|
||||
#include "drivers/can_driver.h"
|
||||
#include "display/lvgl_v8_port.h"
|
||||
|
||||
namespace SportScreen {
|
||||
|
||||
using namespace UiKit;
|
||||
|
||||
// ============================================================================
|
||||
// GAUGE DEFINITIONS
|
||||
// ============================================================================
|
||||
|
||||
// M57N (E60 530d donor): 500 Nm / 160 kW = 218 hp stock. The scales leave
|
||||
// headroom for a remap; the label steps copy the photo's 5 labels per sweep.
|
||||
static const int32_t TORQUE_MAX_NM = 600; // labels every 120 Nm, dividers every 12
|
||||
static const int32_t POWER_MAX_HP = 320; // labels every 80 hp, dividers every 8
|
||||
|
||||
static const lv_coord_t GAUGE_SIZE = 420;
|
||||
static const lv_coord_t GAUGE_Y = 72; // below the header / overlay band
|
||||
// the dial image's geometry (assets/dial_geometry.json): rim r 210, cells 158..190
|
||||
static const int32_t SWEEP_DEG = 230, START_DEG = 155; // open at the bottom, as the photo
|
||||
static const lv_coord_t LABEL_R = 136; // numbers just inside the cells ring
|
||||
|
||||
extern "C" { LV_IMG_DECLARE(needle_img); LV_IMG_DECLARE(dial_img); } // src/assets/*.c (C linkage)
|
||||
static const lv_coord_t NEEDLE_PIVOT_X = 0, NEEDLE_PIVOT_Y = 24;
|
||||
#define COL_NUMBER lv_color_hex(0xF2F2F2)
|
||||
|
||||
typedef struct {
|
||||
lv_obj_t* meter;
|
||||
lv_meter_scale_t* scale;
|
||||
lv_meter_indicator_t* needle;
|
||||
lv_obj_t* value_lbl;
|
||||
int32_t max;
|
||||
int32_t shown; // needle position last written
|
||||
} gauge_t;
|
||||
|
||||
// ============================================================================
|
||||
// STATE
|
||||
// ============================================================================
|
||||
|
||||
static lv_obj_t* g_screen = NULL;
|
||||
static lv_obj_t* g_status = NULL;
|
||||
static lv_obj_t* g_rpm_lbl = NULL;
|
||||
static lv_obj_t* g_speed_lbl = NULL;
|
||||
static gauge_t g_torque, g_power;
|
||||
|
||||
// ============================================================================
|
||||
// BUILD
|
||||
// ============================================================================
|
||||
|
||||
static void onBack(lv_event_t* e) {
|
||||
(void)e;
|
||||
DrivelineScreen::show();
|
||||
}
|
||||
|
||||
static void onGesture(lv_event_t* e) {
|
||||
(void)e;
|
||||
if (lv_indev_get_gesture_dir(lv_indev_get_act()) == LV_DIR_RIGHT) {
|
||||
lv_indev_wait_release(lv_indev_get_act());
|
||||
DrivelineScreen::show();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One BMW-style gauge. `minor_ticks` dividers over the sweep (incl. both
|
||||
* ends), a label every `major_every`-th divider.
|
||||
*/
|
||||
static void makeGauge(gauge_t& g, lv_coord_t x, const char* title, const char* unit,
|
||||
int32_t max, uint16_t minor_ticks, uint16_t major_every) {
|
||||
g.max = max;
|
||||
g.shown = -1;
|
||||
|
||||
// the dial face, then the meter (numbers + needle) on top of it
|
||||
lv_obj_t* face = lv_img_create(g_screen);
|
||||
lv_img_set_src(face, &dial_img);
|
||||
lv_obj_set_pos(face, x, GAUGE_Y);
|
||||
lv_obj_clear_flag(face, LV_OBJ_FLAG_CLICKABLE);
|
||||
|
||||
lv_obj_t* m = lv_meter_create(g_screen);
|
||||
g.meter = m;
|
||||
lv_obj_set_size(m, GAUGE_SIZE, GAUGE_SIZE);
|
||||
lv_obj_set_pos(m, x, GAUGE_Y);
|
||||
lv_obj_set_style_bg_opa(m, LV_OPA_TRANSP, 0); // no dial face: the band floats on black
|
||||
lv_obj_set_style_border_width(m, 0, 0);
|
||||
lv_obj_set_style_shadow_width(m, 0, 0);
|
||||
lv_obj_set_style_pad_all(m, 0, 0);
|
||||
lv_obj_set_style_text_font(m, &lv_font_montserrat_24, LV_PART_TICKS);
|
||||
lv_obj_set_style_text_color(m, COL_NUMBER, LV_PART_TICKS);
|
||||
lv_obj_set_style_size(m, 0, LV_PART_INDICATOR); // no needle hub
|
||||
lv_obj_clear_flag(m, LV_OBJ_FLAG_SCROLLABLE);
|
||||
lv_obj_clear_flag(m, LV_OBJ_FLAG_CLICKABLE); // swipes pass through to the screen
|
||||
|
||||
// same sweep as the image; the image carries the ticks, so the meter's are 0 px wide
|
||||
// and only the major ticks' labels are drawn (placed r_out - len - gap from the centre)
|
||||
g.scale = lv_meter_add_scale(m);
|
||||
lv_meter_set_scale_range(m, g.scale, 0, max, SWEEP_DEG, START_DEG);
|
||||
lv_meter_set_scale_ticks(m, g.scale, minor_ticks, 0, 1, lv_color_black());
|
||||
lv_meter_set_scale_major_ticks(m, g.scale, major_every, 0, 1, lv_color_black(),
|
||||
(GAUGE_SIZE / 2) - 1 - LABEL_R);
|
||||
|
||||
// the image needle: lv_meter rotates it about the pivot placed on the dial centre
|
||||
g.needle = lv_meter_add_needle_img(m, g.scale, &needle_img, NEEDLE_PIVOT_X, NEEDLE_PIVOT_Y);
|
||||
lv_meter_set_indicator_value(m, g.needle, 0);
|
||||
|
||||
// unit large in the middle, the live value small under it
|
||||
lv_obj_t* u = label(m, unit, &lv_font_montserrat_48, COL_NUMBER);
|
||||
lv_obj_align(u, LV_ALIGN_CENTER, 0, -14);
|
||||
g.value_lbl = label(m, "--", &lv_font_montserrat_30, UI_COL_MUTED);
|
||||
lv_obj_align(g.value_lbl, LV_ALIGN_CENTER, 0, 36);
|
||||
|
||||
// the gauge's name in the open bottom of the sweep
|
||||
lv_obj_t* t = label(g_screen, title, &lv_font_montserrat_30, COL_NUMBER);
|
||||
lv_obj_align_to(t, m, LV_ALIGN_BOTTOM_MID, 0, -8);
|
||||
}
|
||||
|
||||
static void build() {
|
||||
if (g_screen) return;
|
||||
g_screen = screen();
|
||||
lv_obj_set_style_bg_color(g_screen, lv_color_black(), 0); // the photo's black
|
||||
lv_obj_add_event_cb(g_screen, onGesture, LV_EVENT_GESTURE, NULL);
|
||||
header(g_screen, "SPORT", onBack);
|
||||
|
||||
g_status = label(g_screen, "", &lv_font_montserrat_20, UI_COL_AMBER);
|
||||
lv_obj_set_pos(g_status, 24, 64);
|
||||
|
||||
// two gauges, centred in their halves of the screen: Power left, Torque right (as in the photo)
|
||||
const lv_coord_t gap = 96;
|
||||
const lv_coord_t x0 = (1024 - 2 * GAUGE_SIZE - gap) / 2;
|
||||
// 5 numbers per sweep (the image has 16 cells, 4 per number): 0 80 ... 320 hp, 0 120 ... 600 Nm
|
||||
makeGauge(g_power, x0, "Power", "hp", POWER_MAX_HP, 5, 1);
|
||||
makeGauge(g_torque, x0 + GAUGE_SIZE + gap, "Torque", "Nm", TORQUE_MAX_NM, 5, 1);
|
||||
|
||||
// rpm and road speed between the gauge names, bottom edge
|
||||
lv_obj_t* row = box(g_screen, LV_FLEX_FLOW_ROW);
|
||||
lv_obj_set_size(row, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
|
||||
lv_obj_set_flex_align(row, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_END, LV_FLEX_ALIGN_END);
|
||||
lv_obj_set_style_pad_column(row, 14, 0);
|
||||
lv_obj_align(row, LV_ALIGN_BOTTOM_MID, 0, -14);
|
||||
label(row, "RPM", &lv_font_montserrat_14, UI_COL_MUTED);
|
||||
g_rpm_lbl = label(row, "----", &lv_font_montserrat_24, UI_COL_TEXT);
|
||||
lv_obj_t* sep = box(row, LV_FLEX_FLOW_ROW);
|
||||
lv_obj_set_size(sep, 24, 1);
|
||||
label(row, "SPEED", &lv_font_montserrat_14, UI_COL_MUTED);
|
||||
g_speed_lbl = label(row, "--", &lv_font_montserrat_24, UI_COL_TEXT);
|
||||
label(row, "~km/h", &lv_font_montserrat_14, UI_COL_MUTED);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// REFRESH
|
||||
// ============================================================================
|
||||
|
||||
/** Move the needle only when the shown value changes (lv_meter invalidates just the needle). */
|
||||
static void setGauge(gauge_t& g, int32_t v) {
|
||||
if (v < 0) v = 0;
|
||||
if (v > g.max) v = g.max;
|
||||
if (v == g.shown) return;
|
||||
g.shown = v;
|
||||
lv_meter_set_indicator_value(g.meter, g.needle, v);
|
||||
}
|
||||
|
||||
static void refresh() {
|
||||
bool can_up = CANDriver::isActive() || BenchSim::isActive(); // `sim` console counts as a live bus
|
||||
driveline_t dl = CANDriver::getDriveline();
|
||||
bool live = can_up && dl.ignition_on;
|
||||
|
||||
const char* st = "";
|
||||
if (BenchSim::isActive()) st = LV_SYMBOL_SETTINGS " SIMULATION - bench values from the console, not the car";
|
||||
else if (!can_up) st = LV_SYMBOL_WARNING " CAN bus is off - turn it on in Settings > System";
|
||||
else if (!dl.ignition_on) st = "Ignition off";
|
||||
setText(g_status, st);
|
||||
|
||||
char buf[24];
|
||||
if (!live) {
|
||||
setGauge(g_torque, 0);
|
||||
setGauge(g_power, 0);
|
||||
setText(g_torque.value_lbl, "--");
|
||||
setText(g_power.value_lbl, "--");
|
||||
setText(g_rpm_lbl, "----");
|
||||
setText(g_speed_lbl, "--");
|
||||
return;
|
||||
}
|
||||
|
||||
// torque: TORQ_AVL is signed (negative on overrun); the gauge floors at 0.
|
||||
// Only while the engine runs: with the key on and the engine off the field
|
||||
// holds a junk value (812 Nm on Patrol 2, 245 on Patrol 1 - captures 2026-10-18).
|
||||
bool running = (dl.engine_run_state == ENGINE_RUN_RUNNING);
|
||||
int32_t nm = running ? dl.engine_torque_x10 / 10 : 0;
|
||||
setGauge(g_torque, nm);
|
||||
if (running) snprintf(buf, sizeof(buf), "%ld", (long)(nm < 0 ? 0 : nm));
|
||||
else snprintf(buf, sizeof(buf), "--");
|
||||
setText(g_torque.value_lbl, buf);
|
||||
|
||||
uint16_t hp_x10 = running ? Vehicle::powerHpX10(dl.engine_torque_x10, dl.engine_rpm) : 0;
|
||||
setGauge(g_power, hp_x10 / 10);
|
||||
if (running) snprintf(buf, sizeof(buf), "%u", hp_x10 / 10);
|
||||
else snprintf(buf, sizeof(buf), "--");
|
||||
setText(g_power.value_lbl, buf);
|
||||
|
||||
snprintf(buf, sizeof(buf), "%u", dl.engine_rpm);
|
||||
setText(g_rpm_lbl, buf);
|
||||
|
||||
uint16_t kmh_x10 = Vehicle::speedKmhX10(dl.output_shaft_raw);
|
||||
snprintf(buf, sizeof(buf), "%u", kmh_x10 / 10);
|
||||
setText(g_speed_lbl, buf);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// PUBLIC API
|
||||
// ============================================================================
|
||||
|
||||
void show() {
|
||||
build();
|
||||
refresh();
|
||||
lv_scr_load_anim(g_screen, LV_SCR_LOAD_ANIM_NONE, 0, 0, false); // instant: fades stutter at 1024x600
|
||||
}
|
||||
|
||||
void tick() {
|
||||
if (g_screen == NULL || lv_scr_act() != g_screen) return;
|
||||
static uint32_t last = 0;
|
||||
if (millis() - last < 100) return; // 10 Hz, like the Driveline
|
||||
last = millis();
|
||||
lvgl_port_lock(-1);
|
||||
refresh();
|
||||
lvgl_port_unlock();
|
||||
}
|
||||
|
||||
} // namespace SportScreen
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Sport Screen Module
|
||||
*
|
||||
* BMW-style "Sport displays": two round gauges, engine torque (Nm, 0x0A8
|
||||
* TORQ_AVL straight from the bus) and engine power (hp, computed:
|
||||
* P(W) = Nm x rpm / 9.5488, hp = W / 745.70 - see Vehicle::powerHpX10()).
|
||||
* Each gauge has an arc fill, a needle, a thin peak needle that holds for a
|
||||
* few seconds, and the value in the gap at the bottom. Engine rpm and the
|
||||
* computed road speed sit under the gauges.
|
||||
*
|
||||
* Opened from the "Sport" button on the Driveline screen; the Driveline button
|
||||
* or a right swipe goes back. Built once and kept, like every screen.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <lvgl.h>
|
||||
|
||||
namespace SportScreen {
|
||||
|
||||
/** Build (idempotent) and load. Caller holds the LVGL lock. */
|
||||
void show();
|
||||
|
||||
/** Refresh the gauges while shown (10 Hz). Call from loop(); takes its own lock. */
|
||||
void tick();
|
||||
|
||||
} // namespace SportScreen
|
||||
@@ -0,0 +1,194 @@
|
||||
/*
|
||||
* Vehicle Module Implementation - see vehicle.h
|
||||
*/
|
||||
|
||||
#include "vehicle.h"
|
||||
#include "serial_lock.h"
|
||||
#include "protocol/automotive_data.h"
|
||||
#include <Preferences.h>
|
||||
|
||||
namespace Vehicle {
|
||||
|
||||
// ============================================================================
|
||||
// PRIVATE MODULE STATE
|
||||
// ============================================================================
|
||||
|
||||
static const char* NVS_NAMESPACE = "settings";
|
||||
static const char* NVS_KEY_FINAL = "final_x100";
|
||||
static const char* NVS_KEY_TYRE = "tyre_mm";
|
||||
|
||||
// Defaults: the Patrol's 4.11:1 final drive (user, 2026-10-13); 2440 mm is a
|
||||
// 265/70 R16 (overall diameter ~777 mm), a common Patrol tyre - adjust on the screen.
|
||||
static const uint16_t DEFAULT_FINAL_X100 = 411;
|
||||
static const uint16_t DEFAULT_TYRE_MM = 2440;
|
||||
|
||||
static volatile uint16_t g_final_x100 = DEFAULT_FINAL_X100;
|
||||
static volatile uint16_t g_tyre_mm = DEFAULT_TYRE_MM;
|
||||
|
||||
static const uint32_t SAVE_IDLE_MS = 3000;
|
||||
static bool g_dirty = false;
|
||||
static uint32_t g_dirty_ms = 0;
|
||||
|
||||
// ============================================================================
|
||||
// PRIVATE HELPERS
|
||||
// ============================================================================
|
||||
|
||||
static void print(const char* fmt, ...) {
|
||||
char buf[160];
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
vsnprintf(buf, sizeof(buf), fmt, ap);
|
||||
va_end(ap);
|
||||
SerialLock::lock();
|
||||
Serial.println(buf);
|
||||
SerialLock::unlock();
|
||||
}
|
||||
|
||||
static void markDirty() {
|
||||
g_dirty = true;
|
||||
g_dirty_ms = millis();
|
||||
}
|
||||
|
||||
static void save() {
|
||||
Preferences prefs;
|
||||
prefs.begin(NVS_NAMESPACE, false);
|
||||
prefs.putUShort(NVS_KEY_FINAL, g_final_x100);
|
||||
prefs.putUShort(NVS_KEY_TYRE, g_tyre_mm);
|
||||
prefs.end();
|
||||
print("[vehicle] saved final drive %u.%02u:1, tyre %u mm",
|
||||
g_final_x100 / 100, g_final_x100 % 100, g_tyre_mm);
|
||||
}
|
||||
|
||||
static void show() {
|
||||
print("[vehicle] final drive %u.%02u:1, tyre circumference %u mm%s",
|
||||
g_final_x100 / 100, g_final_x100 % 100, g_tyre_mm, g_dirty ? " (saving...)" : "");
|
||||
// a worked example so the numbers can be sanity-checked without driving
|
||||
uint16_t v = speedKmhX10FromRpm(1000);
|
||||
print("[vehicle] 1000 shaft rpm = %u.%u km/h (shaft rpm itself is the provisional 0x0BA x 0.1074)",
|
||||
v / 10, v % 10);
|
||||
}
|
||||
|
||||
static void help() {
|
||||
print("vehicle show final drive ratio, tyre circumference");
|
||||
print("vehicle set final <x.xx> final drive (differential) ratio, 2.00..8.00");
|
||||
print("vehicle set tyre <mm> tyre rolling circumference, 1500..3500 mm");
|
||||
print("vehicle reset back to 4.11:1 and 2440 mm");
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// PUBLIC API
|
||||
// ============================================================================
|
||||
|
||||
void init() {
|
||||
Preferences prefs;
|
||||
prefs.begin(NVS_NAMESPACE, true);
|
||||
g_final_x100 = prefs.getUShort(NVS_KEY_FINAL, DEFAULT_FINAL_X100);
|
||||
g_tyre_mm = prefs.getUShort(NVS_KEY_TYRE, DEFAULT_TYRE_MM);
|
||||
prefs.end();
|
||||
g_final_x100 = constrain(g_final_x100, FINAL_DRIVE_MIN_X100, FINAL_DRIVE_MAX_X100);
|
||||
g_tyre_mm = constrain(g_tyre_mm, TYRE_MM_MIN, TYRE_MM_MAX);
|
||||
print("[vehicle] final drive %u.%02u:1, tyre %u mm", g_final_x100 / 100, g_final_x100 % 100, g_tyre_mm);
|
||||
}
|
||||
|
||||
uint16_t finalDriveX100() { return g_final_x100; }
|
||||
uint16_t tyreMm() { return g_tyre_mm; }
|
||||
|
||||
void setFinalDriveX100(uint16_t v) {
|
||||
v = constrain(v, FINAL_DRIVE_MIN_X100, FINAL_DRIVE_MAX_X100);
|
||||
if (v == g_final_x100) return;
|
||||
g_final_x100 = v;
|
||||
markDirty();
|
||||
}
|
||||
|
||||
void setTyreMm(uint16_t v) {
|
||||
v = constrain(v, TYRE_MM_MIN, TYRE_MM_MAX);
|
||||
if (v == g_tyre_mm) return;
|
||||
g_tyre_mm = v;
|
||||
markDirty();
|
||||
}
|
||||
|
||||
uint16_t speedKmhX10FromRpm(uint16_t shaft_rpm) {
|
||||
// km/h = shaft_rpm / ratio * circumference_m * 60 / 1000
|
||||
// = shaft_rpm * tyre_mm * 6 / (final_x100 * 1000)
|
||||
// (tyre_mm / 1000 -> m, ratio = final_x100 / 100, * 60 min/h, / 1000 m/km)
|
||||
// km/h x10 = shaft_rpm * tyre_mm * 3 / (final_x100 * 50)
|
||||
// Integer only: 65535 * 3500 * 3 fits a 32-bit value with room.
|
||||
// Checked on the bench 2026-10-13: 1199 rpm, 4.11:1, 2440 mm -> 42.7 km/h.
|
||||
uint32_t num = (uint32_t)shaft_rpm * g_tyre_mm * 3;
|
||||
uint32_t den = (uint32_t)g_final_x100 * 50;
|
||||
uint32_t v = (num + den / 2) / den;
|
||||
return v > 0xFFFF ? 0xFFFF : (uint16_t)v;
|
||||
}
|
||||
|
||||
uint16_t speedKmhX10(uint16_t output_shaft_raw) {
|
||||
return speedKmhX10FromRpm(can_output_shaft_rpm(output_shaft_raw));
|
||||
}
|
||||
|
||||
uint16_t powerHpX10(int16_t torque_x10, uint16_t rpm) {
|
||||
if (torque_x10 <= 0 || rpm == 0) return 0;
|
||||
// P(W) = T * rpm / 9.5488 ; hp = P / 745.70 ; x10 and T in 0.1 Nm:
|
||||
// hp_x10 = (T_x10 / 10) * rpm / 9.5488 / 745.70 * 10 = T_x10 * rpm / 7120.55
|
||||
float hp_x10 = (float)torque_x10 * (float)rpm / 7120.55f;
|
||||
if (hp_x10 > 65535.0f) return 0xFFFF;
|
||||
return (uint16_t)(hp_x10 + 0.5f);
|
||||
}
|
||||
|
||||
void resetDefaults() {
|
||||
g_final_x100 = DEFAULT_FINAL_X100;
|
||||
g_tyre_mm = DEFAULT_TYRE_MM;
|
||||
markDirty();
|
||||
flush();
|
||||
}
|
||||
|
||||
void flush() {
|
||||
if (!g_dirty) return;
|
||||
g_dirty = false;
|
||||
save();
|
||||
}
|
||||
|
||||
bool isDirty() { return g_dirty; }
|
||||
|
||||
void tick() {
|
||||
if (g_dirty && millis() - g_dirty_ms > SAVE_IDLE_MS) flush();
|
||||
}
|
||||
|
||||
bool handleCommand(const char* line) {
|
||||
if (strncmp(line, "vehicle", 7) != 0 || (line[7] != 0 && line[7] != ' ')) return false;
|
||||
char buf[96];
|
||||
snprintf(buf, sizeof(buf), "%s", line);
|
||||
char* argv[5];
|
||||
int argc = 0;
|
||||
for (char* t = strtok(buf, " \t"); t && argc < 5; t = strtok(NULL, " \t")) argv[argc++] = t;
|
||||
|
||||
if (argc == 1 || !strcmp(argv[1], "help")) { help(); return true; }
|
||||
if (!strcmp(argv[1], "show")) { show(); return true; }
|
||||
if (!strcmp(argv[1], "reset")) { resetDefaults(); show(); return true; }
|
||||
if (!strcmp(argv[1], "set") && argc == 4) {
|
||||
if (!strcmp(argv[2], "final")) {
|
||||
float r = atof(argv[3]);
|
||||
long x100 = lroundf(r * 100.0f);
|
||||
if (x100 < FINAL_DRIVE_MIN_X100 || x100 > FINAL_DRIVE_MAX_X100) {
|
||||
print("[vehicle] final drive must be %u.%02u..%u.%02u", FINAL_DRIVE_MIN_X100 / 100, FINAL_DRIVE_MIN_X100 % 100,
|
||||
FINAL_DRIVE_MAX_X100 / 100, FINAL_DRIVE_MAX_X100 % 100);
|
||||
return true;
|
||||
}
|
||||
setFinalDriveX100((uint16_t)x100);
|
||||
show();
|
||||
return true;
|
||||
}
|
||||
if (!strcmp(argv[2], "tyre")) {
|
||||
long mm = atol(argv[3]);
|
||||
if (mm < TYRE_MM_MIN || mm > TYRE_MM_MAX) {
|
||||
print("[vehicle] tyre circumference must be %u..%u mm", TYRE_MM_MIN, TYRE_MM_MAX);
|
||||
return true;
|
||||
}
|
||||
setTyreMm((uint16_t)mm);
|
||||
show();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
help();
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace Vehicle
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
* Vehicle Module
|
||||
*
|
||||
* The two numbers that turn the gearbox output shaft speed (0x0BA, the only
|
||||
* road-speed signal on this bus - there is no DSC) into road speed, plus the
|
||||
* maths that uses them:
|
||||
*
|
||||
* wheel rpm = output shaft rpm / final drive ratio
|
||||
* speed (km/h) = wheel rpm * tyre circumference (m) * 60 / 1000
|
||||
*
|
||||
* and the engine power the Sport screen shows:
|
||||
*
|
||||
* power (W) = torque (Nm) * rpm / 9.5488
|
||||
* power (hp) = power (W) / 745.70
|
||||
*
|
||||
* Final drive ratio and tyre circumference are the user's (Settings > Vehicle,
|
||||
* `vehicle` console), saved in NVS (namespace "settings", keys `final_x100`,
|
||||
* `tyre_mm`). Writes are deferred like the tunables: every flash write flickers
|
||||
* the RGB panel, so edits are written SAVE_IDLE_MS after the last tap, or on
|
||||
* flush() when the Settings screen is left.
|
||||
*
|
||||
* NB the output shaft factor itself (raw counts -> rpm) is still provisional
|
||||
* (wiki driveline-speed-signals), so the speed carries the same "~".
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
namespace Vehicle {
|
||||
|
||||
/** Load the saved values (defaults if absent). Call after SettingsManager::init(). */
|
||||
void init();
|
||||
|
||||
/** Final drive (differential) ratio x100, e.g. 411 = 4.11:1. */
|
||||
uint16_t finalDriveX100();
|
||||
void setFinalDriveX100(uint16_t v);
|
||||
|
||||
/** Tyre rolling circumference in mm. */
|
||||
uint16_t tyreMm();
|
||||
void setTyreMm(uint16_t v);
|
||||
|
||||
/** Limits for the editors. */
|
||||
static const uint16_t FINAL_DRIVE_MIN_X100 = 200, FINAL_DRIVE_MAX_X100 = 800;
|
||||
static const uint16_t TYRE_MM_MIN = 1500, TYRE_MM_MAX = 3500;
|
||||
|
||||
/** Road speed in km/h x10 from the raw 0x0BA output shaft field. */
|
||||
uint16_t speedKmhX10(uint16_t output_shaft_raw);
|
||||
|
||||
/** Road speed in km/h x10 from an output shaft speed in rpm. */
|
||||
uint16_t speedKmhX10FromRpm(uint16_t shaft_rpm);
|
||||
|
||||
/** Engine power in hp x10 from torque (0.1 Nm, signed) and engine speed. Negative torque gives 0. */
|
||||
uint16_t powerHpX10(int16_t torque_x10, uint16_t rpm);
|
||||
|
||||
/** Back to the defaults (4.11:1, 2440 mm) and save. */
|
||||
void resetDefaults();
|
||||
|
||||
/** Write pending edits to NVS now (call when leaving the Settings screen). */
|
||||
void flush();
|
||||
|
||||
/** True while an edit is waiting for its deferred NVS write. */
|
||||
bool isDirty();
|
||||
|
||||
/** Deferred-save timer. Call from loop(). */
|
||||
void tick();
|
||||
|
||||
/** `vehicle show | set final <x.xx> | set tyre <mm> | reset`. */
|
||||
bool handleCommand(const char* line);
|
||||
|
||||
} // namespace Vehicle
|
||||
Reference in New Issue
Block a user