feat: serve the BYOS device API
The panel now pairs, fetches its image and files its logs against this application rather than against the TRMNL cloud. Four endpoints: /api/setup issues a token on first contact, /api/display hands back an image and a wake interval, /api/log stores firmware diagnostics, and /api/device/image/<hash> serves the bytes. The wake interval is where freshness and battery are traded off. In BYOS nothing can be pushed: the device sleeps, wakes, asks and sleeps again. So the interval is short while the shop trades and long overnight, and it is shortened further whenever a change of state falls inside it — the door opening in twenty minutes means waking in twenty-one, whatever the base interval says. The image filename is the hash of its own bytes. The firmware skips the redraw when the name is unchanged, which is the whole battery strategy, and the URL is immutable, unguessable and safe to cache forever. Two integration tests pin this: unchanged data must yield the same filename and store one row, changed hours must yield a different one. MAC addresses are normalised before use. They are a primary key here, and firmwares are inconsistent about case and separators; without this a panel could register twice by capitalising itself differently. Header names are read in both the hyphen and underscore spellings for the same reason — the TRMNL docs and the Seeed sources disagree, and being liberal costs nothing while being wrong costs a blank shop window. Pairing is deliberately made to survive a rendering failure. The token is issued once and only its digest is kept, so a device stranded by a failed response would be registered yet hold no credential, and unable to register again. The welcome image is worth far less than that. This was found by running the flow, not by reading it. satori, yoga and harfbuzz are marked external: bundling rewrites the relative path satori uses to load its WebAssembly, and the renderer dies on a missing hb.wasm. The integration tests run against a real Postgres, in CI too. Mocking Prisma here would only prove the mock works. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012cSY9pVhZmJUKNN7wf1Myd
This commit is contained in:
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* The only place that turns database rows into a ScheduleContext.
|
||||
*
|
||||
* Keeping every query here is what lets `resolver.ts` stay pure. Nothing below
|
||||
* makes a scheduling decision; it loads, narrows and converts.
|
||||
*/
|
||||
|
||||
import { prisma } from '@/lib/db';
|
||||
|
||||
import { addCivilDays, startOfCivilWeek, toCivilDate, type CivilDate } from './civil';
|
||||
import type { ScheduleContext, Slot } from './types';
|
||||
|
||||
/**
|
||||
* How far either side of today to load.
|
||||
*
|
||||
* Back to the Monday of the current week, because the screen draws it; forward
|
||||
* past the resolver's fourteen-day search, so a reopening is never missed for
|
||||
* want of a row.
|
||||
*/
|
||||
const LOOK_BACK_DAYS = 7;
|
||||
const LOOK_AHEAD_DAYS = 21;
|
||||
|
||||
export type LoadedSettings = {
|
||||
shopName: string;
|
||||
timezone: string;
|
||||
countryIsoCode: string;
|
||||
subdivisionCode: string;
|
||||
refreshRateOpenSec: number;
|
||||
refreshRateClosedSec: number;
|
||||
imageFormat: 'bmp' | 'png';
|
||||
};
|
||||
|
||||
const FALLBACK_SETTINGS: LoadedSettings = {
|
||||
shopName: 'ITA ITO',
|
||||
timezone: 'Europe/Zurich',
|
||||
countryIsoCode: 'CH',
|
||||
subdivisionCode: 'CH-GE',
|
||||
refreshRateOpenSec: 600,
|
||||
refreshRateClosedSec: 7200,
|
||||
imageFormat: 'bmp',
|
||||
};
|
||||
|
||||
export async function loadSettings(): Promise<LoadedSettings> {
|
||||
const row = await prisma.settings.findUnique({ where: { id: 'singleton' } });
|
||||
if (!row) {
|
||||
// A freshly created database must still serve a screen rather than a 500.
|
||||
return FALLBACK_SETTINGS;
|
||||
}
|
||||
return {
|
||||
shopName: row.shopName,
|
||||
timezone: row.timezone,
|
||||
countryIsoCode: row.countryIsoCode,
|
||||
subdivisionCode: row.subdivisionCode,
|
||||
refreshRateOpenSec: row.refreshRateOpenSec,
|
||||
refreshRateClosedSec: row.refreshRateClosedSec,
|
||||
imageFormat: row.imageFormat === 'png' ? 'png' : 'bmp',
|
||||
};
|
||||
}
|
||||
|
||||
export async function loadScheduleContext(
|
||||
now: Date,
|
||||
settings: LoadedSettings,
|
||||
): Promise<ScheduleContext> {
|
||||
const today = toCivilDate(now, settings.timezone);
|
||||
// The window starts at the Monday of the current week or earlier, whichever
|
||||
// reaches further back, so the week strip is always fully covered.
|
||||
const from = min(startOfCivilWeek(today), addCivilDays(today, -LOOK_BACK_DAYS));
|
||||
const to = addCivilDays(today, LOOK_AHEAD_DAYS);
|
||||
|
||||
const [weekly, exceptions, vacations, holidays] = await Promise.all([
|
||||
prisma.weeklySchedule.findMany({ orderBy: { dayOfWeek: 'asc' } }),
|
||||
prisma.scheduleException.findMany({
|
||||
where: { date: { gte: asDate(from), lte: asDate(to) } },
|
||||
}),
|
||||
prisma.vacationPeriod.findMany({
|
||||
where: { startDate: { lte: asDate(to) }, endDate: { gte: asDate(from) } },
|
||||
}),
|
||||
prisma.publicHoliday.findMany({
|
||||
where: {
|
||||
date: { gte: asDate(from), lte: asDate(to) },
|
||||
subdivisionCode: settings.subdivisionCode,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
timezone: settings.timezone,
|
||||
weekly: weekly.map((day) => ({
|
||||
dayOfWeek: day.dayOfWeek,
|
||||
isClosed: day.isClosed,
|
||||
slots: asSlots(day.slots),
|
||||
})),
|
||||
exceptions: exceptions.map((exception) => ({
|
||||
date: asCivil(exception.date),
|
||||
isClosed: exception.isClosed,
|
||||
slots: exception.slots === null ? null : asSlots(exception.slots),
|
||||
reason: exception.reason,
|
||||
noteFr: exception.noteFr,
|
||||
noteEn: exception.noteEn,
|
||||
source: exception.source,
|
||||
})),
|
||||
vacations: vacations.map((period) => ({
|
||||
startDate: asCivil(period.startDate),
|
||||
endDate: asCivil(period.endDate),
|
||||
labelFr: period.labelFr,
|
||||
labelEn: period.labelEn,
|
||||
})),
|
||||
holidays: holidays.map((holiday) => ({
|
||||
date: asCivil(holiday.date),
|
||||
nameFr: holiday.nameFr,
|
||||
nameEn: holiday.nameEn,
|
||||
isAutoClosed: holiday.isAutoClosed,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A `@db.Date` column comes back as midnight UTC, so the first ten characters
|
||||
* of the ISO string are the civil date with no timezone maths involved.
|
||||
*/
|
||||
function asCivil(value: Date): CivilDate {
|
||||
return value.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function asDate(value: CivilDate): Date {
|
||||
return new Date(`${value}T00:00:00.000Z`);
|
||||
}
|
||||
|
||||
function min(a: CivilDate, b: CivilDate): CivilDate {
|
||||
return a < b ? a : b;
|
||||
}
|
||||
|
||||
/**
|
||||
* Slots live in a JSON column, so they arrive untyped. Anything malformed is
|
||||
* dropped rather than allowed to reach the resolver: a bad row should cost one
|
||||
* day's hours, not the whole screen.
|
||||
*/
|
||||
function asSlots(value: unknown): Slot[] {
|
||||
if (!Array.isArray(value)) {
|
||||
return [];
|
||||
}
|
||||
return value.filter(
|
||||
(slot): slot is Slot =>
|
||||
typeof slot === 'object' &&
|
||||
slot !== null &&
|
||||
typeof (slot as Slot).open === 'string' &&
|
||||
typeof (slot as Slot).close === 'string',
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user