Created
June 19, 2021 04:03
-
-
Save slaiyer/596e73d83ed45137bd48c20a2f72bd49 to your computer and use it in GitHub Desktop.
Yeelight bulb switch
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 | |
"""Switch Yeelight bulb on or off.""" | |
import argparse as arg | |
import enum | |
import functools as func | |
import pathlib as path | |
import sys | |
import yeelight as y | |
@enum.unique | |
class PowerState(enum.Enum): | |
ON = 'on' | |
OFF = 'off' | |
def __str__(self): | |
return self.value | |
def main( | |
args: arg.Namespace, | |
) -> int: | |
"""Entry point.""" | |
switch_bulb = func.partial( | |
switch, | |
state=args.state, | |
duration=args.duration, | |
) | |
bulb_ip_file = path.Path(__file__).parent / 'bulb-ip' | |
try: | |
with open(bulb_ip_file, 'r') as file: | |
bulb_ip = file.readline().strip() | |
switch_bulb(bulb_ip=bulb_ip) | |
except (FileNotFoundError, y.BulbException): | |
bulb_ip = next( | |
iter(y.discover_bulbs()), | |
)['ip'].strip() | |
switch_bulb(bulb_ip=bulb_ip) | |
with open(bulb_ip_file, 'w') as file: | |
file.write(bulb_ip) | |
return 0 | |
def switch( | |
bulb_ip: str, | |
state: PowerState, | |
duration: int, | |
) -> None: | |
"""Sets power state of a bulb.""" | |
bulb = y.Bulb( | |
bulb_ip, | |
power_mode=y.PowerMode.HSV, | |
duration=duration, | |
) | |
bulb.turn_on() if state == PowerState.ON else bulb.turn_off() | |
if __name__ == '__main__': | |
parser = arg.ArgumentParser() | |
parser.add_argument( | |
'state', | |
type=PowerState, | |
choices=PowerState, | |
help='Desired power state', | |
) | |
parser.add_argument( | |
'--duration', | |
'-d', | |
type=int, | |
default=1, | |
help='Duration (s)', | |
) | |
arguments = parser.parse_args() | |
arguments.duration *= 1_000 | |
if not 50 < arguments.duration < (1 << 32): | |
raise arg.ArgumentTypeError('Invalid duration') | |
sys.exit( | |
main( | |
args=arguments, | |
), | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment