Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 42 additions & 49 deletions custom_components/vesync/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
VS_SWITCHES,
)

PLATFORMS = {
PLATFORMS: dict[Platform, str] = {
Platform.SWITCH: VS_SWITCHES,
Platform.FAN: VS_FANS,
Platform.LIGHT: VS_LIGHTS,
Expand All @@ -43,32 +43,26 @@


async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
"""Set up Vesync as config entry."""
"""Set up VeSync as config entry."""
username = config_entry.data[CONF_USERNAME]
password = config_entry.data[CONF_PASSWORD]

time_zone = str(hass.config.time_zone)

manager = VeSync(username, password, time_zone)

login = await hass.async_add_executor_job(manager.login)

if not login:
_LOGGER.error("Unable to login to the VeSync server")
return False

forward_setup = hass.config_entries.async_forward_entry_setup
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][config_entry.entry_id] = {VS_MANAGER: manager}

hass.data[DOMAIN] = {config_entry.entry_id: {}}
hass.data[DOMAIN][config_entry.entry_id][VS_MANAGER] = manager

# Create a DataUpdateCoordinator for the manager
# Coordinator
async def async_update_data():
"""Fetch data from API endpoint."""
try:
await hass.async_add_executor_job(manager.update)
except Exception as err:
raise UpdateFailed(f"Update failed: {err}")
raise UpdateFailed(f"Update failed: {err}") from err

coordinator = DataUpdateCoordinator(
hass,
Expand All @@ -77,56 +71,55 @@ async def async_update_data():
update_method=async_update_data,
update_interval=timedelta(seconds=30),
)

# Fetch initial data so we have data when entities subscribe
await coordinator.async_refresh()

# Store the coordinator instance in hass.data
hass.data[DOMAIN][config_entry.entry_id]["coordinator"] = coordinator

# Devices erfassen
device_dict = await async_process_devices(hass, manager)

for p, vs_p in PLATFORMS.items():
hass.data[DOMAIN][config_entry.entry_id][vs_p] = []
if device_dict[vs_p]:
hass.data[DOMAIN][config_entry.entry_id][vs_p].extend(device_dict[vs_p])
hass.async_create_task(forward_setup(config_entry, p))
platforms_to_setup: list[Platform] = []
for platform, bucket in PLATFORMS.items():
hass.data[DOMAIN][config_entry.entry_id][bucket] = []
if device_dict.get(bucket):
hass.data[DOMAIN][config_entry.entry_id][bucket].extend(device_dict[bucket])
platforms_to_setup.append(platform)

async def async_new_device_discovery(service: ServiceCall) -> None:
# Neue API: gesammelt und awaited
if platforms_to_setup:
await hass.config_entries.async_forward_entry_setups(config_entry, platforms_to_setup)

# Service: neue Geräte später hinzufügen
async def async_new_device_discovery(_: ServiceCall) -> None:
"""Discover if new devices should be added."""
manager = hass.data[DOMAIN][config_entry.entry_id][VS_MANAGER]
dev_dict = await async_process_devices(hass, manager)

def _add_new_devices(platform: str) -> None:
"""Add new devices to hass."""
old_devices = hass.data[DOMAIN][config_entry.entry_id][PLATFORMS[platform]]
if new_devices := list(
set(dev_dict.get(VS_SWITCHES, [])).difference(old_devices)
):
manager_local = hass.data[DOMAIN][config_entry.entry_id][VS_MANAGER]
dev_dict = await async_process_devices(hass, manager_local)

async def _add_new_devices(platform: Platform) -> None:
bucket = PLATFORMS[platform]
old_devices = hass.data[DOMAIN][config_entry.entry_id][bucket]
new_devices = list(set(dev_dict.get(bucket, [])) - set(old_devices))
if not new_devices:
return

if old_devices:
# Plattform aktiv → Entities via Dispatcher hinzufügen
old_devices.extend(new_devices)
if old_devices:
async_dispatcher_send(
hass, VS_DISCOVERY.format(PLATFORMS[platform]), new_devices
)
else:
hass.async_create_task(forward_setup(config_entry, platform))

for k, v in PLATFORMS.items():
_add_new_devices(k)

hass.services.async_register(
DOMAIN, SERVICE_UPDATE_DEVS, async_new_device_discovery
)
async_dispatcher_send(hass, VS_DISCOVERY.format(bucket), new_devices)
else:
# Plattform noch nicht aktiv → vormerken & Plattform laden
old_devices.extend(new_devices)
await hass.config_entries.async_forward_entry_setups(config_entry, [platform])

for p in PLATFORMS.keys():
await _add_new_devices(p)

hass.services.async_register(DOMAIN, SERVICE_UPDATE_DEVS, async_new_device_discovery)
return True


async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(
entry, list(PLATFORMS.keys())
)
unload_ok = await hass.config_entries.async_unload_platforms(entry, list(PLATFORMS.keys()))
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)

hass.data[DOMAIN].pop(entry.entry_id, None)
return unload_ok