217 lines
8.6 KiB
TypeScript
217 lines
8.6 KiB
TypeScript
// IP-Symcon adapter for the existing NextFloor web components.
|
|
//
|
|
// The viewer and editor intentionally keep the small HomeAssistant-shaped data surface they already use.
|
|
// Symcon variables are exposed as named synthetic entities (for example `light.12345`), while the browser
|
|
// only ever shows and selects their object-tree path. The numeric object id stays an implementation detail.
|
|
|
|
import type { HassArea, HassEntity, HassEntityEntry, HomeAssistant, SymconObject } from "./types.ts";
|
|
import { callSymcon as call } from "./symcon-api.ts";
|
|
import { symconControl } from "./symcon-controls.ts";
|
|
|
|
interface SymconConfig {
|
|
endpoint: string;
|
|
token: string;
|
|
language?: string;
|
|
title?: string;
|
|
}
|
|
|
|
interface SymconVariable {
|
|
entity_id: string;
|
|
name: string;
|
|
path: string;
|
|
state: string;
|
|
attributes: Record<string, unknown>;
|
|
area_id?: string | null;
|
|
device_id?: string | null;
|
|
}
|
|
|
|
interface Bootstrap {
|
|
state_revision: number;
|
|
building_revision: number;
|
|
variables: SymconVariable[];
|
|
areas: HassArea[];
|
|
objects?: SymconObject[];
|
|
}
|
|
|
|
interface VariableSnapshot {
|
|
state_revision: number;
|
|
building_revision: number;
|
|
variables?: SymconVariable[];
|
|
areas?: HassArea[];
|
|
objects?: SymconObject[];
|
|
}
|
|
|
|
type Listener = () => void;
|
|
type BuildingListener = (revision: number) => void;
|
|
|
|
declare global {
|
|
interface Window {
|
|
__NEXTFLOOR_SYMCON__?: SymconConfig;
|
|
}
|
|
}
|
|
|
|
function config(): SymconConfig {
|
|
const settings = window.__NEXTFLOOR_SYMCON__;
|
|
if (!settings?.endpoint || !settings.token) throw new Error("NextFloor Symcon host configuration is missing");
|
|
return settings;
|
|
}
|
|
|
|
/**
|
|
* Turns the instance WebHook into the interface used by the NextFloor UI. Polling is deliberate here: it
|
|
* works in the designer tab, an iframe in the Tile visualization and a remote WebFront without exposing an
|
|
* unauthenticated JSON-RPC port to the browser. The module returns only variables from the object tree.
|
|
*/
|
|
export class SymconBridge {
|
|
private readonly settings = config();
|
|
private readonly changeListeners = new Set<Listener>();
|
|
private readonly buildingListeners = new Set<BuildingListener>();
|
|
private timer: ReturnType<typeof setInterval> | undefined;
|
|
private stateRevision = -1;
|
|
private buildingRevision = -1;
|
|
private objectsSignature = "";
|
|
private refreshTask: Promise<void> | undefined;
|
|
private states: Record<string, HassEntity> = {};
|
|
private entities: Record<string, HassEntityEntry> = {};
|
|
private areas: Record<string, HassArea> = {};
|
|
|
|
private readonly facade: HomeAssistant = {
|
|
language: this.settings.language || navigator.language || "de",
|
|
user: { is_admin: true, name: this.settings.title || "IP-Symcon" },
|
|
states: this.states,
|
|
entities: this.entities,
|
|
areas: this.areas,
|
|
symconObjects: [],
|
|
symconTitle: this.settings.title?.trim() || "NextFloor",
|
|
symconRefresh: () => this.refresh(true),
|
|
config: { unit_system: { temperature: "°C" } },
|
|
themes: { darkMode: window.matchMedia?.("(prefers-color-scheme: dark)").matches ?? true },
|
|
services: {},
|
|
connection: {
|
|
subscribeMessage: async <T>(callback: (message: T) => void, message: Record<string, unknown>) => {
|
|
if (message.type === "nextfloor/building/subscribe") {
|
|
const listener: BuildingListener = (revision) => callback({ revision } as T);
|
|
this.buildingListeners.add(listener);
|
|
return async () => void this.buildingListeners.delete(listener);
|
|
}
|
|
// Announcements and the Home Assistant-only subscriptions simply have no Symcon equivalent.
|
|
return async () => undefined;
|
|
},
|
|
},
|
|
callWS: <T>(message: Record<string, unknown>) => this.callWS<T>(message),
|
|
callService: (domain, service, data) => this.callService(domain, service, data),
|
|
fetchWithAuth: (path, init) => this.fetchWithToken(path, init),
|
|
hassUrl: (path = "") => new URL(path, window.location.origin).href,
|
|
};
|
|
|
|
/** Read the initial object tree and begin refreshing changed values. */
|
|
async start(): Promise<HomeAssistant> {
|
|
const initial = await call<Bootstrap>(this.settings, "bootstrap");
|
|
this.apply(initial);
|
|
this.stateRevision = initial.state_revision;
|
|
this.buildingRevision = initial.building_revision;
|
|
this.timer = setInterval(() => void this.refresh().catch(() => undefined), 800);
|
|
return this.snapshot();
|
|
}
|
|
|
|
stop(): void {
|
|
if (this.timer) clearInterval(this.timer);
|
|
this.timer = undefined;
|
|
}
|
|
|
|
onChange(listener: Listener): () => void {
|
|
this.changeListeners.add(listener);
|
|
return () => this.changeListeners.delete(listener);
|
|
}
|
|
|
|
/** A new object identity makes Lit propagate a state refresh through all nested components. */
|
|
snapshot(): HomeAssistant {
|
|
return { ...this.facade, states: { ...this.states }, entities: { ...this.entities }, areas: { ...this.areas } };
|
|
}
|
|
|
|
private refresh(force = false): Promise<void> {
|
|
// A manual reload waits for an in-flight poll, then requests a complete fresh tree.
|
|
if (this.refreshTask) return force ? this.refreshTask.catch(() => undefined).then(() => this.refresh(true)) : this.refreshTask;
|
|
const task = this.loadSnapshot(force).finally(() => {
|
|
if (this.refreshTask === task) this.refreshTask = undefined;
|
|
});
|
|
this.refreshTask = task;
|
|
return task;
|
|
}
|
|
|
|
private async loadSnapshot(force: boolean): Promise<void> {
|
|
const next = force ? await call<Bootstrap>(this.settings, "bootstrap")
|
|
: await call<VariableSnapshot>(this.settings, "variables/snapshot", { revision: this.stateRevision });
|
|
if ((force || next.state_revision !== this.stateRevision) && next.variables) {
|
|
this.stateRevision = next.state_revision;
|
|
this.apply({ variables: next.variables, areas: next.areas, objects: next.objects });
|
|
for (const listener of this.changeListeners) listener();
|
|
}
|
|
if (next.building_revision !== this.buildingRevision) {
|
|
this.buildingRevision = next.building_revision;
|
|
for (const listener of this.buildingListeners) listener(next.building_revision);
|
|
}
|
|
}
|
|
|
|
private apply(data: { variables: SymconVariable[]; areas?: HassArea[]; objects?: SymconObject[] }): void {
|
|
this.states = Object.fromEntries(
|
|
data.variables.map((variable) => [
|
|
variable.entity_id,
|
|
{
|
|
entity_id: variable.entity_id,
|
|
state: variable.state,
|
|
attributes: { ...variable.attributes, friendly_name: variable.name, symcon_path: variable.path },
|
|
} satisfies HassEntity,
|
|
]),
|
|
);
|
|
this.entities = Object.fromEntries(
|
|
data.variables.map((variable) => [
|
|
variable.entity_id,
|
|
{
|
|
entity_id: variable.entity_id,
|
|
name: variable.name,
|
|
area_id: variable.area_id ?? null,
|
|
device_id: variable.device_id ?? null,
|
|
} satisfies HassEntityEntry,
|
|
]),
|
|
);
|
|
// Role aliases are offered only when deliberately choosing a control. They never pollute automatic room lists.
|
|
for (const state of Object.values(this.states)) {
|
|
for (const role of ["light", "cover"] as const) {
|
|
const control = symconControl(state, role);
|
|
if (!control || control.entity_id === state.entity_id || this.states[control.entity_id]) continue;
|
|
this.states[control.entity_id] = control;
|
|
this.entities[control.entity_id] = { ...this.entities[state.entity_id], entity_id: control.entity_id, hidden: true };
|
|
}
|
|
}
|
|
if (data.areas) this.areas = Object.fromEntries(data.areas.map((area) => [area.area_id, area]));
|
|
this.facade.states = this.states;
|
|
this.facade.entities = this.entities;
|
|
this.facade.areas = this.areas;
|
|
if (data.objects) {
|
|
const signature = JSON.stringify(data.objects);
|
|
if (signature !== this.objectsSignature) {
|
|
this.facade.symconObjects = data.objects;
|
|
this.objectsSignature = signature;
|
|
}
|
|
}
|
|
}
|
|
|
|
private async callWS<T>(message: Record<string, unknown>): Promise<T> {
|
|
const type = String(message.type ?? "");
|
|
if (!type.startsWith("nextfloor/")) throw new Error(`Unsupported Symcon websocket command: ${type}`);
|
|
const { type: _ignored, ...payload } = message;
|
|
return call<T>(this.settings, type.slice("nextfloor/".length), payload);
|
|
}
|
|
|
|
private async callService(domain: string, service: string, data: Record<string, unknown> = {}): Promise<unknown> {
|
|
return call(this.settings, "variables/action", { domain, service, data });
|
|
}
|
|
|
|
/** Mesh uploads are intentionally not exposed until the Symcon asset store exists. Other paths stay same-origin. */
|
|
private fetchWithToken(path: string, init: Record<string, unknown> = {}): Promise<Response> {
|
|
const url = new URL(path, window.location.origin);
|
|
url.searchParams.set("token", this.settings.token);
|
|
return fetch(url, { ...init, credentials: "same-origin" });
|
|
}
|
|
}
|