Exemplo n.º 1
0
    def __init__(self, id: str, alias: str, host: str) -> None:

        Strip.__init__(self, id, alias, host, DeviceBrand.tp_link)
        self.native_api = SmartStrip(host)
        _LOGGER.debug(
            "Initializing tp-link smartplug: %s",
            self.host,
        )
Exemplo n.º 2
0
Arquivo: common.py Projeto: rudgr/core
def get_static_devices(config_data) -> SmartDevices:
    """Get statically defined devices in the config."""
    _LOGGER.debug("Getting static devices")
    lights = []
    switches = []

    for type_ in (CONF_LIGHT, CONF_SWITCH, CONF_STRIP, CONF_DIMMER):
        for entry in config_data[type_]:
            host = entry["host"]
            try:
                if type_ == CONF_LIGHT:
                    lights.append(SmartBulb(host))
                elif type_ == CONF_SWITCH:
                    switches.append(SmartPlug(host))
                elif type_ == CONF_STRIP:
                    for plug in SmartStrip(host).plugs.values():
                        switches.append(plug)
                # Dimmers need to be defined as smart plugs to work correctly.
                elif type_ == CONF_DIMMER:
                    lights.append(SmartPlug(host))
            except SmartDeviceException as sde:
                _LOGGER.error(
                    "Failed to setup device %s due to %s; not retrying", host, sde
                )
    return SmartDevices(lights, switches)
Exemplo n.º 3
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
Exemplo n.º 4
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        ss_plug=dict(required=True),
        powerstate=dict(required=True),
        plug_index=dict(type=int, required=True),
    )
    power_mappings = {
        "present": 'ON',
        "absent": 'OFF'
    }
    
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=False)
    result = dict(changed=False)

    smart = SmartStrip(module.params['ss_plug'])
    
    if smart.state[module.params['plug_index']] == power_mappings[module.params['powerstate']]:
        result['ansible_module_results'] = {
            'alias': ss_get_alias(smart, module.params['plug_index']),
            'status': 'no change',
            'powerstate': ss_get_powerstate(smart, module.params['plug_index']),
            'info': "No Action needed"}
    elif module.params['powerstate'].lower() == 'present':
        result['ansible_module_results'] = ss_turn_on(smart, module.params['plug_index'])
    elif module.params['powerstate'].lower() == 'absent':
        result['ansible_module_results'] = ss_turn_off(smart, module.params['plug_index'])
    
    if result['ansible_module_results']['status'] == 'Success':
        result['changed'] = True
    
    module.exit_json(**result)
def main():
    """ 
    main entry point for module execution
    """
    argument_spec = dict(ss_plug=dict(required=True),
                         name=dict(required=False))

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=False)
    result = dict(changed=False)

    smart = SmartStrip(module.params['ss_plug'])

    result['plugs'] = ss_get_plugs(smart, module.params['name'])

    module.exit_json(**result)
Exemplo n.º 6
0
    def get_smart_strip(self, max_ip=200):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('10.255.255.255', 1))
        ip = s.getsockname()[0]
        s.close()
        loc = '.'.join(ip.split('.')[:-1])

        idx = 0
        while True:
            if idx > max_ip:
                break
            try:
                strip = SmartStrip('{}.{}'.format(loc, idx))
                return strip
            except SmartDeviceException:
                idx += 1
                pass
        return
Exemplo n.º 7
0
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)
Exemplo n.º 8
0
def get_static_devices(config_data) -> SmartDevices:
    """Get statically defined devices in the config."""
    _LOGGER.debug("Getting static devices")
    lights = []
    switches = []

    for type_ in [CONF_LIGHT, CONF_SWITCH, CONF_STRIP, CONF_DIMMER]:
        for entry in config_data[type_]:
            host = entry["host"]

            if type_ == CONF_LIGHT:
                lights.append(SmartBulb(host))
            elif type_ == CONF_SWITCH:
                switches.append(SmartPlug(host))
            elif type_ == CONF_STRIP:
                for plug in SmartStrip(host).plugs.values():
                    switches.append(plug)
            # Dimmers need to be defined as smart plugs to work correctly.
            elif type_ == CONF_DIMMER:
                lights.append(SmartPlug(host))

    return SmartDevices(lights, switches)
