Files
bg_shutdown/client/bs_shutdown.py
2026-02-25 13:42:03 +00:00

86 lines
1.9 KiB
Python

import urllib.request
import json
import socket
from datetime import datetime
import subprocess
import time
DEFAULT_SHUTDOWN = "21:00"
LAST_VALUE = 0
machine_name = socket.gethostname()
url = "http://192.168.50.27:5000/lookup"
payload = {
"name": machine_name,
}
def get_data():
data = json.dumps(payload).encode("utf-8")
req = urllib.request.Request(
url,
headers={"Content-Type": "application/json"},
data=data,
method="POST"
)
try:
with urllib.request.urlopen(req, timeout=10) as response:
data = response.read()
json_data = json.loads(data)
print(json_data)
return json_data
except:
return None
def to_seconds(t):
return t.hour * 3600 + t.minute * 60 + t.second
def set_shutdown(time, now):
global LAST_VALUE
if (time - now) < 0 or time == LAST_VALUE:
return
LAST_VALUE = time
print("[BS Shutdown] shutting down in " + str(time - now) + " seconds")
# subprocess.run(["shutdown", "/s", "/t", (time - now), " "])
def remove_shutdown():
print("[BS Shutdown] Removed shutdown")
# subprocess.run(["shutdown", "/a"])
def update():
global LAST_VALUE
data = get_data()
if data is not None and data["noshutdown"] == 1:
if (LAST_VALUE != 0):
remove_shutdown() # In case
LAST_VALUE = 0
return
if data is None:
time = to_seconds(datetime.strptime(DEFAULT_SHUTDOWN, "%H:%M").time())
else:
time = to_seconds(datetime.strptime(data["time"], "%H:%M").time())
now = to_seconds(datetime.now().time())
if (time - now) < 0:
return
if (time == LAST_VALUE):
return
if (LAST_VALUE != 0):
remove_shutdown()
print("[BS Shutdown] New value")
LAST_VALUE = time
set_shutdown(time, now)
if __name__ == '__main__':
while True:
update()
time.sleep(30)