def discover(): log.info("Discovering devices") devices = Discover.discover() while not devices: log.warning("... no devices found, retrying in 5 seconds") time.sleep(5) devices = Discover.discover() bulb = next(iter(devices.values())) log.info("... found: %s at %s", bulb.alias, bulb.host) return bulb
def main(): """ print ip addresses of smart plugs :return: """ for dev in Discover.discover().values(): print(dev)
def get_plugs(plugip, plugnames, named_flag): try: for dev in Discover.discover(): plugobj = SmartPlug(dev) plugip[plugobj.alias] = dev if named_flag is False: plugnames.append(plugobj.alias) else: pass except: plugip = {} plugnames = [] send_twilio_msg('Warning - plug discovery failed') traceback.print_exc() return [plugip, plugnames]
def __init__(self, host): self.host = host for dev in Discover.discover().values(): self.deviceList.append(mqttDevice.Device(self.host, dev)) print("Made new device with " + str(len(self.deviceList)) + " devices")
def main(): """ set power budget to 3000 Watts. This really doesn't matter because all devices have the priority and are not "managed". """ dev_man = DeviceManager(max_power_budget=3000) devices = Discover.discover() plugs = [] for key, device in devices.items(): plug = KasaPlug(device.alias, device=device) plugs.append(plug) plug.set(True) @asyncio.coroutine def do_stuff(plugs): while True: for plug in plugs: print("plug {} is running: {} {}W".format( plug.name, plug.running(), plug.power_usage)) yield from asyncio.sleep(MINS(1)) asyncio.get_event_loop().run_until_complete(do_stuff(plugs))
def __init__(self): for dev in Discover.discover().values(): plug = dev self.dev = plug if plug.hw_info == "": logging.exception("could not init powerPlug") logging.info("init power plug: %s", self.dev.model)
def toggle_device(id): for dev in Discover.discover().values(): if dev.alias == id: if dev.state == "ON": dev.turn_off() else: dev.turn_on() return dev.state
def discoverDevices(): deviceList = {} for dev in Discover.discover().values(): print(dev) output = str(dev) deviceList[parseName(output)] = parseIP(output) return deviceList
def get_bulbs(): #get bulb ips. bulbs = Bulb.objects.all() for dev in Discover.discover().values(): strBulb = str(dev).split() print(strBulb) if len(bulbs.filter(name=strBulb[3].strip('(),'))) < 1: print("new bulb") create_new_bulb(strBulb)
def dump_discover(save): for dev in Discover.discover(return_raw=True).values(): model = dev["system"]["get_sysinfo"]["model"] hw_version = dev["system"]["get_sysinfo"]["hw_ver"] save_to = "%s_%s.json" % (model, hw_version) click.echo("Saving info to %s" % save_to) with open(save_to, "w") as f: import json json.dump(dev, f, sort_keys=True, indent=4)
def _scan(self): devices = Discover.discover() self._ip_to_dev = {} self._alias_to_dev = {} for (ip, dev) in devices.items(): self._ip_to_dev[ip] = dev self._alias_to_dev[dev.alias] = dev return devices
def filter_plugs_by_prefix(prefix): """ :param prefix: :return: ip addresses of plugs whose aliases start with the given prefix """ return [ dev.ip_address for dev in Discover.discover().values() if dev.alias.startswith(prefix) ]
def main(): threads = [] for dev in Discover.discover(): threads.append(Thread(name=dev, target=HS110, args=(dev, ))) for thread in threads: thread.start() print("< {}".format(thread))
def discover(ctx, timeout, discover_only): """Discover devices in the network.""" click.echo("Discovering devices for %s seconds" % timeout) found_devs = Discover.discover(timeout=timeout).items() if not discover_only: for ip, dev in found_devs: ctx.obj = dev ctx.invoke(state) print() return found_devs
def __init__(self, appliance, db, interval=1, detect_on=True): self.appliance = appliance.lower() # The collecting variable is used to know the state...the start # method sets collecting to True. The stop, to False. self.collecting = False self.interval = interval self.db = db self.plug = None # These three variables are used for real time detection of a device # If detect_cycle is False, the device doesn't cycle. E.g.s of devices # that cycle include washing machines, refrigerators. E.g.s of devices # that don't cycle include toasters, microwaves... # If the detect cycle is False, then real time detection occurs # if detect_low < P < detect_high -> device is on. self.detect_on = detect_on self.detect_cycle = False self.detect_low = 0 self.detect_high = 0 self.url = '' # Find the plug with the alias named 'appliance' try: # Get the dictionary of smart devices. # The key is the IP address of the device. a_dict = Discover.discover() except SmartDeviceException as err: print("Exception talking to the TP-LINK: ", err) return else: for key, value in a_dict.items(): # Sometimes the name ends up with characters # We don't want in it... # Take out quotes and spaces from the name. name = a_dict[key].alias.strip('" ').lower() if (name == self.appliance): self.plug = value break if (self.detect_on): try: with open("device_thresholds.json", "r") as file: thresholds = json.load(file) self.url = read_config('url') for k in thresholds: if (k == self.appliance): self.detect_low = thresholds[k]['low'] self.detect_high = thresholds[k]['high'] break if (self.detect_high == 0): raise ValueError( 'Values for threshold detection are not available.') except FileNotFoundError as err: print(err) return
class Socket: def __init__(self,name): self.plug_mappings = {'A': 'Fan', 'B' : 'Music', 'C':'Lights'} self.selected_appliance = ''; print("\n\n\nCREATING PLUG\n\n\n") # Showing that when a gesture is picked up being able to see that it works dev_ip = None for dev in ds.discover().values(): if dev.alias.lower() == name: # <--- need the hard code the name of the plug to find IP dev_ip = dev.host break #checking if we are finding the IP address self.plug = SmartPlug(dev_ip)
def get_plug_ip(): print("Checking TP-Link Smartplug connection...") # Check smartplug connection sp_dict = Discover.discover() if bool(sp_dict): for sp_ip in sp_dict: return sp_ip else: pass
def find_host_from_alias(alias, timeout=1, attempts=3): """Discover a device identified by its alias""" host = None click.echo("Trying to discover %s using %s attempts of %s seconds" % (alias, attempts, timeout)) for attempt in range(1, attempts): click.echo("Attempt %s of %s" % (attempt, attempts)) found_devs = Discover.discover(timeout=timeout).items() for ip, dev in found_devs: if dev.alias.lower() == alias.lower(): host = dev.host return host return None
def find_host_from_device_name(ctx, timeout, attempts, devicename): """Discover devices in the network.""" host = None click.echo("Trying to discover %s using %s attempts of %s seconds" % (devicename, attempts, timeout)) for attempt in range(1, attempts): print("Attempt %s of %s" % (attempt, attempts)) found_devs = Discover.discover(timeout=timeout).items() for _, dev in found_devs: if dev.alias.lower() == devicename.lower(): host = dev.host return host return None
def refresh(timeout=8): global lastRefreshed,lookup from pyHS100 import Discover lastRefreshed= time.time() allDevices= Discover.discover(timeout=timeout) l={} #Build a structure that allows lookup by both type and IP address for i in allDevices: try: l[allDevices[i].alias] = allDevices[i] except: logger.exception() lookup=l
def dump_discover(ctx, save): """Dump discovery information. Useful for dumping into a file with `--save` to be added to the test suite. """ target = ctx.parent.params["target"] for dev in Discover.discover(target=target, return_raw=True).values(): model = dev["system"]["get_sysinfo"]["model"] hw_version = dev["system"]["get_sysinfo"]["hw_ver"] save_to = f"{model}_{hw_version}.json" click.echo("Saving info to %s" % save_to) with open(save_to, "w") as f: import json json.dump(dev, f, sort_keys=True, indent=4)
def unearth(ttl_hash=None) -> Dict[str, Device]: devices = [] _LOGGER.debug("Searching for new devices...") try: for dev in Discover.discover().values(): _LOGGER.error("found device: %s", dev) if isinstance(dev, SmartStrip): devices.append(TplinkStrip(dev.sys_info['deviceId'], dev.alias, dev.host)) elif isinstance(dev, SmartPlug): devices.append(TplinkPlug(dev.sys_info['deviceId'], dev.alias, dev.host)) except Exception as ex: _LOGGER.error("Got exception %s", ex, exc_info=True) _LOGGER.debug("Found %s devices", len(devices)) return devices
def __init__(self, ip=None): bulb = None if not ip: d = Discover() devices = d.discover() for ip, device in devices.items(): if isinstance(device, SmartBulb): bulb = device else: bulb = SmartBulb(ip) if bulb: self._bulb = bulb else: raise NoBulbException
def discover(ctx, timeout, discover_only, dump_raw): """Discover devices in the network.""" target = ctx.parent.params["target"] click.echo("Discovering devices for %s seconds" % timeout) found_devs = Discover.discover( target=target, timeout=timeout, return_raw=dump_raw ).items() if not discover_only: for ip, dev in found_devs: if dump_raw: click.echo(dev) continue ctx.obj = dev ctx.invoke(state) print() return found_devs
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.discover(timeout=min(timeout, _TIMEOUT)).values(): if not self.pairing: break self._add_device(dev) self.pairing = False
def update_fan_state(): maybe_create_table() ftemp_in = read_temp() if ftemp_in is None: return print('ftemp_in', ftemp_in) config = SafeConfigParser() config.read('config.ini') PARAMS = { 'lat': config.get('MAIN', 'LAT'), 'lon': config.get('MAIN', 'LON'), 'units': 'imperial', 'APPID': config.get('MAIN', 'API_KEY') } r = requests.get(url='http://api.openweathermap.org/data/2.5/weather', params=PARAMS) ftemp_out = r.json()['main']['temp'] ftemp_out_max = r.json()['main']['temp_max'] print('ftemp_out', ftemp_out) threshold_temp_low = float(config.get('MAIN', 'THRESHOLD_TEMP_LOW')) threshold_temp_high = float(config.get('MAIN', 'THRESHOLD_TEMP_HIGH')) temp_delta_in_out = float(config.get('MAIN', 'TEMP_DELTA_IN_OUT')) now = int(time.time()) db = sqlite3.connect(database_file) cursor = db.cursor() cursor.execute( ''' INSERT INTO Temps(ftemp_in, ftemp_out, timestamp) VALUES(?,?,?) ''', (ftemp_in, ftemp_out, now)) db.commit() for plug in Discover.discover().values(): if (plug.state is not "ON" and ftemp_in > threshold_temp_high and ftemp_out < ftemp_in - temp_delta_in_out): send_new_fan_state(plug, "ON", now) elif (plug.state is not "OFF" and (ftemp_in < threshold_temp_low or ftemp_out > ftemp_in - temp_delta_in_out)): send_new_fan_state(plug, "OFF", now)
def discover(self): self.l_info('discover', 'start') for dev in Discover.discover().values(): self.l_debug( 'discover', "Got Device\n\tAlias:{}\n\tModel:{}\n\tMac:{}\n\tHost:{}". format(dev.alias, dev.model, dev.mac, dev.host)) cname = dev.__class__.__name__ self.l_debug('discover', 'cname={}'.format(cname)) if cname == 'SmartStrip': nname = get_valid_node_name(dev.mac) self.l_info('discover', 'adding SmartStrip {}'.format(nname)) self.addNode( SmartStripNode(self, nname, 'SmartStrip {}'.format(dev.mac), dev)) else: self.l_warning('discover', "Device not yet supported: {}".format(dev)) LOGGER.info("discover: done")
def discoverer(self): self.current_device_set = set() while True: #print('\nloop start') new_device_set = set() for ip, dev in Discover.discover(timeout=self.timeout).items(): try: dev = SmartDeviceContainer(dev) new_device_set.add(dev) except: pass offline_devices = self.current_device_set - new_device_set #print('offline devices:'.ljust(18), (offline_devices) or '-') for dev in offline_devices: if dev.disconnect_count > self.threshold: print(dev, 'disconnected') for e in self.single_disconnect_event.values(): e(device=dev.device) else: dev.disconnect_count += 1 print(dev.alias, 'hwid:', dev.hw_id, 'id:', id(dev), 'dcnts:', dev.disconnect_count) new_device_set.add(dev) offline_devices = self.current_device_set - new_device_set for e in self.multi_disconnect_event.values(): e(device_list=[d.device for d in offline_devices]) new_devices = new_device_set - self.current_device_set #print('new_devices:'.ljust(18), (new_devices) or '-') for e in self.multi_connect_event.values(): e(device_list=[d.device for d in new_devices]) for dev in new_devices: print(dev, 'connected') for e in self.single_connect_event.values(): e(device=dev.device, is_on=dev.device.is_on) #print('noch:'.ljust(18), (new_device_set & self.current_device_set) or '-') self.current_device_set = new_device_set time.sleep(self.time_between_pings)
def __init__(self,Reading): self.monitor_name = Reading.appliance self.plugs = [] self.collecting = False self.interval = Reading.interval # Finds plugs that can send energy readings. try: a_dict = Discover.discover() except SmartDeviceException as err: print("Exception talking to the TP-LINK: ", err) return else: for key in a_dict: # If the plug can send energy readings.... if (a_dict[key].has_emeter): # Take out quotes and spaces from the name. plug_name = a_dict[key].alias plug_name = plug_name.strip('" ') a_dict[key].set_alias(plug_name) # Add the plug to the list of plugs that can take energy readings. self.plugs.append(a_dict)
def start_pairing(self, timeout): """ Start the pairing process. timeout -- Timeout in seconds at which to quit pairing """ self.pairing = True for dev in Discover.discover(timeout=min(timeout, _TIMEOUT)).values(): if not self.pairing: break _id = 'tplink-' + dev.sys_info['deviceId'] if _id not in self.devices: if isinstance(dev, SmartPlug): device = TPLinkPlug(self, _id, dev) elif isinstance(dev, SmartBulb): device = TPLinkBulb(self, _id, dev) else: continue self.handle_device_added(device)