pyren/pyren3/data_logger.py

130 lines
3.0 KiB
Python

from flask import Flask, jsonify, request, send_file
from flask_socketio import SocketIO
from rendash_main import RenDash
from csv import writer, QUOTE_MINIMAL
from datetime import datetime
from time import time_ns
from os import _exit
dash = RenDash("/dev/ttyUSB0")
web = Flask(__name__, static_folder="web_static/", static_url_path="/static")
socket = SocketIO(web)
watched_datarefs = []
watched_ecu = ""
should_log = False
freeze = 0
running = False
bg_thread = None
def mainloop():
global running, watched_datarefs, watched_ecu, should_log, freeze
if should_log:
log_filename = f'../logs/{datetime.now().strftime("%m-%d-%Y %H:%M:%S")}.csv'
print("Creating log on file: " + log_filename)
file = open(log_filename, "w")
csv_writer = writer(file, delimiter=" ", quotechar="|", quoting=QUOTE_MINIMAL)
csv_writer.writerow(["time", "freeze"] + watched_datarefs)
print("Starting data loop")
while running:
frame = [
dash.get_ecu_dataref(watched_ecu, dataref)[0]
for dataref in watched_datarefs
]
socket.emit("frame", {"frame": frame})
if should_log:
csv_writer.writerow([(time_ns() // 1_000_000), freeze] + frame)
freeze = 0
socket.sleep(0.05)
if should_log:
file.flush()
file.close()
@socket.on("freeze")
def freeze_event():
global freeze
freeze = 1
@web.get("/ecus")
def get_ecus():
ecus = dash.get_ecu_names()
return jsonify(ecus)
@web.get("/ecus/<ecu_doc>/states")
def get_ecu_states(ecu_doc):
return jsonify(dash.get_ecu_states(ecu_doc))
@web.get("/ecus/<ecu_doc>/parameters")
def get_ecu_parameters(ecu_doc):
return jsonify(dash.get_ecu_parameters(ecu_doc))
@web.post("/ecus/<ecu_doc>/watch")
def ecu_watch(ecu_doc):
global watched_ecu, watched_datarefs
datarefs = request.get_json()
watched_datarefs = []
for dataref in datarefs:
if dataref in dash.get_ecu_parameters(
ecu_doc
) or dataref in dash.get_ecu_states(ecu_doc):
watched_datarefs.append(dataref)
else:
watched_datarefs = []
raise ValueError("Invalid dataref")
watched_ecu = ecu_doc
return jsonify({"ecu": watched_ecu, "datarefs": watched_datarefs})
@web.get("/start")
def start():
global should_log, bg_thread, running
if running:
return jsonify({"success": False})
log = request.args.get("log")
if log == "true":
should_log = True
else:
should_log = False
running = True
bg_thread = socket.start_background_task(mainloop)
return jsonify({"success": True})
@web.get("/stop")
def stop():
global bg_thread, running
running = False
bg_thread.join()
return jsonify({"success": True})
@web.get("/")
def index():
return send_file("web_html/data_logger.html")
@socket.on("exit")
def exit_logger():
try:
socket.stop()
except Exception as e:
print(e)
_exit(0)
if __name__ == "__main__":
socket.run(web, "0.0.0.0", 5000)