Diff-lock inputs: DI0 rear / DI1 front via CH422G EXIO0/EXIO5 (bank flipped to input per read), Settings > System switch default OFF, DIFF LOCK pills on the Driveline, 'difflock' console; wiki diff-lock-inputs
Firmware / build (push) Successful in 7m26s

This commit is contained in:
2026-09-29 09:48:57 +02:00
parent f07590bbc5
commit 31ca44187e
13 changed files with 362 additions and 10 deletions
+6 -2
View File
@@ -19,6 +19,7 @@
#include "modules/ota_update.h" // Manual firmware updates from Gitea releases (`ota` console)
#include "modules/link_peer.h" // Inst. Cluster status, pairing, credential handoff, B updates (`link` console)
#include "modules/status_overlay.h" // Every screen: Wi-Fi chip top-right, blinking alert banner top-centre
#include "modules/diff_locks.h" // Diff-lock inputs DI0 rear / DI1 front via the CH422G (`difflock` console)
// ============================================================================
// MINIMAL LVGL + UI SETTINGS + WIFI + UART
@@ -57,11 +58,12 @@ static bool memCommand(const char* line) {
return true;
}
// Console lines `cfg` doesn't recognise: diagnostic probe, OTA, Wi-Fi, mem.
// Console lines `cfg` doesn't recognise: diagnostic probe, OTA, Wi-Fi, mem, link, difflock.
static bool consoleExtraCommand(const char* line) {
return DiagProbe::handleCommand(line) || Ota::handleCommand(line) ||
WiFiManager::handleCommand(line) || memCommand(line) ||
PerfMon::handleCommand(line) || LinkPeer::handleCommand(line);
PerfMon::handleCommand(line) || LinkPeer::handleCommand(line) ||
DiffLocks::handleCommand(line);
}
// ============================================================================
@@ -107,6 +109,7 @@ void setup()
bool saved_uart_state = SettingsManager::loadUARTState();
bool saved_can_state = SettingsManager::loadCANState();
bool saved_debug_state = SettingsManager::loadDebugState();
DiffLocks::init(SettingsManager::loadDiffLockState()); // CH422G bus is up since DisplayInit
ESP_LOGI("MAIN", "Saved states loaded (UI will be updated when Settings screen opens)");
// Initialize UI State Manager
@@ -165,6 +168,7 @@ void loop()
DiagProbe::tick();
Ota::tick(); // confirms a freshly installed image after healthy uptime
LinkPeer::tick(); // Inst. Cluster heard/lost, credential sync
DiffLocks::tick(); // DI0/DI1 at 4 Hz, only when the Settings switch is on
DrivelineScreen::tick();
TuningScreen::tick();
+149
View File
@@ -0,0 +1,149 @@
/*
* Differential lock inputs - see diff_locks.h
*
* Schematic (V1.2, sheet 1): DINx -> PC814 LED -> 3.6 kOhm -> DI_COM. The
* optocoupler's transistor pulls DIx (4.7 kOhm to 3V3) LOW while current flows,
* so a LOCKED diff reads 0 on its EXIO bit. The PC814 LED is bidirectional:
* +12 V on DINx with DI_COM on ground is the "PNP / high-level" wiring.
*/
#include "diff_locks.h"
#include "settings_manager.h"
#include "serial_lock.h"
#include "display/lvgl_v8_port.h"
#include <driver/i2c.h>
#include <stdarg.h>
namespace DiffLocks {
// CH422G on the panel library's I2C host 0. Its "registers" are I2C addresses.
static const i2c_port_t CH422G_PORT = I2C_NUM_0;
static const uint8_t ADDR_WR_SET = 0x24; // system parameter byte
static const uint8_t ADDR_RD_IO = 0x26; // IO0-7 pin levels
// WR_SET as the board config leaves it (ESP_PANEL_BOARD_EXPANDER_POST_BEGIN_FUNCTION:
// enableAllIO_Output -> IO_OE only; OC push-pull, no sleep). Input = IO_OE cleared.
static const uint8_t WR_SET_OUTPUT = 0x01;
static const uint8_t WR_SET_INPUT = 0x00;
static const uint8_t BIT_REAR = 1 << 0; // DI0 = EXIO0
static const uint8_t BIT_FRONT = 1 << 5; // DI1 = EXIO5
static const uint32_t POLL_MS = 250;
static const uint8_t FAULT_AFTER = 3; // failed reads in a row
static bool g_enabled = false;
static bool g_rear = false, g_front = false; // debounced
static bool g_have_state = false;
static uint8_t g_last_raw = 0xFF;
static bool g_have_raw = false;
static uint8_t g_fail_run = 0;
static uint32_t g_reads = 0, g_fails = 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();
}
static esp_err_t writeSet(uint8_t v) {
return i2c_master_write_to_device(CH422G_PORT, ADDR_WR_SET, &v, 1, pdMS_TO_TICKS(10));
}
/**
* One raw read of IO0-7. The bank is an input only between the two WR_SET
* writes (three short I2C transactions); the output is restored even when the
* read fails, and retried, because touch reset, backlight and LCD reset live on
* the same bank. The caller holds the LVGL lock, so no touch read (same bus)
* can land in the middle.
*/
static bool readBank(uint8_t* out) {
if (writeSet(WR_SET_INPUT) != ESP_OK) {
writeSet(WR_SET_OUTPUT); // a half-done write: make sure we are back
return false;
}
esp_err_t r = i2c_master_read_from_device(CH422G_PORT, ADDR_RD_IO, out, 1, pdMS_TO_TICKS(10));
for (int i = 0; i < 3 && writeSet(WR_SET_OUTPUT) != ESP_OK; i++) {}
return r == ESP_OK;
}
void init(bool enabled) {
g_enabled = enabled;
print("[difflock] %s (DI0 = rear, DI1 = front)", enabled ? "ON" : "OFF - Settings > System to enable");
}
void setEnabled(bool enabled) {
if (enabled == g_enabled) return;
g_enabled = enabled;
g_have_state = g_have_raw = false;
g_rear = g_front = false;
g_fail_run = 0;
SettingsManager::saveDiffLockState(enabled);
}
bool isEnabled() { return g_enabled; }
bool isValid() { return g_enabled && g_have_state && g_fail_run < FAULT_AFTER; }
bool rearLocked() { return isValid() && g_rear; }
bool frontLocked() { return isValid() && g_front; }
void tick() {
if (!g_enabled || millis() - g_last_poll < POLL_MS) return;
g_last_poll = millis();
if (!lvgl_port_lock(100)) return; // UI busy: try again next poll
uint8_t raw = 0xFF;
bool ok = readBank(&raw);
lvgl_port_unlock();
g_reads++;
if (!ok) {
g_fails++;
if (g_fail_run < 255) g_fail_run++;
if (g_fail_run == FAULT_AFTER) print("[difflock] CH422G read failing - lock states unknown");
return;
}
g_fail_run = 0;
// Accept a state only when two reads in a row agree (<= 0.5 s latency).
uint8_t bits = raw & (BIT_REAR | BIT_FRONT);
if (g_have_raw && bits == (g_last_raw & (BIT_REAR | BIT_FRONT))) {
bool rear = !(bits & BIT_REAR); // opto conducting = pin low = locked
bool front = !(bits & BIT_FRONT);
if (!g_have_state || rear != g_rear || front != g_front) {
g_rear = rear;
g_front = front;
g_have_state = true;
print("[difflock] rear %s, front %s%s", rear ? "LOCKED" : "open", front ? "LOCKED" : "open",
(front && !rear) ? " (front without rear - check the DI0 wiring)" : "");
}
}
g_last_raw = raw;
g_have_raw = true;
}
bool handleCommand(const char* line) {
if (strncmp(line, "difflock", 8) != 0 || (line[8] != 0 && line[8] != ' ')) return false;
const char* a = line + 8;
while (*a == ' ') a++;
if (!strcmp(a, "on")) { setEnabled(true); print("[difflock] ON (saved)"); return true; }
if (!strcmp(a, "off")) { setEnabled(false); print("[difflock] OFF (saved)"); return true; }
if (!*a || !strcmp(a, "status")) {
if (!g_enabled) { print("[difflock] OFF - inputs not read ('difflock on' or Settings > System)"); return true; }
print("[difflock] rear %s, front %s | raw IO0-7 0x%02X | %lu reads, %lu failed%s",
!isValid() ? "?" : g_rear ? "LOCKED" : "open",
!isValid() ? "?" : g_front ? "LOCKED" : "open",
g_last_raw, (unsigned long)g_reads, (unsigned long)g_fails,
g_fail_run >= FAULT_AFTER ? " | READ FAULT" : "");
return true;
}
print("[difflock] usage: difflock status | on | off (DI0 = rear, DI1 = front, 12 V = locked)");
return true;
}
} // namespace DiffLocks
+38
View File
@@ -0,0 +1,38 @@
/*
* Differential lock inputs - DI0 = rear, DI1 = front
*
* The Patrol's lock switches put +12 V on a wire while a diff is locked. Those
* wires go to the board's isolated inputs (PC814 optocouplers, 5-36 V, DI_COM to
* vehicle ground). The inputs reach the ESP32 only through the CH422G expander
* (DI0 = EXIO0, DI1 = EXIO5), whose IO0-7 are all-in or all-out as ONE bank - and
* the same bank drives touch reset, backlight enable and LCD reset. So each read
* switches the bank to input for ~0.1 ms and straight back (output latches are
* kept by the chip). That is why the whole feature sits behind a Settings switch,
* default OFF: a board without diff-lock wiring never touches the bank.
*/
#pragma once
#include <Arduino.h>
namespace DiffLocks {
/** Call once after DisplayInit (the CH422G's I2C bus is installed by the panel library). */
void init(bool enabled);
/** Settings switch / `difflock on|off`. Saved to NVS (SettingsManager). */
void setEnabled(bool enabled);
bool isEnabled();
/** Poll the inputs (4 Hz, debounced over two reads). Call from loop(). */
void tick();
/** Enabled AND the last reads succeeded - otherwise the lock states mean nothing. */
bool isValid();
bool rearLocked();
bool frontLocked();
/** `difflock status | on | off`. Returns true if the line was ours. */
bool handleCommand(const char* line);
} // namespace DiffLocks
+60
View File
@@ -9,6 +9,7 @@
#include "drivers/can_driver.h"
#include "tuning_screen.h"
#include "settings_screen.h"
#include "diff_locks.h"
#include "esp_log.h"
namespace DrivelineScreen {
@@ -49,6 +50,9 @@ static lv_obj_t* g_ign_chip = NULL;
static lv_obj_t* g_eng_chip = NULL;
static lv_obj_t* g_clutch_chip = NULL;
static lv_obj_t* g_cool_chip = NULL;
static lv_obj_t* g_diff_box = NULL; // top-right: DIFF LOCK [REAR] [FRONT]
static lv_obj_t* g_rear_pill = NULL;
static lv_obj_t* g_front_pill = NULL;
// ============================================================================
// PRIVATE HELPERS
@@ -111,6 +115,38 @@ static void setChip(lv_obj_t* chip, const char* text, lv_color_t colour) {
}
}
/** A diff-lock pill: text, fill and text colour, each written only on change. */
static void setPill(lv_obj_t* pill, const char* text, lv_color_t bg, lv_color_t fg) {
setText(pill, text);
if (lv_color_to32(lv_obj_get_style_bg_color(pill, 0)) != lv_color_to32(bg)) {
lv_obj_set_style_bg_color(pill, bg, 0);
}
setColour(pill, fg);
}
/**
* @brief Diff locks, from the isolated inputs (not CAN - shown with CAN off too).
* Locked = amber tell-tale. The front can only lock after the rear, so
* FRONT without REAR is a wiring/switch fault and shows red.
*/
static void refreshDiffLocks() {
bool on = DiffLocks::isEnabled();
if (lv_obj_has_flag(g_diff_box, LV_OBJ_FLAG_HIDDEN) == on) {
if (on) lv_obj_clear_flag(g_diff_box, LV_OBJ_FLAG_HIDDEN);
else lv_obj_add_flag(g_diff_box, LV_OBJ_FLAG_HIDDEN);
}
if (!on) return;
if (!DiffLocks::isValid()) {
setPill(g_rear_pill, "REAR ?", COL_PANEL, COL_MUTED);
setPill(g_front_pill, "FRONT ?", COL_PANEL, COL_MUTED);
return;
}
bool rear = DiffLocks::rearLocked(), front = DiffLocks::frontLocked();
setPill(g_rear_pill, "REAR", rear ? COL_AMBER : COL_PANEL, rear ? COL_BG : COL_MUTED);
if (front && !rear) setPill(g_front_pill, "FRONT", COL_ALERT, COL_TEXT);
else setPill(g_front_pill, "FRONT", front ? COL_AMBER : COL_PANEL, front ? COL_BG : COL_MUTED);
}
/**
* @brief Compose the hero gear label from the 0x1D2 pieces.
*
@@ -212,6 +248,28 @@ static void build() {
g_cool_chip = makeChip(bar, "COOLING --");
// Gear mismatch: the ring and the gear letter turn red, and the overlay banner says so.
// ---- diff locks, top-right under the overlay's Wi-Fi chip (hidden until enabled)
g_diff_box = lv_obj_create(g_screen);
lv_obj_remove_style_all(g_diff_box);
lv_obj_set_size(g_diff_box, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
lv_obj_set_flex_flow(g_diff_box, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(g_diff_box, LV_FLEX_ALIGN_END, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_set_style_pad_column(g_diff_box, 8, 0);
lv_obj_align(g_diff_box, LV_ALIGN_TOP_RIGHT, -24, 60);
lv_obj_clear_flag(g_diff_box, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(g_diff_box, LV_OBJ_FLAG_HIDDEN);
lv_obj_t* diff_title = lv_label_create(g_diff_box);
lv_label_set_text(diff_title, "DIFF LOCK");
lv_obj_set_style_text_font(diff_title, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(diff_title, COL_MUTED, 0);
g_rear_pill = makeChip(g_diff_box, "REAR");
g_front_pill = makeChip(g_diff_box, "FRONT");
for (lv_obj_t* p : {g_rear_pill, g_front_pill}) {
lv_obj_set_style_text_font(p, &lv_font_montserrat_20, 0); // a tell-tale, bigger than the status chips
lv_obj_set_style_pad_hor(p, 14, 0);
}
// ---- gear hero -------------------------------------------------------
g_gear_ring = lv_obj_create(g_screen);
lv_obj_set_size(g_gear_ring, 220, 220);
@@ -322,6 +380,8 @@ void tick() {
(void)gear; // gear now comes from the driveline pieces, not the UART enum
lvgl_port_lock(-1);
refreshDiffLocks(); // hard-wired inputs: live even with CAN or the key off
// 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
+15
View File
@@ -19,6 +19,7 @@ static const char* NVS_KEY_WIFI_ENABLED = "wifi_en";
static const char* NVS_KEY_UART_ENABLED = "uart_en";
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";
// ============================================================================
// PUBLIC API IMPLEMENTATION
@@ -89,4 +90,18 @@ bool loadCANState() {
return enabled;
}
void saveDiffLockState(bool enabled) {
preferences.begin(NVS_NAMESPACE, false); // read-write mode
preferences.putBool(NVS_KEY_DIFFLOCK_ENABLED, enabled);
preferences.end();
Serial.printf("[SettingsManager] Saved DiffLock state = %s\n", enabled ? "ON" : "OFF");
}
bool loadDiffLockState() {
preferences.begin(NVS_NAMESPACE, true); // read-only mode
bool enabled = preferences.getBool(NVS_KEY_DIFFLOCK_ENABLED, false); // default: OFF
preferences.end();
return enabled;
}
} // namespace SettingsManager
+4
View File
@@ -66,4 +66,8 @@ void saveCANState(bool enabled);
*/
bool loadCANState();
/** Diff-lock inputs DI0/DI1 read (DiffLocks). Default OFF. */
void saveDiffLockState(bool enabled);
bool loadDiffLockState();
} // namespace SettingsManager
+24 -6
View File
@@ -8,6 +8,7 @@
#include "wifi_manager.h"
#include "ota_update.h"
#include "link_peer.h"
#include "diff_locks.h"
#include "uart_manager.h"
#include "espnow_link.h"
#include "settings_manager.h"
@@ -82,6 +83,8 @@ static Ota::phase_t g_upd_refusal_phase = Ota::PHASE_IDLE;
static lv_obj_t* g_sys_can = NULL;
static lv_obj_t* g_sys_link = NULL;
static lv_obj_t* g_sys_dbg = NULL;
static lv_obj_t* g_sys_diff = NULL;
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
static void refresh(bool force);
@@ -768,10 +771,22 @@ static void onDebugSwitch(lv_event_t* e) {
UIStateManager::setDebugEnabled(on);
}
static void onDiffSwitch(lv_event_t* e) {
if (g_refreshing) return;
DiffLocks::setEnabled(lv_obj_has_state(lv_event_get_target(e), LV_STATE_CHECKED));
}
static void refreshSystem(bool force) {
setChecked(g_sys_can, CANDriver::isActive());
setChecked(g_sys_link, UARTManager::getState() != UARTManager::UART_STATE_OFF);
setChecked(g_sys_dbg, UIStateManager::isDebugEnabled());
setChecked(g_sys_diff, DiffLocks::isEnabled());
// live state in the sub-line, so the wiring can be tested from this page
if (!DiffLocks::isEnabled()) setText(g_sys_diff_sub, "DI0 rear, DI1 front - 12 V = locked");
else if (!DiffLocks::isValid()) setText(g_sys_diff_sub, "Now: reading...");
else setText(g_sys_diff_sub, DiffLocks::frontLocked()
? (DiffLocks::rearLocked() ? "Now: rear LOCKED, front LOCKED" : "Now: FRONT only - check DI0 wiring")
: (DiffLocks::rearLocked() ? "Now: rear LOCKED, front open" : "Now: both open"));
static uint32_t last = 0; // the figures below change slowly; 1 Hz is plenty
if (!force && millis() - last < 1000) return;
@@ -782,18 +797,17 @@ static void refreshSystem(bool force) {
uint32_t up = millis() / 1000;
char buf[400];
snprintf(buf, sizeof(buf),
"%s (slot %s)\n"
"%s (slot %s), up %lu h %02lu min\n"
"ESP-NOW %s, %lu frames sent, %lu failed\n"
"%lu frames received\n"
"%u KB internal free, %u KB PSRAM free\n"
"%lu h %02lu min",
"%u KB internal free, %u KB PSRAM free",
FW_VERSION, run ? run->label : "?",
(unsigned long)(up / 3600), (unsigned long)((up / 60) % 60),
EspNowLink::isReady() ? "up" : "DOWN",
(unsigned long)EspNowLink::sentCount(), (unsigned long)EspNowLink::failCount(),
(unsigned long)cs.messages_received,
(unsigned)(heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) / 1024),
(unsigned)(heap_caps_get_free_size(MALLOC_CAP_SPIRAM) / 1024),
(unsigned long)(up / 3600), (unsigned long)((up / 60) % 60));
(unsigned)(heap_caps_get_free_size(MALLOC_CAP_SPIRAM) / 1024));
setText(g_sys_info, buf);
}
@@ -810,13 +824,17 @@ static void buildSystemPage(lv_obj_t* page) {
g_sys_link = toggle(right, onLinkSwitch, NULL);
makeSettingRow(c, "Performance overlay", "Frame rate and CPU load in the corner", &right);
g_sys_dbg = toggle(right, onDebugSwitch, NULL);
lv_obj_t* diff_row = makeSettingRow(c, "Diff lock inputs", "DI0 rear, DI1 front - 12 V = locked", &right);
g_sys_diff_sub = lv_obj_get_child(lv_obj_get_child(diff_row, 0), 1);
g_sys_diff = toggle(right, onDiffSwitch, NULL);
// two labels side by side, same line spacing, so keys and values line up
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_ROW);
lv_obj_set_style_pad_column(info, 24, 0);
lv_obj_t* keys = label(info, "Firmware\nLink to B\nCAN bus\nMemory\nUptime", &lv_font_montserrat_20, UI_COL_MUTED);
// Uptime shares the firmware line: a fourth switch row leaves no room for a fifth line (484 px page)
lv_obj_t* keys = label(info, "Firmware\nLink to B\nCAN bus\nMemory", &lv_font_montserrat_20, UI_COL_MUTED);
lv_obj_set_style_text_line_space(keys, 6, 0);
g_sys_info = label(info, "", &lv_font_montserrat_20, UI_COL_TEXT);
lv_obj_set_style_text_line_space(g_sys_info, 6, 0);