class TpLinkHandler(SmartDeviceException):
    def __init__(self, address):
        self.device = SmartPlug(address)

    def update(self):
        asyncio.run(self.device.update())

    def update_two(self):
        asyncio.create_task(self.device.update())

    def shutdown_btn(self):
        asyncio.create_task(self.device.turn_off())
        return "shutdown"

    def turnOn_btn(self):
        asyncio.create_task(self.device.turn_on())
        return "Turning on"

    def shutdown(self):
        asyncio.run(self.device.turn_off())
        return "shutdown"

    def turnOn(self):
        asyncio.run(self.device.turn_on())
        return "Turning on"

    def get_plug_information(self):
        return self.device.hw_info

    def __repr__(self):
        pass
Exemplo n.º 2
0
def switch_plug():
    p = SmartPlug("192.168.0.51")

    try:
        asyncio.run(p.update())
    except SmartDeviceException as e:
        logging.error("Could not reach smart plug...")
        sys.exit(e)

    if p.is_on:
        asyncio.run(p.turn_off())
    else:
        asyncio.run(p.turn_on())

    asyncio.run(p.update())
    print("The plug is on: ",  p.is_on)
Exemplo n.º 3
0
def switch(request):
    if request.method == 'POST':
        post_data = json.loads(request.body.decode("utf-8"))
        plug_name = post_data.get('name', None)
        try:
            switch = get_switch(plug_name)
        except ValueError:
            return JsonResponse({'error': 'invalid name'})
        
        command = post_data.get('command', None)
        if command == 'on':
            if switch.is_on:
                return JsonResponse({'error': 'already on'})
            asyncio.run(switch.turn_on())
            return JsonResponse({'success': f"{plug_name} turned on"})

        elif command == 'off':
            if not switch.is_on:
                return JsonResponse({'error': 'already off'})
            asyncio.run(switch.turn_off())
            return JsonResponse({'success': f"{plug_name} turned off"})
        else:
            print(command)

    if request.method == 'GET':
        switches = get_all_switches()
        if not switches:
            switches = []
            for s in SWITCHES:
                switch = SmartPlug(s['ip'])
                asyncio.run(switch.update())
                switches.append(switch)
        switches = [{'name': switch.alias, 'is_on': switch.is_on} for switch in switches]
        return JsonResponse({'switches': switches})
Exemplo n.º 4
0
def get_switch(switch_name: str):
    found_devices = asyncio.run(Discover.discover())
    device = [
        dev for addr, dev in found_devices.items() if dev.alias == switch_name
    ]
    if len(device) != 1:
        if switch_name not in [s['alias'] for s in SWITCHES]:
            raise ValueError("Invalid Name")
        s = [s for s in SWITCHES if s['alias'] == switch_name][0]
        switch = SmartPlug(s['ip'])
        asyncio.run(switch.update())
        return switch
    return device[0]
class TpLinkHandlerSmartPlug(SmartDeviceException):
    def __init__(self, address):
        self.device = SmartPlug(address)

    def update(self):
        asyncio.run(self.device.update())

    def update_two(self):
        asyncio.create_task(self.device.update())

    def update_three(self):
        future = asyncio.run_coroutine_threadsafe(self.device.update(),
                                                  self.worker.loop)
        result = future.result()

    def shutdown_btn(self, settings):
        asyncio.create_task(self.device.turn_off())
        return "shutdown"

    def turnOn_btn(self, settings):
        asyncio.create_task(self.device.turn_on())
        return "Turning on"

    def shutdown(self):
        asyncio.run(self.device.turn_off())
        return "shutdown"

    def turnOn(self):
        asyncio.run(self.device.turn_on())
        return "Turning on"

    def get_plug_information(self):
        return self.device.hw_info

    def __repr__(self):
        pass
Exemplo n.º 6
0
    def scan():
        """Check whether the smart plug is on.

        After checking the smart plug, we perform a poll operation, as
        in ``poll()``.

        Normally, we rely on the contents of the state file to determine
        whether the smart plug is on. However, this assumes that only
        ``BatteryController`` turns it on and off. If something else
        turns it on or off, we should call ``scan()`` to ensure that
        ``BatteryController`` picks up the change.
        """
        BatteryController._ping_plug()
        plug = SmartPlug(BatteryController._PLUG_IP_ADDRESS)
        asyncio.run(plug.update())
        with BatteryController._lock():
            status = BatteryController._read_state()
            status['currentState'] = plug.is_on
            BatteryController._poll(status)
