def __init__(self, polyglot): super().__init__(polyglot) self.name = 'Wemo Node Server' self.address = 'wemons' self.primary = self.address self.subscription_registry = pywemo.SubscriptionRegistry() LOGGER.info('Wemo Controler Initialized')
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up a wemo config entry.""" config = hass.data[DOMAIN].pop("config") # Keep track of WeMo device subscriptions for push updates registry = hass.data[DOMAIN]["registry"] = pywemo.SubscriptionRegistry() await hass.async_add_executor_job(registry.start) # Respond to discovery requests from WeMo devices. discovery_responder = pywemo.ssdp.DiscoveryResponder(registry.port) await hass.async_add_executor_job(discovery_responder.start) static_conf = config.get(CONF_STATIC, []) wemo_dispatcher = WemoDispatcher(entry) wemo_discovery = WemoDiscovery(hass, wemo_dispatcher, static_conf) async def async_stop_wemo(event): """Shutdown Wemo subscriptions and subscription thread on exit.""" _LOGGER.debug("Shutting down WeMo event subscriptions") await hass.async_add_executor_job(registry.stop) await hass.async_add_executor_job(discovery_responder.stop) wemo_discovery.async_stop_discovery() entry.async_on_unload( hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, async_stop_wemo) ) # Need to do this at least once in case statics are defined and discovery is disabled await wemo_discovery.discover_statics() if config.get(CONF_DISCOVERY, DEFAULT_DISCOVERY): await wemo_discovery.async_discover_and_schedule() return True
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry): """Set up a wemo config entry.""" config = opp.data[DOMAIN].pop("config") # Keep track of WeMo device subscriptions for push updates registry = opp.data[DOMAIN]["registry"] = pywemo.SubscriptionRegistry() await opp.async_add_executor_job(registry.start) static_conf = config.get(CONF_STATIC, []) wemo_dispatcher = WemoDispatcher(entry) wemo_discovery = WemoDiscovery(opp, wemo_dispatcher, static_conf) async def async_stop_wemo(event): """Shutdown Wemo subscriptions and subscription thread on exit.""" _LOGGER.debug("Shutting down WeMo event subscriptions") await opp.async_add_executor_job(registry.stop) wemo_discovery.async_stop_discovery() entry.async_on_unload( opp.bus.async_listen_once(EVENT_OPENPEERPOWER_STOP, async_stop_wemo)) # Need to do this at least once in case statics are defined and discovery is disabled await wemo_discovery.discover_statics() if config.get(CONF_DISCOVERY, DEFAULT_DISCOVERY): await wemo_discovery.async_discover_and_schedule() return True
def setup_platform(hass, config, add_devices_callback, discovery_info=None): """ Find and return WeMo switches. """ import pywemo import pywemo.discovery as discovery global _WEMO_SUBSCRIPTION_REGISTRY if _WEMO_SUBSCRIPTION_REGISTRY is None: _WEMO_SUBSCRIPTION_REGISTRY = pywemo.SubscriptionRegistry() _WEMO_SUBSCRIPTION_REGISTRY.start() def stop_wemo(event): """ Shutdown Wemo subscriptions and subscription thread on exit""" _LOGGER.info("Shutting down subscriptions.") _WEMO_SUBSCRIPTION_REGISTRY.stop() hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_wemo) if discovery_info is not None: location = discovery_info[2] mac = discovery_info[3] device = discovery.device_from_description(location, mac) if device: add_devices_callback([WemoSwitch(device)]) return _LOGGER.info("Scanning for WeMo devices.") switches = pywemo.discover_devices() # Filter out the switches and wrap in WemoSwitch object add_devices_callback([ WemoSwitch(switch) for switch in switches if isinstance(switch, pywemo.Switch) ])
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up a wemo config entry.""" config = hass.data[DOMAIN].pop("config") # Keep track of WeMo device subscriptions for push updates registry = hass.data[DOMAIN]["registry"] = pywemo.SubscriptionRegistry() await hass.async_add_executor_job(registry.start) wemo_dispatcher = WemoDispatcher(entry) wemo_discovery = WemoDiscovery(hass, wemo_dispatcher) async def async_stop_wemo(event): """Shutdown Wemo subscriptions and subscription thread on exit.""" _LOGGER.debug("Shutting down WeMo event subscriptions") await hass.async_add_executor_job(registry.stop) wemo_discovery.async_stop_discovery() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, async_stop_wemo) static_conf = config.get(CONF_STATIC, []) if static_conf: _LOGGER.debug("Adding statically configured WeMo devices") for device in await asyncio.gather(*[ hass.async_add_executor_job(validate_static_config, host, port) for host, port in static_conf ]): if device: wemo_dispatcher.async_add_unique_device(hass, device) if config.get(CONF_DISCOVERY, DEFAULT_DISCOVERY): await wemo_discovery.async_discover_and_schedule() return True
def setup(hass, config): """Common setup for WeMo devices.""" import pywemo global SUBSCRIPTION_REGISTRY SUBSCRIPTION_REGISTRY = pywemo.SubscriptionRegistry() SUBSCRIPTION_REGISTRY.start() def stop_wemo(event): """Shutdown Wemo subscriptions and subscription thread on exit.""" _LOGGER.info("Shutting down subscriptions.") SUBSCRIPTION_REGISTRY.stop() hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_wemo) def discovery_dispatch(service, discovery_info): """Dispatcher for WeMo discovery events.""" # name, model, location, mac _, model_name, _, _, serial = discovery_info # Only register a device once if serial in KNOWN_DEVICES: return _LOGGER.debug('Discovered unique device %s', serial) KNOWN_DEVICES.append(serial) component = WEMO_MODEL_DISPATCH.get(model_name, 'switch') discovery.load_platform(hass, component, DOMAIN, discovery_info, config) discovery.listen(hass, SERVICE_WEMO, discovery_dispatch) hass.add_job(wemo_startup_scan, hass, config) return True
def setup(hass, config): """Common setup for WeMo devices.""" import pywemo global SUBSCRIPTION_REGISTRY SUBSCRIPTION_REGISTRY = pywemo.SubscriptionRegistry() SUBSCRIPTION_REGISTRY.start() def stop_wemo(event): """Shutdown Wemo subscriptions and subscription thread on exit.""" _LOGGER.info("Shutting down subscriptions.") SUBSCRIPTION_REGISTRY.stop() hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_wemo) def discovery_dispatch(service, discovery_info): """Dispatcher for WeMo discovery events.""" # name, model, location, mac _, model_name, _, _, serial = discovery_info # Only register a device once if serial in KNOWN_DEVICES: return _LOGGER.debug('Discovered unique device %s', serial) KNOWN_DEVICES.append(serial) component = WEMO_MODEL_DISPATCH.get(model_name, 'switch') discovery.load_platform(hass, component, DOMAIN, discovery_info, config) discovery.listen(hass, SERVICE_WEMO, discovery_dispatch) _LOGGER.info("Scanning for WeMo devices.") devices = [(device.host, device) for device in pywemo.discover_devices()] # Add static devices from the config file. devices.extend((address, None) for address in config.get(DOMAIN, {}).get(CONF_STATIC, [])) for address, device in devices: port = pywemo.ouimeaux_device.probe_wemo(address) if not port: _LOGGER.warning('Unable to probe wemo at %s', address) continue _LOGGER.info('Adding wemo at %s:%i', address, port) url = 'http://%s:%i/setup.xml' % (address, port) if device is None: device = pywemo.discovery.device_from_description(url, None) discovery_info = (device.name, device.model_name, url, device.mac, device.serialnumber) discovery.discover(hass, SERVICE_WEMO, discovery_info) return True
async def async_setup_entry(hass, entry): """Set up a wemo config entry.""" config = hass.data[DOMAIN].pop("config") # Keep track of WeMo device subscriptions for push updates registry = hass.data[DOMAIN]["registry"] = pywemo.SubscriptionRegistry() await hass.async_add_executor_job(registry.start) def stop_wemo(event): """Shutdown Wemo subscriptions and subscription thread on exit.""" _LOGGER.debug("Shutting down WeMo event subscriptions") registry.stop() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_wemo) devices = {} static_conf = config.get(CONF_STATIC, []) if static_conf: _LOGGER.debug("Adding statically configured WeMo devices...") for device in await asyncio.gather(*[ hass.async_add_executor_job(validate_static_config, host, port) for host, port in static_conf ]): if device is None: continue devices.setdefault(device.serialnumber, device) if config.get(CONF_DISCOVERY, DEFAULT_DISCOVERY): _LOGGER.debug("Scanning network for WeMo devices...") for device in await hass.async_add_executor_job(pywemo.discover_devices ): devices.setdefault( device.serialnumber, device, ) loaded_components = set() for device in devices.values(): _LOGGER.debug( "Adding WeMo device at %s:%i (%s)", device.host, device.port, device.serialnumber, ) component = WEMO_MODEL_DISPATCH.get(device.model_name, "switch") # Three cases: # - First time we see component, we need to load it and initialize the backlog # - Component is being loaded, add to backlog # - Component is loaded, backlog is gone, dispatch discovery if component not in loaded_components: hass.data[DOMAIN]["pending"][component] = [device] loaded_components.add(component) hass.async_create_task( hass.config_entries.async_forward_entry_setup( entry, component)) elif component in hass.data[DOMAIN]["pending"]: hass.data[DOMAIN]["pending"][component].append(device) else: async_dispatcher_send( hass, f"{DOMAIN}.{component}", device, ) return True
def setup(hass, config): """Set up for WeMo devices.""" import pywemo global SUBSCRIPTION_REGISTRY SUBSCRIPTION_REGISTRY = pywemo.SubscriptionRegistry() SUBSCRIPTION_REGISTRY.start() def stop_wemo(event): """Shutdown Wemo subscriptions and subscription thread on exit.""" _LOGGER.info("Shutting down subscriptions.") SUBSCRIPTION_REGISTRY.stop() hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_wemo) def discovery_dispatch(service, discovery_info): """Dispatcher for WeMo discovery events.""" # name, model, location, mac model_name = discovery_info.get('model_name') serial = discovery_info.get('serial') # Only register a device once if serial in KNOWN_DEVICES: return _LOGGER.debug('Discovered unique device %s', serial) KNOWN_DEVICES.append(serial) component = WEMO_MODEL_DISPATCH.get(model_name, 'switch') discovery.load_platform(hass, component, DOMAIN, discovery_info, config) discovery.listen(hass, SERVICE_WEMO, discovery_dispatch) def setup_url_for_device(device): """Determine setup.xml url for given device.""" return 'http://{}:{}/setup.xml'.format(device.host, device.port) def setup_url_for_address(host, port): """Determine setup.xml url for given host and port pair.""" if not port: port = pywemo.ouimeaux_device.probe_wemo(host) if not port: return None return 'http://{}:{}/setup.xml'.format(host, port) devices = [] for host, port in config.get(DOMAIN, {}).get(CONF_STATIC, []): url = setup_url_for_address(host, port) if not url: _LOGGER.error('Unable to get description url for %s', '{}:{}'.format(host, port) if port else host) return False try: device = pywemo.discovery.device_from_description(url, None) except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as err: _LOGGER.error('Unable to access %s (%s)', url, err) return False devices.append((url, device)) _LOGGER.info("Scanning for WeMo devices.") devices.extend((setup_url_for_device(device), device) for device in pywemo.discover_devices()) for url, device in devices: _LOGGER.info('Adding wemo at %s:%i', device.host, device.port) discovery_info = { 'model_name': device.model_name, 'serial': device.serialnumber, 'mac_address': device.mac, 'ssdp_description': url, } discovery.discover(hass, SERVICE_WEMO, discovery_info) return True
def setup(hass, config): """Set up for WeMo devices.""" import pywemo # Keep track of WeMo devices devices = [] # Keep track of WeMo device subscriptions for push updates global SUBSCRIPTION_REGISTRY SUBSCRIPTION_REGISTRY = pywemo.SubscriptionRegistry() SUBSCRIPTION_REGISTRY.start() def stop_wemo(event): """Shutdown Wemo subscriptions and subscription thread on exit.""" _LOGGER.debug("Shutting down WeMo event subscriptions") SUBSCRIPTION_REGISTRY.stop() hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_wemo) def setup_url_for_device(device): """Determine setup.xml url for given device.""" return 'http://{}:{}/setup.xml'.format(device.host, device.port) def setup_url_for_address(host, port): """Determine setup.xml url for given host and port pair.""" if not port: port = pywemo.ouimeaux_device.probe_wemo(host) if not port: return None return 'http://{}:{}/setup.xml'.format(host, port) def discovery_dispatch(service, discovery_info): """Dispatcher for incoming WeMo discovery events.""" # name, model, location, mac model_name = discovery_info.get('model_name') serial = discovery_info.get('serial') # Only register a device once if serial in KNOWN_DEVICES: _LOGGER.debug("Ignoring known device %s %s", service, discovery_info) return _LOGGER.debug("Discovered unique WeMo device: %s", serial) KNOWN_DEVICES.append(serial) component = WEMO_MODEL_DISPATCH.get(model_name, 'switch') discovery.load_platform(hass, component, DOMAIN, discovery_info, config) discovery.listen(hass, SERVICE_WEMO, discovery_dispatch) def discover_wemo_devices(now): """Run discovery for WeMo devices.""" _LOGGER.debug("Beginning WeMo device discovery...") _LOGGER.debug("Adding statically configured WeMo devices...") for host, port in config.get(DOMAIN, {}).get(CONF_STATIC, []): url = setup_url_for_address(host, port) if not url: _LOGGER.error('Unable to get description url for WeMo at: %s', '{}:{}'.format(host, port) if port else host) continue try: device = pywemo.discovery.device_from_description(url, None) except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as err: _LOGGER.error("Unable to access WeMo at %s (%s)", url, err) continue if not [ d[1] for d in devices if d[1].serialnumber == device.serialnumber ]: devices.append((url, device)) if config.get(DOMAIN, {}).get(CONF_DISCOVERY): _LOGGER.debug("Scanning network for WeMo devices...") for device in pywemo.discover_devices(): if not [ d[1] for d in devices if d[1].serialnumber == device.serialnumber ]: devices.append((setup_url_for_device(device), device)) for url, device in devices: _LOGGER.debug("Adding WeMo device at %s:%i", device.host, device.port) discovery_info = { 'model_name': device.model_name, 'serial': device.serialnumber, 'mac_address': device.mac, 'ssdp_description': url, } discovery.discover(hass, SERVICE_WEMO, discovery_info) _LOGGER.debug("WeMo device discovery has finished") hass.bus.listen_once(EVENT_HOMEASSISTANT_START, discover_wemo_devices) return True
self.regsub.on(self.real_switch, "BinaryState", self.toggle_callback) self.regsub.on(self.dumb_switch, "BinaryState", self.toggle_callback) print('"{}" devices callback registration complete\n'.format( self.name)) def toggle_callback(self, device, cb_type, value): print(" {:16}{:24}{:24}{:12}".format(self.name, device.name, cb_type, value)) if device.mac == self.real_switch.mac: self.dumb_switch.set_state(value) if device.mac == self.dumb_switch.mac: self.real_switch.set_state(value) if __name__ == "__main__": regsub = pywemo.SubscriptionRegistry() # three way switches: (Name, dummy switch MAC, real_switch switch MAC) kitchen = ThreeWaySwitch(regsub, "Kitchen Dimmer", "24F5A25D64CC", "58EF68BB617A") foyer = ThreeWaySwitch(regsub, "Foyer Dimmer", "94103E4E72A0", "58EF68BB756C") all_3ways = [kitchen, foyer] print("--- Starting discovery of {} three-way circuits ---".format( len(all_3ways))) for tw in all_3ways: tw.discover() tw.sync() tw.register_callbacks()
del params['state'] else: params["status"] = self.get_state() params["logicalAddress"] = serialnumber payload = json.dumps(params, sort_keys=True, default=str) logger.debug("json dumps payload = %s", payload) urllib.request.urlopen(callbackUrl + urllib.parse.quote(payload)).read() except: logger.warning('bug in event for device with type = %s value %s', _type, value) devices = pywemo.discover_devices() SUBSCRIPTION_REGISTRY = pywemo.SubscriptionRegistry() SUBSCRIPTION_REGISTRY.start() for device in devices: ''' state = device.get_state(True) logger.info('state = %s', str(state)) serialnumber = device.serialnumber logger.info("serialnumber = %s", serialnumber) params = {} if device.model_name == "Insight": params = dict(device.insight_params) params['status'] = _status(int(params['state'])) params['standby'] = _standby(int(params['state'])) del params['state'] else: