Skip to content

Instantly share code, notes, and snippets.

@phwelo
Created January 12, 2022 22:36
Show Gist options
  • Save phwelo/afb5faa2e4c84ad81f846e680c6fc25b to your computer and use it in GitHub Desktop.
Save phwelo/afb5faa2e4c84ad81f846e680c6fc25b to your computer and use it in GitHub Desktop.
Low is too high, so I'll try and turn it on and off at a frequency that leaves me comfortable...
#!/usr/bin/env python3
import argparse, atexit, os, subprocess, time
from datetime import datetime
tmpfile = "/tmp/heaterstate"
# it's going to be nicer to have this switch off when the script is killed
def exit_handler():
set_switch(args.ip, "off")
# argparse
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--percent", default="0", help="Percentage of heater on", type=int)
parser.add_argument("-i", "--ip", default="10.0.0.19", help="IP address of the heater", type=str)
return parser.parse_args()
# take percentage and convert it to on/off seconds out of a period of 30 seconds
def calc_secs(percent, period=30):
on_sec = (percent / 100) * period
off_sec = (100 - percent) / 100 * period
return on_sec, off_sec
# pull the single number percentage from storage file
def get_perc(filepath):
if os.path.exists(filepath):
with open(filepath) as f:
perc = f.read()
return int(perc)
# write the single number percentage to a file
def write_perc(filepath, perc):
with open(filepath, "w") as f:
f.write(str(perc))
# set the physical switch
def set_switch(ip, state):
# obv this would be better if i could figure out how to call natively with python
subprocess.call(["python3", "ouimeaux/client.py", "--device", ip, "--"+state])
print(datetime.now(), "Set switch to", state)
# derp main
def main():
# init
atexit.register(exit_handler)
global args
args = parse_args()
percentage = args.percent if args.percent>0 else get_perc(tmpfile)
write_perc(tmpfile, percentage) if args.percent>0 else None
off, on = calc_secs(percentage)
print(datetime.now(), "Init state: " , {"off":off, "on":on})
# loop
while True:
percentage = get_perc(tmpfile)
off, on = calc_secs(percentage)
set_switch(args.ip, "on")
time.sleep(on)
set_switch(args.ip, "off")
time.sleep(off)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment