From d2170ad2fa6a477cb473c18f0596a5ee4b3c3526 Mon Sep 17 00:00:00 2001 From: Frank Mainz Date: Fri, 6 Nov 2026 19:16:24 +0100 Subject: [PATCH 1/9] Prepare HA-IPFire 0.3.7 beta --- README-de.md | 7 +- README.md | 7 +- custom_components/ipfire/__init__.py | 9 +- custom_components/ipfire/button.py | 10 +- custom_components/ipfire/coordinator.py | 77 +++++++++ custom_components/ipfire/icons.json | 8 + custom_components/ipfire/manifest.json | 4 +- custom_components/ipfire/sensor.py | 91 ++++++++++- custom_components/ipfire/translations/de.json | 16 ++ custom_components/ipfire/translations/en.json | 16 ++ custom_components/ipfire/update.py | 152 ++++++++++++++++++ 11 files changed, 383 insertions(+), 14 deletions(-) create mode 100644 custom_components/ipfire/update.py diff --git a/README-de.md b/README-de.md index a9de650..f9bdc6c 100644 --- a/README-de.md +++ b/README-de.md @@ -87,6 +87,7 @@ HA-IPFire bietet folgende Funktionen: * DHCP-Lease-Sensor mit Clientdaten¹ * Trafficzähler für einzelne Netzwerkzonen¹ * Neustartstatus und Gesamtzahl verfügbarer Updates¹ +* Verfügbare IPFire-Updates anzeigen und das vollständige Pakfire-Upgrade in Home Assistant installieren¹ ¹Benötigt api.cgi aus [IPFire-API](https://github.com/FMainz/IPFire-API) @@ -181,12 +182,14 @@ Sensoren werden nur für interne Schnittstellen angelegt, die auf der IPFire-Fir ### DHCP-Leases -* **Aktive DHCP-Leases** – Anzahl aktiver DHCP-Leases. Das Attribut `leases` enthält die von IPFire gemeldeten Clientdaten mit IP-Adresse, MAC-Adresse, Hostname, Ablaufzeit und Status. Du findest sie in Home Assistant in der Detailansicht des Sensors unter den Attributen. +* **Aktive DHCP-Leases** – Anzahl aktiver DHCP-Leases. Das Attribut `leases` enthält die von IPFire gemeldeten Clientdaten mit IP-Adresse, MAC-Adresse, Hostname, Ablaufzeit und Status. HA-IPFire ergänzt außerdem `mac_vendor`, ermittelt anhand des MAC-Adresspräfixes aus einer lokalen Zuordnungstabelle. Bei privaten oder nicht registrierten MAC-Adressen kann der Wert fehlen oder unzutreffend sein. Die Lease-Details findest du in Home Assistant in der Detailansicht des Sensors unter den Attributen. ### Systemstatus * **Neustart erforderlich** – zeigt an, wenn IPFire nach einem Update einen Neustart verlangt. Benötigt eine aktuelle Version von `api.cgi`; bei älteren Versionen bleibt der Sensor unbekannt. -* **Updates verfügbar** – Gesamtzahl der verfügbaren Updates, einschließlich Core- und Paket-Updates. +* **Updates verfügbar** – Gesamtzahl der verfügbaren Updates, einschließlich Core- und Paket-Updates. Das Attribut `updates` listet die einzelnen Core- und Paket-Updates mit ihren Versionen auf. +* **IPFire-Systemupdates** – native Home-Assistant-Update-Entität. Sie erscheint im Update-Bereich von Home Assistant, wenn Updates verfügbar sind; die Release-Zusammenfassung listet Core- und Paket-Updates auf. Mit „Installieren“ wird das vollständige Pakfire-Upgrade gestartet, da IPFire keine Auswahl einzelner Updates unterstützt. +* **Update-Vorgang** – zeigt an, ob ein über die API gestartetes Update inaktiv ist, läuft, abgeschlossen ist oder fehlgeschlagen ist. ### Internetverbindung diff --git a/README.md b/README.md index e95b4c0..ebcc97c 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,7 @@ HA-IPFire provides the following features: * DHCP lease sensor with client details¹ * Traffic counters for individual network zones¹ * Reboot-required status and total available update count¹ +* Review available IPFire updates and install the full Pakfire upgrade from Home Assistant¹ ¹Requires `api.cgi` from [IPFire-API](https://github.com/FMainz/IPFire-API). @@ -183,12 +184,14 @@ Sensors are created only for internal interfaces configured on the IPFire firewa ### DHCP leases -* **Active DHCP Leases** – number of active DHCP leases. The `leases` attribute contains the client records reported by IPFire, including IP address, MAC address, hostname, expiry, and status. To view them, open the sensor's more-info panel in Home Assistant and inspect its attributes. +* **Active DHCP Leases** – number of active DHCP leases. The `leases` attribute contains the client records reported by IPFire, including IP address, MAC address, hostname, expiry, and status. HA-IPFire also adds `mac_vendor`, looked up locally from the MAC address prefix. This may be unavailable or inaccurate for private or unregistered MAC addresses. To view the lease details, open the sensor's more-info panel in Home Assistant and inspect its attributes. ### System status * **Reboot Required** – indicates when IPFire requires a reboot after an update. Requires a current version of `api.cgi`; older versions leave the sensor unknown. -* **Updates Available** – total number of available updates, including core and package updates. +* **Updates Available** – total number of available updates, including core and package updates. Its `updates` attribute lists the exact core/package updates and versions. +* **IPFire System Updates** – native Home Assistant update entity. It appears in Home Assistant's Updates section when updates are available; its release summary lists the included core and package updates. Installing it starts the full Pakfire upgrade, because IPFire does not support selecting individual updates. +* **Update Operation** – reports whether an API-started update is idle, running, completed, or failed. ### Internet connection diff --git a/custom_components/ipfire/__init__.py b/custom_components/ipfire/__init__.py index 5aed5f4..809f242 100644 --- a/custom_components/ipfire/__init__.py +++ b/custom_components/ipfire/__init__.py @@ -3,6 +3,8 @@ from dataclasses import dataclass from datetime import timedelta +import aiooui + from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv @@ -20,7 +22,7 @@ from .coordinator import IPFireCoordinator -PLATFORMS: list[str] = ["binary_sensor", "button", "sensor"] +PLATFORMS: list[str] = ["binary_sensor", "button", "sensor", "update"] CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) @@ -58,6 +60,9 @@ async def async_setup_entry( ) -> bool: """Set up HA-IPFire from a config entry.""" + if not aiooui.is_loaded(): + await aiooui.async_load() + session = async_get_clientsession(hass) scan_interval = entry.options.get( @@ -100,4 +105,4 @@ async def async_unload_entry( return await hass.config_entries.async_unload_platforms( entry, PLATFORMS, - ) \ No newline at end of file + ) diff --git a/custom_components/ipfire/button.py b/custom_components/ipfire/button.py index 6ccceef..74c2689 100644 --- a/custom_components/ipfire/button.py +++ b/custom_components/ipfire/button.py @@ -48,7 +48,7 @@ async def async_setup_entry( coordinator: IPFireCoordinator = entry.runtime_data.coordinator async_add_entities( - IPFireConnectionButton( + IPFireActionButton( coordinator, entry, description, @@ -57,11 +57,11 @@ async def async_setup_entry( ) -class IPFireConnectionButton( +class IPFireActionButton( CoordinatorEntity[IPFireCoordinator], ButtonEntity, ): - """Represent an IPFire connection control button.""" + """Represent an IPFire control button.""" _attr_has_entity_name = True @@ -89,5 +89,5 @@ async def async_press(self) -> None: if self.entity_description.action == "connect": await self.coordinator.async_connect() - else: - await self.coordinator.async_disconnect() \ No newline at end of file + elif self.entity_description.action == "disconnect": + await self.coordinator.async_disconnect() diff --git a/custom_components/ipfire/coordinator.py b/custom_components/ipfire/coordinator.py index aefa4ef..1e9deb3 100644 --- a/custom_components/ipfire/coordinator.py +++ b/custom_components/ipfire/coordinator.py @@ -102,6 +102,8 @@ class IPFireData: system: IPFireSystemData network: IPFireNetworkData dhcp_leases: tuple[dict[str, object], ...] | None + available_updates: tuple[dict[str, object], ...] | None + update_operation: dict[str, object] | None services: dict[str, bool] addons: dict[str, dict[str, bool]] @@ -208,6 +210,7 @@ async def _async_update_data(self) -> IPFireData: dhcp = payload.get("dhcp", {}) services = payload.get("services", {}) addons = payload.get("addons", {}) + updates = payload.get("updates", {}) if not isinstance(connection, dict): raise ValueError("Invalid connection data from IPFire") @@ -229,6 +232,25 @@ async def _async_update_data(self) -> IPFireData: if not isinstance(addons, dict): raise ValueError("Invalid addons data from IPFire") + if not isinstance(updates, dict): + raise ValueError("Invalid update data from IPFire") + + raw_available_updates = updates.get("available") + if raw_available_updates is not None and ( + not isinstance(raw_available_updates, list) + or not all( + isinstance(update, dict) + for update in raw_available_updates + ) + ): + raise ValueError("Invalid available update list from IPFire") + + raw_update_operation = updates.get("operation") + if raw_update_operation is not None and not isinstance( + raw_update_operation, dict + ): + raise ValueError("Invalid update operation data from IPFire") + raw_interfaces = network.get("interfaces", {}) if not isinstance(raw_interfaces, dict): raise ValueError("Invalid network interface data from IPFire") @@ -415,6 +437,16 @@ async def _async_update_data(self) -> IPFireData: system=system_data, network=network_data, dhcp_leases=dhcp_leases, + available_updates=( + tuple(raw_available_updates) + if isinstance(raw_available_updates, list) + else None + ), + update_operation=( + dict(raw_update_operation) + if isinstance(raw_update_operation, dict) + else None + ), services=services, addons=addons, ) @@ -427,6 +459,51 @@ async def async_disconnect(self) -> None: """Disconnect the IPFire Internet connection.""" await self._async_connection_action("disconnect") + async def async_start_upgrade(self) -> None: + """Start installing all updates available on IPFire.""" + try: + async with self.session.post( + self.api_url, + auth=self._auth(), + ssl=self.verify_ssl, + headers={"X-IPFire-API": "1"}, + data={"action": "upgrade"}, + timeout=aiohttp.ClientTimeout(total=15), + ) as response: + if response.status in (401, 403): + raise ConfigEntryAuthFailed( + "Invalid IPFire username or password" + ) + + try: + payload = await response.json(content_type=None) + except (ValueError, TypeError): + payload = {} + + if not isinstance(payload, dict): + raise UpdateFailed( + "IPFire returned an invalid upgrade response" + ) + + if ( + response.status >= 400 + or payload.get("result") != "accepted" + ): + error = payload.get("error", "unknown_error") + raise UpdateFailed( + f"Unable to start IPFire upgrade: {error}" + ) + + except ConfigEntryAuthFailed: + raise + + except (aiohttp.ClientError, ValueError) as err: + raise UpdateFailed( + f"Unable to start IPFire upgrade: {err}" + ) from err + + await self.async_request_refresh() + async def _async_connection_action(self, action: str) -> None: """Execute a connection action on IPFire.""" if action not in {"connect", "disconnect"}: diff --git a/custom_components/ipfire/icons.json b/custom_components/ipfire/icons.json index 15cbe7c..08a5c39 100644 --- a/custom_components/ipfire/icons.json +++ b/custom_components/ipfire/icons.json @@ -123,6 +123,14 @@ }, "updates_available": { "default": "mdi:package-up" + }, + "update_operation": { + "default": "mdi:progress-clock" + } + }, + "update": { + "system_updates": { + "default": "mdi:package-up" } }, "binary_sensor": { diff --git a/custom_components/ipfire/manifest.json b/custom_components/ipfire/manifest.json index 589fe6d..ddf7ebc 100644 --- a/custom_components/ipfire/manifest.json +++ b/custom_components/ipfire/manifest.json @@ -9,6 +9,6 @@ "integration_type": "device", "iot_class": "local_polling", "issue_tracker": "https://github.com/FMainz/HA-IPFire/issues", - "requirements": [], - "version": "0.3.6" + "requirements": ["aiooui==0.1.9"], + "version": "0.3.7-beta.1" } diff --git a/custom_components/ipfire/sensor.py b/custom_components/ipfire/sensor.py index 13644f2..5d518ca 100644 --- a/custom_components/ipfire/sensor.py +++ b/custom_components/ipfire/sensor.py @@ -2,6 +2,8 @@ from dataclasses import dataclass +import aiooui + from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, @@ -348,6 +350,7 @@ async def async_setup_entry( ] entities.append(IPFireDHCPLeasesSensor(coordinator, entry)) + entities.append(IPFireUpdateOperationSensor(coordinator, entry)) # The overall Download/Upload sensors represent the RED (WAN) interface. # Add separate byte counters for the internal GREEN, ORANGE, and BLUE zones. @@ -412,6 +415,76 @@ def native_value(self) -> int | float | str | None: return value + @property + def extra_state_attributes(self) -> dict[str, object] | None: + """Expose update details and operation state on the update count sensor.""" + if ( + self.entity_description.key != "package_updates" + or self.coordinator.data is None + ): + return None + + data = self.coordinator.data + attributes: dict[str, object] = {} + if data.available_updates is not None: + attributes["updates"] = [ + dict(update) for update in data.available_updates + ] + if data.update_operation is not None: + attributes["operation"] = dict(data.update_operation) + return attributes or None + + +class IPFireUpdateOperationSensor( + CoordinatorEntity[IPFireCoordinator], + SensorEntity, +): + """Report the state of an update started through the API.""" + + _attr_has_entity_name = True + _attr_translation_key = "update_operation" + _attr_entity_registry_enabled_default = True + + def __init__( + self, + coordinator: IPFireCoordinator, + entry: ConfigEntry, + ) -> None: + """Initialize the update operation sensor.""" + super().__init__(coordinator) + self._attr_unique_id = f"{entry.entry_id}_update_operation" + self._attr_device_info = DeviceInfo( + identifiers={("ipfire", entry.entry_id)}, + name="IPFire", + manufacturer="IPFire", + model="Firewall", + ) + + @property + def native_value(self) -> str | None: + """Return the Pakfire update operation state.""" + if self.coordinator.data is None: + return None + operation = self.coordinator.data.update_operation + if operation is None: + return None + status = operation.get("status") + return status if isinstance(status, str) else None + + @property + def extra_state_attributes(self) -> dict[str, object] | None: + """Expose operation timestamps and errors for diagnostics.""" + if self.coordinator.data is None: + return None + operation = self.coordinator.data.update_operation + if operation is None: + return None + return { + key: operation[key] + for key in ("started_at", "finished_at", "exit_code", "error") + if key in operation + } + class IPFireDHCPLeasesSensor( CoordinatorEntity[IPFireCoordinator], @@ -457,7 +530,23 @@ def extra_state_attributes(self) -> dict[str, list[dict[str, object]]] | None: leases = self.coordinator.data.dhcp_leases if leases is None: return None - return {"leases": [dict(lease) for lease in leases]} + + lease_attributes: list[dict[str, object]] = [] + for lease in leases: + lease_data = dict(lease) + mac_address = lease_data.get("mac_address") or lease_data.get( + "mac" + ) + if isinstance(mac_address, str) and mac_address: + try: + lease_data["mac_vendor"] = aiooui.get_vendor(mac_address) + except (TypeError, ValueError): + lease_data["mac_vendor"] = None + else: + lease_data["mac_vendor"] = None + lease_attributes.append(lease_data) + + return {"leases": lease_attributes} class IPFireInterfaceTrafficSensor( diff --git a/custom_components/ipfire/translations/de.json b/custom_components/ipfire/translations/de.json index 4cc7775..0ef9fac 100644 --- a/custom_components/ipfire/translations/de.json +++ b/custom_components/ipfire/translations/de.json @@ -187,6 +187,17 @@ "updates_available": { "name": "Updates verfügbar" }, + "update_operation": { + "name": "Update-Vorgang", + "state": { + "idle": "Inaktiv", + "starting": "Startet", + "running": "Läuft", + "completed": "Abgeschlossen", + "failed": "Fehlgeschlagen", + "unknown": "Unbekannt" + } + }, "external_ip": { "name": "Externe IP-Adresse" }, @@ -257,6 +268,11 @@ "name": "D-Bus Daemon" } }, + "update": { + "system_updates": { + "name": "IPFire-Systemupdates" + } + }, "button": { "connect": { "name": "Verbinden" diff --git a/custom_components/ipfire/translations/en.json b/custom_components/ipfire/translations/en.json index 85a85bc..dee2ec5 100644 --- a/custom_components/ipfire/translations/en.json +++ b/custom_components/ipfire/translations/en.json @@ -187,6 +187,17 @@ "updates_available": { "name": "Updates Available" }, + "update_operation": { + "name": "Update Operation", + "state": { + "idle": "Idle", + "starting": "Starting", + "running": "Running", + "completed": "Completed", + "failed": "Failed", + "unknown": "Unknown" + } + }, "external_ip": { "name": "External IP Address" }, @@ -257,6 +268,11 @@ "name": "D-Bus Daemon" } }, + "update": { + "system_updates": { + "name": "IPFire System Updates" + } + }, "button": { "connect": { "name": "Connect" diff --git a/custom_components/ipfire/update.py b/custom_components/ipfire/update.py new file mode 100644 index 0000000..bb7270b --- /dev/null +++ b/custom_components/ipfire/update.py @@ -0,0 +1,152 @@ +from __future__ import annotations + +from typing import Any + +from homeassistant.components.update import ( + UpdateEntity, + UpdateEntityFeature, +) +from homeassistant.config_entries import ConfigEntry +from homeassistant.core import HomeAssistant +from homeassistant.helpers.device_registry import DeviceInfo +from homeassistant.helpers.entity_platform import AddEntitiesCallback +from homeassistant.helpers.update_coordinator import CoordinatorEntity + +from .coordinator import IPFireCoordinator + + +PARALLEL_UPDATES = 1 + + +async def async_setup_entry( + hass: HomeAssistant, + entry: ConfigEntry, + async_add_entities: AddEntitiesCallback, +) -> None: + """Set up the IPFire system update entity.""" + coordinator: IPFireCoordinator = entry.runtime_data.coordinator + async_add_entities([IPFireSystemUpdateEntity(coordinator, entry)]) + + +class IPFireSystemUpdateEntity( + CoordinatorEntity[IPFireCoordinator], + UpdateEntity, +): + """Represent the complete set of available IPFire updates.""" + + _attr_has_entity_name = True + _attr_translation_key = "system_updates" + _attr_supported_features = ( + UpdateEntityFeature.INSTALL | UpdateEntityFeature.PROGRESS + ) + + def __init__( + self, + coordinator: IPFireCoordinator, + entry: ConfigEntry, + ) -> None: + """Initialize the system update entity.""" + super().__init__(coordinator) + self._attr_unique_id = f"{entry.entry_id}_system_updates" + self._attr_device_info = DeviceInfo( + identifiers={("ipfire", entry.entry_id)}, + name="IPFire", + manufacturer="IPFire", + model="Firewall", + ) + + @property + def available(self) -> bool: + """Require the API's detailed update list for this entity.""" + return ( + super().available + and self.coordinator.data is not None + and self.coordinator.data.available_updates is not None + ) + + @property + def has_update(self) -> bool: + """Return whether any core or package updates are pending.""" + updates = self._available_updates + return updates is not None and bool(updates) + + @property + def installed_version(self) -> str | None: + """Return the installed IPFire version.""" + if self.coordinator.data is None: + return None + return self.coordinator.data.system.version + + @property + def latest_version(self) -> str | None: + """Summarize the batch target; Pakfire installs it as one operation.""" + updates = self._available_updates + if not updates: + return None + + core_update = next( + (update for update in updates if update.get("type") == "core"), + None, + ) + package_count = sum( + update.get("type") == "package" for update in updates + ) + + parts = [] + if core_update is not None: + parts.append(f"Core {core_update.get('available_release')}") + if package_count: + parts.append( + f"{package_count} package update" + f"{'s' if package_count != 1 else ''}" + ) + return " + ".join(parts) + + @property + def release_summary(self) -> str | None: + """List the packages and versions included in the update batch.""" + updates = self._available_updates + if updates is None: + return None + + lines = [] + for update in updates: + if update.get("type") == "core": + lines.append( + "Core update: release " + f"{update.get('installed_release')} → " + f"{update.get('available_release')}" + ) + continue + + name = update.get("name", "Unknown package") + installed = update.get("installed_version", "?") + available = update.get("available_version", "?") + lines.append(f"{name}: {installed} → {available}") + + summary = "\n".join(lines) + return summary[:255] + + @property + def in_progress(self) -> bool: + """Report when Pakfire is currently installing the update batch.""" + if self.coordinator.data is None: + return False + operation = self.coordinator.data.update_operation or {} + return operation.get("status") in {"starting", "running"} + + async def async_install( + self, + version: str | None, + backup: bool, + **kwargs: Any, + ) -> None: + """Start Pakfire's all-updates upgrade through the IPFire API.""" + await self.coordinator.async_start_upgrade() + + @property + def _available_updates(self) -> tuple[dict[str, object], ...] | None: + """Return the API-reported update batch, if available.""" + if self.coordinator.data is None: + return None + return self.coordinator.data.available_updates From c7e8e258c2cbf94ef2995bbd2436ce81069aa717 Mon Sep 17 00:00:00 2001 From: Frank Mainz Date: Fri, 6 Nov 2026 19:23:58 +0100 Subject: [PATCH 2/9] Allow newer aiooui versions --- custom_components/ipfire/manifest.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/custom_components/ipfire/manifest.json b/custom_components/ipfire/manifest.json index ddf7ebc..6198045 100644 --- a/custom_components/ipfire/manifest.json +++ b/custom_components/ipfire/manifest.json @@ -9,6 +9,6 @@ "integration_type": "device", "iot_class": "local_polling", "issue_tracker": "https://github.com/FMainz/HA-IPFire/issues", - "requirements": ["aiooui==0.1.9"], + "requirements": ["aiooui>=0.1.9"], "version": "0.3.7-beta.1" } From 2b8c4b7c7800ef08e9c175ebd6fdc2aab75683ba Mon Sep 17 00:00:00 2001 From: Frank Mainz Date: Sat, 7 Nov 2026 17:47:01 +0100 Subject: [PATCH 3/9] Add HA-IPFire 0.3.7 beta 2 diagnostic report --- README-de.md | 5 +- README.md | 5 +- custom_components/ipfire/button.py | 140 +++++++++++++++++- custom_components/ipfire/coordinator.py | 8 + custom_components/ipfire/icons.json | 5 + custom_components/ipfire/manifest.json | 2 +- custom_components/ipfire/translations/de.json | 3 + custom_components/ipfire/translations/en.json | 3 + 8 files changed, 167 insertions(+), 4 deletions(-) diff --git a/README-de.md b/README-de.md index f9bdc6c..c9cebc6 100644 --- a/README-de.md +++ b/README-de.md @@ -88,6 +88,7 @@ HA-IPFire bietet folgende Funktionen: * Trafficzähler für einzelne Netzwerkzonen¹ * Neustartstatus und Gesamtzahl verfügbarer Updates¹ * Verfügbare IPFire-Updates anzeigen und das vollständige Pakfire-Upgrade in Home Assistant installieren¹ +* Einen datensparsamen Diagnosebericht in den HA-Benachrichtigungen erstellen ¹Benötigt api.cgi aus [IPFire-API](https://github.com/FMainz/IPFire-API) @@ -399,7 +400,9 @@ Die aktuellen Übertragungsraten werden aus den Trafficzählern berechnet und al ## Support -Wenn du einen Fehler findest oder einen Verbesserungsvorschlag hast, kannst du ein Issue im GitHub-Repository erstellen: +Wenn du einen Fehler findest, betätige **Bericht für Fehlermeldungen** im Bereich Diagnose des Geräts. Die Benachrichtigung enthält einen kopierbaren Bericht mit den Versionen von HA-IPFire und Home Assistant, der API-Revision (falls von der API gemeldet), der Verfügbarkeit von API-Funktionen und dem Update-Status. Die API-Revision wird ab IPFire-API v0.2.1 ausgegeben. Prüfe den Bericht vor dem Teilen; Zugangsdaten, IP-Adressen, Hostnamen und DHCP-Clientdaten werden ausgelassen. + +Du kannst auch ein Issue erstellen oder einen Verbesserungsvorschlag im GitHub-Repository einreichen: https://github.com/FMainz/HA-IPFire/issues diff --git a/README.md b/README.md index ebcc97c..2119efb 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,7 @@ HA-IPFire provides the following features: * Traffic counters for individual network zones¹ * Reboot-required status and total available update count¹ * Review available IPFire updates and install the full Pakfire upgrade from Home Assistant¹ +* Generate a privacy-conscious diagnostic report in Home Assistant notifications ¹Requires `api.cgi` from [IPFire-API](https://github.com/FMainz/IPFire-API). @@ -396,7 +397,9 @@ Current transfer rates are calculated from the traffic counters and are provided ## Support -If you encounter a problem or have a suggestion, please open an issue in the GitHub repository: +If you encounter a problem, press **Error Report** in the device's Diagnostics section. The generated notification contains a copyable report with integration and Home Assistant versions, the API revision when reported, API feature availability, and update status. The API revision is included starting with IPFire-API v0.2.1. Review the report before sharing; it excludes credentials, IP addresses, hostnames, and DHCP client details. + +You can also open an issue or suggest an improvement in the GitHub repository: https://github.com/FMainz/HA-IPFire/issues diff --git a/custom_components/ipfire/button.py b/custom_components/ipfire/button.py index 74c2689..06a43ca 100644 --- a/custom_components/ipfire/button.py +++ b/custom_components/ipfire/button.py @@ -1,14 +1,19 @@ from __future__ import annotations +import json from dataclasses import dataclass +from homeassistant.components import persistent_notification from homeassistant.components.button import ButtonEntity, ButtonEntityDescription from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import DeviceInfo +from homeassistant.helpers.entity import EntityCategory from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity +from homeassistant.loader import async_get_loaded_integration +from .const import DOMAIN from .coordinator import IPFireCoordinator @@ -35,6 +40,13 @@ class IPFireButtonDescription(ButtonEntityDescription): icon="mdi:lan-disconnect", action="disconnect", ), + IPFireButtonDescription( + key="diagnostic_report", + translation_key="diagnostic_report", + icon="mdi:bug-outline", + entity_category=EntityCategory.DIAGNOSTIC, + action="diagnostic_report", + ), ) @@ -61,7 +73,7 @@ class IPFireActionButton( CoordinatorEntity[IPFireCoordinator], ButtonEntity, ): - """Represent an IPFire control button.""" + """Represent an IPFire action button.""" _attr_has_entity_name = True @@ -76,6 +88,7 @@ def __init__( super().__init__(coordinator) self.entity_description = description + self.entry = entry self._attr_unique_id = f"{entry.entry_id}_{description.key}" self._attr_device_info = DeviceInfo( identifiers={("ipfire", entry.entry_id)}, @@ -84,6 +97,13 @@ def __init__( model="Firewall", ) + @property + def available(self) -> bool: + """Keep the diagnostic report available during coordinator errors.""" + if self.entity_description.action == "diagnostic_report": + return True + return super().available + async def async_press(self) -> None: """Handle the button press.""" @@ -91,3 +111,121 @@ async def async_press(self) -> None: await self.coordinator.async_connect() elif self.entity_description.action == "disconnect": await self.coordinator.async_disconnect() + elif self.entity_description.action == "diagnostic_report": + await self._async_create_diagnostic_report() + + async def _async_create_diagnostic_report(self) -> None: + """Create a privacy-conscious diagnostic report notification.""" + integration = async_get_loaded_integration(self.hass, DOMAIN) + integration_version = integration.manifest.get("version", "unknown") + data = self.coordinator.data + leases_available = data is not None and data.dhcp_leases is not None + update_list_available = ( + data is not None and data.available_updates is not None + ) + update_operation_available = ( + data is not None and data.update_operation is not None + ) + coordinator_status = ( + "successful" if self.coordinator.last_update_success else "failed" + ) + data_status = "available" if data is not None else "unavailable" + leases_status = "available" if leases_available else "unavailable" + update_list_status = ( + "available" if update_list_available else "unavailable" + ) + operation_status = ( + "available" if update_operation_available else "unavailable" + ) + + lines = [ + "versions:", + f" ha_ipfire: {self._yaml_scalar(integration_version)}", + f" home_assistant: {self._yaml_scalar(self.hass.config.version)}", + "connection:", + f" coordinator_update: {self._yaml_scalar(coordinator_status)}", + " ipfire: " + f"{self._yaml_scalar(data.connection_state if data else None)}", + "api_data:", + f" last_data: {self._yaml_scalar(data_status)}", + f" dhcp_leases: {self._yaml_scalar(leases_status)}", + f" available_update_list: {self._yaml_scalar(update_list_status)}", + f" update_operation: {self._yaml_scalar(operation_status)}", + " api_revision: " + f"{self._yaml_scalar(data.api_revision if data else None)}", + ] + + if data is not None: + lines.extend( + [ + "", + "ipfire:", + f" version: {self._yaml_scalar(data.system.version)}", + " architecture: " + f"{self._yaml_scalar(data.system.architecture)}", + " kernel_version: " + f"{self._yaml_scalar(data.system.kernel_version)}", + ] + ) + + if data.available_updates is not None: + update_types = sorted( + { + str(update.get("type", "unknown")) + for update in data.available_updates + } + ) + lines.extend( + [ + "", + "updates:", + f" count: {len(data.available_updates)}", + " types: " + f"{self._yaml_scalar(', '.join(update_types))}", + ] + ) + + if data.update_operation is not None: + status = data.update_operation.get("status", "unknown") + lines.extend( + [ + "", + "update_operation:", + f" status: {self._yaml_scalar(status)}", + ] + ) + + report = "\n".join(lines) + is_german = self.hass.config.language.startswith("de") + title = ( + "HA-IPFire: Fehlerbericht" + if is_german + else "HA-IPFire: Error report" + ) + notice = ( + "Prüfe den Bericht vor dem Teilen. Er enthält keine Zugangsdaten, " + "IP-Adressen, Hostnamen oder DHCP-Clientdaten." + if is_german + else ( + "Review this report before sharing it. It excludes credentials, " + "IP addresses, hostnames, and DHCP client details." + ) + ) + message = f"{notice}\n\n```yaml\n{report}\n```" + persistent_notification.async_create( + self.hass, + message, + title=title, + notification_id=f"ipfire_diagnostic_report_{self.entry.entry_id}", + ) + + @staticmethod + def _yaml_scalar(value: object) -> str: + """Return a YAML-safe scalar without exposing arbitrary formatting.""" + if value is None: + return "null" + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, (int, float)): + return str(value) + return json.dumps(str(value), ensure_ascii=False) diff --git a/custom_components/ipfire/coordinator.py b/custom_components/ipfire/coordinator.py index 1e9deb3..bc2ed5c 100644 --- a/custom_components/ipfire/coordinator.py +++ b/custom_components/ipfire/coordinator.py @@ -88,6 +88,7 @@ class IPFireInterfaceData: class IPFireData: """Represent data received from IPFire.""" + api_revision: str | None rxb: int txb: int rx_rate: float @@ -211,6 +212,7 @@ async def _async_update_data(self) -> IPFireData: services = payload.get("services", {}) addons = payload.get("addons", {}) updates = payload.get("updates", {}) + raw_api_revision = payload.get("api_revision") if not isinstance(connection, dict): raise ValueError("Invalid connection data from IPFire") @@ -423,6 +425,12 @@ async def _async_update_data(self) -> IPFireData: self._previous_timestamp = now return IPFireData( + api_revision=( + str(raw_api_revision) + if isinstance(raw_api_revision, (str, int)) + and not isinstance(raw_api_revision, bool) + else None + ), rxb=rx_bytes, txb=tx_bytes, rx_rate=rx_rate, diff --git a/custom_components/ipfire/icons.json b/custom_components/ipfire/icons.json index 08a5c39..76f61e0 100644 --- a/custom_components/ipfire/icons.json +++ b/custom_components/ipfire/icons.json @@ -133,6 +133,11 @@ "default": "mdi:package-up" } }, + "button": { + "diagnostic_report": { + "default": "mdi:bug-outline" + } + }, "binary_sensor": { "reboot_required": { "default": "mdi:restart-alert" diff --git a/custom_components/ipfire/manifest.json b/custom_components/ipfire/manifest.json index 6198045..9d106ba 100644 --- a/custom_components/ipfire/manifest.json +++ b/custom_components/ipfire/manifest.json @@ -10,5 +10,5 @@ "iot_class": "local_polling", "issue_tracker": "https://github.com/FMainz/HA-IPFire/issues", "requirements": ["aiooui>=0.1.9"], - "version": "0.3.7-beta.1" + "version": "0.3.7-beta.2" } diff --git a/custom_components/ipfire/translations/de.json b/custom_components/ipfire/translations/de.json index 0ef9fac..0516b19 100644 --- a/custom_components/ipfire/translations/de.json +++ b/custom_components/ipfire/translations/de.json @@ -279,6 +279,9 @@ }, "disconnect": { "name": "Trennen" + }, + "diagnostic_report": { + "name": "Bericht für Fehlermeldungen" } } } diff --git a/custom_components/ipfire/translations/en.json b/custom_components/ipfire/translations/en.json index dee2ec5..77a12e2 100644 --- a/custom_components/ipfire/translations/en.json +++ b/custom_components/ipfire/translations/en.json @@ -279,6 +279,9 @@ }, "disconnect": { "name": "Disconnect" + }, + "diagnostic_report": { + "name": "Error Report" } } } From c595df91a67770e4e62ab62cee7b2143db64ecdc Mon Sep 17 00:00:00 2001 From: Frank Mainz Date: Sat, 7 Nov 2026 18:04:16 +0100 Subject: [PATCH 4/9] Fix HA-IPFire beta diagnostic report --- README-de.md | 2 +- README.md | 2 +- custom_components/ipfire/button.py | 3 ++- custom_components/ipfire/manifest.json | 2 +- 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/README-de.md b/README-de.md index c9cebc6..6720cf8 100644 --- a/README-de.md +++ b/README-de.md @@ -1,4 +1,4 @@ -[![hacs_badge](https://img.shields.io/badge/HACS-Custom-41BDF5.svg)](https://github.com/hacs/integration) +[![marketplace_badge](https://img.shields.io/badge/Marketplace-Custom-41BDF5.svg)](https://www.home-assistant.io/integrations/marketplace) [![GitHub release](https://img.shields.io/github/release/fmainz/ha-ipfire?include_prereleases=&sort=semver&color=blue)](https://github.com/fmainz/ha-ipfire/releases/) ![last commit](https://img.shields.io/github/last-commit/fmainz/ha-ipfire) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) diff --git a/README.md b/README.md index 2119efb..ac8a8cd 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -[![hacs_badge](https://img.shields.io/badge/HACS-Custom-41BDF5.svg)](https://github.com/hacs/integration) +[![marketplace_badge](https://img.shields.io/badge/Marketplace-Custom-41BDF5.svg)](https://www.home-assistant.io/integrations/marketplace) [![GitHub release](https://img.shields.io/github/release/fmainz/ha-ipfire?include_prereleases=&sort=semver&color=blue)](https://github.com/fmainz/ha-ipfire/releases/) ![last commit](https://img.shields.io/github/last-commit/fmainz/ha-ipfire) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) diff --git a/custom_components/ipfire/button.py b/custom_components/ipfire/button.py index 06a43ca..e4cb785 100644 --- a/custom_components/ipfire/button.py +++ b/custom_components/ipfire/button.py @@ -6,6 +6,7 @@ from homeassistant.components import persistent_notification from homeassistant.components.button import ButtonEntity, ButtonEntityDescription from homeassistant.config_entries import ConfigEntry +from homeassistant.const import __version__ as HA_VERSION from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity import EntityCategory @@ -141,7 +142,7 @@ async def _async_create_diagnostic_report(self) -> None: lines = [ "versions:", f" ha_ipfire: {self._yaml_scalar(integration_version)}", - f" home_assistant: {self._yaml_scalar(self.hass.config.version)}", + f" home_assistant: {self._yaml_scalar(HA_VERSION)}", "connection:", f" coordinator_update: {self._yaml_scalar(coordinator_status)}", " ipfire: " diff --git a/custom_components/ipfire/manifest.json b/custom_components/ipfire/manifest.json index 9d106ba..886b11f 100644 --- a/custom_components/ipfire/manifest.json +++ b/custom_components/ipfire/manifest.json @@ -10,5 +10,5 @@ "iot_class": "local_polling", "issue_tracker": "https://github.com/FMainz/HA-IPFire/issues", "requirements": ["aiooui>=0.1.9"], - "version": "0.3.7-beta.2" + "version": "0.3.7-beta.3" } From a9eb87d9ddd58bc0c4a185223ff332b39ce6bca7 Mon Sep 17 00:00:00 2001 From: Frank Mainz Date: Sat, 7 Nov 2026 20:29:38 +0100 Subject: [PATCH 5/9] Expand diagnostic error report --- .github/FUNDING.yml | 1 + README-de.md | 6 +- README.md | 6 +- custom_components/ipfire/button.py | 238 ++++++++++++++++++------ custom_components/ipfire/coordinator.py | 17 +- custom_components/ipfire/manifest.json | 2 +- 6 files changed, 212 insertions(+), 58 deletions(-) create mode 100644 .github/FUNDING.yml diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..12e00ed --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +ko_fi: fmainz diff --git a/README-de.md b/README-de.md index 6720cf8..5914312 100644 --- a/README-de.md +++ b/README-de.md @@ -400,12 +400,16 @@ Die aktuellen Übertragungsraten werden aus den Trafficzählern berechnet und al ## Support -Wenn du einen Fehler findest, betätige **Bericht für Fehlermeldungen** im Bereich Diagnose des Geräts. Die Benachrichtigung enthält einen kopierbaren Bericht mit den Versionen von HA-IPFire und Home Assistant, der API-Revision (falls von der API gemeldet), der Verfügbarkeit von API-Funktionen und dem Update-Status. Die API-Revision wird ab IPFire-API v0.2.1 ausgegeben. Prüfe den Bericht vor dem Teilen; Zugangsdaten, IP-Adressen, Hostnamen und DHCP-Clientdaten werden ausgelassen. +Wenn du einen Fehler findest, betätige **Bericht für Fehlermeldungen** im Bereich Diagnose des Geräts. Die Benachrichtigung enthält einen kopierbaren Bericht mit den Versionen von HA-IPFire und Home Assistant, dem eingestellten Abfrageintervall, der Anzahl aktivierter und deaktivierter Entitäten, UTC-Zeitpunkten der letzten erfolgreichen Abfrage und des letzten Fehlers, einer bereinigten Fehlermeldung, der Anzahl der DHCP-Leases, der Verfügbarkeit von API-Funktionen und dem Update-Status. Die API-Revision wird ab IPFire-API v0.2.1 ausgegeben. Prüfe den Bericht vor dem Teilen; Zugangsdaten, IP-Adressen, Hostnamen und DHCP-Clientdaten werden ausgelassen. Du kannst auch ein Issue erstellen oder einen Verbesserungsvorschlag im GitHub-Repository einreichen: https://github.com/FMainz/HA-IPFire/issues +Wenn dir HA-IPFire weiterhilft, kannst du die Weiterentwicklung auf Ko-fi unterstützen: + +[![FMainz auf Ko-fi unterstützen](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/fmainz) + ## Repository https://github.com/FMainz/HA-IPFire diff --git a/README.md b/README.md index ac8a8cd..0e94a7f 100644 --- a/README.md +++ b/README.md @@ -397,12 +397,16 @@ Current transfer rates are calculated from the traffic counters and are provided ## Support -If you encounter a problem, press **Error Report** in the device's Diagnostics section. The generated notification contains a copyable report with integration and Home Assistant versions, the API revision when reported, API feature availability, and update status. The API revision is included starting with IPFire-API v0.2.1. Review the report before sharing; it excludes credentials, IP addresses, hostnames, and DHCP client details. +If you encounter a problem, press **Error Report** in the device's Diagnostics section. The generated notification contains a copyable report with integration and Home Assistant versions, the configured scan interval, enabled and disabled entity counts, UTC timestamps for the last successful update and last error, a sanitized last error, the DHCP lease count, API feature availability, and update status. The API revision is included starting with IPFire-API v0.2.1. Review the report before sharing; it excludes credentials, IP addresses, hostnames, and DHCP client details. You can also open an issue or suggest an improvement in the GitHub repository: https://github.com/FMainz/HA-IPFire/issues +If you find HA-IPFire useful, you can support its ongoing development on Ko-fi: + +[![Support FMainz on Ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/fmainz) + ## Repository https://github.com/FMainz/HA-IPFire diff --git a/custom_components/ipfire/button.py b/custom_components/ipfire/button.py index e4cb785..3df3e46 100644 --- a/custom_components/ipfire/button.py +++ b/custom_components/ipfire/button.py @@ -1,20 +1,28 @@ from __future__ import annotations import json +import re from dataclasses import dataclass +from datetime import datetime from homeassistant.components import persistent_notification from homeassistant.components.button import ButtonEntity, ButtonEntityDescription from homeassistant.config_entries import ConfigEntry from homeassistant.const import __version__ as HA_VERSION from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity import EntityCategory from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity from homeassistant.loader import async_get_loaded_integration -from .const import DOMAIN +from .const import ( + CONF_SCAN_INTERVAL, + CONF_VERIFY_SSL, + DEFAULT_SCAN_INTERVAL, + DOMAIN, +) from .coordinator import IPFireCoordinator @@ -120,42 +128,90 @@ async def _async_create_diagnostic_report(self) -> None: integration = async_get_loaded_integration(self.hass, DOMAIN) integration_version = integration.manifest.get("version", "unknown") data = self.coordinator.data - leases_available = data is not None and data.dhcp_leases is not None - update_list_available = ( - data is not None and data.available_updates is not None - ) - update_operation_available = ( - data is not None and data.update_operation is not None - ) coordinator_status = ( "successful" if self.coordinator.last_update_success else "failed" ) data_status = "available" if data is not None else "unavailable" - leases_status = "available" if leases_available else "unavailable" - update_list_status = ( - "available" if update_list_available else "unavailable" - ) - operation_status = ( - "available" if update_operation_available else "unavailable" + last_error = self.coordinator.last_update_error + interval = self.entry.options.get( + CONF_SCAN_INTERVAL, + DEFAULT_SCAN_INTERVAL, ) + entity_counts = self._entity_counts() + last_error_type, last_error_message = self._safe_error_details(last_error) lines = [ "versions:", f" ha_ipfire: {self._yaml_scalar(integration_version)}", f" home_assistant: {self._yaml_scalar(HA_VERSION)}", - "connection:", - f" coordinator_update: {self._yaml_scalar(coordinator_status)}", - " ipfire: " - f"{self._yaml_scalar(data.connection_state if data else None)}", - "api_data:", - f" last_data: {self._yaml_scalar(data_status)}", - f" dhcp_leases: {self._yaml_scalar(leases_status)}", - f" available_update_list: {self._yaml_scalar(update_list_status)}", - f" update_operation: {self._yaml_scalar(operation_status)}", - " api_revision: " - f"{self._yaml_scalar(data.api_revision if data else None)}", + "settings:", + f" scan_interval_seconds: {self._yaml_scalar(interval)}", + " verify_ssl_certificate: " + f"{self._yaml_scalar(self.entry.data.get(CONF_VERIFY_SSL))}", + " entities:", ] + for domain, counts in entity_counts.items(): + lines.extend( + [ + f" {domain}:", + f" enabled: {counts['enabled']}", + f" disabled: {counts['disabled']}", + ] + ) + + lines.extend( + [ + "connection:", + " coordinator_update: " + f"{self._yaml_scalar(coordinator_status)}", + " last_successful_update_utc: " + f"{self._yaml_scalar(self._format_utc(self.coordinator.last_successful_update_utc))}", + " last_error_utc: " + f"{self._yaml_scalar(self._format_utc(self.coordinator.last_error_utc))}", + f" last_error_type: {self._yaml_scalar(last_error_type)}", + " last_error_message: " + f"{self._yaml_scalar(last_error_message)}", + " ipfire: " + f"{self._yaml_scalar(data.connection_state if data else None)}", + "api_data:", + f" last_data: {self._yaml_scalar(data_status)}", + " api_revision: " + f"{self._yaml_scalar(data.api_revision if data else None)}", + ] + ) + + def unavailable_reason(value: object) -> str | None: + if value is not None: + return None + if data is None: + return "query_failed" if last_error is not None else "not_queried" + return "not_reported_by_api" + + leases = data.dhcp_leases if data is not None else None + updates = data.available_updates if data is not None else None + operation = data.update_operation if data is not None else None + lines.extend( + [ + " dhcp_leases:", + " count: " + f"{self._yaml_scalar(len(leases) if leases is not None else None)}", + " status: " + f"{self._yaml_scalar('available' if leases is not None else 'unavailable')}", + f" reason: {self._yaml_scalar(unavailable_reason(leases))}", + " available_update_list:", + " count: " + f"{self._yaml_scalar(len(updates) if updates is not None else None)}", + " status: " + f"{self._yaml_scalar('available' if updates is not None else 'unavailable')}", + f" reason: {self._yaml_scalar(unavailable_reason(updates))}", + " update_operation:", + " status: " + f"{self._yaml_scalar(self._safe_operation_status(operation))}", + f" reason: {self._yaml_scalar(unavailable_reason(operation))}", + ] + ) + if data is not None: lines.extend( [ @@ -166,36 +222,15 @@ async def _async_create_diagnostic_report(self) -> None: f"{self._yaml_scalar(data.system.architecture)}", " kernel_version: " f"{self._yaml_scalar(data.system.kernel_version)}", + " core_update_available: " + f"{self._yaml_scalar(data.system.core_update)}", + " package_updates_available: " + f"{self._yaml_scalar(data.system.package_updates)}", + " reboot_required: " + f"{self._yaml_scalar(data.system.reboot_required)}", ] ) - if data.available_updates is not None: - update_types = sorted( - { - str(update.get("type", "unknown")) - for update in data.available_updates - } - ) - lines.extend( - [ - "", - "updates:", - f" count: {len(data.available_updates)}", - " types: " - f"{self._yaml_scalar(', '.join(update_types))}", - ] - ) - - if data.update_operation is not None: - status = data.update_operation.get("status", "unknown") - lines.extend( - [ - "", - "update_operation:", - f" status: {self._yaml_scalar(status)}", - ] - ) - report = "\n".join(lines) is_german = self.hass.config.language.startswith("de") title = ( @@ -220,13 +255,108 @@ async def _async_create_diagnostic_report(self) -> None: notification_id=f"ipfire_diagnostic_report_{self.entry.entry_id}", ) + def _entity_counts(self) -> dict[str, dict[str, int]]: + """Count enabled and disabled entities without including entity IDs.""" + registry = er.async_get(self.hass) + counts: dict[str, dict[str, int]] = {} + for entity in er.async_entries_for_config_entry( + registry, + self.entry.entry_id, + ): + if entity.domain not in { + "sensor", + "binary_sensor", + "button", + "update", + }: + continue + domain_counts = counts.setdefault( + entity.domain, + {"enabled": 0, "disabled": 0}, + ) + key = "disabled" if entity.disabled_by is not None else "enabled" + domain_counts[key] += 1 + return dict(sorted(counts.items())) + + @staticmethod + def _format_utc(value: object) -> str | None: + """Format a timestamp as an ISO 8601 UTC value.""" + return value.isoformat() if isinstance(value, datetime) else None + + @staticmethod + def _safe_operation_status( + operation: dict[str, object] | None, + ) -> str | None: + """Return only known-safe update operation states.""" + if operation is None: + return None + status = operation.get("status") + if isinstance(status, str) and status in { + "idle", + "running", + "completed", + "failed", + }: + return str(status) + return "unknown" + + def _safe_error_details( + self, + error: BaseException | None, + ) -> tuple[str | None, str | None]: + """Redact addresses, hostnames, credentials, and URLs from errors.""" + if error is None: + return None, None + + message = str(error) or "No error details provided" + for secret in ( + self.coordinator.base_url, + self.coordinator.username, + self.coordinator.password, + ): + if secret: + message = message.replace(secret, "[redacted]") + + message = re.sub( + r"https?://[^\s'\"]+", + "[URL redacted]", + message, + flags=re.IGNORECASE, + ) + message = re.sub( + r"(?i)(host(?:name)?\s+)[^\s,;]+", + r"\1[redacted]", + message, + ) + message = re.sub( + r"(?i)\b(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}\b", + "[hostname redacted]", + message, + ) + message = re.sub( + r"\b(?:\d{1,3}\.){3}\d{1,3}\b", + "[IP address redacted]", + message, + ) + message = re.sub( + r"\b(?:[0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2}\b", + "[MAC address redacted]", + message, + ) + message = re.sub( + r"(? str: """Return a YAML-safe scalar without exposing arbitrary formatting.""" if value is None: - return "null" + return "none" if isinstance(value, bool): - return "true" if value else "false" + return "yes" if value else "no" if isinstance(value, (int, float)): return str(value) return json.dumps(str(value), ensure_ascii=False) diff --git a/custom_components/ipfire/coordinator.py b/custom_components/ipfire/coordinator.py index bc2ed5c..adbd45f 100644 --- a/custom_components/ipfire/coordinator.py +++ b/custom_components/ipfire/coordinator.py @@ -4,7 +4,7 @@ import time import xml.etree.ElementTree as ET from dataclasses import dataclass -from datetime import timedelta +from datetime import datetime, timedelta import aiohttp @@ -14,6 +14,7 @@ DataUpdateCoordinator, UpdateFailed, ) +from homeassistant.util import dt as dt_util from .const import DOMAIN, API_PATH _LOGGER = logging.getLogger(__name__) @@ -137,12 +138,26 @@ def __init__( self.password = password self.verify_ssl = verify_ssl + self.last_successful_update_utc: datetime | None = None + self.last_error_utc: datetime | None = None + self.last_update_error: BaseException | None = None + self._previous_rx_bytes: int | None = None self._previous_tx_bytes: int | None = None self._previous_timestamp: float | None = None self._previous_cpu_total: int | None = None self._previous_cpu_idle: int | None = None + def _async_refresh_finished(self) -> None: + """Keep UTC timestamps and the last update error for diagnostics.""" + if self.last_update_success: + self.last_successful_update_utc = dt_util.utcnow() + return + + if self.last_exception is not None: + self.last_error_utc = dt_util.utcnow() + self.last_update_error = self.last_exception + @property def api_url(self) -> str: """Return the IPFire API URL.""" diff --git a/custom_components/ipfire/manifest.json b/custom_components/ipfire/manifest.json index 886b11f..f627155 100644 --- a/custom_components/ipfire/manifest.json +++ b/custom_components/ipfire/manifest.json @@ -10,5 +10,5 @@ "iot_class": "local_polling", "issue_tracker": "https://github.com/FMainz/HA-IPFire/issues", "requirements": ["aiooui>=0.1.9"], - "version": "0.3.7-beta.3" + "version": "0.3.7-beta.4" } From 618f9bc0ef0a21a9516c0f44909262bb8587b750 Mon Sep 17 00:00:00 2001 From: Frank Mainz Date: Sat, 7 Nov 2026 21:39:32 +0100 Subject: [PATCH 6/9] Prepare HA-IPFire 0.3.7 beta 5 --- README-de.md | 2 +- README.md | 2 +- custom_components/ipfire/button.py | 54 ++++++++++++------- custom_components/ipfire/manifest.json | 2 +- custom_components/ipfire/translations/de.json | 4 ++ custom_components/ipfire/translations/en.json | 4 ++ 6 files changed, 46 insertions(+), 22 deletions(-) diff --git a/README-de.md b/README-de.md index 5914312..dbbeeb8 100644 --- a/README-de.md +++ b/README-de.md @@ -400,7 +400,7 @@ Die aktuellen Übertragungsraten werden aus den Trafficzählern berechnet und al ## Support -Wenn du einen Fehler findest, betätige **Bericht für Fehlermeldungen** im Bereich Diagnose des Geräts. Die Benachrichtigung enthält einen kopierbaren Bericht mit den Versionen von HA-IPFire und Home Assistant, dem eingestellten Abfrageintervall, der Anzahl aktivierter und deaktivierter Entitäten, UTC-Zeitpunkten der letzten erfolgreichen Abfrage und des letzten Fehlers, einer bereinigten Fehlermeldung, der Anzahl der DHCP-Leases, der Verfügbarkeit von API-Funktionen und dem Update-Status. Die API-Revision wird ab IPFire-API v0.2.1 ausgegeben. Prüfe den Bericht vor dem Teilen; Zugangsdaten, IP-Adressen, Hostnamen und DHCP-Clientdaten werden ausgelassen. +Wenn du einen Fehler findest, betätige **Bericht für Fehlermeldungen** im Bereich Diagnose des Geräts. Die Benachrichtigung enthält einen kopierbaren Bericht mit den Versionen von HA-IPFire und Home Assistant, dem eingestellten Abfrageintervall, der Anzahl aktivierter und deaktivierter Entitäten, der Anzahl aktivierter Entitäten mit dem Status `unavailable` oder `unknown`, UTC-Zeitpunkten der letzten erfolgreichen Abfrage und des letzten Fehlers (sekundengenau), einer bereinigten Fehlermeldung, der Anzahl der DHCP-Leases, der Verfügbarkeit von API-Funktionen und dem Update-Status. Die API-Revision wird ab IPFire-API v0.2.1 ausgegeben. Prüfe den Bericht vor dem Teilen; Zugangsdaten, IP-Adressen, Hostnamen und DHCP-Clientdaten werden ausgelassen. Du kannst auch ein Issue erstellen oder einen Verbesserungsvorschlag im GitHub-Repository einreichen: diff --git a/README.md b/README.md index 0e94a7f..5a3df9b 100644 --- a/README.md +++ b/README.md @@ -397,7 +397,7 @@ Current transfer rates are calculated from the traffic counters and are provided ## Support -If you encounter a problem, press **Error Report** in the device's Diagnostics section. The generated notification contains a copyable report with integration and Home Assistant versions, the configured scan interval, enabled and disabled entity counts, UTC timestamps for the last successful update and last error, a sanitized last error, the DHCP lease count, API feature availability, and update status. The API revision is included starting with IPFire-API v0.2.1. Review the report before sharing; it excludes credentials, IP addresses, hostnames, and DHCP client details. +If you encounter a problem, press **Error Report** in the device's Diagnostics section. The generated notification contains a copyable report with integration and Home Assistant versions, the configured scan interval, enabled and disabled entity counts, counts of enabled entities in `unavailable` or `unknown` state, UTC timestamps for the last successful update and last error (to the second), a sanitized last error, the DHCP lease count, API feature availability, and update status. The API revision is included starting with IPFire-API v0.2.1. Review the report before sharing; it excludes credentials, IP addresses, hostnames, and DHCP client details. You can also open an issue or suggest an improvement in the GitHub repository: diff --git a/custom_components/ipfire/button.py b/custom_components/ipfire/button.py index 3df3e46..ed9a341 100644 --- a/custom_components/ipfire/button.py +++ b/custom_components/ipfire/button.py @@ -3,7 +3,7 @@ import json import re from dataclasses import dataclass -from datetime import datetime +from datetime import datetime, timezone from homeassistant.components import persistent_notification from homeassistant.components.button import ButtonEntity, ButtonEntityDescription @@ -14,6 +14,7 @@ from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity import EntityCategory from homeassistant.helpers.entity_platform import AddEntitiesCallback +from homeassistant.helpers.translation import async_get_translations from homeassistant.helpers.update_coordinator import CoordinatorEntity from homeassistant.loader import async_get_loaded_integration @@ -157,6 +158,8 @@ async def _async_create_diagnostic_report(self) -> None: f" {domain}:", f" enabled: {counts['enabled']}", f" disabled: {counts['disabled']}", + f" unavailable: {counts['unavailable']}", + f" unknown: {counts['unknown']}", ] ) @@ -232,20 +235,20 @@ def unavailable_reason(value: object) -> str | None: ) report = "\n".join(lines) - is_german = self.hass.config.language.startswith("de") - title = ( - "HA-IPFire: Fehlerbericht" - if is_german - else "HA-IPFire: Error report" + translations = await async_get_translations( + self.hass, + self.hass.config.language, + "common", + {DOMAIN}, ) - notice = ( - "Prüfe den Bericht vor dem Teilen. Er enthält keine Zugangsdaten, " - "IP-Adressen, Hostnamen oder DHCP-Clientdaten." - if is_german - else ( - "Review this report before sharing it. It excludes credentials, " - "IP addresses, hostnames, and DHCP client details." - ) + title = translations.get( + f"component.{DOMAIN}.common.diagnostic_report_title", + "HA-IPFire: Error report", + ) + notice = translations.get( + f"component.{DOMAIN}.common.diagnostic_report_notice", + "Review this report before sharing it. It excludes credentials, " + "IP addresses, hostnames, and DHCP client details.", ) message = f"{notice}\n\n```yaml\n{report}\n```" persistent_notification.async_create( @@ -256,7 +259,7 @@ def unavailable_reason(value: object) -> str | None: ) def _entity_counts(self) -> dict[str, dict[str, int]]: - """Count enabled and disabled entities without including entity IDs.""" + """Count entity states without including entity IDs.""" registry = er.async_get(self.hass) counts: dict[str, dict[str, int]] = {} for entity in er.async_entries_for_config_entry( @@ -272,16 +275,29 @@ def _entity_counts(self) -> dict[str, dict[str, int]]: continue domain_counts = counts.setdefault( entity.domain, - {"enabled": 0, "disabled": 0}, + { + "enabled": 0, + "disabled": 0, + "unavailable": 0, + "unknown": 0, + }, ) - key = "disabled" if entity.disabled_by is not None else "enabled" - domain_counts[key] += 1 + if entity.disabled_by is not None: + domain_counts["disabled"] += 1 + continue + + domain_counts["enabled"] += 1 + state = self.hass.states.get(entity.entity_id) + if state is not None and state.state in {"unavailable", "unknown"}: + domain_counts[state.state] += 1 return dict(sorted(counts.items())) @staticmethod def _format_utc(value: object) -> str | None: """Format a timestamp as an ISO 8601 UTC value.""" - return value.isoformat() if isinstance(value, datetime) else None + if not isinstance(value, datetime): + return None + return value.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC") @staticmethod def _safe_operation_status( diff --git a/custom_components/ipfire/manifest.json b/custom_components/ipfire/manifest.json index f627155..eeb96b3 100644 --- a/custom_components/ipfire/manifest.json +++ b/custom_components/ipfire/manifest.json @@ -10,5 +10,5 @@ "iot_class": "local_polling", "issue_tracker": "https://github.com/FMainz/HA-IPFire/issues", "requirements": ["aiooui>=0.1.9"], - "version": "0.3.7-beta.4" + "version": "0.3.7-beta.5" } diff --git a/custom_components/ipfire/translations/de.json b/custom_components/ipfire/translations/de.json index 0516b19..aa7025b 100644 --- a/custom_components/ipfire/translations/de.json +++ b/custom_components/ipfire/translations/de.json @@ -63,6 +63,10 @@ } } }, + "common": { + "diagnostic_report_title": "HA-IPFire: Fehlerbericht", + "diagnostic_report_notice": "Prüfe den Bericht vor dem Teilen. Er enthält keine Zugangsdaten, IP-Adressen, Hostnamen oder DHCP-Clientdaten." + }, "entity": { "sensor": { "download": { diff --git a/custom_components/ipfire/translations/en.json b/custom_components/ipfire/translations/en.json index 77a12e2..bb976e0 100644 --- a/custom_components/ipfire/translations/en.json +++ b/custom_components/ipfire/translations/en.json @@ -63,6 +63,10 @@ } } }, + "common": { + "diagnostic_report_title": "HA-IPFire: Error report", + "diagnostic_report_notice": "Review this report before sharing it. It excludes credentials, IP addresses, hostnames, and DHCP client details." + }, "entity": { "sensor": { "download": { From ad39fc468d72db34461c050b3a57027ec17f86c0 Mon Sep 17 00:00:00 2001 From: Frank Mainz Date: Sun, 8 Nov 2026 18:13:46 +0100 Subject: [PATCH 7/9] Prepare HA-IPFire 0.3.7 beta 6 --- README-de.md | 4 +- README.md | 4 +- custom_components/ipfire/button.py | 8 ++- custom_components/ipfire/coordinator.py | 65 ++++++++++++++++++- custom_components/ipfire/manifest.json | 2 +- custom_components/ipfire/translations/de.json | 3 + custom_components/ipfire/translations/en.json | 3 + custom_components/ipfire/update.py | 58 ++++++++++++++++- 8 files changed, 139 insertions(+), 8 deletions(-) diff --git a/README-de.md b/README-de.md index dbbeeb8..213c666 100644 --- a/README-de.md +++ b/README-de.md @@ -88,6 +88,7 @@ HA-IPFire bietet folgende Funktionen: * Trafficzähler für einzelne Netzwerkzonen¹ * Neustartstatus und Gesamtzahl verfügbarer Updates¹ * Verfügbare IPFire-Updates anzeigen und das vollständige Pakfire-Upgrade in Home Assistant installieren¹ +* Einen erforderlichen IPFire-Neustart über die native HA-Update-Ansicht bestätigen und starten¹ * Einen datensparsamen Diagnosebericht in den HA-Benachrichtigungen erstellen ¹Benötigt api.cgi aus [IPFire-API](https://github.com/FMainz/IPFire-API) @@ -191,6 +192,7 @@ Sensoren werden nur für interne Schnittstellen angelegt, die auf der IPFire-Fir * **Updates verfügbar** – Gesamtzahl der verfügbaren Updates, einschließlich Core- und Paket-Updates. Das Attribut `updates` listet die einzelnen Core- und Paket-Updates mit ihren Versionen auf. * **IPFire-Systemupdates** – native Home-Assistant-Update-Entität. Sie erscheint im Update-Bereich von Home Assistant, wenn Updates verfügbar sind; die Release-Zusammenfassung listet Core- und Paket-Updates auf. Mit „Installieren“ wird das vollständige Pakfire-Upgrade gestartet, da IPFire keine Auswahl einzelner Updates unterstützt. * **Update-Vorgang** – zeigt an, ob ein über die API gestartetes Update inaktiv ist, läuft, abgeschlossen ist oder fehlgeschlagen ist. +* **Router neu starten** – erscheint als native Home-Assistant-Update-Aktion, wenn `api.cgi` ab Revision 0.2.5 einen erforderlichen Neustart meldet. Über die Update-Ansicht kannst du den Router-Neustart nach Bestätigung starten. ### Internetverbindung @@ -400,7 +402,7 @@ Die aktuellen Übertragungsraten werden aus den Trafficzählern berechnet und al ## Support -Wenn du einen Fehler findest, betätige **Bericht für Fehlermeldungen** im Bereich Diagnose des Geräts. Die Benachrichtigung enthält einen kopierbaren Bericht mit den Versionen von HA-IPFire und Home Assistant, dem eingestellten Abfrageintervall, der Anzahl aktivierter und deaktivierter Entitäten, der Anzahl aktivierter Entitäten mit dem Status `unavailable` oder `unknown`, UTC-Zeitpunkten der letzten erfolgreichen Abfrage und des letzten Fehlers (sekundengenau), einer bereinigten Fehlermeldung, der Anzahl der DHCP-Leases, der Verfügbarkeit von API-Funktionen und dem Update-Status. Die API-Revision wird ab IPFire-API v0.2.1 ausgegeben. Prüfe den Bericht vor dem Teilen; Zugangsdaten, IP-Adressen, Hostnamen und DHCP-Clientdaten werden ausgelassen. +Wenn du einen Fehler findest, betätige **Bericht für Fehlermeldungen** im Bereich Diagnose des Geräts. Die Benachrichtigung enthält einen kopierbaren Bericht mit den Versionen von HA-IPFire und Home Assistant, dem eingestellten Abfrageintervall, der Anzahl aktivierter und deaktivierter Entitäten, der Anzahl aktivierter Entitäten mit dem Status `unavailable` oder `unknown` (der normale `unknown`-Status von Buttons wird ausgelassen), UTC-Zeitpunkten der letzten erfolgreichen Abfrage und des letzten Fehlers (sekundengenau), einer bereinigten Fehlermeldung, der Anzahl der DHCP-Leases, der Verfügbarkeit von API-Funktionen und dem Update-Status. Die API-Revision wird ab IPFire-API v0.2.1 ausgegeben. Prüfe den Bericht vor dem Teilen; Zugangsdaten, IP-Adressen, Hostnamen und DHCP-Clientdaten werden ausgelassen. Du kannst auch ein Issue erstellen oder einen Verbesserungsvorschlag im GitHub-Repository einreichen: diff --git a/README.md b/README.md index 5a3df9b..8825601 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,7 @@ HA-IPFire provides the following features: * Traffic counters for individual network zones¹ * Reboot-required status and total available update count¹ * Review available IPFire updates and install the full Pakfire upgrade from Home Assistant¹ +* Confirm and start a required IPFire reboot through Home Assistant's native Updates interface¹ * Generate a privacy-conscious diagnostic report in Home Assistant notifications ¹Requires `api.cgi` from [IPFire-API](https://github.com/FMainz/IPFire-API). @@ -193,6 +194,7 @@ Sensors are created only for internal interfaces configured on the IPFire firewa * **Updates Available** – total number of available updates, including core and package updates. Its `updates` attribute lists the exact core/package updates and versions. * **IPFire System Updates** – native Home Assistant update entity. It appears in Home Assistant's Updates section when updates are available; its release summary lists the included core and package updates. Installing it starts the full Pakfire upgrade, because IPFire does not support selecting individual updates. * **Update Operation** – reports whether an API-started update is idle, running, completed, or failed. +* **Restart router** – appears as a native Home Assistant update action when `api.cgi` revision 0.2.5 or newer reports that a reboot is required. Start the router reboot from the Updates interface after confirmation. ### Internet connection @@ -397,7 +399,7 @@ Current transfer rates are calculated from the traffic counters and are provided ## Support -If you encounter a problem, press **Error Report** in the device's Diagnostics section. The generated notification contains a copyable report with integration and Home Assistant versions, the configured scan interval, enabled and disabled entity counts, counts of enabled entities in `unavailable` or `unknown` state, UTC timestamps for the last successful update and last error (to the second), a sanitized last error, the DHCP lease count, API feature availability, and update status. The API revision is included starting with IPFire-API v0.2.1. Review the report before sharing; it excludes credentials, IP addresses, hostnames, and DHCP client details. +If you encounter a problem, press **Error Report** in the device's Diagnostics section. The generated notification contains a copyable report with integration and Home Assistant versions, the configured scan interval, enabled and disabled entity counts, counts of enabled entities in `unavailable` or `unknown` state (the normal `unknown` state of buttons is excluded), UTC timestamps for the last successful update and last error (to the second), a sanitized last error, the DHCP lease count, API feature availability, and update status. The API revision is included starting with IPFire-API v0.2.1. Review the report before sharing; it excludes credentials, IP addresses, hostnames, and DHCP client details. You can also open an issue or suggest an improvement in the GitHub repository: diff --git a/custom_components/ipfire/button.py b/custom_components/ipfire/button.py index ed9a341..107cf28 100644 --- a/custom_components/ipfire/button.py +++ b/custom_components/ipfire/button.py @@ -288,8 +288,12 @@ def _entity_counts(self) -> dict[str, dict[str, int]]: domain_counts["enabled"] += 1 state = self.hass.states.get(entity.entity_id) - if state is not None and state.state in {"unavailable", "unknown"}: - domain_counts[state.state] += 1 + if state is None: + continue + if state.state == "unavailable": + domain_counts["unavailable"] += 1 + elif state.state == "unknown" and entity.domain != "button": + domain_counts["unknown"] += 1 return dict(sorted(counts.items())) @staticmethod diff --git a/custom_components/ipfire/coordinator.py b/custom_components/ipfire/coordinator.py index adbd45f..acc8ebe 100644 --- a/custom_components/ipfire/coordinator.py +++ b/custom_components/ipfire/coordinator.py @@ -213,7 +213,7 @@ async def _async_update_data(self) -> IPFireData: except ConfigEntryAuthFailed: raise - except (aiohttp.ClientError, ValueError) as err: + except (aiohttp.ClientError, TimeoutError, ValueError) as err: raise UpdateFailed( f"Unable to read data from IPFire: {err}" ) from err @@ -527,6 +527,69 @@ async def async_start_upgrade(self) -> None: await self.async_request_refresh() + @property + def supports_reboot_action(self) -> bool: + """Return whether the installed API supports reboot requests.""" + if self.data is None or self.data.api_revision is None: + return False + try: + revision = tuple( + int(part) for part in self.data.api_revision.split(".") + ) + except ValueError: + return False + return revision >= (0, 2, 5) + + async def async_reboot(self) -> None: + """Start an IPFire reboot when the API reports it is required.""" + if ( + not self.supports_reboot_action + or self.data is None + or self.data.system.reboot_required is not True + ): + raise UpdateFailed("IPFire does not currently require a reboot") + + try: + async with self.session.post( + self.api_url, + auth=self._auth(), + ssl=self.verify_ssl, + headers={"X-IPFire-API": "1"}, + data={"action": "reboot"}, + timeout=aiohttp.ClientTimeout(total=15), + ) as response: + if response.status in (401, 403): + raise ConfigEntryAuthFailed( + "Invalid IPFire username or password" + ) + + try: + payload = await response.json(content_type=None) + except (ValueError, TypeError): + payload = {} + + if not isinstance(payload, dict): + raise UpdateFailed( + "IPFire returned an invalid reboot response" + ) + + if ( + response.status >= 400 + or payload.get("result") != "accepted" + ): + error = payload.get("error", "unknown_error") + raise UpdateFailed( + f"Unable to start IPFire reboot: {error}" + ) + + except ConfigEntryAuthFailed: + raise + + except (aiohttp.ClientError, TimeoutError, ValueError) as err: + raise UpdateFailed( + f"Unable to start IPFire reboot: {err}" + ) from err + async def _async_connection_action(self, action: str) -> None: """Execute a connection action on IPFire.""" if action not in {"connect", "disconnect"}: diff --git a/custom_components/ipfire/manifest.json b/custom_components/ipfire/manifest.json index eeb96b3..b21dfa7 100644 --- a/custom_components/ipfire/manifest.json +++ b/custom_components/ipfire/manifest.json @@ -10,5 +10,5 @@ "iot_class": "local_polling", "issue_tracker": "https://github.com/FMainz/HA-IPFire/issues", "requirements": ["aiooui>=0.1.9"], - "version": "0.3.7-beta.5" + "version": "0.3.7-beta.6" } diff --git a/custom_components/ipfire/translations/de.json b/custom_components/ipfire/translations/de.json index aa7025b..5f4b09d 100644 --- a/custom_components/ipfire/translations/de.json +++ b/custom_components/ipfire/translations/de.json @@ -275,6 +275,9 @@ "update": { "system_updates": { "name": "IPFire-Systemupdates" + }, + "reboot": { + "name": "Router neu starten" } }, "button": { diff --git a/custom_components/ipfire/translations/en.json b/custom_components/ipfire/translations/en.json index bb976e0..7db8e4d 100644 --- a/custom_components/ipfire/translations/en.json +++ b/custom_components/ipfire/translations/en.json @@ -275,6 +275,9 @@ "update": { "system_updates": { "name": "IPFire System Updates" + }, + "reboot": { + "name": "Restart router" } }, "button": { diff --git a/custom_components/ipfire/update.py b/custom_components/ipfire/update.py index bb7270b..123686a 100644 --- a/custom_components/ipfire/update.py +++ b/custom_components/ipfire/update.py @@ -23,9 +23,14 @@ async def async_setup_entry( entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: - """Set up the IPFire system update entity.""" + """Set up IPFire update entities.""" coordinator: IPFireCoordinator = entry.runtime_data.coordinator - async_add_entities([IPFireSystemUpdateEntity(coordinator, entry)]) + async_add_entities( + [ + IPFireSystemUpdateEntity(coordinator, entry), + IPFireRebootUpdateEntity(coordinator, entry), + ] + ) class IPFireSystemUpdateEntity( @@ -150,3 +155,52 @@ def _available_updates(self) -> tuple[dict[str, object], ...] | None: if self.coordinator.data is None: return None return self.coordinator.data.available_updates + + +class IPFireRebootUpdateEntity( + CoordinatorEntity[IPFireCoordinator], + UpdateEntity, +): + """Offer a native Home Assistant update action for a required IPFire reboot.""" + + _attr_has_entity_name = True + _attr_translation_key = "reboot" + _attr_icon = "mdi:restart" + _attr_supported_features = UpdateEntityFeature.INSTALL + + def __init__( + self, + coordinator: IPFireCoordinator, + entry: ConfigEntry, + ) -> None: + """Initialize the reboot update entity.""" + super().__init__(coordinator) + self._attr_unique_id = f"{entry.entry_id}_reboot" + self._attr_device_info = DeviceInfo( + identifiers={("ipfire", entry.entry_id)}, + name="IPFire", + manufacturer="IPFire", + model="Firewall", + ) + + @property + def available(self) -> bool: + """Require an API revision that supports reboot requests.""" + return super().available and self.coordinator.supports_reboot_action + + @property + def has_update(self) -> bool: + """Report a reboot action when IPFire requires a restart.""" + return ( + self.coordinator.data is not None + and self.coordinator.data.system.reboot_required is True + ) + + async def async_install( + self, + version: str | None, + backup: bool, + **kwargs: Any, + ) -> None: + """Start the IPFire reboot after Home Assistant confirmation.""" + await self.coordinator.async_reboot() From f876498d3b9cc3736377b3b4133f728433d80e87 Mon Sep 17 00:00:00 2001 From: Frank Mainz Date: Sun, 8 Nov 2026 18:30:25 +0100 Subject: [PATCH 8/9] Fix reboot update state in HA-IPFire beta 7 --- custom_components/ipfire/manifest.json | 2 +- custom_components/ipfire/update.py | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/custom_components/ipfire/manifest.json b/custom_components/ipfire/manifest.json index b21dfa7..5552757 100644 --- a/custom_components/ipfire/manifest.json +++ b/custom_components/ipfire/manifest.json @@ -10,5 +10,5 @@ "iot_class": "local_polling", "issue_tracker": "https://github.com/FMainz/HA-IPFire/issues", "requirements": ["aiooui>=0.1.9"], - "version": "0.3.7-beta.6" + "version": "0.3.7-beta.7" } diff --git a/custom_components/ipfire/update.py b/custom_components/ipfire/update.py index 123686a..16887ba 100644 --- a/custom_components/ipfire/update.py +++ b/custom_components/ipfire/update.py @@ -196,6 +196,23 @@ def has_update(self) -> bool: and self.coordinator.data.system.reboot_required is True ) + @property + def installed_version(self) -> str | None: + """Return the currently running IPFire version.""" + if self.coordinator.data is None: + return None + return self.coordinator.data.system.version + + @property + def latest_version(self) -> str | None: + """Change the update state while a reboot is required.""" + if self.coordinator.data is None: + return None + version = self.coordinator.data.system.version + if self.has_update: + return f"{version} (reboot required)" + return version + async def async_install( self, version: str | None, From cd8a7cbfe5c2861f0bc90c216553ab106ea61b88 Mon Sep 17 00:00:00 2001 From: Frank Mainz Date: Sun, 8 Nov 2026 19:10:24 +0100 Subject: [PATCH 9/9] Prepare HA-IPFire v0.3.7 release --- README-de.md | 8 ++++++++ README.md | 8 ++++++++ custom_components/ipfire/manifest.json | 2 +- 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/README-de.md b/README-de.md index 213c666..1c81847 100644 --- a/README-de.md +++ b/README-de.md @@ -41,6 +41,14 @@ Diese Dokumentation ist auch in 🇬🇧 [englischer Sprache](README.md) verfüg ## Neues in dieser Version +### v0.3.7 + +* Datenschutzbewussten Diagnosebericht mit Integrations- und Verbindungsstatus, Verfügbarkeit der API-Daten, Update-Status, Entitätsanzahlen, UTC-Zeitangaben und bereinigten Fehlerinformationen hinzugefügt. Der normale Zustand `unknown` von Button-Entitäten wird bei der Anzahl nicht verfügbarer oder unbekannter Entitäten nicht mitgezählt. Zugangsdaten, IP-Adressen, Hostnamen und DHCP-Clientdaten werden im Bericht nicht ausgegeben. Die API-Revision erscheint, wenn IPFire-API v0.2.1 oder neuer sie bereitstellt. +* Netzwerkhersteller (`mac_vendor`) zu den DHCP-Lease-Attributen hinzugefügt. Die Zuordnung erfolgt lokal anhand der MAC-Adresse des Lease. +* Native Home-Assistant-Update-Entität hinzugefügt, die verfügbare IPFire-Core- und Paket-Updates anzeigt und das vollständige Pakfire-Upgrade starten kann. +* Statusmeldung für den Update-Vorgang sowie eine native Home-Assistant-Update-Aktion zum Starten eines erforderlichen IPFire-Neustarts hinzugefügt. Die Update- und Neustartfunktionen benötigen eine kompatible `api.cgi`; für den Neustart ist IPFire-API v0.2.5 oder neuer erforderlich. +* Versionsanforderung für `aiooui` angepasst, sodass kompatible Versionen ab 0.1.9 verwendet werden können. + ### v0.3.6 * DHCP-Lease-Anzahl und Clientdaten als Sensorattribute hinzugefügt (benötigt api.cgi). diff --git a/README.md b/README.md index 8825601..6712f01 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,14 @@ This documentation is also available in 🇩🇪 [German](README-de.md). ## What’s New in This Version +### v0.3.7 + +* Added a privacy-conscious diagnostic report with integration and connection status, API data availability, update status, entity counts, UTC timestamps and sanitized error details. Button entities in their normal `unknown` state are excluded from the unavailable/unknown count; the report omits credentials, IP addresses, hostnames and DHCP client details. API revision is included when supported by IPFire-API v0.2.1 or later. +* Added the network-card vendor (`mac_vendor`) to DHCP lease attributes, looked up locally from the lease MAC address. +* Added a native Home Assistant update entity that shows available IPFire core and package updates and can start the full Pakfire upgrade. +* Added update-operation status reporting and a native Home Assistant update action for starting a required IPFire reboot. These update and reboot features require a compatible `api.cgi`; reboot requires IPFire-API v0.2.5 or later. +* Updated the `aiooui` dependency requirement to accept compatible versions from 0.1.9 onward. + ### v0.3.6 * Added DHCP lease count and client details as sensor attributes (requires `api.cgi`). diff --git a/custom_components/ipfire/manifest.json b/custom_components/ipfire/manifest.json index 5552757..1a9c75d 100644 --- a/custom_components/ipfire/manifest.json +++ b/custom_components/ipfire/manifest.json @@ -10,5 +10,5 @@ "iot_class": "local_polling", "issue_tracker": "https://github.com/FMainz/HA-IPFire/issues", "requirements": ["aiooui>=0.1.9"], - "version": "0.3.7-beta.7" + "version": "0.3.7" }