From 74e16cd8988d58a4e78e8782eab8dda0604fec13 Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Fri, 23 Oct 2026 13:08:39 +0200 Subject: [PATCH 1/2] feat: update and secure files --- .gitignore | 1 + AGENTS.md | 2 +- app/src/App.tsx | 24 +- app/src/components/EspSidebar.tsx | 9 + app/src/components/Flash.tsx | 55 ---- app/src/components/Layout.tsx | 1 + app/src/components/Setup.module.css | 9 - app/src/components/Setup.tsx | 192 -------------- .../layout/LayoutPluginPalette.module.css | 46 ---- .../components/layout/LayoutPluginPalette.tsx | 56 ---- app/src/lib/config.test.ts | 55 ++++ app/src/lib/config.ts | 248 ++++++++++++++++-- app/src/lib/deviceSetupStorage.ts | 7 +- app/src/lib/globalVarsStorage.test.ts | 28 ++ app/src/lib/globalVarsStorage.ts | 17 ++ app/src/lib/layoutStorage.ts | 7 +- app/src/lib/serial.test.ts | 40 ++- app/src/lib/serial.ts | 70 +++-- app/tsconfig.tsbuildinfo | 1 - firmware/include/AppConfig.h | 1 + firmware/include/AppConfigParser.h | 6 +- firmware/include/ConfigStore.h | 9 +- firmware/include/TimeService.h | 6 + firmware/src/AppConfig.cpp | 15 +- firmware/src/ConfigStore.cpp | 57 ++-- firmware/src/PluginRegistry.cpp | 42 +-- firmware/src/SerialProvisioning.cpp | 57 ++-- firmware/src/TimeService.cpp | 44 +++- firmware/src/main.cpp | 10 +- plugins/get-data/firmware/GetDataPlugin.cpp | 40 ++- plugins/ha-cover/firmware/HaCoverPlugin.cpp | 66 +++-- plugins/ha-sensor/firmware/HaSensorPlugin.cpp | 67 ++++- plugins/weather/firmware/WeatherPlugin.cpp | 50 +++- 33 files changed, 804 insertions(+), 534 deletions(-) delete mode 100644 app/src/components/Flash.tsx delete mode 100644 app/src/components/Setup.module.css delete mode 100644 app/src/components/Setup.tsx delete mode 100644 app/src/components/layout/LayoutPluginPalette.module.css delete mode 100644 app/src/components/layout/LayoutPluginPalette.tsx create mode 100644 app/src/lib/globalVarsStorage.test.ts delete mode 100644 app/tsconfig.tsbuildinfo diff --git a/.gitignore b/.gitignore index 92c50ae..cf13472 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ firmware/include/version.generated.h app/public/firmware/*.bin app/public/firmware/manifest.json +*.tsbuildinfo diff --git a/AGENTS.md b/AGENTS.md index 2e1e48d..5269158 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -84,7 +84,7 @@ Full field reference and step-by-step for adding a plugin: `docs/plugins.md`. - `app/src/lib/layoutStorage.ts`, `deviceSetupStorage.ts`, `globalVarsStorage.ts` — browser-persisted state (layout drafts, device setup, `$var:KEY` global variables referenced by `text`/`color` config fields). - `app/src/lib/serial.ts` — reads device config over USB serial (uses `esp-web-tools` for flashing). - `app/src/models/` — `LayoutCell`, `LayoutDraft`, `BudpyConfigInput`, `DeviceSetupInput` types. -- `app/src/components/layout/` — drag/drop layout editor (`layoutCells.ts`, `layoutDrag.ts`) and the plugin palette/customization panels. +- `app/src/components/layout/` — drag/drop layout editor (`layoutCells.ts`, `layoutDrag.ts`), the preview grid and the customization panel (plugin picker + settings form). - Config field type `image`: file picker resizes to cell pixel size, re-encodes JPEG, stores base64 (no `data:` prefix, 48 KB cap) in cell config; firmware base64-decodes and renders (see `plugins/image`). ## Firmware structure diff --git a/app/src/App.tsx b/app/src/App.tsx index 42744be..7cb37e2 100644 --- a/app/src/App.tsx +++ b/app/src/App.tsx @@ -3,9 +3,6 @@ import { EspSidebar } from "./components/EspSidebar"; import { Layout } from "./components/Layout"; import { createBudpyConfigInputFromConfig, - defaultBackgroundColor, - defaultBrightness, - defaultBrightnessMode, fitCellsToOrientation, getLayoutPageCount, listPluginManifests, @@ -108,25 +105,20 @@ export function App() { config, pluginManifests, ); - const nextCells = fitCellsToOrientation( - importedInput.cells, - importedInput.orientation, - ); - const nextSetupInput = { - ssid: importedInput.ssid, - password: importedInput.password, - backgroundColor: importedInput.backgroundColor ?? defaultBackgroundColor, - brightness: importedInput.brightness ?? defaultBrightness, - brightnessMode: importedInput.brightnessMode ?? defaultBrightnessMode, - } satisfies DeviceSetupInput; + const { + orientation: importedOrientation, + cells: importedCells, + ...nextSetupInput + } = importedInput; + const nextCells = fitCellsToOrientation(importedCells, importedOrientation); setSetupInput(nextSetupInput); saveStoredDeviceSetupInput(nextSetupInput); - setOrientation(importedInput.orientation); + setOrientation(importedOrientation); setActivePage(0); setCells(nextCells); saveStoredLayoutDraft({ - orientation: importedInput.orientation, + orientation: importedOrientation, activePage: 0, cells: nextCells, }); diff --git a/app/src/components/EspSidebar.tsx b/app/src/components/EspSidebar.tsx index 33e7748..b5c1251 100644 --- a/app/src/components/EspSidebar.tsx +++ b/app/src/components/EspSidebar.tsx @@ -33,6 +33,7 @@ import { } from "../lib/config"; import { saveStoredDeviceSetupInput } from "../lib/deviceSetupStorage"; import { + findUnresolvedVarRefs, readGlobalVars, resolveGlobalVarsInConfig, } from "../lib/globalVarsStorage"; @@ -154,6 +155,14 @@ export function EspSidebar({ try { const globalVars = readGlobalVars(); + const missingVars = new Set( + cells.flatMap((cell) => findUnresolvedVarRefs(cell.config, globalVars)), + ); + if (missingVars.size > 0) { + throw new Error( + `Undefined variable(s): ${[...missingVars].join(", ")}. Define them in Variables or pick another value.`, + ); + } const resolvedCells = cells.map((cell) => ({ ...cell, config: resolveGlobalVarsInConfig(cell.config, globalVars), diff --git a/app/src/components/Flash.tsx b/app/src/components/Flash.tsx deleted file mode 100644 index 98db183..0000000 --- a/app/src/components/Flash.tsx +++ /dev/null @@ -1,55 +0,0 @@ -import type { DetailedHTMLProps, HTMLAttributes } from "react"; - -import "esp-web-tools"; - -declare module "react" { - namespace JSX { - interface IntrinsicElements { - "esp-web-install-button": DetailedHTMLProps< - HTMLAttributes, - HTMLElement - > & { - manifest: string; - }; - } - } -} - -const manifest = "/firmware/manifest.json"; - -export function Flash() { - const hasSerial = "serial" in navigator; - const secure = window.isSecureContext; - const canInstall = secure && hasSerial; - - return ( -
-

1. Flash Budpy to ESP32 CYD

-

- Plug the ESP32 in over USB, start the installation, then select the CYD - serial port. It works only on Chrome and Edge because of the Web Serial - API, and requires HTTPS or localhost to work. -

- - {!secure && ( -

- Web Serial requires HTTPS or localhost. -

- )} - - {secure && !hasSerial && ( -

- Use Chrome or Edge to access the serial port from the browser. -

- )} - - {canInstall && ( - - - - )} -
- ); -} diff --git a/app/src/components/Layout.tsx b/app/src/components/Layout.tsx index ab0f3d1..01461d8 100644 --- a/app/src/components/Layout.tsx +++ b/app/src/components/Layout.tsx @@ -524,6 +524,7 @@ export function Layout({ ref={aboutDialogRef} className={`modal-dialog ${styles["about-dialog"]}`} aria-labelledby="about-dialog-title" + onClose={() => setIsAboutOpen(false)} onClick={(e) => { if (e.target === aboutDialogRef.current) setIsAboutOpen(false); }} diff --git a/app/src/components/Setup.module.css b/app/src/components/Setup.module.css deleted file mode 100644 index a8b49a8..0000000 --- a/app/src/components/Setup.module.css +++ /dev/null @@ -1,9 +0,0 @@ -.form-row { - display: flex; - gap: 1rem; - margin-bottom: 1rem; -} - -.form-row :global(.form-field) { - width: 50%; -} diff --git a/app/src/components/Setup.tsx b/app/src/components/Setup.tsx deleted file mode 100644 index 78cae4f..0000000 --- a/app/src/components/Setup.tsx +++ /dev/null @@ -1,192 +0,0 @@ -import { useState } from "react"; -import { buildBudpyConfig, type Orientation } from "../lib/config"; -import { saveStoredDeviceSetupInput } from "../lib/deviceSetupStorage"; -import { - readGlobalVars, - resolveGlobalVarsInConfig, -} from "../lib/globalVarsStorage"; -import { sendConfigOverSerial } from "../lib/serial"; -import type { DeviceSetupInput } from "../models/DeviceSetupInput"; -import type { LayoutCell } from "../models/LayoutCell"; -import styles from "./Setup.module.css"; - -type ProvisioningStatus = - | { tone: "idle"; message: string } - | { tone: "success"; message: string } - | { tone: "error"; message: string } - | { tone: "working"; message: string }; - -interface SetupPageProps { - orientation: Orientation; - cells: LayoutCell[]; - input: DeviceSetupInput; - onInputChange: (key: keyof DeviceSetupInput, value: string) => void; -} - -const orientationLabels: Record = { - "0": "0 deg - portrait", - "90": "90 deg - landscape", - "180": "180 deg - inverted portrait", - "270": "270 deg - inverted landscape", -}; - -function getErrorMessage(error: unknown): string { - if (error instanceof Error) { - return error.message; - } - - return "Unknown error during provisioning."; -} - -export function Setup({ - orientation, - cells, - input, - onInputChange, -}: SetupPageProps) { - const [saveStatus, setSaveStatus] = useState({ - tone: "idle", - message: "Local WiFi configuration ready to save.", - }); - const [sendStatus, setSendStatus] = useState({ - tone: "idle", - message: "Ready to send the layout and configuration to the ESP32.", - }); - const setupIsComplete = - input.ssid.trim().length > 0 && input.password.length >= 8; - - function updateInput(key: keyof DeviceSetupInput, value: string) { - onInputChange(key, value); - setSaveStatus({ - tone: "idle", - message: "Local changes to save.", - }); - } - - function saveSetup() { - saveStoredDeviceSetupInput(input); - setSaveStatus({ - tone: "success", - message: "WiFi configuration saved in this browser.", - }); - } - - async function send() { - setSendStatus({ tone: "working", message: "Sending configuration..." }); - - try { - const globalVars = readGlobalVars(); - const resolvedCells = cells.map((cell) => ({ - ...cell, - config: resolveGlobalVarsInConfig(cell.config, globalVars), - })); - const config = buildBudpyConfig({ - ...input, - orientation, - cells: resolvedCells, - }); - const response = await sendConfigOverSerial(config); - setSendStatus({ - tone: "success", - message: response || "Configuration received by the ESP32.", - }); - } catch (error) { - setSendStatus({ tone: "error", message: getErrorMessage(error) }); - } - } - - return ( - <> -
-

3. Configuration

-

- WiFi credentials are stored locally in this browser. -

- -
{ - event.preventDefault(); - saveSetup(); - }} - > -
- - - -
- -
- -
-
- - {saveStatus.tone !== "idle" && ( -

- {saveStatus.message} -

- )} -
- -
-

4. Summary

-

- If everything looks correct, send the configuration and layout to the - ESP32. -

- -
- -
- -

- {setupIsComplete - ? sendStatus.message - : "Enter an SSID and a password of at least 8 characters."} -

-
- - ); -} diff --git a/app/src/components/layout/LayoutPluginPalette.module.css b/app/src/components/layout/LayoutPluginPalette.module.css deleted file mode 100644 index e23006d..0000000 --- a/app/src/components/layout/LayoutPluginPalette.module.css +++ /dev/null @@ -1,46 +0,0 @@ -.plugin-palette { - display: grid; - gap: 1rem; - min-width: 0; - padding-top: 1rem; -} - -.plugin-list { - list-style: none; - padding: 0; - margin: 0; - display: grid; - gap: 0.75rem; -} - -.plugin-list-item { - display: grid; - grid-template-columns: minmax(0, 1fr) auto; - gap: 0.75rem; - align-items: start; - border-top: 1px solid var(--line); - padding-top: 0.75rem; -} - -.plugin-list-item strong { - font-size: 0.875rem; - color: var(--foreground); - display: block; -} - -.plugin-list-item p { - font-size: 0.72rem; - color: var(--muted); - line-height: 1.4; - margin: 0; -} - -.plugin-list-item span { - font-size: 0.68rem; - color: var(--faint); -} - -.plugin-actions { - display: grid; - gap: 0.4rem; -} diff --git a/app/src/components/layout/LayoutPluginPalette.tsx b/app/src/components/layout/LayoutPluginPalette.tsx deleted file mode 100644 index 4f34e51..0000000 --- a/app/src/components/layout/LayoutPluginPalette.tsx +++ /dev/null @@ -1,56 +0,0 @@ -import type { PluginManifest } from "@budpy/plugin-sdk"; -import { Plus } from "lucide-react"; -import type { DragEvent } from "react"; - -import styles from "./LayoutPluginPalette.module.css"; - -interface LayoutPluginPaletteProps { - plugins: readonly PluginManifest[]; - canAddPlugin: (plugin: PluginManifest) => boolean; - onAddPlugin: (plugin: PluginManifest) => void; - onPluginDragStart: (event: DragEvent, pluginId: string) => void; -} - -export function LayoutPluginPalette({ - plugins, - canAddPlugin, - onAddPlugin, - onPluginDragStart, -}: LayoutPluginPaletteProps) { - return ( - - ); -} diff --git a/app/src/lib/config.test.ts b/app/src/lib/config.test.ts index 9adcf0a..911432f 100644 --- a/app/src/lib/config.test.ts +++ b/app/src/lib/config.test.ts @@ -7,6 +7,7 @@ import { createBudpyConfigInputFromConfig, createDefaultCell, getPluginManifest, + getPosixTimezone, type Orientation, } from "./config"; @@ -471,3 +472,57 @@ describe("createBudpyConfigInputFromConfig", () => { expect(input.screenIdleUnit).toBe("hours"); }); }); + +describe("getPosixTimezone", () => { + const reference = new Date("2026-10-22T12:00:00Z"); + + it("encodes the DST rules of zones missing from the firmware table", () => { + expect(getPosixTimezone("Europe/Berlin", reference)).toBe( + "STD-1DST-2,M3.5.0/2,M10.5.0/3", + ); + expect(getPosixTimezone("America/Chicago", reference)).toBe( + "STD6DST5,M3.2.0/2,M11.1.0/2", + ); + expect(getPosixTimezone("Australia/Lord_Howe", reference)).toBe( + "STD-10:30DST-11,M10.1.0/2,M4.1.0/2", + ); + }); + + it("encodes fixed-offset zones", () => { + expect(getPosixTimezone("Asia/Kolkata", reference)).toBe("STD-5:30"); + expect(getPosixTimezone("UTC", reference)).toBe("STD0"); + }); + + it("returns null for unknown zones", () => { + expect(getPosixTimezone("Not/AZone", reference)).toBeNull(); + }); + + it("sends the POSIX rule with clock cells and drops stale values", () => { + const clockManifest = getPluginManifest("clock"); + + if (!clockManifest) { + throw new Error("Clock manifest not found"); + } + + const cell = createDefaultCell(clockManifest, "0", "clock-berlin"); + cell.config.timezone = "Europe/Berlin"; + cell.config.timezonePosix = "STD0"; + const invalidCell = createDefaultCell(clockManifest, "0", "clock-bad"); + invalidCell.config.timezone = "Not/AZone"; + invalidCell.config.timezonePosix = "STD0"; + + const config = buildBudpyConfig({ + ssid: "Home", + password: "secret-password", + orientation: "0", + cells: [cell, { ...invalidCell, row: 2 }], + }); + + expect(config.layout.cells[0]?.config.timezonePosix).toBe( + "STD-1DST-2,M3.5.0/2,M10.5.0/3", + ); + expect(config.layout.cells[1]?.config).not.toHaveProperty( + "timezonePosix", + ); + }); +}); diff --git a/app/src/lib/config.ts b/app/src/lib/config.ts index 8c604af..957ba7b 100644 --- a/app/src/lib/config.ts +++ b/app/src/lib/config.ts @@ -18,10 +18,9 @@ export const orientations = [ "270", ] as const satisfies readonly Orientation[]; -export function getTimezoneOffsetMinutes( - timezone: string, - date = new Date(), -): number { +type UtcOffsetReader = (date: Date) => number; + +function createUtcOffsetReader(timezone: string): UtcOffsetReader | null { try { const formatter = new Intl.DateTimeFormat("en-US", { timeZone: timezone, @@ -33,23 +32,229 @@ export function getTimezoneOffsetMinutes( second: "2-digit", hourCycle: "h23", }); - const parts = formatter.formatToParts(date); - const values = Object.fromEntries( - parts.map((part) => [part.type, part.value]), - ); - const zonedTime = Date.UTC( - Number(values.year), - Number(values.month) - 1, - Number(values.day), - Number(values.hour), - Number(values.minute), - Number(values.second), - ); - return Math.round((zonedTime - date.getTime()) / 60000) || 0; + return (date) => { + const parts = formatter.formatToParts(date); + const values = Object.fromEntries( + parts.map((part) => [part.type, part.value]), + ); + const zonedTime = Date.UTC( + Number(values.year), + Number(values.month) - 1, + Number(values.day), + Number(values.hour), + Number(values.minute), + Number(values.second), + ); + + return Math.round((zonedTime - date.getTime()) / 60000) || 0; + }; } catch (_error) { - return 0; + return null; + } +} + +export function getTimezoneOffsetMinutes( + timezone: string, + date = new Date(), +): number { + return createUtcOffsetReader(timezone)?.(date) ?? 0; +} + +const minuteMs = 60_000; +const dayMs = 24 * 60 * minuteMs; +const posixRuleCheckYears = 8; + +interface OffsetTransition { + at: number; + before: number; + after: number; +} + +interface PosixTransitionRule { + month: number; + week: number; + weekday: number; + minutes: number; +} + +function findOffsetTransitions( + readOffset: UtcOffsetReader, + year: number, +): OffsetTransition[] { + const transitions: OffsetTransition[] = []; + const end = Date.UTC(year + 1, 0, 1); + let previousTime = Date.UTC(year, 0, 1); + let previousOffset = readOffset(new Date(previousTime)); + + for (let time = previousTime + dayMs; time <= end; time += dayMs) { + const offset = readOffset(new Date(time)); + + if (offset !== previousOffset) { + // Narrow the change down to the minute it happens. + let low = previousTime; + let high = time; + while (high - low > minuteMs) { + const middle = + low + Math.floor((high - low) / 2 / minuteMs) * minuteMs; + if (readOffset(new Date(middle)) === previousOffset) { + low = middle; + } else { + high = middle; + } + } + + transitions.push({ at: high, before: previousOffset, after: offset }); + } + + previousTime = time; + previousOffset = offset; + } + + return transitions; +} + +function getDaysInMonth(year: number, month: number): number { + return new Date(Date.UTC(year, month, 0)).getUTCDate(); +} + +function getRuleInstant( + rule: PosixTransitionRule, + year: number, + offsetBefore: number, +): number { + const firstWeekday = new Date(Date.UTC(year, rule.month - 1, 1)).getUTCDay(); + const daysInMonth = getDaysInMonth(year, rule.month); + let day = 1 + ((rule.weekday - firstWeekday + 7) % 7) + (rule.week - 1) * 7; + while (day > daysInMonth) { + day -= 7; + } + + return ( + Date.UTC(year, rule.month - 1, day) + + (rule.minutes - offsetBefore) * minuteMs + ); +} + +// POSIX rules are expressed in the wall-clock time in effect before the +// change. A day in the last week of the month may mean "last" or "nth", so +// keep the candidate that predicts the next years' transitions. +function findTransitionRule( + readOffset: UtcOffsetReader, + transition: OffsetTransition, + year: number, +): PosixTransitionRule | null { + const local = new Date(transition.at + transition.before * minuteMs); + const month = local.getUTCMonth() + 1; + const day = local.getUTCDate(); + const weeks = [Math.ceil(day / 7)]; + if (day + 7 > getDaysInMonth(local.getUTCFullYear(), month)) { + weeks.unshift(5); } + + for (const week of weeks) { + const rule = { + month, + week, + weekday: local.getUTCDay(), + minutes: local.getUTCHours() * 60 + local.getUTCMinutes(), + }; + const matchesNextYears = Array.from( + { length: posixRuleCheckYears }, + (_, index) => year + index + 1, + ).every((checkYear) => { + const at = getRuleInstant(rule, checkYear, transition.before); + + return ( + readOffset(new Date(at - minuteMs)) === transition.before && + readOffset(new Date(at)) === transition.after + ); + }); + + if (matchesNextYears) { + return rule; + } + } + + return null; +} + +function formatPosixClock(totalMinutes: number): string { + const hours = Math.floor(totalMinutes / 60); + const minutes = totalMinutes % 60; + + return minutes > 0 + ? `${hours}:${String(minutes).padStart(2, "0")}` + : String(hours); +} + +function formatPosixOffset(offsetMinutes: number): string { + // POSIX counts offsets westward: UTC+2 is written "-2". + return `${offsetMinutes > 0 ? "-" : ""}${formatPosixClock(Math.abs(offsetMinutes))}`; +} + +function formatPosixRule(rule: PosixTransitionRule): string { + return `M${rule.month}.${rule.week}.${rule.weekday}/${formatPosixClock(rule.minutes)}`; +} + +/** + * Builds a POSIX TZ string (e.g. `STD-1DST-2,M3.5.0/2,M10.5.0/3`) so the + * firmware can follow DST for zones missing from its built-in table. Returns + * `null` when the zone's rules cannot be expressed that way. + */ +export function getPosixTimezone( + timezone: string, + date = new Date(), +): string | null { + const readOffset = createUtcOffsetReader(timezone); + if (!readOffset) { + return null; + } + + const year = date.getUTCFullYear(); + const transitions = findOffsetTransitions(readOffset, year); + if (transitions.length === 0) { + return `STD${formatPosixOffset(readOffset(date))}`; + } + + const start = transitions.find((item) => item.after > item.before); + const end = transitions.find((item) => item.after < item.before); + if ( + transitions.length !== 2 || + !start || + !end || + start.before !== end.after || + start.after !== end.before + ) { + return null; + } + + const startRule = findTransitionRule(readOffset, start, year); + const endRule = findTransitionRule(readOffset, end, year); + if (!startRule || !endRule) { + return null; + } + + return `STD${formatPosixOffset(start.before)}DST${formatPosixOffset( + start.after, + )},${formatPosixRule(startRule)},${formatPosixRule(endRule)}`; +} + +function withTimezoneFallbacks( + config: Record, +): Record { + if (typeof config.timezone !== "string") { + return config; + } + + const { timezonePosix: _previousPosix, ...rest } = config; + const timezonePosix = getPosixTimezone(config.timezone); + + return { + ...rest, + timezoneOffsetMinutes: getTimezoneOffsetMinutes(config.timezone), + ...(timezonePosix ? { timezonePosix } : {}), + }; } export const maxLayoutCells = 48; @@ -414,12 +619,7 @@ export function buildBudpyConfig(input: BudpyConfigInput): BudpyConfig { row, colSpan, rowSpan, - config: { - ...config, - ...(typeof config.timezone === "string" - ? { timezoneOffsetMinutes: getTimezoneOffsetMinutes(config.timezone) } - : {}), - }, + config: withTimezoneFallbacks(config), }), ); diff --git a/app/src/lib/deviceSetupStorage.ts b/app/src/lib/deviceSetupStorage.ts index 06b2987..c600abd 100644 --- a/app/src/lib/deviceSetupStorage.ts +++ b/app/src/lib/deviceSetupStorage.ts @@ -50,7 +50,12 @@ function getLocalStorage(): KeyValueStorage | null { return null; } - return window.localStorage; + // Accessing localStorage throws when the browser blocks site storage. + try { + return window.localStorage; + } catch (_error) { + return null; + } } function isRecord(value: unknown): value is Record { diff --git a/app/src/lib/globalVarsStorage.test.ts b/app/src/lib/globalVarsStorage.test.ts new file mode 100644 index 0000000..8a71e03 --- /dev/null +++ b/app/src/lib/globalVarsStorage.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from "vitest"; + +import { + findUnresolvedVarRefs, + resolveGlobalVarsInConfig, +} from "./globalVarsStorage"; + +const vars = [{ key: "ha_token", value: "secret" }]; + +describe("global variables", () => { + it("resolves known references and keeps other values", () => { + expect( + resolveGlobalVarsInConfig( + { haToken: "$var:ha_token", title: "Salon", offsetX: 4 }, + vars, + ), + ).toEqual({ haToken: "secret", title: "Salon", offsetX: 4 }); + }); + + it("lists references to variables that do not exist", () => { + expect( + findUnresolvedVarRefs( + { haToken: "$var:ha_token", haUrl: "$var:ha_url", title: "Salon" }, + vars, + ), + ).toEqual(["ha_url"]); + }); +}); diff --git a/app/src/lib/globalVarsStorage.ts b/app/src/lib/globalVarsStorage.ts index f7d6e4a..633356c 100644 --- a/app/src/lib/globalVarsStorage.ts +++ b/app/src/lib/globalVarsStorage.ts @@ -99,6 +99,23 @@ export function resolveVarRef( return vars.find((v) => v.key === key)?.value ?? null; } +/** + * Lists the variable keys referenced in a cell config that have no stored + * value. Such references would otherwise reach the device as literal + * `$var:KEY` strings. + */ +export function findUnresolvedVarRefs( + config: Record, + vars: GlobalVar[], +): string[] { + return Object.values(config) + .map(parseVarRef) + .filter( + (key): key is string => + key !== null && !vars.some((v) => v.key === key), + ); +} + /** * Resolves all variable references in a cell config object. * Values that are not references are left unchanged. diff --git a/app/src/lib/layoutStorage.ts b/app/src/lib/layoutStorage.ts index ff1dbd4..94e4ae2 100644 --- a/app/src/lib/layoutStorage.ts +++ b/app/src/lib/layoutStorage.ts @@ -36,7 +36,12 @@ function getLocalStorage(): KeyValueStorage | null { return null; } - return window.localStorage; + // Accessing localStorage throws when the browser blocks site storage. + try { + return window.localStorage; + } catch (_error) { + return null; + } } function isRecord(value: unknown): value is Record { diff --git a/app/src/lib/serial.test.ts b/app/src/lib/serial.test.ts index 811999f..c9679b3 100644 --- a/app/src/lib/serial.test.ts +++ b/app/src/lib/serial.test.ts @@ -3,8 +3,24 @@ import { describe, expect, it } from "vitest"; import { parseDeviceConfigResponse, parseDeviceResponse, + readResponseLine, } from "./serial"; +function streamReader(chunks: string[], close = true) { + const encoder = new TextEncoder(); + + return new ReadableStream({ + start(controller) { + for (const chunk of chunks) { + controller.enqueue(encoder.encode(chunk)); + } + if (close) { + controller.close(); + } + }, + }).getReader(); +} + describe("parseDeviceResponse", () => { it("returns the success message from an ok response", () => { expect(parseDeviceResponse('{"ok":true,"message":"Config saved"}')).toBe( @@ -34,7 +50,7 @@ describe("parseDeviceResponse", () => { '{"ok":false,"error":"Unsupported display.timezone: America/New_York"}', ), ).toThrow( - "Unsupported display.timezone: America/New_York. Reflash the firmware from the Flash tab to use the new time zones.", + "Unsupported display.timezone: America/New_York. Reflash the firmware from the Flash firmware section to use the new time zones.", ); }); @@ -97,3 +113,25 @@ describe("parseDeviceConfigResponse", () => { ).toThrow("Device returned an invalid configuration."); }); }); + +describe("readResponseLine", () => { + it("returns the first non-empty line split across chunks", async () => { + await expect( + readResponseLine( + streamReader(["\r\n", '{"ok":tr', 'ue}\n{"ok":false}\n']), + ), + ).resolves.toBe('{"ok":true}'); + }); + + it("rejects when the device closes the stream without a line", async () => { + await expect(readResponseLine(streamReader(["partial"]))).rejects.toThrow( + "Device did not acknowledge configuration.", + ); + }); + + it("rejects when the device does not answer in time", async () => { + await expect(readResponseLine(streamReader([], false), 10)).rejects.toThrow( + "The ESP32 did not answer in time.", + ); + }); +}); diff --git a/app/src/lib/serial.ts b/app/src/lib/serial.ts index a38a59a..5fea02d 100644 --- a/app/src/lib/serial.ts +++ b/app/src/lib/serial.ts @@ -41,7 +41,7 @@ function getDeviceErrorMessage(error: unknown): string { } if (/^Unsupported [a-z][a-z0-9-]*\.timezone/.test(message)) { - return `${message}. Reflash the firmware from the Flash tab to use the new time zones.`; + return `${message}. Reflash the firmware from the Flash firmware section to use the new time zones.`; } return message; @@ -123,33 +123,67 @@ async function exchangeSerialCommand(command: unknown): Promise { const reader = port.readable.getReader(); try { - const decoder = new TextDecoder(); - let response = ""; + return await readResponseLine(reader); + } finally { + reader.releaseLock(); + } + } finally { + await port.close().catch(() => undefined); + } +} - while (true) { - const { value, done } = await reader.read(); +export const deviceResponseTimeoutMs = 30_000; - if (done) { - break; - } +/** + * Reads the first non-empty line sent by the device. Gives up after + * `timeoutMs` so an unresponsive board cannot leave the UI (and the port) + * stuck forever. + */ +export async function readResponseLine( + reader: ReadableStreamDefaultReader, + timeoutMs = deviceResponseTimeoutMs, +): Promise { + let timedOut = false; + const timeout = setTimeout(() => { + timedOut = true; + reader.cancel().catch(() => undefined); + }, timeoutMs); + + try { + const decoder = new TextDecoder(); + let response = ""; - if (value) { - response += decoder.decode(value, { stream: true }); - const newlineIndex = response.indexOf("\n"); + while (true) { + const { value, done } = await reader.read(); - if (newlineIndex >= 0) { - return response.slice(0, newlineIndex).trim(); + if (done) { + break; + } + + if (value) { + response += decoder.decode(value, { stream: true }); + let newlineIndex = response.indexOf("\n"); + + while (newlineIndex >= 0) { + const line = response.slice(0, newlineIndex).trim(); + if (line.length > 0) { + return line; } + + response = response.slice(newlineIndex + 1); + newlineIndex = response.indexOf("\n"); } } - } finally { - reader.releaseLock(); } - - throw new Error("Device did not acknowledge configuration."); } finally { - await port.close().catch(() => undefined); + clearTimeout(timeout); } + + throw new Error( + timedOut + ? "The ESP32 did not answer in time. Check the USB connection and that the Budpy firmware is flashed, then try again." + : "Device did not acknowledge configuration.", + ); } export async function sendConfigOverSerial( diff --git a/app/tsconfig.tsbuildinfo b/app/tsconfig.tsbuildinfo deleted file mode 100644 index ede3bed..0000000 --- a/app/tsconfig.tsbuildinfo +++ /dev/null @@ -1 +0,0 @@ -{"root":["./src/app.tsx","./src/main.tsx","./src/components/espsidebar.tsx","./src/components/flash.tsx","./src/components/globalvarsdialog.tsx","./src/components/layout.tsx","./src/components/setup.tsx","./src/components/layout/layoutcustomizationpanel.tsx","./src/components/layout/layoutpluginpalette.tsx","./src/components/layout/layoutpreview.tsx","./src/components/layout/layoutcells.test.ts","./src/components/layout/layoutcells.ts","./src/components/layout/layoutdrag.ts","./src/components/layout/layoutmessages.ts","./src/lib/config.test.ts","./src/lib/config.ts","./src/lib/devicesetupstorage.test.ts","./src/lib/devicesetupstorage.ts","./src/lib/globalvarsstorage.ts","./src/lib/imagefield.test.ts","./src/lib/imagefield.ts","./src/lib/layoutstorage.test.ts","./src/lib/layoutstorage.ts","./src/lib/serial.test.ts","./src/lib/serial.ts","./src/models/budpyconfiginput.ts","./src/models/devicesetupinput.ts","./src/models/layoutcell.ts","./src/models/layoutdraft.ts","./vite.config.ts"],"version":"5.9.3"} \ No newline at end of file diff --git a/firmware/include/AppConfig.h b/firmware/include/AppConfig.h index f164386..18702ba 100644 --- a/firmware/include/AppConfig.h +++ b/firmware/include/AppConfig.h @@ -6,6 +6,7 @@ struct ClockPluginConfig { String timezone = "Europe/Paris"; bool hasTimezoneOffsetMinutes = false; int16_t timezoneOffsetMinutes = 0; + String timezonePosix = ""; String locale = "fr-FR"; String hourCycle = "h23"; String dateTimeOrder = "time-date"; diff --git a/firmware/include/AppConfigParser.h b/firmware/include/AppConfigParser.h index 4505b0c..d27f758 100644 --- a/firmware/include/AppConfigParser.h +++ b/firmware/include/AppConfigParser.h @@ -4,4 +4,8 @@ #include -bool parseAppConfig(const JsonDocument& doc, AppConfig& out, String& error); \ No newline at end of file +bool parseAppConfig(JsonVariantConst config, AppConfig& out, String& error); + +// Releases everything a parsed config holds (cell configs can carry large +// image payloads) by restoring the defaults. +void resetAppConfig(AppConfig& config); diff --git a/firmware/include/ConfigStore.h b/firmware/include/ConfigStore.h index cfc4d35..6037b64 100644 --- a/firmware/include/ConfigStore.h +++ b/firmware/include/ConfigStore.h @@ -2,7 +2,12 @@ #include "AppConfig.h" +#include + bool configStoreBegin(); bool loadAppConfig(AppConfig& config, String& error); -bool loadAppConfigJson(String& json, String& error); -bool saveAppConfigJson(const String& json, String& error); \ No newline at end of file +// Checks that the stored config is still valid for this firmware. +bool checkStoredAppConfig(String& error); +// Streams the stored config JSON as-is, without building a copy in RAM. +bool writeStoredAppConfigJson(Print& out, String& error); +bool saveAppConfig(JsonVariantConst config, String& error); diff --git a/firmware/include/TimeService.h b/firmware/include/TimeService.h index d4339a8..91d29b2 100644 --- a/firmware/include/TimeService.h +++ b/firmware/include/TimeService.h @@ -5,8 +5,14 @@ #include bool connectWifiAndSyncTime(const AppConfig& config, String& error); +// Non-blocking follow-up after connectWifiAndSyncTime() failed: periodically +// retries WiFi, starts SNTP once connected, and returns true when the clock is +// set. +bool pollWifiAndTimeRecovery(const AppConfig& config); bool getLocalTimeParts(struct tm& timeInfo); bool isNativelySupportedTimezone(const String& timezone); bool getTimePartsForTimezone(const String& timezone, struct tm& timeInfo); +bool getTimePartsForPosixTimezone(const String& posixTimezone, + struct tm& timeInfo); bool getTimePartsForUtcOffsetMinutes(int16_t offsetMinutes, struct tm& timeInfo); \ No newline at end of file diff --git a/firmware/src/AppConfig.cpp b/firmware/src/AppConfig.cpp index 5606cfe..af58f5f 100644 --- a/firmware/src/AppConfig.cpp +++ b/firmware/src/AppConfig.cpp @@ -334,14 +334,15 @@ bool readObject(JsonObjectConst parent, const char* key, JsonObjectConst& value, return true; } +} // namespace + void resetAppConfig(AppConfig& config) { config.~AppConfig(); new (&config) AppConfig(); } -} // namespace -bool parseAppConfig(const JsonDocument& doc, AppConfig& out, String& error) { - JsonObjectConst root = doc.as(); +bool parseAppConfig(JsonVariantConst config, AppConfig& out, String& error) { + JsonObjectConst root = config.as(); if (root.isNull()) { return fail(error, "Config root must be an object"); } @@ -592,6 +593,14 @@ bool parseAppConfig(const JsonDocument& doc, AppConfig& out, String& error) { parsedCell.clock.timezoneOffsetMinutes = static_cast(timezoneOffsetMinutes); } + if (!readOptionalText(clock, "timezonePosix", "", + parsedCell.clock.timezonePosix, error, + "clock.timezonePosix")) { + return false; + } + if (parsedCell.clock.timezonePosix.length() > 64) { + return fail(error, "Invalid clock.timezonePosix length"); + } if (!readOptionalString(clock, "locale", parsed.locale, parsedCell.clock.locale, error, "clock.locale")) { diff --git a/firmware/src/ConfigStore.cpp b/firmware/src/ConfigStore.cpp index 488923d..4d9e814 100644 --- a/firmware/src/ConfigStore.cpp +++ b/firmware/src/ConfigStore.cpp @@ -7,6 +7,16 @@ static const char* CONFIG_PATH = "/budpy-config.json"; static AppConfig validationConfig; +namespace { +bool validateAppConfig(JsonVariantConst config, String& error) { + const bool valid = parseAppConfig(config, validationConfig, error); + // Only the verdict matters: do not keep a second copy of every cell config + // alive after validation. + resetAppConfig(validationConfig); + return valid; +} +} // namespace + bool configStoreBegin() { return LittleFS.begin(true); } @@ -26,38 +36,52 @@ bool loadAppConfig(AppConfig& config, String& error) { return false; } - return parseAppConfig(doc, config, error); + return parseAppConfig(doc.as(), config, error); } -bool loadAppConfigJson(String& json, String& error) { +bool checkStoredAppConfig(String& error) { File file = LittleFS.open(CONFIG_PATH, "r"); if (!file) { error = "No valid configuration"; return false; } - json = file.readString(); - file.close(); - JsonDocument doc; - DeserializationError parseError = deserializeJson(doc, json); + DeserializationError parseError = deserializeJson(doc, file); + file.close(); if (parseError) { error = parseError.c_str(); return false; } - return parseAppConfig(doc, validationConfig, error); + return validateAppConfig(doc.as(), error); } -bool saveAppConfigJson(const String& json, String& error) { - JsonDocument doc; - DeserializationError parseError = deserializeJson(doc, json); - if (parseError) { - error = parseError.c_str(); +bool writeStoredAppConfigJson(Print& out, String& error) { + File file = LittleFS.open(CONFIG_PATH, "r"); + if (!file) { + error = "No valid configuration"; return false; } - if (!parseAppConfig(doc, validationConfig, error)) { + while (file.available()) { + const int value = file.read(); + if (value < 0) { + break; + } + + // The serial protocol is line based: never forward a raw line break. + if (value != '\n' && value != '\r') { + out.write(static_cast(value)); + } + } + + file.close(); + return true; +} + +bool saveAppConfig(JsonVariantConst config, String& error) { + if (!validateAppConfig(config, error)) { return false; } @@ -67,13 +91,14 @@ bool saveAppConfigJson(const String& json, String& error) { return false; } - const size_t bytesWritten = file.print(json); + const size_t expectedBytes = measureJson(config); + const size_t bytesWritten = serializeJson(config, file); file.close(); - if (bytesWritten != json.length()) { + if (bytesWritten != expectedBytes) { error = "Could not write complete config"; return false; } error = ""; return true; -} \ No newline at end of file +} diff --git a/firmware/src/PluginRegistry.cpp b/firmware/src/PluginRegistry.cpp index 41817c8..7def235 100644 --- a/firmware/src/PluginRegistry.cpp +++ b/firmware/src/PluginRegistry.cpp @@ -88,6 +88,32 @@ bool normalizeCurrentPage(const AppConfig& config) { return true; } +// Named timezones from the built-in table keep their DST rules. Other clock +// timezones use the POSIX rule computed by the web app, then the fixed UTC +// offset it captured when the config was sent (older web app versions). +bool readCellTime(const AppConfig& config, const LayoutCellConfig& cell, + struct tm& timeInfo) { + if (cell.pluginId != "clock") { + return getTimePartsForTimezone(config.timezone, timeInfo); + } + + const ClockPluginConfig& clock = cell.clock; + if (isNativelySupportedTimezone(clock.timezone)) { + return getTimePartsForTimezone(clock.timezone, timeInfo); + } + + if (clock.timezonePosix.length() > 0) { + return getTimePartsForPosixTimezone(clock.timezonePosix, timeInfo); + } + + if (clock.hasTimezoneOffsetMinutes) { + return getTimePartsForUtcOffsetMinutes(clock.timezoneOffsetMinutes, + timeInfo); + } + + return getTimePartsForTimezone(clock.timezone, timeInfo); +} + void showNextPageForConfig(const AppConfig& config) { const uint8_t pageCount = pageCountForConfig(config); currentPage = static_cast((currentPage + 1) % pageCount); @@ -144,21 +170,7 @@ void renderPlugins(Renderer& renderer, const AppConfig& config, } struct tm cellTimeInfo; - // Named timezones keep DST rules, so only fall back to the fixed UTC - // offset captured by the web app when the timezone is not known natively. - const bool useUtcOffset = cell.pluginId == "clock" && - cell.clock.hasTimezoneOffsetMinutes && - !isNativelySupportedTimezone(cell.clock.timezone); - const bool hasCellTime = - useUtcOffset - ? getTimePartsForUtcOffsetMinutes(cell.clock.timezoneOffsetMinutes, - cellTimeInfo) - : getTimePartsForTimezone(cell.pluginId == "clock" - ? cell.clock.timezone - : config.timezone, - cellTimeInfo); - - if (!hasCellTime) { + if (!readCellTime(config, cell, cellTimeInfo)) { cellTimeInfo = timeInfo; } diff --git a/firmware/src/SerialProvisioning.cpp b/firmware/src/SerialProvisioning.cpp index c8f32e1..b57c00b 100644 --- a/firmware/src/SerialProvisioning.cpp +++ b/firmware/src/SerialProvisioning.cpp @@ -14,6 +14,20 @@ String readLine() { return Serial.readStringUntil('\n'); } +// Parses the next command line into doc. The raw line is released on return, +// so only the parsed copy stays alive while the command runs (configs with +// images are tens of KB). +bool readCommand(JsonDocument& doc, DeserializationError& parseError) { + String line = readLine(); + line.trim(); + if (line.isEmpty()) { + return false; + } + + parseError = deserializeJson(doc, line); + return true; +} + void writeErrorResponse(const String& error) { JsonDocument response; response["ok"] = false; @@ -30,20 +44,17 @@ void writeSuccessResponse() { Serial.println(); } -void writeConfigResponse(const String& configJson) { - JsonDocument configDoc; - DeserializationError parseError = deserializeJson(configDoc, configJson); - if (parseError) { - writeErrorResponse(parseError.c_str()); +void writeConfigResponse() { + String error; + if (!checkStoredAppConfig(error)) { + writeErrorResponse(error); return; } - JsonDocument response; - response["ok"] = true; - response["message"] = "Config loaded"; - response["config"].set(configDoc.as()); - serializeJson(response, Serial); - Serial.println(); + // Stream the stored file into the response instead of rebuilding it in RAM. + Serial.print("{\"ok\":true,\"message\":\"Config loaded\",\"config\":"); + writeStoredAppConfigJson(Serial, error); + Serial.println("}"); } } // namespace @@ -51,14 +62,12 @@ void writeConfigResponse(const String& configJson) { bool pollSerialProvisioning(bool& configChanged) { configChanged = false; - String line = readLine(); - line.trim(); - if (line.isEmpty()) { + JsonDocument doc; + DeserializationError parseError = DeserializationError::Ok; + if (!readCommand(doc, parseError)) { return false; } - JsonDocument doc; - DeserializationError parseError = deserializeJson(doc, line); if (parseError) { writeErrorResponse(parseError.c_str()); return true; @@ -66,14 +75,7 @@ bool pollSerialProvisioning(bool& configChanged) { const char* type = doc["type"] | ""; if (std::strcmp(type, "config:get") == 0) { - String configJson; - String error; - if (!loadAppConfigJson(configJson, error)) { - writeErrorResponse(error); - return true; - } - - writeConfigResponse(configJson); + writeConfigResponse(); return true; } @@ -82,11 +84,8 @@ bool pollSerialProvisioning(bool& configChanged) { return true; } - String configJson; - serializeJson(doc["config"], configJson); - String error; - if (!saveAppConfigJson(configJson, error)) { + if (!saveAppConfig(doc["config"].as(), error)) { writeErrorResponse(error); return true; } @@ -94,4 +93,4 @@ bool pollSerialProvisioning(bool& configChanged) { configChanged = true; writeSuccessResponse(); return true; -} \ No newline at end of file +} diff --git a/firmware/src/TimeService.cpp b/firmware/src/TimeService.cpp index 7db0fd5..c7b8265 100644 --- a/firmware/src/TimeService.cpp +++ b/firmware/src/TimeService.cpp @@ -8,6 +8,11 @@ namespace { constexpr uint32_t WIFI_CONNECT_TIMEOUT_MS = 20000; constexpr uint32_t NTP_SYNC_TIMEOUT_MS = 15000; +constexpr uint32_t WIFI_RETRY_INTERVAL_MS = 30000; +constexpr time_t MIN_VALID_EPOCH = 1609459200; // 2021-01-01 + +static bool sntpConfigured = false; +static uint32_t lastWifiRetryMs = 0; // Returns the POSIX TZ string for natively supported timezones, or nullptr. const char* findPosixTimezone(const String& timezone) { @@ -48,10 +53,16 @@ const char* timezoneToPosix(const String& timezone) { return posixTimezone != nullptr ? posixTimezone : "UTC0"; } +void configureSntp(const AppConfig& config) { + configTzTime(timezoneToPosix(config.timezone), "pool.ntp.org", + "time.nist.gov"); + sntpConfigured = true; +} + bool readTimePartsForPosixTimezone(const char* posixTimezone, struct tm& timeInfo) { const time_t now = time(nullptr); - if (now < 1609459200) { + if (now < MIN_VALID_EPOCH) { return false; } @@ -76,6 +87,8 @@ bool readTimePartsForPosixTimezone(const char* posixTimezone, bool connectWifiAndSyncTime(const AppConfig& config, String& error) { error = ""; + sntpConfigured = false; + lastWifiRetryMs = millis(); WiFi.mode(WIFI_STA); WiFi.disconnect(); @@ -92,8 +105,7 @@ bool connectWifiAndSyncTime(const AppConfig& config, String& error) { return false; } - configTzTime(timezoneToPosix(config.timezone), "pool.ntp.org", - "time.nist.gov"); + configureSntp(config); struct tm timeInfo; if (!getLocalTime(&timeInfo, NTP_SYNC_TIMEOUT_MS)) { @@ -104,6 +116,25 @@ bool connectWifiAndSyncTime(const AppConfig& config, String& error) { return true; } +bool pollWifiAndTimeRecovery(const AppConfig& config) { + if (WiFi.status() != WL_CONNECTED) { + const uint32_t now = millis(); + if (now - lastWifiRetryMs >= WIFI_RETRY_INTERVAL_MS) { + lastWifiRetryMs = now; + WiFi.reconnect(); + } + return false; + } + + // SNTP keeps polling in the background once configured, so the clock gets + // set even when the first synchronization timed out. + if (!sntpConfigured) { + configureSntp(config); + } + + return time(nullptr) >= MIN_VALID_EPOCH; +} + bool getLocalTimeParts(struct tm& timeInfo) { return getLocalTime(&timeInfo, 250); } @@ -116,10 +147,15 @@ bool getTimePartsForTimezone(const String& timezone, struct tm& timeInfo) { return readTimePartsForPosixTimezone(timezoneToPosix(timezone), timeInfo); } +bool getTimePartsForPosixTimezone(const String& posixTimezone, + struct tm& timeInfo) { + return readTimePartsForPosixTimezone(posixTimezone.c_str(), timeInfo); +} + bool getTimePartsForUtcOffsetMinutes(int16_t offsetMinutes, struct tm& timeInfo) { const time_t now = time(nullptr); - if (now < 1609459200) { + if (now < MIN_VALID_EPOCH) { return false; } diff --git a/firmware/src/main.cpp b/firmware/src/main.cpp index 0965966..bd8a8ff 100644 --- a/firmware/src/main.cpp +++ b/firmware/src/main.cpp @@ -238,7 +238,9 @@ static void loadConfigOrShowStatus() { if (hasConfig) { showStatus(tft, "Budpy", "WiFi connecting...", TFT_YELLOW); if (!connectWifiAndSyncTime(appConfig, error)) { - showStatus(tft, "Budpy", error, TFT_RED); + // loop() keeps retrying in the background (e.g. the router boots slower + // than the ESP32 after a power cut). + showStatus(tft, "Budpy", error + ". Retrying...", TFT_RED); return; } @@ -281,6 +283,12 @@ void loop() { loadConfigOrShowStatus(); } + if (hasConfig && !runtimeReady && pollWifiAndTimeRecovery(appConfig)) { + runtimeReady = true; + lastRenderMs = 0; + renderDirty = true; + } + const uint32_t now = millis(); const bool touched = touchServiceTouched(); diff --git a/plugins/get-data/firmware/GetDataPlugin.cpp b/plugins/get-data/firmware/GetDataPlugin.cpp index 3253dad..deabcf2 100644 --- a/plugins/get-data/firmware/GetDataPlugin.cpp +++ b/plugins/get-data/firmware/GetDataPlugin.cpp @@ -290,13 +290,33 @@ static GetDataCache dataCache[MAX_GET_DATA_CACHE]; static GetDataRenderCache renderCacheArr[MAX_LAYOUT_CELLS]; static uint8_t dataCacheCount = 0; -GetDataCache* findOrCreateCache(const String& cacheKey) { +// The cache outlives reprovisioning: once it is full, recycle an entry that +// no get-data cell of the current config requests any more. +GetDataCache* findUnusedCache(const PluginRenderContext& context) { + for (uint8_t i = 0; i < dataCacheCount; i++) { + bool inUse = false; + for (uint8_t c = 0; c < context.config.cellCount && !inUse; c++) { + const LayoutCellConfig& cell = context.config.cells[c]; + inUse = cell.pluginId == context.cell.pluginId && + dataCache[i].cacheKey == buildUrl(readConfig(cell.configJson)); + } + if (!inUse) return &dataCache[i]; + } + return nullptr; +} + +GetDataCache* findOrCreateCache(const String& cacheKey, + const PluginRenderContext& context) { for (uint8_t i = 0; i < dataCacheCount; i++) { if (dataCache[i].cacheKey == cacheKey) return &dataCache[i]; } - if (dataCacheCount >= MAX_GET_DATA_CACHE) return nullptr; - GetDataCache& entry = dataCache[dataCacheCount++]; + GetDataCache* recycled = dataCacheCount < MAX_GET_DATA_CACHE + ? &dataCache[dataCacheCount++] + : findUnusedCache(context); + if (recycled == nullptr) return nullptr; + + GetDataCache& entry = *recycled; entry.cacheKey = cacheKey; entry.payload = ""; entry.errorCode = ""; @@ -370,6 +390,15 @@ bool fetchData(const String& url, String& outPayload, String& outError) { // e.g. "data.key" on {"data":{"key":"value"}} → "value" // --------------------------------------------------------------------------- +// Up to 4 decimals without trailing zeros: 21.5 -> "21.5", not "21.5000". +String formatDecimal(double value) { + String text(value, 4); + if (text.indexOf('.') < 0) return text; + while (text.endsWith("0")) text.remove(text.length() - 1); + if (text.endsWith(".")) text.remove(text.length() - 1); + return text; +} + String resolveJsonPath(JsonVariantConst root, const String& path) { if (path.length() == 0) return ""; @@ -402,8 +431,7 @@ String resolveJsonPath(JsonVariantConst root, const String& path) { if (current.is()) return String(current.as()); if (current.is()) return String(current.as()); if (current.is()) return String(current.as()); - if (current.is()) return String(current.as(), 4); - if (current.is()) return String(current.as(), 4); + if (current.is()) return formatDecimal(current.as()); if (current.is()) return current.as() ? "true" : "false"; return ""; } @@ -478,7 +506,7 @@ void renderGetDataPlugin(PluginRenderContext& context) { displayKey = "SETUP"; } else { const String builtUrl = buildUrl(cfg); - GetDataCache* cache = findOrCreateCache(builtUrl); + GetDataCache* cache = findOrCreateCache(builtUrl, context); if (cache == nullptr) { displayKey = "ERR cache"; diff --git a/plugins/ha-cover/firmware/HaCoverPlugin.cpp b/plugins/ha-cover/firmware/HaCoverPlugin.cpp index d7c8af4..64032dd 100644 --- a/plugins/ha-cover/firmware/HaCoverPlugin.cpp +++ b/plugins/ha-cover/firmware/HaCoverPlugin.cpp @@ -269,6 +269,7 @@ struct HaCoverRenderCache { int16_t cellLeft, cellTop, cellWidth, cellHeight; String configJson; CoverState state; + String statusKey; }; static HaCoverCache haCoverCache[MAX_HA_COVER_CACHE]; @@ -276,12 +277,31 @@ static HaCoverRenderCache haCoverRenderCache[MAX_LAYOUT_CELLS]; static uint32_t haCoverLastTouchMs[MAX_LAYOUT_CELLS] = {0}; static uint8_t haCoverCacheCount = 0; -HaCoverCache* findOrCreateCache(const String& entityId) { +// The cache outlives reprovisioning: once it is full, recycle an entry that +// no ha-cover cell of the current config shows any more. +HaCoverCache* findUnusedCache(const AppConfig& config, const String& pluginId) { + for (uint8_t i = 0; i < haCoverCacheCount; i++) { + bool inUse = false; + for (uint8_t c = 0; c < config.cellCount && !inUse; c++) { + const LayoutCellConfig& cell = config.cells[c]; + inUse = cell.pluginId == pluginId && + haCoverCache[i].entityId == readConfig(cell.configJson).entityId; + } + if (!inUse) return &haCoverCache[i]; + } + return nullptr; +} + +HaCoverCache* findOrCreateCache(const String& entityId, const AppConfig& config, + const String& pluginId) { for (uint8_t i = 0; i < haCoverCacheCount; i++) { if (haCoverCache[i].entityId == entityId) return &haCoverCache[i]; } - if (haCoverCacheCount >= MAX_HA_COVER_CACHE) return nullptr; - HaCoverCache& e = haCoverCache[haCoverCacheCount++]; + HaCoverCache* recycled = haCoverCacheCount < MAX_HA_COVER_CACHE + ? &haCoverCache[haCoverCacheCount++] + : findUnusedCache(config, pluginId); + if (recycled == nullptr) return nullptr; + HaCoverCache& e = *recycled; e.entityId = entityId; e.state = CoverState::Unknown; e.errorCode = ""; @@ -291,22 +311,31 @@ HaCoverCache* findOrCreateCache(const String& entityId) { return &e; } +// Loading and error states all render as CoverState::Unknown, so the render +// cache also keys on which of them is shown. +String coverStatusKey(const HaCoverCache* cache) { + if (cache == nullptr || !cache->initialised) return "-"; + return cache->hasError ? "ERR " + cache->errorCode : "OK"; +} + bool renderCacheMatches(const HaCoverRenderCache& c, const LayoutCellConfig& cell, CoverState state, - int16_t l, int16_t t, int16_t w, int16_t h) { - return c.rendered && c.cellLeft == l && c.cellTop == t && - c.cellWidth == w && c.cellHeight == h && - c.configJson == cell.configJson && c.state == state; + const String& statusKey, int16_t l, int16_t t, + int16_t w, int16_t h) { + return c.rendered && c.cellLeft == l && c.cellTop == t && c.cellWidth == w && + c.cellHeight == h && c.configJson == cell.configJson && + c.state == state && c.statusKey == statusKey; } void rememberRender(HaCoverRenderCache& c, const LayoutCellConfig& cell, - CoverState state, - int16_t l, int16_t t, int16_t w, int16_t h) { + CoverState state, const String& statusKey, int16_t l, + int16_t t, int16_t w, int16_t h) { c.rendered = true; c.cellLeft = l; c.cellTop = t; c.cellWidth = w; c.cellHeight = h; c.configJson = cell.configJson; c.state = state; + c.statusKey = statusKey; } // --------------------------------------------------------------------------- @@ -652,7 +681,7 @@ void renderHaCoverPlugin(PluginRenderContext& context) { const HaCoverConfig cfg = readConfig(cell.configJson); // ── Cache refresh ──────────────────────────────────────────────────── - HaCoverCache* cache = findOrCreateCache(cfg.entityId); + HaCoverCache* cache = findOrCreateCache(cfg.entityId, appCfg, cell.pluginId); const uint32_t now = millis(); if (cache != nullptr && cfg.entityId.length() > 0 && @@ -681,6 +710,7 @@ void renderHaCoverPlugin(PluginRenderContext& context) { (cache != nullptr && cache->initialised && !cache->hasError) ? cache->state : CoverState::Unknown; + const String statusKey = coverStatusKey(cache); // ── Render-cache check ─────────────────────────────────────────────── HaCoverRenderCache* renderCache = @@ -689,8 +719,8 @@ void renderHaCoverPlugin(PluginRenderContext& context) { : nullptr; if (!context.forceClear && renderCache != nullptr && - renderCacheMatches(*renderCache, cell, currentState, - cellLeft, cellTop, cellWidth, cellHeight)) { + renderCacheMatches(*renderCache, cell, currentState, statusKey, cellLeft, + cellTop, cellWidth, cellHeight)) { return; } @@ -774,8 +804,8 @@ void renderHaCoverPlugin(PluginRenderContext& context) { // ── Save render cache ───────────────────────────────────────────────── if (renderCache != nullptr) { - rememberRender(*renderCache, cell, currentState, - cellLeft, cellTop, cellWidth, cellHeight); + rememberRender(*renderCache, cell, currentState, statusKey, cellLeft, + cellTop, cellWidth, cellHeight); } } @@ -798,7 +828,8 @@ void handleTouchHaCoverPlugin(PluginTouchContext& context) { String errCode; const bool ok = toggleCover(cfg, errCode); - HaCoverCache* cache = findOrCreateCache(cfg.entityId); + HaCoverCache* cache = + findOrCreateCache(cfg.entityId, context.config, context.cell.pluginId); if (!cache) { return; } @@ -811,8 +842,9 @@ void handleTouchHaCoverPlugin(PluginTouchContext& context) { return; } + // Refetch on the re-render that follows the touch. (Resetting lastFetchMs + // alone does not make the entry stale during the first minute of uptime.) cache->hasError = false; cache->errorCode = ""; - cache->initialised = true; - cache->lastFetchMs = 0; + cache->initialised = false; } diff --git a/plugins/ha-sensor/firmware/HaSensorPlugin.cpp b/plugins/ha-sensor/firmware/HaSensorPlugin.cpp index 2a27596..83d3713 100644 --- a/plugins/ha-sensor/firmware/HaSensorPlugin.cpp +++ b/plugins/ha-sensor/firmware/HaSensorPlugin.cpp @@ -84,6 +84,22 @@ uint8_t parseFont(const char* text, uint8_t fallback) { return fallback; } +String ellipsizeToWidth(Renderer& renderer, const String& text, uint8_t font, + int16_t maxWidth) { + if (maxWidth <= 0) return ""; + if (renderer.textWidth(text, font) <= maxWidth) return text; + + const String ellipsis = "..."; + String truncated = text; + while (truncated.length() > 0) { + truncated.remove(truncated.length() - 1); + const String candidate = truncated + ellipsis; + if (renderer.textWidth(candidate, font) <= maxWidth) return candidate; + } + + return renderer.textWidth(ellipsis, font) <= maxWidth ? ellipsis : String(); +} + TextHorizontalAlign parseHAlign(const String& s) { if (s == "left") return TextHorizontalAlign::Left; if (s == "right") return TextHorizontalAlign::Right; @@ -138,9 +154,19 @@ HaSensorConfig readConfig(const String& configJson) { cfg.title = doc["title"] | ""; cfg.unit = doc["unit"] | ""; + cfg.haUrl.trim(); + cfg.haToken.trim(); + cfg.entityId.trim(); while (cfg.haUrl.endsWith("/")) { cfg.haUrl.remove(cfg.haUrl.length() - 1); } + // Users often paste URLs ending with /api (same handling as ha-cover). + if (cfg.haUrl.endsWith("/api")) { + cfg.haUrl.remove(cfg.haUrl.length() - 4); + while (cfg.haUrl.endsWith("/")) { + cfg.haUrl.remove(cfg.haUrl.length() - 1); + } + } if (doc["titleFont"].is()) cfg.titleFont = parseFont(doc["titleFont"].as(), 2); @@ -204,13 +230,34 @@ static HaCache haCache[MAX_HA_CACHE]; static HaRenderCache haRenderCache[MAX_LAYOUT_CELLS]; static uint8_t haCacheCount = 0; -HaCache* findOrCreateCache(const String& entityId) { +// The cache outlives reprovisioning: once it is full, recycle an entry that +// no ha-sensor cell of the current config shows any more. +HaCache* findUnusedCache(const AppConfig& config, const String& pluginId) { + for (uint8_t i = 0; i < haCacheCount; i++) { + bool inUse = false; + for (uint8_t c = 0; c < config.cellCount && !inUse; c++) { + const LayoutCellConfig& cell = config.cells[c]; + inUse = cell.pluginId == pluginId && + haCache[i].entityId == readConfig(cell.configJson).entityId; + } + if (!inUse) return &haCache[i]; + } + return nullptr; +} + +HaCache* findOrCreateCache(const String& entityId, + const PluginRenderContext& context) { for (uint8_t i = 0; i < haCacheCount; i++) { if (haCache[i].entityId == entityId) return &haCache[i]; } - if (haCacheCount >= MAX_HA_CACHE) return nullptr; - HaCache& entry = haCache[haCacheCount++]; + HaCache* recycled = + haCacheCount < MAX_HA_CACHE + ? &haCache[haCacheCount++] + : findUnusedCache(context.config, context.cell.pluginId); + if (recycled == nullptr) return nullptr; + + HaCache& entry = *recycled; entry.entityId = entityId; entry.value = ""; entry.errorCode = ""; @@ -347,7 +394,7 @@ void renderHaSensorPlugin(PluginRenderContext& context) { // ----------------------------------------------------------------------- // Cache refresh // ----------------------------------------------------------------------- - HaCache* cache = findOrCreateCache(cfg.entityId); + HaCache* cache = findOrCreateCache(cfg.entityId, context); const uint32_t now = millis(); if (cache != nullptr && cfg.entityId.length() > 0 && cfg.haUrl.length() > 0 && @@ -425,11 +472,15 @@ void renderHaSensorPlugin(PluginRenderContext& context) { parseHAlign(cfg.titleHorizontalAlign), cfg.offsetX); } - // Value + unit side by side + // Value + unit side by side. Long states (e.g. "unavailable" in font 4) + // are shortened so they never spill over neighbouring cells. const String unitStr = showUnit ? toAscii(cfg.unit) : String(""); - const int16_t valW = renderer.textWidth(valueText, cfg.valueFont); const int16_t unitW = showUnit ? renderer.textWidth(unitStr, cfg.unitFont) : 0; + const String clippedValue = + ellipsizeToWidth(renderer, valueText, cfg.valueFont, + static_cast(cellWidth - unitW)); + const int16_t valW = renderer.textWidth(clippedValue, cfg.valueFont); const int16_t pairW = valW + unitW; const int16_t valueY = startY + titleH; const int16_t unitY = valueY; @@ -443,6 +494,8 @@ void renderHaSensorPlugin(PluginRenderContext& context) { } else { pairLeft = cellLeft + cfg.offsetX; } + if (pairLeft + pairW > cellRight) pairLeft = cellRight - pairW; + if (pairLeft < cellLeft) pairLeft = cellLeft; int16_t valX, unitX; if (showUnit && cfg.unitPosition == "before") { @@ -453,7 +506,7 @@ void renderHaSensorPlugin(PluginRenderContext& context) { unitX = pairLeft + valW; } - renderer.textAt(valX, valueY, valueText, cfg.valueFont, cfg.valueColor); + renderer.textAt(valX, valueY, clippedValue, cfg.valueFont, cfg.valueColor); if (showUnit) { renderer.textAt(unitX, unitY, unitStr, cfg.unitFont, cfg.unitColor); } diff --git a/plugins/weather/firmware/WeatherPlugin.cpp b/plugins/weather/firmware/WeatherPlugin.cpp index 2d96adb..1a6c024 100644 --- a/plugins/weather/firmware/WeatherPlugin.cpp +++ b/plugins/weather/firmware/WeatherPlugin.cpp @@ -13,7 +13,9 @@ namespace { constexpr uint8_t MAX_WEATHER_CACHE = 4; constexpr uint8_t MAX_WEATHER_DAYS = 5; constexpr uint32_t FETCH_INTERVAL_MS = 60UL * 60UL * 1000UL; -constexpr uint32_t ERROR_RETRY_INTERVAL_MS = 60UL * 60UL * 1000UL; +// A failed fetch (network down, router rebooting...) should not leave the +// widget in error for a full refresh period. +constexpr uint32_t ERROR_RETRY_INTERVAL_MS = 5UL * 60UL * 1000UL; constexpr uint16_t DEFAULT_ICON_COLOR = 0xFE8C; constexpr uint16_t DEFAULT_LABEL_COLOR = 0x07FF; @@ -127,7 +129,7 @@ uint8_t parseDayOffset(JsonVariantConst value) { if (!value.is()) return 0; const char* text = value.as(); - if (!text || text[1] != '\0') return 0; + if (!text || text[0] == '\0' || text[1] != '\0') return 0; if (text[0] < '0' || text[0] > '4') return 0; return static_cast(text[0] - '0'); } @@ -240,21 +242,45 @@ String urlEncode(const String& value) { return encoded; } -WeatherCache* findOrCreateCache(const String& city, const String& apiKey, - const String& hour) { +bool cacheMatches(const WeatherCache& entry, const WeatherConfig& cfg) { + return entry.city == cfg.city && entry.apiKey == cfg.apiKey && + entry.hour == cfg.hour; +} + +// The cache outlives reprovisioning: once it is full, recycle an entry that +// no weather cell of the current config uses any more. +WeatherCache* findUnusedCache(const PluginRenderContext& context) { + for (uint8_t i = 0; i < weatherCacheCount; i++) { + bool inUse = false; + for (uint8_t c = 0; c < context.config.cellCount && !inUse; c++) { + const LayoutCellConfig& cell = context.config.cells[c]; + inUse = cell.pluginId == context.cell.pluginId && + cacheMatches(weatherCache[i], readConfig(cell.configJson)); + } + + if (!inUse) return &weatherCache[i]; + } + + return nullptr; +} + +WeatherCache* findOrCreateCache(const WeatherConfig& cfg, + const PluginRenderContext& context) { for (uint8_t i = 0; i < weatherCacheCount; i++) { - if (weatherCache[i].city == city && weatherCache[i].apiKey == apiKey && - weatherCache[i].hour == hour) { + if (cacheMatches(weatherCache[i], cfg)) { return &weatherCache[i]; } } - if (weatherCacheCount >= MAX_WEATHER_CACHE) return nullptr; + WeatherCache* recycled = weatherCacheCount < MAX_WEATHER_CACHE + ? &weatherCache[weatherCacheCount++] + : findUnusedCache(context); + if (recycled == nullptr) return nullptr; - WeatherCache& entry = weatherCache[weatherCacheCount++]; - entry.city = city; - entry.apiKey = apiKey; - entry.hour = hour; + WeatherCache& entry = *recycled; + entry.city = cfg.city; + entry.apiKey = cfg.apiKey; + entry.hour = cfg.hour; entry.dayCount = 0; entry.errorCode = ""; entry.lastFetchMs = 0; @@ -838,7 +864,7 @@ void renderWeatherPlugin(PluginRenderContext& context) { if (cfg.apiKey.length() == 0 || cfg.city.length() == 0) { displayKey = "SETUP"; } else { - WeatherCache* cache = findOrCreateCache(cfg.city, cfg.apiKey, cfg.hour); + WeatherCache* cache = findOrCreateCache(cfg, context); if (cache == nullptr) { displayKey = "ERR cache"; } else { From 20cff4c250755e3947e3c13f32e849f3b53649f2 Mon Sep 17 00:00:00 2001 From: Kevin Py Date: Fri, 23 Oct 2026 13:08:56 +0200 Subject: [PATCH 2/2] 1.4.0 --- app/package.json | 2 +- package.json | 2 +- packages/plugin-sdk/package.json | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/package.json b/app/package.json index 89cce12..e729f6e 100644 --- a/app/package.json +++ b/app/package.json @@ -1,6 +1,6 @@ { "name": "@budpy/app", - "version": "1.2.0", + "version": "1.4.0", "private": true, "type": "module", "scripts": { diff --git a/package.json b/package.json index a3e6f9a..292cd81 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "budpy", - "version": "1.3.2", + "version": "1.4.0", "description": "Budpy is an autonomous ESP32 CYD dashboard.", "private": true, "packageManager": "pnpm@11.5.2", diff --git a/packages/plugin-sdk/package.json b/packages/plugin-sdk/package.json index e22639c..6ccf2c9 100644 --- a/packages/plugin-sdk/package.json +++ b/packages/plugin-sdk/package.json @@ -1,6 +1,6 @@ { "name": "@budpy/plugin-sdk", - "version": "1.2.0", + "version": "1.4.0", "private": true, "type": "module", "main": "dist/index.js",