Exemplo n.º 9
0
class TplinkStrip(Strip):
    def __init__(self, id: str, alias: str, host: str) -> None:

        Strip.__init__(self, id, alias, host, DeviceBrand.tp_link)
        self.native_api = SmartStrip(host)
        _LOGGER.debug(
            "Initializing tp-link smartplug: %s",
            self.host,
        )

        # self.initialize()

    def get_sysinfo(self) -> Dict:
        """Retrieve system information.

        :return: sysinfo
        :rtype dict
        :raises SmartDeviceException: on error
        """
        return self.native_api.sys_info

    @property
    def is_off(self) -> bool:
        """Return True if device is off.

        :return: True if device is off, False otherwise.
        :rtype: bool
        """
        return not self.native_api.is_on

    def get_is_off(self, *, index: int = -1) -> Any:
        """
        Returns whether device is off.
        :param index: plug index (-1 for all)
        :return: True if device is off, False otherwise, Dict without index
        :rtype: bool if index is provided
                Dict[int, bool] if no index provided
        :raises SmartStripException: index out of bounds
        """
        return self.native_api.get_is_off(index=index)

    @property
    def is_on(self) -> bool:
        """Return if the device is on.

        :return: True if the device is on, False otherwise.
        :rtype: bool
        :return:
        """
        return self.native_api.is_on

    def get_is_on(self, *, index: int = -1) -> Any:
        """
        Returns whether device is on.
        :param index: plug index (-1 for all)
        :return: True if device is on, False otherwise, Dict without index
        :rtype: bool if index is provided
                Dict[int, bool] if no index provided
        :raises SmartStripException: index out of bounds
        """
        return self.native_api.get_is_on(index=index)

    def turn_on(self, *, index: int = -1):
        """
        Turns outlets on
        :param index: plug index (-1 for all)
        """
        return self.native_api.turn_on(index=index)

    def turn_off(self, *, index: int = -1):
        """
        Turns outlets off
        :param index: plug index (-1 for all)
        """
        return self.native_api.turn_off(index=index)

    @property
    def children_info(self) -> Dict[int, Any]:
        info = {}
        children_on_state = self.native_api.get_is_on()
        children_alias = self.native_api.get_alias()

        for child in children_on_state:
            info[child + 1] = {
                'is_on': children_on_state[child],
                'alias': children_alias[child]
            }

        return info

    @property
    def state_information(self) -> Dict[str, Any]:
        """Return device-type specific, end-user friendly state information.

        :return: dict with state information.
        :rtype: dict
        """
        return self.native_api.state_information
Exemplo n.º 10
0
    bulb.brightness = 5
def bulb_brightness_10():
    bulb.brightness = 10
def bulb_brightness_50():
    bulb.brightness = 50
def bulb_brightness_30():
    bulb.brightness = 30
def bulb_brightness_100():
    bulb.brightness = 100


### TPLINK KASA HS300
### Change the ip addresss accordingly

print('LOADING SMART-STRIP <--- HS300')
strip = SmartStrip("192.168.1.22")

# Plug1
def on_plug_0():
    strip.turn_on(index=0)
def off_plug_0():
    strip.turn_off(index=0)

# Plug2
def on_plug_1():
    strip.turn_on(index=1)
def off_plug_1():
    strip.turn_off(index=1)

# Plug3
def on_plug_2():
Exemplo n.º 11
0
parser = argparse.ArgumentParser("Cleanliness Check")
parser.add_argument(
    "-t",
    "--test",
    help=
    "Cleanliness check example run is executed with clean image 0 or dirty 1",
    type=int)
parser.add_argument("-i", "--image", help="Specify the image to use", type=str)
parser.add_argument("-o",
                    "--once",
                    help="Add this option to run the check just once",
                    action='store_true')
args = parser.parse_args()

# Set up smartplug connection
plug = SmartStrip("192.168.1.131")


def take_picture():
    '''Take a picture of the current room state
    '''
    print('Taking picture of room')
    # Turn on light before image is taken
    plug.turn_on(index=0)
    # Initialize camera
    cam = cv2.VideoCapture(1)
    # Get image
    return_value, image = cam.read()
    cam.release()
    # Convert image to grayscale
    # gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)