fetch config from flask app

master
vuko 2020-11-23 16:35:08 +01:00
parent 681c7dd589
commit 504a9c038b
2 changed files with 166 additions and 29 deletions

117
app.py Normal file
View File

@ -0,0 +1,117 @@
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.send_file('static/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)
config = {
"mqtt_server": "sound.waw.hackerspace.pl",
"mqtt_port": 1881,
"mqtt_username": "light",
"mqtt_password": "MG4Dhp6vCZjgbTzJ",
"lights": {
"l1" : {
"enabled": True,
"mqtt_path": "devices/light_904649/light_2/on",
},
"l2": {
"enabled": True,
"mqtt_path": "devices/light_904649/light_3/on",
},
"l3": {
"enabled": True,
"mqtt_path": "devices/light_904649/light_1/on",
},
"l4": {
"enabled": True,
"mqtt_path": "iot/077521/relay/on",
},
"l7": {
"enabled": True,
"mqtt_path": "devices/light_904649/light_4/on",
},
}
}
@application.route("/config")
def get_config():
return flask.jsonify(config)
@application.route('/light/<lid>/on/set', methods=['POST'])
def set_light(lid):
if lid in config["lights"]:
mqtt.publish.single(
config["lights"][lid]["mqtt_path"] + "/set",
"true",
qos=1,
hostname=config["mqtt_server"],
auth = {
'username':config["mqtt_username"],
'password':config["mqtt_password"]
}
)
return flask.jsonify({"ok": True})
@application.route('/light/<lid>/on/toggle', methods=['POST'])
def toggle_light(lid):
if lid in config["lights"]:
mqtt.publish.single(
config["lights"][lid]["mqtt_path"] + "/toggle",
"true",
qos=1,
hostname=config["mqtt_server"],
auth = {
'username':config["mqtt_username"],
'password':config["mqtt_password"]
}
)
return flask.jsonify({"ok": True})
if __name__ == "__main__":
application.run(host='127.0.0.1',port=8000,debug=True)

View File

@ -108,14 +108,14 @@
id="l6"
width="2.625"
height="2.25"
x="7.4374995"
x="7.4375"
y="6.375"
ry="0.375" />
<rect
id="l7"
width="2.625"
height="2.25"
x="7.4374995"
x="7.4375"
y="9.374999"
ry="0.375" />
<rect
@ -151,48 +151,68 @@
</svg>
</div>
<script src="paho-mqtt.js"></script>
<script src="static/paho-mqtt.js"></script>
<script>
window.onload = function() {
var config_request = new XMLHttpRequest();
config_request.onreadystatechange = function() {
if (config_request.readyState == 4 && config_request.status == 200) {
onConfig(JSON.parse(config_request.responseText));
}
}
config_request.open("GET", "/config", true);
config_request.send(null);
}
var onConfig = function(config) {
var lights = [];
for (i = 1; i <= 8; i++) {
lights[i] = document.getElementById("l" + i);
lights[i].classList = ["light-disabled"];
id = "l" + i;
element = document.getElementById(id);
element.classList = ["light-disabled"];
lights[i] = {
"element": element,
"id" : id,
}
if ( id in config.lights ) {
lights[i].mqtt_path = config.lights[id].mqtt_path;
}
}
var mqtt_server = 'sound.waw.hackerspace.pl';
var mqtt_port = 1881;
var name = "web-client-" + Math.round(Math.random() * 100000);
console.log(name)
var client = new Paho.MQTT.Client(mqtt_server, Number(mqtt_port), "/", name);
var client = new Paho.MQTT.Client(config.mqtt_server, Number(config.mqtt_port), "/", name);
client.onMessageArrived = function(message) {
console.log(message)
var match = /devices\/light_904649\/light_(.*)\/on/.exec(message.topic);
var n = parseInt(match[1]);
if(~isNaN(n) && n > 0 && n <= 4){
if (message.payloadString == "true") {
lights[n].classList = ["light-on"];
} else {
lights[n].classList = ["light-off"];
}
for ( i in lights ) {
var light = lights[i];
if ( message.topic == light.mqtt_path ) {
if (message.payloadString == "true") {
light.element.classList = ["light-on"];
} else {
light.element.classList = ["light-off"];
}
}
}
};
function onConnect(){
for (i = 1; i <= 4; i++) {
client.subscribe("devices/light_904649/light_" + i + "/on");
lights[i].onclick=function(value){
return function(){
client.publish("devices/light_904649/light_" + value + "/on/toggle", 'true');
};
} (i);
};
document.getElementById("up").onclick = function(){
for (i = 1; i <= 8; i++) {
client.publish("devices/light_904649/light_" + i + "/on/set", 'true');
for ( i in lights ) {
light = lights[i];
if ( "mqtt_path" in light ) {
client.subscribe(light.mqtt_path);
};
light.element.onclick=function(light){
return function(){
client.publish(light.mqtt_path + "/toggle", "true");
};
}(light);
};
//document.getElementById("up").onclick = function(){
// for (i = 1; i <= 8; i++) {
// client.publish("devices/light_904649/light_" + i + "/on/set", 'true');
// };
//};
};
client.connect({