Ejemplo n.º 1
0
def allSwitchesOff():
    dehumid = SmartPlug(plugs['Fan'])
    dehumid.turn_off()

    fan = SmartPlug(plugs['Dehumidifier'])
    fan.turn_off()
    return 'Hi!'
Ejemplo n.º 2
0
def command(message):
	msgList = message.split('_')
	if(msgList[0] == "wifiplug"):
		try:
			if('add' in msgList[1]):
				addNewPlug(int(msgList[2])) 
				return	

			id = int(msgList[1]) - 1
			print ips[id]
			if(msgList[2] == "on"):
				plug = SmartPlug(ips[id])
				print("Current state: %s" % plug.state)
				plug.state = "ON"
				return

			if(msgList[2] == "off"):
				plug = SmartPlug(ips[id])
				print("Current state: %s" % plug.state)
				plug.state = "OFF"
				return

		except ValueError:
			logging.warning('Invalid command: Incorrect id format')
			return
		except Exception as e:
			logging.warning(e)
			return
Ejemplo n.º 3
0
    def changeSmartPlug(self, deviceName, state, command=False):
        # Logic for handling sibling devices and turning the current device on or off through a smart plug.
        siblingDevice = acChanger.getActuators().get(deviceName).get("siblingDevice")
        if state == "ON":
            # Logic for substituting sibling devices when the current device has too many consecutive uses
            device = acChanger.checkCount(deviceName, siblingDevice, command)
        else:
            device = deviceName

        # If the device is substituted and is on the breadboard,function for handling breadboard devices is called.
        if self._actuators.get(device).get("type") != "SmartPlug":
            return acChanger.changeBreadBoard(device, state)
        else:
            # Changing the smart plug state.
            try:
                if state == "ON":
                    SmartPlug(self._actuators.get(
                        device).get("device")).turn_on()
                    self._actuators.get(device)["ON"] = True
                else:
                    SmartPlug(self._actuators.get(
                        device).get("device")).turn_off()
                    self._actuators.get(device)["ON"] = False
                return True
            except:
                return False
Ejemplo n.º 4
0
Archivo: common.py Proyecto: 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)
Ejemplo n.º 5
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]
Ejemplo n.º 6
0
def ping_plug(ip_addr):
    try:
        plug = SmartPlug(ip_addr)
        plug.get_sysinfo()
        logger.info("Plug %s is up and running!", ip_addr)
    except SmartDeviceException:
        logger.error("Failed to connect to the plug with IP %s", ip_addr)
Ejemplo n.º 7
0
def set_plug(name, state, plugdict, plugip, plugnames):

# TODO Not currently used!  Trying to encapsulate state call & error checking to pull it out of main
# This is a mess!  Need to consolidate get_plugs and probably put everything in a big dict to pass across fxns

# name is the name of the room / plug
# state is the desired state ('ON' or 'OFF')

    named_flag = True

    plugips = plugip

    try:

        plugdict[name].state = state

    except:

        plugips = get_plugs(plugips, plugnames, named_flag)[0]

        try:

            plugdict[name] = SmartPlug(plugips[name])

        except:

            print("Communication error in ", name)

    return
