home/home/app.py
2022-05-25 09:28:54 +02:00

207 lines
7.1 KiB
Python

"""Flask app"""
import datetime
import json
import os
import shutil
import threading
import time
import xmlrpc.client
from flask import Flask
from flask import render_template
from flask import make_response
from flask import request
from flask import jsonify
CONFIG_FILE = os.path.join(os.path.expanduser('~'), ".config/home/config.json")
class Control(threading.Thread):
"""Control"""
def __init__(self, config_file_name: str):
threading.Thread.__init__(self)
self.run_condition = True
self.config = None
self.config_file = config_file_name
self.water_state = []
def reload_config(self):
"""Reload config"""
try:
with open(self.config_file, "r", encoding="UTF-8") as handle:
self.config = json.load(handle)
except FileNotFoundError:
# create default config
os.makedirs(os.path.dirname(self.config_file), exist_ok=True)
shutil.copyfile("config.json", self.config_file)
with open(self.config_file, "r", encoding="UTF-8") as handle:
self.config = json.load(handle)
for _ in range(len(self.config['configs'])):
self.water_state.append(False)
def run(self):
while self.run_condition:
configs = self.config['configs']
water_index = 0
for config in configs:
water = config["water"]
autostate = water["autostate"]
if autostate:
times = water["times"]
idx = 0
now = datetime.datetime.now()
if int(now.hour) >= 12:
idx = 1
on_time_pattern = times[idx]['on_time']
on_time_pattern = on_time_pattern.split(':')
on_time = now.replace(hour=int(on_time_pattern[0]),
minute=int(on_time_pattern[1]),
second=0,
microsecond=0)
off_time_pattern = times[idx]['off_time']
off_time_pattern = off_time_pattern.split(':')
off_time = now.replace(hour=int(off_time_pattern[0]),
minute=int(off_time_pattern[1]),
second=0,
microsecond=0)
url = "http://" + config["host"] + ":" + str(config["port"])
if now > on_time and now <= off_time and not self.water_state[water_index]:
client = xmlrpc.client.ServerProxy(url)
client.switch_relay(water["relay"], True)
self.water_state[water_index] = client.get_relay_state(water["relay"])
elif now > off_time and self.water_state[water_index]:
client = xmlrpc.client.ServerProxy(url)
client.switch_relay(water["relay"], False)
self.water_state[water_index] = client.get_relay_state(water["relay"])
water_index += 1
time.sleep(1)
control = Control(CONFIG_FILE)
app = Flask(__name__)
@app.route('/', methods=['GET'])
def index():
"""Handle GET to index.html"""
return render_template('index.html')
@app.route('/hochbeet', methods=['GET'])
def hochbeet():
"""Handle GET to index.html"""
return render_template('hochbeet.html')
@app.route('/tomatentuppen', methods=['GET'])
def tomatentuppen():
"""Handle GET to index.html"""
return render_template('tomatentuppen.html')
@app.route('/sample/<idx>', methods=['GET'])
def get_sample(idx='0'):
"""Handle GET to /sample/<idx>"""
response = make_response("", 404)
with open(CONFIG_FILE, "r", encoding="UTF-8") as handle:
config = json.load(handle)
for cfg in config["configs"]:
if cfg["id"] == idx:
water = cfg["water"]
relay = int(water["relay"])
res = {}
url = "http://" + cfg["host"] + ":" + str(cfg["port"])
client = xmlrpc.client.ServerProxy(url)
water = {}
water['id'] = str(idx)
water['state'] = client.get_relay_state(relay)
res['water'] = water
response = make_response(jsonify(res), 200)
break
return response
@app.route('/sample/<idx>', methods=['PATCH'])
def patch_sample(idx='0'):
"""Handle PATCH to /sample"""
record = json.loads(request.data)
response = make_response("", 404)
if 'id' in record:
with open(CONFIG_FILE, "r", encoding="UTF-8") as handle:
config = json.load(handle)
for cfg in config["configs"]:
if cfg["id"] == idx:
water = cfg["water"]
relay = int(water["relay"])
url = "http://" + cfg["host"] + ":" + str(cfg["port"])
client = xmlrpc.client.ServerProxy(url)
client.switch_relay(relay, record["waterstate"])
response = make_response("", 204)
break
return response
@app.route('/config/<idx>', methods=['GET'])
def get_config(idx='0'):
"""Hadnle GET to config/<idx>"""
response = make_response("", 404)
with open(CONFIG_FILE, "r", encoding="UTF-8") as handle:
config = json.load(handle)
for cfg in config["configs"]:
if cfg["id"] == idx:
water = cfg["water"]
res = {}
res["water"] = water
response = make_response(jsonify(res), 200)
break
return response
@app.route('/config/<idx>', methods=['PATCH'])
def patch_config(idx="0"):
"""Handle PATCH to /config/<idx>"""
record = json.loads(request.data)
response = make_response("", 404)
config = None
with open(CONFIG_FILE, "r", encoding="UTF-8") as handle:
config = json.load(handle)
count = -1
for cfg in config["configs"]:
count += 1
if cfg["id"] == idx:
water = record['water']
if 'autostate' in water:
config["configs"][count]["water"]["autostate"] = water["autostate"]
if 'times' in water:
config["configs"][count]["water"]["times"] = water["times"]
break
if config:
with open(CONFIG_FILE, "w", encoding="UTF-8") as handle:
json.dump(config, handle)
# prepare answer
res = {}
water = {}
water['id'] = idx
water['autostate'] = config["configs"][count]["water"]["autostate"]
water['times'] = config["configs"][count]["water"]["times"]
res['water'] = water
response = make_response(jsonify(res), 200)
control.reload_config()
return response
def start_control():
"""Helper to start the control thread"""
control.reload_config()
control.start()
if __name__ == 'app':
start_control()
app.run(debug=True, host='0.0.0.0', port=8000)