Skip to content

Commit 7f0ee97

Browse files
authored
Add Register device and update entry lookup (#62)
1 parent f1cefac commit 7f0ee97

1 file changed

Lines changed: 26 additions & 16 deletions

File tree

custom_components/gicisky/__init__.py

Lines changed: 26 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@
2121
from homeassistant.const import Platform
2222
from homeassistant.core import HomeAssistant, ServiceCall, callback
2323
from homeassistant.helpers import device_registry as dr, entity_registry as er
24-
from homeassistant.helpers.device_registry import DeviceRegistry
24+
from datetime import datetime
25+
26+
from homeassistant.helpers.device_registry import CONNECTION_BLUETOOTH, DeviceRegistry
2527
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
2628
from homeassistant.util.signal_type import SignalType
2729
from homeassistant.util.dt import now
@@ -83,6 +85,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: GiciskyConfigEntry) -> b
8385
hass.data[DOMAIN][LOCK] = Lock()
8486

8587
device_registry = dr.async_get(hass)
88+
_identifier = address.replace(":", "")[-8:]
89+
device_entry = device_registry.async_get_or_create(
90+
config_entry_id=entry.entry_id,
91+
connections={(CONNECTION_BLUETOOTH, address)},
92+
manufacturer="Gicisky",
93+
name=f"Gicisky {_identifier}",
94+
)
95+
hass.data[DOMAIN][entry.entry_id]["device_id"] = device_entry.id
8696
bt_coordinator = GiciskyPassiveBluetoothProcessorCoordinator(
8797
hass,
8898
_LOGGER,
@@ -267,18 +277,18 @@ async def async_unload_entry(hass: HomeAssistant, entry: GiciskyConfigEntry) ->
267277
return unload_ok
268278

269279
async def get_entry_id_from_device(hass, device_id: str) -> str:
270-
device_reg = dr.async_get(hass)
271-
device_entry = device_reg.async_get(device_id)
272-
if not device_entry:
273-
raise ValueError(f"Unknown device_id: {device_id}")
274-
if not device_entry.config_entries:
275-
raise ValueError(f"No config entries for device {device_id}")
276-
277-
_LOGGER.debug(f"{device_id} to {device_entry.config_entries}")
278-
try:
279-
entry_id = next(iter(device_entry.config_entries))
280-
except StopIteration:
281-
_LOGGER.error("%s None", device_id)
282-
return None
283-
284-
return entry_id
280+
"""Resolve HA device_id to config entry_id by scanning hass.data[DOMAIN] only."""
281+
domain_data = hass.data.get(DOMAIN, {})
282+
for entry_id, rt in domain_data.items():
283+
if entry_id == LOCK:
284+
continue
285+
if not isinstance(rt, dict) or "address" not in rt:
286+
continue
287+
if rt.get("device_id") == device_id:
288+
_LOGGER.debug("device %s -> entry %s", device_id, entry_id)
289+
return entry_id
290+
291+
raise ValueError(
292+
f"No loaded Gicisky entry has device_id {device_id!r} in hass.data['{DOMAIN}']. "
293+
"Reload the integration after updating, or target the correct device."
294+
)

0 commit comments

Comments
 (0)