def discovery(self, retry=0): now = datetime.datetime.now() if self.firstRun: self.lastDiscoveryTime = now - datetime.timedelta(seconds=10000000) self.firstRun = False if (now - self.lastDiscoveryTime).seconds > 300 or retry > 0: self.lastDiscoveryTime = now print("Discovering Wemo devices on network") devicesA = pywemo.discover_devices() time.sleep(2) devicesB = pywemo.discover_devices() if len(devicesA) == len(devicesB) and len(devicesA) > 0: self.devices = devicesB print("Found %s devices in discovery" % len(self.devices)) else: if retry < 3: retry += 1 print( "Mismatch in number of detected devices, or no devices found. Trying again in 5 seconds." ) time.sleep(5) self.discovery(retry) else: print( "%s retries and still unable to get devices... backing off a long time (We will never give up though. The fridge depends on us.)" % retry) if retry > 10: time.sleep(120) else: time.sleep(30) retry += 1 self.discovery(retry)
def set_power(mac, state): print('Turning device at MAC {} {}'.format(mac, 'on' if state else 'off')) devices = pywemo.discover_devices() for device in devices: if device.mac == mac: device.set_state(state) break
def get_state(mac): devices = pywemo.discover_devices() for device in devices: if device.mac == mac: state = device.get_state() print('{} is {}.'.format(mac, 'on' if state else 'off')) break
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) ])
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)])
def scan_power_switches(callback=None, **kwargs): for device in pywemo.discover_devices(): yield terrariumPowerSwitch( md5((terrariumPowerSwitchWeMo.TYPE + device.serialnumber).encode()).hexdigest(), terrariumPowerSwitchWeMo.TYPE, device.host, device.name, None, callback)
def _scan_once(self): devices = pywemo.discover_devices() logging.info('Found %d wemo devices.', len(devices)) for device in devices: device_exists = device.serialnumber in self._devices self._devices[device.serialnumber] = device state = device.get_state() serialnumber = device.serialnumber state_changed = state != self._state_cache.get(serialnumber, None) self._state_cache[serialnumber] = state details = { 'serial_number': serialnumber, 'model': device.model, 'name': device.name, 'state': state == 1 } if not device_exists: self._subscriptions.register(device) self._subscriptions.on(device, 'BinaryState', self._event) device_type = self.get_type(device) if device_type is None: return if not device_exists or state_changed: self._callback(device_type, 'wemo-%s' % device.serialnumber, details)
def discover(self, command=None): devices = pywemo.discover_devices() if self.subscription_registry_started is False: self.subscription_registry.start() self.subscription_registry_started = True for wemodev in devices: dtype = wemodev.__class__.__name__ LOGGER.info('Wemo Device {} of type {} found.'.format( wemodev.name, dtype)) #elif dtype == 'Insight': if issubclass(wemodev.__class__, pywemo.Insight): LOGGER.info('Adding {} {} to ISY.'.format(dtype, wemodev.name)) address = wemodev.mac.lower() self.addNode( WemoInsight(self, self.address, address, wemodev.name, wemodev, self.subscription_registry)) # if dtype in ['LightSwitch', 'Switch', 'OutdoorPlug']: elif issubclass(wemodev.__class__, pywemo.Switch): LOGGER.info('Adding {} {} to ISY.'.format(dtype, wemodev.name)) address = wemodev.mac.lower() self.addNode( WemoSwitch(self, self.address, address, wemodev.name, wemodev, self.subscription_registry)) # elif dtype == 'Dimmer': elif issubclass(wemodev.__class__, pywemo.Dimmer): LOGGER.info('Adding {} {} to ISY.'.format(dtype, wemodev.name)) address = wemodev.mac.lower() self.addNode( WemoDimmer(self, self.address, address, wemodev.name, wemodev, self.subscription_registry)) else: LOGGER.warning( 'Device type {} is not currently supported.'.format(dtype))
def start_pairing(self, timeout): """ Start the pairing process. timeout -- Timeout in seconds at which to quit pairing """ if self.pairing: return self.pairing = True for dev in discover_devices(): if not self.pairing: break _id = 'wemo-' + dev.serialnumber if _id not in self.devices: if isinstance(dev, Insight): device = WemoInsight(self, _id, dev) elif isinstance(dev, Switch): device = WemoSwitch(self, _id, dev) elif isinstance(dev, LightSwitch): device = WemoLightSwitch(self, _id, dev) elif isinstance(dev, Dimmer): device = WemoDimmer(self, _id, dev) else: continue self.handle_device_added(device) self.pairing = False
def wemo_startup_scan(hass, config): """Run device discovery once the component has been initialized.""" import pywemo _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)
def discover_wemo(): """ Discover Wemo devices on the network """ global _device_time, _device_cache if _device_time and datetime.now() - _device_time <= CACHE_DURATION: return _device_cache cache = True _device_cache = pywemo.discover_devices() _device_time = datetime.now() if _device_time: for i in reversed(range(0, len(_device_cache))): if _device_cache[i].mac is None: cache = False print('Error: Device {} is missing a mac address!'.format( _device_cache[i]), file=sys.stderr) # Useless to us _device_cache.pop(i) returned_devices = _device_cache # Reset cache if we got invalid devices if cache is False: _device_cache = [] _device_time = None return returned_devices
def __init__(self, TILT_COLOR, TILTPI_HOST, TILTPI_PORT, WEMO_NAME, SETPOINT): self.tilt_color = TILT_COLOR self.tiltpi_host = TILTPI_HOST self.tiltpi_port = TILTPI_PORT self.wemo_name = WEMO_NAME self.setpoint = int(SETPOINT) print( "Starting heating pad control | Tilt Color: {} | TiltPi Host: {} | TiltPi Port: {} | WeMo Switch Name: {} | Setpoint: {}" .format(self.tilt_color, self.tiltpi_host, self.tiltpi_port, self.wemo_name, self.setpoint)) self.wemo = None wemo_devices = pywemo.discover_devices() for device in wemo_devices: if device.name == WEMO_NAME: self.wemo = device if not self.wemo: print("Wemo \"%s\" not found on network" % self.wemo_name) sys.exit(1) print("Found Wemo: {} | mac: {} | serial: {} | ipaddress: {}".format( self.wemo.name, self.wemo.mac, self.wemo.serialnumber, self.wemo.host))
def discover(self, command=None): devices = pywemo.discover_devices() for wemodev in devices: if wemodev.device_type == 'LightSwitch': LOGGER.info('Wemo LighSwitch {} found. Adding to ISY if necessary.'.format(wemodev.name)) address = wemodev.mac.lower() self.addNode(WemoSwitch(self, self.address, address, wemodev.name, wemodev, self.subscription_registry))
def _scan_relays(callback=None, **kwargs): for device in pywemo.discover_devices(): yield terrariumRelay(None, terrariumRelayWeMo.HARDWARE, device.host, f'{terrariumRelayWeMo.NAME} {device.name} device ip: {device.host}({device.mac})', callback=callback)
def discover_and_log_devices(only_needing_setup: bool = False, verbose: int = 0) -> List[Device]: """Discover and log details about devices.""" devices = pywemo.discover_devices() not_setup = [] device = None for device in devices: if only_needing_setup: status = device.WiFiSetup.GetNetworkStatus()['NetworkStatus'] if status not in {'1'}: not_setup.append(device) LOG.info('found device needing setup: %s', device) else: LOG.info(DASHES) LOG.info('found device: %s', device) if verbose >= 0: log_details(device, verbose) if only_needing_setup: return not_setup if device: LOG.info(DASHES) LOG.info('found %s devices', len(devices)) return devices
def get_discovered_devices(self): self._wemoswitch_logger.debug("Discovering devices") self.discovered_devices = pywemo.discover_devices() tmp_ret = [] for index in range(len(self.discovered_devices)): d = self.get_discovered_device(index) tmp_ret.append(d) return tmp_ret
def scan_wemo_switches(callback=None): for device in pywemo.discover_devices(): yield terrariumSwitch(md5(b'' + 'wemo' + device.serialnumber).hexdigest(), 'wemo', device.host, device.name, 0, 0, callback)
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_BLUMATE_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) service = WEMO_MODEL_DISPATCH.get(model_name) or DISCOVER_SWITCHES component = WEMO_SERVICE_DISPATCH.get(service) discovery.discover(hass, service, discovery_info, component, config) discovery.listen(hass, discovery.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('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, discovery.SERVICE_WEMO, discovery_info) return True
def discover(self): devices = pywemo.discover_devices() for device in devices: if isinstance(device, pywemo.Bridge): Application().queue(self.bridgeFound, device) elif isinstance(device, pywemo.Switch): Application().queue(self.switchFound, device) elif isinstance(device, pywemo.Motion): Application().queue(self.motionFound, device) Application().queue(self.deviceManager.finishedLoading, 'wemo')
def scan_for_devices(self): # NOTE: device discovery doesn't work if ufw is enabled. Idk what the firewall rule to allow the traffic is. discovered_devices = pywemo.discover_devices() # Manually add devices: # self.devices += [pywemo.discovery.device_from_description(f'http://{ip}:{pywemo.ouimeaux_device.probe_wemo(ip)}/setup.xml', None) for ip in ["192.168.0.26", "192.168.0.27", "192.168.0.28"]] self.devices = list( [DeviceWrapper(d.host, d) for d in discovered_devices]) log.info(f"found {len(self.devices)} devices") self.last_device_scan = datetime.datetime.now()
def find_and_show_all_wemo_devices(): devices = {} while len(devices) < NUM_WEMO_DEVICES: print("discovering devices ... ", end="") devices = pywemo.discover_devices() print("{}/{}".format(len(devices), NUM_WEMO_DEVICES)) print("--- {} Devices Found ---".format(len(devices))) for d in devices: print(" {:24}{:16}{:12}".format(d.name, d.host, d.mac))
class caller: mode = 0 devices = pywemo.discover_devices() numberOfDevices = len(devices) #use toggle 'modes' to have 3 working gestures, 2 mapped to a command and 1 to switch to a next series of commands def call(self, label): #gibrish text is a placeholder if self.mode == 0: if label=="ok_gesture": self.mode += 1 elif label == "point_up": win32api.keybd_event(VolUp, 48) elif label == "rock_and_roll": win32api.keybd_event(VolDown, 49) elif self.mode == 1: if label == "ok_gesture": self.mode += 1 elif label == "point_up": win32api.keybd_event(NextTrack, 25) elif label == "rock_and_roll": win32api.keybd_event(PrevTrack, 16) elif self.mode == 2: if label == "ok_gesture": self.mode += 1 elif label == "point_up": win32api.keybd_event(PlayPauseMedia, 34) elif label == "rock_and_roll": print("") elif self.mode == 3: if label == "ok_gesture": self.mode += 1 elif label == "point_up": if self.numberOfDevices > 0: self.devices[0].toggle() elif label == "rock_and_roll": if self.numberOfDevices > 1: self.devices[1].toggle() elif self.mode == 4: if label == "ok_gesture": self.mode = 0 elif label == "point_up": if self.numberOfDevices > 2: self.devices[2].toggle() elif label == "rock_and_roll": if self.numberOfDevices > 3: self.devices[3].toggle()
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
def discover_wemo(): """ Discover Wemo devices on the network """ global _device_time, _device_cache if _device_time and _device_time - local_now() <= CACHE_DURATION: return _device_cache _device_cache = pywemo.discover_devices() _device_time = local_now() return _device_cache
def main(): found=False thing=None tries=3 argc=len(sys.argv) if argc < 2: print("Usage: wemo.py <device name> <ON|OFF|TOGGLE>") sys.exit(1) device=pywemo.discover_devices() devName=sys.argv[1] while tries > 0: if len(device) == 0: print("Timed out") tries=tries-1 sleep(2) # sys.exit(2) else: break for dev in device: # print(dev.name) if dev.name == devName: found = True thing = dev break if not found: print(devName,"Not found") sys.exit(0) if argc == 2: flag=state(thing) print(thing.name,"is",flag) if argc == 3: cmd=sys.argv[2].lower() if cmd == "on": flag=on(thing) if cmd == "off": flag=off(thing) # cmd = 'mosquitto_pub -r -t /home/kitchen/"' + thing.name + '" -m ' + flag print(cmd) system(cmd) return
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", f"{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, DEFAULT_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_dispatch(SERVICE_WEMO, discovery_info) _LOGGER.debug("WeMo device discovery has finished")
def main(): found = False thing = None tries = 3 argc = len(sys.argv) if argc < 2: print("Usage: wemo.py <device name> <ON|OFF|TOGGLE>") sys.exit(1) device = pywemo.discover_devices() devName = sys.argv[1] while tries > 0: if len(device) == 0: print("Timed out") tries = tries - 1 sleep(2) # sys.exit(2) else: break for dev in device: # print(dev.name) if dev.name == devName: found = True thing = dev break if not found: print(devName, "Not found") sys.exit(0) if argc == 2: flag = state(thing) print(thing.name, "is", flag) if argc == 3: cmd = sys.argv[2].lower() if cmd == "on": flag = on(thing) if cmd == "off": flag = off(thing) # cmd = 'mosquitto_pub -r -t /home/kitchen/"' + thing.name + '" -m ' + flag print(cmd) system(cmd) return
def on_mount(self): self.title = "Switches" if len(self.devices) == 0: print "[WemoPanel on_mount] Discovering devices..." pub.sendMessage('add_image', img=self.loading_screen("Discovering Devices...")) self.devices = pywemo.discover_devices() print "[WemoPanel on_mount] Discovered:", self.devices # register touch events, right now limited to 4, TODO add "More" as button 5 touchphat.on_release(2, handler=self.on_release) touchphat.on_release(3, handler=self.on_release) touchphat.on_release(4, handler=self.on_release) touchphat.on_release(5, handler=self.on_release)
def __init__(self, logger): # Configure loggers self.logger = logger or logging.getLogger(__name__) # Configure other class objects self._wemo_known = [] self.wemo_device = None self.wemo_port = None self.wemo_url = str() self.result = None self.status = str() self.logger.info('Performing initial scan for wemo devices on network') self._wemo_known = pywemo.discover_devices() for device in self._wemo_known: self.logger.info('Found: %s', device)
def main(): # discover wemo devices devices = pywemo.discover_devices() print(devices) device = devices[0] url = 'http://'+device.deviceinfo.hostname+'/setup.xml' mac = device.mac # Instantiate Pywemo Switch switch = pywemo.Switch(url=url, mac=mac) # Turn on Switch switch.on()
def __init__(self): self.db = DataBase('power') devices = pywemo.discover_devices() print(devices) if len(devices) == 0: devices = [1] print('Discovery failed') address = '192.168.2.70' port = port = pywemo.ouimeaux_device.probe_wemo(address) url = 'http://%s:%i/setup.xml' % (address, port) devices[0] = pywemo.discovery.device_from_description(url, None) self.device = devices[0]
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 = { 'device_type': device.__class__.__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")
def discover(): try: devices = pywemo.discover_devices() if len(devices) < 1: return "There are no wemo devices" else: temp = [] for device in devices: print "Discovered a We Mo %s called %s" % (device.model_name, device.name) temp.append(device) print temp return json.dumps(temp) except Exception as e: feedback = "Error occurred while discovering wemo devices: " + e return feedback
def discover(self): while self.real_switch == None or self.dumb_switch == None: print('Searching for "{}" devices ... '.format(self.name), end="") devices = pywemo.discover_devices() print("saw {}/{} devices.".format(len(devices), NUM_WEMO_DEVICES)) for d in devices: if d.mac == self.real_switch_mac: self.real_switch = d if d.mac == self.dumb_switch_mac: self.dumb_switch = d print(" real_switch: {:24}{:24}{:12}".format(self.real_switch.name, self.real_switch.host, self.real_switch.mac)) print(" dumb_switch: {:24}{:24}{:12}".format(self.dumb_switch.name, self.dumb_switch.host, self.dumb_switch.mac))
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")
def setup_platform(hass, config, add_devices_callback, discovery_info=None): """ Find and return WeMo switches. """ import pywemo import pywemo.discovery as discovery if discovery_info is not None: device = discovery.device_from_description(discovery_info) if device: add_devices_callback([WemoSwitch(device)]) return logging.getLogger(__name__).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)])
def setup_platform(hass, config, add_devices_callback, discovery_info=None): """ Find and return WeMo switches. """ import pywemo import pywemo.discovery as discovery 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)])
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.debug("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) continue 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) continue devices.append((url, device)) if config.get(DOMAIN, {}).get(CONF_DISCOVERY): _LOGGER.debug("Scanning for WeMo devices.") devices.extend( (setup_url_for_device(device), device) for device in pywemo.discover_devices()) for url, device in devices: _LOGGER.debug('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
FAN_PIN = 17 COOL_PIN = 27 GPIO.setmode(GPIO.BCM) GPIO.setup(FAN_PIN, GPIO.IN) GPIO.setup(COOL_PIN, GPIO.IN) # Setup WeMo switches WEMO_SERIAL_FAN = os.environ['FAN_SERIAL_NUMBER'] WEMO_SERIAL_COOL = os.environ['COOL_SERIAL_NUMBER'] WEMO_FAN = None WEMO_COOL = None # TODO: Make it specify based on IP rather than serial number for device in pywemo.discover_devices(): print "Found WeMo: " + device.serialnumber if device.serialnumber == WEMO_SERIAL_FAN: WEMO_FAN = device elif device.serialnumber == WEMO_SERIAL_COOL: WEMO_COOL = device # Main Loop while True: thermostat_cool_state = GPIO.input(COOL_PIN) wemo_cool_state = WEMO_COOL.get_state() print "**Cool*" print "Thermostat Cool is: " + str(wemo_cool_state) print "WeMo Cool is: " + str(thermostat_cool_state)