first push
This commit is contained in:
commit
2a81b4a502
845 files changed
+356635
No files matched your search
@@ -0,0 +1,200 @@
|
||||
// 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 } from "./types.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[];
|
||||
}
|
||||
|
||||
interface VariableSnapshot {
|
||||
state_revision: number;
|
||||
building_revision: number;
|
||||
variables?: SymconVariable[];
|
||||
areas?: HassArea[];
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/** Same-origin JSON call to the instance's protected WebHook. */
|
||||
async function call<T>(settings: SymconConfig, action: string, payload: Record<string, unknown> = {}): Promise<T> {
|
||||
const response = await fetch(`${settings.endpoint}/api?token=${encodeURIComponent(settings.token)}`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
||||
credentials: "same-origin",
|
||||
body: JSON.stringify({ action, ...payload }),
|
||||
});
|
||||
const body: unknown = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));
|
||||
if (!response.ok || !body || typeof body !== "object" || "error" in body) {
|
||||
const error = body && typeof body === "object" && "error" in body ? (body as { error?: unknown }).error : `HTTP ${response.status}`;
|
||||
throw new Error(String(error));
|
||||
}
|
||||
return body as T;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 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,
|
||||
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(), 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 async refresh(): Promise<void> {
|
||||
try {
|
||||
const next = await call<VariableSnapshot>(this.settings, "variables/snapshot", { revision: this.stateRevision });
|
||||
if (next.state_revision !== this.stateRevision && next.variables) {
|
||||
this.stateRevision = next.state_revision;
|
||||
this.apply({ variables: next.variables, areas: next.areas });
|
||||
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);
|
||||
}
|
||||
} catch {
|
||||
// A temporary unavailable WebHook must not blank a running visualization. The next poll retries.
|
||||
}
|
||||
}
|
||||
|
||||
private apply(data: { variables: SymconVariable[]; areas?: HassArea[] }): 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,
|
||||
]),
|
||||
);
|
||||
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;
|
||||
}
|
||||
|
||||
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" });
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user