diff --git a/AGENTS.md b/AGENTS.md deleted file mode 100644 index ce39b43..0000000 --- a/AGENTS.md +++ /dev/null @@ -1,49 +0,0 @@ -# AGENTS.md - -See [CLAUDE.md](CLAUDE.md) for detailed architecture, DI wiring, and settings flow. - -## Build - -```bash -dotnet build EvenBetterFastSim.sln -dotnet run --project EvenBetterFastSim/EvenBetterFastSim.csproj -``` - -Configurations: `Debug` and `Release` (use the `SecsGemBase.MessageHandling` / `SecsGemBase.ScenarioEngine` pre-release NuGet packages from nuget.org), `DebugLocal` (uses SecsGemBase DLLs from `%USERPROFILE%\source\repos\SecsGemBase\`). - -No linter, no typecheck. Tests: `EvenBetterFastSim.Tests` (xUnit v3 via VSTest, package `xunit.v3.mtp-off`) — build the app first, then test: - -```bash -dotnet build EvenBetterFastSim.sln -c DebugLocal -dotnet test EvenBetterFastSim.Tests -``` - -## Where stuff lives - -| What | Where | -|---|---| -| DI wiring | `App.xaml.cs:ConfigureServices()` | -| Central VM | `WPF/ViewModels/MainViewModel.cs` | -| Library manager | `WPF/LibraryManager/SecsGemLibraryManager.cs` | -| Settings | `Services/ApplicationSettings.cs` | -| XAML windows | `WPF/Windows/` | -| Event/report/variable mgmt | `WPF/LibraryManager/EventLibraryManager.cs` | - -## Docs - -- [specification/project_overview.md](specification/project_overview.md) — architecture summary -- [specification/patterns.md](specification/patterns.md) — coding rules -- [specification/dialog_pattern.md](specification/dialog_pattern.md) — dialog wiring -- [specification/secsgembase_library.md](specification/secsgembase_library.md) — SecsGemBase internals -- [specification/features.md](specification/features.md) — feature log -- [specification/scenario-system.md](specification/scenario-system.md) — scenario engine reference -- [specification/scenario-canvas-selection-deletion.md](specification/scenario-canvas-selection-deletion.md) — canvas selection/deletion -- [SESSION_REFACTORING_LOG.md](SESSION_REFACTORING_LOG.md) — SecsGemItem generic refactor log - -## Gotchas - -- **Settings are not written to `appsettings.json`.** Defaults come from `appsettings.json`, runtime edits are saved to `%APPDATA%/EvenBetterFastSim/usersettings.json` only on app close. -- **Add children via `child.SetParent(parent)`**, never assign `Children` directly. -- **DebugLocal** needs the SecsGemBase repo built first at `%USERPROFILE%\source\repos\SecsGemBase\`. -- **`CopyFrom()`** on settings fires `PropertyChanged` which triggers an automatic connection restart. -- **Ordering fix**: If SEND/RECEIVE timestamps appear out of order, add (or check for) `.ConfigureAwait(false)` on `await SendDataMessage(...)` in `CommunicationHandler.SendAndLogMessage()` in SecsGemBase. Without it, the SEND timestamp gets captured on the WPF dispatcher instead of immediately after TCP send, and a fast reply can get an earlier timestamp. diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 6db3860..0000000 --- a/CLAUDE.md +++ /dev/null @@ -1,214 +0,0 @@ -# CLAUDE.md - -This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. - -## Build & Run - -```bash -dotnet build EvenBetterFastSim.sln -dotnet run --project EvenBetterFastSim/EvenBetterFastSim.csproj -``` - -Build configurations: `Debug` and `Release` (use the public `SecsGemBase.*` NuGet packages from nuget.org — `SecsGemBase.MessageHandling` and `SecsGemBase.ScenarioEngine`), `DebugLocal` (uses local SecsGemBase repo at `%USERPROFILE%\source\repos\SecsGemBase\`). - -When modifying SecsGemBase, publish the updated `SecsGemBase.*` packages to nuget.org, then bump the versions in [EvenBetterFastSim.csproj](EvenBetterFastSim/EvenBetterFastSim.csproj). Or use `DebugLocal` for local iterations: build SecsGemBase first (`dotnet build` in that repo), then rebuild EvenBetterFastSim with `-c DebugLocal`. - -### Tests - -`EvenBetterFastSim.Tests` is an xUnit v3 project covering the SecsGemItem binary-save flow. It is an executable: v3 runs the tests in their own process, started from `EvenBetterFastSim.Tests.exe`. It uses `xunit.v3.mtp-off`, so `dotnet test` stays on VSTest; plain `xunit.v3` would bring Microsoft Testing Platform v2, and `dotnet test` on the .NET 10 SDK then fails unless a `global.json` opts into MTP. It validates the **shipping build**, so it references the DLLs from the app's `Release` output (public SecsGemBase NuGet packages, not `DebugLocal`). Build the app in Release first, as its own `dotnet` invocation — the test project's reference glob is expanded at evaluation time and needs the app output to already exist: - -```bash -dotnet build EvenBetterFastSim/EvenBetterFastSim.csproj -c Release -dotnet test EvenBetterFastSim.Tests -c Release -``` - -Don't run `dotnet build EvenBetterFastSim.sln` from clean — the test project would evaluate its glob before the app output exists. This is what CI does ([.github/workflows/ci.yml](.github/workflows/ci.yml)). - -`EvenBetterFastSim.Tests` is an xUnit project covering the SecsGemItem binary-save flow. It references the DLLs from the app's `DebugLocal` output, so build the app first: - -```bash -dotnet build EvenBetterFastSim.sln -c DebugLocal -dotnet test EvenBetterFastSim.Tests -``` - -## Docs - -- [README.md](README.md) — user guide -- [specification/project_overview.md](specification/project_overview.md) — architecture summary -- [specification/patterns.md](specification/patterns.md) — coding rules -- [specification/dialog_pattern.md](specification/dialog_pattern.md) — dialog wiring -- [specification/secsgembase_library.md](specification/secsgembase_library.md) — SecsGemBase internals -- [specification/features.md](specification/features.md) — feature log -- [specification/scenario-system.md](specification/scenario-system.md) — scenario engine reference -- [specification/scenario-canvas-selection-deletion.md](specification/scenario-canvas-selection-deletion.md) — canvas selection/deletion -- [SESSION_REFACTORING_LOG.md](SESSION_REFACTORING_LOG.md) — SecsGemItem generic refactor log - -### Testing HSMS connection behaviour - -To reproduce connection/SelectReq issues without real equipment, use a PowerShell TCP listener that accepts a connection but sends nothing (triggers T6 timeout): - -```powershell -$listener = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Any, 5000) -$listener.Start() -$client = $listener.AcceptTcpClient() -Read-Host "Press Enter to close" -$client.Close() -$listener.Stop() -``` - -## Architecture - -**EvenBetterFastSim** is a WPF desktop app (.NET 10, C# preview) that simulates SECS/GEM semiconductor equipment communication. It uses MVVM + Microsoft DI. - -### Layer Overview - -| Layer | Location | Responsibility | -|---|---|---| -| Presentation | `WPF/Windows/`, `WPF/ViewModels/` | XAML views + CommunityToolkit.MVVM ViewModels | -| Library Management | `WPF/LibraryManager/` | Loads Events, Reports, Equipment Variables; parses SECS/GEM XML libraries | -| Communication | via `SecsGemBase.MessageHandling` NuGet | HSMS TCP/IP protocol, message transactions, control state machine | -| Logging | `Logging/` | `ILogService` → `ObservableCollection` bound to UI | -| Configuration | `appsettings.json` + `Services/ApplicationSettings.cs` | Strongly-typed settings (network, HSMS timers) via `Microsoft.Extensions.Configuration` | - -### DI Wiring - -All composition happens in [App.xaml.cs](EvenBetterFastSim/App.xaml.cs) `ConfigureServices()`: -- **Scoped**: `MainViewModel`, `ViewModelLocator`, `CommunicationHandler`, message handlers -- **Transient**: Dialog ViewModels (Add/Edit) -- **Singleton**: Configuration, `ILoggerProvider` - -### Key Files - -- [App.xaml.cs](EvenBetterFastSim/App.xaml.cs) — startup, DI setup -- [WPF/ViewModels/MainViewModel.cs](EvenBetterFastSim/WPF/ViewModels/MainViewModel.cs) — central orchestrator -- [WPF/LibraryManager/EventLibraryManager.cs](EvenBetterFastSim/WPF/LibraryManager/EventLibraryManager.cs) — events/reports/variables registry -- [Services/ApplicationSettings.cs](EvenBetterFastSim/Services/ApplicationSettings.cs) — settings binding -- [Library/](EvenBetterFastSim/Library/) — XML definitions for SECS/GEM messages - -### Scenario Canvas - -The scenario editor uses **Nodify** (v7.3.0) for the node graph canvas. See **[specification/scenario-system.md](specification/scenario-system.md)** for full architecture documentation covering node types, selection/deletion, transaction deep-copy, message comparison, execution engine, drag-and-drop, and persistence. - -### Patterns - -- **MVVM**: `ObservableObject` + `RelayCommand` from CommunityToolkit.MVVM; `EventToCommandAdaptor` bridges WPF events to commands -- **Dialogs**: `WindowManager` + `CloseAction` callback + `DialogMode` enum (Add/Edit) -- **Results**: `FluentResults` for error handling -- **SECS/GEM protocol**: configured via HSMS parameters (T3–T8 timers, SessionId) in `appsettings.json` - -## Multi-instance Hub - -Launching the app **without** arguments shows `LauncherWindow` (the "Hub", VM `LauncherViewModel`) -instead of `MainWindow`. The Hub manages named `InstanceProfile`s (name + IP/port/mode) stored in -`%APPDATA%\EvenBetterFastSim\profiles\profiles.json` and launches each as its **own process** via -`Process.Start(... --profile )`. "New linked pair" creates a Passive + Active profile sharing -one endpoint so two instances can talk immediately. - -`Services/InstanceContext.cs` reads `--profile ` at startup (first line of -`App.ConfigureServices()`) and redirects every per-instance file to -`%APPDATA%\EvenBetterFastSim\profiles\\` — `SaveToJsonService.UserSettingsPath` and -`ScenariosViewModel.ScenariosIndexPath` both derive from `InstanceContext.SettingsDirectory`. -No profile ⇒ the legacy `%APPDATA%\EvenBetterFastSim\` paths (backward compatible). -`InstanceProfileStore.SeedSettingsFile()` merges the profile's endpoint into that folder's -`usersettings.json` on create/edit/launch, preserving other in-app setting edits. -`MainViewModel.WindowTitle` shows the profile name + endpoint so instances are distinguishable. - -## Settings Change Flow - -Port properties (IP, port, connection mode, HSMS timers) are edited in `SetUpWindow` / `SetUpViewModel`. The viewmodel holds local copies (`NetworkSettingsCopy`, `HsmsParametersCopy`) so the user can cancel without affecting the live state. - -On OK: `AcceptButtonClick` → `SaveServiceAggregator.Save()` → `SaveService.Save()` → `destination.CopyFrom(source)` on the scoped `INetworkSettings` / `IHSMSParameters` instances. - -`CopyFrom` sets three properties individually, each firing `PropertyChanged`. `CommunicationHandler` (in SecsGemBase) subscribes to these events and automatically restarts the connection if the port is open — no manual disconnect/reconnect is needed. Multiple rapid property-change events are coalesced into a single restart by an Interlocked flag in `CommunicationHandler`. - -Settings are **not** written to `appsettings.json` immediately — they are persisted only when the main window closes (`MainViewModel.OnClosing()` → `SaveToJsonService.Save()`). Unsaved settings survive as long as the process is alive. - -## SecsGemBase (library source) - -The `SecsGemBase.*` NuGet packages are published from the [SecsGemBase repo](https://github.com/Pre-Se/SecsGemBase) (`%USERPROFILE%\source\repos\SecsGemBase\` locally). Key files there: - -- `SecsGemBaseItems/Data Containers/SecsGemItem.cs` — abstract tree node model (`SecsGemValueItem` / `SecsGemListItem` concrete); `Name` is auto-set via `Children.CollectionChanged`. Adding children via `SetParent()` (not direct `Children =` assignment) is required to keep the name in sync. -- `SecsGemBaseItems/Data Containers/ItemFactory.cs` — fluent builder for outgoing messages -- `SecsGemMessageHandling/Data Handling/ControlMessageHandling.cs` — HSMS state machine (NotConnected → NotSelected → Selected); sends SelectReq on connect if `InitiateSelectRequest = true` -- `SecsGemMessageHandling/Data Handling/TransactionHandler.cs` — manages request/reply pairing with T3/T6 timeouts; calls `RestartConnection()` internally on timeout -- `SecsGemMessageHandling/Data Handling/MessageParsing.cs` — parses raw bytes into `SecsGemItem` tree - -## Message Logging System - -Messages (SECS/GEM data and control) are logged to a `TreeView` in the right panel of the main window. - -### Architecture - -``` -EventBus (ThreadPoolScheduler) - │ - ├── OnDataMessageIn → SecsMessageLogger.MessageIn() - ├── OnDataMessageOut → SecsMessageLogger.MessageOut() - ├── OnControlMessageIn → SecsMessageLogger.ControlMessageIn() - └── OnControlMessageOut → SecsMessageLogger.ControlMessageOut() - │ - ▼ - AddItemToCollection() - │ - Dispatcher.InvokeAsync(() => - MessagesLog.Add(message)) -``` - -`SecsMessageLogger` simply appends via `Dispatcher.InvokeAsync`. No sequence-number sorting is needed because timestamps are captured in the right order on the send/receive paths (see below). - -### Out-of-Order Fix - -`CommunicationHandler.SendAndLogMessage()` (in SecsGemBase) creates the `LoggedDataMessage` (capturing `TimeStamp = DateTime.Now`) after `await SendDataMessage(...)`. Without `.ConfigureAwait(false)`, the continuation marshals back to the WPF dispatcher because the async chain originated on the UI thread. Meanwhile, `ParseDataReceived()` captures its timestamp immediately on the TCP thread. If the dispatcher is busy, the SEND timestamp can be captured **after** the RECEIVE timestamp — making the send appear later than its reply. - -**Fix** ([CommunicationHandler.cs:187](https://github.com/Pre-Se/SecsGemBase/blob/initialCommit/SecsGemMessageHandling/Data%20Handling/CommunicationHandler.cs)): - -``` -var (status, rawData, header) = await SendDataMessage(message, systemBytes).ConfigureAwait(false); -``` - -`.ConfigureAwait(false)` keeps the continuation on the thread pool, so `DateTime.Now` runs immediately after the TCP send completes — before the reply can arrive. - -The logger (`SecsMessageLogger`) simply appends via `Dispatcher.InvokeAsync(() => MessagesLog.Add(...))`. No sequence‑number sorting is needed because the timestamps are now chronologically correct. - -### UI Template - -Each log item renders as: - -``` -[↑/↓ icon] [HH:mm:ss.fff] [message name] -``` - -Defined in [MainWindow.xaml](EvenBetterFastSim/WPF/Windows/MainWindow.xaml) lines 715–757 with two `HierarchicalDataTemplate`s (one for `LoggedControlMessage`, one for `LoggedDataMessage`): - -| Element | Details | -|---|---| -| Icon | `ArrowCircleUp20` (sent, `#00CC44`) / `ArrowCircleDown20` (received, `#0088FF`), bound by `DataTrigger` on `MessageResult` | -| Timestamp | `{Binding TimeStamp, StringFormat={}{0:HH:mm:ss.fff}}` | -| Message | `Data.Header` for data messages (e.g. `"S1F13"`); `Header` with `MsgHeaderConverter` for control messages (strips leading timestamp and `Sent`/`Received` prefix) | - -The `MsgHeaderConverter` ([MessageHeaderConverter.cs](EvenBetterFastSim/Helpers/MessageHeaderConverter.cs)) strips `"Sent "` / `"Received "` (data messages) and leading `"HH:mm:ss.fff "` pattern + `"Sent"`/`"Received"` (control messages) from the `Header` string so only the message name remains. - -### Colors - -| Direction | Icon | Hex | -|---|---|---| -| Sent (outgoing) | ↑ `ArrowCircleUp20` | `#00CC44` | -| Received (incoming) | ↓ `ArrowCircleDown20` | `#0088FF` | - -### Cloning - -`SecsGemItem` is abstract and declares `abstract SecsGemItem Clone()`; the concrete `SecsGemValueItem` / `SecsGemListItem` implement it. `SecsGemTransaction` implements `IDeepCloneable`, and `SecsGemDataMessage` exposes `Clone()` via `ISecsGemDataMessage`. **No `MemberwiseClone` anywhere** — clones are built with explicit `new T()` + `CopyFrom()` + recursive `child.SetParent(clone)`. See [specification/patterns.md](specification/patterns.md) and [specification/secsgembase_library.md](specification/secsgembase_library.md). - -`SecsGemDataMessage.Clone()` returns `ISecsGemDataMessage`; cast to `SecsGemDataMessage` when assigning to the `PrimaryMessage`/`ReplyMessage` setters. - -### `ICanBeParent` — plain methods, not commands - -`ICanBeParent` exposes three methods for parent-child wiring: - -```csharp -bool CanAddChild(IDataItem? child); -bool TryAddChild(IDataItem child); -bool TryRemoveChild(IDataItem child); -``` - -`DataItem.SetParent` calls these directly. **Do not go back to exposing `IRelayCommand` on this interface.** Commands hold delegates bound to a specific instance; `MemberwiseClone` copies the backing field by reference, so any command on a clone would silently execute on the original. Plain methods are resolved on the actual instance at call time and have no such problem. diff --git a/SESSION_REFACTORING_LOG.md b/SESSION_REFACTORING_LOG.md deleted file mode 100644 index 8afa1e5..0000000 --- a/SESSION_REFACTORING_LOG.md +++ /dev/null @@ -1,162 +0,0 @@ -# Refactoring Session Log — June 2026 (refactor complete) - -Related docs: [CLAUDE.md](CLAUDE.md), [specification/secsgembase_library.md](specification/secsgembase_library.md), [specification/patterns.md](specification/patterns.md). - -## Summary - -Refactored `SecsGemItem` from a single string-typed class to a generic type hierarchy (`SecsGemItem` abstract base → `SecsGemValueItem` + `SecsGemListItem`). Eliminates the hex-string round-trip for binary file uploads, making 500KB+ binary sends near-instant instead of hundreds of milliseconds. - -**~25 files changed across SecsGemBase and EvenBetterFastSim repos.** - ---- - -## Architecture Change - -### Before -``` -DataItem → SecsGemItem (concrete) - Values: ObservableCollection // "FF", "00", "A3", ... -``` -Binary values stored as 500K heap-allocated hex strings. Send path: join 500K strings → parse hex → bytes. ~26MB GC pressure. - -### After -``` -DataItem → SecsGemItem (abstract) - ├── SecsGemListItem (FormatType = List) - └── SecsGemValueItem (all value types) - Values: ObservableCollection -``` -Binary uses `T=byte`. 500KB = 500K entries in a contiguous `byte[]` backing array. No per-element GC allocations. Send path: `Values.CopyTo(result, 0)` — single memcpy. - -### T → FormatType Mapping - -| `T` | FormatTypes | -|---|---| -| `byte` | Binary, U1 | -| `sbyte` | I1 | -| `bool` | Boolean | -| `ushort` | U2 | -| `short` | I2 | -| `uint` | U4 | -| `int` | I4 | -| `ulong` | U8 | -| `long` | I8 | -| `float` | Float | -| `double` | Double | -| `string` | ASCII, JIS8, TwoByteCharacter | - -`FormatType` stays on the base to distinguish wire-level encoding (e.g., Binary vs U1 both use `T=byte`, but have different SECS II format bytes). - ---- - -## All Files Changed - -### SecsGemBase Repo (`%USERPROFILE%\source\repos\SecsGemBase\`) - -#### NEW FILES -- `SecsGemBaseItems/Data Containers/SecsGemValueItem.cs` — Generic value item -- `SecsGemBaseItems/Data Containers/SecsGemListItem.cs` — List item type - -#### REWRITTEN FILES -- `SecsGemBaseItems/Data Containers/SecsGemItem.cs` — Made abstract. Added: - - `Create(SecsGemItemFormatType)` factory method - - `GetBoxedValues()` / `GetStringValues()` / `SetValuesFromStrings()` non-generic accessors - - `CheckValue()` uses `GetStringValues()` (produces hex for Binary) - - `CreateItemHeaderBytes()`, `GetLengthBytes()` moved to base - - `IsEquivalent()` uses `GetBoxedValues()` - -- `SecsGemBaseItems/Data Containers/ItemFactory.cs` — Each `AddXxx()` creates typed `SecsGemValueItem` - -- `SecsGemMessageHandling/Data Handling/MessageParsing.cs` — `ReadItem` uses `SecsGemItem.Create()`, `ReadItemData` dispatches by runtime type - -- `SecsGemBaseItems/Data Containers/SecsGemDataMessage.cs` — Uses `OfType()` instead of `Cast()` - -- `SecsGemBaseItems/Data Containers/Serialization/SecsGemTransactionJsonConverter.cs` — Uses `Create()`, `GetStringValues()`, `SetValuesFromStrings()` - -- `SecsGemBaseItems/XMLParser.cs` — Uses `Create()`, `SetValuesFromStrings()` - -#### MODIFIED FILES -- `SecsGemMessageHandling/Data Handling/DataMessageHandler.cs`: - - `SendCommunicationsRequestAsync` — COMMACK denial logs error + disconnects (was retry loop) - - `HsmsStatusChanged` — added `!CommunicationsEstablished` guard to prevent timer restart after comms established - - `CheckValue` usage in S1F14 validation now works correctly with hex strings - -- `SecsGemMessageHandling/Data Handling/SpecialCasesHandling.cs` — `CheckIfVariableExist` uses `GetBoxedValues()` instead of `Values.Count` - -- `SecsGemMessageHandling/Events/Models/SecsGemEquipmentVariable.cs` — `Item` default is `SecsGemValueItem`, `Value` getter/setter uses `GetStringValues()`/`SetValuesFromStrings()` - -- `SecsGemMessageHandling/Events/SecsGemEventReportHandler.cs` — `Values[0]` → `GetStringValues().FirstOrDefault()`, `Values is [var first, ..]` → `GetBoxedValues().FirstOrDefault()`, `new SecsGemItem()` → `SecsGemItem.Create()` - -### EvenBetterFastSim Repo - -#### REWRITTEN FILES -- `WPF/ViewModels/SecsGemItemViewModel.cs` — File upload sets `SecsGemValueItem.Values` directly, no hex string split. Added `EnsureCorrectCopyType()` for FormatType changes. - -- `WPF/ViewModels/InspectSecsGemItemViewModel.cs` — Display uses `GetStringValues()` instead of `item.Values` - -- `WPF/ViewModels/AddEquipmentVariableViewModel.cs` — `SetValuesFromStrings()`, `GetStringValues()`, `EnsureCorrectCopyType()` - -- `Services/LibraryJsonService.cs` — `GetStringValues()`, `SetValuesFromStrings()`, `SecsGemItem.Create()` - -- `Services/LibraryMessagePackService.cs` — `GetStringValues()`, `SetValuesFromStrings()`, `SecsGemItem.Create()` - -- `Services/LibraryXmlExportService.cs` — `GetStringValues()` instead of `item.Values` - -#### MODIFIED FILES -- `WPF/ViewModels/MainViewModel.cs` — `new SecsGemItem()` → `SecsGemItem.Create(SecsGemItemFormatType.U1)` - -- `Services/ModelViewModelMapper.cs` — `GetViewModel()` walks inheritance chain (`SecsGemValueItem` → `SecsGemItem` → found) instead of exact type match - ---- - -## Bugs Found and Fixed - -### 1. S1F13/S1F14 Infinite Loop -**Root cause:** `CheckValue(SecsGemItemFormatType.Binary, ["00"])` compared `byte.ToString()` = `"0"` against expected hex `"00"`. Always failed → handshake retry forever. -**Fix:** `CheckValue` now uses `GetStringValues()` which returns `"00"` for Binary byte 0. - -### 2. "No view model registered" when opening item dialog -**Root cause:** `ModelViewModelMapper.GetViewModel()` used `dataItem.GetType()` as dictionary key. Runtime types (`SecsGemValueItem`) not registered. -**Fix:** Walk inheritance chain until a registered mapping is found. - -### 3. Missing JIS8/TwoByteCharacter in Create() -**Root cause:** `SecsGemItem.Create()` switch didn't handle JIS8/TwoByteCharacter → `ArgumentOutOfRangeException`. -**Fix:** Added to switch, map to `SecsGemValueItem`. - -### 4. COMMACK denial retry loop -**Root cause:** `SendCommunicationsRequestAsync` returned `false` on COMMACK != 0, causing infinite retry. -**Fix:** COMMACK denial now logs error, calls `RestartConnection()`, returns `true` (stops timer). Also: `HsmsStatusChanged` guarded with `!CommunicationsEstablished` to prevent timer restart after comms is established. - -### 5. Self-induced bug from EventReportHandler rewrite -**Root cause:** Originally attempted full rewrite of `SecsGemEventReportHandler.cs` with incorrect types (`IRegistry` instead of `IRegistry`). -**Fix:** Reverted to original via `git checkout`, applied only minimal changes to `.Values` access. - ---- - -## Files Re-Applied — Final State (done) - -The following EvenBetterFastSim files were reverted to their pre-refactoring state during the session and have since been re-applied and verified (Sept 2026). The refactor is live in both repos. - -| File | Status | -|---|---| -| `WPF/ViewModels/SecsGemItemViewModel.cs` | ✅ Uses `SecsGemItem.Create()`, `SecsGemValueItem`, `EnsureCorrectCopyType()` | -| `WPF/ViewModels/InspectSecsGemItemViewModel.cs` | ✅ Uses `GetStringValues()` | -| `WPF/ViewModels/AddEquipmentVariableViewModel.cs` | ✅ Uses `SecsGemItem.Create()`, `EnsureCorrectCopyType()` | -| `WPF/ViewModels/MainViewModel.cs` | ✅ `SecsGemItem.Create(SecsGemItemFormatType.U1).SetParent(parent)` (line 217) | -| `Services/LibraryJsonService.cs` | ✅ Uses `SecsGemItem.Create()`, `GetStringValues()`, `SetValuesFromStrings()` | -| `Services/LibraryMessagePackService.cs` | ✅ Uses `SecsGemItem.Create()`, `SetValuesFromStrings()` | -| `Services/LibraryXmlExportService.cs` | ✅ Uses `GetStringValues()` | - -Covered by tests: `EvenBetterFastSim.Tests/SecsGemItemBinaryTests.cs` (binary manual-hex entry + empty entry round-trip). - ---- - -## Message Log Out of Order — RESOLVED (via `ConfigureAwait(false)`) - -**Original problem:** Sent messages sometimes appeared after received messages in the message log tree view. - -**Root cause:** `CommunicationHandler.SendAndLogMessage()` captured the SEND timestamp after `await SendDataMessage(...)`. Without `.ConfigureAwait(false)`, the continuation marshaled back to the WPF dispatcher, so the SEND timestamp could be captured after the RECEIVE timestamp. - -**Fix (implemented):** `await SendDataMessage(message, systemBytes).ConfigureAwait(false);` in `SecsGemMessageHandling/Data Handling/CommunicationHandler.cs:187` ([GitHub](https://github.com/Pre-Se/SecsGemBase/blob/initialCommit/SecsGemMessageHandling/Data%20Handling/CommunicationHandler.cs)). The continuation stays on the thread pool, so `DateTime.Now` runs immediately after the TCP send. `SecsMessageLogger` keeps its simple `Dispatcher.InvokeAsync(() => MessagesLog.Add(...))` append — no sequence-number sorting was needed. See [CLAUDE.md](CLAUDE.md#message-logging-system). - -**Obsolete planned fix (not implemented):** Adding `SequenceNumber` to `ILoggedSecsGemMessage` + binary-search insert in `SecsMessageLogger` — superseded by the timestamp fix above. diff --git a/specification/dialog_pattern.md b/specification/dialog_pattern.md deleted file mode 100644 index 6b7961b..0000000 --- a/specification/dialog_pattern.md +++ /dev/null @@ -1,48 +0,0 @@ -# Dialog Pattern - -Related docs: [patterns.md](patterns.md), [project_overview.md](project_overview.md), [CLAUDE.md](../CLAUDE.md) - -## How a dialog opens - -1. Command in `MainViewModel` calls `ViewModelLocator.GetViewModel()` (resolves from DI) -2. Set data on the VM after resolution: `vm.Item = item` or `vm.Initialize(item)` -3. `WindowManager.ShowDialog(vm)` → `WindowMapper` maps VM type → Window → creates window, sets DataContext, shows modal - -## Three files to update for every new dialog - -| File | What to add | -|---|---| -| `App.xaml.cs` | `services.AddTransient()` | -| `Services/WindowMapper.cs` | `TViewModel → DialogWindow` mapping | -| `Window Helpers/DialogWindow.xaml` | `DataTemplate DataType=TViewModel` → UserControl | - -## Current dialog mappings (`Services/WindowMapper.cs`) - -| ViewModel | View | Status | -|---|---|---| -| `SecsGemItemViewModel` | `SecsGemItemView` | Done | -| `SecsGemDataMessageViewModel` | `SecsGemDataMessageView` | Done | -| `InspectSecsGemItemViewModel` | `InspectSecsGemItemView` | Done | -| `SecsGemTransactionViewModel` | `SecsGemTransactionView` | Done | -| `AddEventReportViewModel` | `AddEventReportView` | Done | -| `AddReportViewModel` | `AddReportView` | Done | -| `AddEquipmentVariableViewModel` | `AddEquipmentVariableView` | Done | -| `InstanceProfileViewModel` | `InstanceProfileView` | Done | -| `NodeResponderViewModel` | `NodeResponderView` | Done | -| `NodeMillisecondsViewModel` | `NodeMillisecondsView` | Done (constructed by the caller, not registered in DI) | -| `SetUpViewModel` | `SetUpWindow` | Done | - -## ViewModel conventions - -- `CloseAction` callback — set by the Window, invoked by VM on Accept/Cancel -- **Standard (per [patterns.md](patterns.md))**: don't read `ISecsGemLibraryManager.SelectedItem` in the constructor — resolve the VM, then pass the item after (`vm.Item = item` / `vm.Initialize(item)`). Shared mutable state in DI is unreliable. -- **Legacy (still present in several VMs)**: constructor injection of `ISecsGemLibraryManager`, reading `SelectedItem` directly in the constructor (`SecsGemItemViewModel`, `SecsGemTransactionViewModel`, `AddEquipmentVariableViewModel`). Prefer the standard for new dialogs. -- On Accept: write directly to the item (`item.CopyFrom(copy)` or set properties) then `CloseAction?.Invoke()` -- On Cancel: `CloseAction?.Invoke()` only - -## Double-click bindings (MainWindow.xaml) - -`MouseBinding LeftDoubleClick` on a `StackPanel.InputBindings` inside each TreeView `DataTemplate`. Command bound via `RelativeSource AncestorType=TreeView` to reach the TreeView's `DataContext` (MainViewModel). - -- Library TreeView templates → `ModifySelectedItemCommand` -- Messages Log TreeView SecsGemItem → `InspectLoggedItemCommand` diff --git a/specification/features.md b/specification/features.md deleted file mode 100644 index 8b44504..0000000 --- a/specification/features.md +++ /dev/null @@ -1,173 +0,0 @@ -# Features - -Related docs: [project_overview.md](project_overview.md), [secsgembase_library.md](secsgembase_library.md), [dialog_pattern.md](dialog_pattern.md), [SESSION_REFACTORING_LOG.md](../SESSION_REFACTORING_LOG.md) - -## Connection drop nodes on the canvas - -The nodes **Drop connection** and **Wait for communication** can be made and edited in the app, and the app uses the -SecsGemBase packages `1.0.0-build-0029` that execute them (internal board, issue 25). A scenario can now drop the -connection after an event, keep the port closed for a time and go on when communication is back. - -**Files:** `EvenBetterFastSim.csproj` (package versions), `WPF/ViewModels/Graph/NodeMilliseconds.cs`, -`DropConnectionTime.cs`, `CommunicationTimeout.cs`, `ScenarioNodeViewModel.cs` (outputs, titles, palette defaults), -`WPF/ViewModels/NodeMillisecondsViewModel.cs` (`For`), `WPF/ViewModels/ScenariosViewModel.cs` (`OpenNodeEditor`, -`RunOnceAsync`, `PortClosedByScenario`), `Services/PortHold.cs`, `WPF/ViewModels/MainViewModel.cs` (`CanConnect`), -`WPF/Windows/MainWindow.xaml` (palette chips, node colours, Connect button). - -- **Engine:** both nodes run in the SecsGemBase engine (`NodeType.DropConnection` = 8, `WaitForCommunication` = 9). - It needs `CommunicationHandler` and `ControlMessageHandling`; the DI container passes both to - `ScenarioExecutionService`, they are registered in `App.ConfigureServices`. -- **Parameter:** a time in ms as text in `TransactionName`, like the Wait node: the downtime (0 = connect again at - once) and the timeout (0 = as long as the run may take). The engine reads digits only and lets the node fail for - anything else (`NodeMilliseconds.TryReadDigits` reads the same way). -- **Palette:** the chips **DROP CONNECTION** (5000 ms) and **WAIT FOR COMM.** (20000 ms). -- **Outputs:** Success and Failure. Both nodes fail in normal use (no connection to drop, communication not back in - time); a failure without a failure edge ends the run. -- **Title:** "Drop connection · 5000 ms", "Wait for communication · max 20000 ms" or "· no timeout"; a value the - engine cannot read shows as "(invalid: 5 s)", a missing one as "(no downtime set)" / "(no timeout set)". -- **Editor:** `NodeMillisecondsViewModel.For(node)` gives the editor for all three node types with a time in ms; - for these two the minimum is 0 and the hint says what 0 does. -- **Connect button:** disabled while a Drop connection node keeps the port closed; a click would open the port in - the middle of the downtime. The node reports `Waiting` for that time; `PortHold` keeps track per run, and the end - of a run releases its holds (a cancelled run reports nothing more for the node). Changing the endpoint in - Connection ▸ Properties during the downtime does not open the port: the restart only replaces the connection - object, and the node opens the port on the new endpoint when the downtime is over. -- **Files:** no change to the file format. An older build does not know the two node types: it cannot run them and - drops their failure edges when it saves the scenario. -- **Limits** that belong to the engine and the HSMS stack are listed in the README (section 6). - -## Wait node on the canvas - -A Wait node can be made and edited in the app (internal board, issue 18). Until then it only came from an imported -file, its time could only be changed in the file, and a value the engine cannot read ("20 s", "12,6") silently meant -"no wait" while the node only showed its name or the bare number. - -**Files:** `WPF/ViewModels/Graph/WaitTime.cs`, `WPF/ViewModels/Graph/ScenarioNodeViewModel.cs` (`CreateStructural`, -title), `WPF/ViewModels/NodeMillisecondsViewModel.cs`, `WPF/Windows/NodeMillisecondsView.xaml`, -`WPF/ViewModels/ScenariosViewModel.cs` (`OpenNodeEditor`, `AddStructuralNode`), `WPF/Windows/MainWindow.xaml` (palette -chip, node colour), `Window Helpers/DialogWindow.xaml` and `.xaml.cs`, `Services/WindowMapper.cs`. - -- **Palette:** the chip **WAIT** next to AND. Dropping it on the canvas makes a Wait node with 1000 ms. -- **Editor:** double-click, right-click or Enter on the node opens the dialog "Wait" with the field "Wait time (ms)". - It accepts a whole number from 1 to 2147483647 written in digits; OK or Enter writes it to the node's - `TransactionName`, where the engine reads it. Spaces and characters nobody can see at the ends of the text are - ignored; inside the number the message under the field names them. -- **Title:** "Wait 1500 ms". A value the engine cannot read shows as "Wait (invalid: 20 s)", a missing one as - "Wait (no time set)". A character nobody can see in such a value (a non-breaking space from a hand-edited file) - shows as "[U+00A0]". A `DisplayName` from a file no longer replaces the time. -- `WaitTime.TryRead` reads the time like the engine since package `1.0.0-build-0029`: with the invariant culture, - so a file means the same on every computer. Up to `1.0.0-build-0027` the engine read with the culture of the - computer, which could take a leading sign differently. -- `NodeMillisecondsViewModel` takes its title, label and minimum, so other node types with a time in ms can use it. - It is not an `ObservableValidator`: `DialogWindow` binds its content to the view model, and WPF then draws its red - validation frame around the whole dialog. -- The engine logs a warning for a time it cannot read since package `1.0.0-build-0029` - ([SecsGemBase pull request 12](https://github.com/Pre-Se/SecsGemBase/pull/12)); the node still succeeds without - waiting. With the packages before that the wait was skipped silently and the title was the only sign. - -## Scenario runs leave the UI thread - -A scenario (Run or a loop) now executes on the thread pool. Until then every node ran on the WPF UI thread, because -the engine awaits without `ConfigureAwait(false)`: the time between two nodes depended on what the UI was busy with, -and a node that blocks froze the window (internal board, issue 26). - -**Files:** `Services/ScenarioRun.cs` (`RunAsync`, `Snapshot`, `IsStale`), `WPF/ViewModels/ScenariosViewModel.cs` -(`RunOnceAsync`, `LogInfo`/`LogError`), `Logging/ObservableLogger.cs`. - -- `ScenarioRun.RunAsync` takes a `Snapshot` of the graph on the UI thread and starts the engine with `Task.Run`. - `RunOnceAsync` continues on the UI thread after the await; the `Progress` for the canvas is created there. -- The snapshot is a copy nothing else refers to. The stored graph changes on the UI thread during a run (opening a - scenario clears `TransactionJson` of its nodes), and a node from an older file that only names its transaction gets - a copy of the library transaction, so the engine does not read or write the UI-bound library for it. That copy is - written with the invariant culture (the SecsGemBase converter otherwise turns 1,5 into 15 on a decimal-comma system). -- The System Log logger (`ObservableLogger`) queues its entries with `Dispatcher.InvokeAsync`, like - `SecsMessageLogger`, instead of waiting for the UI thread. `ScenariosViewModel` writes its own lines through the - logger too, so they keep their place between the engine's lines. Without a dispatcher (unit tests, shutdown) an - entry is dropped; pass a dispatcher provider as third constructor argument to observe entries in a test. -- Two things the engine did not need on a single thread: runs enter the engine one at a time (it keeps the run's - cancellation source in a field while it starts), and an And node's late "1/2 branches" report no longer replaces - its Succeeded state. - -## Responder panel — edit the message shape - -The node responder dialog (`NodeResponderView`, opened by double-click on a Send / Receive node) now has a -message-editing toolbar above the field tree: **Add Item** (U1 child of the selected list / message body), -**Add Sibling** (U1 after the selection), **Duplicate**, **Delete**, **Up**, **Down** (also `Alt+Up` / -`Alt+Down`). Each row is a left-aligned strip whose first control is an inline **format dropdown** that -retypes the item in place (values carried over best-effort; children preserved when a value item becomes a -list) — there is no separate text label, the dropdown is the item's identity. Works in both modes — Match -conditions (Receive) and Response values (Send). - -**Files:** `WPF/ViewModels/Responders/NodeResponderViewModel.cs` (`workingMessage` clone, `SelectedField`, -`AddItem` / `AddSibling` / `DuplicateItem` / `DeleteItem` / `MoveItem*` commands, `ApplyFormatChange`, -`CommitStructuralChange`), `WPF/ViewModels/Responders/ResponderFieldViewModel.cs` (`Format`, `FormatChoices`, -`FormatChangeRequested`), `WPF/Windows/NodeResponderView.xaml` (toolbar, per-row format combo, selection -binding via `EventToCommandAdaptor.TreeViewSelectedItem`). - -- Edits mutate a clone; on **OK** the new shape is written back to the node's `Transaction` (Primary, or - Reply when `UseReplyMessage`) only if something structural changed, then persisted via `ToModel()` JSON. -- `BuildFields` wraps `workingMessage` directly (no re-clone) so `SecsGemItem` identity is stable across the - tree rebuild — `CommitStructuralChange` uses it to carry pending condition / binding edits over. - -## Inspect received message items - -Double-clicking a `SecsGemItem` in the messages log TreeView opens a read-only inspect dialog. - -**Files:** `InspectSecsGemItemViewModel.cs`, `InspectSecsGemItemView.xaml/.cs`, `MainViewModel.InspectLoggedItemCommand`, `MainWindow.xaml` (MouseBinding on log TreeView), `WindowMapper`, `DialogWindow.xaml`, `App.xaml.cs` - -- `Item` property set after DI resolution -- `UseBase64` toggle for binary display — default hex (`"0xAB CD..."`), toggle Base64 -- `IsHex` = inverse of `UseBase64` for RadioButton TwoWay binding -- Format row visibility controlled by `IsBinary` - -## Binary values as byte[] - -Binary values are stored as `byte[]` (`SecsGemValueItem`) since the generic refactor; `GetStringValues()` renders them as 2-digit uppercase hex strings. See [secsgembase_library.md](secsgembase_library.md) and [SESSION_REFACTORING_LOG.md](../SESSION_REFACTORING_LOG.md) for all touch points. - -## Double-click library items opens edit dialog - -`MouseBinding LeftDoubleClick → ModifySelectedItemCommand` on SecsGemItem, SecsGemDataMessage, and SecsGemTransaction templates in the library TreeView. - -## Clone/duplicate name update bug — fixed - -Replaced MemberwiseClone with explicit `new T() + CopyFrom() + recurse children` in `SecsGemItem.Clone()` and `SecsGemDataMessage.Clone()`. - -## SecsGemTransaction edit dialog - -Fully wired. Double-clicking a transaction in the library TreeView opens a Name + Description edit dialog. - -**Files:** `SecsGemTransactionViewModel.cs`, `SecsGemTransactionView.xaml`, `App.xaml.cs`, `WindowMapper.cs`, `DialogWindow.xaml`, `ModelViewModelMapper.cs` - -- VM takes `ISecsGemLibraryManager` in constructor, reads `SelectedItem as SecsGemTransaction` -- Holds a `transactionCopy` (new SecsGemTransaction); copies Name + Description into it -- On Accept: writes `transaction.Name` and `transaction.Description` directly (no SaveService) -- `ModelViewModelMapper` maps `SecsGemTransaction → SecsGemTransactionViewModel` so `ModifySelectedItemCommand` routes it automatically - -## Upload file as binary - -"File Upload" mode in `SecsGemItemView` — visible only when `FormatType == Binary`. - -- `IsFileUploadMode` property on `SecsGemItemViewModel` (RadioButton "File Upload" / "Manual Entry" toggle) -- `UploadFileCommand`: opens `OpenFileDialog`, reads all bytes straight into `SecsGemValueItem.Values` (no hex string split) -- Button appears inline next to the Value TextBox - -## Save library as XML - -Library → Save as XML menu item writes the current transaction library to an XML file in the same format that `XmlParser` reads. - -**Files:** `Services/LibraryXmlExportService.cs`, `MainViewModel.SaveLibrary()` (bound to `SaveLibraryCommand` in `MainWindow.xaml`) - -- Multi-value items write one `` element per entry; parser reads all of them -- `LibraryXmlExportService` registered as scoped in `App.xaml.cs` - -## Inspect dialog — selectable TextBoxes - -All fields in `InspectSecsGemItemView` use `IsReadOnly="True"` TextBoxes instead of TextBlocks — text is selectable and copyable. Value box has `MaxHeight="200"` and `VerticalScrollBarVisibility="Auto"` to stay bounded. Value binding uses `Mode=OneWay` on the read-only computed `ValuesDisplay` property. - -## XML library — multi-value items round-trip correctly - -`XmlParser.ReadItems` now uses `SelectNodes("Value")` instead of `SelectSingleNode("Value")`. First value replaces `Values[0]`, subsequent values are `Add`ed. Pairs with `LibraryXmlExportService` which writes one `` per entry. - -## Auto-reconnect on server drop - -When the remote server drops the connection, `TCPIPClientBase` fires `OnDisconnected`, which triggers `CommunicationHandler.RestartConnection`. Status updates immediately to `PortOpen` and the reconnect loop starts fresh. Previously the status stayed `Connected` because `OnDisconnected` only fired when the entire connect task ended (on dispose), not on a mid-loop drop. diff --git a/specification/patterns.md b/specification/patterns.md deleted file mode 100644 index 9a0ef10..0000000 --- a/specification/patterns.md +++ /dev/null @@ -1,23 +0,0 @@ -# Patterns and Conventions - -Related docs: [dialog_pattern.md](dialog_pattern.md), [secsgembase_library.md](secsgembase_library.md), [SESSION_REFACTORING_LOG.md](../SESSION_REFACTORING_LOG.md), [CLAUDE.md](../CLAUDE.md) - -## No MemberwiseClone - -Use `new T() + CopyFrom() + recurse children` for all `Clone()` methods. MemberwiseClone copies the entire `PropertyChanged` invocation list — clones fire `SetName`/`SetHeader` on the original, so Name/Header on the clone never updates. - -## No collection replacement after construction - -Never assign a new collection to `Values` or `Children`. Always mutate in-place (Clear + Add each). The constructor subscribes `CollectionChanged` on the original instance — a replacement collection has no subscribers. - -## No LibraryManager.SelectedItem in VM constructors - -Resolve the VM from DI, then pass the item after: `vm.Item = item` or `vm.Initialize(item)`. Shared mutable state in DI is unreliable — the item can change between registration and use. - -## No IRelayCommand on ICanBeParent - -Exposes plain methods only. Commands hold delegates bound to a specific instance and silently execute on the original after cloning. - -## No SaveServiceAggregator in dialog VMs - -Write directly to the item on Accept. Reserve the save service pattern for the settings flow where it's already established. diff --git a/specification/project_overview.md b/specification/project_overview.md deleted file mode 100644 index 0fbe2ec..0000000 --- a/specification/project_overview.md +++ /dev/null @@ -1,41 +0,0 @@ -# Project Overview - -EvenBetterFastSim is a WPF desktop app (.NET 10, C# preview) simulating SECS/GEM semiconductor equipment communication. Uses MVVM + Microsoft DI. - -Related docs: [CLAUDE.md](../CLAUDE.md), [AGENTS.md](../AGENTS.md), [README.md](../README.md), [patterns.md](patterns.md), [dialog_pattern.md](dialog_pattern.md), [secsgembase_library.md](secsgembase_library.md), [features.md](features.md), [scenario-system.md](scenario-system.md) - -## Build - -```bash -dotnet build EvenBetterFastSim.sln -dotnet run --project EvenBetterFastSim/EvenBetterFastSim.csproj -``` - -Configs: `Debug`, `DebugLocal` (uses local SecsGemBase at `%USERPROFILE%\source\repos\SecsGemBase\`), `Release`. -When modifying SecsGemBase: build it first, then rebuild EvenBetterFastSim with `DebugLocal`. - -## DI Wiring (App.xaml.cs) - -- **Scoped**: `MainViewModel`, `ViewModelLocator`, `CommunicationHandler`, message handlers -- **Transient**: Dialog ViewModels (one per dialog open) -- **Singleton**: Configuration, `ILoggerProvider` - -Transient VMs registered: `SetUpViewModel`, `SecsGemItemViewModel`, `SecsGemDataMessageViewModel`, `InspectSecsGemItemViewModel`, `SecsGemTransactionViewModel`, `AddEventReportViewModel`, `AddReportViewModel`, `AddEquipmentVariableViewModel` - -## Key Files - -- `EvenBetterFastSim/App.xaml.cs` — startup, DI setup, all service registrations -- `EvenBetterFastSim/WPF/ViewModels/MainViewModel.cs` — central orchestrator -- `EvenBetterFastSim/Services/WindowMapper.cs` — maps ViewModel type → Window type for dialogs -- `EvenBetterFastSim/Window Helpers/DialogWindow.xaml` — DataTemplates mapping ViewModel type → UserControl view -- `EvenBetterFastSim/Services/ApplicationSettings.cs` — strongly-typed settings -- `EvenBetterFastSim/Library/` — XML definitions for SECS/GEM messages - -## Two TreeViews in MainWindow.xaml - -1. **Library TreeView** — editable items; double-click opens edit dialog via `ModifySelectedItemCommand` -2. **Messages Log TreeView** (Grid.Column=2) — received messages; double-click on SecsGemItem opens inspect dialog via `InspectLoggedItemCommand` - -## Settings Change Flow - -`SetUpViewModel` holds local copies (`NetworkSettingsCopy`, `HsmsParametersCopy`). On OK: `SaveServiceAggregator.Save()` → `destination.CopyFrom(source)`. `CommunicationHandler` subscribes to `PropertyChanged` and auto-restarts connection. Settings persisted to disk only on main window close (`MainViewModel.OnClosing()` → `SaveToJsonService.Save()`). diff --git a/specification/scenario-canvas-selection-deletion.md b/specification/scenario-canvas-selection-deletion.md deleted file mode 100644 index 634d7dd..0000000 --- a/specification/scenario-canvas-selection-deletion.md +++ /dev/null @@ -1,53 +0,0 @@ -# Scenario Canvas — Connection & Node Selection / Deletion - -Related docs: [scenario-system.md](scenario-system.md), [CLAUDE.md](../CLAUDE.md) - -## Overview - -The **NodifyEditor** (`ScenarioCanvas`) supports selecting and deleting connections and nodes via left-click + Delete, following the Nodify Playground example pattern. - -## Transaction deep-copy on drop - -When a transaction is dragged onto the canvas, it is deep-cloned and serialized to JSON, stored in `ScenarioNode.TransactionJson`. During scenario execution, the clone is deserialized — so each node carries its own independent snapshot, immune to library edits. Existing nodes without `TransactionJson` fall back to the old name-based `FirstOrDefault` library lookup. - -See also: `SecsGemBaseItems/Data Containers/Serialization/SecsGemTransactionJsonConverter.cs` - -## How selection works - -### Connection selection (left-click) - -Left-clicking a connection selects it. The `BaseConnection` style in the `NodifyEditor.ConnectionTemplate` sets `IsSelectable="True"` and `IsSelected="{Binding IsSelected}"`, enabling Nodify's built-in selection mechanism via `ConnectionContainer.OnMouseDown` → `ConnectionsMultiSelector.Select()`. - -Selected connections are synced to `ScenariosViewModel.SelectedConnections` (ObservableCollection) via `NodifyEditor.SelectedConnections` binding. - -### Node selection (left-click) - -Left-clicking a node selects it. The `ItemContainer` style sets `IsSelected="{Binding IsSelected}"`, and `NodifyEditor.SelectedItems` is bound to `ScenariosViewModel.SelectedNodes` (ObservableCollection). - -### Visual feedback - -Selected connections are highlighted using a `LineConnection` style trigger: -- `Stroke` / `Fill` change to the system accent color -- A `DropShadowEffect` (ShadowDepth 0, BlurRadius 14) is applied - -### Deletion (Delete key) - -`KeyBinding Key="Delete"` on the `NodifyEditor` calls `DeleteSelectionCommand`, which iterates `SelectedConnections` and `SelectedNodes` and removes them. - -### Right-click context menu deletion - -Still available for both connectors ("Disconnect") and connections ("Delete"). - -## Key files - -| File | Role | -|---|---| -| `MainWindow.xaml:526-641` | NodifyEditor with `SelectedItems`, `SelectedConnections` bindings, `KeyBinding`, styles | -| `MainWindow.xaml.cs` | Code-behind (drag-and-drop only now; selection/deletion handled by Nodify + bindings) | -| `ScenariosViewModel.cs:68-73,78,109-114` | `SelectedConnections`, `SelectedNodes`, `DeleteSelectionCommand` | -| `ConnectionViewModel.cs:24` | `IsSelected` property (two-way bound to `BaseConnection.IsSelected`) | -| `ScenarioNodeViewModel.cs:30` | `IsSelected` property (two-way bound to `ItemContainer.IsSelected`) | - -## Architecture note - -Both `NodifyEditor.SelectedConnections` and `NodifyEditor.SelectedItems` default to `null`. Nodify's internal selection engine adds/removes items from these collections. When unbound, items are silently dropped. Binding them to VM-backed `ObservableCollection`s (like the Playground does) is required for selection to work. diff --git a/specification/scenario-system.md b/specification/scenario-system.md deleted file mode 100644 index 4524164..0000000 --- a/specification/scenario-system.md +++ /dev/null @@ -1,389 +0,0 @@ -# Scenario System — Architecture & Reference - -> Covers ~22 files / ~3600 lines across EvenBetterFastSim and SecsGemBase. - -Related docs: [scenario-canvas-selection-deletion.md](scenario-canvas-selection-deletion.md), [project_overview.md](project_overview.md), [secsgembase_library.md](secsgembase_library.md), [CLAUDE.md](../CLAUDE.md) - -## Table of Contents - -- [Overview](#overview) -- [Architecture](#architecture) -- [Node Types & Pipeline](#node-types--pipeline) -- [Canvas Selection & Deletion](#canvas-selection--deletion) -- [Transaction Deep-Copy (JSON)](#transaction-deep-copy-json) -- [Message Comparison (Receive nodes)](#message-comparison-receive-nodes) -- [Execution Engine](#execution-engine) -- [Drag & Drop](#drag--drop) -- [Persistence (scenarios.json)](#persistence-scenariosjson) -- [Complete File Index](#complete-file-index) - ---- - -## Overview - -The scenario system lets users build a visual node graph representing a SECS/GEM message exchange sequence. Nodes (Send, Receive, Wait, Condition, etc.) are connected by edges. The graph is executed sequentially, dispatching real SECS/GEM messages over HSMS. - -**Technology:** WPF + Nodify (v7.3.0) for the canvas, CommunityToolkit.MVVM for ViewModels, System.Text.Json for serialization, `SecsGemBase.MessageHandling` NuGet for HSMS communication. - ---- - -## Architecture - -``` -┌─ EvenBetterFastSim ─────────────────────────────────────┐ -│ MainWindow.xaml MainWindow.xaml.cs │ -│ ├─ NodifyEditor canvas ├─ Drag-drop from library tree │ -│ │ (nodes, connections, └─ Viewport transform handling │ -│ │ selection, keybinds) │ -│ └─ Transaction tree (drag source) │ -│ │ -│ ScenariosViewModel (central orchestrator) │ -│ ├─ Nodes / Connections / SelectedNodes / SelectedConn. │ -│ ├─ AddNodeFromDrop / AddNodeToCanvas │ -│ ├─ DeleteConnections / DeleteNodes / DeleteSelectionCmd │ -│ ├─ BuildGraphFromCanvas / LoadGraphToCanvas │ -│ ├─ SaveToJson / LoadFromJson │ -│ └─ RunScenario → ScenarioExecutionService │ -│ │ -│ Graph ViewModels │ -│ ├─ ScenarioNodeViewModel (type, connectors, toggle) │ -│ ├─ ConnectionViewModel (source, target, IsSelected) │ -│ ├─ ConnectorViewModel (anchor, IsConnected) │ -│ └─ PendingConnectionViewModel (drag-to-connect) │ -└──────────────────────────────────────────────────────────┘ - │ - ▼ -┌─ SecsGemBase ────────────────────────────────────────────┐ -│ Models │ -│ ├─ ScenarioNode (Id, Type, TransactionName/Json, X, Y) │ -│ ├─ ScenarioGraph (Name, Nodes[], Edges[]) │ -│ ├─ ScenarioEdge (SourceNodeId, TargetNodeId) │ -│ └─ NodeType enum │ -│ │ -│ ScenarioExecutionService │ -│ ├─ ExecuteAsync → linear walk → ExecuteNodeAsync │ -│ ├─ ExecuteSendAsync (sends via DataMessageHandler) │ -│ ├─ ExecuteWaitAsync (Task.Delay) │ -│ └─ ExecuteReceiveAsync (waits for matching inbound msg) │ -│ │ -│ Data Containers │ -│ ├─ SecsGemTransaction (PrimaryMessage, ReplyMessage) │ -│ ├─ SecsGemDataMessage (Stream, Function, Children) │ -│ ├─ SecsGemItem (FormatType, Values, Children) │ -│ └─ TransactionJsonConverter (JSON serialize/deserialize) │ -│ │ -│ DataMessageHandler │ -│ ├─ SendDataMessage (for Send nodes) │ -│ ├─ CanSendMessage (pre-send gate check) │ -│ └─ WaitForReceivedMessage (for Receive nodes) │ -└──────────────────────────────────────────────────────────┘ -``` - -### DI Wiring - -``` -App.xaml.cs:ConfigureServices() - services.AddScoped() - services.AddScoped() - ↓ -MainViewModel(ScenariosViewModel scenariosVm) - public ScenariosViewModel ScenariosVm { get; } - ↓ -MainWindow.DataContext = MainViewModel - XAML bindings → {Binding ScenariosVm.Nodes}, etc. -``` - ---- - -## Node Types & Pipeline - -### Enum `NodeType` (SecsGemScenarioEngine/Models/NodeType.cs) - -| Value | Behavior | Connectors | -|-------|----------|------------| -| `Start` | Entry point. Skips during execution. | Output: {Out} | -| `SendAndWait` | Sends PrimaryMessage, waits for reply. On success → next node. | Input: {In}, Output: {Reply} | -| `Send` | Same as SendAndWait (sending always waits for reply/Hsms confirm). Legacy. | Input: {In}, Output: {Done} | -| `Receive` | Waits for equipment to send a message matching the stored transaction clone. On match → next node. | Input: {In}, Output: {Out} | -| `Wait` | Pauses for N milliseconds (TransactionName stores the delay). | Input: {In}, Output: {Out} | -| `End` | Termination. Skips. | Input: {In} | -| `Condition` | Branch point. (Not yet implemented in execution engine.) | Input: {In}, Output: {YES}, {NO} | - -### Mode toggle button - -Each Send/SendAndWait/Receive node has a button (`← Receive` / `→ Send & Wait`) that cycles: -- `Send` / `SendAndWait` → `Receive` -- `Receive` → `SendAndWait` - -Implemented in `ScenarioNodeViewModel.cs:ToggleSendMode()`. Trigger updates connectors and title via `OnTypeChanged`. - -### Execution pipeline - -``` -Start → [Send/SendAndWait] → [Receive] → [Wait] → ... → End - │ │ │ - ├─ Sends message ├─ Waits for │ - │ waits for reply │ matching ├─ Delays N ms - │ on reply → next │ msg → next│ → next -``` - -Linear walk from Start node follows edges (success/failure) to build the execution order. Branches (Condition) are not yet handled. - ---- - -## Canvas Selection & Deletion - -### How selection works (Nodify pattern) - -**Connections:** -1. `BaseConnection` style in `NodifyEditor.Resources` sets `IsSelectable="True"` and `IsSelected="{Binding IsSelected}"` -2. Left-click → Nodify's `ConnectionContainer.OnMouseDown` → `ConnectionsMultiSelector.Select()` → `SelectedConnections` DP -3. `NodifyEditor.SelectedConnections` is bound to `ScenariosViewModel.SelectedConnections` (ObservableCollection) -4. Both `SelectedConnections` and `SelectedItems` DPs on `NodifyEditor` **default to null** — must be bound to a collection (matching Playground pattern) - -**Nodes:** -1. `ItemContainer` style sets `IsSelected="{Binding IsSelected}"` (two-way to `ScenarioNodeViewModel.IsSelected`) -2. `NodifyEditor.SelectedItems` bound to `ScenariosViewModel.SelectedNodes` - -### Visual feedback -- Selected connections: stroke/fill change to accent color + drop-shadow effect (via `LineConnection` style trigger) -- Selected nodes: Nodify's default `ItemContainer` selection border - -### Deletion - -| Method | Mechanism | -|--------|-----------| -| Delete key | `KeyBinding Key="Delete"` on NodifyEditor → `DeleteSelectionCommand` → `DeleteConnections(SelectedConnections)` + `DeleteNodes(SelectedNodes)` | -| Right-click connection → Delete | Context menu on `LineConnection` bound to `DeleteConnectionCommand` with `ConnectionViewModel` as parameter | -| Right-click connector → Disconnect | Context menu on `NodeInput`/`NodeOutput` bound to `DisconnectConnectorCommand` with `ConnectorViewModel` as parameter | - -### Key files -- `MainWindow.xaml:528-539` — NodifyEditor bindings (`SelectedItems`, `SelectedConnections`) -- `MainWindow.xaml:540-542` — `KeyBinding` for Delete -- `MainWindow.xaml:543-548` — `ItemContainer` style with `BasedOn` + `IsSelected` binding -- `MainWindow.xaml:596-614` — connection template: `LineConnection` style trigger (accent stroke + drop shadow) -- `ConnectionViewModel.cs:24` — `IsSelected` property -- `ScenarioNodeViewModel.cs:30` — `IsSelected` property -- `ScenariosViewModel.cs:68-73, 78, 109-114` — `SelectedConnections`, `SelectedNodes`, `DeleteSelectionCommand` - ---- - -## Transaction Deep-Copy (JSON) - -### Problem - -Multiple transactions can share the same name (e.g., two different S1F1 items). During execution, a name-based `FirstOrDefault` lookup always returned the first match. Deep-copying the transaction when dropped onto the canvas makes each node independent. - -### Implementation - -When a transaction is dropped / added to the canvas: - -```csharp -// ScenariosViewModel.cs:AddNodeFromDrop() -var node = new ScenarioNodeViewModel -{ - TransactionName = transaction.Name, - TransactionJson = SecsGemTransactionJsonConverter.Serialize(transaction.Clone()), - // ... -}; -``` - -During execution: - -```csharp -// ScenarioExecutionService.cs:FindTransaction() -if (!string.IsNullOrWhiteSpace(node.TransactionJson)) -{ - var tx = SecsGemTransactionJsonConverter.Deserialize(node.TransactionJson); - if (tx != null) return tx; // ← uses the exact clone -} -// Fallback: name-based library lookup for legacy nodes -return libraryManager.Library.FirstOrDefault(t => t.Name == node.TransactionName); -``` - -### JSON Converter - -`SecsGemBaseItems/Data Containers/Serialization/SecsGemTransactionJsonConverter.cs` - -Custom `System.Text.Json` converter that handles the full tree: -- `SecsGemTransaction` → Name, Description, PrimaryMessage, ReplyMessage -- `SecsGemDataMessage` → Name, Description, Reply, Stream, Function, IsPrimary, Children -- `SecsGemItem` → Name, Description, FormatType, Values[], Children (recursive) - -Static helpers: -```csharp -SecsGemTransactionJsonConverter.Serialize(transaction) // → string -SecsGemTransactionJsonConverter.Deserialize(json) // → SecsGemTransaction? -``` - -### Persistence - -`TransactionJson` is a `string?` on `ScenarioNode`. It serializes into `scenarios.json` alongside the node. On deserialization, `ScenarioNodeViewModel.FromModel()` restores it. Legacy nodes without `TransactionJson` gracefully fall back to name lookup. - ---- - -## Message Comparison (Receive nodes) - -Used by `ExecuteReceiveAsync` to match incoming equipment messages against the expected transaction clone. - -### API - -```csharp -// SecsGemDataMessage.cs -public static bool IsEquivalent(SecsGemDataMessage? a, SecsGemDataMessage? b) -// Compares Stream, Function, and recursively compares all children (SecsGemItem) - -// SecsGemItem.cs -public static bool IsEquivalent(SecsGemItem? a, SecsGemItem? b) -// Compares FormatType, Values[] (ordinal), and recursively compares all children -``` - -Both handle nulls via `ReferenceEquals` and null checks. Comparison is structural (not reference equality). - -### Usage in execution - -```csharp -// ScenarioExecutionService.cs:ExecuteReceiveAsync() -var received = await dataMessageHandler.WaitForReceivedMessage( - msg => SecsGemDataMessage.IsEquivalent(msg, transaction.PrimaryMessage), - TimeSpan.FromSeconds(30), - token); -``` - -`DataMessageHandler.WaitForReceivedMessage()` subscribes to `communicationHandler.OnDataMessageIn` with a `TaskCompletionSource`. When a message arrives matching the predicate, the task completes. Timeout returns null → Receive node fails. - ---- - -## Execution Engine - -### File - -`SecsGemBase/SecsGemScenarioEngine/Services/ScenarioExecutionService.cs` (244 lines) - -### Flow - -``` -RunScenario(graph) - ├─ ExecuteAsync: linear walk from Start following edges - │ └─ GetNextNodeId(graph, currentId, isSuccess) picks - │ the next node; visited set detects cycles - │ - ├─ foreach node in walk: - │ └─ ExecuteNodeAsync(node, token) - │ ├─ Start/End → skip (success) - │ ├─ Send / SendAndWait → ExecuteSendAsync - │ │ ├─ FindTransaction (JSON or name lookup) - │ │ ├─ CanSendMessage gate check - │ │ └─ dataMessageHandler.SendDataMessage(primaryMsg) - │ ├─ Receive → ExecuteReceiveAsync - │ │ ├─ FindTransaction - │ │ └─ WaitForReceivedMessage (30s timeout) - │ └─ Wait → ExecuteWaitAsync - │ └─ Task.Delay(TransactionName as int) - │ - └─ Result (Success, CompletedSteps, FailedNodeId, ErrorMessage) -``` - -### Cancellation - -`Cancel()` → `CancellationTokenSource.Cancel()` → `OperationCanceledException` caught → result with "Cancelled" error. - ---- - -## Drag & Drop - -### Source - -`TransactionTree_PreviewMouseMove` in `MainWindow.xaml.cs:70-99` -- Fires on `PreviewMouseMove` of each `TreeViewItem` in the library tree -- Finds the containing `TreeViewItem` via visual tree walk (`VisualTreeHelper.GetParent`) -- Gets `DataContext` as `SecsGemTransaction` -- Starts drag with `DragDrop.DoDragDrop(tvi, transaction, DragDropEffects.Copy)` - -### Target - -`ScenarioCanvas_PreviewDrop` in `MainWindow.xaml.cs:134-155` -- `ScenarioCanvas_PreviewDragOver` accepts the drop (checks for `SecsGemTransaction` type) -- On drop: extracts `SecsGemTransaction` from `e.Data` -- Converts drop position via `ScenarioCanvas.ViewportTransform.Inverse.Transform(position)` (canvas pan/zoom adjustment) -- Calls `ScenariosVm.AddNodeFromDrop(transaction, canvasPosition)` - -### Node creation - -`AddNodeFromDrop` determines `NodeType` from `transaction.PrimaryMessage.Reply`: -- `Reply == true` → `SendAndWait` -- `Reply == false` → `Send` - -Creates `ScenarioNodeViewModel`, serializes cloned transaction as JSON, adds to `Nodes` collection. - ---- - -## Persistence (scenarios.json) - -### Location -`%APPDATA%/EvenBetterFastSim/scenarios.json` — or `%APPDATA%/EvenBetterFastSim/profiles//scenarios.json` when launched with `--profile ` (`ScenariosViewModel.ScenariosIndexPath` derives from `InstanceContext.SettingsDirectory`). - -### Format -```json -[ - { - "Name": "Scenario 1", - "Graph": { - "Name": "Scenario 1", - "Description": "", - "Nodes": [ - { - "Id": "a1b2c3d4", - "Type": "SendAndWait", - "TransactionName": "S1F1", - "TransactionJson": "{\"Name\":\"S1F1\",...}", - "X": 200.0, - "Y": 300.0 - } - ], - "Edges": [ - { "SourceNodeId": "start01", "TargetNodeId": "a1b2c3d4" } - ] - } - } -] -``` - -### Save/Load - -- **Save**: `ScenariosViewModel.SaveToJson()` — calls `JsonSerializer.Serialize(Scenarios.ToList())`. `Scenarios` is an `ObservableCollection`. -- **Build graph**: `BuildGraphFromCanvas()` — iterates `Nodes` (ViewModel), calls `.ToModel()` to get `ScenarioNode`, maps edges via connector references. -- **Load graph**: `LoadGraphToCanvas(graph)` — calls `ScenarioNodeViewModel.FromModel()` for each node, recreates connections from edges. -- **Trigger**: `OnSelectedScenarioChanged` — automatically loads the selected scenario's graph to the canvas. -- **Edges**: `ScenarioEdge` has `SourceNodeId`/`TargetNodeId`. When loading, edges are matched to connectors by node ID → first Input/Output connector. - ---- - -## Complete File Index - -| # | File | Lines | Role | -|---|------|-------|------| -| | **EvenBetterFastSim** | | | -| 1 | `WPF/ViewModels/Graph/ScenarioNodeViewModel.cs` | 166 | Visual node VM: connectors, type toggle (Send/Receive) | -| 2 | `WPF/ViewModels/Graph/ConnectionViewModel.cs` | 36 | Canvas edge: Source/Target connectors, IsSelected | -| 3 | `WPF/ViewModels/Graph/PendingConnectionViewModel.cs` | 27 | Drag-to-connect tracking | -| 4 | `WPF/ViewModels/Graph/ConnectorViewModel.cs` | 37 | Node port: anchor point, connection state | -| 5 | `WPF/ViewModels/ScenariosViewModel.cs` | 738 | Central orchestrator: CRUD, persistence, run | -| 6 | `WPF/Windows/MainWindow.xaml` (L505–641) | ~140 | Scenarios tab XAML: canvas, styles, bindings | -| 7 | `WPF/Windows/MainWindow.xaml.cs` | 156 | Drag-drop from library tree onto canvas | -| 8 | `App.xaml.cs` | 139 | DI: `ScenariosViewModel` + `ScenarioExecutionService` | -| 9 | `WPF/ViewModels/MainViewModel.cs` | 717 | Exposes `ScenariosVm` to window DataContext | -| | **SecsGemBase** | | | -| 10 | `SecsGemScenarioEngine/Models/ScenarioNode.cs` | 13 | Serializable node model | -| 11 | `SecsGemScenarioEngine/Models/ScenarioGraph.cs` | 9 | Top-level scenario container | -| 12 | `SecsGemScenarioEngine/Models/ScenarioEdge.cs` | 8 | Directed edge between node IDs | -| 13 | `SecsGemScenarioEngine/Models/NodeType.cs` | 12 | Enum: Start, SendAndWait, Send, End, Condition, Wait, Receive | -| 14 | `SecsGemScenarioEngine/Services/ScenarioExecutionService.cs` | 244 | Runtime engine: linear walk + send/wait/receive | -| 15 | `SecsGemScenarioEngine/Services/IScenarioExecutionService.cs` | 17 | Interface + result DTO | -| 16 | `SecsGemBaseItems/Data Containers/SecsGemTransaction.cs` | 82 | Transaction with Primary/Reply messages | -| 17 | `SecsGemBaseItems/Data Containers/SecsGemDataMessage.cs` | 133 | SECS/GEM message: Stream, Function, items | -| 18 | `SecsGemBaseItems/Data Containers/SecsGemItem.cs` (+`SecsGemValueItem.cs` 205, `SecsGemListItem.cs` 51) | 193 | Abstract item base + typed value/list items | -| 19 | `SecsGemBaseItems/Data Containers/Serialization/SecsGemTransactionJsonConverter.cs` | 160 | JSON converter for transaction tree | -| 20 | `SecsGemMessageHandling/Data Handling/DataMessageHandler.cs` | 359 | HSMS dispatch: send, receive, gate check | - -**Total: ~22 files, ~3600 lines across both repositories.** diff --git a/specification/secsgembase_library.md b/specification/secsgembase_library.md deleted file mode 100644 index f1d46e4..0000000 --- a/specification/secsgembase_library.md +++ /dev/null @@ -1,160 +0,0 @@ -# SecsGemBase Library - -Location: `%USERPROFILE%\source\repos\SecsGemBase\` ([GitHub: Pre-Se/SecsGemBase](https://github.com/Pre-Se/SecsGemBase)) -NuGet packages (nuget.org, pre-release): `SecsGemBase.MessageHandling`, `SecsGemBase.ScenarioEngine` - -Related docs: [SESSION_REFACTORING_LOG.md](../SESSION_REFACTORING_LOG.md), [patterns.md](patterns.md), [CLAUDE.md](../CLAUDE.md) - -## Class Hierarchy - -``` -DataItem (ObservableObject) - ├── SecsGemItem (abstract) - │ ├── SecsGemListItem (FormatType = List) - │ └── SecsGemValueItem (all value types; Values: ObservableCollection) - └── SecsGemDataMessage -``` - -### DataItem (`SecsGemBaseItems/Data Containers/DataItem.cs`) - -- `Name`, `Description` are `[ObservableProperty]` -- `Header` is derived: `"Name - Description"` or just `"Name"` — updated by `SetHeader` subscribed to `PropertyChanged` in constructor -- `Children`: `ObservableCollection` -- `SetParent(ICanBeParent?)` — removes from old parent, adds to new parent via `TryAddChild` - -### SecsGemItem (`SecsGemBaseItems/Data Containers/SecsGemItem.cs`) — abstract - -- `FormatType`: `SecsGemItemFormatType` enum (List, ASCII, Binary, U1..U8, I1..I8, Float, Double, Boolean, JIS8, TwoByteCharacter) -- **`Values` moved to `SecsGemValueItem`** — the base exposes non-generic accessors instead: - - `Create(SecsGemItemFormatType)` static factory → `SecsGemValueItem` / `SecsGemListItem` - - `GetBoxedValues()` / `GetStringValues()` / `SetValuesFromStrings()` -- Constructor subscribes: `PropertyChanged += SetName`, `Children.CollectionChanged += SetName` -- `Name` is auto-set by `SetName()`: - - List: `"List(N)"` where N = children count - - Binary: `"Binary = 0xABCD..."` (hex, concatenated) - - Others: `"FormatType = firstValue"` - -### T → FormatType Mapping (`SecsGemValueItem`) - -| `T` | FormatTypes | -|---|---| -| `byte` | Binary, U1 | -| `sbyte` | I1 | -| `bool` | Boolean | -| `ushort` | U2 | -| `short` | I2 | -| `uint` | U4 | -| `int` | I4 | -| `ulong` | U8 | -| `long` | I8 | -| `float` | Float | -| `double` | Double | -| `string` | ASCII, JIS8, TwoByteCharacter | - -`FormatType` stays on the base to distinguish wire-level encoding (e.g., Binary vs U1 both use `T=byte`, but have different SECS II format bytes). - -### SecsGemDataMessage (`SecsGemBaseItems/Data Containers/SecsGemDataMessage.cs`) - -- `Reply`, `Stream`, `Function`, `IsPrimary` are `[ObservableProperty]` -- Constructor subscribes `PropertyChanged += SetName`; `SetName` sets `Name = "S{Stream}F{Function}"` - -## Clone Pattern - -**No MemberwiseClone.** `SecsGemItem.Clone()` is abstract; the concrete types build clones explicitly: - -```csharp -// SecsGemValueItem.Clone() -public override SecsGemItem Clone() -{ - var clone = new SecsGemValueItem - { - FormatType = FormatType, - Description = Description - }; - clone.Values.Clear(); - foreach (var v in Values) - clone.Values.Add(v); - foreach (var child in Children.OfType().Select(c => c.Clone())) - child.SetParent(clone); - return clone; -} - -// SecsGemListItem.Clone() -public override SecsGemItem Clone() -{ - var clone = new SecsGemListItem - { - Description = Description - }; - foreach (var child in Children.OfType().Select(c => c.Clone())) - child.SetParent(clone); - return clone; -} - -// SecsGemDataMessage.Clone() — explicit new + CopyFrom + recurse children -// SecsGemTransaction.Clone() — new SecsGemTransaction + cloned Primary/Reply messages -``` - -MemberwiseClone is banned: it copies the PropertyChanged invocation list, so clones fire handlers on the original instance (Name/Header never updates on the clone). See [patterns.md](patterns.md). - -## CopyFrom Rules - -`CopyFrom` must never replace `Values` or `Children` with a new collection — always mutate in-place to preserve existing `CollectionChanged` subscriptions. - -```csharp -// CORRECT -Values.Clear(); -foreach (var v in source.Values) Values.Add(v); - -// WRONG — breaks CollectionChanged subscription set up by constructor -Values = new(source.Values); -``` - -`SecsGemDataMessage.CopyFrom` copies: `Reply`, `Stream`, `Function`, `IsPrimary`, `Description`. -`SecsGemItem.CopyFrom` copies: `Description`, `FormatType`, Values (in-place, when the source is the same `T`). - -## Binary Format - -Binary values are stored as **`byte[]`** (`SecsGemValueItem`) after the generic refactor — no more hex-string round-trip. `GetStringValues()` produces **2-digit uppercase hex strings** (e.g., `"FF"`, `"0A"`) for display and wire encoding. - -| Location | Change | -|---|---| -| `ItemFactory.cs` AddBinary | `AddBinary(byte value, ...)` — stores raw byte, no hex | -| `SecsGemItem.GetStringValues()` | `byte.ToString("X2")` for Binary | -| `SecsGemItem` serialization | `Convert.ToByte(value, 16)` | -| `SecsGemItem` display | `"0x" + string.Join("", GetStringValues())` | -| `DataMessageHandler` CheckValue | `["00"]` not `["0"]` | -| `SpecialCasesHandling` parsing | `NumberStyles.HexNumber`, `boxed[0] is byte b ? b.ToString("X2")` | - -## ICanBeParent - -Exposes plain methods — NOT commands: -```csharp -bool CanAddChild(IDataItem? child); -bool TryAddChild(IDataItem child); -bool TryRemoveChild(IDataItem child); -``` -Commands hold delegates bound to a specific instance and break with cloning. - -## TCPIPClientBase (`TCPIPBaseLibrary/TCPBase/TCPIPClientBase.cs`) - -Connection loop creates a **new `TcpClient` per attempt** — `TcpClient` cannot be reconnected after use. The old singleton instance caused `SocketException(IsConnected)` on the second connect attempt after a drop. - -Key rules: -- A lost connection ends the loop (`if (wasConnected) break;`, no retry wait). `Connect()` then raises `OnDisconnected` once, and `CommunicationHandler` connects again with a new object. Only failed connect attempts are retried in the loop (since package `1.0.0-build-0029`; before, the loop raised `OnDisconnected` on a drop and connected again by itself) -- `catch (Exception e) when (e is SocketException or IOException)` — `IOException` wrapping `SocketException` must be caught alongside bare `SocketException` -- Retry delay after a failed connect attempt uses `await Task.Delay(timeout, cancellationToken)` — cancellable, not `Thread.Sleep` -- `Dispose` catches `AggregateException` from `receiveDataLoopTask.Wait()` containing expected shutdown exceptions -- `activeTcpClient` uses `Volatile.Read/Write` for cross-thread visibility (single writer: loop; reader: `SendData`) - -## SecsGemItem serialization (`ConvertBasicValuesToBytes`) - -Pre-allocates output array once — O(n). Old code called `Combine(growingArray, singleByte)` in a loop which is O(n²) and hangs for large binary payloads. - -Binary is special-cased to avoid per-element array allocations. - -## CommunicationHandler — serialization off UI thread - -`BuildMessageData` (which calls `message.ToBytes()`) is wrapped in `Task.Run` before `SendDataAsync`. Keeps UI responsive for large messages since serialization runs entirely on the thread pool before the first network write. - -Also: `SendAndLogMessage` awaits `SendDataMessage(...).ConfigureAwait(false)` so the SEND timestamp is captured immediately after the TCP send (see [CLAUDE.md](../CLAUDE.md#message-logging-system)).