Ejemplo n.º 8
0
def cli(ctx, ip, 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 None:
        click.echo("No IP given, trying discovery..")
        ctx.invoke(discover)
        return

    elif ip is not None:
        if not bulb and not plug:
            click.echo("No --bulb nor --plug given, discovering..")
            devs = ctx.invoke(discover, discover_only=True)
            for discovered_ip, discovered_dev in devs:
                if discovered_ip == ip:
                    dev = discovered_dev
                    break
        elif bulb:
            dev = SmartBulb(ip)
        elif plug:
            dev = SmartPlug(ip)
        else:
            click.echo("Unable to detect type, use --bulb or --plug!")
            return
        ctx.obj = dev

    if ctx.invoked_subcommand is None:
        ctx.invoke(state)
Ejemplo n.º 9
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the TPLink switch platform."""
    from pyHS100 import SmartPlug
    host = config.get(CONF_HOST)
    name = config.get(CONF_NAME)

    add_devices([SmartPlugSwitch(SmartPlug(host), name)], True)
Ejemplo n.º 10
0
 def status(self):
     try:
         settings.plugins.lights[self.room]
     except Exception:
         return
     try:
         self.isOpen(9999)
     except Exception:
         return
     type = settings.plugins.lights[self.room]['type']
     if type == 'plug':
         emoji = ':electric_plug:'
         tplinklight = SmartPlug(
             settings.plugins.lights[self.room]['ipaddr'])
     else:
         emoji = ':bulb:'
         type = 'light'
         tplinklight = SmartBulb(
             settings.plugins.lights[self.room]['ipaddr'])
     if eval(os.environ['DEBUG']):
         debug = "[{}] ".format(device_name)
     else:
         debug = ""
     room_name = self.room.capitalize()
     if room_name.endswith('s'):
         room_name = room_name[:-1] + "'" + room_name[-1:]
     if tplinklight.state == "OFF":
         chat.post("{} {}{} {} is off.".format(emoji, debug, room_name,
                                               type))
     else:
         chat.post("{} {}{} {} is on.".format(emoji, debug, room_name,
                                              type))
Ejemplo n.º 11
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
Ejemplo n.º 12
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)
Ejemplo n.º 13
0
def cancel_temp():
    auth = request.args.get('auth')
    if auth == "cabin":
        time_now = datetime.now(gmt)
        string_time = time_now.strftime("%d/%m/%y %H:%M:%S")
        plug_log = open("/d1/cabin_log.txt", "a")
        plug = SmartPlug("192.168.1.144")
        temp = read_temp()
        plug_status_file = open("/d1/webserver/reaching_optimum.txt", "r")
        cabin_plug_status = plug_status_file.read()
        plug_status_file.close()
        if cabin_plug_status == "1":
            GPIO.output(17, GPIO.LOW)
            GPIO.output(27, GPIO.LOW)
            plug_log.write(
                string_time +
                " /cancel-temp heating cancelled, current temperature is: " +
                str(temp) + "\n")
            plug_log.close()
            plug_status_file = open("/d1/webserver/reaching_optimum.txt", "w")
            plug.turn_off()
            plug_status_file.write("0")
            plug_status_file.close()
            return jsonify({"message": "Heating cancelled.", "status": "ok"})
        else:
            plug_log.write(string_time +
                           " /cancel-temp plug not on, temperature is: " +
                           str(temp) + "\n")
            plug_log.close()
            return jsonify({
                "message": "Plug is not on so unable to cancel heating.",
                "status": "error"
            })
    else:
        return jsonify({"message": "unauthorised", "status": "error"})
Ejemplo n.º 14
0
def main():
    """
    Print the water level and temperature every second
    :return:
    """
    # create the spi bus
    spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)

    # create the cs (chip select)
    cs = digitalio.DigitalInOut(board.D22)

    # create the mcp object
    mcp = MCP.MCP3008(spi, cs)

    # create an analog input channel on pin 0
    water_level_sensor = AnalogIn(mcp, MCP.P0)

    # create temperature sensor
    temp_sensor = W1ThermSensor()

    pump = SmartPlug(PUMP_IP)
    heater = SmartPlug(HEATER_IP)

    while True:
        temperature = temp_sensor.get_temperature()
        print(
            f"The temperature is {temperature} C, {celsius_to_fahrenheit(temperature)} F"
        )
        print(f"ADC Voltage: {round(water_level_sensor.voltage, 2)}V")
        water_level = get_water_level_inches(water_level_sensor.voltage)
        print(f"Water Level: {water_level} inches")
        print("\n")

        if temperature < HEATER_CUTOFF_CELSIUS:
            print("Turning heater on")
            heater.turn_on()
        else:
            print("Turning heater off")
            heater.turn_off()

        if water_level < PUMP_CUTOFF_INCHES:
            print("Turning pump on")
            pump.turn_on()
        else:
            print("Turning pump off")
            pump.turn_off()
        time.sleep(1)
Ejemplo n.º 15
0
 def __init__(self, name, ip):
     self.name = name
     self.ip = ip
     print(name, ip, type(ip), len(ip))
     self.plug = SmartPlug(ip)
     self.logger = GetLogger('hs100')
     self.logger.info("Link to an HS100 at {0} with name {1}.".format(
         ip, name))
Ejemplo n.º 16
0
def tplink_consumption(ip):
    plug = SmartPlug(ip)
    # read meter information und parse JSON
    pluginfo = json.loads(str(json.dumps(plug.get_emeter_realtime())))
    # filter for total power consumption
    consumption = pluginfo['total']
    # return consumption
    return consumption
Ejemplo n.º 17
0
    def _device_for_type(host, type_):
        dev = None
        if type_ == CONF_LIGHT:
            dev = SmartBulb(host)
        elif type_ == CONF_SWITCH:
            dev = SmartPlug(host)

        return dev
Ejemplo n.º 18
0
def camerac1():
    plug = SmartPlug("Insert IP Address here")
    print("Current state: %s" % plug.state)
    if (plug.state == 'ON'):
        plug.turn_off()
    else:
        plug.turn_on()

    return jsonify(data)
Ejemplo n.º 19
0
    def __init__(self, id: str, alias: str, host: str) -> None:

        Plug.__init__(self, id, alias, host, DeviceBrand.tp_link)

        self.native_api = SmartPlug(host)
        _LOGGER.debug(
            "Initializing tp-link smartplug: %s",
            self.host,
        )
Ejemplo n.º 20
0
async def test_configuring_devices_from_multiple_sources(hass):
    """Test static and discover devices are not duplicated."""
    with patch(
            "homeassistant.components.tplink.common.Discover.discover"
    ) as discover, patch(
            "homeassistant.components.tplink.common.SmartDevice._query_helper"
    ), patch(
            "homeassistant.config_entries.ConfigEntries.async_forward_entry_setup"
    ):
        discover_device_fail = SmartPlug("123.123.123.123")
        discover_device_fail.get_sysinfo = MagicMock(
            side_effect=SmartDeviceException())

        discover.return_value = {
            "123.123.123.1": SmartBulb("123.123.123.1"),
            "123.123.123.2": SmartPlug("123.123.123.2"),
            "123.123.123.3": SmartBulb("123.123.123.3"),
            "123.123.123.4": SmartPlug("123.123.123.4"),
            "123.123.123.123": discover_device_fail,
            "123.123.123.124": UnknownSmartDevice("123.123.123.124"),
        }

        await async_setup_component(
            hass,
            tplink.DOMAIN,
            {
                tplink.DOMAIN: {
                    CONF_LIGHT: [{
                        CONF_HOST: "123.123.123.1"
                    }],
                    CONF_SWITCH: [{
                        CONF_HOST: "123.123.123.2"
                    }],
                    CONF_DIMMER: [{
                        CONF_HOST: "123.123.123.22"
                    }],
                }
            },
        )
        await hass.async_block_till_done()

        assert len(discover.mock_calls) == 1
        assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 3
        assert len(hass.data[tplink.DOMAIN][CONF_SWITCH]) == 2
Ejemplo n.º 21
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_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))
            # Dimmers need to be defined as smart plugs to work correctly.
            elif type_ == CONF_DIMMER:
                lights.append(SmartPlug(host))

    return SmartDevices(lights, switches)
Ejemplo n.º 22
0
    def setDeviceStatus(self, postmsg):
        setDeviceStatusResult = True
        ip = self.get_variable("ip")
        port = self.get_variable("port")
        p = SmartPlug(ip)

        if postmsg['status'] == 'ON':
            p.turn_on()
        if postmsg['status'] == 'OFF':
            p.turn_off()
Ejemplo n.º 23
0
 def __init__(self,
              host: str,
              protocol: 'TPLinkSmartHomeProtocol' = None) -> None:
     SmartPlug.__init__(self, host, protocol)
     self.emeter_type = "emeter"
     self.plugs = {}
     children = self.sys_info["children"]
     self.num_children = len(children)
     for plug in range(self.num_children):
         self.plugs[plug] = SmartPlug(host, protocol,
                                      context=children[plug]["id"])
Ejemplo n.º 24
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Initialise pyLB100 SmartBulb."""
    from pyHS100 import SmartBulb
    from pyHS100 import SmartPlug
    host = config.get(CONF_HOST)
    name = config.get(CONF_NAME)
    device_type = config.get(CONF_DEVICE_TYPE)

    if device_type == "dimmer":
        add_entities([TPLinkSmartDimmer(SmartPlug(host), name)], True)
    else:
        add_entities([TPLinkSmartBulb(SmartBulb(host), name)], True)
Ejemplo n.º 25
0
def tplink_hash(ip):
    plug = SmartPlug(ip)
    # read hw information und parse JSON
    pluginfo = json.loads(str(json.dumps(plug.hw_info)))
    # hash
    plughash = hashlib.sha1()
    # hash hw id
    plughash.update(pluginfo['hwId'].encode())
    # build hash for ETH
    hash_s = "0x" + plughash.hexdigest() + "862ba9e16088902221101976"
    # return hash
    return hash_s
Ejemplo n.º 26
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)
Ejemplo n.º 27
0
 def __init__(
     self, host: str, protocol: TPLinkSmartHomeProtocol = None, cache_ttl: int = 3
 ) -> None:
     SmartPlug.__init__(self, host=host, protocol=protocol, cache_ttl=cache_ttl)
     self.emeter_type = "emeter"
     self._device_type = DeviceType.Strip
     self.plugs = {}
     children = self.sys_info["children"]
     self.num_children = len(children)
     for plug in range(self.num_children):
         self.plugs[plug] = SmartPlug(
             host, protocol, context=children[plug]["id"], cache_ttl=cache_ttl
         )
