diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a47745d..3c326ba 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,7 +34,21 @@ jobs: name: HACS runs-on: ubuntu-latest steps: - - uses: hacs/action@1ebf01c408f29afcb6406bd431bc98fd8cbb15aa # main 2026-06-08 + # HACS installs a plugin from its latest release, so the check needs one. Before the first + # release (and in the run that creates it) there is nothing to check yet. + - name: Find a release + id: release + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + run: | + if gh release view --repo "$REPO" --json tagName >/dev/null 2>&1; then + echo "exists=true" >> "$GITHUB_OUTPUT" + else + echo "::notice::No release yet; the HACS check runs from the first release on." + fi + - if: steps.release.outputs.exists == 'true' + uses: hacs/action@1ebf01c408f29afcb6406bd431bc98fd8cbb15aa # main 2026-06-08 with: category: plugin diff --git a/CHANGELOG.md b/CHANGELOG.md index b8e32e0..33e68df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,9 @@ First release. automatic layout for other switches, and a layout of your own in YAML. - A click on a port opens its device sensor; a settings dialog with a switch picker; English and German. +- While Home Assistant starts or the switch is set up again, the card keeps its last picture, + tries again after 15 seconds and reads the ports again once the switch is back; it says when + the integration is too old. [Unreleased]: https://github.com/eizedev/managed-switch-card/compare/v0.1.0...HEAD [0.1.0]: https://github.com/eizedev/managed-switch-card/releases/tag/v0.1.0 diff --git a/README.md b/README.md index a5817fa..69f599f 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,9 @@ device_id: 0123456789abcdef0123456789abcdef # the switch, chosen in the card's title: Hallway # optional, else the switch's name show_names: true # device names under the ports (default) show_rates: false # data rates; the integration's rate sensors must be on +layout: # optional: your own front panel, by port name + rows: [["1", "3", "5", "7"], ["2", "4", "6", "8"]] + sfp: ["9", "10"] ``` Details, colours and your own layout: [documentation](https://ha-managed-switch.eize.dev/card/). diff --git a/assets/card.png b/assets/card.png index a058816..1ed9881 100644 Binary files a/assets/card.png and b/assets/card.png differ diff --git a/src/loader.ts b/src/loader.ts new file mode 100644 index 0000000..e003abe --- /dev/null +++ b/src/loader.ts @@ -0,0 +1,70 @@ +// When the card asks the integration for a switch's ports, and what it keeps from the answer; +// apart from the card so it can be tested without a browser. + +import type { PortsReply, Words } from "./model"; + +/** The ports are read again this often. */ +export const REFRESH_MS = 5 * 60 * 1000; +/** After a failed read (Home Assistant starting, switch not set up yet) the card tries again. */ +export const RETRY_MS = 15 * 1000; + +export type CallWS = (message: Record) => Promise; + +interface WsError { + code?: string; + message?: string; +} + +/** The text the card shows for a failed read. */ +export function errorText(err: unknown, words: Words): string { + const { code, message } = (err ?? {}) as WsError; + if (code === "unknown_command") return words.oldIntegration; + if (code === "not_found") return words.notFound; + return message ?? String(err); +} + +export class PortsLoader { + /** The last good answer for the current switch; kept while a later read fails. */ + reply?: PortsReply; + /** Why the last read failed, if it did. */ + error?: unknown; + private deviceId?: string; + private loadedAt = 0; + private pending = false; + + constructor(private readonly changed: () => void) {} + + /** Forget the switch, for a new configuration. */ + reset(): void { + this.reply = undefined; + this.error = undefined; + this.deviceId = undefined; + this.loadedAt = 0; + } + + /** + * Read the ports of `deviceId` when due: for a new switch, every REFRESH_MS, RETRY_MS after a + * failure, or at once with `again` (the switch was set up again). One read at a time. + */ + load(callWS: CallWS, deviceId: string, now: number, again = false): void { + if (this.pending && this.deviceId === deviceId) return; + const wait = this.error === undefined ? REFRESH_MS : RETRY_MS; + if (this.deviceId === deviceId && !again && now - this.loadedAt < wait) return; + if (this.deviceId !== deviceId) this.reply = undefined; + this.deviceId = deviceId; + this.loadedAt = now; + this.pending = true; + callWS({ type: "managed_switch/ports", device_id: deviceId }).then( + (reply) => this.settle(deviceId, reply, undefined), + (err: unknown) => this.settle(deviceId, undefined, err ?? "error"), + ); + } + + private settle(deviceId: string, reply: PortsReply | undefined, error: unknown): void { + if (deviceId !== this.deviceId) return; // an answer for a switch the card no longer shows + this.pending = false; + if (reply) this.reply = reply; + this.error = error; + this.changed(); + } +} diff --git a/src/managed-switch-card.ts b/src/managed-switch-card.ts index d19ee6d..666f8f1 100644 --- a/src/managed-switch-card.ts +++ b/src/managed-switch-card.ts @@ -3,9 +3,13 @@ import { LitElement, css, html, nothing, type PropertyValues, type TemplateResult } from "lit"; +import { PortsLoader, errorText } from "./loader"; import { + availability, + cardSize, deviceLabel, layoutFor, + numeric, portTitle, powered, rateLabel, @@ -14,6 +18,7 @@ import { type Layout, type PortInfo, type PortsReply, + type StateLike, type States, } from "./model"; @@ -23,6 +28,7 @@ interface Hass { states: States; entities?: Record; language?: string; + formatEntityState?(state: StateLike): string; callWS(message: Record): Promise; } @@ -35,23 +41,16 @@ interface CardConfig { layout?: Layout; } -// The ports are read again this often, and when the card's switch is set up again. -const REFRESH_MS = 5 * 60 * 1000; - export class ManagedSwitchCard extends LitElement { static override properties = { hass: { attribute: false }, _config: { state: true }, - _reply: { state: true }, - _error: { state: true }, }; hass?: Hass; private _config?: CardConfig; - private _reply?: PortsReply; - private _error?: string; - private _loadedFor?: string; - private _loadedAt = 0; + private _loader = new PortsLoader(() => this.requestUpdate()); + private _available = ""; static getConfigElement(): HTMLElement { return document.createElement("managed-switch-card-editor"); @@ -67,12 +66,15 @@ export class ManagedSwitchCard extends LitElement { setConfig(config: CardConfig): void { this._config = { show_names: true, show_rates: false, ...config }; - this._reply = undefined; - this._loadedFor = undefined; + this._loader.reset(); + this._available = ""; } getCardSize(): number { - return 3; + const reply = this._loader.reply; + if (!reply) return 3; + const trunks = reply.ports.filter((p) => p.kind === "trunk").length; + return cardSize(layoutFor(reply, this._config?.layout), trunks); } getGridOptions(): Record { @@ -83,21 +85,17 @@ export class ManagedSwitchCard extends LitElement { super.updated(changed); const id = this._config?.device_id; if (!this.hass || !id) return; - if (this._loadedFor !== id || Date.now() - this._loadedAt > REFRESH_MS) { - this._loadedFor = id; - this._loadedAt = Date.now(); - this.hass - .callWS({ type: "managed_switch/ports", device_id: id }) - .then((reply) => { - this._reply = reply; - this._error = undefined; - }) - .catch((err: { message?: string }) => { - this._error = err.message ?? String(err); - }); - } + const hass = this.hass; + // Entities coming back mean the switch was set up again: its ports may have changed. + const available = availability(this._loader.reply, hass.states); + const again = this._available !== "" && available !== this._available && !available.includes("0"); + this._available = available; + this._loader.load((m) => hass.callWS(m), id, Date.now(), again); } + private _format = (state: StateLike): string => + this.hass?.formatEntityState?.(state) ?? state.state; + private _open(entityId: string | null | undefined): void { if (!entityId) return; this.dispatchEvent( @@ -113,11 +111,12 @@ export class ManagedSwitchCard extends LitElement { const rates = this._config?.show_rates ? [rateLabel(states[e.received ?? ""]), rateLabel(states[e.sent ?? ""])] : ["", ""]; + const title = portTitle(port, states, w, this._format); return html` ` : nothing} + ${error !== undefined ? html`
${errorText(error, w)}
` : nothing}
${layout.rows.map( @@ -222,6 +223,7 @@ export class ManagedSwitchCard extends LitElement { font-size: 0.85em; } .poe-total { + all: unset; display: flex; align-items: center; gap: 4px; @@ -229,6 +231,10 @@ export class ManagedSwitchCard extends LitElement { color: var(--secondary-text-color); white-space: nowrap; } + .poe-total:focus-visible { + outline: 2px solid var(--primary-color); + outline-offset: 2px; + } .poe-total ha-icon { --mdc-icon-size: 18px; color: var(--warning-color, #e5c07b); @@ -309,6 +315,10 @@ export class ManagedSwitchCard extends LitElement { background: var(--error-color, #db4437); border-color: var(--error-color, #db4437); } + .up .jack { + background: var(--info-color, #039be5); + border-color: var(--info-color, #039be5); + } .down .jack { background: var(--card-background-color); } @@ -338,6 +348,10 @@ export class ManagedSwitchCard extends LitElement { } .name { font-weight: 500; + max-width: 100%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .device, .rate { @@ -392,16 +406,8 @@ export class ManagedSwitchCardEditor extends LitElement { ]; } - private _label = (field: { name: string }): string => { - const de = (this.hass?.language ?? "en").startsWith("de"); - const labels: Record = { - device_id: ["Switch", "Switch"], - title: ["Title (optional)", "Titel (optional)"], - show_names: ["Device names under the ports", "Gerätenamen unter den Ports"], - show_rates: ["Data rates (sensors must be on)", "Datenraten (Sensoren müssen an sein)"], - }; - return labels[field.name]?.[de ? 1 : 0] ?? field.name; - }; + private _label = (field: { name: string }): string => + words(this.hass?.language).fields[field.name] ?? field.name; private _changed(event: CustomEvent<{ value: CardConfig }>): void { this.dispatchEvent( @@ -440,12 +446,14 @@ interface CustomCardEntry { const registry = window as unknown as { customCards?: CustomCardEntry[] }; registry.customCards = registry.customCards ?? []; -registry.customCards.push({ - type: "managed-switch-card", - name: "Managed Switch", - description: "The front panel of a managed switch: ports by link and speed, PoE, connected devices.", - preview: true, - documentationURL: "https://ha-managed-switch.eize.dev/card/", -}); +if (!registry.customCards.some((card) => card.type === "managed-switch-card")) { + registry.customCards.push({ + type: "managed-switch-card", + name: "Managed Switch", + description: "The front panel of a managed switch: ports by link and speed, PoE, connected devices.", + preview: true, + documentationURL: "https://ha-managed-switch.eize.dev/card/", + }); +} console.info(`%c MANAGED-SWITCH-CARD %c ${__VERSION__} `, "color:#fff;background:#4078f2", ""); diff --git a/src/model.ts b/src/model.ts index 903fd19..b6a01a1 100644 --- a/src/model.ts +++ b/src/model.ts @@ -84,17 +84,27 @@ export function layoutFor(reply: PortsReply, override?: Layout): Layout { return { rows: rows.filter((r) => r.length), sfp: [] }; } -export type Tone = "fast" | "slow" | "slowest" | "down" | "unknown"; +export type Tone = "fast" | "slow" | "slowest" | "up" | "down" | "unknown"; -/** The colour class of a port: 1 Gbit/s and more, 100 Mbit/s, 10 Mbit/s, no link. */ +/** + * The colour class of a port: 1 Gbit/s and more, 100 Mbit/s, 10 Mbit/s, a link of unknown speed + * (speed sensor off or unavailable), no link, unknown. + */ export function tone(link: StateLike | undefined, speed: StateLike | undefined): Tone { if (!link || link.state === "unavailable" || link.state === "unknown") return "unknown"; if (link.state !== "on") return "down"; - const mbits = Number(speed?.state); - if (!Number.isFinite(mbits) || mbits >= 1000) return "fast"; + const mbits = speed?.state ? Number(speed.state) : NaN; + if (!Number.isFinite(mbits)) return "up"; + if (mbits >= 1000) return "fast"; return mbits >= 100 ? "slow" : "slowest"; } +/** A number for display, or undefined for a state that is none ("unknown", "unavailable"). */ +export function numeric(state: StateLike | undefined): number | undefined { + const value = state?.state ? Number(state.state) : NaN; + return Number.isFinite(value) ? value : undefined; +} + /** Whether a PoE port delivers power right now. */ export function powered(poe: StateLike | undefined): boolean { return poe?.state === "delivering_power"; @@ -115,15 +125,27 @@ export function rateLabel(rate: StateLike | undefined): string { return mbits >= 100 ? `${Math.round(mbits)}` : mbits.toFixed(mbits >= 10 ? 0 : 1); } -/** The text a pointer or screen reader gets for a port. */ -export function portTitle(port: PortInfo, states: States, words: Words): string { +/** How a state reads in the user's language; Home Assistant's `formatEntityState`. */ +export type FormatState = (state: StateLike) => string; + +/** The text a pointer or screen reader gets for a port, one fact per line. */ +export function portTitle( + port: PortInfo, + states: States, + words: Words, + format: FormatState = (s) => s.state, +): string { const lines = [`${words.port} ${port.name}${port.alias ? ` · ${port.alias}` : ""}`]; const link = states[port.entities.link ?? ""]; const speed = states[port.entities.speed ?? ""]; const t = tone(link, speed); - lines.push(t === "down" ? words.noLink : t === "unknown" ? words.unknown : `${speed?.state} Mbit/s`); + const text = { down: words.noLink, unknown: words.unknown, up: words.linkUp }; + lines.push(t in text ? text[t as keyof typeof text] : `${speed?.state} Mbit/s`); if (port.uplink) lines.push(words.uplink); - if (port.poe) lines.push(`PoE: ${states[port.entities.poe ?? ""]?.state ?? "?"}`); + if (port.poe) { + const poe = states[port.entities.poe ?? ""]; + lines.push(`PoE: ${poe ? format(poe) : "?"}`); + } const device = states[port.entities.device ?? ""]; const devices = (device?.attributes.devices as { name?: string; mac?: string }[] | undefined) ?? []; for (const d of devices.slice(0, 10)) lines.push(`• ${d.name ?? d.mac ?? "?"}`); @@ -134,43 +156,72 @@ export function portTitle(port: PortInfo, states: States, words: Words): string export interface Words { port: string; noLink: string; + linkUp: string; unknown: string; uplink: string; trunks: string; - received: string; - sent: string; - poe: string; - restart: string; noSwitch: string; + oldIntegration: string; + notFound: string; + /** Labels of the settings dialog, by option. */ + fields: Record; } export const WORDS: Record = { en: { port: "Port", noLink: "No link", + linkUp: "Link", unknown: "Unknown", uplink: "Link to another switch", trunks: "Trunks", - received: "in", - sent: "out", - poe: "PoE", - restart: "Restarted", noSwitch: "Choose a managed switch in the card's settings.", + oldIntegration: "This card needs the Managed Switch (SNMP) integration 0.2.0 or newer.", + notFound: "The switch is not set up (yet), or the card's device is not a managed switch.", + fields: { + device_id: "Switch", + title: "Title (optional)", + show_names: "Device names under the ports", + show_rates: "Data rates (sensors must be on)", + }, }, de: { port: "Port", noLink: "Kein Link", + linkUp: "Link", unknown: "Unbekannt", uplink: "Verbindung zu einem anderen Switch", trunks: "Trunks", - received: "rein", - sent: "raus", - poe: "PoE", - restart: "Neustart", noSwitch: "Wähle in den Einstellungen der Karte einen Managed Switch.", + oldIntegration: "Diese Karte braucht die Integration Managed Switch (SNMP) 0.2.0 oder neuer.", + notFound: + "Der Switch ist (noch) nicht eingerichtet, oder das Gerät der Karte ist kein Managed Switch.", + fields: { + device_id: "Switch", + title: "Titel (optional)", + show_names: "Gerätenamen unter den Ports", + show_rates: "Datenraten (Sensoren müssen an sein)", + }, }, }; export function words(language: string | undefined): Words { return WORDS[(language ?? "en").split("-")[0]] ?? WORDS.en; } + +/** + * Which of a switch's port entities are unavailable, as one string: it changes when the switch + * is set up again (its entities come back), the moment for the card to read the ports again. + */ +export function availability(reply: PortsReply | undefined, states: States): string { + if (!reply) return ""; + return reply.ports + .map((p) => (states[p.entities.link ?? ""]?.state === "unavailable" ? "0" : "1")) + .join(""); +} + +/** The card's height in rows of 50 px, as Home Assistant's masonry view counts. */ +export function cardSize(layout: Layout | undefined, trunks: number): number { + const rows = Math.max(layout?.rows.length ?? 1, layout?.sfp.length ? 1 : 0, 1); + return 1 + 2 * rows + (trunks ? 2 : 0); +} diff --git a/test/loader.test.ts b/test/loader.test.ts new file mode 100644 index 0000000..1a20ce2 --- /dev/null +++ b/test/loader.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, it, vi } from "vitest"; + +import { PortsLoader, REFRESH_MS, RETRY_MS, errorText } from "../src/loader"; +import { words, type PortsReply } from "../src/model"; + +const answer = (name: string): PortsReply => ({ + switch: { entry_id: "e", name, vendor: null, model: null, firmware: null, object_id: null, entities: {} }, + ports: [], +}); + +/** A callWS whose answers the test hands out one by one. */ +function fakeWS() { + const calls: { id: unknown; resolve: (r: PortsReply) => void; reject: (e: unknown) => void }[] = []; + const callWS = vi.fn( + (m: Record) => + new Promise((resolve, reject) => calls.push({ id: m.device_id, resolve, reject })), + ); + return { callWS, calls }; +} + +const tick = () => new Promise((r) => setTimeout(r)); + +describe("PortsLoader", () => { + it("reads once, again after the refresh time, and at once when asked", async () => { + const { callWS, calls } = fakeWS(); + const changed = vi.fn(); + const loader = new PortsLoader(changed); + loader.load(callWS, "a", 0); + loader.load(callWS, "a", 1); // still waiting for the answer + calls[0].resolve(answer("A")); + await tick(); + expect(loader.reply?.switch.name).toBe("A"); + expect(changed).toHaveBeenCalledOnce(); + loader.load(callWS, "a", REFRESH_MS - 1); + expect(callWS).toHaveBeenCalledTimes(1); + loader.load(callWS, "a", REFRESH_MS + 1); + expect(callWS).toHaveBeenCalledTimes(2); + calls[1].resolve(answer("A")); + await tick(); + loader.load(callWS, "a", REFRESH_MS + 2, true); + expect(callWS).toHaveBeenCalledTimes(3); + }); + + it("keeps the last answer when a read fails, and tries again soon", async () => { + const { callWS, calls } = fakeWS(); + const loader = new PortsLoader(() => undefined); + loader.load(callWS, "a", 0); + calls[0].resolve(answer("A")); + await tick(); + loader.load(callWS, "a", REFRESH_MS + 1); + calls[1].reject({ code: "not_found", message: "gone" }); + await tick(); + expect(loader.reply?.switch.name).toBe("A"); + expect(loader.error).toEqual({ code: "not_found", message: "gone" }); + loader.load(callWS, "a", REFRESH_MS + RETRY_MS); + expect(callWS).toHaveBeenCalledTimes(2); + loader.load(callWS, "a", REFRESH_MS + RETRY_MS + 2); + expect(callWS).toHaveBeenCalledTimes(3); + calls[2].resolve(answer("A2")); + await tick(); + expect(loader.error).toBeUndefined(); + }); + + it("ignores an answer for a switch the card no longer shows", async () => { + const { callWS, calls } = fakeWS(); + const loader = new PortsLoader(() => undefined); + loader.load(callWS, "a", 0); + loader.load(callWS, "b", 1); + calls[1].resolve(answer("B")); + calls[0].resolve(answer("A")); + await tick(); + expect(loader.reply?.switch.name).toBe("B"); + loader.reset(); + expect(loader.reply).toBeUndefined(); + calls.length = 0; + loader.load(callWS, "b", 2); + calls[0].reject(undefined); + await tick(); + expect(loader.error).toBe("error"); + }); +}); + +describe("errorText", () => { + it("explains the errors a user can fix", () => { + const en = words("en"); + expect(errorText({ code: "unknown_command", message: "Unknown command." }, en)).toBe(en.oldIntegration); + expect(errorText({ code: "not_found" }, en)).toBe(en.notFound); + expect(errorText({ code: "x", message: "boom" }, en)).toBe("boom"); + expect(errorText("plain", en)).toBe("plain"); + }); +}); diff --git a/test/model.test.ts b/test/model.test.ts index 13fb4ad..49c6d83 100644 --- a/test/model.test.ts +++ b/test/model.test.ts @@ -1,8 +1,11 @@ import { describe, expect, it } from "vitest"; import { + availability, + cardSize, deviceLabel, layoutFor, + numeric, portTitle, powered, rateLabel, @@ -72,7 +75,8 @@ describe("tone", () => { expect(tone(on, { state: "2500", attributes: {} })).toBe("fast"); expect(tone(on, { state: "100", attributes: {} })).toBe("slow"); expect(tone(on, { state: "10", attributes: {} })).toBe("slowest"); - expect(tone(on, undefined)).toBe("fast"); + expect(tone(on, undefined)).toBe("up"); + expect(tone(on, { state: "unavailable", attributes: {} })).toBe("up"); expect(tone({ state: "off", attributes: {} }, undefined)).toBe("down"); expect(tone({ state: "unavailable", attributes: {} }, undefined)).toBe("unknown"); expect(tone(undefined, undefined)).toBe("unknown"); @@ -119,6 +123,16 @@ describe("labels", () => { const down = { l: { state: "off", attributes: {} } }; expect(portTitle(port("1", { entities: { link: "l" } }), down, words("en"))).toBe("Port 1\nNo link"); expect(portTitle(port("1"), {}, words("xx"))).toBe("Port 1\nUnknown"); + const noSpeed = { l: { state: "on", attributes: {} } }; + expect(portTitle(port("1", { entities: { link: "l" } }), noSpeed, words("en"))).toBe("Port 1\nLink"); + }); + + it("shows PoE states in the user's language", () => { + const p = port("1", { poe: true, entities: { poe: "p" } }); + const states = { p: { state: "delivering_power", attributes: {} } }; + const lines = portTitle(p, states, words("en"), (s) => `<${s.state}>`).split("\n"); + expect(lines.at(-1)).toBe("PoE: "); + expect(portTitle(p, {}, words("en")).split("\n").at(-1)).toBe("PoE: ?"); }); it("lists at most ten devices", () => { @@ -128,3 +142,25 @@ describe("labels", () => { expect(lines.at(-1)).toBe("… +2"); }); }); + +describe("numbers and sizes", () => { + it("reads numbers, not unknown states", () => { + expect(numeric({ state: "12.5", attributes: {} })).toBe(12.5); + expect(numeric({ state: "unavailable", attributes: {} })).toBeUndefined(); + expect(numeric({ state: "", attributes: {} })).toBeUndefined(); + expect(numeric(undefined)).toBeUndefined(); + }); + + it("notices ports whose entities are unavailable", () => { + const r = reply(null, ["1", "2"]); + const states = { "binary_sensor.p1_link": { state: "unavailable", attributes: {} } }; + expect(availability(r, states)).toBe("011"); + expect(availability(undefined, states)).toBe(""); + }); + + it("grows with rows and trunks", () => { + expect(cardSize(undefined, 0)).toBe(3); + expect(cardSize({ rows: [["1"], ["2"]], sfp: [] }, 1)).toBe(7); + expect(cardSize({ rows: [], sfp: ["9"] }, 0)).toBe(3); + }); +}); diff --git a/tsconfig.json b/tsconfig.json index 85ae867..2118b29 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -11,7 +11,8 @@ "experimentalDecorators": true, "useDefineForClassFields": false, "skipLibCheck": true, - "noEmit": true + "noEmit": true, + "types": ["node"] }, "include": ["src", "test"] }