async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Elgato Light from a config entry.""" session = async_get_clientsession(hass) elgato = Elgato( entry.data[CONF_HOST], port=entry.data[CONF_PORT], session=session, ) async def _async_update_data() -> State: """Fetch Elgato data.""" try: return await elgato.state() except ElgatoConnectionError as err: raise UpdateFailed(err) from err coordinator: DataUpdateCoordinator[State] = DataUpdateCoordinator( hass, LOGGER, name=f"{DOMAIN}_{entry.data[CONF_HOST]}", update_interval=SCAN_INTERVAL, update_method=_async_update_data, ) await coordinator.async_config_entry_first_refresh() info = await elgato.info() hass.data.setdefault(DOMAIN, {})[entry.entry_id] = HomeAssistantElgatoData( client=elgato, coordinator=coordinator, info=info, ) hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True
async def _get_elgato_info(self, host: str, port: int) -> Info: """Get device information from an Elgato Key Light device.""" session = async_get_clientsession(self.hass) elgato = Elgato( host, port=port, session=session, ) return await elgato.info()
async def main(): """Show example on controlling your Elgato Key Light device.""" async with Elgato("elgato-key-light.local") as elgato: info: Info = await elgato.info() print(info) state: State = await elgato.state() print(state) # Toggle the Key Light await elgato.light(on=(not state.on))
async def test_unexpected_response(aresponses): """Test unexpected response handling.""" aresponses.add( "example.com:9123", "/elgato/test", "GET", aresponses.Response(text="OMG PUPPIES!", status=200), ) async with aiohttp.ClientSession() as session: elgato = Elgato("example.com", session=session) with pytest.raises(ElgatoError): assert await elgato._request("test")
async def test_timeout(aresponses): """Test request timeout from the Elgato Key Light.""" # Faking a timeout by sleeping async def response_handler(_): await asyncio.sleep(2) return aresponses.Response(body="Goodmorning!") aresponses.add("example.com:9123", "/elgato/test", "GET", response_handler) async with aiohttp.ClientSession() as session: elgato = Elgato("example.com", session=session, request_timeout=1) with pytest.raises(ElgatoConnectionError): assert await elgato._request("test")
async def test_internal_session(aresponses): """Test JSON response is handled correctly.""" aresponses.add( "example.com:9123", "/elgato/test", "GET", aresponses.Response( status=200, headers={"Content-Type": "application/json"}, text='{"status": "ok"}', ), ) async with Elgato("example.com") as elgato: response = await elgato._request("test") assert response["status"] == "ok"
async def test_put_request(aresponses): """Test PUT requests are handled correctly.""" aresponses.add( "example.com:9123", "/elgato/test", "PUT", aresponses.Response( status=200, headers={"Content-Type": "application/json"}, text='{"status": "ok"}', ), ) async with aiohttp.ClientSession() as session: elgato = Elgato("example.com", session=session) response = await elgato._request("test", data={}) assert response["status"] == "ok"
async def test_request_port(aresponses): """Test the Elgato Key Light running on non-standard port.""" aresponses.add( "example.com:3333", "/elgato/test", "GET", aresponses.Response( status=200, headers={"Content-Type": "application/json"}, text='{"status": "ok"}', ), ) async with aiohttp.ClientSession() as session: elgato = Elgato("example.com", port=3333, session=session) response = await elgato._request("test") assert response["status"] == "ok"
async def test_state(aresponses): """Test getting Elgato Key Light state.""" aresponses.add( "example.com:9123", "/elgato/lights", "GET", aresponses.Response( status=200, headers={"Content-Type": "application/json"}, text=load_fixture("state.json"), ), ) async with aiohttp.ClientSession() as session: elgato = Elgato("example.com", session=session) state: State = await elgato.state() assert state assert state.brightness == 21 assert state.on assert state.temperature == 297
async def _get_elgato_serial_number(self, raise_on_progress: bool = True) -> None: """Get device information from an Elgato Light device.""" session = async_get_clientsession(self.hass) elgato = Elgato( host=self.host, port=self.port, session=session, ) info = await elgato.info() # Check if already configured await self.async_set_unique_id( info.serial_number, raise_on_progress=raise_on_progress ) self._abort_if_unique_id_configured( updates={CONF_HOST: self.host, CONF_PORT: self.port, CONF_MAC: self.mac} ) self.serial_number = info.serial_number
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Elgato Light from a config entry.""" session = async_get_clientsession(hass) elgato = Elgato( entry.data[CONF_HOST], port=entry.data[CONF_PORT], session=session, ) # Ensure we can connect to it try: await elgato.info() except ElgatoConnectionError as exception: logging.getLogger(__name__).debug("Unable to connect: %s", exception) raise ConfigEntryNotReady from exception hass.data.setdefault(DOMAIN, {})[entry.entry_id] = elgato hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry) -> bool: """Set up Elgato Light from a config entry.""" session = async_get_clientsession(opp) elgato = Elgato( entry.data[CONF_HOST], port=entry.data[CONF_PORT], session=session, ) # Ensure we can connect to it try: await elgato.info() except ElgatoConnectionError as exception: logging.getLogger(__name__).debug("Unable to connect: %s", exception) raise ConfigEntryNotReady from exception opp.data.setdefault(DOMAIN, {}) opp.data[DOMAIN][entry.entry_id] = {DATA_ELGATO_CLIENT: elgato} opp.config_entries.async_setup_platforms(entry, PLATFORMS) return True
async def test_info(aresponses): """Test getting Elgato Key Light device information.""" aresponses.add( "example.com:9123", "/elgato/accessory-info", "GET", aresponses.Response( status=200, headers={"Content-Type": "application/json"}, text=load_fixture("info.json"), ), ) async with aiohttp.ClientSession() as session: elgato = Elgato("example.com", session=session) info: Info = await elgato.info() assert info assert info.display_name == "Frenck" assert info.firmware_build_number == 192 assert info.firmware_version == "1.0.3" assert info.hardware_board_type == 53 assert info.product_name == "Elgato Key Light" assert info.serial_number == "CN11A1A00001"
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Elgato Key Light from a config entry.""" session = async_get_clientsession(hass) elgato = Elgato( entry.data[CONF_HOST], port=entry.data[CONF_PORT], session=session, ) # Ensure we can connect to it try: await elgato.info() except ElgatoConnectionError as exception: raise ConfigEntryNotReady from exception hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = {DATA_ELGATO_CLIENT: elgato} hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, LIGHT_DOMAIN)) return True
async def test_change_state(aresponses): """Test changing Elgato Key Light State.""" async def response_handler(request): data = await request.json() assert data == { "numberOfLights": 1, "lights": [{ "on": 1, "brightness": 100, "temperature": 100 }], } return aresponses.Response( status=200, headers={"Content-Type": "application/json"}, text="{}", ) aresponses.add("example.com:9123", "/elgato/lights", "PUT", response_handler) async with aiohttp.ClientSession() as session: elgato = Elgato("example.com", session=session) await elgato.light(on=True, brightness=100, temperature=100)
async def set(on: bool): for ip in ips: async with Elgato(ip) as elgato: await elgato.light(on=on)
async def toggle(): async with Elgato(ips[0]) as elgato: state: State = await elgato.state() await set(not state.on)