Skip to content
This repository was archived by the owner on Nov 2, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/).
Expand Down
Binary file modified assets/card.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
70 changes: 70 additions & 0 deletions src/loader.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>) => Promise<PortsReply>;

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();
}
}
116 changes: 62 additions & 54 deletions src/managed-switch-card.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -14,6 +18,7 @@ import {
type Layout,
type PortInfo,
type PortsReply,
type StateLike,
type States,
} from "./model";

Expand All @@ -23,6 +28,7 @@ interface Hass {
states: States;
entities?: Record<string, { platform?: string; device_id?: string | null } | undefined>;
language?: string;
formatEntityState?(state: StateLike): string;
callWS<T>(message: Record<string, unknown>): Promise<T>;
}

Expand All @@ -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");
Expand All @@ -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<string, number> {
Expand All @@ -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<PortsReply>({ 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<PortsReply>(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(
Expand All @@ -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`
<button
class="port ${kind} ${sfp ? "sfp" : ""}"
title=${portTitle(port, states, w)}
aria-label=${portTitle(port, states, w)}
title=${title}
aria-label=${title.replaceAll("\n", ", ")}
@click=${() => this._open(e.device ?? e.link)}
>
<span class="jack">
Expand All @@ -143,31 +142,33 @@ export class ManagedSwitchCard extends LitElement {
if (!this._config?.device_id) {
return html`<ha-card><div class="note">${w.noSwitch}</div></ha-card>`;
}
if (this._error) {
return html`<ha-card><div class="note">${this._error}</div></ha-card>`;
const reply = this._loader.reply;
const error = this._loader.error;
if (!reply) {
const text = error === undefined ? "…" : errorText(error, w);
return html`<ha-card><div class="note">${text}</div></ha-card>`;
}
const reply = this._reply;
if (!reply) return html`<ha-card><div class="note">…</div></ha-card>`;
const byName = new Map(reply.ports.map((p) => [p.name, p]));
const layout = layoutFor(reply, this._config.layout);
const trunks = reply.ports.filter((p) => p.kind === "trunk");
const states = this.hass?.states ?? {};
const se = reply.switch.entities;
const consumption = states[se.poe_consumption ?? ""];
const budget = states[se.poe_budget ?? ""];
const consumption = numeric(states[se.poe_consumption ?? ""]);
const budget = numeric(states[se.poe_budget ?? ""]);
return html`
<ha-card>
<div class="header">
<div>
<div class="title">${this._config.title ?? reply.switch.name}</div>
<div class="model">${[reply.switch.model, reply.switch.firmware].filter(Boolean).join(" · ")}</div>
</div>
${consumption && budget
? html`<div class="poe-total" @click=${() => this._open(se.poe_consumption)}>
<ha-icon icon="mdi:flash"></ha-icon>${consumption.state} / ${budget.state} W
</div>`
${consumption !== undefined && budget !== undefined
? html`<button class="poe-total" @click=${() => this._open(se.poe_consumption)}>
<ha-icon icon="mdi:flash"></ha-icon>${consumption} / ${budget} W
</button>`
: nothing}
</div>
${error !== undefined ? html`<div class="note">${errorText(error, w)}</div>` : nothing}
<div class="panel">
<div class="rows">
${layout.rows.map(
Expand Down Expand Up @@ -222,13 +223,18 @@ export class ManagedSwitchCard extends LitElement {
font-size: 0.85em;
}
.poe-total {
all: unset;
display: flex;
align-items: center;
gap: 4px;
cursor: pointer;
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);
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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<string, [string, string]> = {
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(
Expand Down Expand Up @@ -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", "");
Loading
Loading