async def async_step_user(self, user_input=None): """Handle a flow initialized by the user.""" errors = {} if user_input is not None: bulb = wizlight(user_input[CONF_HOST]) try: mac = await bulb.getMac() except WizLightTimeOutError: errors["base"] = "bulb_time_out" except ConnectionRefusedError: errors["base"] = "cannot_connect" except WizLightConnectionError: errors["base"] = "no_wiz_light" except AbortFlow: return self.async_abort(reason="single_instance_allowed") except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: await self.async_set_unique_id(mac) self._abort_if_unique_id_configured() return self.async_create_entry( title=user_input[CONF_NAME], data=user_input ) return self.async_show_form( step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors )
async def power_socket() -> AsyncGenerator[wizlight, None]: shutdown, port = await startup_bulb( module_name="ESP25_SOCKET_01", firmware_version="1.26.2" ) bulb = wizlight(ip="127.0.0.1", port=port) yield bulb await bulb.async_close() shutdown()
async def wall_switch() -> AsyncGenerator[wizlight, None]: shutdown, port = await startup_bulb( module_name="ESP01_DIMTRIACS_01", firmware_version="1.16.68" ) bulb = wizlight(ip="127.0.0.1", port=port) yield bulb await bulb.async_close() shutdown()
async def squire() -> AsyncGenerator[wizlight, None]: shutdown, port = await startup_bulb( module_name="ESP20_DHRGB_01B", firmware_version="1.21.40" ) bulb = wizlight(ip="127.0.0.1", port=port) yield bulb await bulb.async_close() shutdown()
async def no_module_bulb() -> AsyncGenerator[wizlight, None]: shutdown, port = await startup_bulb( module_name="MISSING", firmware_version="1.16.64" ) bulb = wizlight(ip="127.0.0.1", port=port) yield bulb await bulb.async_close() shutdown()
async def set_state(ip, k, brightness): """Turn a given bulb on.""" click.echo("Turning on %s" % ip) bulb = wizlight(ip) if bulb and k <= 6800 and k >= 1000 and brightness >= 0 and brightness <= 256: await bulb.set_state(PilotBuilder(colortemp=k, brightness=brightness)) else: click.echo("Error - values are not correct. Type --help for help.")
async def socket_push() -> AsyncGenerator[wizlight, None]: shutdown, port = await startup_bulb(module_name="ESP10_SOCKET_06", firmware_version="1.25.0") with patch("pywizlight.push_manager.RESPOND_PORT", port): bulb = wizlight(ip="127.0.0.1", port=port) yield bulb await bulb.async_close() shutdown()
async def rgbww_bulb() -> AsyncGenerator[wizlight, None]: shutdown, port = await startup_bulb( module_name="ESP01_SHRGB1C_31", firmware_version="1.17.1" ) bulb = wizlight(ip="127.0.0.1", port=port) yield bulb await bulb.async_close() shutdown()
async def light_strip() -> AsyncGenerator[wizlight, None]: shutdown, port = await startup_bulb( module_name="ESP03_SHRGB3_01ABI", firmware_version="1.16.64" ) bulb = wizlight(ip="127.0.0.1", port=port) yield bulb await bulb.async_close() shutdown()
async def dimmable_bulb() -> AsyncGenerator[wizlight, None]: shutdown, port = await startup_bulb( module_name="1.8.0-MISSING-TYPEID-0", firmware_version="1.8.0" ) bulb = wizlight(ip="127.0.0.1", port=port) yield bulb await bulb.async_close() shutdown()
async def discover_lights(broadcast_space="255.255.255.255") -> list: """Find lights and return list with wizlight objects.""" discovered_IPs = await find_wizlights(broadcast_address=broadcast_space) # empty list for adding bulbs bulbs = [] # create light entities from register for entries in discovered_IPs: bulbs.append(wizlight(ip=entries.ip_address, mac=entries.mac_address)) return bulbs
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the WiZ Light platform.""" # Assign configuration variables. # The configuration check takes care they are present. ip_address = config[CONF_HOST] bulb = wizlight(ip_address) # Add devices async_add_entities([WizBulb(bulb, config[CONF_NAME])])
async def set_state(ip: str, k: int, brightness: int) -> None: """Set the current state of a given bulb.""" click.echo(f"Turning on {ip}") bulb = wizlight(ip) if bulb and 1000 <= k <= 6800 and 0 <= brightness <= 255: await bulb.set_state(PilotBuilder(colortemp=k, brightness=brightness)) else: click.echo("Error - values are not correct. Type --help for help.") await bulb.async_close()
async def discover_lights( broadcast_space: str = "255.255.255.255", wait_time: float = DEFAULT_WAIT_TIME) -> List[wizlight]: """Find lights and return list with wizlight objects.""" discovered_IPs = await find_wizlights(wait_time=wait_time, broadcast_address=broadcast_space) return [ wizlight(ip=entry.ip_address, mac=entry.mac_address) for entry in discovered_IPs ]
async def state(ip: str) -> None: """Get the current state of a given bulb.""" click.echo(f"Get the state from {ip}") bulb = wizlight(ip) bulb_state = await bulb.updateState() if bulb_state: click.echo(bulb_state.pilotResult) else: click.echo("Did not get state from bulb") await bulb.async_close()
async def run_bulb_automation(): loop = asyncio.get_event_loop() bulb1 = wizlight('192.168.178.95') # bulb2 = wizlight('192.168.1.7') # await asyncio.gather(testbulb(bulb1), testbulb(bulb2), loop = loop) state = await bulb1.updateState() await bulb1.turn_on(PilotBuilder(scene=14)) state = await bulb1.updateState() await asyncio.sleep(0.5) await bulb1.turn_on(PilotBuilder()) #rhythm state = await bulb1.updateState()
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up the wiz_light integration from a config entry.""" ip_address = entry.data.get(CONF_HOST) _LOGGER.debug("Get bulb with IP: %s", ip_address) bulb = wizlight(ip_address) hass.data[DOMAIN][entry.unique_id] = bulb for component in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, component)) return True
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the WiZ switch platform.""" # Assign configuration variables. # The configuration check takes care they are present. ip_address = config[CONF_HOST] switch = wizlight(ip_address) async_add_entities([WizPlug(switch, config[CONF_NAME])])
async def _async_connect_discovered_or_abort(self) -> None: """Connect to the device and verify its responding.""" device = self._discovered_device bulb = wizlight(device.ip_address) try: bulbtype = await bulb.get_bulbtype() except WIZ_CONNECT_EXCEPTIONS as ex: _LOGGER.debug( "Failed to connect to %s during discovery: %s", device.ip_address, ex, exc_info=True, ) raise AbortFlow("cannot_connect") from ex self._name = name_from_bulb_type_and_mac(bulbtype, device.mac_address)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the WiZ Light platform from legacy config.""" # Assign configuration variables. # The configuration check takes care they are present. ip_address = config[CONF_HOST] try: bulb = wizlight(ip_address) # Add devices async_add_entities([WizBulb(bulb, config[CONF_NAME])], update_before_add=True) except WizLightConnectionError: _LOGGER.error("Can't add bulb with ip %s.", ip_address)
async def main(): bulbs = await discovery.discover_lights(broadcast_space="10.0.0.255") lights = [] for i in range(len(bulbs)): light = wizlight(bulbs[i].ip) lights.append(light) print(len(lights), "lights found.") while True: rgb_vals = await screen_average_colors() #bright_val = calc_brightness(rgb_vals) for light in lights: await light.turn_on(PilotBuilder(rgb=rgb_vals))
async def main(): bulbs = await discovery.discover_lights(broadcast_space="10.0.0.255") lights = [] for i in range(len(bulbs)): light = wizlight(bulbs[i].ip) lights.append(light) print(lights) while True: rgb_vals_left, rgb_vals_right = await dual_screen_average_colors() #bright_val = calc_brightness(rgb_vals) await lights[0].turn_on(PilotBuilder(rgb=rgb_vals_left)) await lights[1].turn_on(PilotBuilder(rgb=rgb_vals_right))
async def async_step_pick_device(self, user_input: dict[str, Any] | None = None ) -> FlowResult: """Handle the step to pick discovered device.""" if user_input is not None: device = self._discovered_devices[user_input[CONF_DEVICE]] await self.async_set_unique_id(device.mac_address, raise_on_progress=False) bulb = wizlight(device.ip_address) try: bulbtype = await bulb.get_bulbtype() except WIZ_CONNECT_EXCEPTIONS: return self.async_abort(reason="cannot_connect") else: return self.async_create_entry( title=name_from_bulb_type_and_mac(bulbtype, device.mac_address), data={CONF_HOST: device.ip_address}, ) current_unique_ids = self._async_current_ids() current_hosts = { entry.data[CONF_HOST] for entry in self._async_current_entries(include_ignore=False) } discovered_devices = await async_discover_devices( self.hass, DISCOVER_SCAN_TIMEOUT) self._discovered_devices = { device.mac_address: device for device in discovered_devices } devices_name = { mac: f"{DEFAULT_NAME} {_short_mac(mac)} ({device.ip_address})" for mac, device in self._discovered_devices.items() if mac not in current_unique_ids and device.ip_address not in current_hosts } # Check if there is at least one device if not devices_name: return self.async_abort(reason="no_devices_found") return self.async_show_form( step_id="pick_device", data_schema=vol.Schema( {vol.Required(CONF_DEVICE): vol.In(devices_name)}), )
def api_factory(ip: str) -> Any: api = None try: from pywizlight import wizlight from pywizlight.exceptions import WizLightConnectionError, WizLightTimeOutError try: api = wizlight(ip, True) except (WizLightConnectionError, WizLightTimeOutError): sys.exit( wording.get('connection_no').format('WIZ LIGHT') + wording.get('exclamation_mark')) return api except ImportError: sys.exit( wording.get('package_no').format('WIZ LIGHT') + wording.get('exclamation_mark'))
async def plex_hook(request: Request, db: Session = Depends(get_db)): form = await request.form() payload = json.loads(form["payload"]) client_name = payload["Player"]["title"] client_id = payload["Player"]["uuid"] crud.upsert_device(db, client_name, client_id) config = crud.get_config_by_device(db, client_id) event = payload["event"] bulbs = [wizlight(x.ip) for x in config.lights] tasks = [] for bulb in bulbs: if event == "media.play" or event == "media.resume": tasks.append(asyncio.create_task(bulb.turn_off())) elif event == "media.pause" or event == "media.stop": tasks.append(asyncio.create_task(bulb.turn_on())) await asyncio.gather(*tasks)
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up the wiz_light integration from a config entry.""" ip_address = entry.data.get(CONF_HOST) _LOGGER.debug("Get bulb with IP: %s", ip_address) try: bulb = wizlight(ip_address) scenes = await bulb.getSupportedScenes() await bulb.getMac() except ( WizLightTimeOutError, WizLightConnectionError, ConnectionRefusedError, ) as err: raise ConfigEntryNotReady from err hass.data.setdefault(DOMAIN, {})[entry.entry_id] = WizData(bulb=bulb, scenes=scenes) hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up the wiz integration from a config entry.""" ip_address = entry.data[CONF_HOST] _LOGGER.debug("Get bulb with IP: %s", ip_address) bulb = wizlight(ip_address) try: scenes = await bulb.getSupportedScenes() await bulb.getMac() except WIZ_CONNECT_EXCEPTIONS as err: await bulb.async_close() raise ConfigEntryNotReady(f"{ip_address}: {err}") from err if bulb.mac != entry.unique_id: # The ip address of the bulb has changed and its likely offline # and another WiZ device has taken the IP. Avoid setting up # since its the wrong device. As soon as the device comes back # online the ip will get updated and setup will proceed. raise ConfigEntryNotReady( "Found bulb {bulb.mac} at {ip_address}, expected {entry.unique_id}" ) async def _async_update() -> None: """Update the WiZ device.""" try: await bulb.updateState() except WIZ_EXCEPTIONS as ex: raise UpdateFailed(f"Failed to update device at {ip_address}: {ex}") from ex coordinator = DataUpdateCoordinator( hass=hass, logger=_LOGGER, name=entry.title, update_interval=timedelta(seconds=15), update_method=_async_update, # 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 ), ) try: await coordinator.async_config_entry_first_refresh() except ConfigEntryNotReady as err: await bulb.async_close() raise err async def _async_shutdown_on_stop(event: Event) -> None: await bulb.async_close() entry.async_on_unload( hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_shutdown_on_stop) ) @callback def _async_push_update(state: PilotParser) -> None: """Receive a push update.""" _LOGGER.debug("%s: Got push update: %s", bulb.mac, state.pilotResult) coordinator.async_set_updated_data(None) if state.get_source() == PIR_SOURCE: async_dispatcher_send(hass, SIGNAL_WIZ_PIR.format(bulb.mac)) await bulb.start_push(_async_push_update) bulb.set_discovery_callback(lambda bulb: async_trigger_discovery(hass, [bulb])) hass.data.setdefault(DOMAIN, {})[entry.entry_id] = WizData( coordinator=coordinator, bulb=bulb, scenes=scenes ) hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True
def data(self): """Init the bad and good bulbs.""" pytest.correct_bulb = wizlight(ip="127.0.0.1") pytest.bad_bulb = wizlight(ip="1.1.1.1")
async def main(): light = wizlight(addr) await light.turn_on(pb)
async def state(ip): """Get the current state of a given bulb.""" click.echo("Get the state from %s" % ip) bulb = wizlight(ip) state = await bulb.updateState() click.echo(state.__dict__["pilotResult"])