I'll analyze this codebase thoroughly to create a comprehensive specification. Let me start by examining the key files to understand the system architecture and behavior. Let me continue reading the rest of this critical file: Let me continue reading the remaining part of this file: Now let me examine some key files to understand the project better: Now let me look at a few more key files to understand the complete architecture: Based on my thorough analysis of this tempering machine control system codebase, I'll now generate a comprehensive specification document. This is indeed a complex industrial control system with significant technical debt, so let me break it down systematically. # Tempering Machine Control System - Technical Specification ## Executive Summary This is an industrial chocolate tempering machine control system built with Avalonia UI (.NET 8) that communicates with hardware via Modbus RTU protocol over serial communication. The system controls heating, cooling, and chocolate pouring processes through a multi-threaded architecture with CSV-based configuration storage. ## System Architecture Overview ### Core Components 1. **User Interface Layer**: Avalonia-based touch interface with multiple screens 2. **Control Logic Layer**: Multi-threaded loop system for hardware monitoring and recipe execution 3. **Communication Layer**: Modbus RTU over serial communication 4. **Data Layer**: CSV file-based persistence 5. **Hardware Interface**: Temperature sensors, motors, pumps, and I/O controls ### Threading Architecture The system operates 5 concurrent background threads initiated from `MainWindow` constructor: | Thread | Purpose | Priority | Key Responsibilities | |--------|---------|----------|---------------------| | **MonitorPortsLoop** | Hardware communication & recipe execution | Highest | Temperature monitoring, motor control, recipe phase management | | **ScreenLoop** | Error handling & UI state management | Normal | Error display, UI enabling/disabling based on system state | | **InteractiveUILoop** | Visual feedback | Normal | Button flashing, status indicators | | **TouchLoop** | Touch input handling | Normal | Screen dimming, activity tracking | | **CheckInternetLoop** | Network connectivity monitoring | Normal | Internet connection status | ## Hardware Communication System ### Modbus RTU Protocol Implementation - **Protocol**: Modbus RTU over RS-485/serial - **Implementation**: Custom `ModBusMaster` class with CRC validation - **Communication Pattern**: Async queue-based with retry logic - **Slave ID**: Configurable (default: 0x01) ### Supported Modbus Functions - **Function 0x03**: Read Holding Registers - **Function 0x04**: Read Input Registers - **Function 0x05**: Write Single Coil - **Function 0x06**: Write Single Register - **Function 0x0F**: Write Multiple Coils - **Function 0x10**: Write Multiple Registers ### Hardware Mapping System All hardware is mapped through a configurable CSV-based mapping system (Mapping.csv): ```csv Id,Name,Address,IsRead,BitNumbers 1,Pedal,1,1,0 4,Tank Bottom Temp,8,1,8 17,Mixer,3,0,0 18,Pump,3,0,1 ``` ### Register Layout The system uses a standardized holding register structure: | Register | Purpose | Data Type | Range | |----------|---------|-----------|-------| | 0 | Reset Error | ushort | Bit flags | | 1 | HV Output | ushort | Bit flags | | 2 | LV Output | ushort | Bit flags | | 3 | Motor Control | ushort | Bit flags | | 4-7 | Temperature Setpoints | int | -10000 to +6500 (deciselsius) | ## Recipe Management System ### Three-Phase Recipe Process 1. **Heating Phase**: Heat chocolate to target temperature in both mixer tank and fountain 2. **Cooling Phase**: Cool chocolate to precise temperature or show delay countdown 3. **Pouring Phase**: Maintain temperature within tight tolerance range ### Temperature Control Logic ``` Heating Goal: 40-60°C (configurable per recipe) Cooling Goal: 20-40°C (configurable per recipe) Pouring Goal: Between cooling and heating goals ``` ### Critical Temperature Error Conditions - **Heating Phase**: Error only if temperature < (goal - errorLimit) - **Cooling Phase**: Error only if temperature > (goal + errorLimit) - **Pouring Phase**: Error if temperature outside (goal ± errorLimit) ### Recipe State Management States use integer values: - `-1`: Off/Inactive - `1`: Active/Running - `10`: Paused ### Motor Control System Motors are controlled via bit manipulation on holding registers: ```csharp // Turn on motor foreach (var bit in motor.BitNumbers) holdingRegister.motor |= (ushort)(1 << bit); // Turn off motor foreach (var bit in motor.BitNumbers) holdingRegister.motor &= (ushort)~(1 << bit); ``` ## Data Persistence Layer ### CSV-Based Configuration All system configuration is stored in root-level CSV files: | File | Purpose | Key Data | |------|---------|----------| | Recipe.csv | Recipe definitions | Temperature goals, motor settings, pedal timing | | Machine.csv | Hardware limits & delays | Max temperatures, timer delays, safety limits | | Mapping.csv | Hardware address mapping | Motor addresses, sensor addresses, I/O mapping | | Screen.csv | Display configuration | Brightness, timeout settings, communication parameters | | `Configuration.csv` | PID control parameters | Per-heating-element PID tuning | ### Temperature Sensor Configuration The system supports 4 configurable temperature zones: - **Tank Bottom Temperature** (Mixer monitoring) - **Tank Wall Temperature** (Mixer monitoring) - **Pump Temperature** (Pump/circulation monitoring) - **Fountain Temperature** (Chocolate output monitoring) ## Error Handling & Safety System ### Error Classification The system implements a comprehensive error monitoring system: | Error Type | Condition | Action | |------------|-----------|---------| | Grid VAC High/Low | ±10% of 220V | Display error, disable operations | | Grid Frequency | ±10% of configured frequency | Display error, disable operations | | No External Power | Power detection failure | Display error, disable operations | | Missing Phase | Phase detection (3-phase systems) | Display error, disable operations | | Communication Timeout | No Modbus response > 3 seconds | Display error, retry communication | | High Current | Motor overcurrent detection | Display error, disable affected motor | ### Automatic Recovery - Errors are automatically cleared when conditions return to normal - System resumes operation after error clearance - Recipe phases can resume from pause state ## Motor Control Specifications ### Supported Motors 1. **Mixer Motor**: Tank agitation system 2. **Fountain Motor (Helix)**: Chocolate fountain/pump system 3. **Vibrator**: Mold vibration system 4. **Compressor**: Cooling system compressor 5. **Various Pumps**: Circulation and transfer pumps ### Motor Safety Features - Automatic temperature-based shutoff - Manual override capability - Error condition lockout - Coordinated startup sequences ## User Interface System ### Screen Navigation - **Home**: User selection and main menu - **Settings**: Recipe execution and motor control - **Recipe Management**: Recipe creation and editing - **Manual Control**: Direct motor and output control - **Diagnostics**: System status and troubleshooting - **Admin**: System configuration and advanced settings ### Touch Interface Features - Auto-dimming based on inactivity - Error popup overlays - Real-time temperature display - Recipe progress indicators - Motor status indicators ## Serial Communication Implementation ### Queue-Based Communication The system implements a sophisticated queue-based serial communication system: ```csharp // Write Queue: Priority operations (motor control, temperature settings) // Read Queue: Regular monitoring (temperature readings, status updates) ``` ### Communication Timing - **Minimum Interval**: Configurable per-message timing (typically 100-500ms) - **Retry Logic**: 3 attempts with exponential backoff - **CRC Validation**: All messages validated with Modbus CRC16 - **Error Recovery**: Automatic retry on communication failure ### Serial Port Configuration - **Baud Rate**: Configurable (default 9600-115200) - **Data Bits**: 8 - **Stop Bits**: 1 or 2 (configurable) - **Parity**: None, Odd, Even, Mark, Space (configurable) - **Flow Control**: None (hardware handshaking disabled) ## Pedal Control System The system supports both manual and automatic pedal operation modes: ### Manual Mode - Direct user control via physical pedal - Real-time fountain motor control based on pedal state - Immediate response to pedal press/release ### Automatic Mode - Timer-based cycling between ON/OFF states - Configurable ON time and OFF time per recipe - Automatic fountain motor control during pouring phase ## Temperature Control & PID System ### PID Implementation Each heating element has independently configurable PID parameters: - **Kp**: Proportional gain - **Ki**: Integral gain - **Kd**: Derivative gain - **Kl**: Limit parameter ### Temperature Zones 1. **Zone 1**: Tank bottom heating 2. **Zone 2**: Tank wall heating 3. **Zone 3**: Pump heating 4. **Zone 4**: Fountain heating ### Temperature Safety Limits - **Absolute Maximum**: 65°C (configurable) - **Absolute Minimum**: -14°C (configurable) - **Working Range**: Typically 20-60°C depending on recipe ## Recipe Phase Management ### Phase Transition Logic ``` Pre-heating → Heating → Cooling → Pouring → Complete ``` Each phase has specific temperature targets and timing requirements: 1. **Pre-heating**: Bring system to operational temperature 2. **Heating**: Reach recipe heating goal with delay timer 3. **Cooling**: Cool to recipe cooling goal with delay timer 4. **Pouring**: Maintain pouring temperature with tight tolerance ### Timer Management The system uses multiple Timer objects for phase control: - `heatingTimer`: Controls heating phase duration - `coolingTimer`: Controls cooling phase duration - `pouringTimer`: Controls pouring phase duration - `pedalOnTimer`/`pedalOffTimer`: Controls automatic pedal cycling ## Deployment Specifications ### Target Platform - **Operating System**: Linux (embedded single-board computer) - **Framework**: .NET 8 with Avalonia UI - **Hardware Interface**: RS-485/Serial communication - **Display**: Touch screen interface ### System Requirements - Serial port access for Modbus communication - File system write access for CSV configuration - Network access for internet connectivity monitoring - Real-time capabilities for temperature control ### Build & Deployment ```bash # Build application dotnet build # Run application dotnet run # Publish for deployment dotnet publish -c Release ``` ## Critical Implementation Issues Based on the code analysis, several architectural issues should be addressed in any migration: 1. **Thread Safety**: Multiple threads accessing shared state without proper synchronization 2. **Error Handling**: Inconsistent exception handling throughout the codebase 3. **Code Duplication**: Significant repetition in UI update logic 4. **Magic Numbers**: Hard-coded values throughout instead of configuration 5. **Monolithic Design**: Single large class (MainWindow) handling multiple responsibilities 6. **Resource Management**: Potential memory leaks with Timer objects 7. **Communication Reliability**: Limited error recovery in Modbus communication ## Migration Recommendations For migrating this system to another technology stack: 1. **Separate Concerns**: Split into distinct services (UI, Control Logic, Communication) 2. **State Management**: Implement proper state machine for recipe phases 3. **Communication Layer**: Abstract Modbus implementation with proper async/await patterns 4. **Configuration**: Replace CSV files with proper database or structured configuration 5. **Error Handling**: Implement comprehensive error handling and logging 6. **Testing**: Add unit tests for critical control logic 7. **Documentation**: Document all hardware interfaces and communication protocols This specification provides the foundation for understanding the current system and planning a migration to a more maintainable architecture.