async def async_added_to_hass(self) -> None: """Register callbacks.""" await super().async_added_to_hass() self.async_accept_signal( None, f"{SIGNAL_GROUP_MEMBERSHIP_CHANGE}_0x{self._group_id:04x}", self._handle_group_membership_changed, signal_override=True, ) if self._change_listener_debouncer is None: self._change_listener_debouncer = Debouncer( self.hass, self, cooldown=UPDATE_GROUP_FROM_CHILD_DELAY, immediate=False, function=functools.partial(self.async_update_ha_state, True), ) self._async_unsub_state_changed = async_track_state_change_event( self.hass, self._entity_ids, self.async_state_changed_listener) def send_removed_signal(): async_dispatcher_send(self.hass, SIGNAL_GROUP_ENTITY_REMOVED, self._group_id) self.async_on_remove(send_removed_signal)
async def async_added_to_hass(self): """ add to home assistant """ self.async_refresh_toggle = Debouncer( self.hass, _LOGGER, cooldown=60, immediate=True, function=self._async_refresh_toggle, ) await super().async_added_to_hass()
def __init__(self, hass: HomeAssistant, entry: ConfigEntry, device: RpcDevice) -> None: """Initialize the Shelly device wrapper.""" self.device_id: str | None = None device_name = get_rpc_device_name( device) if device.initialized else entry.title super().__init__( hass, LOGGER, name=device_name, update_interval=timedelta(seconds=RPC_RECONNECT_INTERVAL), ) self.entry = entry self.device = device self._debounced_reload: Debouncer[Coroutine[ Any, Any, None]] = Debouncer( hass, LOGGER, cooldown=ENTRY_RELOAD_COOLDOWN, immediate=False, function=self._async_reload_entry, ) entry.async_on_unload(self._debounced_reload.async_cancel) entry.async_on_unload( self.async_add_listener(self._async_device_updates_handler)) self._last_event: dict[str, Any] | None = None entry.async_on_unload( hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self._handle_ha_stop))
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the Plex component.""" hass.data.setdefault( PLEX_DOMAIN, { SERVERS: {}, DISPATCHERS: {}, WEBSOCKETS: {}, PLATFORMS_COMPLETED: {} }, ) await async_setup_services(hass) gdm = hass.data[PLEX_DOMAIN][GDM_SCANNER] = GDM() def gdm_scan(): _LOGGER.debug("Scanning for GDM clients") gdm.scan(scan_for_clients=True) hass.data[PLEX_DOMAIN][GDM_DEBOUNCER] = Debouncer( hass, _LOGGER, cooldown=10, immediate=True, function=gdm_scan, ).async_call return True
def __init__(self, hass, server_config, known_server_id=None, options=None): """Initialize a Plex server instance.""" self.hass = hass self._plex_server = None self._known_clients = set() self._known_idle = set() self._url = server_config.get(CONF_URL) self._token = server_config.get(CONF_TOKEN) self._server_name = server_config.get(CONF_SERVER) self._verify_ssl = server_config.get(CONF_VERIFY_SSL, DEFAULT_VERIFY_SSL) self._server_id = known_server_id self.options = options self.server_choice = None self._accounts = [] self._owner_username = None self._version = None self.async_update_platforms = Debouncer( hass, _LOGGER, cooldown=DEBOUNCE_TIMEOUT, immediate=True, function=self._async_update_platforms, ).async_call # Header conditionally added as it is not available in config entry v1 if CONF_CLIENT_IDENTIFIER in server_config: plexapi.X_PLEX_IDENTIFIER = server_config[CONF_CLIENT_IDENTIFIER] plexapi.myplex.BASE_HEADERS = plexapi.reset_base_headers() plexapi.server.BASE_HEADERS = plexapi.reset_base_headers()
async def async_setup(hass, config): """Set up the Plex component.""" hass.data.setdefault( PLEX_DOMAIN, { SERVERS: {}, DISPATCHERS: {}, WEBSOCKETS: {}, PLATFORMS_COMPLETED: {} }, ) await async_setup_services(hass) gdm = hass.data[PLEX_DOMAIN][GDM_SCANNER] = GDM() hass.data[PLEX_DOMAIN][GDM_DEBOUNCER] = Debouncer( hass, _LOGGER, cooldown=10, immediate=True, function=partial(gdm.scan, scan_for_clients=True), ).async_call return True
async def _async_setup(self) -> None: """Finish setup in async context.""" self.cache_update_lock = asyncio.Lock() self.async_poll = Debouncer( self.hass, _LOGGER, cooldown=3, immediate=False, function=self._async_poll, ).async_call
async def async_added_to_hass(self) -> None: """Set up the debouncer when adding to hass.""" self._debouncer = Debouncer( hass=self.hass, logger=_LOGGER, cooldown=DEBOUNCE_TIME, immediate=False, function=self._async_set_value, ) await super().async_added_to_hass()
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Smart Meter Texas from a config entry.""" username = entry.data[CONF_USERNAME] password = entry.data[CONF_PASSWORD] account = Account(username, password) client_ssl_context = ClientSSLContext() ssl_context = await client_ssl_context.get_ssl_context() smart_meter_texas_data = SmartMeterTexasData(hass, entry, account, ssl_context) try: await smart_meter_texas_data.client.authenticate() except SmartMeterTexasAuthError: _LOGGER.error("Username or password was not accepted") return False except asyncio.TimeoutError as error: raise ConfigEntryNotReady from error await smart_meter_texas_data.setup() async def async_update_data(): _LOGGER.debug("Fetching latest data") await smart_meter_texas_data.read_meters() return smart_meter_texas_data # Use a DataUpdateCoordinator to manage the updates. This is due to the # Smart Meter Texas API which takes around 30 seconds to read a meter. # This avoids Home Assistant from complaining about the component taking # too long to update. coordinator = DataUpdateCoordinator( hass, _LOGGER, name="Smart Meter Texas", update_method=async_update_data, update_interval=SCAN_INTERVAL, request_refresh_debouncer=Debouncer(hass, _LOGGER, cooldown=DEBOUNCE_COOLDOWN, immediate=True), ) hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = { DATA_COORDINATOR: coordinator, DATA_SMART_METER: smart_meter_texas_data, } asyncio.create_task(coordinator.async_refresh()) await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) return True
async def async_request_scan(self) -> None: """Request a serial scan.""" if not self._request_debouncer: self._request_debouncer = Debouncer( self.hass, _LOGGER, cooldown=REQUEST_SCAN_COOLDOWN, immediate=True, function=self._async_scan, ) await self._request_debouncer.async_call()
def _async_create_debouncer(self, house_id): """Create a debouncer for the house id.""" async def _async_update_house_id(): await self._async_update_house_id(house_id) return Debouncer( self._hass, _LOGGER, cooldown=ACTIVITY_UPDATE_INTERVAL.total_seconds(), immediate=True, function=_async_update_house_id, )
def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: """Init the debounced entry reloader.""" self.hass = hass self.entry = entry self.token = self.entry.data.get(CONF_TOKEN) self._debounced_reload = Debouncer( hass, LOGGER, cooldown=ENTRY_RELOAD_COOLDOWN, immediate=False, function=self._async_reload_entry, )
async def _async_create_polling_debouncer(self) -> None: """Create a polling debouncer in async context. Used to ensure redundant poll requests from all speakers are coalesced. """ self.async_poll = Debouncer( self.hass, _LOGGER, cooldown=3, immediate=False, function=self._async_poll, ).async_call
async def async_added_to_hass(self): """Run when about to be added to hass.""" await super().async_added_to_hass() if self._debounced_member_refresh is None: force_refresh_debouncer = Debouncer( self.hass, _LOGGER, cooldown=3, immediate=True, function=self._force_member_updates, ) self._debounced_member_refresh = force_refresh_debouncer
def __init__(self, hass: HomeAssistant, client: TapoApiClient): self.api = client debouncer = Debouncer(hass, _LOGGGER, cooldown=DEBOUNCER_COOLDOWN, immediate=True) super().__init__( hass, _LOGGGER, name=DOMAIN, update_interval=SCAN_INTERVAL, request_refresh_debouncer=debouncer, )
def __init__(self, hass, plex_server): """Initialize the sensor.""" self._state = None self._server = plex_server self._name = NAME_FORMAT.format(plex_server.friendly_name) self._unique_id = f"sensor-{plex_server.machine_identifier}" self.async_refresh_sensor = Debouncer( hass, _LOGGER, cooldown=3, immediate=False, function=self._async_refresh_sensor, ).async_call
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up ONYX from a config entry.""" hass.data.setdefault(DOMAIN, {}) fingerprint = entry.data[CONF_FINGERPRINT] token = entry.data[CONF_ACCESS_TOKEN] scan_interval = entry.data[CONF_SCAN_INTERVAL] force_update = entry.data.get(CONF_FORCE_UPDATE, False) _LOGGER.debug("setting up %s integration with fingerprint %s", DOMAIN, fingerprint) if force_update: _LOGGER.warning( "Disabling partial updates. " "This may lead to a higher amount of API calls to Hella, " "and performance impacts. It is advised to not enable this option." ) onyx_api = APIConnector(hass, fingerprint, token) await onyx_api.update() onyx_timezone = await onyx_api.get_timezone() coordinator = DataUpdateCoordinator( hass, _LOGGER, name="ONYX", update_method=onyx_api.update, update_interval=timedelta(minutes=scan_interval), request_refresh_debouncer=Debouncer(hass, _LOGGER, cooldown=0, immediate=True), ) thread = EventThread(onyx_api, coordinator, force_update) hass.data[DOMAIN][entry.entry_id] = { ONYX_API: onyx_api, ONYX_TIMEZONE: onyx_timezone, ONYX_COORDINATOR: coordinator, ONYX_THREAD: thread, } thread.start() for platform in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, platform), ) return True
def __init__(self, hass, plex_server): """Initialize the sensor.""" self._attr_icon = "mdi:plex" self._attr_name = NAME_FORMAT.format(plex_server.friendly_name) self._attr_should_poll = False self._attr_unique_id = f"sensor-{plex_server.machine_identifier}" self._attr_native_unit_of_measurement = "Watching" self._server = plex_server self.async_refresh_sensor = Debouncer( hass, _LOGGER, cooldown=3, immediate=False, function=self._async_refresh_sensor, ).async_call
def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: """Initialize IotaWattUpdater object.""" self.entry = entry super().__init__( hass=hass, logger=_LOGGER, name=entry.title, update_interval=timedelta(seconds=30), request_refresh_debouncer=Debouncer( hass, _LOGGER, cooldown=REQUEST_REFRESH_DEFAULT_COOLDOWN, immediate=True, ), ) self._last_run: datetime | None = None
def __init__(self, hass: HomeAssistant, device: AIOWifiLedBulb, entry: ConfigEntry) -> None: """Initialize DataUpdateCoordinator to gather data for specific device.""" self.device = device self.entry = entry super().__init__( hass, _LOGGER, name=self.device.ipaddr, update_interval=timedelta(seconds=10), # We don't want an immediate refresh since the device # takes a moment to reflect the state change request_refresh_debouncer=Debouncer(hass, _LOGGER, cooldown=REQUEST_REFRESH_DELAY, immediate=False), )
def __init__( self, hass: HomeAssistant, config_entry, ) -> None: """Class to manage fetching Heatzy data API.""" self.heatzy_client = HeatzyClient( config_entry.data[CONF_USERNAME], config_entry.data[CONF_PASSWORD] ) super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=timedelta(seconds=60), request_refresh_debouncer=Debouncer( hass, _LOGGER, cooldown=DEBOUNCE_COOLDOWN, immediate=False ), )
def __init__(self, hass: HomeAssistant, api: Smile) -> None: """Initialize the coordinator.""" super().__init__( hass, LOGGER, name=api.smile_name or DOMAIN, update_interval=DEFAULT_SCAN_INTERVAL.get(str(api.smile_type), timedelta(seconds=60)), # Don't refresh immediately, give the device time to process # the change in state before we query it. request_refresh_debouncer=Debouncer( hass, LOGGER, cooldown=1.5, immediate=False, ), ) self.api = api
def __init__(self, hass, api: PhilipsTV, options: Mapping) -> None: """Set up the coordinator.""" self.api = api self.options = options self._notify_future: asyncio.Task | None = None self.turn_on = PluggableAction(self.async_update_listeners) super().__init__( hass, LOGGER, name=DOMAIN, update_interval=timedelta(seconds=30), request_refresh_debouncer=Debouncer(hass, LOGGER, cooldown=2.0, immediate=False), )
def __init__( self, hass: HomeAssistant, host: str, mac: str, pin: str, ignored_sources: list[str], ) -> None: """Initialize Bravia TV Client.""" self.braviarc = BraviaRC(host, mac) self.pin = pin self.ignored_sources = ignored_sources self.muted: bool = False self.channel_name: str | None = None self.media_title: str | None = None self.source: str | None = None self.source_list: list[str] = [] self.original_content_list: list[str] = [] self.content_mapping: dict[str, str] = {} self.duration: int | None = None self.content_uri: str | None = None self.program_media_type: str | None = None self.audio_output: str | None = None self.min_volume: int | None = None self.max_volume: int | None = None self.volume_level: float | None = None self.is_on = False # Assume that the TV is in Play mode self.playing = True self.state_lock = asyncio.Lock() super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=SCAN_INTERVAL, request_refresh_debouncer=Debouncer(hass, _LOGGER, cooldown=1.0, immediate=False), )
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the bluetooth integration.""" integration_matcher = IntegrationMatcher(await async_get_bluetooth(hass)) integration_matcher.async_setup() manager = BluetoothManager(hass, integration_matcher) manager.async_setup() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, manager.async_stop) hass.data[DATA_MANAGER] = models.MANAGER = manager adapters = await manager.async_get_bluetooth_adapters() async_migrate_entries(hass, adapters) await async_discover_adapters(hass, adapters) async def _async_rediscover_adapters() -> None: """Rediscover adapters when a new one may be available.""" discovered_adapters = await manager.async_get_bluetooth_adapters( cached=False) _LOGGER.debug("Rediscovered adapters: %s", discovered_adapters) await async_discover_adapters(hass, discovered_adapters) discovery_debouncer = Debouncer(hass, _LOGGER, cooldown=5, immediate=False, function=_async_rediscover_adapters) def _async_trigger_discovery() -> None: # There are so many bluetooth adapter models that # we check the bus whenever a usb device is plugged in # to see if it is a bluetooth adapter since we can't # tell if the device is a bluetooth adapter or if its # actually supported unless we ask DBus if its now # present. _LOGGER.debug("Triggering bluetooth usb discovery") hass.async_create_task(discovery_debouncer.async_call()) cancel = usb.async_register_scan_request_callback( hass, _async_trigger_discovery) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, hass_callback(lambda event: cancel())) return True
def __init__(self, hass, *, config_entry, gateway): """Initialize the Screenlogic Data Update Coordinator.""" self.config_entry = config_entry self.gateway = gateway self.screenlogic_data = {} interval = timedelta( seconds=config_entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) ) super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=interval, # Debounced option since the device takes # a moment to reflect the knock-on changes request_refresh_debouncer=Debouncer( hass, _LOGGER, cooldown=REQUEST_REFRESH_DELAY, immediate=False ), )
def __init__( self, hass: HomeAssistant, logger: logging.Logger, *, address: str, mode: BluetoothScanningMode, update_method: Callable[[BluetoothServiceInfoBleak], _T], needs_poll_method: Callable[[BluetoothServiceInfoBleak, float | None], bool], poll_method: Callable[ [BluetoothServiceInfoBleak], Coroutine[Any, Any, _T], ] | None = None, poll_debouncer: Debouncer[Coroutine[Any, Any, None]] | None = None, connectable: bool = True, ) -> None: """Initialize the processor.""" super().__init__(hass, logger, address, mode, update_method, connectable) self._needs_poll_method = needs_poll_method self._poll_method = poll_method self._last_poll: float | None = None self.last_poll_successful = True # We keep the last service info in case the poller needs to refer to # e.g. its BLEDevice self._last_service_info: BluetoothServiceInfoBleak | None = None if poll_debouncer is None: poll_debouncer = Debouncer( hass, logger, cooldown=POLL_DEFAULT_COOLDOWN, immediate=POLL_DEFAULT_IMMEDIATE, function=self._async_poll, ) else: poll_debouncer.function = self._async_poll self._debounced_poll = poll_debouncer
def __init__( self, hass: HomeAssistant, host: str, ) -> None: """Initialize DataUpdateCoordinator to gather data for specific device.""" self.host = host self.device: WifiLedBulb | None = None update_interval = timedelta(seconds=5) super().__init__( hass, _LOGGER, name=host, update_interval=update_interval, # We don't want an immediate refresh since the device # takes a moment to reflect the state change request_refresh_debouncer=Debouncer(hass, _LOGGER, cooldown=REQUEST_REFRESH_DELAY, immediate=False), )
def __init__(self, hass, api: PhilipsTV) -> None: """Set up the coordinator.""" self.api = api self._notify_future: Optional[asyncio.Task] = None @callback def _update_listeners(): for update_callback in self._listeners: update_callback() self.turn_on = PluggableAction(_update_listeners) super().__init__( hass, LOGGER, name=DOMAIN, update_interval=timedelta(seconds=30), request_refresh_debouncer=Debouncer( hass, LOGGER, cooldown=2.0, immediate=False ), )
def __init__( self, hass: HomeAssistant, device: SmartDevice, ) -> None: """Initialize DataUpdateCoordinator to gather data for specific SmartPlug.""" self.device = device self.update_children = True update_interval = timedelta(seconds=10) super().__init__( hass, _LOGGER, name=device.host, update_interval=update_interval, # We don't want an immediate refresh since the device # takes a moment to reflect the state change request_refresh_debouncer=Debouncer(hass, _LOGGER, cooldown=REQUEST_REFRESH_DELAY, immediate=False), )