forked from frustratedgeek/PiServer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
355 lines (286 loc) · 12.7 KB
/
server.py
File metadata and controls
355 lines (286 loc) · 12.7 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
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
## ----- IMPORTS -----
from flask import Flask, render_template, request, jsonify, make_response, Response
from datetime import datetime, timedelta
from threading import Thread
import random
import time
import os
import sys
import math
import ast
from urllib2 import urlopen
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(38, GPIO.OUT)
GPIO.output(38, GPIO.LOW)
GPIO.setup(40, GPIO.OUT)
GPIO.output(40, GPIO.LOW)
try:
from lib import IOPiPlus1
th = Thread(target=IOPiPlus1.readLoop)
th.setDaemon(True)
th.start()
except:
pass
from lib import lighting
from lib import heating
from lib import userControl
from lib import network
from lib import timings
from lib import flags
from lib import schedule
from lib import threads
from lib import power
from lib import appliances
## ----- GLOBAL VARIABLES -----
app = Flask(__name__)
localIpStart = '192.168.1.'
## ----- THREADS -----
th = Thread(target=threads.getMeasuredRoomValues)
th.setDaemon(True)
th.start()
th = Thread(target=threads.getNetworkSpeeds)
th.setDaemon(True)
th.start()
th = Thread(target=threads.pingPC)
th.setDaemon(True)
th.start()
th = Thread(target=threads.runSchedule)
th.setDaemon(True)
th.start()
th = Thread(target=heating.heatingDetectLoop)
th.setDaemon(True)
th.start()
@app.route('/divs/<string:destination>')
def contents(destination):
return render_template(str(destination) + '.html',)
## ----- JSON PAGE DATA -----
@app.route('/pageData/<string:hour>', methods=['GET'])
def pageData(hour):
## TOP DISPLAY
topMessage = userControl.welcomeMessage(str(hour))
## MASTER
customColour = userControl.customStyle('colour')
customOpacity = userControl.customStyle('opacity')
## PI CONTROL
cpuUsage = power.readStatus('currentCpuUsag')
cpuFrequency = power.readStatus('currentCpuFreq')
cpuTemp = power.readStatus('currentCpuTemp')
ping = threads.networkSpeedStatus(0)
download = threads.networkSpeedStatus(1)
upload = threads.networkSpeedStatus(2)
userAddress = power.readStatus('userIpAddress')
publicAddress = power.readStatus('publicIpAddres')
routerAddress = power.readStatus('routerIpAddres')
serverAddress = power.readStatus('localIpAddress')
primaryRelaySatus = str(power.powerRelayStatus('primary'))
auxRelaySatus = str(power.powerRelayStatus('aux'))
## SETTINGS
settingsMessage = userControl.settingsStat()
passwordMessage = userControl.passwordStat()
## SCHEDULE
scheduleStatus = schedule.pauseStatus()
scheduleMessage = schedule.scheduleMessage()
## LIGHTING
hallLight = lighting.status('hall')
kitchenMainLight = lighting.status('kitchenMain')
kitchenSecondLight = lighting.status('kitchenAmbient')
spareLight = lighting.status('bedroom2')
masterMainLight = lighting.status('bedroom1Main')
masterSecondLight = lighting.status('bedroom1Ambient')
loungeLight = lighting.status('lounge')
bathroomLight = lighting.status('bathroom')
## HEATING
hallHeater = heating.status('hall')
kitchenHeater = heating.status('kitchen')
spareHeater = heating.status('bedroom2')
masterHeater = heating.status('bedroom1')
loungeHeater = heating.status('lounge')
bathroomHeater = heating.status('bathroom')
other1Heater = heating.status('other1')
other2Heater = heating.status('other2')
heaterStart = heating.getHeaterTime('start')
heaterEnd = heating.getHeaterTime('end')
## APPLIANCES
pcStatus = appliances.pcStatus()
## MEASURED ROOM VALUES
kitchenLightReading = int(round(threads.measuredValue('kitchen', 'light'),0))
kitchenTemperatureReading = int(round(threads.measuredValue('kitchen', 'temperature'),0))
kitchenHumidityReading = int(round(threads.measuredValue('kitchen', 'humidity'),0))
bathroomLightReading = int(round(threads.measuredValue('bathroom', 'light'),0))
bathroomTemperatureReading = int(round(threads.measuredValue('bathroom', 'temperature'),0))
bathroomHumidityReading = int(round(threads.measuredValue('bathroom', 'humidity'),0))
hallLightReading = int(round(threads.measuredValue('hall', 'light'),0))
hallTemperatureReading = int(round(threads.measuredValue('hall', 'temperature'),0))
hallHumidityReading = int(round(threads.measuredValue('hall', 'humidity'),0))
loungeLightReading = int(round(threads.measuredValue('lounge', 'light'),0))
loungeTemperatureReading = int(round(threads.measuredValue('lounge', 'temperature'),0))
loungeHumidityReading = int(round(threads.measuredValue('lounge', 'humidity'),0))
bedroom1LightReading = int(round(threads.measuredValue('bedroom1', 'light'),0))
bedroom1TemperatureReading = int(round(threads.measuredValue('bedroom1', 'temperature'),0))
bedroom1HumidityReading = int(round(threads.measuredValue('bedroom1', 'humidity'),0))
bedroom2LightReading = int(round(threads.measuredValue('bedroom2', 'light'),0))
bedroom2TemperatureReading = int(round(threads.measuredValue('bedroom2', 'temperature'),0))
bedroom2HumidityReading = int(round(threads.measuredValue('bedroom2', 'humidity'),0))
averageLightReading = int(round(threads.measuredValue('average', 'light'),0))
averageTemperatureReading = int(round(threads.measuredValue('average', 'temperature'),0))
averageHumidityReading = int(round(threads.measuredValue('average', 'humidity'),0))
## RETURN
return jsonify(topMessage=[topMessage],
customColour=[customColour], customOpacity=[customOpacity],
cpuUsage=[cpuUsage], cpuFrequency=[cpuFrequency], cpuTemp=[cpuTemp], ping=[ping], download=[download], upload=[upload], userAddress=[userAddress], publicAddress=[publicAddress],
routerAddress=[routerAddress], serverAddress=[serverAddress], primaryRelaySatus=[primaryRelaySatus], auxRelaySatus=[auxRelaySatus],
settingsMessage=[settingsMessage], passwordMessage=[passwordMessage],
scheduleStatus=[scheduleStatus], scheduleMessage=[scheduleMessage],
hallLight=[hallLight], kitchenMainLight=[kitchenMainLight], kitchenSecondLight=[kitchenSecondLight], spareLight=[spareLight], masterMainLight=[masterMainLight],
masterSecondLight=[masterSecondLight], loungeLight=[loungeLight], bathroomLight=[bathroomLight],
hallHeater=[hallHeater], kitchenHeater=[kitchenHeater], spareHeater=[spareHeater], masterHeater=[masterHeater], loungeHeater=[loungeHeater], bathroomHeater=[bathroomHeater],
other1Heater=[other1Heater], other2Heater=[other2Heater], heaterStart=[heaterStart], heaterEnd=[heaterEnd],
pcStatus=[pcStatus],
kitchenLightReading=kitchenLightReading, kitchenTemperatureReading=kitchenTemperatureReading, kitchenHumidityReading=kitchenHumidityReading,
bathroomLightReading=bathroomLightReading, bathroomTemperatureReading=bathroomTemperatureReading, bathroomHumidityReading=bathroomHumidityReading,
hallLightReading=hallLightReading, hallTemperatureReading=hallTemperatureReading, hallHumidityReading=hallHumidityReading,
loungeLightReading=loungeLightReading, loungeTemperatureReading=loungeTemperatureReading, loungeHumidityReading=loungeHumidityReading,
bedroom1LightReading=bedroom1LightReading, bedroom1TemperatureReading=bedroom1TemperatureReading, bedroom1HumidityReading=bedroom1HumidityReading,
bedroom2LightReading=bedroom2LightReading, bedroom2TemperatureReading=bedroom2TemperatureReading, bedroom2HumidityReading=bedroom2HumidityReading,
averageLightReading=averageLightReading, averageTemperatureReading=averageTemperatureReading, averageHumidityReading=averageHumidityReading)
## ----- SETTINGS PAGE -----
def customSettings(x):
if x == 'opacity':
return (float(userControl.customStyle(x)))*100
else:
return userControl.customStyle(x)
@app.route('/saveSettings', methods=['POST'])
def saveSettings():
backgroundColour = str(request.form['backgroundColour'])
backgroundOpacity = str(round(float(str(request.form['backgroundOpacity']))/100, 2))
if network.validSession() == True:
userControl.setStyle(backgroundColour, backgroundOpacity)
return jsonify()
@app.route('/changePassword', methods=['POST'])
def changePassword():
## REMOVED
## ----- USER LOGIN CONTROL -----
@app.route('/')
def default():
## REMOVED
if ## REMOVED:
return render_template('master.html',)
elif ## REMOVED:
return ## REMOVED
else:
return render_template('login.html',)
@app.route('/login', methods=['POST'])
def login():
## REMOVED
if valid == True:
if user == 'shutdown':
flags.shutDown()
return render_template('login.html',)
else:
## REMOVED
## local host
if network.userAddress() == ## REMOVED:
return ## REMOVED
## local network
elif (network.userAddress()).startswith(localIpStart):
return ## REMOVED
## local via internet
elif network.userAddress() == network.currentPublicIP():
return ## REMOVED
## internet
else:
return ## REMOVED
else:
userControl.latestUser('write', user, 5)
return ## REMOVED
@app.route('/navigate', methods=['POST'])
def navigate():
current = request.form.get('here')
location = request.form.get('location')
if network.validSession() == True:
pass
else:
return render_template('login.html',)
@app.route('/logout', methods=['POST'])
def logout():
return network.logout()
def powerStatus():
return flags.powerStat()
## ----- PI CONTROL -----
@app.route('/powerRelay', methods=['POST'])
def powerRelay():
if network.validSession() == True:
circuit = str(request.form['circuit'])
confirm = str(request.form['confirm'])
power.powerRelays(circuit, confirm)
return jsonify()
@app.route('/piPower', methods=['POST'])
def piPower():
if network.validSession() == True:
action = str(request.form.get('action'))
confirmR = str(request.form.get('confirmRestart'))
confirmSD = str(request.form.get('confirmShutDown'))
if power.switch(action, confirmR, confirmSD) == True:
return render_template('login.html',)
else:
return render_template('piControl.html',)
else:
return render_template('login.html',)
## ----- LIGHTING -----
@app.route('/lightSwitch/<string:light>', methods=['POST'])
def lightSwitch(light):
if network.validSession() == True:
lighting.switch(str(light))
return jsonify()
## ----- HEATING -----
@app.route('/heaterSwitch/<string:heater>', methods=['POST'])
def heaterSwitch(heater):
if network.validSession() == True:
heating.switch(str(heater))
return jsonify()
## ----- APPLIANCES -----
@app.route('/applianceSwitch', methods=['POST'])
def applianceSwitch():
if network.validSession() == True:
appliance = str(request.form['appliance'])
confirm = str(request.form['confirm'])
appliances.switch(appliance, confirm)
return jsonify()
## ----- SCHEDULE -----
def scheduleTime(x):
return schedule.time(x)
@app.route('/pauseSchedule', methods=['POST'])
def pauseSchedule():
if network.validSession() == True:
schedule.pauseSchedule()
return jsonify()
@app.route('/saveSchedule', methods=['POST'])
def saveSchedule():
times = {'mondayMorning': '', 'mondayEvening': '', 'mondayWeekend': '',
'tuesdayMorning': '', 'tuesdayEvening': '', 'tuesdayWeekend': '',
'wednesdayMorning': '', 'wednesdayEvening': '', 'wednesdayWeekend': '',
'thursdayMorning': '', 'thursdayEvening': '', 'thursdayWeekend': '',
'fridayMorning': '', 'fridayEvening': '', 'fridayWeekend': '',
'saturdayMorning': '', 'saturdayEvening': '', 'saturdayWeekend': '',
'sundayMorning': '', 'sundayEvening': '', 'sundayWeekend': ''}
extra = {'morningLightLevel': '', 'eveningLightLevel': '', 'weekendLightLevel': ''}
for key in times:
times[key] = str(request.form[key])
for key in extra:
extra[key] = str(request.form[key])
checkboxData = ast.literal_eval(str(request.form['checkboxSelection']))
if network.validSession() == True:
schedule.setSchedule(times, extra, checkboxData)
return jsonify()
## ----- FUNCTIONS LIBRARY -----
app.jinja_env.globals.update(
powerStatus=powerStatus,
user=userControl.user,
scheduleTime=scheduleTime,
customSettings=customSettings,
)
## ----- END -----
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80, debug=False, threaded=True, use_reloader=False)