pyren/pyren3/data_logger.py
2024-05-07 18:23:39 +03:00

103 lines
2.6 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
import mod_globals
mod_globals.opt_demo = True
dash = RenDash("/dev/tty1")
web = Flask(__name__)
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'{datetime.now().strftime("%m/%d/%Y, %H:%M:%S")}.csv'
print("Creating log on file: " + log_filename)
with open(log_filename, "w+") as file:
csv_writer = writer(file,delimiter=' ', quotechar='|', quoting=QUOTE_MINIMAL)
csv_writer.writerow(["freeze"].extend(watched_datarefs))
print("Starting data loop")
while running:
frame = [dash.get_ecu_dataref(watched_ecu, dataref) for dataref in watched_datarefs]
socket.emit("frame", {"frame": frame})
if should_log:
csv_writer.writerow([freeze].extend(frame))
freeze = 0
print(frame)
@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
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("index.html")
if __name__ == "__main__":
socket.run(web, "0.0.0.0", 5000)