def async_setup(self, config): """Set up a full entity component. Loads the platforms from the config and will listen for supported discovered platforms. This method must be run in the event loop. """ self.config = config # Look in config for Domain, Domain 2, Domain 3 etc and load them tasks = [] for p_type, p_config in config_per_platform(config, self.domain): tasks.append(self._async_setup_platform(p_type, p_config)) if tasks: yield from asyncio.wait(tasks, loop=self.hass.loop) # Generic discovery listener for loading platform dynamically # Refer to: homeassistant.components.discovery.load_platform() @callback def component_platform_discovered(platform, info): """Callback to load a platform.""" self.hass.async_add_job( self._async_setup_platform(platform, {}, info)) discovery.async_listen_platform(self.hass, self.domain, component_platform_discovered)
async def async_setup(self, config: ConfigType) -> None: """Set up a full entity component. Loads the platforms from the config and will listen for supported discovered platforms. This method must be run in the event loop. """ self.config = config # Look in config for Domain, Domain 2, Domain 3 etc and load them tasks = [] for p_type, p_config in config_per_platform(config, self.domain): tasks.append(self.async_setup_platform(p_type, p_config)) if tasks: await asyncio.gather(*tasks) # Generic discovery listener for loading platform dynamically # Refer to: homeassistant.components.discovery.load_platform() async def component_platform_discovered( platform: str, info: Optional[Dict[str, Any]]) -> None: """Handle the loading of a platform.""" await self.async_setup_platform(platform, {}, info) discovery.async_listen_platform(self.hass, self.domain, component_platform_discovered)
def async_setup(self, config): """Set up a full entity component. Loads the platforms from the config and will listen for supported discovered platforms. This method must be run in the event loop. """ self.config = config # Look in config for Domain, Domain 2, Domain 3 etc and load them tasks = [] for p_type, p_config in config_per_platform(config, self.domain): tasks.append(self._async_setup_platform(p_type, p_config)) if tasks: yield from asyncio.wait(tasks, loop=self.hass.loop) # Generic discovery listener for loading platform dynamically # Refer to: homeassistant.components.discovery.load_platform() @callback def component_platform_discovered(platform, info): """Handle the loading of a platform.""" self.hass.async_add_job( self._async_setup_platform(platform, {}, info)) discovery.async_listen_platform( self.hass, self.domain, component_platform_discovered)
async def async_setup(self, config: ConfigType) -> None: """Set up a full entity component. Loads the platforms from the config and will listen for supported discovered platforms. This method must be run in the event loop. """ self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self._async_shutdown) self.config = config # Look in config for Domain, Domain 2, Domain 3 etc and load them for p_type, p_config in config_per_platform(config, self.domain): self.hass.async_create_task( self.async_setup_platform(p_type, p_config)) # Generic discovery listener for loading platform dynamically # Refer to: homeassistant.helpers.discovery.async_load_platform() async def component_platform_discovered( platform: str, info: dict[str, Any] | None) -> None: """Handle the loading of a platform.""" await self.async_setup_platform(platform, {}, info) discovery.async_listen_platform(self.hass, self.domain, component_platform_discovered)
async def test_platform(hass, mock_setup_component): """Test discover platform method.""" calls = [] @callback def platform_callback(platform, info): """Platform callback method.""" calls.append((platform, info)) discovery.async_listen_platform( hass, "test_component", platform_callback, ) await discovery.async_load_platform( hass, "test_component", "test_platform", "discovery info", {"test_component": {}}, ) await hass.async_block_till_done() assert mock_setup_component.called assert mock_setup_component.call_args[0] == ( hass, "test_component", { "test_component": {} }, ) await hass.async_block_till_done() await hass.async_add_executor_job( discovery.load_platform, hass, "test_component_2", "test_platform", "discovery info", {"test_component": {}}, ) await hass.async_block_till_done() assert len(calls) == 1 assert calls[0] == ("test_platform", "discovery info") async_dispatcher_send( hass, discovery.SIGNAL_PLATFORM_DISCOVERED, {"service": discovery.EVENT_LOAD_PLATFORM.format("test_component")}, ) await hass.async_block_till_done() assert len(calls) == 1
def async_setup(hass, config): """Setup the telegram bot component.""" @asyncio.coroutine def async_setup_platform(p_type, p_config=None, discovery_info=None): """Setup a telegram bot platform.""" platform = yield from async_prepare_setup_platform( hass, config, DOMAIN, p_type) if platform is None: _LOGGER.error("Unknown notification service specified") return _LOGGER.info("Setting up1 %s.%s", DOMAIN, p_type) try: if hasattr(platform, 'async_setup_platform'): notify_service = yield from \ platform.async_setup_platform(hass, p_config, discovery_info) elif hasattr(platform, 'setup_platform'): notify_service = yield from hass.loop.run_in_executor( None, platform.setup_platform, hass, p_config, discovery_info) else: raise HomeAssistantError("Invalid telegram bot platform.") if notify_service is None: _LOGGER.error("Failed to initialize telegram bot %s", p_type) return except Exception: # pylint: disable=broad-except _LOGGER.exception('Error setting up platform %s', p_type) return return True setup_tasks = [ async_setup_platform(p_type, p_config) for p_type, p_config in config_per_platform(config, DOMAIN) ] if setup_tasks: yield from asyncio.wait(setup_tasks, loop=hass.loop) @asyncio.coroutine def async_platform_discovered(platform, info): """Callback to load a platform.""" yield from async_setup_platform(platform, discovery_info=info) discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered) return True
def async_setup(hass, config): """Set up the telegram bot component.""" @asyncio.coroutine def async_setup_platform(p_type, p_config=None, discovery_info=None): """Set up a telegram bot platform.""" platform = yield from async_prepare_setup_platform( hass, config, DOMAIN, p_type) if platform is None: _LOGGER.error("Unknown notification service specified") return _LOGGER.info("Setting up %s.%s", DOMAIN, p_type) try: if hasattr(platform, 'async_setup_platform'): notify_service = yield from \ platform.async_setup_platform(hass, p_config, discovery_info) elif hasattr(platform, 'setup_platform'): notify_service = yield from hass.loop.run_in_executor( None, platform.setup_platform, hass, p_config, discovery_info) else: raise HomeAssistantError("Invalid Telegram bot platform") if notify_service is None: _LOGGER.error( "Failed to initialize Telegram bot %s", p_type) return except Exception: # pylint: disable=broad-except _LOGGER.exception('Error setting up platform %s', p_type) return setup_tasks = [async_setup_platform(p_type, p_config) for p_type, p_config in config_per_platform(config, DOMAIN)] if setup_tasks: yield from asyncio.wait(setup_tasks, loop=hass.loop) @asyncio.coroutine def async_platform_discovered(platform, info): """Handle the loading of a platform.""" yield from async_setup_platform(platform, discovery_info=info) discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered) return True
async def async_setup(hass: HomeAssistantType, config: ConfigType): """Set up the device tracker.""" tracker = await legacy.get_tracker(hass, config) legacy_platforms = await setup.async_extract_config(hass, config) setup_tasks = [ legacy_platform.async_setup_legacy(hass, tracker) for legacy_platform in legacy_platforms ] if setup_tasks: await asyncio.wait(setup_tasks) tracker.async_setup_group() async def async_platform_discovered(p_type, info): """Load a platform.""" platform = await setup.async_create_platform_type( hass, config, p_type, {}) if platform is None or platform.type != PLATFORM_TYPE_LEGACY: return await platform.async_setup_legacy(hass, tracker, info) discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered) # Clean up stale devices async_track_utc_time_change(hass, tracker.async_update_stale, second=range(0, 60, 5)) async def async_see_service(call): """Service to see a device.""" # Temp workaround for iOS, introduced in 0.65 data = dict(call.data) data.pop("hostname", None) data.pop("battery_status", None) await tracker.async_see(**data) hass.services.async_register(DOMAIN, SERVICE_SEE, async_see_service, SERVICE_SEE_PAYLOAD_SCHEMA) # restore await tracker.async_setup_tracked_device() return True
async def async_setup(hass: HomeAssistant, config): """Set up STT.""" providers = {} async def async_setup_platform(p_type, p_config=None, discovery_info=None): """Set up a TTS platform.""" if p_config is None: p_config = {} platform = await async_prepare_setup_platform(hass, config, DOMAIN, p_type) if platform is None: return try: provider = await platform.async_get_engine(hass, p_config, discovery_info) if provider is None: _LOGGER.error("Error setting up platform %s", p_type) return provider.name = p_type provider.hass = hass providers[provider.name] = provider except Exception: # pylint: disable=broad-except _LOGGER.exception("Error setting up platform: %s", p_type) return setup_tasks = [ asyncio.create_task(async_setup_platform(p_type, p_config)) for p_type, p_config in config_per_platform(config, DOMAIN) ] if setup_tasks: await asyncio.wait(setup_tasks) # Add discovery support async def async_platform_discovered(platform, info): """Handle for discovered platform.""" await async_setup_platform(platform, discovery_info=info) discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered) hass.http.register_view(SpeechToTextView(providers)) return True
def async_setup(hass, config): _LOGGER.info("starting component setup") """יget the configuration""" st_url = config[DOMAIN][CONF_URL] st_token = config[DOMAIN][CONF_TOKEN] update_interval = config[DOMAIN][CONF_SCAN_INTERVAL] st_headers = {"Authorization": "Bearer " + st_token} ######################### #### Events Handlers #### ######################### @callback def stop_bridge_callback(evt): """יcallback for shutting down the bridge and homeassistant stop event if launched""" _LOGGER.info("stopping the bridge") stop_bridge = send_st_api_requests(st_url, MAPPINGS["stop_bridge"], st_headers) if stop_bridge is None: _LOGGER.error("smartthings bridge failed to stop") return if stop_bridge["status"]: _LOGGER.info(stop_bridge["message"]) else: _LOGGER.error(stop_bridge["message"]) @callback def smartapp_uninstalled_callback(evt): """יcallback for notifying the user when the smartapp is unistalled""" _LOGGER.error( "the bridge smartapp was just uninstalled from your device, please update the url and token after reinstalling and restart" ) notification = { ATTR_TITLE: "Smartthings SmartApp uninstalled", ATTR_MESSAGE: "Please update the url and token after reinstalling and restart" } hass.async_add_job( hass.services.async_call(PERSISTANT_DOMAIN, SERVICE_CREATE, notification)) ######################### #### Scheduled Calls #### ######################### @asyncio.coroutine def async_request_devices_update_callback(evt): """function to be called in intervals from the event loop an request devices update from the bridge""" _LOGGER.debug("requesting devices update from bridge") devices_details = send_st_api_requests(st_url, MAPPINGS["get_devices"], st_headers) if devices_details is None: _LOGGER.error("smartthings bridge did not return any devices") return for device_det in devices_details: hass.bus.async_fire(EVENT_DEVICE_UPDATE, device_det) ############################ #### Platforms Discover #### ############################ @asyncio.coroutine def async_paltform_discoverd(paltform, discovery_info=None): if paltform == DOMAIN: """check and start the bridge when any of the platforms was discoverd""" _LOGGER.info("platform discoverd, starting bridge") bridge_status = send_st_api_requests(st_url, MAPPINGS["check_bridge"], st_headers) if bridge_status is None: _LOGGER.error("smartthings bridge is not responding") return if bridge_status["status"]: _LOGGER.info(bridge_status["message"]) else: start_bridge = send_st_api_requests(st_url, MAPPINGS["start_bridge"], st_headers) if start_bridge is None: _LOGGER.error("smartthings bridge failed to start") return if start_bridge["status"]: _LOGGER.info(start_bridge["message"]) else: _LOGGER.error(start_bridge["message"]) """register to homeassistant stop event""" hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_bridge_callback) _LOGGER.debug("registerd to " + EVENT_HOMEASSISTANT_STOP + " event") """schedule track time interval for requesting device updates from the bridge""" async_track_time_interval(hass, async_request_devices_update_callback, update_interval) _LOGGER.debug("update request interval is set to " + str(update_interval)) """יget devices from smartthings""" response = send_st_api_requests(st_url, MAPPINGS["get_devices"], st_headers) if response is None: _LOGGER.error("smartthings bridge did not return any devices") return False _LOGGER.debug("discoverd " + str(len(response)) + " devices") """create domain lists from devices list""" sensor_devices = [] switch_devices = [] for device in response: if device[ATTR_HA_TYPE] == SENSOR_DOMAIN: sensor_devices.append(device) if device[ATTR_HA_TYPE] == SWITCH_DOMAIN: switch_devices.append(device) tasks = {} if sensor_devices: _LOGGER.debug("found " + str(len(sensor_devices)) + " " + SENSOR_DOMAIN + " devices") tasks[SENSOR_DOMAIN] = sensor_devices if switch_devices: _LOGGER.debug("found " + str(len(switch_devices)) + " " + SWITCH_DOMAIN + " devices") tasks[SWITCH_DOMAIN] = switch_devices """load platforms based on devices types""" if tasks: for component, entities in tasks.items(): _LOGGER.info("discovering " + str(len(tasks)) + " platforms") async_listen_platform(hass, component, async_paltform_discoverd) hass.async_add_job( async_load_platform( hass, component, DOMAIN, { KEY_ST_URL: st_url, KEY_ST_HEADERS: st_headers, KEY_DEVICES: entities }, config)) """register to event launched when the smartapp is uninstalled""" hass.bus.async_listen_once(EVENT_SMARTAPP_UNINSTALLED, smartapp_uninstalled_callback) _LOGGER.debug("registerd to " + EVENT_SMARTAPP_UNINSTALLED + " event") return True else: _LOGGER.error( "smartthings bridge did not return any eligble devices, please make sure you configured the smartapp with authorized devices" ) return False
async def async_setup(hass: HomeAssistantType, config: Dict) -> bool: """Set up the switcher component.""" phone_id = config[DOMAIN][CONF_PHONE_ID] device_id = config[DOMAIN][CONF_DEVICE_ID] device_password = config[DOMAIN][CONF_DEVICE_PASSWORD] v2bridge = SwitcherV2Bridge(hass.loop, phone_id, device_id, device_password) await v2bridge.start() async def async_stop_bridge(event: EventType) -> None: """On Home Assistant stop, gracefully stop the bridge if running.""" await v2bridge.stop() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, async_stop_bridge) try: device_data = await wait_for(v2bridge.queue.get(), timeout=10.0) except (Asyncio_TimeoutError, RuntimeError): _LOGGER.exception("Failed to get response from device") await v2bridge.stop() return False hass.data[DOMAIN] = {DATA_DEVICE: device_data} async def async_switch_platform_discovered( platform: str, discovery_info: DiscoveryInfoType) -> None: """Use for registering services after switch platform is discovered.""" if platform != DOMAIN: return async def async_set_auto_off_service(service: ServiceCallType) -> None: """Use for handling setting device auto-off service calls.""" await _validate_edit_permission(hass, service.context, service.data[ATTR_ENTITY_ID]) async with SwitcherV2Api(hass.loop, device_data.ip_addr, phone_id, device_id, device_password) as swapi: await swapi.set_auto_shutdown(service.data[CONF_AUTO_OFF]) async def async_turn_on_with_timer_service( service: ServiceCallType) -> None: """Use for handling turning device on with a timer service calls.""" await _validate_edit_permission(hass, service.context, service.data[ATTR_ENTITY_ID]) async with SwitcherV2Api(hass.loop, device_data.ip_addr, phone_id, device_id, device_password) as swapi: await swapi.control_device(COMMAND_ON, service.data[CONF_TIMER_MINUTES]) hass.services.async_register( DOMAIN, SERVICE_SET_AUTO_OFF_NAME, async_set_auto_off_service, schema=SERVICE_SET_AUTO_OFF_SCHEMA, ) hass.services.async_register( DOMAIN, SERVICE_TURN_ON_WITH_TIMER_NAME, async_turn_on_with_timer_service, schema=SERVICE_TURN_ON_WITH_TIMER_SCHEMA, ) async_listen_platform(hass, SWITCH_DOMAIN, async_switch_platform_discovered) hass.async_create_task( async_load_platform(hass, SWITCH_DOMAIN, DOMAIN, {}, config)) @callback def device_updates(timestamp: Optional[datetime]) -> None: """Use for updating the device data from the queue.""" if v2bridge.running: try: device_new_data = v2bridge.queue.get_nowait() if device_new_data: async_dispatcher_send(hass, SIGNAL_SWITCHER_DEVICE_UPDATE, device_new_data) except QueueEmpty: pass async_track_time_interval(hass, device_updates, timedelta(seconds=4)) return True
async def async_setup(hass, config): """Set up the notify services.""" hass.data.setdefault(NOTIFY_SERVICES, {}) async def persistent_notification(service: ServiceCall) -> None: """Send notification via the built-in persistsent_notify integration.""" payload = {} message = service.data[ATTR_MESSAGE] message.hass = hass payload[ATTR_MESSAGE] = message.async_render(parse_result=False) title = service.data.get(ATTR_TITLE) if title: title.hass = hass payload[ATTR_TITLE] = title.async_render(parse_result=False) await hass.services.async_call(pn.DOMAIN, pn.SERVICE_CREATE, payload, blocking=True) async def async_setup_platform(integration_name, p_config=None, discovery_info=None): """Set up a notify platform.""" if p_config is None: p_config = {} platform = await async_prepare_setup_platform(hass, config, DOMAIN, integration_name) if platform is None: _LOGGER.error("Unknown notification service specified") return _LOGGER.info("Setting up %s.%s", DOMAIN, integration_name) notify_service = None try: if hasattr(platform, "async_get_service"): notify_service = await platform.async_get_service( hass, p_config, discovery_info) elif hasattr(platform, "get_service"): notify_service = await hass.async_add_executor_job( platform.get_service, hass, p_config, discovery_info) else: raise HomeAssistantError("Invalid notify platform.") if notify_service is None: # Platforms can decide not to create a service based # on discovery data. if discovery_info is None: _LOGGER.error( "Failed to initialize notification service %s", integration_name) return except Exception: # pylint: disable=broad-except _LOGGER.exception("Error setting up platform %s", integration_name) return if discovery_info is None: discovery_info = {} conf_name = p_config.get(CONF_NAME) or discovery_info.get(CONF_NAME) target_service_name_prefix = conf_name or integration_name service_name = slugify(conf_name or SERVICE_NOTIFY) await notify_service.async_setup(hass, service_name, target_service_name_prefix) await notify_service.async_register_services() hass.data[NOTIFY_SERVICES].setdefault(integration_name, []).append(notify_service) hass.config.components.add(f"{DOMAIN}.{integration_name}") return True hass.services.async_register( DOMAIN, SERVICE_PERSISTENT_NOTIFICATION, persistent_notification, schema=PERSISTENT_NOTIFICATION_SERVICE_SCHEMA, ) setup_tasks = [ asyncio.create_task(async_setup_platform(integration_name, p_config)) for integration_name, p_config in config_per_platform(config, DOMAIN) ] if setup_tasks: await asyncio.wait(setup_tasks) async def async_platform_discovered(platform, info): """Handle for discovered platform.""" await async_setup_platform(platform, discovery_info=info) discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered) return True
async def async_setup(hass, config): """Track states and offer events for mailboxes.""" mailboxes = [] await hass.components.frontend.async_register_built_in_panel( 'mailbox', 'mailbox', 'mdi:mailbox') hass.http.register_view(MailboxPlatformsView(mailboxes)) hass.http.register_view(MailboxMessageView(mailboxes)) hass.http.register_view(MailboxMediaView(mailboxes)) hass.http.register_view(MailboxDeleteView(mailboxes)) async def async_setup_platform(p_type, p_config=None, discovery_info=None): """Set up a mailbox platform.""" if p_config is None: p_config = {} if discovery_info is None: discovery_info = {} platform = await async_prepare_setup_platform(hass, config, DOMAIN, p_type) if platform is None: _LOGGER.error("Unknown mailbox platform specified") return _LOGGER.info("Setting up %s.%s", DOMAIN, p_type) mailbox = None try: if hasattr(platform, 'async_get_handler'): mailbox = await \ platform.async_get_handler(hass, p_config, discovery_info) elif hasattr(platform, 'get_handler'): mailbox = await hass.async_add_executor_job( platform.get_handler, hass, p_config, discovery_info) else: raise HomeAssistantError("Invalid mailbox platform.") if mailbox is None: _LOGGER.error("Failed to initialize mailbox platform %s", p_type) return except Exception: # pylint: disable=broad-except _LOGGER.exception('Error setting up platform %s', p_type) return mailboxes.append(mailbox) mailbox_entity = MailboxEntity(mailbox) component = EntityComponent(logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL) await component.async_add_entities([mailbox_entity]) setup_tasks = [ async_setup_platform(p_type, p_config) for p_type, p_config in config_per_platform(config, DOMAIN) ] if setup_tasks: await asyncio.wait(setup_tasks, loop=hass.loop) async def async_platform_discovered(platform, info): """Handle for discovered platform.""" await async_setup_platform(platform, discovery_info=info) discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered) return True
def async_setup(hass, config): """Track states and offer events for mailboxes.""" mailboxes = [] yield from hass.components.frontend.async_register_built_in_panel( 'mailbox', 'mailbox', 'mdi:mailbox') hass.http.register_view(MailboxPlatformsView(mailboxes)) hass.http.register_view(MailboxMessageView(mailboxes)) hass.http.register_view(MailboxMediaView(mailboxes)) hass.http.register_view(MailboxDeleteView(mailboxes)) @asyncio.coroutine def async_setup_platform(p_type, p_config=None, discovery_info=None): """Set up a mailbox platform.""" if p_config is None: p_config = {} if discovery_info is None: discovery_info = {} platform = yield from async_prepare_setup_platform( hass, config, DOMAIN, p_type) if platform is None: _LOGGER.error("Unknown mailbox platform specified") return _LOGGER.info("Setting up %s.%s", DOMAIN, p_type) mailbox = None try: if hasattr(platform, 'async_get_handler'): mailbox = yield from \ platform.async_get_handler(hass, p_config, discovery_info) elif hasattr(platform, 'get_handler'): mailbox = yield from hass.async_add_job( platform.get_handler, hass, p_config, discovery_info) else: raise HomeAssistantError("Invalid mailbox platform.") if mailbox is None: _LOGGER.error( "Failed to initialize mailbox platform %s", p_type) return except Exception: # pylint: disable=broad-except _LOGGER.exception('Error setting up platform %s', p_type) return mailboxes.append(mailbox) mailbox_entity = MailboxEntity(hass, mailbox) component = EntityComponent( logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL) yield from component.async_add_entities([mailbox_entity]) setup_tasks = [async_setup_platform(p_type, p_config) for p_type, p_config in config_per_platform(config, DOMAIN)] if setup_tasks: yield from asyncio.wait(setup_tasks, loop=hass.loop) @asyncio.coroutine def async_platform_discovered(platform, info): """Handle for discovered platform.""" yield from async_setup_platform(platform, discovery_info=info) discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered) return True
async def async_setup(hass: HomeAssistantType, config: ConfigType): """Set up the device tracker.""" yaml_path = hass.config.path(YAML_DEVICES) conf = config.get(DOMAIN, []) conf = conf[0] if conf else {} consider_home = conf.get(CONF_CONSIDER_HOME, DEFAULT_CONSIDER_HOME) defaults = conf.get(CONF_NEW_DEVICE_DEFAULTS, {}) track_new = conf.get(CONF_TRACK_NEW) if track_new is None: track_new = defaults.get(CONF_TRACK_NEW, DEFAULT_TRACK_NEW) devices = await async_load_config(yaml_path, hass, consider_home) tracker = DeviceTracker( hass, consider_home, track_new, defaults, devices) async def async_setup_platform(p_type, p_config, disc_info=None): """Set up a device tracker platform.""" platform = await async_prepare_setup_platform( hass, config, DOMAIN, p_type) if platform is None: return _LOGGER.info("Setting up %s.%s", DOMAIN, p_type) try: scanner = None setup = None if hasattr(platform, 'async_get_scanner'): scanner = await platform.async_get_scanner( hass, {DOMAIN: p_config}) elif hasattr(platform, 'get_scanner'): scanner = await hass.async_add_job( platform.get_scanner, hass, {DOMAIN: p_config}) elif hasattr(platform, 'async_setup_scanner'): setup = await platform.async_setup_scanner( hass, p_config, tracker.async_see, disc_info) elif hasattr(platform, 'setup_scanner'): setup = await hass.async_add_job( platform.setup_scanner, hass, p_config, tracker.see, disc_info) elif hasattr(platform, 'async_setup_entry'): setup = await platform.async_setup_entry( hass, p_config, tracker.async_see) else: raise HomeAssistantError("Invalid device_tracker platform.") if scanner: async_setup_scanner_platform( hass, p_config, scanner, tracker.async_see, p_type) return if not setup: _LOGGER.error("Error setting up platform %s", p_type) return except Exception: # pylint: disable=broad-except _LOGGER.exception("Error setting up platform %s", p_type) hass.data[DOMAIN] = async_setup_platform setup_tasks = [async_setup_platform(p_type, p_config) for p_type, p_config in config_per_platform(config, DOMAIN)] if setup_tasks: await asyncio.wait(setup_tasks, loop=hass.loop) tracker.async_setup_group() async def async_platform_discovered(platform, info): """Load a platform.""" await async_setup_platform(platform, {}, disc_info=info) discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered) # Clean up stale devices async_track_utc_time_change( hass, tracker.async_update_stale, second=range(0, 60, 5)) async def async_see_service(call): """Service to see a device.""" # Temp workaround for iOS, introduced in 0.65 data = dict(call.data) data.pop('hostname', None) data.pop('battery_status', None) await tracker.async_see(**data) hass.services.async_register( DOMAIN, SERVICE_SEE, async_see_service, SERVICE_SEE_PAYLOAD_SCHEMA) # restore await tracker.async_setup_tracked_device() return True
def async_setup(hass: HomeAssistantType, config: ConfigType): """Setup device tracker.""" yaml_path = hass.config.path(YAML_DEVICES) try: conf = config.get(DOMAIN, []) except vol.Invalid as ex: async_log_exception(ex, DOMAIN, config, hass) return False else: conf = conf[0] if len(conf) > 0 else {} consider_home = conf.get(CONF_CONSIDER_HOME, DEFAULT_CONSIDER_HOME) track_new = conf.get(CONF_TRACK_NEW, DEFAULT_TRACK_NEW) devices = yield from async_load_config(yaml_path, hass, consider_home) tracker = DeviceTracker(hass, consider_home, track_new, devices) @asyncio.coroutine def async_setup_platform(p_type, p_config, disc_info=None): """Setup a device tracker platform.""" platform = yield from async_prepare_setup_platform( hass, config, DOMAIN, p_type) if platform is None: return _LOGGER.info("Setting up %s.%s", DOMAIN, p_type) try: scanner = None setup = None if hasattr(platform, 'async_get_scanner'): scanner = yield from platform.async_get_scanner( hass, {DOMAIN: p_config}) elif hasattr(platform, 'get_scanner'): scanner = yield from hass.loop.run_in_executor( None, platform.get_scanner, hass, {DOMAIN: p_config}) elif hasattr(platform, 'async_setup_scanner'): setup = yield from platform.async_setup_scanner( hass, p_config, tracker.async_see, disc_info) elif hasattr(platform, 'setup_scanner'): setup = yield from hass.loop.run_in_executor( None, platform.setup_scanner, hass, p_config, tracker.see, disc_info) else: raise HomeAssistantError("Invalid device_tracker platform.") if scanner: async_setup_scanner_platform(hass, p_config, scanner, tracker.async_see, p_type) return if not setup: _LOGGER.error('Error setting up platform %s', p_type) return except Exception: # pylint: disable=broad-except _LOGGER.exception('Error setting up platform %s', p_type) setup_tasks = [ async_setup_platform(p_type, p_config) for p_type, p_config in config_per_platform(config, DOMAIN) ] if setup_tasks: yield from asyncio.wait(setup_tasks, loop=hass.loop) yield from tracker.async_setup_group() @callback def async_device_tracker_discovered(service, info): """Called when a device tracker platform is discovered.""" hass.async_add_job( async_setup_platform(DISCOVERY_PLATFORMS[service], {}, info)) discovery.async_listen(hass, DISCOVERY_PLATFORMS.keys(), async_device_tracker_discovered) @asyncio.coroutine def async_platform_discovered(platform, info): """Callback to load a platform.""" yield from async_setup_platform(platform, {}, disc_info=info) discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered) # Clean up stale devices async_track_utc_time_change(hass, tracker.async_update_stale, second=range(0, 60, 5)) @asyncio.coroutine def async_see_service(call): """Service to see a device.""" args = { key: value for key, value in call.data.items() if key in (ATTR_MAC, ATTR_DEV_ID, ATTR_HOST_NAME, ATTR_LOCATION_NAME, ATTR_GPS, ATTR_GPS_ACCURACY, ATTR_BATTERY, ATTR_ATTRIBUTES) } yield from tracker.async_see(**args) descriptions = yield from hass.loop.run_in_executor( None, load_yaml_config_file, os.path.join(os.path.dirname(__file__), 'services.yaml')) hass.services.async_register(DOMAIN, SERVICE_SEE, async_see_service, descriptions.get(SERVICE_SEE)) # restore yield from tracker.async_setup_tracked_device() return True
async def async_setup(hass, config): """Set up TTS.""" tts = SpeechManager(hass) try: conf = config[DOMAIN][0] if config.get(DOMAIN, []) else {} use_cache = conf.get(CONF_CACHE, DEFAULT_CACHE) cache_dir = conf.get(CONF_CACHE_DIR, DEFAULT_CACHE_DIR) time_memory = conf.get(CONF_TIME_MEMORY, DEFAULT_TIME_MEMORY) base_url = conf.get(CONF_BASE_URL) hass.data[BASE_URL_KEY] = base_url await tts.async_init_cache(use_cache, cache_dir, time_memory, base_url) except (HomeAssistantError, KeyError): _LOGGER.exception("Error on cache init") return False hass.http.register_view(TextToSpeechView(tts)) hass.http.register_view(TextToSpeechUrlView(tts)) # Load service descriptions from tts/services.yaml integration = await async_get_integration(hass, DOMAIN) services_yaml = integration.file_path / "services.yaml" services_dict = cast( dict, await hass.async_add_executor_job(load_yaml, str(services_yaml)) ) async def async_setup_platform(p_type, p_config=None, discovery_info=None): """Set up a TTS platform.""" if p_config is None: p_config = {} platform = await async_prepare_setup_platform(hass, config, DOMAIN, p_type) if platform is None: return try: if hasattr(platform, "async_get_engine"): provider = await platform.async_get_engine( hass, p_config, discovery_info ) else: provider = await hass.async_add_executor_job( platform.get_engine, hass, p_config, discovery_info ) if provider is None: _LOGGER.error("Error setting up platform %s", p_type) return tts.async_register_engine(p_type, provider, p_config) except Exception: # pylint: disable=broad-except _LOGGER.exception("Error setting up platform: %s", p_type) return async def async_say_handle(service): """Service handle for say.""" entity_ids = service.data[ATTR_ENTITY_ID] message = service.data.get(ATTR_MESSAGE) cache = service.data.get(ATTR_CACHE) language = service.data.get(ATTR_LANGUAGE) options = service.data.get(ATTR_OPTIONS) try: url = await tts.async_get_url_path( p_type, message, cache=cache, language=language, options=options ) except HomeAssistantError as err: _LOGGER.error("Error on init TTS: %s", err) return base = tts.base_url or get_url(hass) url = base + url data = { ATTR_MEDIA_CONTENT_ID: url, ATTR_MEDIA_CONTENT_TYPE: MEDIA_TYPE_MUSIC, ATTR_ENTITY_ID: entity_ids, } await hass.services.async_call( DOMAIN_MP, SERVICE_PLAY_MEDIA, data, blocking=True, context=service.context, ) service_name = p_config.get(CONF_SERVICE_NAME, f"{p_type}_{SERVICE_SAY}") hass.services.async_register( DOMAIN, service_name, async_say_handle, schema=SCHEMA_SERVICE_SAY ) # Register the service description service_desc = { CONF_NAME: f"Say an TTS message with {p_type}", CONF_DESCRIPTION: f"Say something using text-to-speech on a media player with {p_type}.", CONF_FIELDS: services_dict[SERVICE_SAY][CONF_FIELDS], } async_set_service_schema(hass, DOMAIN, service_name, service_desc) setup_tasks = [ asyncio.create_task(async_setup_platform(p_type, p_config)) for p_type, p_config in config_per_platform(config, DOMAIN) ] if setup_tasks: await asyncio.wait(setup_tasks) async def async_platform_discovered(platform, info): """Handle for discovered platform.""" await async_setup_platform(platform, discovery_info=info) discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered) async def async_clear_cache_handle(service): """Handle clear cache service call.""" await tts.async_clear_cache() hass.services.async_register( DOMAIN, SERVICE_CLEAR_CACHE, async_clear_cache_handle, schema=SCHEMA_SERVICE_CLEAR_CACHE, ) return True
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up TTS.""" tts = SpeechManager(hass) try: conf = config[DOMAIN][0] if config.get(DOMAIN, []) else {} use_cache = conf.get(CONF_CACHE, DEFAULT_CACHE) cache_dir = conf.get(CONF_CACHE_DIR, DEFAULT_CACHE_DIR) time_memory = conf.get(CONF_TIME_MEMORY, DEFAULT_TIME_MEMORY) base_url = conf.get(CONF_BASE_URL) if base_url is not None: _LOGGER.warning( "TTS base_url option is deprecated. Configure internal/external URL instead" ) hass.data[BASE_URL_KEY] = base_url await tts.async_init_cache(use_cache, cache_dir, time_memory, base_url) except (HomeAssistantError, KeyError): _LOGGER.exception("Error on cache init") return False hass.data[DOMAIN] = tts hass.http.register_view(TextToSpeechView(tts)) hass.http.register_view(TextToSpeechUrlView(tts)) # Load service descriptions from tts/services.yaml services_yaml = Path(__file__).parent / "services.yaml" services_dict = cast( dict, await hass.async_add_executor_job(load_yaml, str(services_yaml))) async def async_setup_platform( p_type: str, p_config: ConfigType | None = None, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up a TTS platform.""" if p_config is None: p_config = {} platform = await async_prepare_setup_platform(hass, config, DOMAIN, p_type) if platform is None: return try: if hasattr(platform, "async_get_engine"): provider = await platform.async_get_engine( hass, p_config, discovery_info) else: provider = await hass.async_add_executor_job( platform.get_engine, hass, p_config, discovery_info) if provider is None: _LOGGER.error("Error setting up platform %s", p_type) return tts.async_register_engine(p_type, provider, p_config) except Exception: # pylint: disable=broad-except _LOGGER.exception("Error setting up platform: %s", p_type) return async def async_say_handle(service: ServiceCall) -> None: """Service handle for say.""" entity_ids = service.data[ATTR_ENTITY_ID] message = service.data[ATTR_MESSAGE] cache = service.data.get(ATTR_CACHE) language = service.data.get(ATTR_LANGUAGE) options = service.data.get(ATTR_OPTIONS) tts.process_options(p_type, language, options) params = { "message": message, } if cache is not None: params["cache"] = "true" if cache else "false" if language is not None: params["language"] = language if options is not None: params.update(options) await hass.services.async_call( DOMAIN_MP, SERVICE_PLAY_MEDIA, { ATTR_ENTITY_ID: entity_ids, ATTR_MEDIA_CONTENT_ID: generate_media_source_id( DOMAIN, str(yarl.URL.build(path=p_type, query=params)), ), ATTR_MEDIA_CONTENT_TYPE: MEDIA_TYPE_MUSIC, ATTR_MEDIA_ANNOUNCE: True, }, blocking=True, context=service.context, ) service_name = p_config.get(CONF_SERVICE_NAME, f"{p_type}_{SERVICE_SAY}") hass.services.async_register(DOMAIN, service_name, async_say_handle, schema=SCHEMA_SERVICE_SAY) # Register the service description service_desc = { CONF_NAME: f"Say an TTS message with {p_type}", CONF_DESCRIPTION: f"Say something using text-to-speech on a media player with {p_type}.", CONF_FIELDS: services_dict[SERVICE_SAY][CONF_FIELDS], } async_set_service_schema(hass, DOMAIN, service_name, service_desc) setup_tasks = [ asyncio.create_task(async_setup_platform(p_type, p_config)) for p_type, p_config in config_per_platform(config, DOMAIN) if p_type is not None ] if setup_tasks: await asyncio.wait(setup_tasks) async def async_platform_discovered(platform, info): """Handle for discovered platform.""" await async_setup_platform(platform, discovery_info=info) discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered) async def async_clear_cache_handle(service: ServiceCall) -> None: """Handle clear cache service call.""" await tts.async_clear_cache() hass.services.async_register( DOMAIN, SERVICE_CLEAR_CACHE, async_clear_cache_handle, schema=SCHEMA_SERVICE_CLEAR_CACHE, ) return True
def async_setup(hass: HomeAssistantType, config: ConfigType): """Set up the device tracker.""" yaml_path = hass.config.path(YAML_DEVICES) conf = config.get(DOMAIN, []) conf = conf[0] if conf else {} consider_home = conf.get(CONF_CONSIDER_HOME, DEFAULT_CONSIDER_HOME) track_new = conf.get(CONF_TRACK_NEW, DEFAULT_TRACK_NEW) devices = yield from async_load_config(yaml_path, hass, consider_home) tracker = DeviceTracker(hass, consider_home, track_new, devices) @asyncio.coroutine def async_setup_platform(p_type, p_config, disc_info=None): """Set up a device tracker platform.""" platform = yield from async_prepare_setup_platform( hass, config, DOMAIN, p_type) if platform is None: return _LOGGER.info("Setting up %s.%s", DOMAIN, p_type) try: scanner = None setup = None if hasattr(platform, 'async_get_scanner'): scanner = yield from platform.async_get_scanner( hass, {DOMAIN: p_config}) elif hasattr(platform, 'get_scanner'): scanner = yield from hass.async_add_job( platform.get_scanner, hass, {DOMAIN: p_config}) elif hasattr(platform, 'async_setup_scanner'): setup = yield from platform.async_setup_scanner( hass, p_config, tracker.async_see, disc_info) elif hasattr(platform, 'setup_scanner'): setup = yield from hass.async_add_job( platform.setup_scanner, hass, p_config, tracker.see, disc_info) else: raise HomeAssistantError("Invalid device_tracker platform.") if scanner: async_setup_scanner_platform( hass, p_config, scanner, tracker.async_see, p_type) return if not setup: _LOGGER.error("Error setting up platform %s", p_type) return except Exception: # pylint: disable=broad-except _LOGGER.exception("Error setting up platform %s", p_type) setup_tasks = [async_setup_platform(p_type, p_config) for p_type, p_config in config_per_platform(config, DOMAIN)] if setup_tasks: yield from asyncio.wait(setup_tasks, loop=hass.loop) tracker.async_setup_group() @callback def async_device_tracker_discovered(service, info): """Handle the discovery of device tracker platforms.""" hass.async_add_job( async_setup_platform(DISCOVERY_PLATFORMS[service], {}, info)) discovery.async_listen( hass, DISCOVERY_PLATFORMS.keys(), async_device_tracker_discovered) @asyncio.coroutine def async_platform_discovered(platform, info): """Load a platform.""" yield from async_setup_platform(platform, {}, disc_info=info) discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered) # Clean up stale devices async_track_utc_time_change( hass, tracker.async_update_stale, second=range(0, 60, 5)) @asyncio.coroutine def async_see_service(call): """Service to see a device.""" args = {key: value for key, value in call.data.items() if key in (ATTR_MAC, ATTR_DEV_ID, ATTR_HOST_NAME, ATTR_LOCATION_NAME, ATTR_GPS, ATTR_GPS_ACCURACY, ATTR_BATTERY, ATTR_ATTRIBUTES)} yield from tracker.async_see(**args) descriptions = yield from hass.async_add_job( load_yaml_config_file, os.path.join(os.path.dirname(__file__), 'services.yaml') ) hass.services.async_register( DOMAIN, SERVICE_SEE, async_see_service, descriptions.get(SERVICE_SEE)) # restore yield from tracker.async_setup_tracked_device() return True
async def async_setup(hass, config): """Set up TTS.""" tts = SpeechManager(hass) try: conf = config[DOMAIN][0] if config.get(DOMAIN, []) else {} use_cache = conf.get(CONF_CACHE, DEFAULT_CACHE) cache_dir = conf.get(CONF_CACHE_DIR, DEFAULT_CACHE_DIR) time_memory = conf.get(CONF_TIME_MEMORY, DEFAULT_TIME_MEMORY) base_url = conf.get(CONF_BASE_URL) or hass.config.api.base_url await tts.async_init_cache(use_cache, cache_dir, time_memory, base_url) except (HomeAssistantError, KeyError) as err: _LOGGER.error("Error on cache init %s", err) return False hass.http.register_view(TextToSpeechView(tts)) hass.http.register_view(TextToSpeechUrlView(tts)) async def async_setup_platform(p_type, p_config=None, discovery_info=None): """Set up a TTS platform.""" if p_config is None: p_config = {} platform = await async_prepare_setup_platform(hass, config, DOMAIN, p_type) if platform is None: return try: if hasattr(platform, "async_get_engine"): provider = await platform.async_get_engine( hass, p_config, discovery_info ) else: provider = await hass.async_add_executor_job( platform.get_engine, hass, p_config, discovery_info ) if provider is None: _LOGGER.error("Error setting up platform %s", p_type) return tts.async_register_engine(p_type, provider, p_config) except Exception: # pylint: disable=broad-except _LOGGER.exception("Error setting up platform: %s", p_type) return async def async_say_handle(service): """Service handle for say.""" entity_ids = service.data[ATTR_ENTITY_ID] message = service.data.get(ATTR_MESSAGE) cache = service.data.get(ATTR_CACHE) language = service.data.get(ATTR_LANGUAGE) options = service.data.get(ATTR_OPTIONS) try: url = await tts.async_get_url( p_type, message, cache=cache, language=language, options=options ) except HomeAssistantError as err: _LOGGER.error("Error on init TTS: %s", err) return data = { ATTR_MEDIA_CONTENT_ID: url, ATTR_MEDIA_CONTENT_TYPE: MEDIA_TYPE_MUSIC, ATTR_ENTITY_ID: entity_ids, } await hass.services.async_call( DOMAIN_MP, SERVICE_PLAY_MEDIA, data, blocking=True ) service_name = p_config.get(CONF_SERVICE_NAME, f"{p_type}_{SERVICE_SAY}") hass.services.async_register( DOMAIN, service_name, async_say_handle, schema=SCHEMA_SERVICE_SAY ) setup_tasks = [ async_setup_platform(p_type, p_config) for p_type, p_config in config_per_platform(config, DOMAIN) ] if setup_tasks: await asyncio.wait(setup_tasks) async def async_platform_discovered(platform, info): """Handle for discovered platform.""" await async_setup_platform(platform, discovery_info=info) discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered) async def async_clear_cache_handle(service): """Handle clear cache service call.""" await tts.async_clear_cache() hass.services.async_register( DOMAIN, SERVICE_CLEAR_CACHE, async_clear_cache_handle, schema=SCHEMA_SERVICE_CLEAR_CACHE, ) return True
async def async_setup(hass: HomeAssistantType, config: ConfigType): """Set up the device tracker.""" yaml_path = hass.config.path(YAML_DEVICES) conf = config.get(DOMAIN, []) conf = conf[0] if conf else {} consider_home = conf.get(CONF_CONSIDER_HOME, DEFAULT_CONSIDER_HOME) defaults = conf.get(CONF_NEW_DEVICE_DEFAULTS, {}) track_new = conf.get(CONF_TRACK_NEW) if track_new is None: track_new = defaults.get(CONF_TRACK_NEW, DEFAULT_TRACK_NEW) devices = await async_load_config(yaml_path, hass, consider_home) tracker = DeviceTracker(hass, consider_home, track_new, defaults, devices) async def async_setup_platform(p_type, p_config, disc_info=None): """Set up a device tracker platform.""" platform = await async_prepare_setup_platform(hass, config, DOMAIN, p_type) if platform is None: return _LOGGER.info("Setting up %s.%s", DOMAIN, p_type) try: scanner = None setup = None if hasattr(platform, 'async_get_scanner'): scanner = await platform.async_get_scanner( hass, {DOMAIN: p_config}) elif hasattr(platform, 'get_scanner'): scanner = await hass.async_add_job(platform.get_scanner, hass, {DOMAIN: p_config}) elif hasattr(platform, 'async_setup_scanner'): setup = await platform.async_setup_scanner( hass, p_config, tracker.async_see, disc_info) elif hasattr(platform, 'setup_scanner'): setup = await hass.async_add_job(platform.setup_scanner, hass, p_config, tracker.see, disc_info) else: raise HomeAssistantError("Invalid device_tracker platform.") if scanner: async_setup_scanner_platform(hass, p_config, scanner, tracker.async_see, p_type) return if not setup: _LOGGER.error("Error setting up platform %s", p_type) return except Exception: # pylint: disable=broad-except _LOGGER.exception("Error setting up platform %s", p_type) setup_tasks = [ async_setup_platform(p_type, p_config) for p_type, p_config in config_per_platform(config, DOMAIN) ] if setup_tasks: await asyncio.wait(setup_tasks, loop=hass.loop) tracker.async_setup_group() async def async_platform_discovered(platform, info): """Load a platform.""" await async_setup_platform(platform, {}, disc_info=info) discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered) # Clean up stale devices async_track_utc_time_change(hass, tracker.async_update_stale, second=range(0, 60, 5)) async def async_see_service(call): """Service to see a device.""" # Temp workaround for iOS, introduced in 0.65 data = dict(call.data) data.pop('hostname', None) data.pop('battery_status', None) await tracker.async_see(**data) hass.services.async_register(DOMAIN, SERVICE_SEE, async_see_service, SERVICE_SEE_PAYLOAD_SCHEMA) # restore await tracker.async_setup_tracked_device() return True
def async_setup(hass, config): """Set up the notify services.""" targets = {} @asyncio.coroutine def async_setup_platform(p_type, p_config=None, discovery_info=None): """Set up a notify platform.""" if p_config is None: p_config = {} platform = yield from async_prepare_setup_platform( hass, config, DOMAIN, p_type) if platform is None: _LOGGER.error("Unknown notification service specified") return _LOGGER.info("Setting up %s.%s", DOMAIN, p_type) notify_service = None try: if hasattr(platform, 'async_get_service'): notify_service = yield from \ platform.async_get_service(hass, p_config, discovery_info) elif hasattr(platform, 'get_service'): notify_service = yield from hass.async_add_job( platform.get_service, hass, p_config, discovery_info) else: raise HomeAssistantError("Invalid notify platform.") if notify_service is None: # Platforms can decide not to create a service based # on discovery data. if discovery_info is None: _LOGGER.error( "Failed to initialize notification service %s", p_type) return except Exception: # pylint: disable=broad-except _LOGGER.exception('Error setting up platform %s', p_type) return notify_service.hass = hass if discovery_info is None: discovery_info = {} @asyncio.coroutine def async_notify_message(service): """Handle sending notification message service calls.""" kwargs = {} message = service.data[ATTR_MESSAGE] title = service.data.get(ATTR_TITLE) if title: title.hass = hass kwargs[ATTR_TITLE] = title.async_render() if targets.get(service.service) is not None: kwargs[ATTR_TARGET] = [targets[service.service]] elif service.data.get(ATTR_TARGET) is not None: kwargs[ATTR_TARGET] = service.data.get(ATTR_TARGET) message.hass = hass kwargs[ATTR_MESSAGE] = message.async_render() kwargs[ATTR_DATA] = service.data.get(ATTR_DATA) yield from notify_service.async_send_message(**kwargs) if hasattr(notify_service, 'targets'): platform_name = ( p_config.get(CONF_NAME) or discovery_info.get(CONF_NAME) or p_type) for name, target in notify_service.targets.items(): target_name = slugify('{}_{}'.format(platform_name, name)) targets[target_name] = target hass.services.async_register( DOMAIN, target_name, async_notify_message, schema=NOTIFY_SERVICE_SCHEMA) platform_name = ( p_config.get(CONF_NAME) or discovery_info.get(CONF_NAME) or SERVICE_NOTIFY) platform_name_slug = slugify(platform_name) hass.services.async_register( DOMAIN, platform_name_slug, async_notify_message, schema=NOTIFY_SERVICE_SCHEMA) hass.config.components.add('{}.{}'.format(DOMAIN, p_type)) return True setup_tasks = [async_setup_platform(p_type, p_config) for p_type, p_config in config_per_platform(config, DOMAIN)] if setup_tasks: yield from asyncio.wait(setup_tasks, loop=hass.loop) @asyncio.coroutine def async_platform_discovered(platform, info): """Handle for discovered platform.""" yield from async_setup_platform(platform, discovery_info=info) discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered) return True
def async_setup(hass: HomeAssistantType, config: ConfigType): """Set up the device tracker.""" yaml_path = hass.config.path(YAML_DEVICES) conf = config.get(DOMAIN, []) conf = conf[0] if conf else {} consider_home = conf.get(CONF_CONSIDER_HOME, DEFAULT_CONSIDER_HOME) defaults = conf.get(CONF_NEW_DEVICE_DEFAULTS, {}) track_new = conf.get(CONF_TRACK_NEW) if track_new is None: track_new = defaults.get(CONF_TRACK_NEW, DEFAULT_TRACK_NEW) devices = yield from async_load_config(yaml_path, hass, consider_home) tracker = DeviceTracker(hass, consider_home, track_new, defaults, devices) @asyncio.coroutine def async_setup_platform(p_type, p_config, disc_info=None): """Set up a device tracker platform.""" platform = yield from async_prepare_setup_platform( hass, config, DOMAIN, p_type) if platform is None: return _LOGGER.info("Setting up %s.%s", DOMAIN, p_type) try: scanner = None setup = None if hasattr(platform, 'async_get_scanner'): scanner = yield from platform.async_get_scanner( hass, {DOMAIN: p_config}) elif hasattr(platform, 'get_scanner'): scanner = yield from hass.async_add_job( platform.get_scanner, hass, {DOMAIN: p_config}) elif hasattr(platform, 'async_setup_scanner'): setup = yield from platform.async_setup_scanner( hass, p_config, tracker.async_see, disc_info) elif hasattr(platform, 'setup_scanner'): setup = yield from hass.async_add_job(platform.setup_scanner, hass, p_config, tracker.see, disc_info) else: raise HomeAssistantError("Invalid device_tracker platform.") if scanner: async_setup_scanner_platform(hass, p_config, scanner, tracker.async_see, p_type) return if not setup: _LOGGER.error("Error setting up platform %s", p_type) return except Exception: # pylint: disable=broad-except _LOGGER.exception("Error setting up platform %s", p_type) setup_tasks = [ async_setup_platform(p_type, p_config) for p_type, p_config in config_per_platform(config, DOMAIN) ] if setup_tasks: yield from asyncio.wait(setup_tasks, loop=hass.loop) tracker.async_setup_group() @asyncio.coroutine def async_platform_discovered(platform, info): """Load a platform.""" yield from async_setup_platform(platform, {}, disc_info=info) discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered) # Clean up stale devices async_track_utc_time_change(hass, tracker.async_update_stale, second=range(0, 60, 5)) @asyncio.coroutine def async_see_service(call): """Service to see a device.""" args = { key: value for key, value in call.data.items() if key in (ATTR_MAC, ATTR_DEV_ID, ATTR_HOST_NAME, ATTR_LOCATION_NAME, ATTR_GPS, ATTR_GPS_ACCURACY, ATTR_BATTERY, ATTR_ATTRIBUTES) } yield from tracker.async_see(**args) hass.services.async_register(DOMAIN, SERVICE_SEE, async_see_service) # restore yield from tracker.async_setup_tracked_device() return True
async def async_setup_legacy(hass: HomeAssistant, config: ConfigType) -> None: """Set up legacy notify services.""" hass.data.setdefault(NOTIFY_SERVICES, {}) async def async_setup_platform( integration_name: str, p_config: ConfigType | None = None, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up a notify platform.""" if p_config is None: p_config = {} platform = await async_prepare_setup_platform(hass, config, DOMAIN, integration_name) if platform is None: LOGGER.error("Unknown notification service specified") return full_name = f"{DOMAIN}.{integration_name}" LOGGER.info("Setting up %s", full_name) with async_start_setup(hass, [full_name]): notify_service = None try: if hasattr(platform, "async_get_service"): notify_service = await platform.async_get_service( hass, p_config, discovery_info) elif hasattr(platform, "get_service"): notify_service = await hass.async_add_executor_job( platform.get_service, hass, p_config, discovery_info) else: raise HomeAssistantError("Invalid notify platform.") if notify_service is None: # Platforms can decide not to create a service based # on discovery data. if discovery_info is None: LOGGER.error( "Failed to initialize notification service %s", integration_name, ) return except Exception: # pylint: disable=broad-except LOGGER.exception("Error setting up platform %s", integration_name) return if discovery_info is None: discovery_info = {} conf_name = p_config.get(CONF_NAME) or discovery_info.get( CONF_NAME) target_service_name_prefix = conf_name or integration_name service_name = slugify(conf_name or SERVICE_NOTIFY) await notify_service.async_setup(hass, service_name, target_service_name_prefix) await notify_service.async_register_services() hass.data[NOTIFY_SERVICES].setdefault(integration_name, []).append(notify_service) hass.config.components.add(f"{DOMAIN}.{integration_name}") setup_tasks = [ asyncio.create_task(async_setup_platform(integration_name, p_config)) for integration_name, p_config in config_per_platform(config, DOMAIN) ] if setup_tasks: await asyncio.wait(setup_tasks) async def async_platform_discovered( platform: str, info: DiscoveryInfoType | None) -> None: """Handle for discovered platform.""" await async_setup_platform(platform, discovery_info=info) discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered)
async def async_setup(hass: HomeAssistantType, config: ConfigType): """Set up the device tracker.""" tracker = await legacy.get_tracker(hass, config) async def setup_entry_helper(entry): """Set up a config entry.""" platform = await setup.async_create_platform_type( hass, config, entry.domain, entry) if platform is None: return False await platform.async_setup_legacy(hass, tracker) return True hass.data[DOMAIN] = setup_entry_helper component = EntityComponent(LOGGER, DOMAIN, hass, SCAN_INTERVAL) legacy_platforms, entity_platforms = \ await setup.async_extract_config(hass, config) setup_tasks = [ legacy_platform.async_setup_legacy(hass, tracker) for legacy_platform in legacy_platforms ] if entity_platforms: setup_tasks.append( component.async_setup({ **config_without_domain(config, DOMAIN), DOMAIN: [platform.config for platform in entity_platforms] })) if setup_tasks: await asyncio.wait(setup_tasks, loop=hass.loop) tracker.async_setup_group() async def async_platform_discovered(p_type, info): """Load a platform.""" platform = await setup.async_create_platform_type( hass, config, p_type, {}) if platform is None or platform.type != PLATFORM_TYPE_LEGACY: return await platform.async_setup_legacy(hass, tracker, info) discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered) # Clean up stale devices async_track_utc_time_change(hass, tracker.async_update_stale, second=range(0, 60, 5)) async def async_see_service(call): """Service to see a device.""" # Temp workaround for iOS, introduced in 0.65 data = dict(call.data) data.pop('hostname', None) data.pop('battery_status', None) await tracker.async_see(**data) hass.services.async_register(DOMAIN, SERVICE_SEE, async_see_service, SERVICE_SEE_PAYLOAD_SCHEMA) # restore await tracker.async_setup_tracked_device() return True