Last active
January 10, 2021 14:18
-
-
Save jerameel/5a3d260c93181650218e7e2fc01a975c to your computer and use it in GitHub Desktop.
A python script to automatically control yeelight bulb when a target device (mobile phone for example) is connected on a specific network. For example, Brighten/Dim light when user enters/leaves the proximity.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3.7 | |
import os | |
from datetime import datetime,timedelta | |
from yeelight import Bulb,Flow,BulbException | |
from yeelight.flows import night_mode | |
# MAC Address target devices | |
TARGET_DEVICES = [ | |
'00:00:00:00:00:00', | |
'00:00:00:00:00:00' | |
] | |
# Yeelight IP Address | |
LIGHT_IP = "X.X.X.X" | |
bulb = Bulb(LIGHT_IP, model='color', effect='smooth') | |
def is_client_online(): | |
retry = 0 | |
while retry < 3: | |
# Get connected devices on wlan.= | |
# This should be more reliable than ping | |
# But take note of the delay before the arp cache gets updated | |
scan_network = "arp -a -n | grep wlan" | |
network_list = os.popen(scan_network).read() | |
for HOST in TARGET_DEVICES: | |
if HOST in network_list: | |
return True | |
retry += 1 | |
return False | |
last_scan = None | |
is_previously_online = False | |
while True: | |
# on sunset, scan if target user is online | |
current_datetime = datetime.now() | |
current_hour = current_datetime.hour | |
# Between 6:00 PM and 11:00 PM | |
if (current_hour >= 18 and current_hour < 23): | |
# Scan every 10 seconds | |
if not last_scan or ((current_datetime - last_scan).total_seconds()) >= 10: | |
last_scan = current_datetime | |
is_currently_online = is_client_online() | |
if (is_currently_online != is_previously_online): | |
is_previously_online = is_currently_online | |
if (is_currently_online): | |
# if user is online, brighten light | |
print('Lights: In Use', current_datetime, flush=True) | |
try: | |
bulb.set_brightness(50) | |
except BulbException as error: | |
print(error) | |
try: | |
bulb.set_color_temp(3500) | |
except BulbException as error: | |
print(error) | |
else: | |
# if user is offline, dim light | |
print('Lights: Night Mode', current_datetime, flush=True) | |
try: | |
bulb.start_flow(night_mode()) | |
except BulbException as error: | |
print(error) | |
else: | |
# reset state when outside time range | |
if is_previously_online: | |
is_previously_online = False | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment