try adding a data class

This commit is contained in:
Hannes Klinckaert 2020-09-09 19:52:23 +02:00
parent 3a0e512f4c
commit 059543aa6c

View file

@ -9,14 +9,20 @@ from collections import deque
app = Flask(__name__)
last_message_index = -1
# Keep this the same as max_messages on the client!
max_message_cache = 200
shared_message_log = deque(maxlen=max_message_cache)
server_id = uuid.uuid4()
print("Server ID: ", server_id)
@dataclass
class SharedData:
messages: deque
last_message_index: int
# Keep this the same as max_messages on the client!
max_message_cache = 200
shared_data = SharedData(deque(maxlen=max_message_cache), -1)
@dataclass
class Message:
payload: bytes
@ -88,8 +94,7 @@ class Message:
}
def serial_reader(messagelog, message_index):
global last_message_index
def serial_reader(shared_data):
with serial.Serial('/dev/ttyACM0', 115200, timeout=10) as ser:
while True:
line = ser.readline()
@ -100,10 +105,11 @@ def serial_reader(messagelog, message_index):
parts = line.split(' ')
sender = int(parts[1])
message = bytes(int(p) for p in parts[2:])
received = Message(message, sender, datetime.now(), len(messagelog))
messagelog.append(received.serialize())
last_message_index += 1
print(last_message_index)
received = Message(message, sender, datetime.now(), len(shared_data.messages))
shared_data.messages.append(received.serialize())
shared_data.last_message_index += 1
print(shared_data.last_message_index)
print("READER = ", shared_data)
@app.route('/')
def index():
@ -112,16 +118,17 @@ def index():
@app.route('/<last_received>/api.json')
def api(last_received):
last_received = int(last_received)
if last_received < last_message_index - max_message_cache:
return jsonify({"server_id": server_id, "newest_msg": last_message_index, "messages": list(shared_message_log)})
print("REQUEST = ", shared_data)
if last_received < shared_data.last_message_index - max_message_cache:
return jsonify({"server_id": server_id, "newest_msg": last_message_index, "messages": list(shared_data.messages)})
else:
return jsonify({"server_id": server_id, "newest_msg": last_message_index, "messages": list(shared_message_log)[max_message_cache - (last_message_index - last_received):]})
return jsonify({"server_id": server_id, "newest_msg": shared_data.last_message_index, "messages": list(shared_data.messages)[max_message_cache - (shared_data.last_message_index - last_received):]})
@app.route('/max_messages.json')
def get_max_messages():
return jsonify([max_message_cache])
if __name__ == '__main__':
thread = Thread(target=serial_reader, args=(shared_message_log, last_message_index,))
thread = Thread(target=serial_reader, args=(shared_data, ))
thread.start()
app.run(debug=False, host='0.0.0.0')