Compare commits

...
Author SHA1 Message Date
Aidan Timson 559775af9d Flatten the Status filter on the entities page 2026-11-24 14:53:54 +00:00
hoizi89andClaude Opus 5.5 3fbe85d38f Add network health page to ZHA panel (#53641)
* Add network health page to ZHA panel

Zigbee problems are quiet. A device at the edge of its range keeps working
most of the time, and a device that joined but never finished its interview
simply exposes nothing at all. Neither is visible anywhere in the panel
today: link quality and last seen live on individual device pages, so
finding a weak device means opening all of them one by one.

This adds a "Network health" page next to "Network information". It opens
with the reachability of the network and how link quality is distributed
across it, followed by six findings, each expanding to the devices it
covers: not fully added, weak signal, not responding, low battery, nothing
heard for a while, and routers.

Every finding is grouped by area, so it is visible whether a problem is
spread over the house or concentrated in one room, and each device row
names the router it is connected through - the neighbour a weak device
depends on. Findings that expand carry one line of guidance; several of
them deliberately end in "otherwise there is nothing to do", so the page
can be read and dismissed without worry.

No new backend API is needed. Link quality, availability, last seen, area,
neighbours and entity states all come from the existing zha/devices
WebSocket command, and INCOMPLETE_PAIRING_STATUSES already existed but was
only used during the pairing flow.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01X32KGzLGEbQ2vY11rtMrt7

* Address review feedback on the ZHA network health page

Defects the review turned up:

- The status line mixed two device sets: the offline count came from the
  devices the page reports on, the total from all of them including the
  coordinator, so the sentence was normally off by one. Both now come from
  the same list.
- A failing zha/devices call left the page blank forever. It now shows a
  spinner while loading and an error alert carrying the cause.
- pairing_status was never going to arrive. zha/devices returns
  zha_device_info, which has no such field; it only travels with the
  pairing events. That branch is gone. A device exposing no entities is
  still detected, which is the case that matters.
- Resolving the parent router rescanned every neighbour table once per
  rendered row. It is built once per device list now.
- Areas are grouped by area_id instead of by their translated name.
- Four rules hard-coded left and right, so the page came apart in
  right-to-left locales. The chevron compensation in particular is no
  longer a padding hack on the summary row but a margin on the icon that
  takes the chevron's place.
- In English the percent sign follows the number directly.

Two more that only showed up while looking at the page:

- One sleeping device turned the status icon red next to the word
  "Online". The network is down once nothing answers at all, the rule the
  ZHA dashboard already uses, and the heading follows it now.
- A device that is not responding was counted in the signal distribution
  under its last known link quality, and its row showed that value in
  green. It has its own band in the bar now and its reading is greyed out:
  still worth reading, since a strong last reading points at power rather
  than range, but no longer claiming to be current.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01X32KGzLGEbQ2vY11rtMrt7

* Move ZHA network health logic into a testable module

The bands, thresholds and grouping lived inside the page component, where
nothing could reach them without rendering a component and a hass object.
They are plain functions over a device list, so they now live in
network-health.ts and the component keeps what actually needs it: icons,
translations, and the two lookups that read from hass - the battery level
of a device and the name of an area, both passed in as functions.

Nothing about the page changes. What is new is that the rules can be
stated as tests: where the thresholds sit and which side of them counts,
that a link quality of zero is weak rather than missing, that a silent
device is reported as such instead of by its last reading, that the
coordinator is left out, that a device may appear in more than one
finding, and that devices without an area stay apart from an area that
happens to carry the same label.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01X32KGzLGEbQ2vY11rtMrt7

* Follow upstream list components and ZHA types

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Refresh the health snapshot, skip offline routers, guard last_seen

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Rework ZHA network health page after UX review

Follow the design direction from the UX review:
- Top card explains the page is a snapshot and shows when it was updated
- Split findings into "Needs attention" (offline, setup not finished),
  listed with their devices, and "Worth a look" (weak signal, low battery,
  firmware update), each on its own subpage with the value before the chevron
- Rename "Not fully added" to "Setup not finished" and "Not responding"
  to "Offline"; show the power source on offline devices
- Drop the "Nothing heard for a while" and "Routers" findings
- Add a red dot to the Network health row on the ZHA dashboard when
  something needs attention
- Add a firmware update finding based on the devices' update entities
- Offline devices are no longer listed under weak signal or low battery

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Rate ZHA signal from the neighbour tables

The LQI of the last packet swings with every message. Use the link quality
the neighbour tables report instead, falling back to the last packet when no
neighbour lists the device:
- an end device uses the entry of the router it is a child of
- a router uses the best entry any neighbour reports, which ignores "Child"
  entries between routers and the near-zero values some firmware reports
  for every neighbour

On a real network this surfaces end devices in a poorly covered floor that
the last-packet LQI rated as strong.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Match the ZHA network health page to the Figma design

- Top card titled "Your Zigbee network" with the snapshot note, the signal
  bar (fair in a lighter green, segments spaced) and "Updated" with a clock
- "N devices need attention" as a flat list: device icon, name, and the
  status in red followed by power source, area and last seen; devices whose
  setup did not finish show when they joined, from the device registry
- "Worth a look" rows read "N devices with a weak signal" with the advice
  below; rows without devices, and the card when all are empty, are hidden

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Keep "Worth a look" visible when there is nothing to look at

Show "Signal, batteries and firmware look fine" instead of hiding the card,
so it is clear these were checked rather than left out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Tighten ZHA network health findings

- Leave out devices disabled in the device registry
- Only report "Setup not finished" when the entity registry knows no entity
  of the device either: the device list only carries entities that were
  added, so a device whose entities are all disabled looked unfinished
- Show "via <router>" for end devices only
- Only offer firmware updates for devices that are online
- Sort with the user's language, as the neighbouring pages do
- Undo unrelated reformatting of en.json from an earlier commit

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Skip configuration entities when picking a device icon

A child lock switch made a smart plug show a lock icon.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Address review feedback on the network health page

- Only an end device's current parent sets its neighbour-table link;
  a former parent's stale entry no longer overrides the last packet
- Check for registered entities against the full entity registry, so
  devices whose entities are all disabled are not shown as unfinished
- Resolve areas through the device registry (getZHADeviceAreaName)
- Group subpage lists by area, worst reading first within a room
- Hide "Worth a look" when there is nothing to show

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Link firmware update rows to the device page

The ZHA device page has no install control for the update entity.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Reload the entity registry with every device refresh

A device that joins while the page is open was matched against the
registry from when the page opened and shown as setup not finished.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Keep finding values in the secondary text color

Warning-colored text has too little contrast on the light theme; the
icon in front of each row still carries the color.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Color the low battery icon and localize the LQI label

The slot rule for row icons outranked the warning color, so the
battery icon stayed grey.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Rework the network health page after review

- Consume contexts instead of hass; the entity registry comes from
  fullEntitiesContext, so it is no longer fetched on every refresh
- Localize with full keys, format numbers with formatNumberWithUnit,
  use theme tokens for radii and line heights
- Drop the firmware update finding; updates have their own place
- Hide the attention card and empty legend items when there is nothing
  to show
- Subpages get a tip below the card and a Show map button
- Move the dashboard dot to the start of the description line

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Leave disabled devices out of the network snapshot

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Address review: theme colour, localized strings, kebab-case subpage URLs

- Use --ha-color-green-70 for "fair" instead of mixing with white
- "Updated {relative_time}" with ha-relative-time as the value
- LQI value via placeholder instead of string concatenation
- Subpage URLs in kebab-case via slugify(key, "-")

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-11-24 15:32:39 +01:00
Paul Bottein 56bd78dae5 Change cover state color to blue (#56086) 2026-11-24 10:08:26 +01:00
10 changed files with 1788 additions and 158 deletions

No files matched your search

+28 -101
View File
@@ -20,7 +20,6 @@ import "./ha-expansion-panel";
import "./ha-icon";
import "./ha-icon-button";
import "./ha-svg-icon";
import "./ha-tree-indicator";
import "./item/ha-list-item-option";
import type { HaListItemOption } from "./item/ha-list-item-option";
import "./list/ha-list-selectable";
@@ -35,23 +34,6 @@ export interface FilterStateOption {
iconPath?: string;
}
/**
* Two opposite options, like available and unavailable, listed under a row
* that ticks or unticks both. The row is partly ticked when one of the two is.
*/
export interface FilterStatePair {
/** Identifies the row, apart from the values of its options */
value: string;
label: string;
iconPath?: string;
options: [FilterStateOption, FilterStateOption];
}
export type FilterStateItem = FilterStateOption | FilterStatePair;
const isPair = (item: FilterStateItem): item is FilterStatePair =>
"options" in item;
@customElement("ha-filter-states")
export class HaFilterStates extends LitElement {
@state()
@@ -62,7 +44,7 @@ export class HaFilterStates extends LitElement {
@property({ attribute: false }) public value?: string[];
@property({ attribute: false }) public states?: FilterStateItem[];
@property({ attribute: false }) public states?: FilterStateOption[];
@property({ type: Boolean }) public narrow = false;
@@ -108,10 +90,29 @@ export class HaFilterStates extends LitElement {
@ha-list-item-selected=${this._handleItemToggled}
@ha-list-item-deselected=${this._handleItemToggled}
>
${this.states.map((item) =>
isPair(item)
? this._renderPair(item)
: this._renderOption(item)
${this.states.map(
(item) =>
html`<ha-list-item-option
appearance="checkbox"
selection-position="end"
.value=${item.value}
.selected=${this.value?.includes(item.value) ?? false}
>
${
item.iconPath
? html`<ha-svg-icon
slot="start"
.path=${item.iconPath}
></ha-svg-icon>`
: item.icon
? html`<ha-icon
slot="start"
.icon=${item.icon}
></ha-icon>`
: nothing
}
<span slot="headline">${item.label}</span>
</ha-list-item-option>`
)}
</ha-list-selectable>
</div>
@@ -121,56 +122,6 @@ export class HaFilterStates extends LitElement {
`;
}
private _renderOption(item: FilterStateOption, nested?: { last: boolean }) {
return html`<ha-list-item-option
appearance="checkbox"
selection-position="end"
class=${nested ? "nested" : ""}
.value=${item.value}
.selected=${this.value?.includes(item.value) ?? false}
>
${
nested
? html`<ha-tree-indicator
slot="start"
.end=${nested.last}
></ha-tree-indicator>`
: nothing
}
${this._renderIcon(item)}
<span slot="headline">${item.label}</span>
</ha-list-item-option>`;
}
private _renderPair(pair: FilterStatePair) {
const picked = pair.options.filter((option) =>
this.value?.includes(option.value)
).length;
return html`<ha-list-item-option
appearance="checkbox"
selection-position="end"
.value=${pair.value}
.selected=${picked === pair.options.length}
.indeterminate=${picked > 0 && picked < pair.options.length}
>
${this._renderIcon(pair)}
<span slot="headline">${pair.label}</span>
</ha-list-item-option>
${pair.options.map((option, index) =>
this._renderOption(option, {
last: index === pair.options.length - 1,
})
)}`;
}
private _renderIcon(item: { icon?: string; iconPath?: string }) {
return item.iconPath
? html`<ha-svg-icon slot="start" .path=${item.iconPath}></ha-svg-icon>`
: item.icon
? html`<ha-icon slot="start" .icon=${item.icon}></ha-icon>`
: nothing;
}
private _expandedChanged(ev) {
this.expanded = ev.detail.expanded;
}
@@ -185,21 +136,10 @@ export class HaFilterStates extends LitElement {
return;
}
const selected = ev.type === "ha-list-item-selected";
// A pair row ticks or unticks both of its options
const pair = this.states?.find(
(item): item is FilterStatePair =>
isPair(item) && item.value === itemValue
);
const values = pair
? pair.options.map((option) => option.value)
: [itemValue];
this.value = values.reduce(
(value, val) =>
selected ? arrayWith(value, val) : arrayWithout(value, val),
this.value
);
this.value =
ev.type === "ha-list-item-selected"
? arrayWith(this.value, itemValue)
: arrayWithout(this.value, itemValue);
fireEvent(this, "data-table-filter-changed", {
value: this.value,
@@ -229,19 +169,6 @@ export class HaFilterStates extends LitElement {
flex: 1;
min-height: 0;
}
/* Options of a pair sit under it, like areas under their floor */
.nested::part(base) {
padding-inline-start: 48px;
}
ha-tree-indicator {
width: 56px;
position: absolute;
top: 0px;
inset-inline-start: 0px;
}
ha-tree-indicator:dir(rtl) {
transform: scaleX(-1);
}
.header {
display: flex;
align-items: center;
+3 -1
View File
@@ -261,7 +261,9 @@ export const fetchAttributesForCluster = (
cluster_type: clusterType,
});
export const fetchDevices = (hass: HomeAssistant): Promise<ZHADevice[]> =>
export const fetchDevices = (
hass: Pick<HomeAssistant, "callWS">
): Promise<ZHADevice[]> =>
hass.callWS({
type: "zha/devices",
});
@@ -7,14 +7,11 @@ import {
mdiDotsVertical,
mdiEye,
mdiEyeOff,
mdiEyeOutline,
mdiMenuDown,
mdiMicrophoneMessage,
mdiMicrophoneMessageOff,
mdiPencilOff,
mdiPlus,
mdiPower,
mdiPulse,
mdiRestore,
mdiRestoreAlert,
mdiToggleSwitch,
@@ -78,7 +75,7 @@ import "../../../components/ha-filter-floor-areas";
import "../../../components/ha-filter-integrations";
import "../../../components/ha-filter-labels";
import "../../../components/ha-filter-states";
import type { FilterStateItem } from "../../../components/ha-filter-states";
import type { FilterStateOption } from "../../../components/ha-filter-states";
import "../../../components/ha-filter-voice-assistants";
import "../../../components/ha-icon";
import "../../../components/ha-icon-button";
@@ -324,59 +321,36 @@ export class HaConfigEntities extends LitElement {
// The icons of the options match the ones of the status column and of the
// actions for the selected entities
private _states = memoize((localize: LocalizeFunc): FilterStateItem[] => [
private _states = memoize((localize: LocalizeFunc): FilterStateOption[] => [
{
value: "availability",
label: localize("ui.panel.config.entities.picker.headers.availability"),
iconPath: mdiPulse,
options: [
{
value: "available",
label: localize("ui.panel.config.entities.picker.status.available"),
iconPath: mdiCheckCircle,
},
{
value: "unavailable",
label: localize("ui.panel.config.entities.picker.status.unavailable"),
iconPath: mdiAlertCircle,
},
],
value: "available",
label: localize("ui.panel.config.entities.picker.status.available"),
iconPath: mdiCheckCircle,
},
{
value: "activation",
label: localize(
"ui.panel.config.entities.picker.status_pairs.activation"
),
iconPath: mdiPower,
options: [
{
value: "enabled",
label: localize("ui.panel.config.entities.picker.status.enabled"),
iconPath: mdiToggleSwitch,
},
{
value: "disabled",
label: localize("ui.panel.config.entities.picker.status.disabled"),
iconPath: mdiToggleSwitchOffOutline,
},
],
value: "unavailable",
label: localize("ui.panel.config.entities.picker.status.unavailable"),
iconPath: mdiAlertCircle,
},
{
value: "visibility",
label: localize("ui.panel.config.entities.picker.headers.visibility"),
iconPath: mdiEyeOutline,
options: [
{
value: "visible",
label: localize("ui.panel.config.entities.picker.status.visible"),
iconPath: mdiEye,
},
{
value: "hidden",
label: localize("ui.panel.config.entities.picker.status.hidden"),
iconPath: mdiEyeOff,
},
],
value: "enabled",
label: localize("ui.panel.config.entities.picker.status.enabled"),
iconPath: mdiToggleSwitch,
},
{
value: "disabled",
label: localize("ui.panel.config.entities.picker.status.disabled"),
iconPath: mdiToggleSwitchOffOutline,
},
{
value: "visible",
label: localize("ui.panel.config.entities.picker.status.visible"),
iconPath: mdiEye,
},
{
value: "hidden",
label: localize("ui.panel.config.entities.picker.status.hidden"),
iconPath: mdiEyeOff,
},
{
value: "readonly",
@@ -0,0 +1,290 @@
import type { ZHADevice } from "../../../../../data/zha";
import { ZHADeviceType } from "../../../../../data/zha";
/** Link quality below which a device sits at the edge of its radio range. */
export const WEAK_LQI = 30;
/** Link quality from which a device is comfortably connected. */
export const STRONG_LQI = 60;
/** Battery percentage at or below which a device is listed as running low. */
export const LOW_BATTERY = 20;
/** How the link quality of a device reads on its own. */
export type SignalBand = "strong" | "fair" | "weak" | "unknown";
/**
* The bands of the distribution bar, worsening from left to right. An offline
* device gets its own: its last link quality says nothing about how it is
* doing now.
*/
export type BarBand = "strong" | "fair" | "weak" | "offline";
export const BAR_BANDS: BarBand[] = ["strong", "fair", "weak", "offline"];
export type BandCounts = Record<BarBand | "unknown", number>;
/** Findings that stop a device from working. */
export type AttentionKey = "offline" | "setup_unfinished";
/** Findings that are worth knowing but do not stop anything. */
export type WorthALookKey = "weak_signal" | "low_battery";
/** What the page reports on a device. */
export type FindingKey = AttentionKey | WorthALookKey;
/**
* Findings that stop a device from working. Listed with their devices right
* on the page, like repairs.
*/
export const NEEDS_ATTENTION: AttentionKey[] = ["offline", "setup_unfinished"];
/**
* Findings that are worth knowing but do not stop anything. Each has its own
* subpage, reached from a single row on the page.
*/
export const WORTH_A_LOOK: WorthALookKey[] = ["weak_signal", "low_battery"];
export type Findings = Record<FindingKey, ZHADevice[]>;
/** Readings that live in the registries and entity states rather than in the device list. */
export interface DeviceReadings {
/** Battery percentage, or null when the device has no battery sensor. */
batteryLevel: (device: ZHADevice) => number | null;
/** Whether the device is disabled in the device registry. */
isDisabled: (device: ZHADevice) => boolean;
/**
* Whether the entity registry holds any entity of the device, disabled ones
* included. The device list only carries entities that were added.
*/
hasRegisteredEntities: (device: ZHADevice) => boolean;
}
export type PowerSource = "mains" | "battery";
/** The registry ids of all devices that own at least one entity. */
export const devicesWithEntities = (
entities:
| Record<string, { device_id?: string | null }>
| { device_id?: string | null }[]
): Set<string> =>
new Set(
Object.values(entities)
.map((entity) => entity.device_id)
.filter((id): id is string => Boolean(id))
);
/** The devices the page reports on: everything except the coordinator. */
export const managedDevices = (devices: ZHADevice[]): ZHADevice[] =>
devices.filter((device) => !device.active_coordinator);
/** Link quality per device IEEE, as reported by its neighbours. */
export type LinkQualities = Record<string, number>;
/**
* The link quality the neighbour tables report for each device. The value of
* the last packet swings with every message; a neighbour table entry is the
* router's own running estimate of the link and reads much steadier. zigpy
* rescans the tables every few hours, so it can lag behind a sudden change.
*
* An end device uses the entry of the router it is a child of: that is the
* link it actually depends on. A router routes over the whole mesh, so it
* uses the best entry any neighbour reports, whatever the relationship: a
* router with one good link is still reachable, and a single neighbour whose
* firmware reports near-zero values for everything does not drag it down.
* An end device without a current parent entry falls back to its last
* packet. Unavailable routers are skipped, as their tables may be stale.
*/
export const neighborLinkQualities = (devices: ZHADevice[]): LinkQualities => {
const endDevices = new Set(
devices
.filter((device) => device.device_type === ZHADeviceType.EndDevice)
.map((device) => device.ieee)
);
const best: LinkQualities = {};
const parent: LinkQualities = {};
for (const router of devices) {
if (!router.available) {
continue;
}
for (const neighbor of router.neighbors) {
const lqi = Number(neighbor.lqi);
if (neighbor.lqi === "" || isNaN(lqi)) {
continue;
}
if (endDevices.has(neighbor.ieee)) {
// Only the current parent counts: a former parent may still list
// the device as a previous child with a stale reading.
if (neighbor.relationship === "Child") {
parent[neighbor.ieee] = lqi;
}
continue;
}
best[neighbor.ieee] = Math.max(best[neighbor.ieee] ?? -1, lqi);
}
}
return { ...best, ...parent };
};
/**
* The link quality shown for a device: from the neighbour tables when they
* list it, otherwise from its last packet.
*/
export const linkQuality = (
device: ZHADevice,
links: LinkQualities = {}
): number | null => links[device.ieee] ?? device.lqi ?? null;
export const signalBand = (
device: ZHADevice,
links: LinkQualities = {}
): SignalBand => {
const lqi = linkQuality(device, links);
if (lqi === null) {
return "unknown";
}
if (lqi < WEAK_LQI) {
return "weak";
}
return lqi < STRONG_LQI ? "fair" : "strong";
};
export const countBands = (
devices: ZHADevice[],
links: LinkQualities = {}
): BandCounts => {
const counts: BandCounts = {
strong: 0,
fair: 0,
weak: 0,
offline: 0,
unknown: 0,
};
for (const device of devices) {
counts[device.available ? signalBand(device, links) : "offline"]++;
}
return counts;
};
/**
* ZHA reports "Mains" for mains-powered devices and "Battery or Unknown" for
* everything else. The latter is shown as battery: in practice it is almost
* always a battery device.
*/
export const powerSource = (device: ZHADevice): PowerSource | undefined => {
if (device.power_source === "Mains") {
return "mains";
}
return device.power_source?.startsWith("Battery") ? "battery" : undefined;
};
/**
* A device that joined the network but never finished its setup: it is known
* to the coordinator, yet has no entities at all. The device list only
* carries entities that were added, so one whose entities are all disabled
* would look the same; the entity registry tells the two apart.
* `pairing_status` would say so directly, but it only travels with the
* pairing events, not with the device list this page is built on.
*/
export const isSetupUnfinished = (
device: ZHADevice,
readings: Pick<DeviceReadings, "hasRegisteredEntities">
): boolean =>
device.entities.length === 0 && !readings.hasRegisteredEntities(device);
/** When the device was last heard from, or undefined for an empty or malformed stamp. */
export const lastSeenAt = (device: ZHADevice): Date | undefined => {
if (!device.last_seen) {
return undefined;
}
const at = new Date(device.last_seen);
return isNaN(at.getTime()) ? undefined : at;
};
/**
* Map each end device to the router that lists it as a child, so a weak
* device can be traced to the neighbour it depends on. Routers are left out:
* they route over the whole mesh, so a "Child" entry between two routers says
* nothing about a dependency. An unavailable router's table is skipped, as in
* the network visualization: it may still list a child that has long since
* moved to another router.
*/
export const parentByIeee = (devices: ZHADevice[]): Record<string, string> => {
const endDevices = new Set(
devices
.filter((device) => device.device_type === ZHADeviceType.EndDevice)
.map((device) => device.ieee)
);
const parents: Record<string, string> = {};
for (const device of devices) {
if (!device.available) {
continue;
}
for (const neighbor of device.neighbors) {
if (neighbor.relationship === "Child" && endDevices.has(neighbor.ieee)) {
parents[neighbor.ieee] = device.user_given_name || device.name;
}
}
}
return parents;
};
export const findings = (
devices: ZHADevice[],
readings: DeviceReadings,
links: LinkQualities = {}
): Findings => {
// A disabled device was switched off on purpose and is not reported on.
const active = devices.filter((device) => !readings.isDisabled(device));
// An offline device has no current signal or battery reading, so it is
// only listed as offline.
const online = active.filter((device) => device.available);
return {
offline: active.filter((device) => !device.available),
setup_unfinished: active.filter((device) =>
isSetupUnfinished(device, readings)
),
weak_signal: online
.filter((device) => signalBand(device, links) === "weak")
.sort(
(a, b) => (linkQuality(a, links) ?? 0) - (linkQuality(b, links) ?? 0)
),
low_battery: online
.filter((device) => {
const level = readings.batteryLevel(device);
return level !== null && level <= LOW_BATTERY;
})
.sort((a, b) => readings.batteryLevel(a)! - readings.batteryLevel(b)!),
};
};
/**
* How many devices need attention. A device that is both offline and not set
* up is counted once.
*/
export const attentionCount = (found: Findings): number =>
new Set(NEEDS_ATTENTION.flatMap((key) => found[key]).map((d) => d.ieee)).size;
/**
* Order devices by area, so devices in the same room sit together.
* Unassigned devices come last. Within an area, devices are ordered by name,
* or keep their incoming order (for example worst reading first) when no
* name function is given.
*/
export const sortByArea = (
devices: ZHADevice[],
areaName: (device: ZHADevice) => string | undefined,
deviceName: ((device: ZHADevice) => string) | null,
compare: (a: string, b: string) => number = (a, b) => a.localeCompare(b)
): ZHADevice[] =>
// Array.prototype.sort is stable, so returning 0 keeps the incoming order.
[...devices].sort((a, b) => {
const areaA = areaName(a);
const areaB = areaName(b);
if (areaA !== areaB) {
if (areaA === undefined) return 1;
if (areaB === undefined) return -1;
return compare(areaA, areaB);
}
return deviceName ? compare(deviceName(a), deviceName(b)) : 0;
});
@@ -51,6 +51,10 @@ class ZHAConfigDashboardRouter extends HassRouterPage {
tag: "zha-network-info-page",
load: () => import("./zha-network-info-page"),
},
"network-health": {
tag: "zha-network-health-page",
load: () => import("./zha-network-health-page"),
},
section: {
tag: "zha-config-section-page",
load: () => import("./zha-config-section-page"),
@@ -4,6 +4,7 @@ import {
mdiDevices,
mdiDownload,
mdiFolderMultipleOutline,
mdiHeartPulse,
mdiInformationOutline,
mdiPlus,
mdiShape,
@@ -13,7 +14,9 @@ import {
import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { isComponentLoaded } from "../../../../../common/config/is_component_loaded";
import { consume } from "../../../../../common/decorators/consume";
import type { HASSDomCurrentTargetEvent } from "../../../../../common/dom/fire_event";
import { navigate } from "../../../../../common/navigate";
import "../../../../../components/buttons/ha-progress-button";
@@ -32,8 +35,11 @@ import "../../../../../components/list/ha-list-base";
import "../../../../../components/list/ha-list-nav";
import type { ConfigEntry } from "../../../../../data/config_entries";
import { getConfigEntries } from "../../../../../data/config_entries";
import { fullEntitiesContext } from "../../../../../data/context";
import type { EntityRegistryEntry } from "../../../../../data/entity/entity_registry";
import type {
ZHAConfiguration,
ZHADevice,
ZHANetworkBackupAndMetadata,
} from "../../../../../data/zha";
import {
@@ -50,6 +56,12 @@ import type { HomeAssistant, Route } from "../../../../../types";
import { brandsUrl } from "../../../../../util/brands-url";
import { fileDownload } from "../../../../../util/file_download";
import { renderConfigEntryError } from "../../ha-config-integration-page";
import {
attentionCount,
devicesWithEntities,
findings,
managedDevices,
} from "./network-health";
@customElement("zha-config-dashboard")
class ZHAConfigDashboard extends LitElement {
@@ -67,6 +79,13 @@ class ZHAConfigDashboard extends LitElement {
@state() private _offlineDevices = 0;
@state() private _devices?: ZHADevice[];
/** The full registry, as hass.entities leaves out disabled entities. */
@state()
@consume({ context: fullEntitiesContext, subscribe: true })
private _entityReg?: EntityRegistryEntry[];
@state() private _totalGroups?: number;
@state() private _asyncDataLoaded = false;
@@ -295,6 +314,14 @@ class ZHAConfigDashboard extends LitElement {
}
private _renderNavigationCard() {
const healthAttention =
this._devices && this._entityReg
? this._healthAttention(
this._devices,
this._entityReg,
this.hass.devices
)
: 0;
const dynamicSections = this._configuration
? Object.keys(this._configuration.schemas).filter(
(section) => section !== "zha_options"
@@ -348,6 +375,30 @@ class ZHAConfigDashboard extends LitElement {
</div>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>
<ha-list-item-button href="/config/zha/network-health">
<ha-svg-icon slot="start" .path=${mdiHeartPulse}></ha-svg-icon>
<div slot="headline">
${this.hass.localize(
"ui.panel.config.zha.configuration_page.network_health_title"
)}
</div>
<div slot="supporting-text">
${
healthAttention
? html`<span class="attention">
<span class="attention-dot"></span>
${this.hass.localize(
"ui.panel.config.zha.configuration_page.network_health_attention",
{ count: healthAttention }
)}
</span>`
: this.hass.localize(
"ui.panel.config.zha.configuration_page.network_health_description"
)
}
</div>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>
${dynamicSections.map(
(section) => html`
<ha-list-item-button
@@ -504,6 +555,29 @@ class ZHAConfigDashboard extends LitElement {
showOptionsFlowDialog(this, this._configEntry);
}
/**
* How many devices need attention on the network health page. Only those
* findings count here, so battery readings are not needed.
*/
private _healthAttention = memoizeOne(
(
devices: ZHADevice[],
entityReg: EntityRegistryEntry[],
haDevices: HomeAssistant["devices"]
): number => {
const withEntities = devicesWithEntities(entityReg);
return attentionCount(
findings(managedDevices(devices), {
batteryLevel: () => null,
isDisabled: (device) =>
Boolean(haDevices[device.device_reg_id]?.disabled_by),
hasRegisteredEntities: (device) =>
withEntities.has(device.device_reg_id),
})
);
}
);
private async _fetchDevicesAndGroups(): Promise<void> {
const [devicesResult, groupsResult] = await Promise.allSettled([
fetchDevices(this.hass),
@@ -514,6 +588,7 @@ class ZHAConfigDashboard extends LitElement {
this._offlineDevices = devicesResult.value.filter(
(d) => !d.available
).length;
this._devices = devicesResult.value;
} else {
this._error = devicesResult.reason?.message || devicesResult.reason;
}
@@ -530,6 +605,20 @@ class ZHAConfigDashboard extends LitElement {
haStyle,
animationStyles,
css`
.attention {
display: inline-flex;
align-items: center;
gap: var(--ha-space-2);
}
.attention-dot {
width: 8px;
height: 8px;
border-radius: var(--ha-border-radius-circle);
background-color: var(--error-color);
flex-shrink: 0;
}
ha-card {
margin: auto;
margin-top: var(--ha-space-4);
@@ -0,0 +1,831 @@
import type { ContextType } from "@lit/context";
import {
mdiBatteryAlertVariantOutline,
mdiClockOutline,
mdiHelpCircleOutline,
mdiSignalCellular1,
mdiSignalCellular2,
mdiSignalCellular3,
mdiSignalCellularOutline,
} from "@mdi/js";
import type { HassEntity } from "home-assistant-js-websocket";
import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { relativeTime } from "../../../../../common/datetime/relative_time";
import { consume } from "../../../../../common/decorators/consume";
import { consumeEntityStates } from "../../../../../common/decorators/consume-context-entry";
import { batteryLevelIconPath } from "../../../../../common/entity/battery_icon";
import { formatNumberWithUnit } from "../../../../../common/number/format_number";
import { stringCompare } from "../../../../../common/string/compare";
import { slugify } from "../../../../../common/string/slugify";
import "../../../../../components/ha-alert";
import "../../../../../components/ha-button";
import "../../../../../components/ha-card";
import "../../../../../components/ha-icon-next";
import "../../../../../components/ha-relative-time";
import "../../../../../components/ha-spinner";
import "../../../../../components/ha-state-icon";
import "../../../../../components/ha-svg-icon";
import "../../../../../components/item/ha-list-item-base";
import "../../../../../components/item/ha-list-item-button";
import "../../../../../components/list/ha-list-base";
import "../../../../../components/list/ha-list-nav";
import {
apiContext,
areasContext,
devicesContext,
fullEntitiesContext,
internationalizationContext,
} from "../../../../../data/context";
import type { EntityRegistryEntry } from "../../../../../data/entity/entity_registry";
import type { ZHADevice } from "../../../../../data/zha";
import { fetchDevices } from "../../../../../data/zha";
import "../../../../../layouts/hass-subpage";
import { haStyle } from "../../../../../resources/styles";
import type { Route } from "../../../../../types";
import { getZHADeviceAreaName } from "./functions";
import type {
AttentionKey,
BandCounts,
BarBand,
DeviceReadings,
Findings,
SignalBand,
WorthALookKey,
} from "./network-health";
import {
attentionCount,
BAR_BANDS,
countBands,
devicesWithEntities,
findings,
lastSeenAt,
linkQuality,
managedDevices,
neighborLinkQualities,
NEEDS_ATTENTION,
parentByIeee,
powerSource,
signalBand,
sortByArea,
WORTH_A_LOOK,
} from "./network-health";
const BAND_ICON: Record<SignalBand, string> = {
strong: mdiSignalCellular3,
fair: mdiSignalCellular2,
weak: mdiSignalCellular1,
unknown: mdiSignalCellularOutline,
};
const FINDING_ICON: Record<WorthALookKey, string> = {
weak_signal: mdiSignalCellular1,
low_battery: mdiBatteryAlertVariantOutline,
};
/** Domains whose icon tells what a device is, most telling first. */
const PRIMARY_DOMAINS = [
"light",
"switch",
"cover",
"climate",
"lock",
"fan",
"binary_sensor",
"sensor",
];
/**
* ZHA has no subscription for its device list, so link quality, last seen
* and availability are fetched again at the same cadence as the ZHA device
* page, so they do not freeze while the page is open.
*/
const DEVICE_REFRESH_INTERVAL = 60000;
const BASE_PATH = "/config/zha/network-health";
@customElement("zha-network-health-page")
class ZHANetworkHealthPage extends LitElement {
@property({ attribute: false }) public route!: Route;
@property({ type: Boolean }) public narrow = false;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: ContextType<typeof internationalizationContext>;
@consume({ context: apiContext, subscribe: true })
private _api!: ContextType<typeof apiContext>;
@state()
@consume({ context: devicesContext, subscribe: true })
private _haDevices!: ContextType<typeof devicesContext>;
@state()
@consume({ context: areasContext, subscribe: true })
private _areas!: ContextType<typeof areasContext>;
/** The full registry, as the display registry leaves out disabled entities. */
@state()
@consume({ context: fullEntitiesContext, subscribe: true })
private _entityReg?: EntityRegistryEntry[];
@state() private _devices?: ZHADevice[];
/**
* The entities of all ZHA devices, whose states the page reads. Read by
* consumeEntityStates through its path, hence not private.
*/
@state() protected _entityIds: string[] = [];
@state()
@consumeEntityStates({ entityIdPath: ["_entityIds"] })
private _states?: Record<string, HassEntity>;
@state() private _updatedAt?: Date;
@state() private _error?: string;
private _refreshInterval?: number;
public connectedCallback(): void {
super.connectedCallback();
if (this._devices) {
this._startRefresh();
}
}
public disconnectedCallback(): void {
super.disconnectedCallback();
this._stopRefresh();
}
protected firstUpdated(changedProperties: PropertyValues<this>) {
super.firstUpdated(changedProperties);
this._fetchDevices();
}
private async _loadDevices(): Promise<void> {
const devices = await fetchDevices(this._api);
this._devices = devices;
this._entityIds = devices.flatMap((device) =>
device.entities
.map((entity) => entity.entity_id)
.filter((entityId): entityId is string => Boolean(entityId))
);
this._updatedAt = new Date();
}
private async _fetchDevices(): Promise<void> {
try {
await this._loadDevices();
// The page may have been left while the request was in flight.
if (this.isConnected) {
this._startRefresh();
}
} catch (err: any) {
this._error = err.message || err;
}
}
private _startRefresh(): void {
this._stopRefresh();
this._refreshInterval = window.setInterval(
() => this._refreshDevices(),
DEVICE_REFRESH_INTERVAL
);
}
private _stopRefresh(): void {
if (this._refreshInterval) {
window.clearInterval(this._refreshInterval);
this._refreshInterval = undefined;
}
}
private async _refreshDevices(): Promise<void> {
try {
await this._loadDevices();
} catch (_err: any) {
// Keep the last snapshot; "Updated" keeps showing its age.
}
}
/**
* The devices the page reports on. A disabled device was switched off on
* purpose, so it is left out of the snapshot as well as the findings.
*/
private _activeDevices = memoizeOne(
(devices: ZHADevice[], haDevices: ContextType<typeof devicesContext>) =>
managedDevices(devices).filter(
(device) => !haDevices[device.device_reg_id]?.disabled_by
)
);
/** Built once per device list rather than per rendered row. */
private _parentByIeee = memoizeOne(parentByIeee);
/**
* Built from the full device list: the coordinator is the parent of many
* devices, so its neighbour table counts too.
*/
private _links = memoizeOne(neighborLinkQualities);
private _devicesWithEntities = memoizeOne(devicesWithEntities);
private _entityRegById = memoizeOne(
(entityReg: EntityRegistryEntry[]) =>
new Map(entityReg.map((entry) => [entry.entity_id, entry]))
);
private _readings: DeviceReadings = {
batteryLevel: (device) => {
for (const entity of device.entities) {
const stateObj = entity.entity_id
? this._states?.[entity.entity_id]
: undefined;
if (stateObj?.attributes.device_class === "battery") {
const level = Number(stateObj.state);
if (!isNaN(level)) {
return level;
}
}
}
return null;
},
isDisabled: (device) =>
Boolean(this._haDevices[device.device_reg_id]?.disabled_by),
hasRegisteredEntities: (device) =>
this._devicesWithEntities(this._entityReg!).has(device.device_reg_id),
};
private _deviceName = (device: ZHADevice): string =>
device.user_given_name || device.name;
private _areaName = (device: ZHADevice): string | undefined =>
getZHADeviceAreaName(device, this._areas, this._haDevices);
/** The finding a subpage shows, taken from the path below the page. */
private get _subpage(): WorthALookKey | undefined {
const segment = this.route?.path?.replace(/^\//, "").split("/")[0];
return WORTH_A_LOOK.find((key) => slugify(key, "-") === segment);
}
protected render(): TemplateResult {
const subpage = this._subpage;
return html`
<hass-subpage
.narrow=${this.narrow}
.header=${this._i18n.localize(
subpage
? `ui.panel.config.zha.network_health.${subpage}`
: "ui.panel.config.zha.network_health.title"
)}
.backPath=${subpage ? BASE_PATH : "/config/zha/dashboard"}
>
<div class="container">${this._renderContent(subpage)}</div>
</hass-subpage>
`;
}
private _renderContent(subpage?: WorthALookKey) {
if (this._error) {
return html`
<ha-alert
alert-type="error"
.title=${this._i18n.localize(
"ui.panel.config.zha.network_health.loading_error"
)}
>
${this._error}
</ha-alert>
`;
}
if (!this._devices || !this._entityReg) {
return html`
<div class="loading">
<ha-spinner size="large"></ha-spinner>
</div>
`;
}
const devices = this._activeDevices(this._devices, this._haDevices);
const found = findings(devices, this._readings, this._links(this._devices));
if (subpage) {
// Grouped by room; within a room the worst reading stays first.
return this._renderSubpage(
subpage,
this._sorted(found[subpage], { keepOrder: true })
);
}
return html`
${this._renderSnapshotCard(devices)} ${this._renderAttentionCard(found)}
${this._renderWorthALookCard(found)}
`;
}
private _renderBar(counts: BandCounts): TemplateResult {
return html`
<div class="bar">
${BAR_BANDS.map((band: BarBand) =>
counts[band]
? html`<div
class="segment ${band}"
style=${`flex-grow:${counts[band]}`}
></div>`
: nothing
)}
</div>
`;
}
private _renderSnapshotCard(devices: ZHADevice[]): TemplateResult {
const counts = countBands(devices, this._links(this._devices!));
const rated = counts.strong + counts.fair + counts.weak + counts.offline;
return html`
<ha-card>
<div class="card-body">
<h2 class="card-title">
${this._i18n.localize(
"ui.panel.config.zha.network_health.network_title"
)}
</h2>
<p class="description">
${this._i18n.localize(
"ui.panel.config.zha.network_health.snapshot"
)}
</p>
${
rated
? html`
${this._renderBar(counts)}
<div class="legend">
${BAR_BANDS.filter((band) => counts[band]).map(
(band: BarBand) => html`
<span class="legend-item">
<span class="dot ${band}"></span>
${this._i18n.localize(
`ui.panel.config.zha.network_health.signal_${band}`,
{ count: counts[band] }
)}
</span>
`
)}
</div>
`
: nothing
}
<p class="updated">
<ha-svg-icon .path=${mdiClockOutline}></ha-svg-icon>
<span>
${this._i18n.localize(
"ui.panel.config.zha.network_health.updated",
{
relative_time: html`<ha-relative-time
.datetime=${this._updatedAt}
></ha-relative-time>`,
}
)}
</span>
</p>
</div>
</ha-card>
`;
}
private _renderAttentionCard(found: Findings) {
const count = attentionCount(found);
if (!count) {
return nothing;
}
// One row per device: an offline device whose setup did not finish is
// listed as offline, the more pressing of the two.
const rows = new Map<string, { key: AttentionKey; device: ZHADevice }>();
for (const key of NEEDS_ATTENTION) {
for (const device of found[key]) {
if (!rows.has(device.ieee)) {
rows.set(device.ieee, { key, device });
}
}
}
const sorted = this._sorted([...rows.values()].map((row) => row.device));
const title = this._i18n.localize(
"ui.panel.config.zha.network_health.attention_title",
{ count }
);
return html`
<ha-card>
<h2 class="card-title header">${title}</h2>
<ha-list-nav .ariaLabel=${title}>
${sorted.map((device) =>
this._renderAttentionDevice(rows.get(device.ieee)!.key, device)
)}
</ha-list-nav>
</ha-card>
`;
}
/** The entity that best stands for the device, for its icon. */
private _primaryState(device: ZHADevice): HassEntity | undefined {
const entityReg = this._entityRegById(this._entityReg!);
const states = device.entities
// Configuration and diagnostic entities, such as a child lock switch,
// say nothing about what the device is.
.filter(
(entity) =>
entity.entity_id && !entityReg.get(entity.entity_id)?.entity_category
)
.map((entity) => this._states?.[entity.entity_id!])
.filter((stateObj): stateObj is HassEntity => stateObj !== undefined);
for (const domain of PRIMARY_DOMAINS) {
const match = states.find((stateObj) =>
stateObj.entity_id.startsWith(`${domain}.`)
);
if (match) {
return match;
}
}
return undefined;
}
private _renderAttentionDevice(
key: AttentionKey,
device: ZHADevice
): TemplateResult {
const localize = this._i18n.localize;
const locale = this._i18n.locale;
const stateObj = this._primaryState(device);
const power = powerSource(device);
const seen = lastSeenAt(device);
const created = this._haDevices[device.device_reg_id]?.created_at;
const details =
key === "offline"
? [
// A mains device that is offline is often just switched off at
// the wall.
power
? localize(`ui.panel.config.zha.network_health.power_${power}`)
: undefined,
this._areaName(device),
seen
? localize("ui.panel.config.zha.network_health.last_seen", {
time: relativeTime(seen, locale),
})
: undefined,
]
: [
this._areaName(device),
created
? localize("ui.panel.config.zha.network_health.joined", {
time: relativeTime(new Date(created * 1000), locale),
})
: undefined,
];
return html`
<ha-list-item-button href=${`/config/zha/device/${device.ieee}`}>
${
stateObj
? html`<ha-state-icon
slot="start"
.stateObj=${stateObj}
></ha-state-icon>`
: html`<ha-svg-icon
slot="start"
.path=${mdiHelpCircleOutline}
></ha-svg-icon>`
}
<span slot="headline">${this._deviceName(device)}</span>
<span slot="supporting-text">
<span class="status"
>${localize(`ui.panel.config.zha.network_health.${key}`)}</span
>${details.filter(Boolean).map((detail) => ` · ${detail}`)}
</span>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>
`;
}
private _renderWorthALookCard(found: Findings) {
const keys = WORTH_A_LOOK.filter((key) => found[key].length);
if (!keys.length) {
return nothing;
}
const title = this._i18n.localize(
"ui.panel.config.zha.network_health.worth_a_look"
);
return html`
<ha-card>
<h2 class="card-title header">${title}</h2>
<ha-list-nav .ariaLabel=${title}>
${keys.map(
(key) => html`
<ha-list-item-button href=${`${BASE_PATH}/${slugify(key, "-")}`}>
<ha-svg-icon
slot="start"
.path=${FINDING_ICON[key]}
></ha-svg-icon>
<span slot="headline">
${this._i18n.localize(
`ui.panel.config.zha.network_health.${key}_count`,
{ count: found[key].length }
)}
</span>
<span slot="supporting-text">
${this._i18n.localize(
`ui.panel.config.zha.network_health.${key}_advice`
)}
</span>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>
`
)}
</ha-list-nav>
</ha-card>
`;
}
private _renderSubpage(key: WorthALookKey, devices: ZHADevice[]) {
const localize = this._i18n.localize;
return html`
<ha-card>
${
devices.length
? html`
<ha-list-nav
.ariaLabel=${localize(
`ui.panel.config.zha.network_health.${key}`
)}
>
${devices.map((device) =>
this._renderValueDevice(key, device)
)}
</ha-list-nav>
`
: html`
<ha-list-base>
<ha-list-item-base>
<span slot="headline">
${localize("ui.panel.config.zha.network_health.no_devices")}
</span>
</ha-list-item-base>
</ha-list-base>
`
}
<div class="card-actions">
<ha-button appearance="plain" href="/config/zha/visualization">
${localize("ui.panel.config.zha.network_health.show_map")}
</ha-button>
</div>
</ha-card>
<p class="tip">
${localize(`ui.panel.config.zha.network_health.${key}_tip`)}
</p>
`;
}
/** A device row with the value of its finding in front of the chevron. */
private _renderValueDevice(
key: WorthALookKey,
device: ZHADevice
): TemplateResult {
let icon: string;
let iconClass: string;
let value: string;
if (key === "low_battery") {
const level = this._readings.batteryLevel(device)!;
icon = batteryLevelIconPath(level);
iconClass = "warning";
value = formatNumberWithUnit(level, "%", this._i18n.locale);
} else {
const links = this._links(this._devices!);
const band = signalBand(device, links);
const lqi = linkQuality(device, links);
icon = BAND_ICON[band];
iconClass = `signal ${band}`;
value = this._i18n.localize(
"ui.panel.config.zha.network_health.lqi_value",
{
lqi:
lqi === null
? "—"
: formatNumberWithUnit(lqi, null, this._i18n.locale),
}
);
}
const parent =
key === "weak_signal"
? this._parentByIeee(this._devices!)[device.ieee]
: undefined;
const details = [
this._areaName(device),
device.model,
parent
? this._i18n.localize("ui.panel.config.zha.network_health.via_router", {
router: parent,
})
: undefined,
].filter(Boolean);
return html`
<ha-list-item-button href=${`/config/zha/device/${device.ieee}`}>
<ha-svg-icon
slot="start"
class=${iconClass}
.path=${icon}
></ha-svg-icon>
<span slot="headline">${this._deviceName(device)}</span>
<span slot="supporting-text">${details.join(" · ")}</span>
<span slot="end" class="value">${value}</span>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>
`;
}
private _sorted(
devices: ZHADevice[],
{ keepOrder = false } = {}
): ZHADevice[] {
return sortByArea(
devices,
this._areaName,
keepOrder ? null : this._deviceName,
(a, b) => stringCompare(a, b, this._i18n.language)
);
}
static get styles(): CSSResultGroup {
return [
haStyle,
css`
.container {
padding: var(--ha-space-2) var(--ha-content-gutter) var(--ha-space-4);
display: flex;
flex-direction: column;
gap: var(--ha-space-4);
max-width: var(--ha-content-width-narrow);
margin: auto;
}
ha-card {
overflow: hidden;
}
.loading {
display: flex;
justify-content: center;
padding: var(--ha-space-8);
}
.card-title {
margin: 0;
font-size: var(--ha-font-size-2xl);
font-weight: var(--ha-font-weight-normal);
line-height: var(--ha-line-height-condensed);
color: var(--primary-text-color);
}
.card-title.header {
padding: var(--ha-space-4) var(--ha-space-4) var(--ha-space-2);
}
/* Snapshot card */
.card-body {
padding: var(--ha-space-4);
}
.description {
margin: var(--ha-space-2) 0 var(--ha-space-4);
color: var(--secondary-text-color);
font-size: var(--ha-font-size-m);
line-height: var(--ha-line-height-normal);
}
.bar {
display: flex;
gap: 2px;
height: var(--ha-space-2);
border-radius: var(--ha-border-radius-sm);
overflow: hidden;
}
.segment {
min-width: var(--ha-space-2);
}
.segment.strong,
.dot.strong {
background-color: var(--success-color);
}
/* A lighter shade of strong: fair is fine, just not as robust. */
.segment.fair,
.dot.fair {
background-color: var(--ha-color-green-70);
}
.segment.weak,
.dot.weak {
background-color: var(--warning-color);
}
.segment.offline,
.dot.offline {
background-color: var(--disabled-color);
}
.legend {
display: flex;
flex-wrap: wrap;
gap: var(--ha-space-1) var(--ha-space-4);
margin-top: var(--ha-space-2);
color: var(--secondary-text-color);
font-size: var(--ha-font-size-m);
}
.legend-item {
display: flex;
align-items: center;
gap: var(--ha-space-1);
}
.dot {
width: var(--ha-space-2);
height: var(--ha-space-2);
border-radius: var(--ha-border-radius-circle);
flex-shrink: 0;
}
.updated {
display: flex;
align-items: center;
gap: var(--ha-space-2);
margin: var(--ha-space-4) 0 0;
color: var(--secondary-text-color);
font-size: var(--ha-font-size-m);
}
.updated ha-svg-icon {
--mdc-icon-size: 18px;
}
/* Device lists */
ha-state-icon[slot="start"],
ha-svg-icon[slot="start"] {
color: var(--secondary-text-color);
}
.status {
color: var(--error-color);
}
.tip {
margin: 0;
padding: 0 var(--ha-space-4);
color: var(--secondary-text-color);
font-size: var(--ha-font-size-s);
line-height: var(--ha-line-height-normal);
}
.value {
color: var(--secondary-text-color);
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.signal.strong {
color: var(--success-color);
}
.signal.fair {
color: var(--ha-color-green-70);
}
/* ha-svg-icon raises the specificity above the slot rule above. */
.signal.weak,
ha-svg-icon.warning {
color: var(--warning-color);
}
.signal.unknown {
color: var(--disabled-text-color);
}
`,
];
}
}
declare global {
interface HTMLElementTagNameMap {
"zha-network-health-page": ZHANetworkHealthPage;
}
}
+1 -1
View File
@@ -207,7 +207,7 @@ export const colorStyles = css`
--state-climate-fan_only-color: var(--cyan-color);
--state-climate-heat-color: var(--deep-orange-color);
--state-climate-heat-cool-color: var(--amber-color);
--state-cover-active-color: var(--purple-color);
--state-cover-active-color: var(--blue-color);
--state-device_tracker-active-color: var(--blue-color);
--state-device_tracker-home-color: var(--green-color);
--state-fan-active-color: var(--cyan-color);
+34 -3
View File
@@ -7904,9 +7904,6 @@
"not_provided": "Not provided",
"unmanageable": "Unmanageable"
},
"status_pairs": {
"activation": "Activation"
},
"headers": {
"state_icon": "State icon",
"entity": "Entity",
@@ -8704,6 +8701,9 @@
"options_description": "Configure device behavior and network timeouts",
"network_info_title": "Network information",
"network_info_description": "View channel and coordinator details",
"network_health_title": "Network health",
"network_health_description": "Check signal strength and reachability of your devices",
"network_health_attention": "{count, plural,\n one {# device needs}\n other {# devices need}\n} attention",
"backup_restore_title": "Backup and restore",
"backup_restore_description_short": "Download or migrate your Zigbee network backup",
"backup_restore_description": "Back up or restore your Zigbee adapter. The backup only contains your network information.",
@@ -8735,6 +8735,37 @@
"text": "Zigbee and Thread share the same adapter and must use the same channel. Change the channel of both networks by reconfiguring multiprotocol from the hardware menu."
}
},
"network_health": {
"title": "Network health",
"loading_error": "Failed to load the device list",
"network_title": "Your Zigbee network",
"snapshot": "Snapshot of your Zigbee network. Signal strength changes often, so a single weak value is not a problem.",
"signal_strong": "{count} strong",
"signal_fair": "{count} fair",
"signal_weak": "{count} weak",
"signal_offline": "{count} offline",
"updated": "Updated {relative_time}",
"lqi_value": "LQI {lqi}",
"attention_title": "{count, plural,\n one {# device needs attention}\n other {# devices need attention}\n}",
"worth_a_look": "Worth a look",
"no_devices": "No devices",
"via_router": "via {router}",
"last_seen": "last seen {time}",
"joined": "joined {time}",
"power_mains": "mains",
"power_battery": "battery",
"offline": "Offline",
"setup_unfinished": "Setup not finished",
"weak_signal": "Weak signal",
"weak_signal_count": "{count, plural,\n one {# device with a weak signal}\n other {# devices with a weak signal}\n}",
"weak_signal_advice": "Usually harmless. A mains-powered device in between helps.",
"weak_signal_tip": "Usually harmless. A mains-powered device between a weak device and its router steadies the link.",
"low_battery": "Low battery",
"low_battery_count": "{count, plural,\n one {# device with a low battery}\n other {# devices with a low battery}\n}",
"low_battery_advice": "Replace the battery before the device goes offline.",
"low_battery_tip": "Battery levels can drop suddenly. A weak signal drains them faster.",
"show_map": "Show map"
},
"add_device_page": {
"spinner": "Waiting for Zigbee devices to join…",
"pairing_mode": "Make sure your devices are in pairing mode. Check the instructions of your device or {documentation_link} on how to do this.",
@@ -0,0 +1,482 @@
import { describe, expect, it } from "vitest";
import type { ZHADevice } from "../../../../../src/data/zha";
import { ZHADeviceType } from "../../../../../src/data/zha";
import type { DeviceReadings } from "../../../../../src/panels/config/integrations/integration-panels/zha/network-health";
import {
attentionCount,
countBands,
findings,
isSetupUnfinished,
lastSeenAt,
linkQuality,
managedDevices,
neighborLinkQualities,
parentByIeee,
powerSource,
signalBand,
sortByArea,
} from "../../../../../src/panels/config/integrations/integration-panels/zha/network-health";
const NOW = new Date("2026-01-01T12:00:00Z").getTime();
const minutesAgo = (minutes: number) =>
new Date(NOW - minutes * 60000).toISOString();
const device = (overrides: Partial<ZHADevice> & { ieee: string }): ZHADevice =>
({
available: true,
name: overrides.ieee,
nwk: 0,
lqi: 200,
rssi: "-50",
last_seen: minutesAgo(1),
manufacturer: "ACME",
model: "Model",
quirk_applied: false,
quirk_class: "",
entities: [{ entity_id: "sensor.test" }],
manufacturer_code: 0,
device_reg_id: overrides.ieee,
device_type: ZHADeviceType.EndDevice,
active_coordinator: false,
signature: {},
neighbors: [],
routes: [],
...overrides,
}) as ZHADevice;
const noReadings: DeviceReadings = {
batteryLevel: () => null,
isDisabled: () => false,
hasRegisteredEntities: () => false,
};
describe("signalBand", () => {
it("reads the link quality in three steps", () => {
expect(signalBand(device({ ieee: "a", lqi: 200 }))).toBe("strong");
expect(signalBand(device({ ieee: "b", lqi: 45 }))).toBe("fair");
expect(signalBand(device({ ieee: "c", lqi: 12 }))).toBe("weak");
});
it("puts the thresholds themselves in the better band", () => {
expect(signalBand(device({ ieee: "a", lqi: 60 }))).toBe("strong");
expect(signalBand(device({ ieee: "b", lqi: 59 }))).toBe("fair");
expect(signalBand(device({ ieee: "c", lqi: 30 }))).toBe("fair");
expect(signalBand(device({ ieee: "d", lqi: 29 }))).toBe("weak");
});
it("does not guess when there is no reading", () => {
expect(signalBand(device({ ieee: "a", lqi: null as any }))).toBe("unknown");
expect(signalBand(device({ ieee: "b", lqi: undefined as any }))).toBe(
"unknown"
);
});
it("counts a link quality of zero as weak, not as missing", () => {
expect(signalBand(device({ ieee: "a", lqi: 0 }))).toBe("weak");
});
});
describe("countBands", () => {
it("counts every device exactly once", () => {
const counts = countBands([
device({ ieee: "a", lqi: 200 }),
device({ ieee: "b", lqi: 100 }),
device({ ieee: "c", lqi: 45 }),
device({ ieee: "d", lqi: 12 }),
device({ ieee: "e", lqi: null as any }),
]);
expect(counts).toEqual({
strong: 2,
fair: 1,
weak: 1,
offline: 0,
unknown: 1,
});
});
it("reports a silent device as offline, not by its last reading", () => {
const counts = countBands([
device({ ieee: "a", lqi: 200 }),
device({ ieee: "b", lqi: 200, available: false }),
]);
expect(counts.strong).toBe(1);
expect(counts.offline).toBe(1);
});
});
describe("managedDevices", () => {
it("leaves out the coordinator", () => {
const devices = managedDevices([
device({ ieee: "coordinator", active_coordinator: true }),
device({ ieee: "a" }),
]);
expect(devices.map((d) => d.ieee)).toEqual(["a"]);
});
});
describe("isSetupUnfinished", () => {
it("recognises a device that exposes nothing", () => {
expect(
isSetupUnfinished(device({ ieee: "a", entities: [] }), noReadings)
).toBe(true);
expect(isSetupUnfinished(device({ ieee: "b" }), noReadings)).toBe(false);
});
it("does not mistake a device whose entities are all disabled", () => {
expect(
isSetupUnfinished(device({ ieee: "a", entities: [] }), {
hasRegisteredEntities: () => true,
})
).toBe(false);
});
});
describe("powerSource", () => {
it("reads mains and battery, and does not guess otherwise", () => {
expect(powerSource(device({ ieee: "a", power_source: "Mains" }))).toBe(
"mains"
);
expect(
powerSource(device({ ieee: "b", power_source: "Battery or Unknown" }))
).toBe("battery");
expect(powerSource(device({ ieee: "c" }))).toBeUndefined();
});
});
describe("lastSeenAt", () => {
it("reads a valid stamp and drops an empty or malformed one", () => {
expect(lastSeenAt(device({ ieee: "a" }))?.getTime()).toBe(
new Date(minutesAgo(1)).getTime()
);
expect(lastSeenAt(device({ ieee: "b", last_seen: "" }))).toBeUndefined();
expect(
lastSeenAt(device({ ieee: "c", last_seen: "not a date" }))
).toBeUndefined();
});
});
describe("parentByIeee", () => {
it("skips the neighbour table of an unavailable router", () => {
const parents = parentByIeee([
device({
ieee: "old-router",
available: false,
user_given_name: "Old plug",
neighbors: [
{
ieee: "child",
nwk: "1",
lqi: "60",
depth: "1",
relationship: "Child",
},
],
}),
device({
ieee: "router",
user_given_name: "Hallway plug",
neighbors: [
{
ieee: "child",
nwk: "1",
lqi: "60",
depth: "1",
relationship: "Child",
},
],
}),
device({ ieee: "child" }),
]);
expect(parents).toEqual({ child: "Hallway plug" });
});
it("names the router a device hangs off", () => {
const parents = parentByIeee([
device({
ieee: "router",
user_given_name: "Hallway plug",
neighbors: [
{
ieee: "child",
nwk: "1",
lqi: "60",
depth: "1",
relationship: "Child",
},
{
ieee: "sibling",
nwk: "2",
lqi: "60",
depth: "1",
relationship: "Sibling",
},
],
}),
device({ ieee: "child" }),
]);
expect(parents).toEqual({ child: "Hallway plug" });
});
it("falls back to the device name when the user gave none", () => {
const parents = parentByIeee([
device({
ieee: "router",
name: "0x1234",
neighbors: [
{
ieee: "child",
nwk: "1",
lqi: "60",
depth: "1",
relationship: "Child",
},
],
}),
device({ ieee: "child" }),
]);
expect(parents.child).toBe("0x1234");
});
it("leaves out routers listed as another router's child", () => {
const parents = parentByIeee([
device({
ieee: "plug-2",
device_type: ZHADeviceType.Router,
neighbors: [
{
ieee: "plug-1",
nwk: "1",
lqi: "9",
depth: "1",
relationship: "Child",
},
],
}),
device({ ieee: "plug-1", device_type: ZHADeviceType.Router }),
]);
expect(parents).toEqual({});
});
});
describe("findings", () => {
it("lists offline devices and devices whose setup did not finish", () => {
const found = findings(
[
device({ ieee: "off", available: false }),
device({ ieee: "empty", entities: [] }),
device({ ieee: "fine" }),
],
noReadings
);
expect(found.offline.map((d) => d.ieee)).toEqual(["off"]);
expect(found.setup_unfinished.map((d) => d.ieee)).toEqual(["empty"]);
});
it("sorts weak devices worst first", () => {
const found = findings(
[
device({ ieee: "a", lqi: 25 }),
device({ ieee: "b", lqi: 5 }),
device({ ieee: "c", lqi: 15 }),
],
noReadings
);
expect(found.weak_signal.map((d) => d.ieee)).toEqual(["b", "c", "a"]);
});
it("lists an offline device only as offline, not by its last readings", () => {
const found = findings([device({ ieee: "a", lqi: 5, available: false })], {
...noReadings,
batteryLevel: () => 3,
});
expect(found.offline.map((d) => d.ieee)).toEqual(["a"]);
expect(found.weak_signal).toEqual([]);
expect(found.low_battery).toEqual([]);
});
it("lists low batteries emptiest first and includes the threshold", () => {
const levels: Record<string, number> = { a: 20, b: 5, c: 21 };
const found = findings(
[device({ ieee: "a" }), device({ ieee: "b" }), device({ ieee: "c" })],
{ ...noReadings, batteryLevel: (d) => levels[d.ieee] }
);
expect(found.low_battery.map((d) => d.ieee)).toEqual(["b", "a"]);
});
it("ignores devices without a battery sensor", () => {
expect(findings([device({ ieee: "a" })], noReadings).low_battery).toEqual(
[]
);
});
});
describe("findings with registry readings", () => {
it("leaves out devices disabled in the device registry", () => {
const found = findings(
[device({ ieee: "a", available: false, entities: [] })],
{ ...noReadings, isDisabled: () => true }
);
expect(found.offline).toEqual([]);
expect(found.setup_unfinished).toEqual([]);
});
});
describe("attentionCount", () => {
it("counts a device that is offline and not set up only once", () => {
const found = findings(
[
device({ ieee: "a", available: false, entities: [] }),
device({ ieee: "b", available: false }),
device({ ieee: "c", lqi: 5 }),
],
noReadings
);
expect(attentionCount(found)).toBe(2);
});
});
describe("sortByArea", () => {
const areas: Record<string, string> = { kitchen: "Kitchen", attic: "Attic" };
const areaName = (d: ZHADevice) => (d.area_id ? areas[d.area_id] : undefined);
const name = (d: ZHADevice) => d.name;
it("sorts by area, then by name, with unassigned devices last", () => {
const sorted = sortByArea(
[
device({ ieee: "z", name: "Zeta" }),
device({ ieee: "k2", name: "Lamp", area_id: "kitchen" }),
device({ ieee: "a", name: "Plug", area_id: "attic" }),
device({ ieee: "k1", name: "Bulb", area_id: "kitchen" }),
],
areaName,
name
);
expect(sorted.map((d) => d.ieee)).toEqual(["a", "k1", "k2", "z"]);
});
it("keeps the incoming order within an area without a name function", () => {
const sorted = sortByArea(
[
device({ ieee: "k2", name: "Lamp", area_id: "kitchen" }),
device({ ieee: "a", name: "Plug", area_id: "attic" }),
device({ ieee: "k1", name: "Bulb", area_id: "kitchen" }),
],
areaName,
null
);
expect(sorted.map((d) => d.ieee)).toEqual(["a", "k2", "k1"]);
});
});
describe("neighborLinkQualities", () => {
const entry = (
ieee: string,
lqi: string,
relationship: "Child" | "Sibling" | "Parent" | "PreviousChild" = "Sibling"
) => ({ ieee, nwk: "1", lqi, depth: "1", relationship });
it("takes an end device's link from the router it is a child of", () => {
const links = neighborLinkQualities([
device({
ieee: "parent",
neighbors: [entry("child", "40", "Child")],
}),
device({ ieee: "other", neighbors: [entry("child", "200")] }),
device({ ieee: "child" }),
]);
expect(links.child).toBe(40);
});
it("ignores a former parent's entry for an end device", () => {
const links = neighborLinkQualities([
device({
ieee: "old-parent",
neighbors: [entry("child", "200", "PreviousChild")],
}),
device({ ieee: "child", device_type: ZHADeviceType.EndDevice }),
]);
// No current parent entry: the device falls back to its last packet.
expect(links.child).toBeUndefined();
});
it("takes a router's best link from any neighbour", () => {
const links = neighborLinkQualities([
device({ ieee: "a", neighbors: [entry("router", "35")] }),
device({ ieee: "b", neighbors: [entry("router", "120")] }),
device({ ieee: "router", device_type: ZHADeviceType.Router }),
]);
expect(links.router).toBe(120);
});
it("ignores a router listed as another router's child", () => {
// Seen on a real network: a plug listed a well-connected plug as its
// child with LQI 9, while the coordinator heard it at 105.
const links = neighborLinkQualities([
device({
ieee: "plug-2",
device_type: ZHADeviceType.Router,
neighbors: [entry("plug-1", "9", "Child")],
}),
device({
ieee: "coordinator",
active_coordinator: true,
device_type: ZHADeviceType.Coordinator,
neighbors: [entry("plug-1", "105")],
}),
device({ ieee: "plug-1", device_type: ZHADeviceType.Router }),
]);
expect(links["plug-1"]).toBe(105);
});
it("skips unavailable routers and unreadable values", () => {
const links = neighborLinkQualities([
device({
ieee: "gone",
available: false,
neighbors: [entry("x", "250", "Child")],
}),
device({ ieee: "a", neighbors: [entry("x", ""), entry("y", "n/a")] }),
]);
expect(links).toEqual({});
});
});
describe("linkQuality", () => {
it("prefers the neighbour table and falls back to the last packet", () => {
const d = device({ ieee: "a", lqi: 200 });
expect(linkQuality(d, { a: 20 })).toBe(20);
expect(linkQuality(d, {})).toBe(200);
expect(linkQuality(device({ ieee: "b", lqi: null as any }))).toBeNull();
});
it("rates a device weak by its neighbour-table link", () => {
const found = findings([device({ ieee: "a", lqi: 200 })], noReadings, {
a: 12,
});
expect(found.weak_signal.map((d) => d.ieee)).toEqual(["a"]);
expect(signalBand(device({ ieee: "a", lqi: 200 }), { a: 12 })).toBe("weak");
});
});