Last active
September 23, 2020 10:50
-
-
Save devilholk/aa329c5d4ac24d1073be4ee5cf6fa25b to your computer and use it in GitHub Desktop.
Script that controls an external circuit to keep the laptops battery voltage within nominal voltage. The DTR signal is used to control the circuit.
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
#/sys/bus/acpi/drivers/battery/PNP0C0A:00/power_supply/BAT0 | |
#See https://i.imgur.com/yuVyiW7.png for picture of the böp this controls | |
import sys, serial, time | |
min_voltage = 3.5 | |
max_voltage = 3.8 | |
interval = 300 #Every 5 minutes | |
def read_num(filename): | |
with open(filename, 'r') as infile: | |
return float(infile.__next__()) | |
def get_voltage(max_voltage=4.20): | |
return max_voltage * read_num('energy_now') / read_num('energy_full') | |
def control_loop(): | |
current_state = None #Unknown | |
s = serial.Serial('/dev/ttyUSB0') | |
try: | |
while True: | |
v = get_voltage() | |
print(time.ctime(), 'MEASURE', v, file=sys.stderr) | |
if v < min_voltage: | |
if current_state is None or current_state == False: | |
print(time.ctime(), 'ON', file=sys.stderr, flush=True) | |
s.setDTR(False) | |
current_state = True | |
elif v > max_voltage: | |
if current_state is None or current_state == True: | |
print(time.ctime(), 'OFF',file=sys.stderr, flush=True) | |
s.setDTR(True) | |
current_state = False | |
time.sleep(interval) | |
except KeyboardInterrupt: | |
s.close() | |
return | |
if __name__ == '__main__': | |
print(time.ctime(), 'START', file=sys.stderr, flush=True) | |
control_loop() | |
print(time.ctime(), 'STOP', file=sys.stderr, flush=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment