commit f539289f45ec456bf9c6c0d8b93ee805c175fee3 Author: Sami Alzein Date: Wed Aug 6 21:21:34 2025 +0200 Refactor code structure for improved readability and maintainability diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000..f4d9f79 --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,124 @@ +# Tempering Machine Avalonia - AI Agent Instructions + +## Project Overview +Industrial chocolate tempering machine control application built with Avalonia UI (.NET 8). Controls hardware via Modbus RTU over serial communication for chocolate heating, cooling, and pouring processes. + +## Core Architecture + +### Thread-Based Loop System +The application runs 5 concurrent background threads from `MainWindow` constructor: +- **MonitorPortsLoop**: Hardware communication & recipe execution (highest priority) +- **ScreenLoop**: Error handling & UI state management +- **InteractiveUILoop**: Visual feedback (flashing buttons/indicators) +- **TouchLoop**: Touch input handling for screen dimming +- **CheckInternetLoop**: Network connectivity monitoring + +### Hardware Communication Stack +``` +Recipe Logic → MainWindow → ModBusMaster → Serial Port → Hardware +``` +- **ModBusMaster**: Implements Modbus RTU protocol with CRC validation +- **serialThreadLoop**: Async queue-based serial communication with retry logic +- **HoldingRegister**: State object for motor control, temperature setpoints, and outputs + +### Data Persistence (CSV-based) +All configuration stored in root CSV files, managed by `DataBase/` classes: +- `Recipe.csv`: Temperature goals, motor settings, pedal timing +- `Machine.csv`: Hardware limits, delays, pre-heating settings +- `Mapping.csv`: Hardware address mapping (motors, sensors, I/O) +- `Screen.csv`: Display settings, communication parameters +- `Configration.csv`: PID control parameters per heating element + +## Recipe System Architecture + +### Three-Phase Process +1. **Heating Phase**: Reach target temperature (both mixer tank + chocolate fountain) +2. **Cooling Phase**: Cool to precise temperature or show delay if already at target +3. **Pouring Phase**: Maintain temperature within tight range + +### Critical Temperature Logic +- **Heating**: Error only if temperature < (goal - errorLimit) +- **Cooling**: Error only if temperature > (goal + errorLimit) +- **Pouring**: Error if temperature outside (goal ± errorLimit) + +### State Management +Recipe phases use integer states: `-1` (off), `1` (active), `10` (paused) +Timers control phase transitions with automatic goal checking. + +## Hardware Mapping System + +### Bit-Based Motor Control +Motors controlled via bit manipulation on `holdingRegister.motor`: +```csharp +// Turn on motor +foreach (var bit in motor.BitNumbers) + holdingRegister.motor |= (ushort)(1 << bit); +``` + +### Temperature Control +Four temperature setpoints (`setTemp1-4`) mapped to heating elements: +- Tank Bottom/Wall, Pump, Fountain temperatures +- Values in deciselsius (multiply by 10) +- `-10000` = disabled/off + +### I/O Mapping +- Input registers: Temperature sensors, pedal, safety switches +- Output registers: Motors, heaters, alarms +- Mapping defined in `Mapping.csv` with address + bit number pairs + +## Key Development Patterns + +### Async UI Updates +Always use `Dispatcher.UIThread.Post()` for UI updates from background threads: +```csharp +Dispatcher.UIThread.Post(() => { + footerMsg.Text = "Status message"; +}); +``` + +### Serial Communication +Use queue-based system via `serialThreadLoop.EnqueueWrite/Read()` - never write directly to port. + +### Error Handling +Errors use enum-based system (`Error.GridCondition`) with automatic display/removal via `ScreenLoop`. + +### Temperature Validation +Recipe editing enforces logical constraints: +- Heating: 40-60°C +- Cooling: 20-40°C +- Pouring: between cooling and heating goals + +## Build & Debug + +### Development Setup +- Standard .NET 8 Avalonia project +- Build: `dotnet build` or Visual Studio +- Run: `dotnet run` from `DaireApplication/` directory + +### Hardware Testing +Serial communication requires actual hardware or simulator. Debug logs in `serialThreadLoop` show Modbus traffic. + +### Common Issues +- Serial port permissions on Linux +- Temperature sensor calibration +- Recipe phase transitions depend on precise timing +- CSV file corruption breaks app initialization + +## File Organization Priorities + +When modifying: +1. **Recipe logic**: `MainWindow.axaml.cs` (MonitorPortsLoop method) +2. **UI views**: `Views/UserController/` directory +3. **Hardware mapping**: `DataBase/Mapping.cs` + root `Mapping.csv` +4. **Serial communication**: `Loops/serialThreadLoop.cs` +5. **Error handling**: `ViewModels/Error.cs` + `Loops/ScreenLoop.cs` + +## Critical Implementation Notes + +- Recipe temperature goals are validated on save, not on start +- Motor state changes require serial write to take effect +- Phase transitions happen automatically based on temperature + time +- CSV files auto-migrate missing columns via `DataPathManager.MigrateCsvFiles()` +- Thread safety critical - all hardware state changes go through main monitor loop + +Focus on the interplay between recipe logic, hardware communication, and real-time UI updates when making changes. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0115f5d --- /dev/null +++ b/.gitignore @@ -0,0 +1,78 @@ +# Ignore Visual Studio-specific files +.vs/ +*.suo +*.user +*.userosscache +*.sln.docstates + +# Ignore build output +bin/ +obj/ + +# Ignore Rider-specific files +.idea/ +*.iml + +# Ignore Avalonia-specific files +Generated/ +.avalonia/ + +# Ignore NuGet packages +*.nupkg +*.snupkg +packages/ + +# Ignore logs and debug files +*.log +logs/ + +# Ignore environment files +.env +.env.local +.env.*.local + +# Ignore temporary files +*.tmp +*.bak +*.swp + +# Ignore Rider and Resharper +**/.idea/ +**/.vs/ +**/.resharper/ +**/_ReSharper*/ +**/ReSharper*/ +**/ResharperHost/ + +# Ignore DotNet tools +.nuke/ +.nuke.temp/ +.dotnet-tools/ + +# Ignore build artifacts +*.exe +*.dll +*.pdb +*.ilk +*.obj +*.so +*.idb +*.lib +*.dylib +*.a +*.exp +*.o +*.iobj +*.ipdb + +# Ignore coverage reports +coverage/ +*.coverage +*.coveragexml + +# Ignore dependency files +node_modules/ +package-lock.json + +# Ignore Mono and JetBrains Rider-related files +mono_crash.* diff --git a/Configration.csv b/Configration.csv new file mode 100644 index 0000000..2ec2168 --- /dev/null +++ b/Configration.csv @@ -0,0 +1,5 @@ +Id,Max,Min,H_out,C_out,kp,ki,kd,kl,Name +1,0,0,4,-1,0,0,0,0,Tank Heater Bottom +2,0,0,5,-1,0,0,0,0,Tank Heater Wall +3,0,0,3,2,0,0,0,0,Pump Heater +4,0,0,4|5|3,2,0,0,0,0, diff --git a/DaireApplication.sln b/DaireApplication.sln new file mode 100644 index 0000000..4897487 --- /dev/null +++ b/DaireApplication.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.10.35013.160 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DaireApplication", "DaireApplication\DaireApplication.csproj", "{DA99F148-6A84-4C76-9DA1-73A9FF7ADCBB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {DA99F148-6A84-4C76-9DA1-73A9FF7ADCBB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DA99F148-6A84-4C76-9DA1-73A9FF7ADCBB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DA99F148-6A84-4C76-9DA1-73A9FF7ADCBB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DA99F148-6A84-4C76-9DA1-73A9FF7ADCBB}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {CA811FD3-EF83-4D48-9173-EA545A7C1D44} + EndGlobalSection +EndGlobal diff --git a/DaireApplication/App.axaml b/DaireApplication/App.axaml new file mode 100644 index 0000000..6f4b603 --- /dev/null +++ b/DaireApplication/App.axaml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/DaireApplication/App.axaml.cs b/DaireApplication/App.axaml.cs new file mode 100644 index 0000000..2948c32 --- /dev/null +++ b/DaireApplication/App.axaml.cs @@ -0,0 +1,32 @@ +using Avalonia; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Markup.Xaml; +using DaireApplication.ViewModels; +using DaireApplication.Views; + +namespace DaireApplication +{ + public partial class App : Application + { + public override void Initialize() + { + AvaloniaXamlLoader.Load(this); + } + public override void OnFrameworkInitializationCompleted() + { + // Migrate CSV files by adding missing columns with default values + DataBase.DataPathManager.MigrateCsvFiles(); + + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + { + desktop.MainWindow = new MainWindow + { + DataContext = new MainWindowViewModel(), + }; + } + + base.OnFrameworkInitializationCompleted(); + } + + } +} \ No newline at end of file diff --git a/DaireApplication/Assets/AdminGraph.png b/DaireApplication/Assets/AdminGraph.png new file mode 100644 index 0000000..2ca30c7 Binary files /dev/null and b/DaireApplication/Assets/AdminGraph.png differ diff --git a/DaireApplication/Assets/AdminMachine.png b/DaireApplication/Assets/AdminMachine.png new file mode 100644 index 0000000..6a3847b Binary files /dev/null and b/DaireApplication/Assets/AdminMachine.png differ diff --git a/DaireApplication/Assets/Board.png b/DaireApplication/Assets/Board.png new file mode 100644 index 0000000..f9b18b9 Binary files /dev/null and b/DaireApplication/Assets/Board.png differ diff --git a/DaireApplication/Assets/Fonts/HLL.ttf b/DaireApplication/Assets/Fonts/HLL.ttf new file mode 100644 index 0000000..a8da1e5 Binary files /dev/null and b/DaireApplication/Assets/Fonts/HLL.ttf differ diff --git a/DaireApplication/Assets/Fonts/Helvetica.ttf b/DaireApplication/Assets/Fonts/Helvetica.ttf new file mode 100644 index 0000000..718f22d Binary files /dev/null and b/DaireApplication/Assets/Fonts/Helvetica.ttf differ diff --git a/DaireApplication/Assets/Home.png b/DaireApplication/Assets/Home.png new file mode 100644 index 0000000..6fb4637 Binary files /dev/null and b/DaireApplication/Assets/Home.png differ diff --git a/DaireApplication/Assets/LeftArrow.png b/DaireApplication/Assets/LeftArrow.png new file mode 100644 index 0000000..7df4a9b Binary files /dev/null and b/DaireApplication/Assets/LeftArrow.png differ diff --git a/DaireApplication/Assets/LineDots.png b/DaireApplication/Assets/LineDots.png new file mode 100644 index 0000000..3a5679a Binary files /dev/null and b/DaireApplication/Assets/LineDots.png differ diff --git a/DaireApplication/Assets/Logo.png b/DaireApplication/Assets/Logo.png new file mode 100644 index 0000000..a0918b9 Binary files /dev/null and b/DaireApplication/Assets/Logo.png differ diff --git a/DaireApplication/Assets/Machine.png b/DaireApplication/Assets/Machine.png new file mode 100644 index 0000000..524d1d0 Binary files /dev/null and b/DaireApplication/Assets/Machine.png differ diff --git a/DaireApplication/Assets/Manual.png b/DaireApplication/Assets/Manual.png new file mode 100644 index 0000000..94e4986 Binary files /dev/null and b/DaireApplication/Assets/Manual.png differ diff --git a/DaireApplication/Assets/ManualControlMachine.png b/DaireApplication/Assets/ManualControlMachine.png new file mode 100644 index 0000000..95e8f60 Binary files /dev/null and b/DaireApplication/Assets/ManualControlMachine.png differ diff --git a/DaireApplication/Assets/Plus.png b/DaireApplication/Assets/Plus.png new file mode 100644 index 0000000..368d365 Binary files /dev/null and b/DaireApplication/Assets/Plus.png differ diff --git a/DaireApplication/Assets/RedUpArrow.png b/DaireApplication/Assets/RedUpArrow.png new file mode 100644 index 0000000..3f5055e Binary files /dev/null and b/DaireApplication/Assets/RedUpArrow.png differ diff --git a/DaireApplication/Assets/RightArrow.png b/DaireApplication/Assets/RightArrow.png new file mode 100644 index 0000000..f174b8e Binary files /dev/null and b/DaireApplication/Assets/RightArrow.png differ diff --git a/DaireApplication/Assets/Settings.png b/DaireApplication/Assets/Settings.png new file mode 100644 index 0000000..a556b57 Binary files /dev/null and b/DaireApplication/Assets/Settings.png differ diff --git a/DaireApplication/Assets/TempArrow.png b/DaireApplication/Assets/TempArrow.png new file mode 100644 index 0000000..0d0da63 Binary files /dev/null and b/DaireApplication/Assets/TempArrow.png differ diff --git a/DaireApplication/Assets/TemperingGraphics.png b/DaireApplication/Assets/TemperingGraphics.png new file mode 100644 index 0000000..aff9ec6 Binary files /dev/null and b/DaireApplication/Assets/TemperingGraphics.png differ diff --git a/DaireApplication/Assets/TemperingMachine.png b/DaireApplication/Assets/TemperingMachine.png new file mode 100644 index 0000000..55c2ad4 Binary files /dev/null and b/DaireApplication/Assets/TemperingMachine.png differ diff --git a/DaireApplication/Assets/UpArrow.png b/DaireApplication/Assets/UpArrow.png new file mode 100644 index 0000000..3c185f7 Binary files /dev/null and b/DaireApplication/Assets/UpArrow.png differ diff --git a/DaireApplication/Assets/avalonia-logo.ico b/DaireApplication/Assets/avalonia-logo.ico new file mode 100644 index 0000000..da8d49f Binary files /dev/null and b/DaireApplication/Assets/avalonia-logo.ico differ diff --git a/DaireApplication/Assets/bluePlug.png b/DaireApplication/Assets/bluePlug.png new file mode 100644 index 0000000..aa3acac Binary files /dev/null and b/DaireApplication/Assets/bluePlug.png differ diff --git a/DaireApplication/Assets/errorIcon.png b/DaireApplication/Assets/errorIcon.png new file mode 100644 index 0000000..32217b3 Binary files /dev/null and b/DaireApplication/Assets/errorIcon.png differ diff --git a/DaireApplication/Assets/greenPlug.png b/DaireApplication/Assets/greenPlug.png new file mode 100644 index 0000000..1ef1337 Binary files /dev/null and b/DaireApplication/Assets/greenPlug.png differ diff --git a/DaireApplication/Assets/homeTrack.png b/DaireApplication/Assets/homeTrack.png new file mode 100644 index 0000000..6e89eb8 Binary files /dev/null and b/DaireApplication/Assets/homeTrack.png differ diff --git a/DaireApplication/Assets/icons8-green-circle-48.png b/DaireApplication/Assets/icons8-green-circle-48.png new file mode 100644 index 0000000..274b745 Binary files /dev/null and b/DaireApplication/Assets/icons8-green-circle-48.png differ diff --git a/DaireApplication/Assets/icons8-red-circle-48.png b/DaireApplication/Assets/icons8-red-circle-48.png new file mode 100644 index 0000000..c4080c7 Binary files /dev/null and b/DaireApplication/Assets/icons8-red-circle-48.png differ diff --git a/DaireApplication/Assets/orangePlug.png b/DaireApplication/Assets/orangePlug.png new file mode 100644 index 0000000..0c0242e Binary files /dev/null and b/DaireApplication/Assets/orangePlug.png differ diff --git a/DaireApplication/Assets/purplePlug.png b/DaireApplication/Assets/purplePlug.png new file mode 100644 index 0000000..3026fae Binary files /dev/null and b/DaireApplication/Assets/purplePlug.png differ diff --git a/DaireApplication/Assets/redPlug.png b/DaireApplication/Assets/redPlug.png new file mode 100644 index 0000000..15dab02 Binary files /dev/null and b/DaireApplication/Assets/redPlug.png differ diff --git a/DaireApplication/Assets/warningIcon.png b/DaireApplication/Assets/warningIcon.png new file mode 100644 index 0000000..154ff51 Binary files /dev/null and b/DaireApplication/Assets/warningIcon.png differ diff --git a/DaireApplication/Assets/wifi.png b/DaireApplication/Assets/wifi.png new file mode 100644 index 0000000..3f2237c Binary files /dev/null and b/DaireApplication/Assets/wifi.png differ diff --git a/DaireApplication/Assets/wifioff.png b/DaireApplication/Assets/wifioff.png new file mode 100644 index 0000000..69a8e28 Binary files /dev/null and b/DaireApplication/Assets/wifioff.png differ diff --git a/DaireApplication/Assets/yellowPlug.png b/DaireApplication/Assets/yellowPlug.png new file mode 100644 index 0000000..98fc614 Binary files /dev/null and b/DaireApplication/Assets/yellowPlug.png differ diff --git a/DaireApplication/Automatic_Fountain_Control_Implementation.md b/DaireApplication/Automatic_Fountain_Control_Implementation.md new file mode 100644 index 0000000..50d1ffd --- /dev/null +++ b/DaireApplication/Automatic_Fountain_Control_Implementation.md @@ -0,0 +1,294 @@ +# Automatic Fountain Control Implementation + +## Overview + +This implementation adds automatic fountain control functionality that triggers after the pouring phase completes when the pedal is in Auto mode. The fountain state is determined by the second control box (RecipeTable.Fountain property). + +## ✅ Expected Behavior + +- **After pouring phase completion** and **pedal mode set to Auto**: + - If the second control box is **checked/enabled** → Fountain should **open** + - If the second control box is **unchecked/disabled** → Fountain should **remain closed** +- **No blinking/flashing** of the Chocolate button after automatic control is established + +## 🔧 Implementation Details + +### 1. New Properties Added + +```csharp +public bool isAutomaticFountainControlActive { get; set; } = false; +``` + +This flag prevents interference between automatic fountain control and normal temperature-based fountain control. + +### 2. New Methods Added + +#### `HandleAutomaticFountainControlAfterPouring(Settings settings)` +- **Purpose**: Main orchestrator for automatic fountain control +- **Trigger**: Called when pouring phase completes +- **Logic**: + - Checks if pedal is in Auto mode (`!settings._recipeTable.Pedal.Value`) + - Reads second control box state (`settings._recipeTable.Fountain.Value`) + - Calls appropriate fountain control method + +#### `TurnOnFountainAutomatically()` +- **Purpose**: Automatically turns ON the fountain motor +- **Actions**: + - Sets fountain motor state variables + - **Sends hardware command** to turn ON fountain motor + - Updates UI to show fountain is ON + - Logs the action for debugging + +#### `TurnOffFountainAutomatically()` +- **Purpose**: Automatically turns OFF the fountain motor +- **Actions**: + - Sets fountain motor state variables + - **Sends hardware command** to turn OFF fountain motor + - Updates UI to show fountain is OFF + - Logs the action for debugging + +#### `ResetAutomaticFountainControl()` +- **Purpose**: Resets the automatic control flag +- **Usage**: Called when manual control is needed or recipe is reset + +### 3. Integration Points + +#### Pouring Phase Completion +Modified `PouringTimer` method to call automatic fountain control: + +```csharp +// Handle automatic fountain control after pouring phase completion +await HandleAutomaticFountainControlAfterPouring(result); +``` + +#### Fountain Control Logic Protection +Modified main fountain control logic to respect automatic control: + +```csharp +//Fountain Motor - Normal temperature-based control +if (checkFountainTMT_PMT && !isAutomaticFountainControlActive) +{ + // Normal temperature-based fountain control +} + +//Fountain Motor - Manual control (when not in automatic mode) +if (!checkFountainTMT_PMT && !isAutomaticFountainControlActive) +{ + // Manual fountain control +} +``` + +#### Automatic Fountain Control Processing +Added dedicated section for automatic fountain control in main monitoring loop: + +```csharp +//Fountain Motor - Automatic control (when automatic control is active) +if (isAutomaticFountainControlActive) +{ + // Handle automatic fountain control state changes + if (startFountainMotorFlashing == 0 && sendComFountainMotor == 1 && errors.Count == 0 && !isPaused) + { + // Turn ON fountain motor + // Send hardware command + // Update UI + } + else if (startFountainMotorFlashing == 1 && sendComFountainMotor == 0) + { + // Turn OFF fountain motor + // Send hardware command + // Update UI + } +} +``` + +#### Manual Override +Modified `FountainClick` method to reset automatic control when user manually controls fountain: + +```csharp +// Reset automatic fountain control flag when user manually controls fountain +if (isAutomaticFountainControlActive) +{ + ResetAutomaticFountainControl(); +} +``` + +#### Recipe Lifecycle Management +- **Recipe Start**: Resets automatic control flag +- **Recipe Stop**: Resets automatic control flag + +## 🔄 Control Flow + +1. **Recipe Execution**: Normal recipe phases (heating → cooling → pouring) +2. **Pouring Phase Completion**: + - Recipe timer completes + - Pedal control is set based on recipe settings + - **NEW**: Automatic fountain control is triggered +3. **Automatic Fountain Control**: + - Checks pedal mode (must be Auto) + - Checks second control box state + - Sets fountain state accordingly + - **Sends hardware commands** to control fountain motor + - Sets flag to prevent interference +4. **Hardware Control**: Main monitoring loop processes automatic control commands +5. **Manual Override**: User can manually control fountain, which resets automatic control + +## 🛡️ Safety Features + +1. **Flag Protection**: Automatic control flag prevents conflicts with normal fountain control +2. **Manual Override**: Users can always take manual control +3. **Recipe Reset**: Automatic control is reset when starting/stopping recipes +4. **Error Handling**: Comprehensive try-catch blocks with logging +5. **UI Updates**: Visual feedback shows fountain state changes +6. **Hardware Commands**: Direct hardware control ensures fountain state changes are executed + +## 🚫 Blinking Prevention + +### Issue Fixed +The "Chocolate" button was blinking/toggling after pouring phase completion due to conflicting fountain control mechanisms. + +### Solution Implemented + +#### 1. **Flashing Flag Protection** +Modified automatic fountain control to set `startFountainMotorFlashing = -1` instead of `1`: + +```csharp +// In TurnOffFountainAutomatically() +startFountainMotorFlashing = -1; // Prevent flashing in automatic mode +``` + +#### 2. **InteractiveUILoop Protection** +Added automatic control check to prevent flashing in UI loop: + +```csharp +// In InteractiveUILoop.cs +if (_mainWindow.startFountainMotorFlashing == 1 && !_mainWindow.isAutomaticFountainControlActive) +{ + // Only flash when not in automatic control mode +} +``` + +#### 3. **Temperature-Based Control Protection** +Added automatic control checks to prevent normal fountain control from interfering: + +```csharp +// Prevent normal fountain control from setting flashing when automatic control is active +if (!isAutomaticFountainControlActive) +{ + startFountainMotorFlashing = 1; +} +``` + +#### 4. **Flashing Processing Protection** +Added automatic control check to flashing processing logic: + +```csharp +if (startFountainMotorFlashing == 1 && !isAutomaticFountainControlActive) +{ + // Only process flashing when not in automatic control mode +} +``` + +### Result +- **No more blinking** of the Chocolate button after automatic control is established +- **Steady state** maintained based on second control box value +- **Clean visual feedback** without distracting flashing animations + +## 📝 Debugging + +The implementation includes debug logging for: +- Automatic fountain control activation +- Fountain state changes (ON/OFF) +- Hardware command execution +- Flag resets +- Error conditions + +## 🧪 Testing Scenarios + +### Scenario 1: Second Box Checked, Auto Mode +1. Start recipe with second control box enabled +2. Complete pouring phase +3. **Expected**: Fountain turns ON automatically and chocolate flows (no blinking) + +### Scenario 2: Second Box Unchecked, Auto Mode +1. Start recipe with second control box disabled +2. Complete pouring phase +3. **Expected**: Fountain remains OFF and chocolate flow stops (no blinking) + +### Scenario 3: Manual Mode +1. Start recipe in manual pedal mode +2. Complete pouring phase +3. **Expected**: No automatic fountain control (manual control only) + +### Scenario 4: Manual Override +1. Complete recipe with automatic fountain control active +2. Manually click fountain button +3. **Expected**: Automatic control is reset, manual control takes over + +### Scenario 5: No Blinking Verification +1. Complete recipe with automatic fountain control +2. **Expected**: Chocolate button remains steady (ON or OFF) without blinking + +## 🔧 Configuration + +The second control box is configured through the `RecipeTable.Fountain` property: +- `true` = Fountain should be ON after pouring +- `false` = Fountain should be OFF after pouring + +## 🔧 Key Fixes Applied + +### Issue: Fountain State Not Changing +**Problem**: Automatic control was setting state variables but not sending hardware commands. + +**Solution**: +1. **Direct Hardware Control**: Modified `TurnOnFountainAutomatically()` and `TurnOffFountainAutomatically()` to send actual hardware commands +2. **Dedicated Processing**: Added automatic fountain control section in main monitoring loop +3. **State Synchronization**: Ensured UI updates and hardware commands are synchronized + +### Issue: Chocolate Button Blinking +**Problem**: The Chocolate button was blinking/toggling after pouring phase completion. + +**Solution**: +1. **Flashing Flag Control**: Set `startFountainMotorFlashing = -1` in automatic control to prevent flashing +2. **UI Loop Protection**: Added automatic control check to InteractiveUILoop +3. **Temperature Control Protection**: Prevented normal fountain control from interfering +4. **Flashing Processing Protection**: Added automatic control check to flashing processing logic + +### Hardware Command Implementation +```csharp +// Turn ON fountain motor +var fount = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); +if (fount != null && fount.BitNumbers.Count > 0) +{ + foreach (var bit in fount.BitNumbers) + { + holdingRegister.motor |= (ushort)(1 << bit); + } + await WriteToSerialAsync("Automatic Fountain On"); +} + +// Turn OFF fountain motor +var fount = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); +if (fount != null && fount.BitNumbers.Count > 0) +{ + foreach (var bit in fount.BitNumbers) + { + holdingRegister.motor &= (ushort)~(1 << bit); + } + await WriteToSerialAsync("Automatic Fountain Off"); +} +``` + +## 📋 Requirements Met + +✅ **Automatic triggering** after pouring phase completion +✅ **Pedal mode detection** (Auto mode only) +✅ **Second control box integration** (RecipeTable.Fountain) +✅ **Dynamic fountain control** (open/close based on box state) +✅ **Hardware command execution** (actual fountain motor control) +✅ **No interference** with existing fountain control logic +✅ **Manual override capability** +✅ **Proper error handling and logging** +✅ **UI feedback** for fountain state changes +✅ **Chocolate flow control** (stops/starts based on fountain state) +✅ **No blinking/flashing** of Chocolate button after automatic control +✅ **Steady state maintenance** based on second control box value \ No newline at end of file diff --git a/DaireApplication/DaireApplication.csproj b/DaireApplication/DaireApplication.csproj new file mode 100644 index 0000000..ffed958 --- /dev/null +++ b/DaireApplication/DaireApplication.csproj @@ -0,0 +1,75 @@ + + + WinExe + net8.0 + enable + true + app.manifest + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + None + All + + + + + + + + + + + + + + + + + + diff --git a/DaireApplication/DataBase/ConfigrationTable.cs b/DaireApplication/DataBase/ConfigrationTable.cs new file mode 100644 index 0000000..c2fe0ac --- /dev/null +++ b/DaireApplication/DataBase/ConfigrationTable.cs @@ -0,0 +1,202 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; + +namespace DaireApplication.DataBase; + +public class ConfigrationTable +{ + public int Id { get; set; } + public int Max { get; set; } = 0; + public int Min { get; set; } = 0; + public List H_out { get; set; } = new(); + public List FC_out { get; set; } = new(); + public List SC_out { get; set; } = new(); + public int kp { get; set; } = 0; + public int ki { get; set; } = 0; + public int kd { get; set; } = 0; + public int kl { get; set; } = 0; + public string name { get; set; } = ""; + public float i_neut { get; set; } = 0; + public float i_mot1 { get; set; } = 0; + public float i_mot2 { get; set; } = 0; + public float FC_Threshold { get; set; } = 3; + public float HeatConRange { get; set; } = 50; + + public List ReadConfigrations() + { + string filePath = DataPathManager.GetDataFilePath("Configration.csv"); + List configrations = new List(); + + if (File.Exists(filePath)) + { + using StreamReader reader = new(filePath); + string header = reader.ReadLine(); + while (!reader.EndOfStream) + { + string[] columns = reader.ReadLine().Split(','); + configrations.Add(new ConfigrationTable + { + Id = int.Parse(columns[0]), + Max = int.Parse(columns[1]), + Min = int.Parse(columns[2]), + H_out = columns[3].Split('|', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList(), + FC_out = columns[4].Split('|', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList(), + SC_out = columns[5].Split('|', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList(), + kp = int.Parse(columns[6]), + ki = int.Parse(columns[7]), + kd = int.Parse(columns[8]), + kl = int.Parse(columns[9]), + name=columns[10], + i_neut= float.Parse(columns[11]), + i_mot1= float.Parse(columns[12]), + i_mot2= float.Parse(columns[13]), + FC_Threshold = float.Parse(columns[14]), + HeatConRange = float.Parse(columns[15]), + }); + } + return configrations; + } + return null; + } + + public int GetMaxId() + { + string filePath = DataPathManager.GetDataFilePath("Configration.csv"); + if (File.Exists(filePath)) + { + return File.ReadAllLines(filePath) + .Select(line => line.Split(',')) + .Where(columns => columns.Length > 0) + .Select(columns => int.TryParse(columns[0], out int id) ? id : 0) + .Max(); + } + return -1; + } + + public ConfigrationTable ReadConfigrationById(string id) + { + string filePath = DataPathManager.GetDataFilePath("Configration.csv"); + if (File.Exists(filePath)) + { + foreach (var line in File.ReadLines(filePath)) + { + string[] columns = line.Split(','); + if (columns[0] == id) + { + return new ConfigrationTable + { + Id = int.Parse(columns[0]), + Max = int.Parse(columns[1]), + Min = int.Parse(columns[2]), + H_out = columns[3].Split('|', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList(), + FC_out = columns[4].Split('|', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList(), + SC_out = columns[5].Split('|', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList(), + kp = int.Parse(columns[6]), + ki = int.Parse(columns[7]), + kd = int.Parse(columns[8]), + kl = int.Parse(columns[9]), + name=columns[10], + i_neut = float.Parse(columns[11]), + i_mot1 = float.Parse(columns[12]), + i_mot2 = float.Parse(columns[13]), + FC_Threshold = float.Parse(columns[14]), + HeatConRange = float.Parse(columns[15]), + }; + } + } + } + return null; + } + + public bool AddConfigration(ConfigrationTable data) + { + string filePath = DataPathManager.GetDataFilePath("Configration.csv"); + if (File.Exists(filePath)) + { + string newEntry = string.Join(",", [ + GetMaxId() + 1, + data.Max, + data.Min, + string.Join("|", data.H_out), + string.Join("|", data.FC_out), + string.Join("|", data.SC_out), + data.kp, + data.ki, + data.kd, + data.kl, + data.name, + data.i_neut, + data.i_mot1, + data.i_mot2, + data.FC_Threshold, + data.HeatConRange + ]); + File.AppendAllText(filePath, newEntry + Environment.NewLine); + return true; + } + return false; + } + + public bool DeleteConfigration(string id) + { + string filePath = DataPathManager.GetDataFilePath("Configration.csv"); + if (File.Exists(filePath)) + { + var filteredLines = File.ReadLines(filePath).Where(line => !line.StartsWith(id + ",")).ToArray(); + File.WriteAllLines(filePath, filteredLines); + return true; + } + return false; + } + + public bool UpdateConfigration(ConfigrationTable updatedConfig) + { + string filePath = DataPathManager.GetDataFilePath("Configration.csv"); + if (File.Exists(filePath)) + { + string[] lines = File.ReadAllLines(filePath); + bool configFound = false; + + for (int i = 1; i < lines.Length; i++) + { + string[] columns = lines[i].Split(','); + + if (columns.Length < 10) + continue; + + if (int.Parse(columns[0]) == updatedConfig.Id) + { + columns[1] = updatedConfig.Max.ToString(); + columns[2] = updatedConfig.Min.ToString(); + columns[3] = string.Join("|", updatedConfig.H_out); + columns[4] = string.Join("|", updatedConfig.FC_out); + columns[5] = string.Join("|", updatedConfig.SC_out); + columns[6] = updatedConfig.kp.ToString(); + columns[7] = updatedConfig.ki.ToString(); + columns[8] = updatedConfig.kd.ToString(); + columns[9] = updatedConfig.kl.ToString(); + columns[10] = updatedConfig.name; + columns[11] = updatedConfig.i_neut.ToString(CultureInfo.InvariantCulture); + columns[12] = updatedConfig.i_mot1.ToString(CultureInfo.InvariantCulture); + columns[13] = updatedConfig.i_mot2.ToString(CultureInfo.InvariantCulture); + columns[14] = updatedConfig.FC_Threshold.ToString(CultureInfo.InvariantCulture); + columns[15] = updatedConfig.HeatConRange.ToString(CultureInfo.InvariantCulture); + + lines[i] = string.Join(",", columns); + configFound = true; + break; + } + } + + if (configFound) + { + File.WriteAllLines(filePath, lines); + return true; + } + } + return false; + } +} diff --git a/DaireApplication/DataBase/DataPathManager.cs b/DaireApplication/DataBase/DataPathManager.cs new file mode 100644 index 0000000..08d2aa5 --- /dev/null +++ b/DaireApplication/DataBase/DataPathManager.cs @@ -0,0 +1,311 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Reflection; +using System.Collections.Generic; + +namespace DaireApplication.DataBase +{ + public static class DataPathManager + { + private static readonly string AppName = "DaireApplication"; + private static string _dataDirectory; + + // Expected CSV headers for each file + private static readonly string UsersCsvHeader = "ID,UserName,Password,CanEdit,IsAdmin,IsActive"; + private static readonly string RecipeCsvHeader = "ID,Name,TankTemp,FountainTemp,Mixer,Fountain,MoldHeater,Vibration,VibHeater,Pedal,PedalOnTime,PedalOffTime,HeatingGoal,CoolingGoal,PouringGoal"; + private static readonly string MachineCsvHeader = "ID,TankMaxHeat,PumbMaxHeat,PumbDelay,MixerDelay,HeatingDelay,CoolingDelay,PouringDelay,PumbMinHeat,AbsMaxTemp,AbsMinTemp,PreHeatingTemp,SetTemp1,SetTemp2,SetTemp3,SetTemp4"; + private static readonly string MappingCsvHeader = "Id,Name,Address,IsRead,BitNumbers"; + private static readonly string ConfigrationCsvHeader = "Id,Max,Min,H_out,FC_out,SC_out,kp,ki,kd,kl,Name,I_Nuet,I_Mot1,I_Mot2,FC_Threshold,HeatConRange"; + private static readonly string ErrorSettingsCsvHeader = "Id,gridFreq,phaseNumber,extPower,phaseVoltage"; + private static readonly string ScreenCsvHeader = "Id,Brightness,DimSec,OffSec,Port,BoundRate,Parity,StopBits,SendingTime,WarningLimit,ErrorLimit"; + + static DataPathManager() + { + try + { + // Determine the data directory based on the OS + if (OperatingSystem.IsWindows()) + { + // Windows: Use LocalApplicationData + string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + _dataDirectory = Path.Combine(appDataPath, AppName); + } + else + { + // Linux/macOS: Use ~/.local/share/DaireApplication + string home = Environment.GetEnvironmentVariable("HOME") ?? "/tmp"; + _dataDirectory = Path.Combine(home, ".local", "share", AppName); + } + + // Ensure the directory exists + Directory.CreateDirectory(_dataDirectory); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to CreateDirectory: {ex.Message}"); + Console.WriteLine($"_dataDirectory: {_dataDirectory}"); + } + } + + /// + /// Returns the full path for a data file, ensuring the directory exists. + /// + public static string GetDataFilePath(string fileName) + { + try + { + // Ensure the directory exists before returning the file path + Directory.CreateDirectory(_dataDirectory); + return Path.Combine(_dataDirectory, fileName); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to GetDataFilePath: {ex.Message}"); + return string.Empty; + } + } + + /// + /// Migrates legacy data files from the application's base directory to the new data directory. + /// + public static void MigrateLegacyData() + { + try + { + string[] csvFiles = { "Users.csv", "Recipe.csv", "Machine.csv", "Mapping.csv", + "Configration.csv", "ErrorSettings.csv", "Screen.csv" }; + + foreach (string file in csvFiles) + { + string legacyPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, file); + string newPath = GetDataFilePath(file); + + // If the file exists in the old location but not in the new location, move it + if (File.Exists(legacyPath) && !File.Exists(newPath)) + { + // Ensure the target directory exists + Directory.CreateDirectory(Path.GetDirectoryName(newPath) ?? _dataDirectory); + File.Move(legacyPath, newPath); + } + } + } + catch (Exception ex) + { + Console.WriteLine($"Failed to MigrateLegacyData: {ex.Message}"); + } + } + + /// + /// Migrates CSV files by adding missing columns with default values instead of deleting them. + /// + public static void MigrateCsvFiles() + { + MigrateCsvFile("Users.csv", UsersCsvHeader, GetUsersDefaultValues); + MigrateCsvFile("Recipe.csv", RecipeCsvHeader, GetRecipeDefaultValues); + MigrateCsvFile("Machine.csv", MachineCsvHeader, GetMachineDefaultValues); + MigrateCsvFile("Mapping.csv", MappingCsvHeader, GetMappingDefaultValues); + MigrateCsvFile("Configration.csv", ConfigrationCsvHeader, GetConfigrationDefaultValues); + MigrateCsvFile("ErrorSettings.csv", ErrorSettingsCsvHeader, GetErrorSettingsDefaultValues); + MigrateCsvFile("Screen.csv", ScreenCsvHeader, GetScreenDefaultValues); + } + + /// + /// Migrates a CSV file by adding missing columns with default values. + /// + private static void MigrateCsvFile(string fileName, string expectedHeader, Func getDefaultValue) + { + try + { + string filePath = GetDataFilePath(fileName); + if (!File.Exists(filePath)) + return; + + string[] lines = File.ReadAllLines(filePath); + if (lines.Length == 0) + return; + + string actualHeader = lines[0]; + if (string.Equals(actualHeader.Trim(), expectedHeader.Trim(), StringComparison.OrdinalIgnoreCase)) + return; // No migration needed + + string[] expectedColumns = expectedHeader.Split(','); + string[] actualColumns = actualHeader.Split(','); + + // Find missing columns + var missingColumns = new List<(int index, string columnName)>(); + for (int i = 0; i < expectedColumns.Length; i++) + { + if (i >= actualColumns.Length || !string.Equals(actualColumns[i].Trim(), expectedColumns[i].Trim(), StringComparison.OrdinalIgnoreCase)) + { + missingColumns.Add((i, expectedColumns[i])); + } + } + + if (missingColumns.Count == 0) + return; + + // Migrate the file + var migratedLines = new List(); + + // Add new header + migratedLines.Add(expectedHeader); + + // Migrate data rows + for (int i = 1; i < lines.Length; i++) + { + string[] dataColumns = lines[i].Split(','); + var newDataColumns = new List(dataColumns); + + // Add missing columns with default values + foreach (var missing in missingColumns) + { + if (missing.index >= newDataColumns.Count) + { + newDataColumns.Add(getDefaultValue(missing.columnName)); + } + else + { + newDataColumns.Insert(missing.index, getDefaultValue(missing.columnName)); + } + } + + migratedLines.Add(string.Join(",", newDataColumns)); + } + + // Write the migrated file + File.WriteAllLines(filePath, migratedLines); + Console.WriteLine($"Migrated {fileName} - added {missingColumns.Count} missing columns"); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to migrate {fileName}: {ex.Message}"); + } + } + + // Default value providers for each file type + private static string GetUsersDefaultValues(string columnName) + { + return columnName switch + { + "IsActive" => "0", + _ => "" + }; + } + + private static string GetRecipeDefaultValues(string columnName) + { + return columnName switch + { + "TankTemp" => "0", + "FountainTemp" => "0", + "Mixer" => "0", + "Fountain" => "0", + "MoldHeater" => "0", + "Vibration" => "0", + "VibHeater" => "0", + "Pedal" => "0", + "PedalOnTime" => "0", + "PedalOffTime" => "0", + "HeatingGoal" => "46", + "CoolingGoal" => "27", + "PouringGoal" => "30", + _ => "" + }; + } + + private static string GetMachineDefaultValues(string columnName) + { + return columnName switch + { + "TankMaxHeat" => "50", + "PumbMaxHeat" => "50", + "PumbDelay" => "60", + "MixerDelay" => "60", + "HeatingDelay" => "60", + "CoolingDelay" => "60", + "PouringDelay" => "60", + "PumbMinHeat" => "-10", + "AbsMaxTemp" => "65", + "AbsMinTemp" => "-14", + "PreHeatingTemp" => "5", + "SetTemp1" => "0", + "SetTemp2" => "-10", + "SetTemp3" => "5", + "SetTemp4" => "0", + _ => "" + }; + } + + private static string GetMappingDefaultValues(string columnName) + { + return columnName switch + { + "BitNumbers" => "", + _ => "" + }; + } + + private static string GetConfigrationDefaultValues(string columnName) + { + return columnName switch + { + "Max" => "0", + "Min" => "0", + "H_out" => "", + "FC_out" => "", + "SC_out" => "", + "kp" => "0", + "ki" => "0", + "kd" => "0", + "kl" => "0", + "Name" => "", + "I_Nuet" => "0", + "I_Mot1" => "0", + "I_Mot2" => "0", + "FC_Threshold" => "3", + "HeatConRange" => "50", + _ => "" + }; + } + + private static string GetErrorSettingsDefaultValues(string columnName) + { + return columnName switch + { + "gridFreq" => "50", + "phaseNumber" => "3", + "extPower" => "1", + "phaseVoltage" => "220", + _ => "" + }; + } + + private static string GetScreenDefaultValues(string columnName) + { + return columnName switch + { + "Brightness" => "100", + "DimSec" => "3300", + "OffSec" => "3600", + "Port" => "", + "BoundRate" => "19200", + "Parity" => "1", + "StopBits" => "0", + "SendingTime" => "50", + "WarningLimit" => "0.5", + "ErrorLimit" => "2", + _ => "" + }; + } + + // Legacy delete methods (kept for backward compatibility but now call migration) + public static void DeleteUsersCsv() => MigrateCsvFile("Users.csv", UsersCsvHeader, GetUsersDefaultValues); + public static void DeleteRecipeCsv() => MigrateCsvFile("Recipe.csv", RecipeCsvHeader, GetRecipeDefaultValues); + public static void DeleteMachineCsv() => MigrateCsvFile("Machine.csv", MachineCsvHeader, GetMachineDefaultValues); + public static void DeleteMappingCsv() => MigrateCsvFile("Mapping.csv", MappingCsvHeader, GetMappingDefaultValues); + public static void DeleteConfigrationCsv() => MigrateCsvFile("Configration.csv", ConfigrationCsvHeader, GetConfigrationDefaultValues); + public static void DeleteErrorSettingsCsv() => MigrateCsvFile("ErrorSettings.csv", ErrorSettingsCsvHeader, GetErrorSettingsDefaultValues); + public static void DeleteScreenCsv() => MigrateCsvFile("Screen.csv", ScreenCsvHeader, GetScreenDefaultValues); + } +} \ No newline at end of file diff --git a/DaireApplication/DataBase/ErrorSettingsTable.cs b/DaireApplication/DataBase/ErrorSettingsTable.cs new file mode 100644 index 0000000..e443e47 --- /dev/null +++ b/DaireApplication/DataBase/ErrorSettingsTable.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace DaireApplication.DataBase +{ + public class ErrorSettingsTable + { + public int Id { get; set; } + public int gridFreq { get; set; } + public int phaseNumber { get; set; } + public int phaseVoltage { get; set; } + public bool extPower { get; set; } + + public List? ReadErrorSettings() + { + string filePath = DataPathManager.GetDataFilePath("ErrorSettings.csv"); + + if (!File.Exists(filePath)) + return null; + + string[] lines = File.ReadAllLines(filePath); + List errors = new(); + + for (int i = 1; i < lines.Length; i++) + { + string[] columns = lines[i].Split(','); + + errors.Add(new ErrorSettingsTable + { + Id = int.Parse(columns[0]), + gridFreq = int.Parse(columns[1]), + phaseNumber = int.Parse(columns[2]), + extPower = columns[3] == "1", + phaseVoltage = int.Parse(columns[4]), + }); + } + + return errors; + } + + public bool UpdateError(ErrorSettingsTable updatedError) + { + string filePath = DataPathManager.GetDataFilePath("ErrorSettings.csv"); + + if (!File.Exists(filePath)) + return false; + + string[] lines = File.ReadAllLines(filePath); + bool updated = false; + + for (int i = 1; i < lines.Length; i++) + { + string[] columns = lines[i].Split(','); + + if (int.Parse(columns[0]) == updatedError.Id) + { + columns[1] = updatedError.gridFreq.ToString(); + columns[2] = updatedError.phaseNumber.ToString(); + columns[3] = updatedError.extPower ? "1" : "0"; + columns[4] = updatedError.phaseVoltage .ToString(); + lines[i] = string.Join(",", columns); + updated = true; + break; + } + } + + if (updated) + { + File.WriteAllLines(filePath, lines); + return true; + } + + return false; + } + } +} diff --git a/DaireApplication/DataBase/MachineTable.cs b/DaireApplication/DataBase/MachineTable.cs new file mode 100644 index 0000000..9362701 --- /dev/null +++ b/DaireApplication/DataBase/MachineTable.cs @@ -0,0 +1,124 @@ +using AvaloniaApplication1.DataBase; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Threading.Tasks; + +namespace DaireApplication.DataBase +{ + public class MachineTable + { + public int Id { get; set; } + public float TankMaxHeat { get; set; } = 50; + public float PumbMaxHeat { get; set; } = 50; + public int PumbDelay { get; set; } = 60; + public int MixerDelay { get; set; } = 60; + public int HeatingDelay { get; set; } = 60; + public int CoolingDelay { get; set; } = 60; + public int PouringDelay { get; set; } = 60; + public float PumbMinHeat { get; set; } = -10; + public float AbsMaxHeat { get; set; } = 65; + public float AbsMinHeat { get; set; } = -14; + public float PreHeatingTemp { get; set; } = 5; + public float setTemp1 { get; set; } =0; + public float setTemp2 { get; set; } =-10; + public float setTemp3 { get; set; } =+5; + public float setTemp4 { get; set; } =+0; + + public MachineTable ReadMachine() + { + string filePath = DataPathManager.GetDataFilePath("Machine.csv"); + MachineTable machine = new MachineTable(); + + if (File.Exists(filePath)) + { + string[] lines = File.ReadAllLines(filePath); + + foreach (string line in lines) + { + string[] columns = line.Split(','); + + if (columns[0] == "1") + { + machine.Id = int.Parse(columns[0]); + machine.TankMaxHeat = float.Parse(columns[1]); + machine.PumbMaxHeat = float.Parse(columns[2]); + machine.PumbDelay = int.Parse(columns[3]); + machine.MixerDelay = int.Parse(columns[4]); + machine.HeatingDelay = int.Parse(columns[5]); + machine.CoolingDelay = int.Parse(columns[6]); + machine.PouringDelay = int.Parse(columns[7]); + machine.PumbMinHeat = int.Parse(columns[8]); + machine.AbsMaxHeat = int.Parse(columns[9]); + machine.AbsMinHeat = int.Parse(columns[10]); + machine.PreHeatingTemp = float.Parse(columns[11]); + machine.setTemp1 = float.Parse(columns[12]); + machine.setTemp2 = float.Parse(columns[13]); + machine.setTemp3 = float.Parse(columns[14]); + machine.setTemp4 = float.Parse(columns[15]); + return machine; + } + } + return null; + } + else + { + return null; + } + } + + public bool UpdateMachine(MachineTable updatedMachine) + { + string filePath = DataPathManager.GetDataFilePath("Machine.csv"); + + if (!File.Exists(filePath)) + return false; + + string[] lines = File.ReadAllLines(filePath); + bool machineFound = false; + + for (int i = 1; i < lines.Length; i++) + { + string[] columns = lines[i].Split(','); + + if (columns.Length < 8) + continue; + + if (int.Parse(columns[0]) == updatedMachine.Id) + { + columns[1] = updatedMachine.TankMaxHeat.ToString(CultureInfo.InvariantCulture); + columns[2] = updatedMachine.PumbMaxHeat.ToString(CultureInfo.InvariantCulture); + columns[3] = updatedMachine.PumbDelay.ToString(); + columns[4] = updatedMachine.MixerDelay.ToString(); + columns[5] = updatedMachine.HeatingDelay.ToString(); + columns[6] = updatedMachine.CoolingDelay.ToString(); + columns[7] = updatedMachine.PouringDelay.ToString(); + columns[8] = updatedMachine.PumbMinHeat.ToString(CultureInfo.InvariantCulture); + columns[9] = updatedMachine.AbsMaxHeat.ToString(CultureInfo.InvariantCulture); + columns[10] = updatedMachine.AbsMinHeat.ToString(CultureInfo.InvariantCulture); + columns[11] = updatedMachine.PreHeatingTemp.ToString(CultureInfo.InvariantCulture); + columns[12] = updatedMachine.setTemp1.ToString(CultureInfo.InvariantCulture); + columns[13] = updatedMachine.setTemp2.ToString(CultureInfo.InvariantCulture); + columns[14] = updatedMachine.setTemp3.ToString(CultureInfo.InvariantCulture); + columns[15] = updatedMachine.setTemp4.ToString(CultureInfo.InvariantCulture); + + lines[i] = string.Join(",", columns); + machineFound = true; + break; + } + } + + if (machineFound) + { + File.WriteAllLines(filePath, lines); + return true; + } + + return false; + } + } +} diff --git a/DaireApplication/DataBase/Mapping.cs b/DaireApplication/DataBase/Mapping.cs new file mode 100644 index 0000000..c997c78 --- /dev/null +++ b/DaireApplication/DataBase/Mapping.cs @@ -0,0 +1,196 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace DaireApplication.DataBase; + +public class Mapping +{ + public int Id { get; set; } + public string Name { get; set; } = ""; + public string Address { get; set; } = ""; + public bool IsRead { get; set; } = false; + public List BitNumbers { get; set; } = new(); + + + public ushort getSetTempAddress(int tempAddress) + { + string tAddress = "4000"; + tempAddress -= 30004; + tAddress += tempAddress; + return ushort.Parse(tAddress); + } + public List ReadMappings() + { + string filePath = DataPathManager.GetDataFilePath("Mapping.csv"); + List mappings = new(); + + if (File.Exists(filePath)) + { + using StreamReader reader = new(filePath); + string header = reader.ReadLine(); + while (!reader.EndOfStream) + { + string[] columns = reader.ReadLine().Split(','); + mappings.Add(new Mapping + { + Id = int.Parse(columns[0]), + Name = columns[1], + Address = columns[2], + IsRead = columns[3] == "1"|| columns[3] == "True", + BitNumbers =columns[4]!=""? columns[4].Split('|').Select(int.Parse).ToList():new List() + }); + } + return mappings; + } + return null; + } + + public int GetMaxId() + { + string filePath = DataPathManager.GetDataFilePath("Mapping.csv"); + if (File.Exists(filePath)) + { + return File.ReadAllLines(filePath) + .Select(line => line.Split(',')) + .Where(columns => columns.Length > 0) + .Select(columns => int.TryParse(columns[0], out int id) ? id : 0) + .Max(); + } + return -1; + } + + public Mapping ReadMappingById(string id) + { + string filePath = DataPathManager.GetDataFilePath("Mapping.csv"); + if (File.Exists(filePath)) + { + foreach (var line in File.ReadLines(filePath)) + { + string[] columns = line.Split(','); + if (columns[0] == id) + { + return new Mapping + { + Id = int.Parse(columns[0]), + Name = columns[1], + Address = columns[2], + IsRead = columns[3] == "1", + BitNumbers = columns[4].Split('|').Select(int.Parse).ToList() + }; + } + } + } + return null; + } + + public bool AddMapping(Mapping data) + { + string filePath = DataPathManager.GetDataFilePath("Mapping.csv"); + if (File.Exists(filePath)) + { + string newEntry = string.Join(",", [ + GetMaxId() + 1, + data.Name, + data.Address, + data.IsRead ? "1" : "0", + string.Join("|", data.BitNumbers) + ]); + File.AppendAllText(filePath, newEntry + Environment.NewLine); + return true; + } + return false; + } + + public bool DeleteMapping(string id) + { + string filePath = DataPathManager.GetDataFilePath("Mapping.csv"); + if (File.Exists(filePath)) + { + var filteredLines = File.ReadLines(filePath).Where(line => !line.StartsWith(id + ",")).ToArray(); + File.WriteAllLines(filePath, filteredLines); + return true; + } + return false; + } + + public bool UpdateMapping(Mapping updatedMapping) + { + string filePath = DataPathManager.GetDataFilePath("Mapping.csv"); + if (File.Exists(filePath)) + { + string[] lines = File.ReadAllLines(filePath); + bool mappingFound = false; + + for (int i = 1; i < lines.Length; i++) + { + string[] columns = lines[i].Split(','); + + if (columns.Length < 5) + continue; + + if (int.Parse(columns[0]) == updatedMapping.Id) + { + columns[1] = updatedMapping.Name; + columns[2] = updatedMapping.Address; + columns[3] = updatedMapping.IsRead ? "1" : "0"; + columns[4] = string.Join("|", updatedMapping.BitNumbers); + lines[i] = string.Join(",", columns); + mappingFound = true; + break; + } + } + + if (mappingFound) + { + File.WriteAllLines(filePath, lines); + return true; + } + } + return false; + } + + public bool DeleteBitNumber(int id, int bitNumber) + { + string filePath = DataPathManager.GetDataFilePath("Mapping.csv"); + if (!File.Exists(filePath)) + return false; + + List records = ReadMappings(); + Mapping? record = records.Find(x => x.Id == id); + + if (record != null && record.BitNumbers.Remove(bitNumber)) // Remove bit number if found + { + string header; + using (StreamReader sr = new StreamReader(filePath)) + { + header = sr.ReadLine() ?? string.Empty; + } + + using (StreamWriter writer = new StreamWriter(filePath)) + { + writer.WriteLine(header); + string bitNumbersStr = ""; + foreach (var rec in records) + { + if (rec.Id==id) + { + bitNumbersStr = record.BitNumbers.Count > 0 ? string.Join("|", record.BitNumbers) : ""; + writer.WriteLine($"{rec.Id},{rec.Name},{rec.Address},{rec.IsRead},{bitNumbersStr}"); + + } + else + { + bitNumbersStr = rec.BitNumbers.Count > 0 ? string.Join("|", rec.BitNumbers) : ""; + writer.WriteLine($"{rec.Id},{rec.Name},{rec.Address},{rec.IsRead},{bitNumbersStr}"); + } + + } + } + return true; + } + return false; + } + +} diff --git a/DaireApplication/DataBase/RecipeTable.cs b/DaireApplication/DataBase/RecipeTable.cs new file mode 100644 index 0000000..58819c0 --- /dev/null +++ b/DaireApplication/DataBase/RecipeTable.cs @@ -0,0 +1,239 @@ +using DaireApplication.DataBase; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; + +namespace AvaloniaApplication1.DataBase +{ + public class RecipeTable + { + public int Id { get; set; } + public string Name { get; set; } + public float TankTemp { get; set; } = 0; + public float FountainTemp { get; set; } = 0; + public bool? Mixer { get; set; } = false; + public bool? Fountain { get; set; }=false; + public bool? MoldHeater { get; set; }=false; + public bool? Vibration { get; set; } = false; + public bool? VibHeater { get; set; } = false; + public bool? Pedal { get; set; } = false; + public int PedalOnTime { get; set; } = 0; + public int PedalOffTime { get; set; } = 0; + public float HeatingGoal { get; set; } = 46; + public float CoolingGoal { get; set; } = 27; + public float PouringGoal { get; set; } = 30; + + public RecipeTable() + { + Mixer = null; + Fountain = null; + MoldHeater = null; + Vibration = null; + VibHeater = null; + Pedal = null; + } + + + public List ReadRecipes() + { + string filePath = DataPathManager.GetDataFilePath("Recipe.csv"); + List recipes = new List(); + + if (File.Exists(filePath)) + { + using (StreamReader reader = new StreamReader(filePath)) + { + // Skip header + string header = reader.ReadLine(); + while (!reader.EndOfStream) + { + string line = reader.ReadLine(); + string[] columns = line.Split(','); + recipes.Add(new RecipeTable + { + Id = int.Parse(columns[0]), + Name = columns[1], + TankTemp = float.Parse(columns[2]), + FountainTemp = float.Parse(columns[3]), + Mixer = columns[4] == "1", + Fountain = columns[5] == "1", + MoldHeater = columns[6]=="1", + Vibration = columns[7] == "1", + VibHeater = columns[8]== "1", + Pedal = columns[9]=="1", + PedalOnTime = int.Parse(columns[10]), + PedalOffTime = int.Parse(columns[11]), + HeatingGoal = float.Parse(columns[12]), + CoolingGoal = float.Parse(columns[13]), + PouringGoal = float.Parse(columns[14]), + }); + } + } + return recipes; + } + else + { + return null; + } + } + public bool DoesNameExist(string searchName) + { + string filePath = DataPathManager.GetDataFilePath("Recipe.csv"); + + if (!File.Exists(filePath)) + return false; + + string[] lines = File.ReadAllLines(filePath); + + return lines + .Select(line => line.Split(',')) + .Where(columns => columns.Length > 1) + .Any(columns => string.Equals(columns[1].Trim(), searchName, StringComparison.OrdinalIgnoreCase)); + } + + public int GetMaxId() + { + string filePath = DataPathManager.GetDataFilePath("Recipe.csv"); + + if (File.Exists(filePath)) + { + string[] lines = File.ReadAllLines(filePath); + int maxId = lines + .Select(line => line.Split(',')) + .Where(columns => columns.Length > 0) + .Select(columns => int.TryParse(columns[0], out int id) ? id : 0) + .Max(); + return maxId; + } + else + { + return -1; + } + } + public RecipeTable ReadRecipesById(string id) + { + string filePath = DataPathManager.GetDataFilePath("Recipe.csv"); + RecipeTable recipe = new RecipeTable(); + + if (File.Exists(filePath)) + { + string[] lines = File.ReadAllLines(filePath); + + foreach (string line in lines) + { + string[] columns = line.Split(','); + + if (columns[0] == id) + { + recipe.Id = int.Parse(columns[0]); + recipe.Name = columns[1]; + recipe.TankTemp = float.Parse(columns[2]); + recipe.FountainTemp = float.Parse(columns[3]); + recipe.Mixer = columns[4] == "1"; + recipe.Fountain = columns[5] == "1"; + recipe.MoldHeater = columns[6] == "1"; + recipe.Vibration = columns[7] == "1"; + recipe.VibHeater = columns[8] == "1"; + recipe.Pedal = columns[9] == "1"; + recipe.PedalOnTime = int.Parse(columns[10]); + recipe.PedalOffTime = int.Parse(columns[11]); + recipe.HeatingGoal = float.Parse(columns[12]); + recipe.CoolingGoal = float.Parse(columns[13]); + recipe.PouringGoal = float.Parse(columns[14]); + return recipe; + } + } + return null; + } + else + { + return null; + } + } + public bool AddRecipe(RecipeTable data) + { + string filePath = DataPathManager.GetDataFilePath("Recipe.csv"); + + if (File.Exists(filePath)) + { + string newEntry = string.Join(",", [GetMaxId() +1, data.Name,data.TankTemp, data.FountainTemp, data.Mixer.Value?"1":"0", data.Fountain.Value ? "1" : "0", data.MoldHeater.Value ? "1" : "0", data.Vibration.Value ? "1" : "0", data.VibHeater.Value ? "1" : "0", data.Pedal.Value ? "1":"0",data.PedalOnTime,data.PedalOffTime, data.HeatingGoal,data.CoolingGoal,data.PouringGoal]); + + File.AppendAllText(filePath, newEntry + Environment.NewLine); + return true; + } + else + { + return false; + } + } + public bool DeleteRecipe(string id) + { + string filePath = DataPathManager.GetDataFilePath("Recipe.csv"); + + if (File.Exists(filePath)) + { + string[] lines = File.ReadAllLines(filePath); + var filteredLines = lines.Where(line => !line.StartsWith(id + ",")).ToArray(); + + File.WriteAllLines(filePath, filteredLines); + return true; + } + else + { + return false; + } + } + + public bool UpdateRecipe(RecipeTable updatedRecipe) + { + string filePath = DataPathManager.GetDataFilePath("Recipe.csv"); + + if (!File.Exists(filePath)) + return false; + + string[] lines = File.ReadAllLines(filePath); + bool recipeFound = false; + + for (int i = 1; i < lines.Length; i++) + { + string[] columns = lines[i].Split(','); + + if (columns.Length < 15) + continue; + + if (int.TryParse(columns[0], out int id) && id == updatedRecipe.Id) + { + columns[1] = updatedRecipe.Name ?? ""; + columns[2] = updatedRecipe.TankTemp.ToString(CultureInfo.InvariantCulture); + columns[3] = updatedRecipe.FountainTemp.ToString(CultureInfo.InvariantCulture); + columns[4] = (updatedRecipe.Mixer ?? false) ? "1" : "0"; + columns[5] = (updatedRecipe.Fountain ?? false) ? "1" : "0"; + columns[6] = (updatedRecipe.MoldHeater ?? false) ? "1" : "0"; + columns[7] = (updatedRecipe.Vibration ?? false) ? "1" : "0"; + columns[8] = (updatedRecipe.VibHeater ?? false) ? "1" : "0"; + columns[9] = (updatedRecipe.Pedal ?? false) ? "1" : "0"; + columns[10] = updatedRecipe.PedalOnTime.ToString(); + columns[11] = updatedRecipe.PedalOffTime.ToString(); + columns[12] = updatedRecipe.HeatingGoal.ToString(CultureInfo.InvariantCulture); + columns[13] = updatedRecipe.CoolingGoal.ToString(CultureInfo.InvariantCulture); + columns[14] = updatedRecipe.PouringGoal.ToString(CultureInfo.InvariantCulture); + + lines[i] = string.Join(",", columns); + recipeFound = true; + break; + } + } + + if (recipeFound) + { + File.WriteAllLines(filePath, lines); + return true; + } + + return false; + } + + } +} diff --git a/DaireApplication/DataBase/ScreeenTable.cs b/DaireApplication/DataBase/ScreeenTable.cs new file mode 100644 index 0000000..60f5d1a --- /dev/null +++ b/DaireApplication/DataBase/ScreeenTable.cs @@ -0,0 +1,112 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DaireApplication.DataBase +{ + public class ScreeenTable + { + public int Id { get; set; } + public int brightness { get; set; } + public float dimSec { get; set; } + public float offSec { get; set; } + public string port { get; set; } + public int boundRate { get; set; } + public int stopBits { get; set; } + public int parity { get; set; } + public int sendingTime { get; set; } + public double warningLimit { get; set; } + public double errorLimit { get; set; } + + public List? ReadScreens() + { + try + { + string filePath = DataPathManager.GetDataFilePath("Screen.csv"); + + if (!File.Exists(filePath)) + return null; + + string[] lines = File.ReadAllLines(filePath); + List screens = new(); + + for (int i = 1; i < lines.Length; i++) + { + string[] columns = lines[i].Split(','); + + if (columns.Length < 8) + continue; + + screens.Add(new ScreeenTable + { + Id = int.Parse(columns[0]), + brightness = int.Parse(columns[1]), + dimSec = float.Parse(columns[2]), + offSec = float.Parse(columns[3]), + port = columns[4], + boundRate = int.Parse(columns[5]), + stopBits = int.Parse(columns[6]), + parity = int.Parse(columns[7]), + sendingTime = int.Parse(columns[8]), + warningLimit = double.Parse(columns[9]), + errorLimit = double.Parse(columns[10]), + }); + } + + return screens; + } + catch (Exception) + { + return null; + } + } + + public bool UpdateScreen(ScreeenTable updatedScreen) + { + string filePath = DataPathManager.GetDataFilePath("Screen.csv"); + + if (!File.Exists(filePath)) + return false; + + string[] lines = File.ReadAllLines(filePath); + bool updated = false; + + for (int i = 1; i < lines.Length; i++) + { + string[] columns = lines[i].Split(','); + + if (columns.Length < 8) + continue; + + if (int.Parse(columns[0]) == updatedScreen.Id) + { + columns[1] = updatedScreen.brightness.ToString(); + columns[2] = updatedScreen.dimSec.ToString(); + columns[3] = updatedScreen.offSec.ToString(); + columns[4] = updatedScreen.port; + columns[5] = updatedScreen.boundRate.ToString(); + columns[6] = updatedScreen.stopBits.ToString(); + columns[7] = updatedScreen.parity.ToString(); + columns[8] = updatedScreen.sendingTime.ToString(); + columns[9] = updatedScreen.warningLimit.ToString(); + columns[10] = updatedScreen.errorLimit.ToString(); + + lines[i] = string.Join(",", columns); + updated = true; + break; + } + } + + if (updated) + { + File.WriteAllLines(filePath, lines); + return true; + } + + return false; + } + } +} diff --git a/DaireApplication/DataBase/UserTable.cs b/DaireApplication/DataBase/UserTable.cs new file mode 100644 index 0000000..6a7c848 --- /dev/null +++ b/DaireApplication/DataBase/UserTable.cs @@ -0,0 +1,83 @@ +using DaireApplication.DataBase; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AvaloniaApplication1.DataBase +{ + public class UserTable + { + public int Id { get; set; } + public string UserName { get; set; } + public string Password { get; set; } + public bool CanEdit { get; set; } + public bool IsAdmin { get; set; } + public bool IsActive { get; set; } + + public List ReadUsers() + { + string filePath = DataPathManager.GetDataFilePath("Users.csv"); + List users = new List(); + + if (File.Exists(filePath)) + { + string[] lines = File.ReadAllLines(filePath); + + for (int i = 1; i < lines.Length; i++) // Skip header + { + string[] columns = lines[i].Split(','); + users.Add(new UserTable + { + Id = int.Parse(columns[0]), + UserName = columns[1], + Password = columns[2], + CanEdit = columns[3] =="1" ?true:false, + IsAdmin=columns[4] =="1" ?true: false, + IsActive=columns[5] =="1" ?true: false, + }); + } + return users; + } + else + { + return null; + } + } + + public bool UpdateUser(UserTable updatedUser) + { + string filePath = DataPathManager.GetDataFilePath("Users.csv"); + if (File.Exists(filePath)) + { + string[] lines = File.ReadAllLines(filePath); + bool userFound = false; + + for (int i = 1; i < lines.Length; i++) + { + string[] columns = lines[i].Split(','); + if (int.Parse(columns[0]) == updatedUser.Id) + { + columns[1] = updatedUser.UserName; + columns[2] = updatedUser.Password; + columns[3] = updatedUser.CanEdit ? "1" : "0"; + columns[4] = updatedUser.IsAdmin ? "1" : "0"; + columns[5] = updatedUser.IsActive ? "1" : "0"; + lines[i] = string.Join(",", columns); + userFound = true; + break; + } + } + + if (userFound) + { + File.WriteAllLines(filePath, lines); + return true; + } + } + return false; + } + } +} diff --git a/DaireApplication/Loops/CheckInterNetLoop.cs b/DaireApplication/Loops/CheckInterNetLoop.cs new file mode 100644 index 0000000..ee7b404 --- /dev/null +++ b/DaireApplication/Loops/CheckInterNetLoop.cs @@ -0,0 +1,111 @@ +using Avalonia.Media.Imaging; +using Avalonia.Threading; +using DaireApplication.ViewModels; +using DaireApplication.Views; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace DaireApplication.Loops +{ + public class CheckInterNetLoop + { + public static async void CheckInterNet(MainWindow _mainWindow) + { + string textToDelete = ""; + + while (true) + { + if (!Error.IsInternetAvailable()) + { + Dispatcher.UIThread.Post(() => + { + if (_mainWindow.ContentArea.Content is Home || _mainWindow.ContentArea.Content is Admin) + { + if (!_mainWindow.nowifiLogo.IsVisible) + { + _mainWindow.wifiLogo.IsVisible = false; + _mainWindow.nowifiLogo.IsVisible = true; + } + } + else + { + _mainWindow.wifiLogo.IsVisible = false; + _mainWindow.nowifiLogo.IsVisible = false; + } + //if (!_mainWindow.warningMsg.Text.Contains("No Internet Access")) + //{ + // _mainWindow.warningMsg.Text += "\nNo Internet Access"; + // _mainWindow.warningLogo.IsVisible = true; + + //} + + }); + + } + else + { + Dispatcher.UIThread.Post(() => + { + if (_mainWindow.ContentArea.Content is Home || _mainWindow.ContentArea.Content is Admin) + { + if (!_mainWindow.wifiLogo.IsVisible) + { + _mainWindow.nowifiLogo.IsVisible = false; + _mainWindow.wifiLogo.IsVisible = true; + } + } + else + { + _mainWindow.wifiLogo.IsVisible = false; + _mainWindow.nowifiLogo.IsVisible = false; + } + //if (_mainWindow.warningMsg.Text.Contains("No Internet Access")) + //{ + // _mainWindow.warningMsg.Text=_mainWindow.warningMsg.Text.Replace("\nNo Internet Access", ""); + //} + }); + + } + if (!string.IsNullOrEmpty(_mainWindow.warningMessage)) + { + Dispatcher.UIThread.Post(() => + { + if (!_mainWindow.warningMsg.Text.Contains($"\n-{_mainWindow.warningMessage}")) + { + textToDelete = _mainWindow.warningMessage; + _mainWindow.warningMsg.Text += $"\n-{_mainWindow.warningMessage}"; + _mainWindow.warningLogo.IsVisible = true; + + } + + }); + } + else + { + Dispatcher.UIThread.Post(() => + { + if (_mainWindow.warningMsg.Text.Contains($"-{textToDelete}")) + { + _mainWindow.warningMsg.Text= _mainWindow.warningMsg.Text.Replace($"\n-{textToDelete}", ""); + } + + }); + } + if ( string.IsNullOrEmpty(_mainWindow.warningMessage)) + { + Dispatcher.UIThread.Post(() => + { + _mainWindow.warningLogo.IsVisible = false; + + }); + } + Thread.Sleep(10); + } + } + + } +} diff --git a/DaireApplication/Loops/InteractiveUILoop.cs b/DaireApplication/Loops/InteractiveUILoop.cs new file mode 100644 index 0000000..67523d0 --- /dev/null +++ b/DaireApplication/Loops/InteractiveUILoop.cs @@ -0,0 +1,100 @@ +using Avalonia.Media; +using Avalonia.Threading; +using AvaloniaApplication1.ViewModels; +using DaireApplication.DataBase; +using DaireApplication.Views; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace DaireApplication.Loops +{ + public class InteractiveUILoop + { + public static async void Flashing(MainWindow _mainWindow) + { + while (true) + { + // Flashing Pre Heater on + if (_mainWindow.isFlashPreHeating) + { + Dispatcher.UIThread.Post(() => + { + if (_mainWindow.PreHeatingBtn.Foreground == Brushes.Transparent) + { + _mainWindow.PreHeatingBtn.Foreground = Brushes.White; + } + else + { + _mainWindow.PreHeatingBtn.Foreground = Brushes.Transparent; + } + + }); + } + // Flashing Pre Heater off + if (!_mainWindow.isFlashPreHeating) + { + Dispatcher.UIThread.Post(() => + { + _mainWindow.PreHeatingBtn.Foreground = Brushes.White; + }); + } + // Flashing Mixer on + if (_mainWindow.startMixerMotorFlashing == 1) + { + Dispatcher.UIThread.Post(() => + { + if (_mainWindow.ContentArea.Content is Settings result) + { + var motorLable = result.MixerSP.Children[1] as Avalonia.Controls.Label; + var motorRectangel = result.MixerSP.Children[2] as Avalonia.Controls.Shapes.Rectangle; + if (motorLable.Foreground.ToString() == "#ff231f20") + { + motorLable.Foreground = Brushes.Transparent ; + motorRectangel.Fill = Brushes.Transparent; + } + else + { + motorLable.Foreground = Brush.Parse("#ff231f20"); + motorRectangel.Fill = Brush.Parse(_mainWindow.PassiveColor); + + + } + } + + + }); + } + + // Flashing Fountain on (only when not in pedal auto mode) + if (_mainWindow.startFountainMotorFlashing == 1 && !_mainWindow.isPedalAutoMode) + { + Dispatcher.UIThread.Post(() => + { + if (_mainWindow.ContentArea.Content is Settings result) + { + var fountainLable = result.FountainSP.Children[1] as Avalonia.Controls.Label; + var fountainRectangel = result.FountainSP.Children[2] as Avalonia.Controls.Shapes.Rectangle; + if (fountainLable.Foreground.ToString() == "#ff231f20") + { + fountainLable.Foreground = Brushes.Transparent; + fountainRectangel.Fill = Brushes.Transparent; + } + else + { + fountainLable.Foreground = Brush.Parse("#ff231f20"); + fountainRectangel.Fill = Brush.Parse(_mainWindow.PassiveColor); + + + } + } + }); + } + Thread.Sleep(250); + } + } + } +} diff --git a/DaireApplication/Loops/ScreenLoop.cs b/DaireApplication/Loops/ScreenLoop.cs new file mode 100644 index 0000000..524c213 --- /dev/null +++ b/DaireApplication/Loops/ScreenLoop.cs @@ -0,0 +1,172 @@ +using Avalonia.Threading; +using DaireApplication.Views; +using System; +using System.Linq; +using System.Threading.Tasks; + +namespace DaireApplication.Loops; + +public class ScreenLoop +{ + static void SetBrightness(int value) + { + //File.WriteAllText("/sys/class/backlight/backlight/brightness", value.ToString()); + } + public static async void Screen(MainWindow _mainWindow) + { + var screenData = _mainWindow._screeen.ReadScreens()?[0]; + SetBrightness((int)(screenData.brightness / 100 * 255)); + while (true) + { + try + { + screenData = _mainWindow._screeen.ReadScreens()?[0]; + + if ((DateTime.Now - _mainWindow.lastActivity).TotalSeconds >= screenData?.offSec) + { + if (!MainWindow.isOff) + { + MainWindow.isOff = true; + SetBrightness(0); + } + + } + else if ((DateTime.Now - _mainWindow.lastActivity).TotalSeconds >= screenData?.dimSec) + { + MainWindow.isOff = false; + SetBrightness(51); // 20% of 255 + } + + if (MainWindow.errors.Count > 0) + { + foreach (var item in MainWindow.errors.ToList()) + { + + if ((DateTime.Now - item.errorDate).TotalSeconds >= 2.5) + { + if (!item.isShowen) + { + Dispatcher.UIThread.Post(() => + { + if (_mainWindow.errorMsg.Text.Contains($"- {item.GetDisplayNames(item.Condition)}")) + { + item.isShowen = true; + + } + else + { + _mainWindow.errorMsg.Text += $"\n- {item.GetDisplayNames(item.Condition)}"; + item.isShowen = true; + } + + }); + } + if (item.isDeleted) + { + Dispatcher.UIThread.Post(() => + { + _mainWindow.errorMsg.Text = _mainWindow.errorMsg.Text + .Replace($"- {item.GetDisplayNames(item.Condition)}", ""); + MainWindow.errors.Remove(item); + }); + } + + Dispatcher.UIThread.Post(() => + { + _mainWindow.errorMsg.Text = _mainWindow.errorMsg.Text.Trim(); + if (_mainWindow.ContentArea.Content is Settings settings && MainWindow.errors.Count > 0) + { + //_mainWindow.footerMsg.Text = ""; + settings.mixerBtn.IsEnabled = false; + settings.fountainBtn.IsEnabled = false; + settings.moldHeaterBtn.IsEnabled = false; + settings.vibrationBtn.IsEnabled = false; + settings.vibHeaterBtn.IsEnabled = false; + _mainWindow.PreHeatingBtn.IsEnabled = false; + //_mainWindow.recipeStartBtn.IsEnabled = false; + } + }); + + } + } + + if (MainWindow.errors.Count > 0) + { + if ((DateTime.Now - MainWindow.errors.Min(x => x.errorDate)).TotalSeconds >= 3.5) + { + Dispatcher.UIThread.Post(() => + { + _mainWindow.errorLogo.IsVisible = true; + + _mainWindow.errorTitel.Text = $"Error Number: {MainWindow.errors.Count}"; + _mainWindow.errorMsg.Text = _mainWindow.errorMsg.Text.Trim(); + + //_mainWindow.footerMsg.Text = $"Error Numbers: {MainWindow.errors.Count}"; + //_mainWindow.errorLogoBtn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); + }); + } + + + } + + } + else + { + Dispatcher.UIThread.Post(() => + { + + //MainWindow.errors.Clear(); + _mainWindow.errorLogo.IsVisible = false; + _mainWindow.errorPopupOverlay.IsVisible = false; + if (_mainWindow.ContentArea.Content is Settings settings) + { + //_mainWindow.footerMsg.Text = "Ready"; + + settings.moldHeaterBtn.IsEnabled = true; + settings.vibrationBtn.IsEnabled = true; + settings.vibHeaterBtn.IsEnabled = true; + _mainWindow.recipeStartBtn.IsEnabled = true; + if (_mainWindow.startRecipe != 1) + { + _mainWindow.PreHeatingBtn.IsEnabled = true; + settings.mixerBtn.IsEnabled = true; + settings.fountainBtn.IsEnabled = true; + + } + var isFountOn = false; + var isMixerOn = false; + var fountainMotor =_mainWindow._mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + var mixerMotor =_mainWindow._mapping.Find(x => x.Name.ToLower() == "Mixer".ToLower()); + if (isFountOn !=fountainMotor.BitNumbers.All(bit => (_mainWindow.holdingRegister.motor & (1 << bit)) != 0)) + { + isFountOn = fountainMotor.BitNumbers.All(bit => (_mainWindow.holdingRegister.motor & (1 << bit)) != 0); + } + if (isMixerOn != mixerMotor.BitNumbers.All(bit => (_mainWindow.holdingRegister.motor & (1 << bit)) != 0)) + { + isMixerOn = mixerMotor.BitNumbers.All(bit => (_mainWindow.holdingRegister.motor & (1 << bit)) != 0); + } + if (isFountOn && isMixerOn) // both motores are on + { + if (_mainWindow.startRecipe == 1 && (_mainWindow.Heating == 10 || _mainWindow.cooling == 10 || _mainWindow.pouring == 10)) + { + _mainWindow.unPause = true; + } + } + + + } + }); + } + + + await Task.Delay(10); + } + catch (Exception) + { + + } + } + + } + +} diff --git a/DaireApplication/Loops/TouchLoop.cs b/DaireApplication/Loops/TouchLoop.cs new file mode 100644 index 0000000..e99ed45 --- /dev/null +++ b/DaireApplication/Loops/TouchLoop.cs @@ -0,0 +1,54 @@ +using DaireApplication.Views; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace DaireApplication.Loops +{ + public class TouchLoop + { + static void SetBrightness(int value) + { + //File.WriteAllText("/sys/class/backlight/backlight/brightness", value.ToString()); + } + public static async void Touch(MainWindow _mainWindow) + { + static void WatchInput(int bright, MainWindow _mainWindow) + { + + string inputDevice = "/dev/input/event1"; // adjust based on your touch device + using (FileStream fs = new FileStream(inputDevice, FileMode.Open, FileAccess.Read)) + { + byte[] buffer = new byte[24]; + + fs.Read(buffer, 0, buffer.Length); + _mainWindow.lastActivity = DateTime.Now; + SetBrightness(bright); // Restore brightness if touch + } + } + + var screenData = _mainWindow._screeen.ReadScreens()?[0]; + + while (true) + { + try + { + screenData = _mainWindow._screeen.ReadScreens()?[0]; + int brightnessValue = (int)((screenData.brightness) / 100.0 * 255); + MainWindow.isOff = false; + //WatchInput(brightnessValue, _mainWindow); + Thread.Sleep(200); + } + catch (Exception) + { + + } + + } + } + } +} diff --git a/DaireApplication/Loops/serialThreadLoop.cs b/DaireApplication/Loops/serialThreadLoop.cs new file mode 100644 index 0000000..048a218 --- /dev/null +++ b/DaireApplication/Loops/serialThreadLoop.cs @@ -0,0 +1,504 @@ +using Avalonia.Threading; +using AvaloniaApplication1.ViewModels; +using DaireApplication.DataBase; +using DaireApplication.ViewModels; +using DaireApplication.Views; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace DaireApplication.Loops +{ + public class SerialRequest + { + public enum RequestType { Read, Write } + public RequestType Type { get; set; } + public byte[] Data { get; set; } + public int ExpectedLength { get; set; } + public TaskCompletionSource Completion { get; set; } = new(); + } + + public class serialThreadLoop + { + private static readonly ConcurrentQueue writeQueue = new(); + private static readonly ConcurrentQueue readQueue = new(); + private static bool keepSendingRunning = false; + + public static Task EnqueueWrite(byte[] data, int expectedLength) + { + var req = new SerialRequest { Type = SerialRequest.RequestType.Write, Data = data, ExpectedLength = expectedLength }; + writeQueue.Enqueue(req); + return req.Completion.Task; + } + public static Task EnqueueRead(byte[] data, int expectedLength) + { + var req = new SerialRequest { Type = SerialRequest.RequestType.Read, Data = data, ExpectedLength = expectedLength }; + readQueue.Enqueue(req); + return req.Completion.Task; + } + + public static async void SendViaSerial(MainWindow _mainWindow) + { + try + { + //Debug.WriteLine("SendViaSerial started"); + // Start the keepSending background task if not already running + if (!keepSendingRunning) + { + //Debug.WriteLine("Starting KeepSendingLoop"); + keepSendingRunning = true; + _ = Task.Run(() => KeepSendingLoop(_mainWindow)); + } + + List values = new List(); + while (_mainWindow.serialThreadRunning) + { + //Debug.WriteLine($"SendViaSerial loop iteration - Port status: {(_mainWindow._port?.IsOpen ?? false)}"); + if (_mainWindow._port != null && _mainWindow._port.IsOpen) + { + if (_mainWindow.reSendHolding) + { + values.Clear(); + _mainWindow._configrations = _mainWindow._config.ReadConfigrations(); + values.Add(_mainWindow.holdingRegister.resetError); + values.Add(_mainWindow.holdingRegister.hvOut); + values.Add(_mainWindow.holdingRegister.lvOut); + values.Add(_mainWindow.holdingRegister.motor); + values.Add(_mainWindow.holdingRegister.setTemp1); + values.Add(_mainWindow.holdingRegister.setTemp2); + values.Add(_mainWindow.holdingRegister.setTemp3); + values.Add(_mainWindow.holdingRegister.setTemp4); + values.Add((int)(_mainWindow._configrations[0].i_neut * 10)); + values.Add((int)(_mainWindow._configrations[0].i_mot1 * 10)); + values.Add((int)(_mainWindow._configrations[0].i_mot2 * 10)); + foreach (var item in _mainWindow._configrations) + { + values.Add(item.Max * 10); + values.Add(item.Min * 10); + values.Add(ConvertToDecimal(item.H_out.ToList())); + values.Add(ConvertToDecimal(item.FC_out.ToList())); + values.Add(ConvertToDecimal(item.SC_out.ToList())); + values.Add(item.FC_Threshold * 10); + values.Add(item.HeatConRange * 10); + values.Add(item.kp); + values.Add(item.ki); + values.Add(item.kd); + values.Add(item.kl); + } + _mainWindow._port.DiscardInBuffer(); + _mainWindow._port.DiscardOutBuffer(); + byte[] requstConfig = await _mainWindow._modBusMaster.WriteMultipleRegisters(0, values.ToArray()); + await EnqueueWrite(requstConfig, 7); + _mainWindow.reSendHolding = false; + } + if (_mainWindow.sendConfig) + { + values.Clear(); + _mainWindow._configrations = _mainWindow._config.ReadConfigrations(); + if (!_mainWindow.dontResetOutPuts) + { + values.Add(0); + values.Add(0); + values.Add(0); + values.Add(-10000); + values.Add(-10000); + values.Add(-10000); + values.Add(-10000); + } + values.Add((int)(_mainWindow._configrations[0].i_neut * 10)); + values.Add((int)(_mainWindow._configrations[0].i_mot1 * 10)); + values.Add((int)(_mainWindow._configrations[0].i_mot2 * 10)); + foreach (var item in _mainWindow._configrations) + { + values.Add(item.Max * 10); + values.Add(item.Min * 10); + values.Add(ConvertToDecimal(item.H_out.ToList())); + values.Add(ConvertToDecimal(item.FC_out.ToList())); + values.Add(ConvertToDecimal(item.SC_out.ToList())); + values.Add(item.FC_Threshold * 10); + values.Add(item.HeatConRange * 10); + values.Add(item.kp); + values.Add(item.ki); + values.Add(item.kd); + values.Add(item.kl); + } + + byte[] requstConfig = await _mainWindow._modBusMaster.WriteMultipleRegisters(_mainWindow.dontResetOutPuts ? (ushort)8 : (ushort)1, values.ToArray()); + await EnqueueWrite(requstConfig, 7); + _mainWindow.sendConfig = false; + _mainWindow.dontResetOutPuts = false; + } + if (_mainWindow.restBoard) + { + _mainWindow.holdingRegister.hvOut = 0; + _mainWindow.holdingRegister.lvOut = 0; + _mainWindow.holdingRegister.motor = 0; + _mainWindow.holdingRegister.setTemp1 = -10000; + _mainWindow.holdingRegister.setTemp2 = -10000; + _mainWindow.holdingRegister.setTemp3 = -10000; + _mainWindow.holdingRegister.setTemp4 = -10000; + + // Send reset data directly without using the async pattern + List resetValues = new List(); + resetValues.Add(_mainWindow.holdingRegister.resetError); + resetValues.Add(_mainWindow.holdingRegister.hvOut); + resetValues.Add(_mainWindow.holdingRegister.lvOut); + resetValues.Add(_mainWindow.holdingRegister.motor); + resetValues.Add(_mainWindow.holdingRegister.setTemp1); + resetValues.Add(_mainWindow.holdingRegister.setTemp2); + resetValues.Add(_mainWindow.holdingRegister.setTemp3); + resetValues.Add(_mainWindow.holdingRegister.setTemp4); + + byte[] resetRequest = await _mainWindow._modBusMaster.WriteMultipleRegisters(0, resetValues.ToArray()); + await EnqueueWrite(resetRequest, 7); + + _mainWindow.restBoard = false; + } + // Check if there's a pending write request + if (_mainWindow._writeCompletionSource?.Task.Status == TaskStatus.WaitingForActivation) + { + List writingValues = new List(); + writingValues.Add(_mainWindow.holdingRegister.resetError); + writingValues.Add(_mainWindow.holdingRegister.hvOut); + writingValues.Add(_mainWindow.holdingRegister.lvOut); + writingValues.Add(_mainWindow.holdingRegister.motor); + writingValues.Add(_mainWindow.holdingRegister.setTemp1); + writingValues.Add(_mainWindow.holdingRegister.setTemp2); + writingValues.Add(_mainWindow.holdingRegister.setTemp3); + writingValues.Add(_mainWindow.holdingRegister.setTemp4); + byte[] requstConfig = await _mainWindow._modBusMaster.WriteMultipleRegisters(0, writingValues.ToArray()); + var result = await EnqueueWrite(requstConfig, 7); + // Signal completion + bool success = result.Length != 1 || result[0] != 0xFF; + _mainWindow.SetWriteComplete(success); + } + var requstReadingInputs = await _mainWindow._modBusMaster.ReadInputRegisters(0, 18); + await EnqueueRead(requstReadingInputs, 41); + } + } + } + catch (Exception ex) + { + + } + + } + + private static async Task KeepSendingLoop(MainWindow _mainWindow) + { + //Debug.WriteLine("KeepSendingLoop started"); + var startTime = DateTime.Now; + int intervalMs = _mainWindow.screenData.sendingTime; + int requestCount = 0; + + while (_mainWindow.serialThreadRunning) + { + try + { + _mainWindow.screenData = _mainWindow._screeen.ReadScreens()[0]; + //Debug.WriteLine($"KeepSendingLoop iteration - Port status: {(_mainWindow._port?.IsOpen ?? false)}, SendingTime: {_mainWindow.screenData.sendingTime}ms"); + + // Skip if port is not valid + if (_mainWindow._port == null || !_mainWindow._port.IsOpen) + { + //Debug.WriteLine("Port not valid, waiting..."); + await Task.Delay(100); // Wait a bit before checking again + continue; + } + + var scheduledTime = startTime.AddMilliseconds(requestCount * intervalMs); + var now = DateTime.Now; + var waitTime = (scheduledTime - now).TotalMilliseconds; + if (waitTime > 0) + await Task.Delay((int)waitTime); + + SerialRequest req = null; + if (!writeQueue.TryPeek(out req)) + readQueue.TryPeek(out req); + + if (req != null) + { + var requestStart = DateTime.Now; + var response = await keepSendingScenario(_mainWindow, req.Data, req.ExpectedLength,_mainWindow.screenData.sendingTime); + var requestEnd = DateTime.Now; + var requestElapsed = (requestEnd - requestStart).TotalMilliseconds; + if (response.Length != 1 || response[0] != 0xFF) + { + //Debug.WriteLine($"SUCCESS: Total time for request: {requestElapsed} ms"); + if (req.Type == SerialRequest.RequestType.Read) + { + _mainWindow.inputesResponse = response; + } + req.Completion.SetResult(response); + } + else // failed after retries or timeout + { + //Debug.WriteLine($"FAILED: Total time for request: {requestElapsed} ms"); + req.Completion.SetResult(response); // set failure result + } + if (req.Type == SerialRequest.RequestType.Write) + writeQueue.TryDequeue(out _); + else + readQueue.TryDequeue(out _); + } + + requestCount++; + // If we are behind schedule, catch up + if ((DateTime.Now - startTime).TotalMilliseconds > requestCount * intervalMs) + requestCount = (int)((DateTime.Now - startTime).TotalMilliseconds / intervalMs); + } + catch (Exception ex) + { + //Debug.WriteLine($"Error in KeepSendingLoop: {ex.Message}"); + await Task.Delay(100); // Wait a bit before retrying + } + } + } + + private static async Task keepSendingScenario(MainWindow _mainWindow, byte[] request, int expectedLength, int interval) + { + // Enforce minimum interval between packets + using var cts = new CancellationTokenSource(); + int SENDING_INTERVAL = interval; // Minimum interval between sends + + var now = DateTime.Now; + var elapsed = (now - _mainWindow._lastPacketSendTime).TotalMilliseconds; + if (elapsed < _mainWindow.screenData.sendingTime) + { + await Task.Delay((int)(SENDING_INTERVAL - elapsed)); + } + _mainWindow._lastPacketSendTime = DateTime.Now; + + //Debug.WriteLine("keepSending started"); + + // Calculate 4 character delay based on baud rate + double fourCharDelay = (1.0 / _mainWindow.screenData.boundRate) * 44000; + int noResponseRetryCount = 0; + const int MAX_NO_RESPONSE_RETRIES = 3; // Try 3 times, once per second + const int NO_RESPONSE_TIMEOUT = 1000; // 1 second between no-response retries + const int TOTAL_INVALID_RETRY_TIME = 3000; // 3 seconds total for invalid responses + + var startTime = DateTime.Now; + var lastSendTime = DateTime.Now; + var lastValidResponseTime = DateTime.Now; + bool hadValidResponse = false; + + while ((DateTime.Now - startTime).TotalMilliseconds < TOTAL_INVALID_RETRY_TIME) + { + // Calculate time since last send + var timeSinceLastSend = (DateTime.Now - lastSendTime).TotalMilliseconds; + var timeSinceLastValidResponse = (DateTime.Now - lastValidResponseTime).TotalMilliseconds; + + // Check for communication timeout + if (timeSinceLastValidResponse >= TOTAL_INVALID_RETRY_TIME && !hadValidResponse) + { + //Debug.WriteLine("No valid response received within 3 seconds"); + if (!MainWindow.errors.Any(x => x.Condition == Error.GridCondition.NoBoardCom)) + { + MainWindow.errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.NoBoardCom + }); + } + } + + // For no response case, check frequently for response + if (noResponseRetryCount > 0 && timeSinceLastSend < NO_RESPONSE_TIMEOUT) + { + // Check for response every 10ms + if (_mainWindow._port != null && _mainWindow._port.IsOpen) + { + if (_mainWindow._port.BytesToRead >= expectedLength) + { + // Wait 4-char delay when we have enough bytes + await Task.Delay((int)fourCharDelay); + var response = await TryReadOnce(_mainWindow, expectedLength, cts.Token); + //Debug.WriteLine($"Response received during wait after {timeSinceLastSend}ms"); + + if (response.Length == expectedLength && IsValidCrc(response)) + { + hadValidResponse = true; + lastValidResponseTime = DateTime.Now; // Reset valid response timer + var err = MainWindow.errors.FirstOrDefault(x => x.Condition == Error.GridCondition.NoBoardCom); + if (err != null) err.isDeleted = true; + + // For valid response, still respect minimum interval + //if (timeSinceLastSend < SENDING_INTERVAL) + //{ + // var remainingTime = SENDING_INTERVAL - timeSinceLastSend; + // Debug.WriteLine($"Valid response received before {SENDING_INTERVAL}ms, waiting {remainingTime}ms"); + // await Task.Delay((int)remainingTime); + //} + return response; + } + + // For any response (even invalid), increment retry count and continue immediately + noResponseRetryCount++; + if (noResponseRetryCount >= MAX_NO_RESPONSE_RETRIES) + { + //Debug.WriteLine("Max retries exceeded"); + if (!MainWindow.errors.Any(x => x.Condition == Error.GridCondition.NoBoardCom)) + { + MainWindow.errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.NoBoardCom + }); + } + return new byte[] { 0xFF }; + } + + // Break wait and send next retry immediately + lastSendTime = DateTime.Now.AddMilliseconds(-NO_RESPONSE_TIMEOUT); // Force immediate retry + break; + } + /*await Task.Delay(10);*/ // Small delay between checks + continue; + } + } + + // For invalid response case, wait minimum interval between retries + if (timeSinceLastSend < SENDING_INTERVAL) + { + await Task.Delay(1); // Minimal delay to prevent tight loop + continue; + } + + // Send the request + _mainWindow._port.Write(request, 0, request.Length); + lastSendTime = DateTime.Now; + //Debug.WriteLine($"Sent request at {lastSendTime:HH:mm:ss.fffffff}"); + + // Wait 4-char delay after sending + await Task.Delay((int)fourCharDelay); + + // Try to read response + if (_mainWindow._port != null && _mainWindow._port.IsOpen && _mainWindow._port.BytesToRead >= expectedLength) + { + // Wait another 4-char delay when we have enough bytes + await Task.Delay((int)fourCharDelay); + var response = await TryReadOnce(_mainWindow, expectedLength, cts.Token); + + // Handle valid response + if (response.Length >= expectedLength && IsValidCrc(response)) + { + hadValidResponse = true; + lastValidResponseTime = DateTime.Now; // Reset valid response timer + var err = MainWindow.errors.FirstOrDefault(x => x.Condition == Error.GridCondition.NoBoardCom); + if (err != null) err.isDeleted = true; + return response; + } + } + + // Handle invalid/no response + noResponseRetryCount++; + //Debug.WriteLine($"Invalid/No response, attempt {noResponseRetryCount} of {MAX_NO_RESPONSE_RETRIES}"); + if (noResponseRetryCount >= MAX_NO_RESPONSE_RETRIES) + { + //Debug.WriteLine("Max retries exceeded"); + if (!MainWindow.errors.Any(x => x.Condition == Error.GridCondition.NoBoardCom)) + { + MainWindow.errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.NoBoardCom + }); + } + return new byte[] { 0xFF }; + } + } + + return new byte[] { 0xFF }; + } + + private static async Task TryReadOnce(MainWindow _mainWindow, int expectedLength, CancellationToken token) + { + var buffer = new List(); + var startTime = DateTime.UtcNow; + var timeout = 3000; + while ((DateTime.UtcNow - startTime).TotalMilliseconds < timeout) + { + token.ThrowIfCancellationRequested(); + if (_mainWindow._port != null && _mainWindow._port.IsOpen) + { + int available = _mainWindow._port.BytesToRead; + if (available > 0) + { + byte[] temp = new byte[available]; + _mainWindow._port.Read(temp, 0, available); + buffer.AddRange(temp); + if (buffer.Count >= 3) + { + var response = buffer.ToArray(); + if (response.Length < expectedLength) + { + //Debug.WriteLine($"Invalid response length: got {response.Length}, expected {expectedLength}"); + return new byte[] { 0xFF }; + } + if (!IsValidCrc(response)) + { + //Debug.WriteLine("Invalid CRC in response"); + return new byte[] { 0xFF }; + } + var err = MainWindow.errors.FirstOrDefault(x => x.Condition == Error.GridCondition.NoBoardCom); + if (err != null) err.isDeleted = true; + return response; + } + } + } + await Task.Delay(1); + } + //Debug.WriteLine("Response timeout"); + return new byte[] { 0xFF }; + } + + private static bool IsValidCrc(byte[] data) + { + if (data.Length < 3) return false; + ushort calculated = ComputeCRC(data.AsSpan(0, data.Length - 2)); + ushort received = (ushort)(data[^2] | (data[^1] << 8)); + return calculated == received; + } + private static ushort ComputeCRC(ReadOnlySpan data) + { + ushort crc = 0xFFFF; + foreach (var b in data) + { + crc ^= b; + for (int i = 0; i < 8; i++) + { + if ((crc & 0x0001) != 0) + { + crc >>= 1; + crc ^= 0xA001; + } + else + { + crc >>= 1; + } + } + } + return crc; + } + static int ConvertToDecimal(List bitPositions) + { + int result = 0; + if (bitPositions.Count() == 1 && bitPositions[0] == -1) + { + return result; + } + foreach (var pos in bitPositions) + { + if (pos is >= 0 and < 16) + result |= 1 << pos; + } + return result; + } + } +} diff --git a/DaireApplication/Pedal_Based_Fountain_Control_Implementation.md b/DaireApplication/Pedal_Based_Fountain_Control_Implementation.md new file mode 100644 index 0000000..bd49fe1 --- /dev/null +++ b/DaireApplication/Pedal_Based_Fountain_Control_Implementation.md @@ -0,0 +1,247 @@ +# Pedal-Based Fountain Control Implementation + +## Overview + +This implementation replaces the previous automatic fountain control with a **direct pedal-based control system**. When the pedal is in AUTO mode, the chocolate fountain directly follows the pedal state - ON when pedal is active, OFF when pedal is inactive. + +## ✅ Expected Behavior + +When pedal is in **AUTO mode**: +- **Pedal ON** (pedalState = 0) → **Chocolate ON** (fountain flows) +- **Pedal OFF** (pedalState = 1) → **Chocolate OFF** (fountain stops) +- **No blinking/flashing** of the Chocolate button +- **Clean alternating ON/OFF** based on pedal timing settings + +## 🔧 Implementation Details + +### 1. Direct Fountain Control Logic + +Located in the main monitoring loop (`pedalMotor == 1` section): + +```csharp +else if (pedalMotor == 1) // auto Pedal +{ + // Set auto mode flag + isPedalAutoMode = true; + + // Direct fountain control based on pedal state + var fount = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + if (fount != null && fount.BitNumbers.Count > 0) + { + if (pedalState == 0) // Pedal ON - Turn fountain ON + { + foreach (var bit in fount.BitNumbers) + { + holdingRegister.motor |= (ushort)(1 << bit); // Set the motor bit ON + } + isFountainMotorOn = true; + startFountainMotor = 1; + sendComFountainMotor = 1; + startFountainMotorFlashing = -1; // No flashing + // ... UI updates and hardware commands + } + else if (pedalState == 1) // Pedal OFF - Turn fountain OFF + { + foreach (var bit in fount.BitNumbers) + { + holdingRegister.motor &= (ushort)~(1 << bit); // Clear the motor bit OFF + } + isFountainMotorOn = false; + startFountainMotor = 0; + sendComFountainMotor = 0; + startFountainMotorFlashing = -1; // No flashing + // ... UI updates and hardware commands + } + } + + // Handle pedal timing (alternating ON/OFF based on recipe settings) + // ... timer management logic +} +``` + +### 2. Pedal Timing Configuration + +From the UI, users can configure: +- **PEDAL OFF TIME**: Duration fountain stays OFF (e.g., 1 unit) +- **PEDAL ON TIME**: Duration fountain stays ON (e.g., 2 seconds) + +The system automatically alternates between these states using timers. + +### 3. UI Feedback + +#### Chocolate Button State +- **ON**: Shows "ON" with active color (magenta underline) +- **OFF**: Shows "OFF" with passive color (gray) +- **No flashing/blinking** during automatic operation + +#### Temperature Display +When fountain is ON, the UI also shows: +- Current Temp: [actual temperature] +- Target Temp: [target temperature] + +### 4. Manual Override + +When user manually clicks the fountain button: +- **Resets pedal auto mode** (`isPedalAutoMode = false`) +- **Stops all pedal timers** +- **Switches to manual mode** (`pedalMotor = -1`) +- **User gains full manual control** + +### 5. Protection Logic + +#### Fountain Control Protection +Normal fountain control logic is disabled when pedal auto mode is active: + +```csharp +// Temperature-based control (disabled in pedal auto mode) +if (checkFountainTMT_PMT && !isPedalAutoMode) + +// Manual control (disabled in pedal auto mode) +if (!checkFountainTMT_PMT && !isPedalAutoMode) + +// Flashing processing (disabled in pedal auto mode) +if (startFountainMotorFlashing == 1 && !isPedalAutoMode) +``` + +#### UI Flashing Protection +The InteractiveUILoop prevents button flashing in pedal auto mode: + +```csharp +// Only flash when not in pedal auto mode +if (_mainWindow.startFountainMotorFlashing == 1 && !_mainWindow.isPedalAutoMode) +``` + +## 🔄 Control Flow + +1. **User sets pedal to AUTO mode** + - Pedal timers start alternating + - `isPedalAutoMode = true` + +2. **Pedal timer triggers state change** + - `pedalState = 0` (ON) or `pedalState = 1` (OFF) + +3. **Main monitoring loop processes state** + - Directly controls fountain motor based on pedal state + - Updates UI immediately + - Sends hardware commands + +4. **Fountain responds immediately** + - ON: Chocolate flows + - OFF: Chocolate stops + - No delays or intermediate states + +5. **Cycle repeats based on timing settings** + - OFF for configured duration + - ON for configured duration + +## 🛡️ Safety Features + +1. **Manual Override**: User can always take manual control +2. **Timer Cleanup**: Pedal timers are properly stopped when needed +3. **State Reset**: Pedal auto mode is reset when starting/stopping recipes +4. **No Conflicts**: Other fountain control mechanisms are disabled during pedal auto mode +5. **Immediate Response**: No delays or buffering - fountain responds instantly to pedal state + +## 🚫 Previous Logic Removed + +The following complex logic was removed and replaced with direct control: +- ❌ Temperature threshold-based fountain control in pedal auto mode +- ❌ Automatic fountain control based on second control box +- ❌ Complex state management with multiple flags +- ❌ Delayed or conditional fountain control +- ❌ Multiple control mechanisms that could conflict + +## 📱 User Interface + +### Settings Panel +Shows current pedal configuration: +- **PEDAL**: AUTO/MANUAL toggle button +- **PEDAL OFF TIME**: Adjustable duration (e.g., 1 unit) +- **PEDAL ON TIME**: Adjustable duration (e.g., 2 seconds) + +### Fountain Button +- **Steady state display** (ON/OFF) +- **Color coding**: Active (magenta) / Passive (gray) +- **No blinking/flashing** during automatic operation +- **Click to override** and take manual control + +## 🧪 Testing Scenarios + +### Scenario 1: Basic Auto Mode Operation +1. Set pedal to AUTO mode +2. Configure timing (e.g., 2s ON, 1 unit OFF) +3. **Expected**: Fountain alternates cleanly between ON/OFF states + +### Scenario 2: Manual Override +1. While in auto mode, click fountain button +2. **Expected**: Auto mode stops, user gains manual control + +### Scenario 3: Recipe Integration +1. Start recipe with pedal in AUTO mode +2. Complete all phases +3. **Expected**: Fountain follows pedal timing throughout + +### Scenario 4: Visual Feedback +1. Observe fountain button during auto operation +2. **Expected**: Clean ON/OFF display without blinking + +## 📋 Configuration + +### Pedal Timing Settings +- Configured through Settings UI +- **PEDAL OFF TIME**: How long fountain stays OFF +- **PEDAL ON TIME**: How long fountain stays ON +- Values are saved in recipe table + +### Control Mode +- **AUTO**: Fountain follows pedal timing automatically +- **MANUAL**: User controls fountain manually via button clicks + +## 🔧 Key Improvements + +### Simplified Logic ✅ +- **Direct control**: Pedal state directly controls fountain +- **No intermediate states** or complex decision trees +- **Immediate response** with no delays + +### User Experience ✅ +- **Predictable behavior**: ON when pedal ON, OFF when pedal OFF +- **Visual clarity**: Clean state display without blinking +- **Easy override**: Click fountain button to take manual control + +### Reliability ✅ +- **No conflicts**: Other control mechanisms properly disabled +- **Clean state management**: Single source of truth for pedal auto mode +- **Proper cleanup**: Timers and states reset when needed + +### Performance ✅ +- **Efficient processing**: Minimal logic overhead +- **Instant response**: No waiting or buffering +- **Resource management**: Proper timer lifecycle management + +## 📝 Technical Notes + +### Timer Management +- `pedalOnTimer`: Controls ON duration +- `pedalOffTimer`: Controls OFF duration +- Timers are properly disposed when not needed + +### State Variables +- `isPedalAutoMode`: Main flag indicating pedal auto mode is active +- `pedalState`: Current pedal state (0=ON, 1=OFF, -1=reset) +- `pedalMotor`: Pedal mode (1=AUTO, -1=MANUAL) + +### Hardware Control +- Direct bit manipulation of `holdingRegister.motor` +- Immediate serial communication with hardware +- Synchronized UI updates + +## ✅ Requirements Fulfilled + +✅ **Direct pedal control**: Fountain follows pedal state exactly +✅ **Timing-based operation**: Uses configured ON/OFF durations +✅ **No blinking**: Clean visual feedback without flashing +✅ **Manual override**: User can always take control +✅ **Proper integration**: Works with existing recipe system +✅ **Clean UI**: Professional appearance without distractions +✅ **Reliable operation**: No conflicts or unexpected behavior \ No newline at end of file diff --git a/DaireApplication/Program.cs b/DaireApplication/Program.cs new file mode 100644 index 0000000..930fc43 --- /dev/null +++ b/DaireApplication/Program.cs @@ -0,0 +1,33 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.ReactiveUI; +using AvaloniaApplication1.DataBase; +using System; +using System.Threading.Tasks; + +namespace DaireApplication +{ + internal sealed class Program + { + // Initialization code. Don't use any Avalonia, third-party APIs or any + // SynchronizationContext-reliant code before AppMain is called: things aren't initialized + // yet and stuff might break. + [STAThread] + public static void Main(string[] args) => BuildAvaloniaApp() + .StartWithClassicDesktopLifetime(args); + public static UserTable? currentUser; + + public static int pouringMinTemp = -5; + public static int absoluteMaxTemp = 70; + public static int absoluteMinTemp = -10; + // Avalonia configuration, don't remove; also used by visual designer. + public static AppBuilder BuildAvaloniaApp() + => AppBuilder.Configure() + .UsePlatformDetect() + .WithInterFont() + .LogToTrace() + .UseReactiveUI(); + + + } +} diff --git a/DaireApplication/Properties/PublishProfiles/FolderProfile.pubxml b/DaireApplication/Properties/PublishProfiles/FolderProfile.pubxml new file mode 100644 index 0000000..813ca27 --- /dev/null +++ b/DaireApplication/Properties/PublishProfiles/FolderProfile.pubxml @@ -0,0 +1,17 @@ + + + + + Release + Any CPU + C:\Users\Swb\Desktop\test + FileSystem + <_TargetId>Folder + net8.0 + win-x64 + true + false + false + false + + \ No newline at end of file diff --git a/DaireApplication/Recipe_System_Enhancement_Summary.md b/DaireApplication/Recipe_System_Enhancement_Summary.md new file mode 100644 index 0000000..d9d62b4 --- /dev/null +++ b/DaireApplication/Recipe_System_Enhancement_Summary.md @@ -0,0 +1,225 @@ +# Recipe System Enhancement Summary + +## Overview +This document outlines the comprehensive enhancements made to the recipe system in the DaireApplication, implementing proper goal checking, timer initiation, and phase transitions as requested. + +## Key Features Implemented + +### 1. Goal Check and Validation +- **Input Validation**: Validates recipe parameters before starting +- **Temperature Goal Validation**: Ensures heating, cooling, and pouring goals are reasonable +- **Logical Validation**: Verifies cooling goal is less than heating goal +- **Real-time Monitoring**: Continuously monitors temperature goals during execution + +### 2. Timer Initiation Logic +- **Dual Goal Checking**: Checks both mixer (tank) and chocolate (fountain) heating goals +- **Conditional Timer Start**: Only starts timers when both goals are met +- **Phase-specific Timers**: Separate timers for heating, cooling, and pouring phases +- **Automatic Phase Transitions**: Seamless transitions between phases + +### 3. Temperature Monitoring and Phase Transitions +- **Continuous Temperature Tracking**: Monitors chocolate temperature throughout the process +- **Cooling Phase Logic**: + - If chocolate temperature equals cooling threshold → Shows cooling delay + - If chocolate temperature not at cooling threshold → Initiates cooling phase +- **Error Handling**: Comprehensive error handling for temperature deviations +- **Warning System**: Proactive warnings when temperatures approach limits + +## Implementation Details + +### Enhanced RecipeStartBtn Method +```csharp +public async void RecipeStartBtn(object? sender, RoutedEventArgs e) +{ + // 1. Initialize and validate recipe parameters + if (!await InitializeAndValidateRecipe()) return; + + // 2. Start goal monitoring and phase transitions + await StartRecipePhaseMonitoring(); + + // 3. Update UI and begin execution +} +``` + +### Goal Checking Methods +```csharp +// Check if mixer heating goal is reached +private async Task CheckMixerHeatingGoal() +{ + bool goalMet = comTankTemp >= recipeHeatingGoal - 3; + // Provides user feedback when goal is reached + return goalMet; +} + +// Check if chocolate heating goal is reached +private async Task CheckChocolateHeatingGoal() +{ + bool goalMet = comFountainTemp >= recipeHeatingGoal - 3; + // Provides user feedback when goal is reached + return goalMet; +} +``` + +### Phase Transition Logic +```csharp +// Handle cooling phase transition based on chocolate temperature +private async Task HandleCoolingPhaseTransition(Settings settings) +{ + bool chocolateAtCoolingTemp = Math.Abs(comFountainTemp - recipeCoolingGoal) <= 3; + + if (chocolateAtCoolingTemp && cooling == -1 && Heating == -1) + { + await ShowCoolingDelay(settings); // Show delay when at target + } + else if (!chocolateAtCoolingTemp && cooling == -1 && Heating == -1) + { + await InitiateCoolingPhase(settings); // Start cooling phase + } +} +``` + +## Enhanced Timer Methods + +### HeatingTimer +- **Improved Error Detection**: Better temperature range checking +- **Enhanced User Feedback**: Detailed status messages with current temperatures +- **Automatic Phase Transition**: Seamlessly transitions to cooling phase +- **Warning System**: Proactive warnings for temperature deviations + +### CoolingTimer +- **Conditional Phase Logic**: Handles both cooling delay and active cooling +- **Temperature Monitoring**: Continuous monitoring of chocolate temperature +- **UI Updates**: Shows/hides cooling delay indicators appropriately +- **Phase Completion**: Automatic transition to pouring phase + +### PouringTimer +- **Recipe Completion**: Handles final phase of recipe execution +- **Pedal Control**: Automatically configures pedal based on recipe settings +- **Success Feedback**: Provides clear completion status +- **Error Handling**: Comprehensive error handling for final phase + +## User Interface Enhancements + +### Real-time Status Updates +- **Temperature Display**: Shows current vs target temperatures +- **Phase Indicators**: Clear indication of current phase +- **Countdown Timers**: Visual countdown for delays +- **Error Messages**: Descriptive error messages with temperature details + +### Enhanced Feedback +- **Goal Achievement**: Notifications when heating goals are reached +- **Phase Transitions**: Clear messages for phase changes +- **Completion Status**: Success messages when recipe completes +- **Warning System**: Proactive warnings for potential issues + +## Error Handling and Safety + +### Comprehensive Validation +- **Recipe Data Validation**: Ensures recipe exists and is valid +- **Temperature Goal Validation**: Validates all temperature parameters +- **Logical Validation**: Ensures goals make logical sense +- **Runtime Validation**: Continuous validation during execution + +### Error Recovery +- **Temperature Error Handling**: Handles temperature deviations gracefully +- **Timer Error Recovery**: Proper cleanup of timers on errors +- **UI State Recovery**: Maintains consistent UI state during errors +- **User Feedback**: Clear error messages for troubleshooting + +## Performance Optimizations + +### Asynchronous Operations +- **Non-blocking UI**: All operations run asynchronously +- **Efficient Monitoring**: Optimized temperature monitoring loops +- **Resource Management**: Proper timer cleanup and resource disposal +- **Memory Management**: Efficient memory usage for long-running operations + +### Timer Management +- **Conditional Timer Creation**: Only creates timers when needed +- **Proper Cleanup**: Ensures all timers are properly disposed +- **State Management**: Maintains consistent timer states +- **Error Recovery**: Handles timer failures gracefully + +## Benefits of the Enhanced System + +### 1. Improved Reliability +- **Goal Validation**: Prevents invalid recipe execution +- **Error Detection**: Early detection of temperature issues +- **Automatic Recovery**: Self-healing from minor issues +- **Consistent Behavior**: Predictable phase transitions + +### 2. Better User Experience +- **Clear Feedback**: Users always know what's happening +- **Real-time Updates**: Live temperature and status information +- **Intuitive Flow**: Logical progression through phases +- **Error Clarity**: Clear error messages for troubleshooting + +### 3. Enhanced Safety +- **Temperature Monitoring**: Continuous safety monitoring +- **Automatic Stops**: Stops on critical temperature deviations +- **Validation**: Prevents dangerous recipe configurations +- **Recovery**: Graceful handling of unexpected conditions + +### 4. Maintainability +- **Modular Design**: Clear separation of concerns +- **Comprehensive Documentation**: Well-documented methods +- **Error Handling**: Robust error handling throughout +- **Code Organization**: Logical method organization + +## Usage Instructions + +### Starting a Recipe +1. **Select Recipe**: Choose a valid recipe with proper temperature goals +2. **Click Start**: Click "START RECIPE" button +3. **Monitor Progress**: Watch real-time temperature and phase updates +4. **Handle Errors**: Respond to any error messages that appear + +### Understanding Phases +1. **Heating Phase**: Waits for both mixer and chocolate to reach heating goal +2. **Cooling Phase**: Either shows delay (if at target) or actively cools +3. **Pouring Phase**: Final phase with temperature monitoring +4. **Completion**: Recipe finishes and prepares for pouring + +### Error Handling +- **Temperature Errors**: Check temperature sensors and heating systems +- **Validation Errors**: Verify recipe configuration +- **Timer Errors**: Restart recipe if timers fail +- **Phase Errors**: Check phase transition conditions + +## Technical Specifications + +### Temperature Tolerances +- **Goal Checking**: ±3°C tolerance for goal achievement +- **Error Limits**: Configurable via `screenData.errorLimit` +- **Warning Limits**: Configurable via `screenData.warningLimit` + +### Timer Intervals +- **Monitoring Frequency**: 1 second intervals for temperature checking +- **UI Updates**: Real-time UI updates via Dispatcher +- **Phase Transitions**: Immediate phase transitions when conditions are met + +### Memory Management +- **Timer Cleanup**: Automatic cleanup of completed timers +- **Resource Disposal**: Proper disposal of all resources +- **State Reset**: Complete state reset on recipe stop + +## Future Enhancements + +### Potential Improvements +1. **Recipe Templates**: Pre-configured recipe templates +2. **Advanced Monitoring**: Additional sensor monitoring +3. **Data Logging**: Recipe execution logging +4. **Remote Monitoring**: Remote recipe monitoring capabilities +5. **Machine Learning**: Predictive temperature control + +### Scalability Considerations +1. **Multiple Recipes**: Support for concurrent recipe execution +2. **Advanced Phases**: Additional recipe phases +3. **Custom Validations**: User-defined validation rules +4. **Integration**: Integration with external systems + +## Conclusion + +The enhanced recipe system provides a robust, reliable, and user-friendly solution for chocolate tempering operations. With comprehensive goal checking, intelligent phase transitions, and extensive error handling, the system ensures consistent, high-quality results while providing clear feedback to operators. + +The modular design and comprehensive documentation make the system maintainable and extensible for future enhancements. The asynchronous architecture ensures responsive user interface while maintaining system reliability and safety. \ No newline at end of file diff --git a/DaireApplication/Temperature_Error_Fix_Summary.md b/DaireApplication/Temperature_Error_Fix_Summary.md new file mode 100644 index 0000000..8212825 --- /dev/null +++ b/DaireApplication/Temperature_Error_Fix_Summary.md @@ -0,0 +1,217 @@ +# Temperature Error Fix Summary + +## Problem Analysis + +### Issue Identified +The system was incorrectly showing "Temperature Error!!" popup during the heating phase when temperatures were **above** the heating goal. This prevented the system from properly transitioning to the cooling phase. + +### Root Cause +The temperature error detection logic was using a **symmetric range** (±2°C around the target) for all phases, which is incorrect: + +- **Heating Phase**: Should only error if temperature is **below** the goal +- **Cooling Phase**: Should only error if temperature is **above** the goal +- **Pouring Phase**: Should error if temperature is outside the acceptable range + +### Example from Image +- **Current Temperature**: 51.0°C +- **Heating Goal**: 46°C +- **Error Limit**: 2°C +- **Old Logic**: Acceptable range = 44°C to 48°C ❌ +- **New Logic**: Acceptable range = 46°C and above ✅ + +## Fixes Implemented + +### 1. HeatingTimer - Fixed Temperature Error Logic + +**Before:** +```csharp +// Symmetric range check (incorrect for heating) +bool tempInRange = (comFountainTemp * 10 >= (recipeHeatingGoal * 10) - (screenData.errorLimit * 10)) && + (comFountainTemp * 10 <= (recipeHeatingGoal * 10) + (screenData.errorLimit * 10)); +``` + +**After:** +```csharp +// Only check if temperature is too low (correct for heating) +bool tempTooLow = comFountainTemp < (recipeHeatingGoal - screenData.errorLimit); +``` + +**Logic:** +- ✅ **Temperatures above goal**: Acceptable during heating +- ❌ **Temperatures below goal**: Show error +- ✅ **Goal achieved**: Proceed to cooling phase + +### 2. CoolingTimer - Fixed Temperature Error Logic + +**Before:** +```csharp +// Symmetric range check (incorrect for cooling) +bool tempInRange = (comFountainTemp * 10 >= (recipeCoolingGoal * 10) - (screenData.errorLimit * 10)) && + (comFountainTemp * 10 <= (recipeCoolingGoal * 10) + (screenData.errorLimit * 10)); +``` + +**After:** +```csharp +// Only check if temperature is too high (correct for cooling) +bool tempTooHigh = comFountainTemp > (recipeCoolingGoal + screenData.errorLimit); +``` + +**Logic:** +- ✅ **Temperatures below goal**: Acceptable during cooling +- ❌ **Temperatures above goal**: Show error +- ✅ **Goal achieved**: Proceed to pouring phase + +### 3. PouringTimer - Maintained Correct Logic + +**Before & After:** +```csharp +// Symmetric range check (correct for pouring) +bool tempInRange = (comFountainTemp >= (recipePouringGoal - screenData.errorLimit)) && + (comFountainTemp <= (recipePouringGoal + screenData.errorLimit)); +``` + +**Logic:** +- ✅ **Temperatures within range**: Acceptable for pouring +- ❌ **Temperatures outside range**: Show error +- ✅ **Goal achieved**: Recipe completed + +### 4. Goal Checking Methods - Updated Logic + +**Before:** +```csharp +// Using 3°C tolerance (too permissive) +bool goalMet = comFountainTemp >= recipeHeatingGoal - 3; +``` + +**After:** +```csharp +// Exact goal checking (more precise) +bool goalMet = comFountainTemp >= recipeHeatingGoal; +``` + +### 5. Cooling Phase Transition - Updated Logic + +**Before:** +```csharp +// Using 3°C tolerance around cooling goal +bool chocolateAtCoolingTemp = Math.Abs(comFountainTemp - recipeCoolingGoal) <= 3; +``` + +**After:** +```csharp +// Check if temperature is at or below cooling goal +bool chocolateAtCoolingTemp = comFountainTemp <= recipeCoolingGoal; +``` + +## Phase-Specific Logic Summary + +### Heating Phase +- **Goal**: Reach or exceed heating temperature +- **Error Condition**: Temperature below (goal - errorLimit) +- **Success Condition**: Temperature >= goal +- **Next Phase**: Cooling + +### Cooling Phase +- **Goal**: Reach or go below cooling temperature +- **Error Condition**: Temperature above (goal + errorLimit) +- **Success Condition**: Temperature <= goal +- **Next Phase**: Pouring + +### Pouring Phase +- **Goal**: Maintain temperature within range +- **Error Condition**: Temperature outside (goal ± errorLimit) +- **Success Condition**: Temperature within range +- **Next Phase**: Recipe completion + +## Error Messages Improved + +### Before +- Generic: "Temperature error: 51.0°C (Target: 46°C)" + +### After +- **Heating**: "Heating temperature too low: 51.0°C (Target: 46°C)" +- **Cooling**: "Cooling temperature too high: 51.0°C (Target: 27°C)" +- **Pouring**: "Pouring temperature out of range: 51.0°C (Target: 30°C)" + +## Warning Messages Improved + +### Before +- Generic: "Temperature approaching limits" + +### After +- **Heating**: "Heating temperature approaching minimum" +- **Cooling**: "Cooling temperature approaching maximum" +- **Pouring**: "Pouring temperature approaching limits" + +## Expected Behavior After Fix + +### Scenario from Image +1. **Current State**: Heating phase with 51.0°C (above 46°C goal) +2. **Old Behavior**: ❌ Shows error popup, prevents progression +3. **New Behavior**: ✅ Recognizes goal achieved, proceeds to cooling +4. **Next Step**: Cooling phase starts automatically + +### Complete Flow +1. **Heating Phase**: + - Wait for both mixer and chocolate to reach heating goal + - No error if temperature exceeds goal + - Proceed to cooling when goals met + +2. **Cooling Phase**: + - Check if chocolate temperature is at/below cooling goal + - If yes: Show cooling delay + - If no: Start active cooling + - Proceed to pouring when cooling complete + +3. **Pouring Phase**: + - Maintain temperature within pouring range + - Complete recipe when pouring timer finishes + +## Benefits of the Fix + +### 1. Correct Phase Progression +- ✅ Heating phase completes when goals are met +- ✅ Cooling phase starts automatically +- ✅ No false error popups + +### 2. Improved User Experience +- ✅ Clear, phase-specific error messages +- ✅ Logical temperature validation +- ✅ Smooth phase transitions + +### 3. Enhanced Safety +- ✅ Proper error detection for each phase +- ✅ Appropriate warnings for each condition +- ✅ Maintains safety while allowing progression + +### 4. Better Reliability +- ✅ Eliminates false error conditions +- ✅ Ensures recipe completion +- ✅ Maintains quality control + +## Testing Recommendations + +### Test Scenarios +1. **Normal Heating**: Temperature reaches and exceeds goal +2. **Slow Heating**: Temperature takes time to reach goal +3. **Fast Heating**: Temperature quickly exceeds goal +4. **Cooling Transition**: Verify cooling phase starts +5. **Error Conditions**: Test actual error scenarios + +### Validation Points +- ✅ No error popup when temperature exceeds heating goal +- ✅ Cooling phase starts after heating delay completes +- ✅ Cooling delay shows when temperature is at/below cooling goal +- ✅ Pouring phase starts after cooling completes +- ✅ Recipe completes successfully + +## Conclusion + +The fix addresses the core issue where the system incorrectly treated temperatures above the heating goal as errors. With the corrected phase-specific logic, the system now: + +1. **Recognizes heating success** when temperatures reach or exceed the goal +2. **Proceeds to cooling phase** automatically after heating delay +3. **Shows appropriate errors** only when temperatures are actually problematic +4. **Provides clear feedback** for each phase and condition + +This ensures the recipe system works as intended, providing reliable chocolate tempering with proper phase progression and error handling. \ No newline at end of file diff --git a/DaireApplication/ViewLocator.cs b/DaireApplication/ViewLocator.cs new file mode 100644 index 0000000..10e704d --- /dev/null +++ b/DaireApplication/ViewLocator.cs @@ -0,0 +1,32 @@ +using Avalonia.Controls; +using Avalonia.Controls.Templates; +using DaireApplication.ViewModels; +using System; + +namespace DaireApplication +{ + public class ViewLocator : IDataTemplate + { + + public Control? Build(object? param) + { + if (param is null) + return null; + + var name = param.GetType().FullName!.Replace("ViewModel", "View", StringComparison.Ordinal); + var type = Type.GetType(name); + + if (type != null) + { + return (Control)Activator.CreateInstance(type)!; + } + + return new TextBlock { Text = "Not Found: " + name }; + } + + public bool Match(object? data) + { + return data is ViewModelBase; + } + } +} diff --git a/DaireApplication/ViewModels/Error.cs b/DaireApplication/ViewModels/Error.cs new file mode 100644 index 0000000..aa553d6 --- /dev/null +++ b/DaireApplication/ViewModels/Error.cs @@ -0,0 +1,93 @@ +using Avalonia.Controls; +using Avalonia.Threading; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.NetworkInformation; +using System.Text; +using System.Threading.Tasks; +using static DaireApplication.Views.MainWindow; + +namespace DaireApplication.ViewModels +{ + public class Error + { + public enum GridCondition + { + GridFrequencyHigh, + GridFrequencyLow, + GridVACHigh, + GridVACLow, + NoExternalPower, + MissingPhase, + PhaseSequence, + LoadDisconnection, + MotorDisconnection, + NoBoardCom, + NoInternetAccess, + ComPort1, + ComPort2, + HiCurrNeut, + HiCurrMot1, + HiCurrMot2, + } + public DateTime errorDate { get; set; } + public GridCondition Condition { get; set; } + public bool isShowen { get; set; } = false; + public bool isDeleted { get; set; } = false; + + public string GetDisplayNames(GridCondition condition) + { + return condition switch + { + GridCondition.GridFrequencyHigh => "Grid Frequency High", + GridCondition.GridFrequencyLow => "Grid Frequency Low", + GridCondition.GridVACHigh => "Grid VAC High", + GridCondition.GridVACLow => "Grid VAC Low", + GridCondition.NoExternalPower => "No External Power", + GridCondition.MissingPhase => "Missing Phase", + GridCondition.PhaseSequence => "Phase Sequence", + GridCondition.LoadDisconnection => "Load Disconnection", + GridCondition.MotorDisconnection => "Motor Disconnection", + GridCondition.NoBoardCom => "Communication Timeout", + GridCondition.NoInternetAccess => "No InternetAccess", + GridCondition.ComPort1 => "Com Port1", + GridCondition.ComPort2 => "Com Port2", + GridCondition.HiCurrNeut=> "Hi Curr Neut", + GridCondition.HiCurrMot1=> "Hi Curr Mot1", + GridCondition.HiCurrMot2=> "Hi Curr Mot2", + _ => string.Empty + }; + + + } + public static bool IsInternetAvailable() + { + try + { + var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); + + foreach (var networkInterface in networkInterfaces) + { + if (networkInterface.OperationalStatus == OperationalStatus.Up) + { + using (var ping = new Ping()) + { + var reply = ping.Send("8.8.8.8", 3000); // Pinging Google DNS server with a timeout of 3000ms + if (reply != null && reply.Status == IPStatus.Success) + { + return true; // Internet is available + } + } + } + } + } + catch (Exception) + { + return false; // Return false if there is any exception (e.g., no network interface found, or errors during checking) + } + + return false; // Return false if no network interfaces are available or no successful ping + } + } +} diff --git a/DaireApplication/ViewModels/HoldingRegister.cs b/DaireApplication/ViewModels/HoldingRegister.cs new file mode 100644 index 0000000..1cd2cd6 --- /dev/null +++ b/DaireApplication/ViewModels/HoldingRegister.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DaireApplication.ViewModels +{ + public class HoldingRegister + { + public ushort resetError { get; set; } = 0; + public ushort hvOut { get; set; } = 0; + public ushort lvOut { get; set; } = 0; + public ushort motor { get; set; } = 0; + public int setTemp1 { get; set; } = -10000; + public int setTemp2 { get; set; } = -10000; + public int setTemp3 { get; set; } = -10000; + public int setTemp4 { get; set; } = -10000; + } +} diff --git a/DaireApplication/ViewModels/MainWindowViewModel.cs b/DaireApplication/ViewModels/MainWindowViewModel.cs new file mode 100644 index 0000000..19227fb --- /dev/null +++ b/DaireApplication/ViewModels/MainWindowViewModel.cs @@ -0,0 +1,7 @@ +namespace DaireApplication.ViewModels +{ + public class MainWindowViewModel : ViewModelBase + { + public string Greeting { get; } = "Welcome to Avalonia!"; + } +} diff --git a/DaireApplication/ViewModels/ModBusMaster.cs b/DaireApplication/ViewModels/ModBusMaster.cs new file mode 100644 index 0000000..d673249 --- /dev/null +++ b/DaireApplication/ViewModels/ModBusMaster.cs @@ -0,0 +1,306 @@ +using System; +using System.Collections.Generic; +using System.IO.Ports; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace AvaloniaApplication1.ViewModels +{ + public class ModBusMaster + { + public byte slaveId { get; set; } = 0x01; // Slave ID (your ESP slave ID) + //byte functionCode = 0x05; // Function code for Write Single Coil + //byte coilAddressHigh = 0x00; // Coil address (MSB) + //byte coilAddressLow = 0x00; // Coil address (LSB) + //byte coilValueHigh = 0x00; // Coil value (0xFF00 to turn on, 0x0000 to turn off) + //byte coilValueLow = 0x00; + + // Function to read coils + public async Task ReadCoils(SerialPort port, ushort startAddress, ushort numberOfCoils) + { + try + { + byte functionCode = 0x01; // Function code for Read Coils + byte[] frame = new byte[6]; // Request frame size (without CRC) + + // Construct the request frame + frame[0] = slaveId; // Slave address + frame[1] = functionCode; // Function code (0x01 for Read Coils) + frame[2] = (byte)(startAddress >> 8); // Start address high byte + frame[3] = (byte)(startAddress & 0xFF); // Start address low byte + frame[4] = (byte)(numberOfCoils >> 8); // Number of coils high byte + frame[5] = (byte)(numberOfCoils & 0xFF); // Number of coils low byte + + // Calculate CRC and append it to the frame + byte[] crc = CalculateCRC(frame); + byte[] fullFrame = new byte[frame.Length + crc.Length]; + Array.Copy(frame, fullFrame, frame.Length); + Array.Copy(crc, 0, fullFrame, frame.Length, crc.Length); + + // Send the frame over the serial port + port.DiscardOutBuffer(); + port.DiscardInBuffer(); + + port.Write(fullFrame, 0, fullFrame.Length); + Thread.Sleep(500); + Console.WriteLine("Read Coils request sent."); + + // Buffer for the response (modbus slave response size can vary) + byte[] response = new byte[256]; + int bytesRead = port.Read(response, 0, response.Length); + Console.WriteLine("Response Coils sent."); + + + // Ensure that the response is valid (check slave address and function code) + if (response[0] != slaveId || response[1] != functionCode) + { + Console.WriteLine("Invalid response or error in slave response."); + return null; + } + + // Calculate the number of bytes based on the number of coils + int expectedByteCount = (numberOfCoils + 7) / 8; + if (response[2] != expectedByteCount) + { + Console.WriteLine("Incorrect byte count in the response."); + return null; + } + + // The response bytes are in bit form, and we need to extract them + bool[] coilStates = new bool[numberOfCoils]; // Array to store the coil states + int byteIndex = 3; // Start reading from byte 3 (after slave ID and function code) + byte coilByte = response[byteIndex]; // The byte representing the coil states + + // Loop over all coils and check the corresponding bit + for (int coilIndex = 0; coilIndex < numberOfCoils; coilIndex++) + { + // Check the state of the coil by checking the corresponding bit in coilByte + coilStates[coilIndex] = coilByte == 1 ? true : false; /*(coilByte & (1 << (7 - coilIndex))) != 0;*/ + } + if (coilStates==null) + { + Console.WriteLine("status wael: null"); + + } + else + { + Console.WriteLine($"status: {coilStates[0]}"); + + } + + return coilStates; + } + catch (Exception ex) + { + Console.WriteLine($"error wael: {ex.Message}"); + return null; + } + + } + + + // Function to write a single coil + public async Task WriteSingleCoil(ushort coilAddress, bool state) + { + byte functionCode = 0x05; + byte[] frame = new byte[6]; + + frame[0] = slaveId; // Slave address + frame[1] = functionCode; // Function code + frame[2] = (byte)(coilAddress >> 8); // Coil address high byte + frame[3] = (byte)(coilAddress & 0xFF); // Coil address low byte + frame[4] = (byte)(state ? 0xFF : 0x00); // Coil value (ON=0xFF, OFF=0x00) + frame[5] = (byte)(0x00); // Coil value (ON=0xFF, OFF=0x00) + + // Calculate CRC and append it + byte[] crc = CalculateCRC(frame); + byte[] fullFrame = new byte[frame.Length + crc.Length]; + Array.Copy(frame, fullFrame, frame.Length); + Array.Copy(crc, 0, fullFrame, frame.Length, crc.Length); + + return fullFrame; + } + + + + + // Function to write multiple coils + public byte[] WriteMultipleCoils( ushort startAddress, bool[] coilValues) + { + byte functionCode = 0x0F; + int byteCount = (coilValues.Length + 7) / 8; // Calculate the number of bytes needed + byte[] frame = new byte[5 + byteCount]; // Basic frame without CRC + + frame[0] = slaveId; // Slave address + frame[1] = functionCode; // Function code + frame[2] = (byte)(startAddress >> 8); // Start address high byte + frame[3] = (byte)(startAddress & 0xFF); // Start address low byte + frame[4] = (byte)(coilValues.Length); // Number of coils + + frame[5] = (byte)byteCount; // Number of bytes to follow (coil values) + for (int i = 0; i < coilValues.Length; i++) + { + int byteIndex = 5 + 1 + (i / 8); // Start at byte 6, accounting for byte count + if (coilValues[i]) + { + frame[byteIndex] |= (byte)(1 << (i % 8)); // Set the bit corresponding to the coil + } + } + + // Calculate CRC and append it + byte[] crc = CalculateCRC(frame); + byte[] fullFrame = new byte[frame.Length + crc.Length]; + Array.Copy(frame, fullFrame, frame.Length); + Array.Copy(crc, 0, fullFrame, frame.Length, crc.Length); + + return fullFrame; + } + // Function to write multiple registers + public async Task WriteSingleRegister(ushort startAddress, int value) + { + byte functionCode = 0x06; // Function code for writing a single register + byte[] frame = new byte[6]; // Basic frame without CRC + + frame[0] = slaveId; // Slave address + frame[1] = functionCode; // Function code + frame[2] = (byte)(startAddress >> 8); // Start address high byte + frame[3] = (byte)(startAddress & 0xFF); // Start address low byte + frame[4] = (byte)(value >> 8); // Register value high byte + frame[5] = (byte)(value & 0xFF); // Register value low byte + + // Calculate CRC and append it + byte[] crc = CalculateCRC(frame); + byte[] fullFrame = new byte[frame.Length + crc.Length]; + Array.Copy(frame, fullFrame, frame.Length); + Array.Copy(crc, 0, fullFrame, frame.Length, crc.Length); + + return fullFrame; + } + public async Task WriteSingleRegister(ushort startAddress, ushort value) + { + byte functionCode = 0x06; // Function code for writing a single register + byte[] frame = new byte[6]; // Basic frame without CRC + + frame[0] = slaveId; // Slave address + frame[1] = functionCode; // Function code + frame[2] = (byte)(startAddress >> 8); // Start address high byte + frame[3] = (byte)(startAddress & 0xFF); // Start address low byte + frame[4] = (byte)(value >> 8); // Register value high byte + frame[5] = (byte)(value & 0xFF); // Register value low byte + + // Calculate CRC and append it + byte[] crc = CalculateCRC(frame); + byte[] fullFrame = new byte[frame.Length + crc.Length]; + Array.Copy(frame, fullFrame, frame.Length); + Array.Copy(crc, 0, fullFrame, frame.Length, crc.Length); + + return fullFrame; + } + public async Task ReadHoldingRegister(ushort startAddress, ushort numberOfRegisters) + { + byte functionCode = 0x03; // Function code for reading holding registers + byte[] frame = new byte[6]; // Basic frame without CRC + + frame[0] = slaveId; // Slave address + frame[1] = functionCode; // Function code + frame[2] = (byte)(startAddress >> 8); // Start address high byte + frame[3] = (byte)(startAddress & 0xFF); // Start address low byte + frame[4] = (byte)(numberOfRegisters >> 8); // Number of registers high byte + frame[5] = (byte)(numberOfRegisters & 0xFF); // Number of registers low byte + + // Calculate CRC and append it + byte[] crc = CalculateCRC(frame); + byte[] fullFrame = new byte[frame.Length + crc.Length]; + Array.Copy(frame, fullFrame, frame.Length); + Array.Copy(crc, 0, fullFrame, frame.Length, crc.Length); + + return fullFrame; + } + + + + public async Task ReadInputRegisters(ushort startAddress, ushort numberOfRegisters) + { + byte functionCode = 0x04; // Function code for reading input registers + byte[] frame = new byte[6]; // Basic frame without CRC + + frame[0] = slaveId; // Slave address + frame[1] = functionCode; // Function code + frame[2] = (byte)(startAddress >> 8); // Start address high byte + frame[3] = (byte)(startAddress & 0xFF); // Start address low byte + frame[4] = (byte)(numberOfRegisters >> 8); // Number of registers high byte + frame[5] = (byte)(numberOfRegisters & 0xFF); // Number of registers low byte + + // Calculate CRC and append it + byte[] crc = CalculateCRC(frame); + byte[] fullFrame = new byte[frame.Length + crc.Length]; + Array.Copy(frame, fullFrame, frame.Length); + Array.Copy(crc, 0, fullFrame, frame.Length, crc.Length); + + return fullFrame; + } + + + public async Task WriteMultipleRegisters(ushort startAddress, float[] values) + { + byte functionCode = 0x10; // Function code for writing multiple registers + byte byteCount = (byte)(values.Length * 2); // Total number of bytes for values + byte[] frame = new byte[7 + byteCount]; // Frame without CRC + + frame[0] = slaveId; // Slave address + frame[1] = functionCode; // Function code + frame[2] = (byte)(startAddress >> 8); // Start address high byte + frame[3] = (byte)(startAddress & 0xFF); // Start address low byte + frame[4] = (byte)(values.Length >> 8); // Number of registers high byte + frame[5] = (byte)(values.Length & 0xFF); // Number of registers low byte + frame[6] = byteCount; // Byte count + + for (int i = 0; i < values.Length; i++) + { + short val = unchecked((short)values[i]); + frame[7 + i * 2] = (byte)(val >> 8); // Register value high byte + frame[8 + i * 2] = (byte)(val & 0xFF); // Register value low byte1 + } + + // Calculate CRC and append it + byte[] crc = CalculateCRC(frame); + byte[] fullFrame = new byte[frame.Length + crc.Length]; + Array.Copy(frame, fullFrame, frame.Length); + Array.Copy(crc, 0, fullFrame, frame.Length, crc.Length); + + return fullFrame; + } + + + + // Function to calculate CRC16 for Modbus RTU frame + public byte[] CalculateCRC(byte[] data) + { + ushort crc = 0xFFFF; + + foreach (byte byteData in data) + { + crc ^= byteData; + + for (int i = 8; i > 0; i--) + { + if ((crc & 0x0001) == 0x0001) + { + crc >>= 1; + crc ^= 0xA001; + } + else + { + crc >>= 1; + } + } + } + + return new byte[] { (byte)(crc & 0xFF), (byte)((crc >> 8) & 0xFF) }; + } + + + } +} diff --git a/DaireApplication/ViewModels/ViewModelBase.cs b/DaireApplication/ViewModels/ViewModelBase.cs new file mode 100644 index 0000000..5ff6581 --- /dev/null +++ b/DaireApplication/ViewModels/ViewModelBase.cs @@ -0,0 +1,8 @@ +using ReactiveUI; + +namespace DaireApplication.ViewModels +{ + public class ViewModelBase : ReactiveObject + { + } +} diff --git a/DaireApplication/ViewModels/X11CursorHider.cs b/DaireApplication/ViewModels/X11CursorHider.cs new file mode 100644 index 0000000..f9cd303 --- /dev/null +++ b/DaireApplication/ViewModels/X11CursorHider.cs @@ -0,0 +1,69 @@ +using System; +using System.Runtime.InteropServices; + + public class X11CursorHider +{ + const string X11Lib = "libX11.so"; + + [DllImport(X11Lib)] + static extern IntPtr XOpenDisplay(IntPtr display); + + [DllImport(X11Lib)] + static extern int XCloseDisplay(IntPtr display); + + [DllImport(X11Lib)] + static extern IntPtr XCreatePixmap(IntPtr display, IntPtr drawable, uint width, uint height, uint depth); + + [DllImport(X11Lib)] + static extern IntPtr XCreateBitmapFromData(IntPtr display, IntPtr drawable, byte[] data, uint width, uint height); + + [DllImport(X11Lib)] + static extern IntPtr XCreatePixmapCursor(IntPtr display, IntPtr source, IntPtr mask, ref XColor foreground, ref XColor background, uint x, uint y); + + [DllImport(X11Lib)] + static extern int XDefineCursor(IntPtr display, IntPtr window, IntPtr cursor); + + [DllImport(X11Lib)] + static extern int XFreeCursor(IntPtr display, IntPtr cursor); + + [DllImport(X11Lib)] + static extern int XFlush(IntPtr display); + + [DllImport(X11Lib)] + static extern IntPtr XDefaultRootWindow(IntPtr display); + + [StructLayout(LayoutKind.Sequential)] + struct XColor + { + public ulong pixel; + public ushort red, green, blue; + public byte flags; + public byte pad; + } + + public static void HideCursor() + { + IntPtr display = XOpenDisplay(IntPtr.Zero); + if (display == IntPtr.Zero) + { + Console.WriteLine("Cannot open X display"); + return; + } + + IntPtr root = XDefaultRootWindow(display); + + byte[] emptyData = new byte[1] { 0 }; // 1x1 empty bitmap + IntPtr pixmap = XCreateBitmapFromData(display, root, emptyData, 1, 1); + + XColor dummy = new XColor(); + + IntPtr invisibleCursor = XCreatePixmapCursor(display, pixmap, pixmap, ref dummy, ref dummy, 0, 0); + + XDefineCursor(display, root, invisibleCursor); + XFlush(display); + + // Keep the cursor hidden until app closes, remember to call: + // XFreeCursor(display, invisibleCursor); + // XCloseDisplay(display); + } +} diff --git a/DaireApplication/Views/MainWindow.axaml b/DaireApplication/Views/MainWindow.axaml new file mode 100644 index 0000000..8949f9c --- /dev/null +++ b/DaireApplication/Views/MainWindow.axaml @@ -0,0 +1,487 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + V0.6 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/DaireApplication/Views/MainWindow.axaml.cs b/DaireApplication/Views/MainWindow.axaml.cs new file mode 100644 index 0000000..9e0c342 --- /dev/null +++ b/DaireApplication/Views/MainWindow.axaml.cs @@ -0,0 +1,4917 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.Shapes; +using Avalonia.Interactivity; +using Avalonia.Layout; +using Avalonia.Media; +using Avalonia.Threading; +using AvaloniaApplication1.ViewModels; +using DaireApplication.DataBase; +using DaireApplication.Loops; +using DaireApplication.ViewModels; +using DynamicData; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.IO.Ports; +using System.Linq; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; + +namespace DaireApplication.Views; + +public partial class MainWindow : Window +{ + #region properties + List buffer = new List(); + public ModBusMaster _modBusMaster = new ModBusMaster(); + public MachineTable _machine = new MachineTable(); + public ConfigrationTable _config = new ConfigrationTable(); + public List _configrations = new List(); + public Mapping _map = new Mapping(); + public ScreeenTable _screeen = new(); + public ErrorSettingsTable _error = new(); + public List _mapping = new List(); + public static bool isOff { get; set; } + const double deadZone = 1.5; // Changeable based on stability needs + bool shouldRunFountain = false; + public readonly SemaphoreSlim _keepSendingLock = new(1, 1); + + public SerialPort _port { get; set; } + private static Thread monitorThread; + private static Thread screenThread; + private static Thread touchThread; + private static Thread internetThread; + private static Thread InteractiveUIThread; + private static Thread serialThread; + public bool serialThreadRunning = true; + public bool isRunning = true; + public bool restBoard { get; set; } + public bool sendConfig { get; set; } = true; + public bool reSendHolding { get; set; } + public bool dontResetOutPuts { get; set; } + + bool allBitsOn = false; + bool allPedalBitsOn = false; + public int pedalState { get; set; } = -1; + public int pedalStateChanged { get; set; } = -1; + public float recipeHeatingGoal { get; set; } + public float recipeCoolingGoal { get; set; } + public float recipePouringGoal { get; set; } + + public string ActiveColor { get; set; } = "#A4275D"; + public string PassiveColor { get; set; } = "#666666"; + //Pre Heating + public bool isFlashPreHeating { get; set; } = false; + public bool isReadingTemp { get; set; } = true; + public int startPreHeating { get; set; } = -1; + public int writingMaxTemp { get; set; } = -1; + + //Mixer Motor + private Timer mixerTimer; + private Timer preMixerTimer; + private Timer unifiedMotorTimer; + + private static int mixerSeconds = 1; + private static int preMixerSeconds = 1; + public bool setMixerTimerOnce { get; set; } = false; + public bool checkMixerTWT_HWTH { get; set; } = false; + public bool isMixerMotorOn { get; set; } = false; + public int startMixerMotor { get; set; } = -1; + public int startMixerMotorFlashing { get; set; } = -1; + public int sendComMixerMotor { get; set; } = -1; + + //Fountain Motor + private Timer fountainTimer; + private Timer fountainPauseTimer; + private Timer noChoiceChoosenTimer; + + private static int fountainSeconds = 1; + private static int fountainPauseSeconds = 1; + private static int noChoiceChoosenSeconds = 0; + public bool setFountainTimerOnce { get; set; } = false; + public bool checkFountainTMT_PMT { get; set; } = false; + public bool isFountainMotorOn { get; set; } = false; + public int startFountainMotor { get; set; } = -1; + public int startFountainMotorFlashing { get; set; } = -1; + public int sendComFountainMotor { get; set; } = -1; + + public double comTankTemp { get; set; } = 0; + public double comFountainTemp { get; set; } = 0; + public double comPumpTemp { get; set; } = 0; + + //MOLD HEATER(off:0,on:1) , VIBRATION(off:0,on:1) , VIB. HEATER(off:0,on:1) + public int moldHeaterMotor { get; set; } = -1; + public int vibrationMotor { get; set; } = -1; + public int vibHeaterMotor { get; set; } = -1; + + //Pedal(manual=0,auto=1) + public int pedalMotor { get; set; } = -1; + + //Recipe Start + + public int startRecipe { get; set; } = 0; + public int sendComTankTemp { get; set; } = -1; + //phase 1 heating + public int Heating { get; set; } = -1; + public int sendComHeating { get; set; } = -1; + public int setHeatingTimerOnce { get; set; } = -1; + public Timer heatingTimer; + public int heatingSeconds { get; set; } = 0; + //phase 2 cooling + public int cooling { get; set; } = -1; + public int sendComCooling { get; set; } = -1; + public int setCoolingTimerOnce { get; set; } = -1; + public Timer coolingTimer; + public int coolingSeconds { get; set; } = 0; + + //phase 3 pouring + public int pouring { get; set; } = -1; + public int sendComPouring { get; set; } = -1; + public int setPouringTimerOnce { get; set; } = -1; + public Timer pouringTimer; + public int pouringSeconds { get; set; } = 0; + + //start the pumb + public int PumbOn { get; set; } = -1; + public Timer pedalOnTimer; + public Timer pedalOffTimer; + public int pedalOnSeconds { get; set; } = 0; + public int pedalOffSeconds { get; set; } = 0; + // 1 turn off ,0 turn on + public int setPedalTimerOnce { get; set; } = -1; + + //Board + + public bool resetPort { get; set; } = false; + public bool keepSendingFlag { get; set; } = false; + + public DateTime lastActivity = DateTime.Now; + + public ScreeenTable screenData = new(); + public static List errors = new(); + public bool pause { get; set; } + public bool unPause { get; set; } + public bool isPaused { get; set; } + public bool pauseTimer { get; set; } + public bool pauseTempTracking { get; set; } + public string warningMessage { get; set; } + + public HoldingRegister holdingRegister = new HoldingRegister(); + + public bool turnOnFountainMotor { get; set; } + public bool stopRecipeFlag { get; set; } + public bool isCoolingDelayMode { get; set; } = false; + public bool isPouringDelayMode { get; set; } = false; + public bool tempWarningAccepted { get; set; } = false; + public bool isPedalAutoMode { get; set; } = false; + public bool isAutomaticFountainControlActive { get; set; } = false; + + // Recipe phase tracking for footer message management + private enum RecipePhase + { + None, + PreHeating, + HeatingDelay, + CoolingPhase, + CoolingDelay, + PouringPhase, + Completed + } + private RecipePhase currentRecipePhase = RecipePhase.None; + + /// + /// Safely update footer message based on current recipe phase + /// + private string lastFooterMessage = ""; + private void UpdateFooterMessage(RecipePhase phase, string message) + { + // Don't update if recipe is completed (unless setting to completed) + if (currentRecipePhase == RecipePhase.Completed && phase != RecipePhase.Completed) + { + return; + } + + // Only update if message has actually changed + if (lastFooterMessage == message) + { + return; + } + + // Only update if we're in the correct phase or transitioning to it + if (currentRecipePhase == phase || phase != RecipePhase.None) + { + currentRecipePhase = phase; + lastFooterMessage = message; + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = message; + }); + } + } + + public Timer stopMixerTimer; + public int stopMixerSecondes { get; set; } + public Timer stopFountainTimer; + public int stopFountainSecondes { get; set; } + + public DateTime _lastPacketSendTime = DateTime.MinValue; + public byte[] inputesResponse = new byte[] { 0xFF }; + + // Replace isWriting flag with async method + public TaskCompletionSource _writeCompletionSource = new TaskCompletionSource(); + #endregion + public Task WriteToSerialAsync(string caller) + { + _writeCompletionSource = new TaskCompletionSource(); + // Optionally log or store the caller for debugging + Debug.WriteLine($"WriteToSerialAsync called by: {caller}"); + return _writeCompletionSource.Task; + } + public void SetWriteComplete(bool success = true) + { + _writeCompletionSource?.TrySetResult(success); + } + + + + #region Construction + public MainWindow() + { + InitializeComponent(); + // Hide cursor using unclutter + try + { + var process = new System.Diagnostics.Process(); + process.StartInfo.FileName = "unclutter"; + process.StartInfo.Arguments = "-idle 0"; // Hide immediately + process.StartInfo.UseShellExecute = false; + process.StartInfo.CreateNoWindow = true; + process.Start(); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to start unclutter: {ex.Message}"); + } + + ContentArea.Content = new Home(this); + this.Closing += OnClosingWindow; + + _machine = _machine.ReadMachine(); + + _configrations = _config.ReadConfigrations(); + _mapping = _map.ReadMappings(); + serialThread = new Thread(() => serialThreadLoop.SendViaSerial(this)) + { + IsBackground = true + }; + serialThread.Start(); + internetThread = new Thread(() => CheckInterNetLoop.CheckInterNet(this)) + { + IsBackground = true + }; + internetThread.Start(); + + screenThread = new Thread(() => ScreenLoop.Screen(this)) + { + IsBackground = true + }; + screenThread.Start(); + InteractiveUIThread = new Thread(() => InteractiveUILoop.Flashing(this)) + { + IsBackground = true + }; + InteractiveUIThread.Start(); + touchThread = new Thread(() => TouchLoop.Touch(this)) + { + IsBackground = true + }; + touchThread.Start(); + monitorThread = new Thread(() => MonitorPortsLoop()) + { + IsBackground = true, + Priority = ThreadPriority.Highest + }; + monitorThread.Start(); + + + } + #endregion + + private async void MonitorPortsLoop() + { + byte[] tankeResponse = new byte[256]; + var fountainResponse = new byte[256]; + + double tankBottomTempValue = -1; + double tankWallTempValue = -1; + double pumpTempValue = -1; + double fountainTempValue = -1; + var tankBottom = _mapping.Find(x => x.Name == "Tank Bottom Temp"); + var tankWall = _mapping.Find(x => x.Name == "Tank Wall Temp"); + var pump = _mapping.Find(x => x.Name == "Pump Temp"); + var fountain = _mapping.Find(x => x.Name == "Fountain Temp"); + + + static List ToBinary(int number) + { + return Convert.ToString(number, 2) + .PadLeft(16, '0') + .Reverse() + .Select(c => c == '1') + .ToList(); + } + + + while (true) + { + if (isRunning) + { + Dispatcher.UIThread.Post(() => + { + footerDate.Text = DateTime.Now.ToString("dd/MM/yyyy"); + footerTime.Text = DateTime.Now.ToString("hh:mm tt"); + }); + screenData = _screeen.ReadScreens()?[0]; + + try + { + if (!SerialPort.GetPortNames().Contains(screenData.port)) + { + if (_port != null && _port.IsOpen) + { + _port.Close(); + } + _port = null; + Dispatcher.UIThread.Post(() => + { + errors.Clear(); + footerMsg.Text = "Not Connected:Port Name Not Found"; + //Debug.WriteLine("port name not found"); + footerMsg.Foreground = Avalonia.Media.Brushes.DarkRed; + footerMsg.IsVisible = true; + }); + } + else + { + if (resetPort) + { + Debug.WriteLine("Port reset initiated"); + resetAll(); + if (_port != null && _port.IsOpen) + { + Debug.WriteLine("Closing existing port"); + _port.Close(); + } + _port = null; + if (ConnectToSerialPort()) + { + Debug.WriteLine("Port reconnected successfully"); + Dispatcher.UIThread.Post(() => + { + //Conntected + footerMsg.Text = "Connected"; + footerMsg.IsVisible = true; + sendConfig = true; + }); + } + else + { + Debug.WriteLine("Failed to reconnect port"); + Dispatcher.UIThread.Post(() => + { + errors.Clear(); + footerMsg.Text = "Not Connected"; + footerMsg.IsVisible = true; + }); + } + resetPort = false; + Debug.WriteLine("Port reset completed"); + } + if (_port == null) + { + // Connect to the found device + if (!ConnectToSerialPort()) + { + + Dispatcher.UIThread.Post(() => + { + errors.Clear(); + footerMsg.Text = "Not Connected"; + + }); + } + else + { + serialThreadRunning = true; + + sendConfig = true; + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Connected"; + }); + } + } + else + { + try + { + if (!_port.IsOpen) + { + _port.Open(); + } + + + List inputValues = new List(); + + if (isReadingTemp) + { + if (!_port.IsOpen) + { + _port.Open(); + } + // reading inputes + + var requstReadingInputs = await _modBusMaster.ReadInputRegisters(0, 18); + + + + if (inputesResponse.Length != 1 && inputesResponse[0] != 0xFF) + { + var result = inputesResponse.Skip(3).Take(inputesResponse.Count() - 5).ToArray(); + for (int i = 0; i < result.Length; i = i + 2) + { + inputValues.Add(((result[i] << 8) | result[i + 1])); + } + var brdFlags = ToBinary(inputValues[0]); + var inputes = ToBinary(inputValues[1]); + + #region Errors + //Errors + try + { + // Grid Vac + if (inputValues[2] > 220 * 1.1 || inputValues[3] > 220 * 1.1 || inputValues[4] > 220 * 1.1) + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.GridVACHigh) == null) + { + errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.GridVACHigh + }); + } + } + else + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.GridVACHigh) != null) + { + errors.First(x => x.Condition == Error.GridCondition.GridVACHigh).isDeleted = true; + } + + } + if (inputValues[2] < 220 * 0.9 || inputValues[3] < 220 * 0.9 || inputValues[4] < 220 * 0.9) + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.GridVACLow) == null) + { + errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.GridVACLow + }); + } + + } + else + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.GridVACLow) != null) + { + errors.First(x => x.Condition == Error.GridCondition.GridVACLow).isDeleted = true; + } + } + //// Grid Freq + _error = _error.ReadErrorSettings()[0]; + if (inputValues[17] > (_error.gridFreq * 10) * 1.1) + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.GridFrequencyHigh) == null) + { + errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.GridFrequencyHigh + }); + } + + } + else + { + + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.GridFrequencyHigh) != null) + { + errors.First(x => x.Condition == Error.GridCondition.GridFrequencyHigh).isDeleted = true; + } + } + if (inputValues[17] < (_error.gridFreq * 10) * 0.9) + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.GridFrequencyLow) == null) + { + errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.GridFrequencyLow + }); + } + } + else + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.GridFrequencyLow) != null) + { + errors.First(x => x.Condition == Error.GridCondition.GridFrequencyLow).isDeleted = true; + } + } + //// Ext Power + if (brdFlags[3]) + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.NoExternalPower) == null) + { + errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.NoExternalPower + }); + } + } + else + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.NoExternalPower) != null) + { + errors.First(x => x.Condition == Error.GridCondition.NoExternalPower).isDeleted = true; + } + } + //// missing Phase + if (brdFlags[5] && _error.ReadErrorSettings()[0].phaseNumber == 3) + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.MissingPhase) == null) + { + errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.MissingPhase + }); + } + } + else + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.MissingPhase) != null) + { + errors.First(x => x.Condition == Error.GridCondition.MissingPhase).isDeleted = true; + } + } + //// Phase sequence + if (brdFlags[4] && _error.ReadErrorSettings()[0].phaseNumber == 3) + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.PhaseSequence) == null) + { + errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.PhaseSequence + }); + } + } + else + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.PhaseSequence) != null) + { + errors.First(x => x.Condition == Error.GridCondition.PhaseSequence).isDeleted = true; + } + } + //com port1 + if (brdFlags[1]) + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.ComPort1) == null) + { + errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.ComPort1 + }); + } + } + else + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.ComPort1) != null) + { + errors.First(x => x.Condition == Error.GridCondition.ComPort1).isDeleted = true; + } + } + //com port2 + if (brdFlags[2]) + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.ComPort2) == null) + { + errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.ComPort2 + }); + } + } + else + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.ComPort2) != null) + { + errors.First(x => x.Condition == Error.GridCondition.ComPort2).isDeleted = true; + } + } + //hi curr neut + if (brdFlags[6]) + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.HiCurrNeut) == null) + { + errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.HiCurrNeut + }); + } + } + else + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.HiCurrNeut) != null) + { + errors.First(x => x.Condition == Error.GridCondition.HiCurrNeut).isDeleted = true; + } + } + //hi curr mot1 + if (brdFlags[7]) + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.HiCurrMot1) == null) + { + errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.HiCurrMot1 + }); + } + } + else + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.HiCurrMot1) != null) + { + errors.First(x => x.Condition == Error.GridCondition.HiCurrMot1).isDeleted = true; + } + } + //hi curr mot2 + if (brdFlags[8]) + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.HiCurrMot2) == null) + { + errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.HiCurrMot2 + }); + } + } + else + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.HiCurrMot2) != null) + { + errors.First(x => x.Condition == Error.GridCondition.HiCurrMot2).isDeleted = true; + } + } + } + catch (Exception) + { + + } + #endregion + + Dispatcher.UIThread.Post(async () => + { + if (ContentArea.Content is Diagnostics diagnostics) + { + //Board Falgs + foreach (var item in diagnostics.flagRectangles) + { + if (brdFlags[int.Parse(item.Tag.ToString())]) + { + item.Fill = Brush.Parse(diagnostics.RedColor); + } + else + { + item.Fill = Brush.Parse(diagnostics.GrayColor); + + } + } + //power Inputes + diagnostics.ph1.Text = inputValues[2].ToString(); + diagnostics.ph2.Text = inputValues[3].ToString(); + diagnostics.ph3.Text = inputValues[4].ToString(); + + diagnostics.i_nut.Text = (inputValues[5] / 10.0).ToString("0.0"); + diagnostics.gridFreq.Text = (inputValues[17] / 10.0).ToString("0.0"); + // Inputes + foreach (var item in diagnostics.InputesElements.OfType().ToList()) + { + var text = item.Children[0] as TextBlock; + var border = item.Children[1] as Border; + if (inputes[int.Parse(item.Tag.ToString())]) + { + + text.Text = "ACTIVE"; + border.Background = Brush.Parse(diagnostics.PinkColor); + diagnostics.InputesElements.OfType().ToList().Find(x => x.Tag.ToString() == item.Tag.ToString()).Fill = Brush.Parse(diagnostics.GreenColor); + + } + else + { + text.Text = "PASSIVE"; + border.Background = Brush.Parse(diagnostics.GrayColor); + diagnostics.InputesElements.OfType().ToList().Find(x => x.Tag.ToString() == item.Tag.ToString()).Fill = Brush.Parse(diagnostics.GrayColor); + + + } + } + //Analog + diagnostics.an1.Text = inputValues[12].ToString(); + diagnostics.an2.Text = inputValues[13].ToString(); + //Temp + diagnostics.t1.Text = ((short)inputValues[8] / 10f).ToString("0.0"); + diagnostics.t2.Text = ((short)inputValues[9] / 10f).ToString("0.0"); + diagnostics.t3.Text = ((short)inputValues[10] / 10f).ToString("0.0"); + diagnostics.t4.Text = ((short)inputValues[11] / 10f).ToString("0.0"); + //InternalTemp + diagnostics.internalTemp.Text = (inputValues[15] / 10.0).ToString("0.0"); + diagnostics.hsTemp.Text = (inputValues[14] / 10.0).ToString("0.0"); + if (inputValues[16] > 40) + { + diagnostics.extPowerLed.Fill = Brush.Parse(diagnostics.RedColor); + } + else + { + diagnostics.extPowerLed.Fill = Brush.Parse(diagnostics.GrayColor); + } + diagnostics.ExtPwr.Text = (inputValues[16] / 10.0).ToString("0.0"); + + } + + if (ContentArea.Content is Settings settings) + { + if (settings.pedalStateTxt.Text != "AUTO") + { + var pedal = _mapping.Find(x => x.Name.ToLower() == "pedal"); + + ushort registerValue = (ushort)inputValues[1]; + if (allBitsOn != pedal.BitNumbers.All(bit => (registerValue & (1 << bit)) != 0)) + { + allBitsOn = pedal.BitNumbers.All(bit => (registerValue & (1 << bit)) != 0); + } + if (!allBitsOn) + { + settings.pedalUnderLine.Fill = Brush.Parse(settings.PassiveColor); + + } + else + { + settings.pedalUnderLine.Fill = Brush.Parse(settings.ActiveColor); + + } + + } + if (startFountainMotorFlashing != 1) + { + //fountain + + var fount = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + + + if (allBitsOn != fount.BitNumbers.All(bit => (holdingRegister.motor & (1 << bit)) != 0)) + { + allBitsOn = fount.BitNumbers.All(bit => (holdingRegister.motor & (1 << bit)) != 0); + } + var fountainLable = settings.FountainSP.Children[1] as Avalonia.Controls.Label; + var fontainRectangel = settings.FountainSP.Children[2] as Avalonia.Controls.Shapes.Rectangle; + if (!allBitsOn) + { + fountainLable.Content = "OFF"; + fountainLable.Foreground = Brush.Parse("#ff231f20"); + fontainRectangel.Fill = Brush.Parse(PassiveColor); + //isFountainMotorOn = false; + } + else + { + fountainLable.Content = "ON"; + fountainLable.Foreground = Brush.Parse("#ff231f20"); + fontainRectangel.Fill = Brush.Parse(ActiveColor); + //isFountainMotorOn = true; + } + } + + if (startMixerMotorFlashing != 1) + { + //mixer + var mixer = _mapping.Find(x => x.Name.ToLower() == "Mixer".ToLower()); + + + if (allBitsOn != mixer.BitNumbers.All(bit => (holdingRegister.motor & (1 << bit)) != 0)) + { + allBitsOn = mixer.BitNumbers.All(bit => (holdingRegister.motor & (1 << bit)) != 0); + } + var mixerLable = settings.MixerSP.Children[1] as Avalonia.Controls.Label; + var mixerRectangel = settings.MixerSP.Children[2] as + Avalonia.Controls.Shapes.Rectangle; + if (!allBitsOn) + { + mixerLable.Content = "OFF"; + mixerLable.Foreground = Brush.Parse("#ff231f20"); + mixerRectangel.Fill = Brush.Parse(PassiveColor); + //isMixerMotorOn = false; + } + else + { + mixerLable.Content = "ON"; + mixerLable.Foreground = Brush.Parse("#ff231f20"); + mixerRectangel.Fill = Brush.Parse(ActiveColor); + //isMixerMotorOn = true; + } + } + + } + if (ContentArea.Content is ManualControl manual) + { + manual.pumbRealTemp.Text = comPumpTemp.ToString("0.0"); + manual.ChocolateRealTemp.Text = comFountainTemp.ToString("0.0"); + manual.tankWallRealTemp.Text = tankWallTempValue.ToString("0.0"); + manual.pumbRealTemp.Text = comTankTemp.ToString("0.0"); + } + }); + _mapping = _map.ReadMappings(); + //reading Tank Bottom + tankBottom = _mapping.Find(x => x.Name == "Tank Bottom Temp"); + + if (tankBottom != null) + { + if (tankBottom.BitNumbers.Count > 0) + { + tankBottomTempValue = 0; + foreach (var item in tankBottom.BitNumbers) + { + tankBottomTempValue += ((short)inputValues[item] / 10f); + } + tankBottomTempValue /= tankBottom.BitNumbers.Count; + tankBottomTempValue = Math.Round(tankBottomTempValue, 1); + } + } + //reading Tank Wall + tankWall = _mapping.Find(x => x.Name == "Tank Wall Temp"); + + if (tankWall != null) + { + if (tankWall.BitNumbers.Count > 0) + { + tankWallTempValue = 0; + foreach (var item in tankWall.BitNumbers) + { + tankWallTempValue += ((short)inputValues[item] / 10f); + } + tankWallTempValue /= tankWall.BitNumbers.Count; + tankWallTempValue = Math.Round(tankWallTempValue, 1); + } + } + //reading Pump + pump = _mapping.Find(x => x.Name == "Pump Temp"); + + if (pump != null) + { + if (pump.BitNumbers.Count > 0) + { + pumpTempValue = 0; + + foreach (var item in pump.BitNumbers) + { + pumpTempValue += ((short)inputValues[item] / 10f); + } + pumpTempValue /= pump.BitNumbers.Count; + pumpTempValue = Math.Round(pumpTempValue, 1); + } + } + //reading Fountain + fountain = _mapping.Find(x => x.Name == "Fountain Temp"); + if (fountain != null) + { + if (fountain.BitNumbers.Count > 0) + { + fountainTempValue = 0; + + foreach (var item in fountain.BitNumbers) + { + fountainTempValue += ((short)inputValues[item] / 10f); + } + fountainTempValue /= fountain.BitNumbers.Count; + fountainTempValue = Math.Round(fountainTempValue, 1); + } + } + Dispatcher.UIThread.Post(() => + { + if (tankBottomTempValue == -1 && tankWallTempValue == -1) + { + if (ContentArea.Content is Settings) + { + footerMsg.Text = "No Tank Data To Read"; + tankBottomTempValue = 0; + tankWallTempValue = 0; + } + } + else + { + //comTankTemp = tankBottomTempValue < tankWallTempValue ? tankBottomTempValue : tankWallTempValue; + comTankTemp = tankBottomTempValue; + comTankTemp = comTankTemp == -1 ? 0 : comTankTemp; + } + if (pumpTempValue == -1) + { + if (ContentArea.Content is Settings) + { + footerMsg.Text = "No Pump Data To Read"; + pumpTempValue = 0; + } + + } + else + { + comPumpTemp = pumpTempValue; + } + if (fountainTempValue == -1) + { + if (ContentArea.Content is Settings) + { + footerMsg.Text = "No Chocolate Data To Read"; + fountainTempValue = 0; + } + + } + else + { + comFountainTemp = fountainTempValue; + } + if (ContentArea.Content is Settings result) + { + if (result.TankTempValue.Content?.ToString() != comTankTemp.ToString() || result.FountainTempValue.Content?.ToString() != comFountainTemp.ToString()) + { + result.TankTempValue.Content = (comTankTemp).ToString("0.0"); + result.FountainTempValue.Content = (comFountainTemp).ToString("0.0"); + } + } + //if (comTankTemp >= _machine.TankMaxHeat && comFountainTemp >= _machine.PumbMaxHeat) + //{ + // if (preMixerTimer==null) + // { + // preMixerTimer = new Timer(PreMixerTimer, null, 0, 1000); + // } + // mixerSeconds++; + //} + //else + //{ + // if (preMixerTimer != null) + // { + // preMixerTimer.Change(Timeout.Infinite, Timeout.Infinite); + // preMixerTimer = null; + // } + + + //} + } + ); + } + + //read mot val + + if (inputValues.Count != 0) + { + + Dispatcher.UIThread.Post(async () => + { + if (ContentArea.Content is Diagnostics diagnostics) + { + diagnostics.curr1.Text = (inputValues[6] / 10.0).ToString("0.0"); + diagnostics.curr2.Text = (inputValues[7] / 10.0).ToString("0.0"); + } + }); + } + } + + + //Pre Heating + if (startPreHeating == 1) + { + List setTempValues = new List(); + setTempValues.AddRange([holdingRegister.setTemp1, holdingRegister.setTemp2, holdingRegister.setTemp3, holdingRegister.setTemp4]); + + if (writingMaxTemp == 1) + { + tankBottom = _mapping.Find(x => x.Name == "Tank Bottom Temp"); + if (tankBottom != null) + { + if (tankBottom.BitNumbers.Count > 0) + { + foreach (var item in tankBottom.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.TankMaxHeat * 10; + } + + } + + + } + tankWall = _mapping.Find(x => x.Name == "Tank Wall Temp"); + if (tankWall != null) + { + if (tankWall.BitNumbers.Count > 0) + { + foreach (var item in tankWall.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.TankMaxHeat * 10; + } + + } + + + } + + pump = _mapping.Find(x => x.Name == "Pump Temp"); + if (pump != null) + { + if (pump.BitNumbers.Count > 0) + { + foreach (var item in pump.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.PumbMaxHeat * 10; + + } + } + + + } + fountain = _mapping.Find(x => x.Name == "Fountain Temp"); + if (fountain != null) + { + if (fountain.BitNumbers.Count > 0) + { + foreach (var item in fountain.BitNumbers) + { + setTempValues[item - 8] = -10000; + + } + } + + + } + + holdingRegister.setTemp1 = setTempValues[0]; + holdingRegister.setTemp2 = setTempValues[1]; + holdingRegister.setTemp3 = setTempValues[2]; + holdingRegister.setTemp4 = setTempValues[3]; + await WriteToSerialAsync("PreHeating"); + + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + + result.recipeSettings.IsEnabled = false; + isFlashPreHeating = true; + footerMsg.Text = "Pre-Heating Active"; + } + }); + writingMaxTemp = -1; + } + + } + if (startPreHeating == 0) + { + List setTempValues = new List(); + setTempValues.AddRange([holdingRegister.setTemp1, holdingRegister.setTemp2, holdingRegister.setTemp3, holdingRegister.setTemp4]); + if (writingMaxTemp == 0) + { + tankBottom = _mapping.Find(x => x.Name == "Tank Bottom Temp"); + if (tankBottom != null) + { + if (tankBottom.BitNumbers.Count > 0) + { + foreach (var item in tankBottom.BitNumbers) + { + setTempValues[item - 8] = -10000; + + } + + } + + } + + tankWall = _mapping.Find(x => x.Name == "Tank Wall Temp"); + if (tankWall != null) + { + if (tankWall.BitNumbers.Count > 0) + { + foreach (var item in tankWall.BitNumbers) + { + setTempValues[item - 8] = -10000; + } + + } + + + } + + pump = _mapping.Find(x => x.Name == "Pump Temp"); + if (pump != null) + { + if (pump.BitNumbers.Count > 0) + { + foreach (var item in pump.BitNumbers) + { + setTempValues[item - 8] = -10000; + + } + } + + + } + fountain = _mapping.Find(x => x.Name == "Fountain Temp"); + if (fountain != null) + { + if (fountain.BitNumbers.Count > 0) + { + foreach (var item in fountain.BitNumbers) + { + setTempValues[item - 8] = -10000; + + } + } + + + } + + holdingRegister.setTemp1 = setTempValues[0]; + holdingRegister.setTemp2 = setTempValues[1]; + holdingRegister.setTemp3 = setTempValues[2]; + holdingRegister.setTemp4 = setTempValues[3]; + await WriteToSerialAsync("PreHeating"); + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + result.recipeSettings.IsEnabled = true; + if (!stopRecipeFlag) + { + footerMsg.Text = "Pre-Heating Stopped"; + + } + } + }); + writingMaxTemp = -1; + } + + } + //Mixer Motor + //Mixer Motorf + if (checkMixerTWT_HWTH) + { + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + recipeHeatingGoal = result._recipeTable.HeatingGoal; + recipeCoolingGoal = result._recipeTable.CoolingGoal; + recipePouringGoal = result._recipeTable.PouringGoal; + } + + if ((comTankTemp >= _machine.TankMaxHeat - screenData.warningLimit) && (comTankTemp <= _machine.TankMaxHeat + screenData.warningLimit)) + { + if (startMixerMotor != 1) + { + if (mixerTimer == null) + { + if (mixerSeconds == 1) + { + mixerSeconds = _machine.MixerDelay; + } + mixerTimer = new Timer(MixerTimer, null, 0, 1000); + //setMixerTimerOnce = false; + } + } + } + + else if (comTankTemp <= recipeCoolingGoal - 3 && startMixerMotor == 1) + { + if (startMixerMotor != 0) + { + if (stopMixerTimer == null) + { + stopMixerSecondes = 5; + stopMixerTimer = new Timer(StopMixerTimer, null, 0, 1000); + } + } + startMixerMotorFlashing = 1; + } + else if (startMixerMotor != 1) + { + if (startMixerMotor != 0) + { + sendComMixerMotor = 0; + } + startMixerMotorFlashing = 1; + } + }); + } + if (!checkMixerTWT_HWTH) + { + if (sendComMixerMotor == 0 && startMixerMotorFlashing == 0) + { + startMixerMotor = -1; + var mixer = _mapping.Find(x => x.Name.ToLower() == "Mixer".ToLower()); + if (mixer != null) + { + if (mixer.BitNumbers.Count > 0) + { + //turn the motor off and make the button stable + + + foreach (var bit in mixer.BitNumbers) + { + holdingRegister.motor &= (ushort)~(1 << bit); + } + await WriteToSerialAsync("Mixer Off due Clicking"); + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + var motorLable = result.MixerSP.Children[1] as Avalonia.Controls.Label; + var motorRectangel = result.MixerSP.Children[2] as + Avalonia.Controls.Shapes.Rectangle; + motorLable.Content = "OFF"; + motorLable.Foreground = Brush.Parse("#ff231f20"); + motorRectangel.Fill = Brush.Parse(PassiveColor); + if (startRecipe != 1 && !stopRecipeFlag) + { + footerMsg.Text = "Mixer is OFF"; + } + } + }); + sendComMixerMotor = -1; + startMixerMotorFlashing = -1; + } + } + } + } + if (startMixerMotorFlashing == 1) + { + if (sendComMixerMotor == 0) + { + //turn the motor off + startMixerMotor = 0; + + var mixer = _mapping.Find(x => x.Name.ToLower() == "Mixer".ToLower()); + if (mixer != null) + { + if (mixer.BitNumbers.Count > 0) + { + //turn the motor off and make the button stable + + foreach (var bit in mixer.BitNumbers) + { + + holdingRegister.motor &= (ushort)~(1 << bit); + } + await WriteToSerialAsync("Mixer Off due to drop in temp"); + Dispatcher.UIThread.Post(() => + { + if (startRecipe != 1) + { + footerMsg.Text = "waiting for tank target temperature"; + } + }); + sendComMixerMotor = -1; + } + } + } + } + if (startMixerMotorFlashing == 0 && sendComMixerMotor == 1 && !isPaused) + { + startMixerMotor = 1; + //turn the motor on and make the button stable + var mixer = _mapping.Find(x => x.Name.ToLower() == "Mixer".ToLower()); + if (mixer != null) + { + if (mixer.BitNumbers.Count > 0) + { + foreach (var bit in mixer.BitNumbers) + { + + holdingRegister.motor |= (ushort)(1 << bit); + } + await WriteToSerialAsync("Mixer On"); + + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + var motorLable = result.MixerSP.Children[1] as Avalonia.Controls.Label; + var motorRectangel = result.MixerSP.Children[2] as + Avalonia.Controls.Shapes.Rectangle; + motorLable.Content = "ON"; + motorLable.Foreground = Brush.Parse("#ff231f20"); + motorRectangel.Fill = Brush.Parse(ActiveColor); + if (startRecipe != 1) + { + footerMsg.Text = "Temperature is OK,Mixer is on"; + } + //if (comTankTemp < result._recipeTable.PouringGoal || + // comFountainTemp < result._recipeTable.PouringGoal) + //{ + // mixerSeconds = 1; + // //checkTMT_PMT = true; + // setMixerTimerOnce = true; + //} + //else + //{ + // //checkTMT_PMT = true; + // setMixerTimerOnce = true; + //} + + } + + }); + + + startMixerMotorFlashing = -1; + sendComMixerMotor = -1; + + } + } + + + } + + //Fountain Motor - Normal temperature-based control (when not in pedal auto mode) + if (checkFountainTMT_PMT && !isPedalAutoMode) + { + Dispatcher.UIThread.Post(() => + { + + if (ContentArea.Content is Settings result) + { + recipeHeatingGoal = result._recipeTable.HeatingGoal; + recipeCoolingGoal = result._recipeTable.CoolingGoal; + recipePouringGoal = result._recipeTable.PouringGoal; + + + } + + if ((comPumpTemp >= _machine.PumbMaxHeat - screenData.warningLimit) && (comPumpTemp <= _machine.PumbMaxHeat + screenData.warningLimit)) // check the temp and make it stop only if it below cooling temp - 3 degrees + { + if (startFountainMotor != 1) + { + if (fountainTimer is null) + { + if (fountainSeconds == 1) + { + fountainSeconds = _machine.PumbDelay; + } + fountainTimer = new Timer(FountainTimer, null, 0, 1000); + //setFountainTimerOnce = false; + } + } + } + + else if (comPumpTemp <= recipeCoolingGoal - 3 && startFountainMotor == 1) + { + if (startFountainMotor != 0) + { + if (stopFountainTimer == null) + { + stopFountainSecondes = 5; + stopFountainTimer = new Timer(StopFountainTimer, null, 0, 1000); + } + } + if (!isPedalAutoMode) + { + startFountainMotorFlashing = 1; + } + } + else if (startFountainMotor != 1) + { + if (startFountainMotor != 0) + { + sendComFountainMotor = 0; + } + if (!isPedalAutoMode) + { + startFountainMotorFlashing = 1; + } + } + + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + if (startFountainMotor != 1 && fountainTimer == null) + { + if (!result.fountainDelayCounter.Text.Equals(comPumpTemp.ToString("0.0"))) + { + result.fountainDelayTxt.Text = "Current Temp:"; + result.fountainDelayCounter.Text = comPumpTemp.ToString("0.0"); + result.fountainTargetTxt.Text = "Target Temp:"; + result.fountainTagetTemp.Text = _machine.PumbMaxHeat.ToString("0.0"); + result.fountainDelayTxt.IsVisible = true; + result.fountainDelayCounter.IsVisible = true; + result.fountainTargetTxt.IsVisible = true; + result.fountainTagetTemp.IsVisible = true; + } + + } + } + + }); + }); + } + //Fountain Motor - Manual control (when not in pedal auto mode) + if (!checkFountainTMT_PMT && !isPedalAutoMode) + { + if (sendComFountainMotor == 0 && startFountainMotorFlashing == 0) + { + startFountainMotor = -1; + var fount = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + if (fount != null) + { + if (fount.BitNumbers.Count > 0) + { + //turn the motor off and make the button stable + foreach (var bit in fount.BitNumbers) + { + holdingRegister.motor &= (ushort)~(1 << bit); + } + await WriteToSerialAsync("Fountain Off due to click"); + //waitting for 10 sec before pause + if (fountainPauseTimer == null && startRecipe == 1 && (Heating == 1 || heatingTimer != null || cooling == 1 || coolingTimer != null || pouring == 1 || pouringTimer != null + )) + { + fountainPauseSeconds = 10; + fountainPauseTimer = new Timer(FountainPauseTimer, null, 0, 1000); + } + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + result.fountainDelayCounter.Text = "-1"; + var fountainLable = result.FountainSP.Children[1] as Avalonia.Controls.Label; + var fontainRectangel = result.FountainSP.Children[2] as + Avalonia.Controls.Shapes.Rectangle; + fountainLable.Content = "OFF"; + fountainLable.Foreground = Brush.Parse("#ff231f20"); + fontainRectangel.Fill = Brush.Parse(PassiveColor); + if (startRecipe != 1 && !stopRecipeFlag) + { + footerMsg.Text = "Chocolate is OFF"; + } + stopRecipeFlag = false; + } + }); + + + sendComFountainMotor = -1; + startFountainMotorFlashing = -1; + } + } + + } + } + if (startFountainMotorFlashing == 1 && !isPedalAutoMode) + { + if (sendComFountainMotor == 0) + { + startFountainMotor = 0; + + //turn the motor off + var fount = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + if (fount != null) + { + if (fount.BitNumbers.Count > 0) + { + foreach (var bit in fount.BitNumbers) + { + + holdingRegister.motor &= (ushort)~(1 << bit); + } + await WriteToSerialAsync("Fountain Off due to drop in temp"); + //pause the recipe if it started + //waitting for 10 sec before pause + if (fountainPauseTimer == null && startRecipe == 1 && (Heating == 1 || heatingTimer != null || cooling == 1 || coolingTimer != null || pouring == 1 || pouringTimer != null + )) + { + fountainPauseSeconds = 10; + fountainPauseTimer = new Timer(FountainPauseTimer, null, 0, 1000); + } + + Dispatcher.UIThread.Post(() => + { + if (startRecipe == 1 && (Heating == 1 || cooling == 1 || pouring == 1)) + { + //footerMsg.Text = "Recipe Paused... waiting for target temperature"; + } + else if (startRecipe != 1) + { + footerMsg.Text = "waiting for pump target temperature"; + + } + }); + //checkTMT_PMT = true; + sendComFountainMotor = -1; + } + } + + } + } + if (startFountainMotorFlashing == 0 && sendComFountainMotor == 1 && errors.Count == 0 && !isPaused) + { + startFountainMotor = 1; + //turn the motor on and make the button stable + var fount = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + if (fount != null) + { + if (fount.BitNumbers.Count > 0) + { + foreach (var bit in fount.BitNumbers) + { + holdingRegister.motor |= (ushort)(1 << bit); + } + await WriteToSerialAsync("Fountain On"); + if (isPaused) + { + unPause = true; + } + //if (startRecipe == 1 && (Heating == 10 || cooling == 10 || pouring == 10)) + //{ + // if (Heating == 10) + // { + // Heating = 1; + // sendComHeating = 1; + // } + // else if (cooling == 10) + // { + // cooling = 1; + // sendComCooling = 1; + // } + // else if (pouring == 10) + // { + // pouring = 1; + // sendComPouring = 1; + // } + //} + if (fountainPauseTimer != null) + { + fountainPauseTimer = null; + fountainPauseSeconds = 10; + } + Dispatcher.UIThread.Post(async () => + { + if (ContentArea.Content is Settings result) + { + var fountainLable = result.FountainSP.Children[1] as Avalonia.Controls.Label; + var fountainRectangel = result.FountainSP.Children[2] as + Avalonia.Controls.Shapes.Rectangle; + fountainLable.Content = "ON"; + fountainLable.Foreground = Brush.Parse("#ff231f20"); + fountainRectangel.Fill = Brush.Parse(ActiveColor); + if (startRecipe == 1 && (Heating == 1 || cooling == 1 || pouring == 1)) + { + if (Heating == 1) + { + footerMsg.Text = "Heating phase"; + + } + else if (cooling == 1) + { + footerMsg.Text = "Cooling phase"; + + } + else if (pouring == 1) + { + footerMsg.Text = "Prepare for pouring"; + } + } + else if (startRecipe != 1) + { + footerMsg.Text = "Temperature is OK,Chocolate is on"; + } + //if (comTankTemp < result._recipeTable.PouringGoal || + // comFountainTemp < result._recipeTable.PouringGoal) + //{ + // fountainSeconds = 1; + // setFountainTimerOnce = true; + //} + //else + //{ + // setFountainTimerOnce = true; + //} + } + }); + + startFountainMotorFlashing = -1; + sendComFountainMotor = -1; + } + } + + } + + // Fountain Motor - Direct control is now handled by pedal state in auto mode + + if (moldHeaterMotor == 0) // off MOLD HEATER + { + var moldHeater = _mapping.Find(x => x.Name == "Mold Heater"); + if (moldHeater != null) + { + if (moldHeater.BitNumbers.Count > 0) + { + foreach (var bit in moldHeater.BitNumbers) + { + holdingRegister.lvOut &= (ushort)~(1 << bit); + } + await WriteToSerialAsync("MoldHeater"); + + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + var StackPanel = result.moldHeaterBtn.Content as StackPanel; + var Label = StackPanel.Children; + var underLine = Label[2] as Avalonia.Controls.Shapes.Rectangle; + var targetLable = Label[1] as Label; + targetLable.Content = "OFF"; + underLine.Fill = Brush.Parse("#666666"); + } + else if (ContentArea.Content is ManualControl manual) + { + manual.MoldHeaterStatus.Text = "OFF"; + manual.MoldHeaterUnderline.Fill = Brush.Parse("#666666"); + } + }); + + } + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Admin"; + }); + } + } + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Programming Team"; + }); + } + + + moldHeaterMotor = -1; + } + else if (moldHeaterMotor == 1) // on MOLD HEATER + { + var moldHeater = _mapping.Find(x => x.Name == "Mold Heater"); + if (moldHeater != null) + { + if (moldHeater.BitNumbers.Count > 0) + { + foreach (var bit in moldHeater.BitNumbers) + { + + holdingRegister.lvOut |= (ushort)(1 << bit); + } + await WriteToSerialAsync("MoldHeater"); + + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + var StackPanel = result.moldHeaterBtn.Content as StackPanel; + var Label = StackPanel.Children; + var underLine = Label[2] as Avalonia.Controls.Shapes.Rectangle; + var targetLable = Label[1] as Label; + targetLable.Content = "ON"; + underLine.Fill = Brush.Parse("#A4275D"); + } + else if (ContentArea.Content is ManualControl manual) + { + manual.MoldHeaterStatus.Text = "ON"; + manual.MoldHeaterUnderline.Fill = Brush.Parse("#A4275D"); + } + }); + + } + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Admin"; + }); + } + } + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Programming Team"; + }); + } + + moldHeaterMotor = -1; + } + if (vibrationMotor == 0) // off VIBRATION + { + var vibrator = _mapping.Find(x => x.Name == "Vibrator"); + + if (vibrator != null) + { + if (vibrator.BitNumbers.Count > 0) + { + + foreach (var bit in vibrator.BitNumbers) + { + holdingRegister.hvOut &= (ushort)~(1 << bit); + } + await WriteToSerialAsync("Vibrator"); + + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + var StackPanel = result.vibrationBtn.Content as StackPanel; + var Label = StackPanel.Children; + var underLine = Label[2] as Avalonia.Controls.Shapes.Rectangle; + var targetLable = Label[1] as Label; + targetLable.Content = "OFF"; + underLine.Fill = Brush.Parse("#666666"); + } + else if (ContentArea.Content is ManualControl manual) + { + manual.VibrationStatus.Text = "OFF"; + manual.VibrationUnderline.Fill = Brush.Parse("#666666"); + } + }); + + } + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Admin"; + }); + } + + + } + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Programming Team"; + }); + } + + vibrationMotor = -1; + } + else if (vibrationMotor == 1) // on VIBRATION + { + var vibrator = _mapping.Find(x => x.Name == "Vibrator"); + + if (vibrator != null) + { + if (vibrator.BitNumbers.Count > 0) + { + foreach (var bit in vibrator.BitNumbers) + { + holdingRegister.hvOut |= (ushort)(1 << bit); + } + await WriteToSerialAsync("Vibrator"); + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + var StackPanel = result.vibrationBtn.Content as StackPanel; + var Label = StackPanel.Children; + var underLine = Label[2] as Avalonia.Controls.Shapes.Rectangle; + var targetLable = Label[1] as Label; + targetLable.Content = "ON"; + underLine.Fill = Brush.Parse("#A4275D"); + } + else if (ContentArea.Content is ManualControl manual) + { + manual.VibrationStatus.Text = "ON"; + manual.VibrationUnderline.Fill = Brush.Parse("#A4275D"); + } + }); + + + + } + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Admin"; + }); + } + + + + + + } + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Programming Team"; + }); + } + vibrationMotor = -1; + } + if (vibHeaterMotor == 0) // off VIB. HEATER + { + var vibHeater = _mapping.Find(x => x.Name == "Vibrator Heater"); + if (vibHeater != null) + { + if (vibHeater.BitNumbers.Count > 0) + { + + foreach (var bit in vibHeater.BitNumbers) + { + + holdingRegister.lvOut &= (ushort)~(1 << bit); + } + await WriteToSerialAsync("VibratorHeater"); + + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + var StackPanel = result.vibHeaterBtn.Content as StackPanel; + var Label = StackPanel.Children; + var underLine = Label[2] as Avalonia.Controls.Shapes.Rectangle; + var targetLable = Label[1] as Label; + targetLable.Content = "OFF"; + underLine.Fill = Brush.Parse("#666666"); + } + else if (ContentArea.Content is ManualControl manual) + { + manual.VibHeaterStatus.Text = "OFF"; + manual.VibHeaterUnderline.Fill = Brush.Parse("#666666"); + } + }); + + } + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Admin"; + }); + } + } + + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Programming Team"; + }); + } + + vibHeaterMotor = -1; + } + else if (vibHeaterMotor == 1) // on VIB. HEATER + { + var vibHeater = _mapping.Find(x => x.Name == "Vibrator Heater"); + if (vibHeater != null) + { + if (vibHeater.BitNumbers.Count > 0) + { + foreach (var bit in vibHeater.BitNumbers) + { + holdingRegister.lvOut |= (ushort)(1 << bit); + } + await WriteToSerialAsync("VibratorHeater"); + + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + var StackPanel = result.vibHeaterBtn.Content as StackPanel; + var Label = StackPanel.Children; + var underLine = Label[2] as Avalonia.Controls.Shapes.Rectangle; + var targetLable = Label[1] as Label; + targetLable.Content = "ON"; + underLine.Fill = Brush.Parse("#A4275D"); + } + else if (ContentArea.Content is ManualControl manual) + { + manual.VibHeaterStatus.Text = "ON"; + manual.VibHeaterUnderline.Fill = Brush.Parse("#A4275D"); + } + }); + } + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Admin"; + }); + } + + } + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Programming Team"; + }); + } + vibHeaterMotor = -1; + } + + + //Start Recipe + if (startRecipe == 1) + { + var tankBtm = _mapping.Find(x => x.Name.ToLower() == "Tank Bottom Temp".ToLower()); + tankWall = _mapping.Find(x => x.Name.ToLower() == "Tank Wall Temp".ToLower()); + var pumb = _mapping.Find(x => x.Name.ToLower() == "Pump Temp".ToLower()); + var fount = _mapping.Find(x => x.Name.ToLower() == "Fountain Temp".ToLower()); + var fountainMotor = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + var mixerMotor = _mapping.Find(x => x.Name.ToLower() == "Mixer".ToLower()); + + if (tankBtm != null && tankWall != null && pumb != null && fount != null) + { + if (tankBtm.BitNumbers.Count > 0 && tankWall.BitNumbers.Count > 0 && pumb.BitNumbers.Count > 0 && fount.BitNumbers.Count > 0) + { + List setTempValues = new List(); + setTempValues.AddRange([holdingRegister.setTemp1, holdingRegister.setTemp2, holdingRegister.setTemp3, holdingRegister.setTemp4]); + byte[] response = new byte[] { 0xFF }; + + var isFountOn = false; + var isMixerOn = false; + if (isFountOn != fountainMotor.BitNumbers.All(bit => (holdingRegister.motor & (1 << bit)) != 0)) + { + isFountOn = fountainMotor.BitNumbers.All(bit => (holdingRegister.motor & (1 << bit)) != 0); + } + if (isMixerOn != mixerMotor.BitNumbers.All(bit => (holdingRegister.motor & (1 << bit)) != 0)) + { + isMixerOn = mixerMotor.BitNumbers.All(bit => (holdingRegister.motor & (1 << bit)) != 0); + } + if (isFountOn && isMixerOn) // both motors are on + { + // Check if both mixer and chocolate have reached heating goal + bool mixerGoalMet = comTankTemp >= recipeHeatingGoal; + bool chocolateGoalMet = comFountainTemp >= recipeHeatingGoal; + bool bothGoalsMet = mixerGoalMet && chocolateGoalMet; + + if (bothGoalsMet && (cooling != 1 && pouring != 1)) + { + // Both goals met - check temperature before starting heating timer + bool tempTooHigh = comFountainTemp > (recipeHeatingGoal + screenData.warningLimit); + + if (tempTooHigh && !tempWarningAccepted && heatingTimer == null) + { + // Show error window when temperature is too high before starting heating delay + if (noChoiceChoosenTimer == null) + { + noChoiceChoosenSeconds = 0; + noChoiceChoosenTimer = new Timer(NoChoiceChoosenTimer, null, 0, 1000); + } + + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings settings) + { + settings.tempErrorPopupOverlay.IsVisible = true; + } + // Don't change footer message - keep showing pre-heating status + }); + } + else if (heatingTimer == null) + { + // Temperature is acceptable OR user accepted warning - start heating timer + heatingTimer = new Timer(HeatingTimer, null, 1000, 1000); + heatingSeconds = _machine.HeatingDelay; + + + } + } + else if ((Heating != 1) && (cooling != 1 || cooling != 10) && (pouring != 1 || pouring != 10) && heatingTimer == null && coolingTimer == null && pouringTimer == null && startRecipe == 1) + { + // Goals not met yet - continue heating (only if recipe is still running) + sendComTankTemp = 1; + Heating = 1; + sendComHeating = 1; + setHeatingTimerOnce = 1; + + // Only update footer if we're in pre-heating phase + UpdateFooterMessage(RecipePhase.PreHeating, + $"Pre-heating"); + } + } + //if (comPumpTemp>=_machine.PumbMaxHeat) + //{ + // //start timer + // if (fountainTimer==null) + // { + // if (fountainSeconds == 1) + // { + // fountainSeconds = _machine.PumbDelay; + // } + // fountainTimer = new Timer(FountainTimer, null, 0, 1000); + // } + // if (turnOnFountainMotor) + // { + // fount = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + // if (fount != null) + // { + // if (fount.BitNumbers.Count > 0) + // { + // foreach (var bit in fount.BitNumbers) + // { + // holdingRegister.motor |= (ushort)(1 << bit); + // } + // isWriting = true; + + // } + // } + + // turnOnFountainMotor = false; + // } + //} + //else + //{ + // startFountainMotorFlashing = 1; + //} + if (sendComTankTemp == 1) + { + sendComTankTemp = -1; + } + if (pause) + { + isPaused = true; + if (Heating == 1) + { + Heating = 10; + } + else if (cooling == 1) + { + cooling = 10; + } + else if (pouring == 1) + { + pouring = 10; + } + //PumbOn = -1; + if (tankBtm != null) + { + if (tankBtm.BitNumbers.Count > 0) + { + foreach (var item in tankBtm.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.TankMaxHeat * 10; + } + + } + + + } + if (tankWall != null) + { + if (tankWall.BitNumbers.Count > 0) + { + foreach (var item in tankWall.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.TankMaxHeat * 10; + } + + } + + + } + + if (pumb != null) + { + if (pumb.BitNumbers.Count > 0) + { + foreach (var item in pumb.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.PumbMaxHeat * 10; + + } + } + + + } + if (fount != null) + { + if (fount.BitNumbers.Count > 0) + { + foreach (var item in fount.BitNumbers) + { + setTempValues[item - 8] = -10000; + + } + } + + + } + holdingRegister.setTemp1 = setTempValues[0]; + holdingRegister.setTemp2 = setTempValues[1]; + holdingRegister.setTemp3 = setTempValues[2]; + holdingRegister.setTemp4 = setTempValues[3]; + holdingRegister.motor = 0; + + await WriteToSerialAsync("RecipePause"); + startMixerMotor = 0; + startFountainMotor = 0; + if (heatingTimer != null) + { + heatingTimer.Change(Timeout.Infinite, Timeout.Infinite); + heatingSeconds = _machine.HeatingDelay; + heatingTimer = null; + } + if (coolingTimer != null) + { + coolingTimer.Change(Timeout.Infinite, Timeout.Infinite); + coolingSeconds = _machine.CoolingDelay; + coolingTimer = null; + + } + if (pouringTimer != null) + { + pouringTimer.Change(Timeout.Infinite, Timeout.Infinite); + pouringSeconds = _machine.PouringDelay; + pouringTimer = null; + + } + if (pedalOffTimer != null) + { + pedalOffTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOffSeconds = 0; + } + if (pedalOnTimer != null) + { + pedalOnTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOnSeconds = 0; + } + if (fountainPauseTimer != null) + { + fountainPauseTimer.Change(Timeout.Infinite, Timeout.Infinite); + fountainPauseSeconds = 10; + fountainPauseTimer = null; + } + if (fountainTimer != null) + { + fountainTimer.Change(Timeout.Infinite, Timeout.Infinite); + fountainTimer = null; + } + if (mixerTimer != null) + { + mixerTimer.Change(Timeout.Infinite, Timeout.Infinite); + mixerTimer = null; + } + Dispatcher.UIThread.Post(async () => + { + footerMsg.Text = "Recipe Paused"; + + }); + pause = false; + } + else if (unPause) + { + isPaused = false; + if (Heating == 10) + { + Heating = 1; + sendComHeating = 1; + } + else if (cooling == 10) + { + cooling = 1; + sendComCooling = 1; + } + else if (pouring == 10) + { + pouring = 1; + sendComPouring = 1; + } + PumbOn = 1; + + Dispatcher.UIThread.Post(async () => + { + footerMsg.Text = "Recipe Continued"; + }); + unPause = false; + } + if (Heating == 1) + { + if (errors.Count > 0) + { + if ((DateTime.Now - errors.Min(x => x.errorDate)).TotalSeconds >= 3.5) + { + if (!isPaused) + { + pause = true; + + } + } + + } + else + { + Dispatcher.UIThread.Post(async () => + { + if (ContentArea.Content is Settings result) + { + // Only start heating delay timer when temperature reaches or exceeds the heating goal + if (comFountainTemp * 10 >= (result._recipeTable?.HeatingGoal * 10) - (screenData.warningLimit * 10)) + { + if (setHeatingTimerOnce == 1) + { + heatingTimer = new Timer(HeatingTimer, null, 1000, 1000); + heatingSeconds = _machine.HeatingDelay; + setHeatingTimerOnce = -1; + + } + } + else if (sendComHeating == 1) + { + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + recipeHeatingGoal = result._recipeTable.HeatingGoal; + recipeCoolingGoal = result._recipeTable.CoolingGoal; + recipePouringGoal = result._recipeTable.PouringGoal; + } + }); + + foreach (var item in tankBtm.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.TankMaxHeat; + } + foreach (var item in tankWall.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.TankMaxHeat; + } + foreach (var item in pumb.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.PumbMaxHeat; + } + foreach (var item in fount.BitNumbers) + { + setTempValues[item - 8] = (int)recipeHeatingGoal; + } + holdingRegister.setTemp1 = setTempValues[0] * 10; + holdingRegister.setTemp2 = setTempValues[1] * 10; + holdingRegister.setTemp3 = setTempValues[2] * 10; + holdingRegister.setTemp4 = setTempValues[3] * 10; + if (fountainMotor != null) + { + if (fountainMotor.BitNumbers.Count > 0) + { + foreach (var bit in fountainMotor.BitNumbers) + { + holdingRegister.motor |= (ushort)(1 << bit); + } + isFountainMotorOn = true; + + } + } + if (mixerMotor != null) + { + if (mixerMotor.BitNumbers.Count > 0) + { + foreach (var bit in mixerMotor.BitNumbers) + { + holdingRegister.motor |= (ushort)(1 << bit); + } + isMixerMotorOn = true; + + } + } + await WriteToSerialAsync("HeatingPhase"); + Dispatcher.UIThread.Post(async () => + { + footerMsg.Text = "Heating phase"; + + }); + + sendComHeating = -1; + + } + } + }); + } + + + } + else if (cooling == 1) + { + if (errors.Count > 0) + { + if (!isPaused) + { + //pause = true; + + } + } + else + { + if (sendComCooling == 1) + { + foreach (var item in tankBtm.BitNumbers) + { + setTempValues[item - 8] = -1000; + } + foreach (var item in tankWall.BitNumbers) + { + setTempValues[item - 8] = -1000; + } + foreach (var item in pumb.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.PumbMinHeat; + + } + foreach (var item in fount.BitNumbers) + { + setTempValues[item - 8] = (int)recipeCoolingGoal; + + } + holdingRegister.setTemp1 = setTempValues[0] * 10; + holdingRegister.setTemp2 = setTempValues[1] * 10; + holdingRegister.setTemp3 = setTempValues[2] * 10; + holdingRegister.setTemp4 = setTempValues[3] * 10; + if (fountainMotor != null) + { + if (fountainMotor.BitNumbers.Count > 0) + { + foreach (var bit in fountainMotor.BitNumbers) + { + holdingRegister.motor |= (ushort)(1 << bit); + } + isFountainMotorOn = true; + + } + } + if (mixerMotor != null) + { + if (mixerMotor.BitNumbers.Count > 0) + { + foreach (var bit in mixerMotor.BitNumbers) + { + holdingRegister.motor |= (ushort)(1 << bit); + } + isMixerMotorOn = true; + + } + } + await WriteToSerialAsync("CoolingPhase"); + Dispatcher.UIThread.Post(async () => + { + footerMsg.Text = "Cooling phase"; + }); + sendComCooling = -1; + + + } + + Dispatcher.UIThread.Post(async () => + { + + if (ContentArea.Content is Settings result) + { + // Check if current temperature is already at pouring goal - skip cooling phase + if (Math.Abs((double)(comFountainTemp * 10) - (double)(result._recipeTable?.PouringGoal * 10 ?? 0)) <= (screenData.warningLimit * 10)) + { + if (setCoolingTimerOnce == 1) + { + // Skip cooling phase, go directly to pouring + cooling = -1; + pouring = 1; + sendComPouring = 1; + setPouringTimerOnce = 1; + setCoolingTimerOnce = -1; + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Already at pouring temperature - starting pouring phase"; + }); + } + } + // Only start cooling delay timer when temperature reaches or goes below the cooling goal + else if (comFountainTemp * 10 <= (result._recipeTable?.CoolingGoal * 10) + (screenData.warningLimit * 10)) + { + if (setCoolingTimerOnce == 1) + { + if (coolingTimer == null) + { + coolingTimer = new Timer(CoolingTimer, null, 1000, 1000); + } + else + { + // Ensure the timer is running at the correct interval + coolingTimer.Change(1000, 1000); + } + coolingSeconds = _machine.CoolingDelay; + setCoolingTimerOnce = -1; + + } + } + } + }); + } + + + } + else if (pouring == 1) + { + if (errors.Count > 0) + { + if (!isPaused) + { + //pause = true; + + } + } + else + { + if (sendComPouring == 1) + { + + foreach (var item in tankBtm.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.TankMaxHeat; + + } + foreach (var item in tankWall.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.TankMaxHeat; + + } + foreach (var item in pumb.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.PumbMaxHeat; + + } + foreach (var item in fount.BitNumbers) + { + setTempValues[item - 8] = (int)recipePouringGoal; + + } + holdingRegister.setTemp1 = setTempValues[0] * 10; + holdingRegister.setTemp2 = setTempValues[1] * 10; + holdingRegister.setTemp3 = setTempValues[2] * 10; + holdingRegister.setTemp4 = setTempValues[3] * 10; + if (fountainMotor != null) + { + if (fountainMotor.BitNumbers.Count > 0) + { + foreach (var bit in fountainMotor.BitNumbers) + { + holdingRegister.motor |= (ushort)(1 << bit); + } + isFountainMotorOn = true; + + } + } + if (mixerMotor != null) + { + if (mixerMotor.BitNumbers.Count > 0) + { + foreach (var bit in mixerMotor.BitNumbers) + { + holdingRegister.motor |= (ushort)(1 << bit); + } + isMixerMotorOn = true; + + } + } + await WriteToSerialAsync("PouringPhase"); + Dispatcher.UIThread.Post(async () => + { + footerMsg.Text = "Prepare for pouring"; + }); + sendComPouring = -1; + + } + Dispatcher.UIThread.Post(async () => + { + if (ContentArea.Content is Settings result) + { + // Only start pouring delay timer when temperature reaches the pouring goal (within tolerance) + if (Math.Abs((double)(comFountainTemp * 10) - (double)(result._recipeTable?.PouringGoal * 10 ?? 0)) <= (screenData.warningLimit * 10)) + { + if (setPouringTimerOnce == 1) + { + foreach (var item in tankBtm.BitNumbers) + { + setTempValues[item - 8] = (int)(recipePouringGoal + _machine.PreHeatingTemp); + + } + foreach (var item in tankWall.BitNumbers) + { + setTempValues[item - 8] = (int)(recipePouringGoal + _machine.PreHeatingTemp); + + } + foreach (var item in pumb.BitNumbers) + { + setTempValues[item - 8] = -1000; + + } + foreach (var item in fount.BitNumbers) + { + setTempValues[item - 8] = (int)recipePouringGoal; + } + holdingRegister.setTemp1 = setTempValues[0] * 10; + holdingRegister.setTemp2 = setTempValues[1] * 10; + holdingRegister.setTemp3 = setTempValues[2] * 10; + holdingRegister.setTemp4 = setTempValues[3] * 10; + if (fountainMotor != null) + { + if (fountainMotor.BitNumbers.Count > 0) + { + foreach (var bit in fountainMotor.BitNumbers) + { + holdingRegister.motor |= (ushort)(1 << bit); + } + isFountainMotorOn = true; + } + } + if (mixerMotor != null) + { + if (mixerMotor.BitNumbers.Count > 0) + { + foreach (var bit in mixerMotor.BitNumbers) + { + holdingRegister.motor |= (ushort)(1 << bit); + } + isMixerMotorOn = true; + } + } + await WriteToSerialAsync("PouringPhase"); + if (pouringTimer == null) + { + pouringTimer = new Timer(PouringTimer, null, 1000, 1000); + } + else + { + // Ensure the timer is running at the correct interval + pouringTimer.Change(1000, 1000); + } + pouringSeconds = _machine.PouringDelay; + setPouringTimerOnce = -1; + + } + } + } + }); + } + + + } + } + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Admin"; + }); + } + } + + + } + + + if (PumbOn == 1) + { + //Dispatcher.UIThread.Post(() => + //{ + // recipeStartBtn.IsEnabled = true; + + //}); + if (pedalMotor == 0) // Manual Pedal + { + // Reset auto mode flag and stop timers + isPedalAutoMode = false; + + // Stop pedal timers + if (pedalOnTimer != null) + { + pedalOnTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOnTimer.Dispose(); + pedalOnTimer = null; + } + if (pedalOffTimer != null) + { + pedalOffTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOffTimer.Dispose(); + pedalOffTimer = null; + } + + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings settings) + { + settings.pedalDelayTxt.IsVisible = false; + settings.pedalDelayCounter.IsVisible = false; + } + }); + + var pedal = _mapping.Find(x => x.Name.ToLower() == "pedal"); + if (pedal != null) + { + // READING THE INPUT REGISTER + if (errors.Count == 0) + { + ushort registerValue = (ushort)inputValues[1]; + if (allPedalBitsOn != pedal.BitNumbers.All(bit => (registerValue & (1 << bit)) != 0)) + { + allPedalBitsOn = pedal.BitNumbers.All(bit => (registerValue & (1 << bit)) != 0); + pedalStateChanged = 1; + } + else + { + pedalStateChanged = 0; + } + + if (!allPedalBitsOn) + { + pedalState = 1;// All bits ON + } + else + { + pedalState = 0; // At least one bit is OFF + } + + // READING THE motor REGISTER + var fount = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + if (fount != null) + { + if (fount.BitNumbers.Count > 0) + { + bool valueChanged = false; + if (pedalState == 1) // If all monitored bits are ON + { + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + result.pedalUnderLine.Fill = Brush.Parse(result.PassiveColor); + } + }); + if (!(comPumpTemp <= recipeCoolingGoal - 3)) + { + foreach (var bit in fount.BitNumbers) + { + if (!ToBinary(holdingRegister.motor)[bit]) + { + //Debug.WriteLine("input value:" + registerValue); + //Debug.WriteLine("pedal on:" + allBitsOn); + holdingRegister.motor |= (ushort)(1 << bit); + valueChanged = true; + + } + } + if (valueChanged) + { + await WriteToSerialAsync("PedalManual"); + valueChanged = false; + if (isPaused) + { + unPause = true; + } + } + + } + + } + else // If at least one monitored bit is OFF + { + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + result.pedalUnderLine.Fill = Brush.Parse(result.ActiveColor); + } + }); + if (pedalStateChanged == 1) + { + foreach (var bit in fount.BitNumbers) + { + if (ToBinary(holdingRegister.motor)[bit]) + { + holdingRegister.motor &= (ushort)~(1 << bit); + valueChanged = true; + } + + } + if (valueChanged) + { + await WriteToSerialAsync("PedalManual"); + valueChanged = false; + } + + } + + if (fountainPauseTimer == null && startRecipe == 1 && (Heating == 1 || heatingTimer != null || cooling == 1 || coolingTimer != null || pouring == 1 || pouringTimer != null + )) + { + fountainPauseSeconds = 10; + fountainPauseTimer = new Timer(FountainPauseTimer, null, 0, 1000); + } + + } + + if (pedalStateChanged == 1) + { + // WRITE UPDATED VALUE TO HVO REGISTER + //isWriting = true; + } + + } + + } + } + + + } + } + + else if (pedalMotor == 1) // auto Pedal + { + // Set auto mode flag + isPedalAutoMode = true; + + // Direct fountain control based on pedal state + var fount = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + if (fount != null && fount.BitNumbers.Count > 0) + { + if (pedalState == 0) // Pedal ON - Turn fountain ON + { + foreach (var bit in fount.BitNumbers) + { + holdingRegister.motor |= (ushort)(1 << bit); // Set the motor bit ON + } + isFountainMotorOn = true; + startFountainMotor = 1; + sendComFountainMotor = 1; + startFountainMotorFlashing = -1; // No flashing + await WriteToSerialAsync("Pedal Auto - Fountain ON"); + + // Update UI to show fountain is ON + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + var fountainLable = result.FountainSP.Children[1] as Avalonia.Controls.Label; + var fountainRectangel = result.FountainSP.Children[2] as Avalonia.Controls.Shapes.Rectangle; + fountainLable.Content = "ON"; + fountainLable.Foreground = Brush.Parse("#ff231f20"); + fountainRectangel.Fill = Brush.Parse(ActiveColor); + } + }); + } + else if (pedalState == 1) // Pedal OFF - Turn fountain OFF + { + foreach (var bit in fount.BitNumbers) + { + holdingRegister.motor &= (ushort)~(1 << bit); // Clear the motor bit OFF + } + isFountainMotorOn = false; + startFountainMotor = 0; + sendComFountainMotor = 0; + startFountainMotorFlashing = -1; // No flashing + await WriteToSerialAsync("Pedal Auto - Fountain OFF"); + + // Update UI to show fountain is OFF + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + var fountainLable = result.FountainSP.Children[1] as Avalonia.Controls.Label; + var fountainRectangel = result.FountainSP.Children[2] as Avalonia.Controls.Shapes.Rectangle; + fountainLable.Content = "OFF"; + fountainLable.Foreground = Brush.Parse("#ff231f20"); + fountainRectangel.Fill = Brush.Parse(PassiveColor); + } + }); + } + } + + // Reset pedal state and handle timing + pedalState = -1; + + // Handle pedal timing (alternating ON/OFF based on recipe settings) + if (setPedalTimerOnce == 1) // Start OFF timer + { + if (pedalOffTimer == null) + { + pedalOffTimer = new Timer(PedalOffTimer, null, 1000, 1000); + } + else + { + pedalOffTimer.Change(1000, 1000); + } + setPedalTimerOnce = -1; + } + else if (setPedalTimerOnce == 0) // Start ON timer + { + if (pedalOnTimer == null) + { + pedalOnTimer = new Timer(PedalOnTimer, null, 1000, 1000); + } + else + { + pedalOnTimer.Change(1000, 1000); + } + setPedalTimerOnce = -1; + } + } + + //change diag UI + var hvo = ToBinary(holdingRegister.hvOut); + var lvo = ToBinary(holdingRegister.lvOut); + var motor = ToBinary(holdingRegister.motor); + + Dispatcher.UIThread.Post(async () => + { + if (ContentArea.Content is Diagnostics diagnostics) + { + foreach (var item in diagnostics.MotoreState.OfType().ToList()) + { + var stackPanel = item.Children[0] as StackPanel; + var text = stackPanel.Children[1] as TextBlock; + var border = item.Children[1] as Border; + if (motor[int.Parse(item.Tag.ToString())]) + { + + text.Text = "ON"; + border.Background = Brush.Parse(diagnostics.PinkColor); + diagnostics.MotoreState.OfType().ToList().Find(x => x.Tag.ToString() == item.Tag.ToString()).Fill = Brush.Parse(diagnostics.OrangeColor); + + } + else + { + text.Text = "OFF"; + border.Background = Brush.Parse(diagnostics.GrayColor); + diagnostics.MotoreState.OfType().ToList().Find(x => x.Tag.ToString() == item.Tag.ToString()).Fill = Brush.Parse(diagnostics.GrayColor); + + + } + } + + // HVO + foreach (var item in diagnostics.hvoOutPuts.OfType().ToList()) + { + var text = item.Children[1] as TextBlock; + var border = item.Children[2] as Border; + if (hvo[int.Parse(item.Tag.ToString())]) + { + + text.Text = "ON"; + border.Background = Brush.Parse(diagnostics.PinkColor); + diagnostics.hvoOutPuts.OfType().ToList().Find(x => x.Tag.ToString() == item.Tag.ToString()).Fill = Brush.Parse(diagnostics.OrangeColor); + + } + else + { + text.Text = "OFF"; + border.Background = Brush.Parse(diagnostics.GrayColor); + diagnostics.hvoOutPuts.OfType().ToList().Find(x => x.Tag.ToString() == item.Tag.ToString()).Fill = Brush.Parse(diagnostics.GrayColor); + + + } + } + + // LVO + foreach (var item in diagnostics.lvoOutPuts.OfType().ToList()) + { + var text = item.Children[1] as TextBlock; + var border = item.Children[2] as Border; + if (lvo[int.Parse(item.Tag.ToString())]) + { + + text.Text = "ON"; + border.Background = Brush.Parse(diagnostics.PinkColor); + diagnostics.lvoOutPuts.OfType().ToList().Find(x => x.Tag.ToString() == item.Tag.ToString()).Fill = Brush.Parse(diagnostics.GreenColor); + + } + else + { + text.Text = "OFF"; + border.Background = Brush.Parse(diagnostics.GrayColor); + diagnostics.lvoOutPuts.OfType().ToList().Find(x => x.Tag.ToString() == item.Tag.ToString()).Fill = Brush.Parse(diagnostics.GrayColor); + + + } + } + foreach (var item in diagnostics.lvoOutPuts.OfType().ToList()) + { + var text = item.Children[1] as TextBlock; + var border = item.Children[2] as Border; + if (lvo[int.Parse(item.Tag.ToString())]) + { + + text.Text = "ON"; + border.Background = Brush.Parse(diagnostics.PinkColor); + diagnostics.lvoOutPuts.OfType().ToList().Find(x => x.Tag.ToString() == item.Tag.ToString()).Fill = Brush.Parse(diagnostics.GreenColor); + + } + else + { + text.Text = "OFF"; + border.Background = Brush.Parse(diagnostics.GrayColor); + diagnostics.lvoOutPuts.OfType().ToList().Find(x => x.Tag.ToString() == item.Tag.ToString()).Fill = Brush.Parse(diagnostics.GrayColor); + + + } + } + } + }); + + await Task.Delay(100); + + } + } + catch (Exception e) + { + + } + + } + } + } + catch + { + } + finally + { + + } + + } + + + + } + } + + + + + public bool ConnectToSerialPort() + { + screenData = _screeen.ReadScreens()?[0]; + try + { + if (_port != null && _port.IsOpen) + { + _port.Close(); + } + _port = null; + _port = new SerialPort(screenData.port, screenData.boundRate); + switch (screenData.parity) + { + case 0: + _port.Parity = Parity.None; + break; + case 1: + _port.Parity = Parity.Odd; + break; + case 2: + _port.Parity = Parity.Even; + break; + case 3: + _port.Parity = Parity.Mark; + break; + case 4: + _port.Parity = Parity.Space; + break; + default: + _port.Parity = Parity.None; + break; + } + switch (screenData.stopBits) + { + case 2: + _port.StopBits = StopBits.Two; + break; + default: + _port.StopBits = StopBits.One; + break; + } + _port.DataBits = 8; + _port.Handshake = Handshake.None; + _port.DtrEnable = true; + + // Open the serial port + + _port.Open(); + return true; + + } + catch (Exception ex) + { + + Console.WriteLine($"Error connecting to port {screenData.port}: {ex.Message}"); + _port = null; + return false; + } + } + + + + + public void closeConnection() + { + isRunning = false; + monitorThread.Abort(); + } + private async void OnClosing1(object? sender, CancelEventArgs e) + { + closeConnection(); + + } + private void OnClosingWindow(object? sender, WindowClosingEventArgs e) + { + if (_port != null && _port.IsOpen) + { + _port.Close(); + //_port = null; + } + // Example: Cancel the close if needed + // e.Cancel = true; + } + + + + + + //Main Window Functions + private void errorLogoClick(object? sender, RoutedEventArgs e) + { + errorPopupOverlay.IsVisible = true; + //errorTitel.Text = errorLogo.Tag.ToString(); + errorMsg.Text = errorMsg.Text.Trim(); + } + private void warningLogoClick(object? sender, RoutedEventArgs e) + { + warningPopupOverlay.IsVisible = true; + warningTitel.Text = warningLogo.Tag.ToString(); + warningMsg.Text = warningMsg.Text.Trim(); + } + private void HomeTraclBtn(object? sender, RoutedEventArgs e) + { + if (ContentArea.Content is Settings result) + { + result.DeletePopupOverlay.IsVisible = true; + result.DeletePopupOverlay.Tag = "home"; + + } + else if (ContentArea.Content is Diagnostics diagnostics) + { + restBoard = true; + + this.UserName.Content = "Select User"; + footerMsg.Text = ""; + ContentArea.Content = new Home(this); + } + else + { + this.UserName.Content = "Select User"; + footerMsg.Text = ""; + ContentArea.Content = new Home(this); + } + } + private void DiagnosticsBtn(object? sender, RoutedEventArgs e) + { + if (ContentArea.Content is AdvanceSettings advanceSettings) + { + footerMsg.Text = ""; + ContentArea.Content = new Diagnostics(this, true); + } + else if (ContentArea.Content is ManualControl) + { + footerMsg.Text = ""; + ContentArea.Content = new Diagnostics(this, false, true); + } + else + { + footerMsg.Text = ""; + ContentArea.Content = new Diagnostics(this); + } + + } + private void ChefManualBtn(object? sender, RoutedEventArgs e) + { + footerMsg.Text = ""; + ContentArea.Content = new ManualControl(this); + + } + public void AdvanceSettingsView(object? sender, RoutedEventArgs e) + { + if (ContentArea.Content is Diagnostics) + { + ContentArea.Content = new AdvanceSettings(this, true, false); + + } + else if (ContentArea.Content is Software) + { + ContentArea.Content = new AdvanceSettings(this, false, true); + + } + else + { + ContentArea.Content = new AdvanceSettings(this); + + } + + } + private void RecipeSelTrackBtn(object? sender, RoutedEventArgs e) + { + if (ContentArea.Content is Settings result) + { + result.DeletePopupOverlay.IsVisible = true; + result.DeletePopupOverlay.Tag = "recipeSel"; + } + else + { + footerMsg.Text = ""; + ContentArea.Content = new Recipe(this, Program.currentUser); + } + + + } + private void SettingTrackBtn(object? sender, RoutedEventArgs e) + { + if (ContentArea.Content is Diagnostics diagnostics) + { + restBoard = true; + } + footerMsg.Text = ""; + ContentArea.Content = new Admin(this, Program.currentUser); + } + private void SoftwareBtn(object? sender, RoutedEventArgs e) + { + if (ContentArea.Content is AdvanceSettings) + { + footerMsg.Text = ""; + ContentArea.Content = new Software(this, true); + } + else if (ContentArea.Content is ManualControl) + { + footerMsg.Text = ""; + ContentArea.Content = new Software(this, false, true); + } + else + { + footerMsg.Text = ""; + ContentArea.Content = new Software(this); + } + + + } + + private async void PreHeatingClick(object? sender, RoutedEventArgs e) + { + if (ContentArea.Content is Settings result) + { + if (result.recipeSettings.IsEnabled) + { + startPreHeating = 1; + writingMaxTemp = 1; + //if (!isMixerMotorOn) + //{ + // result.mixerBtn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); + //} + //if (!isFountainMotorOn) + //{ + // result.fountainBtn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); + //} + } + else + { + startPreHeating = 0; + writingMaxTemp = 0; + isFlashPreHeating = false; + } + } + + } + //Mixer + public async void MotorClick(object? sender, RoutedEventArgs e) + { + if (!isMixerMotorOn) + { + isMixerMotorOn = true; + checkMixerTWT_HWTH = true; + setMixerTimerOnce = true; + } + else + { + isMixerMotorOn = false; + checkMixerTWT_HWTH = false; + startMixerMotorFlashing = 0; + sendComMixerMotor = 0; + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings settings) + { + settings.mixerDelayTxt.IsVisible = false; + settings.mixerDelayCounter.IsVisible = false; + } + }); + if (mixerTimer != null) + { + mixerTimer.Change(Timeout.Infinite, Timeout.Infinite); + mixerTimer = null; + } + + } + } + private void MixerTimer(object state) + { + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings settings) + { + if (comTankTemp >= recipeCoolingGoal - 3) + { + mixerSeconds--; + } + else + { + //mixerTimer.Change(Timeout.Infinite, Timeout.Infinite); + } + + if (mixerSeconds <= 0) + { + // Stop the timer after 15 seconds + settings.mixerDelayTxt.IsVisible = false; + settings.mixerDelayCounter.IsVisible = false; + + if (mixerTimer != null) + { + mixerTimer.Change(Timeout.Infinite, Timeout.Infinite); + mixerTimer = null; + } + startMixerMotorFlashing = 0; + sendComMixerMotor = 1; + return; + } + if (mixerSeconds <= _machine.MixerDelay) + { + settings.mixerDelayTxt.IsVisible = true; + settings.mixerDelayCounter.Text = mixerSeconds.ToString(); + settings.mixerDelayCounter.IsVisible = true; + + } + } + + }); + + + + } + private void StopMixerTimer(object state) + { + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings settings) + { + if (comTankTemp <= recipeCoolingGoal - 3) + { + stopMixerSecondes--; + } + else + { + //mixerTimer.Change(Timeout.Infinite, Timeout.Infinite); + } + + if (stopMixerSecondes <= 0) + { + sendComMixerMotor = 0; + + + + stopMixerTimer.Change(Timeout.Infinite, Timeout.Infinite); + stopMixerTimer = null; + return; + } + } + + }); + + + + } + //Fountain + public async void FountainClick(object? sender, RoutedEventArgs e) + { + // Reset pedal auto mode when user manually controls fountain + if (isPedalAutoMode) + { + isPedalAutoMode = false; + // Stop pedal timers when user takes manual control + if (pedalOnTimer != null) + { + pedalOnTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOnTimer.Dispose(); + pedalOnTimer = null; + } + if (pedalOffTimer != null) + { + pedalOffTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOffTimer.Dispose(); + pedalOffTimer = null; + } + pedalMotor = -1; // Reset to manual mode + } + + if (!isFountainMotorOn) + { + isFountainMotorOn = true; + checkFountainTMT_PMT = true; + setFountainTimerOnce = true; + } + else + { + isFountainMotorOn = false; + + checkFountainTMT_PMT = false; + startFountainMotorFlashing = 0; + sendComFountainMotor = 0; + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings settings) + { + settings.fountainDelayTxt.IsVisible = false; + settings.fountainDelayCounter.IsVisible = false; + settings.fountainTargetTxt.IsVisible = false; + settings.fountainTagetTemp.IsVisible = false; + } + }); + if (fountainTimer != null) + { + fountainTimer.Change(Timeout.Infinite, Timeout.Infinite); + fountainTimer = null; + + } + + } + } + private void FountainTimer(object state) + { + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings settings) + { + if (comPumpTemp >= recipeCoolingGoal - 3) + { + fountainSeconds--; + } + else + { + //fountainTimer.Change(Timeout.Infinite, Timeout.Infinite); + } + if (fountainSeconds <= 0) + { + // Stop the timer after 15 seconds + settings.fountainDelayTxt.IsVisible = false; + settings.fountainDelayCounter.IsVisible = false; + settings.fountainTargetTxt.IsVisible = false; + settings.fountainTagetTemp.IsVisible = false; + + if (fountainTimer != null) + { + fountainTimer.Change(Timeout.Infinite, Timeout.Infinite); + fountainTimer = null; + } + startFountainMotorFlashing = 0; + sendComFountainMotor = 1; + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + if (startRecipe == 1 && !isPaused) + { + PumbOn = 1; + + } + if (result._recipeTable.Pedal.Value) + { + pedalMotor = 0; + } + else + { + pedalMotor = 1; + pedalState = 0; + setPedalTimerOnce = 1; + } + } + + }); + + return; + } + if (fountainSeconds <= _machine.PumbDelay) + { + + + settings.fountainDelayTxt.Text = "Chocolate Delay: "; + settings.fountainDelayTxt.IsVisible = true; + settings.fountainDelayCounter.Text = fountainSeconds.ToString(); + settings.fountainDelayCounter.IsVisible = true; + settings.fountainTagetTemp.IsVisible = false; + settings.fountainTargetTxt.IsVisible = false; + + } + } + + + + }); + + + } + private void StopFountainTimer(object state) + { + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings settings) + { + if (comPumpTemp <= recipeCoolingGoal - 3) + { + stopFountainSecondes--; + } + else + { + //mixerTimer.Change(Timeout.Infinite, Timeout.Infinite); + } + + if (stopFountainSecondes <= 0) + { + sendComFountainMotor = 0; + + + stopFountainTimer.Change(Timeout.Infinite, Timeout.Infinite); + stopFountainTimer = null; + return; + } + } + + }); + + + + } + private void FountainPauseTimer(object state) + { + Dispatcher.UIThread.Post(() => + { + var fount = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + + if (allBitsOn != fount.BitNumbers.All(bit => (holdingRegister.motor & (1 << bit)) != 0)) + { + allBitsOn = fount.BitNumbers.All(bit => (holdingRegister.motor & (1 << bit)) != 0); + } + if (fountainPauseSeconds <= 0) + { + pause = true; + if (fountainPauseTimer != null) + { + fountainPauseTimer.Change(Timeout.Infinite, Timeout.Infinite); + fountainPauseTimer = null; + } + + return; + } + if (!allBitsOn) + { + //motor is off + //increase the counter + fountainPauseSeconds--; + //footerMsg.Text ="Fountain is off recipe will pause after: "+ fountainPauseSeconds.ToString(); + } + else + { + //motor is on + //cancel the timer + if (fountainPauseTimer != null) + { + + fountainPauseTimer.Change(Timeout.Infinite, Timeout.Infinite); + fountainPauseTimer = null; + } + } + + //if the counter greater than 10 then pause the recipe + }); + + + } + private void NoChoiceChoosenTimer(object state) + { + Dispatcher.UIThread.Post(() => + { + //increase the coiunter + if (ContentArea.Content is Settings settings) + { + if (settings.tempErrorPopupOverlay.IsVisible) + { + noChoiceChoosenSeconds++; + //footerMsg.Text = "sec" + noChoiceChoosenSeconds.ToString(); + } + else + { + //stop the timer + if (noChoiceChoosenTimer != null) + { + noChoiceChoosenTimer.Change(Timeout.Infinite, Timeout.Infinite); + noChoiceChoosenTimer = null; + } + } + if (noChoiceChoosenSeconds >= 180)//change to 3 min + { + //if it reach the 3 min then stop the recipe + startRecipe = 0; + Heating = 0; + cooling = 0; + pouring = 0; + PumbOn = -1; + pedalMotor = -1; + if (heatingTimer != null) + { + heatingTimer.Change(Timeout.Infinite, Timeout.Infinite); + heatingSeconds = _machine.HeatingDelay; + heatingTimer = null; + } + if (coolingTimer != null) + { + coolingTimer.Change(Timeout.Infinite, Timeout.Infinite); + coolingSeconds = _machine.CoolingDelay; + coolingTimer = null; + + } + if (pouringTimer != null) + { + pouringTimer.Change(Timeout.Infinite, Timeout.Infinite); + pouringSeconds = _machine.PouringDelay; + pouringTimer = null; + + } + if (pedalOffTimer != null) + { + pedalOffTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOffSeconds = 0; + } + if (pedalOnTimer != null) + { + pedalOnTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOnSeconds = 0; + } + if (fountainPauseTimer != null) + { + fountainPauseTimer.Change(Timeout.Infinite, Timeout.Infinite); + fountainPauseSeconds = 10; + fountainPauseTimer = null; + } + if (fountainTimer != null) + { + fountainTimer.Change(Timeout.Infinite, Timeout.Infinite); + fountainTimer = null; + } + if (mixerTimer != null) + { + mixerTimer.Change(Timeout.Infinite, Timeout.Infinite); + mixerTimer = null; + } + var fount = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + if (fount != null) + { + if (fount.BitNumbers.Count > 0) + { + foreach (var bit in fount.BitNumbers) + { + + holdingRegister.motor &= (ushort)~(1 << bit); + } + } + } + startPreHeating = 0; + writingMaxTemp = 0; + isFlashPreHeating = false; + holdingRegister.setTemp1 = -10000; + holdingRegister.setTemp2 = -10000; + holdingRegister.setTemp3 = -10000; + holdingRegister.setTemp4 = -10000; + settings.tempErrorPopupOverlay.IsVisible = false; + Dispatcher.UIThread.Post(async () => + { + await WriteToSerialAsync("NoChoiceChoosenTimer"); + + recipeStartBtn.Foreground = Avalonia.Media.Brushes.White; + recipeStartBtn.Background = Brush.Parse("#008000"); + footerMsg.Text = "waitting for too long... Recipe Stoped"; + recipeStartBtn.Content = "START RECIPE"; + PreHeatingBtn.IsEnabled = true; + recipeStartBtn.IsEnabled = true; + }); + + + } + } + + + }); + + + } + /// + /// Enhanced heating timer with improved goal checking and phase transition logic + /// + private void HeatingTimer(object state) + { + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings settings) + { + if (fountainPauseTimer == null) + { + if (!pauseTimer) + { + // Continue heating delay countdown + if (heatingSeconds > 0) + { + heatingSeconds--; + } + Heating = 1; + warningMessage = ""; // Clear any previous warnings + } + + // Clear warning message during heating phase + warningMessage = ""; + + // Check if heating phase is complete + if (heatingSeconds <= 0) + { + // Heating phase complete - stop heating timer first + warningMessage = ""; + heatingTimer?.Change(Timeout.Infinite, Timeout.Infinite); + heatingTimer?.Dispose(); + heatingTimer = null; + pauseTimer = false; + pauseTempTracking = false; + Heating = -1; + + // Check if chocolate temperature equals cooling goal (within tolerance) + // Using a small tolerance (0.5°C) for floating point comparison + bool chocolateAtCoolingTemp = Math.Abs(comFountainTemp - recipeCoolingGoal) <= 0.5; + + if (chocolateAtCoolingTemp) + { + // Chocolate is already at cooling temperature - show cooling delay + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings settings) + { + // Hide cooling delay display + settings.coolingDelayTxt.IsVisible = false; + settings.coolingDelayCounter.IsVisible = false; + settings.coolingDelayCounter.Text = _machine.CoolingDelay.ToString(); + UpdateFooterMessage(RecipePhase.CoolingDelay, + $"Cooling delay: {_machine.CoolingDelay} seconds"); + } + }); + + // Start cooling timer for delay countdown + cooling = 1; + sendComCooling = 1; + setCoolingTimerOnce = 1; + coolingSeconds = _machine.CoolingDelay; + + // Set flag to indicate we're in cooling delay mode + isCoolingDelayMode = true; + + if (coolingTimer == null) + { + coolingTimer = new Timer(CoolingTimer, null, 1000, 1000); + } + else + { + // Ensure the timer is running at the correct interval + coolingTimer.Change(1000, 1000); + } + } + else + { + // Chocolate needs to cool down - start cooling phase + UpdateFooterMessage(RecipePhase.CoolingPhase, "Cooling phase"); + + cooling = 1; + sendComCooling = 1; + setCoolingTimerOnce = 1; + coolingSeconds = 0; // No countdown during cooling phase + + // Set flag to indicate we're in cooling phase mode (not delay mode) + isCoolingDelayMode = false; + + if (coolingTimer == null) + { + coolingTimer = new Timer(CoolingTimer, null, 1000, 1000); + } + else + { + // Ensure the timer is running at the correct interval + coolingTimer.Change(1000, 1000); + } + } + } + else if (heatingSeconds <= _machine.HeatingDelay && !pauseTimer) + { + // Show heating delay countdown + UpdateFooterMessage(RecipePhase.HeatingDelay, $"Heating delay: {heatingSeconds} seconds"); + } + else if (heatingSeconds > _machine.HeatingDelay) + { + // Show heating phase status with current temperature + footerMsg.Text = $"Heating phase"; + } + } + } + }); + } + /// + /// Enhanced cooling timer with improved goal checking and conditional phase transitions + /// Timer runs every 1000ms (1 second) to count down seconds properly + /// + private void CoolingTimer(object state) + { + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings settings) + { + if (fountainPauseTimer == null) + { + // Check if we're in cooling phase and chocolate has reached cooling goal + // Using same tolerance as heating phase for consistency + if (!isCoolingDelayMode && Math.Abs(comFountainTemp - recipeCoolingGoal) <= 0.5) + { + // Chocolate reached cooling goal during cooling phase - switch to cooling delay + isCoolingDelayMode = true; + coolingSeconds = _machine.CoolingDelay; // Reset timer for cooling delay + + // Hide cooling delay display + settings.coolingDelayTxt.IsVisible = false; + settings.coolingDelayCounter.IsVisible = false; + settings.coolingDelayCounter.Text = coolingSeconds.ToString(); + UpdateFooterMessage(RecipePhase.CoolingDelay, + $"Cooling delay: {coolingSeconds} seconds"); + } + + if (!pauseTimer && isCoolingDelayMode && coolingSeconds > 0) + { + // Only count down during cooling DELAY, not during cooling PHASE + coolingSeconds--; + warningMessage = ""; // Clear any previous warnings + + // Update the display to show the current countdown + settings.coolingDelayCounter.Text = coolingSeconds.ToString(); + } + else if (!pauseTimer && !isCoolingDelayMode) + { + // During cooling PHASE, just monitor temperature, don't count down + warningMessage = ""; // Clear any previous warnings + } + + // Check for warning conditions - only warn if temperature is too high + bool tempTooHighForWarning = comFountainTemp > (recipeCoolingGoal + screenData.warningLimit); + + if (tempTooHighForWarning) + { + // Show warning when temperature is approaching the upper limit + if (warningMessage != "Cooling temperature approaching maximum") + { + warningMessage = "Cooling temperature approaching maximum"; + } + } + else + { + warningMessage = ""; + } + + // Check if cooling phase is complete (only when in delay mode) + if (isCoolingDelayMode && coolingSeconds <= 0) + { + // Cooling phase complete - transition to pouring phase + warningMessage = ""; + + // Safely stop the cooling timer + if (coolingTimer != null) + { + coolingTimer.Change(Timeout.Infinite, Timeout.Infinite); + coolingTimer.Dispose(); + coolingTimer = null; + } + + pauseTimer = false; + pauseTempTracking = false; + cooling = -1; + + // Check if chocolate temperature equals pouring goal + bool chocolateAtPouringTemp = Math.Abs(comFountainTemp - recipePouringGoal) <= 0.5; + + if (chocolateAtPouringTemp) + { + // Chocolate is already at pouring temperature - show pouring delay + pouring = 1; + sendComPouring = 1; + setPouringTimerOnce = 1; + pouringSeconds = _machine.PouringDelay; + isPouringDelayMode = true; + + // Start pouring timer + if (pouringTimer == null) + { + pouringTimer = new Timer(PouringTimer, null, 1000, 1000); + } + else + { + // Ensure the timer is running at the correct interval + pouringTimer.Change(1000, 1000); + } + + UpdateFooterMessage(RecipePhase.PouringPhase, + $"Pouring delay: {pouringSeconds} seconds"); + } + else + { + // Chocolate needs to reach pouring temperature - start pouring phase + pouring = 1; + sendComPouring = 1; + setPouringTimerOnce = 1; + pouringSeconds = 0; // No countdown during pouring phase + isPouringDelayMode = false; + + // Start pouring timer + if (pouringTimer == null) + { + pouringTimer = new Timer(PouringTimer, null, 1000, 1000); + } + else + { + // Ensure the timer is running at the correct interval + pouringTimer.Change(1000, 1000); + } + + UpdateFooterMessage(RecipePhase.PouringPhase, "Pouring phase"); + } + + coolingTimer = null; + + // Hide cooling delay labels when cooling phase completes + settings.coolingDelayTxt.IsVisible = false; + settings.coolingDelayCounter.IsVisible = false; + isCoolingDelayMode = false; // Reset the flag + } + else if (isCoolingDelayMode && !pauseTimer) + { + // Show cooling delay countdown when chocolate is already at cooling temperature + // Hide cooling delay display + settings.coolingDelayTxt.IsVisible = false; + settings.coolingDelayCounter.IsVisible = false; + settings.coolingDelayCounter.Text = coolingSeconds.ToString(); + UpdateFooterMessage(RecipePhase.CoolingDelay, + $"Cooling delay: {coolingSeconds} seconds"); + } + else if (!isCoolingDelayMode && !pauseTimer) + { + // Show cooling phase status when chocolate needs to cool down + settings.coolingDelayTxt.IsVisible = false; + settings.coolingDelayCounter.IsVisible = false; + UpdateFooterMessage(RecipePhase.CoolingPhase, "Cooling phase"); + } + } + } + }); + } + /// + /// Enhanced pouring timer with improved goal checking and recipe completion logic + /// Timer runs every 1000ms (1 second) to count down seconds properly + /// + private void PouringTimer(object state) + { + Dispatcher.UIThread.Post(() => + { + try + { + if (ContentArea.Content is Settings settings) + { + if (fountainPauseTimer == null) + { + // For pouring phase: Check if temperature is within acceptable range around the goal + // Both too high and too low are problematic for pouring + bool tempInRange = (comFountainTemp >= (recipePouringGoal - screenData.errorLimit)) && + (comFountainTemp <= (recipePouringGoal + screenData.errorLimit)); + + // Check if we're in pouring phase and chocolate has reached pouring goal + if (!isPouringDelayMode && Math.Abs(comFountainTemp - recipePouringGoal) <= 0.5) + { + // Chocolate reached pouring goal during pouring phase - switch to pouring delay + isPouringDelayMode = true; + pouringSeconds = _machine.PouringDelay; // Reset timer for pouring delay + + UpdateFooterMessage(RecipePhase.PouringPhase, + $"Pouring delay: {pouringSeconds} seconds"); + } + + if (!pauseTimer && isPouringDelayMode && pouringSeconds > 0) + { + // Only count down during pouring DELAY + pouringSeconds--; + warningMessage = ""; // Clear any previous warnings + + // Update the display to show the current countdown + UpdateFooterMessage(RecipePhase.PouringPhase, + $"Pouring delay: {pouringSeconds} seconds"); + } + else if (!pauseTimer && !isPouringDelayMode) + { + // During pouring PHASE, just monitor temperature + warningMessage = ""; // Clear any previous warnings + } + + // Check for warning conditions - warn if approaching limits + bool tempInWarningRange = (comFountainTemp >= (recipePouringGoal - screenData.warningLimit)) && + (comFountainTemp <= (recipePouringGoal + screenData.warningLimit)); + + if (!tempInWarningRange) + { + // Show warning when temperature is approaching limits + if (warningMessage != "Pouring temperature approaching limits") + { + warningMessage = "Pouring temperature approaching limits"; + } + } + else + { + warningMessage = ""; + } + + // Check if pouring phase is complete (only when in delay mode) + if (isPouringDelayMode && pouringSeconds <= 0) + { + // Pouring phase complete - recipe finished + warningMessage = ""; + + // Safely stop the pouring timer + if (pouringTimer != null) + { + pouringTimer.Change(Timeout.Infinite, Timeout.Infinite); + pouringTimer.Dispose(); + pouringTimer = null; + } + + pauseTimer = false; + pauseTempTracking = false; + pouring = -1; + isPouringDelayMode = false; // Reset the flag + + // Recipe completed successfully + Dispatcher.UIThread.Post(async () => + { + if (ContentArea.Content is Settings result) + { + // Handle pedal control based on recipe settings + if (result._recipeTable.Pedal.Value) + { + pedalMotor = 0; // Manual mode + } + else + { + pedalMotor = 1; // Auto mode + pedalState = 0; + setPedalTimerOnce = 1; + } + + // Fountain control is now handled directly by pedal state in auto mode + + UpdateFooterMessage(RecipePhase.Completed, "Ready for pouring"); + startRecipe = 0; // Mark recipe as completed + } + }); + } + else if (isPouringDelayMode && !pauseTimer) + { + // Show pouring delay countdown + UpdateFooterMessage(RecipePhase.PouringPhase, $"Pouring delay: {pouringSeconds} seconds"); + } + else if (!isPouringDelayMode && !pauseTimer) + { + // Show pouring phase status + UpdateFooterMessage(RecipePhase.PouringPhase, "Pouring phase"); + } + + } + } + } + catch (Exception ex) + { + footerMsg.Text = $"Error: {ex.Message}"; + } + + + }); + + + + } + /// + /// Pedal OFF timer - counts down the OFF time and then switches to ON mode + /// Timer runs every 1000ms (1 second) to count down seconds properly + /// + private void PedalOffTimer(object state) + { + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + pedalOffSeconds++; + + // Show countdown during OFF time + if (pedalOffSeconds <= result._recipeTable.PedalOffTime) + { + result.pedalDelayTxt.Text = "Pedal OFF: "; + result.pedalDelayCounter.Text = (result._recipeTable.PedalOffTime - pedalOffSeconds + 1).ToString(); + result.pedalDelayTxt.IsVisible = true; + result.pedalDelayCounter.IsVisible = true; + } + + // When OFF time is complete, switch to ON mode + if (pedalOffSeconds >= result._recipeTable.PedalOffTime) + { + pedalOffSeconds = 0; + PumbOn = 1; + pedalMotor = 1; + pedalState = 1; // Set to ON state + + // Stop the OFF timer + if (pedalOffTimer != null) + { + pedalOffTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOffTimer.Dispose(); + pedalOffTimer = null; + } + + // If still in auto mode, continue the cycle by starting the ON timer + if (isPedalAutoMode) + { + setPedalTimerOnce = 0; + } + } + } + }); + } + /// + /// Pedal ON timer - counts down the ON time and then switches to OFF mode + /// Timer runs every 1000ms (1 second) to count down seconds properly + /// + private void PedalOnTimer(object state) + { + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + pedalOnSeconds++; + + // Show countdown during ON time + if (pedalOnSeconds <= result._recipeTable.PedalOnTime) + { + result.pedalDelayTxt.Text = "Pedal ON: "; + result.pedalDelayCounter.Text = (result._recipeTable.PedalOnTime - pedalOnSeconds + 1).ToString(); + result.pedalDelayTxt.IsVisible = true; + result.pedalDelayCounter.IsVisible = true; + } + + // When ON time is complete, switch to OFF mode + if (pedalOnSeconds >= result._recipeTable.PedalOnTime) + { + pedalOnSeconds = 0; + PumbOn = 1; + pedalMotor = 1; + pedalState = 0; // Set to OFF state + + // Stop the ON timer + if (pedalOnTimer != null) + { + pedalOnTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOnTimer.Dispose(); + pedalOnTimer = null; + } + + // If still in auto mode, continue the cycle by starting the OFF timer + if (isPedalAutoMode) + { + setPedalTimerOnce = 1; + } + } + } + }); + } + //Recipe Start + public async void RecipeStartBtn(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + if (startRecipe == 0) + { + // Initialize and validate recipe parameters + if (!await InitializeAndValidateRecipe()) + { + return; // Exit if validation fails + } + + startRecipe = 1; + stopRecipeFlag = false; + tempWarningAccepted = false; // Reset temperature warning acceptance for new recipe + currentRecipePhase = RecipePhase.PreHeating; // Start with pre-heating phase + isPedalAutoMode = false; // Reset pedal auto mode for new recipe + + if (ContentArea.Content is Settings result) + { + // Retrieve recipe goals from settings + recipeHeatingGoal = result._recipeTable.HeatingGoal; + recipeCoolingGoal = result._recipeTable.CoolingGoal; + recipePouringGoal = result._recipeTable.PouringGoal; + + // Check if pre-heating is required + if (comPumpTemp * 10 < _machine.PumbMaxHeat * 10 || comTankTemp * 10 < _machine.TankMaxHeat * 10) + { + startPreHeating = 1; + writingMaxTemp = 1; + footerMsg.Text = "Pre-heating in progress..."; + } + + // Ensure motors are running if needed + if (!isMixerMotorOn) + { + result.mixerBtn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); + } + if (!isFountainMotorOn) + { + result.fountainBtn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); + } + + // Start goal monitoring and phase transitions + await StartRecipePhaseMonitoring(); + + // Update UI to indicate recipe is running + Dispatcher.UIThread.Post(() => + { + result.mixerBtn.IsEnabled = false; + result.fountainBtn.IsEnabled = false; + PreHeatingBtn.IsEnabled = false; + recipeStartBtn.IsEnabled = true; + button.Background = Avalonia.Media.Brushes.Red; + button.Content = "STOP RECIPE"; + }); + } + } + else if (startRecipe == 1) + { + // Stop recipe execution + await StopRecipeExecution(button); + } + } + } + + /// + /// Initialize and validate recipe parameters before starting + /// + private async Task InitializeAndValidateRecipe() + { + try + { + if (ContentArea.Content is Settings result) + { + // Validate recipe data exists + if (result._recipeTable == null) + { + footerMsg.Text = "Error: No recipe selected"; + return false; + } + + // Validate temperature goals are reasonable + if (result._recipeTable.HeatingGoal <= 0 || result._recipeTable.CoolingGoal <= 0 || result._recipeTable.PouringGoal <= 0) + { + footerMsg.Text = "Error: Invalid temperature goals in recipe"; + return false; + } + + // Validate cooling goal is less than heating goal + if (result._recipeTable.CoolingGoal >= result._recipeTable.HeatingGoal) + { + footerMsg.Text = "Error: Cooling goal must be less than heating goal"; + return false; + } + + footerMsg.Text = "Ready"; + return true; + } + + footerMsg.Text = "Error: Settings not available"; + return false; + } + catch (Exception ex) + { + footerMsg.Text = $"Error initializing recipe: {ex.Message}"; + return false; + } + } + + /// + /// Start monitoring recipe phases and handle goal checking + /// + private async Task StartRecipePhaseMonitoring() + { + try + { + // Start continuous monitoring of temperature goals + await Task.Run(async () => + { + while (startRecipe == 1 && !stopRecipeFlag) + { + await CheckAndHandlePhaseTransitions(); + await Task.Delay(1000); // Check every second + } + }); + } + catch (Exception ex) + { + // Log error silently - don't show in UI since recipe is working + // Console.WriteLine($"Phase monitoring error: {ex.Message}"); + } + } + + /// + /// Check current temperatures and handle phase transitions based on goals + /// + private async Task CheckAndHandlePhaseTransitions() + { + try + { + if (ContentArea.Content is Settings settings) + { + // Check if heating goals are met for both mixer and chocolate + bool mixerHeatingGoalMet = await CheckMixerHeatingGoal(); + bool chocolateHeatingGoalMet = await CheckChocolateHeatingGoal(); + + // If both heating goals are met, start timers + if (mixerHeatingGoalMet && chocolateHeatingGoalMet) + { + await StartHeatingPhaseTimers(); + } + + // Check chocolate temperature for cooling phase transition + await HandleCoolingPhaseTransition(settings); + } + } + catch (Exception ex) + { + footerMsg.Text = $"Error in phase transition: {ex.Message}"; + } + } + + /// + /// Check if mixer heating goal is reached + /// + private async Task CheckMixerHeatingGoal() + { + // Check if tank temperature (mixer) has reached heating goal + // For heating: temperature should be at or above the goal + bool goalMet = comTankTemp >= recipeHeatingGoal; + + if (goalMet && Heating == -1) + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = $"Mixer heating goal reached: {comTankTemp:F1}°C (Target: {recipeHeatingGoal}°C)"; + }); + } + + return goalMet; + } + + /// + /// Check if chocolate heating goal is reached + /// + private async Task CheckChocolateHeatingGoal() + { + // Check if fountain temperature (chocolate) has reached heating goal + // For heating: temperature should be at or above the goal + bool goalMet = comFountainTemp >= recipeHeatingGoal; + + if (goalMet && Heating == -1) + { + + } + + return goalMet; + } + + /// + /// Start heating phase timers when goals are met + /// + private async Task StartHeatingPhaseTimers() + { + if (Heating == -1 && setHeatingTimerOnce == -1) + { + Heating = 1; + sendComHeating = 1; + setHeatingTimerOnce = 1; + heatingSeconds = _machine.HeatingDelay; + + // Start heating timer + if (heatingTimer == null) + { + heatingTimer = new Timer(HeatingTimer, null, 1000, 1000); + } + + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Heating phase started - timers initiated"; + }); + } + } + + /// + /// Handle cooling phase transition based on chocolate temperature + /// + private async Task HandleCoolingPhaseTransition(Settings settings) + { + // Check if chocolate temperature has reached cooling threshold + // For cooling: temperature should be at or below the cooling goal + bool chocolateAtCoolingTemp = comFountainTemp <= recipeCoolingGoal; + + if (chocolateAtCoolingTemp && cooling == -1 && Heating == -1) + { + // Chocolate temperature equals or is below cooling threshold - show cooling delay + await ShowCoolingDelay(settings); + } + else if (!chocolateAtCoolingTemp && cooling == -1 && Heating == -1) + { + // Chocolate temperature not at cooling threshold - initiate cooling phase + await InitiateCoolingPhase(settings); + } + } + + /// + /// Show cooling delay when chocolate temperature equals cooling goal + /// + private async Task ShowCoolingDelay(Settings settings) + { + Dispatcher.UIThread.Post(() => + { + settings.coolingDelayTxt.IsVisible = true; + settings.coolingDelayCounter.IsVisible = true; + settings.coolingDelayCounter.Text = "0"; + footerMsg.Text = $"Cooling delay: Chocolate at target temperature ({comFountainTemp:F1}°C)"; + }); + } + + /// + /// Initiate cooling phase when chocolate temperature is not at cooling goal + /// + private async Task InitiateCoolingPhase(Settings settings) + { + if (setCoolingTimerOnce == -1) + { + cooling = 1; + sendComCooling = 1; + setCoolingTimerOnce = 1; + coolingSeconds = _machine.CoolingDelay; + + // Start cooling timer + if (coolingTimer == null) + { + coolingTimer = new Timer(CoolingTimer, null, 1000, 1000); + } + else + { + // Ensure the timer is running at the correct interval + coolingTimer.Change(1000, 1000); + } + + Dispatcher.UIThread.Post(() => + { + settings.coolingDelayTxt.IsVisible = false; + settings.coolingDelayCounter.IsVisible = false; + footerMsg.Text = $"Cooling phase initiated - Target: {recipeCoolingGoal}°C, Current: {comFountainTemp:F1}°C"; + }); + } + } + + /// + /// Stop recipe execution and clean up resources + /// + private async Task StopRecipeExecution(Button button) + { + startRecipe = 0; + stopRecipeFlag = true; + Heating = -1; + cooling = -1; + pouring = -1; + PumbOn = -1; + pedalMotor = -1; + isCoolingDelayMode = false; // Reset the cooling delay mode flag + isPouringDelayMode = false; // Reset the pouring delay mode flag + tempWarningAccepted = false; // Reset temperature warning acceptance + currentRecipePhase = RecipePhase.None; // Reset recipe phase + lastFooterMessage = ""; // Reset last footer message + isPedalAutoMode = false; // Reset pedal auto mode + + // Stop all timers + await StopAllRecipeTimers(); + + // Reset UI elements + await ResetRecipeUI(button); + + // Reset temperature settings + holdingRegister.setTemp1 = -10000; + holdingRegister.setTemp2 = -10000; + holdingRegister.setTemp3 = -10000; + holdingRegister.setTemp4 = -10000; + holdingRegister.motor = 0; + + await WriteToSerialAsync("RecipeStop"); + footerMsg.Text = "Recipe Stopped"; + } + + /// + /// Stop all recipe-related timers + /// + private async Task StopAllRecipeTimers() + { + // Stop heating timer + if (heatingTimer != null) + { + heatingTimer.Change(Timeout.Infinite, Timeout.Infinite); + heatingSeconds = _machine.HeatingDelay; + heatingTimer = null; + } + + // Stop cooling timer + if (coolingTimer != null) + { + coolingTimer.Change(Timeout.Infinite, Timeout.Infinite); + coolingSeconds = _machine.CoolingDelay; + coolingTimer = null; + } + + // Stop pouring timer + if (pouringTimer != null) + { + pouringTimer.Change(Timeout.Infinite, Timeout.Infinite); + pouringSeconds = _machine.PouringDelay; + pouringTimer = null; + } + + // Stop pedal timers + if (pedalOffTimer != null) + { + pedalOffTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOffSeconds = 0; + } + if (pedalOnTimer != null) + { + pedalOnTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOffSeconds = 0; + } + + // Stop fountain timers + if (fountainPauseTimer != null) + { + fountainPauseTimer.Change(Timeout.Infinite, Timeout.Infinite); + fountainPauseSeconds = 10; + fountainPauseTimer = null; + } + if (fountainTimer != null) + { + fountainTimer.Change(Timeout.Infinite, Timeout.Infinite); + fountainTimer = null; + } + + // Stop mixer timer + if (mixerTimer != null) + { + mixerTimer.Change(Timeout.Infinite, Timeout.Infinite); + mixerTimer = null; + } + } + + /// + /// Reset UI elements when recipe is stopped + /// + private async Task ResetRecipeUI(Button button) + { + startPreHeating = 0; + writingMaxTemp = 0; + isFlashPreHeating = false; + + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings settings) + { + // Turn off motors if they were on + if (isMixerMotorOn) + { + settings.mixerBtn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); + } + if (isFountainMotorOn) + { + settings.fountainBtn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); + } + + // Hide delay indicators + settings.mixerDelayTxt.IsVisible = false; + settings.mixerDelayCounter.IsVisible = false; + settings.fountainDelayTxt.IsVisible = false; + settings.fountainDelayCounter.IsVisible = false; + settings.fountainTargetTxt.IsVisible = false; + settings.fountainTagetTemp.IsVisible = false; + settings.coolingDelayTxt.IsVisible = false; + settings.coolingDelayCounter.IsVisible = false; + settings.pedalDelayTxt.IsVisible = false; + settings.pedalDelayCounter.IsVisible = false; + + // Re-enable buttons + settings.mixerBtn.IsEnabled = true; + settings.fountainBtn.IsEnabled = true; + } + + // Reset recipe start button + button.Content = "START RECIPE"; + PreHeatingBtn.IsEnabled = true; + recipeStartBtn.IsEnabled = true; + recipeStartBtn.Foreground = Avalonia.Media.Brushes.White; + recipeStartBtn.Background = Brush.Parse("#008000"); + }); + } + + public void resetAll() + { + if (heatingTimer != null) + { + heatingTimer.Change(Timeout.Infinite, Timeout.Infinite); + heatingSeconds = _machine.HeatingDelay; + heatingTimer = null; + } + if (coolingTimer != null) + { + coolingTimer.Change(Timeout.Infinite, Timeout.Infinite); + coolingSeconds = _machine.CoolingDelay; + coolingTimer = null; + + } + if (pouringTimer != null) + { + pouringTimer.Change(Timeout.Infinite, Timeout.Infinite); + pouringSeconds = _machine.PouringDelay; + pouringTimer = null; + + } + if (pedalOffTimer != null) + { + pedalOffTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOffSeconds = 0; + } + if (pedalOnTimer != null) + { + pedalOnTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOnSeconds = 0; + } + if (fountainPauseTimer != null) + { + fountainPauseTimer.Change(Timeout.Infinite, Timeout.Infinite); + fountainPauseSeconds = 10; + fountainPauseTimer = null; + } + if (fountainTimer != null) + { + fountainTimer.Change(Timeout.Infinite, Timeout.Infinite); + fountainTimer = null; + } + if (mixerTimer != null) + { + mixerTimer.Change(Timeout.Infinite, Timeout.Infinite); + mixerTimer = null; + } + + + + pedalState = -1; + pedalStateChanged = -1; + recipeHeatingGoal = 0; + recipeCoolingGoal = 0; + recipePouringGoal = 0; + //pre Heating + isFlashPreHeating = false; + startPreHeating = -1; + writingMaxTemp = -1; + // mixer + mixerSeconds = 1; + setMixerTimerOnce = false; + checkMixerTWT_HWTH = false; + isMixerMotorOn = false; + startMixerMotor = -1; + startMixerMotorFlashing = -1; + sendComMixerMotor = -1; + //Fountain Motor + fountainSeconds = 1; + setFountainTimerOnce = false; + checkFountainTMT_PMT = false; + isFountainMotorOn = false; + startFountainMotor = -1; + startFountainMotorFlashing = -1; + sendComFountainMotor = -1; + //MOLD HEATER(off:0,on:1) , VIBRATION(off:0,on:1) , VIB. HEATER(off:0,on:1) + moldHeaterMotor = -1; + vibrationMotor = -1; + vibHeaterMotor = -1; + //Pedal(manual=0,auto=1) + pedalMotor = -1; + //Recipe Start + startRecipe = 0; + sendComTankTemp = -1; + //phase 1 heating + Heating = -1; + sendComHeating = -1; + setHeatingTimerOnce = -1; + heatingSeconds = 0; + //phase 2 cooling + cooling = -1; + sendComCooling = -1; + setCoolingTimerOnce = -1; + coolingSeconds = 0; + //phase 3 pouring + pouring = -1; + sendComPouring = -1; + setPouringTimerOnce = -1; + pouringSeconds = 0; + //start the pumb + PumbOn = -1; + pedalOffSeconds = 0; + pedalOnSeconds = 0; + setPedalTimerOnce = -1; + Dispatcher.UIThread.Post(() => + { + recipeStartBtn.Foreground = Avalonia.Media.Brushes.White; + recipeStartBtn.Background = Brush.Parse("#008000"); + recipeStartBtn.Content = "START RECIPE"; + PreHeatingBtn.IsEnabled = true; + recipeStartBtn.IsEnabled = true; + }); + + + + + } + + + private async void ResetErrors(object? sender, RoutedEventArgs e) + { + holdingRegister.resetError = (ushort)(1 << 0); + await WriteToSerialAsync("ResetErrors"); + + } + private async void OnWarningPopupOverlayPointerPressed(object? sender, RoutedEventArgs e) + { + warningPopupOverlay.IsVisible = false; + + } + private async void OnErrorPopupOverlayPointerPressed(object? sender, RoutedEventArgs e) + { + errorPopupOverlay.IsVisible = false; + + } + + + + public static class MessageBox + { + public static async Task Show(Window owner, string message, string title) + { + var dialog = new Window + { + Title = title, + Width = 300, + Height = 150, + WindowStartupLocation = WindowStartupLocation.CenterOwner, + Topmost = false, + Content = new StackPanel + { + Children = + { + new TextBlock + { + Text = message, + Margin = new Thickness(10), + HorizontalAlignment = HorizontalAlignment.Center + }, + new Button + { + Content = "OK", + Margin = new Thickness(10), + HorizontalAlignment = HorizontalAlignment.Center + } + } + } + }; + + var button = (Button)((StackPanel)dialog.Content).Children[1]; + button.Click += (s, e) => dialog.Close(); + + owner.Topmost = false; + await dialog.ShowDialog(owner); + owner.Topmost = true; + owner.Activate(); + + // Restart keyboard to bring it on top + var (fileName, args) = GetKeyboardCommand(); + if (!string.IsNullOrEmpty(fileName)) + { + try + { + Process.Start(fileName, args); + } + catch + { + // Handle exceptions if needed + } + } + } + + private static (string? fileName, string args) GetKeyboardCommand() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + return ("osk.exe", ""); + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + return ("onboard", ""); // or "florence", "matchbox-keyboard" + return (null, ""); + } + } + + /// + /// Handles automatic fountain control after pouring phase completion based on recipe settings + /// + private async Task HandleAutomaticFountainControlAfterPouring(Settings settings) + { + try + { + // Only proceed if pedal is in Auto mode + if (!settings._recipeTable.Pedal.Value) // Pedal.Value = false means Auto mode + { + // Set flag to indicate automatic fountain control is active + isAutomaticFountainControlActive = true; + + // Check the second control box (RecipeTable.Fountain) to determine fountain state + if (settings._recipeTable.Fountain.Value) + { + // Second box is checked/enabled - Turn ON the fountain + await TurnOnFountainAutomatically(); + } + else + { + // Second box is unchecked/disabled - Keep fountain OFF + await TurnOffFountainAutomatically(); + } + + Debug.WriteLine($"Automatic fountain control activated after pouring phase. Fountain state: {(settings._recipeTable.Fountain.Value ? "ON" : "OFF")}"); + } + } + catch (Exception ex) + { + Debug.WriteLine($"Error in HandleAutomaticFountainControlAfterPouring: {ex.Message}"); + } + } + + /// + /// Automatically turns on the fountain motor + /// + private async Task TurnOnFountainAutomatically() + { + try + { + // Set fountain motor state to ON + isFountainMotorOn = true; + startFountainMotor = 1; + startFountainMotorFlashing = 0; + sendComFountainMotor = 1; + + // Actually send the command to turn ON the fountain motor + var fount = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + if (fount != null && fount.BitNumbers.Count > 0) + { + foreach (var bit in fount.BitNumbers) + { + holdingRegister.motor |= (ushort)(1 << bit); + } + await WriteToSerialAsync("Automatic Fountain On"); + Debug.WriteLine("Fountain motor command sent to hardware - ON"); + } + + // Update UI to show fountain is ON + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + var fountainLable = result.FountainSP.Children[1] as Avalonia.Controls.Label; + var fountainRectangel = result.FountainSP.Children[2] as Avalonia.Controls.Shapes.Rectangle; + fountainLable.Content = "ON"; + fountainLable.Foreground = Brush.Parse("#ff231f20"); + fountainRectangel.Fill = Brush.Parse(ActiveColor); + } + }); + + Debug.WriteLine("Fountain automatically turned ON after pouring phase completion"); + } + catch (Exception ex) + { + Debug.WriteLine($"Error turning on fountain automatically: {ex.Message}"); + } + } + + /// + /// Automatically turns off the fountain motor + /// + private async Task TurnOffFountainAutomatically() + { + try + { + // Set fountain motor state to OFF + isFountainMotorOn = false; + startFountainMotor = 0; + startFountainMotorFlashing = -1; // Prevent flashing in automatic mode + sendComFountainMotor = 0; + + // Actually send the command to turn OFF the fountain motor + var fount = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + if (fount != null && fount.BitNumbers.Count > 0) + { + foreach (var bit in fount.BitNumbers) + { + holdingRegister.motor &= (ushort)~(1 << bit); + } + await WriteToSerialAsync("Automatic Fountain Off"); + Debug.WriteLine("Fountain motor command sent to hardware - OFF"); + } + + // Update UI to show fountain is OFF + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + var fountainLable = result.FountainSP.Children[1] as Avalonia.Controls.Label; + var fontainRectangel = result.FountainSP.Children[2] as Avalonia.Controls.Shapes.Rectangle; + fountainLable.Content = "OFF"; + fountainLable.Foreground = Brush.Parse("#ff231f20"); + fontainRectangel.Fill = Brush.Parse(PassiveColor); + } + }); + + Debug.WriteLine("Fountain automatically turned OFF after pouring phase completion"); + } + catch (Exception ex) + { + Debug.WriteLine($"Error turning off fountain automatically: {ex.Message}"); + } + } + + /// + /// Resets the automatic fountain control flag to allow normal fountain control + /// + public void ResetAutomaticFountainControl() + { + isAutomaticFountainControlActive = false; + Debug.WriteLine("Automatic fountain control flag reset - normal fountain control restored"); + } +} \ No newline at end of file diff --git a/DaireApplication/Views/UserController/Admin.axaml b/DaireApplication/Views/UserController/Admin.axaml new file mode 100644 index 0000000..b5be190 --- /dev/null +++ b/DaireApplication/Views/UserController/Admin.axaml @@ -0,0 +1,1517 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + INs/OUTs MAPPING + + + + + + + IN-1 + + + + + + + + + + + + + + + + + + IN-2 + + + + + + + + + + + + + + + + + IN-3 + + + + + + + + + + + + + + + + + IN-4 + + + + + + + + + + + + + + + + + IN-5 + + + + + + + + + + + + + + + + + IN-6 + + + + + + + + + + + + + + + + + + + LOV-1 + + + + + + + + + + + + + + + + + + LOV-2 + + + + + + + + + + + + + + + + + + LOV-3 + + + + + + + + + + + + + + + + + + LOV-4 + + + + + + + + + + + + + + + + + + LOV-5 + + + + + + + + + + + + + + + + + + LOV-6 + + + + + + + + + + + + + + + + + + + + + + + + INs/OUTs MAPPING + + + + + + + + T-1 + + + + + + + + + + + + + + + + + + + + T-2 + + + + + + + + + + + + + + + + + + + + T-3 + + + + + + + + + + + + + + + + + + + + T-4 + + + + + + + + + + + + + + + + + + + + + + HVO-1 + + + + + + + + + + + + + + + + + + + + HVO-2 + + + + + + + + + + + + + + + + + + + + + HVO-3 + + + + + + + + + + + + + + + + + + + + HVO-4 + + + + + + + + + + + + + + + + + + + + HVO-5 + + + + + + + + + + + + + + + + + + + + HVO-6 + + + + + + + + + + + + + + + + + + + + + + MOT-1 + + + + + + + + + + + + + + + + + MOT-2 + + + + + + + + + + + + + + + + + + + + + + + + INs/OUTs MAPPING + + + + + + + + AN-1 + + + + + + + + + + + + + + + AN-2 + + + + + + + + + + + + + + + + + + + + + VALUES + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/DaireApplication/Views/UserController/AdvanceSettings.axaml.cs b/DaireApplication/Views/UserController/AdvanceSettings.axaml.cs new file mode 100644 index 0000000..0f461e6 --- /dev/null +++ b/DaireApplication/Views/UserController/AdvanceSettings.axaml.cs @@ -0,0 +1,1077 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.LogicalTree; +using Avalonia.Markup.Xaml; +using Avalonia.Media; +using Avalonia.Threading; +using AvaloniaApplication1.DataBase; +using DaireApplication.DataBase; +using DaireApplication.ViewModels; +using DaireApplication.Views; +using DynamicData; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using static DaireApplication.Views.MainWindow; + +namespace DaireApplication; + +public partial class AdvanceSettings : UserControl +{ + public Mapping _mapping; + public ConfigrationTable _configration; + public List _mappingRecordes; + MainWindow _mainWindow; + private Process? _keyboardProcess; + public ErrorSettingsTable _error = new(); + TextBlock targetText = new TextBlock(); + float oldValue = 0; + bool _isDiag; + bool _isSoftware; + public AdvanceSettings(MainWindow mainWindow,bool isDiag=false,bool isSoftware=false) + { + InitializeComponent(); + _mainWindow = mainWindow; + _mapping = new Mapping(); + _mappingRecordes = _mapping.ReadMappings(); + _configration = new(); + _isDiag = isDiag; + _isSoftware = isSoftware; + + setDefaultValues(); + // Remove the old text box event handlers since we're using sliders now + // kp.AddHandler(TextInputEvent, OnTextInputOnlyInteager, RoutingStrategies.Tunnel); + // ki.AddHandler(TextInputEvent, OnTextInputOnlyInteager, RoutingStrategies.Tunnel); + // kd.AddHandler(TextInputEvent, OnTextInputOnlyInteager, RoutingStrategies.Tunnel); + // kl.AddHandler(TextInputEvent, OnTextInputOnlyInteager, RoutingStrategies.Tunnel); + fcThreshold.AddHandler(TextInputEvent, OnTextInput, RoutingStrategies.Tunnel); + heatConRange.AddHandler(TextInputEvent, OnTextInput, RoutingStrategies.Tunnel); + // Remove the old border event handlers since we're using sliders now + // kpBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true); + // kiBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true); + // kdBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true); + // klBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true); + fcThresholdBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true); + heatConRangeBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true); + AttachHandlers(_mainWindow.UserName, CloseApplication); + + setDefaultSettings(); + + } + public AdvanceSettings() + { + InitializeComponent(); + } + public void AttachHandlers(Button button, System.EventHandler func) + { + if (button != null) + { + button.Holding += func; + + button.PointerPressed += (sender, e) => + { + // Simulate a long press on any pointer (mouse or touch) + var point = e.GetPosition(button); + func(sender, new HoldingRoutedEventArgs(HoldingState.Started, point, e.Pointer.Type)); + }; + + button.PointerReleased += (sender, e) => + { + // End simulated long press + var point = e.GetPosition(button); + func(sender, new HoldingRoutedEventArgs(HoldingState.Completed, point, e.Pointer.Type)); + }; + } + } + public static void CloseApplication(object? sender, RoutedEventArgs e) + { + var lifetime = Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime; + lifetime?.Shutdown(); // This should correctly shut down the application + } + private void HVOChanged(object? sender, RoutedEventArgs e) + { + if (sender is ComboBox comboBox) + { + if (comboBox.SelectedItem is ComboBoxItem selectedItem) + { + // Get the displayed content + + //HVO + var result= _mappingRecordes.FindAll(x => x.Address == "1" && x.IsRead==false).Find(c=>c.Name==selectedItem.Content.ToString()); + if (result!=null) + { + if (!result.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))) + { + var oldRecord = _mappingRecordes.Find(x => x.Address == "1" && x.IsRead == false && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))); + if (oldRecord!=null) + { + _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString())); + + } + result.BitNumbers.Add(int.Parse(comboBox.Tag.ToString())); + _mapping.UpdateMapping(result); + setDefaultValues(); + } + + } + else + { + var oldRecord = _mappingRecordes.Find(x => x.Address == "1" && x.IsRead == false && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))); + if (oldRecord != null) + { + _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString())); + + } + } + + + _mappingRecordes = _mapping.ReadMappings(); + _mainWindow._mapping = _mappingRecordes; + var configrations = _configration.ReadConfigrations(); + var compressor = _mappingRecordes.Find(x => x.Name == "Compressor"); + var water = _mappingRecordes.Find(x => x.Name == "Water"); + if (compressor != null && water != null) + { + if (compressor.BitNumbers.Count > 0 ) + { + configrations[2].FC_out = compressor.BitNumbers.Concat(water.BitNumbers).ToList(); + configrations[3].FC_out = compressor.BitNumbers.Concat(water.BitNumbers).ToList(); + + } + else + { + configrations[2].FC_out = [-1]; + configrations[3].FC_out = [-1]; + + } + if (water.BitNumbers.Count > 0) + { + configrations[2].SC_out = water.BitNumbers; + configrations[3].SC_out = water.BitNumbers; + } + else + { + configrations[2].SC_out = [-1]; + configrations[3].SC_out = [-1]; + } + _configration.UpdateConfigration(configrations[2]); + _configration.UpdateConfigration(configrations[3]); + + } + foreach (var item in configrations) + { + var namedMap = _mappingRecordes.Find(x => x.Name == item.name); + if (namedMap!=null) + { + if (namedMap.BitNumbers.Count>0) + { + item.H_out = namedMap.BitNumbers; + if (namedMap.Name!= "HELIX Heater") + { + item.FC_out = [-1]; + item.SC_out = [-1]; + } + _configration.UpdateConfigration(item); + } + else + { + item.H_out =[-1]; + if (namedMap.Name != "HELIX Heater") + { + item.FC_out = [-1]; + item.SC_out = [-1]; + } + _configration.UpdateConfigration(item); + } + } + else + { + + } + } + configrations[3].H_out = configrations[2].H_out; + _configration.UpdateConfigration(configrations[3]); + + + _mainWindow.sendConfig = true; + } + + } + } + + private void TChanged(object? sender, RoutedEventArgs e) + { + if (sender is ComboBox comboBox) + { + if (comboBox.SelectedItem is ComboBoxItem selectedItem) + { + // Get the displayed content + + //HVO + var result = _mappingRecordes.Find(c => c.Name.ToLower() == selectedItem.Tag.ToString().ToLower()); + if (result != null) + { + if (!result.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))) + { + var oldRecord = _mappingRecordes.Find(x => x.Name.EndsWith("Temp") && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))); + if (oldRecord != null) + { + _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString())); + + } + result.BitNumbers.Add(int.Parse(comboBox.Tag.ToString())); + _mapping.UpdateMapping(result); + setDefaultValues(); + } + + } + else + { + var oldRecord = _mappingRecordes.Find(x => x.Name.EndsWith("Temp") && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))); + if (oldRecord != null) + { + _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString())); + setDefaultValues(); + + + } + } + + + _mappingRecordes = _mapping.ReadMappings(); + _mainWindow._mapping = _mappingRecordes; + + } + + } + } + private void LOVChanged(object? sender, RoutedEventArgs e) + { + if (sender is ComboBox comboBox) + { + if (comboBox.SelectedItem is ComboBoxItem selectedItem) + { + var result = _mappingRecordes.FindAll(x => x.Address == "2").Find(c => c.Name.ToLower() == selectedItem.Tag.ToString().ToLower()); + if (result != null) + { + if (!result.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))) + { + var oldRecord = _mappingRecordes.Find(x => x.Address == "2" && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))); + if (oldRecord != null) + { + _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString())); + + } + result.BitNumbers.Add(int.Parse(comboBox.Tag.ToString())); + _mapping.UpdateMapping(result); + setDefaultValues(); + } + + } + else + { + var oldRecord = _mappingRecordes.Find(x => x.Address == "2" && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))); + if (oldRecord != null) + { + _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString())); + setDefaultValues(); + + + } + } + _mappingRecordes = _mapping.ReadMappings(); + _mainWindow._mapping = _mappingRecordes; + + } + + } + } + private void InChanged(object? sender, RoutedEventArgs e) + { + if (sender is ComboBox comboBox) + { + if (comboBox.SelectedItem is ComboBoxItem selectedItem) + { + // Get the displayed content + + //HVO + var result = _mappingRecordes.FindAll(x => x.Address == "1" &&x.IsRead==true).Find(c => c.Name.ToLower() == selectedItem.Content.ToString().ToLower()); + if (result != null) + { + if (!result.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))) + { + var oldRecord = _mappingRecordes.Find(x => x.Address == "1" && x.IsRead == true && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))); + if (oldRecord != null) + { + _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString())); + + } + result.BitNumbers.Add(int.Parse(comboBox.Tag.ToString())); + _mapping.UpdateMapping(result); + setDefaultValues(); + } + + } + else + { + var oldRecord = _mappingRecordes.Find(x => x.Address == "1" && x.IsRead == true && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))); + if (oldRecord != null) + { + _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString())); + setDefaultValues(); + + + } + } + + + _mappingRecordes = _mapping.ReadMappings(); + _mainWindow._mapping = _mappingRecordes; + + } + + } + } + private void MotChanged(object? sender, RoutedEventArgs e) + { + if (sender is ComboBox comboBox) + { + if (comboBox.SelectedItem is ComboBoxItem selectedItem) + { + var result = _mappingRecordes.FindAll(x => x.Address == "3").Find(c => c.Name.ToLower() == selectedItem.Tag.ToString().ToLower()); + if (result != null) + { + if (!result.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))) + { + var oldRecord = _mappingRecordes.Find(x => x.Address == "3" && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))); + if (oldRecord != null) + { + _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString())); + + } + result.BitNumbers.Add(int.Parse(comboBox.Tag.ToString())); + _mapping.UpdateMapping(result); + setDefaultValues(); + } + + } + else + { + var oldRecord = _mappingRecordes.Find(x => x.Address == "3" && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))); + if (oldRecord != null) + { + _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString())); + setDefaultValues(); + + + } + } + + + _mappingRecordes = _mapping.ReadMappings(); + _mainWindow._mapping = _mappingRecordes; + + } + + } + } + + + + private (string? fileName, string args) GetKeyboardCommand() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + return ("osk.exe", ""); + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + return ("onboard", ""); // or "florence", "matchbox-keyboard" + return (null, ""); + } + private async void OnTextBoxFocused(object? sender, PointerPressedEventArgs e) + { + if (_keyboardProcess is { HasExited: false }) + return; + + var (fileName, args) = GetKeyboardCommand(); + if (fileName is null) + return; + + _keyboardProcess = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = fileName, + Arguments = args, + UseShellExecute = true, + WorkingDirectory = "/usr/bin" + }, + EnableRaisingEvents = true + }; + + + try + { + _keyboardProcess.Start(); + + + + Dispatcher.UIThread.Post(() => + { + if (sender is Border border) + { + var textbox = border.Child as TextBox; + textbox.SelectionStart = 0; + textbox.SelectionEnd = textbox.Text?.Length ?? 0; + } + }); + + } + catch + { + // fail silently if keyboard not found + } + } + + + private async void OnIgnoreInnerPidPopupOverlayPointerPressed(object? sender, RoutedEventArgs e) + { + innerPidPopupOverlay.IsVisible = false; + pidPopupOverlay.IsVisible = true; + + + + } + private async void OnIgnorePidPopupOverlayPointerPressed(object? sender, RoutedEventArgs e) + { + pidPopupOverlay.IsVisible = false; + } + private async void YesBtnClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + var configration = _configration.ReadConfigrationById(header.Tag.ToString()); + if (configration!=null) + { + // Read values from sliders instead of text boxes + configration.kp = (int)kpSlider.Value; + configration.ki = (int)kiSlider.Value; + configration.kd = (int)kdSlider.Value; + configration.kl = (int)klSlider.Value; + + if (string.IsNullOrEmpty(fcThreshold.Text)) + { + configration.FC_Threshold = 0; + } + else + { + configration.FC_Threshold = float.Parse(fcThreshold.Text); + + } + if (string.IsNullOrEmpty(heatConRange.Text)) + { + configration.HeatConRange = 1.0F; + } + else + { + if (float.TryParse(heatConRange.Text, out float value)) + { + if (value<1.0) + { + configration.HeatConRange = 1.0F; + } + else + { + configration.HeatConRange = float.Parse(heatConRange.Text); + } + } + else + { + configration.HeatConRange = 1.0F; + } + + } + + _configration.UpdateConfigration(configration); + _mainWindow.sendConfig = true; + CloseKeyboard(); + + innerPidPopupOverlay.IsVisible = false; + pidPopupOverlay.IsVisible = true; + + } + } + + + + } + + private async void showPidPopUp(object? sender, RoutedEventArgs e) + { + pidPopupOverlay.IsVisible = true; + + } + private async void showInnerPid(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + var configratipn = _configration.ReadConfigrationById(button.Tag.ToString()); + pidPopupOverlay.IsVisible = false; + header.Text = button.Content.ToString(); + header.Tag = button.Tag; + + // Set slider values instead of text box values + kpSlider.Value = configratipn.kp; + kiSlider.Value = configratipn.ki; + kdSlider.Value = configratipn.kd; + klSlider.Value = configratipn.kl; + + // Update the display values + kpSliderValue.Text = configratipn.kp.ToString(); + kiSliderValue.Text = configratipn.ki.ToString(); + kdSliderValue.Text = configratipn.kd.ToString(); + klSliderValue.Text = configratipn.kl.ToString(); + + fcThreshold.Text = configratipn.FC_Threshold.ToString("0.0"); + heatConRange.Text = configratipn.HeatConRange.ToString("0.0"); + innerPidPopupOverlay.IsVisible = true; + + } + + } + + // KP Slider and Button Event Handlers + private void KpSliderValueChanged(object? sender, RoutedEventArgs e) + { + if (kpSliderValue != null && sender is Slider slider) + { + kpSliderValue.Text = ((int)slider.Value).ToString(); + } + } + + private void KpMinusClick(object? sender, RoutedEventArgs e) + { + if (kpSlider.Value > kpSlider.Minimum) + { + kpSlider.Value--; + } + } + + private void KpPlusClick(object? sender, RoutedEventArgs e) + { + if (kpSlider.Value < kpSlider.Maximum) + { + kpSlider.Value++; + } + } + + // KI Slider and Button Event Handlers + private void KiSliderValueChanged(object? sender, RoutedEventArgs e) + { + if (kiSliderValue != null && sender is Slider slider) + { + kiSliderValue.Text = ((int)slider.Value).ToString(); + } + } + + private void KiMinusClick(object? sender, RoutedEventArgs e) + { + if (kiSlider.Value > kiSlider.Minimum) + { + kiSlider.Value--; + } + } + + private void KiPlusClick(object? sender, RoutedEventArgs e) + { + if (kiSlider.Value < kiSlider.Maximum) + { + kiSlider.Value++; + } + } + + // KD Slider and Button Event Handlers + private void KdSliderValueChanged(object? sender, RoutedEventArgs e) + { + if (kdSliderValue != null && sender is Slider slider) + { + kdSliderValue.Text = ((int)slider.Value).ToString(); + } + } + + private void KdMinusClick(object? sender, RoutedEventArgs e) + { + if (kdSlider.Value > kdSlider.Minimum) + { + kdSlider.Value--; + } + } + + private void KdPlusClick(object? sender, RoutedEventArgs e) + { + if (kdSlider.Value < kdSlider.Maximum) + { + kdSlider.Value++; + } + } + + // KL Slider and Button Event Handlers + private void KlSliderValueChanged(object? sender, RoutedEventArgs e) + { + if (klSliderValue != null && sender is Slider slider) + { + klSliderValue.Text = ((int)slider.Value).ToString(); + } + } + + private void KlMinusClick(object? sender, RoutedEventArgs e) + { + if (klSlider.Value > klSlider.Minimum) + { + klSlider.Value--; + } + } + + private void KlPlusClick(object? sender, RoutedEventArgs e) + { + if (klSlider.Value < klSlider.Maximum) + { + klSlider.Value++; + } + } + + private void OnTextInput(object? sender, TextInputEventArgs e) + { + if (sender is TextBox textBox) + { + string newText = textBox.Text + e.Text; + if (!Regex.IsMatch(newText, @"^\d*\.?\d*$")) + { + e.Handled = true; + } + } + } + private void OnTextInputOnlyInteager(object? sender, TextInputEventArgs e) + { + if (sender is TextBox textBox) + { + string newText = textBox.Text + e.Text; + if (!Regex.IsMatch(newText, @"^\d*$")) + { + e.Handled = true; + } + } + } + + private async void gridButtonClick(object? sender, RoutedEventArgs e) + { + var error = _error.ReadErrorSettings()[0]; + if (gridValue.Text == "50Hz") + { + error.gridFreq = 60; + _error.UpdateError(error); + setDefaultValues(); + + } + else + { + error.gridFreq = 50; + _error.UpdateError(error); + setDefaultValues(); + } + + } + private async void supplyButtonClick(object? sender, RoutedEventArgs e) + { + var error = _error.ReadErrorSettings()[0]; + int bit = 11; + + if (phasesNumberValue.Text == "3-Phases") + { + error.phaseNumber = 1; + _error.UpdateError(error); + setDefaultValues(); + _mainWindow.holdingRegister.resetError |= (ushort)(1 << bit); + } + else + { + error.phaseNumber = 3; + _error.UpdateError(error); + _mainWindow.holdingRegister.resetError &= (ushort)~(1 << bit); + + + setDefaultValues(); + + } + await _mainWindow.WriteToSerialAsync("supplyButtonClick"); + } + private async void voltageButtonClick(object? sender, RoutedEventArgs e) + { + var error = _error.ReadErrorSettings()[0]; + int bit = 12; + + if (voltageNumberValue.Text.Contains("220")) + { + error.phaseVoltage = 110; + _error.UpdateError(error); + setDefaultValues(); + _mainWindow.holdingRegister.resetError |= (ushort)(1 << bit); + } + else + { + error.phaseVoltage =220; + _error.UpdateError(error); + _mainWindow.holdingRegister.resetError &= (ushort)~(1 << bit); + + + setDefaultValues(); + + } + await _mainWindow.WriteToSerialAsync("voltageButtonClick"); + } + + private async void extPowerClick(object? sender, RoutedEventArgs e) + { + var error = _error.ReadErrorSettings()[0]; + if (extPowerValue.Text == "Yes") + { + error.extPower = false; + _error.UpdateError(error); + setDefaultValues(); + + + } + else + { + error.extPower = true; + _error.UpdateError(error); + setDefaultValues(); + + } + } + private void setDefaultValues() + { + _mappingRecordes = _mapping.ReadMappings(); + var allHVOComboBox= this.GetLogicalDescendants() + .OfType() + .Where(cb => cb.Classes.Contains("HVO")) + .ToList(); + //HVO + for (int i = 0; i < allHVOComboBox.Count; i++) + { + var result = _mappingRecordes.FindAll(x => x.Address == "1" && x.IsRead==false ).Find(c => c.BitNumbers.Contains(int.Parse(allHVOComboBox[i].Tag.ToString()))); + if (result != null) + { + allHVOComboBox[i].SelectedIndex = result.Id - 11; + } + else + { + allHVOComboBox[i].SelectedIndex = 6; + + } + } + // IN + var allINComboBox = this.GetLogicalDescendants() + .OfType() + .Where(cb => cb.Classes.Contains("in")) + .ToList(); + for (int i = 0; i < allINComboBox.Count; i++) + { + var result = _mappingRecordes.FindAll(x => x.Address == "1"&&x.IsRead==true).Find(c => c.BitNumbers.Contains(int.Parse(allINComboBox[i].Tag.ToString()))); + if (result != null) + { + allINComboBox[i].SelectedIndex = result.Id - 1; + } + else + { + allINComboBox[i].SelectedIndex = 3; + + } + } + + //LOV + var allLOVComboBox = this.GetLogicalDescendants() + .OfType() + .Where(cb => cb.Classes.Contains("lov")) + .ToList(); + for (int i = 0; i < allLOVComboBox.Count; i++) + { + var result = _mappingRecordes.FindAll(x => x.Address == "2" && x.IsRead == false).Find(c => c.BitNumbers.Contains(int.Parse(allLOVComboBox[i].Tag.ToString()))); + if (result != null) + { + allLOVComboBox[i].SelectedIndex = result.Id - 8; + } + else + { + allLOVComboBox[i].SelectedIndex = 3; + + } + } + // T + + var allTComboBox = this.GetLogicalDescendants() + .OfType() + .Where(cb => cb.Classes.Contains("T")) + .ToList(); + for (int i = 0; i < allTComboBox.Count; i++) + { + var result = _mappingRecordes.FindAll(x => x.Name.EndsWith("Temp")).Find(c => c.BitNumbers.Contains(int.Parse(allTComboBox[i].Tag.ToString()))); + + if (result != null) + { + allTComboBox[i].SelectedIndex = result.Id - 4; + } + else + { + allTComboBox[i].SelectedIndex = 5; + + } + } + // MOT + var allMotComboBox = this.GetLogicalDescendants() + .OfType() + .Where(cb => cb.Classes.Contains("mot")) + .ToList(); + for (int i = 0; i < allMotComboBox.Count; i++) + { + var result = _mappingRecordes.FindAll(x => x.Address == "3" && x.IsRead==false).Find(c => c.BitNumbers.Contains(int.Parse(allMotComboBox[i].Tag.ToString()))); + if (result != null) + { + allMotComboBox[i].SelectedIndex = result.Id - 17; + } + else + { + allMotComboBox[i].SelectedIndex = 2; + + } + } + var error = _error.ReadErrorSettings()[0]; + + phasesNumberValue.Text = $"{error.phaseNumber}-Phases"; + voltageNumberValue.Text = $"{error.phaseVoltage} V"; + gridValue.Text = $"{error.gridFreq}Hz"; + extPowerValue.Text = error.extPower ? "Yes" : "No"; + var config = _configration.ReadConfigrations()[0]; + i_neutValue.Text = config.i_neut.ToString("0.0"); + i_mot1Value.Text = config.i_mot1.ToString("0.0"); + i_mot2Value.Text = config.i_mot2.ToString("0.0"); + + + + } + private void OnPopupOverlayPointerPressed(object sender, PointerPressedEventArgs e) + { + targetText.Text = oldValue.ToString("0.0"); + keyBoardPopup.IsVisible = false; + } + private void OnKeyClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + if (button.Content == ".") + { + if (Char.IsDigit(targetText.Text[0]) && !targetText.Text.Contains(button.Content.ToString())) + { + targetText.Text += button.Content; + + } + } + else + { + targetText.Text += button.Content; + if (float.Parse(targetText.Text) > 20.0) + { + targetText.Text = "20.0"; + } + } + + } + + } + private void OnBackClick(object? sender, RoutedEventArgs e) + { + if (!string.IsNullOrEmpty(targetText.Text)) + { + // Remove the last character from the text box + targetText.Text = targetText.Text.Remove(targetText.Text.Length - 1, 1); + //number = number.Remove(number.Length - 1); + } + + } + private void EnterClick(object? sender, RoutedEventArgs e) + { + var config = _configration.ReadConfigrations()[0]; + if (targetText.Name== "i_mot2Value") + { + config.i_mot2 = float.Parse(targetText.Text); + } + else if (targetText.Name == "i_mot1Value") + { + config.i_mot1 = float.Parse(targetText.Text); + } + else + { + config.i_neut = float.Parse(targetText.Text); + } + _configration.UpdateConfigration(config); + setDefaultValues(); + _mainWindow.sendConfig = true; + keyBoardPopup.IsVisible = false; + + + } + private void ShowNumberKeyBoard(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + if (button.Name=="i_mot2") + { + targetText = i_mot2Value; + } + else if (button.Name == "i_mot1") + { + targetText = i_mot1Value; + + } + else if (button.Name== "i_neut") + { + targetText = i_neutValue; + + } + oldValue = float.Parse(targetText.Text); + targetText.Text = ""; + keyBoardPopup.IsVisible = true; + + } + + } + + private void OnKeyUp(object? sender, KeyEventArgs e) + { + if (sender is TextBox textBox) + { + if (textBox != null && float.TryParse(textBox.Text, out float value)) + { + if (textBox.Name== "heatConRange") + { + if (value > 25.0) + { + textBox.Text = "25.0"; + } + + } + else + { + if (value > 100) + { + textBox.Text = "100"; + } + } + // Check if the value exceeds 100 and reset to 100 if necessary. + + } + } + + } + + private void InnerPopupPointerPressed(object? sender, PointerPressedEventArgs e) + { + e.Handled = true; + } + private void CloseKeyboard() + { + try + { + if (_keyboardProcess != null) + { + // Kill the keyboard process + _keyboardProcess.Kill(); + _keyboardProcess.Dispose(); + _keyboardProcess = null; + + // Force kill any remaining keyboard processes + var processKill = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = "killall", + Arguments = "-9 onboard matchbox-keyboard florence", // Common Linux on-screen keyboards + UseShellExecute = false, + CreateNoWindow = true + } + }; + processKill.Start(); + processKill.WaitForExit(1000); + processKill.Dispose(); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error closing keyboard: {ex.Message}"); + } + } + private void setDefaultSettings() + { + _mainWindow.minimizeBtn.IsVisible = false; + var stackPanel = _mainWindow.HomeTrack.Parent as StackPanel; + + + //Set Track Up + _mainWindow.HomeTrack.IsVisible = true; + _mainWindow.HomePolygon.Stroke = Avalonia.Media.Brushes.Black; + _mainWindow.RecipeSelTrack.IsVisible = false; + _mainWindow.RunInterfaceTrack.IsVisible = false; + _mainWindow.RecipePanelTrack.IsVisible = false; + _mainWindow.RecipeEditTrack.IsVisible = false; + if (_isDiag||_isSoftware) + { + if (_isDiag) + { + _mainWindow.DiagnosticsTrack.IsVisible = true; + _mainWindow.DiagnosticsPolygon.Stroke = Avalonia.Media.Brushes.Black; + + } + else if (_isSoftware) + { + _mainWindow.SoftwareTrack.IsVisible = true; + _mainWindow.SoftwarePolygon.Stroke = Avalonia.Media.Brushes.Black; + } + _mainWindow.SettingTrack.IsVisible = false; + } + else + { + _mainWindow.DiagnosticsTrack.IsVisible = false; + _mainWindow.SoftwareTrack.IsVisible = false; + + _mainWindow.SettingTrack.IsVisible = true; + _mainWindow.SettingPolygon.Stroke = Avalonia.Media.Brushes.Black; + } + // Remove the button from its current position + stackPanel.Children.Remove(_mainWindow.AdvanceSettingsTrack); + + // Add it back at the end of the StackPanel + stackPanel.Children.Add(_mainWindow.AdvanceSettingsTrack); + _mainWindow.AdvanceSettingsTrack.IsVisible = true; + _mainWindow.AdvanceSettingsPolygon.Stroke = Brush.Parse("#A4275D"); + + + + _mainWindow.TitleBtn.IsVisible = true; + _mainWindow.Title.Text = "DR-62664A"; + //Set Footer + _mainWindow.footerMsg.IsVisible = true; + _mainWindow.footerMsg.Text = "Map Inputs And Outputs, And Set The Board Internal Values"; + _mainWindow.footerMsg.Foreground = Brush.Parse("#A4275D"); + _mainWindow.footer.Background = Brush.Parse("#f2f2f2"); + _mainWindow.footerDate.Text = DateTime.Now.ToString("dd/MM/yyyy"); + _mainWindow.footerTime.Text = DateTime.Now.ToString("hh:mm tt"); + _mainWindow.footerDateContainer.IsVisible = true; + _mainWindow.footerStartBtn.IsVisible = false; + _mainWindow.adminBtns.IsVisible = false; + } +} \ No newline at end of file diff --git a/DaireApplication/Views/UserController/Diagnostics.axaml b/DaireApplication/Views/UserController/Diagnostics.axaml new file mode 100644 index 0000000..cbf542e --- /dev/null +++ b/DaireApplication/Views/UserController/Diagnostics.axaml @@ -0,0 +1,2393 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + T-1 = + +0.0 + °C + + + + + + + + + + + + + T-2 = + +0.0 + °C + + + + + + + + + + + + + T-3 = + +0.0 + °C + + + + + + + + + + + + + T-4 = + +0.0 + °C + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + T-Board + + 0 + °C + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + T-Cooler + + 0 + °C + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Temps Control + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + CALIP. Not Done + + + + + + + + + + + + + + + + + + + + + + + + + + + + Temp Max: + + + + + + + + + + + Temp Min: + + + + + + + + + + + + + Currents + Calibration: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/DaireApplication/Views/UserController/Diagnostics.axaml.cs b/DaireApplication/Views/UserController/Diagnostics.axaml.cs new file mode 100644 index 0000000..2d1cf25 --- /dev/null +++ b/DaireApplication/Views/UserController/Diagnostics.axaml.cs @@ -0,0 +1,1037 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Controls.Shapes; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.LogicalTree; +using Avalonia.Markup.Xaml; +using Avalonia.Media; +using Avalonia.Threading; +using AvaloniaApplication1.DataBase; +using DaireApplication.DataBase; +using DaireApplication.ViewModels; +using DaireApplication.Views; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.Tracing; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text.RegularExpressions; +using static System.Runtime.InteropServices.JavaScript.JSType; + +namespace DaireApplication; + +public partial class Diagnostics : UserControl +{ + private MainWindow? _mainWindow; + private ErrorSettingsTable _error=new(); + public ConfigrationTable _configration; + private Process? _keyboardProcess; + + + public string GrayColor="#666666"; + public string RedColor= "#FF0000"; + public string GreenColor= "#71C837"; + public string PinkColor= "#AF196F"; + public string OrangeColor= "#FF6600"; + public List flagRectangles { get; set; } + public List InputesElements { get; set; } + public List MotoreState { get; set; } + public List hvoOutPuts { get; set; } + public List lvoOutPuts { get; set; } + TextBlock targetText = new TextBlock(); + Button targetButton = new Button(); + float oldValue = 0; + bool isNegative = false; + bool _isAdvSettings; + bool _isFromManualControl; + public MachineTable _machine { get; set; } + + + public Diagnostics() + { + + InitializeComponent(); + + } + public Diagnostics(MainWindow mainWindow,bool isAdvSettings=false, bool isFromManualControl=false) + { + _mainWindow = mainWindow; + _machine = new MachineTable(); + _configration = new(); + _isAdvSettings = isAdvSettings; + _isFromManualControl = isFromManualControl; + + InitializeComponent(); + setDefaultSettings(); + getUiElementes(); + fcThreshold.AddHandler(TextInputEvent, OnTextInput, RoutingStrategies.Tunnel); + heatConRange.AddHandler(TextInputEvent, OnTextInput, RoutingStrategies.Tunnel); + fcThresholdBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true); + heatConRangeBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true); + + AttachHandlers(_mainWindow.logoBtn, AdvanceSettingsView); + } + public void AttachHandlers(Button button, System.EventHandler func) + { + if (button != null) + { + button.Holding += func; + + button.PointerPressed += (sender, e) => + { + // Simulate a long press on any pointer (mouse or touch) + var point = e.GetPosition(button); + func(sender, new HoldingRoutedEventArgs(HoldingState.Started, point, e.Pointer.Type)); + }; + + button.PointerReleased += (sender, e) => + { + // End simulated long press + var point = e.GetPosition(button); + func(sender, new HoldingRoutedEventArgs(HoldingState.Completed, point, e.Pointer.Type)); + }; + } + } + public void AdvanceSettingsView(object? sender, RoutedEventArgs e) + { + if (_mainWindow.ContentArea.Content == this) + { + _mainWindow.ContentArea.Content = new AdvanceSettings(_mainWindow,true,false); + } + + } + public void ResendConfig(object? sender, RoutedEventArgs e) + { + if (!_mainWindow.sendConfig) + { + _mainWindow.reSendHolding = true; + } + } + public static void CloseApplication(object? sender, RoutedEventArgs e) + { + var lifetime = Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime; + lifetime?.Shutdown(); // This should correctly shut down the application + } + private async void motorClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + var grid= button.Content as Grid; + var stackPanel = grid.Children[0] as StackPanel; + var text = stackPanel.Children[1] as TextBlock; + if (text.Text=="ON") + { + _mainWindow.holdingRegister.motor = (ushort)(_mainWindow.holdingRegister.motor & ~(1 << int.Parse(grid.Tag.ToString()))); + + } + else if (text.Text == "OFF") + { + _mainWindow.holdingRegister.motor = (ushort)(_mainWindow.holdingRegister.motor | (1 << int.Parse(grid.Tag.ToString()))); + } + await _mainWindow.WriteToSerialAsync("motorClick"); + + } + + } + private async void hvoClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + var grid= button.Content as Grid; + var text = grid.Children[1] as TextBlock; + if (text.Text=="ON") + { + _mainWindow.holdingRegister.hvOut = (ushort)(_mainWindow.holdingRegister.hvOut & ~(1 << int.Parse(grid.Tag.ToString()))); + + } + else if (text.Text == "OFF") + { + _mainWindow.holdingRegister.hvOut = (ushort)(_mainWindow.holdingRegister.hvOut | (1 << int.Parse(grid.Tag.ToString()))); + + } + await _mainWindow.WriteToSerialAsync("hvoClick"); + + } + + } + private async void lvoClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + var grid= button.Content as Grid; + var stack= button.Content as StackPanel; + if (grid!=null) + { + var text = grid.Children[1] as TextBlock; + if (text.Text == "ON") + { + _mainWindow.holdingRegister.lvOut = (ushort)(_mainWindow.holdingRegister.lvOut & ~(1 << int.Parse(grid.Tag.ToString()))); + + } + else if (text.Text == "OFF") + { + _mainWindow.holdingRegister.lvOut = (ushort)(_mainWindow.holdingRegister.lvOut | (1 << int.Parse(grid.Tag.ToString()))); + } + + } + else if(stack != null) + { + var text = stack.Children[1] as TextBlock; + if (text.Text == "ON") + { + _mainWindow.holdingRegister.lvOut = (ushort)(_mainWindow.holdingRegister.lvOut & ~(1 << int.Parse(stack.Tag.ToString()))); + + } + else if (text.Text == "OFF") + { + _mainWindow.holdingRegister.lvOut = (ushort)(_mainWindow.holdingRegister.lvOut | (1 << int.Parse(stack.Tag.ToString()))); + } + } + await _mainWindow.WriteToSerialAsync("lvoClick"); + + + } + + } + + private async void resetErrorClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + _mainWindow.holdingRegister.resetError = (ushort)(_mainWindow.holdingRegister.resetError | (1 << 0)); + await _mainWindow.WriteToSerialAsync("resetErrorClick"); + } + } + + private async void ChangeTempMode(object sender, RoutedEventArgs e) + { + float number =0; + + if (sender is Border border) + { + if (border.Tag.ToString()=="t1") + { + number = float.Parse(t1Text.Text); + } + else if(border.Tag.ToString() == "t2") + { + number = float.Parse(t2Text.Text); + } + else if (border.Tag.ToString() == "t3") + { + number = float.Parse(t3Text.Text); + } + else if (border.Tag.ToString() == "t4") + { + number = float.Parse(t4Text.Text); + } + var parent = border.Parent as StackPanel; + var brother = parent.Children[1] as Border; + + List allTexts= new (); + if (brother.Tag?.ToString() == "t1") + { + allTexts.Add(t1Container.Children[0] as TextBlock); + allTexts.Add(t1Container.Children[1] as TextBlock); + allTexts.Add(t1Container.Children[2] as TextBlock); + + } + else if (brother.Tag?.ToString() == "t2") + { + allTexts.Add(t2Container.Children[0] as TextBlock); + allTexts.Add(t2Container.Children[1] as TextBlock); + allTexts.Add(t2Container.Children[2] as TextBlock); + } + else if (brother.Tag?.ToString() == "t3") + { + allTexts.Add(t3Container.Children[0] as TextBlock); + allTexts.Add(t3Container.Children[1] as TextBlock); + allTexts.Add(t3Container.Children[2] as TextBlock); + } + else if (brother.Tag?.ToString() == "t4") + { + allTexts.Add(t4Container.Children[0] as TextBlock); + allTexts.Add(t4Container.Children[1] as TextBlock); + allTexts.Add(t4Container.Children[2] as TextBlock); + } + + var button=border.Child as Button; + if (button.Content.ToString()=="M") + { + allTexts[0].Foreground = Brush.Parse("#231f20"); // black + allTexts[1].Foreground = Brush.Parse("#af196f"); // pink + allTexts[2].Foreground = Brush.Parse("#231f20"); // black + button.Foreground = Brush.Parse("#af196f"); + button.Content = "A"; + if (button.Tag.ToString() == "t1") + { + _mainWindow.holdingRegister.setTemp1 = (int)(number * 10); + + } + else if (button.Tag.ToString() == "t2") + { + _mainWindow.holdingRegister.setTemp2 = (int)(number * 10); + + + } + else if (button.Tag.ToString() == "t3") + { + _mainWindow.holdingRegister.setTemp3 = (int)(number * 10); + + + } + else if (button.Tag.ToString() == "t4") + { + _mainWindow.holdingRegister.setTemp4 = (int)(number * 10); + + + } + await _mainWindow.WriteToSerialAsync("DiagnosticsTemp"); + + } + else + { + foreach (var item in allTexts) + { + item.Foreground = Brush.Parse("#808080"); //gray + } + + button.Foreground = Brush.Parse("#4d4d4d"); + button.Content = "M"; + if (button.Tag.ToString()=="t1") + { + _mainWindow.holdingRegister.setTemp1 = -10000; + + } + else if (button.Tag.ToString() == "t2") + { + _mainWindow.holdingRegister.setTemp2 = -10000; + + } + else if (button.Tag.ToString() == "t3") + { + _mainWindow.holdingRegister.setTemp3 = -10000; + + } + else if (button.Tag.ToString() == "t4") + { + _mainWindow.holdingRegister.setTemp4 = -10000; + + } + await _mainWindow.WriteToSerialAsync("DiagnosticsTemp"); + + + } + } + else if(sender is Button btn) + { + if (btn.Tag.ToString() == "t1") + { + number = float.Parse(t1Text.Text); + } + else if (btn.Tag.ToString() == "t2") + { + number = float.Parse(t2Text.Text); + } + else if (btn.Tag.ToString() == "t3") + { + number = float.Parse(t3Text.Text); + } + else if (btn.Tag.ToString() == "t4") + { + number = float.Parse(t4Text.Text); + } + var border1 = btn.Parent as Border; + var parent = border1.Parent as StackPanel; + + var brother = parent.Children[1] as Border; + + List allTexts = new(); + if (brother.Tag?.ToString() == "t1") + { + allTexts.Add(t1Container.Children[0] as TextBlock); + allTexts.Add(t1Container.Children[1] as TextBlock); + allTexts.Add(t1Container.Children[2] as TextBlock); + + } + else if (brother.Tag?.ToString() == "t2") + { + allTexts.Add(t2Container.Children[0] as TextBlock); + allTexts.Add(t2Container.Children[1] as TextBlock); + allTexts.Add(t2Container.Children[2] as TextBlock); + } + else if (brother.Tag?.ToString() == "t3") + { + allTexts.Add(t3Container.Children[0] as TextBlock); + allTexts.Add(t3Container.Children[1] as TextBlock); + allTexts.Add(t3Container.Children[2] as TextBlock); + } + else if (brother.Tag?.ToString() == "t4") + { + allTexts.Add(t4Container.Children[0] as TextBlock); + allTexts.Add(t4Container.Children[1] as TextBlock); + allTexts.Add(t4Container.Children[2] as TextBlock); + } + + var button = border1.Child as Button; + if (button.Content.ToString() == "M") + { + allTexts[0].Foreground = Brush.Parse("#231f20"); // black + allTexts[1].Foreground = Brush.Parse("#af196f"); // pink + allTexts[2].Foreground = Brush.Parse("#231f20"); // black + button.Foreground = Brush.Parse("#af196f"); + button.Content = "A"; + if (button.Tag.ToString() == "t1") + { + _mainWindow.holdingRegister.setTemp1 = (int)(number * 10); + + } + else if (button.Tag.ToString() == "t2") + { + _mainWindow.holdingRegister.setTemp2 = (int)(number * 10); + + + } + else if (button.Tag.ToString() == "t3") + { + _mainWindow.holdingRegister.setTemp3 = (int)(number * 10); + } + else if (button.Tag.ToString() == "t4") + { + _mainWindow.holdingRegister.setTemp4 = (int)(number * 10); + } + await _mainWindow.WriteToSerialAsync("DiagnosticsTemp"); + + + } + else + { + foreach (var item in allTexts) + { + item.Foreground = Brush.Parse("#808080"); //gray + } + + button.Foreground = Brush.Parse("#4d4d4d"); + button.Content = "M"; + if (button.Tag.ToString() == "t1") + { + _mainWindow.holdingRegister.setTemp1 = -10000; + + } + else if (button.Tag.ToString() == "t2") + { + _mainWindow.holdingRegister.setTemp2 = -10000; + + } + else if (button.Tag.ToString() == "t3") + { + _mainWindow.holdingRegister.setTemp3 = -10000; + + } + else if (button.Tag.ToString() == "t4") + { + _mainWindow.holdingRegister.setTemp4 = -10000; + + } + await _mainWindow.WriteToSerialAsync("DiagnosticsTemp"); + + } + } + } + + private void OnPopupOverlayPointerPressed(object sender, PointerPressedEventArgs e) + { + if (isNegative) + { + targetText.Text = "-" + oldValue.ToString("0.0"); + } + else + { + targetText.Text = "+" + oldValue.ToString("0.0"); + } + keyBoardPopup.IsVisible = false; + } + private void InnerPopupPointerPressed(object? sender, PointerPressedEventArgs e) + { + e.Handled = true; + } + private void OnKeyClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + if ((button.Content=="+"|| button.Content == "-")&& targetText.Text.Length>0) + { + + } + else if((targetText.Text.Length==0 && button.Content == ".")||(targetText.Text.Contains(".")&& button.Content == ".")) + { + + } + else + { + targetText.Text += button.Content; + } + + } + + } + private void OnBackClick(object? sender, RoutedEventArgs e) + { + if (!string.IsNullOrEmpty(targetText.Text)) + { + // Remove the last character from the text box + targetText.Text = targetText.Text.Remove(targetText.Text.Length - 1, 1); + //number = number.Remove(number.Length - 1); + } + + } + private async void EnterClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + bool canEdit = targetButton.Content == "A"; + if (!string.IsNullOrEmpty(targetText.Text)) + { + float number = float.Parse(targetText.Text); + + if (char.IsDigit(targetText.Text[0])) + { + targetText.Text = "+" + number.ToString("0.0"); + } + else + { + targetText.Text = number.ToString("0.0"); + } + + var machine = _machine.ReadMachine(); + if (button.Tag.ToString() == "t1") + { + if (canEdit) + { + _mainWindow.holdingRegister.setTemp1 = (int)(number * 10); + + } + machine.setTemp1 = number; + + } + else if (button.Tag.ToString() == "t2") + { + if (canEdit) + { + _mainWindow.holdingRegister.setTemp2 = (int)(number * 10); + + } + machine.setTemp2 = number; + + + } + else if (button.Tag.ToString() == "t3") + { + if (canEdit) + { + _mainWindow.holdingRegister.setTemp3 = (int)(number * 10); + } + machine.setTemp3 = number; + } + else if (button.Tag.ToString() == "t4") + { + if (canEdit) + { + _mainWindow.holdingRegister.setTemp4 = (int)(number * 10); + } + machine.setTemp4 = number; + } + _machine.UpdateMachine(machine); + getUiElementes(); + if (canEdit) + { + await _mainWindow.WriteToSerialAsync("DiagnosticsEnter"); + + } + + keyBoardPopup.IsVisible = false; + } + + } + + } + private void ShowNumberKeyBoard(object? sender, PointerPressedEventArgs e) + { + if (sender is Border border) + { + var parent = border.Parent as StackPanel; + var brother = parent.Children[0] as Border; + targetButton = brother.Child as Button; + if (border.Tag?.ToString() == "t1") + { + targetText = t1Text; + } + else if (border.Tag?.ToString() == "t2") + { + targetText = t2Text; + } + else if (border.Tag?.ToString() == "t3") + { + targetText = t3Text; + } + else if (border.Tag?.ToString() == "t4") + { + targetText = t4Text; + } + enterBtn.Tag = border.Tag; + + isNegative = targetText.Text.StartsWith("-"); + + oldValue = float.Parse(targetText.Text.Substring(1)); + targetText.Text = ""; + keyBoardPopup.IsVisible = true; + + } + + } + + private async void OnIgnorePidPopupOverlayPointerPressed(object? sender, RoutedEventArgs e) + { + pidPopupOverlay.IsVisible = false; + } + private async void showInnerPid(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + var configratipn = _configration.ReadConfigrationById(button.Tag.ToString()); + pidPopupOverlay.IsVisible = false; + header.Text = button.Content.ToString(); + header.Tag = button.Tag; + + // Set slider values instead of text box values + kpSlider.Value = configratipn.kp; + kiSlider.Value = configratipn.ki; + kdSlider.Value = configratipn.kd; + klSlider.Value = configratipn.kl; + + // Update the display values + kpSliderValue.Text = configratipn.kp.ToString(); + kiSliderValue.Text = configratipn.ki.ToString(); + kdSliderValue.Text = configratipn.kd.ToString(); + klSliderValue.Text = configratipn.kl.ToString(); + + fcThreshold.Text = configratipn.FC_Threshold.ToString("0.0"); + heatConRange.Text = configratipn.HeatConRange.ToString("0.0"); + innerPidPopupOverlay.IsVisible = true; + } + } + private async void OnIgnoreInnerPidPopupOverlayPointerPressed(object? sender, RoutedEventArgs e) + { + innerPidPopupOverlay.IsVisible = false; + pidPopupOverlay.IsVisible = true; + } + private void OnKeyUp(object? sender, KeyEventArgs e) + { + if (sender is TextBox textBox) + { + if (textBox != null && float.TryParse(textBox.Text, out float value)) + { + if (textBox.Name == "heatConRange") + { + if (value > 25.0) + { + textBox.Text = "25.0"; + } + + } + else + { + if (value > 100) + { + textBox.Text = "100"; + } + } + // Check if the value exceeds 100 and reset to 100 if necessary. + + } + } + + } + private async void YesBtnClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + var configration = _configration.ReadConfigrationById(header.Tag.ToString()); + if (configration!=null) + { + // Read values from sliders instead of text boxes + configration.kp = (int)kpSlider.Value; + configration.ki = (int)kiSlider.Value; + configration.kd = (int)kdSlider.Value; + configration.kl = (int)klSlider.Value; + + if (string.IsNullOrEmpty(fcThreshold.Text)) + { + configration.FC_Threshold = 0; + } + else + { + configration.FC_Threshold = float.Parse(fcThreshold.Text); + } + if (string.IsNullOrEmpty(heatConRange.Text)) + { + configration.HeatConRange = 1.0F; + } + else + { + if (float.TryParse(heatConRange.Text, out float value)) + { + if (value<1.0) + { + configration.HeatConRange = 1.0F; + } + else + { + configration.HeatConRange = float.Parse(heatConRange.Text); + } + } + else + { + configration.HeatConRange = 1.0F; + } + } + + _configration.UpdateConfigration(configration); + _mainWindow.reSendHolding = true; + CloseKeyboard(); + + innerPidPopupOverlay.IsVisible = false; + pidPopupOverlay.IsVisible = true; + } + } + } + private void CloseKeyboard() + { + try + { + if (_keyboardProcess != null) + { + // Kill the keyboard process + _keyboardProcess.Kill(); + _keyboardProcess.Dispose(); + _keyboardProcess = null; + + // Force kill any remaining keyboard processes + var processKill = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = "killall", + Arguments = "-9 onboard matchbox-keyboard florence", // Common Linux on-screen keyboards + UseShellExecute = false, + CreateNoWindow = true + } + }; + processKill.Start(); + processKill.WaitForExit(1000); + processKill.Dispose(); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error closing keyboard: {ex.Message}"); + } + } + private (string? fileName, string args) GetKeyboardCommand() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + return ("osk.exe", ""); + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + return ("onboard", ""); // or "florence", "matchbox-keyboard" + return (null, ""); + } + private async void OnTextBoxFocused(object? sender, PointerPressedEventArgs e) + { + if (_keyboardProcess is { HasExited: false }) + return; + + var (fileName, args) = GetKeyboardCommand(); + if (fileName is null) + return; + + _keyboardProcess = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = fileName, + Arguments = args, + UseShellExecute = true, + WorkingDirectory = "/usr/bin" + }, + EnableRaisingEvents = true + }; + + + try + { + _keyboardProcess.Start(); + + + + Dispatcher.UIThread.Post(() => + { + if (sender is Border border) + { + var textbox = border.Child as TextBox; + textbox.SelectionStart = 0; + textbox.SelectionEnd = textbox.Text?.Length ?? 0; + } + }); + + } + catch + { + // fail silently if keyboard not found + } + } + private void OnTextInput(object? sender, TextInputEventArgs e) + { + if (sender is TextBox textBox) + { + string newText = textBox.Text + e.Text; + if (!Regex.IsMatch(newText, @"^\d*\.?\d*$")) + { + e.Handled = true; + } + } + } + private void OnTextInputOnlyInteager(object? sender, TextInputEventArgs e) + { + if (sender is TextBox textBox) + { + string newText = textBox.Text + e.Text; + if (!Regex.IsMatch(newText, @"^\d*$")) + { + e.Handled = true; + } + } + } + private async void showPidPopUp(object? sender, RoutedEventArgs e) + { + pidPopupOverlay.IsVisible = true; + + } + + + private void getUiElementes() + { + var error = _error.ReadErrorSettings()[0]; + + if (error.phaseNumber == 1) + { + phaseContainer.Background = Avalonia.Media.Brushes.Gray; + phaseContainer.IsEnabled = false; + } + else + { + phaseContainer.Background = Brush.Parse("#E6E6E6"); + phaseContainer.IsEnabled = true; + } + + flagRectangles = this.GetLogicalDescendants() + .OfType() + .Where(cb => cb.Classes.Contains("flag")) + .ToList(); + + InputesElements = this.GetLogicalDescendants() + .OfType() + .Where(c => c.Classes.Contains("in") && (c is Grid || c is Ellipse)) + .ToList(); + MotoreState = this.GetLogicalDescendants() + .OfType() + .Where(c => c.Classes.Contains("motorState") && (c is Grid || c is Ellipse)) + .ToList(); + hvoOutPuts = this.GetLogicalDescendants() + .OfType() + .Where(c => c.Classes.Contains("hvo") && (c is Grid || c is Ellipse)) + .ToList(); + lvoOutPuts = this.GetLogicalDescendants() + .OfType() + .Where(c => c.Classes.Contains("lvo") && (c is Grid||c is StackPanel || c is Ellipse)) + .ToList(); + var machine=_machine.ReadMachine(); + t1Text.Text = char.IsDigit(machine.setTemp1.ToString()[0])?"+"+ machine.setTemp1.ToString(): machine.setTemp1.ToString(); + t2Text.Text = char.IsDigit(machine.setTemp2.ToString()[0]) ? "+" + machine.setTemp2.ToString() : machine.setTemp2.ToString(); + t3Text.Text = char.IsDigit(machine.setTemp3.ToString()[0]) ? "+" + machine.setTemp3.ToString() : machine.setTemp3.ToString(); + t4Text.Text = char.IsDigit(machine.setTemp4.ToString()[0]) ? "+" + machine.setTemp4.ToString() : machine.setTemp4.ToString(); + + + } + private void setDefaultSettings() + { + var stackPanel = _mainWindow.HomeTrack.Parent as StackPanel; + _mainWindow.minimizeBtn.IsVisible = false; + + if (_isFromManualControl) + { + // Special UI setup when called from ManualControl + _mainWindow.HomeTrack.IsVisible = true; + _mainWindow.HomePolygon.Stroke = Avalonia.Media.Brushes.Black; + _mainWindow.RecipeSelTrack.IsVisible = false; + _mainWindow.RunInterfaceTrack.IsVisible = false; + _mainWindow.RecipePanelTrack.IsVisible = true; + _mainWindow.RecipePanelPolygon.Stroke = Avalonia.Media.Brushes.Black; + _mainWindow.RecipeEditTrack.IsVisible = false; + _mainWindow.SettingTrack.IsVisible = false; + _mainWindow.AdvanceSettingsTrack.IsVisible = false; + _mainWindow.ManualControlTrack.IsVisible = true; + _mainWindow.ManualControlPolygon.Stroke = Avalonia.Media.Brushes.Black; + } + else + { + // Original logic for other callers + //Set Track Up + _mainWindow.HomeTrack.IsVisible = true; + //_mainWindow.HomePolygon.Stroke = Avalonia.Media.Brushes.Black; + _mainWindow.RecipeSelTrack.IsVisible = false; + _mainWindow.RunInterfaceTrack.IsVisible = false; + _mainWindow.RecipePanelTrack.IsVisible = false; + _mainWindow.RecipeEditTrack.IsVisible = false; + if (_isAdvSettings) + { + _mainWindow.SettingTrack.IsVisible = false; + _mainWindow.AdvanceSettingsTrack.IsVisible = true; + _mainWindow.AdvanceSettingsPolygon.Stroke = Avalonia.Media.Brushes.Black; + + } + else + { + _mainWindow.SettingTrack.IsVisible = true; + _mainWindow.SettingPolygon.Stroke = Avalonia.Media.Brushes.Black; + _mainWindow.AdvanceSettingsTrack.IsVisible = false; + + } + } + + _mainWindow.DiagnosticsTrack.IsVisible = true; + _mainWindow.DiagnosticsPolygon.Stroke = Brush.Parse("#A4275D"); + // Remove the button from its current position + stackPanel.Children.Remove(_mainWindow.DiagnosticsTrack); + + // Add it back at the end of the StackPanel + stackPanel.Children.Add(_mainWindow.DiagnosticsTrack); + + _mainWindow.TitleBtn.IsVisible = false; + + _mainWindow.TitleBtn.IsVisible = true; + _mainWindow.Title.Text = "DMC7A"; + //Set Footer + _mainWindow.footerMsg.IsVisible = true; + _mainWindow.footerMsg.Text= "Read Values, And Control Outputs Manually"; + _mainWindow.footerMsg.Foreground= Brush.Parse("#A4275D"); + _mainWindow.footer.Background = Avalonia.Media.Brushes.WhiteSmoke; + _mainWindow.footerDate.Text = DateTime.Now.ToString("dd/MM/yyyy"); + _mainWindow.footerTime.Text = DateTime.Now.ToString("hh:mm tt"); + _mainWindow.footerDateContainer.IsVisible = true; + _mainWindow.footerStartBtn.IsVisible = false; + _mainWindow.adminBtns.IsVisible = false; + } + + // KP Slider and Button Event Handlers + private void KpSliderValueChanged(object? sender, RoutedEventArgs e) + { + if (kpSliderValue != null && sender is Slider slider) + { + kpSliderValue.Text = ((int)slider.Value).ToString(); + } + } + + private void KpMinusClick(object? sender, RoutedEventArgs e) + { + if (kpSlider.Value > kpSlider.Minimum) + { + kpSlider.Value--; + } + } + + private void KpPlusClick(object? sender, RoutedEventArgs e) + { + if (kpSlider.Value < kpSlider.Maximum) + { + kpSlider.Value++; + } + } + + // KI Slider and Button Event Handlers + private void KiSliderValueChanged(object? sender, RoutedEventArgs e) + { + if (kiSliderValue != null && sender is Slider slider) + { + kiSliderValue.Text = ((int)slider.Value).ToString(); + } + } + + private void KiMinusClick(object? sender, RoutedEventArgs e) + { + if (kiSlider.Value > kiSlider.Minimum) + { + kiSlider.Value--; + } + } + + private void KiPlusClick(object? sender, RoutedEventArgs e) + { + if (kiSlider.Value < kiSlider.Maximum) + { + kiSlider.Value++; + } + } + + // KD Slider and Button Event Handlers + private void KdSliderValueChanged(object? sender, RoutedEventArgs e) + { + if (kdSliderValue != null && sender is Slider slider) + { + kdSliderValue.Text = ((int)slider.Value).ToString(); + } + } + + private void KdMinusClick(object? sender, RoutedEventArgs e) + { + if (kdSlider.Value > kdSlider.Minimum) + { + kdSlider.Value--; + } + } + + private void KdPlusClick(object? sender, RoutedEventArgs e) + { + if (kdSlider.Value < kdSlider.Maximum) + { + kdSlider.Value++; + } + } + + // KL Slider and Button Event Handlers + private void KlSliderValueChanged(object? sender, RoutedEventArgs e) + { + if (klSliderValue != null && sender is Slider slider) + { + klSliderValue.Text = ((int)slider.Value).ToString(); + } + } + + private void KlMinusClick(object? sender, RoutedEventArgs e) + { + if (klSlider.Value > klSlider.Minimum) + { + klSlider.Value--; + } + } + + private void KlPlusClick(object? sender, RoutedEventArgs e) + { + if (klSlider.Value < klSlider.Maximum) + { + klSlider.Value++; + } + } +} \ No newline at end of file diff --git a/DaireApplication/Views/UserController/Home.axaml b/DaireApplication/Views/UserController/Home.axaml new file mode 100644 index 0000000..d3b9f02 --- /dev/null +++ b/DaireApplication/Views/UserController/Home.axaml @@ -0,0 +1,140 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/DaireApplication/Views/UserController/Recipe.axaml.cs b/DaireApplication/Views/UserController/Recipe.axaml.cs new file mode 100644 index 0000000..2936265 --- /dev/null +++ b/DaireApplication/Views/UserController/Recipe.axaml.cs @@ -0,0 +1,719 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.Media; +using Avalonia.Threading; +using AvaloniaApplication1.DataBase; +using DaireApplication.Views; +using ReactiveUI; +using System; +using System.Diagnostics; +using System.Linq; +using System.Runtime.InteropServices; +using System.Threading.Tasks; + +namespace DaireApplication; + +public partial class Recipe : UserControl +{ + Button recipeButton = new Button(); + private bool _isLongPress; + + private MainWindow? _mainWindow; + private UserTable? _currentUser; + private RecipeTable _recipeTable=new RecipeTable(); + private Process? _keyboardProcess; + + public Recipe() + { + InitializeComponent(); + + } + public Recipe(MainWindow mainWindow,UserTable currentUser) + { + _currentUser = currentUser; + _mainWindow = mainWindow; + InitializeComponent(); + nameBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true); + updateBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true); + setDefaultSettings(); + addDynamicButtons(); + } + + + private async void OnRecipeClick(object? sender, RoutedEventArgs e) + { + if (_isLongPress) + { + // Reset the flag for future interactions. + _isLongPress = false; + // Ignore this click since a long press was detected. + return; + } + + if (sender is Button button) + { + if (_currentUser.CanEdit) + { + _mainWindow.FindControl("ContentArea").Content = new RecipeEdit(_mainWindow, _currentUser, _recipeTable.ReadRecipesById(button.Name)); + + } + else + { + _mainWindow.FindControl("ContentArea").Content = new Settings(_mainWindow, _currentUser, _recipeTable.ReadRecipesById(button.Name)); + _mainWindow.restBoard = true; + } + + + } + + + + + } + private async void deleteActionClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + deleteMsg.Text = $"You are about to delete {button.Tag}"; + DeletePopupOverlay.IsVisible = true; + + } + + } + private async void UpdateActionClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + var text = recipeButton.Content as TextBlock; + updateInput.Text = $"{text.Text}"; + updatePopupOverlay.IsVisible = true; + + } + + } + private void OnLongRecipeClick(object? sender, RoutedEventArgs e) + { + if (e is HoldingRoutedEventArgs args) + { + if (args.HoldingState == HoldingState.Started) + { + _isLongPress = true; + + if (sender is Button button) + { + var targetText= button.Content as TextBlock; + deleteActionBtn.Tag = targetText.Text; + managePopupOverlay.IsVisible = true; + recipeButton = button; + + //recipeButton = button; + //if (button.Content is TextBlock targetText) + //{ + // deleteMsg.Text = $"You are about to delete {targetText.Text}"; + //} + } + + args.Handled = true; + } + else if (args.HoldingState == HoldingState.Completed) + { + _isLongPress = false; + } + } + } + private void CloseKeyboard() + { + try + { + if (_keyboardProcess != null) + { + // Kill the keyboard process + _keyboardProcess.Kill(); + _keyboardProcess.Dispose(); + _keyboardProcess = null; + + // Force kill any remaining keyboard processes + var processKill = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = "killall", + Arguments = "-9 onboard matchbox-keyboard florence", // Common Linux on-screen keyboards + UseShellExecute = false, + CreateNoWindow = true + } + }; + processKill.Start(); + processKill.WaitForExit(1000); + processKill.Dispose(); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error closing keyboard: {ex.Message}"); + } + } + + public void AttachHandlers(Button button) + { + if (button != null) + { + button.Holding += OnLongRecipeClick; + + button.PointerPressed += (sender, e) => + { + // Simulate a long press on any pointer (mouse or touch) + var point = e.GetPosition(button); + OnLongRecipeClick(sender, new HoldingRoutedEventArgs(HoldingState.Started, point, e.Pointer.Type)); + }; + + button.PointerReleased += (sender, e) => + { + // End simulated long press + var point = e.GetPosition(button); + OnLongRecipeClick(sender, new HoldingRoutedEventArgs(HoldingState.Completed, point, e.Pointer.Type)); + }; + } + } + private async void OnAddRecipeClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + PopupOverlay.IsVisible = true; + } + + } + private async void OnPopupOverlayPointerPressed(object? sender, RoutedEventArgs e) + { + PopupOverlay.IsVisible = false; + + + + } + private async void OnDeletePopupOverlayPointerPressed(object? sender, RoutedEventArgs e) + { + DeletePopupOverlay.IsVisible = false; + managePopupOverlay.IsVisible = false; + updatePopupOverlay.IsVisible = false; + + } + private async void YesBtnClick(object? sender, RoutedEventArgs e) + { + var result = _recipeTable.DeleteRecipe(recipeButton.Name); + if (result) + { + addDynamicButtons(); + DeletePopupOverlay.IsVisible= false; + managePopupOverlay.IsVisible = false; + + } + else + { + + } + + + } + private async void SaveUpdateClick(object? sender, RoutedEventArgs e) + { + if (!_recipeTable.DoesNameExist(updateInput.Text)) + { + var recipe = _recipeTable.ReadRecipesById(recipeButton.Name); + recipe.Name = updateInput.Text; + var result = _recipeTable.UpdateRecipe(recipe); + if (result) + { + addDynamicButtons(); + managePopupOverlay.IsVisible = false; + updatePopupOverlay.IsVisible = false; + CloseKeyboard(); + + + } + else + { + + } + } + else + { + CloseKeyboard(); + await MainWindow.MessageBox.Show(_mainWindow, "this name is already in use", "Error"); + _mainWindow.Topmost = false; + _mainWindow.Focus(); + _mainWindow.Activate(); + + } + + + + } + private void showPopUp(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + recipeButton = button; + button.Foreground = Brush.Parse("#A4275D"); + PopupOverlay.IsVisible = true; + // Append the button's content to the input box + //InputTextBox.Text += button.Content?.ToString(); + } + + } + private async void saveRecipeClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + if (!string.IsNullOrEmpty(NameInput.Text)) + { + if (!_recipeTable.DoesNameExist(NameInput.Text)) + { + RecipeTable data = new RecipeTable(); + data.Name = NameInput.Text; + data.Mixer = false; + data.Fountain = false; + data.MoldHeater = false; + data.Vibration = false; + data.VibHeater = false; + data.Pedal = false; + var result = _recipeTable.AddRecipe(data); + if (result) + { + addDynamicButtons(); + CloseKeyboard(); + NameInput.Text = ""; + PopupOverlay.IsVisible = false; + + } + else + { + + } + } + else + { + CloseKeyboard(); + await MainWindow.MessageBox.Show(_mainWindow, "this name is already in use", "Error"); + _mainWindow.Topmost = false; + _mainWindow.Activate(); + + } + } + + + } + + } + private (string? fileName, string args) GetKeyboardCommand() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + return ("osk.exe", ""); + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + return ("onboard", ""); // or "florence", "matchbox-keyboard" + return (null, ""); + } + private async void OnTextBoxFocused(object? sender, PointerPressedEventArgs e) + { + if (_keyboardProcess is { HasExited: false }) + return; + + var (fileName, args) = GetKeyboardCommand(); + if (fileName is null) + return; + + _keyboardProcess = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = fileName, + Arguments = args, + UseShellExecute = true + }, + EnableRaisingEvents = true + }; + + + try + { + _keyboardProcess.Start(); + + Dispatcher.UIThread.Post(() => + { + if (sender is Border border) + { + var textbox= border.Child as TextBox; + textbox.SelectionStart = 0; + textbox.SelectionEnd = textbox.Text?.Length ?? 0; + } + }); + } + catch + { + // fail silently if keyboard not found + } + } + + private void OnPopupOverlayPointerPressed(object sender, PointerPressedEventArgs e) + { + // Close the popup when clicking outside of it + recipeButton.Foreground = Avalonia.Media.Brushes.Black; + + PopupOverlay.IsVisible = false; + } + + private void setDefaultSettings() + { + + //set recipe title + if (_currentUser.CanEdit) + { + RecipeTitle.Content = "RECIPE EDIT/ADD PANEL"; + } + else + { + RecipeTitle.Content = "RECIPE SELECTION"; + } + //Set Track Up + _mainWindow.HomeTrack.IsVisible = true; + _mainWindow.RecipeSelTrack.IsVisible = false; + _mainWindow.RecipePanelTrack.IsVisible = false; + + + if (_currentUser.CanEdit) + { + _mainWindow.RecipePanelTrack.IsVisible = true; + _mainWindow.RecipePanelPolygon.Stroke = Brush.Parse("#A4275D"); + } + else + { + _mainWindow.RecipeSelTrack.IsVisible = true; + _mainWindow.RecipeSelPolygon.Stroke = Brush.Parse("#A4275D"); + } + //_mainWindow.HomePolygon.Stroke = Avalonia.Media.Brushes.Black; + + _mainWindow.RecipeEditTrack.IsVisible = false; + _mainWindow.RunInterfaceTrack.IsVisible = false; + _mainWindow.SettingTrack.IsVisible = false; + _mainWindow.TitleBtn.IsVisible = false; + _mainWindow.DiagnosticsTrack.IsVisible = false; + _mainWindow.SoftwareTrack.IsVisible = false; + + + //Set Footer + if (_currentUser.CanEdit) + { + _mainWindow.footerMsg.Text = "Long press to delete recipe"; + _mainWindow.footerMsg.IsVisible = true; + _mainWindow.chefBtns.IsVisible = true; + + } + else + { + _mainWindow.footerMsg.Text = "Select a recipe to start"; + _mainWindow.footerMsg.IsVisible = true; + + + } + _mainWindow.ManualControlTrack.IsVisible = false; + + _mainWindow.footerMsg.MaxWidth = 1000; + + _mainWindow.footer.Background = Avalonia.Media.Brushes.WhiteSmoke; + _mainWindow.footerMsg.Foreground = Brush.Parse("#A4275D"); + _mainWindow.footerDate.Text = DateTime.Now.ToString("dd/MM/yyyy"); + _mainWindow.footerTime.Text = DateTime.Now.ToString("hh:mm tt"); + _mainWindow.footerDateContainer.IsVisible = true; + _mainWindow.footerStartBtn.IsVisible = false; + _mainWindow.adminBtns.IsVisible = false; + } + private void addDynamicButtons() + { + var recipes= _recipeTable.ReadRecipes(); + var grid = this.FindControl("DynamicGrid"); + grid.Children.Clear(); + int lastRow = 0; + int lastCol = 0; + int colIndexForExtraData = 0; + int recipeIndex = 0; + + try + { + if (recipes.Count<3) + { + // Add dynamic rows + for (int i = 0; i < (int)Math.Ceiling((double)recipes.Count / 3); i++) // Example: 20 rows + { + lastRow = i; + grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + + // Add content for each column + for (int col = 0; col < recipes.Count; col++) + { + + lastCol = col; + + var text = new TextBlock + { + Padding = new Thickness(10), + Text = recipes[recipeIndex + col].Name, + VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, + HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, + FontSize = 31, + FontWeight=FontWeight.Normal, + Foreground = Avalonia.Media.Brushes.Black + + }; + var button = new Button + { + Width = 210, + Height = 160, + Margin = new Thickness(3), + Content = text, + Name = recipes[recipeIndex + col].Id.ToString(), + CornerRadius = new CornerRadius(10), + Background = Avalonia.Media.Brushes.White, + HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, + VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, + + }; + + button.Click += OnRecipeClick; + + if (_currentUser.CanEdit) + { + //button.Holding += OnLongRecipeClick; + AttachHandlers(button); + //button.DoubleTapped += OnDoubleRecipeClick; + + } + + grid.Children.Add(button); + Grid.SetRow(button, i); + Grid.SetColumn(button, col); + } + recipeIndex += 3; + } + if (_currentUser.CanEdit) + { + var Plus = new TextBlock + { + Padding = new Thickness(10), + Text = "+", + VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, + HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, + FontSize = 100, + Foreground = Brush.Parse("#A4275D") + + }; + var AddButtun = new Button + { + Width = 210, + Height = 160, + Margin = new Thickness(3), + Content = Plus, + CornerRadius = new CornerRadius(10), + Background = Avalonia.Media.Brushes.White, + HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, + VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, + VerticalContentAlignment = Avalonia.Layout.VerticalAlignment.Center, + HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, + Padding = new Thickness(0, 0, 0, 15), + + }; + AddButtun.Click += OnAddRecipeClick; + if (lastCol < 2) + { + grid.Children.Add(AddButtun); + Grid.SetRow(AddButtun, lastRow); + Grid.SetColumn(AddButtun, lastCol + 1); + } + else + { + grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + + grid.Children.Add(AddButtun); + Grid.SetRow(AddButtun, lastRow + 1); + Grid.SetColumn(AddButtun, 0); + } + } + + + + + } + else + { + // Add dynamic rows + for (int i = 0; i < (int)Math.Floor((double)recipes.Count / 3); i++) // Example: 20 rows + { + lastRow = i; + grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + + // Add content for each column + for (int col = 0; col < 3; col++) + { + + + lastCol = col; + + var text = new TextBlock + { + Padding = new Thickness(10), + Text = recipes[recipeIndex + col].Name, + VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, + HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, + FontSize = 31, + FontWeight = FontWeight.Normal, + Foreground = Avalonia.Media.Brushes.Black + + }; + var button = new Button + { + Width = 210, + Height = 160, + Margin = new Thickness(3), + Content = text, + Name = recipes[recipeIndex + col].Id.ToString(), + CornerRadius = new CornerRadius(10), + Background = Avalonia.Media.Brushes.White, + HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, + VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, + + }; + button.Click += OnRecipeClick; + + if (_currentUser.CanEdit) + { + //button.Holding += OnLongRecipeClick; + AttachHandlers(button); + + //button.DoubleTapped += OnDoubleRecipeClick; + + } + + grid.Children.Add(button); + Grid.SetRow(button, i); + Grid.SetColumn(button, col); + } + recipeIndex += 3; + } + for (int i = 0; i < recipes.Count -recipeIndex; i++) + { + var text = new TextBlock + { + Padding = new Thickness(10), + Text = recipes[recipeIndex + i].Name, + VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, + HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, + FontSize = 31, + FontWeight = FontWeight.Normal, + Foreground = Avalonia.Media.Brushes.Black + + }; + var button = new Button + { + Width = 210, + Height = 160, + Margin = new Thickness(3), + Content = text, + Name = recipes[recipeIndex + i].Id.ToString(), + CornerRadius = new CornerRadius(10), + Background = Avalonia.Media.Brushes.White, + HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, + VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, + + }; + button.Click += OnRecipeClick; + + if (_currentUser.CanEdit) + { + //button.Holding += OnLongRecipeClick; + AttachHandlers(button); + + //button.DoubleTapped += OnDoubleRecipeClick; + + } + if (lastCol < 2) + { + lastCol += 1; + + + + + grid.Children.Add(button); + Grid.SetRow(button,lastRow); + Grid.SetColumn(button, lastCol); + } + else + { + + grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + + grid.Children.Add(button); + Grid.SetRow(button, lastRow + 1); + Grid.SetColumn(button, colIndexForExtraData); + colIndexForExtraData += 1; + } + } + if (_currentUser.CanEdit) + { + var Plus = new TextBlock + { + Padding = new Thickness(10), + Text = "+", + VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, + HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, + FontSize = 100, + Foreground = Brush.Parse("#A4275D"), + + + }; + var AddButtun = new Button + { + Width = 210, + Height = 160, + Margin = new Thickness(3), + Content = Plus, + CornerRadius = new CornerRadius(10), + Background = Avalonia.Media.Brushes.White, + VerticalContentAlignment = Avalonia.Layout.VerticalAlignment.Center, + HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, + HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, + VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, + Padding = new Thickness(0,0,0,15), + }; + + AddButtun.Click += OnAddRecipeClick; + + if (lastCol < 2) + { + grid.Children.Add(AddButtun); + Grid.SetRow(AddButtun, lastRow); + Grid.SetColumn(AddButtun, lastCol + 1); + } + else + { + grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + + grid.Children.Add(AddButtun); + Grid.SetRow(AddButtun, lastRow + 1); + Grid.SetColumn(AddButtun, colIndexForExtraData); + } + } + + } + + } + catch (Exception) + { + } + + + + } + + +} \ No newline at end of file diff --git a/DaireApplication/Views/UserController/RecipeEdit.axaml b/DaireApplication/Views/UserController/RecipeEdit.axaml new file mode 100644 index 0000000..adbcf8b --- /dev/null +++ b/DaireApplication/Views/UserController/RecipeEdit.axaml @@ -0,0 +1,232 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/DaireApplication/Views/UserController/RecipeEdit.axaml.cs b/DaireApplication/Views/UserController/RecipeEdit.axaml.cs new file mode 100644 index 0000000..25bcfa1 --- /dev/null +++ b/DaireApplication/Views/UserController/RecipeEdit.axaml.cs @@ -0,0 +1,253 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.Markup.Xaml; +using Avalonia.Media; +using AvaloniaApplication1.DataBase; +using DaireApplication.Views; +using System; + +namespace DaireApplication; + +public partial class RecipeEdit : UserControl +{ + Button controllButton = new Button(); + private MainWindow? _mainWindow; + private UserTable? _currentUser; + private RecipeTable? _recipeTable; + + + public RecipeEdit() + { + InitializeComponent(); + } + public RecipeEdit(MainWindow mainWindow, UserTable currentUser,RecipeTable recipeTable) + { + _currentUser = currentUser; + _mainWindow = mainWindow; + _recipeTable=recipeTable; + InitializeComponent(); + setDefaultSettings(); + } + + string oldNumber = ""; + private void OnKeyClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + + var StackPanel = controllButton.Content as StackPanel; + var Label = StackPanel.Children; + if (Label[1] is TextBlock targetText) + { + //number += button.Content?.ToString(); + targetText.Text += button.Content ; + } + // Append the button's content to the input box + //InputTextBox.Text += button.Content?.ToString(); + } + + } + private void OnBackClick(object? sender, RoutedEventArgs e) + { + var StackPanel = controllButton.Content as StackPanel; + var Label = StackPanel.Children; + if (Label[1] is TextBlock targetText) + { + if (!string.IsNullOrEmpty(targetText.Text)) + { + // Remove the last character from the text box + targetText.Text = targetText.Text.Remove(targetText.Text.Length -1, 1); + //number = number.Remove(number.Length - 1); + } + } + + } + private void EnterClick(object? sender, RoutedEventArgs e) + { + // + RecipeTable recipe = new RecipeTable + { + Id = _recipeTable.Id, + Name = _recipeTable.Name, + TankTemp = _recipeTable.TankTemp, + FountainTemp = _recipeTable.FountainTemp, + Mixer = _recipeTable.Mixer ?? false, + Fountain = _recipeTable.Fountain ?? false, + MoldHeater = _recipeTable.MoldHeater ?? false, + Vibration = _recipeTable.Vibration ?? false, + VibHeater = _recipeTable.VibHeater ?? false, + Pedal = _recipeTable.Pedal ?? false, + PedalOnTime = _recipeTable.PedalOnTime, + PedalOffTime = _recipeTable.PedalOffTime, + HeatingGoal = _recipeTable.HeatingGoal, + CoolingGoal = _recipeTable.CoolingGoal, + PouringGoal = _recipeTable.PouringGoal + }; + + var heatingStackPanel = heatingBtn.Content as StackPanel; + var heatingText = (heatingStackPanel?.Children[1] as TextBlock)?.Text; + + var coolingStackPanel = coolingBtn.Content as StackPanel; + var coolingText = (coolingStackPanel?.Children[1] as TextBlock)?.Text; + + var stackPanel = controllButton.Content as StackPanel; + var label = stackPanel?.Children; + var targetText = label?[1] as TextBlock; + var activeTxt = label?[0] as TextBlock; + + if (activeTxt == null || targetText == null) + return; + + switch (activeTxt.Text) + { + case "HEATING:": + if (!string.IsNullOrEmpty(targetText.Text) && int.TryParse(targetText.Text, out int heatingValue)) + { + if (heatingValue > 60) + { + tempErrorMsg.Text = "Heating Temperature must be lower than 60 C"; + return; + } + else if (heatingValue < 40) + { + tempErrorMsg.Text = "Heating Temperature must be greater than 40 C"; + return; + } + + recipe.HeatingGoal = heatingValue; + } + break; + + case "POURING:": + if (!string.IsNullOrEmpty(targetText.Text) && int.TryParse(targetText.Text, out int pouringValue)) + { + if (string.IsNullOrEmpty(heatingText) || string.IsNullOrEmpty(coolingText)) + { + tempErrorMsg.Text = "Enter heating and cooling temperature first"; + return; + } + + if (!int.TryParse(heatingText, out int heatingTemp) || !int.TryParse(coolingText, out int coolingTemp)) + { + tempErrorMsg.Text = "Invalid temperature values"; + return; + } + + if (pouringValue > heatingTemp) + { + tempErrorMsg.Text = $"Pouring Temperature must be lower than Heating Temperature ({heatingTemp}C)"; + return; + } + else if (pouringValue < coolingTemp) + { + tempErrorMsg.Text = $"Pouring Temperature must be greater than Cooling Temperature ({coolingTemp}C)"; + return; + } + + recipe.PouringGoal = pouringValue; + } + break; + + case "COOLING:": + if (!string.IsNullOrEmpty(targetText.Text) && int.TryParse(targetText.Text, out int coolingValue)) + { + if (coolingValue > 40) + { + tempErrorMsg.Text = "Cooling Temperature must be lower than 40 C"; + return; + } + else if (coolingValue < 20) + { + tempErrorMsg.Text = "Cooling Temperature must be greater than 20 C"; + return; + } + + recipe.CoolingGoal = coolingValue; + } + break; + } + + _recipeTable.UpdateRecipe(recipe); + tempErrorMsg.Text = ""; + heatingBtn.IsEnabled = true; + coolingBtn.IsEnabled = true; + pouringBtn.IsEnabled = true; + PopupOverlay.IsVisible = false; + setDefaultSettings(); + } + + + private void showPopUp(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + heatingBtn.IsEnabled = false; + coolingBtn.IsEnabled = false; + pouringBtn.IsEnabled = false; + button.IsEnabled = true; + var StackPanel = button.Content as StackPanel; + var Label = StackPanel.Children; + if (Label[1] is TextBlock targetText) + { + oldNumber = targetText.Text; + } + controllButton = button; + PopupOverlay.IsVisible = true; + } + + } + private void OnPopupOverlayPointerPressed(object sender, PointerPressedEventArgs e) + { + // Close the popup when clicking outside of it + //controllButton.Foreground = Avalonia.Media.Brushes.Black; + var StackPanel = controllButton.Content as StackPanel; + var Label = StackPanel.Children; + if (Label[1] is TextBlock targetText) + { + //number += button.Content?.ToString(); + targetText.Text = oldNumber; + } + tempErrorMsg.Text = ""; + heatingBtn.IsEnabled = true; + coolingBtn.IsEnabled = true; + pouringBtn.IsEnabled = true; + + PopupOverlay.IsVisible = false; + } + + private void setDefaultSettings() + { + //set Values + _recipeTable = _recipeTable.ReadRecipesById(_recipeTable.Id.ToString()); + heatingValue.Text = _recipeTable?.HeatingGoal == 0 ? "" : _recipeTable?.HeatingGoal.ToString(); + coolingValue.Text = _recipeTable?.CoolingGoal == 0 ? "" : _recipeTable?.CoolingGoal.ToString(); + pouringValue.Text = _recipeTable?.PouringGoal == 0 ? "" : _recipeTable?.PouringGoal.ToString(); + + //Set Track Up + _mainWindow.HomeTrack.IsVisible = true; + //_mainWindow.HomePolygon.Stroke = Avalonia.Media.Brushes.Black; + _mainWindow.RecipePanelTrack.IsVisible = true; + _mainWindow.RecipePanelPolygon.Stroke = Avalonia.Media.Brushes.Black; + _mainWindow.RecipeEditTrack.IsVisible = true; + _mainWindow.RecipeEditPolygon.Stroke = Brush.Parse("#A4275D"); + _mainWindow.RunInterfaceTrack.IsVisible = false; + _mainWindow.RecipeSelTrack.IsVisible = false; + _mainWindow.SettingTrack.IsVisible = false; + _mainWindow.DiagnosticsTrack.IsVisible = false; + + _mainWindow.TitleBtn.IsVisible = true; + _mainWindow.Title.Text = _recipeTable.Name; + + //Set Footer + _mainWindow.footerMsg.Text = "Select the tempereture to edit it"; + _mainWindow.footer.Background = Avalonia.Media.Brushes.WhiteSmoke; + _mainWindow.footerMsg.Foreground = Brush.Parse("#A4275D"); + _mainWindow.footerDate.Text = DateTime.Now.ToString("dd/MM/yyyy"); + _mainWindow.footerTime.Text = DateTime.Now.ToString("hh:mm tt"); + _mainWindow.footerDateContainer.IsVisible = true; + _mainWindow.footerStartBtn.IsVisible = false; + _mainWindow.adminBtns.IsVisible = false; + } +} \ No newline at end of file diff --git a/DaireApplication/Views/UserController/Settings.axaml b/DaireApplication/Views/UserController/Settings.axaml new file mode 100644 index 0000000..af87eae --- /dev/null +++ b/DaireApplication/Views/UserController/Settings.axaml @@ -0,0 +1,513 @@ + + + + + + + + + + + + + + + + + Mixer + Delay: + 120 + + + + + + + + Pedal OFF: + + 120 + + + + + + Cooling Delay: + 120 + + + + + + Fountain Delay: + 120 + + Target Temp: + 120 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/DaireApplication/Views/UserController/Settings.axaml.cs b/DaireApplication/Views/UserController/Settings.axaml.cs new file mode 100644 index 0000000..597cc06 --- /dev/null +++ b/DaireApplication/Views/UserController/Settings.axaml.cs @@ -0,0 +1,388 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.Documents; +using Avalonia.Controls.Shapes; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.Markup.Xaml; +using Avalonia.Media; +using AvaloniaApplication1.DataBase; +using DaireApplication.DataBase; +using DaireApplication.ViewModels; +using DaireApplication.Views; +using System; +using System.Drawing; +using System.Reflection.PortableExecutable; +using System.Threading; + +namespace DaireApplication; + +public partial class Settings : UserControl +{ + Button controllButton = new Button(); + private MainWindow? _mainWindow; + private UserTable? _currentUser; + public RecipeTable? _recipeTable; + private MachineTable _machine; + public string ActiveColor { get; set; } = "#A4275D"; + public string PassiveColor { get; set; } = "#666666"; + + public Settings() + { + InitializeComponent(); + } + public Settings(MainWindow mainWindow, UserTable currentUser,RecipeTable recipeTable) + { + _currentUser = currentUser; + _mainWindow = mainWindow; + _recipeTable = recipeTable; + _machine = new MachineTable(); + _machine = _machine.ReadMachine(); + + InitializeComponent(); + + setDefaultSettings(); + + setDafaultValues(); + mixerBtn.Click += _mainWindow.MotorClick; + fountainBtn.Click += _mainWindow.FountainClick; + } + + + private void toggelOnOffClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + var StackPanel = button.Content as StackPanel; + var Label = StackPanel.Children; + var underLine = Label[2] as Avalonia.Controls.Shapes.Rectangle; + var titelLable = Label[0] as Label; + + + + if (Label[1] is Label targetLable) + { + if (targetLable.Content == "ON") + { + if (titelLable.Content == "MOLD HEATER") + { + _mainWindow.moldHeaterMotor = 0; + } + if (titelLable.Content == "VIBRATION") + { + _mainWindow.vibrationMotor = 0; + + } + if (titelLable.Content == "VIB. HEATER") + { + _mainWindow.vibHeaterMotor = 0; + + } + + + } + else + { + if (titelLable.Content == "MOLD HEATER") + { + _mainWindow.moldHeaterMotor = 1; + } + if (titelLable.Content == "VIBRATION") + { + _mainWindow.vibrationMotor = 1; + + } + if (titelLable.Content == "VIB. HEATER") + { + _mainWindow.vibHeaterMotor = 1; + + } + + } + } + } + + } + private void PedalBtn(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + var StackPanel = button.Content as StackPanel; + var Label = StackPanel.Children; + var underLine = Label[1] as Avalonia.Controls.Shapes.Rectangle; + if (Label[0] is TextBlock targetLable) + { + if (targetLable.Text == "AUTO") + { + if (_mainWindow.pedalOnTimer!=null ) + { + _mainWindow.pedalOnTimer.Change(Timeout.Infinite, Timeout.Infinite); + _mainWindow.pedalOnTimer = null; + _mainWindow.pedalOnSeconds = 0; + } + if (_mainWindow.pedalOffTimer!=null) + { + _mainWindow.pedalOffTimer.Change(Timeout.Infinite, Timeout.Infinite); + _mainWindow.pedalOffTimer = null; + _mainWindow.pedalOffSeconds = 0; + } + _mainWindow.pedalMotor = 0; + targetLable.Text = "MANUAL"; + underLine.Fill = Brush.Parse("#666666"); + PedalAutoContainer.IsEnabled = false; + _recipeTable.Pedal = true; + } + else + { + _mainWindow.pedalMotor = 1; + _mainWindow.pedalState = -1; + _mainWindow.setPedalTimerOnce = 1; + _mainWindow.pedalOnSeconds = 0; + _mainWindow.pedalOffSeconds = 0; + targetLable.Text = "AUTO"; + underLine.Fill = Brush.Parse("#A4275D"); + PedalAutoContainer.IsEnabled = true; + _recipeTable.Pedal = false; + + } + _recipeTable.UpdateRecipe(_recipeTable); + } + } + + } + private void adjustPedalTime(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + if (button.Classes[0].ToString()== "PedalOff") + { + if (button.Content == "−") + { + if (Int32.Parse(PedalOffTime.Text) > 0) + { + PedalOffTime.Text = (Int32.Parse(PedalOffTime.Text) - 1).ToString(); + } + + } + else if (button.Content == "+") + { + + PedalOffTime.Text = (Int32.Parse(PedalOffTime.Text) + 1).ToString(); + } + _recipeTable.PedalOffTime = Int32.Parse(PedalOffTime.Text); + _recipeTable.UpdateRecipe(_recipeTable); + } + else + { + if (button.Content == "−") + { + if (Int32.Parse(PedalOnTime.Text) > 0) + { + PedalOnTime.Text = (Int32.Parse(PedalOnTime.Text) - 1).ToString(); + } + + } + else if (button.Content == "+") + { + if (int.TryParse(PedalOnTime.Text, out int value)) + { + if (value < 9) + { + PedalOnTime.Text = (value + 1).ToString(); + } + } + } + _recipeTable.PedalOnTime = Int32.Parse(PedalOnTime.Text); + _recipeTable.UpdateRecipe(_recipeTable); + } + _recipeTable = _recipeTable.ReadRecipesById(_recipeTable.Id.ToString()); + + } + + } + + private async void OnIgnorePopupOverlayPointerPressed(object? sender, RoutedEventArgs e) + { + DeletePopupOverlay.IsVisible = false; + + + + } + private async void HideTempErrorPopUp(object? sender, RoutedEventArgs e) + { + _mainWindow.pauseTimer = false; + _mainWindow.pauseTempTracking = false; // Allow process to continue after clicking "No" + _mainWindow.tempWarningAccepted = true; // User accepted the temperature warning + tempErrorPopupOverlay.IsVisible = false; + } + private async void YesBtnClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + if (DeletePopupOverlay.Tag=="home") + { + + _mainWindow.resetAll(); + // rest the board + _mainWindow.restBoard = true; + _mainWindow.UserName.Content = "Select User"; + _mainWindow.footerMsg.Text = ""; + _mainWindow.ContentArea.Content = new Home(_mainWindow); + } + else if (DeletePopupOverlay.Tag == "recipeSel") + { + _mainWindow.resetAll(); + // rest the board + _mainWindow.restBoard = true; + _mainWindow.footerMsg.Text = ""; + _mainWindow.ContentArea.Content = new Recipe(_mainWindow, Program.currentUser); + } + } + + + + } + private async void ErrorYesBtnClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + //_mainWindow.pause = true; + //_mainWindow.pauseTempTracking = true; + //_mainWindow.pauseTimer = true; + + // stop the recipe + _mainWindow.startRecipe = 0; + _mainWindow.Heating = 0; + _mainWindow.cooling = 0; + _mainWindow.pouring = 0; + _mainWindow.PumbOn = -1; + _mainWindow.pedalMotor = -1; + if (_mainWindow.heatingTimer != null) + { + _mainWindow.heatingTimer.Change(Timeout.Infinite, Timeout.Infinite); + _mainWindow.heatingSeconds = 0; + } + if (_mainWindow.coolingTimer != null) + { + _mainWindow.coolingTimer.Change(Timeout.Infinite, Timeout.Infinite); + _mainWindow.coolingSeconds = 0; + } + if (_mainWindow.pouringTimer != null) + { + _mainWindow.pouringTimer.Change(Timeout.Infinite, Timeout.Infinite); + _mainWindow.pouringSeconds = 0; + } + var fount = _mainWindow._mapping.Find(x => x.Name.ToLower() == "Pump".ToLower()); + if (fount != null) + { + if (fount.BitNumbers.Count > 0) + { + foreach (var bit in fount.BitNumbers) + { + + _mainWindow.holdingRegister.motor &= (ushort)~(1 << bit); + } + } + } + _mainWindow.holdingRegister.setTemp1 = -10000; + _mainWindow.holdingRegister.setTemp2 = -10000; + _mainWindow.holdingRegister.setTemp3 = -10000; + _mainWindow.holdingRegister.setTemp4 = -10000; + await _mainWindow.WriteToSerialAsync("ErrorYesBtnClick"); + tempErrorPopupOverlay.IsVisible = false; + _mainWindow.footerMsg.Text = "Recipe Stoped"; + _mainWindow.recipeStartBtn.Content = "START RECIPE"; + } + } + + + + private void setDefaultSettings() + { + //Set Track Up + _mainWindow.HomeTrack.IsVisible = true; + //_mainWindow.HomePolygon.Stroke = Avalonia.Media.Brushes.Black; + _mainWindow.RecipeSelTrack.IsVisible = true; + _mainWindow.RecipeSelPolygon.Stroke = Avalonia.Media.Brushes.Black; + _mainWindow.RunInterfaceTrack.IsVisible = true; + _mainWindow.RunInterfacePolygon.Stroke = Brush.Parse("#A4275D"); + _mainWindow.RecipePanelTrack.IsVisible = false; + _mainWindow.RecipeEditTrack.IsVisible = false; + _mainWindow.SettingTrack.IsVisible = false; + _mainWindow.DiagnosticsTrack.IsVisible = false; + _mainWindow.TitleBtn.IsVisible = true; + _mainWindow.Title.Text = _recipeTable.Name; + + //Set Footer + _mainWindow.footerMsg.Text = "Ready"; + _mainWindow.footerMsg.MaxWidth = 500; + _mainWindow.footer.Background = Avalonia.Media.Brushes.WhiteSmoke; + _mainWindow.footerMsg.Foreground = Avalonia.Media.Brushes.Green; + _mainWindow.footerDate.Text = DateTime.Now.ToString("dd/MM/yyyy"); + _mainWindow.footerTime.Text = DateTime.Now.ToString("hh:mm tt"); + _mainWindow.footerDateContainer.IsVisible = true; + _mainWindow.footerStartBtn.IsVisible = true; + _mainWindow.adminBtns.IsVisible = false; + } + private void setDafaultValues() + { + //Recipe Settings + heatingValue.Content = _recipeTable.HeatingGoal; + coolingValue.Content = _recipeTable.CoolingGoal; + pouringValue.Content = _recipeTable.PouringGoal; + //tankTemp + TankTempValue.Content = _recipeTable?.TankTemp; + //mixer + var mixerChildren= MixerSP.Children; + var mixerLable = mixerChildren[1] as Label; + mixerLable.Content = _recipeTable.Mixer.Value ? "ON" : "OFF"; + var mixerUnderLine = mixerChildren[2] as Avalonia.Controls.Shapes.Rectangle; + mixerUnderLine.Fill = _recipeTable.Mixer.Value ? Brush.Parse(ActiveColor) : Brush.Parse(PassiveColor); + //pedal + var pedalChildren = PedalSP.Children; + var pedalText = pedalChildren[0] as TextBlock; + var pedalUnderLine = pedalChildren[1] as Avalonia.Controls.Shapes.Rectangle; + if (_recipeTable.Pedal.Value) + { + pedalText.Text = "MANUAL"; + pedalUnderLine.Fill = Brush.Parse(PassiveColor); + PedalAutoContainer.IsEnabled = false; + } + else + { + pedalText.Text = "AUTO"; + pedalUnderLine.Fill = Brush.Parse(ActiveColor); + PedalAutoContainer.IsEnabled = true; + } + PedalOffTime.Text = _recipeTable.PedalOffTime.ToString(); + PedalOnTime.Text = _recipeTable.PedalOnTime.ToString(); + //fountain Temp + FountainTempValue.Content = _recipeTable?.FountainTemp; + //fountain + var fountainChildren = FountainSP.Children; + var fountainLable = fountainChildren[1] as Label; + fountainLable.Content = _recipeTable.Fountain.Value ? "ON" : "OFF"; + var fountainUnderLine = fountainChildren[2] as Avalonia.Controls.Shapes.Rectangle; + fountainUnderLine.Fill = _recipeTable.Fountain.Value ? Brush.Parse(ActiveColor) : Brush.Parse(PassiveColor); + //mold Heater + var moldHeaterChildren = MoldHeaterSP.Children; + var moldHeaterLable = moldHeaterChildren[1] as Label; + moldHeaterLable.Content = _recipeTable.MoldHeater.Value ? "ON" : "OFF"; + var moldHeaterUnderLine = moldHeaterChildren[2] as Avalonia.Controls.Shapes.Rectangle; + moldHeaterUnderLine.Fill = _recipeTable.MoldHeater.Value ? Brush.Parse(ActiveColor) : Brush.Parse(PassiveColor); + // vibration + var vibrationChildren = VibrationSP.Children; + var vibrationLable = vibrationChildren[1] as Label; + vibrationLable.Content = _recipeTable.Vibration.Value ? "ON" : "OFF"; + var vibrationUnderLine = vibrationChildren[2] as Avalonia.Controls.Shapes.Rectangle; + vibrationUnderLine.Fill = _recipeTable.Vibration.Value ? Brush.Parse(ActiveColor) : Brush.Parse(PassiveColor); + // vib heater + var vibHeaterChildren = VibHeaterSP.Children; + var vibHeaterLable = vibHeaterChildren[1] as Label; + vibHeaterLable.Content = _recipeTable.VibHeater.Value ? "ON" : "OFF"; + var vibHeaterUnderLine = vibHeaterChildren[2] as Avalonia.Controls.Shapes.Rectangle; + vibHeaterUnderLine.Fill = _recipeTable.VibHeater.Value ? Brush.Parse(ActiveColor) : Brush.Parse(PassiveColor); + + + } +} \ No newline at end of file diff --git a/DaireApplication/Views/UserController/Software.axaml b/DaireApplication/Views/UserController/Software.axaml new file mode 100644 index 0000000..47749d7 --- /dev/null +++ b/DaireApplication/Views/UserController/Software.axaml @@ -0,0 +1,783 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + PASSWORDS RESET + + + + + + + + + + + + + + + + + + + + + + + + + + SCREEN SETTINGS + + + + + + + + + + + + + + + + + + + + + + + + + + COM SETTINGS + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + Bound Rate: + + + + + + + + + + + + + + + + + + Stop Bits: + + + + + + + + + + + + Parity: + + + + + + + + + + + Packets Sending Intervals : + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Warning Limit : + + + + + + + Error Limit : + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + INs/OUTs MAPPING + + + + + + + IN-1 + + + + + + + + + + + + + + + + + + IN-2 + + + + + + + + + + + + + + + + + IN-3 + + + + + + + + + + + + + + + + + IN-4 + + + + + + + + + + + + + + + + + IN-5 + + + + + + + + + + + + + + + + + IN-6 + + + + + + + + + + + + + + + + + + + LOV-1 + + + + + + + + + + + + + + + + + + LOV-2 + + + + + + + + + + + + + + + + + + LOV-3 + + + + + + + + + + + + + + + + + + LOV-4 + + + + + + + + + + + + + + + + + + LOV-5 + + + + + + + + + + + + + + + + + + LOV-6 + + + + + + + + + + + + + + + + + + + + + + + + INs/OUTs MAPPING + + + + + + + + T-1 + + + + + + + + + + + + + + + + + + + + T-2 + + + + + + + + + + + + + + + + + + + + T-3 + + + + + + + + + + + + + + + + + + + + T-4 + + + + + + + + + + + + + + + + + + + + + + HVO-1 + + + + + + + + + + + + + + + + + + + + HVO-2 + + + + + + + + + + + + + + + + + + + + + HVO-3 + + + + + + + + + + + + + + + + + + + + HVO-4 + + + + + + + + + + + + + + + + + + + + HVO-5 + + + + + + + + + + + + + + + + + + + + HVO-6 + + + + + + + + + + + + + + + + + + + + + + MOT-1 + + + + + + + + + + + + + + + + + MOT-2 + + + + + + + + + + + + + + + + + + + + + + + + INs/OUTs MAPPING + + + + + + + + AN-1 + + + + + + + + + + + + + + + AN-2 + + + + + + + + + + + + + + + + + + + + + VALUES + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +============================================================ +FILE: DaireApplication/Views/UserController/AdvanceSettings.axaml.cs +============================================================ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.LogicalTree; +using Avalonia.Markup.Xaml; +using Avalonia.Media; +using Avalonia.Threading; +using AvaloniaApplication1.DataBase; +using DaireApplication.DataBase; +using DaireApplication.ViewModels; +using DaireApplication.Views; +using DynamicData; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using static DaireApplication.Views.MainWindow; + +namespace DaireApplication; + +public partial class AdvanceSettings : UserControl +{ + public Mapping _mapping; + public ConfigrationTable _configration; + public List _mappingRecordes; + MainWindow _mainWindow; + private Process? _keyboardProcess; + public ErrorSettingsTable _error = new(); + TextBlock targetText = new TextBlock(); + float oldValue = 0; + bool _isDiag; + bool _isSoftware; + public AdvanceSettings(MainWindow mainWindow,bool isDiag=false,bool isSoftware=false) + { + InitializeComponent(); + _mainWindow = mainWindow; + _mapping = new Mapping(); + _mappingRecordes = _mapping.ReadMappings(); + _configration = new(); + _isDiag = isDiag; + _isSoftware = isSoftware; + + setDefaultValues(); + // Remove the old text box event handlers since we're using sliders now + // kp.AddHandler(TextInputEvent, OnTextInputOnlyInteager, RoutingStrategies.Tunnel); + // ki.AddHandler(TextInputEvent, OnTextInputOnlyInteager, RoutingStrategies.Tunnel); + // kd.AddHandler(TextInputEvent, OnTextInputOnlyInteager, RoutingStrategies.Tunnel); + // kl.AddHandler(TextInputEvent, OnTextInputOnlyInteager, RoutingStrategies.Tunnel); + fcThreshold.AddHandler(TextInputEvent, OnTextInput, RoutingStrategies.Tunnel); + heatConRange.AddHandler(TextInputEvent, OnTextInput, RoutingStrategies.Tunnel); + // Remove the old border event handlers since we're using sliders now + // kpBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true); + // kiBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true); + // kdBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true); + // klBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true); + fcThresholdBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true); + heatConRangeBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true); + AttachHandlers(_mainWindow.UserName, CloseApplication); + + setDefaultSettings(); + + } + public AdvanceSettings() + { + InitializeComponent(); + } + public void AttachHandlers(Button button, System.EventHandler func) + { + if (button != null) + { + button.Holding += func; + + button.PointerPressed += (sender, e) => + { + // Simulate a long press on any pointer (mouse or touch) + var point = e.GetPosition(button); + func(sender, new HoldingRoutedEventArgs(HoldingState.Started, point, e.Pointer.Type)); + }; + + button.PointerReleased += (sender, e) => + { + // End simulated long press + var point = e.GetPosition(button); + func(sender, new HoldingRoutedEventArgs(HoldingState.Completed, point, e.Pointer.Type)); + }; + } + } + public static void CloseApplication(object? sender, RoutedEventArgs e) + { + var lifetime = Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime; + lifetime?.Shutdown(); // This should correctly shut down the application + } + private void HVOChanged(object? sender, RoutedEventArgs e) + { + if (sender is ComboBox comboBox) + { + if (comboBox.SelectedItem is ComboBoxItem selectedItem) + { + // Get the displayed content + + //HVO + var result= _mappingRecordes.FindAll(x => x.Address == "1" && x.IsRead==false).Find(c=>c.Name==selectedItem.Content.ToString()); + if (result!=null) + { + if (!result.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))) + { + var oldRecord = _mappingRecordes.Find(x => x.Address == "1" && x.IsRead == false && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))); + if (oldRecord!=null) + { + _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString())); + + } + result.BitNumbers.Add(int.Parse(comboBox.Tag.ToString())); + _mapping.UpdateMapping(result); + setDefaultValues(); + } + + } + else + { + var oldRecord = _mappingRecordes.Find(x => x.Address == "1" && x.IsRead == false && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))); + if (oldRecord != null) + { + _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString())); + + } + } + + + _mappingRecordes = _mapping.ReadMappings(); + _mainWindow._mapping = _mappingRecordes; + var configrations = _configration.ReadConfigrations(); + var compressor = _mappingRecordes.Find(x => x.Name == "Compressor"); + var water = _mappingRecordes.Find(x => x.Name == "Water"); + if (compressor != null && water != null) + { + if (compressor.BitNumbers.Count > 0 ) + { + configrations[2].FC_out = compressor.BitNumbers.Concat(water.BitNumbers).ToList(); + configrations[3].FC_out = compressor.BitNumbers.Concat(water.BitNumbers).ToList(); + + } + else + { + configrations[2].FC_out = [-1]; + configrations[3].FC_out = [-1]; + + } + if (water.BitNumbers.Count > 0) + { + configrations[2].SC_out = water.BitNumbers; + configrations[3].SC_out = water.BitNumbers; + } + else + { + configrations[2].SC_out = [-1]; + configrations[3].SC_out = [-1]; + } + _configration.UpdateConfigration(configrations[2]); + _configration.UpdateConfigration(configrations[3]); + + } + foreach (var item in configrations) + { + var namedMap = _mappingRecordes.Find(x => x.Name == item.name); + if (namedMap!=null) + { + if (namedMap.BitNumbers.Count>0) + { + item.H_out = namedMap.BitNumbers; + if (namedMap.Name!= "HELIX Heater") + { + item.FC_out = [-1]; + item.SC_out = [-1]; + } + _configration.UpdateConfigration(item); + } + else + { + item.H_out =[-1]; + if (namedMap.Name != "HELIX Heater") + { + item.FC_out = [-1]; + item.SC_out = [-1]; + } + _configration.UpdateConfigration(item); + } + } + else + { + + } + } + configrations[3].H_out = configrations[2].H_out; + _configration.UpdateConfigration(configrations[3]); + + + _mainWindow.sendConfig = true; + } + + } + } + + private void TChanged(object? sender, RoutedEventArgs e) + { + if (sender is ComboBox comboBox) + { + if (comboBox.SelectedItem is ComboBoxItem selectedItem) + { + // Get the displayed content + + //HVO + var result = _mappingRecordes.Find(c => c.Name.ToLower() == selectedItem.Tag.ToString().ToLower()); + if (result != null) + { + if (!result.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))) + { + var oldRecord = _mappingRecordes.Find(x => x.Name.EndsWith("Temp") && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))); + if (oldRecord != null) + { + _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString())); + + } + result.BitNumbers.Add(int.Parse(comboBox.Tag.ToString())); + _mapping.UpdateMapping(result); + setDefaultValues(); + } + + } + else + { + var oldRecord = _mappingRecordes.Find(x => x.Name.EndsWith("Temp") && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))); + if (oldRecord != null) + { + _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString())); + setDefaultValues(); + + + } + } + + + _mappingRecordes = _mapping.ReadMappings(); + _mainWindow._mapping = _mappingRecordes; + + } + + } + } + private void LOVChanged(object? sender, RoutedEventArgs e) + { + if (sender is ComboBox comboBox) + { + if (comboBox.SelectedItem is ComboBoxItem selectedItem) + { + var result = _mappingRecordes.FindAll(x => x.Address == "2").Find(c => c.Name.ToLower() == selectedItem.Tag.ToString().ToLower()); + if (result != null) + { + if (!result.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))) + { + var oldRecord = _mappingRecordes.Find(x => x.Address == "2" && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))); + if (oldRecord != null) + { + _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString())); + + } + result.BitNumbers.Add(int.Parse(comboBox.Tag.ToString())); + _mapping.UpdateMapping(result); + setDefaultValues(); + } + + } + else + { + var oldRecord = _mappingRecordes.Find(x => x.Address == "2" && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))); + if (oldRecord != null) + { + _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString())); + setDefaultValues(); + + + } + } + _mappingRecordes = _mapping.ReadMappings(); + _mainWindow._mapping = _mappingRecordes; + + } + + } + } + private void InChanged(object? sender, RoutedEventArgs e) + { + if (sender is ComboBox comboBox) + { + if (comboBox.SelectedItem is ComboBoxItem selectedItem) + { + // Get the displayed content + + //HVO + var result = _mappingRecordes.FindAll(x => x.Address == "1" &&x.IsRead==true).Find(c => c.Name.ToLower() == selectedItem.Content.ToString().ToLower()); + if (result != null) + { + if (!result.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))) + { + var oldRecord = _mappingRecordes.Find(x => x.Address == "1" && x.IsRead == true && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))); + if (oldRecord != null) + { + _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString())); + + } + result.BitNumbers.Add(int.Parse(comboBox.Tag.ToString())); + _mapping.UpdateMapping(result); + setDefaultValues(); + } + + } + else + { + var oldRecord = _mappingRecordes.Find(x => x.Address == "1" && x.IsRead == true && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))); + if (oldRecord != null) + { + _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString())); + setDefaultValues(); + + + } + } + + + _mappingRecordes = _mapping.ReadMappings(); + _mainWindow._mapping = _mappingRecordes; + + } + + } + } + private void MotChanged(object? sender, RoutedEventArgs e) + { + if (sender is ComboBox comboBox) + { + if (comboBox.SelectedItem is ComboBoxItem selectedItem) + { + var result = _mappingRecordes.FindAll(x => x.Address == "3").Find(c => c.Name.ToLower() == selectedItem.Tag.ToString().ToLower()); + if (result != null) + { + if (!result.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))) + { + var oldRecord = _mappingRecordes.Find(x => x.Address == "3" && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))); + if (oldRecord != null) + { + _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString())); + + } + result.BitNumbers.Add(int.Parse(comboBox.Tag.ToString())); + _mapping.UpdateMapping(result); + setDefaultValues(); + } + + } + else + { + var oldRecord = _mappingRecordes.Find(x => x.Address == "3" && x.BitNumbers.Contains(int.Parse(comboBox.Tag.ToString()))); + if (oldRecord != null) + { + _mapping.DeleteBitNumber(oldRecord.Id, int.Parse(comboBox.Tag.ToString())); + setDefaultValues(); + + + } + } + + + _mappingRecordes = _mapping.ReadMappings(); + _mainWindow._mapping = _mappingRecordes; + + } + + } + } + + + + private (string? fileName, string args) GetKeyboardCommand() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + return ("osk.exe", ""); + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + return ("onboard", ""); // or "florence", "matchbox-keyboard" + return (null, ""); + } + private async void OnTextBoxFocused(object? sender, PointerPressedEventArgs e) + { + if (_keyboardProcess is { HasExited: false }) + return; + + var (fileName, args) = GetKeyboardCommand(); + if (fileName is null) + return; + + _keyboardProcess = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = fileName, + Arguments = args, + UseShellExecute = true, + WorkingDirectory = "/usr/bin" + }, + EnableRaisingEvents = true + }; + + + try + { + _keyboardProcess.Start(); + + + + Dispatcher.UIThread.Post(() => + { + if (sender is Border border) + { + var textbox = border.Child as TextBox; + textbox.SelectionStart = 0; + textbox.SelectionEnd = textbox.Text?.Length ?? 0; + } + }); + + } + catch + { + // fail silently if keyboard not found + } + } + + + private async void OnIgnoreInnerPidPopupOverlayPointerPressed(object? sender, RoutedEventArgs e) + { + innerPidPopupOverlay.IsVisible = false; + pidPopupOverlay.IsVisible = true; + + + + } + private async void OnIgnorePidPopupOverlayPointerPressed(object? sender, RoutedEventArgs e) + { + pidPopupOverlay.IsVisible = false; + } + private async void YesBtnClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + var configration = _configration.ReadConfigrationById(header.Tag.ToString()); + if (configration!=null) + { + // Read values from sliders instead of text boxes + configration.kp = (int)kpSlider.Value; + configration.ki = (int)kiSlider.Value; + configration.kd = (int)kdSlider.Value; + configration.kl = (int)klSlider.Value; + + if (string.IsNullOrEmpty(fcThreshold.Text)) + { + configration.FC_Threshold = 0; + } + else + { + configration.FC_Threshold = float.Parse(fcThreshold.Text); + + } + if (string.IsNullOrEmpty(heatConRange.Text)) + { + configration.HeatConRange = 1.0F; + } + else + { + if (float.TryParse(heatConRange.Text, out float value)) + { + if (value<1.0) + { + configration.HeatConRange = 1.0F; + } + else + { + configration.HeatConRange = float.Parse(heatConRange.Text); + } + } + else + { + configration.HeatConRange = 1.0F; + } + + } + + _configration.UpdateConfigration(configration); + _mainWindow.sendConfig = true; + CloseKeyboard(); + + innerPidPopupOverlay.IsVisible = false; + pidPopupOverlay.IsVisible = true; + + } + } + + + + } + + private async void showPidPopUp(object? sender, RoutedEventArgs e) + { + pidPopupOverlay.IsVisible = true; + + } + private async void showInnerPid(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + var configratipn = _configration.ReadConfigrationById(button.Tag.ToString()); + pidPopupOverlay.IsVisible = false; + header.Text = button.Content.ToString(); + header.Tag = button.Tag; + + // Set slider values instead of text box values + kpSlider.Value = configratipn.kp; + kiSlider.Value = configratipn.ki; + kdSlider.Value = configratipn.kd; + klSlider.Value = configratipn.kl; + + // Update the display values + kpSliderValue.Text = configratipn.kp.ToString(); + kiSliderValue.Text = configratipn.ki.ToString(); + kdSliderValue.Text = configratipn.kd.ToString(); + klSliderValue.Text = configratipn.kl.ToString(); + + fcThreshold.Text = configratipn.FC_Threshold.ToString("0.0"); + heatConRange.Text = configratipn.HeatConRange.ToString("0.0"); + innerPidPopupOverlay.IsVisible = true; + + } + + } + + // KP Slider and Button Event Handlers + private void KpSliderValueChanged(object? sender, RoutedEventArgs e) + { + if (kpSliderValue != null && sender is Slider slider) + { + kpSliderValue.Text = ((int)slider.Value).ToString(); + } + } + + private void KpMinusClick(object? sender, RoutedEventArgs e) + { + if (kpSlider.Value > kpSlider.Minimum) + { + kpSlider.Value--; + } + } + + private void KpPlusClick(object? sender, RoutedEventArgs e) + { + if (kpSlider.Value < kpSlider.Maximum) + { + kpSlider.Value++; + } + } + + // KI Slider and Button Event Handlers + private void KiSliderValueChanged(object? sender, RoutedEventArgs e) + { + if (kiSliderValue != null && sender is Slider slider) + { + kiSliderValue.Text = ((int)slider.Value).ToString(); + } + } + + private void KiMinusClick(object? sender, RoutedEventArgs e) + { + if (kiSlider.Value > kiSlider.Minimum) + { + kiSlider.Value--; + } + } + + private void KiPlusClick(object? sender, RoutedEventArgs e) + { + if (kiSlider.Value < kiSlider.Maximum) + { + kiSlider.Value++; + } + } + + // KD Slider and Button Event Handlers + private void KdSliderValueChanged(object? sender, RoutedEventArgs e) + { + if (kdSliderValue != null && sender is Slider slider) + { + kdSliderValue.Text = ((int)slider.Value).ToString(); + } + } + + private void KdMinusClick(object? sender, RoutedEventArgs e) + { + if (kdSlider.Value > kdSlider.Minimum) + { + kdSlider.Value--; + } + } + + private void KdPlusClick(object? sender, RoutedEventArgs e) + { + if (kdSlider.Value < kdSlider.Maximum) + { + kdSlider.Value++; + } + } + + // KL Slider and Button Event Handlers + private void KlSliderValueChanged(object? sender, RoutedEventArgs e) + { + if (klSliderValue != null && sender is Slider slider) + { + klSliderValue.Text = ((int)slider.Value).ToString(); + } + } + + private void KlMinusClick(object? sender, RoutedEventArgs e) + { + if (klSlider.Value > klSlider.Minimum) + { + klSlider.Value--; + } + } + + private void KlPlusClick(object? sender, RoutedEventArgs e) + { + if (klSlider.Value < klSlider.Maximum) + { + klSlider.Value++; + } + } + + private void OnTextInput(object? sender, TextInputEventArgs e) + { + if (sender is TextBox textBox) + { + string newText = textBox.Text + e.Text; + if (!Regex.IsMatch(newText, @"^\d*\.?\d*$")) + { + e.Handled = true; + } + } + } + private void OnTextInputOnlyInteager(object? sender, TextInputEventArgs e) + { + if (sender is TextBox textBox) + { + string newText = textBox.Text + e.Text; + if (!Regex.IsMatch(newText, @"^\d*$")) + { + e.Handled = true; + } + } + } + + private async void gridButtonClick(object? sender, RoutedEventArgs e) + { + var error = _error.ReadErrorSettings()[0]; + if (gridValue.Text == "50Hz") + { + error.gridFreq = 60; + _error.UpdateError(error); + setDefaultValues(); + + } + else + { + error.gridFreq = 50; + _error.UpdateError(error); + setDefaultValues(); + } + + } + private async void supplyButtonClick(object? sender, RoutedEventArgs e) + { + var error = _error.ReadErrorSettings()[0]; + int bit = 11; + + if (phasesNumberValue.Text == "3-Phases") + { + error.phaseNumber = 1; + _error.UpdateError(error); + setDefaultValues(); + _mainWindow.holdingRegister.resetError |= (ushort)(1 << bit); + } + else + { + error.phaseNumber = 3; + _error.UpdateError(error); + _mainWindow.holdingRegister.resetError &= (ushort)~(1 << bit); + + + setDefaultValues(); + + } + await _mainWindow.WriteToSerialAsync("supplyButtonClick"); + } + private async void voltageButtonClick(object? sender, RoutedEventArgs e) + { + var error = _error.ReadErrorSettings()[0]; + int bit = 12; + + if (voltageNumberValue.Text.Contains("220")) + { + error.phaseVoltage = 110; + _error.UpdateError(error); + setDefaultValues(); + _mainWindow.holdingRegister.resetError |= (ushort)(1 << bit); + } + else + { + error.phaseVoltage =220; + _error.UpdateError(error); + _mainWindow.holdingRegister.resetError &= (ushort)~(1 << bit); + + + setDefaultValues(); + + } + await _mainWindow.WriteToSerialAsync("voltageButtonClick"); + } + + private async void extPowerClick(object? sender, RoutedEventArgs e) + { + var error = _error.ReadErrorSettings()[0]; + if (extPowerValue.Text == "Yes") + { + error.extPower = false; + _error.UpdateError(error); + setDefaultValues(); + + + } + else + { + error.extPower = true; + _error.UpdateError(error); + setDefaultValues(); + + } + } + private void setDefaultValues() + { + _mappingRecordes = _mapping.ReadMappings(); + var allHVOComboBox= this.GetLogicalDescendants() + .OfType() + .Where(cb => cb.Classes.Contains("HVO")) + .ToList(); + //HVO + for (int i = 0; i < allHVOComboBox.Count; i++) + { + var result = _mappingRecordes.FindAll(x => x.Address == "1" && x.IsRead==false ).Find(c => c.BitNumbers.Contains(int.Parse(allHVOComboBox[i].Tag.ToString()))); + if (result != null) + { + allHVOComboBox[i].SelectedIndex = result.Id - 11; + } + else + { + allHVOComboBox[i].SelectedIndex = 6; + + } + } + // IN + var allINComboBox = this.GetLogicalDescendants() + .OfType() + .Where(cb => cb.Classes.Contains("in")) + .ToList(); + for (int i = 0; i < allINComboBox.Count; i++) + { + var result = _mappingRecordes.FindAll(x => x.Address == "1"&&x.IsRead==true).Find(c => c.BitNumbers.Contains(int.Parse(allINComboBox[i].Tag.ToString()))); + if (result != null) + { + allINComboBox[i].SelectedIndex = result.Id - 1; + } + else + { + allINComboBox[i].SelectedIndex = 3; + + } + } + + //LOV + var allLOVComboBox = this.GetLogicalDescendants() + .OfType() + .Where(cb => cb.Classes.Contains("lov")) + .ToList(); + for (int i = 0; i < allLOVComboBox.Count; i++) + { + var result = _mappingRecordes.FindAll(x => x.Address == "2" && x.IsRead == false).Find(c => c.BitNumbers.Contains(int.Parse(allLOVComboBox[i].Tag.ToString()))); + if (result != null) + { + allLOVComboBox[i].SelectedIndex = result.Id - 8; + } + else + { + allLOVComboBox[i].SelectedIndex = 3; + + } + } + // T + + var allTComboBox = this.GetLogicalDescendants() + .OfType() + .Where(cb => cb.Classes.Contains("T")) + .ToList(); + for (int i = 0; i < allTComboBox.Count; i++) + { + var result = _mappingRecordes.FindAll(x => x.Name.EndsWith("Temp")).Find(c => c.BitNumbers.Contains(int.Parse(allTComboBox[i].Tag.ToString()))); + + if (result != null) + { + allTComboBox[i].SelectedIndex = result.Id - 4; + } + else + { + allTComboBox[i].SelectedIndex = 5; + + } + } + // MOT + var allMotComboBox = this.GetLogicalDescendants() + .OfType() + .Where(cb => cb.Classes.Contains("mot")) + .ToList(); + for (int i = 0; i < allMotComboBox.Count; i++) + { + var result = _mappingRecordes.FindAll(x => x.Address == "3" && x.IsRead==false).Find(c => c.BitNumbers.Contains(int.Parse(allMotComboBox[i].Tag.ToString()))); + if (result != null) + { + allMotComboBox[i].SelectedIndex = result.Id - 17; + } + else + { + allMotComboBox[i].SelectedIndex = 2; + + } + } + var error = _error.ReadErrorSettings()[0]; + + phasesNumberValue.Text = $"{error.phaseNumber}-Phases"; + voltageNumberValue.Text = $"{error.phaseVoltage} V"; + gridValue.Text = $"{error.gridFreq}Hz"; + extPowerValue.Text = error.extPower ? "Yes" : "No"; + var config = _configration.ReadConfigrations()[0]; + i_neutValue.Text = config.i_neut.ToString("0.0"); + i_mot1Value.Text = config.i_mot1.ToString("0.0"); + i_mot2Value.Text = config.i_mot2.ToString("0.0"); + + + + } + private void OnPopupOverlayPointerPressed(object sender, PointerPressedEventArgs e) + { + targetText.Text = oldValue.ToString("0.0"); + keyBoardPopup.IsVisible = false; + } + private void OnKeyClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + if (button.Content == ".") + { + if (Char.IsDigit(targetText.Text[0]) && !targetText.Text.Contains(button.Content.ToString())) + { + targetText.Text += button.Content; + + } + } + else + { + targetText.Text += button.Content; + if (float.Parse(targetText.Text) > 20.0) + { + targetText.Text = "20.0"; + } + } + + } + + } + private void OnBackClick(object? sender, RoutedEventArgs e) + { + if (!string.IsNullOrEmpty(targetText.Text)) + { + // Remove the last character from the text box + targetText.Text = targetText.Text.Remove(targetText.Text.Length - 1, 1); + //number = number.Remove(number.Length - 1); + } + + } + private void EnterClick(object? sender, RoutedEventArgs e) + { + var config = _configration.ReadConfigrations()[0]; + if (targetText.Name== "i_mot2Value") + { + config.i_mot2 = float.Parse(targetText.Text); + } + else if (targetText.Name == "i_mot1Value") + { + config.i_mot1 = float.Parse(targetText.Text); + } + else + { + config.i_neut = float.Parse(targetText.Text); + } + _configration.UpdateConfigration(config); + setDefaultValues(); + _mainWindow.sendConfig = true; + keyBoardPopup.IsVisible = false; + + + } + private void ShowNumberKeyBoard(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + if (button.Name=="i_mot2") + { + targetText = i_mot2Value; + } + else if (button.Name == "i_mot1") + { + targetText = i_mot1Value; + + } + else if (button.Name== "i_neut") + { + targetText = i_neutValue; + + } + oldValue = float.Parse(targetText.Text); + targetText.Text = ""; + keyBoardPopup.IsVisible = true; + + } + + } + + private void OnKeyUp(object? sender, KeyEventArgs e) + { + if (sender is TextBox textBox) + { + if (textBox != null && float.TryParse(textBox.Text, out float value)) + { + if (textBox.Name== "heatConRange") + { + if (value > 25.0) + { + textBox.Text = "25.0"; + } + + } + else + { + if (value > 100) + { + textBox.Text = "100"; + } + } + // Check if the value exceeds 100 and reset to 100 if necessary. + + } + } + + } + + private void InnerPopupPointerPressed(object? sender, PointerPressedEventArgs e) + { + e.Handled = true; + } + private void CloseKeyboard() + { + try + { + if (_keyboardProcess != null) + { + // Kill the keyboard process + _keyboardProcess.Kill(); + _keyboardProcess.Dispose(); + _keyboardProcess = null; + + // Force kill any remaining keyboard processes + var processKill = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = "killall", + Arguments = "-9 onboard matchbox-keyboard florence", // Common Linux on-screen keyboards + UseShellExecute = false, + CreateNoWindow = true + } + }; + processKill.Start(); + processKill.WaitForExit(1000); + processKill.Dispose(); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error closing keyboard: {ex.Message}"); + } + } + private void setDefaultSettings() + { + _mainWindow.minimizeBtn.IsVisible = false; + var stackPanel = _mainWindow.HomeTrack.Parent as StackPanel; + + + //Set Track Up + _mainWindow.HomeTrack.IsVisible = true; + _mainWindow.HomePolygon.Stroke = Avalonia.Media.Brushes.Black; + _mainWindow.RecipeSelTrack.IsVisible = false; + _mainWindow.RunInterfaceTrack.IsVisible = false; + _mainWindow.RecipePanelTrack.IsVisible = false; + _mainWindow.RecipeEditTrack.IsVisible = false; + if (_isDiag||_isSoftware) + { + if (_isDiag) + { + _mainWindow.DiagnosticsTrack.IsVisible = true; + _mainWindow.DiagnosticsPolygon.Stroke = Avalonia.Media.Brushes.Black; + + } + else if (_isSoftware) + { + _mainWindow.SoftwareTrack.IsVisible = true; + _mainWindow.SoftwarePolygon.Stroke = Avalonia.Media.Brushes.Black; + } + _mainWindow.SettingTrack.IsVisible = false; + } + else + { + _mainWindow.DiagnosticsTrack.IsVisible = false; + _mainWindow.SoftwareTrack.IsVisible = false; + + _mainWindow.SettingTrack.IsVisible = true; + _mainWindow.SettingPolygon.Stroke = Avalonia.Media.Brushes.Black; + } + // Remove the button from its current position + stackPanel.Children.Remove(_mainWindow.AdvanceSettingsTrack); + + // Add it back at the end of the StackPanel + stackPanel.Children.Add(_mainWindow.AdvanceSettingsTrack); + _mainWindow.AdvanceSettingsTrack.IsVisible = true; + _mainWindow.AdvanceSettingsPolygon.Stroke = Brush.Parse("#A4275D"); + + + + _mainWindow.TitleBtn.IsVisible = true; + _mainWindow.Title.Text = "DR-62664A"; + //Set Footer + _mainWindow.footerMsg.IsVisible = true; + _mainWindow.footerMsg.Text = "Map Inputs And Outputs, And Set The Board Internal Values"; + _mainWindow.footerMsg.Foreground = Brush.Parse("#A4275D"); + _mainWindow.footer.Background = Brush.Parse("#f2f2f2"); + _mainWindow.footerDate.Text = DateTime.Now.ToString("dd/MM/yyyy"); + _mainWindow.footerTime.Text = DateTime.Now.ToString("hh:mm tt"); + _mainWindow.footerDateContainer.IsVisible = true; + _mainWindow.footerStartBtn.IsVisible = false; + _mainWindow.adminBtns.IsVisible = false; + } +} + +============================================================ +FILE: DaireApplication/Views/UserController/Diagnostics.axaml +============================================================ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + T-1 = + +0.0 + °C + + + + + + + + + + + + + T-2 = + +0.0 + °C + + + + + + + + + + + + + T-3 = + +0.0 + °C + + + + + + + + + + + + + T-4 = + +0.0 + °C + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + T-Board + + 0 + °C + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + T-Cooler + + 0 + °C + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Temps Control + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + CALIP. Not Done + + + + + + + + + + + + + + + + + + + + + + + + + + + + Temp Max: + + + + + + + + + + + Temp Min: + + + + + + + + + + + + + Currents + Calibration: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +============================================================ +FILE: DaireApplication/Views/UserController/Diagnostics.axaml.cs +============================================================ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Controls.Shapes; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.LogicalTree; +using Avalonia.Markup.Xaml; +using Avalonia.Media; +using Avalonia.Threading; +using AvaloniaApplication1.DataBase; +using DaireApplication.DataBase; +using DaireApplication.ViewModels; +using DaireApplication.Views; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.Tracing; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text.RegularExpressions; +using static System.Runtime.InteropServices.JavaScript.JSType; + +namespace DaireApplication; + +public partial class Diagnostics : UserControl +{ + private MainWindow? _mainWindow; + private ErrorSettingsTable _error=new(); + public ConfigrationTable _configration; + private Process? _keyboardProcess; + + + public string GrayColor="#666666"; + public string RedColor= "#FF0000"; + public string GreenColor= "#71C837"; + public string PinkColor= "#AF196F"; + public string OrangeColor= "#FF6600"; + public List flagRectangles { get; set; } + public List InputesElements { get; set; } + public List MotoreState { get; set; } + public List hvoOutPuts { get; set; } + public List lvoOutPuts { get; set; } + TextBlock targetText = new TextBlock(); + Button targetButton = new Button(); + float oldValue = 0; + bool isNegative = false; + bool _isAdvSettings; + bool _isFromManualControl; + public MachineTable _machine { get; set; } + + + public Diagnostics() + { + + InitializeComponent(); + + } + public Diagnostics(MainWindow mainWindow,bool isAdvSettings=false, bool isFromManualControl=false) + { + _mainWindow = mainWindow; + _machine = new MachineTable(); + _configration = new(); + _isAdvSettings = isAdvSettings; + _isFromManualControl = isFromManualControl; + + InitializeComponent(); + setDefaultSettings(); + getUiElementes(); + fcThreshold.AddHandler(TextInputEvent, OnTextInput, RoutingStrategies.Tunnel); + heatConRange.AddHandler(TextInputEvent, OnTextInput, RoutingStrategies.Tunnel); + fcThresholdBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true); + heatConRangeBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true); + + AttachHandlers(_mainWindow.logoBtn, AdvanceSettingsView); + } + public void AttachHandlers(Button button, System.EventHandler func) + { + if (button != null) + { + button.Holding += func; + + button.PointerPressed += (sender, e) => + { + // Simulate a long press on any pointer (mouse or touch) + var point = e.GetPosition(button); + func(sender, new HoldingRoutedEventArgs(HoldingState.Started, point, e.Pointer.Type)); + }; + + button.PointerReleased += (sender, e) => + { + // End simulated long press + var point = e.GetPosition(button); + func(sender, new HoldingRoutedEventArgs(HoldingState.Completed, point, e.Pointer.Type)); + }; + } + } + public void AdvanceSettingsView(object? sender, RoutedEventArgs e) + { + if (_mainWindow.ContentArea.Content == this) + { + _mainWindow.ContentArea.Content = new AdvanceSettings(_mainWindow,true,false); + } + + } + public void ResendConfig(object? sender, RoutedEventArgs e) + { + if (!_mainWindow.sendConfig) + { + _mainWindow.reSendHolding = true; + } + } + public static void CloseApplication(object? sender, RoutedEventArgs e) + { + var lifetime = Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime; + lifetime?.Shutdown(); // This should correctly shut down the application + } + private async void motorClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + var grid= button.Content as Grid; + var stackPanel = grid.Children[0] as StackPanel; + var text = stackPanel.Children[1] as TextBlock; + if (text.Text=="ON") + { + _mainWindow.holdingRegister.motor = (ushort)(_mainWindow.holdingRegister.motor & ~(1 << int.Parse(grid.Tag.ToString()))); + + } + else if (text.Text == "OFF") + { + _mainWindow.holdingRegister.motor = (ushort)(_mainWindow.holdingRegister.motor | (1 << int.Parse(grid.Tag.ToString()))); + } + await _mainWindow.WriteToSerialAsync("motorClick"); + + } + + } + private async void hvoClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + var grid= button.Content as Grid; + var text = grid.Children[1] as TextBlock; + if (text.Text=="ON") + { + _mainWindow.holdingRegister.hvOut = (ushort)(_mainWindow.holdingRegister.hvOut & ~(1 << int.Parse(grid.Tag.ToString()))); + + } + else if (text.Text == "OFF") + { + _mainWindow.holdingRegister.hvOut = (ushort)(_mainWindow.holdingRegister.hvOut | (1 << int.Parse(grid.Tag.ToString()))); + + } + await _mainWindow.WriteToSerialAsync("hvoClick"); + + } + + } + private async void lvoClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + var grid= button.Content as Grid; + var stack= button.Content as StackPanel; + if (grid!=null) + { + var text = grid.Children[1] as TextBlock; + if (text.Text == "ON") + { + _mainWindow.holdingRegister.lvOut = (ushort)(_mainWindow.holdingRegister.lvOut & ~(1 << int.Parse(grid.Tag.ToString()))); + + } + else if (text.Text == "OFF") + { + _mainWindow.holdingRegister.lvOut = (ushort)(_mainWindow.holdingRegister.lvOut | (1 << int.Parse(grid.Tag.ToString()))); + } + + } + else if(stack != null) + { + var text = stack.Children[1] as TextBlock; + if (text.Text == "ON") + { + _mainWindow.holdingRegister.lvOut = (ushort)(_mainWindow.holdingRegister.lvOut & ~(1 << int.Parse(stack.Tag.ToString()))); + + } + else if (text.Text == "OFF") + { + _mainWindow.holdingRegister.lvOut = (ushort)(_mainWindow.holdingRegister.lvOut | (1 << int.Parse(stack.Tag.ToString()))); + } + } + await _mainWindow.WriteToSerialAsync("lvoClick"); + + + } + + } + + private async void resetErrorClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + _mainWindow.holdingRegister.resetError = (ushort)(_mainWindow.holdingRegister.resetError | (1 << 0)); + await _mainWindow.WriteToSerialAsync("resetErrorClick"); + } + } + + private async void ChangeTempMode(object sender, RoutedEventArgs e) + { + float number =0; + + if (sender is Border border) + { + if (border.Tag.ToString()=="t1") + { + number = float.Parse(t1Text.Text); + } + else if(border.Tag.ToString() == "t2") + { + number = float.Parse(t2Text.Text); + } + else if (border.Tag.ToString() == "t3") + { + number = float.Parse(t3Text.Text); + } + else if (border.Tag.ToString() == "t4") + { + number = float.Parse(t4Text.Text); + } + var parent = border.Parent as StackPanel; + var brother = parent.Children[1] as Border; + + List allTexts= new (); + if (brother.Tag?.ToString() == "t1") + { + allTexts.Add(t1Container.Children[0] as TextBlock); + allTexts.Add(t1Container.Children[1] as TextBlock); + allTexts.Add(t1Container.Children[2] as TextBlock); + + } + else if (brother.Tag?.ToString() == "t2") + { + allTexts.Add(t2Container.Children[0] as TextBlock); + allTexts.Add(t2Container.Children[1] as TextBlock); + allTexts.Add(t2Container.Children[2] as TextBlock); + } + else if (brother.Tag?.ToString() == "t3") + { + allTexts.Add(t3Container.Children[0] as TextBlock); + allTexts.Add(t3Container.Children[1] as TextBlock); + allTexts.Add(t3Container.Children[2] as TextBlock); + } + else if (brother.Tag?.ToString() == "t4") + { + allTexts.Add(t4Container.Children[0] as TextBlock); + allTexts.Add(t4Container.Children[1] as TextBlock); + allTexts.Add(t4Container.Children[2] as TextBlock); + } + + var button=border.Child as Button; + if (button.Content.ToString()=="M") + { + allTexts[0].Foreground = Brush.Parse("#231f20"); // black + allTexts[1].Foreground = Brush.Parse("#af196f"); // pink + allTexts[2].Foreground = Brush.Parse("#231f20"); // black + button.Foreground = Brush.Parse("#af196f"); + button.Content = "A"; + if (button.Tag.ToString() == "t1") + { + _mainWindow.holdingRegister.setTemp1 = (int)(number * 10); + + } + else if (button.Tag.ToString() == "t2") + { + _mainWindow.holdingRegister.setTemp2 = (int)(number * 10); + + + } + else if (button.Tag.ToString() == "t3") + { + _mainWindow.holdingRegister.setTemp3 = (int)(number * 10); + + + } + else if (button.Tag.ToString() == "t4") + { + _mainWindow.holdingRegister.setTemp4 = (int)(number * 10); + + + } + await _mainWindow.WriteToSerialAsync("DiagnosticsTemp"); + + } + else + { + foreach (var item in allTexts) + { + item.Foreground = Brush.Parse("#808080"); //gray + } + + button.Foreground = Brush.Parse("#4d4d4d"); + button.Content = "M"; + if (button.Tag.ToString()=="t1") + { + _mainWindow.holdingRegister.setTemp1 = -10000; + + } + else if (button.Tag.ToString() == "t2") + { + _mainWindow.holdingRegister.setTemp2 = -10000; + + } + else if (button.Tag.ToString() == "t3") + { + _mainWindow.holdingRegister.setTemp3 = -10000; + + } + else if (button.Tag.ToString() == "t4") + { + _mainWindow.holdingRegister.setTemp4 = -10000; + + } + await _mainWindow.WriteToSerialAsync("DiagnosticsTemp"); + + + } + } + else if(sender is Button btn) + { + if (btn.Tag.ToString() == "t1") + { + number = float.Parse(t1Text.Text); + } + else if (btn.Tag.ToString() == "t2") + { + number = float.Parse(t2Text.Text); + } + else if (btn.Tag.ToString() == "t3") + { + number = float.Parse(t3Text.Text); + } + else if (btn.Tag.ToString() == "t4") + { + number = float.Parse(t4Text.Text); + } + var border1 = btn.Parent as Border; + var parent = border1.Parent as StackPanel; + + var brother = parent.Children[1] as Border; + + List allTexts = new(); + if (brother.Tag?.ToString() == "t1") + { + allTexts.Add(t1Container.Children[0] as TextBlock); + allTexts.Add(t1Container.Children[1] as TextBlock); + allTexts.Add(t1Container.Children[2] as TextBlock); + + } + else if (brother.Tag?.ToString() == "t2") + { + allTexts.Add(t2Container.Children[0] as TextBlock); + allTexts.Add(t2Container.Children[1] as TextBlock); + allTexts.Add(t2Container.Children[2] as TextBlock); + } + else if (brother.Tag?.ToString() == "t3") + { + allTexts.Add(t3Container.Children[0] as TextBlock); + allTexts.Add(t3Container.Children[1] as TextBlock); + allTexts.Add(t3Container.Children[2] as TextBlock); + } + else if (brother.Tag?.ToString() == "t4") + { + allTexts.Add(t4Container.Children[0] as TextBlock); + allTexts.Add(t4Container.Children[1] as TextBlock); + allTexts.Add(t4Container.Children[2] as TextBlock); + } + + var button = border1.Child as Button; + if (button.Content.ToString() == "M") + { + allTexts[0].Foreground = Brush.Parse("#231f20"); // black + allTexts[1].Foreground = Brush.Parse("#af196f"); // pink + allTexts[2].Foreground = Brush.Parse("#231f20"); // black + button.Foreground = Brush.Parse("#af196f"); + button.Content = "A"; + if (button.Tag.ToString() == "t1") + { + _mainWindow.holdingRegister.setTemp1 = (int)(number * 10); + + } + else if (button.Tag.ToString() == "t2") + { + _mainWindow.holdingRegister.setTemp2 = (int)(number * 10); + + + } + else if (button.Tag.ToString() == "t3") + { + _mainWindow.holdingRegister.setTemp3 = (int)(number * 10); + } + else if (button.Tag.ToString() == "t4") + { + _mainWindow.holdingRegister.setTemp4 = (int)(number * 10); + } + await _mainWindow.WriteToSerialAsync("DiagnosticsTemp"); + + + } + else + { + foreach (var item in allTexts) + { + item.Foreground = Brush.Parse("#808080"); //gray + } + + button.Foreground = Brush.Parse("#4d4d4d"); + button.Content = "M"; + if (button.Tag.ToString() == "t1") + { + _mainWindow.holdingRegister.setTemp1 = -10000; + + } + else if (button.Tag.ToString() == "t2") + { + _mainWindow.holdingRegister.setTemp2 = -10000; + + } + else if (button.Tag.ToString() == "t3") + { + _mainWindow.holdingRegister.setTemp3 = -10000; + + } + else if (button.Tag.ToString() == "t4") + { + _mainWindow.holdingRegister.setTemp4 = -10000; + + } + await _mainWindow.WriteToSerialAsync("DiagnosticsTemp"); + + } + } + } + + private void OnPopupOverlayPointerPressed(object sender, PointerPressedEventArgs e) + { + if (isNegative) + { + targetText.Text = "-" + oldValue.ToString("0.0"); + } + else + { + targetText.Text = "+" + oldValue.ToString("0.0"); + } + keyBoardPopup.IsVisible = false; + } + private void InnerPopupPointerPressed(object? sender, PointerPressedEventArgs e) + { + e.Handled = true; + } + private void OnKeyClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + if ((button.Content=="+"|| button.Content == "-")&& targetText.Text.Length>0) + { + + } + else if((targetText.Text.Length==0 && button.Content == ".")||(targetText.Text.Contains(".")&& button.Content == ".")) + { + + } + else + { + targetText.Text += button.Content; + } + + } + + } + private void OnBackClick(object? sender, RoutedEventArgs e) + { + if (!string.IsNullOrEmpty(targetText.Text)) + { + // Remove the last character from the text box + targetText.Text = targetText.Text.Remove(targetText.Text.Length - 1, 1); + //number = number.Remove(number.Length - 1); + } + + } + private async void EnterClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + bool canEdit = targetButton.Content == "A"; + if (!string.IsNullOrEmpty(targetText.Text)) + { + float number = float.Parse(targetText.Text); + + if (char.IsDigit(targetText.Text[0])) + { + targetText.Text = "+" + number.ToString("0.0"); + } + else + { + targetText.Text = number.ToString("0.0"); + } + + var machine = _machine.ReadMachine(); + if (button.Tag.ToString() == "t1") + { + if (canEdit) + { + _mainWindow.holdingRegister.setTemp1 = (int)(number * 10); + + } + machine.setTemp1 = number; + + } + else if (button.Tag.ToString() == "t2") + { + if (canEdit) + { + _mainWindow.holdingRegister.setTemp2 = (int)(number * 10); + + } + machine.setTemp2 = number; + + + } + else if (button.Tag.ToString() == "t3") + { + if (canEdit) + { + _mainWindow.holdingRegister.setTemp3 = (int)(number * 10); + } + machine.setTemp3 = number; + } + else if (button.Tag.ToString() == "t4") + { + if (canEdit) + { + _mainWindow.holdingRegister.setTemp4 = (int)(number * 10); + } + machine.setTemp4 = number; + } + _machine.UpdateMachine(machine); + getUiElementes(); + if (canEdit) + { + await _mainWindow.WriteToSerialAsync("DiagnosticsEnter"); + + } + + keyBoardPopup.IsVisible = false; + } + + } + + } + private void ShowNumberKeyBoard(object? sender, PointerPressedEventArgs e) + { + if (sender is Border border) + { + var parent = border.Parent as StackPanel; + var brother = parent.Children[0] as Border; + targetButton = brother.Child as Button; + if (border.Tag?.ToString() == "t1") + { + targetText = t1Text; + } + else if (border.Tag?.ToString() == "t2") + { + targetText = t2Text; + } + else if (border.Tag?.ToString() == "t3") + { + targetText = t3Text; + } + else if (border.Tag?.ToString() == "t4") + { + targetText = t4Text; + } + enterBtn.Tag = border.Tag; + + isNegative = targetText.Text.StartsWith("-"); + + oldValue = float.Parse(targetText.Text.Substring(1)); + targetText.Text = ""; + keyBoardPopup.IsVisible = true; + + } + + } + + private async void OnIgnorePidPopupOverlayPointerPressed(object? sender, RoutedEventArgs e) + { + pidPopupOverlay.IsVisible = false; + } + private async void showInnerPid(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + var configratipn = _configration.ReadConfigrationById(button.Tag.ToString()); + pidPopupOverlay.IsVisible = false; + header.Text = button.Content.ToString(); + header.Tag = button.Tag; + + // Set slider values instead of text box values + kpSlider.Value = configratipn.kp; + kiSlider.Value = configratipn.ki; + kdSlider.Value = configratipn.kd; + klSlider.Value = configratipn.kl; + + // Update the display values + kpSliderValue.Text = configratipn.kp.ToString(); + kiSliderValue.Text = configratipn.ki.ToString(); + kdSliderValue.Text = configratipn.kd.ToString(); + klSliderValue.Text = configratipn.kl.ToString(); + + fcThreshold.Text = configratipn.FC_Threshold.ToString("0.0"); + heatConRange.Text = configratipn.HeatConRange.ToString("0.0"); + innerPidPopupOverlay.IsVisible = true; + } + } + private async void OnIgnoreInnerPidPopupOverlayPointerPressed(object? sender, RoutedEventArgs e) + { + innerPidPopupOverlay.IsVisible = false; + pidPopupOverlay.IsVisible = true; + } + private void OnKeyUp(object? sender, KeyEventArgs e) + { + if (sender is TextBox textBox) + { + if (textBox != null && float.TryParse(textBox.Text, out float value)) + { + if (textBox.Name == "heatConRange") + { + if (value > 25.0) + { + textBox.Text = "25.0"; + } + + } + else + { + if (value > 100) + { + textBox.Text = "100"; + } + } + // Check if the value exceeds 100 and reset to 100 if necessary. + + } + } + + } + private async void YesBtnClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + var configration = _configration.ReadConfigrationById(header.Tag.ToString()); + if (configration!=null) + { + // Read values from sliders instead of text boxes + configration.kp = (int)kpSlider.Value; + configration.ki = (int)kiSlider.Value; + configration.kd = (int)kdSlider.Value; + configration.kl = (int)klSlider.Value; + + if (string.IsNullOrEmpty(fcThreshold.Text)) + { + configration.FC_Threshold = 0; + } + else + { + configration.FC_Threshold = float.Parse(fcThreshold.Text); + } + if (string.IsNullOrEmpty(heatConRange.Text)) + { + configration.HeatConRange = 1.0F; + } + else + { + if (float.TryParse(heatConRange.Text, out float value)) + { + if (value<1.0) + { + configration.HeatConRange = 1.0F; + } + else + { + configration.HeatConRange = float.Parse(heatConRange.Text); + } + } + else + { + configration.HeatConRange = 1.0F; + } + } + + _configration.UpdateConfigration(configration); + _mainWindow.reSendHolding = true; + CloseKeyboard(); + + innerPidPopupOverlay.IsVisible = false; + pidPopupOverlay.IsVisible = true; + } + } + } + private void CloseKeyboard() + { + try + { + if (_keyboardProcess != null) + { + // Kill the keyboard process + _keyboardProcess.Kill(); + _keyboardProcess.Dispose(); + _keyboardProcess = null; + + // Force kill any remaining keyboard processes + var processKill = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = "killall", + Arguments = "-9 onboard matchbox-keyboard florence", // Common Linux on-screen keyboards + UseShellExecute = false, + CreateNoWindow = true + } + }; + processKill.Start(); + processKill.WaitForExit(1000); + processKill.Dispose(); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error closing keyboard: {ex.Message}"); + } + } + private (string? fileName, string args) GetKeyboardCommand() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + return ("osk.exe", ""); + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + return ("onboard", ""); // or "florence", "matchbox-keyboard" + return (null, ""); + } + private async void OnTextBoxFocused(object? sender, PointerPressedEventArgs e) + { + if (_keyboardProcess is { HasExited: false }) + return; + + var (fileName, args) = GetKeyboardCommand(); + if (fileName is null) + return; + + _keyboardProcess = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = fileName, + Arguments = args, + UseShellExecute = true, + WorkingDirectory = "/usr/bin" + }, + EnableRaisingEvents = true + }; + + + try + { + _keyboardProcess.Start(); + + + + Dispatcher.UIThread.Post(() => + { + if (sender is Border border) + { + var textbox = border.Child as TextBox; + textbox.SelectionStart = 0; + textbox.SelectionEnd = textbox.Text?.Length ?? 0; + } + }); + + } + catch + { + // fail silently if keyboard not found + } + } + private void OnTextInput(object? sender, TextInputEventArgs e) + { + if (sender is TextBox textBox) + { + string newText = textBox.Text + e.Text; + if (!Regex.IsMatch(newText, @"^\d*\.?\d*$")) + { + e.Handled = true; + } + } + } + private void OnTextInputOnlyInteager(object? sender, TextInputEventArgs e) + { + if (sender is TextBox textBox) + { + string newText = textBox.Text + e.Text; + if (!Regex.IsMatch(newText, @"^\d*$")) + { + e.Handled = true; + } + } + } + private async void showPidPopUp(object? sender, RoutedEventArgs e) + { + pidPopupOverlay.IsVisible = true; + + } + + + private void getUiElementes() + { + var error = _error.ReadErrorSettings()[0]; + + if (error.phaseNumber == 1) + { + phaseContainer.Background = Avalonia.Media.Brushes.Gray; + phaseContainer.IsEnabled = false; + } + else + { + phaseContainer.Background = Brush.Parse("#E6E6E6"); + phaseContainer.IsEnabled = true; + } + + flagRectangles = this.GetLogicalDescendants() + .OfType() + .Where(cb => cb.Classes.Contains("flag")) + .ToList(); + + InputesElements = this.GetLogicalDescendants() + .OfType() + .Where(c => c.Classes.Contains("in") && (c is Grid || c is Ellipse)) + .ToList(); + MotoreState = this.GetLogicalDescendants() + .OfType() + .Where(c => c.Classes.Contains("motorState") && (c is Grid || c is Ellipse)) + .ToList(); + hvoOutPuts = this.GetLogicalDescendants() + .OfType() + .Where(c => c.Classes.Contains("hvo") && (c is Grid || c is Ellipse)) + .ToList(); + lvoOutPuts = this.GetLogicalDescendants() + .OfType() + .Where(c => c.Classes.Contains("lvo") && (c is Grid||c is StackPanel || c is Ellipse)) + .ToList(); + var machine=_machine.ReadMachine(); + t1Text.Text = char.IsDigit(machine.setTemp1.ToString()[0])?"+"+ machine.setTemp1.ToString(): machine.setTemp1.ToString(); + t2Text.Text = char.IsDigit(machine.setTemp2.ToString()[0]) ? "+" + machine.setTemp2.ToString() : machine.setTemp2.ToString(); + t3Text.Text = char.IsDigit(machine.setTemp3.ToString()[0]) ? "+" + machine.setTemp3.ToString() : machine.setTemp3.ToString(); + t4Text.Text = char.IsDigit(machine.setTemp4.ToString()[0]) ? "+" + machine.setTemp4.ToString() : machine.setTemp4.ToString(); + + + } + private void setDefaultSettings() + { + var stackPanel = _mainWindow.HomeTrack.Parent as StackPanel; + _mainWindow.minimizeBtn.IsVisible = false; + + if (_isFromManualControl) + { + // Special UI setup when called from ManualControl + _mainWindow.HomeTrack.IsVisible = true; + _mainWindow.HomePolygon.Stroke = Avalonia.Media.Brushes.Black; + _mainWindow.RecipeSelTrack.IsVisible = false; + _mainWindow.RunInterfaceTrack.IsVisible = false; + _mainWindow.RecipePanelTrack.IsVisible = true; + _mainWindow.RecipePanelPolygon.Stroke = Avalonia.Media.Brushes.Black; + _mainWindow.RecipeEditTrack.IsVisible = false; + _mainWindow.SettingTrack.IsVisible = false; + _mainWindow.AdvanceSettingsTrack.IsVisible = false; + _mainWindow.ManualControlTrack.IsVisible = true; + _mainWindow.ManualControlPolygon.Stroke = Avalonia.Media.Brushes.Black; + } + else + { + // Original logic for other callers + //Set Track Up + _mainWindow.HomeTrack.IsVisible = true; + //_mainWindow.HomePolygon.Stroke = Avalonia.Media.Brushes.Black; + _mainWindow.RecipeSelTrack.IsVisible = false; + _mainWindow.RunInterfaceTrack.IsVisible = false; + _mainWindow.RecipePanelTrack.IsVisible = false; + _mainWindow.RecipeEditTrack.IsVisible = false; + if (_isAdvSettings) + { + _mainWindow.SettingTrack.IsVisible = false; + _mainWindow.AdvanceSettingsTrack.IsVisible = true; + _mainWindow.AdvanceSettingsPolygon.Stroke = Avalonia.Media.Brushes.Black; + + } + else + { + _mainWindow.SettingTrack.IsVisible = true; + _mainWindow.SettingPolygon.Stroke = Avalonia.Media.Brushes.Black; + _mainWindow.AdvanceSettingsTrack.IsVisible = false; + + } + } + + _mainWindow.DiagnosticsTrack.IsVisible = true; + _mainWindow.DiagnosticsPolygon.Stroke = Brush.Parse("#A4275D"); + // Remove the button from its current position + stackPanel.Children.Remove(_mainWindow.DiagnosticsTrack); + + // Add it back at the end of the StackPanel + stackPanel.Children.Add(_mainWindow.DiagnosticsTrack); + + _mainWindow.TitleBtn.IsVisible = false; + + _mainWindow.TitleBtn.IsVisible = true; + _mainWindow.Title.Text = "DMC7A"; + //Set Footer + _mainWindow.footerMsg.IsVisible = true; + _mainWindow.footerMsg.Text= "Read Values, And Control Outputs Manually"; + _mainWindow.footerMsg.Foreground= Brush.Parse("#A4275D"); + _mainWindow.footer.Background = Avalonia.Media.Brushes.WhiteSmoke; + _mainWindow.footerDate.Text = DateTime.Now.ToString("dd/MM/yyyy"); + _mainWindow.footerTime.Text = DateTime.Now.ToString("hh:mm tt"); + _mainWindow.footerDateContainer.IsVisible = true; + _mainWindow.footerStartBtn.IsVisible = false; + _mainWindow.adminBtns.IsVisible = false; + } + + // KP Slider and Button Event Handlers + private void KpSliderValueChanged(object? sender, RoutedEventArgs e) + { + if (kpSliderValue != null && sender is Slider slider) + { + kpSliderValue.Text = ((int)slider.Value).ToString(); + } + } + + private void KpMinusClick(object? sender, RoutedEventArgs e) + { + if (kpSlider.Value > kpSlider.Minimum) + { + kpSlider.Value--; + } + } + + private void KpPlusClick(object? sender, RoutedEventArgs e) + { + if (kpSlider.Value < kpSlider.Maximum) + { + kpSlider.Value++; + } + } + + // KI Slider and Button Event Handlers + private void KiSliderValueChanged(object? sender, RoutedEventArgs e) + { + if (kiSliderValue != null && sender is Slider slider) + { + kiSliderValue.Text = ((int)slider.Value).ToString(); + } + } + + private void KiMinusClick(object? sender, RoutedEventArgs e) + { + if (kiSlider.Value > kiSlider.Minimum) + { + kiSlider.Value--; + } + } + + private void KiPlusClick(object? sender, RoutedEventArgs e) + { + if (kiSlider.Value < kiSlider.Maximum) + { + kiSlider.Value++; + } + } + + // KD Slider and Button Event Handlers + private void KdSliderValueChanged(object? sender, RoutedEventArgs e) + { + if (kdSliderValue != null && sender is Slider slider) + { + kdSliderValue.Text = ((int)slider.Value).ToString(); + } + } + + private void KdMinusClick(object? sender, RoutedEventArgs e) + { + if (kdSlider.Value > kdSlider.Minimum) + { + kdSlider.Value--; + } + } + + private void KdPlusClick(object? sender, RoutedEventArgs e) + { + if (kdSlider.Value < kdSlider.Maximum) + { + kdSlider.Value++; + } + } + + // KL Slider and Button Event Handlers + private void KlSliderValueChanged(object? sender, RoutedEventArgs e) + { + if (klSliderValue != null && sender is Slider slider) + { + klSliderValue.Text = ((int)slider.Value).ToString(); + } + } + + private void KlMinusClick(object? sender, RoutedEventArgs e) + { + if (klSlider.Value > klSlider.Minimum) + { + klSlider.Value--; + } + } + + private void KlPlusClick(object? sender, RoutedEventArgs e) + { + if (klSlider.Value < klSlider.Maximum) + { + klSlider.Value++; + } + } +} + +============================================================ +FILE: DaireApplication/Views/UserController/Home.axaml +============================================================ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +============================================================ +FILE: DaireApplication/Views/UserController/Recipe.axaml.cs +============================================================ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.Media; +using Avalonia.Threading; +using AvaloniaApplication1.DataBase; +using DaireApplication.Views; +using ReactiveUI; +using System; +using System.Diagnostics; +using System.Linq; +using System.Runtime.InteropServices; +using System.Threading.Tasks; + +namespace DaireApplication; + +public partial class Recipe : UserControl +{ + Button recipeButton = new Button(); + private bool _isLongPress; + + private MainWindow? _mainWindow; + private UserTable? _currentUser; + private RecipeTable _recipeTable=new RecipeTable(); + private Process? _keyboardProcess; + + public Recipe() + { + InitializeComponent(); + + } + public Recipe(MainWindow mainWindow,UserTable currentUser) + { + _currentUser = currentUser; + _mainWindow = mainWindow; + InitializeComponent(); + nameBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true); + updateBorder.AddHandler(InputElement.PointerPressedEvent, OnTextBoxFocused, RoutingStrategies.Tunnel, handledEventsToo: true); + setDefaultSettings(); + addDynamicButtons(); + } + + + private async void OnRecipeClick(object? sender, RoutedEventArgs e) + { + if (_isLongPress) + { + // Reset the flag for future interactions. + _isLongPress = false; + // Ignore this click since a long press was detected. + return; + } + + if (sender is Button button) + { + if (_currentUser.CanEdit) + { + _mainWindow.FindControl("ContentArea").Content = new RecipeEdit(_mainWindow, _currentUser, _recipeTable.ReadRecipesById(button.Name)); + + } + else + { + _mainWindow.FindControl("ContentArea").Content = new Settings(_mainWindow, _currentUser, _recipeTable.ReadRecipesById(button.Name)); + _mainWindow.restBoard = true; + } + + + } + + + + + } + private async void deleteActionClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + deleteMsg.Text = $"You are about to delete {button.Tag}"; + DeletePopupOverlay.IsVisible = true; + + } + + } + private async void UpdateActionClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + var text = recipeButton.Content as TextBlock; + updateInput.Text = $"{text.Text}"; + updatePopupOverlay.IsVisible = true; + + } + + } + private void OnLongRecipeClick(object? sender, RoutedEventArgs e) + { + if (e is HoldingRoutedEventArgs args) + { + if (args.HoldingState == HoldingState.Started) + { + _isLongPress = true; + + if (sender is Button button) + { + var targetText= button.Content as TextBlock; + deleteActionBtn.Tag = targetText.Text; + managePopupOverlay.IsVisible = true; + recipeButton = button; + + //recipeButton = button; + //if (button.Content is TextBlock targetText) + //{ + // deleteMsg.Text = $"You are about to delete {targetText.Text}"; + //} + } + + args.Handled = true; + } + else if (args.HoldingState == HoldingState.Completed) + { + _isLongPress = false; + } + } + } + private void CloseKeyboard() + { + try + { + if (_keyboardProcess != null) + { + // Kill the keyboard process + _keyboardProcess.Kill(); + _keyboardProcess.Dispose(); + _keyboardProcess = null; + + // Force kill any remaining keyboard processes + var processKill = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = "killall", + Arguments = "-9 onboard matchbox-keyboard florence", // Common Linux on-screen keyboards + UseShellExecute = false, + CreateNoWindow = true + } + }; + processKill.Start(); + processKill.WaitForExit(1000); + processKill.Dispose(); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error closing keyboard: {ex.Message}"); + } + } + + public void AttachHandlers(Button button) + { + if (button != null) + { + button.Holding += OnLongRecipeClick; + + button.PointerPressed += (sender, e) => + { + // Simulate a long press on any pointer (mouse or touch) + var point = e.GetPosition(button); + OnLongRecipeClick(sender, new HoldingRoutedEventArgs(HoldingState.Started, point, e.Pointer.Type)); + }; + + button.PointerReleased += (sender, e) => + { + // End simulated long press + var point = e.GetPosition(button); + OnLongRecipeClick(sender, new HoldingRoutedEventArgs(HoldingState.Completed, point, e.Pointer.Type)); + }; + } + } + private async void OnAddRecipeClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + PopupOverlay.IsVisible = true; + } + + } + private async void OnPopupOverlayPointerPressed(object? sender, RoutedEventArgs e) + { + PopupOverlay.IsVisible = false; + + + + } + private async void OnDeletePopupOverlayPointerPressed(object? sender, RoutedEventArgs e) + { + DeletePopupOverlay.IsVisible = false; + managePopupOverlay.IsVisible = false; + updatePopupOverlay.IsVisible = false; + + } + private async void YesBtnClick(object? sender, RoutedEventArgs e) + { + var result = _recipeTable.DeleteRecipe(recipeButton.Name); + if (result) + { + addDynamicButtons(); + DeletePopupOverlay.IsVisible= false; + managePopupOverlay.IsVisible = false; + + } + else + { + + } + + + } + private async void SaveUpdateClick(object? sender, RoutedEventArgs e) + { + if (!_recipeTable.DoesNameExist(updateInput.Text)) + { + var recipe = _recipeTable.ReadRecipesById(recipeButton.Name); + recipe.Name = updateInput.Text; + var result = _recipeTable.UpdateRecipe(recipe); + if (result) + { + addDynamicButtons(); + managePopupOverlay.IsVisible = false; + updatePopupOverlay.IsVisible = false; + CloseKeyboard(); + + + } + else + { + + } + } + else + { + CloseKeyboard(); + await MainWindow.MessageBox.Show(_mainWindow, "this name is already in use", "Error"); + _mainWindow.Topmost = false; + _mainWindow.Focus(); + _mainWindow.Activate(); + + } + + + + } + private void showPopUp(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + recipeButton = button; + button.Foreground = Brush.Parse("#A4275D"); + PopupOverlay.IsVisible = true; + // Append the button's content to the input box + //InputTextBox.Text += button.Content?.ToString(); + } + + } + private async void saveRecipeClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + if (!string.IsNullOrEmpty(NameInput.Text)) + { + if (!_recipeTable.DoesNameExist(NameInput.Text)) + { + RecipeTable data = new RecipeTable(); + data.Name = NameInput.Text; + data.Mixer = false; + data.Fountain = false; + data.MoldHeater = false; + data.Vibration = false; + data.VibHeater = false; + data.Pedal = false; + var result = _recipeTable.AddRecipe(data); + if (result) + { + addDynamicButtons(); + CloseKeyboard(); + NameInput.Text = ""; + PopupOverlay.IsVisible = false; + + } + else + { + + } + } + else + { + CloseKeyboard(); + await MainWindow.MessageBox.Show(_mainWindow, "this name is already in use", "Error"); + _mainWindow.Topmost = false; + _mainWindow.Activate(); + + } + } + + + } + + } + private (string? fileName, string args) GetKeyboardCommand() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + return ("osk.exe", ""); + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + return ("onboard", ""); // or "florence", "matchbox-keyboard" + return (null, ""); + } + private async void OnTextBoxFocused(object? sender, PointerPressedEventArgs e) + { + if (_keyboardProcess is { HasExited: false }) + return; + + var (fileName, args) = GetKeyboardCommand(); + if (fileName is null) + return; + + _keyboardProcess = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = fileName, + Arguments = args, + UseShellExecute = true + }, + EnableRaisingEvents = true + }; + + + try + { + _keyboardProcess.Start(); + + Dispatcher.UIThread.Post(() => + { + if (sender is Border border) + { + var textbox= border.Child as TextBox; + textbox.SelectionStart = 0; + textbox.SelectionEnd = textbox.Text?.Length ?? 0; + } + }); + } + catch + { + // fail silently if keyboard not found + } + } + + private void OnPopupOverlayPointerPressed(object sender, PointerPressedEventArgs e) + { + // Close the popup when clicking outside of it + recipeButton.Foreground = Avalonia.Media.Brushes.Black; + + PopupOverlay.IsVisible = false; + } + + private void setDefaultSettings() + { + + //set recipe title + if (_currentUser.CanEdit) + { + RecipeTitle.Content = "RECIPE EDIT/ADD PANEL"; + } + else + { + RecipeTitle.Content = "RECIPE SELECTION"; + } + //Set Track Up + _mainWindow.HomeTrack.IsVisible = true; + _mainWindow.RecipeSelTrack.IsVisible = false; + _mainWindow.RecipePanelTrack.IsVisible = false; + + + if (_currentUser.CanEdit) + { + _mainWindow.RecipePanelTrack.IsVisible = true; + _mainWindow.RecipePanelPolygon.Stroke = Brush.Parse("#A4275D"); + } + else + { + _mainWindow.RecipeSelTrack.IsVisible = true; + _mainWindow.RecipeSelPolygon.Stroke = Brush.Parse("#A4275D"); + } + //_mainWindow.HomePolygon.Stroke = Avalonia.Media.Brushes.Black; + + _mainWindow.RecipeEditTrack.IsVisible = false; + _mainWindow.RunInterfaceTrack.IsVisible = false; + _mainWindow.SettingTrack.IsVisible = false; + _mainWindow.TitleBtn.IsVisible = false; + _mainWindow.DiagnosticsTrack.IsVisible = false; + _mainWindow.SoftwareTrack.IsVisible = false; + + + //Set Footer + if (_currentUser.CanEdit) + { + _mainWindow.footerMsg.Text = "Long press to delete recipe"; + _mainWindow.footerMsg.IsVisible = true; + _mainWindow.chefBtns.IsVisible = true; + + } + else + { + _mainWindow.footerMsg.Text = "Select a recipe to start"; + _mainWindow.footerMsg.IsVisible = true; + + + } + _mainWindow.ManualControlTrack.IsVisible = false; + + _mainWindow.footerMsg.MaxWidth = 1000; + + _mainWindow.footer.Background = Avalonia.Media.Brushes.WhiteSmoke; + _mainWindow.footerMsg.Foreground = Brush.Parse("#A4275D"); + _mainWindow.footerDate.Text = DateTime.Now.ToString("dd/MM/yyyy"); + _mainWindow.footerTime.Text = DateTime.Now.ToString("hh:mm tt"); + _mainWindow.footerDateContainer.IsVisible = true; + _mainWindow.footerStartBtn.IsVisible = false; + _mainWindow.adminBtns.IsVisible = false; + } + private void addDynamicButtons() + { + var recipes= _recipeTable.ReadRecipes(); + var grid = this.FindControl("DynamicGrid"); + grid.Children.Clear(); + int lastRow = 0; + int lastCol = 0; + int colIndexForExtraData = 0; + int recipeIndex = 0; + + try + { + if (recipes.Count<3) + { + // Add dynamic rows + for (int i = 0; i < (int)Math.Ceiling((double)recipes.Count / 3); i++) // Example: 20 rows + { + lastRow = i; + grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + + // Add content for each column + for (int col = 0; col < recipes.Count; col++) + { + + lastCol = col; + + var text = new TextBlock + { + Padding = new Thickness(10), + Text = recipes[recipeIndex + col].Name, + VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, + HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, + FontSize = 31, + FontWeight=FontWeight.Normal, + Foreground = Avalonia.Media.Brushes.Black + + }; + var button = new Button + { + Width = 210, + Height = 160, + Margin = new Thickness(3), + Content = text, + Name = recipes[recipeIndex + col].Id.ToString(), + CornerRadius = new CornerRadius(10), + Background = Avalonia.Media.Brushes.White, + HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, + VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, + + }; + + button.Click += OnRecipeClick; + + if (_currentUser.CanEdit) + { + //button.Holding += OnLongRecipeClick; + AttachHandlers(button); + //button.DoubleTapped += OnDoubleRecipeClick; + + } + + grid.Children.Add(button); + Grid.SetRow(button, i); + Grid.SetColumn(button, col); + } + recipeIndex += 3; + } + if (_currentUser.CanEdit) + { + var Plus = new TextBlock + { + Padding = new Thickness(10), + Text = "+", + VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, + HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, + FontSize = 100, + Foreground = Brush.Parse("#A4275D") + + }; + var AddButtun = new Button + { + Width = 210, + Height = 160, + Margin = new Thickness(3), + Content = Plus, + CornerRadius = new CornerRadius(10), + Background = Avalonia.Media.Brushes.White, + HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, + VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, + VerticalContentAlignment = Avalonia.Layout.VerticalAlignment.Center, + HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, + Padding = new Thickness(0, 0, 0, 15), + + }; + AddButtun.Click += OnAddRecipeClick; + if (lastCol < 2) + { + grid.Children.Add(AddButtun); + Grid.SetRow(AddButtun, lastRow); + Grid.SetColumn(AddButtun, lastCol + 1); + } + else + { + grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + + grid.Children.Add(AddButtun); + Grid.SetRow(AddButtun, lastRow + 1); + Grid.SetColumn(AddButtun, 0); + } + } + + + + + } + else + { + // Add dynamic rows + for (int i = 0; i < (int)Math.Floor((double)recipes.Count / 3); i++) // Example: 20 rows + { + lastRow = i; + grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + + // Add content for each column + for (int col = 0; col < 3; col++) + { + + + lastCol = col; + + var text = new TextBlock + { + Padding = new Thickness(10), + Text = recipes[recipeIndex + col].Name, + VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, + HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, + FontSize = 31, + FontWeight = FontWeight.Normal, + Foreground = Avalonia.Media.Brushes.Black + + }; + var button = new Button + { + Width = 210, + Height = 160, + Margin = new Thickness(3), + Content = text, + Name = recipes[recipeIndex + col].Id.ToString(), + CornerRadius = new CornerRadius(10), + Background = Avalonia.Media.Brushes.White, + HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, + VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, + + }; + button.Click += OnRecipeClick; + + if (_currentUser.CanEdit) + { + //button.Holding += OnLongRecipeClick; + AttachHandlers(button); + + //button.DoubleTapped += OnDoubleRecipeClick; + + } + + grid.Children.Add(button); + Grid.SetRow(button, i); + Grid.SetColumn(button, col); + } + recipeIndex += 3; + } + for (int i = 0; i < recipes.Count -recipeIndex; i++) + { + var text = new TextBlock + { + Padding = new Thickness(10), + Text = recipes[recipeIndex + i].Name, + VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, + HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, + FontSize = 31, + FontWeight = FontWeight.Normal, + Foreground = Avalonia.Media.Brushes.Black + + }; + var button = new Button + { + Width = 210, + Height = 160, + Margin = new Thickness(3), + Content = text, + Name = recipes[recipeIndex + i].Id.ToString(), + CornerRadius = new CornerRadius(10), + Background = Avalonia.Media.Brushes.White, + HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, + VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, + + }; + button.Click += OnRecipeClick; + + if (_currentUser.CanEdit) + { + //button.Holding += OnLongRecipeClick; + AttachHandlers(button); + + //button.DoubleTapped += OnDoubleRecipeClick; + + } + if (lastCol < 2) + { + lastCol += 1; + + + + + grid.Children.Add(button); + Grid.SetRow(button,lastRow); + Grid.SetColumn(button, lastCol); + } + else + { + + grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + + grid.Children.Add(button); + Grid.SetRow(button, lastRow + 1); + Grid.SetColumn(button, colIndexForExtraData); + colIndexForExtraData += 1; + } + } + if (_currentUser.CanEdit) + { + var Plus = new TextBlock + { + Padding = new Thickness(10), + Text = "+", + VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, + HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, + FontSize = 100, + Foreground = Brush.Parse("#A4275D"), + + + }; + var AddButtun = new Button + { + Width = 210, + Height = 160, + Margin = new Thickness(3), + Content = Plus, + CornerRadius = new CornerRadius(10), + Background = Avalonia.Media.Brushes.White, + VerticalContentAlignment = Avalonia.Layout.VerticalAlignment.Center, + HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, + HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, + VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, + Padding = new Thickness(0,0,0,15), + }; + + AddButtun.Click += OnAddRecipeClick; + + if (lastCol < 2) + { + grid.Children.Add(AddButtun); + Grid.SetRow(AddButtun, lastRow); + Grid.SetColumn(AddButtun, lastCol + 1); + } + else + { + grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + + grid.Children.Add(AddButtun); + Grid.SetRow(AddButtun, lastRow + 1); + Grid.SetColumn(AddButtun, colIndexForExtraData); + } + } + + } + + } + catch (Exception) + { + } + + + + } + + +} + +============================================================ +FILE: DaireApplication/Views/UserController/RecipeEdit.axaml +============================================================ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +============================================================ +FILE: DaireApplication/Views/UserController/RecipeEdit.axaml.cs +============================================================ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.Markup.Xaml; +using Avalonia.Media; +using AvaloniaApplication1.DataBase; +using DaireApplication.Views; +using System; + +namespace DaireApplication; + +public partial class RecipeEdit : UserControl +{ + Button controllButton = new Button(); + private MainWindow? _mainWindow; + private UserTable? _currentUser; + private RecipeTable? _recipeTable; + + + public RecipeEdit() + { + InitializeComponent(); + } + public RecipeEdit(MainWindow mainWindow, UserTable currentUser,RecipeTable recipeTable) + { + _currentUser = currentUser; + _mainWindow = mainWindow; + _recipeTable=recipeTable; + InitializeComponent(); + setDefaultSettings(); + } + + string oldNumber = ""; + private void OnKeyClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + + var StackPanel = controllButton.Content as StackPanel; + var Label = StackPanel.Children; + if (Label[1] is TextBlock targetText) + { + //number += button.Content?.ToString(); + targetText.Text += button.Content ; + } + // Append the button's content to the input box + //InputTextBox.Text += button.Content?.ToString(); + } + + } + private void OnBackClick(object? sender, RoutedEventArgs e) + { + var StackPanel = controllButton.Content as StackPanel; + var Label = StackPanel.Children; + if (Label[1] is TextBlock targetText) + { + if (!string.IsNullOrEmpty(targetText.Text)) + { + // Remove the last character from the text box + targetText.Text = targetText.Text.Remove(targetText.Text.Length -1, 1); + //number = number.Remove(number.Length - 1); + } + } + + } + private void EnterClick(object? sender, RoutedEventArgs e) + { + RecipeTable recipe = new RecipeTable(); + recipe.Id = _recipeTable.Id; + recipe.Mixer = null; + recipe.Fountain = null; + recipe.MoldHeater = null; + recipe.Vibration = null; + recipe.VibHeater = null; + recipe.Pedal = null; + //getting the btn value + var heatingStackPanel = heatingBtn.Content as StackPanel; + var heatingLabel = heatingStackPanel.Children; + var heatingText = heatingLabel[1] as TextBlock; + + var coolingStackPanel = coolingBtn.Content as StackPanel; + var coolingLabel = coolingStackPanel.Children; + var coolingText = coolingLabel[1] as TextBlock; + + + var StackPanel = controllButton.Content as StackPanel; + var Label = StackPanel.Children; + var targetText = Label[1] as TextBlock; + var activeTxt= Label[0] as TextBlock; + switch (activeTxt.Text) + { + case "HEATING:": + if (!string.IsNullOrEmpty(targetText.Text)) + { + int value = Int32.Parse(targetText.Text); + if (value>60) + { + tempErrorMsg.Text = "Heating Tempreature must be lower than 60 �C"; + return; + } + else if (value<40) + { + tempErrorMsg.Text = "Heating Tempreature must be greater than 40 �C"; + return; + + } + else + { + recipe.CoolingGoal = 0; + recipe.PouringGoal = 0; + recipe.HeatingGoal = value; + _recipeTable.UpdateRecipe(recipe); + tempErrorMsg.Text = ""; + heatingBtn.IsEnabled = true; + coolingBtn.IsEnabled = true; + pouringBtn.IsEnabled = true; + PopupOverlay.IsVisible = false; + setDefaultSettings(); + + } + } + break; + case "POURING:": + if (!string.IsNullOrEmpty(targetText.Text)) + { + int value = Int32.Parse(targetText.Text); + if (string.IsNullOrEmpty(heatingText.Text)||string.IsNullOrEmpty(coolingText.Text)) + { + tempErrorMsg.Text = $"Enter heating and cooling tempreature first"; + return; + } + if (value > Int32.Parse(heatingText.Text)) + { + tempErrorMsg.Text = $"Pouring Tempreature must be lower than Heating Tempreatur({heatingText.Text}�C)"; + return; + } + else if (value < Int32.Parse(coolingText.Text)) + { + tempErrorMsg.Text = $"Pouring Tempreature must be greater than Cooling Tempreatur({coolingText.Text}�C)"; + return; + + + } + else + { + recipe.HeatingGoal = 0; + recipe.CoolingGoal = 0; + recipe.PouringGoal = value; + _recipeTable.UpdateRecipe(recipe); + tempErrorMsg.Text = ""; + heatingBtn.IsEnabled = true; + coolingBtn.IsEnabled = true; + pouringBtn.IsEnabled = true; + PopupOverlay.IsVisible = false; + setDefaultSettings(); + + } + } + break; + case "COOLING:": + if (!string.IsNullOrEmpty(targetText.Text)) + { + int value = Int32.Parse(targetText.Text); + if (value > 40) + { + tempErrorMsg.Text = "Cooling Tempreature must be lower than 40 �C"; + return; + + } + else if (value < 20) + { + tempErrorMsg.Text = "Cooling Tempreature must be greater than 20 �C"; + return; + + } + else + { + recipe.HeatingGoal = 0; + recipe.PouringGoal = 0; + recipe.CoolingGoal = value; + _recipeTable.UpdateRecipe(recipe); + tempErrorMsg.Text = ""; + heatingBtn.IsEnabled = true; + coolingBtn.IsEnabled = true; + pouringBtn.IsEnabled = true; + PopupOverlay.IsVisible = false; + setDefaultSettings(); + + } + } + break; + } + + + + + + } + private void showPopUp(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + heatingBtn.IsEnabled = false; + coolingBtn.IsEnabled = false; + pouringBtn.IsEnabled = false; + button.IsEnabled = true; + var StackPanel = button.Content as StackPanel; + var Label = StackPanel.Children; + if (Label[1] is TextBlock targetText) + { + oldNumber = targetText.Text; + } + controllButton = button; + PopupOverlay.IsVisible = true; + } + + } + private void OnPopupOverlayPointerPressed(object sender, PointerPressedEventArgs e) + { + // Close the popup when clicking outside of it + //controllButton.Foreground = Avalonia.Media.Brushes.Black; + var StackPanel = controllButton.Content as StackPanel; + var Label = StackPanel.Children; + if (Label[1] is TextBlock targetText) + { + //number += button.Content?.ToString(); + targetText.Text = oldNumber; + } + tempErrorMsg.Text = ""; + heatingBtn.IsEnabled = true; + coolingBtn.IsEnabled = true; + pouringBtn.IsEnabled = true; + + PopupOverlay.IsVisible = false; + } + + private void setDefaultSettings() + { + //set Values + _recipeTable = _recipeTable.ReadRecipesById(_recipeTable.Id.ToString()); + heatingValue.Text = _recipeTable?.HeatingGoal == 0 ? "" : _recipeTable?.HeatingGoal.ToString(); + coolingValue.Text = _recipeTable?.CoolingGoal == 0 ? "" : _recipeTable?.CoolingGoal.ToString(); + pouringValue.Text = _recipeTable?.PouringGoal == 0 ? "" : _recipeTable?.PouringGoal.ToString(); + + //Set Track Up + _mainWindow.HomeTrack.IsVisible = true; + //_mainWindow.HomePolygon.Stroke = Avalonia.Media.Brushes.Black; + _mainWindow.RecipePanelTrack.IsVisible = true; + _mainWindow.RecipePanelPolygon.Stroke = Avalonia.Media.Brushes.Black; + _mainWindow.RecipeEditTrack.IsVisible = true; + _mainWindow.RecipeEditPolygon.Stroke = Brush.Parse("#A4275D"); + _mainWindow.RunInterfaceTrack.IsVisible = false; + _mainWindow.RecipeSelTrack.IsVisible = false; + _mainWindow.SettingTrack.IsVisible = false; + _mainWindow.DiagnosticsTrack.IsVisible = false; + + _mainWindow.TitleBtn.IsVisible = true; + _mainWindow.Title.Text = _recipeTable.Name; + + //Set Footer + _mainWindow.footerMsg.Text = "Select the tempereture to edit it"; + _mainWindow.footer.Background = Avalonia.Media.Brushes.WhiteSmoke; + _mainWindow.footerMsg.Foreground = Brush.Parse("#A4275D"); + _mainWindow.footerDate.Text = DateTime.Now.ToString("dd/MM/yyyy"); + _mainWindow.footerTime.Text = DateTime.Now.ToString("hh:mm tt"); + _mainWindow.footerDateContainer.IsVisible = true; + _mainWindow.footerStartBtn.IsVisible = false; + _mainWindow.adminBtns.IsVisible = false; + } +} + +============================================================ +FILE: DaireApplication/Views/UserController/Settings.axaml +============================================================ + + + + + + + + + + + + + + + + + Mixer + Delay: + 120 + + + + + + + + Pedal OFF: + + 120 + + + + + + + + + Fountain Delay: + 120 + + Target Temp: + 120 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +============================================================ +FILE: DaireApplication/Views/UserController/Settings.axaml.cs +============================================================ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.Documents; +using Avalonia.Controls.Shapes; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.Markup.Xaml; +using Avalonia.Media; +using AvaloniaApplication1.DataBase; +using DaireApplication.DataBase; +using DaireApplication.ViewModels; +using DaireApplication.Views; +using System; +using System.Drawing; +using System.Reflection.PortableExecutable; +using System.Threading; + +namespace DaireApplication; + +public partial class Settings : UserControl +{ + Button controllButton = new Button(); + private MainWindow? _mainWindow; + private UserTable? _currentUser; + public RecipeTable? _recipeTable; + private MachineTable _machine; + public string ActiveColor { get; set; } = "#A4275D"; + public string PassiveColor { get; set; } = "#666666"; + + public Settings() + { + InitializeComponent(); + } + public Settings(MainWindow mainWindow, UserTable currentUser,RecipeTable recipeTable) + { + _currentUser = currentUser; + _mainWindow = mainWindow; + _recipeTable = recipeTable; + _machine = new MachineTable(); + _machine = _machine.ReadMachine(); + + InitializeComponent(); + + setDefaultSettings(); + + setDafaultValues(); + mixerBtn.Click += _mainWindow.MotorClick; + fountainBtn.Click += _mainWindow.FountainClick; + } + + + private void toggelOnOffClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + var StackPanel = button.Content as StackPanel; + var Label = StackPanel.Children; + var underLine = Label[2] as Avalonia.Controls.Shapes.Rectangle; + var titelLable = Label[0] as Label; + + + + if (Label[1] is Label targetLable) + { + if (targetLable.Content == "ON") + { + if (titelLable.Content == "MOLD HEATER") + { + _mainWindow.moldHeaterMotor = 0; + } + if (titelLable.Content == "VIBRATION") + { + _mainWindow.vibrationMotor = 0; + + } + if (titelLable.Content == "VIB. HEATER") + { + _mainWindow.vibHeaterMotor = 0; + + } + + + } + else + { + if (titelLable.Content == "MOLD HEATER") + { + _mainWindow.moldHeaterMotor = 1; + } + if (titelLable.Content == "VIBRATION") + { + _mainWindow.vibrationMotor = 1; + + } + if (titelLable.Content == "VIB. HEATER") + { + _mainWindow.vibHeaterMotor = 1; + + } + + } + } + } + + } + private void PedalBtn(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + RecipeTable recipe = new RecipeTable(); + recipe.Id = _recipeTable.Id; + var StackPanel = button.Content as StackPanel; + var Label = StackPanel.Children; + var underLine = Label[1] as Avalonia.Controls.Shapes.Rectangle; + if (Label[0] is TextBlock targetLable) + { + if (targetLable.Text == "AUTO") + { + if (_mainWindow.pedalOnTimer!=null ) + { + _mainWindow.pedalOnTimer.Change(Timeout.Infinite, Timeout.Infinite); + _mainWindow.pedalOnTimer = null; + _mainWindow.pedalOnSeconds = 0; + + + } + if (_mainWindow.pedalOffTimer!=null) + { + _mainWindow.pedalOffTimer.Change(Timeout.Infinite, Timeout.Infinite); + _mainWindow.pedalOffTimer = null; + _mainWindow.pedalOffSeconds = 0; + } + _mainWindow.pedalMotor = 0; + + targetLable.Text = "MANUAL"; + underLine.Fill = Brush.Parse("#666666"); + PedalAutoContainer.IsEnabled = false; + recipe.Pedal = true; + } + else + { + _mainWindow.pedalMotor = 1; + _mainWindow.pedalState = -1; + _mainWindow.setPedalTimerOnce = 1; + _mainWindow.pedalOnSeconds = 0; + _mainWindow.pedalOffSeconds = 0; + targetLable.Text = "AUTO"; + underLine.Fill = Brush.Parse("#A4275D"); + PedalAutoContainer.IsEnabled = true; + recipe.Pedal = false; + + } + _recipeTable.UpdateRecipe(recipe); + } + } + + } + private void adjustPedalTime(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + RecipeTable recipe = new RecipeTable(); + recipe.Id = _recipeTable.Id; + + if (button.Classes[0].ToString()== "PedalOff") + { + if (button.Content == "−") + { + if (Int32.Parse(PedalOffTime.Text) > 0) + { + PedalOffTime.Text = (Int32.Parse(PedalOffTime.Text) - 1).ToString(); + } + + } + else if (button.Content == "+") + { + + PedalOffTime.Text = (Int32.Parse(PedalOffTime.Text) + 1).ToString(); + } + recipe.PedalOffTime = Int32.Parse(PedalOffTime.Text); + _recipeTable.UpdateRecipe(recipe); + } + else + { + if (button.Content == "−") + { + if (Int32.Parse(PedalOnTime.Text) > 0) + { + PedalOnTime.Text = (Int32.Parse(PedalOnTime.Text) - 1).ToString(); + } + + } + else if (button.Content == "+") + { + if (int.TryParse(PedalOnTime.Text, out int value)) + { + if (value < 9) + { + PedalOnTime.Text = (value + 1).ToString(); + } + } + } + recipe.PedalOnTime = Int32.Parse(PedalOnTime.Text); + _recipeTable.UpdateRecipe(recipe); + } + _recipeTable = _recipeTable.ReadRecipesById(_recipeTable.Id.ToString()); + + } + + } + + private async void OnIgnorePopupOverlayPointerPressed(object? sender, RoutedEventArgs e) + { + DeletePopupOverlay.IsVisible = false; + + + + } + private async void HideTempErrorPopUp(object? sender, RoutedEventArgs e) + { + _mainWindow.pauseTimer = false; + _mainWindow.pauseTempTracking = true; + tempErrorPopupOverlay.IsVisible = false; + } + private async void YesBtnClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + if (DeletePopupOverlay.Tag=="home") + { + + _mainWindow.resetAll(); + // rest the board + _mainWindow.restBoard = true; + _mainWindow.UserName.Content = "Select User"; + _mainWindow.footerMsg.Text = ""; + _mainWindow.ContentArea.Content = new Home(_mainWindow); + } + else if (DeletePopupOverlay.Tag == "recipeSel") + { + _mainWindow.resetAll(); + // rest the board + _mainWindow.restBoard = true; + _mainWindow.footerMsg.Text = ""; + _mainWindow.ContentArea.Content = new Recipe(_mainWindow, Program.currentUser); + } + } + + + + } + private async void ErrorYesBtnClick(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + //_mainWindow.pause = true; + //_mainWindow.pauseTempTracking = true; + //_mainWindow.pauseTimer = true; + + // stop the recipe + _mainWindow.startRecipe = 0; + _mainWindow.Heating = 0; + _mainWindow.cooling = 0; + _mainWindow.pouring = 0; + _mainWindow.PumbOn = -1; + _mainWindow.pedalMotor = -1; + if (_mainWindow.heatingTimer != null) + { + _mainWindow.heatingTimer.Change(Timeout.Infinite, Timeout.Infinite); + _mainWindow.heatingSeconds = 0; + } + if (_mainWindow.coolingTimer != null) + { + _mainWindow.coolingTimer.Change(Timeout.Infinite, Timeout.Infinite); + _mainWindow.coolingSeconds = 0; + } + if (_mainWindow.pouringTimer != null) + { + _mainWindow.pouringTimer.Change(Timeout.Infinite, Timeout.Infinite); + _mainWindow.pouringSeconds = 0; + } + var fount = _mainWindow._mapping.Find(x => x.Name.ToLower() == "Pump".ToLower()); + if (fount != null) + { + if (fount.BitNumbers.Count > 0) + { + foreach (var bit in fount.BitNumbers) + { + + _mainWindow.holdingRegister.motor &= (ushort)~(1 << bit); + } + } + } + _mainWindow.holdingRegister.setTemp1 = -10000; + _mainWindow.holdingRegister.setTemp2 = -10000; + _mainWindow.holdingRegister.setTemp3 = -10000; + _mainWindow.holdingRegister.setTemp4 = -10000; + await _mainWindow.WriteToSerialAsync("ErrorYesBtnClick"); + tempErrorPopupOverlay.IsVisible = false; + _mainWindow.footerMsg.Text = "Recipe Stoped"; + _mainWindow.recipeStartBtn.Content = "START RECIPE"; + } + } + + + + private void setDefaultSettings() + { + //Set Track Up + _mainWindow.HomeTrack.IsVisible = true; + //_mainWindow.HomePolygon.Stroke = Avalonia.Media.Brushes.Black; + _mainWindow.RecipeSelTrack.IsVisible = true; + _mainWindow.RecipeSelPolygon.Stroke = Avalonia.Media.Brushes.Black; + _mainWindow.RunInterfaceTrack.IsVisible = true; + _mainWindow.RunInterfacePolygon.Stroke = Brush.Parse("#A4275D"); + _mainWindow.RecipePanelTrack.IsVisible = false; + _mainWindow.RecipeEditTrack.IsVisible = false; + _mainWindow.SettingTrack.IsVisible = false; + _mainWindow.DiagnosticsTrack.IsVisible = false; + _mainWindow.TitleBtn.IsVisible = true; + _mainWindow.Title.Text = _recipeTable.Name; + + //Set Footer + _mainWindow.footerMsg.Text = "Ready"; + _mainWindow.footerMsg.MaxWidth = 500; + _mainWindow.footer.Background = Avalonia.Media.Brushes.WhiteSmoke; + _mainWindow.footerMsg.Foreground = Avalonia.Media.Brushes.Green; + _mainWindow.footerDate.Text = DateTime.Now.ToString("dd/MM/yyyy"); + _mainWindow.footerTime.Text = DateTime.Now.ToString("hh:mm tt"); + _mainWindow.footerDateContainer.IsVisible = true; + _mainWindow.footerStartBtn.IsVisible = true; + _mainWindow.adminBtns.IsVisible = false; + } + private void setDafaultValues() + { + //Recipe Settings + heatingValue.Content = _recipeTable.HeatingGoal; + coolingValue.Content = _recipeTable.CoolingGoal; + pouringValue.Content = _recipeTable.PouringGoal; + //tankTemp + TankTempValue.Content = _recipeTable?.TankTemp; + //mixer + var mixerChildren= MixerSP.Children; + var mixerLable = mixerChildren[1] as Label; + mixerLable.Content = _recipeTable.Mixer.Value ? "ON" : "OFF"; + var mixerUnderLine = mixerChildren[2] as Avalonia.Controls.Shapes.Rectangle; + mixerUnderLine.Fill = _recipeTable.Mixer.Value ? Brush.Parse(ActiveColor) : Brush.Parse(PassiveColor); + //pedal + var pedalChildren = PedalSP.Children; + var pedalText = pedalChildren[0] as TextBlock; + var pedalUnderLine = pedalChildren[1] as Avalonia.Controls.Shapes.Rectangle; + if (_recipeTable.Pedal.Value) + { + pedalText.Text = "MANUAL"; + pedalUnderLine.Fill = Brush.Parse(PassiveColor); + PedalAutoContainer.IsEnabled = false; + } + else + { + pedalText.Text = "AUTO"; + pedalUnderLine.Fill = Brush.Parse(ActiveColor); + PedalAutoContainer.IsEnabled = true; + } + PedalOffTime.Text = _recipeTable.PedalOffTime.ToString(); + PedalOnTime.Text = _recipeTable.PedalOnTime.ToString(); + //fountain Temp + FountainTempValue.Content = _recipeTable?.FountainTemp; + //fountain + var fountainChildren = FountainSP.Children; + var fountainLable = fountainChildren[1] as Label; + fountainLable.Content = _recipeTable.Fountain.Value ? "ON" : "OFF"; + var fountainUnderLine = fountainChildren[2] as Avalonia.Controls.Shapes.Rectangle; + fountainUnderLine.Fill = _recipeTable.Fountain.Value ? Brush.Parse(ActiveColor) : Brush.Parse(PassiveColor); + //mold Heater + var moldHeaterChildren = MoldHeaterSP.Children; + var moldHeaterLable = moldHeaterChildren[1] as Label; + moldHeaterLable.Content = _recipeTable.MoldHeater.Value ? "ON" : "OFF"; + var moldHeaterUnderLine = moldHeaterChildren[2] as Avalonia.Controls.Shapes.Rectangle; + moldHeaterUnderLine.Fill = _recipeTable.MoldHeater.Value ? Brush.Parse(ActiveColor) : Brush.Parse(PassiveColor); + // vibration + var vibrationChildren = VibrationSP.Children; + var vibrationLable = vibrationChildren[1] as Label; + vibrationLable.Content = _recipeTable.Vibration.Value ? "ON" : "OFF"; + var vibrationUnderLine = vibrationChildren[2] as Avalonia.Controls.Shapes.Rectangle; + vibrationUnderLine.Fill = _recipeTable.Vibration.Value ? Brush.Parse(ActiveColor) : Brush.Parse(PassiveColor); + // vib heater + var vibHeaterChildren = VibHeaterSP.Children; + var vibHeaterLable = vibHeaterChildren[1] as Label; + vibHeaterLable.Content = _recipeTable.VibHeater.Value ? "ON" : "OFF"; + var vibHeaterUnderLine = vibHeaterChildren[2] as Avalonia.Controls.Shapes.Rectangle; + vibHeaterUnderLine.Fill = _recipeTable.VibHeater.Value ? Brush.Parse(ActiveColor) : Brush.Parse(PassiveColor); + + + } +} + +============================================================ +FILE: DaireApplication/Views/UserController/Software.axaml +============================================================ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + PASSWORDS RESET + + + + + + + + + + + + + + + + + + + + + + + + + + SCREEN SETTINGS + + + + + + + + + + + + + + + + + + + + + + + + + + COM SETTINGS + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + Bound Rate: + + + + + + + + + + + + + + + + + + Stop Bits: + + + + + + + + + + + + Parity: + + + + + + + + + + + Packets Sending Intervals : + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Warning Limit : + + + + + + + Error Limit : + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + V0.6 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +============================================================ +FILE: DaireApplication/Views/MainWindow.axaml.cs +============================================================ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.Shapes; +using Avalonia.Interactivity; +using Avalonia.Layout; +using Avalonia.Media; +using Avalonia.Threading; +using AvaloniaApplication1.ViewModels; +using DaireApplication.DataBase; +using DaireApplication.Loops; +using DaireApplication.ViewModels; +using DynamicData; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; +using System.IO.Ports; +using System.Linq; +using System.Management; +using System.Runtime.InteropServices; +using System.Security.Cryptography.X509Certificates; +using System.Threading; +using System.Threading.Tasks; +using static DaireApplication.ViewModels.Error; + +namespace DaireApplication.Views +{ + public partial class MainWindow : Window + { + List buffer = new List(); + public ModBusMaster _modBusMaster = new ModBusMaster(); + public MachineTable _machine = new MachineTable(); + public ConfigrationTable _config = new ConfigrationTable(); + public List _configrations = new List(); + public Mapping _map = new Mapping(); + public ScreeenTable _screeen = new(); + public ErrorSettingsTable _error = new(); + public List _mapping = new List(); + public static bool isOff { get; set; } + const double deadZone = 1.5; // Changeable based on stability needs + bool shouldRunFountain = false; + public readonly SemaphoreSlim _keepSendingLock = new(1, 1); + + public SerialPort _port { get; set; } + private static Thread monitorThread; + private static Thread screenThread; + private static Thread touchThread; + private static Thread internetThread; + private static Thread InteractiveUIThread; + private static Thread serialThread; + public bool serialThreadRunning = true; + public bool isRunning = true; + public bool restBoard { get; set; } + public bool sendConfig { get; set; } = true; + public bool reSendHolding { get; set; } + public bool dontResetOutPuts { get; set; } + + bool allBitsOn = false; + bool allPedalBitsOn = false; + public int pedalState { get; set; } = -1; + public int pedalStateChanged { get; set; } = -1; + public float recipeHeatingGoal { get; set; } + public float recipeCoolingGoal { get; set; } + public float recipePouringGoal { get; set; } + + public string ActiveColor { get; set; } = "#A4275D"; + public string PassiveColor { get; set; } = "#666666"; + //Pre Heating + public bool isFlashPreHeating { get; set; } = false; + public bool isReadingTemp { get; set; } = true; + public int startPreHeating { get; set; } = -1; + public int writingMaxTemp { get; set; } = -1; + + //Mixer Motor + private Timer mixerTimer; + private Timer preMixerTimer; + + private static int mixerSeconds = 1; + private static int preMixerSeconds = 1; + public bool setMixerTimerOnce { get; set; } = false; + public bool checkMixerTWT_HWTH { get; set; } = false; + public bool isMixerMotorOn { get; set; } = false; + public int startMixerMotor { get; set; } = -1; + public int startMixerMotorFlashing { get; set; } = -1; + public int sendComMixerMotor { get; set; } = -1; + + //Fountain Motor + private Timer fountainTimer; + private Timer fountainPauseTimer; + private Timer noChoiceChoosenTimer; + + private static int fountainSeconds = 1; + private static int fountainPauseSeconds = 1; + private static int noChoiceChoosenSeconds = 0; + public bool setFountainTimerOnce { get; set; } = false; + public bool checkFountainTMT_PMT { get; set; } = false; + public bool isFountainMotorOn { get; set; } = false; + public int startFountainMotor { get; set; } = -1; + public int startFountainMotorFlashing { get; set; } = -1; + public int sendComFountainMotor { get; set; } = -1; + + public double comTankTemp { get; set; } = 0; + public double comFountainTemp { get; set; } = 0; + public double comPumpTemp { get; set; } = 0; + + //MOLD HEATER(off:0,on:1) , VIBRATION(off:0,on:1) , VIB. HEATER(off:0,on:1) + public int moldHeaterMotor { get; set; } = -1; + public int vibrationMotor { get; set; } = -1; + public int vibHeaterMotor { get; set; } = -1; + + //Pedal(manual=0,auto=1) + public int pedalMotor { get; set; } = -1; + + //Recipe Start + + public int startRecipe { get; set; } = 0; + public int sendComTankTemp { get; set; } = -1; + //phase 1 heating + public int Heating { get; set; } = -1; + public int sendComHeating { get; set; } = -1; + public int setHeatingTimerOnce { get; set; } = -1; + public Timer heatingTimer; + public int heatingSeconds { get; set; } = 0; + //phase 2 cooling + public int cooling { get; set; } = -1; + public int sendComCooling { get; set; } = -1; + public int setCoolingTimerOnce { get; set; } = -1; + public Timer coolingTimer; + public int coolingSeconds { get; set; } = 0; + + //phase 3 pouring + public int pouring { get; set; } = -1; + public int sendComPouring { get; set; } = -1; + public int setPouringTimerOnce { get; set; } = -1; + public Timer pouringTimer; + public int pouringSeconds { get; set; } = 0; + + //start the pumb + public int PumbOn { get; set; } = -1; + public Timer pedalOnTimer; + public Timer pedalOffTimer; + public int pedalOnSeconds { get; set; } = 0; + public int pedalOffSeconds { get; set; } = 0; + // 1 turn off ,0 turn on + public int setPedalTimerOnce { get; set; } = -1; + + //Board + + public bool resetPort { get; set; } = false; + public bool keepSendingFlag { get; set; } = false; + + public DateTime lastActivity = DateTime.Now; + + public ScreeenTable screenData = new(); + public static List errors = new(); + public bool pause { get; set; } + public bool unPause { get; set; } + public bool isPaused { get; set; } + public bool pauseTimer { get; set; } + public bool pauseTempTracking { get; set; } + public string warningMessage { get; set; } + + public HoldingRegister holdingRegister = new HoldingRegister(); + + public bool turnOnFountainMotor { get; set; } + public bool stopRecipeFlag { get; set; } + + public Timer stopMixerTimer; + public int stopMixerSecondes { get; set; } + public Timer stopFountainTimer; + public int stopFountainSecondes { get; set; } + + public DateTime _lastPacketSendTime = DateTime.MinValue; + public byte[] inputesResponse = new byte[] { 0xFF }; + + // Replace isWriting flag with async method + public TaskCompletionSource _writeCompletionSource = new TaskCompletionSource(); + public Task WriteToSerialAsync(string caller) + { + _writeCompletionSource = new TaskCompletionSource(); + // Optionally log or store the caller for debugging + Debug.WriteLine($"WriteToSerialAsync called by: {caller}"); + return _writeCompletionSource.Task; + } + public void SetWriteComplete(bool success = true) + { + _writeCompletionSource?.TrySetResult(success); + } + + + + + public MainWindow() + { + InitializeComponent(); + // Hide cursor using unclutter + try + { + var process = new System.Diagnostics.Process(); + process.StartInfo.FileName = "unclutter"; + process.StartInfo.Arguments = "-idle 0"; // Hide immediately + process.StartInfo.UseShellExecute = false; + process.StartInfo.CreateNoWindow = true; + process.Start(); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to start unclutter: {ex.Message}"); + } + + ContentArea.Content = new Home(this); + this.Closing += OnClosingWindow; + + _machine = _machine.ReadMachine(); + + _configrations = _config.ReadConfigrations(); + _mapping = _map.ReadMappings(); + serialThread = new Thread(() => serialThreadLoop.SendViaSerial(this)) + { + IsBackground = true + }; + serialThread.Start(); + internetThread = new Thread(() => CheckInterNetLoop.CheckInterNet(this)) + { + IsBackground = true + }; + internetThread.Start(); + + screenThread = new Thread(() => ScreenLoop.Screen(this)) + { + IsBackground = true + }; + screenThread.Start(); + InteractiveUIThread = new Thread(() => InteractiveUILoop.Flashing(this)) + { + IsBackground = true + }; + InteractiveUIThread.Start(); + touchThread = new Thread(() => TouchLoop.Touch(this)) + { + IsBackground = true + }; + touchThread.Start(); + monitorThread = new Thread(() => MonitorPortsLoop()) + { + IsBackground = true, + Priority = ThreadPriority.Highest + }; + monitorThread.Start(); + + + } + + private async void MonitorPortsLoop() + { + byte[] tankeResponse = new byte[256]; + var fountainResponse = new byte[256]; + + double tankBottomTempValue = -1; + double tankWallTempValue = -1; + double pumpTempValue = -1; + double fountainTempValue = -1; + var tankBottom = _mapping.Find(x => x.Name == "Tank Bottom Temp"); + var tankWall = _mapping.Find(x => x.Name == "Tank Wall Temp"); + var pump = _mapping.Find(x => x.Name == "Pump Temp"); + var fountain = _mapping.Find(x => x.Name == "Fountain Temp"); + + + static List ToBinary(int number) + { + return Convert.ToString(number, 2) + .PadLeft(16, '0') + .Reverse() + .Select(c => c == '1') + .ToList(); + } + + + while (true) + { + if (isRunning) + { + Dispatcher.UIThread.Post(() => + { + footerDate.Text = DateTime.Now.ToString("dd/MM/yyyy"); + footerTime.Text = DateTime.Now.ToString("hh:mm tt"); + }); + screenData = _screeen.ReadScreens()?[0]; + + try + { + if (!SerialPort.GetPortNames().Contains(screenData.port)) + { + if (_port != null && _port.IsOpen) + { + _port.Close(); + } + _port = null; + Dispatcher.UIThread.Post(() => + { + errors.Clear(); + footerMsg.Text = "Not Connected:Port Name Not Found"; + //Debug.WriteLine("port name not found"); + footerMsg.Foreground = Avalonia.Media.Brushes.DarkRed; + footerMsg.IsVisible = true; + }); + } + else + { + if (resetPort) + { + Debug.WriteLine("Port reset initiated"); + resetAll(); + if (_port != null && _port.IsOpen) + { + Debug.WriteLine("Closing existing port"); + _port.Close(); + } + _port = null; + if (ConnectToSerialPort()) + { + Debug.WriteLine("Port reconnected successfully"); + Dispatcher.UIThread.Post(() => + { + //Conntected + footerMsg.Text = "Connected"; + footerMsg.IsVisible = true; + sendConfig = true; + }); + } + else + { + Debug.WriteLine("Failed to reconnect port"); + Dispatcher.UIThread.Post(() => + { + errors.Clear(); + footerMsg.Text = "Not Connected"; + footerMsg.IsVisible = true; + }); + } + resetPort = false; + Debug.WriteLine("Port reset completed"); + } + if (_port == null) + { + // Connect to the found device + if (!ConnectToSerialPort()) + { + + Dispatcher.UIThread.Post(() => + { + errors.Clear(); + footerMsg.Text = "Not Connected"; + + }); + } + else + { + serialThreadRunning = true; + + sendConfig = true; + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Connected"; + }); + } + } + else + { + try + { + if (!_port.IsOpen) + { + _port.Open(); + } + + + List inputValues = new List(); + + if (isReadingTemp) + { + if (!_port.IsOpen) + { + _port.Open(); + } + // reading inputes + + var requstReadingInputs = await _modBusMaster.ReadInputRegisters(0, 18); + + + + if (inputesResponse.Length != 1 && inputesResponse[0] != 0xFF) + { + var result = inputesResponse.Skip(3).Take(inputesResponse.Count() - 5).ToArray(); + for (int i = 0; i < result.Length; i = i + 2) + { + inputValues.Add(((result[i] << 8) | result[i + 1])); + } + var brdFlags = ToBinary(inputValues[0]); + var inputes = ToBinary(inputValues[1]); + + // Errors + try + { + // Grid Vac + if (inputValues[2] > 220 * 1.1 || inputValues[3] > 220 * 1.1 || inputValues[4] > 220 * 1.1) + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.GridVACHigh) == null) + { + errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.GridVACHigh + }); + } + } + else + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.GridVACHigh) != null) + { + errors.First(x => x.Condition == Error.GridCondition.GridVACHigh).isDeleted = true; + } + + } + if (inputValues[2] < 220 * 0.9 || inputValues[3] < 220 * 0.9 || inputValues[4] < 220 * 0.9) + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.GridVACLow) == null) + { + errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.GridVACLow + }); + } + + } + else + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.GridVACLow) != null) + { + errors.First(x => x.Condition == Error.GridCondition.GridVACLow).isDeleted = true; + } + } + //// Grid Freq + _error = _error.ReadErrorSettings()[0]; + if (inputValues[17] > (_error.gridFreq * 10) * 1.1) + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.GridFrequencyHigh) == null) + { + errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.GridFrequencyHigh + }); + } + + } + else + { + + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.GridFrequencyHigh) != null) + { + errors.First(x => x.Condition == Error.GridCondition.GridFrequencyHigh).isDeleted = true; + } + } + if (inputValues[17] < (_error.gridFreq * 10) * 0.9) + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.GridFrequencyLow) == null) + { + errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.GridFrequencyLow + }); + } + } + else + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.GridFrequencyLow) != null) + { + errors.First(x => x.Condition == Error.GridCondition.GridFrequencyLow).isDeleted = true; + } + } + //// Ext Power + if (brdFlags[3]) + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.NoExternalPower) == null) + { + errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.NoExternalPower + }); + } + } + else + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.NoExternalPower) != null) + { + errors.First(x => x.Condition == Error.GridCondition.NoExternalPower).isDeleted = true; + } + } + //// missing Phase + if (brdFlags[5] && _error.ReadErrorSettings()[0].phaseNumber == 3) + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.MissingPhase) == null) + { + errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.MissingPhase + }); + } + } + else + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.MissingPhase) != null) + { + errors.First(x => x.Condition == Error.GridCondition.MissingPhase).isDeleted = true; + } + } + //// Phase sequence + if (brdFlags[4] && _error.ReadErrorSettings()[0].phaseNumber == 3) + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.PhaseSequence) == null) + { + errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.PhaseSequence + }); + } + } + else + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.PhaseSequence) != null) + { + errors.First(x => x.Condition == Error.GridCondition.PhaseSequence).isDeleted = true; + } + } + //com port1 + if (brdFlags[1]) + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.ComPort1) == null) + { + errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.ComPort1 + }); + } + } + else + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.ComPort1) != null) + { + errors.First(x => x.Condition == Error.GridCondition.ComPort1).isDeleted = true; + } + } + //com port2 + if (brdFlags[2]) + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.ComPort2) == null) + { + errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.ComPort2 + }); + } + } + else + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.ComPort2) != null) + { + errors.First(x => x.Condition == Error.GridCondition.ComPort2).isDeleted = true; + } + } + //hi curr neut + if (brdFlags[6]) + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.HiCurrNeut) == null) + { + errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.HiCurrNeut + }); + } + } + else + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.HiCurrNeut) != null) + { + errors.First(x => x.Condition == Error.GridCondition.HiCurrNeut).isDeleted = true; + } + } + //hi curr mot1 + if (brdFlags[7]) + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.HiCurrMot1) == null) + { + errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.HiCurrMot1 + }); + } + } + else + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.HiCurrMot1) != null) + { + errors.First(x => x.Condition == Error.GridCondition.HiCurrMot1).isDeleted = true; + } + } + //hi curr mot2 + if (brdFlags[8]) + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.HiCurrMot2) == null) + { + errors.Add(new Error + { + errorDate = DateTime.Now, + Condition = Error.GridCondition.HiCurrMot2 + }); + } + } + else + { + if (errors.FirstOrDefault(x => x.Condition == Error.GridCondition.HiCurrMot2) != null) + { + errors.First(x => x.Condition == Error.GridCondition.HiCurrMot2).isDeleted = true; + } + } + } + catch (Exception) + { + + } + + + Dispatcher.UIThread.Post(async () => + { + if (ContentArea.Content is Diagnostics diagnostics) + { + //Board Falgs + foreach (var item in diagnostics.flagRectangles) + { + if (brdFlags[int.Parse(item.Tag.ToString())]) + { + item.Fill = Brush.Parse(diagnostics.RedColor); + } + else + { + item.Fill = Brush.Parse(diagnostics.GrayColor); + + } + } + //power Inputes + diagnostics.ph1.Text = inputValues[2].ToString(); + diagnostics.ph2.Text = inputValues[3].ToString(); + diagnostics.ph3.Text = inputValues[4].ToString(); + + diagnostics.i_nut.Text = (inputValues[5] / 10.0).ToString("0.0"); + diagnostics.gridFreq.Text = (inputValues[17] / 10.0).ToString("0.0"); + // Inputes + foreach (var item in diagnostics.InputesElements.OfType().ToList()) + { + var text = item.Children[0] as TextBlock; + var border = item.Children[1] as Border; + if (inputes[int.Parse(item.Tag.ToString())]) + { + + text.Text = "ACTIVE"; + border.Background = Brush.Parse(diagnostics.PinkColor); + diagnostics.InputesElements.OfType().ToList().Find(x => x.Tag.ToString() == item.Tag.ToString()).Fill = Brush.Parse(diagnostics.GreenColor); + + } + else + { + text.Text = "PASSIVE"; + border.Background = Brush.Parse(diagnostics.GrayColor); + diagnostics.InputesElements.OfType().ToList().Find(x => x.Tag.ToString() == item.Tag.ToString()).Fill = Brush.Parse(diagnostics.GrayColor); + + + } + } + //Analog + diagnostics.an1.Text = inputValues[12].ToString(); + diagnostics.an2.Text = inputValues[13].ToString(); + //Temp + diagnostics.t1.Text = ((short)inputValues[8] / 10f).ToString("0.0"); + diagnostics.t2.Text = ((short)inputValues[9] / 10f).ToString("0.0"); + diagnostics.t3.Text = ((short)inputValues[10] / 10f).ToString("0.0"); + diagnostics.t4.Text = ((short)inputValues[11] / 10f).ToString("0.0"); + //InternalTemp + diagnostics.internalTemp.Text = (inputValues[15] / 10.0).ToString("0.0"); + diagnostics.hsTemp.Text = (inputValues[14] / 10.0).ToString("0.0"); + if (inputValues[16] > 40) + { + diagnostics.extPowerLed.Fill = Brush.Parse(diagnostics.RedColor); + } + else + { + diagnostics.extPowerLed.Fill = Brush.Parse(diagnostics.GrayColor); + } + diagnostics.ExtPwr.Text = (inputValues[16] / 10.0).ToString("0.0"); + + } + if (ContentArea.Content is Settings settings) + { + if (settings.pedalStateTxt.Text != "AUTO") + { + var pedal = _mapping.Find(x => x.Name.ToLower() == "pedal"); + + ushort registerValue = (ushort)inputValues[1]; + if (allBitsOn != pedal.BitNumbers.All(bit => (registerValue & (1 << bit)) != 0)) + { + allBitsOn = pedal.BitNumbers.All(bit => (registerValue & (1 << bit)) != 0); + } + if (!allBitsOn) + { + settings.pedalUnderLine.Fill = Brush.Parse(settings.PassiveColor); + + } + else + { + settings.pedalUnderLine.Fill = Brush.Parse(settings.ActiveColor); + + } + + } + if (startFountainMotorFlashing != 1) + { + //fountain + + var fount = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + + + if (allBitsOn != fount.BitNumbers.All(bit => (holdingRegister.motor & (1 << bit)) != 0)) + { + allBitsOn = fount.BitNumbers.All(bit => (holdingRegister.motor & (1 << bit)) != 0); + } + var fountainLable = settings.FountainSP.Children[1] as Avalonia.Controls.Label; + var fontainRectangel = settings.FountainSP.Children[2] as Avalonia.Controls.Shapes.Rectangle; + if (!allBitsOn) + { + fountainLable.Content = "OFF"; + fountainLable.Foreground = Brush.Parse("#ff231f20"); + fontainRectangel.Fill = Brush.Parse(PassiveColor); + //isFountainMotorOn = false; + } + else + { + fountainLable.Content = "ON"; + fountainLable.Foreground = Brush.Parse("#ff231f20"); + fontainRectangel.Fill = Brush.Parse(ActiveColor); + //isFountainMotorOn = true; + } + } + + if (startMixerMotorFlashing != 1) + { + //mixer + var mixer = _mapping.Find(x => x.Name.ToLower() == "Mixer".ToLower()); + + + if (allBitsOn != mixer.BitNumbers.All(bit => (holdingRegister.motor & (1 << bit)) != 0)) + { + allBitsOn = mixer.BitNumbers.All(bit => (holdingRegister.motor & (1 << bit)) != 0); + } + var mixerLable = settings.MixerSP.Children[1] as Avalonia.Controls.Label; + var mixerRectangel = settings.MixerSP.Children[2] as + Avalonia.Controls.Shapes.Rectangle; + if (!allBitsOn) + { + mixerLable.Content = "OFF"; + mixerLable.Foreground = Brush.Parse("#ff231f20"); + mixerRectangel.Fill = Brush.Parse(PassiveColor); + //isMixerMotorOn = false; + } + else + { + mixerLable.Content = "ON"; + mixerLable.Foreground = Brush.Parse("#ff231f20"); + mixerRectangel.Fill = Brush.Parse(ActiveColor); + //isMixerMotorOn = true; + } + } + + } + if (ContentArea.Content is ManualControl manual) + { + manual.pumbRealTemp.Text = comPumpTemp.ToString("0.0"); + manual.ChocolateRealTemp.Text = comFountainTemp.ToString("0.0"); + manual.tankWallRealTemp.Text = tankWallTempValue.ToString("0.0"); + manual.pumbRealTemp.Text = comTankTemp.ToString("0.0"); + } + }); + _mapping = _map.ReadMappings(); + //reading Tank Bottom + tankBottom = _mapping.Find(x => x.Name == "Tank Bottom Temp"); + + if (tankBottom != null) + { + if (tankBottom.BitNumbers.Count > 0) + { + tankBottomTempValue = 0; + foreach (var item in tankBottom.BitNumbers) + { + tankBottomTempValue += ((short)inputValues[item] / 10f); + } + tankBottomTempValue /= tankBottom.BitNumbers.Count; + tankBottomTempValue = Math.Round(tankBottomTempValue, 1); + } + } + //reading Tank Wall + tankWall = _mapping.Find(x => x.Name == "Tank Wall Temp"); + + if (tankWall != null) + { + if (tankWall.BitNumbers.Count > 0) + { + tankWallTempValue = 0; + foreach (var item in tankWall.BitNumbers) + { + tankWallTempValue += ((short)inputValues[item] / 10f); + } + tankWallTempValue /= tankWall.BitNumbers.Count; + tankWallTempValue = Math.Round(tankWallTempValue, 1); + } + } + //reading Pump + pump = _mapping.Find(x => x.Name == "Pump Temp"); + + if (pump != null) + { + if (pump.BitNumbers.Count > 0) + { + pumpTempValue = 0; + + foreach (var item in pump.BitNumbers) + { + pumpTempValue += ((short)inputValues[item] / 10f); + } + pumpTempValue /= pump.BitNumbers.Count; + pumpTempValue = Math.Round(pumpTempValue, 1); + } + } + //reading Fountain + fountain = _mapping.Find(x => x.Name == "Fountain Temp"); + if (fountain != null) + { + if (fountain.BitNumbers.Count > 0) + { + fountainTempValue = 0; + + foreach (var item in fountain.BitNumbers) + { + fountainTempValue += ((short)inputValues[item] / 10f); + } + fountainTempValue /= fountain.BitNumbers.Count; + fountainTempValue = Math.Round(fountainTempValue, 1); + } + } + Dispatcher.UIThread.Post(() => + { + if (tankBottomTempValue == -1 && tankWallTempValue == -1) + { + if (ContentArea.Content is Settings) + { + footerMsg.Text = "No Tank Data To Read"; + tankBottomTempValue = 0; + tankWallTempValue = 0; + } + } + else + { + //comTankTemp = tankBottomTempValue < tankWallTempValue ? tankBottomTempValue : tankWallTempValue; + comTankTemp = tankBottomTempValue; + comTankTemp = comTankTemp == -1 ? 0 : comTankTemp; + } + if (pumpTempValue == -1) + { + if (ContentArea.Content is Settings) + { + footerMsg.Text = "No Pump Data To Read"; + pumpTempValue = 0; + } + + } + else + { + comPumpTemp = pumpTempValue; + } + if (fountainTempValue == -1) + { + if (ContentArea.Content is Settings) + { + footerMsg.Text = "No Chocolate Data To Read"; + fountainTempValue = 0; + } + + } + else + { + comFountainTemp = fountainTempValue; + } + if (ContentArea.Content is Settings result) + { + if (result.TankTempValue.Content?.ToString() != comTankTemp.ToString() || result.FountainTempValue.Content?.ToString() != comFountainTemp.ToString()) + { + result.TankTempValue.Content = (comTankTemp).ToString("0.0"); + result.FountainTempValue.Content = (comFountainTemp).ToString("0.0"); + } + } + //if (comTankTemp >= _machine.TankMaxHeat && comFountainTemp >= _machine.PumbMaxHeat) + //{ + // if (preMixerTimer==null) + // { + // preMixerTimer = new Timer(PreMixerTimer, null, 0, 1000); + // } + // mixerSeconds++; + //} + //else + //{ + // if (preMixerTimer != null) + // { + // preMixerTimer.Change(Timeout.Infinite, Timeout.Infinite); + // preMixerTimer = null; + // } + + + //} + } + ); + } + + //read mot val + + if (inputValues.Count != 0) + { + + Dispatcher.UIThread.Post(async () => + { + if (ContentArea.Content is Diagnostics diagnostics) + { + diagnostics.curr1.Text = (inputValues[6] / 10.0).ToString("0.0"); + diagnostics.curr2.Text = (inputValues[7] / 10.0).ToString("0.0"); + } + }); + } + + } + + + //Pre Heating + if (startPreHeating == 1) + { + List setTempValues = new List(); + setTempValues.AddRange([holdingRegister.setTemp1, holdingRegister.setTemp2, holdingRegister.setTemp3, holdingRegister.setTemp4]); + + if (writingMaxTemp == 1) + { + tankBottom = _mapping.Find(x => x.Name == "Tank Bottom Temp"); + if (tankBottom != null) + { + if (tankBottom.BitNumbers.Count > 0) + { + foreach (var item in tankBottom.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.TankMaxHeat * 10; + } + + } + + + } + tankWall = _mapping.Find(x => x.Name == "Tank Wall Temp"); + if (tankWall != null) + { + if (tankWall.BitNumbers.Count > 0) + { + foreach (var item in tankWall.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.TankMaxHeat * 10; + } + + } + + + } + + pump = _mapping.Find(x => x.Name == "Pump Temp"); + if (pump != null) + { + if (pump.BitNumbers.Count > 0) + { + foreach (var item in pump.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.PumbMaxHeat * 10; + + } + } + + + } + fountain = _mapping.Find(x => x.Name == "Fountain Temp"); + if (fountain != null) + { + if (fountain.BitNumbers.Count > 0) + { + foreach (var item in fountain.BitNumbers) + { + setTempValues[item - 8] = -10000; + + } + } + + + } + + holdingRegister.setTemp1 = setTempValues[0]; + holdingRegister.setTemp2 = setTempValues[1]; + holdingRegister.setTemp3 = setTempValues[2]; + holdingRegister.setTemp4 = setTempValues[3]; + await WriteToSerialAsync("PreHeating"); + + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + + result.recipeSettings.IsEnabled = false; + isFlashPreHeating = true; + footerMsg.Text = "Pre-Heating Active"; + } + }); + writingMaxTemp = -1; + } + + } + if (startPreHeating == 0) + { + List setTempValues = new List(); + setTempValues.AddRange([holdingRegister.setTemp1, holdingRegister.setTemp2, holdingRegister.setTemp3, holdingRegister.setTemp4]); + if (writingMaxTemp == 0) + { + tankBottom = _mapping.Find(x => x.Name == "Tank Bottom Temp"); + if (tankBottom != null) + { + if (tankBottom.BitNumbers.Count > 0) + { + foreach (var item in tankBottom.BitNumbers) + { + setTempValues[item - 8] = -10000; + + } + + } + + } + + tankWall = _mapping.Find(x => x.Name == "Tank Wall Temp"); + if (tankWall != null) + { + if (tankWall.BitNumbers.Count > 0) + { + foreach (var item in tankWall.BitNumbers) + { + setTempValues[item - 8] = -10000; + } + + } + + + } + + pump = _mapping.Find(x => x.Name == "Pump Temp"); + if (pump != null) + { + if (pump.BitNumbers.Count > 0) + { + foreach (var item in pump.BitNumbers) + { + setTempValues[item - 8] = -10000; + + } + } + + + } + fountain = _mapping.Find(x => x.Name == "Fountain Temp"); + if (fountain != null) + { + if (fountain.BitNumbers.Count > 0) + { + foreach (var item in fountain.BitNumbers) + { + setTempValues[item - 8] = -10000; + + } + } + + + } + + holdingRegister.setTemp1 = setTempValues[0]; + holdingRegister.setTemp2 = setTempValues[1]; + holdingRegister.setTemp3 = setTempValues[2]; + holdingRegister.setTemp4 = setTempValues[3]; + await WriteToSerialAsync("PreHeating"); + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + result.recipeSettings.IsEnabled = true; + if (!stopRecipeFlag) + { + footerMsg.Text = "Pre-Heating Stopped"; + + } + } + }); + writingMaxTemp = -1; + } + + } + //Mixer Motor + //Mixer Motorf + if (checkMixerTWT_HWTH) + { + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + recipeHeatingGoal = result._recipeTable.HeatingGoal; + recipeCoolingGoal = result._recipeTable.CoolingGoal; + recipePouringGoal = result._recipeTable.PouringGoal; + } + + if ((comTankTemp >= _machine.TankMaxHeat - screenData.warningLimit) && (comTankTemp <= _machine.TankMaxHeat + screenData.warningLimit)) + { + if (startMixerMotor != 1) + { + if (mixerTimer == null) + { + if (mixerSeconds == 1) + { + mixerSeconds = _machine.MixerDelay; + } + mixerTimer = new Timer(MixerTimer, null, 0, 1000); + //setMixerTimerOnce = false; + } + } + } + + else if (comTankTemp <= recipeCoolingGoal - 3 && startMixerMotor == 1) + { + if (startMixerMotor != 0) + { + if (stopMixerTimer == null) + { + stopMixerSecondes = 5; + stopMixerTimer = new Timer(StopMixerTimer, null, 0, 1000); + } + } + startMixerMotorFlashing = 1; + } + else if (startMixerMotor != 1) + { + if (startMixerMotor != 0) + { + sendComMixerMotor = 0; + } + startMixerMotorFlashing = 1; + } + }); + } + if (!checkMixerTWT_HWTH) + { + if (sendComMixerMotor == 0 && startMixerMotorFlashing == 0) + { + startMixerMotor = -1; + var mixer = _mapping.Find(x => x.Name.ToLower() == "Mixer".ToLower()); + if (mixer != null) + { + if (mixer.BitNumbers.Count > 0) + { + //turn the motor off and make the button stable + + + foreach (var bit in mixer.BitNumbers) + { + holdingRegister.motor &= (ushort)~(1 << bit); + } + await WriteToSerialAsync("Mixer Off due Clicking"); + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + var motorLable = result.MixerSP.Children[1] as Avalonia.Controls.Label; + var motorRectangel = result.MixerSP.Children[2] as + Avalonia.Controls.Shapes.Rectangle; + motorLable.Content = "OFF"; + motorLable.Foreground = Brush.Parse("#ff231f20"); + motorRectangel.Fill = Brush.Parse(PassiveColor); + if (startRecipe != 1 && !stopRecipeFlag) + { + footerMsg.Text = "Mixer is OFF"; + } + } + }); + sendComMixerMotor = -1; + startMixerMotorFlashing = -1; + } + } + } + } + if (startMixerMotorFlashing == 1) + { + if (sendComMixerMotor == 0) + { + //turn the motor off + startMixerMotor = 0; + + var mixer = _mapping.Find(x => x.Name.ToLower() == "Mixer".ToLower()); + if (mixer != null) + { + if (mixer.BitNumbers.Count > 0) + { + //turn the motor off and make the button stable + + foreach (var bit in mixer.BitNumbers) + { + + holdingRegister.motor &= (ushort)~(1 << bit); + } + await WriteToSerialAsync("Mixer Off due to drop in temp"); + Dispatcher.UIThread.Post(() => + { + if (startRecipe != 1) + { + footerMsg.Text = "waiting for tank target temperature"; + } + }); + sendComMixerMotor = -1; + } + } + } + } + if (startMixerMotorFlashing == 0 && sendComMixerMotor == 1 && !isPaused) + { + startMixerMotor = 1; + //turn the motor on and make the button stable + var mixer = _mapping.Find(x => x.Name.ToLower() == "Mixer".ToLower()); + if (mixer != null) + { + if (mixer.BitNumbers.Count > 0) + { + foreach (var bit in mixer.BitNumbers) + { + + holdingRegister.motor |= (ushort)(1 << bit); + } + await WriteToSerialAsync("Mixer On"); + + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + var motorLable = result.MixerSP.Children[1] as Avalonia.Controls.Label; + var motorRectangel = result.MixerSP.Children[2] as + Avalonia.Controls.Shapes.Rectangle; + motorLable.Content = "ON"; + motorLable.Foreground = Brush.Parse("#ff231f20"); + motorRectangel.Fill = Brush.Parse(ActiveColor); + if (startRecipe != 1) + { + footerMsg.Text = "Temperature is OK,Mixer is on"; + } + //if (comTankTemp < result._recipeTable.PouringGoal || + // comFountainTemp < result._recipeTable.PouringGoal) + //{ + // mixerSeconds = 1; + // //checkTMT_PMT = true; + // setMixerTimerOnce = true; + //} + //else + //{ + // //checkTMT_PMT = true; + // setMixerTimerOnce = true; + //} + + } + + }); + + + startMixerMotorFlashing = -1; + sendComMixerMotor = -1; + + } + } + + + } + + //Fountain Motor + if (checkFountainTMT_PMT) + { + Dispatcher.UIThread.Post(() => + { + + if (ContentArea.Content is Settings result) + { + recipeHeatingGoal = result._recipeTable.HeatingGoal; + recipeCoolingGoal = result._recipeTable.CoolingGoal; + recipePouringGoal = result._recipeTable.PouringGoal; + + + } + + if ((comPumpTemp >= _machine.PumbMaxHeat - screenData.warningLimit) && (comPumpTemp <= _machine.PumbMaxHeat + screenData.warningLimit)) // check the temp and make it stop only if it below cooling temp - 3 degrees + { + if (startFountainMotor != 1) + { + if (fountainTimer == null) + { + if (fountainSeconds == 1) + { + fountainSeconds = _machine.PumbDelay; + } + fountainTimer = new Timer(FountainTimer, null, 0, 1000); + //setFountainTimerOnce = false; + } + } + } + + else if (comPumpTemp <= recipeCoolingGoal - 3 && startFountainMotor == 1) + { + if (startFountainMotor != 0) + { + if (stopFountainTimer == null) + { + stopFountainSecondes = 5; + stopFountainTimer = new Timer(StopFountainTimer, null, 0, 1000); + } + } + startFountainMotorFlashing = 1; + } + else if (startFountainMotor != 1) + { + if (startFountainMotor != 0) + { + sendComFountainMotor = 0; + } + startFountainMotorFlashing = 1; + } + + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + if (startFountainMotor != 1 && fountainTimer == null) + { + if (!result.fountainDelayCounter.Text.Equals(comPumpTemp.ToString("0.0"))) + { + result.fountainDelayTxt.Text = "Current Temp:"; + result.fountainDelayCounter.Text = comPumpTemp.ToString("0.0"); + result.fountainTargetTxt.Text = "Target Temp:"; + result.fountainTagetTemp.Text = _machine.PumbMaxHeat.ToString("0.0"); + result.fountainDelayTxt.IsVisible = true; + result.fountainDelayCounter.IsVisible = true; + result.fountainTargetTxt.IsVisible = true; + result.fountainTagetTemp.IsVisible = true; + } + + } + } + + }); + }); + } + if (!checkFountainTMT_PMT) + { + if (sendComFountainMotor == 0 && startFountainMotorFlashing == 0) + { + startFountainMotor = -1; + var fount = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + if (fount != null) + { + if (fount.BitNumbers.Count > 0) + { + //turn the motor off and make the button stable + foreach (var bit in fount.BitNumbers) + { + holdingRegister.motor &= (ushort)~(1 << bit); + } + await WriteToSerialAsync("Fountain Off due to click"); + //waitting for 10 sec before pause + if (fountainPauseTimer == null && startRecipe == 1 && (Heating == 1 || heatingTimer != null || cooling == 1 || coolingTimer != null || pouring == 1 || pouringTimer != null + )) + { + fountainPauseSeconds = 10; + fountainPauseTimer = new Timer(FountainPauseTimer, null, 0, 1000); + } + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + result.fountainDelayCounter.Text = "-1"; + var fountainLable = result.FountainSP.Children[1] as Avalonia.Controls.Label; + var fontainRectangel = result.FountainSP.Children[2] as + Avalonia.Controls.Shapes.Rectangle; + fountainLable.Content = "OFF"; + fountainLable.Foreground = Brush.Parse("#ff231f20"); + fontainRectangel.Fill = Brush.Parse(PassiveColor); + if (startRecipe != 1 && !stopRecipeFlag) + { + footerMsg.Text = "Chocolate is OFF"; + } + stopRecipeFlag = false; + } + }); + + + sendComFountainMotor = -1; + startFountainMotorFlashing = -1; + } + } + + } + } + if (startFountainMotorFlashing == 1) + { + if (sendComFountainMotor == 0) + { + startFountainMotor = 0; + + //turn the motor off + var fount = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + if (fount != null) + { + if (fount.BitNumbers.Count > 0) + { + foreach (var bit in fount.BitNumbers) + { + + holdingRegister.motor &= (ushort)~(1 << bit); + } + await WriteToSerialAsync("Fountain Off due to drop in temp"); + //pause the recipe if it started + //waitting for 10 sec before pause + if (fountainPauseTimer == null && startRecipe == 1 && (Heating == 1 || heatingTimer != null || cooling == 1 || coolingTimer != null || pouring == 1 || pouringTimer != null + )) + { + fountainPauseSeconds = 10; + fountainPauseTimer = new Timer(FountainPauseTimer, null, 0, 1000); + } + + Dispatcher.UIThread.Post(() => + { + if (startRecipe == 1 && (Heating == 1 || cooling == 1 || pouring == 1)) + { + //footerMsg.Text = "Recipe Paused... waiting for target temperature"; + } + else if (startRecipe != 1) + { + footerMsg.Text = "waiting for pump target temperature"; + + } + }); + //checkTMT_PMT = true; + sendComFountainMotor = -1; + } + } + + } + } + if (startFountainMotorFlashing == 0 && sendComFountainMotor == 1 && errors.Count == 0 && !isPaused) + { + startFountainMotor = 1; + //turn the motor on and make the button stable + var fount = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + if (fount != null) + { + if (fount.BitNumbers.Count > 0) + { + foreach (var bit in fount.BitNumbers) + { + holdingRegister.motor |= (ushort)(1 << bit); + } + await WriteToSerialAsync("Fountain On"); + if (isPaused) + { + unPause = true; + } + //if (startRecipe == 1 && (Heating == 10 || cooling == 10 || pouring == 10)) + //{ + // if (Heating == 10) + // { + // Heating = 1; + // sendComHeating = 1; + // } + // else if (cooling == 10) + // { + // cooling = 1; + // sendComCooling = 1; + // } + // else if (pouring == 10) + // { + // pouring = 1; + // sendComPouring = 1; + // } + //} + if (fountainPauseTimer != null) + { + fountainPauseTimer = null; + fountainPauseSeconds = 10; + } + Dispatcher.UIThread.Post(async () => + { + if (ContentArea.Content is Settings result) + { + var fountainLable = result.FountainSP.Children[1] as Avalonia.Controls.Label; + var fountainRectangel = result.FountainSP.Children[2] as + Avalonia.Controls.Shapes.Rectangle; + fountainLable.Content = "ON"; + fountainLable.Foreground = Brush.Parse("#ff231f20"); + fountainRectangel.Fill = Brush.Parse(ActiveColor); + if (startRecipe == 1 && (Heating == 1 || cooling == 1 || pouring == 1)) + { + if (Heating == 1) + { + footerMsg.Text = "Heating phase"; + + + } + else if (cooling == 1) + { + footerMsg.Text = "Cooling phase"; + + } + else if (pouring == 1) + { + footerMsg.Text = "Prepare for pouring"; + } + } + else if (startRecipe != 1) + { + footerMsg.Text = "Temperature is OK,Chocolate is on"; + } + //if (comTankTemp < result._recipeTable.PouringGoal || + // comFountainTemp < result._recipeTable.PouringGoal) + //{ + // fountainSeconds = 1; + // setFountainTimerOnce = true; + //} + //else + //{ + // setFountainTimerOnce = true; + //} + } + }); + + startFountainMotorFlashing = -1; + sendComFountainMotor = -1; + } + } + + } + + if (moldHeaterMotor == 0) // off MOLD HEATER + { + var moldHeater = _mapping.Find(x => x.Name == "Mold Heater"); + if (moldHeater != null) + { + if (moldHeater.BitNumbers.Count > 0) + { + foreach (var bit in moldHeater.BitNumbers) + { + holdingRegister.lvOut &= (ushort)~(1 << bit); + } + await WriteToSerialAsync("MoldHeater"); + + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + var StackPanel = result.moldHeaterBtn.Content as StackPanel; + var Label = StackPanel.Children; + var underLine = Label[2] as Avalonia.Controls.Shapes.Rectangle; + var targetLable = Label[1] as Label; + targetLable.Content = "OFF"; + underLine.Fill = Brush.Parse("#666666"); + } + else if (ContentArea.Content is ManualControl manual) + { + manual.MoldHeaterStatus.Text = "OFF"; + manual.MoldHeaterUnderline.Fill = Brush.Parse("#666666"); + } + }); + + } + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Admin"; + }); + } + } + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Programming Team"; + }); + } + + + moldHeaterMotor = -1; + } + else if (moldHeaterMotor == 1) // on MOLD HEATER + { + var moldHeater = _mapping.Find(x => x.Name == "Mold Heater"); + if (moldHeater != null) + { + if (moldHeater.BitNumbers.Count > 0) + { + foreach (var bit in moldHeater.BitNumbers) + { + + holdingRegister.lvOut |= (ushort)(1 << bit); + } + await WriteToSerialAsync("MoldHeater"); + + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + var StackPanel = result.moldHeaterBtn.Content as StackPanel; + var Label = StackPanel.Children; + var underLine = Label[2] as Avalonia.Controls.Shapes.Rectangle; + var targetLable = Label[1] as Label; + targetLable.Content = "ON"; + underLine.Fill = Brush.Parse("#A4275D"); + } + else if (ContentArea.Content is ManualControl manual) + { + manual.MoldHeaterStatus.Text = "ON"; + manual.MoldHeaterUnderline.Fill = Brush.Parse("#A4275D"); + } + }); + + } + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Admin"; + }); + } + } + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Programming Team"; + }); + } + + moldHeaterMotor = -1; + } + if (vibrationMotor == 0) // off VIBRATION + { + var vibrator = _mapping.Find(x => x.Name == "Vibrator"); + + if (vibrator != null) + { + if (vibrator.BitNumbers.Count > 0) + { + + foreach (var bit in vibrator.BitNumbers) + { + holdingRegister.hvOut &= (ushort)~(1 << bit); + } + await WriteToSerialAsync("Vibrator"); + + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + var StackPanel = result.vibrationBtn.Content as StackPanel; + var Label = StackPanel.Children; + var underLine = Label[2] as Avalonia.Controls.Shapes.Rectangle; + var targetLable = Label[1] as Label; + targetLable.Content = "OFF"; + underLine.Fill = Brush.Parse("#666666"); + } + else if (ContentArea.Content is ManualControl manual) + { + manual.VibrationStatus.Text = "OFF"; + manual.VibrationUnderline.Fill = Brush.Parse("#666666"); + } + }); + + } + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Admin"; + }); + } + + + } + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Programming Team"; + }); + } + + vibrationMotor = -1; + } + else if (vibrationMotor == 1) // on VIBRATION + { + var vibrator = _mapping.Find(x => x.Name == "Vibrator"); + + if (vibrator != null) + { + if (vibrator.BitNumbers.Count > 0) + { + foreach (var bit in vibrator.BitNumbers) + { + holdingRegister.hvOut |= (ushort)(1 << bit); + } + await WriteToSerialAsync("Vibrator"); + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + var StackPanel = result.vibrationBtn.Content as StackPanel; + var Label = StackPanel.Children; + var underLine = Label[2] as Avalonia.Controls.Shapes.Rectangle; + var targetLable = Label[1] as Label; + targetLable.Content = "ON"; + underLine.Fill = Brush.Parse("#A4275D"); + } + else if (ContentArea.Content is ManualControl manual) + { + manual.VibrationStatus.Text = "ON"; + manual.VibrationUnderline.Fill = Brush.Parse("#A4275D"); + } + }); + + + + } + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Admin"; + }); + } + + + + + + } + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Programming Team"; + }); + } + vibrationMotor = -1; + } + if (vibHeaterMotor == 0) // off VIB. HEATER + { + var vibHeater = _mapping.Find(x => x.Name == "Vibrator Heater"); + if (vibHeater != null) + { + if (vibHeater.BitNumbers.Count > 0) + { + + foreach (var bit in vibHeater.BitNumbers) + { + + holdingRegister.lvOut &= (ushort)~(1 << bit); + } + await WriteToSerialAsync("VibratorHeater"); + + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + var StackPanel = result.vibHeaterBtn.Content as StackPanel; + var Label = StackPanel.Children; + var underLine = Label[2] as Avalonia.Controls.Shapes.Rectangle; + var targetLable = Label[1] as Label; + targetLable.Content = "OFF"; + underLine.Fill = Brush.Parse("#666666"); + } + else if (ContentArea.Content is ManualControl manual) + { + manual.VibHeaterStatus.Text = "OFF"; + manual.VibHeaterUnderline.Fill = Brush.Parse("#666666"); + } + }); + + } + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Admin"; + }); + } + } + + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Programming Team"; + }); + } + + vibHeaterMotor = -1; + } + else if (vibHeaterMotor == 1) // on VIB. HEATER + { + var vibHeater = _mapping.Find(x => x.Name == "Vibrator Heater"); + if (vibHeater != null) + { + if (vibHeater.BitNumbers.Count > 0) + { + foreach (var bit in vibHeater.BitNumbers) + { + holdingRegister.lvOut |= (ushort)(1 << bit); + } + await WriteToSerialAsync("VibratorHeater"); + + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + var StackPanel = result.vibHeaterBtn.Content as StackPanel; + var Label = StackPanel.Children; + var underLine = Label[2] as Avalonia.Controls.Shapes.Rectangle; + var targetLable = Label[1] as Label; + targetLable.Content = "ON"; + underLine.Fill = Brush.Parse("#A4275D"); + } + else if (ContentArea.Content is ManualControl manual) + { + manual.VibHeaterStatus.Text = "ON"; + manual.VibHeaterUnderline.Fill = Brush.Parse("#A4275D"); + } + }); + } + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Admin"; + }); + } + + } + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Programming Team"; + }); + } + vibHeaterMotor = -1; + } + + + //Start Recipe + if (startRecipe == 1) + { + var tankBtm = _mapping.Find(x => x.Name.ToLower() == "Tank Bottom Temp".ToLower()); + tankWall = _mapping.Find(x => x.Name.ToLower() == "Tank Wall Temp".ToLower()); + var pumb = _mapping.Find(x => x.Name.ToLower() == "Pump Temp".ToLower()); + var fount = _mapping.Find(x => x.Name.ToLower() == "Fountain Temp".ToLower()); + var fountainMotor = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + var mixerMotor = _mapping.Find(x => x.Name.ToLower() == "Mixer".ToLower()); + + if (tankBtm != null && tankWall != null && pumb != null && fount != null) + { + if (tankBtm.BitNumbers.Count > 0 && tankWall.BitNumbers.Count > 0 && pumb.BitNumbers.Count > 0 && fount.BitNumbers.Count > 0) + { + List setTempValues = new List(); + setTempValues.AddRange([holdingRegister.setTemp1, holdingRegister.setTemp2, holdingRegister.setTemp3, holdingRegister.setTemp4]); + byte[] response = new byte[] { 0xFF }; + + var isFountOn = false; + var isMixerOn = false; + if (isFountOn != fountainMotor.BitNumbers.All(bit => (holdingRegister.motor & (1 << bit)) != 0)) + { + isFountOn = fountainMotor.BitNumbers.All(bit => (holdingRegister.motor & (1 << bit)) != 0); + } + if (isMixerOn != mixerMotor.BitNumbers.All(bit => (holdingRegister.motor & (1 << bit)) != 0)) + { + isMixerOn = mixerMotor.BitNumbers.All(bit => (holdingRegister.motor & (1 << bit)) != 0); + } + if (isFountOn && isMixerOn) // both motores are on + { + + if ((comFountainTemp * 10 >= (recipeHeatingGoal * 10)) && (cooling != 1 && pouring != 1)) + { + if (heatingTimer == null) + { + heatingTimer = new Timer(HeatingTimer, null, 0, 1000); + heatingSeconds = _machine.HeatingDelay; + } + } + else if ((Heating != 1) && (cooling != 1 || cooling != 10) && (pouring != 1 || pouring != 10)) + { + sendComTankTemp = 1; + Heating = 1; + sendComHeating = 1; + setHeatingTimerOnce = 1; + } + + } + //if (comPumpTemp>=_machine.PumbMaxHeat) + //{ + // //start timer + // if (fountainTimer==null) + // { + // if (fountainSeconds == 1) + // { + // fountainSeconds = _machine.PumbDelay; + // } + // fountainTimer = new Timer(FountainTimer, null, 0, 1000); + // } + // if (turnOnFountainMotor) + // { + // fount = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + // if (fount != null) + // { + // if (fount.BitNumbers.Count > 0) + // { + // foreach (var bit in fount.BitNumbers) + // { + // holdingRegister.motor |= (ushort)(1 << bit); + // } + // isWriting = true; + + // } + // } + + // turnOnFountainMotor = false; + // } + //} + //else + //{ + // startFountainMotorFlashing = 1; + //} + if (sendComTankTemp == 1) + { + sendComTankTemp = -1; + } + if (pause) + { + isPaused = true; + if (Heating == 1) + { + Heating = 10; + } + else if (cooling == 1) + { + cooling = 10; + } + else if (pouring == 1) + { + pouring = 10; + } + //PumbOn = -1; + if (tankBtm != null) + { + if (tankBtm.BitNumbers.Count > 0) + { + foreach (var item in tankBtm.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.TankMaxHeat * 10; + } + + } + + + } + if (tankWall != null) + { + if (tankWall.BitNumbers.Count > 0) + { + foreach (var item in tankWall.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.TankMaxHeat * 10; + } + + } + + + } + + if (pumb != null) + { + if (pumb.BitNumbers.Count > 0) + { + foreach (var item in pumb.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.PumbMaxHeat * 10; + + } + } + + + } + if (fount != null) + { + if (fount.BitNumbers.Count > 0) + { + foreach (var item in fount.BitNumbers) + { + setTempValues[item - 8] = -10000; + + } + } + + + } + holdingRegister.setTemp1 = setTempValues[0]; + holdingRegister.setTemp2 = setTempValues[1]; + holdingRegister.setTemp3 = setTempValues[2]; + holdingRegister.setTemp4 = setTempValues[3]; + holdingRegister.motor = 0; + + await WriteToSerialAsync("RecipePause"); + startMixerMotor = 0; + startFountainMotor = 0; + if (heatingTimer != null) + { + heatingTimer.Change(Timeout.Infinite, Timeout.Infinite); + heatingSeconds = _machine.HeatingDelay; + heatingTimer = null; + } + if (coolingTimer != null) + { + coolingTimer.Change(Timeout.Infinite, Timeout.Infinite); + coolingSeconds = _machine.CoolingDelay; + coolingTimer = null; + + } + if (pouringTimer != null) + { + pouringTimer.Change(Timeout.Infinite, Timeout.Infinite); + pouringSeconds = _machine.PouringDelay; + pouringTimer = null; + + } + if (pedalOffTimer != null) + { + pedalOffTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOffSeconds = 0; + } + if (pedalOnTimer != null) + { + pedalOnTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOnSeconds = 0; + } + if (fountainPauseTimer != null) + { + fountainPauseTimer.Change(Timeout.Infinite, Timeout.Infinite); + fountainPauseSeconds = 10; + fountainPauseTimer = null; + } + if (fountainTimer != null) + { + fountainTimer.Change(Timeout.Infinite, Timeout.Infinite); + fountainTimer = null; + } + if (mixerTimer != null) + { + mixerTimer.Change(Timeout.Infinite, Timeout.Infinite); + mixerTimer = null; + } + Dispatcher.UIThread.Post(async () => + { + footerMsg.Text = "Recipe Paused"; + + }); + pause = false; + } + else if (unPause) + { + isPaused = false; + if (Heating == 10) + { + Heating = 1; + sendComHeating = 1; + } + else if (cooling == 10) + { + cooling = 1; + sendComCooling = 1; + } + else if (pouring == 10) + { + pouring = 1; + sendComPouring = 1; + } + PumbOn = 1; + + Dispatcher.UIThread.Post(async () => + { + footerMsg.Text = "Recipe Continued"; + }); + unPause = false; + } + if (Heating == 1) + { + if (errors.Count > 0) + { + if ((DateTime.Now - errors.Min(x => x.errorDate)).TotalSeconds >= 3.5) + { + if (!isPaused) + { + pause = true; + + } + } + + } + else + { + Dispatcher.UIThread.Post(async () => + { + if (ContentArea.Content is Settings result) + { + if (comFountainTemp * 10 <= (result._recipeTable?.HeatingGoal * 10) + screenData.warningLimit && + comFountainTemp * 10 >= (result._recipeTable?.HeatingGoal * 10) - screenData.warningLimit) + { + if (setHeatingTimerOnce == 1) + { + heatingTimer = new Timer(HeatingTimer, null, 0, 1000); + heatingSeconds = _machine.HeatingDelay; + setHeatingTimerOnce = -1; + } + } + else if (sendComHeating == 1) + { + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + recipeHeatingGoal = result._recipeTable.HeatingGoal; + recipeCoolingGoal = result._recipeTable.CoolingGoal; + recipePouringGoal = result._recipeTable.PouringGoal; + } + }); + + foreach (var item in tankBtm.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.TankMaxHeat; + } + foreach (var item in tankWall.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.TankMaxHeat; + } + foreach (var item in pumb.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.PumbMaxHeat; + } + foreach (var item in fount.BitNumbers) + { + setTempValues[item - 8] = (int)recipeHeatingGoal; + } + holdingRegister.setTemp1 = setTempValues[0] * 10; + holdingRegister.setTemp2 = setTempValues[1] * 10; + holdingRegister.setTemp3 = setTempValues[2] * 10; + holdingRegister.setTemp4 = setTempValues[3] * 10; + if (fountainMotor != null) + { + if (fountainMotor.BitNumbers.Count > 0) + { + foreach (var bit in fountainMotor.BitNumbers) + { + holdingRegister.motor |= (ushort)(1 << bit); + } + isFountainMotorOn = true; + + } + } + if (mixerMotor != null) + { + if (mixerMotor.BitNumbers.Count > 0) + { + foreach (var bit in mixerMotor.BitNumbers) + { + holdingRegister.motor |= (ushort)(1 << bit); + } + isMixerMotorOn = true; + + } + } + await WriteToSerialAsync("HeatingPhase"); + Dispatcher.UIThread.Post(async () => + { + footerMsg.Text = "Heating phase"; + + }); + + sendComHeating = -1; + + } + } + }); + } + + + } + else if (cooling == 1) + { + if (errors.Count > 0) + { + if (!isPaused) + { + //pause = true; + + } + } + else + { + if (sendComCooling == 1) + { + foreach (var item in tankBtm.BitNumbers) + { + setTempValues[item - 8] = -1000; + } + foreach (var item in tankWall.BitNumbers) + { + setTempValues[item - 8] = -1000; + } + foreach (var item in pumb.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.PumbMinHeat; + + } + foreach (var item in fount.BitNumbers) + { + setTempValues[item - 8] = (int)recipeCoolingGoal; + + } + holdingRegister.setTemp1 = setTempValues[0] * 10; + holdingRegister.setTemp2 = setTempValues[1] * 10; + holdingRegister.setTemp3 = setTempValues[2] * 10; + holdingRegister.setTemp4 = setTempValues[3] * 10; + if (fountainMotor != null) + { + if (fountainMotor.BitNumbers.Count > 0) + { + foreach (var bit in fountainMotor.BitNumbers) + { + holdingRegister.motor |= (ushort)(1 << bit); + } + isFountainMotorOn = true; + + } + } + if (mixerMotor != null) + { + if (mixerMotor.BitNumbers.Count > 0) + { + foreach (var bit in mixerMotor.BitNumbers) + { + holdingRegister.motor |= (ushort)(1 << bit); + } + isMixerMotorOn = true; + + } + } + await WriteToSerialAsync("CoolingPhase"); + Dispatcher.UIThread.Post(async () => + { + footerMsg.Text = "Cooling phase"; + }); + sendComCooling = -1; + + + } + + Dispatcher.UIThread.Post(async () => + { + + if (ContentArea.Content is Settings result) + { + if (comFountainTemp * 10 <= (result._recipeTable?.CoolingGoal * 10) + screenData.warningLimit && + comFountainTemp * 10 > (result._recipeTable?.CoolingGoal * 10) - screenData.warningLimit) + { + if (setCoolingTimerOnce == 1) + { + coolingTimer = new Timer(CoolingTimer, null, 0, 1000); + coolingSeconds = _machine.CoolingDelay; + setCoolingTimerOnce = -1; + } + } + } + }); + } + + + } + else if (pouring == 1) + { + if (errors.Count > 0) + { + if (!isPaused) + { + //pause = true; + + } + } + else + { + if (sendComPouring == 1) + { + + foreach (var item in tankBtm.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.TankMaxHeat; + + } + foreach (var item in tankWall.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.TankMaxHeat; + + } + foreach (var item in pumb.BitNumbers) + { + setTempValues[item - 8] = (int)_machine.PumbMaxHeat; + + } + foreach (var item in fount.BitNumbers) + { + setTempValues[item - 8] = (int)recipePouringGoal; + + } + holdingRegister.setTemp1 = setTempValues[0] * 10; + holdingRegister.setTemp2 = setTempValues[1] * 10; + holdingRegister.setTemp3 = setTempValues[2] * 10; + holdingRegister.setTemp4 = setTempValues[3] * 10; + if (fountainMotor != null) + { + if (fountainMotor.BitNumbers.Count > 0) + { + foreach (var bit in fountainMotor.BitNumbers) + { + holdingRegister.motor |= (ushort)(1 << bit); + } + isFountainMotorOn = true; + + } + } + if (mixerMotor != null) + { + if (mixerMotor.BitNumbers.Count > 0) + { + foreach (var bit in mixerMotor.BitNumbers) + { + holdingRegister.motor |= (ushort)(1 << bit); + } + isMixerMotorOn = true; + + } + } + await WriteToSerialAsync("PouringPhase"); + Dispatcher.UIThread.Post(async () => + { + footerMsg.Text = "Prepare for pouring"; + }); + sendComPouring = -1; + + } + Dispatcher.UIThread.Post(async () => + { + if (ContentArea.Content is Settings result) + { + if (comFountainTemp * 10 < (result._recipeTable?.PouringGoal * 10) + screenData.warningLimit && + comFountainTemp * 10 > (result._recipeTable?.PouringGoal * 10) - screenData.warningLimit) + { + if (setPouringTimerOnce == 1) + { + foreach (var item in tankBtm.BitNumbers) + { + setTempValues[item - 8] = (int)(recipePouringGoal + _machine.PreHeatingTemp); + + } + foreach (var item in tankWall.BitNumbers) + { + setTempValues[item - 8] = (int)(recipePouringGoal + _machine.PreHeatingTemp); + + } + foreach (var item in pumb.BitNumbers) + { + setTempValues[item - 8] = -1000; + + } + foreach (var item in fount.BitNumbers) + { + setTempValues[item - 8] = (int)recipePouringGoal; + } + holdingRegister.setTemp1 = setTempValues[0] * 10; + holdingRegister.setTemp2 = setTempValues[1] * 10; + holdingRegister.setTemp3 = setTempValues[2] * 10; + holdingRegister.setTemp4 = setTempValues[3] * 10; + if (fountainMotor != null) + { + if (fountainMotor.BitNumbers.Count > 0) + { + foreach (var bit in fountainMotor.BitNumbers) + { + holdingRegister.motor |= (ushort)(1 << bit); + } + isFountainMotorOn = true; + } + } + if (mixerMotor != null) + { + if (mixerMotor.BitNumbers.Count > 0) + { + foreach (var bit in mixerMotor.BitNumbers) + { + holdingRegister.motor |= (ushort)(1 << bit); + } + isMixerMotorOn = true; + } + } + await WriteToSerialAsync("PouringPhase"); + pouringTimer = new Timer(PouringTimer, null, 0, 1000); + pouringSeconds = _machine.PouringDelay; + setPouringTimerOnce = -1; + } + } + } + }); + } + + + } + } + else + { + Dispatcher.UIThread.Post(() => + { + footerMsg.Text = "Contact Admin"; + }); + } + } + + + } + + + if (PumbOn == 1) + { + //Dispatcher.UIThread.Post(() => + //{ + // recipeStartBtn.IsEnabled = true; + + //}); + if (pedalMotor == 0) // Manual Pedal + { + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings settings) + { + settings.pedalDelayTxt.IsVisible = false; + settings.pedalDelayCounter.IsVisible = false; + if (pedalOnTimer != null) + { + pedalOnTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOnTimer = null; + + } + if (pedalOffTimer != null) + { + pedalOffTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOffTimer = null; + } + + } + }); + + var pedal = _mapping.Find(x => x.Name.ToLower() == "pedal"); + if (pedal != null) + { + // READING THE INPUT REGISTER + if (errors.Count == 0) + { + ushort registerValue = (ushort)inputValues[1]; + if (allPedalBitsOn != pedal.BitNumbers.All(bit => (registerValue & (1 << bit)) != 0)) + { + allPedalBitsOn = pedal.BitNumbers.All(bit => (registerValue & (1 << bit)) != 0); + pedalStateChanged = 1; + } + else + { + pedalStateChanged = 0; + } + + if (!allPedalBitsOn) + { + pedalState = 1;// All bits ON + } + else + { + pedalState = 0; // At least one bit is OFF + } + + // READING THE motor REGISTER + var fount = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + if (fount != null) + { + if (fount.BitNumbers.Count > 0) + { + bool valueChanged = false; + if (pedalState == 1) // If all monitored bits are ON + { + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + result.pedalUnderLine.Fill = Brush.Parse(result.PassiveColor); + } + }); + if (!(comPumpTemp <= recipeCoolingGoal - 3)) + { + foreach (var bit in fount.BitNumbers) + { + if (!ToBinary(holdingRegister.motor)[bit]) + { + //Debug.WriteLine("input value:" + registerValue); + //Debug.WriteLine("pedal on:" + allBitsOn); + holdingRegister.motor |= (ushort)(1 << bit); + valueChanged = true; + + } + } + if (valueChanged) + { + await WriteToSerialAsync("PedalManual"); + valueChanged = false; + if (isPaused) + { + unPause = true; + } + } + + } + + } + else // If at least one monitored bit is OFF + { + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + result.pedalUnderLine.Fill = Brush.Parse(result.ActiveColor); + } + }); + if (pedalStateChanged == 1) + { + foreach (var bit in fount.BitNumbers) + { + if (ToBinary(holdingRegister.motor)[bit]) + { + holdingRegister.motor &= (ushort)~(1 << bit); + valueChanged = true; + } + + } + if (valueChanged) + { + await WriteToSerialAsync("PedalManual"); + valueChanged = false; + } + + } + + if (fountainPauseTimer == null && startRecipe == 1 && (Heating == 1 || heatingTimer != null || cooling == 1 || coolingTimer != null || pouring == 1 || pouringTimer != null + )) + { + fountainPauseSeconds = 10; + fountainPauseTimer = new Timer(FountainPauseTimer, null, 0, 1000); + } + + } + + if (pedalStateChanged == 1) + { + // WRITE UPDATED VALUE TO HVO REGISTER + //isWriting = true; + } + + } + + } + } + + + } + } + + else if (pedalMotor == 1) // auto Pedal + { + const double deadZone = 1.5; + if (pedalState == 0) // on + { + var fountt = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + if (fountt != null) + { + if (fountt.BitNumbers.Count > 0) + { + if (!(comPumpTemp <= recipeCoolingGoal - 3 + deadZone)) + { + foreach (var bit in fountt.BitNumbers) + { + holdingRegister.motor |= (ushort)(1 << bit); + isFountainMotorOn = true; + } + await WriteToSerialAsync("PedalAuto"); + } + } + else + { + // Turn OFF only if it dropped below the lower threshold + if (comPumpTemp <= recipeCoolingGoal - 3 - deadZone) + { + foreach (var bit in fountt.BitNumbers) + holdingRegister.motor &= (ushort)~(1 << bit); + + isFountainMotorOn = false; + await WriteToSerialAsync("PedalAuto - OFF"); + } + + } + + } + else if (pedalState == 1) // off + { + var fount = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + + if (fount != null) + { + if (fount.BitNumbers.Count > 0) + { + + + foreach (var bit in fount.BitNumbers) + { + holdingRegister.motor &= (ushort)~(1 << bit); + } + await WriteToSerialAsync("PedalAuto"); + if (fountainPauseTimer == null && startRecipe == 1 && (Heating == 1 || heatingTimer != null || cooling == 1 || coolingTimer != null || pouring == 1 || pouringTimer != null + )) + { + fountainPauseSeconds = 10; + fountainPauseTimer = new Timer(FountainPauseTimer, null, 0, 1000); + } + } + } + + } + + pedalState = -1; + if (!(comPumpTemp <= recipeCoolingGoal - 3)) + { + if (setPedalTimerOnce == 1) + { + pedalOffTimer = new Timer(PedalOffTimer, null, 0, 1000); + setPedalTimerOnce = -1; + } + else if (setPedalTimerOnce == 0) + { + pedalOnTimer = new Timer(PedalOnTimer, null, 0, 1000); + setPedalTimerOnce = -1; + } + } + + } + + } + + //change diag UI + var hvo = ToBinary(holdingRegister.hvOut); + var lvo = ToBinary(holdingRegister.lvOut); + var motor = ToBinary(holdingRegister.motor); + + Dispatcher.UIThread.Post(async () => + { + if (ContentArea.Content is Diagnostics diagnostics) + { + foreach (var item in diagnostics.MotoreState.OfType().ToList()) + { + var stackPanel = item.Children[0] as StackPanel; + var text = stackPanel.Children[1] as TextBlock; + var border = item.Children[1] as Border; + if (motor[int.Parse(item.Tag.ToString())]) + { + + text.Text = "ON"; + border.Background = Brush.Parse(diagnostics.PinkColor); + diagnostics.MotoreState.OfType().ToList().Find(x => x.Tag.ToString() == item.Tag.ToString()).Fill = Brush.Parse(diagnostics.OrangeColor); + + } + else + { + text.Text = "OFF"; + border.Background = Brush.Parse(diagnostics.GrayColor); + diagnostics.MotoreState.OfType().ToList().Find(x => x.Tag.ToString() == item.Tag.ToString()).Fill = Brush.Parse(diagnostics.GrayColor); + + + } + } + + // HVO + foreach (var item in diagnostics.hvoOutPuts.OfType().ToList()) + { + var text = item.Children[1] as TextBlock; + var border = item.Children[2] as Border; + if (hvo[int.Parse(item.Tag.ToString())]) + { + + text.Text = "ON"; + border.Background = Brush.Parse(diagnostics.PinkColor); + diagnostics.hvoOutPuts.OfType().ToList().Find(x => x.Tag.ToString() == item.Tag.ToString()).Fill = Brush.Parse(diagnostics.OrangeColor); + + } + else + { + text.Text = "OFF"; + border.Background = Brush.Parse(diagnostics.GrayColor); + diagnostics.hvoOutPuts.OfType().ToList().Find(x => x.Tag.ToString() == item.Tag.ToString()).Fill = Brush.Parse(diagnostics.GrayColor); + + + } + } + + // LVO + foreach (var item in diagnostics.lvoOutPuts.OfType().ToList()) + { + var text = item.Children[1] as TextBlock; + var border = item.Children[2] as Border; + if (lvo[int.Parse(item.Tag.ToString())]) + { + + text.Text = "ON"; + border.Background = Brush.Parse(diagnostics.PinkColor); + diagnostics.lvoOutPuts.OfType().ToList().Find(x => x.Tag.ToString() == item.Tag.ToString()).Fill = Brush.Parse(diagnostics.GreenColor); + + } + else + { + text.Text = "OFF"; + border.Background = Brush.Parse(diagnostics.GrayColor); + diagnostics.lvoOutPuts.OfType().ToList().Find(x => x.Tag.ToString() == item.Tag.ToString()).Fill = Brush.Parse(diagnostics.GrayColor); + + + } + } + foreach (var item in diagnostics.lvoOutPuts.OfType().ToList()) + { + var text = item.Children[1] as TextBlock; + var border = item.Children[2] as Border; + if (lvo[int.Parse(item.Tag.ToString())]) + { + + text.Text = "ON"; + border.Background = Brush.Parse(diagnostics.PinkColor); + diagnostics.lvoOutPuts.OfType().ToList().Find(x => x.Tag.ToString() == item.Tag.ToString()).Fill = Brush.Parse(diagnostics.GreenColor); + + } + else + { + text.Text = "OFF"; + border.Background = Brush.Parse(diagnostics.GrayColor); + diagnostics.lvoOutPuts.OfType().ToList().Find(x => x.Tag.ToString() == item.Tag.ToString()).Fill = Brush.Parse(diagnostics.GrayColor); + + + } + } + } + }); + + await Task.Delay(100); + + } + } + catch (Exception e) + { + + } + + } + } + } + catch + { + } + finally + { + + } + + } + + // Find the port name corresponding to this serial number + + Thread.Sleep(50); // Check every 1 seconds + } + } + + + + + public bool ConnectToSerialPort() + { + screenData = _screeen.ReadScreens()?[0]; + try + { + if (_port != null && _port.IsOpen) + { + _port.Close(); + } + _port = null; + _port = new SerialPort(screenData.port, screenData.boundRate); + switch (screenData.parity) + { + case 0: + _port.Parity = Parity.None; + break; + case 1: + _port.Parity = Parity.Odd; + break; + case 2: + _port.Parity = Parity.Even; + break; + case 3: + _port.Parity = Parity.Mark; + break; + case 4: + _port.Parity = Parity.Space; + break; + default: + _port.Parity = Parity.None; + break; + } + switch (screenData.stopBits) + { + case 2: + _port.StopBits = StopBits.Two; + break; + default: + _port.StopBits = StopBits.One; + break; + } + _port.DataBits = 8; + _port.Handshake = Handshake.None; + _port.DtrEnable = true; + + // Open the serial port + + _port.Open(); + return true; + + } + catch (Exception ex) + { + + Console.WriteLine($"Error connecting to port {screenData.port}: {ex.Message}"); + _port = null; + return false; + } + } + + + + + public void closeConnection() + { + isRunning = false; + monitorThread.Abort(); + } + private async void OnClosing1(object? sender, CancelEventArgs e) + { + closeConnection(); + + } + private void OnClosingWindow(object? sender, WindowClosingEventArgs e) + { + if (_port != null && _port.IsOpen) + { + _port.Close(); + //_port = null; + } + // Example: Cancel the close if needed + // e.Cancel = true; + } + + + + + + //Main Window Functions + private void errorLogoClick(object? sender, RoutedEventArgs e) + { + errorPopupOverlay.IsVisible = true; + //errorTitel.Text = errorLogo.Tag.ToString(); + errorMsg.Text = errorMsg.Text.Trim(); + } + private void warningLogoClick(object? sender, RoutedEventArgs e) + { + warningPopupOverlay.IsVisible = true; + warningTitel.Text = warningLogo.Tag.ToString(); + warningMsg.Text = warningMsg.Text.Trim(); + } + private void HomeTraclBtn(object? sender, RoutedEventArgs e) + { + if (ContentArea.Content is Settings result) + { + result.DeletePopupOverlay.IsVisible = true; + result.DeletePopupOverlay.Tag = "home"; + + } + else if (ContentArea.Content is Diagnostics diagnostics) + { + restBoard = true; + + this.UserName.Content = "Select User"; + footerMsg.Text = ""; + ContentArea.Content = new Home(this); + } + else + { + this.UserName.Content = "Select User"; + footerMsg.Text = ""; + ContentArea.Content = new Home(this); + } + } + private void DiagnosticsBtn(object? sender, RoutedEventArgs e) + { + if (ContentArea.Content is AdvanceSettings advanceSettings) + { + footerMsg.Text = ""; + ContentArea.Content = new Diagnostics(this, true); + } + else if (ContentArea.Content is ManualControl) + { + footerMsg.Text = ""; + ContentArea.Content = new Diagnostics(this, false, true); + } + else + { + footerMsg.Text = ""; + ContentArea.Content = new Diagnostics(this); + } + + } + private void ChefManualBtn(object? sender, RoutedEventArgs e) + { + footerMsg.Text = ""; + ContentArea.Content = new ManualControl(this); + + } + public void AdvanceSettingsView(object? sender, RoutedEventArgs e) + { + if (ContentArea.Content is Diagnostics) + { + ContentArea.Content = new AdvanceSettings(this, true, false); + + } + else if (ContentArea.Content is Software) + { + ContentArea.Content = new AdvanceSettings(this, false, true); + + } + else + { + ContentArea.Content = new AdvanceSettings(this); + + } + + } + private void RecipeSelTrackBtn(object? sender, RoutedEventArgs e) + { + if (ContentArea.Content is Settings result) + { + result.DeletePopupOverlay.IsVisible = true; + result.DeletePopupOverlay.Tag = "recipeSel"; + } + else + { + footerMsg.Text = ""; + ContentArea.Content = new Recipe(this, Program.currentUser); + } + + + } + private void SettingTrackBtn(object? sender, RoutedEventArgs e) + { + if (ContentArea.Content is Diagnostics diagnostics) + { + restBoard = true; + } + footerMsg.Text = ""; + ContentArea.Content = new Admin(this, Program.currentUser); + } + private void SoftwareBtn(object? sender, RoutedEventArgs e) + { + if (ContentArea.Content is AdvanceSettings) + { + footerMsg.Text = ""; + ContentArea.Content = new Software(this, true); + } + else if (ContentArea.Content is ManualControl) + { + footerMsg.Text = ""; + ContentArea.Content = new Software(this, false, true); + } + else + { + footerMsg.Text = ""; + ContentArea.Content = new Software(this); + } + + + } + + private async void PreHeatingClick(object? sender, RoutedEventArgs e) + { + if (ContentArea.Content is Settings result) + { + if (result.recipeSettings.IsEnabled) + { + startPreHeating = 1; + writingMaxTemp = 1; + //if (!isMixerMotorOn) + //{ + // result.mixerBtn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); + //} + //if (!isFountainMotorOn) + //{ + // result.fountainBtn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); + //} + } + else + { + startPreHeating = 0; + writingMaxTemp = 0; + isFlashPreHeating = false; + } + } + + } + //Mixer + public async void MotorClick(object? sender, RoutedEventArgs e) + { + if (!isMixerMotorOn) + { + isMixerMotorOn = true; + checkMixerTWT_HWTH = true; + setMixerTimerOnce = true; + } + else + { + isMixerMotorOn = false; + checkMixerTWT_HWTH = false; + startMixerMotorFlashing = 0; + sendComMixerMotor = 0; + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings settings) + { + settings.mixerDelayTxt.IsVisible = false; + settings.mixerDelayCounter.IsVisible = false; + } + }); + if (mixerTimer != null) + { + mixerTimer.Change(Timeout.Infinite, Timeout.Infinite); + mixerTimer = null; + } + + } + } + private void MixerTimer(object state) + { + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings settings) + { + if (comTankTemp >= recipeCoolingGoal - 3) + { + mixerSeconds--; + } + else + { + //mixerTimer.Change(Timeout.Infinite, Timeout.Infinite); + } + + if (mixerSeconds <= 0) + { + // Stop the timer after 15 seconds + settings.mixerDelayTxt.IsVisible = false; + settings.mixerDelayCounter.IsVisible = false; + + if (mixerTimer != null) + { + mixerTimer.Change(Timeout.Infinite, Timeout.Infinite); + mixerTimer = null; + } + startMixerMotorFlashing = 0; + sendComMixerMotor = 1; + return; + } + if (mixerSeconds <= _machine.MixerDelay) + { + settings.mixerDelayTxt.IsVisible = true; + settings.mixerDelayCounter.Text = mixerSeconds.ToString(); + settings.mixerDelayCounter.IsVisible = true; + + } + } + + }); + + + + } + private void StopMixerTimer(object state) + { + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings settings) + { + if (comTankTemp <= recipeCoolingGoal - 3) + { + stopMixerSecondes--; + } + else + { + //mixerTimer.Change(Timeout.Infinite, Timeout.Infinite); + } + + if (stopMixerSecondes <= 0) + { + sendComMixerMotor = 0; + + + + stopMixerTimer.Change(Timeout.Infinite, Timeout.Infinite); + stopMixerTimer = null; + return; + } + } + + }); + + + + } + //Fountain + public async void FountainClick(object? sender, RoutedEventArgs e) + { + if (!isFountainMotorOn) + { + isFountainMotorOn = true; + checkFountainTMT_PMT = true; + setFountainTimerOnce = true; + } + else + { + isFountainMotorOn = false; + + checkFountainTMT_PMT = false; + startFountainMotorFlashing = 0; + sendComFountainMotor = 0; + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings settings) + { + settings.fountainDelayTxt.IsVisible = false; + settings.fountainDelayCounter.IsVisible = false; + settings.fountainTargetTxt.IsVisible = false; + settings.fountainTagetTemp.IsVisible = false; + } + }); + if (fountainTimer != null) + { + fountainTimer.Change(Timeout.Infinite, Timeout.Infinite); + fountainTimer = null; + + } + + } + } + private void FountainTimer(object state) + { + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings settings) + { + if (comPumpTemp >= recipeCoolingGoal - 3) + { + fountainSeconds--; + } + else + { + //fountainTimer.Change(Timeout.Infinite, Timeout.Infinite); + } + if (fountainSeconds <= 0) + { + // Stop the timer after 15 seconds + settings.fountainDelayTxt.IsVisible = false; + settings.fountainDelayCounter.IsVisible = false; + settings.fountainTargetTxt.IsVisible = false; + settings.fountainTagetTemp.IsVisible = false; + + if (fountainTimer != null) + { + fountainTimer.Change(Timeout.Infinite, Timeout.Infinite); + fountainTimer = null; + } + startFountainMotorFlashing = 0; + sendComFountainMotor = 1; + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + if (startRecipe == 1 && !isPaused) + { + PumbOn = 1; + + } + if (result._recipeTable.Pedal.Value) + { + pedalMotor = 0; + } + else + { + pedalMotor = 1; + pedalState = 0; + setPedalTimerOnce = 1; + } + } + + }); + + return; + } + if (fountainSeconds <= _machine.PumbDelay) + { + + + settings.fountainDelayTxt.Text = "Chocolate Delay: "; + settings.fountainDelayTxt.IsVisible = true; + settings.fountainDelayCounter.Text = fountainSeconds.ToString(); + settings.fountainDelayCounter.IsVisible = true; + settings.fountainTagetTemp.IsVisible = false; + settings.fountainTargetTxt.IsVisible = false; + + } + } + + + + }); + + + } + private void StopFountainTimer(object state) + { + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings settings) + { + if (comPumpTemp <= recipeCoolingGoal - 3) + { + stopFountainSecondes--; + } + else + { + //mixerTimer.Change(Timeout.Infinite, Timeout.Infinite); + } + + if (stopFountainSecondes <= 0) + { + sendComFountainMotor = 0; + + + stopFountainTimer.Change(Timeout.Infinite, Timeout.Infinite); + stopFountainTimer = null; + return; + } + } + + }); + + + + } + private void FountainPauseTimer(object state) + { + Dispatcher.UIThread.Post(() => + { + var fount = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + + if (allBitsOn != fount.BitNumbers.All(bit => (holdingRegister.motor & (1 << bit)) != 0)) + { + allBitsOn = fount.BitNumbers.All(bit => (holdingRegister.motor & (1 << bit)) != 0); + } + if (fountainPauseSeconds <= 0) + { + pause = true; + if (fountainPauseTimer != null) + { + fountainPauseTimer.Change(Timeout.Infinite, Timeout.Infinite); + fountainPauseTimer = null; + } + + return; + } + if (!allBitsOn) + { + //motor is off + //increase the counter + fountainPauseSeconds--; + //footerMsg.Text ="Fountain is off recipe will pause after: "+ fountainPauseSeconds.ToString(); + } + else + { + //motor is on + //cancel the timer + if (fountainPauseTimer != null) + { + + fountainPauseTimer.Change(Timeout.Infinite, Timeout.Infinite); + fountainPauseTimer = null; + } + } + + //if the counter greater than 10 then pause the recipe + }); + + + } + private void NoChoiceChoosenTimer(object state) + { + Dispatcher.UIThread.Post(() => + { + //increase the coiunter + if (ContentArea.Content is Settings settings) + { + if (settings.tempErrorPopupOverlay.IsVisible) + { + noChoiceChoosenSeconds++; + //footerMsg.Text = "sec" + noChoiceChoosenSeconds.ToString(); + } + else + { + //stop the timer + if (noChoiceChoosenTimer != null) + { + noChoiceChoosenTimer.Change(Timeout.Infinite, Timeout.Infinite); + noChoiceChoosenTimer = null; + } + } + if (noChoiceChoosenSeconds >= 180)//change to 3 min + { + //if it reach the 3 min then stop the recipe + startRecipe = 0; + Heating = 0; + cooling = 0; + pouring = 0; + PumbOn = -1; + pedalMotor = -1; + if (heatingTimer != null) + { + heatingTimer.Change(Timeout.Infinite, Timeout.Infinite); + heatingSeconds = _machine.HeatingDelay; + heatingTimer = null; + } + if (coolingTimer != null) + { + coolingTimer.Change(Timeout.Infinite, Timeout.Infinite); + coolingSeconds = _machine.CoolingDelay; + coolingTimer = null; + + } + if (pouringTimer != null) + { + pouringTimer.Change(Timeout.Infinite, Timeout.Infinite); + pouringSeconds = _machine.PouringDelay; + pouringTimer = null; + + } + if (pedalOffTimer != null) + { + pedalOffTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOffSeconds = 0; + } + if (pedalOnTimer != null) + { + pedalOnTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOnSeconds = 0; + } + if (fountainPauseTimer != null) + { + fountainPauseTimer.Change(Timeout.Infinite, Timeout.Infinite); + fountainPauseSeconds = 10; + fountainPauseTimer = null; + } + if (fountainTimer != null) + { + fountainTimer.Change(Timeout.Infinite, Timeout.Infinite); + fountainTimer = null; + } + if (mixerTimer != null) + { + mixerTimer.Change(Timeout.Infinite, Timeout.Infinite); + mixerTimer = null; + } + var fount = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + if (fount != null) + { + if (fount.BitNumbers.Count > 0) + { + foreach (var bit in fount.BitNumbers) + { + + holdingRegister.motor &= (ushort)~(1 << bit); + } + } + } + startPreHeating = 0; + writingMaxTemp = 0; + isFlashPreHeating = false; + holdingRegister.setTemp1 = -10000; + holdingRegister.setTemp2 = -10000; + holdingRegister.setTemp3 = -10000; + holdingRegister.setTemp4 = -10000; + settings.tempErrorPopupOverlay.IsVisible = false; + Dispatcher.UIThread.Post(async () => + { + await WriteToSerialAsync("NoChoiceChoosenTimer"); + + recipeStartBtn.Foreground = Avalonia.Media.Brushes.White; + recipeStartBtn.Background = Brush.Parse("#008000"); + footerMsg.Text = "waitting for too long... Recipe Stoped"; + recipeStartBtn.Content = "START RECIPE"; + PreHeatingBtn.IsEnabled = true; + recipeStartBtn.IsEnabled = true; + }); + + + } + } + + + }); + + + } + private void HeatingTimer(object state) + { + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings settings) + { + if (fountainPauseTimer == null) + { + if ((comFountainTemp * 10 <= (recipeHeatingGoal * 10) - (screenData.errorLimit * 10) || comFountainTemp * 10 >= (recipeHeatingGoal * 10) + (screenData.errorLimit * 10)) && !pauseTempTracking) + { + // show error window + if (noChoiceChoosenTimer == null) + { + noChoiceChoosenSeconds = 0; + noChoiceChoosenTimer = new Timer(NoChoiceChoosenTimer, null, 0, 1000); + } + settings.tempErrorPopupOverlay.IsVisible = true; + } + else if (!pauseTimer) + { + // emty error and warning temp is fine + //warningMessage = ""; + //continue counting + heatingSeconds--; + Heating = 1; + + } + //warning + + if (comFountainTemp * 10 <= (recipeHeatingGoal * 10) - (screenData.warningLimit * 10) || comFountainTemp * 10 >= (recipeHeatingGoal * 10) + (screenData.warningLimit * 10)) + { + // show waring and delet error if located + if (warningMessage != "Can Not Locate Temperature Correctly") + { + warningMessage = "Can Not Locate Temperature Correctly"; + } + } + else + { + warningMessage = ""; + } + + + if (heatingSeconds <= 0) + { + // Stop the timer after 15 seconds + warningMessage = ""; + heatingTimer.Change(Timeout.Infinite, Timeout.Infinite); + pauseTimer = false; + pauseTempTracking = false; + startRecipe = 1; + Heating = -1; + cooling = 1; + sendComCooling = 1; + setCoolingTimerOnce = 1; + heatingTimer = null; + } + if (heatingSeconds <= _machine.HeatingDelay && !pauseTimer) + { + footerMsg.Text = "Heating delay: " + heatingSeconds.ToString(); + + } + } + } + + }); + + } + private void CoolingTimer(object state) + { + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings settings) + { + if (fountainPauseTimer == null) + { + if ((comFountainTemp * 10 <= (recipeCoolingGoal * 10) - (screenData.errorLimit * 10) || comFountainTemp * 10 >= (recipeCoolingGoal * 10) + (screenData.errorLimit * 10)) && !pauseTempTracking) + { + // show error window + if (noChoiceChoosenTimer == null) + { + noChoiceChoosenSeconds = 0; + noChoiceChoosenTimer = new Timer(NoChoiceChoosenTimer, null, 0, 1000); + } + settings.tempErrorPopupOverlay.IsVisible = true; + } + else if (!pauseTimer) + { + // emty error and warning temp is fine + //warningMessage = ""; + //continue counting + coolingSeconds--; + } + //warning + if (comFountainTemp * 10 <= (recipeCoolingGoal * 10) - (screenData.warningLimit * 10) || comFountainTemp * 10 >= (recipeCoolingGoal * 10) + (screenData.warningLimit * 10)) + { + // show waring and delet error if located + if (warningMessage != "Can Not Locate Temperature Correctly") + { + warningMessage = "Can Not Locate Temperature Correctly"; + } + } + else + { + warningMessage = ""; + } + if (coolingSeconds <= 0) + { + // Stop the timer after 15 seconds + warningMessage = ""; + coolingTimer.Change(Timeout.Infinite, Timeout.Infinite); + pauseTimer = false; + pauseTempTracking = false; + pouring = 1; + sendComPouring = 1; + setPouringTimerOnce = 1; + cooling = -1; + coolingTimer = null; + } + if (coolingSeconds <= _machine.CoolingDelay && !pauseTimer) + { + footerMsg.Text = "Cooling delay: " + coolingSeconds.ToString(); + + } + + } + + + } + + }); + + } + private void PouringTimer(object state) + { + + + Dispatcher.UIThread.Post(() => + { + try + { + if (ContentArea.Content is Settings settings) + { + if (fountainPauseTimer == null) + { + if ((comFountainTemp * 10 <= (recipePouringGoal * 10) - (screenData.errorLimit * 10) || comFountainTemp * 10 >= (recipePouringGoal * 10) + (screenData.errorLimit * 10)) && !pauseTempTracking) + { + // show error window + if (noChoiceChoosenTimer == null) + { + noChoiceChoosenSeconds = 0; + noChoiceChoosenTimer = new Timer(NoChoiceChoosenTimer, null, 0, 1000); + } + settings.tempErrorPopupOverlay.IsVisible = true; + } + else if (!pauseTimer) + { + // emty error and warning temp is fine + //warningMessage = ""; + //continue counting + pouringSeconds--; + } + //warning + if (comFountainTemp * 10 <= (recipePouringGoal * 10) - (screenData.warningLimit * 10) || comFountainTemp * 10 >= (recipePouringGoal * 10) + (screenData.warningLimit * 10)) + { + // show waring and delet error if located + if (warningMessage != "Can Not Locate Temperature Correctly") + { + warningMessage = "Can Not Locate Temperature Correctly"; + } + } + else + { + warningMessage = ""; + } + if (pouringSeconds <= 0) + { + // Stop the timer after 15 seconds + if (pouringTimer != null) + { + pouringTimer.Change(Timeout.Infinite, Timeout.Infinite); + pouringTimer = null; + + } + pauseTimer = false; + pauseTempTracking = false; + //pouring = -1; + //PumbOn = 1; + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + //if (result._recipeTable.Pedal.Value) + //{ + // pedalMotor = 0; + //} + //else + //{ + // pedalMotor = 1; + // pedalState = 0; + // setPedalTimerOnce = 1; + //} + footerMsg.Text = "Ready for pouring"; + } + + }); + + } + if (pouringSeconds <= _machine.PouringDelay && !pauseTimer) + { + footerMsg.Text = "Pouring delay: " + pouringSeconds.ToString(); + + } + + } + } + } + catch (Exception ex) + { + footerMsg.Text = $"Error: {ex.Message}"; + } + + + }); + + + + } + private void PedalOffTimer(object state) + { + Dispatcher.UIThread.Post(() => + { + + // Stop the timer after 15 seconds + if (ContentArea.Content is Settings result) + { + pedalOffSeconds++; + + if (pedalOffSeconds <= result._recipeTable.PedalOffTime) + { + result.pedalDelayTxt.Text = "Pedal ON: "; + result.pedalDelayCounter.Text = pedalOffSeconds.ToString(); + result.pedalDelayTxt.IsVisible = true; + result.pedalDelayCounter.IsVisible = true; + + } + if (pedalOffSeconds >= result._recipeTable.PedalOffTime) + { + pedalOffSeconds = 0; + PumbOn = 1; + pedalMotor = 1; + pedalState = 1; + setPedalTimerOnce = 0; + if (pedalOffTimer != null) + { + pedalOffTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOffTimer = null; + } + + + + } + } + }); + + + + + } + private void PedalOnTimer(object state) + { + Dispatcher.UIThread.Invoke(() => + { + if (ContentArea.Content is Settings result) + { + pedalOnSeconds++; + + if (pedalOnSeconds <= result._recipeTable.PedalOnTime) + { + result.pedalDelayTxt.Text = "Pedal OFF: "; + result.pedalDelayCounter.Text = pedalOnSeconds.ToString(); + result.pedalDelayTxt.IsVisible = true; + result.pedalDelayCounter.IsVisible = true; + + } + if (pedalOnSeconds >= result._recipeTable.PedalOnTime) + { + pedalOnSeconds = 0; + PumbOn = 1; + pedalMotor = 1; + pedalState = 0; + setPedalTimerOnce = 1; + if (pedalOnTimer != null) + { + pedalOnTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOnTimer = null; + } + + + } + } + + + }); + + + + } + //Recipe Start + public async void RecipeStartBtn(object? sender, RoutedEventArgs e) + { + if (sender is Button button) + { + if (startRecipe == 0) + { + startRecipe = 1; + stopRecipeFlag = false; + + if (ContentArea.Content is Settings result) + { + recipeHeatingGoal = result._recipeTable.HeatingGoal; + recipeCoolingGoal = result._recipeTable.CoolingGoal; + recipePouringGoal = result._recipeTable.PouringGoal; + if (comPumpTemp * 10 < _machine.PumbMaxHeat * 10 || comTankTemp * 10 < _machine.TankMaxHeat * 10) + { + startPreHeating = 1; + writingMaxTemp = 1; + // Assuming you have a Button named myButton + } + if (!isMixerMotorOn) + { + result.mixerBtn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); + } + if (!isFountainMotorOn) + { + result.fountainBtn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); + + } + + Dispatcher.UIThread.Post(() => + { + result.mixerBtn.IsEnabled = false; + result.fountainBtn.IsEnabled = false; + PreHeatingBtn.IsEnabled = false; + recipeStartBtn.IsEnabled = true; + button.Background = Avalonia.Media.Brushes.Red; + button.Content = "STOP RECIPE"; + }); + } + + + + } + else if (startRecipe == 1) + { + startRecipe = 0; + stopRecipeFlag = true; + Heating = -1; + cooling = -1; + pouring = -1; + PumbOn = -1; + pedalMotor = -1; + + if (heatingTimer != null) + { + heatingTimer.Change(Timeout.Infinite, Timeout.Infinite); + heatingSeconds = _machine.HeatingDelay; + heatingTimer = null; + } + if (coolingTimer != null) + { + coolingTimer.Change(Timeout.Infinite, Timeout.Infinite); + coolingSeconds = _machine.CoolingDelay; + coolingTimer = null; + + } + if (pouringTimer != null) + { + pouringTimer.Change(Timeout.Infinite, Timeout.Infinite); + pouringSeconds = _machine.PouringDelay; + pouringTimer = null; + + } + if (pedalOffTimer != null) + { + pedalOffTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOffSeconds = 0; + } + if (pedalOnTimer != null) + { + pedalOnTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOnSeconds = 0; + } + if (fountainPauseTimer != null) + { + fountainPauseTimer.Change(Timeout.Infinite, Timeout.Infinite); + fountainPauseSeconds = 10; + fountainPauseTimer = null; + } + if (fountainTimer != null) + { + fountainTimer.Change(Timeout.Infinite, Timeout.Infinite); + fountainTimer = null; + } + if (mixerTimer != null) + { + mixerTimer.Change(Timeout.Infinite, Timeout.Infinite); + mixerTimer = null; + } + if (ContentArea.Content is Settings settings) + { + if (isMixerMotorOn) + { + settings.mixerBtn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); + } + if (isFountainMotorOn) + { + settings.fountainBtn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); + } + settings.mixerDelayTxt.IsVisible = false; + settings.mixerDelayCounter.IsVisible = false; + settings.fountainDelayTxt.IsVisible = false; + settings.fountainDelayCounter.IsVisible = false; + settings.fountainTargetTxt.IsVisible = false; + settings.fountainTagetTemp.IsVisible = false; + } + + //var fount = _mapping.Find(x => x.Name.ToLower() == "Helix".ToLower()); + //if (fount != null) + //{ + // if (fount.BitNumbers.Count > 0) + // { + // foreach (var bit in fount.BitNumbers) + // { + + // holdingRegister.motor &= (ushort)~(1 << bit); + // } + // } + //} + startPreHeating = 0; + writingMaxTemp = 0; + isFlashPreHeating = false; + holdingRegister.setTemp1 = -10000; + holdingRegister.setTemp2 = -10000; + holdingRegister.setTemp3 = -10000; + holdingRegister.setTemp4 = -10000; + holdingRegister.motor = 0; + await WriteToSerialAsync("RecipeStop"); + footerMsg.Text = "Recipe Stoped"; + button.Content = "START RECIPE"; + PreHeatingBtn.IsEnabled = true; + recipeStartBtn.IsEnabled = true; + Dispatcher.UIThread.Post(() => + { + if (ContentArea.Content is Settings result) + { + result.mixerBtn.IsEnabled = true; + result.fountainBtn.IsEnabled = true; + result.pedalDelayTxt.IsVisible = false; + result.pedalDelayCounter.IsVisible = false; + } + recipeStartBtn.Foreground = Avalonia.Media.Brushes.White; + recipeStartBtn.Background = Brush.Parse("#008000"); + }); + } + } + + + } + + public void resetAll() + { + if (heatingTimer != null) + { + heatingTimer.Change(Timeout.Infinite, Timeout.Infinite); + heatingSeconds = _machine.HeatingDelay; + heatingTimer = null; + } + if (coolingTimer != null) + { + coolingTimer.Change(Timeout.Infinite, Timeout.Infinite); + coolingSeconds = _machine.CoolingDelay; + coolingTimer = null; + + } + if (pouringTimer != null) + { + pouringTimer.Change(Timeout.Infinite, Timeout.Infinite); + pouringSeconds = _machine.PouringDelay; + pouringTimer = null; + + } + if (pedalOffTimer != null) + { + pedalOffTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOffSeconds = 0; + } + if (pedalOnTimer != null) + { + pedalOnTimer.Change(Timeout.Infinite, Timeout.Infinite); + pedalOnSeconds = 0; + } + if (fountainPauseTimer != null) + { + fountainPauseTimer.Change(Timeout.Infinite, Timeout.Infinite); + fountainPauseSeconds = 10; + fountainPauseTimer = null; + } + if (fountainTimer != null) + { + fountainTimer.Change(Timeout.Infinite, Timeout.Infinite); + fountainTimer = null; + } + if (mixerTimer != null) + { + mixerTimer.Change(Timeout.Infinite, Timeout.Infinite); + mixerTimer = null; + } + + + + pedalState = -1; + pedalStateChanged = -1; + recipeHeatingGoal = 0; + recipeCoolingGoal = 0; + recipePouringGoal = 0; + //pre Heating + isFlashPreHeating = false; + startPreHeating = -1; + writingMaxTemp = -1; + // mixer + mixerSeconds = 1; + setMixerTimerOnce = false; + checkMixerTWT_HWTH = false; + isMixerMotorOn = false; + startMixerMotor = -1; + startMixerMotorFlashing = -1; + sendComMixerMotor = -1; + //Fountain Motor + fountainSeconds = 1; + setFountainTimerOnce = false; + checkFountainTMT_PMT = false; + isFountainMotorOn = false; + startFountainMotor = -1; + startFountainMotorFlashing = -1; + sendComFountainMotor = -1; + //MOLD HEATER(off:0,on:1) , VIBRATION(off:0,on:1) , VIB. HEATER(off:0,on:1) + moldHeaterMotor = -1; + vibrationMotor = -1; + vibHeaterMotor = -1; + //Pedal(manual=0,auto=1) + pedalMotor = -1; + //Recipe Start + startRecipe = 0; + sendComTankTemp = -1; + //phase 1 heating + Heating = -1; + sendComHeating = -1; + setHeatingTimerOnce = -1; + heatingSeconds = 0; + //phase 2 cooling + cooling = -1; + sendComCooling = -1; + setCoolingTimerOnce = -1; + coolingSeconds = 0; + //phase 3 pouring + pouring = -1; + sendComPouring = -1; + setPouringTimerOnce = -1; + pouringSeconds = 0; + //start the pumb + PumbOn = -1; + pedalOffSeconds = 0; + pedalOnSeconds = 0; + setPedalTimerOnce = -1; + Dispatcher.UIThread.Post(() => + { + recipeStartBtn.Foreground = Avalonia.Media.Brushes.White; + recipeStartBtn.Background = Brush.Parse("#008000"); + recipeStartBtn.Content = "START RECIPE"; + PreHeatingBtn.IsEnabled = true; + recipeStartBtn.IsEnabled = true; + }); + + + + + } + + + private async void ResetErrors(object? sender, RoutedEventArgs e) + { + holdingRegister.resetError = (ushort)(1 << 0); + await WriteToSerialAsync("ResetErrors"); + + } + private async void OnWarningPopupOverlayPointerPressed(object? sender, RoutedEventArgs e) + { + warningPopupOverlay.IsVisible = false; + + } + private async void OnErrorPopupOverlayPointerPressed(object? sender, RoutedEventArgs e) + { + errorPopupOverlay.IsVisible = false; + + } + + + + public static class MessageBox + { + public static async Task Show(Window owner, string message, string title) + { + var dialog = new Window + { + Title = title, + Width = 300, + Height = 150, + WindowStartupLocation = WindowStartupLocation.CenterOwner, + Topmost = false, + Content = new StackPanel + { + Children = + { + new TextBlock + { + Text = message, + Margin = new Thickness(10), + HorizontalAlignment = HorizontalAlignment.Center + }, + new Button + { + Content = "OK", + Margin = new Thickness(10), + HorizontalAlignment = HorizontalAlignment.Center + } + } + } + }; + + var button = (Button)((StackPanel)dialog.Content).Children[1]; + button.Click += (s, e) => dialog.Close(); + + owner.Topmost = false; + await dialog.ShowDialog(owner); + owner.Topmost = true; + owner.Activate(); + + // Restart keyboard to bring it on top + var (fileName, args) = GetKeyboardCommand(); + if (!string.IsNullOrEmpty(fileName)) + { + try + { + Process.Start(fileName, args); + } + catch + { + // Handle exceptions if needed + } + } + } + + private static (string? fileName, string args) GetKeyboardCommand() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + return ("osk.exe", ""); + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + return ("onboard", ""); // or "florence", "matchbox-keyboard" + return (null, ""); + } + } + } +} + +============================================================ +FILE: DaireApplication/App.axaml +============================================================ + + + + + + + + + + + + + + + + + +============================================================ +FILE: DaireApplication/App.axaml.cs +============================================================ +using Avalonia; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Markup.Xaml; +using DaireApplication.ViewModels; +using DaireApplication.Views; + +namespace DaireApplication +{ + public partial class App : Application + { + public override void Initialize() + { + AvaloniaXamlLoader.Load(this); + } + public override void OnFrameworkInitializationCompleted() + { + // Migrate CSV files by adding missing columns with default values + DataBase.DataPathManager.MigrateCsvFiles(); + + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + { + desktop.MainWindow = new MainWindow + { + DataContext = new MainWindowViewModel(), + }; + } + + base.OnFrameworkInitializationCompleted(); + } + + } +} + +============================================================ +FILE: DaireApplication/app.manifest +============================================================ + + + + + + + + + + + + + + + + +============================================================ +FILE: DaireApplication/Program.cs +============================================================ +using Avalonia; +using Avalonia.Controls; +using Avalonia.ReactiveUI; +using AvaloniaApplication1.DataBase; +using System; +using System.Threading.Tasks; + +namespace DaireApplication +{ + internal sealed class Program + { + // Initialization code. Don't use any Avalonia, third-party APIs or any + // SynchronizationContext-reliant code before AppMain is called: things aren't initialized + // yet and stuff might break. + [STAThread] + public static void Main(string[] args) => BuildAvaloniaApp() + .StartWithClassicDesktopLifetime(args); + public static UserTable? currentUser; + + public static int pouringMinTemp = -5; + public static int absoluteMaxTemp = 70; + public static int absoluteMinTemp = -10; + // Avalonia configuration, don't remove; also used by visual designer. + public static AppBuilder BuildAvaloniaApp() + => AppBuilder.Configure() + .UsePlatformDetect() + .WithInterFont() + .LogToTrace() + .UseReactiveUI(); + + + } +} + + +============================================================ +FILE: DaireApplication/ViewLocator.cs +============================================================ +using Avalonia.Controls; +using Avalonia.Controls.Templates; +using DaireApplication.ViewModels; +using System; + +namespace DaireApplication +{ + public class ViewLocator : IDataTemplate + { + + public Control? Build(object? param) + { + if (param is null) + return null; + + var name = param.GetType().FullName!.Replace("ViewModel", "View", StringComparison.Ordinal); + var type = Type.GetType(name); + + if (type != null) + { + return (Control)Activator.CreateInstance(type)!; + } + + return new TextBlock { Text = "Not Found: " + name }; + } + + public bool Match(object? data) + { + return data is ViewModelBase; + } + } +} + + +============================================================ +FILE: README.md +============================================================ +# copyVersoin + + + +## Getting started + +To make it easy for you to get started with GitLab, here's a list of recommended next steps. + +Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! + +## Add your files + +- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files +- [ ] [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command: + +``` +cd existing_repo +git remote add origin https://gitlab.com/wael.badawi2000/copyversoin.git +git branch -M main +git push -uf origin main +``` + +## Integrate with your tools + +- [ ] [Set up project integrations](https://gitlab.com/wael.badawi2000/copyversoin/-/settings/integrations) + +## Collaborate with your team + +- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) +- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) +- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) +- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) +- [ ] [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/) + +## Test and Deploy + +Use the built-in continuous integration in GitLab. + +- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/) +- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) +- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) +- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) +- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) + +*** + +# Editing this README + +When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. + +## Suggestions for a good README + +Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. + +## Name +Choose a self-explaining name for your project. + +## Description +Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. + +## Badges +On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. + +## Visuals +Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. + +## Installation +Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. + +## Usage +Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. + +## Support +Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. + +## Roadmap +If you have ideas for releases in the future, it is a good idea to list them in the README. + +## Contributing +State if you are open to contributions and what your requirements are for accepting them. + +For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. + +You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. + +## Authors and acknowledgment +Show your appreciation to those who have contributed to the project. + +## License +For open source projects, say how it is licensed. + +## Project status +If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. \ No newline at end of file