Ejemplo n.º 28
0
    def __init__(self, ip):

        self.plug = SmartPlug(ip)
        self.name = self.plug.alias

        while True:
            self.today = datetime.date.today()

            try:
                self.write(self.read())
            except Exception as e:
                print("Current Stats Exception: {}".format(e))

            time.sleep(1)
Ejemplo n.º 29
0
    def getDeviceStatus(self):

        ip = self.get_variable("ip")
        port = self.get_variable("port")
        p = SmartPlug(ip)
        emeter_info = p.get_emeter_realtime()
        self.set_variable('status', str(p.state))

        try:
            self.set_variable('current', str(emeter_info['current']))
            self.set_variable('voltage', str(emeter_info['voltage']))
            self.set_variable('power', str(emeter_info['power']))
        except:
            print("no energy measument modul")
        self.printDeviceStatus()
Ejemplo n.º 30
0
async def test_is_dimmable(hass):
    """Test that is_dimmable switches are correctly added as lights."""
    with patch("pyHS100.Discover.discover") as discover, patch(
            "homeassistant.components.tplink.light.async_setup_entry",
            return_value=mock_coro(True),
    ) as setup, patch("pyHS100.SmartDevice._query_helper"), patch(
            "pyHS100.SmartPlug.is_dimmable", True):
        dimmable_switch = SmartPlug("123.123.123.123")
        discover.return_value = {"host": dimmable_switch}

        await async_setup_component(hass, tplink.DOMAIN, {tplink.DOMAIN: {}})
        await hass.async_block_till_done()

    assert len(discover.mock_calls) == 1
    assert len(setup.mock_calls) == 1
    assert len(hass.data[tplink.DOMAIN][CONF_LIGHT]) == 1
    assert not hass.data[tplink.DOMAIN][CONF_SWITCH]