A short demo using python-kasa to control a Kasa EP10 WiFi smart plug, using a Pi.
Steps:
- provision the EP10 using the kasa CLI.
- Configure the python code for smart plug device name, location, off time.
- start a Pi cron job that executes the python code.
- watch a lamp go on around sunset, and off awhile later. Whee!
OS tested:
- Windows 10 (py 3.8), Ubuntu 22.04 (py 3.10), Raspberry Pi OS 11 bullseye on Pi 3B+ (py 3.9).
In the python code user supplies:
- smart plug name (alias). Use kasa CLI to provision. This is optional but convenient.
- Your location lat/lon (use google map.)
- off time (24 hr, hh:mm), in this example 12:05 am.
- adj min before/after sunset (+/- up to 15 min or so), in this example 5 min before sunset.
BOOTUP:
- When running on a Pi it's desired to run in the background upon bootup. Supplied is a simple cron.d script to do this on a Pi.
- If there's a power fail/restore the home router may take several minutes to reboot and acquire network devices. On a Pi delay code startup a few minutes to allow for this.
LOGIC:
- On startup,
- compare local time to on/off time and today's sunset, and turn plug on/off accordingly (in case Pi reboot.) plug_state = on/off
main loop:
- if plug_state=on, calc S seconds to off time
- else, calc S seconds to on time (sunset) with any adjust
- sleep S seconds
- (awaken)
- flip plug_state state
- plug = plug_state (on/off)
Errors:
- Not much error checking, exits if plug isn't found on startup.
- Removing (unplugging) plug will cause an exception. Code requires try / except SmartDeviceException error handling.
Modules likely needing install:
- pip install suntime
- pip install python-kasa
On github:
https://github.com/relwin/kasa-smart-plug-python-demo/tree/main
------------------------ provisioning notes ---------------------------------------------
For kasa CLI commands, refer to https://python-kasa.readthedocs.io/en/latest/cli.html#provisioning
First find the plug's wifi and connect to its network (use a laptop), its wifi SSID ends with its 4-digit MAC.
- Example: TP-LINK_Smart Plug_8714
Provision to your main router on 192.168.0.1:
kasa --host 192.168.0.1 wifi join 'your network SSID' --password routerspasswordorhexdigits
Shorten alias name:
kasa --alias "TP-LINK_Smart Plug_8714" alias "Plug_8714"
Test, turn on:
kasa --alias "Plug_8714" on