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.polling_thread = None
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")
def connect(self):
@ -58,40 +62,43 @@ class CANBackend:
while self.polling_active:
with self.lock:
try:
# Poll only PU1 (node ID 0x02) for live monitor values
node = self.nodes.get(2)
if node:
fm1 = node.sdo[0x2004][1].raw
fm2 = node.sdo[0x2004][2].raw
fm3 = node.sdo[0x2004][3].raw
fm4 = node.sdo[0x2004][4].raw
for pu_number, node in self.nodes.items():
try:
fm1 = node.sdo[0x2004][1].raw
fm2 = node.sdo[0x2004][2].raw
fm3 = node.sdo[0x2004][3].raw
fm4 = node.sdo[0x2004][4].raw
ps1 = node.sdo[0x2005][1].raw
ps2 = node.sdo[0x2005][2].raw
ps3 = node.sdo[0x2005][3].raw
ps4 = node.sdo[0x2005][4].raw
ps1 = node.sdo[0x2005][1].raw
ps2 = node.sdo[0x2005][2].raw
ps3 = node.sdo[0x2005][3].raw
ps4 = node.sdo[0x2005][4].raw
self.latest_data["FM1"] = fm1 / 100.0
self.latest_data["FM2"] = fm2 / 100.0
self.latest_data["FM3"] = fm3 / 100.0
self.latest_data["FM4"] = fm4 / 100.0
self.latest_data[pu_number] = {
"FM1": fm1 / 100.0,
"FM2": fm2 / 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
}
print(f"[PU{pu_number}] FM1: {fm1}, PS1: {ps1}")
except Exception as inner_e:
print(f"[SDO READ ERROR] PU{pu_number}: {inner_e}")
except Exception as outer_e:
print(f"[SDO POLL ERROR] {outer_e}")
self.latest_data["PS1"] = ps1 / 1000.0
self.latest_data["PS2"] = ps2 / 1000.0
self.latest_data["PS3"] = ps3 / 1000.0
self.latest_data["PS4"] = ps4 / 1000.0
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)
def get_latest_data(self):
def get_latest_data(self, pu_number: int):
with self.lock:
return self.latest_data.copy()
return self.latest_data.get(pu_number, {}).copy()
def read_current_state(self, pu_number: int):
try:

85
main.py
View File

@ -145,12 +145,13 @@ def get_pu_status():
return JSONResponse(content=states)
from typing import Optional
from fastapi import Query
@app.get("/monitor")
def get_monitor_data():
data = can_backend.get_latest_data()
print(f"[MONITOR] Latest SDO: {data}")
return {
"PU_1": {
def get_monitor_data(pu_number: Optional[int] = Query(None)):
def format_data(data):
return {
"Qperm": data.get("FM1", 0.0),
"Qdilute": data.get("FM2", 0.0),
"Qdrain": data.get("FM3", 0.0),
@ -177,70 +178,22 @@ def get_monitor_data():
"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),
"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)
}
}
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")
def can_status():

View File

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

View File

@ -360,7 +360,6 @@ function updatePloopSetpoint(value) {
}
}
async function fetchPUStatus() {
const response = await fetch("/api/pu_status");
const data = await response.json();
@ -419,10 +418,12 @@ function updatePloopSetpoint(value) {
<script>
async function fetchMonitorData() {
try {
const response = await fetch('/monitor');
const data = await response.json();
const puMap = {
"PU_1": 1,
"PU_2": 2,
"PU_3": 3
};
const keys = ["PU_1", "PU_2", "PU_3"];
const fields = {
"Qperm": "L/h",
"Pdilute": "bar",
@ -430,23 +431,34 @@ function updatePloopSetpoint(value) {
"Pro": "bar"
};
for (const field in fields) {
const container = document.getElementById(field);
const dataResponse = await fetch('/monitor');
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;
container.innerHTML = keys.map((pu, i) => {
const value = data[pu]?.[field] ?? 0.0;
return `<div class="monitor-value">#${i + 1}<br>${value.toFixed(1)} ${fields[field]}</div>`;
}).join('');
const valueElements = container.querySelectorAll('.monitor-value');
let index = 0;
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) {
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);
fetchMonitorData(); // First call
fetchMonitorData(); // initial load
</script>
</body>
</html>