From 08b3edc18cf148c314ca91e0da12356000195705 Mon Sep 17 00:00:00 2001 From: Wolfgang Wendefeuer Date: Tue, 14 Jul 2026 12:15:35 +0200 Subject: [PATCH 1/4] Add multi-AP routing support --- README.md | 2 +- .../open_epaper_link/__init__.py | 35 +++ custom_components/open_epaper_link/button.py | 13 +- .../open_epaper_link/config_flow.py | 13 +- .../open_epaper_link/coordinator.py | 42 ++- custom_components/open_epaper_link/entity.py | 29 ++- .../open_epaper_link/hub_manager.py | 244 ++++++++++++++++++ custom_components/open_epaper_link/image.py | 11 +- .../open_epaper_link/imagegen/core.py | 6 +- .../open_epaper_link/manifest.json | 2 +- custom_components/open_epaper_link/sensor.py | 5 + .../open_epaper_link/services.py | 139 +++++----- .../open_epaper_link/strings.json | 6 +- custom_components/open_epaper_link/text.py | 12 +- .../open_epaper_link/translations/de.json | 6 +- .../open_epaper_link/translations/en.json | 6 +- .../open_epaper_link/translations/pl.json | 6 +- .../open_epaper_link/translations/pt.json | 6 +- custom_components/open_epaper_link/util.py | 32 ++- tests/test_multi_ap.py | 172 ++++++++++++ 20 files changed, 676 insertions(+), 111 deletions(-) create mode 100644 custom_components/open_epaper_link/hub_manager.py create mode 100644 tests/test_multi_ap.py diff --git a/README.md b/README.md index e71919a1..ab78eeda 100644 --- a/README.md +++ b/README.md @@ -142,7 +142,7 @@ After setup, you can configure additional options through the integration's opti **AP Device Configuration:** - **Automatic Discovery** (recommended): APs are automatically discovered via DHCP when connected to the network - **Manual Setup** (fallback): Go to Settings → Integrations → Add Integration and enter your AP's IP address -- ⚠️ **Single Hub Limitation**: Only one AP hub allowed per Home Assistant instance +- **Multiple AP hubs supported**: Add every AP separately. A physical tag remains one logical Home Assistant device; actions are routed to the online AP with the freshest tag check-in. - All tags connected to the AP are automatically discovered **BLE Device Discovery:** diff --git a/custom_components/open_epaper_link/__init__.py b/custom_components/open_epaper_link/__init__.py index 8da396c9..1b7b5556 100644 --- a/custom_components/open_epaper_link/__init__.py +++ b/custom_components/open_epaper_link/__init__.py @@ -14,6 +14,7 @@ from .ble import BLEDeviceMetadata from .const import DOMAIN from .coordinator import Hub +from .hub_manager import get_hub_manager from .runtime_data import OpenEPaperLinkConfigEntry, OpenEPaperLinkBLERuntimeData from .services import async_setup_services from .tag_types import get_tag_types_manager @@ -108,6 +109,8 @@ async def async_migrate_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> Version 3 -> 4: Fix color support. + Version 4 -> 5: Enable multi-AP runtime and AP-specific storage. + Returns: bool: True if migration was successful, False otherwise. """ @@ -224,6 +227,10 @@ async def async_migrate_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> ) _LOGGER.info("Successfully migrated config entry to version 4") + if config_entry.version == 4: + hass.config_entries.async_update_entry(config_entry, version=5) + _LOGGER.info("Successfully migrated config entry to multi-AP schema version 5") + return True @@ -430,6 +437,7 @@ def _ble_device_found( await hub.async_setup_initial() entry.runtime_data = hub + get_hub_manager(hass).register_hub(hub) removed_entities = await async_migrate_camera_entities(hass, entry) if removed_entities: @@ -448,6 +456,7 @@ def _ble_device_found( ) await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) + await async_cleanup_legacy_ap_device(hass) async def start_websocket(_): """Start WebSocket connection after HA is fully started.""" @@ -515,6 +524,7 @@ async def async_unload_entry(hass: HomeAssistant, entry: OpenEPaperLinkConfigEnt unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) if unload_ok: + get_hub_manager(hass).unregister_hub(entry.entry_id) await hub.shutdown() return unload_ok @@ -546,6 +556,9 @@ async def async_remove_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: hass: Home Assistant instance entry: Configuration entry being removed """ + if CONF_HOST in entry.data: + await storage.async_remove_store(hass, f"{DOMAIN}_tags_{entry.entry_id}") + # Only remove shared storage files if this is the last config entry remaining_entries = [ config_entry for config_entry in hass.config_entries.async_entries(DOMAIN) @@ -624,6 +637,28 @@ async def async_remove_storage_files(hass: HomeAssistant) -> None: _LOGGER.debug("Reset tag types manager singleton") +async def async_cleanup_legacy_ap_device(hass: HomeAssistant) -> None: + """Remove the old globally identified AP device once it is orphaned.""" + device_registry = dr.async_get(hass) + legacy_device = device_registry.async_get_device(identifiers={(DOMAIN, "ap")}) + if legacy_device is None: + return + + entity_registry = er.async_get(hass) + if any( + entity.device_id == legacy_device.id + for entity in entity_registry.entities.values() + ): + _LOGGER.debug( + "Legacy AP device %s still owns entities; deferring cleanup", + legacy_device.id, + ) + return + + device_registry.async_remove_device(legacy_device.id) + _LOGGER.info("Removed orphaned legacy OpenEPaperLink AP device") + + async def _send_welcome_image( hass: HomeAssistant, diff --git a/custom_components/open_epaper_link/button.py b/custom_components/open_epaper_link/button.py index f5c543f8..ec6428db 100644 --- a/custom_components/open_epaper_link/button.py +++ b/custom_components/open_epaper_link/button.py @@ -17,6 +17,7 @@ from .tag_types import get_tag_types_manager from .util import is_ble_entry from .const import DOMAIN +from .hub_manager import get_hub_manager _LOGGER = logging.getLogger(__name__) @@ -59,6 +60,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: OpenEPaperLinkConfigEntr # AP device setup (original logic) hub = entry_data + hub_manager = get_hub_manager(hass) # Track added tags to prevent duplicates added_tags = set() @@ -85,9 +87,12 @@ async def async_add_tag_buttons(tag_mac: str) -> None: tag_mac: MAC address of the tag to create buttons for """ - # Skip if tag is blacklisted - if tag_mac in hub.get_blacklisted_tags(): - _LOGGER.debug("Skipping button creation for blacklisted tag: %s", tag_mac) + if not hub_manager.is_tag_entity_owner(entry.entry_id, tag_mac): + return + + # Skip only when no AP exposes an eligible copy of the tag. + if not hub_manager.hubs_for_tag(tag_mac): + _LOGGER.debug("Skipping button creation for unavailable tag: %s", tag_mac) return if tag_mac in added_tags: @@ -145,6 +150,8 @@ async def handle_blacklist_update() -> None: if device: for identifier in device.identifiers: if identifier[0] == DOMAIN and identifier[1] in hub.get_blacklisted_tags(): + if hub_manager.hubs_for_tag(identifier[1]): + continue entities_to_remove.append(entity.entity_id) # Add device to removal list devices_to_remove.add(device.id) diff --git a/custom_components/open_epaper_link/config_flow.py b/custom_components/open_epaper_link/config_flow.py index c44a0e57..27479a00 100644 --- a/custom_components/open_epaper_link/config_flow.py +++ b/custom_components/open_epaper_link/config_flow.py @@ -50,7 +50,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): context between user interactions. """ - VERSION = 4 + VERSION = 5 def __init__(self) -> None: """Initialize flow.""" @@ -108,11 +108,6 @@ async def async_step_user( FlowResult: Result of the flow step, either showing the form again (with errors if applicable) or creating an entry """ - # Check for existing AP hub entries immediately (before showing form) - for entry_id, entry_data in self.hass.data.get(DOMAIN, {}).items(): - if not is_ble_entry(entry_data): # This is an AP (Hub object) - return self.async_abort(reason="single_instance_allowed") - errors: dict[str, str] = {} if user_input is not None: @@ -393,12 +388,6 @@ async def async_step_dhcp( # Extract host IP from discovery info host = discovery_info.ip - # Check for existing AP entries in config entries - # AP entries have CONF_HOST in data, BLE entries have device_type - for entry in self._async_current_entries(): - if CONF_HOST in entry.data: - return self.async_abort(reason="single_instance_allowed") - # Set unique_id to IP address (same as manual setup) # This ensures DHCP and manual discoveries are treated as the same entry await self.async_set_unique_id(host) diff --git a/custom_components/open_epaper_link/coordinator.py b/custom_components/open_epaper_link/coordinator.py index eba5646b..bf5640b6 100644 --- a/custom_components/open_epaper_link/coordinator.py +++ b/custom_components/open_epaper_link/coordinator.py @@ -20,13 +20,14 @@ import logging from .const import DOMAIN, SIGNAL_AP_UPDATE, SIGNAL_TAG_UPDATE, SIGNAL_TAG_IMAGE_UPDATE +from .hub_manager import get_hub_manager from .tag_types import get_tag_types_manager, get_hw_string _LOGGER: Final = logging.getLogger(__name__) STORAGE_VERSION = 1 -STORAGE_KEY = f"{DOMAIN}_tags" +LEGACY_STORAGE_KEY = f"{DOMAIN}_tags" RECONNECT_INTERVAL = 30 SAVE_DELAY = 10 WEBSOCKET_TIMEOUT = 60 @@ -90,8 +91,12 @@ def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: self._session = async_get_clientsession(hass) self._shutdown_handler: CALLBACK_TYPE | None = None self._shutdown = asyncio.Event() + self.storage_key = f"{DOMAIN}_tags_{entry.entry_id}" self._store = Store[dict[str, any]]( - hass, STORAGE_VERSION, STORAGE_KEY, private=True, atomic_writes=True + hass, STORAGE_VERSION, self.storage_key, private=True, atomic_writes=True + ) + self._legacy_store = Store[dict[str, any]]( + hass, STORAGE_VERSION, LEGACY_STORAGE_KEY, private=True, atomic_writes=True ) self._data: dict[str, dict] = {} self._ap_data: dict[str, any] = {} @@ -162,6 +167,16 @@ async def async_setup_initial(self) -> None: """ # Load stored data stored = await self._store.async_load() + if stored is None: + # Version 3 used one shared store for every AP. It is safe to use + # this only as migration input; async_load_all_tags filters the + # data against the inventory actually returned by this AP. + stored = await self._legacy_store.async_load() + if stored: + _LOGGER.info( + "Migrating legacy tag cache to AP-specific storage %s", + self.storage_key, + ) if stored: self._data = stored.get("tags", {}) self._known_tags = set(self._data.keys()) @@ -895,6 +910,16 @@ async def async_load_all_tags(self) -> None: # Get all tag data from AP all_tags = await self._fetch_all_tags_from_ap() + # Never retain legacy or cached tags that are not in this AP's + # current inventory. This prevents cross-AP cache contamination. + actual_macs = {tag_mac.upper() for tag_mac in all_tags} + self._data = { + tag_mac: data + for tag_mac, data in self._data.items() + if tag_mac.upper() in actual_macs + } + self._known_tags = set(self._data) + # Process each tag using the common helper function for tag_mac, tag_data in all_tags.items(): # Process tag with the initial load flag set @@ -1000,6 +1025,19 @@ async def _remove_tag(self, tag_mac: str) -> None: # Notify that this tag has been removed async_dispatcher_send(self.hass, f"{SIGNAL_TAG_UPDATE}_{tag_mac}") + # Preserve the logical HA device while another AP still exposes + # the same tag. + manager = get_hub_manager(self.hass) + if manager.tag_exists_elsewhere( + tag_mac, exclude_entry_id=self.entry.entry_id + ): + _LOGGER.info( + "Keeping logical tag %s because another AP still exposes it", + tag_mac, + ) + await self._store.async_save({"tags": self._data}) + return + # Remove related devices and entities device_registry = dr.async_get(self.hass) entity_registry = er.async_get(self.hass) diff --git a/custom_components/open_epaper_link/entity.py b/custom_components/open_epaper_link/entity.py index 957d6cec..186d40cb 100644 --- a/custom_components/open_epaper_link/entity.py +++ b/custom_components/open_epaper_link/entity.py @@ -4,11 +4,13 @@ from homeassistant.components import bluetooth from homeassistant.core import callback +from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity import DeviceInfo, Entity from .ble import BLEDeviceMetadata from .const import DOMAIN, ATC_CONFIG_URL +from .hub_manager import ap_identifier, get_hub_manager from .tag_types import get_hw_string, get_hw_dimensions if TYPE_CHECKING: @@ -40,8 +42,8 @@ def __init__(self, hub: Hub) -> None: def device_info(self) -> DeviceInfo: """Return device info for the AP.""" return DeviceInfo( - identifiers={(DOMAIN, "ap")}, - name="OpenEPaperLink AP", + identifiers={(DOMAIN, ap_identifier(self._hub.entry.entry_id))}, + name=f"OpenEPaperLink AP ({self._hub.host})", model=self._hub.ap_model, manufacturer="OpenEPaperLink", configuration_url=f"http://{self._hub.host}" @@ -92,13 +94,25 @@ class OpenEPaperLinkTagEntity(Entity): def __init__(self, hub: Hub, tag_mac: str) -> None: """Initialize the tag entity.""" - self._hub = hub + self._initial_hub = hub + self._hub_manager = get_hub_manager(hub.hass) self._tag_mac = tag_mac + @property + def _hub(self) -> Hub: + """Return the freshest hub for this logical tag.""" + try: + return self._hub_manager.resolve_tag_hub( + self._tag_mac, require_online=False + ) + except HomeAssistantError: + # Entity construction can happen before all hubs are registered. + return self._initial_hub + @property def device_info(self) -> DeviceInfo: """Return device info for the tag.""" - tag_data = self._hub.get_tag_data(self._tag_mac) + tag_data = self._hub_manager.get_tag_data(self._tag_mac) tag_name = tag_data.get("tag_name", self._tag_mac) hw_type = tag_data.get("hw_type", 0) hw_string = get_hw_string(hw_type) @@ -110,7 +124,6 @@ def device_info(self) -> DeviceInfo: name=tag_name, manufacturer="OpenEPaperLink", model=hw_string, - via_device=(DOMAIN, "ap"), sw_version=f"0x{int(firmware_version, 16):X}" if firmware_version else "Unknown", serial_number=self._tag_mac, hw_version=f"{width}x{height}", @@ -119,11 +132,7 @@ def device_info(self) -> DeviceInfo: @property def available(self) -> bool: """Return if the entity is available.""" - return ( - self._hub.online - and self._hub.is_tag_online(self._tag_mac) - and self._tag_mac not in self._hub.get_blacklisted_tags() - ) + return self._hub_manager.is_tag_available(self._tag_mac) async def async_added_to_hass(self) -> None: """Register update signal handlers.""" diff --git a/custom_components/open_epaper_link/hub_manager.py b/custom_components/open_epaper_link/hub_manager.py new file mode 100644 index 00000000..aba2a721 --- /dev/null +++ b/custom_components/open_epaper_link/hub_manager.py @@ -0,0 +1,244 @@ +"""Runtime registry and routing for multiple OpenEPaperLink access points.""" + +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING, Any, Final + +from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError, ServiceValidationError +from homeassistant.helpers import device_registry as dr, entity_registry as er + +from .const import DOMAIN + +if TYPE_CHECKING: + from .coordinator import Hub + +_LOGGER: Final = logging.getLogger(__name__) + +HUB_MANAGER_KEY = "hub_manager" +AP_IDENTIFIER_PREFIX = "ap_" + + +def normalize_tag_mac(tag_mac: str) -> str: + """Return the canonical tag MAC representation used by the integration.""" + return tag_mac.upper() + + +def ap_identifier(entry_id: str) -> str: + """Return the unique device-registry identifier for an AP config entry.""" + return f"{AP_IDENTIFIER_PREFIX}{entry_id}" + + +class MultiHubManager: + """Track loaded AP hubs and route a logical tag to the correct AP.""" + + def __init__(self, hass: HomeAssistant) -> None: + self.hass = hass + self._hubs: dict[str, Hub] = {} + self._tag_owners: dict[str, str] = {} + + @property + def hubs(self) -> tuple[Hub, ...]: + """Return all registered AP hubs.""" + return tuple(self._hubs.values()) + + def register_hub(self, hub: Hub) -> None: + """Register or replace the runtime hub for a config entry.""" + self._hubs[hub.entry.entry_id] = hub + _LOGGER.debug( + "Registered OpenEPaperLink AP %s for entry %s", + hub.host, + hub.entry.entry_id, + ) + + def unregister_hub(self, entry_id: str) -> None: + """Remove an unloaded AP hub from routing.""" + hub = self._hubs.pop(entry_id, None) + self._tag_owners = { + tag_mac: owner + for tag_mac, owner in self._tag_owners.items() + if owner != entry_id + } + if hub: + _LOGGER.debug( + "Unregistered OpenEPaperLink AP %s for entry %s", + hub.host, + entry_id, + ) + + def get_hub_for_entry(self, entry_id: str) -> Hub: + """Return the AP hub for an integration config entry.""" + hub = self._hubs.get(entry_id) + if hub is None: + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="ap_entry_not_loaded", + translation_placeholders={"entry_id": entry_id}, + ) + return hub + + @staticmethod + def _tag_last_seen(hub: Hub, tag_mac: str) -> float: + value = hub.get_tag_data(tag_mac).get("last_seen", 0) + try: + return float(value or 0) + except (TypeError, ValueError): + return 0 + + def hubs_for_tag(self, tag_mac: str) -> list[Hub]: + """Return hubs that currently know an unblacklisted tag.""" + tag_mac = normalize_tag_mac(tag_mac) + return [ + hub + for hub in self._hubs.values() + if tag_mac in {normalize_tag_mac(mac) for mac in hub.tags} + and tag_mac + not in {normalize_tag_mac(mac) for mac in hub.get_blacklisted_tags()} + ] + + def resolve_tag_hub(self, tag_mac: str, *, require_online: bool = True) -> Hub: + """Resolve a logical tag to its active AP. + + Online hubs that also report the tag as online are preferred. If more + than one AP reports the tag online, the freshest ``last_seen`` wins. + Read-only callers may set ``require_online=False`` and receive the + freshest online or cached candidate. + """ + tag_mac = normalize_tag_mac(tag_mac) + candidates = self.hubs_for_tag(tag_mac) + active = [ + hub for hub in candidates if hub.online and hub.is_tag_online(tag_mac) + ] + + if require_online: + selectable = active + else: + selectable = ( + active or [hub for hub in candidates if hub.online] or candidates + ) + + if not selectable: + candidate_hosts = ", ".join(sorted(hub.host for hub in candidates)) or "none" + _LOGGER.debug( + "No routable AP for tag %s (candidates: %s)", + tag_mac, + candidate_hosts, + ) + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key=( + "tag_no_online_ap" + if candidates + else "tag_not_registered_any_ap" + ), + translation_placeholders={ + "tag_mac": tag_mac, + "candidate_hosts": candidate_hosts, + }, + ) + + selected = max( + selectable, + key=lambda hub: (self._tag_last_seen(hub, tag_mac), hub.entry.entry_id), + ) + _LOGGER.debug( + "Resolved tag %s to AP %s; candidates=%s; reason=%s", + tag_mac, + selected.host, + [ + { + "host": hub.host, + "online": hub.online, + "tag_online": hub.is_tag_online(tag_mac) if hub.online else False, + "last_seen": self._tag_last_seen(hub, tag_mac), + } + for hub in candidates + ], + "freshest active last_seen" if active else "freshest cached data", + ) + return selected + + def get_tag_data(self, tag_mac: str) -> dict[str, Any]: + """Return the freshest available data for a logical tag.""" + try: + return self.resolve_tag_hub(tag_mac, require_online=False).get_tag_data( + normalize_tag_mac(tag_mac) + ) + except HomeAssistantError: + return {} + + def is_tag_available(self, tag_mac: str) -> bool: + """Return whether any loaded AP currently owns the live tag connection.""" + try: + self.resolve_tag_hub(tag_mac, require_online=True) + except HomeAssistantError: + return False + return True + + def tag_exists_elsewhere(self, tag_mac: str, *, exclude_entry_id: str) -> bool: + """Return whether another AP still exposes an unblacklisted tag.""" + return any( + hub.entry.entry_id != exclude_entry_id + for hub in self.hubs_for_tag(tag_mac) + ) + + def is_tag_entity_owner(self, entry_id: str, tag_mac: str) -> bool: + """Choose one config entry to create the shared tag entities. + + Existing entity-registry ownership wins so entity IDs and automation + references stay stable across upgrades and restarts. + """ + tag_mac = normalize_tag_mac(tag_mac) + owner = self._tag_owners.get(tag_mac) + if owner is None: + entity_registry = er.async_get(self.hass) + prefix = f"{tag_mac}_" + existing_owners = { + entity.config_entry_id + for entity in entity_registry.entities.values() + if entity.platform == DOMAIN + and entity.unique_id + and entity.unique_id.upper().startswith(prefix) + and entity.config_entry_id + } + owner = sorted(existing_owners)[0] if existing_owners else entry_id + self._tag_owners[tag_mac] = owner + _LOGGER.debug("Logical tag %s entity owner is %s", tag_mac, owner) + return owner == entry_id + + def resolve_ap_device(self, device_id: str) -> Hub: + """Resolve a selected HA AP device to its exact hub.""" + device = dr.async_get(self.hass).async_get(device_id) + if device is None: + raise ServiceValidationError( + translation_domain=DOMAIN, + translation_key="device_not_found", + translation_placeholders={"device_id": device_id}, + ) + + identifier = next( + ( + value + for domain, value in device.identifiers + if domain == DOMAIN and value.startswith(AP_IDENTIFIER_PREFIX) + ), + None, + ) + if identifier is None: + raise ServiceValidationError( + translation_domain=DOMAIN, + translation_key="device_not_ap", + translation_placeholders={"device_id": device_id}, + ) + return self.get_hub_for_entry(identifier[len(AP_IDENTIFIER_PREFIX):]) + + +def get_hub_manager(hass: HomeAssistant) -> MultiHubManager: + """Return the integration-wide multi-hub manager.""" + domain_data = hass.data.setdefault(DOMAIN, {}) + manager = domain_data.get(HUB_MANAGER_KEY) + if manager is None: + manager = MultiHubManager(hass) + domain_data[HUB_MANAGER_KEY] = manager + return manager diff --git a/custom_components/open_epaper_link/image.py b/custom_components/open_epaper_link/image.py index 26b1c962..5a555839 100644 --- a/custom_components/open_epaper_link/image.py +++ b/custom_components/open_epaper_link/image.py @@ -12,6 +12,7 @@ from .entity import OpenEPaperLinkTagEntity, OpenEPaperLinkBLEEntity from .runtime_data import OpenEPaperLinkConfigEntry from .const import DOMAIN, SIGNAL_TAG_IMAGE_UPDATE +from .hub_manager import get_hub_manager from homeassistant.components.image import ImageEntity from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.entity_platform import AddEntitiesCallback @@ -45,18 +46,22 @@ async def async_setup_entry( return True hub = entry.runtime_data + hub_manager = get_hub_manager(hass) # Track added image entities to prevent duplicates added_image_entities = set() async def async_add_image_entity(tag_mac: str) -> None: + if not hub_manager.is_tag_entity_owner(entry.entry_id, tag_mac): + return + # Skip if image entity already exists if tag_mac in added_image_entities: return # Skip if tag is blacklisted - if tag_mac in hub.get_blacklisted_tags(): + if not hub_manager.hubs_for_tag(tag_mac): _LOGGER.debug("Skipping image entity creation for blacklisted tag: %s", tag_mac) return @@ -98,6 +103,8 @@ async def handle_blacklist_update() -> None: don't consume resources with unnecessary image processing. """ for tag_mac in hub.get_blacklisted_tags(): + if hub_manager.hubs_for_tag(tag_mac): + continue if tag_mac in added_image_entities: added_image_entities.remove(tag_mac) @@ -295,4 +302,4 @@ def _handle_image_update(self, data) -> None: if isinstance(data, bytes): self._cached_image = data self._last_updated = datetime.now() - self.async_write_ha_state() \ No newline at end of file + self.async_write_ha_state() diff --git a/custom_components/open_epaper_link/imagegen/core.py b/custom_components/open_epaper_link/imagegen/core.py index 55c272ff..84f42306 100644 --- a/custom_components/open_epaper_link/imagegen/core.py +++ b/custom_components/open_epaper_link/imagegen/core.py @@ -10,7 +10,7 @@ from ..const import DOMAIN from ..tag_types import TagType, get_tag_types_manager -from ..util import get_hub_from_hass +from ..util import get_hub_for_tag from ..runtime_data import OpenEPaperLinkBLERuntimeData from .types import ElementType, DrawingContext @@ -107,8 +107,8 @@ async def get_tag_info(self, entity_id: str) -> Optional[tuple[TagType, str]]: """ try: - # Get hub instance - hub = get_hub_from_hass(self.hass) + # Route this logical tag to the AP that currently reports it online. + hub = get_hub_for_tag(self.hass, entity_id) if not hub.online: raise HomeAssistantError( translation_domain=DOMAIN, diff --git a/custom_components/open_epaper_link/manifest.json b/custom_components/open_epaper_link/manifest.json index 9f8f640e..0ad3c50b 100644 --- a/custom_components/open_epaper_link/manifest.json +++ b/custom_components/open_epaper_link/manifest.json @@ -35,5 +35,5 @@ "numpy>=1.26.4", "Pillow>=10.4.0" ], - "version": "3.0.0" + "version": "3.0.1-multi-ap.1" } diff --git a/custom_components/open_epaper_link/sensor.py b/custom_components/open_epaper_link/sensor.py index 2aa859cb..e130e621 100644 --- a/custom_components/open_epaper_link/sensor.py +++ b/custom_components/open_epaper_link/sensor.py @@ -30,6 +30,7 @@ from .entity import OpenEPaperLinkTagEntity, OpenEPaperLinkAPEntity, OpenEPaperLinkBLEEntity from .runtime_data import OpenEPaperLinkConfigEntry from .const import DOMAIN +from .hub_manager import get_hub_manager from .util import is_ble_entry from .tag_types import get_hw_string, get_hw_dimensions @@ -646,6 +647,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: OpenEPaperLinkConfigEntr # Traditional AP setup hub = entry_data # For AP entries, entry_data is the Hub instance + hub_manager = get_hub_manager(hass) # Set up AP sensors ap_sensors = [OpenEPaperLinkAPSensor(hub, description) for description in AP_SENSOR_TYPES] @@ -662,6 +664,9 @@ def async_add_tag_sensor(tag_mac: str) -> None: Args: tag_mac: MAC address of the newly discovered tag """ + if not hub_manager.is_tag_entity_owner(entry.entry_id, tag_mac): + return + entities = [] tag_data = hub.get_tag_data(tag_mac) diff --git a/custom_components/open_epaper_link/services.py b/custom_components/open_epaper_link/services.py index 4c362938..fc9b4904 100644 --- a/custom_components/open_epaper_link/services.py +++ b/custom_components/open_epaper_link/services.py @@ -8,14 +8,14 @@ from homeassistant.exceptions import ServiceValidationError, HomeAssistantError from homeassistant.helpers import device_registry as dr from homeassistant.helpers.dispatcher import async_dispatcher_send -from .coordinator import Hub from .ble import BLEConnectionError, BLETimeoutError, BLEProtocolError from .const import DOMAIN, SIGNAL_TAG_IMAGE_UPDATE from .imagegen import ImageGen from .tag_types import get_tag_types_manager from .upload import create_upload_queues, DITHER_DEFAULT, upload_to_ble_block, upload_to_hub -from .util import is_ble_entry, get_hub_from_hass, rgb_to_rgb332, int_to_hex_string, \ +from .util import get_hub_for_tag, rgb_to_rgb332, int_to_hex_string, \ is_ble_device, get_mac_from_entity_id +from .hub_manager import AP_IDENTIFIER_PREFIX, get_hub_manager _LOGGER: Final = logging.getLogger(__name__) @@ -74,8 +74,16 @@ async def get_entity_id_from_device_id(device_id: str) -> str: translation_placeholders={"device_id": device_id}, ) - domain_mac = next(iter(device.identifiers)) - if domain_mac[0] != DOMAIN: + domain_mac = next( + ( + identifier + for identifier in device.identifiers + if identifier[0] == DOMAIN + and not identifier[1].startswith(AP_IDENTIFIER_PREFIX) + ), + None, + ) + if domain_mac is None: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="device_not_oepl", @@ -127,52 +135,33 @@ def _color_segment(color_num: int) -> str: ) - def require_hub_online(func: Callable) -> Callable: - """Decorator to require the AP to be online before executing a service.""" - @wraps(func) - async def wrapper(service: ServiceCall, *args, **kwargs) -> None: - hub = get_hub_from_hass(hass) - if not hub.online: - raise HomeAssistantError( - translation_domain=DOMAIN, - translation_key="ap_offline", - ) - return await func(service, *args, hub=hub, **kwargs) - return wrapper + async def get_target_device_ids(service: ServiceCall) -> list[str]: + """Expand device, label, and area targets into unique device IDs.""" + device_ids = service.data.get("device_id", []) + label_ids = service.data.get("label_id", []) + area_ids = service.data.get("area_id", []) + + if isinstance(device_ids, str): + device_ids = [device_ids] + else: + device_ids = list(device_ids) + if isinstance(label_ids, str): + label_ids = [label_ids] + if isinstance(area_ids, str): + area_ids = [area_ids] + + for label_id in label_ids: + device_ids.extend(await get_device_ids_from_label_id(label_id)) + for area_id in area_ids: + device_ids.extend(await get_device_ids_from_area_id(area_id)) + + return list(dict.fromkeys(device_ids)) def handle_targets(func: Callable) -> Callable: """Decorator to handle device_id, label_id, and area_id targeting.""" @wraps(func) async def wrapper(service: ServiceCall, *args, **kwargs): - device_ids = service.data.get("device_id", []) - label_ids = service.data.get("label_id", []) - area_ids = service.data.get("area_id", []) - - # Normalize to lists - if isinstance(device_ids, str): - device_ids = [device_ids] - if isinstance(label_ids, str): - label_ids = [label_ids] - if isinstance(area_ids, str): - area_ids = [area_ids] - - # Expand labels - for label_id in label_ids: - expanded = await get_device_ids_from_label_id(label_id) - device_ids.extend(expanded) - - # Expand areas - for area_id in area_ids: - expanded = await get_device_ids_from_area_id(area_id) - device_ids.extend(expanded) - - # Remove duplicates while preserving order - seen = set() - unique_device_ids = [] - for device_id in device_ids: - if device_id not in seen: - seen.add(device_id) - unique_device_ids.append(device_id) + unique_device_ids = await get_target_device_ids(service) if not unique_device_ids: raise ServiceValidationError( @@ -238,12 +227,7 @@ async def drawcustom_service(service: ServiceCall, entity_id: str) -> None: # For hub devices, ensure hub is online hub = None if not is_ble: - hub = get_hub_from_hass(hass) - if not hub.online: - raise HomeAssistantError( - translation_domain=DOMAIN, - translation_key="ap_offline", - ) + hub = get_hub_for_tag(hass, entity_id) # Generate image generator = ImageGen(hass) @@ -328,41 +312,66 @@ async def drawcustom_service(service: ServiceCall, entity_id: str) -> None: - @require_hub_online @handle_targets - async def setled_service(service: ServiceCall, entity_id: str, hub: Hub) -> None: + async def setled_service(service: ServiceCall, entity_id: str) -> None: + hub = get_hub_for_tag(hass, entity_id) pattern = _build_led_pattern(service.data) await hub.set_led_pattern(entity_id, pattern) - @require_hub_online @handle_targets - async def clear_pending_service(service: ServiceCall, entity_id: str, hub: Hub) -> None: + async def clear_pending_service(service: ServiceCall, entity_id: str) -> None: """Clear pending updates for target devices.""" + hub = get_hub_for_tag(hass, entity_id) await hub.send_tag_cmd(entity_id, "clear") - @require_hub_online @handle_targets - async def force_refresh_service(service: ServiceCall, entity_id: str, hub: Hub) -> None: + async def force_refresh_service(service: ServiceCall, entity_id: str) -> None: """Force refresh target devices.""" + hub = get_hub_for_tag(hass, entity_id) await hub.send_tag_cmd(entity_id, "refresh") - @require_hub_online @handle_targets - async def reboot_tag_service(service: ServiceCall,entity_id: str, hub: Hub) -> None: + async def reboot_tag_service(service: ServiceCall,entity_id: str) -> None: """Reboot target devices.""" + hub = get_hub_for_tag(hass, entity_id) await hub.send_tag_cmd(entity_id, "reboot") - @require_hub_online @handle_targets - async def scan_channels_service(service: ServiceCall, entity_id: str, hub: Hub) -> None: + async def scan_channels_service(service: ServiceCall, entity_id: str) -> None: """Trigger channel scan on target devices.""" + hub = get_hub_for_tag(hass, entity_id) await hub.send_tag_cmd(entity_id, "scan") - @require_hub_online - async def reboot_ap_service(service: ServiceCall, hub: Hub) -> None: - """Reboot the Access Point.""" - await hub.reboot_ap() + async def reboot_ap_service(service: ServiceCall) -> None: + """Reboot the explicitly targeted access point or points.""" + device_ids = await get_target_device_ids(service) + if not device_ids: + raise ServiceValidationError( + translation_domain=DOMAIN, + translation_key="no_targets_specified", + ) + + manager = get_hub_manager(hass) + errors: list[str] = [] + for device_id in device_ids: + try: + hub = manager.resolve_ap_device(device_id) + if not hub.online: + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="ap_offline", + ) + await hub.reboot_ap() + except (ServiceValidationError, HomeAssistantError) as err: + errors.append(f"{device_id}: {err}") + + if errors: + raise ServiceValidationError( + translation_domain=DOMAIN, + translation_key="multiple_errors", + translation_placeholders={"errors": "\n".join(errors)}, + ) async def refresh_tag_types_service(service: ServiceCall) -> None: """Force refresh tag types from GitHub.""" diff --git a/custom_components/open_epaper_link/strings.json b/custom_components/open_epaper_link/strings.json index b3bf8a26..33ca4f47 100644 --- a/custom_components/open_epaper_link/strings.json +++ b/custom_components/open_epaper_link/strings.json @@ -33,7 +33,6 @@ "invalid_device_config": "Device returned invalid configuration data. Please reconfigure the device or update its firmware." }, "abort": { - "single_instance_allowed": "Only one OpenEPaperLink hub can be configured. Multiple BLE devices are supported, but only one AP hub is allowed.", "unsupported_protocol": "Unsupported BLE firmware protocol. Only ATC firmware is supported.", "invalid_advertising_data": "Could not parse device advertising data. Please ensure the device is using compatible firmware.", "no_reconfigure_ble": "BLE devices do not support reconfiguration. Remove and re-add the device if you need to change its settings.", @@ -337,6 +336,11 @@ "tagtypes_load_failed": { "message": "Failed to load tag type definitions. No stored data available. Check network connectivity or GitHub access." }, "tagtypes_refresh_failed": { "message": "Failed to refresh tag type definitions. Check network connectivity or GitHub access." }, "no_hub_configured": { "message": "No AP hub configured. Only BLE devices found." }, + "hub_target_required": { "message": "More than one AP is configured. Select a tag or AP target so OpenEPaperLink can route the action." }, + "ap_entry_not_loaded": { "message": "OpenEPaperLink AP config entry {entry_id} is not loaded." }, + "device_not_ap": { "message": "Device {device_id} is not an OpenEPaperLink access point." }, + "tag_no_online_ap": { "message": "No online access point currently reports tag {tag_mac} as active. Candidate APs: {candidate_hosts}." }, + "tag_not_registered_any_ap": { "message": "Tag {tag_mac} is not registered on any loaded OpenEPaperLink access point." }, "ble_slots_unavailable": { "message": "No available Bluetooth connection slots for {mac_address}. Add more ESPHome Bluetooth proxies near this device or wait for existing connections to free up. Details: {error}." }, "ble_device_not_found": { "message": "Device {mac_address} not found." }, "ble_characteristic_not_resolved": { "message": "Could not resolve characteristic for service {service_uuid}." }, diff --git a/custom_components/open_epaper_link/text.py b/custom_components/open_epaper_link/text.py index 9a2c4426..7c9aed40 100644 --- a/custom_components/open_epaper_link/text.py +++ b/custom_components/open_epaper_link/text.py @@ -15,6 +15,7 @@ from .runtime_data import OpenEPaperLinkConfigEntry from .const import DOMAIN +from .hub_manager import get_hub_manager import logging @@ -193,6 +194,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: OpenEPaperLinkConfigEntr async_add_entities: Callback to register new entities """ hub = entry.runtime_data + hub_manager = get_hub_manager(hass) # Wait for initial AP config to be loaded if not hub.ap_config: @@ -206,7 +208,10 @@ async def async_setup_entry(hass: HomeAssistant, entry: OpenEPaperLinkConfigEntr # Add tag name/alias text entities for tag_mac in hub.tags: - if tag_mac not in hub.get_blacklisted_tags(): + if ( + hub_manager.is_tag_entity_owner(entry.entry_id, tag_mac) + and hub_manager.hubs_for_tag(tag_mac) + ): entities.append(TagNameText(hub, tag_mac)) async_add_entities(entities) @@ -223,7 +228,10 @@ async def async_add_tag_text(tag_mac: str) -> None: Args: tag_mac: MAC address of the newly discovered tag """ - if tag_mac not in hub.get_blacklisted_tags(): + if ( + hub_manager.is_tag_entity_owner(entry.entry_id, tag_mac) + and hub_manager.hubs_for_tag(tag_mac) + ): async_add_entities([TagNameText(hub, tag_mac)]) entry.async_on_unload( diff --git a/custom_components/open_epaper_link/translations/de.json b/custom_components/open_epaper_link/translations/de.json index 62e489bc..3e24fbd6 100644 --- a/custom_components/open_epaper_link/translations/de.json +++ b/custom_components/open_epaper_link/translations/de.json @@ -33,7 +33,6 @@ "invalid_device_config": "Gerät hat ungültige Konfigurationsdaten zurückgegeben. Bitte Gerät neu konfigurieren oder die Firmware aktualisieren." }, "abort": { - "single_instance_allowed": "Nur ein OpenEPaperLink-Hub kann konfiguriert werden. Mehrere BLE-Geräte werden unterstützt, aber nur ein AP-Hub ist erlaubt.", "unsupported_protocol": "Nicht unterstütztes BLE-Firmware-Protokoll. Nur ATC- und OEPL-Firmware werden unterstützt.", "invalid_advertising_data": "Advertising-Daten des Geräts konnten nicht analysiert werden. Bitte sicherstellen, dass das Gerät eine kompatible Firmware verwendet.", "no_reconfigure_ble": "BLE-Geräte unterstützen keine Neukonfiguration. Gerät entfernen und erneut hinzufügen, wenn Einstellungen geändert werden sollen.", @@ -444,6 +443,11 @@ "tagtypes_load_failed": "Tag-Typ-Definitionen konnten nicht geladen werden. Keine gespeicherten Daten verfügbar. Netzwerkverbindung oder GitHub-Zugriff prüfen.", "tagtypes_refresh_failed": "Tag-Typ-Definitionen konnten nicht aktualisiert werden. Netzwerkverbindung oder GitHub-Zugriff prüfen.", "no_hub_configured": "Kein AP-Hub konfiguriert. Nur BLE-Geräte gefunden.", + "hub_target_required": "Mehrere APs sind konfiguriert. Ein Tag- oder AP-Ziel auswählen, damit OpenEPaperLink die Aktion korrekt zuordnen kann.", + "ap_entry_not_loaded": "Der OpenEPaperLink-AP-Konfigurationseintrag {entry_id} ist nicht geladen.", + "device_not_ap": "Gerät {device_id} ist kein OpenEPaperLink-Access-Point.", + "tag_no_online_ap": "Kein online erreichbarer Access Point meldet Tag {tag_mac} derzeit als aktiv. Mögliche APs: {candidate_hosts}.", + "tag_not_registered_any_ap": "Tag {tag_mac} ist auf keinem geladenen OpenEPaperLink-Access-Point registriert.", "ble_slots_unavailable": "Keine verfügbaren Bluetooth-Verbindungsslots für {mac_address}. Weitere ESPHome-Bluetooth-Proxys in der Nähe hinzufügen oder auf freie Verbindungen warten. Details: {error}.", "ble_device_not_found": "Gerät {mac_address} nicht gefunden.", "ble_characteristic_not_resolved": "Charakteristik für Service {service_uuid} konnte nicht aufgelöst werden.", diff --git a/custom_components/open_epaper_link/translations/en.json b/custom_components/open_epaper_link/translations/en.json index 2736c87d..a1a350ff 100644 --- a/custom_components/open_epaper_link/translations/en.json +++ b/custom_components/open_epaper_link/translations/en.json @@ -33,7 +33,6 @@ "invalid_device_config": "Device returned invalid configuration data. Please reconfigure the device or update its firmware." }, "abort": { - "single_instance_allowed": "Only one OpenEPaperLink hub can be configured. Multiple BLE devices are supported, but only one AP hub is allowed.", "unsupported_protocol": "Unsupported BLE firmware protocol. Only ATC firmware is supported.", "invalid_advertising_data": "Could not parse device advertising data. Please ensure the device is using compatible firmware.", "no_reconfigure_ble": "BLE devices do not support reconfiguration. Remove and re-add the device if you need to change its settings.", @@ -469,6 +468,11 @@ "no_hub_configured": { "message": "No AP hub configured. Only BLE devices found." }, + "hub_target_required": { "message": "More than one AP is configured. Select a tag or AP target so OpenEPaperLink can route the action." }, + "ap_entry_not_loaded": { "message": "OpenEPaperLink AP config entry {entry_id} is not loaded." }, + "device_not_ap": { "message": "Device {device_id} is not an OpenEPaperLink access point." }, + "tag_no_online_ap": { "message": "No online access point currently reports tag {tag_mac} as active. Candidate APs: {candidate_hosts}." }, + "tag_not_registered_any_ap": { "message": "Tag {tag_mac} is not registered on any loaded OpenEPaperLink access point." }, "ble_slots_unavailable": { "message": "No available Bluetooth connection slots for {mac_address}. Add more ESPHome Bluetooth proxies near this device or wait for existing connections to free up. Details: {error}." }, diff --git a/custom_components/open_epaper_link/translations/pl.json b/custom_components/open_epaper_link/translations/pl.json index 171f0ef6..c54051e0 100644 --- a/custom_components/open_epaper_link/translations/pl.json +++ b/custom_components/open_epaper_link/translations/pl.json @@ -33,7 +33,6 @@ "invalid_device_config": "Urządzenie zwróciło nieprawidłowe dane konfiguracyjne. Skonfiguruj urządzenie ponownie lub zaktualizuj jego firmware." }, "abort": { - "single_instance_allowed": "Tylko jeden hub OpenEPaperLink może być skonfigurowany. Obsługiwanych jest wiele urządzeń BLE, ale tylko jeden hub AP.", "unsupported_protocol": "Nieobsługiwany protokół firmware BLE. Obsługiwane są tylko ATC i OEPL.", "invalid_advertising_data": "Nie można przetworzyć danych reklamowych urządzenia. Upewnij się, że urządzenie używa kompatybilnego firmware.", "no_reconfigure_ble": "Urządzenia BLE nie obsługują rekonfiguracji. Usuń i dodaj urządzenie ponownie, jeśli potrzebna jest zmiana ustawień.", @@ -463,6 +462,11 @@ "no_hub_configured": { "message": "Brak skonfigurowanego huba AP. Znaleziono tylko urządzenia BLE." }, + "hub_target_required": { "message": "Skonfigurowano więcej niż jeden AP. Wybierz tag lub AP, aby akcja mogła zostać poprawnie przekierowana." }, + "ap_entry_not_loaded": { "message": "Wpis konfiguracji AP OpenEPaperLink {entry_id} nie jest załadowany." }, + "device_not_ap": { "message": "Urządzenie {device_id} nie jest punktem dostępowym OpenEPaperLink." }, + "tag_no_online_ap": { "message": "Żaden AP online nie zgłasza tagu {tag_mac} jako aktywnego. Kandydaci: {candidate_hosts}." }, + "tag_not_registered_any_ap": { "message": "Tag {tag_mac} nie jest zarejestrowany w żadnym załadowanym AP OpenEPaperLink." }, "ble_slots_unavailable": { "message": "Brak dostępnych slotów połączeń Bluetooth dla {mac_address}. Dodaj więcej proxy Bluetooth ESPHome w pobliżu lub poczekaj na zwolnienie połączeń. Szczegóły: {error}." }, diff --git a/custom_components/open_epaper_link/translations/pt.json b/custom_components/open_epaper_link/translations/pt.json index 3409adcc..816badf1 100644 --- a/custom_components/open_epaper_link/translations/pt.json +++ b/custom_components/open_epaper_link/translations/pt.json @@ -33,7 +33,6 @@ "invalid_device_config": "O dispositivo retornou dados de configuração inválidos. Por favor, reconfigure o dispositivo ou atualize o firmware." }, "abort": { - "single_instance_allowed": "Apenas um hub OpenEPaperLink pode ser configurado. Múltiplos dispositivos BLE são suportados, mas apenas um hub AP é permitido.", "unsupported_protocol": "Protocolo de firmware BLE não suportado. Apenas firmware ATC são suportados.", "invalid_advertising_data": "Não foi possível analisar os dados de advertising do dispositivo. Por favor, certifique-se de que o dispositivo está usando firmware compatível.", "no_reconfigure_ble": "Dispositivos BLE não suportam reconfiguração. Remova e adicione o dispositivo novamente se precisar alterar suas definições.", @@ -335,6 +334,11 @@ "tagtypes_load_failed": "Não foi possível carregar definições de tipos de tag. Nenhum dado armazenado disponível. Verifique conectividade de rede ou acesso ao GitHub.", "tagtypes_refresh_failed": "Não foi possível atualizar definições de tipos de tag. Verifique conectividade de rede ou acesso ao GitHub.", "no_hub_configured": "Nenhum hub AP configurado. Apenas dispositivos BLE encontrados.", + "hub_target_required": "Mais de um AP está configurado. Selecione uma tag ou um AP para encaminhar a ação corretamente.", + "ap_entry_not_loaded": "A entrada de configuração do AP OpenEPaperLink {entry_id} não está carregada.", + "device_not_ap": "O dispositivo {device_id} não é um ponto de acesso OpenEPaperLink.", + "tag_no_online_ap": "Nenhum AP online informa a tag {tag_mac} como ativa. APs candidatos: {candidate_hosts}.", + "tag_not_registered_any_ap": "A tag {tag_mac} não está registrada em nenhum AP OpenEPaperLink carregado.", "ble_slots_unavailable": "Sem slots de conexão Bluetooth disponíveis para {mac_address}. Adicione mais proxies Bluetooth ESPHome próximos ou aguarde conexões liberarem. Detalhes: {error}.", "ble_device_not_found": "Dispositivo {mac_address} não encontrado.", "ble_characteristic_not_resolved": "Não foi possível resolver a característica para o serviço {service_uuid}.", diff --git a/custom_components/open_epaper_link/util.py b/custom_components/open_epaper_link/util.py index 0afc919d..a76dd62b 100644 --- a/custom_components/open_epaper_link/util.py +++ b/custom_components/open_epaper_link/util.py @@ -7,6 +7,7 @@ from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.dispatcher import async_dispatcher_send from .runtime_data import OpenEPaperLinkBLERuntimeData +from .hub_manager import get_hub_manager, normalize_tag_mac _LOGGER = logging.getLogger(__name__) @@ -67,7 +68,7 @@ def get_image_path(hass: HomeAssistant, entity_id: str) -> str: return hass.config.path("www/open_epaper_link/open_epaper_link." + str(entity_id).lower() + ".jpg") -def get_hub_from_hass(hass: HomeAssistant): +def get_hub_from_hass(hass: HomeAssistant, tag_mac: str | None = None): """ Get the AP Hub instance from config entries. @@ -83,10 +84,19 @@ def get_hub_from_hass(hass: HomeAssistant): Raises: HomeAssistantError: If no AP hub is configured """ - for entry in hass.config_entries.async_entries(DOMAIN): - if hasattr(entry, 'runtime_data') and entry.runtime_data is not None: - if not isinstance(entry.runtime_data, OpenEPaperLinkBLERuntimeData): - return entry.runtime_data + manager = get_hub_manager(hass) + if tag_mac is not None: + return manager.resolve_tag_hub(normalize_tag_mac(tag_mac)) + + hubs = manager.hubs + if len(hubs) == 1: + return hubs[0] + + if len(hubs) > 1: + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="hub_target_required", + ) raise HomeAssistantError( translation_domain=DOMAIN, @@ -94,6 +104,18 @@ def get_hub_from_hass(hass: HomeAssistant): ) +def get_hub_for_tag(hass: HomeAssistant, entity_id_or_mac: str, *, require_online: bool = True): + """Resolve the active AP for a tag entity ID or MAC address.""" + tag_mac = ( + get_mac_from_entity_id(entity_id_or_mac) + if "." in entity_id_or_mac + else normalize_tag_mac(entity_id_or_mac) + ) + return get_hub_manager(hass).resolve_tag_hub( + tag_mac, require_online=require_online + ) + + def is_ble_entry(entry_data) -> bool: """ Check if entry data represents a BLE device. diff --git a/tests/test_multi_ap.py b/tests/test_multi_ap.py new file mode 100644 index 00000000..a19879ea --- /dev/null +++ b/tests/test_multi_ap.py @@ -0,0 +1,172 @@ +"""Tests for OpenEPaperLink multi-AP routing.""" + +from __future__ import annotations + +from dataclasses import dataclass +from types import SimpleNamespace + +import pytest + +from homeassistant.exceptions import HomeAssistantError + +from custom_components.open_epaper_link import coordinator +from custom_components.open_epaper_link.hub_manager import ( + MultiHubManager, + ap_identifier, +) +from custom_components.open_epaper_link.util import get_hub_for_tag + +TAG = "0000021A7D163B1D" + + +@dataclass +class FakeEntry: + entry_id: str + + +class FakeHub: + """Small Hub stand-in exposing only the router contract.""" + + def __init__( + self, + entry_id: str, + host: str, + *, + last_seen: int, + online: bool = True, + tag_online: bool = True, + tags: list[str] | None = None, + blacklisted: list[str] | None = None, + ) -> None: + self.entry = FakeEntry(entry_id) + self.host = host + self.online = online + self.tags = tags if tags is not None else [TAG] + self._blacklisted = blacklisted or [] + self._tag_online = tag_online + self._data = {TAG: {"last_seen": last_seen, "host": host}} + + def get_tag_data(self, tag_mac: str) -> dict: + return self._data.get(tag_mac, {}) + + def get_blacklisted_tags(self) -> list[str]: + return self._blacklisted + + def is_tag_online(self, tag_mac: str) -> bool: + return tag_mac in self.tags and self._tag_online + + +class FakeHass: + def __init__(self) -> None: + self.data = {} + + +def test_freshest_active_ap_is_selected() -> None: + manager = MultiHubManager(FakeHass()) + office = FakeHub("office", "192.168.0.143", last_seen=100) + cellar = FakeHub("cellar", "192.168.0.166", last_seen=200) + manager.register_hub(office) + manager.register_hub(cellar) + + assert manager.resolve_tag_hub(TAG) is cellar + assert manager.get_tag_data(TAG)["host"] == "192.168.0.166" + + +def test_inactive_duplicate_does_not_steal_route() -> None: + manager = MultiHubManager(FakeHass()) + office = FakeHub( + "office", + "192.168.0.143", + last_seen=300, + tag_online=False, + ) + cellar = FakeHub("cellar", "192.168.0.166", last_seen=200) + manager.register_hub(office) + manager.register_hub(cellar) + + assert manager.resolve_tag_hub(TAG) is cellar + + +def test_offline_ap_falls_back_to_active_ap() -> None: + manager = MultiHubManager(FakeHass()) + office = FakeHub( + "office", + "192.168.0.143", + last_seen=500, + online=False, + ) + cellar = FakeHub("cellar", "192.168.0.166", last_seen=100) + manager.register_hub(office) + manager.register_hub(cellar) + + assert manager.resolve_tag_hub(TAG) is cellar + + +def test_no_online_ap_fails_closed() -> None: + manager = MultiHubManager(FakeHass()) + manager.register_hub( + FakeHub("office", "192.168.0.143", last_seen=100, online=False) + ) + + with pytest.raises(HomeAssistantError): + manager.resolve_tag_hub(TAG) + + +def test_blacklisted_copy_does_not_hide_other_ap() -> None: + manager = MultiHubManager(FakeHass()) + manager.register_hub( + FakeHub( + "office", + "192.168.0.143", + last_seen=300, + blacklisted=[TAG], + ) + ) + cellar = FakeHub("cellar", "192.168.0.166", last_seen=200) + manager.register_hub(cellar) + + assert manager.resolve_tag_hub(TAG) is cellar + assert manager.tag_exists_elsewhere(TAG, exclude_entry_id="office") + + +def test_service_lookup_uses_manager_route() -> None: + hass = FakeHass() + manager = MultiHubManager(hass) + hass.data["open_epaper_link"] = {"hub_manager": manager} + office = FakeHub("office", "192.168.0.143", last_seen=100, tag_online=False) + cellar = FakeHub("cellar", "192.168.0.166", last_seen=200) + manager.register_hub(office) + manager.register_hub(cellar) + + assert get_hub_for_tag(hass, f"open_epaper_link.{TAG}") is cellar + + +def test_ap_identifiers_are_config_entry_specific() -> None: + assert ap_identifier("entry-a") == "ap_entry-a" + assert ap_identifier("entry-a") != ap_identifier("entry-b") + + +def test_hub_storage_is_config_entry_specific(monkeypatch: pytest.MonkeyPatch) -> None: + stores: list[str] = [] + + class FakeStore: + def __class_getitem__(cls, _item): + return cls + + def __init__(self, _hass, _version, key, **_kwargs): + stores.append(key) + + fake_hass = SimpleNamespace(bus=SimpleNamespace()) + entry = SimpleNamespace( + entry_id="entry-a", + data={"host": "192.168.0.166"}, + options={}, + ) + monkeypatch.setattr(coordinator, "Store", FakeStore) + monkeypatch.setattr(coordinator, "async_get_clientsession", lambda _hass: object()) + + hub = coordinator.Hub(fake_hass, entry) + + assert hub.storage_key == "open_epaper_link_tags_entry-a" + assert "open_epaper_link_tags_entry-a" in stores + assert "open_epaper_link_tags" in stores From ac3419b15d56d3c8d81e8205c70079e0cf113929 Mon Sep 17 00:00:00 2001 From: Wolfgang Wendefeuer Date: Tue, 14 Jul 2026 12:24:03 +0200 Subject: [PATCH 2/4] Handle AP reboot disconnect response --- .../open_epaper_link/coordinator.py | 33 +++++++++++++++++-- tests/test_multi_ap.py | 14 ++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/custom_components/open_epaper_link/coordinator.py b/custom_components/open_epaper_link/coordinator.py index bf5640b6..26d639c2 100644 --- a/custom_components/open_epaper_link/coordinator.py +++ b/custom_components/open_epaper_link/coordinator.py @@ -765,12 +765,36 @@ async def _run_ap_command(self, func: Callable[[], Any | Awaitable[Any]]) -> Any return await func() return await self.hass.async_add_executor_job(func) - async def _ap_request(self, method: str, path: str, *, data=None, timeout=10, action: str) -> requests.Response: + async def _ap_request( + self, + method: str, + path: str, + *, + data=None, + timeout=10, + action: str, + accept_read_timeout: bool = False, + ) -> requests.Response | None: url = f"http://{self.host}/{path.lstrip('/')}" def call(): return requests.request(method, url, data=data, timeout=timeout) try: resp = await self._run_ap_command(call) + except requests.exceptions.ReadTimeout: + if accept_read_timeout: + # Current AP firmware restarts before it can finish the HTTP + # response. A read timeout therefore confirms that the POST + # reached the previously online AP and is expected here. + _LOGGER.info( + "AP disconnected while handling %s; treating request as accepted", + action, + ) + return None + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="ap_timeout_action", + translation_placeholders={"action": action}, + ) from None except requests.exceptions.Timeout: raise HomeAssistantError( translation_domain=DOMAIN, @@ -803,7 +827,12 @@ async def send_tag_cmd(self, entity_id: str, cmd: str) -> bool: return True async def reboot_ap(self) -> bool: - await self._ap_request("post", "reboot", action="reboot OEPL AP") + await self._ap_request( + "post", + "reboot", + action="reboot OEPL AP", + accept_read_timeout=True, + ) _LOGGER.info("Rebooted OEPL AP") return True diff --git a/tests/test_multi_ap.py b/tests/test_multi_ap.py index a19879ea..f527cc82 100644 --- a/tests/test_multi_ap.py +++ b/tests/test_multi_ap.py @@ -4,8 +4,10 @@ from dataclasses import dataclass from types import SimpleNamespace +from unittest.mock import AsyncMock import pytest +import requests from homeassistant.exceptions import HomeAssistantError @@ -170,3 +172,15 @@ def __init__(self, _hass, _version, key, **_kwargs): assert hub.storage_key == "open_epaper_link_tags_entry-a" assert "open_epaper_link_tags_entry-a" in stores assert "open_epaper_link_tags" in stores + + +@pytest.mark.asyncio +async def test_ap_reboot_accepts_firmware_read_timeout() -> None: + """The AP restarts before its reboot HTTP response can be completed.""" + hub = object.__new__(coordinator.Hub) + hub.host = "192.168.0.143" + hub._run_ap_command = AsyncMock( + side_effect=requests.exceptions.ReadTimeout("AP is restarting") + ) + + assert await hub.reboot_ap() From 2e09ec1f1107e68fba8b396c2b97a30d35f62b01 Mon Sep 17 00:00:00 2001 From: Wolfgang Wendefeuer Date: Tue, 14 Jul 2026 13:49:58 +0200 Subject: [PATCH 3/4] Document Multi-AP beta release --- .../ISSUE_TEMPLATE/multi_ap_beta_report.md | 35 ++++++++++ CHANGELOG.md | 33 +++++++++ README.md | 54 ++++++++++++++ tests/test_multi_ap.py | 70 +++++++++---------- 4 files changed, 157 insertions(+), 35 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/multi_ap_beta_report.md diff --git a/.github/ISSUE_TEMPLATE/multi_ap_beta_report.md b/.github/ISSUE_TEMPLATE/multi_ap_beta_report.md new file mode 100644 index 00000000..27c05d77 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/multi_ap_beta_report.md @@ -0,0 +1,35 @@ +--- +name: Multi-AP beta report +about: Report a problem or test result for the Multi-AP pre-release +title: "[Multi-AP beta] " +labels: "bug" +assignees: "" +--- + +## Before submitting + +- Confirm that you are testing `3.0.1-multi-ap.1` or a later Multi-AP pre-release. +- Search existing issues for the same behavior. +- Remove passwords, tokens, private IP addresses, tag identifiers, location names, and other personal data from logs and screenshots. + +## Environment + +- Multi-AP beta version: +- Home Assistant version: +- Installation method (manual/HACS): +- Number of OpenEPaperLink APs: +- AP hardware and firmware versions: +- Number of tags visible through more than one AP: +- BLE tags in the same HA instance (yes/no): + +## Result + +- Expected behavior: +- Actual behavior: +- Steps to reproduce: +- Does the problem remain after restarting Home Assistant? +- Does routing recover when the affected AP comes back online? + +## Sanitized diagnostics and logs + +Attach only the smallest relevant excerpt. Enable debug logging if needed, reproduce the problem once, and sanitize all private data before posting. diff --git a/CHANGELOG.md b/CHANGELOG.md index 12c18023..5cfec33c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,38 @@ # Changelog +## [3.0.1-multi-ap.1](https://github.com/wendefeuer/Home_Assistant_Integration/compare/3.0.0...3.0.1-multi-ap.1) (2026-07-14) + +> **Pre-release:** Test version for broader Multi-AP validation. Back up Home Assistant and the existing integration folder before installation. + +### Features + +* allow multiple AP config entries while continuing to reject duplicate hosts +* keep one logical Home Assistant device per physical tag across multiple APs +* route tag state and actions to an online AP, preferring the freshest `last_seen` +* create unique AP device identifiers and separate per-entry tag stores +* add debug logging for routing candidates, the selected AP, and the selection reason + +### Bug Fixes + +* retain a shared tag when it is deleted or blacklisted on only one AP +* route `reboot_ap` to the explicitly selected AP device +* treat an accepted AP reboot followed by the expected connection loss as successful + +### Validation + +* nine focused Multi-AP tests passed +* Python compilation and JSON/translation validation passed +* live validation passed on Home Assistant Core 2026.7.2 with two APs and shared tags +* AP fallback/recovery, separate AP reboot, and unchanged BLE operation were verified +* 27 existing image snapshot differences were reproduced unchanged on the upstream code in the same Windows/Pillow environment and are not caused by this beta + +### Known limitations + +* pre-release from a public fork; not yet merged into the upstream stable release +* Multi-AP routing covers AP-based tags; BLE paths are intentionally unchanged +* the selected AP can change when connectivity or tag `last_seen` data changes +* broader field testing with other AP counts, firmware combinations, and Home Assistant versions is still required + ## [3.0.0](https://github.com/OpenEPaperLink/Home_Assistant_Integration/compare/2.8.0...3.0.0) (2026-03-27) diff --git a/README.md b/README.md index ab78eeda..9306f2e4 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,60 @@ Home Assistant Integration for the [OpenEPaperLink](https://github.com/jjwbruijn/OpenEPaperLink) project, enabling control and monitoring of electronic shelf labels (ESLs) through Home Assistant. +## Multi-AP beta / Multi-AP-Beta + +> [!WARNING] +> **Test version — create a Home Assistant backup and a separate copy of your existing `custom_components/open_epaper_link` folder before installation.** This pre-release is intended for testing and has not yet been merged into the upstream stable version. +> +> **Testversion – vor der Installation ein Home-Assistant-Backup und zusätzlich eine Kopie des vorhandenen Ordners `custom_components/open_epaper_link` erstellen.** Diese Vorabversion ist zum Testen bestimmt und noch nicht in die stabile Upstream-Version übernommen. + +Beta version: [`3.0.1-multi-ap.1`](https://github.com/wendefeuer/Home_Assistant_Integration/releases/tag/3.0.1-multi-ap.1) + +Feedback and bug reports: [GitHub Issues in the beta repository](https://github.com/wendefeuer/Home_Assistant_Integration/issues/new/choose) + +### English beta installation + +This beta allows multiple OpenEPaperLink AP config entries in one Home Assistant instance. A physical tag remains one logical Home Assistant device, and tag actions are routed to an online AP with the freshest `last_seen` value. + +1. Create a full Home Assistant backup. +2. Back up the existing `/config/custom_components/open_epaper_link` folder separately. +3. Install the beta using one of these methods: + - **Manual (recommended for the beta):** Download the source archive from the [`3.0.1-multi-ap.1` pre-release](https://github.com/wendefeuer/Home_Assistant_Integration/releases/tag/3.0.1-multi-ap.1), extract it, and copy its `custom_components/open_epaper_link` folder to `/config/custom_components/open_epaper_link`, replacing the integration files. + - **HACS custom repository:** In HACS, open the three-dot menu, select **Custom repositories**, add `https://github.com/wendefeuer/Home_Assistant_Integration` as type **Integration**, then use **Download** or **Redownload**. Under **Need a different version?**, select `3.0.1-multi-ap.1` if HACS offers the pre-release. If it is not listed, use the manual method. +4. Restart Home Assistant. Do not edit files below `.storage`. +5. Open **Settings → Devices & services → OpenEPaperLink** and add each AP separately. Existing AP entries can remain in place. +6. Verify that every AP has its own device, shared tags appear only once, and a test action reaches the expected online AP. + +To roll back, restore the backed-up integration folder or reinstall the latest upstream stable release, restart Home Assistant, and verify the integration and its devices again. + +When reporting a problem, use the [beta issue tracker](https://github.com/wendefeuer/Home_Assistant_Integration/issues/new/choose) and include the beta version, Home Assistant version, AP count and firmware versions, reproduction steps, and sanitized logs. Remove tokens, passwords, private addresses, tag identifiers, and other personal data before posting. + +### Deutsche Beta-Installation + +Diese Beta erlaubt mehrere OpenEPaperLink-AP-Konfigurationseinträge in einer Home-Assistant-Instanz. Ein physisches Tag bleibt ein logisches Home-Assistant-Gerät; Tag-Aktionen werden an einen erreichbaren AP mit dem neuesten `last_seen`-Wert geleitet. + +1. Ein vollständiges Home-Assistant-Backup erstellen. +2. Den vorhandenen Ordner `/config/custom_components/open_epaper_link` zusätzlich separat sichern. +3. Die Beta mit einer der folgenden Methoden installieren: + - **Manuell (für die Beta empfohlen):** Das Quellarchiv der [Vorabversion `3.0.1-multi-ap.1`](https://github.com/wendefeuer/Home_Assistant_Integration/releases/tag/3.0.1-multi-ap.1) herunterladen, entpacken und den enthaltenen Ordner `custom_components/open_epaper_link` nach `/config/custom_components/open_epaper_link` kopieren. Dabei die vorhandenen Integrationsdateien ersetzen. + - **HACS Custom Repository:** In HACS das Drei-Punkte-Menü öffnen, **Benutzerdefinierte Repositories** auswählen, `https://github.com/wendefeuer/Home_Assistant_Integration` mit dem Typ **Integration** hinzufügen und anschließend **Herunterladen** oder **Erneut herunterladen** wählen. Unter **Andere Version benötigt?** `3.0.1-multi-ap.1` auswählen, falls HACS die Vorabversion anbietet. Andernfalls die manuelle Methode verwenden. +4. Home Assistant neu starten. Keine Dateien unter `.storage` bearbeiten. +5. Unter **Einstellungen → Geräte & Dienste → OpenEPaperLink** jeden AP einzeln hinzufügen. Vorhandene AP-Einträge können bestehen bleiben. +6. Prüfen, ob jeder AP ein eigenes Gerät besitzt, gemeinsam sichtbare Tags nur einmal erscheinen und eine Testaktion den erwarteten erreichbaren AP erreicht. + +Für ein Rollback den gesicherten Integrationsordner wiederherstellen oder die aktuelle stabile Upstream-Version erneut installieren, Home Assistant neu starten und anschließend Integration und Geräte erneut prüfen. + +Probleme bitte zentral im [Issue-Tracker der Beta](https://github.com/wendefeuer/Home_Assistant_Integration/issues/new/choose) melden. Dabei Beta-Version, Home-Assistant-Version, Anzahl und Firmwarestände der APs, Reproduktionsschritte und bereinigte Logs angeben. Tokens, Passwörter, private Adressen, Tag-Kennungen und andere personenbezogene Daten vor dem Veröffentlichen entfernen. + +### Known limitations / Bekannte Einschränkungen + +- This is a pre-release from a public fork and is not yet part of the upstream stable release. / Dies ist eine Vorabversion aus einem öffentlichen Fork und noch nicht Teil der stabilen Upstream-Version. +- Multi-AP routing applies to AP-based tags. Existing BLE behavior is intentionally unchanged. / Das Multi-AP-Routing gilt für AP-basierte Tags. Das bestehende BLE-Verhalten bleibt absichtlich unverändert. +- Routing depends on AP connectivity and the most recent tag `last_seen` data. The selected AP can therefore change after a newer check-in or an AP outage. / Das Routing hängt von der AP-Erreichbarkeit und den neuesten `last_seen`-Daten des Tags ab. Der gewählte AP kann sich daher nach einem neueren Check-in oder AP-Ausfall ändern. +- A tag shared by multiple APs is intentionally shown as one HA device and has no permanent parent-AP assignment. / Ein von mehreren APs erfasstes Tag wird absichtlich als ein HA-Gerät angezeigt und besitzt keine dauerhafte Zuordnung zu einem übergeordneten AP. +- An AP reboot can close the HTTP connection before returning a response; an accepted reboot request followed by that disconnect is treated as successful. / Ein AP-Neustart kann die HTTP-Verbindung schließen, bevor eine Antwort zurückkommt; eine zuvor angenommene Neustartanforderung wird in diesem Fall als erfolgreich behandelt. +- The beta was validated with two APs on Home Assistant Core 2026.7.2. Other AP counts, firmware combinations, and HA versions need broader field testing. / Die Beta wurde mit zwei APs unter Home Assistant Core 2026.7.2 geprüft. Andere AP-Anzahlen, Firmwarekombinationen und HA-Versionen benötigen weitere Feldtests. + ## Requirements ### Hardware diff --git a/tests/test_multi_ap.py b/tests/test_multi_ap.py index f527cc82..a476a37e 100644 --- a/tests/test_multi_ap.py +++ b/tests/test_multi_ap.py @@ -18,7 +18,7 @@ ) from custom_components.open_epaper_link.util import get_hub_for_tag -TAG = "0000021A7D163B1D" +TAG = "0011223344556677" @dataclass @@ -65,49 +65,49 @@ def __init__(self) -> None: def test_freshest_active_ap_is_selected() -> None: manager = MultiHubManager(FakeHass()) - office = FakeHub("office", "192.168.0.143", last_seen=100) - cellar = FakeHub("cellar", "192.168.0.166", last_seen=200) - manager.register_hub(office) - manager.register_hub(cellar) + hub_a = FakeHub("hub-a", "192.0.2.143", last_seen=100) + hub_b = FakeHub("hub-b", "192.0.2.166", last_seen=200) + manager.register_hub(hub_a) + manager.register_hub(hub_b) - assert manager.resolve_tag_hub(TAG) is cellar - assert manager.get_tag_data(TAG)["host"] == "192.168.0.166" + assert manager.resolve_tag_hub(TAG) is hub_b + assert manager.get_tag_data(TAG)["host"] == "192.0.2.166" def test_inactive_duplicate_does_not_steal_route() -> None: manager = MultiHubManager(FakeHass()) - office = FakeHub( - "office", - "192.168.0.143", + hub_a = FakeHub( + "hub-a", + "192.0.2.143", last_seen=300, tag_online=False, ) - cellar = FakeHub("cellar", "192.168.0.166", last_seen=200) - manager.register_hub(office) - manager.register_hub(cellar) + hub_b = FakeHub("hub-b", "192.0.2.166", last_seen=200) + manager.register_hub(hub_a) + manager.register_hub(hub_b) - assert manager.resolve_tag_hub(TAG) is cellar + assert manager.resolve_tag_hub(TAG) is hub_b def test_offline_ap_falls_back_to_active_ap() -> None: manager = MultiHubManager(FakeHass()) - office = FakeHub( - "office", - "192.168.0.143", + hub_a = FakeHub( + "hub-a", + "192.0.2.143", last_seen=500, online=False, ) - cellar = FakeHub("cellar", "192.168.0.166", last_seen=100) - manager.register_hub(office) - manager.register_hub(cellar) + hub_b = FakeHub("hub-b", "192.0.2.166", last_seen=100) + manager.register_hub(hub_a) + manager.register_hub(hub_b) - assert manager.resolve_tag_hub(TAG) is cellar + assert manager.resolve_tag_hub(TAG) is hub_b def test_no_online_ap_fails_closed() -> None: manager = MultiHubManager(FakeHass()) manager.register_hub( - FakeHub("office", "192.168.0.143", last_seen=100, online=False) + FakeHub("hub-a", "192.0.2.143", last_seen=100, online=False) ) with pytest.raises(HomeAssistantError): @@ -118,29 +118,29 @@ def test_blacklisted_copy_does_not_hide_other_ap() -> None: manager = MultiHubManager(FakeHass()) manager.register_hub( FakeHub( - "office", - "192.168.0.143", + "hub-a", + "192.0.2.143", last_seen=300, blacklisted=[TAG], ) ) - cellar = FakeHub("cellar", "192.168.0.166", last_seen=200) - manager.register_hub(cellar) + hub_b = FakeHub("hub-b", "192.0.2.166", last_seen=200) + manager.register_hub(hub_b) - assert manager.resolve_tag_hub(TAG) is cellar - assert manager.tag_exists_elsewhere(TAG, exclude_entry_id="office") + assert manager.resolve_tag_hub(TAG) is hub_b + assert manager.tag_exists_elsewhere(TAG, exclude_entry_id="hub-a") def test_service_lookup_uses_manager_route() -> None: hass = FakeHass() manager = MultiHubManager(hass) hass.data["open_epaper_link"] = {"hub_manager": manager} - office = FakeHub("office", "192.168.0.143", last_seen=100, tag_online=False) - cellar = FakeHub("cellar", "192.168.0.166", last_seen=200) - manager.register_hub(office) - manager.register_hub(cellar) + hub_a = FakeHub("hub-a", "192.0.2.143", last_seen=100, tag_online=False) + hub_b = FakeHub("hub-b", "192.0.2.166", last_seen=200) + manager.register_hub(hub_a) + manager.register_hub(hub_b) - assert get_hub_for_tag(hass, f"open_epaper_link.{TAG}") is cellar + assert get_hub_for_tag(hass, f"open_epaper_link.{TAG}") is hub_b def test_ap_identifiers_are_config_entry_specific() -> None: @@ -161,7 +161,7 @@ def __init__(self, _hass, _version, key, **_kwargs): fake_hass = SimpleNamespace(bus=SimpleNamespace()) entry = SimpleNamespace( entry_id="entry-a", - data={"host": "192.168.0.166"}, + data={"host": "192.0.2.166"}, options={}, ) monkeypatch.setattr(coordinator, "Store", FakeStore) @@ -178,7 +178,7 @@ def __init__(self, _hass, _version, key, **_kwargs): async def test_ap_reboot_accepts_firmware_read_timeout() -> None: """The AP restarts before its reboot HTTP response can be completed.""" hub = object.__new__(coordinator.Hub) - hub.host = "192.168.0.143" + hub.host = "192.0.2.143" hub._run_ap_command = AsyncMock( side_effect=requests.exceptions.ReadTimeout("AP is restarting") ) From d6eb5504e4addaf1cbd46f438b00543251a519ae Mon Sep 17 00:00:00 2001 From: Wolfgang Wendefeuer Date: Tue, 14 Jul 2026 14:17:04 +0200 Subject: [PATCH 4/4] Promote Multi-AP release to 3.0.1 --- ...i_ap_beta_report.md => multi_ap_report.md} | 10 ++--- CHANGELOG.md | 15 +++++++ README.md | 40 +++++++++---------- .../open_epaper_link/manifest.json | 2 +- 4 files changed, 41 insertions(+), 26 deletions(-) rename .github/ISSUE_TEMPLATE/{multi_ap_beta_report.md => multi_ap_report.md} (79%) diff --git a/.github/ISSUE_TEMPLATE/multi_ap_beta_report.md b/.github/ISSUE_TEMPLATE/multi_ap_report.md similarity index 79% rename from .github/ISSUE_TEMPLATE/multi_ap_beta_report.md rename to .github/ISSUE_TEMPLATE/multi_ap_report.md index 27c05d77..f99395d0 100644 --- a/.github/ISSUE_TEMPLATE/multi_ap_beta_report.md +++ b/.github/ISSUE_TEMPLATE/multi_ap_report.md @@ -1,20 +1,20 @@ --- -name: Multi-AP beta report -about: Report a problem or test result for the Multi-AP pre-release -title: "[Multi-AP beta] " +name: Multi-AP report +about: Report a problem or test result for the Multi-AP release +title: "[Multi-AP] " labels: "bug" assignees: "" --- ## Before submitting -- Confirm that you are testing `3.0.1-multi-ap.1` or a later Multi-AP pre-release. +- Confirm that you are using the current Multi-AP release. - Search existing issues for the same behavior. - Remove passwords, tokens, private IP addresses, tag identifiers, location names, and other personal data from logs and screenshots. ## Environment -- Multi-AP beta version: +- Multi-AP release version: - Home Assistant version: - Installation method (manual/HACS): - Number of OpenEPaperLink APs: diff --git a/CHANGELOG.md b/CHANGELOG.md index 5cfec33c..8250c232 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## [3.0.1](https://github.com/wendefeuer/Home_Assistant_Integration/compare/3.0.1-multi-ap.1...3.0.1) (2026-07-14) + +### Release + +* promote the validated Multi-AP beta to the stable `3.0.1` fork release +* no functional code changes compared with `3.0.1-multi-ap.1` +* retain the backup, rollback, known-limitations, and sanitized issue-reporting guidance + +### Validation + +* nine focused Multi-AP tests passed +* Python 3.12 compilation and JSON/translation validation passed +* live validation passed on Home Assistant Core 2026.7.2 with two APs and shared tags +* AP fallback/recovery, separate AP reboot, and unchanged BLE operation were verified + ## [3.0.1-multi-ap.1](https://github.com/wendefeuer/Home_Assistant_Integration/compare/3.0.0...3.0.1-multi-ap.1) (2026-07-14) > **Pre-release:** Test version for broader Multi-AP validation. Back up Home Assistant and the existing integration folder before installation. diff --git a/README.md b/README.md index 9306f2e4..604f3450 100644 --- a/README.md +++ b/README.md @@ -11,59 +11,59 @@ Home Assistant Integration for the [OpenEPaperLink](https://github.com/jjwbruijn/OpenEPaperLink) project, enabling control and monitoring of electronic shelf labels (ESLs) through Home Assistant. -## Multi-AP beta / Multi-AP-Beta +## Multi-AP release / Multi-AP-Version -> [!WARNING] -> **Test version — create a Home Assistant backup and a separate copy of your existing `custom_components/open_epaper_link` folder before installation.** This pre-release is intended for testing and has not yet been merged into the upstream stable version. +> [!IMPORTANT] +> **Create a Home Assistant backup and a separate copy of your existing `custom_components/open_epaper_link` folder before installation.** Version `3.0.1` is the stable Multi-AP release of this public fork and has not yet been merged into the upstream project. > -> **Testversion – vor der Installation ein Home-Assistant-Backup und zusätzlich eine Kopie des vorhandenen Ordners `custom_components/open_epaper_link` erstellen.** Diese Vorabversion ist zum Testen bestimmt und noch nicht in die stabile Upstream-Version übernommen. +> **Vor der Installation ein Home-Assistant-Backup und zusätzlich eine Kopie des vorhandenen Ordners `custom_components/open_epaper_link` erstellen.** Version `3.0.1` ist die stabile Multi-AP-Version dieses öffentlichen Forks und noch nicht in das Upstream-Projekt übernommen. -Beta version: [`3.0.1-multi-ap.1`](https://github.com/wendefeuer/Home_Assistant_Integration/releases/tag/3.0.1-multi-ap.1) +Release version: [`3.0.1`](https://github.com/wendefeuer/Home_Assistant_Integration/releases/tag/3.0.1) -Feedback and bug reports: [GitHub Issues in the beta repository](https://github.com/wendefeuer/Home_Assistant_Integration/issues/new/choose) +Feedback and bug reports: [GitHub Issues in the fork](https://github.com/wendefeuer/Home_Assistant_Integration/issues/new/choose) -### English beta installation +### English Multi-AP installation -This beta allows multiple OpenEPaperLink AP config entries in one Home Assistant instance. A physical tag remains one logical Home Assistant device, and tag actions are routed to an online AP with the freshest `last_seen` value. +This release allows multiple OpenEPaperLink AP config entries in one Home Assistant instance. A physical tag remains one logical Home Assistant device, and tag actions are routed to an online AP with the freshest `last_seen` value. 1. Create a full Home Assistant backup. 2. Back up the existing `/config/custom_components/open_epaper_link` folder separately. -3. Install the beta using one of these methods: - - **Manual (recommended for the beta):** Download the source archive from the [`3.0.1-multi-ap.1` pre-release](https://github.com/wendefeuer/Home_Assistant_Integration/releases/tag/3.0.1-multi-ap.1), extract it, and copy its `custom_components/open_epaper_link` folder to `/config/custom_components/open_epaper_link`, replacing the integration files. - - **HACS custom repository:** In HACS, open the three-dot menu, select **Custom repositories**, add `https://github.com/wendefeuer/Home_Assistant_Integration` as type **Integration**, then use **Download** or **Redownload**. Under **Need a different version?**, select `3.0.1-multi-ap.1` if HACS offers the pre-release. If it is not listed, use the manual method. +3. Install the release using one of these methods: + - **HACS custom repository (recommended):** In HACS, open the three-dot menu, select **Custom repositories**, add `https://github.com/wendefeuer/Home_Assistant_Integration` as type **Integration**, then use **Download** or **Redownload**. Under **Need a different version?**, select `3.0.1` if necessary. + - **Manual:** Download the source archive from the [`3.0.1` release](https://github.com/wendefeuer/Home_Assistant_Integration/releases/tag/3.0.1), extract it, and copy its `custom_components/open_epaper_link` folder to `/config/custom_components/open_epaper_link`, replacing the integration files. 4. Restart Home Assistant. Do not edit files below `.storage`. 5. Open **Settings → Devices & services → OpenEPaperLink** and add each AP separately. Existing AP entries can remain in place. 6. Verify that every AP has its own device, shared tags appear only once, and a test action reaches the expected online AP. To roll back, restore the backed-up integration folder or reinstall the latest upstream stable release, restart Home Assistant, and verify the integration and its devices again. -When reporting a problem, use the [beta issue tracker](https://github.com/wendefeuer/Home_Assistant_Integration/issues/new/choose) and include the beta version, Home Assistant version, AP count and firmware versions, reproduction steps, and sanitized logs. Remove tokens, passwords, private addresses, tag identifiers, and other personal data before posting. +When reporting a problem, use the [fork issue tracker](https://github.com/wendefeuer/Home_Assistant_Integration/issues/new/choose) and include the release version, Home Assistant version, AP count and firmware versions, reproduction steps, and sanitized logs. Remove tokens, passwords, private addresses, tag identifiers, and other personal data before posting. -### Deutsche Beta-Installation +### Deutsche Multi-AP-Installation -Diese Beta erlaubt mehrere OpenEPaperLink-AP-Konfigurationseinträge in einer Home-Assistant-Instanz. Ein physisches Tag bleibt ein logisches Home-Assistant-Gerät; Tag-Aktionen werden an einen erreichbaren AP mit dem neuesten `last_seen`-Wert geleitet. +Diese Version erlaubt mehrere OpenEPaperLink-AP-Konfigurationseinträge in einer Home-Assistant-Instanz. Ein physisches Tag bleibt ein logisches Home-Assistant-Gerät; Tag-Aktionen werden an einen erreichbaren AP mit dem neuesten `last_seen`-Wert geleitet. 1. Ein vollständiges Home-Assistant-Backup erstellen. 2. Den vorhandenen Ordner `/config/custom_components/open_epaper_link` zusätzlich separat sichern. -3. Die Beta mit einer der folgenden Methoden installieren: - - **Manuell (für die Beta empfohlen):** Das Quellarchiv der [Vorabversion `3.0.1-multi-ap.1`](https://github.com/wendefeuer/Home_Assistant_Integration/releases/tag/3.0.1-multi-ap.1) herunterladen, entpacken und den enthaltenen Ordner `custom_components/open_epaper_link` nach `/config/custom_components/open_epaper_link` kopieren. Dabei die vorhandenen Integrationsdateien ersetzen. - - **HACS Custom Repository:** In HACS das Drei-Punkte-Menü öffnen, **Benutzerdefinierte Repositories** auswählen, `https://github.com/wendefeuer/Home_Assistant_Integration` mit dem Typ **Integration** hinzufügen und anschließend **Herunterladen** oder **Erneut herunterladen** wählen. Unter **Andere Version benötigt?** `3.0.1-multi-ap.1` auswählen, falls HACS die Vorabversion anbietet. Andernfalls die manuelle Methode verwenden. +3. Die Version mit einer der folgenden Methoden installieren: + - **HACS Custom Repository (empfohlen):** In HACS das Drei-Punkte-Menü öffnen, **Benutzerdefinierte Repositories** auswählen, `https://github.com/wendefeuer/Home_Assistant_Integration` mit dem Typ **Integration** hinzufügen und anschließend **Herunterladen** oder **Erneut herunterladen** wählen. Unter **Andere Version benötigt?** bei Bedarf `3.0.1` auswählen. + - **Manuell:** Das Quellarchiv der [Version `3.0.1`](https://github.com/wendefeuer/Home_Assistant_Integration/releases/tag/3.0.1) herunterladen, entpacken und den enthaltenen Ordner `custom_components/open_epaper_link` nach `/config/custom_components/open_epaper_link` kopieren. Dabei die vorhandenen Integrationsdateien ersetzen. 4. Home Assistant neu starten. Keine Dateien unter `.storage` bearbeiten. 5. Unter **Einstellungen → Geräte & Dienste → OpenEPaperLink** jeden AP einzeln hinzufügen. Vorhandene AP-Einträge können bestehen bleiben. 6. Prüfen, ob jeder AP ein eigenes Gerät besitzt, gemeinsam sichtbare Tags nur einmal erscheinen und eine Testaktion den erwarteten erreichbaren AP erreicht. Für ein Rollback den gesicherten Integrationsordner wiederherstellen oder die aktuelle stabile Upstream-Version erneut installieren, Home Assistant neu starten und anschließend Integration und Geräte erneut prüfen. -Probleme bitte zentral im [Issue-Tracker der Beta](https://github.com/wendefeuer/Home_Assistant_Integration/issues/new/choose) melden. Dabei Beta-Version, Home-Assistant-Version, Anzahl und Firmwarestände der APs, Reproduktionsschritte und bereinigte Logs angeben. Tokens, Passwörter, private Adressen, Tag-Kennungen und andere personenbezogene Daten vor dem Veröffentlichen entfernen. +Probleme bitte zentral im [Issue-Tracker des Forks](https://github.com/wendefeuer/Home_Assistant_Integration/issues/new/choose) melden. Dabei Release-Version, Home-Assistant-Version, Anzahl und Firmwarestände der APs, Reproduktionsschritte und bereinigte Logs angeben. Tokens, Passwörter, private Adressen, Tag-Kennungen und andere personenbezogene Daten vor dem Veröffentlichen entfernen. ### Known limitations / Bekannte Einschränkungen -- This is a pre-release from a public fork and is not yet part of the upstream stable release. / Dies ist eine Vorabversion aus einem öffentlichen Fork und noch nicht Teil der stabilen Upstream-Version. +- This is a stable release of a public fork and is not yet part of the upstream project. / Dies ist eine stabile Version eines öffentlichen Forks und noch nicht Teil des Upstream-Projekts. - Multi-AP routing applies to AP-based tags. Existing BLE behavior is intentionally unchanged. / Das Multi-AP-Routing gilt für AP-basierte Tags. Das bestehende BLE-Verhalten bleibt absichtlich unverändert. - Routing depends on AP connectivity and the most recent tag `last_seen` data. The selected AP can therefore change after a newer check-in or an AP outage. / Das Routing hängt von der AP-Erreichbarkeit und den neuesten `last_seen`-Daten des Tags ab. Der gewählte AP kann sich daher nach einem neueren Check-in oder AP-Ausfall ändern. - A tag shared by multiple APs is intentionally shown as one HA device and has no permanent parent-AP assignment. / Ein von mehreren APs erfasstes Tag wird absichtlich als ein HA-Gerät angezeigt und besitzt keine dauerhafte Zuordnung zu einem übergeordneten AP. - An AP reboot can close the HTTP connection before returning a response; an accepted reboot request followed by that disconnect is treated as successful. / Ein AP-Neustart kann die HTTP-Verbindung schließen, bevor eine Antwort zurückkommt; eine zuvor angenommene Neustartanforderung wird in diesem Fall als erfolgreich behandelt. -- The beta was validated with two APs on Home Assistant Core 2026.7.2. Other AP counts, firmware combinations, and HA versions need broader field testing. / Die Beta wurde mit zwei APs unter Home Assistant Core 2026.7.2 geprüft. Andere AP-Anzahlen, Firmwarekombinationen und HA-Versionen benötigen weitere Feldtests. +- Version `3.0.1` was validated with two APs on Home Assistant Core 2026.7.2. Other AP counts, firmware combinations, and HA versions have not been validated to the same extent. / Version `3.0.1` wurde mit zwei APs unter Home Assistant Core 2026.7.2 geprüft. Andere AP-Anzahlen, Firmwarekombinationen und HA-Versionen wurden noch nicht im gleichen Umfang validiert. ## Requirements diff --git a/custom_components/open_epaper_link/manifest.json b/custom_components/open_epaper_link/manifest.json index 0ad3c50b..40e4b673 100644 --- a/custom_components/open_epaper_link/manifest.json +++ b/custom_components/open_epaper_link/manifest.json @@ -35,5 +35,5 @@ "numpy>=1.26.4", "Pillow>=10.4.0" ], - "version": "3.0.1-multi-ap.1" + "version": "3.0.1" }