hue lights: http-first bridge transport, rate-limit backoff, clearer errors
CI/CD Pipeline / Build and Push PocketBase Docker Image (push) Successful in 10s
CI/CD Pipeline / i18n Catalog Check (push) Successful in 45s
CI/CD Pipeline / Build and Push App Docker Image (push) Successful in 2m7s
CI/CD Pipeline / Deploy to Kubernetes (push) Successful in 47s

This commit is contained in:
2026-11-14 16:32:27 -06:00
parent 81d3cf85b3
commit 0dcc631675
8 changed files with 158 additions and 75 deletions
@@ -37,8 +37,8 @@ export const LightsControls = () => {
setBusy(true);
try {
await runLights(settings);
} catch {
toast.error(t`Couldn't reach the Hue bridge`);
} catch (error) {
toast.error(t`Hue lights failed: ${error instanceof Error ? error.message : String(error)}`);
} finally {
setBusy(false);
}
@@ -17,7 +17,7 @@ import { TrashIcon } from "@phosphor-icons/react";
import { Trans, useLingui } from "@lingui/react/macro";
import Button from "@/components/button";
import toast from "@/lib/sonner";
import { bridgeOrigin, fetchLights, HueLight, pairBridge } from "../hue";
import { bridgeCertUrl, fetchLights, HueLight, pairBridge } from "../hue";
import { LightsPreset, LightsSettings, LightsZone, newZone, runLights } from "../lights";
const SWATCHES = ["#ff2a2a", "#ffffff", "#2a7bff", "#20d060", "#ffb000", "#c03cff"];
@@ -188,8 +188,8 @@ export const LightsSettingsForm = ({ settings, onChange }: LightsSettingsFormPro
setTesting(zoneId ?? "all");
try {
await runLights(settings, zoneId);
} catch {
toast.error(t`Couldn't reach the Hue bridge`);
} catch (error) {
toast.error(t`Hue lights failed: ${error instanceof Error ? error.message : String(error)}`);
} finally {
setTesting(null);
}
@@ -229,11 +229,11 @@ export const LightsSettingsForm = ({ settings, onChange }: LightsSettingsFormPro
{settings.bridgeIp && !settings.appKey && (
<Text size="xs" c="dimmed">
<Trans>
First time on this laptop:{" "}
<Anchor href={`${bridgeOrigin(settings.bridgeIp)}/api/0/config`} target="_blank" size="xs">
If pairing can't reach the bridge,{" "}
<Anchor href={bridgeCertUrl(settings.bridgeIp)} target="_blank" size="xs">
open the bridge
</Anchor>{" "}
and accept the certificate warning, then come back.
</Anchor>
, accept the certificate warning, then try again.
</Trans>
</Text>
)}
+73 -19
View File
@@ -16,22 +16,74 @@ export interface HueLightState {
effect?: string;
}
export const bridgeOrigin = (ip: string) =>
`${typeof window !== "undefined" && window.location.protocol === "http:" ? "http" : "https"}://${ip.trim()}`;
export const bridgeCertUrl = (ip: string) => `https://${ip.trim()}/api/0/config`;
const request = async (url: string, init?: RequestInit) => {
const res = await fetch(url, {
...init,
headers: init?.body ? { "Content-Type": "application/json" } : undefined,
const pageIsHttps = () => typeof window !== "undefined" && window.location.protocol === "https:";
let preferHttps = false;
const MAX_IN_FLIGHT = 4;
const RETRIES = 4;
let inFlight = 0;
const waiting: (() => void)[] = [];
const MIN_GAP_MS = 60;
let nextStart = 0;
const acquire = async () => {
while (inFlight >= MAX_IN_FLIGHT) await new Promise<void>((resolve) => waiting.push(resolve));
inFlight++;
const wait = nextStart - Date.now();
nextStart = Math.max(Date.now(), nextStart) + MIN_GAP_MS;
if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait));
};
const release = () => {
inFlight--;
waiting.shift()?.();
};
const fetchWithBackoff = async (url: string, init?: RequestInit) => {
for (let attempt = 0; ; attempt++) {
await acquire();
let res: Response;
try {
res = await fetch(url, {
...init,
headers: init?.body ? { "Content-Type": "application/json" } : undefined,
});
} finally {
release();
}
if (res.status !== 429 || attempt >= RETRIES) return res;
await new Promise((resolve) => setTimeout(resolve, 200 * 2 ** attempt));
}
};
const send = async (ip: string, path: string, init?: RequestInit) => {
const host = ip.trim();
if (!pageIsHttps()) return fetchWithBackoff(`http://${host}${path}`, init);
if (!preferHttps) {
try {
return await fetchWithBackoff(`http://${host}${path}`, { ...init, targetAddressSpace: "local" } as RequestInit);
} catch {}
}
const res = await fetchWithBackoff(`https://${host}${path}`, init);
preferHttps = true;
return res;
};
const request = async (ip: string, path: string, init?: RequestInit) => {
const res = await send(ip, path, init);
const body = await res.json().catch(() => {
throw new Error(`HTTP ${res.status}`);
});
const body = await res.json();
const error = Array.isArray(body) ? body.find((item) => item?.error)?.error : undefined;
if (error) throw new Error(error.description ?? "Hue bridge error");
return body;
};
export const pairBridge = async (ip: string): Promise<string> => {
const body = await request(`${bridgeOrigin(ip)}/api`, {
const body = await request(ip, "/api", {
method: "POST",
body: JSON.stringify({ devicetype: "flxn#runner" }),
});
@@ -41,8 +93,10 @@ export const pairBridge = async (ip: string): Promise<string> => {
};
export const fetchLights = async (ip: string, key: string): Promise<HueLight[]> => {
const base = `${bridgeOrigin(ip)}/api/${key}`;
const [lights, groups] = await Promise.all([request(`${base}/lights`), request(`${base}/groups`)]);
const [lights, groups] = await Promise.all([
request(ip, `/api/${key}/lights`),
request(ip, `/api/${key}/groups`),
]);
const roomOf = new Map<string, string>();
for (const group of Object.values<any>(groups)) {
if (group.type !== "Room") continue;
@@ -58,28 +112,28 @@ export const fetchLights = async (ip: string, key: string): Promise<HueLight[]>
.sort((a, b) => (a.room ?? "~").localeCompare(b.room ?? "~") || a.name.localeCompare(b.name));
};
export const getLightState = async (ip: string, key: string, id: string): Promise<HueLightState> => {
const light = await request(`${bridgeOrigin(ip)}/api/${key}/lights/${id}`);
return light.state;
export const getLightStates = async (ip: string, key: string): Promise<Record<string, HueLightState>> => {
const lights = await request(ip, `/api/${key}/lights`);
return Object.fromEntries(Object.entries<any>(lights).map(([id, light]) => [id, light.state]));
};
export const setLightState = (ip: string, key: string, id: string, state: Record<string, unknown>) =>
request(`${bridgeOrigin(ip)}/api/${key}/lights/${id}/state`, {
request(ip, `/api/${key}/lights/${id}/state`, {
method: "PUT",
body: JSON.stringify(state),
});
export const ensureGroup = async (ip: string, key: string, name: string, lightIds: string[]): Promise<string> => {
const base = `${bridgeOrigin(ip)}/api/${key}/groups`;
const groups = await request(base);
const base = `/api/${key}/groups`;
const groups = await request(ip, base);
const existing = Object.entries<any>(groups).find(([, group]) => group.name === name);
if (existing) {
const [id, group] = existing;
const same = group.lights?.length === lightIds.length && lightIds.every((light) => group.lights.includes(light));
if (!same) await request(`${base}/${id}`, { method: "PUT", body: JSON.stringify({ lights: lightIds }) });
if (!same) await request(ip, `${base}/${id}`, { method: "PUT", body: JSON.stringify({ lights: lightIds }) });
return id;
}
const created = await request(base, {
const created = await request(ip, base, {
method: "POST",
body: JSON.stringify({ name, type: "LightGroup", lights: lightIds }),
});
@@ -89,7 +143,7 @@ export const ensureGroup = async (ip: string, key: string, name: string, lightId
};
export const setGroupAction = (ip: string, key: string, groupId: string, action: Record<string, unknown>) =>
request(`${bridgeOrigin(ip)}/api/${key}/groups/${groupId}/action`, {
request(ip, `/api/${key}/groups/${groupId}/action`, {
method: "PUT",
body: JSON.stringify(action),
});
+36 -23
View File
@@ -1,4 +1,4 @@
import { ensureGroup, getLightState, hexToXy, HueLightState, setGroupAction, setLightState } from "./hue";
import { ensureGroup, getLightStates, hexToXy, HueLightState, setGroupAction, setLightState } from "./hue";
export type LightsPreset = "color_flash" | "chase" | "blink" | "breathe";
@@ -132,9 +132,17 @@ export const restoreInterruptedLights = async () => {
}
};
const errorText = (reason: unknown) => (reason instanceof Error ? reason.message : String(reason));
const runZone = async (bridgeIp: string, appKey: string, zone: LightsZone) => {
const { lightIds, repeats, speedMs } = zone;
if (!lightIds.length) return;
const { repeats, speedMs } = zone;
if (!zone.lightIds.length) return;
const states = await getLightStates(bridgeIp, appKey);
const unreadable = zone.lightIds.filter((id) => !states[id]);
const lightIds = zone.lightIds.filter((id) => states[id]);
if (!lightIds.length) throw new Error(`lights ${unreadable.join(", ")} not found on the bridge`);
const snapshot = new Map(lightIds.map((id) => [id, states[id]] as const));
const send = async (id: string, state: Record<string, unknown>) => {
await setLightState(bridgeIp, appKey, id, state).catch(() => {});
@@ -144,9 +152,6 @@ const runZone = async (bridgeIp: string, appKey: string, zone: LightsZone) => {
Promise.all(lightIds.map((id) => setLightState(bridgeIp, appKey, id, state(id)).catch(() => {})));
const togetherGap = Math.max(speedMs, lightIds.length * COMMAND_GAP_MS);
const snapshot = new Map(
await Promise.all(lightIds.map(async (id) => [id, await getLightState(bridgeIp, appKey, id)] as const))
);
const lit = (id: string) => ({
on: true,
bri: 254,
@@ -162,9 +167,11 @@ const runZone = async (bridgeIp: string, appKey: string, zone: LightsZone) => {
try {
if (zone.preset === "blink" || zone.preset === "breathe") {
const groupId = await ensureGroup(bridgeIp, appKey, `FLXN ${zone.id}`, lightIds);
const groupId = await ensureGroup(bridgeIp, appKey, `FLXN ${zone.id}`, lightIds).catch(() => null);
const group = (action: Record<string, unknown>) =>
setGroupAction(bridgeIp, appKey, groupId, action).catch(() => {});
groupId
? setGroupAction(bridgeIp, appKey, groupId, action).catch(() => {})
: sendTogether(() => action);
await sendTogether(lit);
await sleep(togetherGap);
if (zone.preset === "blink") {
@@ -177,21 +184,20 @@ const runZone = async (bridgeIp: string, appKey: string, zone: LightsZone) => {
await sleep(repeats * 1000);
await group({ alert: "none" });
}
return;
}
for (let i = 0; i < repeats; i++) {
if (zone.preset === "chase") {
for (const id of lightIds) {
await send(id, lit(id));
await sleep(Math.max(0, speedMs - COMMAND_GAP_MS));
await send(id, restore(id, 1));
} else {
for (let i = 0; i < repeats; i++) {
if (zone.preset === "chase") {
for (const id of lightIds) {
await send(id, lit(id));
await sleep(Math.max(0, speedMs - COMMAND_GAP_MS));
await send(id, restore(id, 1));
}
} else {
await sendTogether(lit);
await sleep(togetherGap);
await sendTogether((id) => restore(id, 0));
await sleep(togetherGap);
}
} else {
await sendTogether(lit);
await sleep(togetherGap);
await sendTogether((id) => restore(id, 0));
await sleep(togetherGap);
}
}
} finally {
@@ -200,6 +206,7 @@ const runZone = async (bridgeIp: string, appKey: string, zone: LightsZone) => {
for (const id of lightIds) delete pending[id];
writePendingRestore(pending);
}
if (unreadable.length) throw new Error(`lights ${unreadable.join(", ")} not found on the bridge`);
};
let running = false;
@@ -209,7 +216,13 @@ export const runLights = async (settings: LightsSettings, zoneId?: string): Prom
running = true;
try {
const zones = settings.zones.filter((zone) => !zoneId || zone.id === zoneId);
await Promise.all(zones.map((zone) => runZone(settings.bridgeIp, settings.appKey, zone)));
const results = await Promise.allSettled(
zones.map((zone) => runZone(settings.bridgeIp, settings.appKey, zone))
);
const failures = results.flatMap((result, i) =>
result.status === "rejected" ? [`${zones[i].name}: ${errorText(result.reason)}`] : []
);
if (failures.length) throw new Error(failures.join(" · "));
return true;
} finally {
running = false;
+10 -6
View File
@@ -877,10 +877,8 @@ msgstr "Benachrichtigungen konnten nicht deaktiviert werden"
msgid "Couldn't enable notifications"
msgstr "Benachrichtigungen konnten nicht aktiviert werden"
#: src/features/lights/components/lights-controls.tsx:41
#: src/features/lights/components/lights-settings-form.tsx:168
#: src/features/lights/components/lights-settings-form.tsx:180
#: src/features/lights/components/lights-settings-form.tsx:192
msgid "Couldn't reach the Hue bridge"
msgstr "Hue Bridge nicht erreichbar"
@@ -1312,10 +1310,6 @@ msgstr "Vorname muss 2-20 Zeichen lang sein und darf nur Buchstaben enthalten"
msgid "First name must be 3-20 characters long and contain only letters"
msgstr "Vorname muss 3-20 Zeichen lang sein und darf nur Buchstaben enthalten"
#: src/features/lights/components/lights-settings-form.tsx:231
msgid "First time on this laptop: <0>open the bridge</0> and accept the certificate warning, then come back."
msgstr "Zum ersten Mal auf diesem Laptop: <0>Bridge öffnen</0>, die Zertifikatswarnung akzeptieren und dann zurückkommen."
#: src/features/lights/components/lights-settings-form.tsx:71
msgid "Flash"
msgstr "Aufblitzen"
@@ -1481,6 +1475,16 @@ msgstr "So funktionieren Tipps"
msgid "HTTP {0}: {1}"
msgstr "HTTP {0}: {1}"
#. placeholder {0}: error instanceof Error ? error.message : String(error)
#: src/features/lights/components/lights-controls.tsx:41
#: src/features/lights/components/lights-settings-form.tsx:192
msgid "Hue lights failed: {0}"
msgstr "Hue-Lichter fehlgeschlagen: {0}"
#: src/features/lights/components/lights-settings-form.tsx:231
msgid "If pairing can't reach the bridge, <0>open the bridge</0>, accept the certificate warning, then try again."
msgstr "Falls das Koppeln die Bridge nicht erreicht, <0>öffne die Bridge</0>, akzeptiere die Zertifikatswarnung und versuche es erneut."
#: src/features/login/components/player-prompt/index.tsx:82
msgid "If this is your first time participating, please select <0>New Player</0>, otherwise select <1>Returning Player</1>"
msgstr "Wenn du zum ersten Mal dabei bist, wähle <0>Neuer Spieler</0>, andernfalls wähle <1>Wiederkehrender Spieler</1>"
+10 -6
View File
@@ -877,10 +877,8 @@ msgstr "Couldn't disable notifications"
msgid "Couldn't enable notifications"
msgstr "Couldn't enable notifications"
#: src/features/lights/components/lights-controls.tsx:41
#: src/features/lights/components/lights-settings-form.tsx:168
#: src/features/lights/components/lights-settings-form.tsx:180
#: src/features/lights/components/lights-settings-form.tsx:192
msgid "Couldn't reach the Hue bridge"
msgstr "Couldn't reach the Hue bridge"
@@ -1312,10 +1310,6 @@ msgstr "First name must be 2-20 characters long and contain only letters"
msgid "First name must be 3-20 characters long and contain only letters"
msgstr "First name must be 3-20 characters long and contain only letters"
#: src/features/lights/components/lights-settings-form.tsx:231
msgid "First time on this laptop: <0>open the bridge</0> and accept the certificate warning, then come back."
msgstr "First time on this laptop: <0>open the bridge</0> and accept the certificate warning, then come back."
#: src/features/lights/components/lights-settings-form.tsx:71
msgid "Flash"
msgstr "Flash"
@@ -1481,6 +1475,16 @@ msgstr "How predictions work"
msgid "HTTP {0}: {1}"
msgstr "HTTP {0}: {1}"
#. placeholder {0}: error instanceof Error ? error.message : String(error)
#: src/features/lights/components/lights-controls.tsx:41
#: src/features/lights/components/lights-settings-form.tsx:192
msgid "Hue lights failed: {0}"
msgstr "Hue lights failed: {0}"
#: src/features/lights/components/lights-settings-form.tsx:231
msgid "If pairing can't reach the bridge, <0>open the bridge</0>, accept the certificate warning, then try again."
msgstr "If pairing can't reach the bridge, <0>open the bridge</0>, accept the certificate warning, then try again."
#: src/features/login/components/player-prompt/index.tsx:82
msgid "If this is your first time participating, please select <0>New Player</0>, otherwise select <1>Returning Player</1>"
msgstr "If this is your first time participating, please select <0>New Player</0>, otherwise select <1>Returning Player</1>"
+10 -6
View File
@@ -877,10 +877,8 @@ msgstr "No se pudieron desactivar las notificaciones"
msgid "Couldn't enable notifications"
msgstr "No se pudieron activar las notificaciones"
#: src/features/lights/components/lights-controls.tsx:41
#: src/features/lights/components/lights-settings-form.tsx:168
#: src/features/lights/components/lights-settings-form.tsx:180
#: src/features/lights/components/lights-settings-form.tsx:192
msgid "Couldn't reach the Hue bridge"
msgstr "No se pudo conectar con el bridge de Hue"
@@ -1312,10 +1310,6 @@ msgstr "El nombre debe tener entre 2 y 20 caracteres y contener solo letras"
msgid "First name must be 3-20 characters long and contain only letters"
msgstr "El nombre debe tener entre 3 y 20 caracteres y contener solo letras"
#: src/features/lights/components/lights-settings-form.tsx:231
msgid "First time on this laptop: <0>open the bridge</0> and accept the certificate warning, then come back."
msgstr "Primera vez en esta laptop: <0>abre el bridge</0>, acepta la advertencia del certificado y vuelve."
#: src/features/lights/components/lights-settings-form.tsx:71
msgid "Flash"
msgstr "Destello"
@@ -1481,6 +1475,16 @@ msgstr "Cómo funcionan las predicciones"
msgid "HTTP {0}: {1}"
msgstr "HTTP {0}: {1}"
#. placeholder {0}: error instanceof Error ? error.message : String(error)
#: src/features/lights/components/lights-controls.tsx:41
#: src/features/lights/components/lights-settings-form.tsx:192
msgid "Hue lights failed: {0}"
msgstr "Fallaron las luces Hue: {0}"
#: src/features/lights/components/lights-settings-form.tsx:231
msgid "If pairing can't reach the bridge, <0>open the bridge</0>, accept the certificate warning, then try again."
msgstr "Si la vinculación no llega al bridge, <0>abre el bridge</0>, acepta la advertencia del certificado y vuelve a intentarlo."
#: src/features/login/components/player-prompt/index.tsx:82
msgid "If this is your first time participating, please select <0>New Player</0>, otherwise select <1>Returning Player</1>"
msgstr "Si es tu primera vez participando, selecciona <0>Nuevo jugador</0>; si no, selecciona <1>Ya soy jugador</1>"
+10 -6
View File
@@ -877,10 +877,8 @@ msgstr "通知を無効にできませんでした"
msgid "Couldn't enable notifications"
msgstr "通知を有効にできませんでした"
#: src/features/lights/components/lights-controls.tsx:41
#: src/features/lights/components/lights-settings-form.tsx:168
#: src/features/lights/components/lights-settings-form.tsx:180
#: src/features/lights/components/lights-settings-form.tsx:192
msgid "Couldn't reach the Hue bridge"
msgstr "Hueブリッジに接続できません"
@@ -1312,10 +1310,6 @@ msgstr "名は2〜20文字の英字のみで入力してください"
msgid "First name must be 3-20 characters long and contain only letters"
msgstr "名は3〜20文字の英字のみで入力してください"
#: src/features/lights/components/lights-settings-form.tsx:231
msgid "First time on this laptop: <0>open the bridge</0> and accept the certificate warning, then come back."
msgstr "このノートPCで初めての場合: <0>ブリッジを開いて</0>証明書の警告を許可し、戻ってきてください。"
#: src/features/lights/components/lights-settings-form.tsx:71
msgid "Flash"
msgstr "フラッシュ"
@@ -1481,6 +1475,16 @@ msgstr "予想のしくみ"
msgid "HTTP {0}: {1}"
msgstr "HTTP {0}: {1}"
#. placeholder {0}: error instanceof Error ? error.message : String(error)
#: src/features/lights/components/lights-controls.tsx:41
#: src/features/lights/components/lights-settings-form.tsx:192
msgid "Hue lights failed: {0}"
msgstr "Hueライトのエラー: {0}"
#: src/features/lights/components/lights-settings-form.tsx:231
msgid "If pairing can't reach the bridge, <0>open the bridge</0>, accept the certificate warning, then try again."
msgstr "ペアリングでブリッジに接続できない場合は、<0>ブリッジを開いて</0>証明書の警告を許可し、もう一度お試しください。"
#: src/features/login/components/player-prompt/index.tsx:82
msgid "If this is your first time participating, please select <0>New Player</0>, otherwise select <1>Returning Player</1>"
msgstr "初めて参加する場合は<0>新しいプレイヤー</0>を、そうでない場合は<1>既存プレイヤー</1>を選択してください"