Compare commits

...

10 Commits

24 changed files with 813 additions and 87 deletions

1
.gitignore vendored
View File

@@ -16,4 +16,5 @@ vendor/esp32-s3-lcd-43/GFX_Library_for_Arduino/
*~
.DS_Store
compile_commands.json
.board-last
.cache/

View File

@@ -90,7 +90,8 @@ void DisplayDriverTFT::begin() {
_tft.setRotation(DISPLAY_ROTATION);
_tft.fillScreen(TFT_BLACK);
Serial.printf("[GFX] Display OK: %dx%d\n", DISPLAY_WIDTH, DISPLAY_HEIGHT);
Serial.printf("[GFX] Display OK: const %dx%d, tft %dx%d\n", DISPLAY_WIDTH, DISPLAY_HEIGHT,
_tft.width(), _tft.height());
Serial.flush();
// Debug: check if touch controller is responding
@@ -137,6 +138,12 @@ void DisplayDriverTFT::render(const ScreenState& st) {
_needsRedraw = false;
}
break;
case ScreenID::STATUS:
if(_needsRedraw) {
drawStatus(st);
_needsRedraw = false;
}
break;
case ScreenID::OFF:
if(_needsRedraw) {
_tft.fillScreen(TFT_BLACK);
@@ -153,16 +160,16 @@ void DisplayDriverTFT::drawBoot(const ScreenState& st) {
_tft.setTextColor(TFT_WHITE, TFT_BLACK);
setTitleFont();
_tft.setCursor(10, 10);
_tft.setCursor(10, 28); // y=28 baseline accounts for ~18px font height above baseline
_tft.print("KLUBHAUS");
setBodyFont();
_tft.setCursor(10, 40);
_tft.setCursor(10, 55); // y adjusted for ~12px font
_tft.print(BOARD_NAME);
// Show boot stage status
setLabelFont();
_tft.setCursor(10, 70);
_tft.setCursor(10, 85); // y adjusted for ~9px label font
switch(stage) {
case BootStage::SPLASH:
_tft.print("Initializing...");
@@ -186,39 +193,69 @@ void DisplayDriverTFT::drawBoot(const ScreenState& st) {
}
void DisplayDriverTFT::drawAlert(const ScreenState& st) {
// Static 2-color pulse - alternate every ~2 seconds
uint32_t elapsed = millis() - st.alertStartMs;
uint8_t pulse = 180 + (uint8_t)(75.0f * sinf(elapsed / 300.0f));
uint16_t bg = _tft.color565(pulse, 0, 0);
bool brightPhase = (elapsed / 2000) % 2 == 0;
_tft.fillScreen(bg);
_tft.setTextColor(TFT_WHITE, bg);
// Redraw when phase changes OR when touch was released (to clear fill)
bool needsRedraw = (brightPhase != _lastAlertPhase) || _alertNeedsRedraw;
setTitleFont();
_tft.setCursor(10, 20);
_tft.print(st.alertTitle.length() > 0 ? st.alertTitle : "ALERT");
if(needsRedraw) {
_lastAlertPhase = brightPhase;
_alertNeedsRedraw = false; // clear the flag
uint16_t bg = brightPhase ? TFT_RED : _tft.color565(180, 0, 0);
setBodyFont();
_tft.setCursor(10, 80);
_tft.print(st.alertBody);
_tft.fillScreen(bg);
_tft.setTextColor(TFT_WHITE, bg);
setLabelFont();
_tft.setCursor(10, DISPLAY_HEIGHT - 20);
_tft.print("Hold to silence...");
setTitleFont();
_tft.setCursor(10, 28);
_tft.print(st.alertTitle.length() > 0 ? st.alertTitle : "ALERT");
setBodyFont();
_tft.setCursor(10, 70);
_tft.print(st.alertBody);
setLabelFont();
_tft.setCursor(10, _tft.height() - 10);
_tft.print("Hold to silence...");
}
// Progressive fill hint - while touch is held
if(_alertTouchDown) {
uint32_t touchElapsed = millis() - _alertTouchStartMs;
float progress = (float)touchElapsed / (float)ALERT_FILL_DURATION_MS;
if(progress > 1.0f)
progress = 1.0f;
int dispH = _tft.height();
int fillHeight = (int)(dispH * progress);
if(fillHeight > 0) {
uint16_t overlay = _tft.color565(80, 0, 0);
_tft.fillRect(0, dispH - fillHeight, _tft.width(), fillHeight, overlay);
}
}
}
void DisplayDriverTFT::drawDashboard(const ScreenState& st) {
_tft.fillScreen(TFT_BLACK);
// Header
_tft.fillRect(0, 0, DISPLAY_WIDTH, 30, 0x1A1A); // Dark gray header
setBodyFont();
// Use actual display dimensions (after rotation)
int dispW = _tft.width();
int dispH = _tft.height();
// Header - using standard bitmap font for reliable positioning
_tft.fillRect(0, 0, dispW, STYLE_HEADER_HEIGHT, 0x1A1A); // Dark gray header
_tft.setTextSize(1);
_tft.setTextColor(TFT_WHITE);
_tft.setCursor(5, 10);
_tft.setCursor(5, 20); // y=28 is baseline, text sits above this
_tft.print("KLUBHAUS");
// WiFi indicator
_tft.setCursor(DISPLAY_WIDTH - 60, 10);
_tft.print(st.wifiSsid.length() > 0 ? "WiFi:ON" : "WiFi:OFF");
// WiFi indicator - right aligned in header
const char* wifiText = st.wifiSsid.length() > 0 ? "WiFi:ON" : "WiFi:OFF";
int wifiW = _tft.textWidth(wifiText);
_tft.setCursor(dispW - wifiW - 10, 20);
_tft.print(wifiText);
// Get tile layouts from library helper
int tileCount = display.calculateDashboardLayouts(STYLE_HEADER_HEIGHT, STYLE_TILE_GAP);
@@ -250,6 +287,61 @@ void DisplayDriverTFT::drawDashboard(const ScreenState& st) {
}
}
void DisplayDriverTFT::drawStatus(const ScreenState& st) {
int dispW = _tft.width();
int dispH = _tft.height();
_tft.fillScreen(TFT_BLACK);
// Header
_tft.fillRect(0, 0, dispW, STYLE_HEADER_HEIGHT, 0x1A1A);
_tft.setTextSize(1);
_tft.setTextColor(TFT_WHITE);
_tft.setCursor(5, 20);
_tft.print("STATUS");
// Back button in lower right
_tft.setCursor(dispW - 60, dispH - 20);
_tft.print("[BACK]");
// Status info
setBodyFont();
int y = STYLE_HEADER_HEIGHT + 20;
// WiFi
_tft.setCursor(10, y);
_tft.printf("WiFi: %s", st.wifiSsid.length() > 0 ? st.wifiSsid.c_str() : "N/A");
y += 20;
_tft.setCursor(10, y);
_tft.printf("RSSI: %d dBm", st.wifiRssi);
y += 20;
_tft.setCursor(10, y);
_tft.printf("IP: %s", st.ipAddr.length() > 0 ? st.ipAddr.c_str() : "N/A");
y += 30;
// Uptime
uint32_t upSec = st.uptimeMs / 1000;
uint32_t upMin = upSec / 60;
uint32_t upHr = upMin / 60;
upSec = upSec % 60;
upMin = upMin % 60;
_tft.setCursor(10, y);
_tft.printf("Uptime: %02lu:%02lu:%02lu", upHr, upMin, upSec);
y += 20;
// Heap
_tft.setCursor(10, y);
_tft.printf("Heap: %d bytes", ESP.getFreeHeap());
y += 20;
// Last poll
uint32_t pollAgo = (millis() - st.lastPollMs) / 1000;
_tft.setCursor(10, y);
_tft.printf("Last poll: %lu sec ago", pollAgo);
}
// ── Touch ───────────────────────────────────────────────────
TouchEvent DisplayDriverTFT::readTouch() {
@@ -285,6 +377,12 @@ TouchEvent DisplayDriverTFT::readTouch() {
uint16_t tx, ty;
uint8_t touched = _tft.getTouch(&tx, &ty, 100);
// Debug: log touch state changes
if(touched != _touchWasPressed) {
Serial.printf("[TOUCH] raw touched=%d wasPressed=%d (x=%d,y=%d)\n", touched,
_touchWasPressed, tx, ty);
}
// Detect transitions (press/release)
if(touched && !_touchWasPressed) {
// Press transition: finger just touched down
@@ -310,6 +408,16 @@ TouchEvent DisplayDriverTFT::readTouch() {
// Track previous state for next call
_touchWasPressed = touched;
// Track alert touch for progressive hint
if(evt.pressed) {
_alertTouchDown = true;
_alertTouchStartMs = millis();
} else if(evt.released) {
_alertTouchDown = false;
_alertNeedsRedraw = true; // force redraw to clear fill
}
return evt;
}
@@ -320,11 +428,10 @@ void DisplayDriverTFT::transformTouch(int* x, int* y) {
*y = temp;
}
HoldState DisplayDriverTFT::updateHold(unsigned long holdMs) {
HoldState DisplayDriverTFT::updateHold(const TouchEvent& evt, unsigned long holdMs) {
HoldState h;
TouchEvent t = readTouch();
if(t.pressed) {
if(evt.pressed) {
if(!_holdActive) {
_holdActive = true;
_holdStartMs = millis();
@@ -336,13 +443,15 @@ HoldState DisplayDriverTFT::updateHold(unsigned long holdMs) {
h.completed = (held >= holdMs);
// Simple progress bar at bottom of screen
int barW = (int)(DISPLAY_WIDTH * h.progress);
_tft.fillRect(0, DISPLAY_HEIGHT - 8, barW, 8, TFT_WHITE);
_tft.fillRect(barW, DISPLAY_HEIGHT - 8, DISPLAY_WIDTH - barW, 8, TFT_DARKGREY);
int dispW = _tft.width();
int dispH = _tft.height();
int barW = (int)(dispW * h.progress);
_tft.fillRect(0, dispH - 8, barW, 8, TFT_WHITE);
_tft.fillRect(barW, dispH - 8, dispW - barW, 8, TFT_DARKGREY);
} else {
if(_holdActive) {
// Clear the progress bar when released
_tft.fillRect(0, DISPLAY_HEIGHT - 8, DISPLAY_WIDTH, 8, TFT_DARKGREY);
_tft.fillRect(0, _tft.height() - 8, _tft.width(), 8, TFT_DARKGREY);
}
_holdActive = false;
}

View File

@@ -11,8 +11,11 @@ public:
void setBacklight(bool on) override;
void render(const ScreenState& state) override;
TouchEvent readTouch() override;
HoldState updateHold(unsigned long holdMs) override;
int width() override { return _tft.width(); }
HoldState updateHold(const TouchEvent& evt, unsigned long holdMs) override;
int width() override {
// Use TFT_eSPI's dimensions after rotation - it's more reliable
return _tft.width();
}
int height() override { return _tft.height(); }
// Dashboard - uses transform for touch coordinate correction
@@ -28,6 +31,7 @@ private:
void drawBoot(const ScreenState& st);
void drawAlert(const ScreenState& st);
void drawDashboard(const ScreenState& st);
void drawStatus(const ScreenState& st);
TFT_eSPI _tft;
@@ -37,6 +41,13 @@ private:
BootStage _lastBootStage = BootStage::SPLASH;
bool _needsRedraw = true;
// Touch hint for alert - progressive fill from bottom
bool _alertTouchDown = false;
bool _alertNeedsRedraw = false; // force redraw after touch release
uint32_t _alertTouchStartMs = 0;
bool _lastAlertPhase = false; // tracks bright/dark phase for 2-color alert
static constexpr uint32_t ALERT_FILL_DURATION_MS = 3000;
// Touch tracking for press/release detection
bool _touchWasPressed = false;
int _touchDownX = -1;

View File

@@ -1,4 +1,4 @@
FQBN="esp32:esp32:esp32:FlashSize=4M,PartitionScheme=default"
PORT="/dev/ttyUSB0"
LIBS="--libraries ./vendor/esp32-32e-4/TFT_eSPI"
LIBS="--library ./vendor/esp32-32e-4/TFT_eSPI"
OPTS="-DDEBUG_MODE -DBOARD_HAS_PSRAM -DLOAD_GFXFF=1"

View File

@@ -1,6 +1,6 @@
#pragma once
#define BOARD_NAME "WS_32E_4"
#define BOARD_NAME "esp32-32e-4"
// ══════════════════════════════════════════════════════════
// Hosyond ESP32-32E 4" (320x480) with ST7796 + XPT2046

View File

@@ -200,7 +200,7 @@ void DisplayDriverTFT::drawDashboard(const ScreenState& st) {
_tft.setTextColor(TFT_WHITE, TFT_BLACK);
_tft.setTextSize(1);
_tft.setCursor(5, 5);
_tft.setCursor(5, 10);
_tft.printf("KLUBHAUS — %s", deviceStateStr(st.deviceState));
int y = 30;
@@ -298,11 +298,10 @@ int DisplayDriverTFT::dashboardTouch(int x, int y) {
return row * 2 + col; // 0, 1, 2, or 3
}
HoldState DisplayDriverTFT::updateHold(unsigned long holdMs) {
HoldState DisplayDriverTFT::updateHold(const TouchEvent& evt, unsigned long holdMs) {
HoldState h;
TouchEvent t = readTouch();
if(t.pressed) {
if(evt.pressed) {
if(!_holdActive) {
_holdActive = true;
_holdStartMs = millis();

View File

@@ -12,7 +12,7 @@ public:
void render(const ScreenState& state) override;
TouchEvent readTouch() override;
int dashboardTouch(int x, int y);
HoldState updateHold(unsigned long holdMs) override;
HoldState updateHold(const TouchEvent& evt, unsigned long holdMs) override;
int width() override { return DISPLAY_WIDTH; }
int height() override { return DISPLAY_HEIGHT; }

View File

@@ -1,4 +1,4 @@
FQBN="esp32:esp32:esp32:FlashSize=4M,PartitionScheme=default"
PORT="/dev/ttyUSB0"
LIBS="--libraries ./vendor/esp32-32e/TFT_eSPI"
LIBS="--library ./vendor/esp32-32e/TFT_eSPI"
OPTS="-DDEBUG_MODE -DBOARD_HAS_PSRAM -DLOCAL_SECRETS -DLOAD_GFXFF=1"

View File

@@ -1,6 +1,6 @@
#pragma once
#define BOARD_NAME "WS_32E"
#define BOARD_NAME "esp32-32e"
// ══════════════════════════════════════════════════════════
// TODO: Set these to match YOUR display + wiring.

View File

@@ -261,10 +261,10 @@ int DisplayDriverGFX::dashboardTouch(int x, int y) {
return row * cols + col;
}
HoldState DisplayDriverGFX::updateHold(unsigned long holdMs) {
HoldState DisplayDriverGFX::updateHold(const TouchEvent& evt, unsigned long holdMs) {
HoldState state;
if(!_lastTouch.pressed) {
if(!evt.pressed) {
_isHolding = false;
return state;
}
@@ -395,16 +395,37 @@ void DisplayDriverGFX::drawAlert(const ScreenState& state) {
void DisplayDriverGFX::drawDashboard(const ScreenState& state) {
_gfx->fillScreen(STYLE_COLOR_BG);
// Header
// Header - use Layout for safe positioning
_gfx->fillRect(0, 0, DISP_W, STYLE_HEADER_HEIGHT, STYLE_COLOR_HEADER);
Layout header = Layout::header(DISP_W, STYLE_HEADER_HEIGHT);
Layout safeText = header.padded(STYLE_SPACING_X);
setBodyFont();
_gfx->setTextColor(STYLE_COLOR_FG);
_gfx->setCursor(STYLE_SPACING_X, 12);
_gfx->printf("KLUBHAUS");
// WiFi status
_gfx->setCursor(DISP_W - 120, 12);
_gfx->printf("WiFi:%s", state.wifiSsid.length() > 0 ? "ON" : "OFF");
// Title with scrolling support
_headerScroller.setText("KLUBHAUS");
_headerScroller.setScrollSpeed(80);
_headerScroller.setPauseDuration(2000);
_headerScroller.render(
[&](int16_t x, const char* s) {
_gfx->setCursor(safeText.x + x, safeText.y + 4);
_gfx->print(s);
},
safeText.w);
// WiFi status - right aligned with scrolling
Layout wifiArea(DISP_W - 150, 0, 140, STYLE_HEADER_HEIGHT);
Layout safeWifi = wifiArea.padded(4);
_wifiScroller.setText(state.wifiSsid.length() > 0 ? state.wifiSsid.c_str() : "WiFi: OFF");
_wifiScroller.setScrollSpeed(60);
_wifiScroller.setPauseDuration(1500);
_wifiScroller.render(
[&](int16_t x, const char* s) {
_gfx->setCursor(safeWifi.x + x, safeWifi.y + 4);
_gfx->print(s);
},
safeWifi.w);
// Get tile layouts from library helper
int tileCount = display.calculateDashboardLayouts(STYLE_HEADER_HEIGHT, STYLE_TILE_GAP);

View File

@@ -1,6 +1,7 @@
#pragma once
#include "IDisplayDriver.h"
#include "Style.h"
#include <Arduino.h>
@@ -12,7 +13,7 @@ public:
void render(const ScreenState& state) override;
TouchEvent readTouch() override;
HoldState updateHold(unsigned long holdMs) override;
HoldState updateHold(const TouchEvent& evt, unsigned long holdMs) override;
void drawDebugTouch(int x, int y) override;
int width() override;
@@ -54,4 +55,8 @@ private:
ScreenID _lastScreen = ScreenID::BOOT;
BootStage _lastBootStage = BootStage::SPLASH;
bool _needsRedraw = true;
// Text scrollers for scrolling elements
TextScroller _headerScroller;
TextScroller _wifiScroller;
};

View File

@@ -1,4 +1,4 @@
FQBN="esp32:esp32:waveshare_esp32_s3_touch_lcd_43:PSRAM=enabled,FlashSize=16M,USBMode=hwcdc,PartitionScheme=app3M_fat9M_16MB"
PORT="/dev/ttyACM0"
LIBS="--libraries ~/Arduino/libraries/LovyanGFX"
PORT="/dev/ttyUSB0"
LIBS="--library ./vendor/esp32-s3-lcd-43/LovyanGFX"
OPTS="-DDEBUG_MODE -DBOARD_HAS_PSRAM -DLGFX_USE_V1 -DLOCAL_SECRETS"

View File

@@ -1,6 +1,6 @@
#pragma once
#define BOARD_NAME "WS_S3_43"
#define BOARD_NAME "esp32-s3-lcd-43"
#define DISPLAY_WIDTH 800
#define DISPLAY_HEIGHT 480
#define DISPLAY_ROTATION 0

189
justfile Normal file
View File

@@ -0,0 +1,189 @@
# Klubhaus Doorbell - justfile
# Run with: just <recipe>
# Set BOARD: just BOARD=esp32-32e-4 compile
# Default recipe - show help
default:
@just --list
# Set default BOARD
BOARD := "esp32-32e-4"
# Helper to source board config
# just passes args as positional, so we source in each recipe
# Compile firmware
compile:
#!/usr/bin/env bash
set -e
source ./boards/{{BOARD}}/board-config.sh
# Only regenerate compile_commands.json if needed (board changed or first run)
NEED_GEN=false
if [ ! -f compile_commands.json ]; then
NEED_GEN=true
elif [ ! -f .board-last ] || [ "$(cat .board-last)" != "{{BOARD}}" ]; then
NEED_GEN=true
fi
if [ "$NEED_GEN" = "true" ]; then
rm -rf /tmp/arduino-build
arduino-cli compile --only-compilation-database --fqbn "$FQBN" --libraries ./libraries $LIBS --build-property "compiler.cpp.extra_flags=$OPTS" --build-path /tmp/arduino-build ./boards/{{BOARD}}
cp /tmp/arduino-build/compile_commands.json .
echo "{{BOARD}}" > .board-last
echo "[OK] Generated compile_commands.json for {{BOARD}}"
else
echo "[SKIP] compile_commands.json already up to date for {{BOARD}}"
fi
arduino-cli compile --fqbn "$FQBN" --libraries ./libraries $LIBS --build-property "compiler.cpp.extra_flags=$OPTS" --warnings default ./boards/{{BOARD}}
# Upload firmware
upload: kill
#!/usr/bin/env bash
set -e
source ./boards/{{BOARD}}/board-config.sh
arduino-cli upload --fqbn "$FQBN" --port "$PORT" ./boards/{{BOARD}}
# Kill processes using serial port
kill:
#!/usr/bin/env bash
set +e
source ./boards/{{BOARD}}/board-config.sh
PORT="${PORT:-$PORT}"
echo "Killing processes on $PORT..."
fuser -k "$PORT" 2>/dev/null || true
for pid in $(pgrep -f "monitor-agent.py.*{{BOARD}}" 2>/dev/null || true); do
echo "Killing monitor-agent.py (PID: $pid)..."
kill "$pid" 2>/dev/null || true
done
rm -f "/tmp/doorbell-{{BOARD}}.lock" 2>/dev/null || true
sleep 1
echo "[OK] Killed processes for {{BOARD}}"
# Monitor raw serial
monitor-raw: kill
#!/usr/bin/env bash
source ./boards/{{BOARD}}/board-config.sh
PORT="${PORT:-$PORT}"
TARGET="$(readlink -f "$PORT" 2>/dev/null || echo "$PORT")"
arduino-cli monitor -p "$TARGET" --config baudrate=115200
# Show tio command
monitor-tio: kill
#!/usr/bin/env bash
source ./boards/{{BOARD}}/board-config.sh
PORT="${PORT:-$PORT}"
TARGET="$(readlink -f "$PORT" 2>/dev/null || echo "$PORT")"
echo "Run: tio --map INLCRNL $TARGET -e"
# Monitor with JSON logging
monitor: kill
#!/usr/bin/env bash
python3 ./scripts/monitor-agent.py "{{BOARD}}" &
# Tail colored logs
watch:
#!/usr/bin/env bash
tail -f "/tmp/doorbell-{{BOARD}}.jsonl" | while read -r line; do
ts=$(echo "$line" | python3 -c "import sys,json; print(json.load(sys.stdin)['ts'])" 2>/dev/null)
txt=$(echo "$line" | python3 -c "import sys,json; print(json.load(sys.stdin)['line'])" 2>/dev/null)
if [[ "$txt" == *"[STATE]"* ]]; then
echo -e "\033[1;35m[$ts]\033[0m $txt"
elif [[ "$txt" == *"[ADMIN]"* ]]; then
echo -e "\033[1;36m[$ts]\033[0m $txt"
elif [[ "$txt" == *"[TOUCH]"* ]]; then
echo -e "\033[1;33m[$ts]\033[0m $txt"
elif [[ "$txt" == *"ALERT"* ]]; then
echo -e "\033[1;31m[$ts]\033[0m $txt"
else
echo "[$ts] $txt"
fi
done
# Send command to device
cmd command:
#!/usr/bin/env bash
echo -n "{{command}}" > "/tmp/doorbell-{{BOARD}}-cmd.fifo"
echo "[SENT] {{command}}"
# Show device state
state:
@cat "/tmp/doorbell-{{BOARD}}-state.json"
# Detect connected board
detect:
#!/usr/bin/env bash
bash ./scripts/detect-device.sh
# Install shared libraries
install-libs-shared:
#!/usr/bin/env bash
./scripts/install-shared.sh
# Install all libraries
install: install-libs-shared
#!/usr/bin/env bash
./boards/{{BOARD}}/install.sh
arduino-cli core install esp32:esp32
# Clean build artifacts
clean:
#!/usr/bin/env bash
rm -rf vendor/
rm -rf .cache/
rm -rf boards/esp32-32e/build
rm -rf boards/esp32-32e-4/build
rm -rf boards/esp32-s3-lcd-43/build
rm -f .board-last
echo "[OK] Build artifacts cleaned"
# Clean temporary files (monitor logs, FIFOs, state files)
clean-temp:
#!/usr/bin/env bash
rm -f /tmp/doorbell-esp32-32e.jsonl /tmp/doorbell-esp32-32e-state.json /tmp/doorbell-esp32-32e-cmd.fifo
rm -f /tmp/doorbell-esp32-32e-4.jsonl /tmp/doorbell-esp32-32e-4-state.json /tmp/doorbell-esp32-32e-4-cmd.fifo
rm -f /tmp/doorbell-esp32-s3-lcd-43.jsonl /tmp/doorbell-esp32-s3-lcd-43-state.json /tmp/doorbell-esp32-s3-lcd-43-cmd.fifo
rm -f .board-last
echo "[OK] Temp files cleaned"
# Clean Arduino cache
arduino-clean:
#!/usr/bin/env bash
echo "Checking ~/.arduino15..."
du -sh ~/.arduino15/staging 2>/dev/null || echo "No staging folder"
du -sh ~/.arduino15/packages 2>/dev/null || echo "No packages folder"
read -p "Delete staging + packages folders? [y/N] " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
rm -rf ~/.arduino15/staging
rm -rf ~/.arduino15/packages
echo "[OK] Arduino staging + packages cleared"
else
echo "Aborted"
fi
# Format code
format:
#!/usr/bin/env bash
clang-format -i --style=file \
boards/esp32-32e/*.cpp \
boards/esp32-32e/*.h \
boards/esp32-32e/*.ino \
boards/esp32-32e-4/*.cpp \
boards/esp32-32e-4/*.h \
boards/esp32-32e-4/*.ino \
boards/esp32-s3-lcd-43/*.cpp \
boards/esp32-s3-lcd-43/*.h \
boards/esp32-s3-lcd-43/*.ino \
libraries/KlubhausCore/src/*.cpp \
libraries/KlubhausCore/src/*.h \
libraries/KlubhausCore/*.properties
# Generate crush config
gen-crush-config:
#!/usr/bin/env bash
set -e
source ./boards/{{BOARD}}/board-config.sh
printf '{\n "lsp": {\n "arduino": {\n "command": "arduino-language-server",\n "args": ["-fqbn", "%s"]\n },\n "cpp": {\n "command": "clangd"\n }\n }\n}\n' "$FQBN" > .crush.json
echo "[OK] Generated .crush.json with FQBN: $FQBN"

View File

@@ -13,7 +13,7 @@
#define POLL_INTERVAL_MS 15000
#define HEARTBEAT_INTERVAL_MS 300000
#define BOOT_GRACE_MS 5000
#define HOLD_TO_SILENCE_MS 3000
#define HOLD_TO_SILENCE_MS 2000
#define ALERT_TIMEOUT_MS 120000
#define SILENCE_DISPLAY_MS 10000
#define INACTIVITY_TIMEOUT_MS 30000

View File

@@ -2,6 +2,7 @@
#include "IDisplayDriver.h"
#include "ScreenState.h"
#include "Style.h"
#include <cmath>
@@ -59,6 +60,14 @@ private:
/// Calculate optimal grid dimensions based on display and tile constraints
static void calculateGrid(
int tileCount, int displayW, int contentH, int* outCols, int* outRows) {
// Use 2x2 grid for 4 tiles regardless of aspect ratio
// This provides better visual balance than a single row
if(tileCount == 4) {
*outCols = 2;
*outRows = 2;
return;
}
// Calculate aspect ratio to determine preferred layout
float aspectRatio = (float)displayW / contentH;
@@ -137,7 +146,9 @@ public:
TouchEvent readTouch() { return _drv ? _drv->readTouch() : TouchEvent {}; }
HoldState updateHold(unsigned long ms) { return _drv ? _drv->updateHold(ms) : HoldState {}; }
HoldState updateHold(const TouchEvent& evt, unsigned long ms) {
return _drv ? _drv->updateHold(evt, ms) : HoldState {};
}
void drawDebugTouch(int x, int y) {
if(_drv)
@@ -172,50 +183,54 @@ public:
/// Handle dashboard touch - returns action for tapped tile, or NONE
TileAction handleDashboardTouch(int x, int y) const {
if(!_drv || _gridCols <= 0)
return TileAction::NONE;
HitResult hr = hitTest(x, y);
if(hr.type == UIElementType::TILE && hr.index >= 0 && hr.index < DASHBOARD_TILE_COUNT) {
return DASHBOARD_TILES[hr.index].action;
}
return TileAction::NONE;
}
// Transform touch coordinates (handles rotated touch panels)
_drv->transformTouch(&x, &y);
/// Perform hit test at coordinates - returns element type, index, and bounds
HitResult hitTest(int x, int y) const {
if(!_drv)
return HitResult();
int tx = x, ty = y;
_drv->transformTouch(&tx, &ty);
int dispW = _drv->width();
int dispH = _drv->height();
int headerH = 30;
int headerH = _headerHeight;
// Check if in header area
if(y < headerH)
return TileAction::NONE;
// Calculate which tile was touched using grid
int cellW = dispW / _gridCols;
int cellH = (dispH - headerH) / _gridRows;
int col = x / cellW;
int row = (y - headerH) / cellH;
// Bounds check
if(col < 0 || col >= _gridCols || row < 0 || row >= _gridRows) {
return TileAction::NONE;
// Check header
Rect headerRect = UIElements::header(dispW, headerH);
if(headerRect.contains(tx, ty)) {
return HitResult(UIElementType::HEADER, 0, headerRect);
}
// Find which tile occupies this cell
// Check tiles
for(int i = 0; i < _tileCount; i++) {
const TileLayout& layout = _layouts[i];
if(layout.col <= col && col < layout.col + layout.cols && layout.row <= row
&& row < layout.row + layout.rows) {
return DASHBOARD_TILES[i].action;
const TileLayout& lay = _layouts[i];
Rect tileRect(lay.x, lay.y, lay.w, lay.h);
if(tileRect.contains(tx, ty)) {
return HitResult(UIElementType::TILE, i, tileRect);
}
}
return TileAction::NONE;
return HitResult();
}
/// Set header height for hit testing (call after calculateDashboardLayouts or manually)
void setHeaderHeight(int h) { _headerHeight = h; }
int getHeaderHeight() const { return _headerHeight; }
/// Calculate and store layouts for dashboard tiles
/// Called by drivers who want to use the layout helper
int calculateDashboardLayouts(int headerH = 30, int margin = 8) {
if(!_drv)
return 0;
_headerHeight = headerH;
_tileCount = TileLayoutHelper::calculateLayouts(
_drv->width(), _drv->height(), headerH, margin, _layouts, &_gridCols, &_gridRows);
return _tileCount;
@@ -232,4 +247,5 @@ private:
int _tileCount = 0;
int _gridCols = 0;
int _gridRows = 0;
int _headerHeight = 30;
};

View File

@@ -304,8 +304,24 @@ void DoorbellLogic::onSerialCommand(const String& cmd) {
Serial.println();
Serial.printf("[NET] %s RSSI:%d IP:%s\n", _state.wifiSsid.c_str(), _state.wifiRssi,
_state.ipAddr.c_str());
} else if(cmd == "board") {
Serial.printf("[BOARD] %s\n", _board);
} else if(cmd.startsWith("hittest ")) {
String args = cmd.substring(8);
int comma = args.indexOf(',');
if(comma > 0) {
int x = args.substring(0, comma).toInt();
int y = args.substring(comma + 1).toInt();
HitResult hr = _display->hitTest(x, y);
Serial.printf("[Hittest] raw:(%d,%d) type:%d index:%d bounds:(%d,%d,%d,%d)\n", x, y,
(int)hr.type, hr.index, hr.bounds.x, hr.bounds.y, hr.bounds.w, hr.bounds.h);
Serial.printf("[Display] w:%d h:%d headerH:%d\n", _display->width(), _display->height(),
_display->getHeaderHeight());
} else {
Serial.println("[Hittest] Usage: hittest x,y");
}
} else
Serial.println(F("[CMD] alert|silence|reboot|dashboard|off|status"));
Serial.println(F("[CMD] alert|silence|reboot|dashboard|off|status|board"));
}
void DoorbellLogic::setScreen(ScreenID s) {
@@ -319,8 +335,19 @@ void DoorbellLogic::setScreen(ScreenID s) {
}
int DoorbellLogic::handleTouch(const TouchEvent& evt) {
// Check hold completion FIRST - before any release handling
// This ensures hold-to-silence works on ALERT screen
if(evt.released && _state.deviceState == DeviceState::ALERTING) {
Serial.printf("[TOUCH] checking hold: deviceState=ALERTING\n");
if(updateHold(evt)) {
return (int)TileAction::SILENCE;
}
}
// Handle press - show visual feedback
if(evt.pressed) {
Serial.printf("[TOUCH] pressed screen=%d deviceState=%d\n", (int)_state.screen,
(int)_state.deviceState);
// Reset inactivity timer on any touch
_lastActivityMs = millis();
@@ -330,6 +357,18 @@ int DoorbellLogic::handleTouch(const TouchEvent& evt) {
return -1;
}
// Handle STATUS screen back button (lower right corner)
if(_state.screen == ScreenID::STATUS) {
int dispW = _display->width();
int dispH = _display->height();
// Back button area: lower right (dispW-60 to dispW, dispH-30 to dispH)
if(evt.x >= dispW - 60 && evt.y >= dispH - 30) {
Serial.printf("[%lu] [TOUCH] STATUS → DASHBOARD (back)\n", millis());
setScreen(ScreenID::DASHBOARD);
return -1;
}
}
// Draw debug crosshair at touch point
#ifdef DEBUG_MODE
if(_state.screen == ScreenID::DASHBOARD) {
@@ -341,6 +380,9 @@ int DoorbellLogic::handleTouch(const TouchEvent& evt) {
// Handle release - fire action if same tile
if(evt.released) {
Serial.printf("[TOUCH] released screen=%d deviceState=%d\n", (int)_state.screen,
(int)_state.deviceState);
if(_state.screen == ScreenID::DASHBOARD) {
// Only fire action if finger stayed on same tile
if(evt.downX >= 0 && _display->isSameTile(evt.downX, evt.downY, evt.x, evt.y)) {
@@ -356,7 +398,7 @@ int DoorbellLogic::handleTouch(const TouchEvent& evt) {
silenceAlert();
break;
case TileAction::STATUS:
heartbeat();
setScreen(ScreenID::STATUS);
break;
case TileAction::REBOOT:
flushStatus("REBOOT (tile)");
@@ -390,7 +432,7 @@ bool DoorbellLogic::updateHold(const TouchEvent& evt) {
static int holdStartX = -1;
static int holdStartY = -1;
HoldState h = _display->updateHold(HOLD_TO_SILENCE_MS);
HoldState h = _display->updateHold(evt, HOLD_TO_SILENCE_MS);
if(h.completed) {
silenceAlert();

View File

@@ -23,6 +23,7 @@ public:
void processSerial();
const ScreenState& getScreenState() const { return _state; }
const char* getBoard() const { return _board; }
/// Externally trigger silence (e.g. hold-to-silence gesture).
void silenceAlert();

View File

@@ -31,7 +31,7 @@ public:
// ── Touch ──
virtual TouchEvent readTouch() = 0;
virtual HoldState updateHold(unsigned long holdMs) = 0;
virtual HoldState updateHold(const TouchEvent& evt, unsigned long holdMs) = 0;
virtual void drawDebugTouch(int x, int y) { /* default: no-op */ }
virtual int width() = 0;
virtual int height() = 0;

View File

@@ -3,7 +3,7 @@
enum class DeviceState { BOOTED, SILENT, ALERTING, SILENCED };
enum class ScreenID { BOOT, OFF, ALERT, DASHBOARD };
enum class ScreenID { BOOT, OFF, ALERT, DASHBOARD, STATUS };
enum class BootStage { SPLASH, INIT_DISPLAY, INIT_NETWORK, CONNECTING_WIFI, READY, DONE };
@@ -94,6 +94,8 @@ inline const char* screenIdStr(ScreenID s) {
return "ALERT";
case ScreenID::DASHBOARD:
return "DASHBOARD";
case ScreenID::STATUS:
return "STATUS";
}
return "?";
}

View File

@@ -1,5 +1,6 @@
#pragma once
#include <Arduino.h>
#include <cstdint>
struct Layout {
@@ -36,6 +37,89 @@ struct Layout {
uint16_t y = row * (tileH + gap);
return Layout(x, y, tileW, tileH);
}
Layout clamp(uint16_t maxW, uint16_t maxH) const {
return Layout(
x < maxW ? x : maxW, y < maxH ? y : maxH, w <= maxW ? w : maxW, h <= maxH ? h : maxH);
}
Layout padded(uint16_t padding) const {
uint16_t newX = x + padding;
uint16_t newY = y + padding;
uint16_t newW = w > 2 * padding ? w - 2 * padding : 0;
uint16_t newH = h > 2 * padding ? h - 2 * padding : 0;
return Layout(newX, newY, newW, newH);
}
bool contains(uint16_t px, uint16_t py) const {
return px >= x && px < x + w && py >= y && py < y + h;
}
};
class TextScroller {
public:
TextScroller()
: _text()
, _scrollOffset(0)
, _lastUpdateMs(0)
, _scrollSpeed(50)
, _pauseMs(2000) { }
void setText(const char* text) {
if(text != _text.c_str()) {
_text = text;
_scrollOffset = 0;
_lastUpdateMs = 0;
_paused = false;
}
}
void setScrollSpeed(uint16_t msPerPixel) { _scrollSpeed = msPerPixel; }
void setPauseDuration(uint16_t ms) { _pauseMs = ms; }
template <typename DrawFn> void render(DrawFn draw, uint16_t maxWidth) {
uint32_t now = millis();
if(_text.length() <= maxWidth / 8) {
draw(0, _text.c_str());
return;
}
if(!_paused && now - _lastUpdateMs > _scrollSpeed) {
_scrollOffset++;
_lastUpdateMs = now;
if(_scrollOffset > (int)_text.length() * 6) {
_paused = true;
_pauseStartMs = now;
}
}
if(_paused && now - _pauseStartMs > _pauseMs) {
_paused = false;
_scrollOffset = 0;
_lastUpdateMs = now;
}
int16_t x = -_scrollOffset;
char buf[2] = { 0 };
for(size_t i = 0; i < _text.length(); i++) {
buf[0] = _text.charAt(i);
if(x + 8 > 0 && x < (int)maxWidth) {
draw(x, buf);
}
x += 6;
}
}
private:
String _text;
int16_t _scrollOffset;
uint32_t _lastUpdateMs;
uint32_t _pauseStartMs;
uint16_t _scrollSpeed;
uint16_t _pauseMs;
bool _paused;
};
struct TileMetrics {
@@ -60,3 +144,86 @@ struct TileMetrics {
return Layout(col * (tileW + gap), row * (tileH + gap), tileW, tileH);
}
};
struct Rect {
int16_t x, y;
int16_t w, h;
Rect()
: x(0)
, y(0)
, w(0)
, h(0) { }
Rect(int16_t x_, int16_t y_, int16_t w_, int16_t h_)
: x(x_)
, y(y_)
, w(w_)
, h(h_) { }
int16_t left() const { return x; }
int16_t top() const { return y; }
int16_t right() const { return x + w; }
int16_t bottom() const { return y + h; }
bool contains(int16_t px, int16_t py) const {
return px >= x && px < x + w && py >= y && py < y + h;
}
bool intersects(const Rect& other) const {
return !(
right() <= other.x || other.right() <= x || bottom() <= other.y || other.bottom() <= y);
}
Rect expanded(int16_t dx, int16_t dy) const {
return Rect(x - dx, y - dy, w + 2 * dx, h + 2 * dy);
}
Rect translated(int16_t dx, int16_t dy) const { return Rect(x + dx, y + dy, w, h); }
};
enum class UIElementType { NONE, HEADER, TILE, BUTTON, ICON };
struct HitResult {
UIElementType type;
int16_t index;
Rect bounds;
HitResult()
: type(UIElementType::NONE)
, index(-1)
, bounds() { }
HitResult(UIElementType t, int16_t i, const Rect& b)
: type(t)
, index(i)
, bounds(b) { }
bool isValid() const { return type != UIElementType::NONE; }
operator bool() const { return isValid(); }
};
class UIElements {
public:
static Rect header(uint16_t screenW, uint16_t headerH) { return Rect(0, 0, screenW, headerH); }
static Rect contentArea(
uint16_t screenW, uint16_t screenH, uint16_t headerH, uint16_t padding = 10) {
return Rect(
padding, headerH + padding, screenW - 2 * padding, screenH - headerH - 2 * padding);
}
static Rect tile(uint8_t col, uint8_t row, uint8_t cols, uint8_t rows, uint16_t contentX,
uint16_t contentY, uint16_t contentW, uint16_t contentH, uint8_t gap = 8) {
uint16_t tileW = (contentW - (cols - 1) * gap) / cols;
uint16_t tileH = (contentH - (rows - 1) * gap) / rows;
int16_t x = contentX + col * (tileW + gap);
int16_t y = contentY + row * (tileH + gap);
return Rect(x, y, tileW, tileH);
}
static Rect button(int16_t x, int16_t y, int16_t w, int16_t h, int16_t padding = 8) {
return Rect(x - padding, y - padding, w + 2 * padding, h + 2 * padding);
}
static Rect icon(int16_t x, int16_t y, int16_t size) { return Rect(x, y, size, size); }
};

View File

@@ -135,6 +135,10 @@ run = """
./boards/$BOARD/install.sh
"""
[tasks.detect]
description = "Detect connected doorbell board"
run = "bash ./scripts/detect-device.sh"
# Convenience
[tasks.clean]

160
scripts/detect-device.sh Executable file
View File

@@ -0,0 +1,160 @@
#!/bin/bash
#
# detect-device.sh - Detect which doorbell board is connected
#
# Uses two methods:
# 1. Firmware query (if flashed): sends "board" command, expects "[BOARD] xxx"
# 2. Hardware probe (fallback): uses esptool to query chip type and flash size
#
# Usage: ./scripts/detect-device.sh [port]
# If no port specified, tries common ports: /dev/ttyUSB0 /dev/ttyACM0
set -e
# Configuration
TIMEOUT_FIRMWARE=2
TIMEOUT_HARDWARE=5
# Known boards and their characteristics
declare -A BOARD_CHIP=(
["esp32-s3-lcd-43"]="ESP32-S3"
["esp32-32e"]="ESP32"
["esp32-32e-4"]="ESP32"
)
# Find available serial ports
find_ports() {
local ports=()
for p in /dev/ttyUSB0 /dev/ttyUSB1 /dev/ttyACM0 /dev/ttyACM1; do
if [ -e "$p" ]; then
ports+=("$p")
fi
done
printf '%s\n' "${ports[@]}"
}
# Query firmware for board name
query_firmware() {
local port="$1"
# Try using Python for more reliable serial communication
local output
output=$(python3 -c "
import serial
import time
try:
s = serial.Serial('$port', 115200, timeout=$TIMEOUT_FIRMWARE)
time.sleep(0.5)
s.write(b'board\r\n')
time.sleep($TIMEOUT_FIRMWARE)
print(s.read(200).decode('utf-8', errors='ignore'))
s.close()
except:
pass
" 2>/dev/null || true)
# Look for [BOARD] xxx pattern
if echo "$output" | grep -q '\[BOARD\]'; then
local board
board=$(echo "$output" | grep '\[BOARD\]' | sed 's/.*\[BOARD\] //' | tr -d '\r\n')
if [ -n "$board" ]; then
echo "$board"
return 0
fi
fi
return 1
}
# Hardware probe using esptool
probe_hardware() {
local port="$1"
# Get chip info
local chip_info
chip_info=$(timeout "$TIMEOUT_HARDWARE" esptool --port "$port" chip_id 2>/dev/null || true)
if [ -z "$chip_info" ]; then
return 1
fi
# Check for ESP32-S3
if echo "$chip_info" | grep -q "ESP32-S3"; then
echo "esp32-s3-lcd-43"
return 0
fi
# For ESP32, check flash size
if echo "$chip_info" | grep -q "ESP32"; then
local flash_size
flash_size=$(echo "$chip_info" | grep -i "flash size" | grep -oE '[0-9]+' | head -1 || echo "0")
if [ -n "$flash_size" ] && [ "$flash_size" -ge 8 ]; then
# 8MB+ flash - likely esp32-32e-4
echo "esp32-32e-4 (or esp32-32e)"
return 0
else
# 4MB or less - likely esp32-32e
echo "esp32-32e (or esp32-32e-4)"
return 0
fi
fi
return 1
}
# Main detection logic
detect() {
local port="$1"
# Try firmware query first (100% accurate if firmware responds)
echo "Trying firmware query on $port..." >&2
local result
result=$(query_firmware "$port" || true)
if [ -n "$result" ]; then
echo "Detected via firmware: $result"
return 0
fi
# Fall back to hardware probe
echo "Trying hardware probe on $port..." >&2
result=$(probe_hardware "$port" || true)
if [ -n "$result" ]; then
echo "Detected via hardware: $result"
return 0
fi
echo "No device detected on $port" >&2
return 1
}
# Entry point
main() {
local target_port="$1"
if [ -n "$target_port" ]; then
# Specific port requested
if [ ! -e "$target_port" ]; then
echo "Error: Port $target_port does not exist" >&2
exit 1
fi
detect "$target_port"
else
# Auto-detect: try all available ports
local found=0
for port in $(find_ports); do
if detect "$port"; then
found=1
break
fi
done
if [ "$found" -eq 0 ]; then
echo "No doorbell device detected" >&2
exit 1
fi
fi
}
main "$@"

Submodule vendor/esp32-s3-lcd-43/LovyanGFX deleted from 42998359d8