Added changes for multiple PU monitoring

This commit is contained in:
aniketSaha 2025-07-11 16:13:34 +02:00
parent 94cc1a5d1e
commit e21bfa26f6
4 changed files with 145 additions and 169 deletions

View File

@ -12,7 +12,11 @@ class CANBackend:
self.lock = threading.Lock() self.lock = threading.Lock()
self.polling_thread = None self.polling_thread = None
self.polling_active = False self.polling_active = False
self.latest_data = {} self.latest_data = {
1: {}, # PU1
2: {}, # PU2
3: {} # PU3
}
self.eds_path = os.path.join(os.path.dirname(__file__), "eds_file", "processBoard_0.eds") self.eds_path = os.path.join(os.path.dirname(__file__), "eds_file", "processBoard_0.eds")
def connect(self): def connect(self):
@ -58,9 +62,8 @@ class CANBackend:
while self.polling_active: while self.polling_active:
with self.lock: with self.lock:
try: try:
# Poll only PU1 (node ID 0x02) for live monitor values for pu_number, node in self.nodes.items():
node = self.nodes.get(2) try:
if node:
fm1 = node.sdo[0x2004][1].raw fm1 = node.sdo[0x2004][1].raw
fm2 = node.sdo[0x2004][2].raw fm2 = node.sdo[0x2004][2].raw
fm3 = node.sdo[0x2004][3].raw fm3 = node.sdo[0x2004][3].raw
@ -71,27 +74,31 @@ class CANBackend:
ps3 = node.sdo[0x2005][3].raw ps3 = node.sdo[0x2005][3].raw
ps4 = node.sdo[0x2005][4].raw ps4 = node.sdo[0x2005][4].raw
self.latest_data["FM1"] = fm1 / 100.0 self.latest_data[pu_number] = {
self.latest_data["FM2"] = fm2 / 100.0 "FM1": fm1 / 100.0,
self.latest_data["FM3"] = fm3 / 100.0 "FM2": fm2 / 100.0,
self.latest_data["FM4"] = fm4 / 100.0 "FM3": fm3 / 100.0,
"FM4": fm4 / 100.0,
"PS1": ps1 / 1000.0,
"PS2": ps2 / 1000.0,
"PS3": ps3 / 1000.0,
"PS4": ps4 / 1000.0
}
self.latest_data["PS1"] = ps1 / 1000.0 print(f"[PU{pu_number}] FM1: {fm1}, PS1: {ps1}")
self.latest_data["PS2"] = ps2 / 1000.0 except Exception as inner_e:
self.latest_data["PS3"] = ps3 / 1000.0 print(f"[SDO READ ERROR] PU{pu_number}: {inner_e}")
self.latest_data["PS4"] = ps4 / 1000.0
except Exception as outer_e:
print(f"[SDO POLL ERROR] {outer_e}")
print(f"[SDO POLL] FM1: {fm1}, PS1: {ps1}")
print(f"[SDO POLL] FM2: {fm2}, PS2: {ps2}")
print(f"[SDO POLL] FM3: {fm3}, PS3: {ps3}")
print(f"[SDO POLL] FM4: {fm4}, PS4: {ps4}")
except Exception as e:
print(f"[SDO POLL ERROR] {e}")
time.sleep(1.0) time.sleep(1.0)
def get_latest_data(self):
def get_latest_data(self, pu_number: int):
with self.lock: with self.lock:
return self.latest_data.copy() return self.latest_data.get(pu_number, {}).copy()
def read_current_state(self, pu_number: int): def read_current_state(self, pu_number: int):
try: try:

83
main.py
View File

