kiosko 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli.js CHANGED
@@ -346,19 +346,39 @@ function setDefaultFamily(family) {
346
346
  defaultFamily = family;
347
347
  }
348
348
  function registerFontFiles(fonts) {
349
+ widths.clear();
349
350
  return Object.entries(fonts).filter(([family, path]) => !GlobalFonts.registerFromPath(path, family)).map(([, path]) => path);
350
351
  }
352
+ function widthOf(ctx, font, ch) {
353
+ let byChar = widths.get(font);
354
+ if (!byChar) {
355
+ if (widths.size >= MAX_FONTS) widths.clear();
356
+ byChar = /* @__PURE__ */ new Map();
357
+ widths.set(font, byChar);
358
+ }
359
+ let w = byChar.get(ch);
360
+ if (w === void 0) {
361
+ if (ctx.font !== font) ctx.font = font;
362
+ w = ctx.measureText(ch).width;
363
+ byChar.set(ch, w);
364
+ }
365
+ return w;
366
+ }
367
+ function clearTextCache() {
368
+ widths.clear();
369
+ }
351
370
  function glyphs(ctx, text2, o) {
352
371
  const family = o.family ?? defaultFamily;
353
372
  const small = o.smallCaps === true;
354
373
  const capSize = o.size * (o.capRatio ?? 0.76);
355
374
  const out = [];
375
+ const font = `${o.size}px "${family}"`;
376
+ const capFont = `${capSize}px "${family}"`;
356
377
  for (const ch of text2) {
357
378
  const isLower = small && ch !== ch.toUpperCase() && ch === ch.toLowerCase();
358
379
  const size = isLower ? capSize : o.size;
359
380
  const draw = small ? ch.toUpperCase() : ch;
360
- ctx.font = `${size}px "${family}"`;
361
- out.push({ ch: draw, size, width: ctx.measureText(draw).width });
381
+ out.push({ ch: draw, size, width: widthOf(ctx, isLower ? capFont : font, draw) });
362
382
  }
363
383
  return out;
364
384
  }
@@ -377,8 +397,12 @@ function drawTracked(ctx, text2, x, y, o) {
377
397
  let cursor = o.align === "right" ? x - total : o.align === "center" ? x - total / 2 : x;
378
398
  if (o.color) ctx.fillStyle = o.color;
379
399
  ctx.textBaseline = "alphabetic";
400
+ let size = -1;
380
401
  for (const g of gs) {
381
- ctx.font = `${g.size}px "${family}"`;
402
+ if (g.size !== size) {
403
+ ctx.font = `${g.size}px "${family}"`;
404
+ size = g.size;
405
+ }
382
406
  ctx.fillText(g.ch, cursor, y);
383
407
  cursor += g.width + tracking;
384
408
  }
@@ -433,11 +457,13 @@ function wrapLines(ctx, text2, maxWidth, maxLines, o) {
433
457
  }
434
458
  return lines;
435
459
  }
436
- var defaultFamily;
460
+ var defaultFamily, widths, MAX_FONTS;
437
461
  var init_text = __esm({
438
462
  "packages/lcd-canvas-kit/src/text.ts"() {
439
463
  "use strict";
440
464
  defaultFamily = "sans-serif";
465
+ widths = /* @__PURE__ */ new Map();
466
+ MAX_FONTS = 400;
441
467
  }
442
468
  });
443
469
 
