async def get_gateway_info(hass, host, identity, key): """Return info for the gateway.""" from pytradfri.api.aiocoap_api import APIFactory from pytradfri import Gateway, RequestError try: factory = APIFactory( host, psk_id=identity, psk=key, loop=hass.loop ) api = factory.request gateway = Gateway() gateway_info_result = await api(gateway.get_gateway_info()) await factory.shutdown() except (OSError, RequestError): # We're also catching OSError as PyTradfri doesn't catch that one yet # Upstream PR: https://github.com/ggravlingen/pytradfri/pull/189 raise AuthError('cannot_connect') return { CONF_HOST: host, CONF_IDENTITY: identity, CONF_KEY: key, CONF_GATEWAY_ID: gateway_info_result.id, }
def _setup_gateway(hass, hass_config, host, key, allow_tradfri_groups): """Create a gateway.""" from pytradfri import cli_api_factory, Gateway, RequestError, retry_timeout try: api = retry_timeout(cli_api_factory(host, key)) except RequestError: return False gateway = Gateway(api) gateway_id = gateway.get_gateway_info().id hass.data.setdefault(KEY_GATEWAY, {}) gateways = hass.data[KEY_GATEWAY] hass.data.setdefault(KEY_TRADFRI_GROUPS, {}) tradfri_groups = hass.data[KEY_TRADFRI_GROUPS] tradfri_groups[gateway_id] = allow_tradfri_groups # Check if already set up if gateway_id in gateways: return True gateways[gateway_id] = gateway hass.async_add_job(discovery.async_load_platform( hass, 'light', DOMAIN, {'gateway': gateway_id}, hass_config)) return True
def _setup_gateway(hass, hass_config, host, key, allow_tradfri_groups): """Create a gateway.""" from pytradfri import Gateway, RequestError from pytradfri.api.libcoap_api import api_factory try: api = api_factory(host, key) except RequestError: return False gateway = Gateway() # pylint: disable=no-member gateway_id = api(gateway.get_gateway_info()).id hass.data.setdefault(KEY_API, {}) hass.data.setdefault(KEY_GATEWAY, {}) gateways = hass.data[KEY_GATEWAY] hass.data[KEY_API][gateway_id] = api hass.data.setdefault(KEY_TRADFRI_GROUPS, {}) tradfri_groups = hass.data[KEY_TRADFRI_GROUPS] tradfri_groups[gateway_id] = allow_tradfri_groups # Check if already set up if gateway_id in gateways: return True gateways[gateway_id] = gateway hass.async_add_job(discovery.async_load_platform( hass, 'light', DOMAIN, {'gateway': gateway_id}, hass_config)) return True
async def async_setup_entry(hass, entry): """Create a gateway.""" # host, identity, key, allow_tradfri_groups from pytradfri import Gateway, RequestError # pylint: disable=import-error from pytradfri.api.aiocoap_api import APIFactory factory = APIFactory( entry.data[CONF_HOST], psk_id=entry.data[CONF_IDENTITY], psk=entry.data[CONF_KEY], loop=hass.loop ) async def on_hass_stop(event): """Close connection when hass stops.""" await factory.shutdown() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, on_hass_stop) api = factory.request gateway = Gateway() try: gateway_info = await api(gateway.get_gateway_info()) except RequestError: _LOGGER.error("Tradfri setup failed.") return False hass.data.setdefault(KEY_API, {})[entry.entry_id] = api hass.data.setdefault(KEY_GATEWAY, {})[entry.entry_id] = gateway dev_reg = await hass.helpers.device_registry.async_get_registry() dev_reg.async_get_or_create( config_entry_id=entry.entry_id, connections=set(), identifiers={ (DOMAIN, entry.data[CONF_GATEWAY_ID]) }, manufacturer='IKEA', name='Gateway', # They just have 1 gateway model. Type is not exposed yet. model='E1526', sw_version=gateway_info.firmware_version, ) hass.async_create_task(hass.config_entries.async_forward_entry_setup( entry, 'light' )) hass.async_create_task(hass.config_entries.async_forward_entry_setup( entry, 'sensor' )) hass.async_create_task(hass.config_entries.async_forward_entry_setup( entry, 'switch' )) return True
async def async_setup_entry(hass, entry): """Create a gateway.""" # host, identity, key, allow_tradfri_groups tradfri_data = hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {} listeners = tradfri_data[LISTENERS] = [] factory = await APIFactory.init( entry.data[CONF_HOST], psk_id=entry.data[CONF_IDENTITY], psk=entry.data[CONF_KEY], ) async def on_hass_stop(event): """Close connection when hass stops.""" await factory.shutdown() listeners.append( hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, on_hass_stop)) api = factory.request gateway = Gateway() try: gateway_info = await api(gateway.get_gateway_info()) devices_commands = await api(gateway.get_devices()) devices = await api(devices_commands) groups_commands = await api(gateway.get_groups()) groups = await api(groups_commands) except RequestError as err: await factory.shutdown() raise ConfigEntryNotReady from err tradfri_data[KEY_API] = api tradfri_data[FACTORY] = factory tradfri_data[DEVICES] = devices tradfri_data[GROUPS] = groups dev_reg = await hass.helpers.device_registry.async_get_registry() dev_reg.async_get_or_create( config_entry_id=entry.entry_id, connections=set(), identifiers={(DOMAIN, entry.data[CONF_GATEWAY_ID])}, manufacturer=ATTR_TRADFRI_MANUFACTURER, name=ATTR_TRADFRI_GATEWAY, # They just have 1 gateway model. Type is not exposed yet. model=ATTR_TRADFRI_GATEWAY_MODEL, sw_version=gateway_info.firmware_version, ) for component in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, component)) return True
async def async_setup_entry(hass, entry): """Create a gateway.""" # host, identity, key, allow_tradfri_groups from pytradfri import Gateway, RequestError # pylint: disable=import-error from pytradfri.api.aiocoap_api import APIFactory factory = APIFactory( entry.data[CONF_HOST], psk_id=entry.data[CONF_IDENTITY], psk=entry.data[CONF_KEY], loop=hass.loop, ) async def on_hass_stop(event): """Close connection when hass stops.""" await factory.shutdown() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, on_hass_stop) api = factory.request gateway = Gateway() try: gateway_info = await api(gateway.get_gateway_info()) except RequestError: _LOGGER.error("Tradfri setup failed.") return False hass.data.setdefault(KEY_API, {})[entry.entry_id] = api hass.data.setdefault(KEY_GATEWAY, {})[entry.entry_id] = gateway dev_reg = await hass.helpers.device_registry.async_get_registry() dev_reg.async_get_or_create( config_entry_id=entry.entry_id, connections=set(), identifiers={(DOMAIN, entry.data[CONF_GATEWAY_ID])}, manufacturer="IKEA", name="Gateway", # They just have 1 gateway model. Type is not exposed yet. model="E1526", sw_version=gateway_info.firmware_version, ) hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, "light") ) hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, "sensor") ) hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, "switch") ) return True
async def async_setup_entry(hass, entry): """Create a gateway.""" # host, identity, key, allow_tradfri_groups factory = APIFactory( entry.data[CONF_HOST], psk_id=entry.data[CONF_IDENTITY], psk=entry.data[CONF_KEY], loop=hass.loop, ) async def on_hass_stop(event): """Close connection when hass stops.""" await factory.shutdown() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, on_hass_stop) api = factory.request gateway = Gateway() try: gateway_info = await api(gateway.get_gateway_info()) except RequestError: await factory.shutdown() raise ConfigEntryNotReady hass.data.setdefault(KEY_API, {})[entry.entry_id] = api hass.data.setdefault(KEY_GATEWAY, {})[entry.entry_id] = gateway dev_reg = await hass.helpers.device_registry.async_get_registry() dev_reg.async_get_or_create( config_entry_id=entry.entry_id, connections=set(), identifiers={(DOMAIN, entry.data[CONF_GATEWAY_ID])}, manufacturer=ATTR_TRADFRI_MANUFACTURER, name=ATTR_TRADFRI_GATEWAY, # They just have 1 gateway model. Type is not exposed yet. model=ATTR_TRADFRI_GATEWAY_MODEL, sw_version=gateway_info.firmware_version, ) for device in TRADFRI_DEVICE_TYPES: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, device)) async def keepalive(): while True: await api(gateway.get_gateway_info()) await asyncio.sleep(45) asyncio.ensure_future(keepalive(), loop=asyncio.get_event_loop()) return True
async def get_gateway_info(hass, host, identity, key): """Return info for the gateway.""" from pytradfri.api.aiocoap_api import APIFactory from pytradfri import Gateway, RequestError try: factory = APIFactory(host, psk_id=identity, psk=key, loop=hass.loop) api = factory.request gateway = Gateway() gateway_info_result = await api(gateway.get_gateway_info()) except RequestError: raise AuthError('cannot_connect') return { CONF_HOST: host, CONF_IDENTITY: identity, CONF_KEY: key, CONF_GATEWAY_ID: gateway_info_result.id, }
async def _setup_gateway(hass, hass_config, host, identity, key, allow_tradfri_groups): """Create a gateway.""" from pytradfri import Gateway, RequestError # pylint: disable=import-error try: from pytradfri.api.aiocoap_api import APIFactory except ImportError: _LOGGER.exception("Looks like something isn't installed!") return False try: factory = APIFactory(host, psk_id=identity, psk=key, loop=hass.loop) api = factory.request gateway = Gateway() gateway_info_result = await api(gateway.get_gateway_info()) except RequestError: _LOGGER.exception("Tradfri setup failed.") return False gateway_id = gateway_info_result.id hass.data.setdefault(KEY_API, {}) hass.data.setdefault(KEY_GATEWAY, {}) gateways = hass.data[KEY_GATEWAY] hass.data[KEY_API][gateway_id] = api hass.data.setdefault(KEY_TRADFRI_GROUPS, {}) tradfri_groups = hass.data[KEY_TRADFRI_GROUPS] tradfri_groups[gateway_id] = allow_tradfri_groups # Check if already set up if gateway_id in gateways: return True gateways[gateway_id] = gateway hass.async_add_job( discovery.async_load_platform(hass, 'light', DOMAIN, {'gateway': gateway_id}, hass_config)) hass.async_add_job( discovery.async_load_platform(hass, 'sensor', DOMAIN, {'gateway': gateway_id}, hass_config)) return True
async def async_setup_entry(hass, entry): """Create a gateway.""" # host, identity, key, allow_tradfri_groups from pytradfri import Gateway, RequestError # pylint: disable=import-error from pytradfri.api.aiocoap_api import APIFactory factory = APIFactory(entry.data[CONF_HOST], psk_id=entry.data[CONF_IDENTITY], psk=entry.data[CONF_KEY], loop=hass.loop) api = factory.request gateway = Gateway() try: gateway_info = await api(gateway.get_gateway_info()) except RequestError: _LOGGER.error("Tradfri setup failed.") return False hass.data.setdefault(KEY_API, {})[entry.entry_id] = api hass.data.setdefault(KEY_GATEWAY, {})[entry.entry_id] = gateway dev_reg = await hass.helpers.device_registry.async_get_registry() dev_reg.async_get_or_create( config_entry_id=entry.entry_id, connections=set(), identifiers={(DOMAIN, entry.data[CONF_GATEWAY_ID])}, manufacturer='IKEA', name='Gateway', # They just have 1 gateway model. Type is not exposed yet. model='E1526', sw_version=gateway_info.firmware_version, ) hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, 'light')) hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, 'sensor')) return True
async def _setup_gateway(hass, hass_config, host, identity, key, allow_tradfri_groups): """Create a gateway.""" from pytradfri import Gateway, RequestError # pylint: disable=import-error try: from pytradfri.api.aiocoap_api import APIFactory except ImportError: _LOGGER.exception("Looks like something isn't installed!") return False try: factory = APIFactory(host, psk_id=identity, psk=key, loop=hass.loop) api = factory.request gateway = Gateway() gateway_info_result = await api(gateway.get_gateway_info()) except RequestError: _LOGGER.exception("Tradfri setup failed.") return False gateway_id = gateway_info_result.id hass.data.setdefault(KEY_API, {}) hass.data.setdefault(KEY_GATEWAY, {}) gateways = hass.data[KEY_GATEWAY] hass.data[KEY_API][gateway_id] = api hass.data.setdefault(KEY_TRADFRI_GROUPS, {}) tradfri_groups = hass.data[KEY_TRADFRI_GROUPS] tradfri_groups[gateway_id] = allow_tradfri_groups # Check if already set up if gateway_id in gateways: return True gateways[gateway_id] = gateway hass.async_create_task(discovery.async_load_platform( hass, 'light', DOMAIN, {'gateway': gateway_id}, hass_config)) hass.async_create_task(discovery.async_load_platform( hass, 'sensor', DOMAIN, {'gateway': gateway_id}, hass_config)) return True
async def get_gateway_info(opp, host, identity, key): """Return info for the gateway.""" try: factory = await APIFactory.init(host, psk_id=identity, psk=key) api = factory.request gateway = Gateway() gateway_info_result = await api(gateway.get_gateway_info()) await factory.shutdown() except (OSError, RequestError) as err: # We're also catching OSError as PyTradfri doesn't catch that one yet # Upstream PR: https://github.com/ggravlingen/pytradfri/pull/189 raise AuthError("cannot_connect") from err return { CONF_HOST: host, CONF_IDENTITY: identity, CONF_KEY: key, CONF_GATEWAY_ID: gateway_info_result.id, }
def _setup_gateway(hass, hass_config, host, key): """Create a gateway.""" from pytradfri import cli_api_factory, Gateway, RequestError, retry_timeout try: api = retry_timeout(cli_api_factory(host, key)) except RequestError: return False gateway = Gateway(api) gateway_id = gateway.get_gateway_info().id hass.data.setdefault(KEY_GATEWAY, {}) gateways = hass.data[KEY_GATEWAY] # Check if already set up if gateway_id in gateways: return True gateways[gateway_id] = gateway hass.async_add_job(discovery.async_load_platform( hass, 'light', DOMAIN, {'gateway': gateway_id}, hass_config)) return True
async def get_gateway_info(hass, host, identity, key): """Return info for the gateway.""" from pytradfri.api.aiocoap_api import APIFactory from pytradfri import Gateway, RequestError try: factory = APIFactory( host, psk_id=identity, psk=key, loop=hass.loop ) api = factory.request gateway = Gateway() gateway_info_result = await api(gateway.get_gateway_info()) except RequestError: raise AuthError('cannot_connect') return { CONF_HOST: host, CONF_IDENTITY: identity, CONF_KEY: key, CONF_GATEWAY_ID: gateway_info_result.id, }
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Create a gateway.""" # host, identity, key, allow_tradfri_groups tradfri_data: dict[str, Any] = {} hass.data.setdefault(DOMAIN, {})[entry.entry_id] = tradfri_data listeners = tradfri_data[LISTENERS] = [] factory = await APIFactory.init( entry.data[CONF_HOST], psk_id=entry.data[CONF_IDENTITY], psk=entry.data[CONF_KEY], ) async def on_hass_stop(event): """Close connection when hass stops.""" await factory.shutdown() listeners.append(hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, on_hass_stop)) api = factory.request gateway = Gateway() try: gateway_info = await api(gateway.get_gateway_info()) devices_commands = await api(gateway.get_devices()) devices = await api(devices_commands) groups_commands = await api(gateway.get_groups()) groups = await api(groups_commands) except RequestError as err: await factory.shutdown() raise ConfigEntryNotReady from err tradfri_data[KEY_API] = api tradfri_data[FACTORY] = factory tradfri_data[DEVICES] = devices tradfri_data[GROUPS] = groups dev_reg = await hass.helpers.device_registry.async_get_registry() dev_reg.async_get_or_create( config_entry_id=entry.entry_id, connections=set(), identifiers={(DOMAIN, entry.data[CONF_GATEWAY_ID])}, manufacturer=ATTR_TRADFRI_MANUFACTURER, name=ATTR_TRADFRI_GATEWAY, # They just have 1 gateway model. Type is not exposed yet. model=ATTR_TRADFRI_GATEWAY_MODEL, sw_version=gateway_info.firmware_version, ) hass.config_entries.async_setup_platforms(entry, PLATFORMS) async def async_keep_alive(now): if hass.is_stopping: return try: await api(gateway.get_gateway_info()) except RequestError: _LOGGER.error("Keep-alive failed") listeners.append( async_track_time_interval(hass, async_keep_alive, timedelta(seconds=60)) ) return True
async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, ) -> bool: """Create a gateway.""" tradfri_data: dict[str, Any] = {} hass.data.setdefault(DOMAIN, {})[entry.entry_id] = tradfri_data factory = await APIFactory.init( entry.data[CONF_HOST], psk_id=entry.data[CONF_IDENTITY], psk=entry.data[CONF_KEY], ) tradfri_data[FACTORY] = factory # Used for async_unload_entry async def on_hass_stop(event: Event) -> None: """Close connection when hass stops.""" await factory.shutdown() # Setup listeners entry.async_on_unload( hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, on_hass_stop)) api = factory.request gateway = Gateway() try: gateway_info = await api(gateway.get_gateway_info(), timeout=TIMEOUT_API) devices_commands: Command = await api(gateway.get_devices(), timeout=TIMEOUT_API) devices: list[Device] = await api(devices_commands, timeout=TIMEOUT_API) except RequestError as exc: await factory.shutdown() raise ConfigEntryNotReady from exc dev_reg = await hass.helpers.device_registry.async_get_registry() dev_reg.async_get_or_create( config_entry_id=entry.entry_id, connections=set(), identifiers={(DOMAIN, entry.data[CONF_GATEWAY_ID])}, manufacturer="IKEA of Sweden", name="Gateway", # They just have 1 gateway model. Type is not exposed yet. model="E1526", sw_version=gateway_info.firmware_version, ) remove_stale_devices(hass, entry, devices) # Setup the device coordinators coordinator_data = { CONF_GATEWAY_ID: gateway, KEY_API: api, COORDINATOR_LIST: [], } for device in devices: coordinator = TradfriDeviceDataUpdateCoordinator(hass=hass, api=api, device=device) await coordinator.async_config_entry_first_refresh() entry.async_on_unload( async_dispatcher_connect(hass, SIGNAL_GW, coordinator.set_hub_available)) coordinator_data[COORDINATOR_LIST].append(coordinator) tradfri_data[COORDINATOR] = coordinator_data async def async_keep_alive(now: datetime) -> None: if hass.is_stopping: return gw_status = True try: await api(gateway.get_gateway_info()) except RequestError: LOGGER.error("Keep-alive failed") gw_status = False async_dispatcher_send(hass, SIGNAL_GW, gw_status) entry.async_on_unload( async_track_time_interval(hass, async_keep_alive, timedelta(seconds=60))) hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True
async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, ) -> bool: """Create a gateway.""" tradfri_data: dict[str, Any] = {} hass.data.setdefault(DOMAIN, {})[entry.entry_id] = tradfri_data listeners = tradfri_data[LISTENERS] = [] factory = await APIFactory.init( entry.data[CONF_HOST], psk_id=entry.data[CONF_IDENTITY], psk=entry.data[CONF_KEY], ) tradfri_data[FACTORY] = factory # Used for async_unload_entry async def on_hass_stop(event: Event) -> None: """Close connection when hass stops.""" await factory.shutdown() # Setup listeners listeners.append( hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, on_hass_stop)) api = factory.request gateway = Gateway() groups: list[Group] = [] try: gateway_info = await api(gateway.get_gateway_info(), timeout=TIMEOUT_API) devices_commands: Command = await api(gateway.get_devices(), timeout=TIMEOUT_API) devices: list[Device] = await api(devices_commands, timeout=TIMEOUT_API) if entry.data[CONF_IMPORT_GROUPS]: # Note: we should update this page when deprecating: # https://www.home-assistant.io/integrations/tradfri/ _LOGGER.warning( "Importing of Tradfri groups has been deprecated due to stability issues " "and will be removed in Home Assistant core 2022.4") # No need to load groups if the user hasn't requested it groups_commands: Command = await api(gateway.get_groups(), timeout=TIMEOUT_API) groups = await api(groups_commands, timeout=TIMEOUT_API) except RequestError as exc: await factory.shutdown() raise ConfigEntryNotReady from exc dev_reg = await hass.helpers.device_registry.async_get_registry() dev_reg.async_get_or_create( config_entry_id=entry.entry_id, connections=set(), identifiers={(DOMAIN, entry.data[CONF_GATEWAY_ID])}, manufacturer=ATTR_TRADFRI_MANUFACTURER, name=ATTR_TRADFRI_GATEWAY, # They just have 1 gateway model. Type is not exposed yet. model=ATTR_TRADFRI_GATEWAY_MODEL, sw_version=gateway_info.firmware_version, ) remove_stale_devices(hass, entry, devices) # Setup the device coordinators coordinator_data = { CONF_GATEWAY_ID: gateway, KEY_API: api, COORDINATOR_LIST: [], GROUPS_LIST: [], } for device in devices: coordinator = TradfriDeviceDataUpdateCoordinator(hass=hass, api=api, device=device) await coordinator.async_config_entry_first_refresh() entry.async_on_unload( async_dispatcher_connect(hass, SIGNAL_GW, coordinator.set_hub_available)) coordinator_data[COORDINATOR_LIST].append(coordinator) for group in groups: group_coordinator = TradfriGroupDataUpdateCoordinator(hass=hass, api=api, group=group) await group_coordinator.async_config_entry_first_refresh() entry.async_on_unload( async_dispatcher_connect(hass, SIGNAL_GW, group_coordinator.set_hub_available)) coordinator_data[GROUPS_LIST].append(group_coordinator) tradfri_data[COORDINATOR] = coordinator_data async def async_keep_alive(now: datetime) -> None: if hass.is_stopping: return gw_status = True try: await api(gateway.get_gateway_info()) except RequestError: _LOGGER.error("Keep-alive failed") gw_status = False async_dispatcher_send(hass, SIGNAL_GW, gw_status) listeners.append( async_track_time_interval(hass, async_keep_alive, timedelta(seconds=60))) hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True