@ -145,72 +145,13 @@ def get_pu_status():
return JSONResponse(content=states) return JSONResponse(content=states)
from typing import Optional
from fastapi import Query
@app.get("/monitor") @app.get("/monitor")
def get_monitor_data(): def get_monitor_data(pu_number: Optional[int] = Query(None)):
data = can_backend.get_latest_data() def format_data(data):
print(f"[MONITOR] Latest SDO: {data}")
return { return {
"PU_1": {
"Qperm": data.get("FM1", 0.0),
"Qdilute": data.get("FM2", 0.0),
"Qdrain": data.get("FM3", 0.0),
"Qrecirc": data.get("FM4", 0.0),
"Pro": data.get("PS1", 0.0),
"Pdilute": data.get("PS2", 0.0),
"Prentate": data.get("PS3", 0.0),
"Conductivity": data.get("Cond", 0.0),
"MV02": data.get("MV02", 0.0),
"MV02_sp": data.get("MV02_sp", 0.0),
"MV03": data.get("MV03", 0.0),
"MV03_sp": data.get("MV03_sp", 0.0),
"MV05": data.get("MV05", 0.0),
"MV05_sp": data.get("MV05_sp", 0.0),
"MV06": data.get("MV06", 0.0),
"MV06_sp": data.get("MV06_sp", 0.0),
"MV07": data.get("MV07", 0.0),
"MV07_sp": data.get("MV07_sp", 0.0),
"MV08": data.get("MV08", 0.0),
"MV08_sp": data.get("MV08_sp", 0.0)
},
"PU_2": {
"Qperm": data.get("FM1", 0.0),
"Qdilute": data.get("FM2", 0.0),
"Qdrain": data.get("FM3", 0.0),
"Qrecirc": data.get("FM4", 0.0),
"Pro": data.get("PS1", 0.0),
"Pdilute": data.get("PS2", 0.0),
"Prentate": data.get("PS3", 0.0),
"Conductivity": data.get("Cond", 0.0),
"MV02": data.get("MV02", 0.0),
"MV02_sp": data.get("MV02_sp", 0.0),
"MV03": data.get("MV03", 0.0),
"MV03_sp": data.get("MV03_sp", 0.0),
"MV05": data.get("MV05", 0.0),
"MV05_sp": data.get("MV05_sp", 0.0),
"MV06": data.get("MV06", 0.0),
"MV06_sp": data.get("MV06_sp", 0.0),
"MV07": data.get("MV07", 0.0),
"MV07_sp": data.get("MV07_sp", 0.0),
"MV08": data.get("MV08", 0.0),
"MV08_sp": data.get("MV08_sp", 0.0)
},
"PU_3": {
"Qperm": data.get("FM1", 0.0), "Qperm": data.get("FM1", 0.0),
"Qdilute": data.get("FM2", 0.0), "Qdilute": data.get("FM2", 0.0),
"Qdrain": data.get("FM3", 0.0), "Qdrain": data.get("FM3", 0.0),
@ -240,7 +181,19 @@ def get_monitor_data():
"MV08": data.get("MV08", 0.0), "MV08": data.get("MV08", 0.0),
"MV08_sp": data.get("MV08_sp", 0.0) "MV08_sp": data.get("MV08_sp", 0.0)
} }
}
if pu_number is not None:
data = can_backend.get_latest_data(pu_number)
print(f"[MONITOR] PU{pu_number}: {data}")
return format_data(data)
else:
all_data = {}
for pu in [1, 2, 3]:
data = can_backend.get_latest_data(pu)
print(f"[MONITOR] PU{pu}: {data}")
all_data[f"PU_{pu}"] = format_data(data)
return all_data
@app.get("/can_status") @app.get("/can_status")
def can_status(): def can_status():

View File

