Compare commits

..
67 changed files with 986 additions and 2138 deletions

No files matched your search

-2
View File
@@ -3,5 +3,3 @@ dist/
.DS_Store
Cargo.lock
dhat-heap.json
build.sh
-14
View File
@@ -1,17 +1,3 @@
# `2.11.0`
_21.10.2025_
## General
- [#829](https://github.com/qitechgmbh/control/pull/829), [#834](https://github.com/qitechgmbh/control/pull/834), Improved overall system stability
## Winder V2
- [#840](https://github.com/qitechgmbh/control/pull/840) Added XL Winder option
- [#827](https://github.com/qitechgmbh/control/pull/827) Spool can now be run in reverse
## Extruder V2
- [#826](https://github.com/qitechgmbh/control/pull/826) Fine grained Temperature-PID configuration now possible
# `2.10.0`
_16.10.2025_
Generated
+3 -6
View File
@@ -1036,8 +1036,7 @@ dependencies = [
[[package]]
name = "ethercrab"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fbb13becfa15713adb09b27fdb74468b827cdc78aa99aea638a89c1b0db3ce94"
source = "git+https://github.com/kraemr/ethercrab-deterministic.git?rev=53533ee42d11a32f6b8638233b59c402f3eb1998#53533ee42d11a32f6b8638233b59c402f3eb1998"
dependencies = [
"async-io",
"atomic-waker",
@@ -1066,8 +1065,7 @@ dependencies = [
[[package]]
name = "ethercrab-wire"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d15828cb020fb44c92ca67e1ee3c122c9621c2e00d383d066e488f0619023ba2"
source = "git+https://github.com/kraemr/ethercrab-deterministic.git?rev=53533ee42d11a32f6b8638233b59c402f3eb1998#53533ee42d11a32f6b8638233b59c402f3eb1998"
dependencies = [
"ethercrab-wire-derive",
"heapless",
@@ -1076,8 +1074,7 @@ dependencies = [
[[package]]
name = "ethercrab-wire-derive"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e790b8011211ed70babfcacbd4277b91ee21402ad5ba6a2c293db02e2f12919"
source = "git+https://github.com/kraemr/ethercrab-deterministic.git?rev=53533ee42d11a32f6b8638233b59c402f3eb1998#53533ee42d11a32f6b8638233b59c402f3eb1998"
dependencies = [
"criterion",
"proc-macro2",
+3
View File
@@ -25,3 +25,6 @@ style = { level = "warn", priority = -1 }
pendantic = { level = "warn", priority = -1 }
cargo = { level = "warn", priority = -1 }
nursery = { level = "warn", priority = -1 }
[patch.crates-io]
ethercrab = { git = "https://github.com/kraemr/ethercrab-deterministic.git",rev = "53533ee42d11a32f6b8638233b59c402f3eb1998" }
+1 -1
View File
@@ -15,7 +15,7 @@ if [[ "$1" == "release" ]]; then
cargo build --release
else
echo "Building Debug Code"
cargo build $FEATURE --features development-build
cargo build $FEATURE
fi
# Only setcap if not building with mock-machine
@@ -27,7 +27,6 @@ use ethercat_hal::devices::el7031::{EL7031_IDENTITY_A, EL7031_IDENTITY_B};
use ethercat_hal::devices::el7031_0030::EL7031_0030_IDENTITY_A;
use ethercat_hal::devices::el7041_0052::EL7041_0052_IDENTITY_A;
use ethercat_hal::devices::subdevice_identity_to_tuple;
use ethercat_hal::devices::wago_750_354::WAGO_750_354_IDENTITY;
use ethercat_hal::helpers::ethercrab_types::{
EthercrabSubDeviceOperational, EthercrabSubDevicePreoperational,
};
@@ -259,7 +258,6 @@ pub fn get_identification_addresses(
EL7031_IDENTITY_A | EL7031_IDENTITY_B => MachineIdentificationAddresses::default(),
EL7031_0030_IDENTITY_A => MachineIdentificationAddresses::default(),
EL7041_0052_IDENTITY_A => MachineIdentificationAddresses::default(),
WAGO_750_354_IDENTITY => MachineIdentificationAddresses::default(),
_ => {
// block_on(u16dump(&subdevice, maindevice, 0x00, 0xff))?;
@@ -153,13 +153,13 @@ fn test_interface(interface: &str) -> Result<(), anyhow::Error> {
// Default 0ms
wait_loop_delay: Duration::from_millis(0),
// Default 100ms
mailbox_echo: Duration::from_millis(1000),
mailbox_echo: Duration::from_millis(100),
// Default 1000ms
mailbox_response: Duration::from_millis(2000),
mailbox_response: Duration::from_millis(1000),
},
MainDeviceConfig {
// Default 10000
dc_static_sync_iterations: 0,
dc_static_sync_iterations: 10000,
// Default None
retry_behaviour: ethercrab::RetryBehaviour::Count(3),
},
+1 -1
View File
@@ -102,7 +102,7 @@ pub struct MachineCrossConnection<
// to an unknown type. See also https://github.com/qitechgmbh/control/pull/625#discussion_r2379566315
}
#[derive(Serialize, Debug, Clone, Default)]
#[derive(Serialize, Debug, Clone)]
pub struct MachineCrossConnectionState {
/// Connected Machine
pub machine_identification_unique: Option<MachineIdentificationUnique>,
+2 -2
View File
@@ -52,7 +52,7 @@ pub fn set_realtime_priority() -> Result<(), anyhow::Error> {
use anyhow::anyhow;
use libc::{SCHED_FIFO, pthread_setschedparam, sched_param};
use std::mem;
/*
unsafe {
// Get the pthread_t of the current thread using pthread_self()
let pthread_self = libc::pthread_self();
@@ -80,7 +80,7 @@ pub fn set_realtime_priority() -> Result<(), anyhow::Error> {
std::thread::current().name().unwrap_or("unknown")
);
}
}*/
}
Ok(())
}
+7 -3
View File
@@ -1,10 +1,13 @@
use std::{any::Any, sync::Arc};
use smol::lock::RwLock;
use smol::{channel::Sender, lock::RwLock};
use std::fmt::Debug;
use crate::machines::identification::DeviceIdentification;
use crate::{
machines::identification::DeviceIdentification, serial::serial_detection::SerialDeviceRemoval,
};
pub mod panic;
pub mod registry;
pub mod serial_detection;
@@ -24,9 +27,10 @@ pub trait SerialDeviceThread {
pub struct SerialDeviceNewParams {
pub path: String,
pub device_thread_panic_tx: Sender<SerialDeviceRemoval<String>>,
}
#[derive(PartialEq, Eq, Clone, Debug, Hash)]
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct SerialDeviceIdentification {
pub vendor_id: u16,
pub product_id: u16,
+53
View File
@@ -0,0 +1,53 @@
use smol::channel::Sender;
use crate::serial::serial_detection::SerialDeviceRemoval;
/// Device-level panic handler for individual device crashes
/// Sends device identifier and error information for cleanup
/// Used by serial devices and other individual components that need to be removed on panic
pub fn send_serial_device_panic<T>(
device_identifier: T,
thread_panic_tx: Sender<SerialDeviceRemoval<T>>,
) where
T: Send + Sync + Clone + 'static,
{
// Ensure backtrace is enabled for panics
if std::env::var("RUST_BACKTRACE").is_err() {
unsafe {
std::env::set_var("RUST_BACKTRACE", "full");
}
}
std::panic::set_hook(Box::new(move |panic_info| {
let thread_name = std::thread::current()
.name()
.unwrap_or("unnamed")
.to_string();
let location = panic_info.location().map_or("unknown".to_string(), |loc| {
format!("{}:{}:{}", loc.file(), loc.line(), loc.column())
});
let message = panic_info
.payload()
.downcast_ref::<&str>()
.unwrap_or(&"Box<dyn Any>")
.to_string();
let panic_message = format!(
"Device panicked in thread '{}' at {}: {}",
thread_name, location, message
);
// Send device panic info through channel
smol::block_on(async {
let _ = thread_panic_tx
.send(SerialDeviceRemoval::Error(
device_identifier.clone(),
anyhow::anyhow!("{}", panic_message),
))
.await;
});
// Note: We don't call old_hook to avoid duplicate logging
// All logging is handled in the main thread when receiving panic details
}));
}
+173 -49
View File
@@ -7,70 +7,194 @@
*/
use serialport::{SerialPortInfo, SerialPortType, UsbPortInfo};
use std::collections::HashMap;
use smol::{
channel::{Receiver, Sender, unbounded},
lock::RwLock,
};
use std::{collections::HashMap, sync::Arc};
use super::SerialDeviceIdentification;
/// Handles scanning and caching of connected USB serial devices.
pub struct SerialDetection {}
use crate::{
helpers::compare_lists::compare_lists, machines::identification::DeviceIdentification,
};
impl SerialDetection {
/// Returns all serial ports on the system (minus macOS "cu" noise).
fn get_ports() -> Vec<SerialPortInfo> {
match serialport::available_ports() {
Ok(ports) => ports
.into_iter()
.filter(|port| !port.port_name.contains("cu"))
.collect(),
Err(_) => Vec::new(),
use super::{
SerialDevice, SerialDeviceIdentification, SerialDeviceNewParams, registry::SerialDeviceRegistry,
};
pub enum SerialDeviceRemoval<T> {
Disconnect(T),
Error(T, anyhow::Error),
}
pub struct SerialDetection<'serialdeviceregistry> {
pub serial_device_registry: &'serialdeviceregistry SerialDeviceRegistry,
pub ports: HashMap<
String,
(
UsbPortInfo,
DeviceIdentification,
Arc<RwLock<dyn SerialDevice>>,
),
>,
pub device_removal_signal_rx: Receiver<SerialDeviceRemoval<String>>,
pub device_removal_signal_tx: Sender<SerialDeviceRemoval<String>>,
}
impl<'serialdeviceregistry> SerialDetection<'serialdeviceregistry> {
pub fn new(serial_device_registry: &'serialdeviceregistry SerialDeviceRegistry) -> Self {
let (device_removal_signal_tx, device_removal_signal_rx) = unbounded();
SerialDetection {
serial_device_registry,
ports: HashMap::new(),
device_removal_signal_rx,
device_removal_signal_tx,
}
}
/// Extracts only USB serial devices from the port list.
fn extract_usb_serial_devices(port_list: Vec<SerialPortInfo>) -> HashMap<String, UsbPortInfo> {
let mut map = HashMap::new();
/*
*@return: Option::None if there are no available ports on device
*@return: Option::Some(Vec) with all available ports
*
*@description: detects all available ports and returns them as list
*/
fn get_ports() -> Vec<SerialPortInfo> {
let all = match serialport::available_ports() {
Ok(ports) => ports,
Err(_) => return Vec::new(),
};
// exclude ports that contai "cu" in their name
all.into_iter()
.filter(|port| !port.port_name.contains("cu"))
.collect::<Vec<_>>()
}
/* @param: port_list -> list of available ports
*
* @return: Vec<(String, UsbPortInfo)> -> list of ports with their names and usb information
*
* @description: This function extracts the USB serial devices from the given list of ports.
*/
fn extract_usb_serial_devices(
&self,
port_list: Vec<SerialPortInfo>,
) -> Vec<(String, UsbPortInfo)> {
let mut usb_ports: Vec<(String, UsbPortInfo)> = Vec::new();
for port in port_list {
if let SerialPortType::UsbPort(usb_info) = port.port_type {
map.insert(port.port_name, usb_info);
if let SerialPortType::UsbPort(usb_info) = &port.port_type {
usb_ports.push((port.port_name.to_string(), usb_info.clone()));
};
}
usb_ports
}
pub async fn check_ports(&mut self) -> CheckPortsResult {
// get available ports
let ports = Self::get_ports();
// extract all ports that are usb ports
let usb_ports = self.extract_usb_serial_devices(ports);
let last_usb_ports = self
.ports
.iter()
.map(|last_usb_port| (last_usb_port.0.clone(), last_usb_port.1.0.clone()))
.collect::<Vec<_>>();
let usb_ports_diff = compare_lists(&last_usb_ports, &usb_ports);
let mut result = CheckPortsResult {
added: Vec::new(),
removed: Vec::new(),
};
// reamove ports
for removed in usb_ports_diff.removed {
if let Some((_, device_identification, _)) = self.ports.remove(&removed.0) {
result.removed.push(device_identification);
}
tracing::trace!("Removed port: {}", removed.0);
}
// add new ports
for added in usb_ports_diff.added {
// add the port to the list
let serial_device_identification = SerialDeviceIdentification {
vendor_id: added.1.vid,
product_id: added.1.pid,
};
let device_result = self.serial_device_registry.new_serial_device(
&SerialDeviceNewParams {
path: added.0.clone(),
device_thread_panic_tx: self.device_removal_signal_tx.clone(),
},
&serial_device_identification,
);
// only if created device driver sucessfully
if let Ok((device_identification, device)) = device_result {
// add the device to the ports list
self.ports.insert(
added.0.clone(),
(
added.1.clone(),
device_identification.clone(),
device.clone(),
),
);
// add to result list
result.added.push((device_identification, device.clone()));
tracing::trace!("Added port: {}", added.0);
}
}
map
result
}
/// Scans for connected USB serial devices and updates the internal map.
/// Returns a clone of the map for quick access.
pub fn detect_devices() -> HashMap<String, UsbPortInfo> {
let ports = Self::get_ports();
let usb_devices = Self::extract_usb_serial_devices(ports);
usb_devices
}
pub async fn check_remove_signals(&mut self) -> Vec<DeviceIdentification> {
let mut removed_signals: Vec<DeviceIdentification> = Vec::new();
pub fn device_port_exists(device_path: &str) -> bool {
let ports = Self::get_ports();
return ports.iter().any(|p| p.port_name == device_path);
}
let mut add_removal_signal = |path: &String| {
if let Some(info) = self.ports.get(path) {
removed_signals.push(info.1.clone());
};
self.ports.remove(path);
};
pub fn device_id_exists(sdevid: SerialDeviceIdentification) -> bool {
let ports = Self::get_ports();
for port in ports {
if let SerialPortType::UsbPort(usb_info) = port.port_type {
if usb_info.vid == sdevid.vendor_id && usb_info.pid == sdevid.product_id {
return true;
}
if self.device_removal_signal_rx.is_empty() {
return removed_signals;
}
let removal = self
.device_removal_signal_rx
.recv()
.await
.expect("Failed to receive removal signals");
match removal {
SerialDeviceRemoval::Disconnect(path) => {
add_removal_signal(&path);
tracing::trace!("Removed serial device after disconnect: {:?}", path);
}
SerialDeviceRemoval::Error(path, error) => {
add_removal_signal(&path);
tracing::error!("Removed erroring serial device: {:?}: {}", path, error);
}
}
return false;
}
pub fn get_path_by_id(
sdevid: SerialDeviceIdentification,
map: HashMap<String, UsbPortInfo>,
) -> Option<String> {
for (port, usbport) in map.iter() {
if usbport.vid == sdevid.vendor_id && usbport.pid == sdevid.product_id {
return Some(port.clone());
}
}
return None;
removed_signals
}
}
#[derive(Debug)]
pub struct CheckPortsResult {
pub added: Vec<(DeviceIdentification, Arc<RwLock<dyn SerialDevice>>)>,
pub removed: Vec<DeviceIdentification>,
}
+1
View File
@@ -118,6 +118,7 @@ impl Namespace {
) {
// cache the event
self.cache(event.clone(), buffer_fn);
// emit the event - inlined from emit function
// Send to global queue for each socket in the namespace
for socket in self.sockets.clone() {
+26 -19
View File
@@ -70,7 +70,7 @@
"@electron/fuses": "^2.0.0",
"@eslint/compat": "^1.2.6",
"@eslint/js": "^9.18.0",
"@playwright/test": "^1.56.1",
"@playwright/test": "^1.50.1",
"@tailwindcss/postcss": "^4.0.6",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
@@ -97,7 +97,7 @@
"ts-node": "^10.9.2",
"typescript": "^5.7.3",
"typescript-eslint": "^8.24.1",
"vite": "^6.4.1",
"vite": "^6.3.6",
"vitest": "^3.0.6"
}
},
@@ -2278,13 +2278,12 @@
}
},
"node_modules/@playwright/test": {
"version": "1.56.1",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.56.1.tgz",
"integrity": "sha512-vSMYtL/zOcFpvJCW71Q/OEGQb7KYBPAdKh35WNSkaZA75JlAO8ED8UN6GUNTm3drWomcbcqRPFqQbLae8yBTdg==",
"version": "1.54.2",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.54.2.tgz",
"integrity": "sha512-A+znathYxPf+72riFd1r1ovOLqsIIB0jKIoPjyK2kqEIe30/6jF6BC7QNluHuwUmsD2tv1XZVugN8GqfTMOxsA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright": "1.56.1"
"playwright": "1.54.2"
},
"bin": {
"playwright": "cli.js"
@@ -7015,6 +7014,16 @@
"integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==",
"dev": true
},
"node_modules/encoding": {
"version": "0.1.13",
"resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.13.tgz",
"integrity": "sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A==",
"dev": true,
"optional": true,
"dependencies": {
"iconv-lite": "^0.6.2"
}
},
"node_modules/end-of-stream": {
"version": "1.4.5",
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
@@ -11868,13 +11877,12 @@
}
},
"node_modules/playwright": {
"version": "1.56.1",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.56.1.tgz",
"integrity": "sha512-aFi5B0WovBHTEvpM3DzXTUaeN6eN0qWnTkKx4NQaH4Wvcmc153PdaY2UBdSYKaGYw+UyWXSVyxDUg5DoPEttjw==",
"version": "1.54.2",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.54.2.tgz",
"integrity": "sha512-Hu/BMoA1NAdRUuulyvQC0pEqZ4vQbGfn8f7wPXcnqQmM+zct9UliKxsIkLNmz/ku7LElUNqmaiv1TG/aL5ACsw==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.56.1"
"playwright-core": "1.54.2"
},
"bin": {
"playwright": "cli.js"
@@ -11887,11 +11895,10 @@
}
},
"node_modules/playwright-core": {
"version": "1.56.1",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.56.1.tgz",
"integrity": "sha512-hutraynyn31F+Bifme+Ps9Vq59hKuUCz7H1kDOcBs+2oGguKkWTU50bBWrtz34OUWmIwpBTWDxaRPXrIXkgvmQ==",
"version": "1.54.2",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.54.2.tgz",
"integrity": "sha512-n5r4HFbMmWsB4twG7tJLDN9gmBUeSPcsBZiWSE4DnYz9mJMAFqr2ID7+eGC9kpEnxExJ1epttwR59LEWCk8mtA==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
@@ -14665,9 +14672,9 @@
}
},
"node_modules/vite": {
"version": "6.4.1",
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.1.tgz",
"integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==",
"version": "6.3.6",
"resolved": "https://registry.npmjs.org/vite/-/vite-6.3.6.tgz",
"integrity": "sha512-0msEVHJEScQbhkbVTb/4iHZdJ6SXp/AvxL2sjwYQFfBqleHtnCqv1J3sa9zbWz/6kW1m9Tfzn92vW+kZ1WV6QA==",
"license": "MIT",
"dependencies": {
"esbuild": "^0.25.0",
+2 -2
View File
@@ -34,7 +34,7 @@
"@electron/fuses": "^2.0.0",
"@eslint/compat": "^1.2.6",
"@eslint/js": "^9.18.0",
"@playwright/test": "^1.56.1",
"@playwright/test": "^1.50.1",
"@tailwindcss/postcss": "^4.0.6",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
@@ -61,7 +61,7 @@
"ts-node": "^10.9.2",
"typescript": "^5.7.3",
"typescript-eslint": "^8.24.1",
"vite": "^6.4.1",
"vite": "^6.3.6",
"vitest": "^3.0.6"
},
"dependencies": {
+2 -2
View File
@@ -386,7 +386,7 @@ const useSocketioStore = create<SocketioStore>()((set, get) => ({
// check if the namespace exists
const namespace = get().namespaces[namespace_path];
/*if (namespace) {
if (namespace) {
set(
produce((state: SocketioStore) => {
// decrement the count
@@ -430,7 +430,7 @@ const useSocketioStore = create<SocketioStore>()((set, get) => ({
}
}),
);
}*/
}
},
}));
@@ -6,7 +6,6 @@ import { SelectionGroupBoolean } from "@/control/SelectionGroup";
import { EditValue } from "@/control/EditValue";
import { roundToDecimals } from "@/lib/decimal";
import { useExtruder2 } from "./useExtruder";
import { ControlGrid } from "@/control/ControlGrid";
export function Extruder2SettingsPage() {
const {
@@ -19,7 +18,6 @@ export function Extruder2SettingsPage() {
setPressurePidKp,
setPressurePidKi,
setPressurePidKd,
setTemperaturePidValue,
} = useExtruder2();
const [showAdvanced, setShowAdvanced] = useState(false);
@@ -118,128 +116,6 @@ export function Extruder2SettingsPage() {
/>
</Label>
</ControlCard>
<ControlGrid>
<ControlCard title="Temperature PID Settings (Front) ">
<Label label="Kp">
<EditValue
value={state?.pid_settings.temperature.front.kp}
defaultValue={defaultState?.pid_settings.temperature.front.kp}
min={0}
max={100}
step={0.001}
renderValue={(v) => roundToDecimals(v, 3)}
onChange={(v) => setTemperaturePidValue("front", "kp", v)}
title="Temperature PID KP"
/>
</Label>
<Label label="Ki">
<EditValue
value={state?.pid_settings.temperature.front.ki}
defaultValue={defaultState?.pid_settings.temperature.front.ki}
min={0}
max={100}
step={0.001}
renderValue={(v) => roundToDecimals(v, 3)}
onChange={(v) => setTemperaturePidValue("front", "ki", v)}
title="Temperature PID KI"
/>
</Label>
<Label label="Kd">
<EditValue
value={state?.pid_settings.temperature.front.kd}
defaultValue={defaultState?.pid_settings.temperature.front.kd}
min={0}
max={100}
step={0.001}
renderValue={(v) => roundToDecimals(v, 3)}
onChange={(v) => setTemperaturePidValue("front", "kd", v)}
title="Temperature PID KD"
/>
</Label>
</ControlCard>
<ControlCard title="Temperature PID Settings (Middle) ">
<Label label="Kp">
<EditValue
value={state?.pid_settings.temperature.middle.kp}
defaultValue={
defaultState?.pid_settings.temperature.middle.kp
}
min={0}
max={100}
step={0.001}
renderValue={(v) => roundToDecimals(v, 3)}
onChange={(v) => setTemperaturePidValue("middle", "kp", v)}
title="Temperature PID KP"
/>
</Label>
<Label label="Ki">
<EditValue
value={state?.pid_settings.temperature.middle.ki}
defaultValue={
defaultState?.pid_settings.temperature.middle.ki
}
min={0}
max={100}
step={0.001}
renderValue={(v) => roundToDecimals(v, 3)}
onChange={(v) => setTemperaturePidValue("middle", "ki", v)}
title="Temperature PID KI"
/>
</Label>
<Label label="Kd">
<EditValue
value={state?.pid_settings.temperature.middle.kd}
defaultValue={
defaultState?.pid_settings.temperature.middle.kd
}
min={0}
max={100}
step={0.001}
renderValue={(v) => roundToDecimals(v, 3)}
onChange={(v) => setTemperaturePidValue("middle", "kd", v)}
title="Temperature PID KD"
/>
</Label>
</ControlCard>
<ControlCard title="Temperature PID Settings (Back) ">
<Label label="Kp">
<EditValue
value={state?.pid_settings.temperature.back.kp}
defaultValue={defaultState?.pid_settings.temperature.back.kp}
min={0}
max={100}
step={0.001}
renderValue={(v) => roundToDecimals(v, 3)}
onChange={(v) => setTemperaturePidValue("back", "kp", v)}
title="Temperature PID KP"
/>
</Label>
<Label label="Ki">
<EditValue
value={state?.pid_settings.temperature.back.ki}
defaultValue={defaultState?.pid_settings.temperature.back.ki}
min={0}
max={100}
step={0.001}
renderValue={(v) => roundToDecimals(v, 3)}
onChange={(v) => setTemperaturePidValue("back", "ki", v)}
title="Temperature PID KI"
/>
</Label>
<Label label="Kd">
<EditValue
value={state?.pid_settings.temperature.back.kd}
defaultValue={defaultState?.pid_settings.temperature.back.kd}
min={0}
max={100}
step={0.001}
renderValue={(v) => roundToDecimals(v, 3)}
onChange={(v) => setTemperaturePidValue("back", "kd", v)}
title="Temperature PID KD"
/>
</Label>
</ControlCard>
</ControlGrid>
</>
)}
</Page>
@@ -131,24 +131,9 @@ export const inverterStatusStateSchema = z.object({
*/
export const pidSettingsSchema = z.object({
temperature: z.object({
front: z.object({
ki: z.number(),
kp: z.number(),
kd: z.number(),
zone: z.string(),
}),
middle: z.object({
ki: z.number(),
kp: z.number(),
kd: z.number(),
zone: z.string(),
}),
back: z.object({
ki: z.number(),
kp: z.number(),
kd: z.number(),
zone: z.string(),
}),
ki: z.number(),
kp: z.number(),
kd: z.number(),
}),
pressure: z.object({
ki: z.number(),
@@ -293,33 +293,6 @@ export function useExtruder2() {
);
};
const setTemperaturePidValue = (
zone: "front" | "middle" | "back",
key: "kp" | "ki" | "kd",
value: number,
) => {
updateStateOptimistically(
(current) => {
current.data.pid_settings.temperature[zone][key] = value;
},
() => {
const currentState = stateOptimistic.value;
if (currentState) {
const settings = produce(
currentState.data.pid_settings.temperature[zone],
(draft) => {
draft[key] = value;
},
);
requestTemperaturePidSettings({
machine_identification_unique: machineIdentification,
data: { SetTemperaturePidSettings: settings },
});
}
},
);
};
const resetInverter = () => {
// No optimistic update needed for reset
requestResetInverter({
@@ -383,17 +356,6 @@ export function useExtruder2() {
}),
);
const { request: requestTemperaturePidSettings } = useMachineMutation(
z.object({
SetTemperaturePidSettings: z.object({
ki: z.number(),
kp: z.number(),
kd: z.number(),
zone: z.string(),
}),
}),
);
const { request: requestResetInverter } = useMachineMutation(
z.object({ ResetInverter: z.boolean() }),
);
@@ -442,7 +404,6 @@ export function useExtruder2() {
setPressurePidKp,
setPressurePidKi,
setPressurePidKd,
setTemperaturePidValue,
resetInverter,
};
}
@@ -28,11 +28,9 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { getWinder2TraverseMax } from "./winder2Config";
export function Winder2ControlPage() {
const [showResetConfirmDialog, setShowResetConfirmDialog] = useState(false);
const traverseMax = getWinder2TraverseMax();
// use optimistic state
const {
@@ -104,7 +102,7 @@ export function Winder2ControlPage() {
{state?.traverse_state && (
<TraverseBar
inside={0}
outside={traverseMax}
outside={180}
min={state?.traverse_state.limit_inner}
max={state?.traverse_state.limit_outer}
current={traversePosition.current?.value ?? 0}
@@ -123,7 +121,7 @@ export function Winder2ControlPage() {
min={Math.max(0, (state?.traverse_state?.limit_inner ?? 0) + 1)}
minLabel="IN"
maxLabel="OUT"
max={traverseMax}
max={180}
renderValue={(value) => roundToDecimals(value, 0)}
onChange={setTraverseLimitOuter}
/>
@@ -147,8 +145,8 @@ export function Winder2ControlPage() {
// We use 1mm buffer to ensure the backend validation (which requires outer > inner + 0.9mm) will pass
// Formula: max_inner = outer_limit - 1mm
max={Math.min(
traverseMax,
(state?.traverse_state?.limit_outer ?? traverseMax) - 1,
180,
(state?.traverse_state?.limit_outer ?? 180) - 1,
)}
defaultValue={defaultState?.traverse_state?.limit_inner}
minLabel="IN"
@@ -101,11 +101,6 @@ const previewEntries: PresetPreviewEntries<Winder2> = [
renderValue: (data: PresetData<Winder2>) =>
data.spool_speed_controller_state?.regulation_mode,
},
{
name: "Spool Direction",
renderValue: (data: PresetData<Winder2>) =>
data.spool_speed_controller_state?.forward ? "Forward" : "Reverse",
},
{
name: "Spool Min Speed",
unit: "rpm",
@@ -171,7 +166,6 @@ export function Winder2PresetsPage() {
setPullerGearRatio,
setSpoolRegulationMode,
setSpoolForward,
setSpoolMinMaxMinSpeed,
setSpoolMinMaxMaxSpeed,
@@ -200,7 +194,6 @@ export function Winder2PresetsPage() {
setSpoolRegulationMode(
preset.data?.spool_speed_controller_state?.regulation_mode ?? "MinMax",
);
setSpoolForward(preset.data?.spool_speed_controller_state?.forward ?? true);
setSpoolMinMaxMinSpeed(
preset.data?.spool_speed_controller_state?.minmax_min_speed ?? 0,
);
@@ -2,37 +2,25 @@ import { Page } from "@/components/Page";
import { ControlCard } from "@/control/ControlCard";
import { ControlGrid } from "@/control/ControlGrid";
import { EditValue } from "@/control/EditValue";
import React, { useState } from "react";
import React from "react";
import { useWinder2 } from "./useWinder";
import { roundToDecimals } from "@/lib/decimal";
import { Label } from "@/control/Label";
import { SelectionGroupBoolean } from "@/control/SelectionGroup";
import { SelectionGroup } from "@/control/SelectionGroup";
import { MachineSelector } from "@/components/MachineConnectionDropdown";
import {
getWinder2XLMode,
setWinder2XLMode,
WINDER2_TRAVERSE_MAX_STANDARD,
WINDER2_TRAVERSE_MAX_XL,
} from "./winder2Config";
export function Winder2SettingPage() {
const [xlMode, setXlMode] = useState(getWinder2XLMode());
const {
state,
defaultState,
setTraverseStepSize,
setTraversePadding,
setTraverseLimitInner,
setTraverseLimitOuter,
gotoTraverseHome,
setPullerForward,
setPullerGearRatio,
setSpoolRegulationMode,
setSpoolMinMaxMinSpeed,
setSpoolMinMaxMaxSpeed,
setSpoolForward,
setSpoolAdaptiveTensionTarget,
setSpoolAdaptiveRadiusLearningRate,
setSpoolAdaptiveMaxSpeedMultiplier,
@@ -46,58 +34,10 @@ export function Winder2SettingPage() {
disconnectMachine,
} = useWinder2();
const handleXlModeChange = (enabled: boolean) => {
setWinder2XLMode(enabled);
setXlMode(enabled);
// When switching from XL to normal mode, reset traverse limits to default values
if (!enabled && defaultState) {
// Only reset if current values exceed the standard max
const currentOuter = state?.traverse_state?.limit_outer ?? 0;
const currentInner = state?.traverse_state?.limit_inner ?? 0;
const defaultOuter = defaultState.traverse_state?.limit_outer;
const defaultInner = defaultState.traverse_state?.limit_inner;
if (
currentOuter > WINDER2_TRAVERSE_MAX_STANDARD &&
defaultOuter !== undefined
) {
setTraverseLimitOuter(defaultOuter);
setTraverseLimitInner(defaultInner);
}
if (
currentInner > WINDER2_TRAVERSE_MAX_STANDARD &&
defaultInner !== undefined
) {
setTraverseLimitOuter(defaultOuter);
setTraverseLimitInner(defaultInner);
}
// Home the traverse when switching from XL to normal mode
gotoTraverseHome();
}
};
return (
<Page>
<ControlGrid>
<ControlCard title="Traverse">
<Label label="Traverse Size">
<SelectionGroupBoolean
value={xlMode}
disabled={isDisabled}
loading={isLoading}
optionFalse={{
children: `Standard (${WINDER2_TRAVERSE_MAX_STANDARD}mm)`,
icon: "lu:Settings",
}}
optionTrue={{
children: `XL (${WINDER2_TRAVERSE_MAX_XL}mm)`,
icon: "lu:Maximize2",
}}
onChange={handleXlModeChange}
/>
</Label>
<Label label="Step Size">
<EditValue
value={state?.traverse_state?.step_size}
@@ -148,23 +88,6 @@ export function Winder2SettingPage() {
/>
</Label>
<Label label="Rotation Direction">
<SelectionGroupBoolean
value={state?.spool_speed_controller_state?.forward}
disabled={isDisabled}
loading={isLoading}
optionFalse={{
children: "Reverse",
icon: "lu:RotateCcw",
}}
optionTrue={{
children: "Forward",
icon: "lu:RotateCw",
}}
onChange={(value) => setSpoolForward(value)}
/>
</Label>
{state?.spool_speed_controller_state?.regulation_mode ===
"MinMax" && (
<>
@@ -134,9 +134,6 @@ export function useWinder2() {
const { request: requestSpoolSetMinMaxMaxSpeed } = useMachineMutation(
z.object({ SetSpoolMinMaxMaxSpeed: z.number() }),
);
const { request: requestSpoolSetForward } = useMachineMutation(
z.object({ SetSpoolForward: z.boolean() }),
);
const { request: requestSpoolSetAdaptiveTensionTarget } = useMachineMutation(
z.object({ SetSpoolAdaptiveTensionTarget: z.number() }),
);
@@ -470,19 +467,6 @@ export function useWinder2() {
);
};
const setSpoolForward = (forward: boolean) => {
updateStateOptimistically(
(current) => {
current.data.spool_speed_controller_state.forward = forward;
},
() =>
requestSpoolSetForward({
machine_identification_unique: machineIdentification,
data: { SetSpoolForward: forward },
}),
);
};
const setSpoolAdaptiveTensionTarget = (value: number) => {
updateStateOptimistically(
(current) => {
@@ -668,7 +652,6 @@ export function useWinder2() {
setSpoolRegulationMode,
setSpoolMinMaxMinSpeed,
setSpoolMinMaxMaxSpeed,
setSpoolForward,
setSpoolAdaptiveTensionTarget,
setSpoolAdaptiveRadiusLearningRate,
setSpoolAdaptiveMaxSpeedMultiplier,
@@ -1,35 +0,0 @@
/**
* Configuration helper for Winder2 machine settings
*/
const WINDER2_XL_MODE_KEY = "winder2_xl_mode";
export const WINDER2_TRAVERSE_MAX_STANDARD = 180; // mm
export const WINDER2_TRAVERSE_MAX_XL = 385; // mm
/**
* Get the XL mode setting from localStorage
* @returns true if XL mode is enabled, false otherwise
*/
export function getWinder2XLMode(): boolean {
const stored = localStorage.getItem(WINDER2_XL_MODE_KEY);
return stored === "true";
}
/**
* Set the XL mode setting in localStorage
* @param enabled - true to enable XL mode, false to disable
*/
export function setWinder2XLMode(enabled: boolean): void {
localStorage.setItem(WINDER2_XL_MODE_KEY, enabled.toString());
}
/**
* Get the maximum traverse limit based on XL mode
* @returns the maximum traverse limit in mm
*/
export function getWinder2TraverseMax(): number {
return getWinder2XLMode()
? WINDER2_TRAVERSE_MAX_XL
: WINDER2_TRAVERSE_MAX_STANDARD;
}
@@ -177,7 +177,6 @@ export const spoolSpeedControllerStateSchema = z.object({
adaptive_max_speed_multiplier: z.number(),
adaptive_acceleration_factor: z.number(),
adaptive_deacceleration_urgency_multiplier: z.number(),
forward: z.boolean(),
});
/**
+2 -8
View File
@@ -20,14 +20,11 @@ pub mod el6021;
pub mod el7031;
pub mod el7031_0030;
pub mod el7041_0052;
pub mod wago_750_354;
// pub mod el4008;
use super::devices::el1008::EL1008;
use crate::{
devices::{el2521::EL2521, el4002::EL4002},
helpers::ethercrab_types::{
EthercrabSubDeviceGroupPreoperational, EthercrabSubDeviceGroupSafeOperational,
},
helpers::ethercrab_types::EthercrabSubDeviceGroupPreoperational,
};
use anyhow::anyhow;
use bitvec::{order::Lsb0, slice::BitSlice};
@@ -56,7 +53,6 @@ use el7041_0052::EL7041_0052_IDENTITY_A;
use ethercrab::{MainDevice, SubDeviceIdentity};
use smol::lock::RwLock;
use std::{any::Any, fmt::Debug, sync::Arc};
use wago_750_354::{WAGO_750_354, WAGO_750_354_IDENTITY, WAGO_750_354_REVISION};
/// A trait for all devices
///
@@ -222,8 +218,6 @@ pub fn device_from_subdevice_identity_tuple(
EL2521_IDENTITY_0000_A | EL2521_IDENTITY_0000_B | EL2521_IDENTITY_0024_A => {
Ok(Arc::new(RwLock::new(EL2521::new())))
}
WAGO_750_354_IDENTITY => Ok(Arc::new(RwLock::new(WAGO_750_354::new()))),
_ => Err(anyhow::anyhow!(
"[{}::device_from_subdevice] No Driver: vendor_id: 0x{:x}, product_id: 0x{:x}, revision: 0x{:x}",
module_path!(),
@@ -245,7 +239,7 @@ pub fn device_from_subdevice_identity(
/// Array equivalent of [`device_from_subdevice`]
pub fn devices_from_subdevices<'maindevice, const MAX_SUBDEVICES: usize, const PDI_LEN: usize>(
group: &mut EthercrabSubDeviceGroupSafeOperational<MAX_SUBDEVICES, PDI_LEN>,
group: &mut EthercrabSubDeviceGroupPreoperational<MAX_SUBDEVICES, PDI_LEN>,
maindevice: &MainDevice,
) -> Result<Vec<Arc<RwLock<dyn EthercatDevice>>>, anyhow::Error> {
group
-133
View File
@@ -1,133 +0,0 @@
use super::{EthercatDeviceProcessing, NewEthercatDevice, SubDeviceIdentityTuple};
use crate::helpers::ethercrab_types::EthercrabSubDevicePreoperational;
use crate::io::digital_output::{DigitalOutputDevice, DigitalOutputOutput};
use crate::pdo::{RxPdo, basic::BoolPdoObject};
use ethercat_hal_derive::{EthercatDevice, RxPdo};
/// WAGO_730_1506 8-channel digital output device
///
/// 24V DC, 0.5A per channel
#[derive(EthercatDevice)]
pub struct WAGO_730_1506 {
pub rxpdo: WAGO_730_1506_RxPdo,
is_used: bool,
}
impl EthercatDeviceProcessing for WAGO_730_1506 {}
impl std::fmt::Debug for WAGO_730_1506 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "WAGO_730_1506")
}
}
impl NewEthercatDevice for WAGO_730_1506 {
fn new() -> Self {
Self {
rxpdo: WAGO_730_1506_RxPdo::default(),
is_used: false,
}
}
}
impl DigitalOutputDevice<WAGO_730_1506_Port> for WAGO_730_1506 {
fn set_output(&mut self, port: WAGO_730_1506_Port, value: DigitalOutputOutput) {
let expect_text = "All channels should be Some(_)";
match port {
WAGO_730_1506_Port::DO1 => {
self.rxpdo.channel1.as_mut().expect(expect_text).value = value.into()
}
WAGO_730_1506_Port::DO2 => {
self.rxpdo.channel2.as_mut().expect(expect_text).value = value.into()
}
WAGO_730_1506_Port::DO3 => {
self.rxpdo.channel3.as_mut().expect(expect_text).value = value.into()
}
WAGO_730_1506_Port::DO4 => {
self.rxpdo.channel4.as_mut().expect(expect_text).value = value.into()
}
WAGO_730_1506_Port::DO5 => {
self.rxpdo.channel5.as_mut().expect(expect_text).value = value.into()
}
WAGO_730_1506_Port::DO6 => {
self.rxpdo.channel6.as_mut().expect(expect_text).value = value.into()
}
WAGO_730_1506_Port::DO7 => {
self.rxpdo.channel7.as_mut().expect(expect_text).value = value.into()
}
WAGO_730_1506_Port::DO8 => {
self.rxpdo.channel8.as_mut().expect(expect_text).value = value.into()
}
}
}
fn get_output(&self, port: WAGO_730_1506_Port) -> DigitalOutputOutput {
let expect_text = "All channels should be Some(_)";
DigitalOutputOutput(match port {
WAGO_730_1506_Port::DO1 => self.rxpdo.channel1.as_ref().expect(expect_text).value,
WAGO_730_1506_Port::DO2 => self.rxpdo.channel2.as_ref().expect(expect_text).value,
WAGO_730_1506_Port::DO3 => self.rxpdo.channel3.as_ref().expect(expect_text).value,
WAGO_730_1506_Port::DO4 => self.rxpdo.channel4.as_ref().expect(expect_text).value,
WAGO_730_1506_Port::DO5 => self.rxpdo.channel5.as_ref().expect(expect_text).value,
WAGO_730_1506_Port::DO6 => self.rxpdo.channel6.as_ref().expect(expect_text).value,
WAGO_730_1506_Port::DO7 => self.rxpdo.channel7.as_ref().expect(expect_text).value,
WAGO_730_1506_Port::DO8 => self.rxpdo.channel8.as_ref().expect(expect_text).value,
})
}
}
#[derive(Debug, Clone)]
pub enum WAGO_730_1506_Port {
DO1,
DO2,
DO3,
DO4,
DO5,
DO6,
DO7,
DO8,
}
#[derive(Debug, Clone, RxPdo)]
pub struct WAGO_730_1506_RxPdo {
#[pdo_object_index(0x1600)]
pub channel1: Option<BoolPdoObject>,
#[pdo_object_index(0x1601)]
pub channel2: Option<BoolPdoObject>,
#[pdo_object_index(0x1602)]
pub channel3: Option<BoolPdoObject>,
#[pdo_object_index(0x1603)]
pub channel4: Option<BoolPdoObject>,
#[pdo_object_index(0x1604)]
pub channel5: Option<BoolPdoObject>,
#[pdo_object_index(0x1605)]
pub channel6: Option<BoolPdoObject>,
#[pdo_object_index(0x1606)]
pub channel7: Option<BoolPdoObject>,
#[pdo_object_index(0x1607)]
pub channel8: Option<BoolPdoObject>,
}
impl Default for WAGO_730_1506_RxPdo {
fn default() -> Self {
Self {
channel1: Some(BoolPdoObject::default()),
channel2: Some(BoolPdoObject::default()),
channel3: Some(BoolPdoObject::default()),
channel4: Some(BoolPdoObject::default()),
channel5: Some(BoolPdoObject::default()),
channel6: Some(BoolPdoObject::default()),
channel7: Some(BoolPdoObject::default()),
channel8: Some(BoolPdoObject::default()),
}
}
}
pub const WAGO_730_1506_VENDOR_ID: u32 = 0x21;
pub const WAGO_730_1506_PRODUCT_ID: u32 = 0x7500354;
pub const WAGO_730_1506_REVISION: u32 = 0x2;
pub const WAGO_730_1506_IDENTITY: SubDeviceIdentityTuple = (
WAGO_730_1506_VENDOR_ID,
WAGO_730_1506_PRODUCT_ID,
WAGO_730_1506_REVISION,
);
-30
View File
@@ -1,30 +0,0 @@
use super::{EthercatDeviceProcessing, NewEthercatDevice, SubDeviceIdentityTuple};
use ethercat_hal_derive::EthercatDevice;
/// WAGO_750_354 bus coupler
#[derive(Clone, EthercatDevice)]
pub struct WAGO_750_354 {
is_used: bool,
}
impl EthercatDeviceProcessing for WAGO_750_354 {}
impl NewEthercatDevice for WAGO_750_354 {
fn new() -> Self {
Self { is_used: false }
}
}
impl std::fmt::Debug for WAGO_750_354 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "WAGO_750_354")
}
}
pub const WAGO_750_354_VENDOR_ID: u32 = 0x21;
pub const WAGO_750_354_PRODUCT_ID: u32 = 0x7500354;
pub const WAGO_750_354_REVISION: u32 = 0x2;
pub const WAGO_750_354_IDENTITY: SubDeviceIdentityTuple = (
WAGO_750_354_VENDOR_ID,
WAGO_750_354_PRODUCT_ID,
WAGO_750_354_REVISION,
);
+1 -7
View File
@@ -1,7 +1,4 @@
use ethercrab::{
SubDevice, SubDeviceGroup, SubDevicePdi, SubDeviceRef,
subdevice_group::{Op, SafeOp},
};
use ethercrab::{SubDevice, SubDeviceGroup, SubDevicePdi, SubDeviceRef, subdevice_group::Op};
pub type EthercrabSubDevicePreoperational<'maindevice> =
SubDeviceRef<'maindevice, &'maindevice SubDevice>;
pub type EthercrabSubDeviceOperational<'maindevice, const MAX_PDI: usize> =
@@ -10,8 +7,5 @@ pub type EthercrabSubDeviceOperational<'maindevice, const MAX_PDI: usize> =
pub type EthercrabSubDeviceGroupOperational<const MAX_SUBDEVICES: usize, const MAX_PDI: usize> =
SubDeviceGroup<MAX_SUBDEVICES, MAX_PDI, Op>;
pub type EthercrabSubDeviceGroupSafeOperational<const MAX_SUBDEVICES: usize, const MAX_PDI: usize> =
SubDeviceGroup<MAX_SUBDEVICES, MAX_PDI, SafeOp>;
pub type EthercrabSubDeviceGroupPreoperational<const MAX_SUBDEVICES: usize, const MAX_PDI: usize> =
SubDeviceGroup<MAX_SUBDEVICES, MAX_PDI>;
+1 -4
View File
@@ -15,15 +15,12 @@ in
consoleMode = "max"; # Use the highest available resolution
};
boot.loader.efi.canTouchEfiVariables = true;
boot.kernelPackages = pkgs.linuxPackages_6_13;
boot.kernelPackages = pkgs.linuxPackages-rt_latest;
boot.kernelModules = [ "i915" ];
boot.kernelParams = [
# Realtime Preemption
"preempt=full"
# Graphical
"logo.nologo" # Remove kernel logo during boot
+4
View File
@@ -55,6 +55,10 @@ opentelemetry-otlp = { version = "0.30.0", features = [
], optional = true }
tonic = { version = "0.13.1", optional = true }
#[target.'cfg(not(target_env = "msvc"))'.dependencies]
#tikv-jemallocator = { version = "0.6", features = ["profiling", "stats"] }
#tikv-jemalloc-ctl = "0.6"
[dev-dependencies]
approx = "0.5.1"
textplots = "0.8.7"
+3 -2
View File
@@ -6,6 +6,7 @@ use crate::socketio::namespaces::Namespaces;
use control_core::machines::Machine;
use control_core::machines::identification::{DeviceIdentification, MachineIdentificationUnique};
use control_core::machines::manager::MachineManager;
use control_core::serial::serial_detection::SerialDetection;
use control_core::socketio::event::GenericEvent;
use ethercat_hal::devices::EthercatDevice;
use ethercrab::{MainDevice, SubDeviceGroup, subdevice_group::Op};
@@ -24,7 +25,7 @@ pub struct SocketioSetup {
}
pub struct SerialSetup {
pub serial_registry: &'static SERIAL_DEVICE_REGISTRY,
pub serial_detection: SerialDetection<'static>,
}
pub struct AppState {
@@ -84,7 +85,7 @@ impl AppState {
},
ethercat_setup: Arc::new(RwLock::new(None)),
serial_setup: Arc::new(RwLock::new(SerialSetup {
serial_registry: &SERIAL_DEVICE_REGISTRY,
serial_detection: SerialDetection::new(&SERIAL_DEVICE_REGISTRY),
})),
machines: Arc::new(RwLock::new(MachineManager::new())),
performance_metrics: Arc::new(RwLock::new(EthercatPerformanceMetrics::new())),
+4 -2
View File
@@ -3,6 +3,8 @@ use ethercrab::PduStorage;
/// Maximum number of SubDevices that can be stored. This must be a power of 2 greater than 1.
pub const MAX_SUBDEVICES: usize = 16;
/// Maximum PDU data payload size - set this to the max PDI size or higher.
pub const PDI_LEN: usize = 32;
pub const MAX_PDU_DATA: usize = PduStorage::element_size(PDI_LEN * 16);
pub const MAX_PDU_DATA: usize = PduStorage::element_size(256);
/// Maximum number of EtherCAT frames that can be in flight at any one time.
pub const MAX_FRAMES: usize = 16;
/// Maximum total PDI length.
pub const PDI_LEN: usize = 256;
@@ -1,38 +0,0 @@
use std::sync::Arc;
use control_core::socketio::namespace::NamespaceCacheingLogic;
use crate::{
app_state::AppState,
socketio::main_namespace::{
MainNamespaceEvents, ethercat_interface_discovery_event::EthercatInterfaceDiscoveryEvent,
},
};
pub async fn send_ethercat_discovering(app_state: Arc<AppState>) {
{
let main_namespace = &mut app_state
.socketio_setup
.namespaces
.write()
.await
.main_namespace;
let event = EthercatInterfaceDiscoveryEvent::Discovering(true).build();
main_namespace.emit(MainNamespaceEvents::EthercatInterfaceDiscoveryEvent(event));
}
}
pub async fn send_ethercat_found(app_state: Arc<AppState>, interface: &str) {
// Notify client via socketio
let interface = interface.to_string();
let app_state_socketio = app_state.clone();
smol::block_on(async move {
let main_namespace = &mut app_state_socketio
.socketio_setup
.namespaces
.write()
.await
.main_namespace;
let event = EthercatInterfaceDiscoveryEvent::Done(interface).build();
main_namespace.emit(MainNamespaceEvents::EthercatInterfaceDiscoveryEvent(event));
});
}
+67 -20
View File
@@ -1,23 +1,70 @@
use control_core::ethercat::interface_discovery::discover_ethercat_interface;
use smol::{Task, Timer};
use std::time::Duration;
use super::setup::setup_loop;
use crate::{
app_state::AppState,
socketio::main_namespace::{
MainNamespaceEvents, ethercat_interface_discovery_event::EthercatInterfaceDiscoveryEvent,
},
};
use control_core::{
ethercat::interface_discovery::discover_ethercat_interface,
socketio::namespace::NamespaceCacheingLogic,
};
use std::sync::Arc;
pub async fn find_ethercat_interface() -> Result<String, anyhow::Error> {
loop {
match discover_ethercat_interface().await {
Ok(interface) => {
tracing::info!("Found EtherCAT Interface at: {}", interface);
return Ok(interface);
}
Err(e) => {
tracing::warn!("No working interface found: {}. Retrying...", e);
Timer::after(Duration::from_secs(1)).await;
}
}
}
}
pub fn init_ethercat(app_state: Arc<AppState>) -> Result<(), anyhow::Error> {
let app_state_clone = app_state;
// Returns a Future to the interface
pub fn start_interface_discovery() -> Task<Result<String, anyhow::Error>> {
smol::spawn(find_ethercat_interface())
std::thread::Builder::new()
.name("init_ethercat".to_string())
.spawn(move || {
// Notify client via socketio
let app_state_socketio = app_state_clone.clone();
smol::block_on(async move {
let main_namespace = &mut app_state_socketio
.socketio_setup
.namespaces
.write()
.await
.main_namespace;
let event = EthercatInterfaceDiscoveryEvent::Discovering(true).build();
main_namespace.emit(MainNamespaceEvents::EthercatInterfaceDiscoveryEvent(event));
});
// tries to find a suitable interface in a loop
let interface = smol::block_on(async {
loop {
match discover_ethercat_interface().await {
Ok(interface) => {
tracing::info!("Found working interface: {}", interface);
break interface;
}
Err(_) => {
tracing::warn!("No working interface found, retrying...");
// wait 1 seconds before retrying
smol::Timer::after(std::time::Duration::from_secs(1)).await;
}
}
}
});
// Notify client via socketio
let interface_clone = interface.clone();
let app_state_socketio = app_state_clone.clone();
smol::block_on(async move {
let main_namespace = &mut app_state_socketio
.socketio_setup
.namespaces
.write()
.await
.main_namespace;
let event = EthercatInterfaceDiscoveryEvent::Done(interface_clone).build();
main_namespace.emit(MainNamespaceEvents::EthercatInterfaceDiscoveryEvent(event));
});
if let Err(e) = smol::block_on(setup_loop(&interface, app_state_clone)) {
tracing::error!("EtherCAT setup failed: {:?}", e);
}
})?;
Ok(())
}
-1
View File
@@ -1,4 +1,3 @@
pub mod config;
pub mod ethercat_discovery_info;
pub mod init;
pub mod setup;
+168 -231
View File
@@ -17,298 +17,235 @@ use control_core::machines::new::MachineNewHardwareEthercat;
use control_core::realtime::{set_core_affinity, set_realtime_priority};
use control_core::socketio::namespace::NamespaceCacheingLogic;
use ethercat_hal::devices::devices_from_subdevices;
use ethercrab::std::ethercat_now;
use ethercrab::{MainDevice, MainDeviceConfig, PduStorage, RetryBehaviour, Timeouts};
use ethercrab::std::{ethercat_now, tx_rx_task};
use ethercrab::{
MainDevice, MainDeviceConfig, PduLoop, PduRx, PduStorage, PduTx, RetryBehaviour, Timeouts,
};
use std::{sync::Arc, time::Duration};
const SM_OUTPUT: u16 = 0x1C32;
const SM_INPUT: u16 = 0x1C33;
pub async fn setup_loop(interface: &str, app_state: Arc<AppState>) -> Result<(), anyhow::Error> {
tracing::info!("Starting Ethercat PDU loop");
pub struct EtherCatBackend<'maindevice> {
pub tx: PduTx<'maindevice>,
pub rx: PduRx<'maindevice>,
pub interface: String,
}
// Erase all all setup data from `app_state`
{
tracing::debug!("Setting up Ethercat network");
let mut ethercat_setup_guard = app_state.ethercat_setup.write().await;
*ethercat_setup_guard = None;
}
/*
pub async hack_el5125(){
for subdevice in subdevices.iter() {
if subdevice.name() == "EL5152" {
subdevice.sdo_write(SM_OUTPUT, 0x1, 0x00u16).await; //set sync mode (1) for free run (0)
subdevice.sdo_write(SM_INPUT, 0x1, 0x00u16).await; //set sync mode (1) for free run (0)
}
}
}
*/
pub async fn setup_loop(
interface: &str,
app_state: Arc<AppState>,
) -> Result<EtherCatBackend<'_>, anyhow::Error> {
tracing::info!("Starting EtherCAT PDU loop");
// Setup ethercrab tx/rx task
// Set real-time priority and CPU affinity
set_realtime_priority();
#[cfg(all(target_os = "linux", not(feature = "development-build")))]
set_irq_affinity(interface, 3)
.map(|_| tracing::info!("Ethernet IRQ on CPU 3"))
.map_err(|e| tracing::error!("Failed IRQ affinity: {:?}", e))
.ok();
*app_state.ethercat_setup.write().await = None;
// Setup PDU storage
let pdu_storage = Box::leak(Box::new(PduStorage::<MAX_FRAMES, MAX_PDU_DATA>::new()));
let (tx, rx, pdu) = pdu_storage.try_split().expect("can only split once");
let interface = interface.to_string();
std::thread::Builder::new()
let interface: String = interface.to_string();
let cloned_interface = interface.clone();
let ethercat_thread = std::thread::Builder::new()
.name("EthercatTxRxThread".to_owned())
.spawn(move || {
#[cfg(all(target_os = "linux", not(feature = "development-build")))]
match set_irq_affinity(&interface, 3) {
match set_irq_affinity(&cloned_interface, 3) {
Ok(_) => tracing::info!("ethernet interrupt handler now runs on cpu:{}", 3),
Err(e) => tracing::error!("set_irq_handler_affinity failed: {:?}", e),
}
// Set core affinity to 4th core
let _ = set_core_affinity(3);
// Set the thread to real-time priority
#[cfg(not(feature = "development-build"))]
let _ = set_realtime_priority();
// #[cfg(not(all(target_os = "linux", feature = "io-uring")))]
#[cfg(not(all(target_os = "linux", feature = "io-uring")))]
{
use ethercrab::std::tx_rx_task;
use futures::executor::block_on;
let rt = smol::LocalExecutor::new();
let _ = block_on(rt.run(async {
tx_rx_task(&interface, tx, rx)
block_on(rt.run(async {
tx_rx_task(&cloned_interface, tx, rx)
.expect("spawn TX/RX task")
.await
}));
}))
}
/* #[cfg(all(target_os = "linux", feature = "io-uring"))]
#[cfg(all(target_os = "linux", feature = "io-uring"))]
{
use ethercrab::std::tx_rx_task_io_uring;
let _ = tx_rx_task_io_uring(&interface, tx, rx)
.expect("Failed to spawn TX/RX task (io_uring)");
}*/
tx_rx_task_io_uring(&cloned_interface, tx, rx)
.expect("Failed to spawn TX/RX task (io_uring)")
}
})
.expect("Building thread");
std::thread::sleep(Duration::from_millis(500)); // let TX/RX thread breathe
// Create maindevice
let maindevice = MainDevice::new(
pdu,
Timeouts {
// Default 5000ms
state_transition: Duration::from_millis(5000),
// Default 30_000us
pdu: Duration::from_micros(30_000),
// Default 10ms
eeprom: Duration::from_millis(10),
// Default 0ms
wait_loop_delay: Duration::from_millis(0),
// Default 100ms
mailbox_echo: Duration::from_millis(1000),
// Default 1000ms
mailbox_response: Duration::from_millis(2000),
mailbox_echo: Duration::from_millis(100),
mailbox_response: Duration::from_millis(1000),
},
MainDeviceConfig {
// Default 10000
dc_static_sync_iterations: 0,
// Default None
retry_behaviour: ethercrab::RetryBehaviour::Count(3),
retry_behaviour: RetryBehaviour::Count(5),
dc_static_sync_iterations: 10_000,
},
);
smol::block_on({
let app_state_clone = app_state.clone();
async move {
let main_namespace = &mut app_state_clone
.socketio_setup
.namespaces
.write()
.await
.main_namespace;
let event = EthercatDevicesEventBuilder().initializing();
main_namespace.emit(MainNamespaceEvents::EthercatDevicesEvent(event));
}
});
// Emit "initializing" event
{
let mut main_namespace = &mut app_state
.socketio_setup
.namespaces
.write()
.await
.main_namespace;
let event = EthercatDevicesEventBuilder().initializing();
main_namespace.emit(MainNamespaceEvents::EthercatDevicesEvent(event));
}
// Initalize subdevices
// Fails if DC setup detects a mispatching working copunter, then just try again in loop
let mut group_preop = match maindevice
// Initialize subdevices
let mut group_preop = maindevice
.init_single_group::<MAX_SUBDEVICES, PDI_LEN>(ethercat_now)
.await
{
Ok(group) => {
tracing::info!("Initialized {} subdevices", &group.len());
group
}
Err(err) => Err(anyhow::anyhow!(
"[{}::setup_loop] Failed to initialize subdevices: {:?}",
module_path!(),
err
))?,
};
.map_err(|e| anyhow::anyhow!("Failed to initialize subdevices: {:?}", e))?;
/* let subdevices = group_preop.iter(&maindevice).collect::<Vec<_>>();
// Create devices
let devices =
devices_from_subdevices::<MAX_SUBDEVICES, PDI_LEN>(&mut group_preop, &maindevice)?;
let subdevices = group_preop.iter(&maindevice).collect::<Vec<_>>();
let master = subdevices.get(0).unwrap();
let rxpdo_count: u8 = master.sdo_read(0x1C12, 0x00).await?;
let txpdo_count: u8 = master.sdo_read(0x1C13, 0x00).await?;
tracing::info!("RxPDO count {}, TxPDO count {}", rxpdo_count, txpdo_count);*/
// master.sdo_write(0x1C12, 0x00, 0u16).await?;
// master.sdo_write(0x1C13, 0x00, 0u16).await?;
// Map 0x1AFF "Device Status PDO" as first TxPDO
// master.sdo_write(0x1C13, 0x01, 0x1AFF).await?;
// Map 0x1A00 "TxPDO Mapping Terminal 1" as second TxPDO
//master.sdo_write(0x1C13, 0x02, 0x1A00).await?;
// Set number of TxPDO entries
//master.sdo_write(0x1C13, 0x00, 2u16).await?;
// SM2 = Outputs (MasterWrite)
//master.sdo_write(SM_OUTPUT, 0x01, 0x00u16).await?;
// SM3 = Inputs (MasterRead)
//master.sdo_write(SM_INPUT, 0x01, 0x00u16).await?;
let mut group_safe = match group_preop.into_safe_op(&maindevice).await {
Ok(group) => group,
Err(_) => return Ok(()),
};
// create devices
let devices = devices_from_subdevices::<MAX_SUBDEVICES, PDI_LEN>(&mut group_safe, &maindevice)?;
let subdevices = group_safe.iter(&maindevice).collect::<Vec<_>>();
/*
// extract device identifications
let device_identifications = read_device_identifications(&subdevices, &maindevice)
.await
.into_iter()
.enumerate()
.map(|(i, result)| (i, result.ok()))
.map(
|(subdevice_index, device_machine_identification)| DeviceIdentification {
device_machine_identification,
device_hardware_identification: DeviceHardwareIdentification::Ethercat(
DeviceHardwareIdentificationEthercat { subdevice_index },
),
},
)
.collect::<Vec<_>>();
let devices = device_identifications
.into_iter()
.zip(devices)
.zip(&subdevices)
.map(|((a, b), c)| (a, b, c))
.collect::<Vec<_>>();
// filter devices and if Option<DeviceMachineIdentification> is Some
// return identified_devices, identified_device_identifications, identified_subdevices
let (identified_device_identifications, identified_devices, identified_subdevices): (
Vec<_>,
Vec<_>,
Vec<_>,
) = devices
.iter()
.filter(|(device_identification, _, _)| {
match device_identification {
DeviceIdentification {
device_machine_identification: Some(_),
..
} => true,
_ => false
}
})
.map(|(device_identification, device, subdevice)| {
(
device_identification.clone(),
device.clone(),
*subdevice,
)
})
.fold(
(Vec::new(), Vec::new(), Vec::new()),
|mut acc, (identified_device_identification, identified_device, identified_subdevice)| {
acc.0.push(identified_device_identification);
acc.1.push(identified_device);
acc.2.push(identified_subdevice);
acc
},
);
// construct machines
{
let mut machines_guard = app_state.machines.write().await;
machines_guard.set_ethercat_devices::<MAX_SUBDEVICES, PDI_LEN>(
&identified_device_identifications,
&MACHINE_REGISTRY,
&MachineNewHardwareEthercat {
ethercat_devices: &identified_devices,
subdevices: &identified_subdevices,
},
app_state.socketio_setup.socket_queue_tx.clone(),
Arc::downgrade(&app_state.machines),
);
}
// remove subdevice from devices tuple
let devices = devices
.iter()
.map(|(device_identification, device, _)| (device_identification.clone(), device.clone()))
// Extract device identifications
let device_identifications = read_device_identifications(&subdevices, &maindevice)
.await
.into_iter()
.enumerate()
.map(|(i, result)| (i, result.ok()))
.map(
|(subdevice_index, device_machine_identification)| DeviceIdentification {
device_machine_identification,
device_hardware_identification: DeviceHardwareIdentification::Ethercat(
DeviceHardwareIdentificationEthercat { subdevice_index },
),
},
)
.collect::<Vec<_>>();
*/
for subdevice in subdevices.iter() {
println!("Erro reg: {:?}", subdevice.sdo_read::<u8>(0x1001, 0).await?);
// let al_status: u16 = subdevice.sdo_read(0x0134, 0x00).await?;
// println!("AL status: 0x{:04x}", al_status);
// println!("{:?}", subdevice.name());
/* if subdevice.name() == "EL5152" {
subdevice.sdo_write(SM_OUTPUT, 0x1, 0x00u16).await?; //set sync mode (1) for free run (0)
subdevice.sdo_write(SM_INPUT, 0x1, 0x00u16).await?; //set sync mode (1) for free run (0)
let devices_tuple = device_identifications
.into_iter()
.zip(devices)
.zip(&subdevices)
.map(|((a, b), c)| (a, b, c))
.collect::<Vec<_>>();
}*/
/*if subdevice.name().starts_with("750") {
// pseudo-code, depends on your crate API
subdevice.sdo_write(0x1C32, 0x1, 0x00u16).await?; // set SM2 mode
subdevice.sdo_write(0x1C33, 0x1, 0x00u16).await?; // set SM3 mode
}*/
}
// Notify client via socketio
let app_state_clone = app_state.clone();
smol::block_on(async move {
let main_namespace = &mut app_state_clone
.socketio_setup
.namespaces
.write()
.await
.main_namespace;
let event = MachinesEventBuilder().build(app_state_clone.clone());
main_namespace.emit(MainNamespaceEvents::MachinesEvent(event));
});
let group_op = group_safe.into_op(&maindevice).await?;
/*
// Put group in operational state
let group_op = match group_safe.into_op(&maindevice).await {
Ok(group_op) => {
tracing::info!("Group in OP state");
group_op
}
Err(err) => Err(anyhow::anyhow!(
"[{}::setup_loop] Failed to put group in OP state: {:?}",
module_path!(),
err
))?,
};
*/
// Write all this stuff to `app_state`
/*{
let mut ethercat_setup_guard = app_state.ethercat_setup.write().await;
*ethercat_setup_guard = Some(EthercatSetup {
devices,
group: group_op,
maindevice,
let (identified_device_identifications, identified_devices, identified_subdevices): (
Vec<_>,
Vec<_>,
Vec<_>,
) = devices_tuple
.iter()
.filter(|(id, _, _)| id.device_machine_identification.is_some())
.map(|(id, dev, sub)| (id.clone(), dev.clone(), *sub))
.fold((Vec::new(), Vec::new(), Vec::new()), |mut acc, x| {
acc.0.push(x.0);
acc.1.push(x.1);
acc.2.push(x.2);
acc
});
}*/
// Notify client via socketio
let app_state_clone = app_state.clone();
smol::block_on(async move {
let main_namespace = &mut app_state_clone
// Construct machines
{
let mut machines_guard = app_state.machines.write().await;
machines_guard.set_ethercat_devices::<MAX_SUBDEVICES, PDI_LEN>(
&identified_device_identifications,
&MACHINE_REGISTRY,
&MachineNewHardwareEthercat {
ethercat_devices: &identified_devices,
subdevices: &identified_subdevices,
},
app_state.socketio_setup.socket_queue_tx.clone(),
Arc::downgrade(&app_state.machines),
);
}
// Remove subdevice from devices tuple for app_state
let devices_clean = devices_tuple
.iter()
.map(|(id, dev, _)| (id.clone(), dev.clone()))
.collect::<Vec<_>>();
// Emit Machines event
{
let mut main_namespace = &mut app_state
.socketio_setup
.namespaces
.write()
.await
.main_namespace;
let event = EthercatDevicesEventBuilder()
.build(app_state_clone.clone())
.await;
main_namespace.emit(MainNamespaceEvents::EthercatDevicesEvent(event));
let event = MachinesEventBuilder().build(app_state.clone());
main_namespace.emit(MainNamespaceEvents::MachinesEvent(event));
}
// Put group in operational state
let group_op = group_preop
.into_op(&maindevice)
.await
.map_err(|e| anyhow::anyhow!("Failed to put group in OP state: {:?}", e))?;
// Save final setup into app_state
*app_state.ethercat_setup.write().await = Some(EthercatSetup {
devices: devices_clean,
group: group_op,
maindevice,
});
Ok(())
// Emit final EthercatDevicesEvent
{
let mut main_namespace = &mut app_state
.socketio_setup
.namespaces
.write()
.await
.main_namespace;
let event = EthercatDevicesEventBuilder().build(app_state.clone()).await;
main_namespace.emit(MainNamespaceEvents::EthercatDevicesEvent(event));
}
let res: Result<(PduTx<'_>, PduRx<'_>), ethercrab::error::Error> =
ethercat_thread.join().expect("Thread panicked");
let tx_rx_tuple = match res {
Ok(tuple) => tuple,
Err(e) => return Err(anyhow::anyhow!("HELP")),
};
let ethercat_backend = EtherCatBackend {
tx: tx_rx_tuple.0,
rx: tx_rx_tuple.1,
interface,
};
Ok(ethercat_backend)
}
+62 -73
View File
@@ -1,113 +1,96 @@
use crate::{app_state::AppState, ethercat::setup::setup_loop};
use crate::app_state::AppState;
use crate::ethercat::setup::{EtherCatBackend, setup_loop};
use bitvec::prelude::*;
use control_core::machines::connection::MachineConnection;
use control_core::realtime::set_core_affinity;
#[cfg(not(feature = "development-build"))]
use control_core::realtime::set_realtime_priority;
use control_core::realtime::{set_core_affinity, set_realtime_priority};
use std::sync::Arc;
use std::time::Instant;
use std::time::Duration;
use tracing::{instrument, trace_span};
pub fn start_loop_thread(
interface: &str,
app_state: Arc<AppState>,
) -> Result<std::thread::JoinHandle<()>, std::io::Error> {
let res = smol::block_on(async { setup_loop(interface, app_state.clone()).await });
match res {
Ok(_) => tracing::info!("Successfully initialized EtherCAT network"),
Err(e) => {
tracing::error!(
"[{}::init_loop] Failed to initialize EtherCAT network \n{:?}",
module_path!(),
e
);
}
}
pub fn init_loop(app_state: Arc<AppState>) -> Result<(), anyhow::Error> {
// Start control loop
let res = std::thread::Builder::new()
std::thread::Builder::new()
.name("loop".to_owned())
.spawn(move || {
let _ = set_core_affinity(2);
#[cfg(not(feature = "development-build"))]
// Before we do anything else setup the Ethercat Network
let res: Result<EtherCatBackend, anyhow::Error> =
smol::block_on(async { setup_loop("eno1", app_state.clone()).await });
let ethercat_backend: EtherCatBackend = match res {
Ok(ethercat_backend) => ethercat_backend,
Err(e) => return e,
};
let mut tx = ethercat_backend.tx;
let mut rx = ethercat_backend.rx;
let rt = smol::LocalExecutor::new();
// Set core affinity to fourth core
let _ = set_core_affinity(3);
if let Err(e) = set_realtime_priority() {
tracing::error!(
"[{}::init_loop] Failed to set thread to real-time priority \n{:?}",
"[{}::init_loop] Failed to set real-time priority \n{:?}",
module_path!(),
e
);
} else {
tracing::info!(
"[{}::init_loop] Real-time priority set successfully for current thread",
"[{}::init_loop] Real-time priority set successfully",
module_path!()
);
}
let rt = smol::LocalExecutor::new();
// Instead of creating a NEW async task every iteration of our realtime txrx loop, create it ONCE
smol::block_on(async {
rt.run(async {
loop {
if let Err(e) = loop_once(app_state.clone()).await {
tracing::error!("Loop failed\n{:?}", e);
std::process::exit(1);
}
}
})
.await;
});
let result = ethercrab::std::io_uring_one_cycle::setup_tx_rx_task("eno1");
/*
// If timeouts keep happenning do a spin_sleep, better then thread_sleep and allows for more deterministic timing
let elapsed = start.elapsed();
if elapsed < target_cycle {
spin_sleep::sleep(target_cycle - elapsed);
let mut tx_rx_conf = match result {
Ok(tx_rx_conf) => tx_rx_conf,
Err(_) => todo!(),
};
loop {
let tuple = match ethercrab::std::io_uring_one_cycle::tx_rx_task_io_uring_cycle(
&mut tx_rx_conf,
tx,
rx,
) {
Ok((tx, rx)) => (tx, rx),
Err(_) => return anyhow::anyhow!("tx_rx_task_io_uring failed"),
};
tx = tuple.0;
rx = tuple.1;
let res = smol::block_on(rt.run(async { loop_once(app_state.clone()).await }));
if let Err(err) = res {
tracing::error!("Loop failed\n{:?}", err);
break;
}
*/
if let Some(last_loop_start) = app_state
.performance_metrics
.read_arc_blocking()
.last_loop_start
{
tracing::info!("Failing Loop Took {:?}", last_loop_start.elapsed());
}
// Exit the entire program if the Loop fails
// gets restarted by systemd if running on NixOS, or different distro wtih the same sysd service
// Exit the entire program if the Loop fails (gets restarted by systemd if running on NixOS)
std::process::exit(1);
});
return res;
})
.map_err(|e| {
anyhow::anyhow!(
"[{}::init_loop] Failed to spawn loop thread\n{:?}",
module_path!(),
e
)
})?;
Ok(())
}
#[instrument(skip(app_state))]
pub async fn loop_once<'maindevice>(app_state: Arc<AppState>) -> Result<(), anyhow::Error> {
// Record cycle start for performance metrics
{
let mut metrics = app_state.performance_metrics.write().await;
metrics.cycle_start();
}
let ethercat_setup_guard = app_state.ethercat_setup.read().await;
// only if we have an ethercat setup
// - tx/rx cycle
// - copy inputs to devices
if let Some(ethercat_setup) = ethercat_setup_guard.as_ref() {
let span = trace_span!("loop_once_inputs");
let _enter = span.enter();
// Measure tx_rx performance
let txrx_start = Instant::now();
ethercat_setup
.group
.tx_rx(&ethercat_setup.maindevice)
.await?;
let txrx_duration = txrx_start.elapsed();
// Record tx_rx performance metrics
{
let mut metrics = app_state.performance_metrics.write().await;
metrics.record_txrx_time(txrx_duration);
}
// copy inputs to devices
for (i, subdevice) in ethercat_setup
@@ -148,6 +131,12 @@ pub async fn loop_once<'maindevice>(app_state: Arc<AppState>) -> Result<(), anyh
)
})?;
}
#[cfg(feature = "development-build")]
smol::Timer::after(Duration::from_micros(2000)).await;
#[cfg(not(feature = "development-build"))]
smol::Timer::after(Duration::from_micros(500)).await;
}
// execute machines
+2 -2
View File
@@ -3,8 +3,6 @@ pub mod api;
pub mod buffer_tower_controller;
pub mod new;
#[cfg(not(feature = "mock-machine"))]
use crate::machines::{MACHINE_BUFFER_V1, VENDOR_QITECH, winder2::Winder2};
use api::{Buffer1Namespace, BufferV1Events, LiveValuesEvent, ModeState, StateEvent};
use buffer_tower_controller::BufferTowerController;
use control_core::machines::connection::{CrossConnectableMachine, MachineCrossConnection};
@@ -20,6 +18,8 @@ use serde::{Deserialize, Serialize};
use smol::lock::RwLock;
use std::{sync::Weak, time::Instant};
use crate::machines::{MACHINE_BUFFER_V1, VENDOR_QITECH, winder2::Winder2};
#[derive(Debug, Machine)]
pub struct BufferV1 {
// controllers
+1 -21
View File
@@ -183,24 +183,9 @@ pub struct PidSettings {
pub kd: f64,
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
pub struct TemperaturePidStates {
pub front: TemperaturePid,
pub middle: TemperaturePid,
pub back: TemperaturePid,
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
pub struct TemperaturePid {
pub ki: f64,
pub kp: f64,
pub kd: f64,
pub zone: String,
}
#[derive(Serialize, Debug, Clone, PartialEq)]
pub struct PidSettingsStates {
pub temperature: TemperaturePidStates,
pub temperature: PidSettings,
pub pressure: PidSettings,
}
@@ -232,7 +217,6 @@ pub enum Mutation {
// Pid Configure
SetPressurePidSettings(PidSettings),
SetTemperaturePidSettings(TemperaturePid),
// Reset
ResetInverter(bool),
@@ -308,10 +292,6 @@ impl MachineApi for ExtruderV2 {
Mutation::SetPressurePidSettings(settings) => {
self.configure_pressure_pid(settings);
}
Mutation::SetTemperaturePidSettings(settings) => {
self.configure_temperature_pid(settings);
}
}
Ok(())
}
+5 -50
View File
@@ -5,7 +5,7 @@ use crate::machines::extruder1::{
api::{
ExtruderSettingsState, ExtruderV2Events, HeatingState, HeatingStates, InverterStatusState,
LiveValuesEvent, ModeState, PidSettings, PidSettingsStates, PressureState, RegulationState,
RotationState, ScrewState, StateEvent, TemperaturePid,
RotationState, ScrewState, StateEvent,
},
};
#[cfg(not(feature = "mock-machine"))]
@@ -27,8 +27,6 @@ use uom::si::thermodynamic_temperature::ThermodynamicTemperature;
#[cfg(not(feature = "mock-machine"))]
impl ExtruderV2 {
pub fn build_state_event(&mut self) -> StateEvent {
use crate::machines::extruder1::api::{TemperaturePid, TemperaturePidStates};
StateEvent {
is_default_state: !std::mem::replace(&mut self.emitted_default_state, true),
rotation_state: RotationState {
@@ -108,25 +106,10 @@ impl ExtruderV2 {
fault_occurence: self.screw_speed_controller.inverter.status.fault_occurence,
},
pid_settings: PidSettingsStates {
temperature: TemperaturePidStates {
front: TemperaturePid {
ki: self.temperature_controller_front.pid.get_ki(),
kp: self.temperature_controller_front.pid.get_kp(),
kd: self.temperature_controller_front.pid.get_kd(),
zone: String::from("front"),
},
middle: TemperaturePid {
ki: self.temperature_controller_middle.pid.get_ki(),
kp: self.temperature_controller_middle.pid.get_kp(),
kd: self.temperature_controller_middle.pid.get_kd(),
zone: String::from("middle"),
},
back: TemperaturePid {
ki: self.temperature_controller_back.pid.get_ki(),
kp: self.temperature_controller_back.pid.get_kp(),
kd: self.temperature_controller_back.pid.get_kd(),
zone: String::from("back"),
},
temperature: PidSettings {
ki: 0.0,
kp: 0.0,
kd: 0.0,
},
pressure: PidSettings {
ki: self.screw_speed_controller.pid.get_ki(),
@@ -296,32 +279,4 @@ impl ExtruderV2 {
.configure(settings.ki, settings.kp, settings.kd);
self.emit_state();
}
pub fn configure_temperature_pid(&mut self, settings: TemperaturePid) {
match settings.zone.as_str() {
"front" => {
self.temperature_controller_front.pid.configure(
settings.ki,
settings.kp,
settings.kd,
);
}
"middle" => {
self.temperature_controller_middle.pid.configure(
settings.ki,
settings.kp,
settings.kd,
);
}
"back" => {
self.temperature_controller_back.pid.configure(
settings.ki,
settings.kp,
settings.kd,
);
}
_ => tracing::warn!("Unknown zone: {}", settings.zone),
}
self.emit_state();
}
}
@@ -37,10 +37,6 @@ impl MachineApi for ExtruderV2 {
Mutation::SetPressurePidSettings(settings) => {
self.configure_pressure_pid(settings);
}
Mutation::SetTemperaturePidSettings(settings) => {
self.configure_temperature_pid(settings);
}
}
Ok(())
}
@@ -1,6 +1,6 @@
use crate::machines::extruder1::{
ExtruderV2Mode, HeatingType,
api::{ExtruderV2Events, LiveValuesEvent, ModeState, PidSettings, StateEvent, TemperaturePid},
api::{ExtruderV2Events, LiveValuesEvent, ModeState, PidSettings, StateEvent},
mock::ExtruderV2,
};
use control_core::{
@@ -133,26 +133,4 @@ impl ExtruderV2 {
self.pid_settings.pressure.kd = settings.kd;
self.emit_state();
}
pub fn configure_temperature_pid(&mut self, settings: TemperaturePid) {
match settings.zone.as_str() {
"front" => {
self.pid_settings.temperature.front.ki = settings.ki;
self.pid_settings.temperature.front.kp = settings.kp;
self.pid_settings.temperature.front.kd = settings.kd;
}
"middle" => {
self.pid_settings.temperature.middle.ki = settings.ki;
self.pid_settings.temperature.middle.kp = settings.kp;
self.pid_settings.temperature.middle.kd = settings.kd;
}
"back" => {
self.pid_settings.temperature.back.ki = settings.ki;
self.pid_settings.temperature.back.kp = settings.kp;
self.pid_settings.temperature.back.kd = settings.kd;
}
_ => tracing::warn!("Unknown zone: {}", settings.zone),
}
self.emit_state();
}
}
+5 -21
View File
@@ -3,8 +3,7 @@ use crate::machines::extruder1::{
api::{
ExtruderSettingsState, ExtruderV2Namespace, HeatingState, HeatingStates,
InverterStatusState, ModeState, MotorStatusValues, PidSettings, PidSettingsStates,
PressureState, RegulationState, RotationState, ScrewState, TemperaturePid,
TemperaturePidStates,
PressureState, RegulationState, RotationState, ScrewState,
},
mock::ExtruderV2,
};
@@ -89,25 +88,10 @@ impl control_core::machines::new::MachineNewTrait for ExtruderV2 {
fault_occurence: false,
},
pid_settings: PidSettingsStates {
temperature: TemperaturePidStates {
front: TemperaturePid {
ki: 0.0,
kp: 0.0,
kd: 0.0,
zone: String::from("front"),
},
middle: TemperaturePid {
ki: 0.0,
kp: 0.0,
kd: 0.0,
zone: String::from("middle"),
},
back: TemperaturePid {
ki: 0.0,
kp: 0.0,
kd: 0.0,
zone: String::from("back"),
},
temperature: PidSettings {
ki: 0.0,
kp: 0.0,
kd: 0.0,
},
pressure: PidSettings {
ki: 0.0,
+1 -6
View File
@@ -14,10 +14,7 @@ use ethercrab::{SubDevice, SubDeviceRef};
use smol::lock::RwLock;
pub mod aquapath1;
#[cfg(not(feature = "mock-machine"))]
pub mod buffer1;
pub mod extruder1;
pub mod laser;
pub mod mock;
@@ -29,10 +26,8 @@ pub const MACHINE_WINDER_V1: u16 = 0x0002;
pub const MACHINE_EXTRUDER_V1: u16 = 0x0004;
pub const MACHINE_LASER_V1: u16 = 0x0006;
pub const MACHINE_MOCK: u16 = 0x0007;
pub const MACHINE_AQUAPATH_V1: u16 = 0x0009;
#[cfg(not(feature = "mock-machine"))]
pub const MACHINE_BUFFER_V1: u16 = 0x0008;
pub const MACHINE_AQUAPATH_V1: u16 = 0x0009;
async fn get_device_ident<
'maindevice,
+6 -13
View File
@@ -1,12 +1,12 @@
#[cfg(feature = "mock-machine")]
use crate::machines::{extruder1::mock::ExtruderV2, mock::MockMachine, winder2::mock::Winder2};
use crate::machines::{extruder1::mock::ExtruderV2, mock::MockMachine};
#[cfg(not(feature = "mock-machine"))]
use crate::machines::{
aquapath1::AquaPathV1, buffer1::BufferV1, extruder1::ExtruderV2, laser::LaserMachine,
winder2::Winder2,
};
use crate::machines::extruder1::ExtruderV2;
use crate::machines::{
aquapath1::AquaPathV1, buffer1::BufferV1, laser::LaserMachine, winder2::Winder2,
};
use control_core::machines::registry::MachineRegistry;
use lazy_static::lazy_static;
@@ -14,18 +14,11 @@ lazy_static! {
pub static ref MACHINE_REGISTRY: MachineRegistry = {
let mut mc = MachineRegistry::new();
mc.register::<Winder2>(Winder2::MACHINE_IDENTIFICATION);
mc.register::<LaserMachine>(LaserMachine::MACHINE_IDENTIFICATION);
mc.register::<ExtruderV2>(ExtruderV2::MACHINE_IDENTIFICATION);
#[cfg(feature = "mock-machine")]
mc.register::<MockMachine>(MockMachine::MACHINE_IDENTIFICATION);
#[cfg(not(feature = "mock-machine"))]
mc.register::<LaserMachine>(LaserMachine::MACHINE_IDENTIFICATION);
#[cfg(not(feature = "mock-machine"))]
mc.register::<BufferV1>(BufferV1::MACHINE_IDENTIFICATION);
#[cfg(not(feature = "mock-machine"))]
mc.register::<AquaPathV1>(AquaPathV1::MACHINE_IDENTIFICATION);
mc
};
-4
View File
@@ -1,11 +1,7 @@
#[cfg(not(feature = "mock-machine"))]
use super::Winder2;
#[cfg(not(feature = "mock-machine"))]
use control_core::machines::new::MachineAct;
#[cfg(not(feature = "mock-machine"))]
use std::time::{Duration, Instant};
#[cfg(not(feature = "mock-machine"))]
impl MachineAct for Winder2 {
fn act(&mut self, now: Instant) {
// sync the spool speed
+32 -70
View File
@@ -1,63 +1,31 @@
#[cfg(feature = "mock-machine")]
mod winder2_imports {
pub use super::super::Winder2Mode;
pub use super::super::puller_speed_controller::{GearRatio, PullerRegulationMode};
pub use serde::Deserialize;
pub use serde::Serialize;
pub use std::{sync::Arc, time::Duration};
pub use control_core::{
machines::{
connection::MachineCrossConnectionState, identification::MachineIdentificationUnique,
use super::puller_speed_controller::GearRatio;
use super::{Winder2, Winder2Mode, puller_speed_controller::PullerRegulationMode};
use control_core::{
machines::{
api::MachineApi, connection::MachineCrossConnectionState,
identification::MachineIdentificationUnique,
},
socketio::{
event::{Event, GenericEvent},
namespace::{
CacheFn, CacheableEvents, Namespace, NamespaceCacheingLogic, cache_duration,
cache_first_and_last_event,
},
socketio::{
event::{Event, GenericEvent},
namespace::{
CacheFn, CacheableEvents, Namespace, NamespaceCacheingLogic, cache_duration,
cache_first_and_last_event,
},
},
};
pub use control_core_derive::BuildEvent;
pub use smol::lock::Mutex;
pub use tracing::instrument;
}
},
};
#[cfg(not(feature = "mock-machine"))]
mod winder2_imports {
pub use super::super::puller_speed_controller::{GearRatio, PullerRegulationMode};
pub use super::super::{Winder2, Winder2Mode};
pub use control_core::{
machines::{
api::MachineApi, connection::MachineCrossConnectionState,
identification::MachineIdentificationUnique,
},
socketio::{
event::{Event, GenericEvent},
namespace::{
CacheFn, CacheableEvents, Namespace, NamespaceCacheingLogic, cache_duration,
cache_first_and_last_event,
},
},
};
use control_core_derive::BuildEvent;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use smol::lock::Mutex;
use std::{
sync::Arc,
time::{Duration, Instant},
};
use tracing::instrument;
pub use control_core_derive::BuildEvent;
pub use serde::{Deserialize, Serialize};
pub use serde_json::Value;
pub use smol::lock::Mutex;
pub use std::{
sync::Arc,
time::{Duration, Instant},
};
pub use tracing::instrument;
}
pub use winder2_imports::*;
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum Mode {
#[default]
Standby,
Hold,
Pull,
@@ -87,7 +55,7 @@ impl From<Mode> for Winder2Mode {
}
#[derive(Deserialize, Serialize)]
pub enum Mutation {
enum Mutation {
// Traverse
/// Position in mm from home point
SetTraverseLimitOuter(f64),
@@ -115,7 +83,6 @@ pub enum Mutation {
SetSpoolRegulationMode(super::spool_speed_controller::SpoolSpeedControllerType),
SetSpoolMinMaxMinSpeed(f64),
SetSpoolMinMaxMaxSpeed(f64),
SetSpoolForward(bool),
// Adaptive Spool Speed Controller Parameters
SetSpoolAdaptiveTensionTarget(f64),
@@ -181,7 +148,7 @@ pub struct StateEvent {
pub connected_machine_state: MachineCrossConnectionState,
}
#[derive(Serialize, Debug, Clone, Default)]
#[derive(Serialize, Debug, Clone)]
pub struct TraverseState {
/// min position in mm
pub limit_inner: f64,
@@ -215,7 +182,7 @@ pub struct TraverseState {
pub can_go_home: bool,
}
#[derive(Serialize, Debug, Clone, Default)]
#[derive(Serialize, Debug, Clone)]
pub struct PullerState {
/// regulation type
pub regulation: PullerRegulationMode,
@@ -229,21 +196,20 @@ pub struct PullerState {
pub gear_ratio: GearRatio,
}
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub enum SpoolAutomaticActionMode {
#[default]
NoAction,
Pull,
Hold,
}
#[derive(Serialize, Debug, Clone, Default)]
#[derive(Serialize, Debug, Clone)]
pub struct SpoolAutomaticActionState {
pub spool_required_meters: f64,
pub spool_automatic_action_mode: SpoolAutomaticActionMode,
}
#[derive(Serialize, Debug, Clone, Default)]
#[derive(Serialize, Debug, Clone)]
pub struct ModeState {
/// mode
pub mode: Mode,
@@ -251,13 +217,13 @@ pub struct ModeState {
pub can_wind: bool,
}
#[derive(Serialize, Debug, Clone, Default)]
#[derive(Serialize, Debug, Clone)]
pub struct TensionArmState {
/// is zeroed
pub zeroed: bool,
}
#[derive(Serialize, Debug, Clone, Default)]
#[derive(Serialize, Debug, Clone)]
pub struct SpoolSpeedControllerState {
/// regulation mode
pub regulation_mode: super::spool_speed_controller::SpoolSpeedControllerType,
@@ -275,8 +241,6 @@ pub struct SpoolSpeedControllerState {
pub adaptive_acceleration_factor: f64,
/// deacceleration urgency multiplier for adaptive mode
pub adaptive_deacceleration_urgency_multiplier: f64,
/// forward rotation direction
pub forward: bool,
}
pub enum Winder2Events {
@@ -319,7 +283,6 @@ impl CacheableEvents<Self> for Winder2Events {
}
}
#[cfg(not(feature = "mock-machine"))]
impl MachineApi for Winder2 {
fn api_mutate(&mut self, request_body: Value) -> Result<(), anyhow::Error> {
let mutation: Mutation = serde_json::from_value(request_body)?;
@@ -341,7 +304,6 @@ impl MachineApi for Winder2 {
Mutation::SetSpoolRegulationMode(mode) => self.spool_set_regulation_mode(mode),
Mutation::SetSpoolMinMaxMinSpeed(speed) => self.spool_set_minmax_min_speed(speed),
Mutation::SetSpoolMinMaxMaxSpeed(speed) => self.spool_set_minmax_max_speed(speed),
Mutation::SetSpoolForward(value) => self.spool_set_forward(value),
Mutation::SetSpoolAdaptiveTensionTarget(value) => {
self.spool_set_adaptive_tension_target(value)
}
+22 -45
View File
@@ -1,33 +1,26 @@
#[cfg(not(feature = "mock-machine"))]
mod winder2_imports {
pub use super::super::puller_speed_controller::PullerRegulationMode;
use std::time::Instant;
pub use super::super::{TraverseMode, Winder2, Winder2Mode, api, spool_speed_controller};
pub use crate::machines::buffer1::BufferV1;
use crate::machines::buffer1::BufferV1;
pub use api::{
LiveValuesEvent, ModeState, PullerState, SpoolAutomaticActionMode,
SpoolAutomaticActionState, SpoolSpeedControllerState, StateEvent, TensionArmState,
TraverseState, Winder2Events,
};
pub use control_core::socketio::event::BuildEvent;
pub use control_core::{
machines::identification::MachineIdentificationUnique,
socketio::namespace::NamespaceCacheingLogic, uom_extensions::velocity::meter_per_minute,
};
pub use std::time::Instant;
pub use uom::si::{
angle::degree,
angular_velocity::revolution_per_minute,
f64::{Length, Velocity},
length::{meter, millimeter},
};
}
use super::puller_speed_controller::PullerRegulationMode;
use super::{TraverseMode, Winder2, Winder2Mode, api, spool_speed_controller};
use api::{
LiveValuesEvent, ModeState, PullerState, SpoolAutomaticActionMode, SpoolAutomaticActionState,
SpoolSpeedControllerState, StateEvent, TensionArmState, TraverseState, Winder2Events,
};
use control_core::socketio::event::BuildEvent;
use control_core::{
machines::identification::MachineIdentificationUnique,
socketio::namespace::NamespaceCacheingLogic, uom_extensions::velocity::meter_per_minute,
};
#[cfg(not(feature = "mock-machine"))]
pub use winder2_imports::*;
use uom::si::{
angle::degree,
angular_velocity::revolution_per_minute,
f64::{Length, Velocity},
length::{meter, millimeter},
};
#[cfg(not(feature = "mock-machine"))]
impl Winder2 {
/// Implement Spool
/// called by `act`
@@ -37,17 +30,9 @@ impl Winder2 {
&self.tension_arm,
&self.puller_speed_controller,
);
// Apply direction based on forward setting
let directed_angular_velocity = if self.spool_speed_controller.get_forward() {
angular_velocity
} else {
-angular_velocity
};
let steps_per_second = self
.spool_step_converter
.angular_velocity_to_steps(directed_angular_velocity);
.angular_velocity_to_steps(angular_velocity);
let _ = self.spool.set_speed(steps_per_second);
}
@@ -189,12 +174,11 @@ impl Winder2 {
// Divide by gear ratio to get actual puller/material speed
let puller_speed = motor_speed / self.puller_speed_controller.get_gear_ratio().multiplier();
// Calculate spool RPM from current motor steps (always positive regardless of direction)
// Calculate spool RPM from current motor steps
let spool_rpm = self
.spool_step_converter
.steps_to_angular_velocity(self.spool.get_speed() as f64)
.get::<revolution_per_minute>()
.abs();
.get::<revolution_per_minute>();
let live_values = LiveValuesEvent {
traverse_position: self
@@ -286,7 +270,6 @@ impl Winder2 {
adaptive_deacceleration_urgency_multiplier: self
.spool_speed_controller
.get_adaptive_deacceleration_urgency_multiplier(),
forward: self.spool_speed_controller.get_forward(),
},
spool_automatic_action_state: SpoolAutomaticActionState {
spool_required_meters: self.spool_automatic_action.target_length.get::<meter>(),
@@ -489,12 +472,6 @@ impl Winder2 {
self.emit_state();
}
/// Set forward rotation direction
pub fn spool_set_forward(&mut self, forward: bool) {
self.spool_speed_controller.set_forward(forward);
self.emit_state();
}
/// implement machine connection
/// set connected buffer
pub fn set_connected_buffer(
-13
View File
@@ -1,13 +0,0 @@
use crate::machines::winder2::mock::Winder2;
use control_core::machines::new::MachineAct;
use std::time::{Duration, Instant};
impl MachineAct for Winder2 {
fn act(&mut self, now: Instant) {
// more than 33ms have passed since last emit (30 "fps" target)
if now.duration_since(self.last_measurement_emit) > Duration::from_secs_f64(1.0 / 30.0) {
self.emit_live_values();
self.last_measurement_emit = now;
}
}
}
-67
View File
@@ -1,67 +0,0 @@
use std::{sync::Arc, time::Instant};
use control_core::{machines::api::MachineApi, socketio::namespace::Namespace};
use serde_json::Value;
use smol::lock::Mutex;
use crate::machines::winder2::api::Mutation;
use super::Winder2;
impl MachineApi for Winder2 {
fn api_mutate(&mut self, request_body: Value) -> Result<(), anyhow::Error> {
let mutation: Mutation = serde_json::from_value(request_body)?;
match mutation {
Mutation::EnableTraverseLaserpointer(enable) => self.set_laser(enable),
Mutation::SetMode(mode) => self.set_mode(&mode.into()),
Mutation::SetTraverseLimitOuter(limit) => self.traverse_set_limit_outer(limit),
Mutation::SetTraverseLimitInner(limit) => self.traverse_set_limit_inner(limit),
Mutation::SetTraverseStepSize(size) => self.traverse_set_step_size(size),
Mutation::SetTraversePadding(padding) => self.traverse_set_padding(padding),
Mutation::GotoTraverseLimitOuter => self.traverse_goto_limit_outer(),
Mutation::GotoTraverseLimitInner => self.traverse_goto_limit_inner(),
Mutation::GotoTraverseHome => self.traverse_goto_home(),
Mutation::SetPullerRegulationMode(regulation) => self.puller_set_regulation(regulation),
Mutation::SetPullerTargetSpeed(value) => self.puller_set_target_speed(value),
Mutation::SetPullerTargetDiameter(_) => todo!(),
Mutation::SetPullerForward(value) => self.puller_set_forward(value),
Mutation::SetPullerGearRatio(gear_ratio) => self.puller_set_gear_ratio(gear_ratio),
Mutation::SetSpoolRegulationMode(mode) => self.spool_set_regulation_mode(mode),
Mutation::SetSpoolMinMaxMinSpeed(speed) => self.spool_set_minmax_min_speed(speed),
Mutation::SetSpoolMinMaxMaxSpeed(speed) => self.spool_set_minmax_max_speed(speed),
Mutation::SetSpoolForward(value) => self.spool_set_forward(value),
Mutation::SetSpoolAdaptiveTensionTarget(value) => {
self.spool_set_adaptive_tension_target(value)
}
Mutation::SetSpoolAdaptiveRadiusLearningRate(value) => {
self.spool_set_adaptive_radius_learning_rate(value)
}
Mutation::SetSpoolAdaptiveMaxSpeedMultiplier(value) => {
self.spool_set_adaptive_max_speed_multiplier(value)
}
Mutation::SetSpoolAdaptiveAccelerationFactor(value) => {
self.spool_set_adaptive_acceleration_factor(value)
}
Mutation::SetSpoolAdaptiveDeaccelerationUrgencyMultiplier(value) => {
self.spool_set_adaptive_deacceleration_urgency_multiplier(value)
}
Mutation::SetSpoolAutomaticRequiredMeters(meters) => {
self.set_spool_automatic_required_meters(meters)
}
Mutation::SetSpoolAutomaticAction(mode) => self.set_spool_automatic_mode(mode),
Mutation::ResetSpoolProgress => self.stop_or_pull_spool_reset(Instant::now()),
Mutation::ZeroTensionArmAngle => self.tension_arm_zero(),
Mutation::SetConnectedMachine(machine_identification_unique) => {
self.set_connected_buffer(machine_identification_unique)
}
Mutation::DisconnectMachine(machine_identification_unique) => {
self.disconnect_buffer(machine_identification_unique)
}
}
Ok(())
}
fn api_event_namespace(&mut self) -> Arc<Mutex<Namespace>> {
self.namespace.namespace.clone()
}
}
@@ -1,242 +0,0 @@
use std::time::Instant;
use crate::machines::winder2::Winder2Mode;
use crate::machines::winder2::api::LiveValuesEvent;
use crate::machines::winder2::api::{
ModeState, SpoolAutomaticActionMode, StateEvent, Winder2Events,
};
use crate::machines::winder2::puller_speed_controller::{GearRatio, PullerRegulationMode};
use crate::machines::winder2::spool_speed_controller::SpoolSpeedControllerType;
use crate::machines::{MACHINE_WINDER_V1, VENDOR_QITECH};
use control_core::machines::identification::{MachineIdentification, MachineIdentificationUnique};
use control_core::socketio::event::BuildEvent;
use control_core::socketio::namespace::NamespaceCacheingLogic;
use super::Winder2;
impl Winder2 {
pub const MACHINE_IDENTIFICATION: MachineIdentification = MachineIdentification {
vendor: VENDOR_QITECH,
machine: MACHINE_WINDER_V1,
};
pub fn stop_or_pull_spool_reset(&mut self, now: Instant) {}
/// Implement Mode
pub fn set_mode(&mut self, mode: &Winder2Mode) {
self.mode_state = ModeState {
mode: mode.clone().into(),
can_wind: true,
};
self.emit_state();
}
/// Implement Traverse
pub fn set_laser(&mut self, value: bool) {
self.traverse_state.laserpointer = value;
self.emit_state();
}
pub fn traverse_set_limit_inner(&mut self, limit: f64) {
self.traverse_state.limit_inner = limit;
self.emit_state();
}
pub fn traverse_set_limit_outer(&mut self, limit: f64) {
self.traverse_state.limit_outer = limit;
self.emit_state();
}
pub fn traverse_set_step_size(&mut self, step_size: f64) {
self.traverse_state.step_size = step_size;
self.emit_state();
}
pub fn traverse_set_padding(&mut self, padding: f64) {
self.traverse_state.padding = padding;
self.emit_state();
}
pub fn traverse_goto_limit_inner(&mut self) {
self.traverse_state.position_in = self.traverse_state.limit_inner;
self.emit_state();
}
pub fn traverse_goto_limit_outer(&mut self) {
self.traverse_state.position_in = self.traverse_state.limit_outer;
self.emit_state();
}
pub fn traverse_goto_home(&mut self) {
self.traverse_state.position_in = 0.0;
self.emit_state();
}
pub fn emit_live_values(&mut self) {
let event = LiveValuesEvent {
traverse_position: Some(0.0),
puller_speed: 0.0,
spool_rpm: 0.0,
tension_arm_angle: 0.0,
spool_progress: 0.0,
};
let event = event.build();
self.namespace.emit(Winder2Events::LiveValues(event));
}
pub fn build_state_event(&mut self) -> StateEvent {
StateEvent {
is_default_state: self.is_default_state,
traverse_state: self.traverse_state.clone(),
puller_state: self.puller_state.clone(),
spool_automatic_action_state: self.spool_automatic_action_state.clone(),
mode_state: self.mode_state.clone(),
tension_arm_state: self.tension_arm_state.clone(),
spool_speed_controller_state: self.spool_speed_controller_state.clone(),
connected_machine_state: self.connected_machine_state.clone(),
}
}
pub fn emit_state(&mut self) {
let state = self.build_state_event();
let event = state.build();
self.namespace.emit(Winder2Events::State(event));
}
/// Apply the mode changes to the spool
///
/// It contains a transition matrix for atomic changes.
/// It will set [`Self::spool_mode`]
fn set_traverse_mode(&mut self, mode: &Winder2Mode) {
self.mode_state = ModeState {
mode: crate::machines::winder2::api::Mode::Standby,
can_wind: true,
};
self.emit_state();
}
/// Implement Tension Arm
pub fn tension_arm_zero(&mut self) {
self.tension_arm_state.zeroed = true;
self.emit_state();
}
pub fn set_spool_automatic_required_meters(&mut self, meters: f64) {
self.spool_automatic_action_state.spool_required_meters = meters;
self.emit_state();
}
pub fn set_spool_automatic_mode(&mut self, mode: SpoolAutomaticActionMode) {
self.spool_automatic_action_state
.spool_automatic_action_mode = mode;
self.emit_state();
}
pub fn puller_set_regulation(&mut self, puller_regulation_mode: PullerRegulationMode) {
self.puller_state.regulation = puller_regulation_mode;
self.emit_state();
}
/// Set target speed in m/min
pub fn puller_set_target_speed(&mut self, target_speed: f64) {
self.puller_state.target_speed = target_speed;
self.emit_state();
}
/// Set target diameter in mm
pub fn puller_set_target_diameter(&mut self, target_diameter: f64) {
self.puller_state.target_diameter = target_diameter;
self.emit_state();
}
/// Set forward direction
pub fn puller_set_forward(&mut self, forward: bool) {
self.puller_state.forward = forward;
self.emit_state();
}
/// Set gear ratio for winding speed
pub fn puller_set_gear_ratio(&mut self, gear_ratio: GearRatio) {
self.puller_state.gear_ratio = gear_ratio;
self.emit_state();
}
// Spool Speed Controller API methods
pub fn spool_set_regulation_mode(&mut self, regulation_mode: SpoolSpeedControllerType) {
self.spool_speed_controller_state.regulation_mode = regulation_mode;
self.emit_state();
}
/// Set minimum speed for minmax mode in RPM
pub fn spool_set_minmax_min_speed(&mut self, min_speed_rpm: f64) {
self.spool_speed_controller_state.minmax_min_speed = min_speed_rpm;
self.emit_state();
}
/// Set maximum speed for minmax mode in RPM
pub fn spool_set_minmax_max_speed(&mut self, max_speed_rpm: f64) {
self.spool_speed_controller_state.minmax_max_speed = max_speed_rpm;
self.emit_state();
}
/// Set tension target for adaptive mode (0.0-1.0)
pub fn spool_set_adaptive_tension_target(&mut self, tension_target: f64) {
self.spool_speed_controller_state.adaptive_tension_target = tension_target;
self.emit_state();
}
/// Set radius learning rate for adaptive mode
pub fn spool_set_adaptive_radius_learning_rate(&mut self, radius_learning_rate: f64) {
self.spool_speed_controller_state
.adaptive_radius_learning_rate = radius_learning_rate;
self.emit_state();
}
/// Set max speed multiplier for adaptive mode
pub fn spool_set_adaptive_max_speed_multiplier(&mut self, max_speed_multiplier: f64) {
self.spool_speed_controller_state
.adaptive_max_speed_multiplier = max_speed_multiplier;
self.emit_state();
}
/// Set acceleration factor for adaptive mode
pub fn spool_set_adaptive_acceleration_factor(&mut self, acceleration_factor: f64) {
self.spool_speed_controller_state
.adaptive_acceleration_factor = acceleration_factor;
self.emit_state();
}
/// Set deacceleration urgency multiplier for adaptive mode
pub fn spool_set_adaptive_deacceleration_urgency_multiplier(
&mut self,
deacceleration_urgency_multiplier: f64,
) {
self.spool_speed_controller_state
.adaptive_deacceleration_urgency_multiplier = deacceleration_urgency_multiplier;
self.emit_state();
}
/// Set forward rotation direction
pub fn spool_set_forward(&mut self, forward: bool) {
self.spool_speed_controller_state.forward = forward;
self.emit_state();
}
/// implement machine connection
/// set connected buffer
pub fn set_connected_buffer(
&mut self,
machine_identification_unique: MachineIdentificationUnique,
) {
self.emit_state();
}
/// disconnect buffer
pub fn disconnect_buffer(
&mut self,
machine_identification_unique: MachineIdentificationUnique,
) {
self.emit_state();
}
}
-44
View File
@@ -1,44 +0,0 @@
use std::time::Instant;
use control_core::machines::{
connection::MachineCrossConnectionState, identification::MachineIdentificationUnique,
};
use control_core_derive::Machine;
pub mod act;
pub mod api;
pub mod mock_emit;
pub mod new;
use crate::machines::winder2::api::Winder2Namespace;
use super::api::{
ModeState, PullerState, SpoolAutomaticActionState, SpoolSpeedControllerState, TensionArmState,
TraverseState,
};
#[derive(Debug, Machine)]
pub struct Winder2 {
machine_identification_unique: MachineIdentificationUnique,
namespace: Winder2Namespace,
last_measurement_emit: Instant,
pub is_default_state: bool,
/// traverse state
pub traverse_state: TraverseState,
/// puller state
pub puller_state: PullerState,
/// spool automatic action state and progress
pub spool_automatic_action_state: SpoolAutomaticActionState,
/// mode state
pub mode_state: ModeState,
/// tension arm state
pub tension_arm_state: TensionArmState,
/// spool speed controller state
pub spool_speed_controller_state: SpoolSpeedControllerState,
/// connected machine state
pub connected_machine_state: MachineCrossConnectionState,
}
impl std::fmt::Display for Winder2 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Winder2")
}
}
-53
View File
@@ -1,53 +0,0 @@
use crate::machines::winder2::{
api::{
ModeState, PullerState, SpoolAutomaticActionState, SpoolSpeedControllerState,
TensionArmState, TraverseState, Winder2Namespace,
},
mock::Winder2,
};
use control_core::machines::connection::MachineCrossConnectionState;
impl control_core::machines::new::MachineNewTrait for Winder2 {
fn new(
params: &control_core::machines::new::MachineNewParams<'_, '_, '_, '_, '_, '_, '_>,
) -> Result<Self, anyhow::Error>
where
Self: Sized,
{
// Mock machine can work with either Serial or Ethercat hardware
// For the mock machine, we don't need to actually use the hardware
// We just validate that we have the expected hardware type
match params.hardware {
control_core::machines::new::MachineNewHardware::Serial(_) => {
// For serial mode, we could potentially use the serial device if needed
// but for a mock machine, we'll just note it and proceed
}
control_core::machines::new::MachineNewHardware::Ethercat(_) => {
// For ethercat mode, we could potentially use the ethercat devices
// but for a mock machine, we'll just note it and proceed
}
}
let now = std::time::Instant::now();
let mut extruder_mock_machine = Self {
machine_identification_unique: params.get_machine_identification_unique(),
namespace: Winder2Namespace {
namespace: params.namespace.clone(),
},
last_measurement_emit: now,
is_default_state: true,
traverse_state: TraverseState::default(),
puller_state: PullerState::default(),
spool_automatic_action_state: SpoolAutomaticActionState::default(),
mode_state: ModeState::default(),
tension_arm_state: TensionArmState::default(),
spool_speed_controller_state: SpoolSpeedControllerState::default(),
connected_machine_state: MachineCrossConnectionState::default(),
};
extruder_mock_machine.emit_state();
Ok(extruder_mock_machine)
}
}
+29 -56
View File
@@ -11,47 +11,37 @@ pub mod spool_speed_controller;
pub mod tension_arm;
pub mod traverse_controller;
#[cfg(feature = "mock-machine")]
pub mod mock;
use std::{fmt::Debug, sync::Weak, time::Instant};
#[cfg(feature = "mock-machine")]
mod winder2_imports {
pub use super::api::SpoolAutomaticActionMode;
pub use std::time::Instant;
pub use uom::si::f64::Length;
}
use api::{SpoolAutomaticActionMode, Winder2Namespace};
use control_core::{
converters::angular_step_converter::AngularStepConverter,
machines::{
connection::{CrossConnectableMachine, MachineCrossConnection},
identification::{MachineIdentification, MachineIdentificationUnique},
manager::MachineManager,
},
};
use control_core_derive::Machine;
use ethercat_hal::io::{
digital_input::DigitalInput, digital_output::DigitalOutput,
stepper_velocity_el70x1::StepperVelocityEL70x1,
};
use puller_speed_controller::PullerSpeedController;
use smol::lock::RwLock;
use spool_speed_controller::SpoolSpeedController;
use tension_arm::TensionArm;
use traverse_controller::TraverseController;
use uom::{
ConstZero,
si::{
f64::Length,
length::{meter, millimeter},
velocity::meter_per_second,
},
};
#[cfg(not(feature = "mock-machine"))]
mod winder2_imports {
pub use super::api::SpoolAutomaticActionMode;
pub use super::api::Winder2Namespace;
pub use super::puller_speed_controller::PullerSpeedController;
pub use super::spool_speed_controller::SpoolSpeedController;
pub use super::tension_arm::TensionArm;
pub use super::traverse_controller::TraverseController;
pub use control_core::{
converters::angular_step_converter::AngularStepConverter,
machines::{
connection::{CrossConnectableMachine, MachineCrossConnection},
identification::{MachineIdentification, MachineIdentificationUnique},
manager::MachineManager,
},
};
pub use control_core_derive::Machine;
pub use ethercat_hal::io::{
digital_input::DigitalInput, digital_output::DigitalOutput,
stepper_velocity_el70x1::StepperVelocityEL70x1,
};
pub use smol::lock::RwLock;
pub use std::{fmt::Debug, sync::Weak, time::Instant};
pub use uom::si::f64::Length;
pub use crate::machines::{MACHINE_WINDER_V1, VENDOR_QITECH, buffer1::BufferV1};
pub use uom::ConstZero;
pub use uom::si::{length::meter, length::millimeter, velocity::meter_per_second};
}
pub use winder2_imports::*;
use crate::machines::{MACHINE_WINDER_V1, VENDOR_QITECH, buffer1::BufferV1};
#[derive(Debug)]
pub struct SpoolAutomaticAction {
@@ -61,18 +51,6 @@ pub struct SpoolAutomaticAction {
pub mode: SpoolAutomaticActionMode,
}
impl Default for SpoolAutomaticAction {
fn default() -> Self {
SpoolAutomaticAction {
progress: Length::new::<uom::si::length::meter>(0.0),
progress_last_check: Instant::now(),
target_length: Length::new::<uom::si::length::meter>(0.0),
mode: SpoolAutomaticActionMode::default(),
}
}
}
#[cfg(not(feature = "mock-machine"))]
#[derive(Debug, Machine)]
pub struct Winder2 {
// drivers
@@ -118,14 +96,12 @@ pub struct Winder2 {
emitted_default_state: bool,
}
#[cfg(not(feature = "mock-machine"))]
impl CrossConnectableMachine<Winder2, BufferV1> for Winder2 {
fn get_cross_connection(&mut self) -> &mut MachineCrossConnection<Winder2, BufferV1> {
&mut self.connected_buffer
}
}
#[cfg(not(feature = "mock-machine"))]
impl Winder2 {
pub const MACHINE_IDENTIFICATION: MachineIdentification = MachineIdentification {
vendor: VENDOR_QITECH,
@@ -301,7 +277,6 @@ impl Winder2 {
pub fn calculate_spool_auto_progress_(&mut self, now: Instant) {
// Calculate time elapsed since last progress check (in minutes)
let dt = now
.duration_since(self.spool_automatic_action.progress_last_check)
.as_secs_f64();
@@ -393,14 +368,12 @@ impl From<Winder2Mode> for PullerMode {
}
}
#[cfg(not(feature = "mock-machine"))]
impl std::fmt::Display for Winder2 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Winder2")
}
}
#[cfg(not(feature = "mock-machine"))]
#[cfg(test)]
mod tests {
use super::*;
+41 -54
View File
@@ -1,63 +1,50 @@
#[cfg(not(feature = "mock-machine"))]
mod winder2_imports {
pub use super::super::api::Winder2Namespace;
pub use super::super::tension_arm::TensionArm;
pub use super::super::{Winder2, Winder2Mode};
pub use crate::machines::winder2::puller_speed_controller::PullerSpeedController;
pub use crate::machines::winder2::spool_speed_controller::SpoolSpeedController;
pub use crate::machines::winder2::traverse_controller::TraverseController;
pub use anyhow::Error;
pub use control_core::converters::angular_step_converter::AngularStepConverter;
pub use control_core::converters::linear_step_converter::LinearStepConverter;
pub use control_core::machines::connection::MachineCrossConnection;
pub use control_core::machines::new::{
MachineNewHardware, MachineNewParams, MachineNewTrait, validate_no_role_dublicates,
validate_same_machine_identification_unique,
};
use std::time::Instant;
pub use control_core::uom_extensions::velocity::meter_per_minute;
pub use ethercat_hal::coe::ConfigurableDevice;
pub use ethercat_hal::devices::ek1100::EK1100;
pub use ethercat_hal::devices::el2002::{EL2002, EL2002_IDENTITY_B, EL2002Port};
pub use ethercat_hal::devices::el7031::coe::EL7031Configuration;
pub use ethercat_hal::devices::el7031::pdo::EL7031PredefinedPdoAssignment;
pub use ethercat_hal::devices::el7031::{
EL7031, EL7031_IDENTITY_A, EL7031_IDENTITY_B, EL7031DigitalInputPort, EL7031StepperPort,
};
pub use ethercat_hal::devices::el7031_0030::coe::EL7031_0030Configuration;
pub use ethercat_hal::devices::el7031_0030::pdo::EL7031_0030PredefinedPdoAssignment;
pub use ethercat_hal::devices::el7031_0030::{
self, EL7031_0030, EL7031_0030_IDENTITY_A, EL7031_0030AnalogInputPort,
EL7031_0030StepperPort,
};
pub use ethercat_hal::devices::el7041_0052::coe::EL7041_0052Configuration;
pub use ethercat_hal::devices::el7041_0052::{
EL7041_0052, EL7041_0052_IDENTITY_A, EL7041_0052Port,
};
pub use ethercat_hal::devices::{ek1100::EK1100_IDENTITY_A, el2002::EL2002_IDENTITY_A};
pub use ethercat_hal::io::analog_input::AnalogInput;
pub use ethercat_hal::io::digital_input::DigitalInput;
pub use ethercat_hal::io::digital_output::DigitalOutput;
pub use ethercat_hal::io::stepper_velocity_el70x1::StepperVelocityEL70x1;
pub use ethercat_hal::shared_config;
pub use ethercat_hal::shared_config::el70x1::{EL70x1OperationMode, StmMotorConfiguration};
pub use std::time::Instant;
pub use uom::ConstZero;
pub use uom::si::f64::{Length, Velocity};
pub use uom::si::length::{centimeter, meter, millimeter};
}
#[cfg(not(feature = "mock-machine"))]
pub use winder2_imports::*;
#[cfg(not(feature = "mock-machine"))]
use super::api::Winder2Namespace;
use super::tension_arm::TensionArm;
use super::{Winder2, Winder2Mode};
use crate::machines::get_ethercat_device;
use crate::machines::winder2::puller_speed_controller::PullerSpeedController;
use crate::machines::winder2::spool_speed_controller::SpoolSpeedController;
use crate::machines::winder2::traverse_controller::TraverseController;
use anyhow::Error;
use control_core::converters::angular_step_converter::AngularStepConverter;
use control_core::converters::linear_step_converter::LinearStepConverter;
use control_core::machines::connection::MachineCrossConnection;
use control_core::machines::new::{
MachineNewHardware, MachineNewParams, MachineNewTrait, validate_no_role_dublicates,
validate_same_machine_identification_unique,
};
use control_core::uom_extensions::velocity::meter_per_minute;
use ethercat_hal::coe::ConfigurableDevice;
use ethercat_hal::devices::ek1100::EK1100;
use ethercat_hal::devices::el2002::{EL2002, EL2002_IDENTITY_B, EL2002Port};
use ethercat_hal::devices::el7031::coe::EL7031Configuration;
use ethercat_hal::devices::el7031::pdo::EL7031PredefinedPdoAssignment;
use ethercat_hal::devices::el7031::{
EL7031, EL7031_IDENTITY_A, EL7031_IDENTITY_B, EL7031DigitalInputPort, EL7031StepperPort,
};
use ethercat_hal::devices::el7031_0030::coe::EL7031_0030Configuration;
use ethercat_hal::devices::el7031_0030::pdo::EL7031_0030PredefinedPdoAssignment;
use ethercat_hal::devices::el7031_0030::{
self, EL7031_0030, EL7031_0030_IDENTITY_A, EL7031_0030AnalogInputPort, EL7031_0030StepperPort,
};
use ethercat_hal::devices::el7041_0052::coe::EL7041_0052Configuration;
use ethercat_hal::devices::el7041_0052::{EL7041_0052, EL7041_0052_IDENTITY_A, EL7041_0052Port};
use ethercat_hal::devices::{ek1100::EK1100_IDENTITY_A, el2002::EL2002_IDENTITY_A};
use ethercat_hal::io::analog_input::AnalogInput;
use ethercat_hal::io::digital_input::DigitalInput;
use ethercat_hal::io::digital_output::DigitalOutput;
use ethercat_hal::io::stepper_velocity_el70x1::StepperVelocityEL70x1;
use ethercat_hal::shared_config;
use ethercat_hal::shared_config::el70x1::{EL70x1OperationMode, StmMotorConfiguration};
use uom::ConstZero;
use uom::si::f64::{Length, Velocity};
use uom::si::length::{centimeter, meter, millimeter};
#[cfg(not(feature = "mock-machine"))]
impl MachineNewTrait for Winder2 {
fn new<'maindevice>(params: &MachineNewParams) -> Result<Self, Error> {
// validate general stuff
let device_identification = params.device_group.to_vec();
validate_same_machine_identification_unique(&device_identification)?;
@@ -150,9 +150,8 @@ impl PullerSpeedController {
}
}
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum PullerRegulationMode {
#[default]
Speed,
Diameter,
}
@@ -10,9 +10,8 @@ use serde::{Deserialize, Serialize};
use std::time::Instant;
use uom::si::f64::AngularVelocity;
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SpoolSpeedControllerType {
#[default]
Adaptive,
MinMax,
}
@@ -22,7 +21,6 @@ pub struct SpoolSpeedController {
adaptive_controller: AdaptiveSpoolSpeedController,
minmax_controller: MinMaxSpoolSpeedController,
r#type: SpoolSpeedControllerType,
forward: bool,
}
impl Default for SpoolSpeedController {
@@ -37,7 +35,6 @@ impl SpoolSpeedController {
adaptive_controller: AdaptiveSpoolSpeedController::new(),
minmax_controller: MinMaxSpoolSpeedController::new(),
r#type: SpoolSpeedControllerType::Adaptive,
forward: true,
}
}
@@ -183,12 +180,4 @@ impl SpoolSpeedController {
self.adaptive_controller
.set_deacceleration_urgency_multiplier(deacceleration_urgency_multiplier);
}
pub const fn get_forward(&self) -> bool {
self.forward
}
pub const fn set_forward(&mut self, forward: bool) {
self.forward = forward;
}
}
+47 -46
View File
@@ -1,71 +1,72 @@
use futures::{FutureExt, select};
#[cfg(feature = "dhat-heap")]
#[global_allocator]
static ALLOC: dhat::Alloc = dhat::Alloc;
use app_state::AppState;
use r#loop::init_loop;
#[cfg(feature = "mock-machine")]
use mock::init::init_mock;
#[cfg(feature = "mock-machine")]
pub mod mock;
use rest::init::init_api;
#[cfg(not(feature = "mock-machine"))]
use serial::init::init_serial;
use std::sync::Arc;
use crate::panic::init_panic_handling;
use app_state::AppState;
use ethercat::{
ethercat_discovery_info::{send_ethercat_discovering, send_ethercat_found},
init::start_interface_discovery,
};
use r#loop::start_loop_thread;
use rest::init::start_api_thread;
use serial::init::{handle_serial_device_hotplug, start_serial_discovery};
use socketio::queue::start_socketio_queue;
use std::sync::Arc;
use crate::socketio::queue::init_socketio_queue;
pub mod app_state;
pub mod ethercat;
pub mod logging;
pub mod r#loop;
pub mod machines;
#[cfg(feature = "mock-machine")]
pub mod mock;
pub mod panic;
pub mod performance_metrics;
pub mod rest;
pub mod serial;
pub mod socketio;
use crate::ethercat::init::init_ethercat;
fn main() {
logging::init_tracing();
tracing::info!("Tracing initialized successfully");
init_panic_handling();
#[cfg(feature = "memory-locking")]
if let Err(e) = control_core::realtime::lock_memory() {
tracing::error!("[{}::main] Failed to lock memory: {:?}", module_path!(), e);
} else {
tracing::info!("[{}::main] Memory locked successfully", module_path!());
}
let app_state = Arc::new(AppState::new());
let _ = start_api_thread(app_state.clone());
let mut socketio_fut = start_socketio_queue(app_state.clone()).fuse();
let mut ethercat_fut = start_interface_discovery().fuse();
let mut serial_fut = start_serial_discovery().fuse();
// Spawn init thread
let init_thread = std::thread::Builder::new()
.name("init".to_string())
.spawn({
move || {
init_socketio_queue(app_state.clone());
init_api(app_state.clone()).expect("Failed to initialize API");
init_loop(app_state.clone()).expect("Failed to initialize loop");
smol::block_on(async { send_ethercat_discovering(app_state.clone()).await });
smol::block_on(async {
loop {
// lets the async runtime decide which future to run next
select! {
res = ethercat_fut => {
tracing::info!("EtherCAT task finished: {:?}", res);
match res {
Ok(interface) =>
{
send_ethercat_found(app_state.clone(), &interface).await;
let _ = start_loop_thread(&interface, app_state.clone());
},
Err(_) => (),
};
},
res = serial_fut => {
let _ = handle_serial_device_hotplug(app_state.clone(),res).await;
serial_fut = start_serial_discovery().fuse();
},
res = socketio_fut => {
// In theory it should never finish
tracing::warn!("SocketIO task finished: {:?}", res);
},
#[cfg(feature = "mock-machine")]
init_mock(app_state.clone()).expect("Failed to initialize mock machines");
#[cfg(not(feature = "mock-machine"))]
init_serial(app_state.clone()).expect("Failed to initialize Serial");
#[cfg(not(feature = "mock-machine"))]
init_ethercat(app_state).expect("Failed to initialize EtherCAT");
}
}
});
})
.expect("Failed to spawn init thread");
// Wait for init thread to complete
init_thread.join().expect("Init thread panicked");
// Keep the main thread alive indefinitely
// The program should only exit via panic handling or external signals
loop {
// better way to "sleep", uses basically
std::thread::park();
}
}
+3 -35
View File
@@ -1,6 +1,5 @@
#[cfg(feature = "mock-machine")]
use crate::serial::devices::extruder_mock::ExtruderMockSerialDevice;
use crate::serial::devices::winder_mock::WinderMockSerialDevice;
#[cfg(feature = "mock-machine")]
use {
crate::app_state::AppState,
@@ -13,15 +12,16 @@ use {
},
std::sync::Arc,
};
#[cfg(feature = "mock-machine")]
pub fn init_mock(app_state: Arc<AppState>) -> Result<(), anyhow::Error> {
// For mock devices, we need to manually create and add them to the machine manager
// since they won't be detected by the serial detection loop
return smol::block_on(async {
// Create a mock serial device manually
let (device_thread_panic_tx, _device_thread_panic_rx) = smol::channel::unbounded();
let serial_params = SerialDeviceNewParams {
path: "/dev/mock-serial".to_string(),
device_thread_panic_tx,
};
// Create the mock serial device
@@ -57,39 +57,7 @@ pub fn init_mock(app_state: Arc<AppState>) -> Result<(), anyhow::Error> {
}
};
let _ = match ExtruderMockSerialDevice::new_serial(&serial_params) {
Ok((device_identification, mock_serial_device)) => {
// Add the mock device to the machine manager
{
let mut machine_guard = app_state.machines.write().await;
machine_guard.add_serial_device(
&device_identification,
mock_serial_device,
&MACHINE_REGISTRY,
app_state.socketio_setup.socket_queue_tx.clone(),
Arc::downgrade(&app_state.machines),
);
}
// Notify clients via socketio about the new machine
let app_state_event = app_state.clone();
let main_namespace = &mut app_state_event
.socketio_setup
.namespaces
.write()
.await
.main_namespace;
let event = MachinesEventBuilder().build(app_state_event.clone());
main_namespace.emit(MainNamespaceEvents::MachinesEvent(event));
Ok::<(), anyhow::Error>(())
}
Err(e) => {
tracing::error!("Failed to create extruder mock serial device: {}", e);
return Err(e);
}
};
match WinderMockSerialDevice::new_serial(&serial_params) {
match ExtruderMockSerialDevice::new_serial(&serial_params) {
Ok((device_identification, mock_serial_device)) => {
// Add the mock device to the machine manager
{
+2 -2
View File
@@ -10,8 +10,8 @@ const METRICS_LOG_INTERVAL_SECS: u64 = 30; // Log every 30 seconds
pub struct EthercatPerformanceMetrics {
txrx_times: VecDeque<Duration>,
loop_times: VecDeque<Duration>,
pub last_loop_start: Option<Instant>,
pub last_log_time: Instant,
last_loop_start: Option<Instant>,
last_log_time: Instant,
}
impl Default for EthercatPerformanceMetrics {
+53 -45
View File
@@ -1,57 +1,65 @@
use anyhow::Result;
use axum::routing::post;
use std::sync::Arc;
use std::thread;
use tower_http::cors::CorsLayer;
use tower_http::trace::{DefaultMakeSpan, DefaultOnRequest, DefaultOnResponse, TraceLayer};
use tracing::Level;
use super::handlers::machine_mutation::post_machine_mutate;
use super::handlers::write_machine_device_identification::post_write_machine_device_identification;
use crate::app_state::AppState;
use crate::socketio::init::init_socketio;
use anyhow::anyhow;
use axum::routing::post;
use std::sync::Arc;
use std::thread::JoinHandle;
use tower_http::cors::CorsLayer;
use tower_http::trace::{DefaultMakeSpan, DefaultOnRequest, DefaultOnResponse, TraceLayer};
use tracing::Level;
async fn init_api(app_state: Arc<AppState>) -> Result<()> {
let cors = CorsLayer::permissive();
let socketio_layer = init_socketio(&app_state).await;
pub fn init_api(app_state: Arc<AppState>) -> Result<JoinHandle<()>, anyhow::Error> {
std::thread::Builder::new()
.name("api".to_string())
.spawn(|| {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_io()
.enable_time()
.build()
.expect("Failed to create runtime");
let trace_layer = TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::new().level(Level::DEBUG))
.on_request(DefaultOnRequest::new().level(Level::TRACE))
.on_response(DefaultOnResponse::new().level(Level::TRACE));
rt.block_on(async {
// allow all CORS requests
let cors = CorsLayer::permissive();
let app = axum::Router::new()
.route(
"/api/v1/write_machine_device_identification",
post(post_write_machine_device_identification),
)
.route("/api/v1/machine/mutate", post(post_machine_mutate))
.layer(socketio_layer)
.layer(cors)
.layer(trace_layer)
.with_state(app_state);
// creat socketio layer
let socketio_layer = init_socketio(&app_state).await;
let listener = tokio::net::TcpListener::bind("0.0.0.0:3001")
.await
.expect("Failed to bind to port 3001");
// Create a more detailed trace layer for HTTP requests
let trace_layer = TraceLayer::new_for_http()
.make_span_with(
DefaultMakeSpan::new()
.level(Level::DEBUG)
.include_headers(false),
)
.on_request(DefaultOnRequest::new().level(Level::TRACE))
.on_response(
DefaultOnResponse::new()
.level(Level::TRACE)
.include_headers(false),
);
tracing::info!("HTTP server running on 0.0.0.0:3001");
// make axum server to serve the data on /ethercat
let app = axum::Router::new()
.route(
"/api/v1/write_machine_device_identification",
post(post_write_machine_device_identification),
)
.route("/api/v1/machine/mutate", post(post_machine_mutate))
.layer(socketio_layer)
.layer(cors)
.layer(trace_layer)
.with_state(app_state);
axum::serve(listener, app)
.await
.map_err(|e| anyhow::anyhow!("Server error: {}", e))
}
let listener = tokio::net::TcpListener::bind("0.0.0.0:3001")
.await
.expect("Failed to bind to port 3001");
/// Starts the API server in its own thread with a single-threaded Tokio runtime
pub fn start_api_thread(app_state: Arc<AppState>) -> std::thread::JoinHandle<()> {
thread::spawn(move || {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("Failed to create Tokio runtime");
if let Err(err) = rt.block_on(init_api(app_state)) {
eprintln!("API server exited with error: {err:?}");
}
})
tracing::info!("Starting HTTP server on 0.0.0.0:3001");
axum::serve(listener, app).await.expect("Failed to serve");
});
})
.map_err(|e| anyhow!("Failed to spawn API thread: {}", e))
}
+20 -3
View File
@@ -17,7 +17,10 @@ use control_core::{
DeviceMachineIdentification, MachineIdentification, MachineIdentificationUnique,
},
modbus::{self, ModbusRequest, ModbusResponse},
serial::{SerialDevice, SerialDeviceNew, SerialDeviceNewParams},
serial::{
SerialDevice, SerialDeviceNew, SerialDeviceNewParams, panic::send_serial_device_panic,
serial_detection::SerialDeviceRemoval,
},
};
use serialport::SerialPort;
use serialport::{ClearBuffer, DataBits, FlowControl, Parity, StopBits};
@@ -122,13 +125,27 @@ impl SerialDeviceNew for Laser {
path: params.path.clone(),
}));
//// Spawn the device thread
// Spawn the device thread
let device_thread_panic_tx = params.device_thread_panic_tx.clone();
let _self_clone = _self.clone();
let path = params.path.clone();
thread::Builder::new()
.name("laser".to_owned())
.spawn(move || {
send_serial_device_panic(path.clone(), device_thread_panic_tx.clone());
smol::block_on(async {
let _ = Self::process(_self_clone).await;
let process_result = Self::process(_self_clone).await;
let removal = match process_result {
Ok(_) => SerialDeviceRemoval::Disconnect(path),
Err(e) => SerialDeviceRemoval::Error(path, e),
};
// if the task exists we want to remove the device
device_thread_panic_tx
.send(removal)
.await
.expect("Failed to send device removal signal");
});
})?;
-2
View File
@@ -3,5 +3,3 @@ pub mod extruder_mock;
pub mod laser;
#[cfg(feature = "mock-machine")]
pub mod mock;
#[cfg(feature = "mock-machine")]
pub mod winder_mock;
@@ -1,59 +0,0 @@
use std::sync::Arc;
use control_core::{
helpers::hashing::{byte_folding_u16, hash_djb2},
machines::identification::{
DeviceHardwareIdentification, DeviceHardwareIdentificationSerial, DeviceIdentification,
DeviceMachineIdentification, MachineIdentification, MachineIdentificationUnique,
},
serial::{SerialDevice, SerialDeviceNew, SerialDeviceNewParams},
};
use smol::lock::RwLock;
use crate::machines::{MACHINE_WINDER_V1, VENDOR_QITECH};
/// Mock serial device for testing MockMachine
/// This provides a minimal SerialDevice implementation that doesn't require actual hardware
#[derive(Debug)]
pub struct WinderMockSerialDevice {
pub path: String,
}
impl SerialDevice for WinderMockSerialDevice {}
impl SerialDeviceNew for WinderMockSerialDevice {
fn new_serial(
params: &SerialDeviceNewParams,
) -> Result<(DeviceIdentification, Arc<RwLock<Self>>), anyhow::Error>
where
Self: Sized,
{
// Generate a unique serial number based on the path
let hash = hash_djb2(params.path.as_bytes());
let serial = byte_folding_u16(&hash.to_le_bytes());
let device_identification = DeviceIdentification {
device_machine_identification: Some(DeviceMachineIdentification {
machine_identification_unique: MachineIdentificationUnique {
machine_identification: MachineIdentification {
vendor: VENDOR_QITECH,
machine: MACHINE_WINDER_V1,
},
serial,
},
role: 0,
}),
device_hardware_identification: DeviceHardwareIdentification::Serial(
DeviceHardwareIdentificationSerial {
path: params.path.clone(),
},
),
};
let mock_serial_device = Arc::new(RwLock::new(WinderMockSerialDevice {
path: params.path.clone(),
}));
Ok((device_identification, mock_serial_device))
}
}
+70 -135
View File
@@ -1,139 +1,74 @@
use control_core::{
machines::identification::MachineIdentificationUnique,
serial::{
SerialDeviceIdentification, SerialDeviceNew, SerialDeviceNewParams,
serial_detection::SerialDetection,
},
socketio::namespace::NamespaceCacheingLogic,
};
use serialport::UsbPortInfo;
use smol::Task;
use std::{collections::HashMap, sync::Arc, time::Duration};
use crate::socketio::main_namespace::MainNamespaceEvents;
use crate::socketio::main_namespace::machines_event::MachinesEventBuilder;
use crate::{app_state::AppState, machines::registry::MACHINE_REGISTRY};
use control_core::socketio::namespace::NamespaceCacheingLogic;
use std::{sync::Arc, thread, time::Duration};
use crate::{
app_state::AppState,
machines::{laser::LaserMachine, registry::MACHINE_REGISTRY},
socketio::main_namespace::{MainNamespaceEvents, machines_event::MachinesEventBuilder},
};
pub fn init_serial(app_state: Arc<AppState>) -> Result<(), anyhow::Error> {
let app_state_clone = app_state.clone();
use super::devices::laser::Laser;
thread::Builder::new()
.name("SerialDetectionThread".to_owned())
.spawn(move || {
let app_state_clone = app_state_clone;
smol::block_on(async move {
let rt = smol::LocalExecutor::new();
rt.run(async {
loop {
let result = {
let mut serial_setup_guard = app_state_clone.serial_setup.write().await;
// Async function that runs until at least one serial device is found.
pub async fn find_serial() -> Option<HashMap<String, UsbPortInfo>> {
smol::Timer::after(Duration::from_secs(1)).await;
let devices = SerialDetection::detect_devices();
if !devices.is_empty() {
return Some(devices);
} else {
return None;
}
}
// Returns a smol::Task that resolves when atleast one device is found.
pub fn start_serial_discovery() -> Task<Option<HashMap<String, UsbPortInfo>>> {
smol::spawn(find_serial())
}
// This function handles a disconnection and or reconnection of Laser
// You can easily rewrite it when we have more serialdevices
// TODO: Add A static list of known SeriadeviceIdents
pub async fn handle_serial_device_hotplug(
app_state: Arc<AppState>,
map: Option<HashMap<String, UsbPortInfo>>,
) {
let laser_ident = SerialDeviceIdentification {
vendor_id: 0x0403,
product_id: 0x6001,
};
let laser = match map {
Some(map) => SerialDetection::get_path_by_id(laser_ident, map),
None => None,
};
let mut unique_ident: Option<MachineIdentificationUnique> = None;
{
let machines = app_state.machines.read_arc_blocking();
for (id, _) in machines.iter() {
if id.machine_identification == LaserMachine::MACHINE_IDENTIFICATION {
unique_ident = Some(id.clone());
break;
}
}
}
// Machine isnt connected, so add it back
if laser.is_some() && unique_ident.is_none() {
let serial_params = SerialDeviceNewParams {
path: laser.unwrap(),
};
let _ = match Laser::new_serial(&serial_params) {
Ok((device_identification, serial_device)) => {
{
let mut machines = app_state.machines.write().await;
machines.add_serial_device(
&device_identification,
serial_device,
&MACHINE_REGISTRY,
app_state.socketio_setup.socket_queue_tx.clone(),
Arc::downgrade(&app_state.machines),
);
}
let app_state_event = app_state.clone();
let main_namespace = &mut app_state_event
.socketio_setup
.namespaces
.write()
.await
.main_namespace;
let event = MachinesEventBuilder().build(app_state_event.clone());
main_namespace.emit(MainNamespaceEvents::MachinesEvent(event));
}
_ => (),
};
} else if laser.is_none() && unique_ident.is_some() {
let serial_params = SerialDeviceNewParams {
path: "".to_string(),
};
let _ = match Laser::new_serial(&serial_params) {
Ok((device_identification, _)) => {
app_state
.machines
.write()
.await
.remove_serial_device(&device_identification);
drop(app_state.machines.clone());
app_state
.machines
.write_arc()
.await
.serial_machines
.remove(&unique_ident.clone().unwrap());
app_state
.machines
.write_arc()
.await
.ethercat_machines
.remove(&unique_ident.clone().unwrap());
drop(app_state.machines.clone());
let main_namespace = &mut app_state
.socketio_setup
.namespaces
.write()
.await
.main_namespace;
let event = MachinesEventBuilder().build(app_state.clone());
main_namespace.emit(MainNamespaceEvents::MachinesEvent(event));
}
_ => (),
};
}
let mut port_result =
serial_setup_guard.serial_detection.check_ports().await;
let mut removed_signals = serial_setup_guard
.serial_detection
.check_remove_signals()
.await;
port_result.removed.append(&mut removed_signals);
port_result
};
if !result.added.is_empty() || !result.removed.is_empty() {
// sync serial device discovery to machine manager
{
let mut machine_guard = app_state_clone.machines.write().await;
// turn added devices into machines
for (device_identifiaction, device) in result.added {
machine_guard.add_serial_device(
&device_identifiaction,
device.clone(),
&MACHINE_REGISTRY,
app_state_clone.socketio_setup.socket_queue_tx.clone(),
Arc::downgrade(&app_state.machines),
)
}
for device_identification in result.removed {
machine_guard.remove_serial_device(&device_identification)
}
}
// Notify client via socketio
let app_state_event = app_state.clone();
smol::block_on(async {
let main_namespace = &mut app_state_event
.socketio_setup
.namespaces
.write()
.await
.main_namespace;
let event = MachinesEventBuilder().build(app_state_event.clone());
main_namespace.emit(MainNamespaceEvents::MachinesEvent(event));
});
}
smol::Timer::after(Duration::from_millis(300)).await;
}
})
.await;
});
})
.expect("Failed to spawn SerialTxRxThread");
Ok(())
}
+47 -29
View File
@@ -1,7 +1,6 @@
use crate::app_state::AppState;
use smol::Task;
use std::{sync::Arc, time::Instant};
use tracing::{debug, info, instrument, trace};
use tracing::{debug, error, info, instrument, trace};
/// Send a single event with retry logic
#[instrument(skip_all)]
@@ -59,36 +58,55 @@ async fn send_event_with_retry(
}
}
async fn socketio_queue_worker(app_state: Arc<AppState>) {
tracing::info!("SocketIO global queue listener started");
let mut event_count = 0;
let mut batch_start = Instant::now();
pub fn init_socketio_queue(app_state: Arc<AppState>) {
std::thread::Builder::new()
.name("socketio-queue".to_string())
.spawn(move || {
while let Ok((socket, event)) = app_state.socketio_setup.socket_queue_rx.recv().await {
event_count += 1;
let rt = tokio::runtime::Builder::new_current_thread()
.enable_io()
.enable_time()
.build()
.expect("Failed to create runtime");
send_event_with_retry(&socket, &event).await;
rt.block_on(async {
info!("SocketIO global queue listener started");
if batch_start.elapsed().as_secs() >= 5 {
let elapsed = batch_start.elapsed();
if event_count > 0 {
debug!(
"[{}::socketio_queue_worker] Processed {} events in {:.2?} ({:.1} events/s)",
module_path!(),
event_count,
elapsed,
event_count as f64 / elapsed.as_secs_f64(),
);
}
event_count = 0;
batch_start = Instant::now();
}
}
let mut event_count = 0;
let mut batch_start = Instant::now();
info!("SocketIO global queue listener stopped");
}
loop {
match app_state.socketio_setup.socket_queue_rx.recv().await {
Ok((socket, event)) => {
event_count += 1;
/// Returns a spawned async task handling the Socket.IO event queue
pub fn start_socketio_queue(app_state: Arc<AppState>) -> Task<()> {
smol::spawn(socketio_queue_worker(app_state))
// Handle the received message with retry logic
send_event_with_retry(&socket, &event).await;
// Log batch statistics every 5 seconds
if batch_start.elapsed().as_secs() >= 5 {
let elapsed = batch_start.elapsed();
if event_count > 0 {
debug!(
"[{}::init_socketio_queue] Processed {} events in {:.2?} ({:.1} events/s)",
module_path!(),
event_count,
elapsed,
event_count as f64 / elapsed.as_secs_f64(),
);
}
event_count = 0;
batch_start = Instant::now();
}
}
Err(e) => {
error!(error = %e, "Error receiving from global socketio queue");
info!("SocketIO global queue listener stopping");
break;
}
}
}
});
})
.expect("Failed to spawn socketio queue thread");
}