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"})
class TplinkPlug(Plug): 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, ) # 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 self.native_api.is_off def turn_on(self) -> None: """Turn device on.""" return self.native_api.turn_on() def turn_off(self) -> None: """Turn device off.""" return self.native_api.turn_off() @property def is_on(self) -> bool: """Return if the device is on. :return: True if the device is on, False otherwise. :rtype: bool :return: """ try: return self.native_api.is_on except: return None @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
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
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)
class PlugHandler(object): def __init__(self): self.plug = SmartPlug(plug_devices['living_room']) def switch_on(self): try: if self.plug.state == 'OFF': self.plug.turn_on() return 'switched on.' else: return 'already Switched on.' except Exception as e: print e return 'Try Again.' def switch_off(self): try: if self.plug.state == 'ON': self.plug.turn_off() return 'switched off.' else: return 'already Switched off.' except Exception as e: print e return 'Try Again.'
class Fan: FAN_OFF_DELAY = 500.0 def __init__(self, fan_ip, logger): self.logger = logger self.state = False self.changing = False self.fan_ip = fan_ip self.plug = SmartPlug(self.fan_ip) def fan_off(self): try: self.plug.turn_off() self.logger.info("Turned fan off") except Exception: self.logger.warning("Outlet is down") self.changing = False def should_be(self, heat): if heat == HEAT_ON: try: if self.plug.is_off: self.plug.turn_on() self.logger.info("Turned fan on") except Exception: self.logger.warning("Outlet is down") self.state = True try: if heat == HEAT_OFF and self.plug.is_on and self.changing is False: self.logger.info("Turning fan off") self.changing = True Timer(self.FAN_OFF_DELAY, self.fan_off).start() except Exception: self.logger.warning("Outlet is down")
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)
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
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))
def add_entity(device: SmartPlug, async_add_entities): """Check if device is online and add the entity.""" # Attempt to get the sysinfo. If it fails, it will raise an # exception that is caught by async_add_entities_retry which # will try again later. device.get_sysinfo() async_add_entities([SmartPlugSwitch(device)], update_before_add=True)
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, )
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"])
class DigitalDevice(RaspberiumDevice): def __init__(self, address): super().__init__() self.digitalOutputDevice = SmartPlug(address) def on(self): self.digitalOutputDevice.turn_on() self.digitalOutputDevice.led = True def off(self): self.digitalOutputDevice.turn_off() self.digitalOutputDevice.led = False
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 )
class HS100(): 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)) def state(self): return self.plug.state def turn_on(self): self.plug.turn_on() self.logger.info("Turn on {0} (HS100).".format(self.name)) def turn_off(self): self.plug.turn_off() self.logger.info("Turn off {0} (HS100).".format(self.name)) def switch(self): if self.state() == SmartPlug.SWITCH_STATE_OFF: self.plug.turn_on() else: self.plug.turn_off() self.logger.info("Switch {0} (HS100) to {1}.".format( self.name, self.state()))
def allSwitchesOff(): dehumid = SmartPlug(plugs['Fan']) dehumid.turn_off() fan = SmartPlug(plugs['Dehumidifier']) fan.turn_off() return 'Hi!'
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)
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()
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)
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
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 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
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)
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)
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))
def _device_for_type(host, type_): dev = None if type_ == CONF_LIGHT: dev = SmartBulb(host) elif type_ == CONF_SWITCH: dev = SmartPlug(host) return dev
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
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)
def restart_plug(ip_addr, delay): """ Restarts a smart plug: powers it OFF and, then, ON Args: ip_addr: IP address of the smart plug delay: the time to wait before powering plug ON after it was powered OFF """ try: plug = SmartPlug(ip_addr) if plug.state == "ON": plug.turn_off() threading.Timer(delay, plug.turn_on).start() else: threading.Timer(delay, plug.turn_on).start() logger.info("Restart successful!") except SmartDeviceException: #TODO: add retrying to communicate again after timeout, if after multiple retry attempts it still failes, send email or Telegram logger.error("Failed to communicate with plug at IP address %s!", ip_addr)
async def test_unload(hass, platform): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=tplink.DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.tplink.get_static_devices" ) as get_static_devices, patch( "homeassistant.components.tplink.common.SmartDevice._query_helper" ), patch( f"homeassistant.components.tplink.{platform}.async_setup_entry", return_value=mock_coro(True), ) as async_setup_entry: config = { tplink.DOMAIN: { platform: [{ CONF_HOST: "123.123.123.123" }], CONF_DISCOVERY: False, } } light = SmartBulb("123.123.123.123") switch = SmartPlug("321.321.321.321") switch.get_sysinfo = MagicMock( return_value=SMARTPLUG_HS110_DATA["sysinfo"]) switch.get_emeter_realtime = MagicMock( return_value=EmeterStatus(SMARTPLUG_HS110_DATA["realtime"])) if platform == "light": get_static_devices.return_value = SmartDevices([light], []) elif platform == "switch": get_static_devices.return_value = SmartDevices([], [switch]) assert await async_setup_component(hass, tplink.DOMAIN, config) await hass.async_block_till_done() assert len(async_setup_entry.mock_calls) == 1 assert tplink.DOMAIN in hass.data assert await tplink.async_unload_entry(hass, entry) assert not hass.data[tplink.DOMAIN]