-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp.py
More file actions
322 lines (246 loc) · 12.4 KB
/
Copy pathapp.py
File metadata and controls
322 lines (246 loc) · 12.4 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
from flask import Flask, request, jsonify
from flask_mqtt import Mqtt
import json
import random
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from isdProjectImports import credentials
from isdProjectImports import mqttImports
from isdProjectImports import dbFunctions
from isdProjectImports import voteHandling
from isdProjectImports import logHandler
from flask_cors import CORS
import threading
import time # testing purposes
mqttBrokerPort = 1883
mqttKeepAliveSec = 10
mqttBrokerIP = 'localhost' # Replace with broker IP if not running locally.
mqttQoSLevel = 1
globalVoteInformation = voteHandling.VoteInformation() # Global vote information object.
globalVoteInformationList = [] # List of global vote information objects.
# Flask app setup.
app = Flask(__name__)
CORS(app)
# MQTT setup.
app.config['MQTT_BROKER_URL'] = mqttBrokerIP
app.config['MQTT_BROKER_PORT'] = mqttBrokerPort
app.config['MQTT_KEEPALIVE'] = mqttKeepAliveSec
app.config['MQTT_TLS_ENABLED'] = False
# Database setup.
app.config['SQLALCHEMY_DATABASE_URI'] = f'mysql+pymysql://{credentials.dbUsername}:{credentials.dbPassword}@{credentials.dbHostname}:{credentials.dbPort}/{credentials.dbName}'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Only for confirming that server is running.
@app.route('/')
def index():
return 'Flask MQTT Server is running!'
# Subscribe to all topics in 'initialSubscribeTopics' list when server is started.
@mqttImports.mqtt.on_connect()
def handle_connect(client, userdata, flags, rc):
if rc == 0:
for topic in mqttImports.initialSubscribeTopics:
mqttImports.mqtt.subscribe(topic, qos=1) # subscribe to each topic
logHandler.log(f'handle_message(), Subscribed to topic: {topic}')
else:
logHandler.log(f'handle_message(), Connection failed with result code {str(rc)}')
# MQTT message handling
# TODO: Figure out a way to move the case handling to their own functions.
@mqttImports.mqtt.on_message()
def handle_message(client, userdata, message):
receivedMessage = message.payload.decode("utf-8")
receivedTopic = message.topic
logHandler.log(f'handle_message(), Received message: {receivedMessage} on topic: {receivedTopic}')
# Decode JSON message.
decodedMessage = mqttImports.decodeStringToJSON(receivedMessage)
if decodedMessage == -1:
logHandler.log(f'JSON decode failed.')
return # TODO: maybe add something to notify ESPs about failed JSON decode.
# Handle received message based on topic.
# ESP registration handling.
if receivedTopic.startswith("/registration/Server/") == True:
logHandler.log(f'handle_message(), Message handling going to ESP registration handling path.')
# Extract ESP MAC address from topic.
macAddress = receivedTopic.split("/")[3]
# Register ESP in database.
# Inside mqtt.on_message() in app.py
registeredESP, registrationStatus = dbFunctions.register_esp(app, macAddress)
if registrationStatus == True:
# return uniqueID to ESP.
#time.sleep(10) #TODO: remove this once ESP is updated to handle the registration response.
mqttImports.mqtt.publish(f'/registration/esp/{macAddress}', f'{{"VotingID":"{registeredESP.DeviceID}"}}', qos=1)
mqttImports.mqtt.subscribe(f'/registration/ESP/{registeredESP.DeviceID}', qos=1) # Subscribe to ESP's uniqueID topic.
logHandler.log(f'handle_message(), ESP registration successful, ESP uniqueID: {registeredESP.DeviceID}, ESP MAC address: {registeredESP.MacAddress}\n')
else:
#TODO: add something to notify ESP about failed registration.
logHandler.log(f'handle_message(), ESP registration failed, ESP MAC address: {macAddress}\n')
return # end of ESP registration handling.
# Vote handling.
elif receivedTopic.startswith("/vote/") == True:
logHandler.log(f'handle_message(), Message handling going to vote handling path.')
# Extract ESP ID from topic.
deviceID = receivedTopic.split("/")[2]
# Convert strings to datetime objects
if globalVoteInformation.voteStartTime == None and globalVoteInformation.voteEndTime == None:
return # No vote is active #TODO: Figure out a more reliable way to handle this.
try:
vote_end_time = globalVoteInformation.voteEndTime
#datetime.strptime(vote_end_time, "%Y-%m-%d %H:%M:%S")
vote_start_time = globalVoteInformation.voteStartTime
#datetime.strptime(vote_start_time, "%Y-%m-%d %H:%M:%S")
# Test timing restrictions and if vote is for the correct topic.
logHandler.log(f'handle_message(), vote_end_time: {vote_end_time}, vote_start_time: {vote_start_time}, datetime.now(): {datetime.now()}')
logHandler.log(f'handle_message(), decodedMessage[\'VoteTitle\']: {decodedMessage["VoteTitle"]}, globalVoteInformation.title: {globalVoteInformation.title}')
if (
vote_end_time < datetime.now()
or vote_start_time > datetime.now()
or decodedMessage['VoteTitle'] != globalVoteInformation.title
):
logHandler.log(f'handle_message(), vote is not active or vote is not for the correct topic, exit function.')
logHandler.log(f'handle_message(), vote_end_time: {vote_end_time}, vote_start_time: {vote_start_time}, datetime.now(): {datetime.now()}')
logHandler.log(f'handle_message(), decodedMessage[\'VoteTitle\']: {decodedMessage["VoteTitle"]}, globalVoteInformation.title: {globalVoteInformation.title}')
return # Vote is not active or vote is not for the correct topic, exit function.
elif dbFunctions.find_if_vote_exists(app, deviceID, globalVoteInformation) == False:
dbFunctions.create_vote(app, deviceID, decodedMessage['vote'], globalVoteInformation)
return # Exit function.
else:
dbFunctions.update_vote(app, deviceID, decodedMessage['vote'], globalVoteInformation)
return # Exit function.
except Exception as errorMsg:
logHandler.log(f'handle_message(), Another crash in vote handling. Somebody should really fix this shite.')
logHandler.log(f'handle_message(), Error: {errorMsg}')
return
# Vote resync handling.
elif receivedTopic == "/setupVote/Resync":
try:
logHandler.log(f'handle_message(), Message handling going to vote resync handling path.')
# Create message.
if globalVoteInformation.voteEndTime < datetime.now():
resyncMessage = f"""{{
"VoteTitle": "{globalVoteInformation.title}",
"VoteType": "public",
"VoteStatus": "ended"
}}"""
else:
resyncMessage = f"""{{
"VoteTitle": "{globalVoteInformation.title}",
"VoteType": "public",
"VoteStatus": "started"
}}"""
# Send vote information to /setupVote/Resync topic.
mqttImports.publishJSONtoMQTT('/setupVote/Setup', resyncMessage)
return # End of vote handling.
except Exception as errorMsg:
logHandler.log(f'handle_message(), Error: {errorMsg}')
return
return # End of function.
# API endpoints
@app.route('/api/getRegisteredESPs', methods=['GET'])
def getRegisteredESPs():
return dbFunctions.get_registered_esps(app)
@app.route('/api/getUnassignedESPs', methods=['GET'])
def getUnassignedESPs():
return dbFunctions.get_unassigned_esps(app)
@app.route('/api/getTopics', methods=['GET'])
def getTopics():
return dbFunctions.get_all_topics(app)
@app.route('/api/getTopic/<topicID>', methods=['GET'])
def getTopic(topicID):
return dbFunctions.get_topic(app, topicID)
@app.route('/api/createTopic', methods=['POST'])
def createTopic():
"""Input JSON format:
{
"Title": "TEXT",
"Description": "TEXT",
"StartTime": "YYYY-MM-DD HH:MM:SS",
"EndTime": "YYYY-MM-DD HH:MM:SS"
}
"""
try:
data = request.json
# Validate request.
if mqttImports.validateKeywordsInJSON(data, ['Title', 'Description', 'StartTime', 'EndTime'], 1) == False:
logHandler.log(f'createTopic(), Invalid request.')
return jsonify({'message': 'Invalid request.'}), 400
globalVoteInformation.updateVoteInformation(data['Title'], data['Description'], datetime.strptime(data['StartTime'], '%Y-%m-%d %H:%M:%S'), data['EndTime'])
# convert datetime string to datetime object
voteStartTime = globalVoteInformation.voteStartTime
# Publish vote information to /setupVote/Setup topic.
if voteStartTime < datetime.now():
voteInformationJson = f'{{"VoteTitle":"{globalVoteInformation.title}","VoteType":"public","VoteStatus":"started"}}'
else:
voteInformationJson = f'{{"VoteTitle":"{globalVoteInformation.title}","VoteType":"public","VoteStatus":"ended"}}'
mqttImports.publishJSONtoMQTT('/setupVote/Setup', voteInformationJson)
# Create new topic in database.
if dbFunctions.create_topic(app, globalVoteInformation) == True:
# TODO: figure out voteStartTiming.
return jsonify({'message': 'Topic created successfully.'}), 200
else:
return jsonify({'message': 'Topic creation failed.'}), 400
except Exception as errorMsg:
logHandler.log(f'createTopic(), Error: {errorMsg}')
return jsonify({'message': 'Internal server error.'}), 500
@app.route('/api/assignUserToESP', methods=['POST'])
def assignUserToESP():
"""Input JSON format:
{
"username": "TEXT",
"espID": "INT"
}
"""
try:
data = request.json
# Validate request.
if mqttImports.validateKeywordsInJSON(data, ['username', 'espID'], 1) == False:
logHandler.log(f'assignUserToESP(), Invalid request.')
return jsonify({'message': 'Invalid request.'}), 400
return dbFunctions.assign_user_to_esp(app, data['username'], data['espID'])
except Exception as errorMsg:
logHandler.log(f'assignUserToESP(), Error: {errorMsg}')
return jsonify({'message': f'{str(errorMsg)}'}), 400
@app.route('/api/unassignESP', methods=['POST'])
def unassignESP():
"""Input JSON format:
{
"espID": "INT"
}
"""
try:
data = request.json
# Validate request.
if mqttImports.validateKeywordsInJSON(data, ['espID'], 1) == False:
logHandler.log(f'unassignESP(), Invalid request.')
return jsonify({'message': 'Invalid request.'}), 400
return dbFunctions.unassign_esp_with_id(app, data['espID'])
except Exception as errorMsg:
logHandler.log(f'unassignESP(), Error: {errorMsg}')
return jsonify({'message': f'{str(errorMsg)}'}), 500
@app.route('/api/unassignAllESPs', methods=['POST'])
def unassignAllESPs():
return dbFunctions.unassign_all_esps(app)
@app.route('/api/getVotes/<int:topicID>', methods=['GET'])
def get_votes_by_topic(topicID):
return dbFunctions.get_votes(app, topicID)
@app.route('/api/getAssignedESPs', methods=['GET'])
def get_assigned_esps():
return dbFunctions.get_assigned_esps(app)
@app.route('/api/forceResync', methods=['GET'])
def force_resync():
mqttImports.publishJSONtoMQTT('/setupVote/Resync', '"{“resync”:”---”}"')
return jsonify({'message': 'Resync message sent.'}), 200
def startup_procedures():
time.sleep(3) # Wait for app to be fully initialized.
with app.app_context():
logHandler.log(f'Server started.')
logHandler.log(f'Finding active topic.')
dbFunctions.find_active_topic(app, globalVoteInformation)
logHandler.log(f'Active topic: {globalVoteInformation.title}, voteStartTime: {globalVoteInformation.voteStartTime}, voteEndTime: {globalVoteInformation.voteEndTime}')
if __name__ == '__main__':
# Initialize imported app extensions.
dbFunctions.db.init_app(app)
mqttImports.mqtt.init_app(app)
# Create a thread for startup procedures.
startup_thread = threading.Thread(target=startup_procedures)
# Start the thread.
startup_thread.start()
# Run the Flask application.
app.run(host='0.0.0.0', port=5000, use_reloader=False)