@ -28,10 +28,23 @@
h1 { h1 {
text-align: center; text-align: center;
} }
#puSelector {
display: block;
margin: 10px auto 20px auto;
font-size: 16px;
padding: 5px 10px;
}
</style> </style>
</head> </head>
<body> <body>
<h1>Live Monitoring Dashboard</h1> <h1>Live Monitoring Dashboard</h1>
<label for="puSelector" style="text-align:center; display:block;">Select PU:</label>
<select id="puSelector">
<option value="1">PU 1</option>
<option value="2">PU 2</option>
<option value="3">PU 3</option>
</select>
<div class="plot-container"> <div class="plot-container">
<div id="flow-plot" class="large-plot"></div> <div id="flow-plot" class="large-plot"></div>
<div id="pressure-plot" class="large-plot"></div> <div id="pressure-plot" class="large-plot"></div>
@ -44,8 +57,13 @@
</div> </div>
<script> <script>
const maxPoints = 100; // Number of time points to keep const maxPoints = 100;
const time = () => new Date(); // Timestamp for x-axis const time = () => new Date();
let selectedPU = 1;
document.getElementById("puSelector").addEventListener("change", function () {
selectedPU = parseInt(this.value);
});
function getLastMinuteRange() { function getLastMinuteRange() {
const now = new Date(); const now = new Date();
@ -53,47 +71,40 @@
return [oneMinuteAgo, now]; return [oneMinuteAgo, now];
} }
async function updatePlots() { async function updatePlots() {
try { try {
const response = await fetch('/monitor'); const response = await fetch(`/monitor?pu_number=${selectedPU}`);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`); if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const data = await response.json(); const pu = await response.json(); // <- Directly using it
const pu = data["PU_1"];
const t = time(); const t = time();
// Extend traces for flow plot
Plotly.extendTraces('flow-plot', { Plotly.extendTraces('flow-plot', {
x: [[t], [t], [t], [t]], x: [[t], [t], [t], [t]],
y: [[pu.Qperm], [pu.Qdilute], [pu.Qdrain], [pu.Qrecirc]] y: [[pu.Qperm], [pu.Qdilute], [pu.Qdrain], [pu.Qrecirc]]
}, [0, 1, 2, 3], maxPoints); }, [0, 1, 2, 3], maxPoints);
// Extend traces for pressure plot
Plotly.extendTraces('pressure-plot', { Plotly.extendTraces('pressure-plot', {
x: [[t], [t], [t]], x: [[t], [t], [t]],
y: [[pu.Pro], [pu.Pdilute], [pu.Prentate]] y: [[pu.Pro], [pu.Pdilute], [pu.Prentate]]
}, [0, 1, 2], maxPoints); }, [0, 1, 2], maxPoints);
const mv = pu; // assuming pu = data.PU_1 Plotly.extendTraces('mv02-plot', { x: [[t]], y: [[pu.MV02]] }, [0]);
Plotly.extendTraces('mv03-plot', { x: [[t]], y: [[pu.MV03]] }, [0]);
Plotly.extendTraces('mv02-plot', { x: [[t]], y: [[mv.MV02]] }, [0]);
Plotly.extendTraces('mv03-plot', { x: [[t]], y: [[mv.MV03]] }, [0]);
Plotly.extendTraces('mv04-05-plot', { Plotly.extendTraces('mv04-05-plot', {
x: [[t], [t]], x: [[t], [t]],
y: [[mv.MV04], [mv.MV05]] y: [[pu.MV04], [pu.MV05]]
}, [0, 1]); }, [0, 1]);
Plotly.extendTraces('mv06-plot', { x: [[t]], y: [[mv.MV06]] }, [0]); Plotly.extendTraces('mv06-plot', { x: [[t]], y: [[pu.MV06]] }, [0]);
Plotly.extendTraces('mv07-plot', { x: [[t]], y: [[mv.MV07]] }, [0]); Plotly.extendTraces('mv07-plot', { x: [[t]], y: [[pu.MV07]] }, [0]);
Plotly.extendTraces('mv08-plot', { x: [[t]], y: [[mv.MV08]] }, [0]); Plotly.extendTraces('mv08-plot', { x: [[t]], y: [[pu.MV08]] }, [0]);
const range = getLastMinuteRange(); const range = getLastMinuteRange();
const plotIds = [
// Update X-axis for all plots 'flow-plot', 'pressure-plot', 'mv02-plot', 'mv03-plot',
['flow-plot', 'pressure-plot', 'mv02-plot', 'mv03-plot', 'mv04-05-plot', 'mv06-plot', 'mv07-plot', 'mv08-plot'].forEach(id => { 'mv04-05-plot', 'mv06-plot', 'mv07-plot', 'mv08-plot'
Plotly.relayout(id, { ];
'xaxis.range': range plotIds.forEach(id => {
}); Plotly.relayout(id, { 'xaxis.range': range });
}); });
} catch (error) { } catch (error) {
@ -101,10 +112,10 @@
} }
} }
function initPlots() { function initPlots() {
const time0 = [time()]; const time0 = [time()];
// Flow plot with multiple traces
Plotly.newPlot('flow-plot', [ Plotly.newPlot('flow-plot', [
{ x: time0, y: [0], name: 'Qperm', mode: 'lines', line: { color: 'blue' } }, { x: time0, y: [0], name: 'Qperm', mode: 'lines', line: { color: 'blue' } },
{ x: time0, y: [0], name: 'Qdilute', mode: 'lines', line: { color: 'green' } }, { x: time0, y: [0], name: 'Qdilute', mode: 'lines', line: { color: 'green' } },
@ -116,7 +127,6 @@
yaxis: { title: 'Flow (L/h)', range: [0, 2000] } yaxis: { title: 'Flow (L/h)', range: [0, 2000] }
}); });
// Pressure plot
Plotly.newPlot('pressure-plot', [ Plotly.newPlot('pressure-plot', [
{ x: time0, y: [0], name: 'Pro', mode: 'lines', line: { color: 'purple' } }, { x: time0, y: [0], name: 'Pro', mode: 'lines', line: { color: 'purple' } },
{ x: time0, y: [0], name: 'Pdilute', mode: 'lines', line: { color: 'teal' } }, { x: time0, y: [0], name: 'Pdilute', mode: 'lines', line: { color: 'teal' } },
@ -126,50 +136,44 @@
xaxis: { title: 'Time', type: 'date' }, xaxis: { title: 'Time', type: 'date' },
yaxis: { title: 'Pressure (bar)', range: [0, 15] } yaxis: { title: 'Pressure (bar)', range: [0, 15] }
}); });
// MV02
Plotly.newPlot('mv02-plot', [{ Plotly.newPlot('mv02-plot', [{
x: [time()], y: [0], name: 'MV02', mode: 'lines' x: time0, y: [0], name: 'MV02', mode: 'lines'
}], { }], {
title: 'MV02 (%)', yaxis: { range: [0, 100] }, xaxis: { type: 'date' } title: 'MV02 (%)', yaxis: { range: [0, 100] }, xaxis: { type: 'date' }
}); });
// MV03
Plotly.newPlot('mv03-plot', [{ Plotly.newPlot('mv03-plot', [{
x: [time()], y: [0], name: 'MV03', mode: 'lines' x: time0, y: [0], name: 'MV03', mode: 'lines'
}], { }], {
title: 'MV03 (%)', yaxis: { range: [0, 100] }, xaxis: { type: 'date' } title: 'MV03 (%)', yaxis: { range: [0, 100] }, xaxis: { type: 'date' }
}); });
// MV04 + MV05
Plotly.newPlot('mv04-05-plot', [ Plotly.newPlot('mv04-05-plot', [
{ x: [time()], y: [0], name: 'MV04', mode: 'lines' }, { x: time0, y: [0], name: 'MV04', mode: 'lines' },
{ x: [time()], y: [0], name: 'MV05', mode: 'lines' } { x: time0, y: [0], name: 'MV05', mode: 'lines' }
], { ], {
title: 'MV04 + MV05 (%)', yaxis: { range: [0, 100] }, xaxis: { type: 'date' } title: 'MV04 + MV05 (%)', yaxis: { range: [0, 100] }, xaxis: { type: 'date' }
}); });
// MV06
Plotly.newPlot('mv06-plot', [{ Plotly.newPlot('mv06-plot', [{
x: [time()], y: [0], name: 'MV06', mode: 'lines' x: time0, y: [0], name: 'MV06', mode: 'lines'
}], { }], {
title: 'MV06 (%)', yaxis: { range: [0, 100] }, xaxis: { type: 'date' } title: 'MV06 (%)', yaxis: { range: [0, 100] }, xaxis: { type: 'date' }
}); });
// MV07
Plotly.newPlot('mv07-plot', [{ Plotly.newPlot('mv07-plot', [{
x: [time()], y: [0], name: 'MV07', mode: 'lines' x: time0, y: [0], name: 'MV07', mode: 'lines'
}], { }], {
title: 'MV07 (%)', yaxis: { range: [0, 100] }, xaxis: { type: 'date' } title: 'MV07 (%)', yaxis: { range: [0, 100] }, xaxis: { type: 'date' }
}); });
// MV08
Plotly.newPlot('mv08-plot', [{ Plotly.newPlot('mv08-plot', [{
x: [time()], y: [0], name: 'MV08', mode: 'lines' x: time0, y: [0], name: 'MV08', mode: 'lines'
}], { }], {
title: 'MV08 (%)', yaxis: { range: [0, 100] }, xaxis: { type: 'date' } title: 'MV08 (%)', yaxis: { range: [0, 100] }, xaxis: { type: 'date' }
}); });
// Update every second
setInterval(updatePlots, 1000); setInterval(updatePlots, 1000);
} }

View File

@ -360,7 +360,6 @@ function updatePloopSetpoint(value) {
} }
} }
async function fetchPUStatus() { async function fetchPUStatus() {
const response = await fetch("/api/pu_status"); const response = await fetch("/api/pu_status");
const data = await response.json(); const data = await response.json();
@ -419,10 +418,12 @@ function updatePloopSetpoint(value) {
<script> <script>
async function fetchMonitorData() { async function fetchMonitorData() {
try { try {
const response = await fetch('/monitor'); const puMap = {
const data = await response.json(); "PU_1": 1,
"PU_2": 2,
"PU_3": 3
};
const keys = ["PU_1", "PU_2", "PU_3"];
const fields = { const fields = {
"Qperm": "L/h", "Qperm": "L/h",
"Pdilute": "bar", "Pdilute": "bar",
@ -430,23 +431,34 @@ function updatePloopSetpoint(value) {
"Pro": "bar" "Pro": "bar"
}; };
for (const field in fields) { const dataResponse = await fetch('/monitor');
const container = document.getElementById(field); const allData = await dataResponse.json(); // Returns {PU_1: {...}, PU_2: {...}, PU_3: {...}}
for (const [fieldId, unit] of Object.entries(fields)) {
const container = document.getElementById(fieldId);
if (!container) continue; if (!container) continue;
container.innerHTML = keys.map((pu, i) => { const valueElements = container.querySelectorAll('.monitor-value');
const value = data[pu]?.[field] ?? 0.0;
return `<div class="monitor-value">#${i + 1}<br>${value.toFixed(1)} ${fields[field]}</div>`; let index = 0;
}).join(''); for (const [puLabel, puData] of Object.entries(allData)) {
const value = puData[fieldId] ?? 0.0;
// Reuse DOM element if it exists
if (valueElements[index]) {
valueElements[index].innerHTML = `#${index + 1}<br>${value.toFixed(1)} ${unit}`;
}
index++;
}
} }
} catch (error) { } catch (error) {
console.error('Erreur lors de la récupération des données de /monitor :', error); console.error('Error fetching monitor data:', error);
} }
} }
setInterval(fetchMonitorData, 1000); setInterval(fetchMonitorData, 1000);
fetchMonitorData(); // First call fetchMonitorData(); // initial load
</script> </script>
</body> </body>
</html> </html>