-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrelay.py
More file actions
170 lines (157 loc) · 4.58 KB
/
relay.py
File metadata and controls
170 lines (157 loc) · 4.58 KB
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
#!/usr/bin/python3
import re
import time
import serial
import Queue
import config
import threading
import requests
import gpiozero
from flask import Flask
relays = [gpiozero.LED(x) for x in [4, 22, 6, 26]]
outlets = ["a"]
power_switch = "http://10.0.0.23/outlet{}?{}"
app = Flask(__name__)
state = "off"
state_enter_time = 0
commands = Queue.Queue()
display_status = {}
for i in config.DISPLAYS:
display_status[i] = {
"DISPLAY.POWER": "OFF"
}
def delayThread():
global state
global state_enter_time
while True:
if state == "boot_wait":
for i in display_status.keys():
if display_status[i]["DISPLAY.POWER"] != "ON":
if time.time() - state_enter_time > 60:
state = "off"
state_enter_time = time.time()
print("Failed to turn on display, timed out.")
break
else:
state = "on"
state_enter_time = time.time()
for i in display_status.keys():
serialCommand("DISPLAY.POWER", selected=i)
elif state == "on":
for i in display_status.keys():
serialCommand("DISPLAY.POWER", selected=i)
time.sleep(15)
def update_status(display, key, value):
global state
global state_enter_time
if not display in display_status.keys():
print("Unknown display {} ({}={})".format(display, key, value))
return
if key in display_status[display].keys():
if display_status[display][key] == value:
return
display_status[display][key] = value
print("Updated {} ({}={})".format(display, key, value))
if state == "boot_wait":
if key == "SYSTEM.STATE":
if value == "READY":
for i in display_status.keys():
if "SYSTEM.STATE" in display_status[i].keys():
if display_status[i]["SYSTEM.STATE"] != "READY":
break
else:
serialCommand("DISPLAY.POWER", value="ON", selected="**")
state = "on"
state_enter_time = time.time()
else:
serialCommand("SYSTEM.STATE", selected=display)
if state == "on":
if key == "DISPLAY.POWER":
if value == "OFF":
serialCommand("DISPLAY.POWER", value="ON", selected=display)
def serialThread():
pending = []
with serial.Serial(config.SERIAL_PORT, config.SERIAL_BAUDRATE, timeout=1) as port:
resp = bytearray()
while True:
try:
while True:
command = commands.get(block=False)
for i in pending:
if i[0] == command:
break
else:
pending.append([command, time.time()])
port.write(command)
except Queue.Empty:
pass
now = time.time()
for i in pending:
if i[1] < now - 3:
port.write(i[0])
i[1] = now
char = port.read()
if char == '\r':
try:
string = resp.decode('ASCII')
resp = bytearray()
except UnicodeDecodeError:
resp = bytearray()
continue
pattern = re.compile(r'(OP|KY|ST)([A-Z]\d)([A-Z\d\.]+)=(.+)')
match = pattern.match(string)
if match:
if match.group(1) == "OP":
target = match.group(2)
key = match.group(3)
value = match.group(4)
pending = [x for x in pending if not x[0].startswith("OP{}{}".format(target, key))]
update_status(target, key, value)
else:
print("Unmatched: {}".format(string))
else:
if char:
resp.append(char)
def serialCommand(command, value="", cmd_type="OP", selected="A1", target=""):
cmd = "{}{}{}".format(cmd_type, selected, command)
if target:
cmd += "({})".format(target)
if value:
cmd += "={}\r".format(value)
else:
cmd += "?\r"
commands.put(cmd.encode('ASCII'))
@app.route("/status")
def get_status():
return state
@app.route("/on")
def on():
global state
global state_enter_time
state = "boot_wait"
state_enter_time = time.time()
for i in display_status.keys():
serialCommand("SYSTEM.STATE", selected=i)
for i in relays:
i.on()
for i in outlets:
requests.get(power_switch.format('on', i), auth=('admin', 'admin'))
return "success"
@app.route("/off")
def off():
global state
global state_enter_time
state = "off"
state_enter_time = time.time()
for i in relays:
i.off()
for i in outlets:
requests.get(power_switch.format('off', i), auth=('admin', 'admin'))
return "success"
off()
serialThreadHandle = threading.Thread(target=serialThread)
serialThreadHandle.daemon = True
serialThreadHandle.start()
delayThreadHandle = threading.Thread(target=delayThread)
delayThreadHandle.daemon = True
delayThreadHandle.start()