Exemplo n.º 7
0
def create_device_from_ip_or_scan(ip, device_name):
    """Tries to create a kasa SmartDevice object either from a given IP address
    or by scanning the network."""
    device = None
    if ip:
        try:
            device = SmartPlug(ip)
            asyncio.run(device.update())
        except exceptions.SmartDeviceException:
            print(
                "Unable to connect to device at provided IP. Attempting scan.")

    # If unable to create device from ip, or ip is not given, scan the network.
    if not device:
        devices = asyncio.run(Discover.discover())
        for _, dev in devices.items():
            if dev.alias == device_name:
                asyncio.run(dev.update())
                device = dev

    return device
Exemplo n.º 8
0
def off():
    plug = SmartPlug("192.168.178.23")
    asyncio.run(plug.update())
    asyncio.run(plug.turn_off())
    return redirect("/")
Exemplo n.º 9
0
def status():
    plug = SmartPlug("192.168.178.23")
    asyncio.run(plug.update())
    return {'host': plug.host, 'state': plug.is_on}
Exemplo n.º 10
0
from astral import LocationInfo
from astral.sun import sun
from datetime import date, datetime, timedelta
from apscheduler.schedulers.blocking import BlockingScheduler
from kasa import SmartPlug
import asyncio
import os

IP_ADDRESS = "192.168.1.3"
scheduler = BlockingScheduler()
plug = SmartPlug(IP_ADDRESS)
asyncio.run(plug.update())
os.environ['TZ'] = 'America/New_York'


def main():
    print(f"{datetime.now()} - Adding Daily Job To Scheduler")
    print(datetime.now())
    scheduler.add_job(schedule_on_and_off_time,
                      'cron',
                      hour=18,
                      minute=50,
                      misfire_grace_time=300)

    try:
        print(f"{datetime.now()} - Scheduler Starting")
        scheduler.start()
    except (KeyboardInterrupt, SystemExit):
        pass

Exemplo n.º 11
0
class LightControl:

	def __init__(self, ip=None):
		self._ip = ip
		self._plug = None
		self._args = None

	def parse_args(self):
		parser = argparse.ArgumentParser(prog="light")
		parser.add_argument('command', choices=['on', 'off', 'status'])
		parser.add_argument('--verbose', '-v', action='count', default=0)
		parser.add_argument('-ip', help='IP address of smart plug', default=None)
		self._args = parser.parse_args()
		self._debug(self._args, 3)
		self._debug('debug level only goes to 3 (-vvv)', 4)
		if hasattr(self._args, 'ip') and self._args.ip is not None:
			self._debug('loading ip from sys.argv', 3)
			self._ip = self._args.ip
		else:
			self._debug('loading ip from environment', 3)
			load_dotenv()
			self._ip = os.getenv('LIGHT_CONTROL_IP_ADDR')
		if self._ip is None:
			self._debug(f'Invalid IP address (actual {self._ip} expected XX.XX.XX.XX)')
			sys.exit()
		if verify_ip(self._ip) == False:
			self._debug(f'Invalid IP address (actual {self._ip} expected XX.XX.XX.XX)')
			sys.exit()
		self._debug(f'ip address is set to {self._ip}', 1)

	def run_command(self):
		self._initalize_device()
		if self._args.command == 'on':
			self._on()
		elif self._args.command == 'off':
			self._off()
		elif self._args.command == 'status':
			self._status()
		else:
			print(f"command not valid (actual {self._args.command} expected one of {'on', 'off', 'status'}")

	def _initalize_device(self):
		# self._ip
		self._plug = SmartPlug(self._ip)
		asyncio.run(self._plug.update())
		self._debug(f'connected to plug: {self._plug.alias}', 1)

	def _on(self):
		asyncio.run(self._plug.turn_on())
		if self._verify_state(True):
			self._debug('light is turned on', 1)
		else:
			self._debug('light failed to turn on')

	def _off(self):
		asyncio.run(self._plug.turn_off())
		if self._verify_state(False):
			self._debug('light is turned off', 1)
		else:
			self._debug('light failed to turn off')

	def _status(self):
		if self._verify_state(True):
			self._debug('light is turned on', 0)
		else:
			self._debug('light is turned off', 0)


	def _verify_state(self, state):
		asyncio.run(self._plug.update())
		return self._plug.is_on == state

	def _debug(self, msg, level=0):
		if level <= self._args.verbose:
			print("-"*level, end="")
			print(msg)