Files
NextFloor/frontend/src/entities/symcon-values.ts
T

39 lines
1.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { HassEntity, HomeAssistant } from "../types.ts";
export const isSymcon = (hass: HomeAssistant | undefined): boolean => hass?.symconObjects !== undefined;
/** Pick the original native variable, regardless of a guessed actuator domain. */
export function isSymconVariable(hass: HomeAssistant | undefined, id: string, types: readonly number[] = [0, 1, 2, 3]): boolean {
const a = hass?.states[id]?.attributes;
return !!a?.symcon_id && !a.symcon_source_entity && types.includes(Number(a.symcon_variable_type));
}
export function nativeValue(st: HassEntity | undefined): unknown {
if (!st || st.state === "unknown" || st.state === "unavailable") return null;
return st.attributes.symcon_value ?? st.attributes.symcon_numeric_value ?? st.state;
}
export function nativeNumber(st: HassEntity | undefined): number | null {
const value = nativeValue(st);
if (value === null || typeof value === "boolean" || value === "") return null;
const n = Number(value);
return Number.isFinite(n) ? n : null;
}
export function nativeBool(st: HassEntity | undefined): boolean | null {
const value = nativeValue(st);
if (value === null) return null;
if (typeof value === "boolean") return value;
if (typeof value === "number") return value > 0;
const word = String(value).trim().toLowerCase();
if (["on", "true", "1", "home", "open", "an", "ein", "ja", "regen", "rain", "wet", "nass"].includes(word)) return true;
if (["off", "false", "0", "not_home", "closed", "aus", "nein", "trocken", "dry"].includes(word)) return false;
const n = Number(word);
return word !== "" && Number.isFinite(n) ? n > 0 : null;
}
export function nativeText(st: HassEntity | undefined): string {
if (nativeValue(st) === null) return "–";
return String(st?.attributes.symcon_formatted ?? nativeValue(st));
}