示例#1
0
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
示例#2
0
 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)
示例#3
0
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 main():
    """
    print ip addresses of smart plugs
    :return:
    """
    for dev in Discover.discover().values():
        print(dev)
示例#5
0
def dev(request):
    file = request.param

    ip = request.config.getoption("--ip")
    if ip:
        d = Discover.discover_single(ip)
        print(d.model)
        if d.model in file:
            return d
        return

    with open(file) as f:
        sysinfo = json.load(f)
        model = basename(file)
        params = {
            "host": "123.123.123.123",
            "protocol": FakeTransportProtocol(sysinfo),
            "cache_ttl": 0,
        }
        if "LB" in model or "KL" in model:
            p = SmartBulb(**params)
        elif "HS300" in model:
            p = SmartStrip(**params)
        elif "HS" in model:
            p = SmartPlug(**params)
        else:
            raise Exception("No tests for %s" % model)
        yield p
示例#6
0
    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")
示例#7
0
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]
示例#8
0
def cli(ctx, ip, host, debug, bulb, plug):
    """A cli tool for controlling TP-Link smart home plugs."""
    if debug:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)

    if ctx.invoked_subcommand == "discover":
        return

    if ip is not None and host is None:
        host = ip

    if host is None:
        click.echo("No host name given, trying discovery..")
        ctx.invoke(discover)
        return

    else:
        if not bulb and not plug:
            click.echo("No --bulb nor --plug given, discovering..")
            dev = Discover.discover_single(host)
        elif bulb:
            dev = SmartBulb(host)
        elif plug:
            dev = SmartPlug(host)
        else:
            click.echo("Unable to detect type, use --bulb or --plug!")
            return
        ctx.obj = dev

    if ctx.invoked_subcommand is None:
        ctx.invoke(state)
示例#9
0
    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
示例#10
0
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
示例#12
0
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)
示例#13
0
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))
示例#14
0
    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
示例#15
0
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)
    ]
示例#16
0
文件: cli.py 项目: dberlin/pyHS100
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)
示例#17
0
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
示例#18
0
    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
示例#19
0
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
示例#21
0
文件: cli.py 项目: kwazel/pyHS100
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
示例#22
0
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 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
示例#24
0
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)
示例#25
0
    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
示例#26
0
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
示例#27
0
    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)
示例#29
0
文件: cli.py 项目: dberlin/pyHS100
def cli(ctx, ip, host, alias, debug, bulb, plug, strip):
    """A cli tool for controlling TP-Link smart home plugs."""
    if debug:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)

    if ctx.invoked_subcommand == "discover":
        return

    if ip is not None and host is None:
        host = ip

    if alias is not None and host is None:
        click.echo("Alias is given, using discovery to find host %s" % alias)
        host = find_host_from_alias(alias=alias)
        if host:
            click.echo("Found hostname is {}".format(host))
        else:
            click.echo("No device with name {} found".format(alias))
            return

    if host is None:
        click.echo("No host name given, trying discovery..")
        ctx.invoke(discover)
        return
    else:
        if not bulb and not plug and not strip:
            click.echo("No --strip nor --bulb nor --plug given, discovering..")
            dev = Discover.discover_single(host)
        elif bulb:
            dev = SmartBulb(host)
        elif plug:
            dev = SmartPlug(host)
        elif strip:
            dev = SmartStrip(host)
        else:
            click.echo(
                "Unable to detect type, use --strip or --bulb or --plug!")
            return
        ctx.obj = dev

    if ctx.invoked_subcommand is None:
        ctx.invoke(state)
示例#30
0
 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")