コード例 #1
0
    def __init__(self, config):
        self.config = config

        stick = plugwise.Stick(config.STICK_PORT)

        for address in config.CIRCLES.keys():
            self.circles.append(EnergyCircle(address, stick))
コード例 #2
0
 def initializePlugs(self, plug={}):
     if plug:
         self.plugs.pop(plug["ID"], None)
         if plug["brand"] == "PW":
             self.plugs[plug["ID"]] = pw.Circle(plug['Mac'].encode(),
                                                pw.Stick(port='COM7'))
             self.updateSensorStatus(plug["ID"], [
                 1 if self.plugs[plug["ID"]].get_info() == "ON" else 0
             ][0])
         elif plug["brand"] == "DL":
             address, pwd = plug['Mac'].encode().split(":")
             self.plugs[plug["ID"]] = SmartPlug(address, pwd)
             self.updateSensorStatus(plug["ID"], [
                 1 if self.plugs[plug["ID"]].state == "ON" else 0
             ][0])
     else:
         self.plugs = {}
         try:
             ports = self.serial_ports()
             if isinstance(ports[0], serial.serialposix.Serial):
                 pw_port = pw.Stick(port=ports[0].port)
             else:
                 pw_port = pw.Stick(port=ports[0])
         except SerialException:
             print("couldnot connect to port")
         for i in self.plug_details:
             if i["brand"] == "PW":
                 self.plugs[i["ID"]] = pw.Circle(i['Mac'].encode(), pw_port)
                 self.updateSensorStatus(i["ID"], [
                     1 if self.plugs[i["ID"]].get_info() == "ON" else 0
                 ][0])
             elif i["brand"] == "DL":
                 address, pwd = i['Mac'].encode().split(":")
                 self.plugs[i["ID"]] = SmartPlug(address, pwd)
                 self.updateSensorStatus(i["ID"], [
                     1 if self.plugs[i["ID"]].state == "ON" else 0
                 ][0])
         print("Initialised Plugs")
コード例 #3
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup Plugwise."""
    # Connect to the plugwise stick
    try:
        stick = plugwise.Stick(config.get(CONF_PORT))
        _LOGGER.info("Connected to Plugwise stick")
    except (TimeoutException, SerialException) as reason:
        _LOGGER.error("Error: %s" % (reason, ))
        return

    # Add all circles to hass
    for name, mac in config[CONF_CIRCLES].items():
        data = PlugwiseSwitchData(stick, mac)
        add_devices([PlugwiseSwitch(hass, data, name)], True)
        _LOGGER.info("Created Plugwise switch for Circle: %s", name)
コード例 #4
0
ファイル: scan.py プロジェクト: aequitas/plugwise_graphite
def main():
    # config and logging
    config = anyconfig.load('config.yaml')
    logging.basicConfig(level=config.get('loglevel'))

    # setup plugwise stick
    stick = plugwise.Stick(config.get('tty'), config.get('timeout', 10))
    circle = partial(plugwise.Circle, comchan=stick)

    # configure circles
    circles = [
        dict(d, circle=circle(d.get('mac')), name=d.get('name', d.get('mac')))
        for d in config.get('devices')
    ]
    log.info('probing %s devices', len(circles))

    while True:
        # get power usage for active devices
        [
            log.info('{:20s}: {:6.2f}W'.format(
                c.get('name'), catch_error(c.get('circle').get_power_usage)))
            for c in circles
        ]
コード例 #5
0
def main():
    config_file_path = os.environ.get('PLUGWISE_CONFIG_FILE', 'config.yaml')

    # config and logging
    config = anyconfig.load(config_file_path)
    logging.basicConfig(level=config.get('loglevel'))

    # setup plugwise stick
    stick = plugwise.Stick(config.get('tty'), config.get('timeout', 10))
    circle = partial(plugwise.Circle, comchan=stick)

    # configure circles
    circles = [
        dict(d, circle=circle(d.get('mac')), name=d.get('name', d.get('mac')))
        for d in config.get('devices')
    ]
    pool_queue = cycle(circles)

    # get active circles
    log.info('probing %s devices', len(circles))
    [
        c.__setitem__('active',
                      bool(catch_error(c.get('circle').get_info) != -1))
        for c in circles
    ]

    while True:
        start = int(time.time())
        # get power usage for active devices
        [
            c.__setitem__('power_usage',
                          catch_error(c.get('circle').get_power_usage))
            for c in circles if c.get('active')
        ]

        # remove inactive devices
        [
            c.__setitem__('active', False) for c in circles
            if c.get('power_usage') == None
        ]

        now = int(time.time())
        msg = "\n".join([
            C_TEMPLATE.format(config=config, circle=c, time=now)
            for c in circles if c.get('active')
        ]) + '\n'
        read_devices = len([c for c in circles if c.get('active')])
        msg += TEMPLATE.format(config=config,
                               name='read_devices',
                               value=read_devices,
                               time=now)
        log.info(msg)

        if config.get('stdout'):
            print(msg + '\n')
        else:
            # make autoclosing socket to graphite
            with closing(socket.socket(socket.AF_INET,
                                       socket.SOCK_STREAM)) as s:
                s.connect((config.get('graphite').get('host'),
                           config.get('graphite').get('port')))
                s.send(msg + '\n')

        # want up to interval
        while start + config.get('interval') > int(time.time()):
            # if there is enought time left, try to reconnect inactive circles
            if config.get('timeout') < start + config.get('interval') - int(
                    time.time()):
                try_circle = next(pool_queue)
                log.debug('trying {c[name]}'.format(c=try_circle))
                try_circle['active'] = bool(
                    catch_error(try_circle.get('circle').get_info) != -1)
            time.sleep(1)