commit 69a443c8a804de303235e2ad2652dbd0b10e5263 Author: vuko Date: Mon Nov 23 12:08:38 2020 +0100 initial version flask with active status polling diff --git a/app.py b/app.py new file mode 100644 index 0000000..66c858d --- /dev/null +++ b/app.py @@ -0,0 +1,62 @@ +import flask +import threading +import paho.mqtt as mqtt +import paho.mqtt.client +import paho.mqtt.publish +import re +import json +c = threading.Condition() +application = flask.Flask(__name__) +application.msg="ab" +application.lights = [False, False, False, False] + +def on_message(client,userdata,message): + c.acquire() + application.msg = str(message.payload) + print(message.payload) + light_status = re.compile('devices/light_[^/]+/light_([0-9]+)/on') + m = light_status.search(message.topic) + if m: + n = int(m.group(1)) + if n > 0 and n < 5: + if message.payload == "true": + application.lights[n-1] = True + else: + application.lights[n-1] = False + + + c.release() + print("MQTT Thread: " + str(threading.current_thread())) + +mc = mqtt.client.Client() +mc.username_pw_set("light","MG4Dhp6vCZjgbTzJ") +mc.connect("10.8.1.16") +mc.on_message = on_message +mc.subscribe("devices/#") +mc.loop_start() + +@application.route("/") +def main(): + return flask.render_template('index.html') + +@application.route("/status") +def status(): + print("Main Thread: " + str(threading.current_thread())) + c.acquire() + st = {"lights" : application.lights} + c.release() + return json.dumps(st) + +@application.route('/light//on/set/true', methods=['POST']) +def set_light(lid): + mqtt.publish.single("devices/light_904649/light_" + str(lid) + "/on/set", "true", qos=1, hostname="10.8.1.16", auth = {'username':"light", 'password':"MG4Dhp6vCZjgbTzJ"}) + return "Succes" + +@application.route('/light//on/toggle', methods=['POST']) +def toggle_light(lid): + mqtt.publish.single("devices/light_904649/light_" + str(lid) + "/on/toggle", "true", qos=1, hostname="10.8.1.16", auth = {'username':"light", 'password':"MG4Dhp6vCZjgbTzJ"}) + return "Succes" + +if __name__ == "__main__": + application.run(host='127.0.0.1',port=8000,debug=True) + diff --git a/templates/index.html b/templates/index.html new file mode 100644 index 0000000..035db33 --- /dev/null +++ b/templates/index.html @@ -0,0 +1,101 @@ + + + + + title + + + +

Warsaw Hackespace lights switching panel

+ + + + + + + + + + + + + + + + +