class FullyKioskDataUpdateCoordinator(DataUpdateCoordinator): """Define an object to hold Fully Kiosk Browser data.""" def __init__(self, hass: HomeAssistantType, session: ClientSession, host, port, password): """Initialize.""" self.fully = FullyKiosk(session, host, port, password) super().__init__( hass, _LOGGER, name=f"{host} deviceInfo", update_interval=timedelta(seconds=UPDATE_INTERVAL), ) async def _async_update_data(self): """Update data via library.""" try: with timeout(15): """Get device info and settings in parallel""" result = await asyncio.gather(self.fully.getDeviceInfo(), self.fully.getSettings()) """Store settings under settings key in data""" result[0]["settings"] = result[1] return result[0] except (FullyKioskError, ClientConnectorError) as error: raise UpdateFailed(error) from error
class FullyKioskDataUpdateCoordinator(DataUpdateCoordinator): """Define an object to hold Fully Kiosk Browser data.""" def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: """Initialize.""" self.fully = FullyKiosk( async_get_clientsession(hass), entry.data[CONF_HOST], DEFAULT_PORT, entry.data[CONF_PASSWORD], ) super().__init__( hass, LOGGER, name=entry.data[CONF_HOST], update_interval=UPDATE_INTERVAL, ) async def _async_update_data(self) -> dict[str, Any]: """Update data via library.""" try: async with timeout(15): # Get device info and settings in parallel result = await asyncio.gather(self.fully.getDeviceInfo(), self.fully.getSettings()) # Store settings under settings key in data result[0]["settings"] = result[1] return cast(dict[str, Any], result[0]) except FullyKioskError as error: raise UpdateFailed(error) from error
def __init__(self, hass: HomeAssistantType, session: ClientSession, host, port, password): """Initialize.""" self.fully = FullyKiosk(session, host, port, password) super().__init__( hass, _LOGGER, name=f"{host} deviceInfo", update_interval=timedelta(seconds=UPDATE_INTERVAL), )
def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: """Initialize.""" self.fully = FullyKiosk( async_get_clientsession(hass), entry.data[CONF_HOST], DEFAULT_PORT, entry.data[CONF_PASSWORD], ) super().__init__( hass, LOGGER, name=entry.data[CONF_HOST], update_interval=UPDATE_INTERVAL, )
async def validate_input(hass: core.HomeAssistant, data): """Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user. """ # TODO validate the data can be used to set up a connection. # If your PyPI package is not built with async, pass your methods # to the executor: # await hass.async_add_executor_job( # your_validate_func, data["username"], data["password"] # ) fully = FullyKiosk(data["host"], data["port"], data["password"]) # try: deviceInfo = await hass.async_add_executor_job(fully.getDeviceInfo) # except: # raise InvalidAuth # If you cannot connect: # throw CannotConnect # If the authentication is wrong: # InvalidAuth # Return info that you want to store in the config entry. return { "title": f"{deviceInfo['deviceName']} {deviceInfo['deviceID']}", "host": data["host"], "port": data["port"], "password": data["password"], }
async def async_step_user(self, user_input: dict[str, Any] | None = None ) -> FlowResult: """Handle the initial step.""" errors: dict[str, str] = {} if user_input is not None: fully = FullyKiosk( async_get_clientsession(self.hass), user_input[CONF_HOST], DEFAULT_PORT, user_input[CONF_PASSWORD], ) try: async with timeout(15): device_info = await fully.getDeviceInfo() except (ClientConnectorError, FullyKioskError, asyncio.TimeoutError): errors["base"] = "cannot_connect" except Exception: # pylint: disable=broad-except LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: await self.async_set_unique_id(device_info["deviceID"]) self._abort_if_unique_id_configured(updates=user_input) return self.async_create_entry( title=device_info["deviceName"], data=user_input | {CONF_MAC: format_mac(device_info["Mac"])}, ) return self.async_show_form( step_id="user", data_schema=vol.Schema({ vol.Required(CONF_HOST): str, vol.Required(CONF_PASSWORD): str, }), errors=errors, )
async def validate_input(hass: core.HomeAssistant, data): """Validate the user input allows us to connect.""" session = async_get_clientsession(hass) fully = FullyKiosk(session, data["host"], data["port"], data["password"]) try: with timeout(15): deviceInfo = await fully.getDeviceInfo() except (FullyKioskError, ClientConnectorError): raise CannotConnect # If you cannot connect: # throw CannotConnect # If the authentication is wrong: # InvalidAuth # Return info that you want to store in the config entry. return { "title": f"{deviceInfo['deviceName']} {deviceInfo['deviceID']}", "host": data["host"], "port": data["port"], "password": data["password"], }
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up Fully Kiosk Browser from a config entry.""" hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = {} config = entry.data fully = FullyKiosk(config[CONF_HOST], config[CONF_PORT], config[CONF_PASSWORD]) async def async_update_data(): """Fetch data from REST API.""" data = await hass.async_add_executor_job(fully.getDeviceInfo) return data coordinator = DataUpdateCoordinator( hass, _LOGGER, name="deviceInfo", update_method=async_update_data, update_interval=timedelta(seconds=30), ) await coordinator.async_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady hass.data[DOMAIN][entry.entry_id][COORDINATOR] = coordinator hass.data[DOMAIN][entry.entry_id][CONTROLLER] = fully for component in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, component)) return True