-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdevlolwebstatus
executable file
·118 lines (90 loc) · 2.97 KB
/
devlolwebstatus
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#!/usr/bin/python3
from http.server import BaseHTTPRequestHandler,HTTPServer
import paho.mqtt.client as paho
import logging,sys
import argparse
spaceOpen = False
brokerHost = "mqtt.devlol.org"
mqttTopic = "devlol/h19/door/lockstatus"
class MyHandler(BaseHTTPRequestHandler):
def do_HEAD(client):
client.send_response(200)
client.send_header("Content-type", "text/html")
client.end_headers()
def do_GET(self):
global spaceOpen
if self.path == "/":
self.send_response(200)
self.send_header("Content-type", "image/png")
self.end_headers()
if spaceOpen:
logging.info("return OPEN")
try:
self.wfile.write(load_binary('assets/open.png'))
except BrokenPipeError:
pass
else:
logging.info("return CLOSED")
try:
self.wfile.write(load_binary('assets/closed.png'))
except BrokenPipeError:
pass
def load_binary(file):
with open(file, 'rb') as file:
return file.read()
def load(file):
with open(file, 'r') as file:
return encode(str(file.read()))
def encode(file):
return bytes(file, 'UTF-8')
def on_message(client, userdata, msg):
global spaceOpen
payload = msg.payload.decode("utf-8")
logging.debug(payload)
""" Callback for mqtt message."""
if payload == "UNLOCKED":
spaceOpen = True
logging.info("received mqtt: UNLOCKED")
elif payload == "LOCKED":
spaceOpen = False
logging.info("received mqtt: LOCKED")
def on_disconnect(client, userdata, foo):
connected = False
while not connected:
try:
client.reconnect()
connected = True
# resubscribe to the topics
client.subscribe(mqttTopic)
except:
logging.error("Failed to reconnect mqtt...")
time.sleep(1)
def run(server_class=HTTPServer,
handler_class=MyHandler):
parser = argparse.ArgumentParser()
parser.add_argument("-p", default=8321, help="port to bind to", type=int)
parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true")
args = parser.parse_args()
port = args.p
if args.verbose:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.ERROR)
## setup MQTT client
client = paho.Client()
client.on_message = on_message
client.on_disconnect = on_disconnect
try:
client.connect(brokerHost)
logging.info ("connected to mqtt")
except:
logging.error("failed to connect to mqtt")
on_disconnect(client, None, None)
client.subscribe(mqttTopic)
server_address = ('', port)
httpd = server_class(server_address, handler_class)
while True:
httpd.handle_request()
client.loop()
if __name__ == "__main__":
run()