Added hmi project
This commit is contained in:
commit
f411d715d8
101
classCAN.py
Normal file
101
classCAN.py
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
import threading
|
||||
import canopen
|
||||
import time
|
||||
|
||||
class CANBackend:
|
||||
def __init__(self):
|
||||
self.network = None
|
||||
self.node = None
|
||||
self.connected = False
|
||||
self.latest_data = {}
|
||||
self.lock = threading.Lock()
|
||||
|
||||
# Initialize thread-related attributes
|
||||
self.polling_thread = None
|
||||
self.polling_active = False
|
||||
|
||||
def connect(self, node_id, eds_path):
|
||||
try:
|
||||
self.network = canopen.Network()
|
||||
self.network.connect(bustype='socketcan', channel='can0', bitrate=250000)
|
||||
self.node = canopen.RemoteNode(node_id, eds_path)
|
||||
self.network.add_node(self.node)
|
||||
self.node.nmt.state = 'PRE-OPERATIONAL'
|
||||
|
||||
self.connected = True
|
||||
self.latest_data = {}
|
||||
|
||||
# Start polling thread
|
||||
self._start_sdo_polling()
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"[CAN ERROR] {e}")
|
||||
self.connected = False
|
||||
return False
|
||||
|
||||
def _start_sdo_polling(self):
|
||||
if self.polling_thread and self.polling_thread.is_alive():
|
||||
return # Already running
|
||||
self.polling_active = True
|
||||
self.polling_thread = threading.Thread(target=self._sdo_polling_loop, daemon=True)
|
||||
self.polling_thread.start()
|
||||
|
||||
def _sdo_polling_loop(self):
|
||||
while self.polling_active:
|
||||
with self.lock:
|
||||
try:
|
||||
fm2 = self.node.sdo[0x2004][2].raw
|
||||
ps1 = self.node.sdo[0x2005][1].raw
|
||||
self.latest_data["FM2"] = fm2/100
|
||||
self.latest_data["PS1"] = ps1/1000
|
||||
print(f"[SDO POLL] FM2: {fm2}, PS1: {ps1}")
|
||||
except Exception as e:
|
||||
print(f"[SDO POLL ERROR] {e}")
|
||||
time.sleep(1.0)
|
||||
|
||||
def get_latest_data(self):
|
||||
with self.lock:
|
||||
return self.latest_data.copy()
|
||||
|
||||
def send_state_command(self, state: str, pu_number: int):
|
||||
if not self.connected:
|
||||
raise RuntimeError("CAN not connected")
|
||||
|
||||
state_map = {
|
||||
"IDLE": 0,
|
||||
"PRODUCTION": 1,
|
||||
"MAINTENANCE": 3,
|
||||
"EMERGENCY_STOP": 4,
|
||||
"FIRST_START": 5
|
||||
}
|
||||
|
||||
if state not in state_map:
|
||||
raise ValueError(f"Invalid state: {state}")
|
||||
|
||||
try:
|
||||
print(f"[DEBUG] Writing state {state_map[state]} to index 0x2024, subindex {pu_number}")
|
||||
self.node.sdo[0x2024][0x01].raw = state_map[state]
|
||||
except Exception as e:
|
||||
print(f"[SDO WRITE ERROR] Failed to write to 0x2024:{pu_number} - {e}")
|
||||
raise
|
||||
|
||||
|
||||
def send_thermal_loop_cleaning(self, mode: str):
|
||||
if not self.connected:
|
||||
raise RuntimeError("Not connected to CAN")
|
||||
|
||||
mode_map = {
|
||||
"IDLE": 0,
|
||||
"ACTIVE": 1
|
||||
}
|
||||
|
||||
if mode not in mode_map:
|
||||
raise ValueError(f"Invalid thermal loop mode: {mode}")
|
||||
|
||||
self.node.sdo[0x2024][0x01].raw = mode_map[mode]
|
||||
|
||||
def shutdown(self):
|
||||
self.polling_active = False
|
||||
if self.network:
|
||||
self.network.disconnect()
|
||||
self.connected = False
|
||||
2422
eds_file/processBoard_0.eds
Normal file
2422
eds_file/processBoard_0.eds
Normal file
File diff suppressed because it is too large
Load Diff
95
main.py
Normal file
95
main.py
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.responses import HTMLResponse
|
||||
import logging
|
||||
from classCAN import CANBackend # Your real backend
|
||||
|
||||
app = FastAPI()
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
can_backend = CANBackend()
|
||||
|
||||
# Serve static files (HTML, JS, CSS)
|
||||
app.mount("/static", StaticFiles(directory="static"), name="static")
|
||||
|
||||
@app.post("/connect_toggle")
|
||||
def connect_toggle():
|
||||
"""Toggle CAN connection."""
|
||||
logging.info("Toggling CAN connection...")
|
||||
if can_backend.connected:
|
||||
can_backend.shutdown()
|
||||
return {"connected": False}
|
||||
else:
|
||||
success = can_backend.connect(
|
||||
node_id=0x02,
|
||||
eds_path=r"/eds_file/processBoard_0.eds"
|
||||
)
|
||||
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):
|
||||
"""Send a state command to a specific PU."""
|
||||
logging.info(f"Sending state '{state}' to PU {pu_number}")
|
||||
try:
|
||||
can_backend.send_state_command(state.upper(), pu_number)
|
||||
return {"status": "success", "command": state.upper(), "pu": pu_number}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@app.get("/monitor")
|
||||
def get_monitor_data():
|
||||
data = can_backend.get_latest_data()
|
||||
print(f"[MONITOR] Latest SDO: {data}")
|
||||
return {
|
||||
"Qperm": [0.0, data.get("FM2", 0.0), 0.0],
|
||||
"Pdilute": [data.get("PS1", 0.0), 0.0, 0.0],
|
||||
"Conductivity": [0.0, 0.0, 0.0],
|
||||
"Pro": [0.0, 0.0, 0.0],
|
||||
}
|
||||
|
||||
|
||||
|
||||
#
|
||||
# @app.get("/monitor")
|
||||
# def get_monitor_values():
|
||||
# """
|
||||
# Returns current machine monitoring data.
|
||||
# Expected structure:
|
||||
# Q_perm: [Q1, Q2, Q3]
|
||||
# Pdilute: [P1, P2, P3]
|
||||
# Conductivity: [C1, C2, C3]
|
||||
# Pro: [PR1, PR2, PR3]
|
||||
# """
|
||||
# try:
|
||||
# return {
|
||||
# "Q_perm": can_backend.get_q_perm(),
|
||||
# "Pdilute": can_backend.get_pdilute(),
|
||||
# "Conductivity": can_backend.get_conductivity(),
|
||||
# "Pro": can_backend.get_pro(),
|
||||
# }
|
||||
# except Exception as e:
|
||||
# raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@app.get("/can_status")
|
||||
def can_status():
|
||||
"""Return current CAN connection status."""
|
||||
return {"connected": can_backend.connected}
|
||||
|
||||
@app.get("/", response_class=HTMLResponse)
|
||||
async def read_root():
|
||||
"""Serve main HTML page."""
|
||||
with open("static/index.html", "r") as file:
|
||||
return HTMLResponse(content=file.read(), status_code=200)
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run(
|
||||
"main:app",
|
||||
host="0.0.0.0",
|
||||
port=8000,
|
||||
reload=True,
|
||||
reload_dirs=["."],
|
||||
)
|
||||
253
static/index.html
Normal file
253
static/index.html
Normal file
|
|
@ -0,0 +1,253 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Hydraulic Machine Control</title>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
|
||||
<style>
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100vh;
|
||||
background-color: #f4f4f9;
|
||||
}
|
||||
.header {
|
||||
background-color: #333;
|
||||
padding: 10px;
|
||||
text-align: center;
|
||||
}
|
||||
.connect-button {
|
||||
background-color: #ff4444;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 10px 20px;
|
||||
font-size: 16px;
|
||||
cursor: pointer;
|
||||
border-radius: 5px;
|
||||
transition: background-color 0.3s;
|
||||
}
|
||||
.connected {
|
||||
background-color: #00C851;
|
||||
}
|
||||
.container {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
}
|
||||
.left-panel, .right-panel {
|
||||
flex: 1;
|
||||
padding: 20px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.left-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 15px;
|
||||
background-color: #e9ecef;
|
||||
}
|
||||
.mode-block {
|
||||
border: 1px solid #ccc;
|
||||
padding: 15px;
|
||||
border-radius: 5px;
|
||||
background-color: #fff;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
transition: background-color 0.3s;
|
||||
}
|
||||
.mode-block.active {
|
||||
background-color: #a5d6a7; /* Light green background for active mode */
|
||||
}
|
||||
.mode-block h2 {
|
||||
margin-top: 0;
|
||||
color: #333;
|
||||
}
|
||||
.mode-block button {
|
||||
background-color: #4285F4;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 10px;
|
||||
margin: 5px 0;
|
||||
cursor: pointer;
|
||||
border-radius: 5px;
|
||||
width: 100%;
|
||||
font-size: 14px;
|
||||
transition: background-color 0.3s;
|
||||
}
|
||||
.mode-block button:hover {
|
||||
background-color: #3367d6;
|
||||
}
|
||||
.mode-block button i {
|
||||
margin-right: 8px;
|
||||
}
|
||||
.monitor-block {
|
||||
border: 1px solid #ccc;
|
||||
padding: 15px;
|
||||
border-radius: 5px;
|
||||
background-color: #fff;
|
||||
margin-bottom: 15px;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
}
|
||||
.monitor-block h2 {
|
||||
margin-top: 0;
|
||||
color: #333;
|
||||
}
|
||||
.monitor-values {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 10px;
|
||||
}
|
||||
.monitor-value {
|
||||
border: 1px solid #ddd;
|
||||
padding: 10px;
|
||||
text-align: center;
|
||||
border-radius: 5px;
|
||||
background-color: #f8f9fa;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="header">
|
||||
<button id="connectButton" class="connect-button" onclick="toggleConnection()">
|
||||
<i class="fas fa-plug"></i> Disconnected
|
||||
</button>
|
||||
</div>
|
||||
<div class="container">
|
||||
<div class="left-panel">
|
||||
<div class="mode-block" id="idleMode">
|
||||
<h2><i class="fas fa-pause-circle"></i> IDLE Mode</h2>
|
||||
<button onclick="triggerPU('IDLE', 1)"><i class="fas fa-power-off"></i> PU 1</button>
|
||||
<button onclick="triggerPU('IDLE', 2)"><i class="fas fa-power-off"></i> PU 2</button>
|
||||
<button onclick="triggerPU('IDLE', 3)"><i class="fas fa-power-off"></i> PU 3</button>
|
||||
</div>
|
||||
<div class="mode-block" id="prodMode">
|
||||
<h2><i class="fas fa-play-circle"></i> PRODUCTION Mode</h2>
|
||||
<button onclick="triggerPU('PRODUCTION', 1)"><i class="fas fa-power-off"></i> PU 1</button>
|
||||
<button onclick="triggerPU('PRODUCTION', 2)"><i class="fas fa-power-off"></i> PU 2</button>
|
||||
<button onclick="triggerPU('PRODUCTION', 3)"><i class="fas fa-power-off"></i> PU 3</button>
|
||||
</div>
|
||||
<div class="mode-block" id="firstStartMode">
|
||||
<h2><i class="fas fa-sync-alt"></i> First Start</h2>
|
||||
<button onclick="triggerPU('FIRST_START', 1)"><i class="fas fa-power-off"></i> PU 1</button>
|
||||
<button onclick="triggerPU('FIRST_START', 2)"><i class="fas fa-power-off"></i> PU 2</button>
|
||||
<button onclick="triggerPU('FIRST_START', 3)"><i class="fas fa-power-off"></i> PU 3</button>
|
||||
</div>
|
||||
<div class="mode-block">
|
||||
<h2><i class="fas fa-broom"></i> Thermal Loop Cleaning</h2>
|
||||
<button onclick="thermalLoopCleaning('IDLE')"><i class="fas fa-broom"></i> Clean</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="right-panel">
|
||||
<div class="monitor-block">
|
||||
<h2><i class="fas fa-tachometer-alt"></i> Q perm</h2>
|
||||
<div class="monitor-values" id="Qperm">
|
||||
<div class="monitor-value">Q1: 0.0</div>
|
||||
<div class="monitor-value">Q2: 0.0</div>
|
||||
<div class="monitor-value">Q3: 0.0</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="monitor-block">
|
||||
<h2><i class="fas fa-water"></i> Pdilute</h2>
|
||||
<div class="monitor-values" id="Pdilute">
|
||||
<div class="monitor-value">P1: 0.0</div>
|
||||
<div class="monitor-value">P2: 0.0</div>
|
||||
<div class="monitor-value">P3: 0.0</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="monitor-block">
|
||||
<h2><i class="fas fa-bolt"></i> Conductivity</h2>
|
||||
<div class="monitor-values" id="Conductivity">
|
||||
<div class="monitor-value">C1: 0.0</div>
|
||||
<div class="monitor-value">C2: 0.0</div>
|
||||
<div class="monitor-value">C3: 0.0</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="monitor-block">
|
||||
<h2><i class="fas fa-flask"></i> Pro</h2>
|
||||
<div class="monitor-values" id="Pro">
|
||||
<div class="monitor-value">PR1: 0.0</div>
|
||||
<div class="monitor-value">PR2: 0.0</div>
|
||||
<div class="monitor-value">PR3: 0.0</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
async function toggleConnection() {
|
||||
const response = await fetch('/connect_toggle', {
|
||||
method: 'POST'
|
||||
});
|
||||
const data = await response.json();
|
||||
const connectButton = document.getElementById('connectButton');
|
||||
if (data.connected) {
|
||||
connectButton.classList.add('connected');
|
||||
connectButton.innerHTML = '<i class="fas fa-plug"></i> Connected';
|
||||
} else {
|
||||
connectButton.classList.remove('connected');
|
||||
connectButton.innerHTML = '<i class="fas fa-plug"></i> Disconnected';
|
||||
}
|
||||
}
|
||||
|
||||
async function triggerPU(state, puNumber) {
|
||||
const response = await fetch(`/command/${state}/pu/${puNumber}`, {
|
||||
method: 'POST'
|
||||
});
|
||||
const data = await response.json();
|
||||
console.log(data);
|
||||
|
||||
// Highlight the active mode block based on the state
|
||||
document.querySelectorAll('.mode-block').forEach(block => {
|
||||
block.classList.remove('active');
|
||||
});
|
||||
|
||||
// Map state to lowercase div ID suffix
|
||||
const stateToId = {
|
||||
"IDLE": "idle",
|
||||
"PRODUCTION": "prod",
|
||||
"FIRST_START": "firstStart"
|
||||
};
|
||||
|
||||
const blockId = stateToId[state];
|
||||
if (blockId) {
|
||||
const block = document.getElementById(`${blockId}Mode`);
|
||||
if (block) {
|
||||
block.classList.add('active');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async function thermalLoopCleaning(mode) {
|
||||
const response = await fetch(`/mode/${mode}/thermal_loop`, {
|
||||
method: 'POST'
|
||||
});
|
||||
const data = await response.json();
|
||||
console.log(data);
|
||||
}
|
||||
|
||||
async function updateMonitorData() {
|
||||
const response = await fetch('/monitor');
|
||||
const data = await response.json();
|
||||
updateMonitorValues('Qperm', data.Qperm);
|
||||
updateMonitorValues('Pdilute', data.Pdilute);
|
||||
updateMonitorValues('Conductivity', data.Conductivity);
|
||||
updateMonitorValues('Pro', data.Pro);
|
||||
}
|
||||
|
||||
function updateMonitorValues(id, values) {
|
||||
const container = document.getElementById(id);
|
||||
const valueElements = container.querySelectorAll('.monitor-value');
|
||||
valueElements.forEach((element, index) => {
|
||||
if (index < values.length) {
|
||||
element.textContent = `${id.charAt(0)}${index + 1}: ${values[index]}`;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Update monitor data every second
|
||||
setInterval(updateMonitorData, 1000);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Loading…
Reference in New Issue
Block a user