obus/python/debugserver.py

64 lines
2.1 KiB
Python
Raw Normal View History

2020-08-16 04:16:36 +02:00
from threading import Thread
from flask import Flask, jsonify, send_file
from time import sleep
from dataclasses import dataclass
from datetime import datetime
2020-08-19 02:10:30 +02:00
import serial
import uuid
from collections import deque
2022-01-17 18:52:39 +01:00
import sys
2022-01-17 20:12:13 +01:00
from obus import Message
2020-08-16 04:16:36 +02:00
app = Flask(__name__)
2020-09-09 19:52:23 +02:00
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
2020-09-09 19:52:23 +02:00
shared_data = SharedData(deque(maxlen=max_message_cache), -1)
2022-01-19 20:44:54 +01:00
def serial_reader(serialport, shared_data):
with serial.Serial(serialport, 115200, timeout=0.05) as ser:
2020-09-08 18:57:03 +02:00
while True:
line = ser.read(12)
if not line:
continue
2022-01-17 18:52:39 +01:00
print(line)
if len(line) == 12:
if line == b'BEGIN START\n' or line[0] > 0b111:
2022-01-17 18:52:39 +01:00
continue
2022-01-17 19:01:00 +01:00
sender = (int(line[0]) << 8) + int(line[1])
2022-01-17 18:52:39 +01:00
size = int(line[2])
message = line[3:3+size]
2022-01-17 20:12:13 +01:00
received = Message(message, sender, datetime.now())
2020-09-09 19:52:23 +02:00
shared_data.messages.append(received.serialize())
shared_data.last_message_index += 1
print(shared_data.last_message_index)
2020-08-16 04:16:36 +02:00
@app.route('/')
def index():
2022-01-17 20:00:53 +01:00
return send_file('static/debugger.html')
2020-08-16 04:16:36 +02:00
@app.route('/<last_received>/api.json')
def api(last_received):
last_received = int(last_received)
2020-09-09 20:39:47 +02:00
if last_received < shared_data.last_message_index - len(shared_data.messages):
return jsonify({"server_id": server_id, "newest_msg": shared_data.last_message_index, "messages": list(shared_data.messages)})
else:
2020-09-09 20:39:47 +02:00
return jsonify({"server_id": server_id, "newest_msg": shared_data.last_message_index, "messages": list(shared_data.messages)[len(shared_data.messages) - (shared_data.last_message_index - last_received):]})
2020-08-16 04:16:36 +02:00
if __name__ == '__main__':
2022-01-19 20:44:54 +01:00
if len(sys.argv) != 2:
print("Usage: python3 debugserver.py [serial port]")
sys.exit()
thread = Thread(target=serial_reader, args=(sys.argv[1], shared_data, ))
2020-08-16 04:16:36 +02:00
thread.start()
app.run(debug=False, host='0.0.0.0')