-
Notifications
You must be signed in to change notification settings - Fork 0
/
WebRelay.py
executable file
·412 lines (309 loc) · 12.4 KB
/
WebRelay.py
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
#!/usr/bin/env python2.7
import datetime
import zlib
import gevent
from gevent import monkey, spawn as gspawn, sleep as gsleep, socket, signal_handler as sig
monkey.patch_all()
import signal
import os
import configparser
import logging
import schedule
import bottle
import requests
from bottle import get, request, route, static_file, auth_basic
from gevent.pywsgi import WSGIServer
import time
import bcrypt
from astral import Astral
from termcolor import colored
import RPi.GPIO as GPIO
from passlib.hash import sha256_crypt
configFile = "WebRelay.ini"
myLogFile = "WebRelay.log"
myBlacklist = "blacklist.ips"
myCity = ""
myDepression = ""
myAddress = ""
myPort = ""
myAdmin = ""
myPasswd = ""
myNormally = ""
mySwitches = list()
serverStartTime = "1970/01/01 00:00"
serverLastInit = "1970/01/01 00:00"
plan = ""
iftttKey = ""
lastFailed = time.time()
myTimeGap = 30
failedIPs = {}
blockAfter = 10
class Switch:
Name = ""
GPIOchannel = 0
Type = "Sun"
Status = False
timeOn = "00:00"
timeOff = "00:01"
imgTop = "0px"
imgLeft = "0px"
def jobRelayOn(self):
# print(colored("{} turned on {}, type {}".format(self.Name, self.GPIOchannel, self.Type), 'green'))
self.Status = True
if myNormally == "closed":
GPIO.output(int(self.GPIOchannel), GPIO.LOW)
else:
GPIO.output(int(self.GPIOchannel), GPIO.HIGH)
logging.info("+++ [%s] turned on %s (%s)", self.Name, self.GPIOchannel, self.Type)
# sendMessage(self.Name + " turned on")
def jobRelayOff(self):
# print(colored("{} turned off {}, type {}".format(self.Name, self.GPIOchannel, self.Type), 'red'))
self.Status = False
if myNormally == "closed":
GPIO.output(int(self.GPIOchannel), GPIO.HIGH)
else:
GPIO.output(int(self.GPIOchannel), GPIO.LOW)
logging.info("--- [%s] turned off %s (%s)", self.Name, self.GPIOchannel, self.Type)
def Start(self):
# print(colored("Schedule \"{}\" started using {} on {}, off {}".format(self.Name, self.GPIOchannel, self.timeOn, self.timeOff), "blue"))
schedule.every().day.at(str(self.timeOn)).do(self.jobRelayOn).tag(self.Name)
schedule.every().day.at(str(self.timeOff)).do(self.jobRelayOff).tag(self.Name)
GPIO.setmode(GPIO.BCM)
GPIO.setup(int(self.GPIOchannel), GPIO.OUT)
now = datetime.datetime.now()
today = datetime.date.today()
t = datetime.datetime.strptime(self.timeOn, '%H:%M').time()
myTimeOn = datetime.datetime.combine(today, t)
t = datetime.datetime.strptime(self.timeOff, '%H:%M').time()
myTimeOff = datetime.datetime.combine(today, t)
self.jobRelayOff()
if ((myTimeOn > myTimeOff) and (now > myTimeOn)):
self.jobRelayOn()
elif ((myTimeOn > myTimeOff) and (now < myTimeOff)):
self.jobRelayOn()
if (myTimeOn < myTimeOff) and (now > myTimeOn) and (now < myTimeOff):
self.jobRelayOn()
logging.info("^^^ Schedule [%s] started using %s on %s, off %s", self.Name, self.GPIOchannel, self.timeOn, self.timeOff)
# sendMessage(self.Name + " schdeuled on: " + self.timeOn + " off: " + self.timeOff)
def Stop(self):
# print(colored("Schdeule \"{}\" stopped".format(self.Name), "blue"))
schedule.clear(self.Name)
logging.info("Schdeule [%s] stopped", self.Name)
def crc(fileName):
prev = 0
for eachLine in open(fileName,"rb"):
prev = zlib.crc32(eachLine, prev)
return "%X"%(prev & 0xFFFFFFFF)
configCRC = crc(configFile)
def loadConfig(file = configFile):
config = configparser.RawConfigParser()
config.read(file)
logging.debug("*** Loading config file from %s ***", file)
for e in config.sections():
if e == "Global":
global myCity
global myDepression
global myAddress
global myPort
global plan
global myAdmin
global myPasswd
global myNormally
global iftttKey
myCity = config["Global"]["City"]
myDepression = config["Global"]["Depression"]
myAddress = config["Global"]["Address"]
myPort = config["Global"]["Port"]
plan = config["Global"]["Plan"]
myAdmin = config["Global"]["user"]
myPasswd = config["Global"]["passwd"].encode('utf-8')
myNormally = config["Global"]["normally"]
iftttKey = config["Global"]["iftttKey"]
logging.debug("Loaded global settings. City: %s, Depression: %s, web: %s@%s:%s Notifications key: %s, Relays are normally %s", myCity, myDepression, myAdmin, myAddress, myPort, iftttKey, myNormally)
else:
s = Switch()
s.Name = e
for name, value in config.items(e):
if name=="type":
s.Type = value
elif name=="gpiochannel":
s.GPIOchannel = value
elif name=="timeon":
s.timeOn = value
elif name=="timeoff":
s.timeOff = value
elif name=="imgtop":
s.imgTop = value
elif name=="imgleft":
s.imgLeft = value
logging.debug("Loaded [%s] Type: %s, Channel: %s, TimeON: %s, TimeOFF: %s, X: %s, Y: %s", s.Name, s.Type, s.GPIOchannel, s.timeOn, s.timeOff, s.imgLeft, s.imgTop)
mySwitches.append(s)
a = Astral()
a.solar_depression = myDepression
city = a[myCity]
sun = city.sun(date=datetime.date(datetime.datetime.today().year, datetime.datetime.today().month, datetime.datetime.today().day), local=True)
duskh = str(sun['dusk'])[11:13]
duskm = str(sun['dusk'])[14:16]
dusk = duskh + ":" + duskm
logging.debug("%s dusk in %s today is %s", myDepression, myCity, dusk)
dawnh = str(sun['dawn'])[11:13]
dawnm = str(sun['dawn'])[14:16]
dawn = dawnh + ":" + dawnm
logging.debug("%s dawn in %s today is %s", myDepression, myCity, dawn)
GPIO.setmode(GPIO.BCM)
for s in mySwitches:
if s.Type == "Sun":
s.timeOn = dusk
s.timeOff = dawn
s.Start()
global serverLastInit
now = datetime.datetime.now()
serverLastInit = now.strftime("%Y/%m/%d %H:%M:%S")
logging.debug("*** Initialization is complete ***")
sendMessage ("Server config loaded. PID:" + str(os.getpid()))
def sendMessage (t1, t2 = "", t3 = ""):
requests.post("https://maker.ifttt.com/trigger/notify/with/key/" + iftttKey, params={"value1":t1,"value2":t2,"value3":t3})
def jobUpdateAstral():
a = Astral()
a.solar_depression = myDepression
city = a[myCity]
sun = city.sun(date=datetime.date(datetime.datetime.today().year, datetime.datetime.today().month, datetime.datetime.today().day), local=True)
duskh = str(sun['dusk'])[11:13]
duskm = str(sun['dusk'])[14:16]
dusk = duskh + ":" + duskm
logging.debug("New %s dusk in %s is set to %s", myDepression, myCity, dusk)
dawnh = str(sun['dawn'])[11:13]
dawnm = str(sun['dawn'])[14:16]
dawn = dawnh + ":" + dawnm
logging.debug("New %s dawn in %s is set to %s", myDepression, myCity, dawn)
for s in mySwitches:
if s.Type == "Sun":
s.Stop()
s.timeOn = dusk
s.timeOff = dawn
logging.info(">>> Astral updated %s and %s", dusk, dawn)
s.Start()
def ReLoadConfig():
global mySwitches
for s in mySwitches:
s.Stop()
del s
mySwitches *= 0
loadConfig()
def jobCheckConfig():
global configCRC
if configCRC == crc(configFile):
logging.debug("Configuration unchaged")
else:
logging.debug("Configuration chaged! Reloading...")
ReLoadConfig()
configCRC = crc(configFile)
def setSchedule():
schedule.every(1).minutes.do(jobCheckConfig)
schedule.every().day.at("12:00").do(jobUpdateAstral)
def startServer():
now = datetime.datetime.now()
global serverStartTime
serverStartTime = now.strftime("%Y/%m/%d %H:%M:%S")
def start_thread():
while True:
try:
schedule.run_pending()
except Exception as e:
print(str(e))
gsleep(1)
gspawn(start_thread)
def FailedLogin(src_ip):
global lastFailed
global myBlacklist
global myTimeGap
if time.time() - lastFailed <= myTimeGap:
lastFailed = time.time()
if failedIPs.get(src_ip) == None:
failedIPs[src_ip] = 1
else:
failedIPs[src_ip] = failedIPs[src_ip] + 1
if failedIPs[src_ip] >= blockAfter:
f = open(myBlacklist, "a+")
f.write(src_ip)
f.close()
sendMessage("Bruteforce blocked from " + src_ip)
res = ""
# res = os.popen("ufw deny from " + scr_ip).read()
logging.warning("Added to blacklist %s: %s", src_ip, res)
def isAuthUser(user, passwd):
global myAdmin
global myPasswd
if user == myAdmin and myPasswd == bcrypt.hashpw(passwd.encode('utf-8'), myPasswd[:29]):
from_ip = request.environ.get('REMOTE_ADDR')
logging.debug("Successful login from %s", from_ip)
return True
else:
FailedLogin(request.environ.get('REMOTE_ADDR'))
logging.warning("!!! Failed login from %s", request.environ.get('REMOTE_ADDR'))
logging.debug("L: %s, P: %s", user, passwd)
logging.debug("Client: %s", request.environ.get('HTTP_USER_AGENT'))
# sendMessage("Failed login attempt from " + request.environ.get('REMOTE_ADDR') + " " + request.environ.get('HTTP_USER_AGENT') + " Username: " + user + " Password: " + passwd)
return False
@get('/<filename>')
def img(filename):
return static_file(filename, root="/home/pi/Relay/img")
@get('/')
@auth_basic(isAuthUser)
def app():
global mySwitches
try:
WebAction = request.query["action"]
except:
WebAction = ""
try:
toggleName = request.query["toggle"]
except:
toggleName = ""
if toggleName:
for s in mySwitches:
if toggleName == s.Name:
s.Type = "Manual"
if s.Status:
s.jobRelayOff()
s.Stop()
else:
s.jobRelayOn()
s.Stop()
if WebAction == "reloadConfig": ReLoadConfig()
global plan
res = "<html>\n<head>\n<title>WebRelay</title>\n</head>\n\n\n<body>\n"
res += "<img src=\"" + plan + "\"/>\n"
for s in mySwitches:
if s.Status:
if s.Type == "Manual":
res += "<a href=\"?toggle=" + s.Name + "\"><img src=\"on.png\" style=\"position: absolute; top: " + s.imgTop + "; left: " + s.imgLeft + "\" title=\"" + s.Name + " (Manual)\"/></a>"
else:
res += "<a href=\"?toggle=" + s.Name + "\"><img src=\"on.png\" style=\"position: absolute; top: " + s.imgTop + "; left: " + s.imgLeft + "\" title=\"" + s.Name + " (triggered by " + s.Type + ", on: " + s.timeOn + " off: " + s.timeOff + ")\"/></a>"
else:
if s.Type == "Manual":
res += "<a href=\"?toggle=" + s.Name + "\"><img src=\"off.png\" style=\"position: absolute; top: " + s.imgTop + "; left: " + s.imgLeft + "\" title=\"" +s.Name + " (Manual)\"/></a>"
else:
res += "<a href=\"?toggle=" + s.Name + "\"><img src=\"off.png\" style=\"position: absolute; top: " + s.imgTop + "; left: " + s.imgLeft + "\" title=\"" +s.Name + " (triggered by " + s.Type + ", on: " + s.timeOn + " off: " + s.timeOff + ")\"/></a>"
res += "<br>\n<br>\nServer started on: " + serverStartTime + " <a href=\"/\">[Refresh]</a> Last config loaded on: " + serverLastInit + " <a href=\"?action=reloadConfig\">[reload]</a>"
logTail = os.popen("tail -n16 " + myLogFile).read()
res += "<hr>\n<pre>\n" + logTail + "</pre>\n"
res += "</body>\n</html>\n"
return res
if __name__ == '__main__':
logging.basicConfig(filename=myLogFile, format='%(asctime)s - %(message)s', level=logging.INFO, datefmt='%y/%m/%d %H:%M:%S')
logging.getLogger('schedule').setLevel(logging.WARNING)
loadConfig()
setSchedule()
startServer()
botapp = bottle.app()
server = WSGIServer((myAddress, int(myPort)), botapp)
GPIO.setwarnings(False)
def shutdown():
logging.info("Shutting down...")
GPIO.cleanup()
server.stop(timeout=5)
exit(signal.SIGTERM)
sig(signal.SIGTERM, shutdown)
sig(signal.SIGINT, shutdown)
server.serve_forever()