Asyncio integration

This commit is contained in:
Etienne Chassaing 2025-07-18 11:18:45 +02:00
parent e3492dd5de
commit 7d2eab97d7
2 changed files with 12 additions and 10 deletions

View File

@ -2,7 +2,7 @@ import threading
import canopen
import time
import os
import asyncio
class CANBackend:
def __init__(self, eds_file =None):
@ -58,10 +58,12 @@ class CANBackend:
if self.polling_thread and self.polling_thread.is_alive():
return
self.polling_active = True
self.polling_thread = threading.Thread(target=self._sdo_polling_loop, daemon=True)
self.polling_thread.start()
# self.polling_thread = threading.Thread(target=self._sdo_polling_loop, daemon=True)
# self.polling_thread.start()
self.polling_task = asyncio.create_task(self._sdo_polling_loop())
def _sdo_polling_loop(self):
async def _sdo_polling_loop(self):
while self.polling_active:
with self.lock:
try:
@ -127,10 +129,10 @@ class CANBackend:
except Exception as outer_e:
print(f"[SDO POLL ERROR] {outer_e}")
time.sleep(1.0)
asyncio.sleep(0.1)
def get_latest_data(self, pu_number: int):
with self.lock:
async def get_latest_data(self, pu_number: int):
async with self.lock:
return self.latest_data.get(pu_number, {}).copy()
def read_current_state(self, pu_number: int):

View File

@ -81,7 +81,7 @@ def format_data(data):
"Pro": np.round(data.get("PS2", 0.0), 2),
"Pdilute": np.round(data.get("PS3", 0.0), 2),
"Pretentate": np.round(data.get("PS1", 0.0), 2),
"Conductivity": np.round(data.get("Cond", 0.0), 1),
"Conductivity": np.round(data.get("Cond", 0.0), 2),
"MV02": np.round(data.get("MV02", 0.0), 1),
"MV02_sp": np.round(data.get("MV02_sp", 0.0), 1),
"MV03": np.round(data.get("MV03", 0.0), 1),
@ -242,12 +242,12 @@ async def update_latest_data():
1,
2,
]: # TODO: REPLACE THIS WITH CONNECTED PUs, IS GET PU STATUS SLOW?
data = can_backend.get_latest_data(pu_number=pu)
data = await can_backend.get_latest_data(pu_number=pu)
latest_data[f"PU_{pu}"] = format_data(data)
current_data = latest_data[f"PU_{pu}"]
logging.debug(f"[MONITOR BUFFER] PU{pu}: {current_data}")
# logging.info(f"[MONITOR BUFFER] latest_data: {latest_data}")
await asyncio.sleep(0.05)
await asyncio.sleep(0.1)
@app.get("/monitor")