1
0

__init__.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. from __future__ import annotations
  2. from homeassistant.core import HomeAssistant, callback
  3. from homeassistant.const import Platform
  4. from homeassistant.config_entries import ConfigEntry
  5. from homeassistant.helpers.device import async_entity_id_to_device
  6. from homeassistant.helpers.device_registry import DATA_REGISTRY
  7. from homeassistant.helpers.entity_component import DATA_INSTANCES
  8. from .reservation import Reservation
  9. from .const import DOMAIN, PLATFORMS, RESERVATION_FIELDS
  10. type ZiBConfigEntry = ConfigEntry[Reservation]
  11. async def async_setup_entry(hass: HomeAssistant, entry: ZiBConfigEntry) -> bool:
  12. entry.runtime_data = Reservation(hass, entry.data["Name"])
  13. await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
  14. return True
  15. async def async_unload_entry(hass: HomeAssistant, entry: ZiBConfigEntry) -> bool:
  16. unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
  17. return unload_ok
  18. async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
  19. @callback
  20. async def get_reservations(devices, entities) -> list:
  21. reservations = []
  22. if devices:
  23. for device in devices:
  24. dev = hass.data[DATA_REGISTRY].async_get(device)
  25. if not dev:
  26. continue
  27. conf = hass.config_entries.async_get_entry(dev.primary_config_entry)
  28. if not conf:
  29. continue
  30. reservations.append(conf.runtime_data)
  31. if entities:
  32. for entity in hass.data[DATA_INSTANCES][Platform.SENSOR].entities:
  33. if entity.entity_id in entities:
  34. reservations.append(entity.platform.config_entry.runtime_data)
  35. for res in reservations:
  36. if not isinstance(res, Reservation):
  37. reservations.remove(res);
  38. return reservations
  39. @callback
  40. async def set_reservation(call: ServiceCall) -> None:
  41. reservations = await get_reservations(call.data.get('device_id'), call.data.get('entity_id'))
  42. for res in reservations:
  43. for field in RESERVATION_FIELDS:
  44. value = call.data.get(field)
  45. if value is not None:
  46. res.set(field, value)
  47. await res.publish_updates()
  48. hass.services.async_register(DOMAIN, 'set_reservation', set_reservation)
  49. return True