Range updates

This commit is contained in:
Etienne Chassaing 2025-07-17 12:31:16 +02:00
parent c1ce7da3d8
commit c74264545b
2 changed files with 31 additions and 17 deletions

40
main.py
View File

@ -25,10 +25,12 @@ import aiohttp
if platform.system() in ["Darwin"]: # macOS or Windows
from MockCAN import CANBackend
logging.basicConfig(level=logging.INFO)
else:
from classCAN import CANBackend # Your real backend
logging.basicConfig(level=logging.ERROR)
app = FastAPI()
@ -36,14 +38,21 @@ app.add_middleware(SessionMiddleware, secret_key="your_super_secret_key")
router = APIRouter()
templates = Jinja2Templates(directory="templates")
can_backend = CANBackend()
valve_backend = ValveBackend(eds_file="/home/hmi/Desktop/HMI/eds_file/inletvalveboard.eds")
valve_backend = ValveBackend(
eds_file="/home/hmi/Desktop/HMI/eds_file/inletvalveboard.eds"
)
# Serve static files (HTML, JS, CSS)
app.mount("/static", StaticFiles(directory="static"), name="static")
## BUFFER CREATION AND HELPER
# Global object to store the latest data
latest_data: Dict[str, Any] = {"PU_1": None, "PU_2": None, "PU_3": None, "PatientSkid" : {"QSkid":0.0}}
latest_data: Dict[str, Any] = {
"PU_1": None,
"PU_2": None,
"PU_3": None,
"PatientSkid": {"QSkid": 0.0},
}
# RECORDER
recording_flag = False
@ -54,6 +63,7 @@ write_buffer = deque()
flush_interval = 1.0 # flush every 1 second
last_flush_time = datetime.datetime.now()
## LOGGING QSkid
async def update_latest_flow():
async with aiohttp.ClientSession() as session:
@ -97,6 +107,7 @@ def format_data(data):
"MV08_sp": np.round(data.get("MV08_sp", 0.0), 1),
}
# CREDENTIALS
# Load users from JSON file at startup
@ -169,14 +180,14 @@ def connect_toggle():
else:
success = can_backend.connect()
try:
valve_backend.connect()
valve_backend.connect()
except Exception as e:
print(f"Connection error : {e}")
if not success:
raise HTTPException(status_code=500, detail="Connection failed.")
return {"connected": True}
@app.post("/command/{state}/pu/{pu_number}")
def send_command(state: str, pu_number: int, ploop_setpoint: float = Query(...)):
@ -225,7 +236,10 @@ def get_pu_status():
async def update_latest_data():
while True:
for pu in [1, 2]: # TODO: REPLACE THIS WITH CONNECTED PUs, IS GET PU STATUS SLOW?
for pu in [
1,
2,
]: # TODO: REPLACE THIS WITH CONNECTED PUs, IS GET PU STATUS SLOW?
data = can_backend.get_latest_data(pu_number=pu)
latest_data[f"PU_{pu}"] = format_data(data)
current_data = latest_data[f"PU_{pu}"]
@ -261,7 +275,8 @@ def feedvalve_control(MV01_opening: int = Query(...)):
logging.info(f"Feed valve opening to {MV01_opening}")
return {"status": "ok"}
#LOCAL RECORDER
# LOCAL RECORDER
@app.post("/start_recording")
async def start_recording():
global recording_flag, recording_task, recording_file, recording_writer
@ -305,7 +320,6 @@ async def stop_recording():
return {"status": "recording stopped"}
async def record_data_loop():
global recording_writer, recording_file, write_buffer, last_flush_time
@ -313,19 +327,19 @@ async def record_data_loop():
timestamp = datetime.datetime.now().isoformat()
for pu, data in latest_data.items():
if data:
row = {
"timestamp": timestamp,
"pu": pu,
**data
}
row = {"timestamp": timestamp, "pu": pu, **data}
recording_writer.writerow(row)
# Flush every flush_interval seconds
if (datetime.datetime.now() - last_flush_time).total_seconds() >= flush_interval:
if (
datetime.datetime.now() - last_flush_time
).total_seconds() >= flush_interval:
recording_file.flush()
last_flush_time = datetime.datetime.now()
await asyncio.sleep(0.1) # 10 Hz
app.include_router(router)
if __name__ == "__main__":

View File

@ -260,13 +260,13 @@
Plotly.newPlot('MV02_sp-plot', [{
x: time0, y: [0], name: 'MV02_sp', mode: 'lines'
}], {
title: 'MV02_sp (%)', yaxis: { range: [0, 100] }, xaxis: { type: 'date' }
title: 'MV02_sp (%)', yaxis: { }, xaxis: { type: 'date' }
});
Plotly.newPlot('MV03_sp-plot', [{
x: time0, y: [0], name: 'MV03_sp', mode: 'lines'
}], {
title: 'MV03_sp (%)', yaxis: { range: [0, 100] }, xaxis: { type: 'date' }
title: 'MV03_sp (%)', yaxis: { }, xaxis: { type: 'date' }
});
Plotly.newPlot('MV04_sp-05-plot', [
@ -279,13 +279,13 @@
Plotly.newPlot('MV06_sp-plot', [{
x: time0, y: [0], name: 'MV06_sp', mode: 'lines'
}], {
title: 'MV06_sp (%)', yaxis: { range: [0, 100] }, xaxis: { type: 'date' }
title: 'MV06_sp (%)', yaxis: { }, xaxis: { type: 'date' }
});
Plotly.newPlot('MV07_sp-plot', [{
x: time0, y: [0], name: 'MV07_sp', mode: 'lines'
}], {
title: 'MV07_sp (%)', yaxis: { range: [0, 100] }, xaxis: { type: 'date' }
title: 'MV07_sp (%)', yaxis: { }, xaxis: { type: 'date' }
});
Plotly.newPlot('MV08_sp-plot', [{