@@ -750,6 +776,7 @@ __export(src_exports, {
750
776
  TAU: () => TAU,
751
777
  bezierPts: () => bezierPts,
752
778
  clamp: () => clamp3,
779
+ clearTextCache: () => clearTextCache,
753
780
  css: () => css,
754
781
  drawClipped: () => drawClipped,
755
782
  drawMoonPhase: () => drawMoonPhase,
@@ -791,7 +818,7 @@ __export(testing_exports, {
791
818
  renderWidget: () => renderWidget,
792
819
  widgetState: () => widgetState
793
820
  });
794
- import { createCanvas as createCanvas4, loadImage as loadImage3 } from "@napi-rs/canvas";
821
+ import { createCanvas as createCanvas5, loadImage as loadImage4 } from "@napi-rs/canvas";
795
822
  function resolve3(w, o) {
796
823
  const now = o.now ?? Date.UTC(2026, 10, 5, 9, 42);
797
824
  const locale = o.locale ?? "en";
@@ -808,7 +835,7 @@ function renderWidget(w, o = {}) {
808
835
  const theme = typeof o.theme === "object" ? o.theme : themeById(o.theme);
809
836
  const texts = [];
810
837
  const spy = { ...src_exports, drawTracked: (...a) => (texts.push(a[1]), drawTracked(...a)) };
811
- const canvas = createCanvas4(size.w + 2 * MARGIN, size.h + 2 * MARGIN);
838
+ const canvas = createCanvas5(size.w + 2 * MARGIN, size.h + 2 * MARGIN);
812
839
  const g = canvas.getContext("2d");
813
840
  const box = { x: MARGIN, y: MARGIN, w: size.w, h: size.h };
814
841
  const ctx = {
@@ -821,7 +848,7 @@ function renderWidget(w, o = {}) {
821
848
  theme,
822
849
  fonts: theme.fonts,
823
850
  kit: spy,
824
- canvas: { createCanvas: createCanvas4, loadImage: loadImage3 },
851
+ canvas: { createCanvas: createCanvas5, loadImage: loadImage4 },
825
852
  preview: !!o.preview
826
853
  };
827
854
  const t0 = performance.now();
@@ -849,7 +876,7 @@ function renderWidget(w, o = {}) {
849
876
  ms,
850
877
  ...error !== void 0 ? { error } : {},
851
878
  png() {
852
- const out = createCanvas4(box.w, box.h);
879
+ const out = createCanvas5(box.w, box.h);
853
880
  out.getContext("2d").drawImage(canvas, -box.x, -box.y);
854
881
  return out.toBuffer("image/png");
855
882
  }
@@ -1110,7 +1137,7 @@ var CATEGORIES = [
1110
1137
  { id: "scene", label: { en: "Scenes", es: "Escenas" } },
1111
1138
  { id: "fun", label: { en: "Fun", es: "Diversi\xF3n" } }
1112
1139
  ];
1113
- var SDK_VERSION = "0.2.3";
1140
+ var SDK_VERSION = "0.2.5";
1114
1141
  function defineWidget(w) {
1115
1142
  return w;
1116
1143
  }
@@ -1460,9 +1487,21 @@ function normalize(raw) {
1460
1487
  sources: c.sources ?? {},
1461
1488
  plugins: { disabled: c.plugins?.disabled ?? [] },
1462
1489
  server: { ...DEFAULT_CONFIG.server, ...c.server ?? {} },
1490
+ ...c.homeassistant && typeof c.homeassistant === "object" ? { homeassistant: normalizeHa(c.homeassistant) } : {},
1463
1491
  screens
1464
1492
  };
1465
1493
  }
1494
+ function normalizeHa(h) {
1495
+ const id = String(h.nodeId ?? "").toLowerCase().replace(/[^a-z0-9_-]+/g, "_").replace(/^_+|_+$/g, "");
1496
+ return {
1497
+ enabled: h.enabled ?? false,
1498
+ broker: typeof h.broker === "string" ? h.broker.trim() : "",
1499
+ ...h.username ? { username: String(h.username) } : {},
1500
+ ...h.password ? { password: String(h.password) } : {},
1501
+ discoveryPrefix: typeof h.discoveryPrefix === "string" && h.discoveryPrefix.trim() || "homeassistant",
1502
+ nodeId: id || "kiosko"
1503
+ };
1504
+ }
1466
1505
  function normalizeScreen(s, i) {
1467
1506
  const width = s.width ?? 1920;
1468
1507
  const height = s.height ?? 462;
@@ -1750,6 +1789,20 @@ function configSchema(plugins) {
1750
1789
  host: { type: "string", default: DEFAULT_CONFIG.server.host, description: "Keep 127.0.0.1 unless you know why: the editor can install plugins." },
1751
1790
  port: { type: "integer", minimum: 1, maximum: 65535, default: DEFAULT_CONFIG.server.port }
1752
1791
  }
1792
+ },
1793
+ homeassistant: {
1794
+ type: "object",
1795
+ additionalProperties: false,
1796
+ description: "Kiosko as a device in Home Assistant, over MQTT discovery: each screen with its page to choose, a switch to turn it off and a button per interlude.",
1797
+ required: ["broker"],
1798
+ properties: {
1799
+ enabled: { type: "boolean", default: false },
1800
+ broker: { type: "string", description: "The MQTT broker Home Assistant uses: mqtt://host:1883, or mqtts:// for TLS." },
1801
+ username: { type: "string" },
1802
+ password: { type: "string", "x-secret": true },
1803
+ discoveryPrefix: { type: "string", default: "homeassistant", description: "Home Assistant's MQTT discovery prefix." },
1804
+ nodeId: { type: "string", pattern: "^[a-z0-9_-]+$", description: "This Kiosko's id in the topics, so several machines don't collide. Default: kiosko." }
1805
+ }
1753
1806
  }
1754
1807
  },
1755
1808
  $defs: {
@@ -2694,13 +2747,106 @@ function pickPage(pages, now, pinned) {
2694
2747
 
2695
2748
  // packages/core/src/compositor.ts
2696
2749
  init_src();
2697
- import { createCanvas as createCanvas3, loadImage as loadImage2 } from "@napi-rs/canvas";
2750
+ import { createCanvas as createCanvas4, loadImage as loadImage3 } from "@napi-rs/canvas";
2698
2751
 
2699
2752
  // packages/core/src/env.ts
2700
2753
  init_src();
2701
2754
  import { mkdirSync as mkdirSync2 } from "node:fs";
2755
+ import { createCanvas as createCanvas3, loadImage as loadImage2 } from "@napi-rs/canvas";
2756
+
2757
+ // packages/core/src/scaled-images.ts
2758
+ import { createRequire } from "node:module";
2759
+ import { Worker } from "node:worker_threads";
2702
2760
  import { createCanvas as createCanvas2, loadImage } from "@napi-rs/canvas";
2703
- var CANVAS = { createCanvas: createCanvas2, loadImage };
2761
+ function scaledSize(w, h, size) {
2762
+ const sx = size.width / w, sy = size.height / h;
2763
+ const s = Math.min(1, (size.fit ?? "cover") === "cover" ? Math.max(sx, sy) : Math.min(sx, sy));
2764
+ return { width: Math.max(1, Math.round(w * s)), height: Math.max(1, Math.round(h * s)) };
2765
+ }
2766
+ var WORKER = `
2767
+ const { parentPort, workerData } = require('node:worker_threads');
2768
+ const { readFile } = require('node:fs/promises');
2769
+ const { createCanvas, loadImage } = require(workerData.canvas);
2770
+ const scaledSize = ${scaledSize.toString()};
2771
+ parentPort.on('message', async (job) => {
2772
+ try {
2773
+ const src = typeof job.src === 'string' ? await readFile(job.src) : Buffer.from(job.src);
2774
+ const img = await loadImage(src);
2775
+ const to = scaledSize(img.width, img.height, job.size);
2776
+ if (to.width >= img.width && to.height >= img.height) {
2777
+ // Already small enough: the bytes as they are.
2778
+ parentPort.postMessage({ id: job.id, ok: true, same: true });
2779
+ return;
2780
+ }
2781
+ const c = createCanvas(to.width, to.height);
2782
+ const g = c.getContext('2d');
2783
+ g.imageSmoothingQuality = 'high';
2784
+ g.drawImage(img, 0, 0, to.width, to.height);
2785
+ const png = src[0] === 0x89 && src[1] === 0x50;
2786
+ const out = png ? await c.encode('png') : await c.encode('jpeg', 90);
2787
+ const ab = out.buffer.slice(out.byteOffset, out.byteOffset + out.byteLength);
2788
+ parentPort.postMessage({ id: job.id, ok: true, bytes: ab }, [ab]);
2789
+ } catch (err) {
2790
+ parentPort.postMessage({ id: job.id, ok: false, error: err && err.message ? err.message : String(err) });
2791
+ }
2792
+ });
2793
+ `;
2794
+ var worker = null;
2795
+ var broken = false;
2796
+ var nextId = 1;
2797
+ var pending = /* @__PURE__ */ new Map();
2798
+ function startWorker() {
2799
+ if (worker) return worker;
2800
+ if (broken) return null;
2801
+ try {
2802
+ const canvas = createRequire(import.meta.url).resolve("@napi-rs/canvas");
2803
+ const w = new Worker(WORKER, { eval: true, workerData: { canvas } });
2804
+ w.on("message", (m) => {
2805
+ const p = pending.get(m.id);
2806
+ if (!p) return;
2807
+ pending.delete(m.id);
2808
+ if (!pending.size) w.unref();
2809
+ if (m.ok) p.resolve(m);
2810
+ else p.reject(new Error(m.error ?? "could not scale the image"));
2811
+ });
2812
+ const gone = (err) => {
2813
+ if (worker === w) worker = null;
2814
+ for (const [id, p] of pending) {
2815
+ pending.delete(id);
2816
+ p.reject(err ?? new Error("the image thread stopped"));
2817
+ }
2818
+ };
2819
+ w.on("error", gone);
2820
+ w.on("exit", () => gone());
2821
+ w.unref();
2822
+ worker = w;
2823
+ return w;
2824
+ } catch {
2825
+ broken = true;
2826
+ return null;
2827
+ }
2828
+ }
2829
+ function warm(img) {
2830
+ const w = Math.max(1, Math.round(img.width / 3)), h = Math.max(1, Math.round(img.height / 3));
2831
+ createCanvas2(w, h).getContext("2d").drawImage(img, 0, 0, w, h);
2832
+ return img;
2833
+ }
2834
+ async function loadImageScaled(src, size) {
2835
+ if (!(size.width > 0) || !(size.height > 0)) throw new Error("loadImageScaled: width and height must be over 0");
2836
+ const w = startWorker();
2837
+ if (!w) return warm(await loadImage(src));
2838
+ const id = nextId++;
2839
+ const job = typeof src === "string" ? src : src.buffer.slice(src.byteOffset, src.byteOffset + src.byteLength);
2840
+ const r = await new Promise((resolve8, reject) => {
2841
+ pending.set(id, { resolve: resolve8, reject });
2842
+ w.ref();
2843
+ w.postMessage({ id, src: job, size });
2844
+ });
2845
+ return warm(await loadImage(r.same || !r.bytes ? src : Buffer.from(r.bytes)));
2846
+ }
2847
+
2848
+ // packages/core/src/env.ts
2849
+ var CANVAS = { createCanvas: createCanvas3, loadImage: loadImage2, loadImageScaled };
2704
2850
  function systemLocale() {
2705
2851
  try {
2706
2852
  return Intl.DateTimeFormat().resolvedOptions().locale || "en";
@@ -2746,10 +2892,10 @@ function baseContext(cfg, plugin, log, now) {
2746
2892
 
2747
2893
  // packages/core/src/fonts.ts
2748
2894
  import { existsSync as existsSync3 } from "node:fs";
2749
- import { createRequire } from "node:module";
2895
+ import { createRequire as createRequire2 } from "node:module";
2750
2896
  import { dirname as dirname2, join as join3 } from "node:path";
2751
2897
  import { GlobalFonts as GlobalFonts2 } from "@napi-rs/canvas";
2752
- var require2 = createRequire(import.meta.url);
2898
+ var require2 = createRequire2(import.meta.url);
2753
2899
  var done = false;
2754
2900
  function ttfDir() {
2755
2901
  try {
@@ -2780,7 +2926,7 @@ var images = /* @__PURE__ */ new Map();
2780
2926
  function backgroundImage(path) {
2781
2927
  if (!images.has(path)) {
2782
2928
  images.set(path, null);
2783
- loadImage2(path).then((img) => images.set(path, img)).catch(() => void 0);
2929
+ loadImage3(path).then((img) => images.set(path, img)).catch(() => void 0);
2784
2930
  }
2785
2931
  return images.get(path) ?? null;
2786
2932
  }
@@ -2915,7 +3061,7 @@ function paintTile(g, input, tile, rect2, out, nextAt, idles, animatable) {
2915
3061
  if (hit.error) out.error = hit.error;
2916
3062
  return;
2917
3063
  }
2918
- const canvas = createCanvas3(rect2.w, rect2.h);
3064
+ const canvas = createCanvas4(rect2.w, rect2.h);
2919
3065
  const tg = canvas.getContext("2d");
2920
3066
  tg.translate(-rect2.x, -rect2.y);
2921
3067
  draw(tg);
@@ -2978,7 +3124,7 @@ function drawTileContent(g, input, r, rect2, chrome, out, anim) {
2978
3124
  function composePage(input) {
2979
3125
  registerFonts();
2980
3126
  const { screen, page, theme, now } = input;
2981
- const canvas = createCanvas3(screen.width, screen.height);
3127
+ const canvas = createCanvas4(screen.width, screen.height);
2982
3128
  const g = canvas.getContext("2d");
2983
3129
  g.fillStyle = page.background.color || theme.colors.bg;
2984
3130
  g.fillRect(0, 0, screen.width, screen.height);
@@ -3012,7 +3158,7 @@ function composePage(input) {
3012
3158
  function rotateCanvas(src, rotate) {
3013
3159
  if (!rotate) return src;
3014
3160
  const swap = rotate === 90 || rotate === 270;
3015
- const out = createCanvas3(swap ? src.height : src.width, swap ? src.width : src.height);
3161
+ const out = createCanvas4(swap ? src.height : src.width, swap ? src.width : src.height);
3016
3162
  const g = out.getContext("2d");
3017
3163
  g.translate(out.width / 2, out.height / 2);
3018
3164
  g.rotate(rotate * Math.PI / 180);
@@ -4087,17 +4233,17 @@ function lazyJpeg(c) {
4087
4233
  return () => b ??= c.toBuffer("image/jpeg", 88);
4088
4234
  }
4089
4235
  function encode(c, kind, quality) {
4090
- return kind === "jpeg" ? c.toBuffer("image/jpeg", Math.max(1, Math.min(100, quality || 90))) : c.toBuffer("image/png");
4236
+ return kind === "jpeg" ? c.encode("jpeg", Math.max(1, Math.min(100, quality || 90))) : c.encode("png");
4091
4237
  }
4092
4238
  var MIN_FIT_QUALITY = 20;
4093
- function encodeFit(c, kind, quality, maxBytes) {
4239
+ async function encodeFit(c, kind, quality, maxBytes) {
4094
4240
  const q0 = Math.max(1, Math.min(100, quality || 90));
4095
- let out = encode(c, kind, q0);
4241
+ let out = await encode(c, kind, q0);
4096
4242
  if (kind !== "jpeg" || !(maxBytes > 0) || out.length <= maxBytes) return { out, quality: q0, over: false };
4097
4243
  let q3 = q0;
4098
4244
  while (q3 > MIN_FIT_QUALITY) {
4099
4245
  q3 = Math.max(MIN_FIT_QUALITY, q3 - 10);
4100
- out = encode(c, kind, q3);
4246
+ out = await encode(c, kind, q3);
4101
4247
  if (out.length <= maxBytes) return { out, quality: q3, over: false };
4102
4248
  }
4103
4249
  return { out, quality: q3, over: true };
@@ -4114,6 +4260,10 @@ var ScreenRunner = class {
4114
4260
  pinned = null;
4115
4261
  playedSlot = /* @__PURE__ */ new Map();
4116
4262
  interlude = null;
4263
+ /** Switched off from outside (Home Assistant, the API): black until switched on. Not saved. */
4264
+ off = false;
4265
+ /** An interlude asked for now (the editor, Home Assistant): played as soon as the screen is free. */
4266
+ wanted = null;
4117
4267
  /** When `fit` last told the log that frames were shrunk, to say it now and then, not every frame. */
4118
4268
  fitLoggedAt = 0;
4119
4269
  /** Instance ids on the current page, to know if a data change concerns us. */
@@ -4139,8 +4289,8 @@ var ScreenRunner = class {
4139
4289
  this.scheduler = new AnimationScheduler(() => rt.rnd(), (type, why) => rt.log(type, `animation ignored: ${why}`));
4140
4290
  }
4141
4291
  /** Encodes a frame within the screen's `maxBytes`, saying so in the log (at most every 10 min) when it had to shrink it. */
4142
- fit(c, kind, quality, screen) {
4143
- const r = encodeFit(c, kind, quality, screen.maxBytes);
4292
+ async fit(c, kind, quality, screen) {
4293
+ const r = await encodeFit(c, kind, quality, screen.maxBytes);
4144
4294
  if ((r.quality !== Math.max(1, Math.min(100, quality || 90)) || r.over) && Date.now() - this.fitLoggedAt > 10 * 6e4) {
4145
4295
  this.fitLoggedAt = Date.now();
4146
4296
  this.rt.log(
@@ -4178,7 +4328,9 @@ var ScreenRunner = class {
4178
4328
  if (this.busy || !this.screen.enabled) return;
4179
4329
  this.busy = true;
4180
4330
  try {
4181
- if (await this.maybeInterlude(now)) return;
4331
+ const asked = this.wanted;
4332
+ this.wanted = null;
4333
+ if (!this.off && await this.maybeInterlude(now, asked ?? void 0)) return;
4182
4334
  const page = this.currentPage(now);
4183
4335
  if (page?.id !== this.page?.id) {
4184
4336
  this.page = page;
@@ -4203,7 +4355,7 @@ var ScreenRunner = class {
4203
4355
  const theme = this.rt.theme();
4204
4356
  let result = null;
4205
4357
  let canvas;
4206
- if (page) {
4358
+ if (page && !this.off) {
4207
4359
  result = composePage({
4208
4360
  cfg: this.rt.config,
4209
4361
  screen,
@@ -4234,14 +4386,14 @@ var ScreenRunner = class {
4234
4386
  this.animatable = [];
4235
4387
  this.nextAt = now + 6e4;
4236
4388
  }
4237
- const sleeping = !!(screen.sleepWhenIdle && result?.idle);
4389
+ const sleeping = this.off || !!(screen.sleepWhenIdle && result?.idle);
4238
4390
  if (sleeping) {
4239
4391
  const g = canvas.getContext("2d");
4240
4392
  g.fillStyle = "#000";
4241
4393
  g.fillRect(0, 0, screen.width, screen.height);
4242
4394
  }
4243
4395
  const kind = encodeFor(screen.device, screen.jpegQuality);
4244
- const out = this.fit(rotateCanvas(canvas, screen.rotate), kind, screen.jpegQuality, screen);
4396
+ const out = await this.fit(rotateCanvas(canvas, screen.rotate), kind, screen.jpegQuality, screen);
4245
4397
  this.lastInfo = { screenId: screen.id, pageId: page?.id ?? null, at: now, image: lazyJpeg(canvas), tiles: result?.tiles ?? [], interlude: null, sleeping };
4246
4398
  this.rt.emit("frame", this.lastInfo);
4247
4399
  if (this.last?.equals(out)) return;
@@ -4277,7 +4429,7 @@ var ScreenRunner = class {
4277
4429
  const kind = encodeFor(this.screen.device, this.screen.jpegQuality || 85);
4278
4430
  const canvas = CANVAS.createCanvas(this.screen.width, this.screen.height);
4279
4431
  const g = canvas.getContext("2d");
4280
- const start = Date.now();
4432
+ let start = Date.now();
4281
4433
  for (let i = 0; i < frames && this.interlude; i++) {
4282
4434
  g.save();
4283
4435
  try {
@@ -4288,7 +4440,7 @@ var ScreenRunner = class {
4288
4440
  } finally {
4289
4441
  g.restore();
4290
4442
  }
4291
- const out = this.fit(rotateCanvas(canvas, this.screen.rotate), kind, this.screen.jpegQuality || 85, this.screen);
4443
+ const out = await this.fit(rotateCanvas(canvas, this.screen.rotate), kind, this.screen.jpegQuality || 85, this.screen);
4292
4444
  await this.device.send(out);
4293
4445
  if (i % 3 === 0) {
4294
4446
  const snap = CANVAS.createCanvas(canvas.width, canvas.height);
@@ -4298,6 +4450,10 @@ var ScreenRunner = class {
4298
4450
  }
4299
4451
  const wait = start + (i + 1) * 1e3 / fps - Date.now();
4300
4452
  if (wait > 0) await new Promise((r) => setTimeout(r, wait));
4453
+ else {
4454
+ start -= wait;
4455
+ await new Promise((r) => setImmediate(r));
4456
+ }
4301
4457
  }
4302
4458
  this.interlude = null;
4303
4459
  this.last = null;
@@ -4383,6 +4539,7 @@ var ScreenRunner = class {
4383
4539
  sent.push({ out: this.fit(rotateCanvas(result.canvas, screen.rotate), kind, screen.jpegQuality || 85, screen), snap: s % 3 === 1 ? result.canvas : null });
4384
4540
  await new Promise((r) => setImmediate(r));
4385
4541
  }
4542
+ const outs = await Promise.all(sent.map((x) => x.out));
4386
4543
  const what = items.map((x) => `${x.animatable.type} ${x.play.plan.id}`).join(" + ");
4387
4544
  this.rt.log(`screen:${screen.name}`, `animating ${what}: ${sent.length} frames at ${fps} fps (painted in ${Date.now() - t0} ms)`);
4388
4545
  const holdAt = hold ? Math.max(0, Math.min(sent.length - 1, hold.index - 1)) : -1;
@@ -4391,7 +4548,7 @@ var ScreenRunner = class {
4391
4548
  if (abort()) return false;
4392
4549
  const due = Math.floor((Date.now() - start) * fps / 1e3);
4393
4550
  if (k < due - 1 && k !== holdAt && k < sent.length - 1) continue;
4394
- await this.device.send(sent[k].out);
4551
+ await this.device.send(outs[k]);
4395
4552
  const snap = sent[k].snap;
4396
4553
  if (snap) {
4397
4554
  this.lastInfo = { screenId: screen.id, pageId: page.id, at: Date.now(), image: lazyJpeg(snap), tiles: [], interlude: null, animation: items.map((x) => x.animatable.type).join(", "), sleeping: false };
@@ -4408,10 +4565,18 @@ var ScreenRunner = class {
4408
4565
  }
4409
4566
  return true;
4410
4567
  }
4568
+ /**
4569
+ * Plays an interlude as soon as the screen is free: now if it is, or right
4570
+ * after the paint or animation under way (asked in the middle of one, it
4571
+ * used to be dropped without a word).
4572
+ */
4411
4573
  async playNow(slotId) {
4574
+ if (this.off) return;
4575
+ this.wanted = slotId;
4412
4576
  if (this.busy) return;
4413
4577
  this.busy = true;
4414
4578
  try {
4579
+ this.wanted = null;
4415
4580
  await this.maybeInterlude(Date.now(), slotId);
4416
4581
  } finally {
4417
4582
  this.busy = false;
@@ -4597,6 +4762,15 @@ var Runtime = class extends EventEmitter {
4597
4762
  stopInterlude(screenId) {
4598
4763
  this.runners.get(screenId)?.stopInterlude();
4599
4764
  }
4765
+ /** Switches a screen's picture off (black) or back on, until the next restart. */
4766
+ setOff(screenId, off) {
4767
+ const r = this.runners.get(screenId);
4768
+ if (!r || r.off === off) return;
4769
+ r.off = off;
4770
+ if (off) r.stopInterlude();
4771
+ r.dirty = true;
4772
+ this.emit("screen", { screenId, off });
4773
+ }
4600
4774
  refreshWidget(instanceId) {
4601
4775
  this.fetches.refresh(instanceId);
4602
4776
  }
@@ -4611,7 +4785,8 @@ var Runtime = class extends EventEmitter {
4611
4785
  animation: r.animating,
4612
4786
  device: r.device.status,
4613
4787
  lastFrameAt: r.lastInfo?.at ?? null,
4614
- sleeping: r.lastInfo?.sleeping ?? false
4788
+ sleeping: r.lastInfo?.sleeping ?? false,
4789
+ off: r.off
4615
4790
  })),
4616
4791
  sources: this.hub.status(),
4617
4792
  fetches: this.fetches.status(),
@@ -5500,6 +5675,7 @@ function placeImage(box, w, h, fit3, position) {
5500
5675
  const fy = position === "top" ? 0 : position === "bottom" ? 1 : 0.5;
5501
5676
  return { x: box.x + (box.w - dw) * fx, y: box.y + (box.h - dh) * fy, w: dw, h: dh };
5502
5677
  }
5678
+ var load = (canvas, src) => canvas.loadImageScaled ? canvas.loadImageScaled(src, { width: 1920, height: 1080, fit: "cover" }) : canvas.loadImage(src);
5503
5679
  var image = defineWidget({
5504
5680
  id: "image",
5505
5681
  name: { en: "Picture", es: "Imagen" },
@@ -5540,11 +5716,11 @@ var image = defineWidget({
5540
5716
  if (/^https?:/.test(options2.src)) {
5541
5717
  const res = await fetch(imageUrl(options2.src, Date.now(), options2.addTimestamp), { signal });
5542
5718
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
5543
- return { img: await canvas.loadImage(Buffer.from(await res.arrayBuffer())) };
5719
+ return { img: await load(canvas, Buffer.from(await res.arrayBuffer())) };
5544
5720
  }
5545
5721
  const path = (await stat(options2.src)).isDirectory() ? await nextInFolder(options2.src) : options2.src;
5546
5722
  if (!path) throw new Error(`no pictures in ${options2.src}`);
5547
- return { img: await canvas.loadImage(path) };
5723
+ return { img: await load(canvas, path) };
5548
5724
  },
5549
5725
  render(g, { box, data, options: options2, theme, kit, t: tr }) {
5550
5726
  const img = data?.img;
@@ -5570,7 +5746,7 @@ var image = defineWidget({
5570
5746
  var src_default = definePlugin({
5571
5747
  id: "core",
5572
5748
  name: { en: "Essentials", es: "B\xE1sicos" },
5573
- version: "0.2.3",
5749
+ version: "0.2.5",
5574
5750
  sdk: "^0.2.0",
5575
5751
  // The picture widget reads the image (or folder, or URL) you give it.
5576
5752
  permissions: { files: ["user"], network: ["user"] },
@@ -5594,7 +5770,7 @@ function resolveModule(name, dir) {
5594
5770
  }
5595
5771
  return null;
5596
5772
  }
5597
- async function load(path) {
5773
+ async function load2(path) {
5598
5774
  const hit = loaded.get(path);
5599
5775
  if (hit) return hit;
5600
5776
  const m = (await import(pathToFileURL3(path).href)).default;
@@ -5636,7 +5812,7 @@ var module2 = defineWidget({
5636
5812
  if (!options2.module) throw new Error("no module set");
5637
5813
  const path = resolveModule(options2.module, options2.dir);
5638
5814
  if (!path) throw new Error(`module "${options2.module}" not found in ${options2.dir}`);
5639
- const mod = await load(path);
5815
+ const mod = await load2(path);
5640
5816
  if (options2.json.trim()) JSON.parse(options2.json);
5641
5817
  const data = mod.fetch ? await mod.fetch({ config: moduleConfig(mod, options2), now, log, canvas }) : void 0;
5642
5818
  return { path, data };
@@ -5665,7 +5841,7 @@ var module2 = defineWidget({
5665
5841
  var src_default2 = definePlugin({
5666
5842
  id: "legacy",
5667
5843
  name: { en: "aimonitor compatibility", es: "Compatibilidad aimonitor" },
5668
- version: "0.2.3",
5844
+ version: "0.2.5",
5669
5845
  sdk: "^0.2.0",
5670
5846
  // Runs the aimonitor modules you point it at, and reads their folder.
5671
5847
  permissions: { exec: ["user"], files: ["user"] },
@@ -6696,7 +6872,7 @@ function runService(action, plan) {
6696
6872
  // packages/server/src/server.ts
6697
6873
  import { existsSync as existsSync12, readFileSync as readFileSync7, statSync as statSync3 } from "node:fs";
6698
6874
  import { createServer } from "node:http";
6699
- import { createRequire as createRequire2 } from "node:module";
6875
+ import { createRequire as createRequire3 } from "node:module";
6700
6876
  import { dirname as dirname6, extname, join as join15, normalize as normPath, resolve as resolve7 } from "node:path";
6701
6877
 
6702
6878
  // packages/server/src/plugins-manage.ts
@@ -6792,8 +6968,430 @@ async function reloadPlugin(id, o) {
6792
6968
  return problem;
6793
6969
  }
6794
6970
 
6971
+ // packages/server/src/homeassistant.ts
6972
+ import { hostname } from "node:os";
6973
+
6974
+ // packages/server/src/mqtt.ts
6975
+ import { EventEmitter as EventEmitter2 } from "node:events";
6976
+ import { connect as tcp } from "node:net";
6977
+ import { connect as tls } from "node:tls";
6978
+ var RETRY_MS2 = [2e3, 5e3, 1e4, 3e4, 6e4];
6979
+ function encodeLength(n) {
6980
+ const out = [];
6981
+ do {
6982
+ let b = n % 128;
6983
+ n = Math.floor(n / 128);
6984
+ if (n > 0) b |= 128;
6985
+ out.push(b);
6986
+ } while (n > 0);
6987
+ return Buffer.from(out);
6988
+ }
6989
+ var str = (s) => {
6990
+ const b = Buffer.from(s, "utf8");
6991
+ const len = Buffer.alloc(2);
6992
+ len.writeUInt16BE(b.length);
6993
+ return Buffer.concat([len, b]);
6994
+ };
6995
+ var packet = (type, flags, body2) => Buffer.concat([Buffer.from([type << 4 | flags]), encodeLength(body2.length), body2]);
6996
+ function connectPacket(o) {
6997
+ let flags = 2;
6998
+ const payload = [str(o.clientId)];
6999
+ if (o.will) {
7000
+ flags |= 4 | (o.will.retain ? 32 : 0);
7001
+ payload.push(str(o.will.topic), str(o.will.payload));
7002
+ }
7003
+ if (o.username) {
7004
+ flags |= 128;
7005
+ payload.push(str(o.username));
7006
+ if (o.password) {
7007
+ flags |= 64;
7008
+ payload.push(str(o.password));
7009
+ }
7010
+ }
7011
+ const keep = Buffer.alloc(2);
7012
+ keep.writeUInt16BE(o.keepalive ?? 30);
7013
+ return packet(1, 0, Buffer.concat([str("MQTT"), Buffer.from([4, flags]), keep, ...payload]));
7014
+ }
7015
+ var publishPacket = (topic, payload, retain = false) => packet(3, retain ? 1 : 0, Buffer.concat([str(topic), Buffer.from(payload, "utf8")]));
7016
+ function subscribePacket(id, topics) {
7017
+ const pid = Buffer.alloc(2);
7018
+ pid.writeUInt16BE(id);
7019
+ return packet(8, 2, Buffer.concat([pid, ...topics.map((t2) => Buffer.concat([str(t2), Buffer.from([0])]))]));
7020
+ }
7021
+ function readPackets(buf) {
7022
+ const packets = [];
7023
+ let i = 0;
7024
+ for (; ; ) {
7025
+ if (buf.length - i < 2) break;
7026
+ let len = 0, mult = 1, j = i + 1, ok = false;
7027
+ for (; j < buf.length && j < i + 5; j++) {
7028
+ len += (buf[j] & 127) * mult;
7029
+ mult *= 128;
7030
+ if (!(buf[j] & 128)) {
7031
+ ok = true;
7032
+ break;
7033
+ }
7034
+ }
7035
+ if (!ok || buf.length < j + 1 + len) break;
7036
+ packets.push({ type: buf[i] >> 4, flags: buf[i] & 15, body: buf.subarray(j + 1, j + 1 + len) });
7037
+ i = j + 1 + len;
7038
+ }
7039
+ return { packets, rest: buf.subarray(i) };
7040
+ }
7041
+ var CONNACK_ERRORS = {
7042
+ 1: "the broker refused the protocol version",
7043
+ 2: "the broker refused the client id",
7044
+ 3: "the broker is unavailable",
7045
+ 4: "wrong user name or password",
7046
+ 5: "not authorised"
7047
+ };
7048
+ var MqttClient = class extends EventEmitter2 {
7049
+ state = "connecting";
7050
+ error = null;
7051
+ sock = null;
7052
+ buf = Buffer.alloc(0);
7053
+ timers = [];
7054
+ attempt = 0;
7055
+ closed = false;
7056
+ nextId = 1;
7057
+ awaitingPong = false;
7058
+ o;
7059
+ constructor(o) {
7060
+ super();
7061
+ this.o = o;
7062
+ this.open();
7063
+ }
7064
+ get connected() {
7065
+ return this.state === "connected";
7066
+ }
7067
+ publish(topic, payload, retain = false) {
7068
+ if (this.connected) this.sock?.write(publishPacket(topic, payload, retain));
7069
+ }
7070
+ subscribe(topics) {
7071
+ if (this.connected && topics.length) this.sock?.write(subscribePacket(this.nextId++ % 65535 || 1, topics));
7072
+ }
7073
+ /** Goes away cleanly: the will is not published (publish your own "offline" first). */
7074
+ close() {
7075
+ this.closed = true;
7076
+ this.clear();
7077
+ if (this.sock && this.connected) this.sock.write(Buffer.from([224, 0]));
7078
+ this.sock?.end();
7079
+ this.sock?.destroy();
7080
+ this.sock = null;
7081
+ this.set("closed");
7082
+ }
7083
+ set(state, error = null) {
7084
+ this.state = state;
7085
+ this.error = error;
7086
+ this.emit("state", state, error);
7087
+ }
7088
+ clear() {
7089
+ for (const t2 of this.timers) clearTimeout(t2);
7090
+ this.timers = [];
7091
+ }
7092
+ later(fn, ms) {
7093
+ const t2 = setTimeout(fn, ms);
7094
+ t2.unref?.();
7095
+ this.timers.push(t2);
7096
+ }
7097
+ open() {
7098
+ if (this.closed) return;
7099
+ let u;
7100
+ try {
7101
+ u = new URL(this.o.url);
7102
+ } catch {
7103
+ this.set("error", `not a broker address: ${this.o.url}`);
7104
+ return;
7105
+ }
7106
+ const secure = u.protocol === "mqtts:";
7107
+ if (!secure && u.protocol !== "mqtt:") {
7108
+ this.set("error", `use mqtt:// or mqtts:// (got ${u.protocol})`);
7109
+ return;
7110
+ }
7111
+ const port = Number(u.port) || (secure ? 8883 : 1883);
7112
+ this.set("connecting", this.error);
7113
+ const s = this.o.socket ? this.o.socket(u.hostname, port, secure) : secure ? tls({ host: u.hostname, port, servername: u.hostname }) : tcp({ host: u.hostname, port });
7114
+ this.sock = s;
7115
+ this.buf = Buffer.alloc(0);
7116
+ const mine = (fn) => (...a) => this.sock === s && fn(...a);
7117
+ s.setNoDelay?.(true);
7118
+ s.on(secure ? "secureConnect" : "connect", mine(() => s.write(connectPacket(this.o))));
7119
+ s.on("data", mine((d) => this.onData(d)));
7120
+ s.on("error", mine((err) => this.drop(err.message)));
7121
+ s.on("close", mine(() => this.drop(this.error ?? "connection closed")));
7122
+ }
7123
+ onData(d) {
7124
+ const { packets, rest } = readPackets(Buffer.concat([this.buf, d]));
7125
+ this.buf = Buffer.from(rest);
7126
+ for (const p of packets) {
7127
+ if (p.type === 2) {
7128
+ const code = p.body[1] ?? 0;
7129
+ if (code) {
7130
+ this.drop(CONNACK_ERRORS[code] ?? `refused (${code})`, true);
7131
+ return;
7132
+ }
7133
+ this.attempt = 0;
7134
+ this.set("connected");
7135
+ this.ping();
7136
+ this.emit("connect");
7137
+ } else if (p.type === 3) {
7138
+ const len = p.body.readUInt16BE(0);
7139
+ const topic = p.body.subarray(2, 2 + len).toString("utf8");
7140
+ const qos = p.flags >> 1 & 3;
7141
+ const payload = p.body.subarray(2 + len + (qos ? 2 : 0)).toString("utf8");
7142
+ this.emit("message", topic, payload);
7143
+ } else if (p.type === 13) {
7144
+ this.awaitingPong = false;
7145
+ }
7146
+ }
7147
+ }
7148
+ ping() {
7149
+ const every = (this.o.keepalive ?? 30) * 1e3 * 0.8;
7150
+ this.later(() => {
7151
+ if (!this.connected) return;
7152
+ if (this.awaitingPong) {
7153
+ this.drop("no answer from the broker");
7154
+ return;
7155
+ }
7156
+ this.awaitingPong = true;
7157
+ this.sock?.write(Buffer.from([192, 0]));
7158
+ this.ping();
7159
+ }, every);
7160
+ }
7161
+ drop(why, refused = false) {
7162
+ if (this.closed) return;
7163
+ this.clear();
7164
+ const s = this.sock;
7165
+ this.sock = null;
7166
+ s?.destroy();
7167
+ this.awaitingPong = false;
7168
+ this.set("error", why);
7169
+ const ms = refused ? 5 * 6e4 : RETRY_MS2[Math.min(this.attempt++, RETRY_MS2.length - 1)];
7170
+ this.later(() => this.open(), ms);
7171
+ }
7172
+ };
7173
+
7174
+ // packages/server/src/homeassistant.ts
7175
+ var AUTO = { en: "Auto", es: "Autom\xE1tica" };
7176
+ var NAMES = {
7177
+ page: { en: "Page", es: "P\xE1gina" },
7178
+ shown: { en: "Page shown", es: "P\xE1gina en pantalla" },
7179
+ display: { en: "Display", es: "Pantalla" },
7180
+ interlude: { en: "Play", es: "Reproducir" }
7181
+ };
7182
+ var slug3 = (s) => s.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[^a-z0-9_-]+/g, "_").replace(/^_+|_+$/g, "") || "x";
7183
+ function pageOptions(screen, auto) {
7184
+ const byName = /* @__PURE__ */ new Map([[auto, null]]);
7185
+ const nameOf = /* @__PURE__ */ new Map();
7186
+ for (const p of screen.pages.filter((x) => x.enabled)) {
7187
+ let name = p.name.trim() || p.id;
7188
+ for (let i = 2; byName.has(name); i++) name = `${p.name} (${i})`;
7189
+ byName.set(name, p.id);
7190
+ nameOf.set(p.id, name);
7191
+ }
7192
+ return { options: [...byName.keys()], byName, nameOf };
7193
+ }
7194
+ var HomeAssistantBridge = class {
7195
+ client = null;
7196
+ link = null;
7197
+ /** Discovery topics announced, to remove the ones that disappear. */
7198
+ announced = /* @__PURE__ */ new Set();
7199
+ /** Last state published per topic: only changes go out. */
7200
+ last = /* @__PURE__ */ new Map();
7201
+ onFrame = () => this.publishStates();
7202
+ onConfig = (cfg) => this.apply(cfg);
7203
+ onScreen = () => this.publishStates();
7204
+ runtime;
7205
+ version;
7206
+ makeClient;
7207
+ constructor(runtime, version, makeClient = (o) => new MqttClient(o)) {
7208
+ this.runtime = runtime;
7209
+ this.version = version;
7210
+ this.makeClient = makeClient;
7211
+ runtime.on("frame", this.onFrame);
7212
+ runtime.on("config", this.onConfig);
7213
+ runtime.on("screen", this.onScreen);
7214
+ this.apply(runtime.config);
7215
+ }
7216
+ status() {
7217
+ if (!this.link?.enabled) return { enabled: false, state: "off", error: null };
7218
+ return { enabled: true, state: this.client?.state ?? "connecting", error: this.client?.error ?? null, broker: this.link.broker };
7219
+ }
7220
+ stop() {
7221
+ this.runtime.off("frame", this.onFrame);
7222
+ this.runtime.off("config", this.onConfig);
7223
+ this.runtime.off("screen", this.onScreen);
7224
+ this.disconnect();
7225
+ }
7226
+ get base() {
7227
+ return `kiosko/${this.link.nodeId}`;
7228
+ }
7229
+ loc(l) {
7230
+ return resolveLocale(this.runtime.config).startsWith("es") ? l.es : l.en;
7231
+ }
7232
+ /** A new config: connect, reconnect (other broker or login) or just announce again. */
7233
+ apply(cfg) {
7234
+ const want = cfg.homeassistant?.enabled && cfg.homeassistant.broker ? cfg.homeassistant : null;
7235
+ const same3 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
7236
+ if (!want) {
7237
+ this.disconnect();
7238
+ this.link = null;
7239
+ return;
7240
+ }
7241
+ if (this.client && same3(this.link, want)) {
7242
+ this.announce();
7243
+ return;
7244
+ }
7245
+ this.disconnect();
7246
+ this.link = want;
7247
+ const base3 = `kiosko/${want.nodeId}`;
7248
+ const c = this.makeClient({
7249
+ url: want.broker,
7250
+ clientId: `kiosko-${want.nodeId}-${hostname().slice(0, 20)}`.slice(0, 23),
7251
+ ...want.username ? { username: want.username } : {},
7252
+ ...want.password ? { password: want.password } : {},
7253
+ keepalive: 30,
7254
+ will: { topic: `${base3}/status`, payload: "offline", retain: true }
7255
+ });
7256
+ this.client = c;
7257
+ c.on("connect", () => {
7258
+ if (this.client !== c) return;
7259
+ this.last.clear();
7260
+ c.publish(`${base3}/status`, "online", true);
7261
+ c.subscribe([`${base3}/+/page/set`, `${base3}/+/display/set`, `${base3}/+/interlude/+/press`, `${this.link.discoveryPrefix}/status`]);
7262
+ this.announce();
7263
+ });
7264
+ c.on("message", (topic, payload) => this.client === c && this.onMessage(topic, payload));
7265
+ }
7266
+ disconnect() {
7267
+ const c = this.client;
7268
+ this.client = null;
7269
+ if (!c) return;
7270
+ if (c.connected && this.link) c.publish(`${this.base}/status`, "offline", true);
7271
+ c.close();
7272
+ this.announced.clear();
7273
+ this.last.clear();
7274
+ }
7275
+ /** Every entity's discovery config, and its state. */
7276
+ announce() {
7277
+ const c = this.client;
7278
+ if (!c?.connected || !this.link) return;
7279
+ const cfg = this.runtime.config;
7280
+ const prefix = this.link.discoveryPrefix;
7281
+ const node = this.link.nodeId;
7282
+ const now = /* @__PURE__ */ new Set();
7283
+ const put = (component, objectId, body2) => {
7284
+ const topic = `${prefix}/${component}/${node}/${objectId}/config`;
7285
+ now.add(topic);
7286
+ c.publish(topic, JSON.stringify(body2), true);
7287
+ };
7288
+ const availability = { availability_topic: `${this.base}/status` };
7289
+ for (const screen of cfg.screens) {
7290
+ const sid = slug3(screen.id);
7291
+ const device = {
7292
+ identifiers: [`kiosko_${node}_${sid}`],
7293
+ name: `Kiosko ${screen.name}`,
7294
+ manufacturer: "Kiosko",
7295
+ model: `${screen.width}\xD7${screen.height}`,
7296
+ sw_version: this.version
7297
+ };
7298
+ const id = (what) => `kiosko_${node}_${sid}_${what}`;
7299
+ const { options: options2 } = pageOptions(screen, this.loc(AUTO));
7300
+ put("select", `${sid}_page`, {
7301
+ name: this.loc(NAMES.page),
7302
+ unique_id: id("page"),
7303
+ icon: "mdi:book-open-page-variant",
7304
+ command_topic: `${this.base}/${sid}/page/set`,
7305
+ state_topic: `${this.base}/${sid}/page`,
7306
+ options: options2,
7307
+ device,
7308
+ ...availability
7309
+ });
7310
+ put("sensor", `${sid}_shown`, {
7311
+ name: this.loc(NAMES.shown),
7312
+ unique_id: id("shown"),
7313
+ icon: "mdi:monitor-eye",
7314
+ state_topic: `${this.base}/${sid}/shown`,
7315
+ device,
7316
+ ...availability
7317
+ });
7318
+ put("switch", `${sid}_display`, {
7319
+ name: this.loc(NAMES.display),
7320
+ unique_id: id("display"),
7321
+ icon: "mdi:monitor",
7322
+ command_topic: `${this.base}/${sid}/display/set`,
7323
+ state_topic: `${this.base}/${sid}/display`,
7324
+ payload_on: "ON",
7325
+ payload_off: "OFF",
7326
+ device,
7327
+ ...availability
7328
+ });
7329
+ for (const slot of screen.interludes) {
7330
+ const def = this.runtime.registry.interlude(slot.type);
7331
+ const name = def ? typeof def.name === "string" ? def.name : this.loc({ en: def.name.en ?? slot.type, es: def.name.es ?? def.name.en ?? slot.type }) : slot.type;
7332
+ put("button", `${sid}_${slug3(slot.id)}`, {
7333
+ name: `${this.loc(NAMES.interlude)}: ${name}`,
7334
+ unique_id: id(slug3(slot.id)),
7335
+ icon: "mdi:play-circle-outline",
7336
+ command_topic: `${this.base}/${sid}/interlude/${slot.id}/press`,
7337
+ payload_press: "PRESS",
7338
+ device,
7339
+ ...availability
7340
+ });
7341
+ }
7342
+ }
7343
+ for (const topic of this.announced) if (!now.has(topic)) c.publish(topic, "", true);
7344
+ this.announced = now;
7345
+ this.last.clear();
7346
+ this.publishStates();
7347
+ }
7348
+ /** Each screen's page (chosen and shown) and display, when they change. */
7349
+ publishStates() {
7350
+ const c = this.client;
7351
+ if (!c?.connected || !this.link) return;
7352
+ const status = this.runtime.status();
7353
+ for (const screen of this.runtime.config.screens) {
7354
+ const sid = slug3(screen.id);
7355
+ const st = status.screens.find((x) => x.id === screen.id);
7356
+ const { nameOf } = pageOptions(screen, this.loc(AUTO));
7357
+ const states = [
7358
+ [`${this.base}/${sid}/page`, st?.pinned ? nameOf.get(st.pinned) ?? this.loc(AUTO) : this.loc(AUTO)],
7359
+ [`${this.base}/${sid}/shown`, st?.off ? "\u2014" : st?.page ? nameOf.get(st.page) ?? st.page : "\u2014"],
7360
+ [`${this.base}/${sid}/display`, st?.off ? "OFF" : "ON"]
7361
+ ];
7362
+ for (const [topic, value] of states) {
7363
+ if (this.last.get(topic) === value) continue;
7364
+ this.last.set(topic, value);
7365
+ c.publish(topic, value, true);
7366
+ }
7367
+ }
7368
+ }
7369
+ onMessage(topic, payload) {
7370
+ if (!this.link) return;
7371
+ if (topic === `${this.link.discoveryPrefix}/status`) {
7372
+ if (payload === "online") this.announce();
7373
+ return;
7374
+ }
7375
+ const m = new RegExp(`^${this.base.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/([^/]+)/(page/set|display/set|interlude/([^/]+)/press)$`).exec(topic);
7376
+ if (!m) return;
7377
+ const screen = this.runtime.config.screens.find((s) => slug3(s.id) === m[1]);
7378
+ if (!screen) return;
7379
+ if (m[2] === "page/set") {
7380
+ const { byName } = pageOptions(screen, this.loc(AUTO));
7381
+ if (!byName.has(payload)) return;
7382
+ this.runtime.pin(screen.id, byName.get(payload) ?? null);
7383
+ } else if (m[2] === "display/set") {
7384
+ if (payload !== "ON" && payload !== "OFF") return;
7385
+ this.runtime.setOff(screen.id, payload === "OFF");
7386
+ } else if (m[3]) {
7387
+ if (screen.interludes.some((s) => s.id === m[3])) this.runtime.playInterlude(screen.id, m[3]);
7388
+ }
7389
+ this.publishStates();
7390
+ }
7391
+ };
7392
+
6795
7393
  // packages/server/src/server.ts
6796
- var require3 = createRequire2(import.meta.url);
7394
+ var require3 = createRequire3(import.meta.url);
6797
7395
  var MIME = {
6798
7396
  ".html": "text/html; charset=utf-8",
6799
7397
  ".js": "text/javascript; charset=utf-8",
@@ -6862,7 +7460,9 @@ data: ${JSON.stringify(data)}
6862
7460
  runtime.on("frame", (f) => send("frame", { screenId: f.screenId, pageId: f.pageId, at: f.at, interlude: f.interlude, sleeping: f.sleeping, tiles: f.tiles }));
6863
7461
  runtime.on("log", (e) => send("log", e));
6864
7462
  runtime.on("config", () => thumbs.clear());
6865
- const statusTimer = setInterval(() => send("status", runtime.status()), 3e3);
7463
+ const bridge = o.homeassistant ?? !runtime.demoMode ? new HomeAssistantBridge(runtime, o.version) : null;
7464
+ const fullStatus = () => ({ ...runtime.status(), homeassistant: bridge?.status() ?? { enabled: false, state: "off", error: null } });
7465
+ const statusTimer = setInterval(() => send("status", fullStatus()), 3e3);
6866
7466
  const allowedHosts = /* @__PURE__ */ new Set([`127.0.0.1:${o.port}`, `localhost:${o.port}`, `[::1]:${o.port}`, `${o.host}:${o.port}`]);
6867
7467
  function state() {
6868
7468
  const locale = resolveLocale(runtime.config);
@@ -6877,7 +7477,7 @@ data: ${JSON.stringify(data)}
6877
7477
  categories: CATEGORIES,
6878
7478
  themes: THEMES,
6879
7479
  presets: PANEL_PRESETS,
6880
- status: runtime.status(),
7480
+ status: fullStatus(),
6881
7481
  paths: { config: o.configPath, plugins: paths.plugins, home: paths.home },
6882
7482
  restartNeeded,
6883
7483
  official: OFFICIAL_PLUGINS,
@@ -7099,6 +7699,7 @@ data: ${JSON.stringify({ version: o.version })}
7099
7699
  server,
7100
7700
  close() {
7101
7701
  clearInterval(statusTimer);
7702
+ bridge?.stop();
7102
7703
  for (const t2 of updateTimers) clearTimeout(t2);
7103
7704
  for (const c of clients) c.end();
7104
7705
  server.close();
@@ -7143,7 +7744,7 @@ function starterConfig(registry2, o = {}) {
7143
7744
  }
7144
7745
 
7145
7746
  // packages/server/src/cli.ts
7146
- var VERSION = "0.2.3";
7747
+ var VERSION = "0.2.5";
7147
7748
  var USAGE2 = `Kiosko ${VERSION}: a widget mosaic for USB LCD panels
7148
7749
 
7149
7750
  kiosko start [--port 7420] [--host 127.0.0.1] [--config file] [--open] [--demo]