From cf5a1afa511a0f727b47ba17edf0d573cb9b8a65 Mon Sep 17 00:00:00 2001 From: freezy Date: Thu, 26 Nov 2026 17:05:57 +0100 Subject: [PATCH 1/6] dof: move to upstream libdof and fix what the libdof review found libdof now builds from vpinball/libdof master (5e90261), which has the fixes that went upstream from VPE's patch: finish, conditions, schedules, alarms, Art-Net reopening, buffer sizes, the PAC boards and the RGBA layers. The patch keeps only what upstream does not have yet: the output gate, confirmed transfers, path confinement and VPE's setup policy. The review of those parts found these, now fixed: - gate: a close can no longer be overtaken by the next input, a latch stops UMX between HID reports, the earliest latch decides, counts and failed names agree, a dead unit counts as failed, and the final zeros confirm a close that was pending at Finish - Dude's Cab: a failed HID open skips the board, a reconnect keeps the requested frame, a board without serial stops instead of reconnecting forever but still gets its blackout, and one MX device that fails no longer stops the cabinet's auto-configuration - Finish counts a blackout that went out while disconnecting, and a failed all-off of Pinscape and Pinscape Pico is reported - a controller whose XML throws is freed, and schedules load last - the Ultimate I/O warns once about an unknown LED interface Table configs are no longer passed to libdof: its table XML reader loads no effect assignments, so a {TableName}.xml silenced the table's ini rows. The table config selection is removed from the plugin. The ABI goes to 4: vpe_dof_gate_state reports untouched units separately, and the release check compares vpe_dof_abi_version with the header. --- README.md | 8 +- THIRD-PARTY-NOTICES.md | 2 +- Tools~/parity/README.md | 2 +- .../DofImporterTests.cs | 15 +- .../DofInstanceTests.cs | 160 +- .../DofSessionIntegrationTests.cs | 50 +- .../DofSessionTests.cs | 10 +- VisualPinball.Engine.DOF.Test/FakeNative.cs | 5 + .../Runtime/Player/DofGameSetup.cs | 49 +- .../Runtime/Player/DofPlugin.cs | 18 +- .../Runtime/Player/DofPluginFactory.cs | 18 +- .../Tests/DofGameSetupTests.cs | 18 +- .../Configuration/DofCatalog.cs | 5 +- .../Configuration/DofGlobalConfig.cs | 10 +- .../Configuration/DofImporter.cs | 7 +- .../Configuration/DofRevision.cs | 27 +- VisualPinball.Engine.DOF/DofInstance.cs | 54 +- VisualPinball.Engine.DOF/Native/DofNative.cs | 4 +- .../Session/DofSession.cs | 9 +- .../Session/IDofNative.cs | 2 +- native/CMakeLists.txt | 36 +- native/build-linux.sh | 5 + native/build-macos.sh | 5 + native/build-windows.cmd | 6 + native/include/vpe_dof.h | 50 +- native/patches/0001-vpe-libdof.patch | 3170 +++++++++-------- native/release-check.py | 30 + native/src/vpe_dof.cpp | 16 +- native/tests/internal.cpp | 463 +++ native/tests/smoke.c | 36 +- third-party/libdof | 2 +- 31 files changed, 2573 insertions(+), 1719 deletions(-) create mode 100644 native/tests/internal.cpp diff --git a/README.md b/README.md index 14ce480..83900e8 100644 --- a/README.md +++ b/README.md @@ -67,11 +67,11 @@ Table authors add a `DofTriggerComponent` (*DOF Triggers*) to send DOF's numbere libdof is used as upstream has it, except for what `native/patches/0001-vpe-libdof.patch` changes: -- **Output gate.** A process-wide gate that turns all outputs off while the game is paused or stopping, whatever effects are running. For each change it reports which controllers have sent it, which failed, and whether a later change replaced it before every controller had it. A stop or a fault latches it closed from any thread, without allocating: every controller's updater sends the closing without DOF's main thread (an idle updater checks the gate every 50 ms, its polling interval, which bounds how long it takes to notice; a PacLed64 or PacUIO drops the rest of an opening's update), and an opening still queued for that thread, or any later one, applies as a closing. +- **Output gate.** A process-wide gate that turns all outputs off while the game is paused or stopping, whatever effects are running. For each change it reports which controllers have sent it, which failed, and whether a later change replaced it before every controller had it. A stop or a fault latches it closed from any thread, without allocating: every controller's updater sends the closing without DOF's main thread (an idle updater checks the gate every 50 ms, its polling interval, which bounds how long it takes to notice; a PacLed64 or PacUIO drops the rest of an opening's update, a UMX one the rest of the frame it is sending). An opening still queued for that thread never goes out and reports as superseded, any later change applies as a closing, and when latches race the first one to start counts. A controller whose updater ended on its own reports failed, even for a change it had sent. - **File confinement.** libdof reads only files inside the configuration folder it was given, and never writes or deletes files. Its log goes to the host instead of a file. -- **Sessions.** `Setup` fails instead of falling back to defaults when the global config cannot be loaded, and instead of auto-configuring when the configured cabinet config is missing or invalid (without a configured cabinet, auto-configuration works as before). It clears what the previous session left in libdof's singletons, and the Art-Net socket reopens for the next session. `Finish` undoes only what `Init` started, applies changes still queued, finishes every controller even when one fails, and fails when a controller could not turn its outputs off. -- **Controllers.** A controller reports a change as sent only after a complete transfer; failed transfers are reported and retried. PinOne owns its serial port inside the process instead of sharing it through a named pipe or socket. Auto-configuration never opens a serial port: the host leases only the ports the configuration names, so a serial PinOne is used where the cabinet configuration names its port, and the auto-configurator neither probes the legacy PinOne port nor scans the others (on Linux it does not even list them, since listing opens some ports). HID PinOne boards are still found. A few shutdown, locking and buffer-size bugs are fixed. -- **Parity with C# DOF.** Fixes for differences the parity harness found. They are listed in the parity [README](Tools~/parity/README.md#differences-found). +- **Sessions.** `Setup` fails instead of falling back to defaults when the global config cannot be loaded, and instead of auto-configuring when the configured cabinet config is missing or invalid (without a configured cabinet, auto-configuration works as before). Controllers that outlive a session (LedWiz, PacDrive, PacLed64, PacUIO) start the next one from all off and unused. `Finish` applies changes still queued, and fails when a controller could not turn its outputs off, neither with its final update nor with its disconnect blackout. +- **Controllers.** A controller reports a change as sent only after a complete transfer; failed transfers are reported and retried. PinOne owns its serial port inside the process instead of sharing it through a named pipe or socket. Auto-configuration never opens a serial port: the host leases only the ports the configuration names, so a serial PinOne is used where the cabinet configuration names its port, and the auto-configurator neither probes the legacy PinOne port nor scans the others (on Linux it does not even list them, since listing opens some ports). HID PinOne boards are still found. A Dude's Cab board is opened again after a failed write until that works, and one without a serial number stops instead; a UMX device whose configuration cannot be read is skipped, so the other controllers are still set up. +- **Parity with C# DOF.** The differences the parity harness found are fixed in libdof itself. They are listed in the parity [README](Tools~/parity/README.md#differences-found). ## License diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index 72f0d0e..239ee2a 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -6,7 +6,7 @@ The complete corresponding source of every release is attached to the release as | Component | Version | Licence | Licence text | | --- | --- | --- | --- | -| [libdof](https://github.com/vpinball/libdof), C++ port of the [DirectOutput Framework](https://github.com/DirectOutput/DirectOutput), with VPE's patches (`native/patches`) | 0.5.4 (d92f8fc) | GPL-3.0-or-later | `third-party/libdof/LICENSE` | +| [libdof](https://github.com/vpinball/libdof), C++ port of the [DirectOutput Framework](https://github.com/DirectOutput/DirectOutput), with VPE's patches (`native/patches`) | 0.5.4 (5e90261) | GPL-3.0-or-later | `third-party/libdof/LICENSE` | | [hidapi](https://github.com/libusb/hidapi) | 0.15.0 (d6b2a97) | BSD-3-Clause (one of its three licence options, chosen here) | `third-party/hidapi/LICENSE-bsd.txt`, below | | [libusb](https://github.com/libusb/libusb) | 1.0.29 (15a7ebb) | LGPL-2.1-or-later | `third-party/libusb/COPYING` | | [libserialport](https://github.com/sigrokproject/libserialport) | 21b3dfe | LGPL-3.0-or-later | `third-party/libserialport/COPYING` | diff --git a/Tools~/parity/README.md b/Tools~/parity/README.md index 9ac5960..023c8d4 100644 --- a/Tools~/parity/README.md +++ b/Tools~/parity/README.md @@ -65,7 +65,7 @@ The engines run in different processes with their own timers, so a sample in the ## Differences found -Against libdof d92f8fc (0.5.4). Each one was fixed in the patch unless noted. +Against libdof d92f8fc (0.5.4). Each one is fixed in libdof since 5e90261 unless noted. | Difference | Effect | Scenario | | --- | --- | --- | diff --git a/VisualPinball.Engine.DOF.Test/DofImporterTests.cs b/VisualPinball.Engine.DOF.Test/DofImporterTests.cs index ffe5d64..3e6571c 100644 --- a/VisualPinball.Engine.DOF.Test/DofImporterTests.cs +++ b/VisualPinball.Engine.DOF.Test/DofImporterTests.cs @@ -140,7 +140,7 @@ public void RelocatesAWindowsAuthoredConfiguration() var global = XDocument.Load(revision.GlobalConfigFile).Root; Assert.That(global.Element("IniFilesPath").Value, Is.EqualTo(revision.ConfigDir)); Assert.That(global.Element("CabinetConfigFilePattern").Value, Is.EqualTo(Path.Combine(revision.ConfigDir, "cabinet.xml"))); - Assert.That(global.Element("TableConfigFilePatterns").Element("FilePattern").Value, Is.EqualTo(Path.Combine(revision.TablesDir, "{TableName}.xml"))); + Assert.That(global.Element("TableConfigFilePatterns").Elements(), Is.Empty, "no table config is loaded"); Assert.That(global.Element("LogFilePattern").Value, Is.Empty); Assert.That(global.Element("ClearLogOnSessionStart").Value, Is.EqualTo("false")); Assert.That(global.Element("LedWizDefaultMinCommandIntervalMs").Value, Is.EqualTo("1"), "other settings are kept"); @@ -426,16 +426,10 @@ public void RollbackAndLeasesKeepRevisionsAlive() } [Test] - public void TableFileSelectsTheBoundTableConfig() + public void TableConfigsAreKeptAsAnInventory() { - Accepted(_importer.Import(Folder("tables", ("directoutputconfig.ini", MainIni), ("afm.xml", TableXml)))); - var revision = _store.Active; - Assert.That(revision.TableConfigs, Is.EqualTo(new[] { "afm" })); - Assert.That(Path.GetFileName(revision.TableFileFor("afm", "Attack From Mars")), Is.EqualTo("afm.vpx")); - // Unbound: no table file at all, so libdof looks up no table config, whatever the platform's name comparison. - Assert.That(revision.TableFileFor(null, "afm"), Is.Null); - Assert.That(revision.TableFileFor(null, "AFM"), Is.Null); - Assert.Throws(() => revision.TableFileFor("missing", "x")); + Accepted(_importer.Import(Folder("tables", ("directoutputconfig.ini", MainIni), ("table.xml", TableXml)))); + Assert.That(_store.Active.TableConfigs, Is.EqualTo(new[] { "table" })); } [Test] @@ -621,7 +615,6 @@ public void GlobalConfigUsesPathsLibdofCanOpen() foreach (var element in new[] { "IniFilesPath", "CabinetConfigFilePattern" }) { Assert.That(DofPaths.IsAscii(global.Element(element).Value), Is.True, global.Element(element).Value); } - Assert.That(DofPaths.IsAscii(global.Element("TableConfigFilePatterns").Element("FilePattern").Value), Is.True); } } } diff --git a/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs b/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs index 39fff84..3441a9f 100644 --- a/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs +++ b/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs @@ -98,7 +98,7 @@ private void Expect(int universe, Func match, string what, int aft [Test] public void ReportsAbiAndLibdofVersion() { - Assert.That(DofLibrary.NativeAbiVersion, Is.EqualTo(3)); + Assert.That(DofLibrary.NativeAbiVersion, Is.EqualTo(4)); Assert.That(DofLibrary.LibdofVersion, Does.Match(@"^\d+\.\d+\.\d+")); } @@ -634,6 +634,164 @@ public void NamedElementsDriveConditionsAndPorts() dof.Finish(); } + [Test] + public void ConditionNamesTheWholeElement() + { + // As in C# DOF, "S1X" is not a table element: the condition is dropped instead of following S1. + var unit = Unit("ArtNetA"); + using var config = new TestConfig().GlobalConfig().Cabinet(8, unit).Ini(1, "vpetest,(S1X=1),S1"); + using var dof = Start(config); + dof.Data('S', 1, 1); + Expect(unit.Universe, f => f[1] == 255, "S1 on"); + Thread.Sleep(200); + Assert.That(_capture.Frames(unit.Universe).All(f => f[0] == 0), Is.True, "(S1X=1) does not follow S1"); + dof.Finish(); + } + + [Test] + public void SignedDirectTriggerDrivesItsPort() + { + // The number of a direct trigger has to parse whole, and a sign is part of it, as in C# DOF. + var unit = Unit("ArtNetA"); + using var config = new TestConfig().GlobalConfig().Cabinet(8, unit).Ini(1, "vpetest,E-1,S1X,S2"); + using var dof = Start(config); + dof.Data('E', -1, 1); + Expect(unit.Universe, f => f[0] == 255, "E-1 on"); + dof.Data('S', 1, 1); + dof.Data('S', 2, 1); + Expect(unit.Universe, f => f[2] == 255, "S2 on"); + Thread.Sleep(200); + Assert.That(_capture.Frames(unit.Universe).All(f => f[1] == 0), Is.True, "S1X does not follow S1"); + dof.Finish(); + } + + [Test] + public void OffQueuedBeforeAnOpeningIsNotSentAsOn() + { + var unit = Unit("ArtNetA"); + using var config = new TestConfig().GlobalConfig().Cabinet(8, unit).Ini(1, "vpetest,S1"); + using var dof = Start(config); + // Used while open, so the opening below has to send its frame. + dof.Data('S', 1, 1); + Expect(unit.Universe, f => f[0] == 255, "S1 on"); + // Past the minimum effect duration (60 ms), which would hold S1 on for a moment after it goes off. + Thread.Sleep(100); + var start = _capture.Count(unit.Universe); + Assert.That(WaitSettled(dof, dof.SetOutputGate(false)).Settled, Is.True); + // The closing's frame was sent; frames sent before it may still be on their way. + Expect(unit.Universe, f => f[0] == 0, "closed", start); + var mark = _capture.Count(unit.Universe); + + // The opening comes behind a backlog of input that ends with S1 going off: it applies after that input. + Backlog(dof); + dof.Data('S', 1, 0); + var open = dof.SetOutputGate(true); + Assert.That(WaitSettled(dof, open).Settled, Is.True); + Thread.Sleep(200); + var after = _capture.Frames(unit.Universe).Skip(mark).ToList(); + Assert.That(after, Is.Not.Empty); + Assert.That(after.All(f => f[0] == 0), Is.True, "S1 was off before the gate opened: " + string.Join(",", after.Select(f => f[0]))); + dof.Finish(); + } + + [Test] + public void FinishDoesNotSendAnOffQueuedBeforeAnOpeningAsOn() + { + var unit = Unit("ArtNetA"); + using var config = new TestConfig().GlobalConfig().Cabinet(8, unit).Ini(1, "vpetest,S1"); + using var dof = Start(config); + // Used while open, so finish has to send its final frame. + dof.Data('S', 1, 1); + Expect(unit.Universe, f => f[0] == 255, "S1 on"); + // Past the minimum effect duration (60 ms), which would hold S1 on for a moment after it goes off. + Thread.Sleep(100); + var start = _capture.Count(unit.Universe); + Assert.That(WaitSettled(dof, dof.SetOutputGate(false)).Settled, Is.True); + // The closing's frame was sent; frames sent before it may still be on their way. + Expect(unit.Universe, f => f[0] == 0, "closed", start); + var mark = _capture.Count(unit.Universe); + + // Finish right after the opening: the input queued before it still goes first. + Backlog(dof); + dof.Data('S', 1, 0); + dof.SetOutputGate(true); + dof.Finish(); + Thread.Sleep(100); + var after = _capture.Frames(unit.Universe).Skip(mark).ToList(); + Assert.That(after, Is.Not.Empty, "finish sends a final frame"); + Assert.That(after.All(f => f[0] == 0), Is.True, "S1 was off before the gate opened: " + string.Join(",", after.Select(f => f[0]))); + } + + [Test] + public void OnQueuedAfterAClosingIsNotSent() + { + var unit = Unit("ArtNetA"); + using var config = new TestConfig().GlobalConfig().Cabinet(8, unit).Ini(1, "vpetest,S1"); + using var dof = Start(config); + dof.Data('S', 1, 1); + Expect(unit.Universe, f => f[0] == 255, "S1 on"); + // Rounds with and without input still queued when the closing comes, so the main thread is busy or idle. + for (var round = 0; round < 6; round++) { + var start = _capture.Count(unit.Universe); + dof.Data('S', 1, 0); + Expect(unit.Universe, f => f[0] == 0, "S1 off", start); + var mark = _capture.Count(unit.Universe); + if (round % 2 == 1) { + Backlog(dof); + } + var closed = dof.SetOutputGate(false); + dof.Data('S', 1, 1); + Assert.That(WaitSettled(dof, closed).Settled, Is.True, "round " + round); + WaitForInput(dof); + var after = _capture.Frames(unit.Universe).Skip(mark).ToList(); + Assert.That(after, Is.Not.Empty, "round " + round); + Assert.That(after.All(f => f[0] == 0), Is.True, $"round {round}: S1 came on after the closing"); + + var open = dof.SetOutputGate(true); + Assert.That(WaitSettled(dof, open).Settled, Is.True, "round " + round); + Expect(unit.Universe, f => f[0] == 255, "S1 shows once the gate opens", mark); + } + dof.Finish(); + } + + [Test] + public void UnusedUnitIsUntouchedWhileOpen() + { + // Unit B has no port the ini row uses, so DOF leaves it alone while the gate is open. A closing still goes to it. + var a = Unit("ArtNetA"); + var b = Unit("ArtNetB"); + using var config = new TestConfig().GlobalConfig().Cabinet(4, a, b).Ini(1, "vpetest,S1"); + using var dof = Start(config); + dof.Data('S', 1, 1); + Expect(a.Universe, f => f[0] == 255, "frame"); + + var closed = dof.SetOutputGate(false); + var closing = WaitSettled(dof, closed); + Assert.That((closing.Written, closing.Pending, closing.Failed, closing.Untouched), Is.EqualTo((2, 0, 0, 0)), closing.ToString()); + + var open = dof.SetOutputGate(true); + var opening = WaitSettled(dof, open); + Assert.That((opening.Settled, opening.Written, opening.Pending, opening.Failed, opening.Untouched), Is.EqualTo((true, 1, 0, 0, 1)), opening.ToString()); + Assert.That(dof.GetGatePending(open), Is.Empty); + dof.Finish(); + } + + private static void Backlog(DofInstance dof) + { + for (var i = 0; i < 3000; i++) { + dof.Data('L', 1 + i % 64, i & 1); + } + } + + private static void WaitForInput(DofInstance dof) + { + var watch = Stopwatch.StartNew(); + while (dof.PendingInput > 0 && watch.ElapsedMilliseconds < 2000) { + Thread.Sleep(5); + } + Thread.Sleep(100); + } + [Test] public void EnumeratesDevicesWithoutAnInstance() { diff --git a/VisualPinball.Engine.DOF.Test/DofSessionIntegrationTests.cs b/VisualPinball.Engine.DOF.Test/DofSessionIntegrationTests.cs index f6e1fd1..4ba5005 100644 --- a/VisualPinball.Engine.DOF.Test/DofSessionIntegrationTests.cs +++ b/VisualPinball.Engine.DOF.Test/DofSessionIntegrationTests.cs @@ -88,7 +88,6 @@ private static DofRevisionLease Import(string dir, int universe, string row) private static DofSession Session(DofRevision revision, bool waitForSnapshot = true) => new DofSession(new DofSessionOptions { BasePath = revision.BasePath, - TableFile = revision.TableFileFor(null, "Test Table"), RomName = "vpetest_l1", GameSession = Game, WaitForSnapshot = waitForSnapshot, @@ -116,6 +115,55 @@ public void NamedEventsDriveNamedElementsOnly() Wait(session.StopAsync()); } + [Test] + public void TableConfigsDoNotSilenceTheIniRows() + { + // libdof reads no effect assignments from a table config: loaded, one without AddLedControlConfig would leave + // the game without effects. A session passes no table file, so none is looked up, also in a revision whose + // global config still names a table config pattern, as earlier imports wrote it, and after a rollback to one. + const int universe = 304; + var source = Path.Combine(_dir, "source"); + Directory.CreateDirectory(source); + foreach (var name in new[] { "bound", "vpetest_l1" }) { + File.WriteAllText(Path.Combine(source, name + ".xml"), + $"\r\n{name}false
\r\n"); + } + string earlier; + using (var lease = Import(universe, "vpetest,S1")) { + var revision = lease.Revision; + earlier = revision.Id; + Assert.That(revision.TableConfigs, Is.EqualTo(new[] { "bound", "vpetest_l1" })); + var global = System.Xml.Linq.XDocument.Load(revision.GlobalConfigFile); + var patterns = global.Root.Element("TableConfigFilePatterns"); + Assert.That(patterns.Elements(), Is.Empty, "a new import names no pattern"); + DrivesTheIniRow(revision, universe, "a new import"); + + patterns.Add(new System.Xml.Linq.XElement("FilePattern", Path.Combine(revision.TablesDir, "{TableName}.xml"))); + global.Save(revision.GlobalConfigFile); + DrivesTheIniRow(revision, universe, "a revision with a pattern"); + } + + using (Import(universe, "vpetest,S2")) { + } + var store = new DofConfigStore(Path.Combine(_dir, "store")); + Assert.That(store.Rollback(), Is.True); + using (var lease = store.Acquire()) { + Assert.That(lease.Revision.Id, Is.EqualTo(earlier)); + DrivesTheIniRow(lease.Revision, universe, "the revision a rollback restored"); + } + } + + private void DrivesTheIniRow(DofRevision revision, int universe, string what) + { + var session = Session(revision, false); + var started = Wait(session.StartAsync()); + Assert.That(started.Started, Is.True, started.Error); + var mark = _capture.Count(universe); + session.Publish(Game, DofElementKind.Solenoid, 1, 255); + Expect(universe, f => f[0] == 255, $"the ini row drives the port ({what})", mark); + Wait(session.StopAsync()); + } + [Test] public void RunsFromAFolderWithANonAsciiName() { diff --git a/VisualPinball.Engine.DOF.Test/DofSessionTests.cs b/VisualPinball.Engine.DOF.Test/DofSessionTests.cs index 51bbbbc..6407818 100644 --- a/VisualPinball.Engine.DOF.Test/DofSessionTests.cs +++ b/VisualPinball.Engine.DOF.Test/DofSessionTests.cs @@ -26,7 +26,6 @@ private static (DofSession session, FakeNative native) Create(ActionThrown by when set. public string InitError; + /// The table file of each . + public readonly List InitTableFiles = new List(); /// How long takes. public TimeSpan FinishDelay = TimeSpan.Zero; /// Reported as . @@ -74,6 +76,9 @@ private void Record(string call) public void Init(string tableFile, string romName) { + lock (_lock) { + InitTableFiles.Add(tableFile); + } Record("init"); if (InitError != null) { throw new DofException(DofStatus.Error, InitError); diff --git a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofGameSetup.cs b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofGameSetup.cs index 2af2856..73c5316 100644 --- a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofGameSetup.cs +++ b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofGameSetup.cs @@ -15,11 +15,10 @@ namespace VisualPinball.Engine.DOF.Player { - /// What a game runs DOF with: the ROM name, the table XML config and the devices to reserve. + /// What a game runs DOF with: the ROM name and the devices to reserve. internal static class DofGameSetup { internal const string Auto = "auto"; - internal const string None = "none"; /// The lease key of the FTDI chip family, which DOF's FT245R boards share with PinDMD 1 (the DMD plugin's key). internal const string FtdiFamily = "usb:pindmd1:auto"; @@ -40,16 +39,11 @@ internal static class DofGameSetup /// The ROM the gamelogic engine plays (PinMAME can play a compatible one), or null. /// The DOF game name the table sets on its DofTriggerComponent, or null. /// The configuration, or null. - /// - /// The table config the game runs with (), or null. Its effects go by the table's - /// elements, not by rows, so without rows the game is not left without effects. - /// - internal static (string Rom, string Problem) ResolveRom(string setting, GameIdentity identity, string runningRom, string gameName, DofCatalog catalog, - string tableConfig = null) + internal static (string Rom, string Problem) ResolveRom(string setting, GameIdentity identity, string runningRom, string gameName, DofCatalog catalog) { if (!string.IsNullOrWhiteSpace(setting) && !string.Equals(setting, Auto, StringComparison.Ordinal)) { var chosen = setting.Trim(); - return (chosen, catalog != null && catalog.Match(chosen).Count == 0 ? NoRows(chosen, tableConfig) : null); + return (chosen, catalog != null && catalog.Match(chosen).Count == 0 ? NoRows(chosen) : null); } var rom = !string.IsNullOrWhiteSpace(runningRom) ? runningRom.Trim() : string.IsNullOrWhiteSpace(identity.Key) ? null : identity.Key.Trim(); var declared = string.IsNullOrWhiteSpace(gameName) ? null : gameName.Trim(); @@ -69,17 +63,12 @@ internal static (string Rom, string Problem) ResolveRom(string setting, GameIden } var fallback = rom ?? declared; if (fallback == null) { - return (null, tableConfig == null - ? "The game has no ROM and the table declares no DOF game name; choose one in the game's DOF settings." - : $"The game has no ROM and the table declares no DOF game name, so only what the table config {tableConfig} defines responds; " - + "choose a game name in the game's DOF settings for the configuration's rows."); + return (null, "The game has no ROM and the table declares no DOF game name; choose one in the game's DOF settings."); } - return (fallback, catalog != null ? NoRows(fallback, tableConfig) : null); + return (fallback, catalog != null ? NoRows(fallback) : null); } - private static string NoRows(string rom, string tableConfig) => tableConfig == null - ? $"The configuration has no rows for {rom}, so nothing in the cabinet responds to this game." - : $"The configuration has no rows for {rom}, so only what the table config {tableConfig} defines responds to this game."; + private static string NoRows(string rom) => $"The configuration has no rows for {rom}, so nothing in the cabinet responds to this game."; /// The table mapping for one of the table's names: the mapped name and the ROM, or null. internal static KeyValuePair? TableMapping(DofCatalog catalog, IEnumerable tableNames) @@ -100,31 +89,7 @@ private static string NoRows(string rom, string tableConfig) => tableConfig == n return null; } - /// The table XML config to bind (a name from ), or null for none. - /// , or a config name. - /// The configs of the revision. - /// Names of the table automatic binding looks for, in order. - internal static string ResolveTableConfig(string setting, IReadOnlyList tableConfigs, IEnumerable tableNames) - { - if (string.Equals(setting, None, StringComparison.Ordinal) || tableConfigs == null || tableConfigs.Count == 0) { - return null; - } - if (!string.IsNullOrWhiteSpace(setting) && !string.Equals(setting, Auto, StringComparison.Ordinal)) { - return tableConfigs.FirstOrDefault(c => string.Equals(c, setting, StringComparison.OrdinalIgnoreCase)); - } - foreach (var name in tableNames ?? Enumerable.Empty()) { - if (string.IsNullOrWhiteSpace(name)) { - continue; - } - var match = tableConfigs.FirstOrDefault(c => string.Equals(c, name.Trim(), StringComparison.OrdinalIgnoreCase)); - if (match != null) { - return match; - } - } - return null; - } - - /// The names a table goes by for table mappings and table configs: its package file name, then its title. + /// The names a table goes by for table mappings: its package file name, then its title. internal static IEnumerable TableNames(string packagePath, string title) { if (!string.IsNullOrEmpty(packagePath)) { diff --git a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPlugin.cs b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPlugin.cs index 2389261..28edb59 100644 --- a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPlugin.cs +++ b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPlugin.cs @@ -61,7 +61,6 @@ internal sealed class DofPlugin : PlayerPlugin, IPluginEmergencyStop, IPluginDef private string _revision; private string _rom; private string _romProblem; - private string _tableConfig; private string _feed = "none"; private int _boundTriggers; @@ -99,7 +98,7 @@ public override async Task PrepareGameAsync(PluginGameContext game, Cancellation _triggers = null; _cabinet = null; _ending = false; - _revision = _rom = _romProblem = _tableConfig = null; + _revision = _rom = _romProblem = null; _leaseKeys.Clear(); _feed = "none"; _boundTriggers = 0; @@ -125,12 +124,8 @@ public override async Task PrepareGameAsync(PluginGameContext game, Cancellation var components = scene?.Table != null ? scene.Table.GetComponentsInChildren(true) : Array.Empty(); var lamps = LampsOf(scene); var gameName = components.Select(c => c.GameName).FirstOrDefault(n => !string.IsNullOrWhiteSpace(n)); - var names = DofGameSetup.TableNames(game.PackagePath, game.Title).ToArray(); - _tableConfig = DofGameSetup.ResolveTableConfig(game.Settings.String("TableConfig", DofGameSetup.Auto), catalog.TableConfigs, names); - var tableFile = revision.TableFileFor(_tableConfig, game.Title); - // After the table config, whose effects respond without rows. - (_rom, _romProblem) = DofGameSetup.ResolveRom(game.Settings.String("Rom", DofGameSetup.Auto), game.Identity, RunningRom(scene, game.Identity), gameName, catalog, - _tableConfig); + // The ini rows drive the outputs: the session loads no table XML config (DofSession). + (_rom, _romProblem) = DofGameSetup.ResolveRom(game.Settings.String("Rom", DofGameSetup.Auto), game.Identity, RunningRom(scene, game.Identity), gameName, catalog); // One DOF instance per process: a previous game's may still be finishing. var ownership = DofOwnership.TryAcquire(); @@ -158,7 +153,6 @@ public override async Task PrepareGameAsync(PluginGameContext game, Cancellation var feed = FeedOf(outputs); session = new DofGameSession(new DofSessionOptions { BasePath = revision.BasePath, - TableFile = tableFile, RomName = _rom, GameSession = unchecked((int)game.Session), // Without a feed only the triggers drive DOF; there is no initial state to wait for. @@ -203,7 +197,7 @@ public override async Task PrepareGameAsync(PluginGameContext game, Cancellation Quiescence = ReleaseWhenFinished(session, hold); game.Lifetime.Own(new Subscription(EmergencyStop)); _status = "Ready"; - _application.Logger.Info($"DOF for {_rom ?? "no ROM"}{(_tableConfig != null ? ", table config " + _tableConfig : "")}, revision {_revision}" + _application.Logger.Info($"DOF for {_rom ?? "no ROM"}, revision {_revision}" + (_leaseKeys.Count > 0 ? ", reserved " + string.Join(", ", _leaseKeys) : "") + "."); if (_romProblem != null) { _application.Logger.Warn(_romProblem); @@ -457,9 +451,6 @@ public void DescribeStatus(PluginStatusWriter writer) if (_romProblem != null) { writer.Add("Rows", _romProblem); } - if (_tableConfig != null) { - writer.Add("Table config", _tableConfig); - } var cabinet = _cabinet; if (cabinet != null) { writer.Add("Cabinet", cabinet); @@ -510,7 +501,6 @@ public void Describe(DiagnosticsWriter writer) if (_romProblem != null) { writer.Add("rom.problem", _romProblem); } - writer.Add("table config", _tableConfig ?? "none"); writer.Add("feed", _feed); writer.Add("triggers", _boundTriggers.ToString()); writer.Add("leases", _leaseKeys.Count > 0 ? string.Join(", ", _leaseKeys) : "none"); diff --git a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPluginFactory.cs b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPluginFactory.cs index 3e6649f..5499ef6 100644 --- a/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPluginFactory.cs +++ b/VisualPinball.Engine.DOF.Unity/Runtime/Player/DofPluginFactory.cs @@ -204,11 +204,9 @@ internal static NLog.LogLevel LogLevelOf(DofLogLevel level) new PluginField("PulsePort", "Test output", SettingKind.Action) { Provider = "pulse-port" }, new PluginField("AllOff", "All off", SettingKind.Action) { Provider = "all-off", Description = "Turns every output of the cabinet off, such as one a game that crashed left on." }), - new PluginSettingsGroup("This game", "Which configuration rows and table config the game uses.", + new PluginSettingsGroup("This game", "Which configuration rows the game uses.", new PluginField("Rom", "Game name", SettingKind.Choice) { Default = DofGameSetup.Auto, Scope = ConfigurationScope.GameOnly, Provider = "roms", FullWidth = true, - Description = "Automatic uses the ROM the game plays, or the name the table sets for DOF. A table mapping for the table's name is offered here." }, - new PluginField("TableConfig", "Table config", SettingKind.Choice) { Default = DofGameSetup.Auto, Scope = ConfigurationScope.GameOnly, Provider = "table-configs", - Description = "A table XML config of the configuration, for tables that bring their own toys. Automatic uses the one named after the table file." })); + Description = "Automatic uses the ROM the game plays, or the name the table sets for DOF. A table mapping for the table's name is offered here." })); #endregion @@ -265,16 +263,6 @@ private PluginChoiceCatalog Discover(string provider, PluginChoiceRequest reques MissingSelectionMessage = "The configuration has no rows for this name any more.", }; } - case "table-configs": { - choices.Add(new PluginChoice(DofGameSetup.Auto, "Automatic", "The table config named after the table file, if there is one.")); - choices.Add(new PluginChoice(DofGameSetup.None, "None")); - if (catalog != null) { - foreach (var config in catalog.TableConfigs) { - choices.Add(new PluginChoice(config, config)); - } - } - return new PluginChoiceCatalog(id, choices) { MissingSelectionMessage = "The configuration has no table config of this name any more." }; - } case "test-ports": { if (catalog != null) { foreach (var device in catalog.Devices) { @@ -387,7 +375,7 @@ private PluginActionResult ShowImport() text.Append(catalog.Devices.Count == 1 ? "1 ini device" : $"{catalog.Devices.Count} ini devices"); text.Append($", {catalog.Rows.Select(r => r.Rom).Distinct(StringComparer.OrdinalIgnoreCase).Count()} games"); text.Append(catalog.Controllers.Count == 0 ? ", no cabinet file (DOF configures connected boards itself)" : ", controllers " + string.Join(", ", catalog.Controllers.Select(c => c.SerialPort != null ? $"{c.Name} ({c.Type}, {c.SerialPort})" : $"{c.Name} ({c.Type})"))); - text.Append(catalog.TableConfigs.Count == 0 ? "." : $", {catalog.TableConfigs.Count} table configs."); + text.Append(catalog.TableConfigs.Count == 0 ? "." : $", {catalog.TableConfigs.Count} table configs (stored only, not loaded)."); var report = revision.ReadReport(); if (!string.IsNullOrWhiteSpace(report)) { text.Append("\n").Append(report.Trim()); diff --git a/VisualPinball.Engine.DOF.Unity/Tests/DofGameSetupTests.cs b/VisualPinball.Engine.DOF.Unity/Tests/DofGameSetupTests.cs index 77771d6..d2b82b3 100644 --- a/VisualPinball.Engine.DOF.Unity/Tests/DofGameSetupTests.cs +++ b/VisualPinball.Engine.DOF.Unity/Tests/DofGameSetupTests.cs @@ -54,11 +54,8 @@ public void TakesTheQualifiedRomThenTheRomThenTheDeclaredName() Assert.That(DofGameSetup.ResolveRom("missing", Rom, null, null, catalog).Problem, Does.Contain("no rows for missing"), "a chosen name without rows is reported too"); Assert.That(problem, Is.EqualTo("The configuration has no rows for other, so nothing in the cabinet responds to this game.")); - Assert.That(DofGameSetup.ResolveRom("auto", new GameIdentity("vpe", "other"), null, "nothing", catalog, "mytable").Problem, - Is.EqualTo("The configuration has no rows for other, so only what the table config mytable defines responds to this game."), - "a table config's effects respond without rows"); - Assert.That(DofGameSetup.ResolveRom("auto", default(GameIdentity), null, null, catalog, "mytable").Problem, - Does.Contain("only what the table config mytable defines responds").And.Not.Contain("nothing")); + Assert.That(DofGameSetup.ResolveRom("auto", default(GameIdentity), null, null, catalog), + Is.EqualTo(((string)null, "The game has no ROM and the table declares no DOF game name; choose one in the game's DOF settings."))); // A table mapping goes by the title, which another table can share: it is only offered. Assert.That(DofGameSetup.ResolveRom("auto", new GameIdentity("vpe", "other"), null, null, catalog).Rom, Is.EqualTo("other")); @@ -84,16 +81,9 @@ public void OffersTheTableMappingAsAChoice() } [Test] - public void BindsTableConfigsByNameOrSetting() + public void NamesTheTableByItsFileThenItsTitle() { - var configs = new[] { "Castle Siege", "Robot Wars" }; - var names = DofGameSetup.TableNames(@"C:\Tables\robot wars.vpe", "RW").ToArray(); - Assert.That(names, Is.EqualTo(new[] { "robot wars", "RW" })); - Assert.That(DofGameSetup.ResolveTableConfig("auto", configs, names), Is.EqualTo("Robot Wars")); - Assert.That(DofGameSetup.ResolveTableConfig("none", configs, names), Is.Null); - Assert.That(DofGameSetup.ResolveTableConfig("castle siege", configs, names), Is.EqualTo("Castle Siege")); - Assert.That(DofGameSetup.ResolveTableConfig("gone", configs, names), Is.Null); - Assert.That(DofGameSetup.ResolveTableConfig("auto", configs, new[] { "other" }), Is.Null); + Assert.That(DofGameSetup.TableNames(@"C:\Tables\my table.vpe", "MT").ToArray(), Is.EqualTo(new[] { "my table", "MT" })); } [Test] diff --git a/VisualPinball.Engine.DOF/Configuration/DofCatalog.cs b/VisualPinball.Engine.DOF/Configuration/DofCatalog.cs index 52b0234..f7f0124 100644 --- a/VisualPinball.Engine.DOF/Configuration/DofCatalog.cs +++ b/VisualPinball.Engine.DOF/Configuration/DofCatalog.cs @@ -69,7 +69,10 @@ public sealed class DofCatalog public bool RowsFromLibdof { get; } /// tablemappings.xml: table name to ROM name. public IReadOnlyList> TableMappings { get; } - /// Table XML configs that a game can bind (see ). + /// + /// The table XML configs the configuration contains, by name. An inventory only: the player loads none of them + /// (see ). + /// public IReadOnlyList TableConfigs { get; } public IReadOnlyList Controllers { get; } diff --git a/VisualPinball.Engine.DOF/Configuration/DofGlobalConfig.cs b/VisualPinball.Engine.DOF/Configuration/DofGlobalConfig.cs index 63cb44c..3d78266 100644 --- a/VisualPinball.Engine.DOF/Configuration/DofGlobalConfig.cs +++ b/VisualPinball.Engine.DOF/Configuration/DofGlobalConfig.cs @@ -19,9 +19,11 @@ namespace VisualPinball.Engine.DOF.Configuration /// /// /// Settings of an imported global config that are not file patterns are kept. The cabinet file and the shapes file - /// are the imported ones the original patterns name; table XML configs are looked up only in the revision's - /// tables folder as {TableName}.xml, which is how the session binds one (see - /// ). Logging goes to the host: no log file is configured. + /// are the imported ones the original patterns name. No table XML config is loaded: the list of table config + /// patterns is empty, and a game session passes libdof no table file, which also covers revisions imported with a + /// pattern. libdof reads a table config's effects but not the effects it assigns to the table elements, + /// so loading one would leave the table's effects without a trigger and, without AddLedControlConfig, drop + /// the ini rows as well. Logging goes to the host: no log file is configured. /// public static class DofGlobalConfig { @@ -87,7 +89,7 @@ public static XDocument Build(XDocument imported, string configDir, string table root.AddFirst( new XElement("IniFilesPath", configDir), new XElement("CabinetConfigFilePattern", cabinetFile == null ? string.Empty : Path.Combine(configDir, cabinetFile)), - new XElement("TableConfigFilePatterns", new XElement("FilePattern", Path.Combine(tablesDir, "{TableName}.xml"))), + new XElement("TableConfigFilePatterns"), new XElement("ShapeDefinitionFilePattern", shapesFile == null ? string.Empty : Path.Combine(configDir, shapesFile)), new XElement("LogFilePattern", string.Empty), new XElement("ClearLogOnSessionStart", "false")); diff --git a/VisualPinball.Engine.DOF/Configuration/DofImporter.cs b/VisualPinball.Engine.DOF/Configuration/DofImporter.cs index 008d908..6ae641f 100644 --- a/VisualPinball.Engine.DOF/Configuration/DofImporter.cs +++ b/VisualPinball.Engine.DOF/Configuration/DofImporter.cs @@ -818,7 +818,7 @@ private static void Analyse(ConfigSet config, bool windowsPorts, DofImportReport break; } case "TableConfigFilePatterns": - report.Info(DofReportTopic.Relocation, $"Table config pattern \"{pattern}\": table configs are the imported table XML files, chosen per game."); + report.Info(DofReportTopic.Relocation, $"Table config pattern \"{pattern}\": the player loads no table configs; the ini rows drive the outputs."); break; case "LogFilePattern": report.Info(DofReportTopic.Relocation, "The log goes to the player's log instead of a file."); @@ -849,10 +849,7 @@ private static void Analyse(ConfigSet config, bool windowsPorts, DofImportReport AnalyseCabinet(config.Cabinet, windowsPorts, report); } foreach (var table in config.TableConfigs.Values) { - var xml = table.Xml ?? DofXml.Load(table.Path); - if (xml.Descendants("AssignedEffects").Any(e => e.HasElements)) { - report.Warning(DofReportTopic.Unsupported, $"Table config {table.Name} assigns effects to table elements; libdof uses only its effects and LedControl settings, not the assignments."); - } + report.Warning(DofReportTopic.Unsupported, $"Table config {table.Name} is kept but not loaded: libdof does not read the effects it assigns to table elements, so the ini rows drive the outputs instead."); } } diff --git a/VisualPinball.Engine.DOF/Configuration/DofRevision.cs b/VisualPinball.Engine.DOF/Configuration/DofRevision.cs index b7e4e39..7ca91e7 100644 --- a/VisualPinball.Engine.DOF/Configuration/DofRevision.cs +++ b/VisualPinball.Engine.DOF/Configuration/DofRevision.cs @@ -43,7 +43,10 @@ internal DofRevision(string id, string basePath) BasePath = basePath; } - /// The table XML configs of the revision, by name (without extension). + /// + /// The table XML configs the import kept, by name (without extension). An inventory only: a game session loads + /// none of them (see ). + /// public string[] TableConfigs { get { @@ -60,28 +63,6 @@ public string[] TableConfigs } } - /// - /// The table file name to pass to . The file does not exist; its base name is what - /// libdof substitutes for {TableName}, so it selects the table XML config. - /// - /// The bound table XML config (a name from ), or null for none. - /// The table's name. Not used for the lookup: an unbound game loads no table XML config. - /// - /// The table file, or null without a binding: libdof then looks up no table XML config at all, whatever the - /// table is called and however the platform compares file names. - /// - /// The bound table XML config is not part of the revision. - public string TableFileFor(string tableConfig, string tableName) - { - if (tableConfig == null) { - return null; - } - if (!File.Exists(Path.Combine(TablesDir, tableConfig + ".xml"))) { - throw new ArgumentException($"The DOF configuration has no table config named \"{tableConfig}\".", nameof(tableConfig)); - } - return Path.Combine(TablesDir, tableConfig + ".vpx"); - } - /// /// The serial ports the cabinet file names (see ), for the device leases a /// game takes before DOF opens them. diff --git a/VisualPinball.Engine.DOF/DofInstance.cs b/VisualPinball.Engine.DOF/DofInstance.cs index d5a9d93..0700b3d 100644 --- a/VisualPinball.Engine.DOF/DofInstance.cs +++ b/VisualPinball.Engine.DOF/DofInstance.cs @@ -15,38 +15,56 @@ public readonly struct DofGateState /// DOF's main thread has applied the change. public bool Applied { get; } /// - /// A later change set the other state while some unit had not confirmed this one. The later change is the one to - /// wait for. + /// A later change that reached the controllers set the other state, or this is an opening that a latch overtook + /// (requested before the latch, applied after it), which never reaches them as an opening. The latest change is + /// the one to wait for. A superseded change stays superseded. /// /// /// Only the latest change's counts tell what the outputs show. For an older change they are what each unit wrote - /// last in that state, at different times, and a superseded change can later count as written by every unit. + /// last in that state, at different times. A change old enough to be forgotten reports superseded. /// public bool Superseded { get; } /// - /// Controller units that confirmed the state: a transfer to their device carried it, or, for a unit DOF never - /// used, the gate is open and DOF leaves its device alone. + /// Controller units that confirmed the state: a transfer to their device carried it, or a later change to the same + /// state did. /// - /// Written is not a physical acknowledgement: an Art-Net unit, for one, has only sent a packet. + /// + /// Written is not a physical acknowledgement: it means the transport took the data (an Art-Net unit, for one, has + /// only sent a packet). + /// public int Written { get; } /// Units that have not written it yet. public int Pending { get; } - /// Units whose write failed, whose device is missing, or whose updater stopped or finished. + /// + /// Units whose write failed, whose device is missing, or whose updater ended on its own, even after it wrote the + /// state. A unit that finished cleanly keeps what it wrote or left alone, and fails later changes. + /// public int Failed { get; } + /// + /// Units DOF never used, which it leaves alone while the gate is open: nothing was written to them. A closing has + /// none, since it is written to every unit. + /// + public int Untouched { get; } - /// Applied, and every unit has either written it or failed. + /// Applied, and every unit has written it, failed, or is left alone. public bool Settled => Applied && Pending == 0; public DofGateState(bool applied, int written, int pending, int failed, bool superseded = false) + : this(applied, written, pending, failed, superseded, 0) + { + } + + public DofGateState(bool applied, int written, int pending, int failed, bool superseded, int untouched) { Applied = applied || superseded; Superseded = superseded; Written = written; Pending = pending; Failed = failed; + Untouched = untouched; } - public override string ToString() => $"applied={Applied} superseded={Superseded} written={Written} pending={Pending} failed={Failed}"; + public override string ToString() => $"applied={Applied} superseded={Superseded} written={Written} pending={Pending} failed={Failed} untouched={Untouched}"; } public readonly struct DofController @@ -218,12 +236,14 @@ public long SetOutputGate(bool open) /// /// Any thread, in any state until disposed: closes the output gate at once and latches it closed for the rest of - /// the instance. Openings that DOF's main thread has not applied yet, and every later one, apply as closings, - /// and their generations report the closed state. The closing reaches the controllers without waiting for DOF's - /// main thread: an idle updater checks the gate every 50 ms, its polling interval, which bounds how long it takes - /// to notice; a busy one sends it after the write in progress (a PacLed64 or PacUIO drops the rest of an - /// opening's update). Never blocks beyond a short internal lock and never allocates, so the simulation thread may - /// call it. + /// the instance. An opening requested before the latch that DOF's main thread has not applied yet never reaches + /// the controllers as an opening and reports ; every change requested after + /// it applies as a closing and reports the closed state. When latches race, the first to start decides, and a + /// state once reported does not change when a later latch returns. The closing reaches the controllers without + /// waiting for DOF's main thread: an idle updater checks the gate every 50 ms, its polling interval, which bounds + /// how long it takes to notice; a busy one sends it after the write in progress (a PacLed64 or PacUIO drops the + /// rest of an opening's update, a UMX one the rest of the frame it is sending). Takes no lock and never allocates, so the simulation thread or a fault handler may call it. + /// Once it returned, the gate reports closed, also to an opening DOF's main thread is applying at that moment. /// /// The closing's generation, or -1 after . public long LatchOutputGate() @@ -234,8 +254,8 @@ public long LatchOutputGate() public DofGateState GetGateState(long generation) { - var status = DofNative.GateState(Handle, generation, out var written, out var pending, out var failed); - return new DofGateState(status == 1, written, pending, failed, status == 2); + var status = DofNative.GateState(Handle, generation, out var written, out var pending, out var failed, out var untouched); + return new DofGateState(status == 1, written, pending, failed, status == 2, untouched); } /// The names of the controller units that have not written yet, or failed. diff --git a/VisualPinball.Engine.DOF/Native/DofNative.cs b/VisualPinball.Engine.DOF/Native/DofNative.cs index e3cff0a..0f5560b 100644 --- a/VisualPinball.Engine.DOF/Native/DofNative.cs +++ b/VisualPinball.Engine.DOF/Native/DofNative.cs @@ -15,7 +15,7 @@ namespace VisualPinball.Engine.DOF.Native internal static class DofNative { public const string Library = "VpeDof"; - public const int AbiVersion = 3; + public const int AbiVersion = 4; [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void LogCallback(int level, IntPtr message, IntPtr user); @@ -63,7 +63,7 @@ internal static class DofNative public static extern long LatchOutputGate(IntPtr dof); [DllImport(Library, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vpe_dof_gate_state")] - public static extern int GateState(IntPtr dof, long generation, out int confirmed, out int pending, out int failed); + public static extern int GateState(IntPtr dof, long generation, out int confirmed, out int pending, out int failed, out int untouched); [DllImport(Library, CallingConvention = CallingConvention.Cdecl, EntryPoint = "vpe_dof_gate_pending")] public static extern int GatePending(IntPtr dof, long generation, StringCallback callback, IntPtr user); diff --git a/VisualPinball.Engine.DOF/Session/DofSession.cs b/VisualPinball.Engine.DOF/Session/DofSession.cs index f5ab944..8eb0cfd 100644 --- a/VisualPinball.Engine.DOF/Session/DofSession.cs +++ b/VisualPinball.Engine.DOF/Session/DofSession.cs @@ -31,8 +31,6 @@ public sealed class DofSessionOptions { /// The revision folder (). public string BasePath { get; set; } - /// See ; null when no table XML config is bound. - public string TableFile { get; set; } public string RomName { get; set; } /// The game session this DOF session belongs to; events published for another one are rejected. public int GameSession { get; set; } @@ -195,7 +193,7 @@ internal DofSessionDiagnostics(DofSessionState state, string fault, long publish /// The gate is closed before DOF initialises: the session starts dark, and opens once the snapshot is in and DOF /// has processed it. It closes on pause, on a fault and before finishing. A stop, an emergency stop and a fault /// latch it closed, in DOF too (), so an opening DOF has not applied yet - /// applies as a closing and none follows. and complete only when DOF has finished + /// never goes out and none follows. and complete only when DOF has finished /// and been freed, however long that takes; until then no other session can start in the process, and the /// session's owner keeps what DOF uses (device leases, the configuration). tells when /// that takes longer than it should. @@ -611,7 +609,10 @@ private bool Initialise() return false; } try { - native.Init(_options.TableFile, _options.RomName); + // No table file: libdof then looks up no table XML config, whatever the revision's global config names. + // It reads a table config's effects but not the effects it assigns to the table elements, so a loaded one + // leaves the table's effects without a trigger and can drop the ini rows (AddLedControlConfig). + native.Init(null, _options.RomName); } catch (Exception e) { Fail($"DOF could not start: {e.Message}"); return false; diff --git a/VisualPinball.Engine.DOF/Session/IDofNative.cs b/VisualPinball.Engine.DOF/Session/IDofNative.cs index 5eb61ef..2593488 100644 --- a/VisualPinball.Engine.DOF/Session/IDofNative.cs +++ b/VisualPinball.Engine.DOF/Session/IDofNative.cs @@ -18,7 +18,7 @@ public interface IDofNative : IDisposable int PendingInput { get; } void Finish(); long SetOutputGate(bool open); - /// Closes the gate at once and for good: queued and later openings apply as closings. See . + /// Closes the gate at once and for good: queued openings are superseded, later changes apply as closings. See . long LatchOutputGate(); DofGateState GetGateState(long generation); IReadOnlyList GetGatePending(long generation); diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 5c5f69a..5a39f8d 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -28,7 +28,7 @@ set(CMAKE_VISIBILITY_INLINES_HIDDEN ON) set(TP "${CMAKE_CURRENT_SOURCE_DIR}/../third-party") set(GEN "${CMAKE_BINARY_DIR}/generated") -option(VPE_DOF_BUILD_TESTS "Build the native smoke test" ON) +option(VPE_DOF_BUILD_TESTS "Build the native smoke and internal tests" ON) set(VPE_DOF_OUTPUT_DIR "" CACHE PATH "Folder the library is copied to after the build (the Unity package's Plugins/)") if(MSVC) @@ -212,23 +212,28 @@ target_link_libraries(vpe_ftdi PUBLIC vpe_libusb) # --------------------------------------------------------------------------------------------------------------------- # VpeDof -add_library(VpeDof SHARED - ${LIBDOF_SOURCES} - src/vpe_dof.cpp - src/vpe_dof_devices.cpp) -target_include_directories(VpeDof PRIVATE - "${CMAKE_CURRENT_SOURCE_DIR}/include" +# libdof is compiled once, as objects that both the library and the internal tests link. +add_library(vpe_libdof OBJECT ${LIBDOF_SOURCES}) +target_include_directories(vpe_libdof PUBLIC "${LIBDOF}/include" "${LIBDOF}/src" "${LIBDOF}/third-party/include" "${GEN}/include") -target_compile_definitions(VpeDof PRIVATE VPE_DOF_BUILD) +target_compile_definitions(vpe_libdof PUBLIC VPE_DOF_BUILD LIBDOF_STATIC) if(WIN32) - target_compile_definitions(VpeDof PRIVATE NOMINMAX) + target_compile_definitions(vpe_libdof PUBLIC NOMINMAX) endif() -target_link_libraries(VpeDof PRIVATE vpe_hidapi vpe_libusb vpe_serialport vpe_ftdi) +target_link_libraries(vpe_libdof PUBLIC vpe_hidapi vpe_libusb vpe_serialport vpe_ftdi) +if(WIN32) + target_link_libraries(vpe_libdof PUBLIC ws2_32 setupapi cfgmgr32 hid) +endif() + +add_library(VpeDof SHARED + src/vpe_dof.cpp + src/vpe_dof_devices.cpp) +target_include_directories(VpeDof PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_link_libraries(VpeDof PRIVATE vpe_libdof) if(WIN32) - target_link_libraries(VpeDof PRIVATE ws2_32 setupapi cfgmgr32 hid) set_target_properties(VpeDof PROPERTIES PREFIX "" OUTPUT_NAME "VpeDof") elseif(APPLE) set_target_properties(VpeDof PROPERTIES OUTPUT_NAME "VpeDof" INSTALL_NAME_DIR "@rpath" BUILD_WITH_INSTALL_NAME_DIR ON @@ -246,7 +251,7 @@ endif() if(MSVC) # libserialport defines these itself. - foreach(_target vpe_libusb vpe_hidapi vpe_ftdi VpeDof) + foreach(_target vpe_libusb vpe_hidapi vpe_ftdi vpe_libdof VpeDof) target_compile_definitions(${_target} PRIVATE _CRT_SECURE_NO_WARNINGS _CRT_NONSTDC_NO_DEPRECATE) endforeach() endif() @@ -275,4 +280,11 @@ if(VPE_DOF_BUILD_TESTS) add_executable(vpe_dof_smoke tests/smoke.c) target_include_directories(vpe_dof_smoke PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/include") target_link_libraries(vpe_dof_smoke PRIVATE VpeDof) + + # libdof's internals, without the C ABI: what no configuration can reach, such as a toy that fails. + add_executable(vpe_dof_internal tests/internal.cpp) + target_link_libraries(vpe_dof_internal PRIVATE vpe_libdof) + if(NOT WIN32 AND NOT APPLE) + target_link_options(vpe_dof_internal PRIVATE -static-libstdc++ -static-libgcc) + endif() endif() diff --git a/native/build-linux.sh b/native/build-linux.sh index 71d7ddb..d5364f8 100755 --- a/native/build-linux.sh +++ b/native/build-linux.sh @@ -34,4 +34,9 @@ if ! "$BUILD/vpe_dof_smoke" "$NATIVE/tests/fixtures/artnet" "$NATIVE/tests/fixtu echo "The native smoke test failed." exit 1 fi +if ! "$BUILD/vpe_dof_internal" > "$BUILD/internal.log" 2>&1; then + cat "$BUILD/internal.log" + echo "The native internal tests failed." + exit 1 +fi echo "VpeDof $CONFIG built and copied to $OUT" diff --git a/native/build-macos.sh b/native/build-macos.sh index 8be0f67..4fa8f97 100755 --- a/native/build-macos.sh +++ b/native/build-macos.sh @@ -41,6 +41,11 @@ for arch in "${ARCHES[@]}"; do echo "The native smoke test failed ($arch)." exit 1 fi + if ! arch "-$arch" "$BUILD/vpe_dof_internal" > "$BUILD/internal-$arch.log" 2>&1; then + cat "$BUILD/internal-$arch.log" + echo "The native internal tests failed ($arch)." + exit 1 + fi echo "Smoke test passed ($arch)" done echo "VpeDof $CONFIG built and copied to $OUT" diff --git a/native/build-windows.cmd b/native/build-windows.cmd index 7b7eeec..4c68bcd 100644 --- a/native/build-windows.cmd +++ b/native/build-windows.cmd @@ -30,4 +30,10 @@ if errorlevel 1 ( echo The native smoke test failed. exit /b 1 ) +"%BUILD%\%CONFIG%\vpe_dof_internal.exe" > "%BUILD%\internal.log" 2>&1 +if errorlevel 1 ( + type "%BUILD%\internal.log" + echo The native internal tests failed. + exit /b 1 +) echo VpeDof %CONFIG% built and copied to %OUT% diff --git a/native/include/vpe_dof.h b/native/include/vpe_dof.h index 57b7c55..9371827 100644 --- a/native/include/vpe_dof.h +++ b/native/include/vpe_dof.h @@ -36,7 +36,7 @@ extern "C" { #endif /// Version of this ABI. Bumped on every incompatible change; the managed binding refuses a library with another one. -#define VPE_DOF_ABI_VERSION 3 +#define VPE_DOF_ABI_VERSION 4 enum vpe_dof_status { @@ -85,7 +85,8 @@ VPE_DOF_API void VPE_DOF_CALL vpe_dof_data(vpe_dof* dof, char type, int32_t numb VPE_DOF_API void VPE_DOF_CALL vpe_dof_data_named(vpe_dof* dof, const char* name, int32_t value); /// Table element changes queued but not processed by DOF's main thread yet. VPE_DOF_API int32_t VPE_DOF_CALL vpe_dof_pending_input(vpe_dof* dof); -/// Turns every output off, stops DOF's threads and disconnects the controllers. Blocks until they stopped. +/// Turns every output off, stops DOF's threads and disconnects the controllers. Blocks until they stopped. Fails if +/// a controller could not turn its outputs off, neither with its final update nor with its disconnect blackout; the zeros that went out also confirm a closing published just before. VPE_DOF_API int32_t VPE_DOF_CALL vpe_dof_finish(vpe_dof* dof, char* error, int32_t error_size); /// Frees the instance. Calls finish first if it was not called. VPE_DOF_API void VPE_DOF_CALL vpe_dof_destroy(vpe_dof* dof); @@ -95,7 +96,7 @@ VPE_DOF_API void VPE_DOF_CALL vpe_dof_destroy(vpe_dof* dof); /// so a session can start closed; after init it runs on DOF's main thread and returns at once. Returns the gate /// generation, which vpe_dof_gate_state reports against, or -1 while init or finish runs and after finish. It never /// waits for DOF's main thread or a device; it only takes short internal locks. A change queued before finish is still -/// applied. The gate opens with every new instance; after vpe_dof_latch_output_gate an opening applies as a closing. +/// applied. The gate opens with every new instance; after vpe_dof_latch_output_gate a change applies as a closing. VPE_DOF_API int64_t VPE_DOF_CALL vpe_dof_set_output_gate(vpe_dof* dof, int32_t open); /// Turns the controllers' connect test sequences (TestOnConnect of Wemos D1 and UMX controllers) off (allowed = 0) for /// the rest of the instance, or on again. They run only while the gate is open anyway; turned off, they do not run when @@ -104,24 +105,33 @@ VPE_DOF_API int64_t VPE_DOF_CALL vpe_dof_set_output_gate(vpe_dof* dof, int32_t o /// them. VPE_DOF_INVALID_ARGUMENT if `dof` is NULL. VPE_DOF_API int32_t VPE_DOF_CALL vpe_dof_set_connect_tests(vpe_dof* dof, int32_t allowed); /// Closes the output gate at once, from any thread and in any state, and latches it closed for the rest of the -/// instance: openings queued for DOF's main thread and not applied yet, and every later one, apply as closings, and -/// their generations report the closed state. The closing is published to the controllers at once and every -/// controller's updater sends it without DOF's main thread: an idle updater checks the gate every 50 ms, its polling -/// interval, which bounds how long it takes to notice; a busy one sends it after the write in progress (a PacLed64 -/// or PacUIO drops the rest of an opening's update). Returns the closing's generation, or -1 if `dof` is NULL. Safe to call -/// from a realtime thread: it never waits beyond a short internal lock and never allocates (the closing's history entry -/// is storage the other gate calls reserve or, once that ran out, the oldest entry's). +/// instance. An opening requested before the latch that DOF's main thread has not applied yet never reaches the +/// controllers as an opening and reports 2 (superseded); every change requested after it applies as a closing and +/// reports the closed state. When latches race, the first to start decides: every change requested after it started, +/// the other latches included, is a closing, and a result a caller saw does not change when a later latch returns. +/// The closing is published to the controllers at once and every controller's updater sends it without +/// DOF's main thread: an idle updater checks the gate every 50 ms, its polling interval, which bounds how long it takes +/// to notice; a busy one sends it after the write in progress (a PacLed64 or PacUIO drops the rest of an opening's +/// update, a UMX one the rest of the frame it is sending, and sends every line on its next update). Returns the closing's generation, or -1 if `dof` is NULL. Safe to call +/// from a realtime thread or a fault handler: it takes no lock and never allocates. Once it returned, the gate reports +/// closed to every caller, also to an opening DOF's main thread is applying at that moment. VPE_DOF_API int64_t VPE_DOF_CALL vpe_dof_latch_output_gate(vpe_dof* dof); -/// Reports a gate change: 0 until DOF's main thread applied it, then 1, or 2 if a later change set the other state -/// while some unit had not confirmed this one. Also how many controller units confirmed the state: a transfer to their -/// device carried it or a later change to the same state, or, for a unit DOF never used, the gate is open and DOF -/// leaves it alone. And how many have not yet, and how many failed (device missing, write failed, updater stopped or -/// finished). The counts describe the latest generation exactly. For an older one they are what each unit wrote last -/// in that state, at different times, so they do not tell what the outputs show now and 2 can later turn into 1: ask -/// about the latest generation to know the outputs' state. A confirmed state is not a physical acknowledgement: -/// Art-Net, for one, only sends a packet. Counts stay after finish. -VPE_DOF_API int32_t VPE_DOF_CALL vpe_dof_gate_state(vpe_dof* dof, int64_t generation, int32_t* confirmed, int32_t* pending, int32_t* failed); -/// Names the controllers that have not confirmed `generation` yet, through `callback`. +/// Reports a gate change: 0 until DOF's main thread applied it, then 1, or 2 (superseded) if a later change that reached +/// the controllers set the other state, or if it is an opening a latch overtook (see vpe_dof_latch_output_gate). 2 is +/// final. Also how many controller units confirmed the state: a transfer to their device carried it, or a later change +/// to the same state. How many have not yet, how many failed (device missing, write failed, or the updater ended on its +/// own, which outranks what it confirmed before; a unit that finished cleanly keeps what it confirmed or left alone and +/// fails later changes), and how many are untouched: units DOF never used, which it leaves alone while the gate is +/// open, so nothing was written to them. A closing has no untouched units: it is written to every unit. Any of the +/// count pointers may be NULL. The +/// counts describe the latest generation exactly. For an older one they are what each unit wrote last in that state, +/// at different times, so they do not tell what the outputs show now: ask about the latest generation to know the +/// outputs' state. A generation old enough to be forgotten reports 2. A confirmed state is not a physical +/// acknowledgement: it means the transport took the data (Art-Net, for one, only sends a packet). Counts stay after +/// finish. +VPE_DOF_API int32_t VPE_DOF_CALL vpe_dof_gate_state(vpe_dof* dof, int64_t generation, int32_t* confirmed, int32_t* pending, int32_t* failed, int32_t* untouched); +/// Names the controllers that have not confirmed `generation` yet, through `callback`: the ones vpe_dof_gate_state +/// counts as pending or failed. VPE_DOF_API int32_t VPE_DOF_CALL vpe_dof_gate_pending(vpe_dof* dof, int64_t generation, vpe_dof_string_fn callback, void* user); /// Sets one port of an ini device (the N of directoutputconfigN.ini; 1 for directoutputconfig.ini) to a value, as the diff --git a/native/patches/0001-vpe-libdof.patch b/native/patches/0001-vpe-libdof.patch index 4e9976c..01b90f2 100644 --- a/native/patches/0001-vpe-libdof.patch +++ b/native/patches/0001-vpe-libdof.patch @@ -1,47 +1,8 @@ -diff --git a/include/DOF/Config.h b/include/DOF/Config.h -index d07f8b9..80ac11e 100644 ---- a/include/DOF/Config.h -+++ b/include/DOF/Config.h -@@ -1,6 +1,14 @@ - #pragma once - -+#if defined(VPE_DOF_BUILD) -+// Linked into VpeDof, which exports its own C ABI only. -+#define LIBDOFAPI - #ifdef _MSC_VER -+#define LIBDOFCALLBACK __stdcall -+#else -+#define LIBDOFCALLBACK -+#endif -+#elif defined(_MSC_VER) - #define LIBDOFAPI __declspec(dllexport) - #define LIBDOFCALLBACK __stdcall - #else -diff --git a/include/DOF/DOF.h b/include/DOF/DOF.h -index 329ee41..fdfbe4a 100644 ---- a/include/DOF/DOF.h -+++ b/include/DOF/DOF.h -@@ -10,7 +10,15 @@ - #define LIBDOF_VERSION LIBDOF_STR(LIBDOF_VERSION_MAJOR) "." LIBDOF_STR(LIBDOF_VERSION_MINOR) "." LIBDOF_STR(LIBDOF_VERSION_PATCH) - #define LIBDOF_MINOR_VERSION LIBDOF_STR(LIBDOF_VERSION_MAJOR) "." LIBDOF_STR(LIBDOF_VERSION_MINOR) - -+#if defined(VPE_DOF_BUILD) -+// Linked into VpeDof, which exports its own C ABI only. -+#define LIBDOFAPI - #ifdef _MSC_VER -+#define LIBDOFCALLBACK __stdcall -+#else -+#define LIBDOFCALLBACK -+#endif -+#elif defined(_MSC_VER) - #define LIBDOFAPI __declspec(dllexport) - #define LIBDOFCALLBACK __stdcall - #else diff --git a/src/Pinball.cpp b/src/Pinball.cpp -index 0711626..dea04b1 100644 +index fca1659..8e9771b 100644 --- a/src/Pinball.cpp +++ b/src/Pinball.cpp -@@ -11,7 +11,12 @@ +@@ -11,6 +11,9 @@ #include "cab/ICabinetOwner.h" #include "cab/CabinetOwner.h" #include "cab/out/OutputControllerList.h" @@ -49,24 +10,9 @@ index 0711626..dea04b1 100644 +#include "cab/out/OutputGate.h" +#include "cab/out/OutputList.h" #include "cab/overrides/TableOverrideSettings.h" -+#include "cab/schedules/ScheduledSettings.h" -+#include "cab/sequencer/SequentialOutputSettings.h" - #include "cab/toys/ToyList.h" - #include "globalconfiguration/GlobalConfig.h" - #include "pinballsupport/AlarmHandler.h" -@@ -52,6 +57,11 @@ void Pinball::Setup(const std::string& globalConfigFileName, const std::string& - { - bool globalConfigLoaded = true; - -+ // These settings are process-wide and only loaded when a cabinet config has them: forget the previous session's. -+ ScheduledSettings::GetInstance().Clear(); -+ SequentialOutputSettings::GetInstance().Clear(); -+ TableOverrideSettings::GetInstance()->ClearSettings(); -+ - try - { - Log::Write(StringExtensions::Build("Global config filename is \"{0}\"", globalConfigFileName)); -@@ -59,12 +69,11 @@ void Pinball::Setup(const std::string& globalConfigFileName, const std::string& + #include "cab/schedules/ScheduledSettings.h" + #include "cab/sequencer/SequentialOutputSettings.h" +@@ -66,12 +69,11 @@ void Pinball::Setup(const std::string& globalConfigFileName, const std::string& { FileInfo* globalConfigFile = new FileInfo(globalConfigFileName); GlobalConfig* newGlobalConfig = GlobalConfig::GetGlobalConfigFromConfigXmlFile(globalConfigFile->FullName()); @@ -82,16 +28,7 @@ index 0711626..dea04b1 100644 } delete m_globalConfig; m_globalConfig = newGlobalConfig; -@@ -80,7 +89,7 @@ void Pinball::Setup(const std::string& globalConfigFileName, const std::string& - } - catch (const std::exception& e) - { -- throw std::runtime_error("DirectOutput framework could not initialize global config."); -+ throw std::runtime_error(std::string("DirectOutput framework could not initialize global config: ") + e.what()); - } - - try -@@ -88,19 +97,8 @@ void Pinball::Setup(const std::string& globalConfigFileName, const std::string& +@@ -95,19 +97,8 @@ void Pinball::Setup(const std::string& globalConfigFileName, const std::string& Log::SetFilename(m_globalConfig->GetLogFilename(!StringExtensions::IsNullOrWhiteSpace(tableFilename) ? FileInfo(tableFilename).FullName() : "", romName)); Log::SetInstrumentations(m_globalConfig->GetInstrumentation()); @@ -113,16 +50,7 @@ index 0711626..dea04b1 100644 Log::Init(m_globalConfig->IsEnableLogging()); } -@@ -144,6 +142,8 @@ void Pinball::Setup(const std::string& globalConfigFileName, const std::string& - try - { - m_cabinet = Cabinet::GetCabinetFromConfigXmlFile(cabinetConfigFile); -+ if (!m_cabinet) -+ throw std::runtime_error("the file is not a valid cabinet config"); - - Log::Write(StringExtensions::Build("{0} output controller definitions and {1} toy definitions loaded from cabinet config.", - std::to_string(static_cast(m_cabinet->GetOutputControllers()->size())), std::to_string(static_cast(m_cabinet->GetToys()->size())))); -@@ -166,15 +166,30 @@ void Pinball::Setup(const std::string& globalConfigFileName, const std::string& +@@ -175,15 +166,30 @@ void Pinball::Setup(const std::string& globalConfigFileName, const std::string& } catch (const std::exception& e) { @@ -153,18 +81,20 @@ index 0711626..dea04b1 100644 if (m_cabinet == nullptr) { Log::Write("No cabinet config file loaded. Will use AutoConfig."); -@@ -200,7 +215,9 @@ void Pinball::Setup(const std::string& globalConfigFileName, const std::string& +@@ -209,9 +215,10 @@ void Pinball::Setup(const std::string& globalConfigFileName, const std::string& Log::Write(StringExtensions::Build("Will load table config from {0}", tableConfigFile->FullName())); try { - Table* newTable = Table::GetTableFromConfigXmlFile(tableFile->FullName()); ++ // VPE: the table config, not the table file it was found for. + Table* newTable = Table::GetTableFromConfigXmlFile(tableConfigFile->FullName()); -+ if (!newTable) -+ throw std::runtime_error("the file is not a valid table config"); + if (!newTable) +- throw std::runtime_error(StringExtensions::Build("{0} is not a valid table config", tableFile->FullName())); ++ throw std::runtime_error(StringExtensions::Build("{0} is not a valid table config", tableConfigFile->FullName())); delete m_table; m_table = newTable; m_table->SetTableConfigurationFilename(tableConfigFile->FullName()); -@@ -258,32 +275,6 @@ void Pinball::Setup(const std::string& globalConfigFileName, const std::string& +@@ -269,32 +276,6 @@ void Pinball::Setup(const std::string& globalConfigFileName, const std::string& c->SetEffectRGBMinDurationMs(m_globalConfig->GetLedControlMinimumRGBEffectDurationMs()); c->Setup(l, m_table, m_cabinet, romName); delete c; @@ -197,124 +127,43 @@ index 0711626..dea04b1 100644 } delete l; } -@@ -314,7 +305,7 @@ void Pinball::Setup(const std::string& globalConfigFileName, const std::string& - catch (const std::exception& e) - { - Log::Exception(StringExtensions::Build("DirectOutput framework has encountered an exception during setup: {0}", e.what())); -- throw std::runtime_error("DirectOutput framework has encountered a exception during setup."); -+ throw std::runtime_error(std::string("DirectOutput framework has encountered a exception during setup: ") + e.what()); - } - } - -@@ -329,10 +320,22 @@ void Pinball::Init() - co->GetConfigurationSettings().emplace("LedControlMinimumEffectDurationMs", std::to_string(m_globalConfig->GetLedControlMinimumEffectDurationMs())); - co->GetConfigurationSettings().emplace("LedWizDefaultMinCommandIntervalMs", std::to_string(m_globalConfig->GetLedWizDefaultMinCommandIntervalMs())); - co->GetConfigurationSettings().emplace("PacLedDefaultMinCommandIntervalMs", std::to_string(m_globalConfig->GetPacLedDefaultMinCommandIntervalMs())); -- m_cabinet->Init(co); -+ // VPE: Finish unwinds what was started, also when an Init below fails half-way. -+ m_cabinetStarted = true; -+ try -+ { -+ m_cabinet->Init(co); -+ } -+ catch (...) -+ { -+ delete co; -+ throw; -+ } - delete co; - -+ m_tableStarted = true; - m_table->Init(this); -+ m_alarmsStarted = true; - m_alarms->Init(this); - m_table->TriggerStaticEffects(); - m_cabinet->Update(); -@@ -344,29 +347,46 @@ void Pinball::Init() - catch (const std::exception& e) - { - Log::Exception(StringExtensions::Build("DirectOutput framework has encountered an exception during initialization: {0}", e.what())); -- throw std::runtime_error("DirectOutput framework has encountered a exception during initialization."); -+ throw std::runtime_error(std::string("DirectOutput framework has encountered a exception during initialization: ") + e.what()); - } - } - - void Pinball::Finish() - { -- try -- { -- Log::Write("Finishing framework"); -- FinishMainThread(); -- -- m_alarms->Finish(); -- m_table->Finish(); -- m_cabinet->Finish(); -- -- Log::Write("DirectOutput framework finished."); -- Log::Write("Bye and thanks for using!"); -- } -- catch (const std::exception& e) -- { -- Log::Exception(StringExtensions::Build("An exception occured while finishing the DirectOutput framework: {0}", e.what())); -- throw std::runtime_error("DirectOutput framework has encountered while finishing."); -- } -+ // Every step runs even if an earlier one failed, so the output controllers always get to turn their outputs off. -+ Log::Write("Finishing framework"); -+ std::string firstError; -+ auto step = [&firstError](const char* name, const std::function& action) { -+ try -+ { -+ action(); -+ } -+ catch (const std::exception& e) -+ { -+ Log::Exception(StringExtensions::Build("An exception occured while finishing the {0}: {1}", name, e.what())); -+ if (firstError.empty()) -+ firstError = StringExtensions::Build("{0}: {1}", name, e.what()); -+ } -+ catch (...) -+ { -+ Log::Exception(StringExtensions::Build("An unknown exception occured while finishing the {0}", name)); -+ if (firstError.empty()) -+ firstError = name; -+ } -+ }; -+ step("main thread", [this]() { FinishMainThread(); }); -+ if (m_alarmsStarted && m_alarms) -+ step("alarms", [this]() { m_alarms->Finish(); }); -+ if (m_tableStarted && m_table) -+ step("table", [this]() { m_table->Finish(); }); -+ if (m_cabinetStarted && m_cabinet) -+ step("cabinet", [this]() { m_cabinet->Finish(); }); -+ m_alarmsStarted = m_tableStarted = m_cabinetStarted = false; -+ if (!firstError.empty()) -+ throw std::runtime_error("DirectOutput framework failed to finish: " + firstError); -+ -+ Log::Write("DirectOutput framework finished."); -+ Log::Write("Bye and thanks for using!"); - } - - void Pinball::InitMainThread() -@@ -422,6 +442,18 @@ void Pinball::MainThreadDoIt() - while (m_keepMainThreadAlive) - { +@@ -460,19 +441,23 @@ void Pinball::MainThreadDoIt() bool updateRequired = false; -+ -+ bool hasCommands; -+ { -+ std::lock_guard lock(m_mainThreadMutex); -+ hasCommands = !m_commands.empty(); -+ } -+ if (hasCommands) -+ { -+ RunCommands(); -+ updateRequired = true; -+ } -+ auto start = std::chrono::steady_clock::now(); - while (m_inputQueue->Count() > 0 && std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count() <= MAX_INPUT_DATA_PROCESSING_TIME_MS -@@ -471,12 +503,12 @@ void Pinball::MainThreadDoIt() +- while (m_inputQueue->Count() > 0 && std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count() <= MAX_INPUT_DATA_PROCESSING_TIME_MS +- && m_keepMainThreadAlive) ++ // VPE: host commands and table element changes are processed in the order they came: a command runs once the ++ // changes queued before it are processed, so a gate that opens does not send a value that was already turned off, ++ // and a change queued after a closing does not go out before it. ++ while (m_keepMainThreadAlive) + { +- try +- { +- TableElementData data = m_inputQueue->Dequeue(); +- m_table->UpdateTableElement(&data); +- updateRequired = true; +- } +- catch (const std::exception& e) +- { +- Log::Exception(StringExtensions::Build("An unhandled exception occured while processing table element data: {0}", e.what())); +- } ++ std::function command; ++ TableElementData data; ++ Work work = TakeWork(false, command, data); ++ if (work == Work::None) ++ break; ++ if (work == Work::Command) ++ RunCommand(command); ++ else ++ ProcessInput(data); ++ updateRequired = true; ++ if (std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count() > MAX_INPUT_DATA_PROCESSING_TIME_MS) ++ break; + } + + if (m_keepMainThreadAlive) +@@ -507,12 +492,12 @@ void Pinball::MainThreadDoIt() std::unique_lock lock(m_mainThreadMutex); @@ -329,41 +178,97 @@ index 0711626..dea04b1 100644 now = std::chrono::steady_clock::now(); nextAlarm = m_alarms->GetNextAlarmTime(); -@@ -489,6 +521,33 @@ void Pinball::MainThreadDoIt() +@@ -525,6 +510,89 @@ void Pinball::MainThreadDoIt() { Log::Exception(StringExtensions::Build("An unexpected exception occured in the DirectOutput MainThread: {0}", e.what())); } + // VPE: commands posted before the thread was asked to stop still run, so a gate change queued just before Finish is + // applied (and its generation published) before the controllers turn everything off. -+ RunCommands(); ++ DrainCommands(); +} + -+void Pinball::RunCommands() ++void Pinball::DrainCommands() +{ -+ std::vector> commands; ++ // The input a command waits for is processed first, so an opening does not restore an output whose off came before it. ++ // Input queued after the last command is left: Finish turns everything off. ++ while (true) + { -+ std::lock_guard lock(m_mainThreadMutex); -+ commands.swap(m_commands); ++ std::function command; ++ TableElementData data; ++ Work work = TakeWork(true, command, data); ++ if (work == Work::None) ++ break; ++ if (work == Work::Command) ++ RunCommand(command); ++ else ++ ProcessInput(data); + } -+ for (auto& command : commands) ++ // Commands whose input is gone. ++ while (true) + { -+ try ++ std::function command; + { -+ command(); -+ } -+ catch (const std::exception& e) -+ { -+ Log::Exception(StringExtensions::Build("An unhandled exception occured while running a host command: {0}", e.what())); -+ } -+ catch (...) -+ { -+ Log::Exception("An unhandled exception occured while running a host command"); ++ std::lock_guard lock(m_mainThreadMutex); ++ if (m_commands.empty()) ++ return; ++ command = std::move(m_commands.front().run); ++ m_commands.pop_front(); + } ++ RunCommand(command); ++ } ++} ++ ++Pinball::Work Pinball::TakeWork(bool onlyForCommands, std::function& command, TableElementData& data) ++{ ++ // One lock for the choice and the dequeue: what the host queues in between waits for the next call. ++ std::lock_guard lock(m_mainThreadMutex); ++ if (!m_commands.empty() && m_commands.front().inputsBefore <= 0) ++ { ++ command = std::move(m_commands.front().run); ++ m_commands.pop_front(); ++ return Work::Command; ++ } ++ if ((onlyForCommands && m_commands.empty()) || m_inputQueue->Count() == 0) ++ return Work::None; ++ data = m_inputQueue->Dequeue(); ++ for (Command& queued : m_commands) ++ { ++ if (queued.inputsBefore > 0) ++ queued.inputsBefore--; ++ } ++ return Work::Input; ++} ++ ++void Pinball::RunCommand(std::function& command) ++{ ++ try ++ { ++ command(); ++ } ++ catch (const std::exception& e) ++ { ++ Log::Exception(StringExtensions::Build("An unhandled exception occured while running a host command: {0}", e.what())); ++ } ++ catch (...) ++ { ++ Log::Exception("An unhandled exception occured while running a host command"); ++ } ++} ++ ++void Pinball::ProcessInput(TableElementData& data) ++{ ++ try ++ { ++ m_table->UpdateTableElement(&data); ++ } ++ catch (const std::exception& e) ++ { ++ Log::Exception(StringExtensions::Build("An unhandled exception occured while processing table element data: {0}", e.what())); + } } void Pinball::ReceiveData(char type, int number, int value) -@@ -509,4 +568,62 @@ void Pinball::ReceiveData(const TableElementData& tableElementData) +@@ -545,4 +613,68 @@ void Pinball::ReceiveData(const TableElementData& tableElementData) MainThreadSignal(); } @@ -373,7 +278,7 @@ index 0711626..dea04b1 100644 + std::lock_guard lock(m_mainThreadMutex); + if (!m_keepMainThreadAlive || !IsMainThreadActive()) + return false; -+ m_commands.push_back(std::move(command)); ++ m_commands.push_back({ m_inputQueue->Count(), std::move(command) }); + m_mainThreadDoWork = true; + } + m_mainThreadCV.notify_one(); @@ -386,7 +291,7 @@ index 0711626..dea04b1 100644 + if (!m_keepMainThreadAlive || !IsMainThreadActive()) + return -1; + int64_t generation = OutputGate::Instance().Request(open); -+ m_commands.push_back([this, open, generation]() { ApplyOutputGate(open, generation); }); ++ m_commands.push_back({ m_inputQueue->Count(), [this, open, generation]() { ApplyOutputGate(open, generation); } }); + m_mainThreadDoWork = true; + m_mainThreadCV.notify_one(); + return generation; @@ -396,8 +301,14 @@ index 0711626..dea04b1 100644 +{ + OutputGate& gate = OutputGate::Instance(); + bool wasOpen = gate.IsOpen(); ++ // The toys get the input processed before this change. An opening updates them while the gate is still closed, a ++ // closing once it is closed, so neither sends a value the gate should hold back. ++ if (open && m_cabinet && m_cabinet->GetToys()) ++ m_cabinet->GetToys()->UpdateOutputs(); + // A latched gate applies an opening as a closing. + open = gate.Apply(open); ++ if (!open && m_cabinet && m_cabinet->GetToys()) ++ m_cabinet->GetToys()->UpdateOutputs(); + if (wasOpen != open) + { + // Outputs with a value now report another one: tell their controllers. Outputs at 0 report 0 either way. @@ -427,22 +338,23 @@ index 0711626..dea04b1 100644 + } diff --git a/src/Pinball.h b/src/Pinball.h -index a48d4e7..433d804 100644 +index 4bf85b5..d45e4df 100644 --- a/src/Pinball.h +++ b/src/Pinball.h -@@ -3,8 +3,11 @@ +@@ -3,9 +3,12 @@ #include #include #include +#include -+#include ++#include + #include #include #include +#include #include "DOF/DOF.h" -@@ -40,6 +43,15 @@ public: +@@ -42,7 +45,18 @@ public: void ReceiveData(const std::string& tableElementName, int value); void ReceiveData(const TableElementData& tableElementData); @@ -456,55 +368,105 @@ index a48d4e7..433d804 100644 + int GetPendingInputCount() const; + private: ++ friend class PinballTestAccess; ++ void SetAlarms(AlarmHandler* alarms) { m_alarms = alarms; } void SetGlobalConfig(GlobalConfig* globalConfig) { m_globalConfig = globalConfig; } -@@ -59,6 +71,15 @@ private: + +@@ -61,6 +75,29 @@ private: std::condition_variable m_mainThreadCV; std::atomic m_keepMainThreadAlive; std::atomic m_mainThreadDoWork; -+ std::vector> m_commands; ++ // A host command waits for the table element changes that were queued before it (inputsBefore of them are left). ++ struct Command ++ { ++ int inputsBefore; ++ std::function run; ++ }; ++ std::deque m_commands; + -+ void ApplyOutputGate(bool open, int64_t generation); -+ void RunCommands(); ++ enum class Work ++ { ++ None, ++ Command, ++ Input, ++ }; + -+ // What Init started, so that Finish stops only that. -+ bool m_cabinetStarted = false; -+ bool m_tableStarted = false; -+ bool m_alarmsStarted = false; - - static const int MAX_INPUT_DATA_PROCESSING_TIME_MS = 10; - }; ++ void ApplyOutputGate(bool open, int64_t generation); ++ // Takes the next thing to do: the first command once the input queued before it was processed, or else the next ++ // input (only while a command waits for it, if `onlyForCommands`). ++ Work TakeWork(bool onlyForCommands, std::function& command, TableElementData& data); ++ void RunCommand(std::function& command); ++ void ProcessInput(TableElementData& data); ++ // When the main thread stops: runs the commands still queued, each after the input that was queued before it. ++ void DrainCommands(); + + bool m_tableStarted = false; + bool m_alarmsStarted = false; diff --git a/src/cab/Cabinet.cpp b/src/cab/Cabinet.cpp -index cbb4552..9dbd29c 100644 +index 75f454d..d528403 100644 --- a/src/cab/Cabinet.cpp +++ b/src/cab/Cabinet.cpp -@@ -16,6 +16,7 @@ - #include "sequencer/SequentialOutputSettings.h" - #include "overrides/TableOverrideSettings.h" - #include -+#include +@@ -4,6 +4,7 @@ + #include "../general/StringExtensions.h" + #include "../general/FileInfo.h" + #include "../general/FileReader.h" ++#include "../general/PathConfinement.h" + #include "../general/CurveList.h" + #include "../general/color/ColorList.h" + #include "CabinetOutputList.h" +@@ -151,6 +152,9 @@ std::string Cabinet::GetConfigXml() - #ifdef __HIDAPI__ - #include "out/ps/Pinscape.h" -@@ -267,8 +268,19 @@ void Cabinet::Finish() + void Cabinet::SaveConfigXmlFile(const std::string& filename) { - Log::Write("Finishing cabinet"); ++ // VPE: tinyxml2 writes the file itself, past the check in WriteToFile. ++ if (!PathConfinement::IsWriteAllowed(filename)) ++ return; + std::string xml = GetConfigXml(); + if (xml.empty()) + { +@@ -387,20 +391,6 @@ bool Cabinet::FromXml(const tinyxml2::XMLElement* element) + m_autoConfigEnabled = (autoConfigText == "true"); + } -- m_toys->Finish(); -+ // VPE: the controllers are finished (and turned off) even when a toy fails to finish. -+ std::exception_ptr toyError; -+ try +- const tinyxml2::XMLElement* scheduledElement = element->FirstChildElement("ScheduledSettings"); +- if (scheduledElement) +- { +- ScheduledSettings& scheduledSettings = ScheduledSettings::GetInstance(); +- scheduledSettings.FromXml(scheduledElement); +- } +- +- const tinyxml2::XMLElement* sequentialElement = element->FirstChildElement("SequentialOutputSettings"); +- if (sequentialElement) +- { +- SequentialOutputSettings& sequentialSettings = SequentialOutputSettings::GetInstance(); +- sequentialSettings.FromXml(sequentialElement); +- } +- + const tinyxml2::XMLElement* controllersElement = element->FirstChildElement("OutputControllers"); + if (controllersElement && m_outputControllers) + { +@@ -460,6 +450,22 @@ bool Cabinet::FromXml(const tinyxml2::XMLElement* element) + } + } + ++ // VPE: the process-wide settings go in last, so a cabinet config that fails while its controllers or toys load does ++ // not leave its schedules behind. ++ const tinyxml2::XMLElement* scheduledElement = element->FirstChildElement("ScheduledSettings"); ++ if (scheduledElement) + { -+ m_toys->Finish(); ++ ScheduledSettings& scheduledSettings = ScheduledSettings::GetInstance(); ++ scheduledSettings.FromXml(scheduledElement); + } -+ catch (...) ++ ++ const tinyxml2::XMLElement* sequentialElement = element->FirstChildElement("SequentialOutputSettings"); ++ if (sequentialElement) + { -+ toyError = std::current_exception(); ++ SequentialOutputSettings& sequentialSettings = SequentialOutputSettings::GetInstance(); ++ sequentialSettings.FromXml(sequentialElement); + } - m_outputControllers->Finish(); -+ if (toyError) -+ std::rethrow_exception(toyError); - Log::Write("Cabinet finished"); ++ + return true; } diff --git a/src/cab/out/IOutput.cpp b/src/cab/out/IOutput.cpp @@ -571,7 +533,7 @@ index f222f0c..bdd8bf0 100644 } diff --git a/src/cab/out/OutputControllerCompleteBase.cpp b/src/cab/out/OutputControllerCompleteBase.cpp -index f4958df..4d709cb 100644 +index f4958df..101b3cb 100644 --- a/src/cab/out/OutputControllerCompleteBase.cpp +++ b/src/cab/out/OutputControllerCompleteBase.cpp @@ -1,5 +1,6 @@ @@ -632,7 +594,7 @@ index f4958df..4d709cb 100644 try { try -@@ -277,19 +299,27 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() +@@ -277,19 +299,29 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() catch (...) { } @@ -644,6 +606,8 @@ index f4958df..4d709cb 100644 Log::Write(StringExtensions::Build("Updater thread connected to {0} {1}", GetXmlElementName(), GetName())); + bool died = false; ++ // VPE: the outputs were turned off by the blackout sent while reconnecting, the last thing a unit that died got. ++ bool offWhenDied = false; while (m_keepUpdaterThreadAlive) { + // The generation and its state are read together, before the values: the main thread stores the values of a @@ -660,20 +624,21 @@ index f4958df..4d709cb 100644 bool updateOK = true; try -@@ -302,13 +332,20 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() +@@ -302,18 +334,27 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() m_inUseState = InUseState::Running; } - if (m_inUseState == InUseState::Running) - UpdateOutputs(valuesToSend); -+ bool delivered; + if (m_inUseState == InUseState::Running || !gate.open) -+ delivered = Transfer(valuesToSend, !gateUnit->IsAcked(gate)); ++ { ++ if (Transfer(valuesToSend, !gateUnit->IsAcked(gate))) ++ gateUnit->Ack(gate); ++ } + else -+ // Open, and DOF never used this controller: it leaves the hardware alone, so there is nothing to send. -+ delivered = true; -+ if (delivered) -+ gateUnit->Ack(gate); ++ // Open, and DOF never used this controller: it leaves the hardware alone, so there is nothing to send, and ++ // nothing is confirmed either. ++ gateUnit->Untouched(gate); } catch (const std::exception& e) { @@ -683,47 +648,88 @@ index f4958df..4d709cb 100644 } if (!updateOK) -@@ -328,6 +365,7 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() + { + Log::Warning("Trying to reconnect to controller..."); ++ m_disconnectSentZeros = false; + try + { + DisconnectFromController(); +@@ -328,6 +369,8 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() } catch (...) { ++ offWhenDied = m_disconnectSentZeros; + died = true; break; } Log::Write("Reconnected to controller"); -@@ -343,15 +381,22 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() +@@ -341,33 +384,93 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() + m_updateRequired = false; + } ++ // Whether the final transfer is skipped: open, and DOF never used the controller. ++ bool untouched = m_inUseState == InUseState::Startup && OutputGate::Instance().IsOpen(); ++ // VPE: read before the zeros go out, so a closing published just before Finish is confirmed by them. ++ OutputGate::Snapshot finalGate = gateUnit->Observe(); ++ bool zerosSent = false; ++ bool finalFailed = false; try { - if (m_inUseState != InUseState::Startup) + if (died) + { -+ if (m_inUseState != InUseState::Startup || !OutputGate::Instance().IsOpen()) ++ if (!untouched && !offWhenDied) + m_finishError = StringExtensions::Build("{0} {1} lost its connection; its outputs may still be on", GetXmlElementName(), GetName()); + } -+ else if (m_inUseState != InUseState::Startup || !OutputGate::Instance().IsOpen()) ++ else if (!untouched) { std::vector zeroValues(m_outputValues.size(), 0); - UpdateOutputs(zeroValues); -+ if (!Transfer(zeroValues, true)) ++ zerosSent = Transfer(zeroValues, true); ++ if (!zerosSent) ++ { + m_finishError = StringExtensions::Build("{0} {1} could not send its final update", GetXmlElementName(), GetName()); ++ finalFailed = true; ++ } } } catch (const std::exception& e) { Log::Exception(StringExtensions::Build("Exception occurred while trying to turn off all outputs: {0}", e.what())); + m_finishError = StringExtensions::Build("{0} {1} could not turn its outputs off: {2}", GetXmlElementName(), GetName(), e.what()); ++ finalFailed = true; } try -@@ -361,13 +406,36 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() + { ++ m_disconnectSentZeros = false; + DisconnectFromController(); ++ // VPE: a blackout the disconnect sent turns the outputs off as well. One that sends nothing changes nothing. ++ if (m_disconnectSentZeros) ++ { ++ zerosSent = true; ++ if (finalFailed || died) ++ m_finishError.clear(); ++ } ++ } ++ catch (const std::exception& e) ++ { ++ // VPE: without a final transfer, what the controller sends as it disconnects (a blackout) is the last word. ++ Log::Exception(StringExtensions::Build("Disconnecting from {0} {1} failed: {2}", GetXmlElementName(), GetName(), e.what())); ++ if (untouched && !died && m_finishError.empty()) ++ m_finishError = StringExtensions::Build("{0} {1} could not turn its outputs off: {2}", GetXmlElementName(), GetName(), e.what()); + } catch (...) { } + if (died) + gateUnit->Die(); + else ++ { ++ if (zerosSent && !finalGate.open) ++ gateUnit->Ack(finalGate); + gateUnit->Stop(); ++ } Log::Write("Updater thread disconnected and will terminate"); } catch (const std::exception& e) @@ -754,7 +760,7 @@ index f4958df..4d709cb 100644 + } diff --git a/src/cab/out/OutputControllerCompleteBase.h b/src/cab/out/OutputControllerCompleteBase.h -index 48b8eb9..27f0886 100644 +index 48b8eb9..7d04351 100644 --- a/src/cab/out/OutputControllerCompleteBase.h +++ b/src/cab/out/OutputControllerCompleteBase.h @@ -3,8 +3,10 @@ @@ -768,7 +774,7 @@ index 48b8eb9..27f0886 100644 #include #include -@@ -44,7 +46,12 @@ protected: +@@ -44,7 +46,15 @@ protected: virtual bool VerifySettings() = 0; virtual void ConnectToController() = 0; virtual void DisconnectFromController() = 0; @@ -778,10 +784,13 @@ index 48b8eb9..27f0886 100644 virtual void UpdateOutputs(const std::vector& outputValues) = 0; + bool m_forceFullTransfer = false; + bool m_transferSkipped = false; ++ // VPE: set by a DisconnectFromController that turned every output off (a blackout that got to the device), which ++ // counts as the final update the updater sends when it ends. ++ bool m_disconnectSentZeros = false; void InitUpdaterThread(); -@@ -72,7 +79,12 @@ private: +@@ -72,7 +82,12 @@ private: mutable std::mutex m_conditionMutex; bool m_keepUpdaterThreadAlive; std::atomic m_updaterThreadFinished { false }; @@ -795,62 +804,35 @@ index 48b8eb9..27f0886 100644 } diff --git a/src/cab/out/OutputControllerList.cpp b/src/cab/out/OutputControllerList.cpp -index a52dbe7..7343139 100644 +index 89138e9..4c92600 100644 --- a/src/cab/out/OutputControllerList.cpp +++ b/src/cab/out/OutputControllerList.cpp -@@ -1,4 +1,5 @@ - #include "OutputControllerList.h" -+#include - - #include "../../Log.h" - #include "../../general/StringExtensions.h" -@@ -60,8 +61,30 @@ void OutputControllerList::Finish() - { - Log::Write("Finishing output controllers"); +@@ -215,7 +215,18 @@ bool OutputControllerList::FromXml(const tinyxml2::XMLElement* element) -+ // VPE: every controller is finished, and the ones that failed (a final all-off that did not get there) are reported -+ // together once all are done. -+ std::string failures; - for (IOutputController* controller : *this) -- controller->Finish(); -+ { -+ std::string error; -+ try -+ { -+ controller->Finish(); -+ } -+ catch (const std::exception& e) -+ { -+ error = e.what(); -+ } -+ catch (...) -+ { -+ error = "unknown error"; -+ } -+ if (!error.empty()) -+ { -+ Log::Exception(StringExtensions::Build("Finishing output controller {0} failed: {1}", controller->GetName(), error)); -+ failures += (failures.empty() ? "" : "; ") + controller->GetName() + ": " + error; -+ } -+ } - - #ifdef __HIDAPI__ - DudesCab::ClearDevices(); -@@ -69,6 +92,8 @@ void OutputControllerList::Finish() - #endif - - Log::Write("Output controllers finished"); -+ if (!failures.empty()) -+ throw std::runtime_error("output controllers failed to finish: " + failures); - } - - void OutputControllerList::Update() + if (controller) + { +- if (controller->FromXml(controllerElement)) ++ // VPE: a controller whose settings throw is freed before the error goes on. ++ bool loaded; ++ try ++ { ++ loaded = controller->FromXml(controllerElement); ++ } ++ catch (...) ++ { ++ delete controller; ++ throw; ++ } ++ if (loaded) + { + push_back(controller); + Log::Write(StringExtensions::Build("Loaded output controller: {0} ({1})", controller->GetName(), typeName)); diff --git a/src/cab/out/OutputGate.cpp b/src/cab/out/OutputGate.cpp new file mode 100644 -index 0000000..824f940 +index 0000000..41909e6 --- /dev/null +++ b/src/cab/out/OutputGate.cpp -@@ -0,0 +1,221 @@ +@@ -0,0 +1,291 @@ +#include "OutputGate.h" + +#include @@ -876,14 +858,24 @@ index 0000000..824f940 +bool OutputGate::Unit::IsAcked(const Snapshot& snapshot) const +{ + const std::atomic& acked = snapshot.open ? m_ackedOpen : m_ackedClosed; -+ return acked.load(std::memory_order_acquire) >= snapshot.generation; ++ return acked.load(std::memory_order_acquire) >= snapshot.generation || (snapshot.open && m_untouched.load(std::memory_order_acquire) >= snapshot.generation); +} + +void OutputGate::Unit::Ack(const Snapshot& snapshot) { RaiseTo(snapshot.open ? m_ackedOpen : m_ackedClosed, snapshot.generation); } + ++void OutputGate::Unit::Untouched(const Snapshot& snapshot) ++{ ++ if (snapshot.open) ++ RaiseTo(m_untouched, snapshot.generation); ++} ++ +void OutputGate::Unit::Fail(int64_t generation) { RaiseTo(m_failed, generation); } + -+void OutputGate::Unit::Die() { Fail(INT64_MAX); } ++void OutputGate::Unit::Die() ++{ ++ m_dead.store(true, std::memory_order_release); ++ Fail(INT64_MAX); ++} + +void OutputGate::Unit::Stop() { m_stopped.store(true, std::memory_order_release); } + @@ -903,10 +895,13 @@ index 0000000..824f940 +{ + std::lock_guard lock(m_mutex); + m_session++; -+ int64_t generation = ++m_requested; -+ Record(generation, true); -+ Reserve(); ++ m_history.clear(); ++ // The new session's first generation, with the latch flag cleared. ++ int64_t generation = (m_requested.load(std::memory_order_acquire) >> 1) + 1; ++ m_requested.store(generation << 1, std::memory_order_release); ++ Record(generation, true, true); + m_latched.store(false, std::memory_order_release); ++ m_latchGeneration.store(0, std::memory_order_release); + m_open.store(true, std::memory_order_release); + m_connectTests.store(true, std::memory_order_release); + m_published.store(Pack(generation, true), std::memory_order_release); @@ -930,142 +925,199 @@ index 0000000..824f940 + +void OutputGate::RegisterFailed(const std::string& name) { Register(name)->Die(); } + ++int64_t OutputGate::Reserve(bool& latched) ++{ ++ // The latch flag shares the word with the counter, so a generation is taken either before the session's first latch ++ // or after it, never in between. ++ int64_t word = m_requested.fetch_add(2, std::memory_order_acq_rel); ++ latched = (word & 1) != 0; ++ return (word >> 1) + 1; ++} ++ +int64_t OutputGate::Request(bool open) +{ + std::lock_guard lock(m_mutex); -+ int64_t generation = ++m_requested; -+ Record(generation, open && !m_latched.load(std::memory_order_relaxed)); -+ Reserve(); ++ bool latched; ++ int64_t generation = Reserve(latched); ++ // A change requested once a latch took its generation is a closing, from the start. One taken before stays what it ++ // asked for, also when a latch comes before it is recorded. ++ Record(generation, open && !latched, false); + return generation; +} + -+void OutputGate::Record(int64_t generation, bool open) ++void OutputGate::Record(int64_t generation, bool open, bool published) +{ -+ m_history[generation] = open; ++ m_history[generation] = { open, published }; + while (m_history.size() > MaxHistory) + m_history.erase(m_history.begin()); +} + -+void OutputGate::Reserve() -+{ -+ while (m_spares.size() < SpareNodes) -+ { -+ std::map scratch; -+ scratch.emplace(0, false); -+ m_spares.push_back(scratch.extract(scratch.begin())); -+ } -+} -+ +bool OutputGate::Apply(bool open) +{ + std::lock_guard lock(m_mutex); -+ if (m_latched.load(std::memory_order_relaxed)) ++ if (m_latched.load(std::memory_order_acquire)) + open = false; + m_open.store(open, std::memory_order_release); ++ // A latch that came after the check above wins: it does not take the mutex. ++ if (open && m_latched.load(std::memory_order_acquire)) ++ { ++ m_open.store(false, std::memory_order_release); ++ open = false; ++ } + return open; +} + -+int64_t OutputGate::Latch() ++int64_t OutputGate::BeginLatch() +{ -+ int64_t generation; ++ m_latched.store(true, std::memory_order_release); ++ m_open.store(false, std::memory_order_release); ++ // Takes the generation and sets the latch flag in one step: every generation taken after it is recorded as a closing ++ // (Request), so what a change reports does not depend on when this latch gets to install its generation below. ++ int64_t word = m_requested.load(std::memory_order_acquire); ++ while (!m_requested.compare_exchange_weak(word, (((word >> 1) + 1) << 1) | 1, std::memory_order_acq_rel, std::memory_order_acquire)) + { -+ std::lock_guard lock(m_mutex); -+ m_latched.store(true, std::memory_order_release); -+ m_open.store(false, std::memory_order_release); -+ // Openings still queued for the main thread are obsolete: they apply as closings. -+ for (auto it = m_history.upper_bound(Applied()); it != m_history.end(); ++it) -+ it->second = false; -+ generation = ++m_requested; -+ // Never allocates: a reserved node, or the oldest entry once the history is full or the reserve ran out (more -+ // than SpareNodes latches in a row). A forgotten generation reports as superseded, which an old one is anyway. -+ std::map::node_type node; -+ if (m_history.size() < MaxHistory && !m_spares.empty()) -+ { -+ node = std::move(m_spares.back()); -+ m_spares.pop_back(); -+ } -+ else if (!m_history.empty()) -+ node = m_history.extract(m_history.begin()); -+ // Without a node the generation goes unrecorded, and Publish takes the closed state from m_open. -+ if (node) -+ { -+ node.key() = generation; -+ node.mapped() = false; -+ m_history.insert(std::move(node)); -+ } + } -+ // Published at once, so the updaters send zeros without waiting for the main thread. -+ Publish(generation); -+ return generation; ++ return (word >> 1) + 1; +} + -+void OutputGate::Publish(int64_t generation) ++void OutputGate::FinishLatch(int64_t generation) +{ -+ bool open; ++ // The earliest latch generation of the session, whichever latch gets here first. Only latch generations are decided ++ // by it: requested ones carry their state in the history. Until it is installed, the latch's generation is not ++ // published either, so it reports as not applied. ++ int64_t current = m_latchGeneration.load(std::memory_order_acquire); ++ while ((current == 0 || current > generation) ++ && !m_latchGeneration.compare_exchange_weak(current, generation, std::memory_order_acq_rel, std::memory_order_acquire)) + { -+ std::lock_guard lock(m_mutex); -+ auto it = m_history.find(generation); -+ open = it != m_history.end() ? it->second : m_open.load(std::memory_order_acquire); + } ++ // Published at once, so the updaters send zeros without waiting for the main thread. ++ RaisePublished(generation, false); ++} ++ ++int64_t OutputGate::Latch() ++{ ++ // No lock: a fault handler may run while another thread holds the gate's mutex. The history is not touched; the ++ // latch generation tells which generations are closings (StateOf), and an opening that the main thread applies after ++ // this is not published as an opening. ++ int64_t generation = BeginLatch(); ++ FinishLatch(generation); ++ return generation; ++} ++ ++bool OutputGate::RaisePublished(int64_t generation, bool open) ++{ + int64_t current = m_published.load(std::memory_order_relaxed); + int64_t word = Pack(generation, open); -+ while ((current >> 1) < generation && !m_published.compare_exchange_weak(current, word, std::memory_order_release, std::memory_order_relaxed)) ++ while ((current >> 1) < generation) + { ++ if (m_published.compare_exchange_weak(current, word, std::memory_order_release, std::memory_order_relaxed)) ++ return true; + } ++ return false; ++} ++ ++void OutputGate::Publish(int64_t generation) ++{ ++ std::lock_guard lock(m_mutex); ++ auto it = m_history.find(generation); ++ bool requested = it != m_history.end() ? it->second.open : m_open.load(std::memory_order_acquire); ++ bool open = requested && !m_latched.load(std::memory_order_acquire); ++ // Only a generation that became the published one with the state it asked for counts as published: an opening a ++ // latch turned into a closing, or one a latch overtook, never reached a unit as an opening. ++ if (RaisePublished(generation, open) && it != m_history.end() && open == requested) ++ it->second.published = true; ++} ++ ++bool OutputGate::StateOf(int64_t generation, bool& open) const ++{ ++ int64_t latchGeneration = m_latchGeneration.load(std::memory_order_acquire); ++ if (latchGeneration > 0 && generation >= latchGeneration) ++ { ++ open = false; ++ return true; ++ } ++ auto it = m_history.find(generation); ++ if (it == m_history.end()) ++ return false; ++ open = it->second.open; ++ return true; +} + +bool OutputGate::IsSuperseded(int64_t generation, bool open, int64_t applied) const +{ ++ // An opening the latch overtook. ++ int64_t latchGeneration = m_latchGeneration.load(std::memory_order_acquire); ++ if (open && latchGeneration > generation && latchGeneration <= applied) ++ return true; ++ // Only changes that were published supersede: one that never reached a unit changed nothing. + for (auto it = m_history.upper_bound(generation); it != m_history.end() && it->first <= applied; ++it) + { -+ if (it->second != open) ++ bool state; ++ if (it->second.published && StateOf(it->first, state) && state != open) + return true; + } + return false; +} + -+bool OutputGate::IsConfirmed(const Unit& unit, int64_t generation, bool open) const ++OutputGate::UnitState OutputGate::Classify(const Unit& unit, int64_t generation, bool open, bool known) const +{ ++ // An updater that ended on its own delivers nothing any more, whatever it confirmed before. ++ if (unit.m_dead.load(std::memory_order_acquire)) ++ return UnitState::Failed; + // A later generation of the same state confirms this one too: the hardware has that state. -+ return (open ? unit.m_ackedOpen : unit.m_ackedClosed).load(std::memory_order_acquire) >= generation; ++ if (known && (open ? unit.m_ackedOpen : unit.m_ackedClosed).load(std::memory_order_acquire) >= generation) ++ return UnitState::Confirmed; ++ if (unit.m_failed.load(std::memory_order_acquire) >= generation) ++ return UnitState::Failed; ++ if (known && open && unit.m_untouched.load(std::memory_order_acquire) >= generation) ++ return UnitState::Untouched; ++ // Finished cleanly: what it confirmed or left alone stays so, and it delivers nothing later. ++ if (unit.m_stopped.load(std::memory_order_acquire)) ++ return UnitState::Failed; ++ return UnitState::Pending; +} + -+OutputGate::Status OutputGate::GetState(int64_t generation, int& confirmed, int& pending, int& failed) const ++OutputGate::Status OutputGate::GetState(int64_t generation, Counts& counts) const +{ -+ confirmed = pending = failed = 0; ++ counts = Counts(); + std::lock_guard lock(m_mutex); + int64_t applied = Applied(); -+ auto it = m_history.find(generation); -+ if (it == m_history.end()) -+ // Never requested, or forgotten long ago. -+ return generation > applied ? Status::NotApplied : Status::Superseded; -+ bool open = it->second; ++ bool open = false; ++ bool recorded = StateOf(generation, open); ++ bool known = recorded && generation <= applied; + for (const auto& unit : m_units) + { + if (unit->m_session != m_session) + continue; -+ if (IsConfirmed(*unit, generation, open)) -+ confirmed++; -+ else if (unit->m_stopped.load(std::memory_order_acquire) || unit->m_failed.load(std::memory_order_acquire) >= generation) -+ failed++; -+ else -+ pending++; ++ switch (Classify(*unit, generation, open, known)) ++ { ++ case UnitState::Confirmed: counts.confirmed++; break; ++ case UnitState::Failed: counts.failed++; break; ++ case UnitState::Untouched: counts.untouched++; break; ++ default: counts.pending++; break; ++ } + } -+ if (generation > applied) ++ if (!recorded) ++ // Never requested, or forgotten long ago. ++ return generation > applied ? Status::NotApplied : Status::Superseded; ++ if (!known) + return Status::NotApplied; -+ return IsSuperseded(generation, open, applied) && pending + failed > 0 ? Status::Superseded : Status::Applied; ++ return IsSuperseded(generation, open, applied) ? Status::Superseded : Status::Applied; +} + +std::vector OutputGate::GetPending(int64_t generation) const +{ + std::vector names; + std::lock_guard lock(m_mutex); -+ auto it = m_history.find(generation); ++ int64_t applied = Applied(); ++ bool open = false; ++ bool known = StateOf(generation, open) && generation <= applied; + for (const auto& unit : m_units) + { + if (unit->m_session != m_session) + continue; -+ if (it == m_history.end() || !IsConfirmed(*unit, generation, it->second)) ++ UnitState state = Classify(*unit, generation, open, known); ++ if (state == UnitState::Pending || state == UnitState::Failed) + names.push_back(unit->m_name); + } + return names; @@ -1074,10 +1126,10 @@ index 0000000..824f940 +} diff --git a/src/cab/out/OutputGate.h b/src/cab/out/OutputGate.h new file mode 100644 -index 0000000..672ad8f +index 0000000..b7480e3 --- /dev/null +++ b/src/cab/out/OutputGate.h -@@ -0,0 +1,139 @@ +@@ -0,0 +1,188 @@ +#pragma once + +#include @@ -1113,23 +1165,39 @@ index 0000000..672ad8f + // The generation was not applied by DOF's main thread yet. + NotApplied, + Applied, -+ // A later generation set the other state while some unit had not confirmed this one. Only the latest -+ // generation's state tells what the outputs show; an older one can later count as confirmed by every unit. ++ // A later generation that was published set the other state, or the generation is an opening that a latch ++ // overtook (requested before the latch, applied after it), which never reaches a unit as an opening. This does not ++ // change any more: only the latest generation's state tells what the outputs show. + Superseded, + }; + ++ struct Counts ++ { ++ // Units whose hardware got the state (or a later generation of the same state). ++ int confirmed = 0; ++ int pending = 0; ++ // The device is missing, a write failed, or the updater ended on its own. A unit that finished cleanly keeps what ++ // it confirmed or left alone, and fails later generations. ++ int failed = 0; ++ // Units DOF never used, left alone while the gate is open: nothing was written to them. ++ int untouched = 0; ++ }; ++ + class Unit + { + public: + // Called by the unit's updater before it copies the values it sends. + Snapshot Observe() const; -+ // Whether the hardware already got the state of `snapshot`; until then the updater transfers every output. ++ // Whether the hardware already got the state of `snapshot`, or the gate is open at a unit DOF leaves alone; until ++ // then the updater transfers every output. + bool IsAcked(const Snapshot& snapshot) const; + // A transfer to the hardware carried the state of `snapshot`. + void Ack(const Snapshot& snapshot); ++ // The gate is open at `snapshot` and DOF never used the unit, so nothing was written to its hardware. ++ void Untouched(const Snapshot& snapshot); + // The unit could not deliver `generation` (no device, failed write). + void Fail(int64_t generation); -+ // The unit's updater ended without being asked to: it fails every later generation. ++ // The unit's updater ended without being asked to: it fails every generation, also those it confirmed before. + void Die(); + // The unit was finished: it delivers nothing any more. What it confirmed stays confirmed. + void Stop(); @@ -1140,14 +1208,17 @@ index 0000000..672ad8f + uint64_t m_session = 0; + std::atomic m_ackedClosed { 0 }; + std::atomic m_ackedOpen { 0 }; ++ std::atomic m_untouched { 0 }; + std::atomic m_failed { 0 }; ++ std::atomic m_dead { false }; + std::atomic m_stopped { false }; + }; + + static OutputGate& Instance(); + -+ // The state outputs report. It changes before the generation that set it is published. -+ bool IsOpen() const { return m_open.load(std::memory_order_acquire); } ++ // The state outputs report. It changes before the generation that set it is published. The latch decides on its own, ++ // so an Apply that raced it cannot report the gate open again. ++ bool IsOpen() const { return !m_latched.load(std::memory_order_acquire) && m_open.load(std::memory_order_acquire); } + // Whether a controller may run its connect test sequence (TestOnConnect): only while the gate is open, and never in a + // session that turned them off, such as a port test, where a controller that connects late or reconnects would light + // its whole strip. @@ -1156,7 +1227,7 @@ index 0000000..672ad8f + void SetConnectTests(bool allowed) { m_connectTests.store(allowed, std::memory_order_release); } + Snapshot Current() const; + -+ // Starts a new session: opens the gate and forgets the units of the previous one. ++ // Starts a new session: opens the gate and forgets the units and generations of the previous one. + void BeginSession(); + // Registers an output controller unit of the current session, before its updater starts. The returned unit lives + // until the process ends. @@ -1164,56 +1235,86 @@ index 0000000..672ad8f + // Registers a configured unit that cannot deliver anything, such as a device that is not connected. + void RegisterFailed(const std::string& name); + -+ // Reserves the generation of a change to `open`. Once latched, every change is a closing. ++ // Reserves the generation of a change to `open` and records the requested state. Generations from the session's ++ // first latch on are closings. + int64_t Request(bool open); + // On DOF's main thread, in the order of the generations: sets the state outputs report and returns it, closed once + // latched. The caller re-raises the output values, then publishes the generation. + bool Apply(bool open); + // Any thread, at once: closes the gate for the rest of the session and publishes the closing, which every unit's -+ // updater sends within its polling interval, without DOF's main thread. Openings requested and not applied yet, and -+ // every later one, apply as closings, and their generations report the closed state. Returns the closing's -+ // generation. It never allocates: the closing's history entry is a node reserved by the other calls or, once they -+ // ran out, the oldest entry's. ++ // updater sends within its polling interval, without DOF's main thread. Openings with an earlier generation that ++ // were not applied yet are never published as openings and report as superseded; every later change applies as a ++ // closing and reports the closed state. When latches race, the earliest generation is the session's latch, whatever ++ // order the threads finish in. Returns the closing's generation. It takes no lock and never allocates. + int64_t Latch(); + bool IsLatched() const { return m_latched.load(std::memory_order_acquire); } + void Publish(int64_t generation); + int64_t Applied() const { return Current().generation; } + -+ Status GetState(int64_t generation, int& confirmed, int& pending, int& failed) const; -+ // The units that did not confirm `generation`, failed ones included. ++ Status GetState(int64_t generation, Counts& counts) const; ++ // The units GetState counts as pending or failed for `generation`. + std::vector GetPending(int64_t generation) const; + +private: -+ OutputGate() { m_spares.reserve(SpareNodes); } ++ friend class OutputGateTestAccess; ++ ++ enum class UnitState ++ { ++ Confirmed, ++ Pending, ++ Failed, ++ Untouched, ++ }; ++ ++ struct Entry ++ { ++ bool open; ++ // Whether the generation became the published one. One that a latch overtook never does. ++ bool published; ++ }; ++ ++ OutputGate() = default; + + static int64_t Pack(int64_t generation, bool open) { return (generation << 1) | (open ? 1 : 0); } + ++ // The two halves of Latch: closes at once and reserves the generation with the latch flag, then installs and ++ // publishes it. ++ int64_t BeginLatch(); ++ void FinishLatch(int64_t generation); ++ // Takes the next generation; `latched`: a latch took one before. ++ int64_t Reserve(bool& latched); ++ + // Called with m_mutex held. ++ bool StateOf(int64_t generation, bool& open) const; ++ // What `unit` reports for `generation`, for both the counts and the names. `known`: the generation was applied and ++ // its state is `open`. ++ UnitState Classify(const Unit& unit, int64_t generation, bool open, bool known) const; + bool IsSuperseded(int64_t generation, bool open, int64_t applied) const; -+ bool IsConfirmed(const Unit& unit, int64_t generation, bool open) const; ++ // Records the state of a generation and forgets the oldest ones. ++ void Record(int64_t generation, bool open, bool published); ++ // Publishes `generation` unless a later one was published already. Lock-free. ++ bool RaisePublished(int64_t generation, bool open); + + std::atomic m_open { true }; + std::atomic m_connectTests { true }; -+ // Written with m_mutex held. + std::atomic m_latched { false }; ++ // The earliest latch generation of the session, 0 before it: it and every later generation are closings. ++ std::atomic m_latchGeneration { 0 }; + // The last published generation and its state: (generation << 1) | open. + std::atomic m_published { Pack(0, true) }; -+ int64_t m_requested = 0; ++ // The last generation taken, and whether a latch took one in this session: (generation << 1) | latched. ++ std::atomic m_requested { 0 }; + uint64_t m_session = 0; + mutable std::mutex m_mutex; + // The state each generation set, the latest ones only. -+ std::map m_history; -+ // History nodes reserved for Latch, which must not allocate. Refilled, with m_mutex held, by the other calls. -+ std::vector::node_type> m_spares; ++ std::map m_history; + std::vector> m_units; + std::vector> m_retired; + + static constexpr size_t MaxHistory = 4096; -+ static constexpr size_t SpareNodes = 8; + -+ // Called with m_mutex held. Records the state of a generation and forgets the oldest ones. -+ void Record(int64_t generation, bool open); -+ void Reserve(); ++ static_assert(std::atomic::is_always_lock_free); ++ static_assert(std::atomic::is_always_lock_free); +}; + +} @@ -1322,7 +1423,7 @@ index e112579..175fad3 100644 } \ No newline at end of file diff --git a/src/cab/out/adressableledstrip/UMXController.cpp b/src/cab/out/adressableledstrip/UMXController.cpp -index d460fbd..4c70be3 100644 +index d460fbd..a0ef66d 100644 --- a/src/cab/out/adressableledstrip/UMXController.cpp +++ b/src/cab/out/adressableledstrip/UMXController.cpp @@ -1,4 +1,5 @@ @@ -1331,48 +1432,228 @@ index d460fbd..4c70be3 100644 #include "UMXControllerAutoConfigurator.h" #include "../../Cabinet.h" #include "../OutputControllerList.h" -@@ -76,14 +77,17 @@ void UMXController::UpdateOutputs(const std::vector& outputValues) +@@ -47,7 +48,18 @@ int UMXController::GetNumberOfConfiguredOutputs() { return m_dev ? m_dev->NumOut + + void UMXController::ConnectToController() + { +- DisconnectFromController(); ++ // A unit that cannot be turned off before the reconnect is still reconnected. ++ try ++ { ++ DisconnectFromController(); ++ } ++ catch (const std::exception& e) ++ { ++ Log::Warning(StringExtensions::Build("UMX controller {0} could not turn its outputs off before connecting: {1}", GetName(), e.what())); ++ } ++ // VPE: a device that cannot come back ends the updater instead of failing on every pass. ++ if (m_dev && m_dev->IsLost()) ++ throw std::runtime_error(StringExtensions::Build("UMX controller {0} lost its device", GetName())); + if (m_dev) + m_dev->ResetDataLines(); + } +@@ -55,7 +67,11 @@ void UMXController::ConnectToController() + void UMXController::DisconnectFromController() + { + if (m_inUseState == InUseState::Running && m_dev) ++ { + m_dev->SendCommand(UMXDevice::UMXCommand::UMX_AllOff); ++ // VPE: SendCommand throws when the command did not get to the device, so the outputs are off now. ++ m_disconnectSentZeros = true; ++ } + } + + bool UMXController::VerifySettings() +@@ -74,17 +90,32 @@ void UMXController::UpdateOutputs(const std::vector& outputValues) + auto now = std::chrono::steady_clock::now(); + int delay = m_lastTimeInit ? static_cast(std::chrono::duration_cast(now - m_lastTime).count()) : 0; - if (!m_lastTimeInit || delay >= m_longestDataLineDelayMs) +- if (!m_lastTimeInit || delay >= m_longestDataLineDelayMs) ++ if (m_lastTimeInit && delay < m_longestDataLineDelayMs) { - if (m_dev) - m_dev->UpdateOutputs(outputValues); -+ if (!m_dev) -+ throw std::runtime_error(StringExtensions::Build("UMX controller {0} has no device", GetName())); -+ m_dev->UpdateOutputs(outputValues, m_forceFullTransfer); - m_lastTime = std::chrono::steady_clock::now(); - m_lastTimeInit = true; +- m_lastTime = std::chrono::steady_clock::now(); +- m_lastTimeInit = true; ++ std::this_thread::sleep_for(std::chrono::milliseconds(m_longestDataLineDelayMs - delay)); ++ // VPE: nothing was sent; the updater sends again after this wait. A full transfer (the final all-off among them) ++ // is sent once the wait is over instead. ++ if (!m_forceFullTransfer) ++ { ++ m_transferSkipped = true; ++ return; ++ } } - else +- else ++ ++ if (!m_dev) ++ throw std::runtime_error(StringExtensions::Build("UMX controller {0} has no device", GetName())); ++ // VPE: values copied before a latch that came during the wait, or while the frame was built, are not sent: the ++ // transfer stays unconfirmed, and the updater sends the closing in full next. ++ auto stale = [&outputValues]() { ++ return OutputGate::Instance().IsLatched() && std::any_of(outputValues.begin(), outputValues.end(), [](uint8_t value) { return value != 0; }); ++ }; ++ if (stale() || !m_dev->UpdateOutputs(outputValues, m_forceFullTransfer, stale)) { -+ // VPE: nothing was sent; the updater sends again after this wait. - std::this_thread::sleep_for(std::chrono::milliseconds(m_longestDataLineDelayMs - delay)); +- std::this_thread::sleep_for(std::chrono::milliseconds(m_longestDataLineDelayMs - delay)); + m_transferSkipped = true; ++ return; } ++ m_lastTime = std::chrono::steady_clock::now(); ++ m_lastTimeInit = true; } -@@ -212,7 +216,7 @@ void UMXController::UpdateCabinetFromConfig(Cabinet* cabinet) - } + void UMXController::UpdateCabinetFromConfig(Cabinet* cabinet) +@@ -106,6 +137,26 @@ void UMXController::UpdateCabinetFromConfig(Cabinet* cabinet) + return; } -- if (m_dev->m_testOnConnect != UMXDevice::TestMode::None) ++ // VPE: the connect test runs before the controller is added. A device lost by a failed test write is not added (the ++ // auto-configurator lets it go); after another failure the controller is added and its next write opens it again. + if (m_dev->m_testOnConnect != UMXDevice::TestMode::None && OutputGate::Instance().AllowsConnectTests()) ++ { ++ std::vector parameters = { ++ static_cast(m_dev->m_testOnConnect), ++ m_dev->m_testOnConnectDuration, ++ }; ++ try ++ { ++ m_dev->SendCommand(UMXDevice::UMXCommand::UMX_StartTest, parameters); ++ } ++ catch (const std::exception& e) ++ { ++ if (m_dev->IsLost()) ++ throw; ++ Log::Warning(StringExtensions::Build("UMX controller {0} could not start its connect test: {1}", GetName(), e.what())); ++ } ++ } ++ + Log::Write(StringExtensions::Build("Detected and added UMX Controller Nr. {0} with name {1}", std::to_string(m_number), GetName())); + cabinet->GetOutputControllers()->push_back(this); + +@@ -211,15 +262,6 @@ void UMXController::UpdateCabinetFromConfig(Cabinet* cabinet) + lwe->GetOutputs().AddOutput(lweo); + } + } +- +- if (m_dev->m_testOnConnect != UMXDevice::TestMode::None) +- { +- std::vector parameters = { +- static_cast(m_dev->m_testOnConnect), +- m_dev->m_testOnConnectDuration, +- }; +- m_dev->SendCommand(UMXDevice::UMXCommand::UMX_StartTest, parameters); +- } + } + + tinyxml2::XMLElement* UMXController::ToXml(tinyxml2::XMLDocument& doc) const +diff --git a/src/cab/out/adressableledstrip/UMXControllerAutoConfigurator.cpp b/src/cab/out/adressableledstrip/UMXControllerAutoConfigurator.cpp +index 6ae1dfa..6e37c51 100644 +--- a/src/cab/out/adressableledstrip/UMXControllerAutoConfigurator.cpp ++++ b/src/cab/out/adressableledstrip/UMXControllerAutoConfigurator.cpp +@@ -4,10 +4,41 @@ + #include "../OutputControllerList.h" + #include "../../../Log.h" + #include "../../../general/StringExtensions.h" ++#include + + namespace DOF + { + ++namespace ++{ ++ ++// VPE: adds a controller for `device`. A device whose configuration cannot be read (an MX handshake that times out, a ++// connect test that lost the device) is skipped, so the other devices and the later auto-configurators still run: its ++// controller is deleted unless the cabinet holds it already, and the device is let go. Returns false then. ++bool AddController(Cabinet* cabinet, UMXDevice* device) ++{ ++ UMXController* umxC = new UMXController(); ++ try ++ { ++ umxC->SetNumber(device->UnitNo()); ++ umxC->UpdateCabinetFromConfig(cabinet); ++ } ++ catch (const std::exception& e) ++ { ++ Log::Exception(StringExtensions::Build("UMX device {0} could not be configured and is skipped: {1}", device->m_name, e.what())); ++ OutputControllerList* controllers = cabinet->GetOutputControllers(); ++ if (std::find(controllers->begin(), controllers->end(), umxC) == controllers->end()) ++ { ++ delete umxC; ++ device->Release(); ++ return false; ++ } ++ } ++ return true; ++} ++ ++} ++ + std::vector UMXControllerAutoConfigurator::s_devices; + bool UMXControllerAutoConfigurator::s_inited = false; + Cabinet* UMXControllerAutoConfigurator::s_cabinet = nullptr; +@@ -27,11 +58,8 @@ void UMXControllerAutoConfigurator::AddUMXDevice(UMXDevice* dev) + { + if (s_inited && s_cabinet != nullptr) + { +- UMXController* umxC = new UMXController(); +- umxC->SetNumber(dev->UnitNo()); +- Log::Instrumentation( +- "UMX", StringExtensions::Build("Adding new device {0} & controller {1} to cabinet after UMXControllerAutoConfigurator initialization", dev->m_name, umxC->GetName())); +- umxC->UpdateCabinetFromConfig(s_cabinet); ++ Log::Instrumentation("UMX", StringExtensions::Build("Adding new device {0} to cabinet after UMXControllerAutoConfigurator initialization", dev->m_name)); ++ AddController(s_cabinet, dev); + } + } + catch (const std::exception& e) +@@ -70,8 +98,9 @@ void UMXControllerAutoConfigurator::AutoConfig(Cabinet* cabinet) + preconfigured.push_back(umxC->GetNumber()); + } + +- for (auto* device : s_devices) ++ for (auto deviceIt = s_devices.begin(); deviceIt != s_devices.end();) { - std::vector parameters = { - static_cast(m_dev->m_testOnConnect), ++ UMXDevice* device = *deviceIt; + bool found = false; + for (int num : preconfigured) + { +@@ -82,12 +111,14 @@ void UMXControllerAutoConfigurator::AutoConfig(Cabinet* cabinet) + } + } + +- if (!found) ++ // VPE: a device that was let go leaves the list, so the next session does not ask its closed handle again. ++ if (!found && !AddController(cabinet, device)) + { +- UMXController* umxC = new UMXController(); +- umxC->SetNumber(device->UnitNo()); +- umxC->UpdateCabinetFromConfig(cabinet); ++ deviceIt = s_devices.erase(deviceIt); ++ delete device; ++ continue; + } ++ ++deviceIt; + } + + s_inited = true; diff --git a/src/cab/out/adressableledstrip/UMXDevice.cpp b/src/cab/out/adressableledstrip/UMXDevice.cpp -index dc50fe2..fafcf27 100644 +index dc50fe2..4626a8e 100644 --- a/src/cab/out/adressableledstrip/UMXDevice.cpp +++ b/src/cab/out/adressableledstrip/UMXDevice.cpp -@@ -83,7 +83,7 @@ void UMXDevice::ResetDataLines() +@@ -83,10 +83,10 @@ void UMXDevice::ResetDataLines() line.m_oldValues.assign(line.m_nbValues, 255); } -void UMXDevice::UpdateOutputs(const std::vector& outputValues) -+void UMXDevice::UpdateOutputs(const std::vector& outputValues, bool full) ++bool UMXDevice::UpdateOutputs(const std::vector& outputValues, bool full, const std::function& cancel) { if (!m_enabled) - return; +- return; ++ return true; + + for (auto& line : m_dataLines) + { @@ -115,7 +115,7 @@ void UMXDevice::UpdateOutputs(const std::vector& outputValues) auto& line = m_dataLines[numLine]; if (line.m_nbLeds > 0) @@ -1390,8 +1671,14 @@ index dc50fe2..fafcf27 100644 } } } -@@ -153,6 +152,12 @@ void UMXDevice::UpdateOutputs(const std::vector& outputValues) - SendCommand(UMXCommand::UMX_SendStripsData, buffer); +@@ -150,9 +149,18 @@ void UMXDevice::UpdateOutputs(const std::vector& outputValues) + { + std::vector buffer = { nbChangedLines }; + buffer.insert(buffer.end(), sendBuffer.begin(), sendBuffer.end()); +- SendCommand(UMXCommand::UMX_SendStripsData, buffer); ++ // VPE: the device asks `cancel` before each of its writes, so a latch holds back the rest of the frame. ++ if (!SendCommand(UMXCommand::UMX_SendStripsData, buffer, cancel)) ++ return false; WaitAck(static_cast(UMXCommand::UMX_SendStripsData)); } + // VPE: the lines remember what the device got, after it got it (SendCommand throws otherwise). @@ -1400,25 +1687,51 @@ index dc50fe2..fafcf27 100644 + if (line.m_nbLeds > 0) + line.m_oldValues = line.m_values; + } ++ return true; } std::vector UMXDevice::CompressDataLineValues(const std::vector& values) diff --git a/src/cab/out/adressableledstrip/UMXDevice.h b/src/cab/out/adressableledstrip/UMXDevice.h -index 81af672..51be088 100644 +index 81af672..47a30ac 100644 --- a/src/cab/out/adressableledstrip/UMXDevice.h +++ b/src/cab/out/adressableledstrip/UMXDevice.h -@@ -97,7 +97,8 @@ public: +@@ -3,6 +3,7 @@ + #include + #include + #include ++#include + #include "../../toys/layer/RGBOrderEnum.h" + #include "../../toys/layer/StripArrangementEnum.h" + #include "../../../general/Curve.h" +@@ -97,11 +98,25 @@ public: void ComputeNumOutputs(); void CreateDataLines(); void ResetDataLines(); - void UpdateOutputs(const std::vector& outputValues); + // VPE: `full` sends every data line, whatever was sent before. Throws if the device did not get the data. -+ void UpdateOutputs(const std::vector& outputValues, bool full = false); ++ // Returns false if `cancel` said so before the data was all out; the device may then have part of the frame. ++ bool UpdateOutputs(const std::vector& outputValues, bool full = false, const std::function& cancel = nullptr); virtual void Initialize() = 0; virtual void SendCommand(UMXCommand command, const std::vector& parameters = { }) = 0; ++ // VPE: SendCommand that asks `cancel` before each write to the device and stops when it says so; returns false then. ++ virtual bool SendCommand(UMXCommand command, const std::vector& parameters, const std::function& cancel) ++ { ++ if (cancel && cancel()) ++ return false; ++ SendCommand(command, parameters); ++ return true; ++ } + virtual void WaitAck(uint8_t command) = 0; ++ // VPE: whether the device failed and cannot be opened again during the session. ++ virtual bool IsLost() const { return false; } ++ // VPE: lets go of a device no controller uses, such as one whose configuration could not be read. ++ virtual void Release() { } + + std::vector m_ledStrips; + std::vector m_dataLines; diff --git a/src/cab/out/adressableledstrip/WemosD1StripController.cpp b/src/cab/out/adressableledstrip/WemosD1StripController.cpp -index 1832b60..417b43c 100644 +index 1832b60..a3d04f4 100644 --- a/src/cab/out/adressableledstrip/WemosD1StripController.cpp +++ b/src/cab/out/adressableledstrip/WemosD1StripController.cpp @@ -1,4 +1,5 @@ @@ -1504,7 +1817,7 @@ index d76a7d8..1bebe23 100644 virtual void DisconnectFromController() override; diff --git a/src/cab/out/dmx/ArtNet.cpp b/src/cab/out/dmx/ArtNet.cpp -index ba74e6e..bdfc821 100644 +index 44d0e43..ad4faf3 100644 --- a/src/cab/out/dmx/ArtNet.cpp +++ b/src/cab/out/dmx/ArtNet.cpp @@ -28,7 +28,8 @@ void ArtNet::UpdateOutputs(const std::vector& outputValues) @@ -1517,48 +1830,51 @@ index ba74e6e..bdfc821 100644 } else { -@@ -61,6 +62,8 @@ void ArtNet::ConnectToController() - try - { - m_engine = Engine::GetInstance(); -+ if (!m_engine->Reopen()) -+ throw std::runtime_error("the Art-Net socket could not be opened"); - std::vector zeroData(DMX_CHANNELS, 0); - m_engine->SendDMX(m_broadcastAddress, m_universe, zeroData, DMX_CHANNELS); - } -diff --git a/src/cab/out/dmx/artnetengine/Engine.cpp b/src/cab/out/dmx/artnetengine/Engine.cpp -index c390c73..79733ce 100644 ---- a/src/cab/out/dmx/artnetengine/Engine.cpp -+++ b/src/cab/out/dmx/artnetengine/Engine.cpp -@@ -63,6 +63,8 @@ Engine::~Engine() - bool Engine::InitializeSocket() - { - std::lock_guard lock(m_udpMutex); -+ if (m_socketInitialized && m_socket >= 0) -+ return true; +@@ -79,21 +80,17 @@ void ArtNet::ConnectToController() - try + void ArtNet::DisconnectFromController() + { +- try +- { +- if (m_engine != nullptr) +- { +- std::vector zeroData(DMX_CHANNELS, 0); +- m_engine->SendDMX(m_broadcastAddress, m_universe, zeroData, DMX_CHANNELS); +- } +- } +- catch (...) +- { +- } +- +- if (m_engine != nullptr) ++ // VPE: a blackout that did not go out is reported. For a controller DOF never used, it is the only one sent at the ++ // end of the session. ++ Engine* engine = m_engine; ++ m_engine = nullptr; ++ if (engine != nullptr) { -@@ -129,16 +131,25 @@ void Engine::CloseSocket() +- m_engine = nullptr; ++ std::vector zeroData(DMX_CHANNELS, 0); ++ if (!engine->SendDMX(m_broadcastAddress, m_universe, zeroData, DMX_CHANNELS)) ++ throw std::runtime_error(StringExtensions::Build( ++ "{0} {1} (Universe: {2}, Broadcast Address: {3}) could not send its blackout", { GetXmlElementName(), GetName(), std::to_string(m_universe), m_broadcastAddress })); ++ m_disconnectSentZeros = true; } } -+bool Engine::Reopen() -+{ -+ { -+ std::lock_guard lock(m_udpMutex); -+ m_sendExceptionCount = 0; -+ } -+ return InitializeSocket(); -+} -+ - uint8_t Engine::LoByte(int value) const { return static_cast(value & 0xFF); } +diff --git a/src/cab/out/dmx/artnetengine/Engine.cpp b/src/cab/out/dmx/artnetengine/Engine.cpp +index d95af44..302baa3 100644 +--- a/src/cab/out/dmx/artnetengine/Engine.cpp ++++ b/src/cab/out/dmx/artnetengine/Engine.cpp +@@ -141,14 +141,14 @@ uint8_t Engine::LoByte(int value) const { return static_cast(value & 0x uint8_t Engine::HiByte(int value) const { return static_cast((value >> 8) & 0xFF); } -void Engine::SendDMX(const std::string& broadcastAddress, short universe, const std::vector& data, int dataLength) +bool Engine::SendDMX(const std::string& broadcastAddress, short universe, const std::vector& data, int dataLength) { + std::lock_guard lock(m_udpMutex); + if (!m_socketInitialized || m_socket < 0) { Log::Exception("ArtNet engine socket not initialized"); @@ -1567,7 +1883,7 @@ index c390c73..79733ce 100644 } std::vector packet(0x12 + dataLength); -@@ -167,7 +178,7 @@ void Engine::SendDMX(const std::string& broadcastAddress, short universe, const +@@ -177,7 +177,7 @@ void Engine::SendDMX(const std::string& broadcastAddress, short universe, const catch (const std::exception& e) { Log::Exception(StringExtensions::Build("Exception occurred copying DMX data in ArtNet Engine: {0}", e.what())); @@ -1575,8 +1891,8 @@ index c390c73..79733ce 100644 + return false; } - std::lock_guard lock(m_udpMutex); -@@ -190,7 +201,7 @@ void Engine::SendDMX(const std::string& broadcastAddress, short universe, const + if (m_socketInitialized && m_socket >= 0) +@@ -198,7 +198,7 @@ void Engine::SendDMX(const std::string& broadcastAddress, short universe, const if (inet_pton(AF_INET, broadcastAddress.c_str(), &addr.sin_addr) <= 0) { Log::Exception(StringExtensions::Build("Invalid broadcast address for ArtNet: {0}", broadcastAddress)); @@ -1585,7 +1901,7 @@ index c390c73..79733ce 100644 } } -@@ -212,6 +223,7 @@ void Engine::SendDMX(const std::string& broadcastAddress, short universe, const +@@ -220,6 +220,7 @@ void Engine::SendDMX(const std::string& broadcastAddress, short universe, const } m_sendExceptionCount = 0; @@ -1593,7 +1909,7 @@ index c390c73..79733ce 100644 } catch (const std::exception& e) { -@@ -229,6 +241,7 @@ void Engine::SendDMX(const std::string& broadcastAddress, short universe, const +@@ -237,6 +238,7 @@ void Engine::SendDMX(const std::string& broadcastAddress, short universe, const } } } @@ -1603,26 +1919,33 @@ index c390c73..79733ce 100644 } \ No newline at end of file diff --git a/src/cab/out/dmx/artnetengine/Engine.h b/src/cab/out/dmx/artnetengine/Engine.h -index 8c01721..a3bae1a 100644 +index 84b1c02..006cb28 100644 --- a/src/cab/out/dmx/artnetengine/Engine.h +++ b/src/cab/out/dmx/artnetengine/Engine.h -@@ -13,7 +13,10 @@ class Engine +@@ -13,7 +13,8 @@ class Engine public: static Engine* GetInstance(); - void SendDMX(const std::string& broadcastAddress, short universe, const std::vector& data, int dataLength); -+ // Returns false if the packet was not sent. ++ // VPE: returns false if the packet was not sent. + bool SendDMX(const std::string& broadcastAddress, short universe, const std::vector& data, int dataLength); -+ // VPE: the engine outlives sessions; reopens the socket a previous session closed after repeated failures. -+ bool Reopen(); + bool Reopen(); private: - Engine(); diff --git a/src/cab/out/dudescab/DudesCab.cpp b/src/cab/out/dudescab/DudesCab.cpp -index 77e90f9..579936b 100644 +index 77e90f9..d10030d 100644 --- a/src/cab/out/dudescab/DudesCab.cpp +++ b/src/cab/out/dudescab/DudesCab.cpp -@@ -88,16 +88,23 @@ void DudesCab::Init(Cabinet* cabinet) +@@ -25,6 +25,8 @@ namespace DOF + { + + std::vector DudesCab::s_devices; ++std::vector DudesCab::s_mxDevices; ++bool DudesCab::s_discovered = false; + + const DudesCab::Device::Version DudesCab::Device::s_minimalMxVersion(1, 9, 0); + const DudesCab::Device::Version DudesCab::Device::s_newProtocolVersion(1, 9, 0); +@@ -88,16 +90,23 @@ void DudesCab::Init(Cabinet* cabinet) void DudesCab::Finish() { OutputControllerFlexCompleteBase::Finish(); } @@ -1649,7 +1972,7 @@ index 77e90f9..579936b 100644 { m_outputBuffer.clear(); m_outputBuffer.push_back(0); -@@ -110,7 +117,7 @@ void DudesCab::UpdateOutputs(const std::vector& newOutputValues) +@@ -110,7 +119,7 @@ void DudesCab::UpdateOutputs(const std::vector& newOutputValues) for (int numDofOutput = 0; numDofOutput < static_cast(newOutputValues.size()); numDofOutput++) { @@ -1658,7 +1981,7 @@ index 77e90f9..579936b 100644 { uint8_t extNum = static_cast(numDofOutput / m_dev->m_pwmMaxOutputsPerExtension); uint8_t outputNum = static_cast(numDofOutput % m_dev->m_pwmMaxOutputsPerExtension); -@@ -163,8 +170,15 @@ void DudesCab::UpdateOutputs(const std::vector& newOutputValues) +@@ -163,8 +172,15 @@ void DudesCab::UpdateOutputs(const std::vector& newOutputValues) Instrumentation(StringExtensions::Build("{0} Dof Values to send to Dude's cab", std::to_string(nbValuesToSend))); m_dev->SendCommand(Device::HIDReportType::RT_PWM_OUTPUTS, m_outputBuffer); @@ -1674,7 +1997,7 @@ index 77e90f9..579936b 100644 } } -@@ -178,7 +192,28 @@ void DudesCab::UpdateDelay() +@@ -178,21 +194,53 @@ void DudesCab::UpdateDelay() m_lastUpdate = std::chrono::steady_clock::now(); } @@ -1687,32 +2010,154 @@ index 77e90f9..579936b 100644 + auto it = std::find_if(devices.begin(), devices.end(), [this](Device* d) { return d->UnitNo() == m_number; }); + if (it == devices.end()) + return; -+ if ((*it)->LastWriteFailed() && !(*it)->Reopen()) ++ // A blackout that went through on the old handle does not make it usable again: only a reopen does. ++ if ((*it)->NeedsReopen() && !(*it)->Reopen()) + { + m_dev = nullptr; + m_cacheInvalid = true; ++ // A board without a serial number is not opened again during the session: the updater gives up on it instead of ++ // trying again on every pass. ++ if (!(*it)->CanReopen()) ++ throw std::runtime_error(StringExtensions::Build("Dude's Cab {0} has no serial number and cannot be opened again", GetName())); + return; + } -+ if (m_dev != *it) -+ { -+ m_dev = *it; ++ m_dev = *it; ++ // Setting up the outputs again takes their values from the Output objects, which values set in bulk (SetValues) are ++ // not in: a reconnect keeps the requested values. ++ if (GetNumberOfOutputs() != m_dev->NumOutputs()) + SetNumberOfOutputs(m_dev->NumOutputs()); -+ } + m_oldOutputValues.assign(GetNumberOfOutputs(), 0); + m_cacheInvalid = true; +} void DudesCab::DisconnectFromController() { -@@ -186,6 +221,7 @@ void DudesCab::DisconnectFromController() + if (m_inUseState == InUseState::Running && m_dev) { - m_dev->AllOff(); +- m_dev->AllOff(); ++ // VPE: a blackout that got to the board counts as the final update. ++ if (m_dev->AllOff()) ++ m_disconnectSentZeros = true; m_dev = nullptr; + m_cacheInvalid = true; } } -@@ -402,6 +438,81 @@ DudesCab::Device::~Device() + std::vector DudesCab::AllDevices() + { +- if (s_devices.empty()) ++ if (!s_discovered) ++ { + s_devices = FindDevices(); ++ s_discovered = true; ++ } + return s_devices; + } + +@@ -200,13 +248,20 @@ void DudesCab::ClearDevices() + { + for (Device* device : s_devices) + delete device; ++ for (Device* device : s_mxDevices) ++ delete device; + + s_devices.clear(); ++ s_mxDevices.clear(); ++ s_discovered = false; + } + + std::vector DudesCab::FindDevices() + { + UMXControllerAutoConfigurator::RemoveAllUMXDevices(); ++ for (Device* device : s_mxDevices) ++ delete device; ++ s_mxDevices.clear(); + + std::vector dudedevices; + std::vector devices; +@@ -286,21 +341,36 @@ std::vector DudesCab::FindDevices() + + if (!alreadyEnumerated) + { +- Device* newDevice = new Device(deviceRid, cur_dev->path, productName, serialNumber, cur_dev->vendor_id, cur_dev->product_id, cur_dev->release_number); +- dudedevices.push_back(newDevice); +- +- if (deviceRid == Device::RIDType::RIDOutputs) ++ // VPE: a device that does not answer is skipped instead of ending the discovery. ++ Device* newDevice = nullptr; ++ try ++ { ++ newDevice = new Device(deviceRid, cur_dev->path, productName, serialNumber, cur_dev->vendor_id, cur_dev->product_id, cur_dev->release_number); ++ if (deviceRid == Device::RIDType::RIDOutputs) ++ newDevice->ReadPwmOutputsConfig(); ++ } ++ catch (const std::exception& e) + { +- newDevice->ReadPwmOutputsConfig(); +- devices.push_back(newDevice); ++ Log::Exception(StringExtensions::Build("Dude's Cab {0} did not answer and is skipped: {1}", productName, e.what())); ++ delete newDevice; ++ newDevice = nullptr; + } +- else if (deviceRid == Device::RIDType::RIDOutputsMx) ++ ++ if (newDevice) + { +- if (newDevice->SupportMx()) ++ dudedevices.push_back(newDevice); ++ ++ if (deviceRid == Device::RIDType::RIDOutputs) ++ devices.push_back(newDevice); ++ else if (deviceRid == Device::RIDType::RIDOutputsMx) + { +- UMXDudesCabDevice* dudeUMX = new UMXDudesCabDevice(); +- dudeUMX->SetDevice(newDevice); +- UMXControllerAutoConfigurator::AddUMXDevice(dudeUMX); ++ s_mxDevices.push_back(newDevice); ++ if (newDevice->SupportMx()) ++ { ++ UMXDudesCabDevice* dudeUMX = new UMXDudesCabDevice(); ++ dudeUMX->SetDevice(newDevice); ++ UMXControllerAutoConfigurator::AddUMXDevice(dudeUMX); ++ } + } + } + } +@@ -331,8 +401,24 @@ DudesCab::Device::Device(RIDType rid, const std::string& path, const std::string + , m_hidDevice(nullptr) + { + m_hidDevice = hid_open_path(path.c_str()); ++ // VPE: an interface that went away or is not accessible is not a device: discovery skips it. + if (!m_hidDevice) +- return; ++ throw std::runtime_error(StringExtensions::Build("could not open {0}", path)); ++ ++ // VPE: a handshake that throws leaves no destructor to close the handle. ++ struct CloseOnThrow ++ { ++ hid_device*& handle; ++ bool armed; ++ ~CloseOnThrow() ++ { ++ if (armed && handle) ++ { ++ hid_close(handle); ++ handle = nullptr; ++ } ++ } ++ } closeOnThrow { m_hidDevice, true }; + + std::vector answer; + +@@ -394,6 +480,7 @@ DudesCab::Device::Device(RIDType rid, const std::string& path, const std::string + m_configVersion = info[5]; + } + } ++ closeOnThrow.armed = false; + } + + DudesCab::Device::~Device() +@@ -402,6 +489,84 @@ DudesCab::Device::~Device() hid_close(m_hidDevice); } @@ -1745,15 +2190,17 @@ index 77e90f9..579936b 100644 +// chose. Until that interface opens, the device stays failed and has no handle. +bool DudesCab::Device::Reopen() +{ -+ if (m_hidDevice) -+ hid_close(m_hidDevice); -+ m_hidDevice = nullptr; + m_lastWriteFailed = true; -+ ++ m_needsReopen = true; + // Without a serial number nothing tells this board from another one plugged in its place, so it is not reopened -+ // during the session; it stays failed until the next one enumerates the devices again. -+ if (m_serial.empty() || m_serial == "") ++ // during the session; it stays failed until the next one enumerates the devices again. Its handle is kept, so the ++ // blackout at the end of the session can still try it. ++ if (!CanReopen()) + return false; ++ ++ if (m_hidDevice) ++ hid_close(m_hidDevice); ++ m_hidDevice = nullptr; + const char* candidate = nullptr; + struct hid_device_info* devs = hid_enumerate(m_vendorID, m_productID); + for (struct hid_device_info* cur = devs; cur; cur = cur->next) @@ -1788,13 +2235,58 @@ index 77e90f9..579936b 100644 + if (!m_hidDevice) + return false; + m_lastWriteFailed = false; ++ m_needsReopen = false; + return true; +} + std::string DudesCab::Device::ToString() const { return StringExtensions::Build("{0} (name: {1} unit:{2})", m_devicename, m_name, std::to_string(m_unitNo)); } void DudesCab::Device::ReadPwmOutputsConfig() -@@ -528,8 +639,9 @@ bool DudesCab::Device::WriteUSB(const std::vector& data) +@@ -466,7 +631,19 @@ bool DudesCab::Device::HasOutputEnabled(uint8_t extNum, uint8_t outputNum) + + bool DudesCab::Device::SupportMx() { return m_firmwareVersion >= s_minimalMxVersion; } + +-void DudesCab::Device::AllOff() { SendCommand(HIDReportType::RT_PWM_ALLOFF); } ++bool DudesCab::Device::AllOff() ++{ ++ SendCommand(HIDReportType::RT_PWM_ALLOFF); ++ return !m_lastWriteFailed; ++} ++ ++void DudesCab::Device::Close() ++{ ++ if (m_hidDevice) ++ hid_close(m_hidDevice); ++ m_hidDevice = nullptr; ++ m_needsReopen = true; ++} + + std::vector DudesCab::Device::ReadUSB(uint8_t command) + { +@@ -475,7 +652,12 @@ std::vector DudesCab::Device::ReadUSB(uint8_t command) + try + { + while (answer.size() < 2 || answer[1] != remapCommand) ++ { + answer = ReadUSB(); ++ // VPE: a read that timed out returns nothing; without this, a device that does not answer is asked forever. ++ if (answer.empty()) ++ throw std::runtime_error("timed out"); ++ } + } + catch (const std::exception& ex) + { +@@ -488,6 +670,9 @@ std::vector DudesCab::Device::ReadUSB(uint8_t command) + std::vector DudesCab::Device::ReadUSB() + { + std::vector incomingData; ++ // VPE: a device that is not open has nothing to read. ++ if (!m_hidDevice) ++ return incomingData; + uint8_t receivedCommand = 0; + auto startRead = std::chrono::steady_clock::now(); + +@@ -528,8 +713,9 @@ bool DudesCab::Device::WriteUSB(const std::vector& data) { if (m_hidDevice && !data.empty()) { @@ -1805,48 +2297,109 @@ index 77e90f9..579936b 100644 } return false; } -@@ -549,8 +661,10 @@ void DudesCab::Device::SendCommand(HIDReportTypeMx command, const std::vector(command), parameters); + } - void DudesCab::Device::SendCommand(RIDType rid, uint8_t command, const std::vector& parameters) +-void DudesCab::Device::SendCommand(RIDType rid, uint8_t command, const std::vector& parameters) ++bool DudesCab::Device::SendCommand(HIDReportTypeMx command, const std::vector& parameters, const std::function& cancel) { ++ if (!SupportMx()) ++ return true; ++ return SendCommand(m_deviceRid, static_cast(command), parameters, cancel); ++} ++ ++bool DudesCab::Device::SendCommand(RIDType rid, uint8_t command, const std::vector& parameters, const std::function& cancel) ++{ + m_lastWriteFailed = true; if (!m_hidDevice) - return; +- return; ++ { ++ m_needsReopen = true; ++ return true; ++ } + m_lastWriteFailed = false; if (rid == RIDType::RIDOutputs) Log::Instrumentation("DudesCab", StringExtensions::Build("DudesCab SendCommand: {0}", std::to_string(static_cast(command)))); -@@ -581,7 +695,8 @@ void DudesCab::Device::SendCommand(RIDType rid, uint8_t command, const std::vect +@@ -581,8 +779,16 @@ void DudesCab::Device::SendCommand(RIDType rid, uint8_t command, const std::vect sendData.insert(sendData.end(), data.begin() + startPos, data.begin() + startPos + toSend); } - WriteUSB(sendData); ++ // VPE: a latch that came during the earlier reports holds back the rest of the command. ++ if (cancel && cancel()) ++ return false; + if (!WriteUSB(sendData)) ++ { + m_lastWriteFailed = true; ++ m_needsReopen = true; ++ } } ++ return true; } + DudesCab::Device::HIDCommonReportType DudesCab::Device::RemapCommonCommand(HIDCommonReportType command) diff --git a/src/cab/out/dudescab/DudesCab.h b/src/cab/out/dudescab/DudesCab.h -index b2b1f6c..c76403e 100644 +index b2b1f6c..6514666 100644 --- a/src/cab/out/dudescab/DudesCab.h +++ b/src/cab/out/dudescab/DudesCab.h -@@ -162,6 +162,15 @@ public: - void SendCommand(RIDType rid, uint8_t command, const std::vector& parameters = { }); +@@ -5,6 +5,7 @@ + #include + #include + #include ++#include + + #include + +@@ -129,7 +130,10 @@ public: + int NumOutputs() const { return m_numOutputs; } + const std::string& GetSerial() const { return m_serial; } + +- void AllOff(); ++ // VPE: returns whether the command got to the board. ++ bool AllOff(); ++ // VPE: closes the HID handle of a board that is not used. ++ void Close(); + void ReadPwmOutputsConfig(); + bool HasOutputEnabled(uint8_t extNum, uint8_t outputNum); + bool SupportMx(); +@@ -137,6 +141,8 @@ public: + void SendCommand(HIDCommonReportType command, const std::vector& parameters = { }); + void SendCommand(HIDReportType command, const std::vector& parameters = { }); + void SendCommand(HIDReportTypeMx command, const std::vector& parameters = { }); ++ // VPE: asks `cancel` before each report it writes and stops when it says so; returns false then. ++ bool SendCommand(HIDReportTypeMx command, const std::vector& parameters, const std::function& cancel); + + std::vector ReadUSB(uint8_t command); + +@@ -159,9 +165,24 @@ public: + uint8_t m_configVersion; + + private: +- void SendCommand(RIDType rid, uint8_t command, const std::vector& parameters = { }); ++ bool SendCommand(RIDType rid, uint8_t command, const std::vector& parameters = { }, const std::function& cancel = nullptr); std::vector ReadUSB(); bool WriteUSB(const std::vector& data); + bool m_lastWriteFailed = false; ++ // VPE: a write failed since the device was opened: only Reopen clears it, not a later write that went through. ++ bool m_needsReopen = false; + + public: + // VPE: whether a part of the last command could not be written. + bool LastWriteFailed() const { return m_lastWriteFailed; } ++ // VPE: whether a write failed since the device was last opened, so the handle has to be opened again. ++ bool NeedsReopen() const { return m_needsReopen; } + // VPE: opens the device again after a transport failure, such as after it was unplugged and plugged in again. + bool Reopen(); ++ // VPE: whether Reopen can find this board again, which takes a serial number. ++ bool CanReopen() const { return !m_serial.empty() && m_serial != ""; } + + private: HIDCommonReportType RemapCommonCommand(HIDCommonReportType command); HIDReportType RemapPwmCommand(HIDReportType command); -@@ -197,6 +206,8 @@ private: +@@ -197,6 +218,8 @@ private: bool m_minCommandIntervalMsSet; Device* m_dev; @@ -1855,22 +2408,99 @@ index b2b1f6c..c76403e 100644 std::vector m_oldOutputValues; std::vector m_outputBuffer; +@@ -206,6 +229,11 @@ private: + + static std::vector FindDevices(); + static std::vector s_devices; ++ // VPE: the MX interfaces, which the UMX devices use, are owned here too, and the devices are listed once until ++ // ClearDevices: a cabinet with an MX interface but no PWM one would otherwise list them again on every lookup and ++ // delete the UMX devices its controllers still use. ++ static std::vector s_mxDevices; ++ static bool s_discovered; + }; + + } +diff --git a/src/cab/out/dudescab/DudesCabAutoConfigurator.cpp b/src/cab/out/dudescab/DudesCabAutoConfigurator.cpp +index ecf905a..84147f9 100644 +--- a/src/cab/out/dudescab/DudesCabAutoConfigurator.cpp ++++ b/src/cab/out/dudescab/DudesCabAutoConfigurator.cpp +@@ -18,7 +18,20 @@ void DudesCabAutoConfigurator::AutoConfig(Cabinet* cabinet) + + for (DudesCab::Device* device : devices) + { +- if (device->UnitNo() >= 1 && device->UnitNo() <= 5) ++ // VPE: a controller binds by unit number, so a unit any Dude's Cab controller of the cabinet uses is skipped, as in ++ // C#: two updaters on one board would overwrite each other's frames. ++ bool preconfigured = false; ++ for (IOutputController* controller : *cabinet->GetOutputControllers()) ++ { ++ DudesCab* existing = dynamic_cast(controller); ++ if (existing && existing->GetNumber() == device->UnitNo()) ++ { ++ preconfigured = true; ++ break; ++ } ++ } ++ ++ if (!preconfigured && device->UnitNo() >= 1 && device->UnitNo() <= 5) + { + std::string controllerName = StringExtensions::Build("DudesCab Controller {0:00}", std::to_string(device->UnitNo())); + diff --git a/src/cab/out/dudescab/UMXDudesCabDevice.cpp b/src/cab/out/dudescab/UMXDudesCabDevice.cpp -index 7bd8055..d2ce82b 100644 +index 7bd8055..3dc6c35 100644 --- a/src/cab/out/dudescab/UMXDudesCabDevice.cpp +++ b/src/cab/out/dudescab/UMXDudesCabDevice.cpp -@@ -113,6 +113,9 @@ void UMXDudesCabDevice::SendCommand(UMXCommand command, const std::vector& parameters) ++void UMXDudesCabDevice::SendCommand(UMXCommand command, const std::vector& parameters) { SendCommand(command, parameters, nullptr); } ++ ++bool UMXDudesCabDevice::SendCommand(UMXCommand command, const std::vector& parameters, const std::function& cancel) { ++ // VPE: a retry after a failed write goes to the device found again, not to the stale handle. ++ if (m_device->NeedsReopen()) ++ m_device->Reopen(); auto dudeCommand = UMXToDudeCommand(command); - m_device->SendCommand(dudeCommand, parameters); +- m_device->SendCommand(dudeCommand, parameters); ++ bool sent = m_device->SendCommand(dudeCommand, parameters, cancel); + // VPE: a command that did not get to the device is an error. + if (m_device->LastWriteFailed()) + throw std::runtime_error(StringExtensions::Build("Sending UMX command {0} failed", std::to_string(static_cast(command)))); ++ return sent; } void UMXDudesCabDevice::WaitAck(uint8_t command) { } + ++bool UMXDudesCabDevice::IsLost() const { return m_device && m_device->NeedsReopen() && !m_device->CanReopen(); } ++ ++void UMXDudesCabDevice::Release() ++{ ++ if (m_device) ++ m_device->Close(); ++} ++ + DudesCab::Device::HIDReportTypeMx UMXDudesCabDevice::UMXToDudeCommand(UMXCommand command) + { + switch (command) +diff --git a/src/cab/out/dudescab/UMXDudesCabDevice.h b/src/cab/out/dudescab/UMXDudesCabDevice.h +index f981906..6f13772 100644 +--- a/src/cab/out/dudescab/UMXDudesCabDevice.h ++++ b/src/cab/out/dudescab/UMXDudesCabDevice.h +@@ -16,7 +16,10 @@ public: + + void Initialize() override; + void SendCommand(UMXCommand command, const std::vector& parameters = { }) override; ++ bool SendCommand(UMXCommand command, const std::vector& parameters, const std::function& cancel) override; + void WaitAck(uint8_t command) override; ++ bool IsLost() const override; ++ void Release() override; + + DudesCab::Device* GetDevice() const { return m_device; } + void SetDevice(DudesCab::Device* device) { m_device = device; } diff --git a/src/cab/out/ftdichip/FT245RBitbangController.cpp b/src/cab/out/ftdichip/FT245RBitbangController.cpp -index 29f2e7e..b8ab01a 100644 +index d698a04..2215df1 100644 --- a/src/cab/out/ftdichip/FT245RBitbangController.cpp +++ b/src/cab/out/ftdichip/FT245RBitbangController.cpp @@ -7,6 +7,7 @@ @@ -1912,7 +2542,7 @@ index 29f2e7e..b8ab01a 100644 } void FT245RBitbangController::Update() -@@ -177,10 +189,12 @@ void FT245RBitbangController::UpdaterThreadSignal() +@@ -185,10 +197,12 @@ void FT245RBitbangController::UpdaterThreadSignal() void FT245RBitbangController::UpdaterThreadDoIt() { @@ -1925,10 +2555,15 @@ index 29f2e7e..b8ab01a 100644 m_updaterThreadFinished = true; return; } -@@ -193,17 +207,23 @@ void FT245RBitbangController::UpdaterThreadDoIt() +@@ -200,18 +214,27 @@ void FT245RBitbangController::UpdaterThreadDoIt() + catch (const std::exception&) { Log::Exception(StringExtensions::Build("Could not send initial update to FTDI chip {0}. Updater thread will terminate.", m_serialNumber)); - Disconnect(); +- Disconnect(); ++ // VPE: Disconnect tries to turn the outputs off once more; when that fails too, Finish reports it. ++ std::string error; ++ if (!Disconnect(&error)) ++ m_finishError = StringExtensions::Build("FT245RBitbangController {0} could not turn its outputs off: {1}", GetName(), error); + gateUnit->Die(); m_updaterThreadFinished = true; return; @@ -1950,7 +2585,7 @@ index 29f2e7e..b8ab01a 100644 } catch (const std::exception& e) { -@@ -225,6 +245,7 @@ void FT245RBitbangController::UpdaterThreadDoIt() +@@ -233,6 +256,7 @@ void FT245RBitbangController::UpdaterThreadDoIt() catch (const std::exception& ec) { Log::Exception(StringExtensions::Build("Could not send update to FTDI chip {0}. Tried to reconnect to device but failed. Updater thread will terminate.", m_serialNumber)); @@ -1958,7 +2593,7 @@ index 29f2e7e..b8ab01a 100644 break; } -@@ -232,18 +253,24 @@ void FT245RBitbangController::UpdaterThreadDoIt() +@@ -240,18 +264,24 @@ void FT245RBitbangController::UpdaterThreadDoIt() { try { @@ -1984,21 +2619,45 @@ index 29f2e7e..b8ab01a 100644 break; } } -@@ -262,8 +289,13 @@ void FT245RBitbangController::UpdaterThreadDoIt() +@@ -263,15 +293,36 @@ void FT245RBitbangController::UpdaterThreadDoIt() + } + } + ++ // VPE: the outputs are off when either the final update or the one Disconnect sends got there. Taken before the ++ // final update, so the zeros confirm the closing that was published when the updater ended. ++ OutputGate::Snapshot finalGate = gateUnit->Observe(); ++ bool off = false; ++ std::string error; + try + { + SendUpdate(0); ++ off = true; + } catch (const std::exception& e) { Log::Exception(StringExtensions::Build("Final update to turn off all output for FTDI chip {0} failed.", m_serialNumber)); -+ m_finishError = StringExtensions::Build("FT245RBitbangController {0} could not turn its outputs off: {1}", GetName(), e.what()); - } - Disconnect(); ++ error = e.what(); ++ } ++ std::string disconnectError; ++ if (Disconnect(&disconnectError)) ++ off = true; ++ else if (error.empty()) ++ error = disconnectError; ++ if (!off) ++ m_finishError = StringExtensions::Build("FT245RBitbangController {0} could not turn its outputs off: {1}", GetName(), error); + if (died) + gateUnit->Die(); + else ++ { ++ if (off && !finalGate.open) ++ gateUnit->Ack(finalGate); + gateUnit->Stop(); + } +- Disconnect(); m_updaterThreadFinished = true; } -@@ -341,6 +373,9 @@ void FT245RBitbangController::SendUpdate(uint8_t outputData) +@@ -349,20 +400,27 @@ void FT245RBitbangController::SendUpdate(uint8_t outputData) "Wrong number of written bytes (expected 1, received {0}) was returned when sending data to the FTDI chip {1}", std::to_string(numBytes), m_serialNumber)); } } @@ -2007,9 +2666,39 @@ index 29f2e7e..b8ab01a 100644 + throw std::runtime_error(StringExtensions::Build("FTDI chip {0} is not connected", m_serialNumber)); } - void FT245RBitbangController::Disconnect() +-void FT245RBitbangController::Disconnect() ++bool FT245RBitbangController::Disconnect(std::string* error) + { + std::lock_guard lock(m_ftdiLocker); + ++ bool off = false; + if (m_ftdi) + { + try + { + SendUpdate(0); ++ off = true; + } +- catch (...) ++ catch (const std::exception& e) + { ++ if (error) ++ *error = e.what(); + } + + if (m_ftdi->IsOpen()) +@@ -380,6 +438,9 @@ void FT245RBitbangController::Disconnect() + m_ftdi = nullptr; + Log::Write(StringExtensions::Build("Connection to FTDI chip {0} closed.", m_serialNumber)); + } ++ else if (error) ++ *error = StringExtensions::Build("FTDI chip {0} is not connected", m_serialNumber); ++ return off; + } + + tinyxml2::XMLElement* FT245RBitbangController::ToXml(tinyxml2::XMLDocument& doc) const diff --git a/src/cab/out/ftdichip/FT245RBitbangController.h b/src/cab/out/ftdichip/FT245RBitbangController.h -index de1b98d..e0b2567 100644 +index de1b98d..bbe3c05 100644 --- a/src/cab/out/ftdichip/FT245RBitbangController.h +++ b/src/cab/out/ftdichip/FT245RBitbangController.h @@ -2,6 +2,7 @@ @@ -2029,69 +2718,19 @@ index de1b98d..e0b2567 100644 int m_firstTryFailCnt; std::recursive_mutex m_ftdiLocker; -diff --git a/src/cab/out/ftdichip/FT245RBitbangControllerAutoConfigurator.cpp b/src/cab/out/ftdichip/FT245RBitbangControllerAutoConfigurator.cpp -index 3b4a24c..60d53f4 100644 ---- a/src/cab/out/ftdichip/FT245RBitbangControllerAutoConfigurator.cpp -+++ b/src/cab/out/ftdichip/FT245RBitbangControllerAutoConfigurator.cpp -@@ -30,17 +30,17 @@ void FT245RBitbangControllerAutoConfigurator::AutoConfig(Cabinet* cabinet) - return; - } - -- for (uint32_t i = 0; i < amountDevices; i++) -+ // VPE: list the boards once, into storage for all of them. Upstream listed them once per board into room for one -+ // entry, so a second board overflowed the buffer, and every pass took the first board again. - { - FTDI* connectFTDI = new FTDI(); -- -- FTDI::FT_DEVICE_INFO_NODE devInfo; -- uint32_t numDevs = 1; -- status = connectFTDI->GetDeviceInfoList(&devInfo, numDevs); -- -- if (status == FTDI::FT_OK && numDevs > 0) -+ std::vector devInfo(amountDevices); -+ uint32_t numDevs = amountDevices; -+ status = connectFTDI->GetDeviceInfoList(devInfo.data(), numDevs); -+ if (status == FTDI::FT_OK) - { -- deviceList.emplace_back(devInfo.SerialNumber, devInfo.Description); -+ for (uint32_t i = 0; i < numDevs; i++) -+ deviceList.emplace_back(devInfo[i].SerialNumber, devInfo[i].Description); - } - delete connectFTDI; - } -diff --git a/src/cab/out/ftdichip/FTDI.cpp b/src/cab/out/ftdichip/FTDI.cpp -index 97d6458..10aa4e5 100644 ---- a/src/cab/out/ftdichip/FTDI.cpp -+++ b/src/cab/out/ftdichip/FTDI.cpp -@@ -1,6 +1,7 @@ - #include "FTDI.h" - #include "../../../Log.h" - #include "../../../general/StringExtensions.h" -+#include - #include - - namespace DOF -@@ -71,6 +72,9 @@ FTDI::FT_STATUS FTDI::GetDeviceInfoList(FT_DEVICE_INFO_NODE* devinfo, uint32_t& - if (!m_ftdiContext || !devinfo) - return FT_INVALID_PARAMETER; - -+ // VPE: numdevs is the capacity of devinfo on input and the number of entries written on output. Upstream wrote one -+ // entry per connected board whatever the caller had room for. -+ const uint32_t capacity = numdevs; - struct ftdi_device_list* devlist = nullptr; - int result = ftdi_usb_find_all(m_ftdiContext, &devlist, 0x0403, 0x6001); - -@@ -80,7 +84,7 @@ FTDI::FT_STATUS FTDI::GetDeviceInfoList(FT_DEVICE_INFO_NODE* devinfo, uint32_t& - return ConvertLibftdiError(result); - } +@@ -70,7 +73,8 @@ private: -- numdevs = static_cast(result); -+ numdevs = (std::min)(static_cast(result), capacity); + void Connect(); + void SendUpdate(uint8_t outputData); +- void Disconnect(); ++ // Returns whether it turned the outputs off before closing; when not, the reason is in `error`. ++ bool Disconnect(std::string* error = nullptr); + }; - struct ftdi_device_list* curdev = devlist; - for (uint32_t i = 0; i < numdevs && curdev; ++i, curdev = curdev->next) + } +\ No newline at end of file diff --git a/src/cab/out/lw/LedWiz.cpp b/src/cab/out/lw/LedWiz.cpp -index 96aa2a0..10c8b4d 100644 +index c136d75..a597cd8 100644 --- a/src/cab/out/lw/LedWiz.cpp +++ b/src/cab/out/lw/LedWiz.cpp @@ -1,5 +1,6 @@ @@ -2112,49 +2751,56 @@ index 96aa2a0..10c8b4d 100644 } void LedWiz::AddOutputs() -@@ -161,11 +163,13 @@ void LedWiz::OnOutputValueChanged(IOutput* output) - - LedWizUnit* s = s_ledWizUnits.at(m_number); - -+ // The scheduled value goes to the unit only: writing it back into the output would make the output gate lose the -+ // value it holds back while closed. - IOutput* recalculatedOutput = ScheduledSettings::GetInstance().GetNewRecalculatedOutput(output, 1, m_number - 1); -- lwo->SetOutput(recalculatedOutput->GetOutput()); -+ uint8_t value = recalculatedOutput->GetOutput(); - if (recalculatedOutput != output) - delete recalculatedOutput; -- s->UpdateValue(lwo); -+ s->UpdateValue(lwo, value); - } - - void LedWiz::StartupLedWiz() -@@ -483,18 +487,23 @@ LedWiz::LedWizUnit::~LedWizUnit() +@@ -484,13 +486,48 @@ LedWiz::LedWizUnit::~LedWizUnit() void LedWiz::LedWizUnit::Init(Cabinet* cabinet, int minCommandIntervalMs) { m_minCommandIntervalMs = minCommandIntervalMs; + // VPE: the gate unit exists before the updater starts, so a gate change made right after init counts it. + if (!IsUpdaterThreadAlive()) ++ { ++ ResetState(); + m_gateUnit = OutputGate::Instance().Register(StringExtensions::Build("LedWiz {0:00}", std::to_string(m_number))); ++ } StartLedWizUpdaterThread(); } ++void LedWiz::LedWizUnit::ResetState() ++{ ++ std::lock_guard lock(m_valueChangeLocker); ++ m_newOutputValues.fill(49); ++ m_currentOutputValues.fill(0); ++ m_newAfterValueSwitches.fill(0); ++ m_newBeforeValueSwitches.fill(0); ++ m_currentAfterValueSwitches.fill(0); ++ m_currentBeforeValueSwitches.fill(0); ++ m_newValueUpdateRequired = true; ++ m_newSwitchUpdateBeforeValueUpdateRequired = true; ++ m_newSwitchUpdateAfterValueUpdateRequired = true; ++ m_currentValueUpdateRequired = true; ++ m_currentSwitchUpdateBeforeValueUpdateRequired = true; ++ m_currentSwitchUpdateAfterValueUpdateRequired = true; ++ m_updateRequired = true; ++ m_inUseState = InUseStates::Startup; ++ m_pbaTime = std::chrono::steady_clock::time_point(); ++} ++ void LedWiz::LedWizUnit::Finish() { TerminateLedWizUpdaterThread(); ++ // Taken before the zeros, so they confirm the closing that was published when the updater ended. ++ OutputGate::Snapshot finalGate {}; ++ if (m_gateUnit) ++ finalGate = m_gateUnit->Observe(); + m_writeFailed = false; ShutdownLighting(); -+ m_shutdownFailed = m_writeFailed && m_fp != nullptr; ++ // A unit that was found but whose handle never opened could not turn its outputs off either. ++ m_shutdownFailed = m_writeFailed && (m_fp != nullptr || IsPresent()); ++ if (m_gateUnit && !m_writeFailed && !finalGate.open) ++ m_gateUnit->Ack(finalGate); } --void LedWiz::LedWizUnit::UpdateValue(LedWizOutput* ledWizOutput) -+void LedWiz::LedWizUnit::UpdateValue(LedWizOutput* ledWizOutput, uint8_t value) - { -- uint8_t v = s_byteToLedWizValue[ledWizOutput->GetOutput()]; -+ uint8_t v = s_byteToLedWizValue[value]; - bool s = (v != 0); - int zeroBasedOutputNumber = ledWizOutput->GetLedWizOutputNumber() - 1; - int byteNr = zeroBasedOutputNumber >> 3; -@@ -612,9 +621,15 @@ void LedWiz::LedWizUnit::LedWizUpdaterDoIt() + void LedWiz::LedWizUnit::UpdateValue(LedWizOutput* ledWizOutput) +@@ -613,9 +650,15 @@ void LedWiz::LedWizUnit::LedWizUpdaterDoIt() { Log::Write(StringExtensions::Build("Updater thread for LedWiz {0:00} started.", std::to_string(m_number))); @@ -2170,26 +2816,31 @@ index 96aa2a0..10c8b4d 100644 try { if (IsPresent()) -@@ -629,14 +644,31 @@ void LedWiz::LedWizUnit::LedWizUpdaterDoIt() +@@ -630,14 +673,36 @@ void LedWiz::LedWizUnit::LedWizUpdaterDoIt() m_inUseState = InUseStates::Running; } - if (m_inUseState == InUseStates::Running) + // The observed state governs what is sent. Closed: all off, whatever the values (a gate that opens restores + // them before it publishes); they go out in full once the opened generation is observed. ++ bool wrote = true; + if (!gate.open) + ShutdownLighting(); + else if (m_inUseState == InUseStates::Running) SendLedWizUpdate(); -+ // Open and never used: DOF leaves the hardware alone, there is nothing to send. ++ else ++ // Open and never used: DOF leaves the hardware alone, there is nothing to send and nothing to confirm. ++ wrote = false; + if (m_writeFailed) + { + // The values that did not get there are sent again. + ForceFullUpdate(); + gateUnit->Fail(gate.generation); + } -+ else ++ else if (wrote) + gateUnit->Ack(gate); ++ else ++ gateUnit->Untouched(gate); } + else + gateUnit->Fail(gate.generation); @@ -2203,7 +2854,7 @@ index 96aa2a0..10c8b4d 100644 failCnt++; if (failCnt > MAX_UPDATE_FAIL_COUNT) { -@@ -648,17 +680,38 @@ void LedWiz::LedWizUnit::LedWizUpdaterDoIt() +@@ -649,17 +714,38 @@ void LedWiz::LedWizUnit::LedWizUpdaterDoIt() if (m_keepLedWizUpdaterAlive) { @@ -2243,7 +2894,7 @@ index 96aa2a0..10c8b4d 100644 void LedWiz::LedWizUnit::UpdateDelay() { int ms = static_cast(std::chrono::duration_cast(std::chrono::steady_clock::now() - m_lastUpdate).count()); -@@ -726,9 +779,13 @@ void LedWiz::LedWizUnit::WriteUSB(const uint8_t* buf, size_t length) +@@ -727,9 +813,13 @@ void LedWiz::LedWizUnit::WriteUSB(const uint8_t* buf, size_t length) std::this_thread::sleep_for(std::chrono::milliseconds(s_retryWait[tries])); } Log::Error(StringExtensions::Build("LedWiz {0} WriteUSB failed after {1} retries", std::to_string(m_number), std::to_string(std::size(s_retryWait)))); @@ -2258,7 +2909,7 @@ index 96aa2a0..10c8b4d 100644 bool LedWiz::LedWizUnit::IsPresent() const diff --git a/src/cab/out/lw/LedWiz.h b/src/cab/out/lw/LedWiz.h -index 9f42dc1..7fcf360 100644 +index 9f42dc1..7c3c3a0 100644 --- a/src/cab/out/lw/LedWiz.h +++ b/src/cab/out/lw/LedWiz.h @@ -1,6 +1,7 @@ @@ -2269,16 +2920,7 @@ index 9f42dc1..7fcf360 100644 #include #include #include -@@ -96,7 +97,7 @@ private: - int GetNumber() const { return m_number; } - void Init(Cabinet* cabinet, int minCommandIntervalMs); - void Finish(); -- void UpdateValue(LedWizOutput* ledWizOutput); -+ void UpdateValue(LedWizOutput* ledWizOutput, uint8_t value); - void CopyNewToCurrent(); - bool IsUpdaterThreadAlive() const; - void StartLedWizUpdaterThread(); -@@ -157,6 +158,16 @@ private: +@@ -157,6 +158,19 @@ private: std::chrono::steady_clock::time_point m_lastUpdate; int m_minCommandIntervalMs; std::chrono::steady_clock::time_point m_pbaTime; @@ -2292,11 +2934,14 @@ index 9f42dc1..7fcf360 100644 + + private: + void ForceFullUpdate(); ++ // VPE: the units outlive sessions. A new session starts from all off and unused, so it never sends what the ++ // previous one had requested (a latch sent zeros but kept the values). ++ void ResetState(); }; }; diff --git a/src/cab/out/pac/PacDrive.cpp b/src/cab/out/pac/PacDrive.cpp -index 5c8b6e7..79f5387 100644 +index 1a2be63..ef76acd 100644 --- a/src/cab/out/pac/PacDrive.cpp +++ b/src/cab/out/pac/PacDrive.cpp @@ -1,5 +1,6 @@ @@ -2323,27 +2968,17 @@ index 5c8b6e7..79f5387 100644 } void PacDrive::Update() -@@ -70,7 +74,8 @@ void PacDrive::AddOutputs() - Output* newOutput = new Output(); - newOutput->SetName(StringExtensions::Build("{0}.{1:00}", GetName(), std::to_string(i))); - newOutput->SetNumber(i); -- outputs->push_back(newOutput); -+ // VPE: Add, not push_back: only Add connects the output's change event (and the output gate). -+ outputs->Add(newOutput); - } - } - } -@@ -129,17 +134,25 @@ PacDrive::PacDriveUnit::~PacDriveUnit() { TerminatePacDriveUpdaterThread(); } +@@ -129,23 +133,25 @@ PacDrive::PacDriveUnit::~PacDriveUnit() { TerminatePacDriveUpdaterThread(); } void PacDrive::PacDriveUnit::Init(Cabinet* cabinet) { m_index = PacDriveSingleton::GetInstance().PacDriveGetIndex(); + // VPE: the unit outlives a session; the next one starts from all off, not from the last game's outputs. -+ { -+ std::lock_guard lock(m_valueChangeLocker); -+ m_newValue = 0; -+ m_currentValue = 0; -+ m_updateRequired = true; -+ } + { + std::lock_guard lock(m_valueChangeLocker); + m_newValue = 0; + m_currentValue = 0; + m_updateRequired = true; + } + // VPE: the gate unit exists before the updater starts; a PacDrive that is not connected counts as failed. if (m_index >= 0) { @@ -2364,7 +2999,7 @@ index 5c8b6e7..79f5387 100644 void PacDrive::PacDriveUnit::UpdateValue(IOutput* output) { -@@ -171,13 +184,15 @@ void PacDrive::PacDriveUnit::TriggerPacDriveUpdaterThread() +@@ -177,13 +183,21 @@ void PacDrive::PacDriveUnit::TriggerPacDriveUpdaterThread() m_updateCondition.notify_one(); } @@ -2375,14 +3010,20 @@ index 5c8b6e7..79f5387 100644 if (m_index >= 0) { - PacDriveSetLEDStates(0); ++ // Taken before the zeros, so they confirm the closing that was published when the updater ended. ++ OutputGate::Snapshot finalGate {}; ++ if (m_gateUnit) ++ finalGate = m_gateUnit->Observe(); + ok = PacDriveSetLEDStates(0); ++ if (ok && m_gateUnit && !finalGate.open) ++ m_gateUnit->Ack(finalGate); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } + return ok; } void PacDrive::PacDriveUnit::StartPacDriveUpdaterThread() -@@ -214,19 +229,31 @@ void PacDrive::PacDriveUnit::TerminatePacDriveUpdaterThread() +@@ -220,19 +234,34 @@ void PacDrive::PacDriveUnit::TerminatePacDriveUpdaterThread() void PacDrive::PacDriveUnit::PacDriveUpdaterDoIt() { @@ -2402,8 +3043,11 @@ index 5c8b6e7..79f5387 100644 if (m_index >= 0) { - SendPacDriveUpdate(); -+ SendPacDriveUpdate(gate.open); -+ gateUnit->Ack(gate); ++ // VPE: a failed write is reported and retried on the next pass, without ending the updater. ++ if (SendPacDriveUpdate(gate.open)) ++ gateUnit->Ack(gate); ++ else ++ gateUnit->Fail(gate.generation); } + else + gateUnit->Fail(gate.generation); @@ -2415,7 +3059,7 @@ index 5c8b6e7..79f5387 100644 Log::Exception(StringExtensions::Build("Error occurred when updating PacDrive: {0}", e.what())); failCount++; -@@ -244,24 +271,39 @@ void PacDrive::PacDriveUnit::PacDriveUpdaterDoIt() +@@ -250,27 +279,39 @@ void PacDrive::PacDriveUnit::PacDriveUpdaterDoIt() } m_triggerUpdate = false; } @@ -2427,45 +3071,41 @@ index 5c8b6e7..79f5387 100644 } -void PacDrive::PacDriveUnit::SendPacDriveUpdate() -+void PacDrive::PacDriveUnit::SendPacDriveUpdate(bool open) ++bool PacDrive::PacDriveUnit::SendPacDriveUpdate(bool open) { if (m_index < 0) - return; +- return; ++ return false; std::lock_guard updateLock(m_pacDriveUpdateLocker); -- std::lock_guard valueLock(m_valueChangeLocker); -- -- if (!m_updateRequired) -- return; -- -- CopyNewToCurrent(); -- m_updateRequired = false; -+ uint16_t data; -+ { + uint16_t data; + { + // VPE: the values are copied under the lock and written without it, so a slow device never holds up the + // main thread's value changes (and with them a gate change for the other controllers). -+ std::lock_guard valueLock(m_valueChangeLocker); -+ if (!m_updateRequired) -+ return; -+ CopyNewToCurrent(); -+ m_updateRequired = false; -+ data = m_currentValue; -+ } + std::lock_guard valueLock(m_valueChangeLocker); + if (!m_updateRequired) +- return; +- ++ return true; + CopyNewToCurrent(); + m_updateRequired = false; + data = m_currentValue; + } -- PacDriveSetLEDStates(m_currentValue); +- PacDriveSetLEDStates(data); + // VPE: the observed gate state governs what is sent; an opening gate restores the values before it publishes. -+ if (!PacDriveSetLEDStates(open ? data : 0)) -+ { -+ // VPE: sent again on the next pass. -+ std::lock_guard valueLock(m_valueChangeLocker); -+ m_updateRequired = true; -+ throw std::runtime_error("PacDrive: write failed"); -+ } ++ if (PacDriveSetLEDStates(open ? data : 0)) ++ return true; ++ ++ // VPE: sent again on the next pass. ++ std::lock_guard valueLock(m_valueChangeLocker); ++ m_updateRequired = true; ++ return false; } void PacDrive::PacDriveUnit::CopyNewToCurrent() { m_currentValue = m_newValue; } diff --git a/src/cab/out/pac/PacDrive.h b/src/cab/out/pac/PacDrive.h -index e9e1876..7e9af8b 100644 +index e9e1876..55fd93c 100644 --- a/src/cab/out/pac/PacDrive.h +++ b/src/cab/out/pac/PacDrive.h @@ -1,6 +1,7 @@ @@ -2494,20 +3134,21 @@ index e9e1876..7e9af8b 100644 std::mutex m_pacDriveUpdateLocker; std::mutex m_valueChangeLocker; -@@ -70,7 +73,7 @@ private: +@@ -70,7 +73,8 @@ private: void StartPacDriveUpdaterThread(); void TerminatePacDriveUpdaterThread(); void PacDriveUpdaterDoIt(); - void SendPacDriveUpdate(); -+ void SendPacDriveUpdate(bool open); ++ // Returns false if the write failed; the update is then sent again on the next pass. ++ bool SendPacDriveUpdate(bool open); void CopyNewToCurrent(); bool IsUpdaterThreadAlive() const; bool PacDriveSetLEDStates(uint16_t data); diff --git a/src/cab/out/pac/PacDriveSingleton.cpp b/src/cab/out/pac/PacDriveSingleton.cpp -index c093209..4ffa650 100644 +index b5b88a6..c53d5b3 100644 --- a/src/cab/out/pac/PacDriveSingleton.cpp +++ b/src/cab/out/pac/PacDriveSingleton.cpp -@@ -367,8 +367,10 @@ std::vector PacDriveSingleton::PacUIOGetIdList() +@@ -374,8 +374,10 @@ std::vector PacDriveSingleton::PacUIOGetIdList() return idList; } @@ -2519,17 +3160,36 @@ index c093209..4ffa650 100644 if (index < 0 || index >= static_cast(m_devices.size())) return false; -@@ -385,12 +387,19 @@ bool PacDriveSingleton::PacLed64SetLEDIntensities(int index, const uint8_t* data +@@ -389,26 +391,30 @@ bool PacDriveSingleton::PacLed64SetLEDIntensities(int index, const uint8_t* data + + bool success = true; + int maxLeds = (device.type == DeviceType::PacLED64) ? 64 : 96; ++ int interfaceNumber = (device.type == DeviceType::IPACIO) ? GetUsbInterface(index) : 0; - for (int i = 0; i < maxLeds; i++) +- if (device.type == DeviceType::IPACIO) ++ for (int i = 0; i < maxLeds; i++) { -+ // VPE: one transfer per port, so a full update takes a while; the caller can end it between two ports. +- int interfaceNumber = GetUsbInterface(index); +- for (int i = 0; i < maxLeds; i++) ++ // VPE: one transfer per port, so a full update takes a while; the caller can end it between two ports, also on ++ // an Ultimate I/O. + if (cancel && cancel()) + { + if (cancelled) + *cancelled = true; + return success; + } ++ if (device.type == DeviceType::IPACIO) + { + if (!SendUltimateIOCommand(usbDevice, interfaceNumber, static_cast(i), data[i])) + success = false; ++ continue; + } +- return success; +- } +- +- for (int i = 0; i < maxLeds; i++) +- { uint8_t ledData[2]; ledData[0] = static_cast(i); ledData[1] = data[i]; @@ -2540,7 +3200,7 @@ index c093209..4ffa650 100644 { success = false; } -@@ -422,7 +431,7 @@ bool PacDriveSingleton::PacLed64SetLEDIntensity(int index, int port, uint8_t int +@@ -443,7 +449,7 @@ bool PacDriveSingleton::PacLed64SetLEDIntensity(int index, int port, uint8_t int int result = libusb_control_transfer(usbDevice, 0x21, 9, 0x0200, 0, data, 2, 2000); @@ -2549,7 +3209,7 @@ index c093209..4ffa650 100644 } bool PacDriveSingleton::PacLed64SetLEDStates(int index, int group, uint8_t data) -@@ -451,7 +460,7 @@ bool PacDriveSingleton::PacLed64SetLEDStates(int index, int group, uint8_t data) +@@ -486,7 +492,7 @@ bool PacDriveSingleton::PacLed64SetLEDStates(int index, int group, uint8_t data) ledData[1] = 0; // intensity = 0 int result = libusb_control_transfer(usbDevice, 0x21, 9, 0x0200, 0, ledData, 2, 2000); @@ -2558,7 +3218,7 @@ index c093209..4ffa650 100644 { success = false; } -@@ -472,7 +481,7 @@ bool PacDriveSingleton::PacLed64SetLEDStates(int index, int group, uint8_t data) +@@ -507,7 +513,7 @@ bool PacDriveSingleton::PacLed64SetLEDStates(int index, int group, uint8_t data) ledData[1] = intensity; int result = libusb_control_transfer(usbDevice, 0x21, 9, 0x0200, 0, ledData, 2, 2000); @@ -2567,7 +3227,7 @@ index c093209..4ffa650 100644 { success = false; } -@@ -502,7 +511,7 @@ bool PacDriveSingleton::PacLed64SetLEDFadeTime(int index, uint8_t fadeTime) +@@ -540,7 +546,7 @@ bool PacDriveSingleton::PacLed64SetLEDFadeTime(int index, uint8_t fadeTime) int result = libusb_control_transfer(usbDevice, 0x21, 9, 0x0300, 0, data, 2, 2000); @@ -2577,7 +3237,7 @@ index c093209..4ffa650 100644 hid_device* PacDriveSingleton::GetHidDevice(int index) diff --git a/src/cab/out/pac/PacDriveSingleton.h b/src/cab/out/pac/PacDriveSingleton.h -index b246346..6c5bac1 100644 +index c71dc9d..2fbebff 100644 --- a/src/cab/out/pac/PacDriveSingleton.h +++ b/src/cab/out/pac/PacDriveSingleton.h @@ -38,7 +38,9 @@ public: @@ -2592,7 +3252,7 @@ index b246346..6c5bac1 100644 bool PacLed64SetLEDStates(int index, int group, uint8_t data); bool PacLed64SetLEDFadeTime(int index, uint8_t fadeTime); diff --git a/src/cab/out/pac/PacLed64.cpp b/src/cab/out/pac/PacLed64.cpp -index b7a8f8a..43d0067 100644 +index 3a4215f..74f62da 100644 --- a/src/cab/out/pac/PacLed64.cpp +++ b/src/cab/out/pac/PacLed64.cpp @@ -1,4 +1,5 @@ @@ -2656,17 +3316,23 @@ index b7a8f8a..43d0067 100644 m_index = -1; } -@@ -274,7 +292,8 @@ void PacLed64::PacLed64Unit::ShutdownLighting() +@@ -274,7 +292,14 @@ void PacLed64::PacLed64Unit::ShutdownLighting() if (IsPresent()) { EnforceMinUpdateInterval(); -- PacDriveSingleton::GetInstance().PacLed64SetLEDStates(0, 0, 0); +- PacDriveSingleton::GetInstance().PacLed64SetLEDStates(m_index, 0, 0); ++ // Taken before the zeros, so they confirm the closing that was published when the updater ended. ++ OutputGate::Snapshot finalGate {}; ++ if (m_gateUnit) ++ finalGate = m_gateUnit->Observe(); + if (!PacDriveSingleton::GetInstance().PacLed64SetLEDStates(m_index, 0, 0)) + throw std::runtime_error("PacLed64: turning the outputs off failed"); ++ if (m_gateUnit && !finalGate.open) ++ m_gateUnit->Ack(finalGate); std::this_thread::sleep_for(std::chrono::milliseconds(100)); std::fill(m_lastStateSent.begin(), m_lastStateSent.end(), false); } -@@ -314,6 +333,7 @@ void PacLed64::PacLed64Unit::TerminatePacLed64UpdaterThread() +@@ -314,6 +339,7 @@ void PacLed64::PacLed64Unit::TerminatePacLed64UpdaterThread() void PacLed64::PacLed64Unit::PacLed64UpdaterDoIt() { @@ -2674,7 +3340,7 @@ index b7a8f8a..43d0067 100644 try { ResetFadeTime(); -@@ -321,6 +341,7 @@ void PacLed64::PacLed64Unit::PacLed64UpdaterDoIt() +@@ -321,6 +347,7 @@ void PacLed64::PacLed64Unit::PacLed64UpdaterDoIt() catch (const std::exception& e) { Log::Exception(StringExtensions::Build("Exception occurred while setting fade time for PacLed64 {0} to 0: {1}", std::to_string(m_index), e.what())); @@ -2682,7 +3348,7 @@ index b7a8f8a..43d0067 100644 m_updaterThreadFinished = true; return; } -@@ -328,16 +349,30 @@ void PacLed64::PacLed64Unit::PacLed64UpdaterDoIt() +@@ -328,16 +355,34 @@ void PacLed64::PacLed64Unit::PacLed64UpdaterDoIt() int failCount = 0; while (m_keepPacLed64UpdaterAlive) { @@ -2698,8 +3364,12 @@ index b7a8f8a..43d0067 100644 if (IsPresent()) { - SendPacLed64Update(); -+ if (SendPacLed64Update(gate.open)) ++ // VPE: a failed write is reported and retried on the next pass, without ending the updater. ++ bool failed = false; ++ if (SendPacLed64Update(gate.open, failed)) + gateUnit->Ack(gate); ++ else if (failed) ++ gateUnit->Fail(gate.generation); } + else + gateUnit->Fail(gate.generation); @@ -2714,7 +3384,7 @@ index b7a8f8a..43d0067 100644 Log::Exception(StringExtensions::Build("Error occurred when updating PacLed64 {0}: {1}", std::to_string(m_id), e.what())); failCount++; -@@ -356,112 +391,92 @@ void PacLed64::PacLed64Unit::PacLed64UpdaterDoIt() +@@ -356,72 +401,109 @@ void PacLed64::PacLed64Unit::PacLed64UpdaterDoIt() } m_triggerUpdate = false; } @@ -2726,173 +3396,144 @@ index b7a8f8a..43d0067 100644 } -void PacLed64::PacLed64Unit::SendPacLed64Update() -+bool PacLed64::PacLed64Unit::SendPacLed64Update(bool open) ++bool PacLed64::PacLed64Unit::SendPacLed64Update(bool open, bool& failed) { ++ failed = false; if (!IsPresent()) - return; + return true; std::lock_guard updateLock(m_pacLed64UpdateLocker); -- std::lock_guard valueLock(m_valueChangeLocker); -- -- if (!m_updateRequired && !m_forceFullUpdate) -- return; -- -- CopyNewToCurrent(); -- m_updateRequired = false; -- -- uint8_t intensityUpdatesRequired = 0; -- uint8_t stateUpdatesRequired = 0; + std::array target {}; + bool full; -+ { + { + // VPE: the values are copied under the lock and written without it, so a slow device never holds up the main + // thread's value changes (and with them a gate change for the other controllers). -+ std::lock_guard valueLock(m_valueChangeLocker); -+ if (!m_updateRequired && !m_forceFullUpdate) + std::lock_guard valueLock(m_valueChangeLocker); + if (!m_updateRequired && !m_forceFullUpdate) +- return; +- + return true; -+ CopyNewToCurrent(); -+ m_updateRequired = false; + CopyNewToCurrent(); + m_updateRequired = false; + full = m_forceFullUpdate; + // VPE: the observed gate state governs what is sent; an opening gate restores the values before it publishes. + if (open) + std::copy_n(m_currentValue.begin(), 64, target.begin()); -+ } + } +- int updatesRequired = 0; - if (!m_forceFullUpdate) + int changed = 0; + for (int o = 0; o < 64; o++) { -- for (int g = 0; g < 8; g++) +- for (int o = 0; o < 64; o++) - { -- bool stateUpdateRequired = false; -- for (int p = 0; p < 8; p++) -- { -- int o = (g << 3) | p; -- if (m_currentValue[o] > 0) -- { -- if (m_currentValue[o] != m_lastValueSent[o]) -- { -- intensityUpdatesRequired++; -- } -- else if (!m_lastStateSent[o]) -- { -- stateUpdateRequired = true; -- } -- } -- else if (m_lastStateSent[o]) -- { -- stateUpdateRequired = true; -- } -- } -- if (stateUpdateRequired) -- stateUpdatesRequired++; +- if (m_currentValue[o] != m_lastValueSent[o] || (m_currentValue[o] > 0) != m_lastStateSent[o]) +- updatesRequired++; - } + if (target[o] != m_lastValueSent[o] || (target[o] > 0) != m_lastStateSent[o]) + changed++; } -- if (m_forceFullUpdate || (intensityUpdatesRequired + stateUpdatesRequired) > m_fullUpdateThreshold) +- if (m_forceFullUpdate || updatesRequired > m_fullUpdateThreshold) + if (full || changed > m_fullUpdateThreshold) { EnforceMinUpdateInterval(); -- PacDriveSingleton::GetInstance().PacLed64SetLEDIntensities(m_index, m_currentValue.data()); +- bool written = PacDriveSingleton::GetInstance().PacLed64SetLEDIntensities(m_index, m_currentValue.data()); + // VPE: a latch before or during the transfer makes this opening's update obsolete (see below); the ports it + // reached are not known to the next pass, which sends all of them. + bool cancelled = false; + bool written = PacDriveSingleton::GetInstance().PacLed64SetLEDIntensities(m_index, target.data(), open ? GateLatched : nullptr, &cancelled); m_lastCommand = std::chrono::steady_clock::now(); - -- m_lastValueSent = m_currentValue; -- for (int i = 0; i < 64; i++) +- if (written) + if (cancelled) { -- m_lastStateSent[i] = (m_lastValueSent[i] > 0); +- m_lastValueSent = m_currentValue; +- for (int i = 0; i < 64; i++) +- { +- m_lastStateSent[i] = (m_lastValueSent[i] > 0); +- } +- m_forceFullUpdate = false; + std::lock_guard valueLock(m_valueChangeLocker); + m_forceFullUpdate = true; + m_updateRequired = true; + return false; } +- else + if (!written) -+ throw std::runtime_error("PacLed64: write failed"); -+ for (int o = 0; o < 64; o++) + { ++ std::lock_guard valueLock(m_valueChangeLocker); + m_forceFullUpdate = true; +- } +- else +- { ++ m_updateRequired = true; ++ failed = true; ++ return false; ++ } + for (int o = 0; o < 64; o++) + { +- if (m_currentValue[o] == m_lastValueSent[o] && (m_currentValue[o] > 0) == m_lastStateSent[o]) +- continue; +- +- EnforceMinUpdateInterval(); +- bool written = PacDriveSingleton::GetInstance().PacLed64SetLEDIntensity(m_index, o, m_currentValue[o]); +- m_lastCommand = std::chrono::steady_clock::now(); +- if (!written) +- { +- m_forceFullUpdate = true; +- continue; +- } + m_lastValueSent[o] = target[o]; + m_lastStateSent[o] = target[o] > 0; + } + std::lock_guard valueLock(m_valueChangeLocker); - m_forceFullUpdate = false; ++ m_forceFullUpdate = false; + return true; - } -- else -+ -+ // VPE: each changed port gets its intensity, zero included. libdof's state call writes 255 or 0 to every port of -+ // a group, which would turn dimmed and unchanged neighbours to full or off. ++ } + +- m_lastValueSent[o] = m_currentValue[o]; +- m_lastStateSent[o] = (m_currentValue[o] > 0); + for (int o = 0; o < 64; o++) - { -- for (int g = 0; g < 8; g++) ++ { + if (target[o] == m_lastValueSent[o] && (target[o] > 0) == m_lastStateSent[o]) + continue; + EnforceMinUpdateInterval(); + // VPE: each write waits for the minimum interval, so an update of many ports takes a while. Once the gate is + // latched, the rest of an opening's update is obsolete: the next pass sends the closing in full instead. + if (open && OutputGate::Instance().IsLatched()) - { -- int mask = 0; -- bool stateUpdateRequired = false; -- -- for (int p = 0; p < 8; p++) -- { -- int o = (g << 3) | p; -- if (m_currentValue[o] > 0) -- { -- if (m_currentValue[o] != m_lastValueSent[o]) -- { -- EnforceMinUpdateInterval(); -- PacDriveSingleton::GetInstance().PacLed64SetLEDIntensity(m_index, o, m_currentValue[o]); -- m_lastCommand = std::chrono::steady_clock::now(); -- -- m_lastStateSent[o] = true; -- m_lastValueSent[o] = m_currentValue[o]; -- } -- else if (!m_lastStateSent[o]) -- { -- mask |= (1 << p); -- stateUpdateRequired = true; -- m_lastStateSent[o] = true; -- } -- } -- else if (m_lastStateSent[o]) -- { -- stateUpdateRequired = true; -- m_lastStateSent[o] = false; -- m_lastValueSent[o] = 0; -- } -- } -- -- if (stateUpdateRequired) -- { -- EnforceMinUpdateInterval(); -- PacDriveSingleton::GetInstance().PacLed64SetLEDStates(m_index, g + 1, static_cast(mask)); -- m_lastCommand = std::chrono::steady_clock::now(); -- } ++ { + std::lock_guard valueLock(m_valueChangeLocker); + m_forceFullUpdate = true; + m_updateRequired = true; + return false; - } -+ if (!PacDriveSingleton::GetInstance().PacLed64SetLEDIntensity(m_index, o, target[o])) -+ throw std::runtime_error("PacLed64: write failed"); ++ } ++ bool written = PacDriveSingleton::GetInstance().PacLed64SetLEDIntensity(m_index, o, target[o]); + m_lastCommand = std::chrono::steady_clock::now(); ++ if (!written) ++ { ++ failed = true; ++ continue; + } + m_lastValueSent[o] = target[o]; + m_lastStateSent[o] = target[o] > 0; } ++ if (failed) ++ { ++ // VPE: what a failed port has is not known: the next pass sends everything. ++ std::lock_guard valueLock(m_valueChangeLocker); ++ m_forceFullUpdate = true; ++ m_updateRequired = true; ++ return false; ++ } + return true; } void PacLed64::PacLed64Unit::CopyNewToCurrent() { m_currentValue = m_newValue; } diff --git a/src/cab/out/pac/PacLed64.h b/src/cab/out/pac/PacLed64.h -index 640daa8..88ea8c3 100644 +index 640daa8..173532d 100644 --- a/src/cab/out/pac/PacLed64.h +++ b/src/cab/out/pac/PacLed64.h @@ -1,6 +1,7 @@ @@ -2911,18 +3552,19 @@ index 640daa8..88ea8c3 100644 std::vector m_newValue; std::vector m_currentValue; -@@ -105,7 +107,8 @@ private: +@@ -105,7 +107,9 @@ private: void StartPacLed64UpdaterThread(); void TerminatePacLed64UpdaterThread(); void PacLed64UpdaterDoIt(); - void SendPacLed64Update(); + // Returns false if a latch of the gate ended an opening's update early; the next pass sends everything. -+ bool SendPacLed64Update(bool open); ++ // Returns true once the update is sent. `failed` is set when a write failed; the next pass sends everything. ++ bool SendPacLed64Update(bool open, bool& failed); void CopyNewToCurrent(); void ResetFadeTime(); void EnforceMinUpdateInterval(); diff --git a/src/cab/out/pac/PacUIO.cpp b/src/cab/out/pac/PacUIO.cpp -index 314ea83..fb7ab81 100644 +index 894e0ed..74c3cf3 100644 --- a/src/cab/out/pac/PacUIO.cpp +++ b/src/cab/out/pac/PacUIO.cpp @@ -1,5 +1,6 @@ @@ -2950,25 +3592,23 @@ index 314ea83..fb7ab81 100644 Log::Write(StringExtensions::Build("PacUIO Id:{0} finished and updater thread stopped.", std::to_string(m_id))); } -@@ -153,17 +156,46 @@ PacUIO::PacUIOUnit::PacUIOUnit(int id) - std::fill_n(m_currentValue, 96, 0); - std::fill_n(m_lastValueSent, 96, 0); - std::fill_n(m_lastStateSent, 96, false); -- -- InitUnit(); -+ // VPE: constructing a unit writes nothing; a board is touched only once a configured controller starts its unit. - } - - PacUIO::PacUIOUnit::~PacUIOUnit() { TerminatePacUIOUpdaterThread(); } +@@ -159,17 +162,30 @@ PacUIO::PacUIOUnit::~PacUIOUnit() { TerminatePacUIOUpdaterThread(); } --void PacUIO::PacUIOUnit::Init(Cabinet* cabinet) { StartPacUIOUpdaterThread(); } -+void PacUIO::PacUIOUnit::Init(Cabinet* cabinet) -+{ + void PacUIO::PacUIOUnit::Init(Cabinet* cabinet) + { + // VPE: the units live as long as the process. Each session finds the device again and starts from nothing, so + // values and the enumeration index of an earlier session are never sent. -+ if (!IsUpdaterThreadAlive()) -+ { -+ m_index = PacDriveSingleton::GetInstance().PacUIOGetIndexForDeviceId(m_id); + if (!IsUpdaterThreadAlive()) + { + m_pdSingleton = &PacDriveSingleton::GetInstance(); + m_index = m_pdSingleton->PacUIOGetIndexForDeviceId(m_id); +- std::lock_guard lock(m_valueChangeLocker); +- std::fill_n(m_newValue, 96, 0); +- std::fill_n(m_currentValue, 96, 0); +- std::fill_n(m_lastValueSent, 96, 0); +- std::fill_n(m_lastStateSent, 96, false); +- m_updateRequired = true; +- m_forceFullUpdate = true; + { + std::lock_guard lock(m_valueChangeLocker); + std::fill_n(m_newValue, 96, 0); @@ -2987,10 +3627,10 @@ index 314ea83..fb7ab81 100644 + } + m_gateUnit = OutputGate::Instance().Register(unitName); + m_started = true; -+ } -+ StartPacUIOUpdaterThread(); -+} - + } + StartPacUIOUpdaterThread(); + } +@@ -177,6 +193,9 @@ void PacUIO::PacUIOUnit::Init(Cabinet* cabinet) void PacUIO::PacUIOUnit::Finish() { TerminatePacUIOUpdaterThread(); @@ -3000,21 +3640,7 @@ index 314ea83..fb7ab81 100644 ShutdownLighting(); } -@@ -183,11 +215,8 @@ void PacUIO::PacUIOUnit::UpdateValue(IOutput* output) - } - } - --void PacUIO::PacUIOUnit::CopyNewToCurrent() --{ -- std::lock_guard lock(m_valueChangeLocker); -- std::copy(m_newValue, m_newValue + 96, m_currentValue); --} -+// Called with m_valueChangeLocker held. -+void PacUIO::PacUIOUnit::CopyNewToCurrent() { std::copy(m_newValue, m_newValue + 96, m_currentValue); } - - bool PacUIO::PacUIOUnit::IsUpdaterThreadAlive() { return m_pacUIOUpdater.joinable(); } - -@@ -229,6 +258,7 @@ void PacUIO::PacUIOUnit::TriggerPacUIOUpdaterThread() +@@ -238,6 +257,7 @@ void PacUIO::PacUIOUnit::TriggerPacUIOUpdaterThread() void PacUIO::PacUIOUnit::PacUIOUpdaterDoIt() { @@ -3022,7 +3648,7 @@ index 314ea83..fb7ab81 100644 try { ResetFadeTime(); -@@ -236,6 +266,7 @@ void PacUIO::PacUIOUnit::PacUIOUpdaterDoIt() +@@ -245,6 +265,7 @@ void PacUIO::PacUIOUnit::PacUIOUpdaterDoIt() catch (const std::exception& e) { Log::Exception(StringExtensions::Build("A exception occurred while setting the fadetime for PacUIO {0} to 0.", std::to_string(m_index))); @@ -3030,7 +3656,7 @@ index 314ea83..fb7ab81 100644 m_updaterThreadFinished = true; return; } -@@ -243,16 +274,34 @@ void PacUIO::PacUIOUnit::PacUIOUpdaterDoIt() +@@ -252,16 +273,38 @@ void PacUIO::PacUIOUnit::PacUIOUpdaterDoIt() int failCnt = 0; while (m_keepPacUIOUpdaterAlive.load()) { @@ -3047,8 +3673,12 @@ index 314ea83..fb7ab81 100644 if (IsPresent()) { - SendPacUIOUpdate(); -+ if (SendPacUIOUpdate(gate.open)) ++ // VPE: a failed write is reported and retried on the next pass, without ending the updater. ++ bool failed = false; ++ if (SendPacUIOUpdate(gate.open, failed)) + gateUnit->Ack(gate); ++ else if (failed) ++ gateUnit->Fail(gate.generation); } + else + gateUnit->Fail(gate.generation); @@ -3066,7 +3696,7 @@ index 314ea83..fb7ab81 100644 Log::Exception(StringExtensions::Build("A error occurred when updating PacUIO {0}", std::to_string(m_id))); failCnt++; -@@ -271,112 +320,94 @@ void PacUIO::PacUIOUnit::PacUIOUpdaterDoIt() +@@ -280,68 +323,101 @@ void PacUIO::PacUIOUnit::PacUIOUpdaterDoIt() } m_triggerUpdate.store(false); } @@ -3078,8 +3708,9 @@ index 314ea83..fb7ab81 100644 } -void PacUIO::PacUIOUnit::SendPacUIOUpdate() -+bool PacUIO::PacUIOUnit::SendPacUIOUpdate(bool open) ++bool PacUIO::PacUIOUnit::SendPacUIOUpdate(bool open, bool& failed) { ++ failed = false; if (!IsPresent()) { m_forceFullUpdate = true; @@ -3103,62 +3734,50 @@ index 314ea83..fb7ab81 100644 + std::copy(m_currentValue, m_currentValue + 96, target); } -- uint8_t intensityUpdatesRequired = 0; -- uint8_t stateUpdatesRequired = 0; -- +- int updatesRequired = 0; - if (!m_forceFullUpdate) + int changed = 0; + for (int o = 0; o < 96; o++) { -- for (int g = 0; g < 12; g++) +- for (int o = 0; o < 96; o++) - { -- bool stateUpdateRequired = false; -- for (int p = 0; p < 8; p++) -- { -- int o = g << 3 | p; -- if (m_currentValue[o] > 0) -- { -- if (m_currentValue[o] != m_lastValueSent[o]) -- { -- intensityUpdatesRequired++; -- } -- else if (!m_lastStateSent[o]) -- { -- stateUpdateRequired = true; -- } -- } -- else if (m_lastStateSent[o]) -- { -- stateUpdateRequired = true; -- } -- } -- if (stateUpdateRequired) -- stateUpdatesRequired++; +- if (m_currentValue[o] != m_lastValueSent[o] || (m_currentValue[o] > 0) != m_lastStateSent[o]) +- updatesRequired++; - } + if (target[o] != m_lastValueSent[o] || (target[o] > 0) != m_lastStateSent[o]) + changed++; } -- if (m_forceFullUpdate || (intensityUpdatesRequired + stateUpdatesRequired) > 50) +- if (m_forceFullUpdate || updatesRequired > 50) + if (m_forceFullUpdate || changed > 50) { -- m_pdSingleton->PacLed64SetLEDIntensities(m_index, m_currentValue); -- std::copy(m_currentValue, m_currentValue + 96, m_lastValueSent); -- for (int i = 0; i < 96; i++) +- if (m_pdSingleton->PacLed64SetLEDIntensities(m_index, m_currentValue)) + // VPE: a latch before or during the transfer makes this opening's update obsolete; the ports it reached are not + // known to the next pass, which sends all of them. + bool cancelled = false; + bool written = m_pdSingleton->PacLed64SetLEDIntensities(m_index, target, open ? GateLatched : nullptr, &cancelled); + if (cancelled) { -- m_lastStateSent[i] = (m_lastValueSent[i] > 0); +- std::copy(m_currentValue, m_currentValue + 96, m_lastValueSent); +- for (int i = 0; i < 96; i++) +- { +- m_lastStateSent[i] = (m_lastValueSent[i] > 0); +- } +- m_forceFullUpdate = false; + std::lock_guard valueLock(m_valueChangeLocker); + m_forceFullUpdate = true; + m_updateRequired = true; + return false; } +- else + if (!written) -+ throw std::runtime_error("PacUIO: write failed"); ++ { ++ std::lock_guard valueLock(m_valueChangeLocker); + m_forceFullUpdate = true; ++ m_updateRequired = true; ++ failed = true; ++ return false; ++ } + std::copy(target, target + 96, m_lastValueSent); + for (int i = 0; i < 96; i++) + m_lastStateSent[i] = (m_lastValueSent[i] > 0); @@ -3168,72 +3787,66 @@ index 314ea83..fb7ab81 100644 } - else + -+ // VPE: each changed port gets its intensity, zero included. libdof's state call writes 255 or 0 to every port of -+ // a group, which would turn dimmed and unchanged neighbours to full or off. + for (int o = 0; o < 96; o++) { -- for (int g = 0; g < 12; g++) +- for (int o = 0; o < 96; o++) + if (target[o] == m_lastValueSent[o] && (target[o] > 0) == m_lastStateSent[o]) + continue; + // VPE: once the gate is latched, the rest of an opening's update is obsolete: the next pass sends the closing. + if (open && OutputGate::Instance().IsLatched()) { -- int mask = 0; -- bool stateUpdateRequired = false; -- for (int p = 0; p < 8; p++) -- { -- int o = g << 3 | p; -- if (m_currentValue[o] > 0) -- { -- if (m_currentValue[o] != m_lastValueSent[o]) -- { -- m_pdSingleton->PacLed64SetLEDIntensity(m_index, o, m_currentValue[o]); -- m_lastStateSent[o] = true; -- m_lastValueSent[o] = m_currentValue[o]; -- } -- else if (!m_lastStateSent[o]) -- { -- mask |= (1 << p); -- stateUpdateRequired = true; -- m_lastStateSent[o] = true; -- } -- } -- else if (m_lastStateSent[o]) -- { -- stateUpdateRequired = true; -- m_lastStateSent[o] = false; -- m_lastValueSent[o] = 0; -- } -- } -- if (stateUpdateRequired) +- if (m_currentValue[o] == m_lastValueSent[o] && (m_currentValue[o] > 0) == m_lastStateSent[o]) +- continue; +- +- if (!m_pdSingleton->PacLed64SetLEDIntensity(m_index, o, m_currentValue[o])) - { -- m_pdSingleton->PacLed64SetLEDStates(m_index, g + 1, static_cast(mask)); +- m_forceFullUpdate = true; +- continue; - } +- m_lastValueSent[o] = m_currentValue[o]; +- m_lastStateSent[o] = (m_currentValue[o] > 0); + std::lock_guard valueLock(m_valueChangeLocker); + m_forceFullUpdate = true; + m_updateRequired = true; + return false; - } ++ } + if (!m_pdSingleton->PacLed64SetLEDIntensity(m_index, o, target[o])) -+ throw std::runtime_error("PacUIO: write failed"); ++ { ++ failed = true; ++ continue; + } + m_lastValueSent[o] = target[o]; + m_lastStateSent[o] = target[o] > 0; } ++ if (failed) ++ { ++ // VPE: what a failed port has is not known: the next pass sends everything. ++ std::lock_guard valueLock(m_valueChangeLocker); ++ m_forceFullUpdate = true; ++ m_updateRequired = true; ++ return false; ++ } + return true; } void PacUIO::PacUIOUnit::ShutdownLighting() - { +@@ -349,7 +425,14 @@ void PacUIO::PacUIOUnit::ShutdownLighting() Log::Write("PacUIO.ShutdownLighting"); -- m_pdSingleton->PacLed64SetLEDStates(0, 0, 0); -+ if (!IsPresent()) -+ return; + if (!IsPresent()) + return; +- m_pdSingleton->PacLed64SetLEDStates(m_index, 0, 0); ++ // Taken before the zeros, so they confirm the closing that was published when the updater ended. ++ OutputGate::Snapshot finalGate {}; ++ if (m_gateUnit) ++ finalGate = m_gateUnit->Observe(); + if (!m_pdSingleton->PacLed64SetLEDStates(m_index, 0, 0)) + throw std::runtime_error("PacUIO: turning the outputs off failed"); ++ if (m_gateUnit && !finalGate.open) ++ m_gateUnit->Ack(finalGate); std::fill_n(m_lastStateSent, 96, false); } -@@ -393,24 +424,19 @@ bool PacUIO::PacUIOUnit::IsPresent() +@@ -366,24 +449,19 @@ bool PacUIO::PacUIOUnit::IsPresent() return m_index >= 0; } @@ -3269,7 +3882,7 @@ index 314ea83..fb7ab81 100644 } \ No newline at end of file diff --git a/src/cab/out/pac/PacUIO.h b/src/cab/out/pac/PacUIO.h -index 0da2310..cb2591d 100644 +index 0da2310..60f089b 100644 --- a/src/cab/out/pac/PacUIO.h +++ b/src/cab/out/pac/PacUIO.h @@ -1,6 +1,7 @@ @@ -3297,37 +3910,35 @@ index 0da2310..cb2591d 100644 std::mutex m_pacUIOUpdateLocker; std::mutex m_valueChangeLocker; -@@ -82,9 +86,9 @@ private: +@@ -82,9 +86,10 @@ private: private: void CopyNewToCurrent(); void PacUIOUpdaterDoIt(); - void SendPacUIOUpdate(); + // VPE: false if a latch ended an opening's update early (the gate's opening was then not sent). -+ bool SendPacUIOUpdate(bool open); ++ // Returns true once the update is sent. `failed` is set when a write failed; the next pass sends everything. ++ bool SendPacUIOUpdate(bool open, bool& failed); void ResetFadeTime(); - void InitUnit(); bool IsPresent(); void OnPacAttached(int index); diff --git a/src/cab/out/pinone/PinOne.cpp b/src/cab/out/pinone/PinOne.cpp -index b898d3f..926ed3d 100644 +index 0cce88a..cc59c9d 100644 --- a/src/cab/out/pinone/PinOne.cpp +++ b/src/cab/out/pinone/PinOne.cpp -@@ -171,21 +171,27 @@ void PinOne::UpdateOutputs(const std::vector& newOutputValues) - int lim = std::min(i + 7, GetNumberOfOutputs()); +@@ -172,7 +172,7 @@ void PinOne::UpdateOutputs(const std::vector& newOutputValues) + int lim = std::min(i + 7, count); for (int j = i; j < lim; ++j) { - if (newOutputValues[j] != m_oldOutputValues[j]) -+ if (j < static_cast(newOutputValues.size()) && j < static_cast(m_oldOutputValues.size()) -+ && (m_forceFullTransfer || newOutputValues[j] != m_oldOutputValues[j])) ++ if (m_forceFullTransfer || newOutputValues[j] != m_oldOutputValues[j]) { UpdateDelay(); std::vector buf(9); - buf[0] = 0; +@@ -180,13 +180,16 @@ void PinOne::UpdateOutputs(const std::vector& newOutputValues) buf[1] = pfx; -- std::copy(newOutputValues.begin() + i, newOutputValues.begin() + lim, buf.begin() + 2); -+ int end = std::min(lim, static_cast(newOutputValues.size())); -+ std::copy(newOutputValues.begin() + i, newOutputValues.begin() + end, buf.begin() + 2); + std::copy(newOutputValues.begin() + i, newOutputValues.begin() + lim, buf.begin() + 2); + // VPE: the cache only learns what the device got. if (m_comPort == HidSentinel) @@ -3341,11 +3952,10 @@ index b898d3f..926ed3d 100644 m_pinOneCommunication->Write(buf); + else + throw std::runtime_error(StringExtensions::Build("{0} {1} is not connected", "PinOne", GetName())); -+ lim = end; std::copy(newOutputValues.begin() + i, newOutputValues.begin() + lim, m_oldOutputValues.begin() + i); break; -@@ -238,15 +244,9 @@ void PinOne::ConnectToController() +@@ -239,15 +242,9 @@ void PinOne::ConnectToController() m_pinOneCommunication = new PinOneCommunication(m_comPort); if (!m_pinOneCommunication->ConnectToServer()) { @@ -3797,7 +4407,7 @@ index 0536494..4fa07c7 100644 \ No newline at end of file +} diff --git a/src/cab/out/ps/Pinscape.cpp b/src/cab/out/ps/Pinscape.cpp -index 698dccc..9da61b7 100644 +index 698dccc..4cf24b0 100644 --- a/src/cab/out/ps/Pinscape.cpp +++ b/src/cab/out/ps/Pinscape.cpp @@ -75,7 +75,16 @@ void Pinscape::SetNumber(int value) @@ -3818,13 +4428,33 @@ index 698dccc..9da61b7 100644 void Pinscape::SetMinCommandIntervalMs(int value) { -@@ -113,7 +122,10 @@ void Pinscape::ConnectToController() { } +@@ -101,19 +110,22 @@ void Pinscape::Init(Cabinet* cabinet) + OutputControllerFlexCompleteBase::Init(cabinet); + } + +-void Pinscape::Finish() +-{ +- if (m_dev) +- m_dev->AllOff(); +- OutputControllerFlexCompleteBase::Finish(); +-} ++// VPE: the all-off goes out on the updater's way out (DisconnectFromController), after its last transfer and checked; ++// a failure reaches the caller through the base class once the updater has ended. ++void Pinscape::Finish() { OutputControllerFlexCompleteBase::Finish(); } + + void Pinscape::ConnectToController() { } + void Pinscape::DisconnectFromController() { - if (m_dev && m_inUseState == InUseState::Running) +- if (m_dev && m_inUseState == InUseState::Running) +- m_dev->AllOff(); ++ // VPE: also for a controller DOF never used, whose blackout is the only update it gets at the end of the session. ++ if (m_dev) + { - m_dev->AllOff(); + m_cacheInvalid = true; ++ if (!m_dev->AllOff()) ++ throw std::runtime_error(StringExtensions::Build("{0} could not turn its outputs off", GetName())); ++ m_disconnectSentZeros = true; + } } @@ -3874,10 +4504,28 @@ index 698dccc..9da61b7 100644 } void Pinscape::UpdateDelay() +@@ -349,7 +372,7 @@ bool Pinscape::Device::ReadUSB(uint8_t* pBuf) + return true; + } + +-void Pinscape::Device::AllOff() { SpecialRequest(0x05); } ++bool Pinscape::Device::AllOff() { return SpecialRequest(0x05); } + + bool Pinscape::Device::SpecialRequest(uint8_t id) + { diff --git a/src/cab/out/ps/Pinscape.h b/src/cab/out/ps/Pinscape.h -index ee1ca84..fa6fbb8 100644 +index ee1ca84..8b7a11e 100644 --- a/src/cab/out/ps/Pinscape.h +++ b/src/cab/out/ps/Pinscape.h +@@ -56,7 +56,7 @@ private: + int GetNumOutputs() const { return m_numOutputs; } + bool IsLedWizEmulator(int unitNum); + bool ReadUSB(uint8_t* buf); +- void AllOff(); ++ bool AllOff(); + bool SpecialRequest(uint8_t id); + bool WriteUSB(uint8_t* buf); + void UpdateOutputs(uint8_t* NewOutputValues); @@ -79,6 +79,8 @@ private: int m_minCommandIntervalMs; bool m_minCommandIntervalMsSet; @@ -3888,36 +4536,18 @@ index ee1ca84..fa6fbb8 100644 static std::vector s_devices; Device* m_dev; diff --git a/src/cab/out/pspico/PinscapePico.cpp b/src/cab/out/pspico/PinscapePico.cpp -index 4b5ddd4..aa0f37c 100644 +index 6cdcc74..8b85dc7 100644 --- a/src/cab/out/pspico/PinscapePico.cpp +++ b/src/cab/out/pspico/PinscapePico.cpp -@@ -81,19 +81,15 @@ void PinscapePico::Init(Cabinet* cabinet) - m_minCommandIntervalMs = 0; - } - -- OutputControllerFlexCompleteBase::Init(cabinet); -+ // VPE: the device is bound before the outputs and the cache are made from its output count, and before the -+ // updater starts, which then owns the cache. - ConnectToController(); -+ OutputControllerFlexCompleteBase::Init(cabinet); - } - --void PinscapePico::Finish() --{ -- if (m_dev) -- { -- AllOff(); -- } -- DisconnectFromController(); -- OutputControllerFlexCompleteBase::Finish(); --} -+// VPE: the updater turns the outputs off and disconnects when it stops; doing it here as well raced with its last -+// transfers. -+void PinscapePico::Finish() { OutputControllerFlexCompleteBase::Finish(); } - - bool PinscapePico::VerifySettings() - { -@@ -103,13 +99,16 @@ bool PinscapePico::VerifySettings() +@@ -7,6 +7,7 @@ + #include + #include + #include ++#include + #include + #include + #include +@@ -95,13 +96,16 @@ bool PinscapePico::VerifySettings() return false; } @@ -3935,15 +4565,20 @@ index 4b5ddd4..aa0f37c 100644 for (auto device : s_devices) { -@@ -133,6 +132,7 @@ void PinscapePico::DisconnectFromController() +@@ -124,7 +128,11 @@ void PinscapePico::DisconnectFromController() + { if (m_dev) { - m_dev->AllOff(); +- m_dev->AllOff(); + m_cacheInvalid = true; ++ // VPE: the blackout is the last word for a unit DOF never used: one that did not get there is an error. ++ if (!m_dev->AllOff()) ++ throw std::runtime_error(StringExtensions::Build("Pinscape Pico {0} could not turn its outputs off", GetName())); ++ m_disconnectSentZeros = true; } } -@@ -196,7 +196,9 @@ public: +@@ -188,7 +196,9 @@ public: { for (const auto& l : list) { @@ -3954,7 +4589,7 @@ index 4b5ddd4..aa0f37c 100644 buf[0] = psp->m_dev->GetOutputReportId(); buf[1] = 0x22; buf[2] = static_cast(l.outputs.size()); -@@ -207,7 +209,8 @@ public: +@@ -199,7 +209,8 @@ public: buf[idx++] = static_cast(output.second); } @@ -3964,7 +4599,7 @@ index 4b5ddd4..aa0f37c 100644 } } -@@ -285,7 +288,8 @@ public: +@@ -277,7 +288,8 @@ public: { for (const auto& l : list) { @@ -3974,7 +4609,7 @@ index 4b5ddd4..aa0f37c 100644 buf[0] = psp->m_dev->GetOutputReportId(); buf[1] = 0x21; buf[2] = static_cast(l.numToSend); -@@ -294,7 +298,8 @@ public: +@@ -286,7 +298,8 @@ public: for (const auto& output : l.outputs) buf[idx++] = static_cast(output); @@ -3984,7 +4619,7 @@ index 4b5ddd4..aa0f37c 100644 } } -@@ -309,17 +314,21 @@ private: +@@ -301,7 +314,7 @@ private: void PinscapePico::UpdateOutputs(const std::vector& newOutputValues) { if (!m_dev) @@ -3993,15 +4628,8 @@ index 4b5ddd4..aa0f37c 100644 ContiguousOutputListGroup contiguousGroup; RandomAccessOutputListGroup randomGroup; - int firstChangedIndex = -1; - int lastChangedIndex = -1; - -- for (int i = 0; i < GetNumberOfOutputs(); ++i) -+ // VPE: the outputs were created before the device reported its port count; only the ports both know are sent. -+ if (static_cast(m_oldOutputValues.size()) < GetNumberOfOutputs()) -+ m_oldOutputValues.resize(GetNumberOfOutputs(), 255); -+ int count = std::min(GetNumberOfOutputs(), static_cast(newOutputValues.size())); -+ for (int i = 0; i < count; ++i) +@@ -314,7 +327,7 @@ void PinscapePico::UpdateOutputs(const std::vector& newOutputValues) + for (int i = 0; i < count; ++i) { int val = newOutputValues[i]; - bool changed = (newOutputValues[i] != m_oldOutputValues[i]); @@ -4009,7 +4637,7 @@ index 4b5ddd4..aa0f37c 100644 contiguousGroup.Add(i, val, changed); randomGroup.Add(i, val, changed); -@@ -332,10 +341,12 @@ void PinscapePico::UpdateOutputs(const std::vector& newOutputValues) +@@ -327,10 +340,12 @@ void PinscapePico::UpdateOutputs(const std::vector& newOutputValues) } } @@ -4022,23 +4650,28 @@ index 4b5ddd4..aa0f37c 100644 if (firstChangedIndex >= 0) { -@@ -349,6 +360,12 @@ int PinscapePico::GetNumberOfOutputs() const - { - if (m_dev) - return m_dev->NumOutputs(); -+ // VPE: before binding, the enumerated device of this unit knows its port count; auto-configuration maps that many. -+ for (auto device : s_devices) -+ { -+ if (device->UnitNo() == m_number) -+ return device->NumOutputs(); -+ } - return 128; +@@ -700,7 +715,7 @@ void PinscapePico::Device::Close() + } } +-void PinscapePico::Device::AllOff() { DeviceRequest("ALL PORTS OFF", 0x20); } ++bool PinscapePico::Device::AllOff() { return DeviceRequest("ALL PORTS OFF", 0x20); } + + bool PinscapePico::Device::DeviceRequest(const std::string& desc, uint8_t commandId) + { diff --git a/src/cab/out/pspico/PinscapePico.h b/src/cab/out/pspico/PinscapePico.h -index e78cf9c..f12a7cf 100644 +index e78cf9c..f529cc1 100644 --- a/src/cab/out/pspico/PinscapePico.h +++ b/src/cab/out/pspico/PinscapePico.h +@@ -68,7 +68,7 @@ public: + bool Open(); + uint8_t* ReadUSB(uint32_t timeoutMs); + void Close(); +- void AllOff(); ++ bool AllOff(); + bool WriteUSB(const std::string& desc, uint8_t* buf, uint32_t timeoutMs); + bool DeviceRequest(const std::string& desc, uint8_t commandId); + @@ -108,6 +108,8 @@ private: std::chrono::steady_clock::time_point m_lastUpdate; static std::vector s_devices; @@ -4049,308 +4682,6 @@ index e78cf9c..f12a7cf 100644 } \ No newline at end of file -diff --git a/src/cab/schedules/ScheduledSettings.cpp b/src/cab/schedules/ScheduledSettings.cpp -index a6d0b0d..0da2207 100644 ---- a/src/cab/schedules/ScheduledSettings.cpp -+++ b/src/cab/schedules/ScheduledSettings.cpp -@@ -89,18 +89,8 @@ ScheduledSettingDevice* ScheduledSettings::GetActiveSchedule(IOutput* currentOut - std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); - int deviceID = startingDeviceIndex + currentDeviceIndex; - -- static std::vector cacheList; -- -- static int callCount = 0; -- if (++callCount > 1000) -- { -- cacheList.clear(); -- callCount = 0; -- } -- -- if (std::find(cacheList.begin(), cacheList.end(), deviceID) != cacheList.end()) -- return nullptr; -- -+ // VPE: no cache of devices. It skipped every lookup after the first match of a device, so later outputs of that -+ // device (and values sent again after the output gate opened) went out at full strength. - for (ScheduledSetting* scheduledSetting : *this) - { - if (!scheduledSetting || !scheduledSetting->IsEnabled()) -@@ -143,8 +133,6 @@ ScheduledSettingDevice* ScheduledSettings::GetActiveSchedule(IOutput* currentOut - } - } - -- cacheList.push_back(deviceID); -- - return device; - } - } -diff --git a/src/cab/schedules/ScheduledSettings.h b/src/cab/schedules/ScheduledSettings.h -index c98d622..7d636ff 100644 ---- a/src/cab/schedules/ScheduledSettings.h -+++ b/src/cab/schedules/ScheduledSettings.h -@@ -31,13 +31,12 @@ public: - virtual tinyxml2::XMLElement* ToXml(tinyxml2::XMLDocument& doc) const override; - virtual bool FromXml(const tinyxml2::XMLElement* element) override; - virtual std::string GetXmlElementName() const override { return "ScheduledSettings"; } -+ void Clear(); - - private: - ScheduledSettings() = default; - ScheduledSettings(const ScheduledSettings&) = delete; - ScheduledSettings& operator=(const ScheduledSettings&) = delete; -- -- void Clear(); - }; - - } -\ No newline at end of file -diff --git a/src/cab/sequencer/SequentialOutputSettings.h b/src/cab/sequencer/SequentialOutputSettings.h -index 031af6b..a4a3dcb 100644 ---- a/src/cab/sequencer/SequentialOutputSettings.h -+++ b/src/cab/sequencer/SequentialOutputSettings.h -@@ -21,13 +21,12 @@ public: - virtual tinyxml2::XMLElement* ToXml(tinyxml2::XMLDocument& doc) const override; - virtual bool FromXml(const tinyxml2::XMLElement* element) override; - virtual std::string GetXmlElementName() const override { return "SequentialOutputSettings"; } -+ void Clear(); - - private: - SequentialOutputSettings() = default; - SequentialOutputSettings(const SequentialOutputSettings&) = delete; - SequentialOutputSettings& operator=(const SequentialOutputSettings&) = delete; -- -- void Clear(); - }; - - } -\ No newline at end of file -diff --git a/src/cab/toys/layer/AlphaMappingTable.cpp b/src/cab/toys/layer/AlphaMappingTable.cpp -index 84fd974..8bfca11 100644 ---- a/src/cab/toys/layer/AlphaMappingTable.cpp -+++ b/src/cab/toys/layer/AlphaMappingTable.cpp -@@ -14,7 +14,7 @@ void AlphaMappingTable::Initialize() - for (int alpha = 0; alpha < 256; alpha++) - { - for (int value = 0; value < 256; value++) -- AlphaMapping[alpha][value] = static_cast(value) / 255.0f * static_cast(alpha); -+ AlphaMapping[alpha][value] = static_cast(static_cast(value) / 255 * static_cast(alpha)); - } - - s_initialized = true; -diff --git a/src/cab/toys/layer/RGBAToy.cpp b/src/cab/toys/layer/RGBAToy.cpp -index d797b7b..daa4f5b 100644 ---- a/src/cab/toys/layer/RGBAToy.cpp -+++ b/src/cab/toys/layer/RGBAToy.cpp -@@ -4,6 +4,7 @@ - #include "../../out/IOutput.h" - #include "../../../Log.h" - #include "../../../general/StringExtensions.h" -+#include "AlphaMappingTable.h" - - #include - -@@ -37,10 +38,47 @@ void RGBAToy::Init(Cabinet* cabinet) - Reset(); - } - -+RGBColor RGBAToy::GetResultingData() -+{ -+ if (m_layers.GetLayerNumbers().size() > 0) -+ { -+ float red = 0; -+ float green = 0; -+ float blue = 0; -+ std::vector layerNumbers = m_layers.GetLayerNumbers(); -+ for (int layerNumber : layerNumbers) -+ { -+ RGBAColor* layer = m_layers.GetLayer(layerNumber, 1); -+ if (layer == nullptr) -+ continue; -+ const RGBAColor& layerColor = layer[0]; -+ int alpha = layerColor.GetAlpha(); -+ if (alpha != 0) -+ { -+ int negAlpha = 255 - alpha; -+ red = AlphaMappingTable::AlphaMapping[negAlpha][(int)red] + AlphaMappingTable::AlphaMapping[alpha][layerColor.GetRed()]; -+ green = AlphaMappingTable::AlphaMapping[negAlpha][(int)green] + AlphaMappingTable::AlphaMapping[alpha][layerColor.GetGreen()]; -+ blue = AlphaMappingTable::AlphaMapping[negAlpha][(int)blue] + AlphaMappingTable::AlphaMapping[alpha][layerColor.GetBlue()]; -+ } -+ } -+ -+ return RGBColor((int)red, (int)green, (int)blue); -+ } -+ else -+ { -+ return RGBColor(0, 0, 0); -+ } -+} -+ - void RGBAToy::Reset() - { -- m_currentColor = RGBAColor(0, 0, 0, 255); -- UpdateOutputs(); -+ m_layers.Clear(); -+ if (m_redOutput != nullptr) -+ m_redOutput->SetOutput(0); -+ if (m_greenOutput != nullptr) -+ m_greenOutput->SetOutput(0); -+ if (m_blueOutput != nullptr) -+ m_blueOutput->SetOutput(0); - } - - void RGBAToy::Finish() -@@ -49,52 +87,21 @@ void RGBAToy::Finish() - Reset(); - } - --void RGBAToy::UpdateToy() --{ -- MergeLayers(); -- -- UpdateOutputs(); --} -+void RGBAToy::UpdateToy() { UpdateOutputs(); } - - void RGBAToy::UpdateOutputs() - { -+ RGBColor rgb = GetResultingData(); -+ - if (m_redOutput != nullptr) -- m_redOutput->SetOutput(static_cast(m_currentColor.GetRed())); -+ m_redOutput->SetOutput(static_cast(rgb.GetRed())); - - if (m_greenOutput != nullptr) -- m_greenOutput->SetOutput(static_cast(m_currentColor.GetGreen())); -+ m_greenOutput->SetOutput(static_cast(rgb.GetGreen())); - - if (m_blueOutput != nullptr) -- m_blueOutput->SetOutput(static_cast(m_currentColor.GetBlue())); -+ m_blueOutput->SetOutput(static_cast(rgb.GetBlue())); - } - --void RGBAToy::MergeLayers() --{ -- m_currentColor = RGBAColor(0, 0, 0, 255); -- -- std::vector layerNumbers = m_layers.GetLayerNumbers(); -- std::sort(layerNumbers.begin(), layerNumbers.end()); -- -- for (int layerNumber : layerNumbers) -- { -- RGBAColor* layer = m_layers.GetLayer(layerNumber, 1); -- if (layer != nullptr) -- { -- const RGBAColor& layerColor = layer[0]; -- -- if (layerColor.GetAlpha() > 0) -- { -- float alpha = layerColor.GetAlpha() / 255.0f; -- float invAlpha = 1.0f - alpha; -- -- int red = static_cast(m_currentColor.GetRed() * invAlpha + layerColor.GetRed() * alpha); -- int green = static_cast(m_currentColor.GetGreen() * invAlpha + layerColor.GetGreen() * alpha); -- int blue = static_cast(m_currentColor.GetBlue() * invAlpha + layerColor.GetBlue() * alpha); -- -- m_currentColor.SetRGBA(red, green, blue, 255); -- } -- } -- } --} - - } -\ No newline at end of file -diff --git a/src/cab/toys/layer/RGBAToy.h b/src/cab/toys/layer/RGBAToy.h -index 429a6de..665726e 100644 ---- a/src/cab/toys/layer/RGBAToy.h -+++ b/src/cab/toys/layer/RGBAToy.h -@@ -5,6 +5,7 @@ - #include "../IRGBOutputToy.h" - #include "ILayerToy.h" - #include "../../../general/color/RGBAColor.h" -+#include "../../../general/color/RGBColor.h" - #include - - namespace DOF -@@ -34,7 +35,7 @@ public: - IOutput* GetGreenOutput() const { return m_greenOutput; } - IOutput* GetBlueOutput() const { return m_blueOutput; } - -- RGBAColor GetCurrentColor() const { return m_currentColor; } -+ RGBColor GetResultingData(); - - virtual const std::string& GetOutputNameBlue() const override { return m_outputNameBlue; } - virtual void SetOutputNameBlue(const std::string& name) override { m_outputNameBlue = name; } -@@ -43,12 +44,8 @@ public: - virtual const std::string& GetOutputNameRed() const override { return m_outputNameRed; } - virtual void SetOutputNameRed(const std::string& name) override { m_outputNameRed = name; } - --protected: -- void MergeLayers(); -- - private: - LayerDictionary m_layers; -- RGBAColor m_currentColor; - - std::string m_outputNameRed; - std::string m_outputNameGreen; -diff --git a/src/fx/EffectEffectBase.cpp b/src/fx/EffectEffectBase.cpp -index 973be2b..0b3ca68 100644 ---- a/src/fx/EffectEffectBase.cpp -+++ b/src/fx/EffectEffectBase.cpp -@@ -31,7 +31,9 @@ void EffectEffectBase::TriggerTargetEffect(TableElementData* triggerData) - { - try - { -- m_targetEffect->Trigger(triggerData); -+ // VPE: C# DOF passes the data by value; a copy keeps the target's changes (ValueInvertEffect) out of the caller. -+ TableElementData data = *triggerData; -+ m_targetEffect->Trigger(&data); - } - catch (const std::exception& e) - { -diff --git a/src/fx/conditionfx/TableElementConditionEffect.cpp b/src/fx/conditionfx/TableElementConditionEffect.cpp -index e28b0ab..b4e5045 100644 ---- a/src/fx/conditionfx/TableElementConditionEffect.cpp -+++ b/src/fx/conditionfx/TableElementConditionEffect.cpp -@@ -133,7 +133,8 @@ void TableElementConditionEffect::UpdateVariableValues() - - if (StringExtensions::StartsWith(varName, "NamedElement_")) - { -- std::string elementName = varName.substr(13); -+ // VPE: element names are stored upper case. -+ std::string elementName = StringExtensions::ToUpper(varName.substr(13)); - - for (TableElement* element : *tableElements) - { -diff --git a/src/fx/matrixfx/RGBAMatrixColorScaleShapeEffect.cpp b/src/fx/matrixfx/RGBAMatrixColorScaleShapeEffect.cpp -index 1da6c1a..82cb7ce 100644 ---- a/src/fx/matrixfx/RGBAMatrixColorScaleShapeEffect.cpp -+++ b/src/fx/matrixfx/RGBAMatrixColorScaleShapeEffect.cpp -@@ -109,7 +109,9 @@ void RGBAMatrixColorScaleShapeEffect::Trigger(TableElementData* tableElementData - { - if (m_targetEffect != nullptr) - { -- m_targetEffect->Trigger(tableElementData); -+ // VPE: pass a copy, as C# DOF passes the data by value. -+ TableElementData data = *tableElementData; -+ m_targetEffect->Trigger(&data); - } - } - -diff --git a/src/fx/matrixfx/RGBAMatrixShapeEffect.cpp b/src/fx/matrixfx/RGBAMatrixShapeEffect.cpp -index d30e7f2..8716f8a 100644 ---- a/src/fx/matrixfx/RGBAMatrixShapeEffect.cpp -+++ b/src/fx/matrixfx/RGBAMatrixShapeEffect.cpp -@@ -104,7 +104,9 @@ void RGBAMatrixShapeEffect::Trigger(TableElementData* tableElementData) - { - if (m_targetEffect != nullptr) - { -- m_targetEffect->Trigger(tableElementData); -+ // VPE: pass a copy, as C# DOF passes the data by value. -+ TableElementData data = *tableElementData; -+ m_targetEffect->Trigger(&data); - } - } - diff --git a/src/fx/matrixfx/bitmapshapes/ShapeDefinitions.cpp b/src/fx/matrixfx/bitmapshapes/ShapeDefinitions.cpp index 303936f..afd013f 100644 --- a/src/fx/matrixfx/bitmapshapes/ShapeDefinitions.cpp @@ -4499,10 +4830,10 @@ index b6baeda..6b7ca12 100644 diff --git a/src/general/PathConfinement.cpp b/src/general/PathConfinement.cpp new file mode 100644 -index 0000000..4c48ae9 +index 0000000..be98f3c --- /dev/null +++ b/src/general/PathConfinement.cpp -@@ -0,0 +1,146 @@ +@@ -0,0 +1,155 @@ +#include "PathConfinement.h" + +#include @@ -4522,9 +4853,11 @@ index 0000000..4c48ae9 +{ + // A root was given. Without one every path is allowed (upstream behavior). + bool set = false; -+ // The root resolved; if it did not, nothing is allowed. ++ // The root resolved; until it does, nothing is allowed. + bool valid = false; + fs::path path; ++ // As given, so that a root that did not resolve (a folder not created yet) is looked up again on the next access. ++ std::string given; +}; + +std::mutex s_mutex; @@ -4538,6 +4871,7 @@ index 0000000..4c48ae9 + if (root.empty()) + return r; + r.set = true; ++ r.given = root; + std::error_code ec; + fs::path canonical = fs::canonical(fs::path(root), ec); + if (!ec && !canonical.empty()) @@ -4551,8 +4885,14 @@ index 0000000..4c48ae9 +Root CurrentRoot() +{ + if (t_hasRoot) ++ { ++ if (t_root.set && !t_root.valid) ++ t_root = MakeRoot(t_root.given); + return t_root; ++ } + std::lock_guard lock(s_mutex); ++ if (s_root.set && !s_root.valid) ++ s_root = MakeRoot(s_root.given); + return s_root; +} + @@ -4651,7 +4991,7 @@ index 0000000..4c48ae9 +} diff --git a/src/general/PathConfinement.h b/src/general/PathConfinement.h new file mode 100644 -index 0000000..9319509 +index 0000000..00a6e77 --- /dev/null +++ b/src/general/PathConfinement.h @@ -0,0 +1,34 @@ @@ -4668,7 +5008,7 @@ index 0000000..9319509 +{ +public: + // Folder that reads are limited to. Empty allows every path (upstream behavior); writes and deletions are always -+ // refused while a root is set. A root that does not resolve allows nothing. ++ // refused while a root is set. A root that does not resolve allows nothing, and is looked up again on every access. + static void SetRoot(const std::string& root); + static bool HasRoot(); + // Whether the path, with its symbolic links and dot components resolved, lies inside the root. Any error denies. @@ -4708,19 +5048,6 @@ index 6c25106..51d74de 100644 std::ofstream ofs; ofs.exceptions(std::ios::failbit | std::ios::badbit); ofs.open(filename, append ? (std::ios::out | std::ios::app) : std::ios::out); -diff --git a/src/general/analog/AnalogAlpha.cpp b/src/general/analog/AnalogAlpha.cpp -index 83f83be..5ce32e2 100644 ---- a/src/general/analog/AnalogAlpha.cpp -+++ b/src/general/analog/AnalogAlpha.cpp -@@ -5,7 +5,7 @@ namespace DOF - - AnalogAlpha::AnalogAlpha() - : m_value(0) -- , m_alpha(255) -+ , m_alpha(0) - { - } - diff --git a/src/general/bitmap/Image.cpp b/src/general/bitmap/Image.cpp index 023ce64..c2f72fd 100644 --- a/src/general/bitmap/Image.cpp @@ -4741,7 +5068,7 @@ index 023ce64..c2f72fd 100644 if (!file) { diff --git a/src/globalconfiguration/GlobalConfig.cpp b/src/globalconfiguration/GlobalConfig.cpp -index 96ea59f..e17eab8 100644 +index 96ea59f..f55b488 100644 --- a/src/globalconfiguration/GlobalConfig.cpp +++ b/src/globalconfiguration/GlobalConfig.cpp @@ -6,9 +6,11 @@ @@ -4787,167 +5114,17 @@ index 96ea59f..e17eab8 100644 return nullptr; } -diff --git a/src/ledcontrol/setup/Configurator.cpp b/src/ledcontrol/setup/Configurator.cpp -index 778587c..9ffb994 100644 ---- a/src/ledcontrol/setup/Configurator.cpp -+++ b/src/ledcontrol/setup/Configurator.cpp -@@ -36,6 +36,7 @@ - #include "../../fx/timmedfx/DelayEffect.h" - #include "../../fx/timmedfx/FadeEffect.h" - #include "../../fx/valuefx/ValueInvertEffect.h" -+#include "../../fx/conditionfx/TableElementConditionEffect.h" - #include "../../fx/valuefx/ValueMapFullRangeEffect.h" - #include "../../fx/matrixfx/RGBAMatrixColorEffect.h" - #include "../../fx/matrixfx/RGBAMatrixFlickerEffect.h" -@@ -859,6 +860,8 @@ void Configurator::SetupTable( - "Ledwiz {0:00} Column {1:00} Setting {2:00} AnalogToyValueEffect", std::to_string(ledWizNr), std::to_string(tcc->GetNumber()), std::to_string(settingNumber)); - analogEffect->SetName(effectName); - analogEffect->SetToyName(toy->GetName()); -+ int layer = tcs->HasLayer() ? tcs->GetLayer() : settingNumber; -+ analogEffect->SetLayerNr(layer); - - AnalogAlpha activeValue(MathExtensions::Limit(tcs->GetIntensity(), 0, 255), 255); - AnalogAlpha inactiveValue = activeValue; -@@ -1060,9 +1063,16 @@ void Configurator::SetupTable( - break; - case OutputControlEnum::Condition: - { -- std::vector tableElementDescriptors; -- tableElementDescriptors.push_back(StringExtensions::Build("{0}.{1}.{2}", std::to_string(ledWizNr), std::to_string(tcc->GetNumber()), std::to_string(settingNumber))); -- AssignEffectToTableElements(table, tableElementDescriptors, finalEffect); -+ // VPE: as C# DOF, the condition becomes an effect in front of the chain, triggered by every table -+ // element the condition reads. -+ TableElementConditionEffect* conditionEffect = new TableElementConditionEffect(); -+ conditionEffect->SetName(StringExtensions::Build("Ledwiz {0:00} Column {1:00} Setting {2:00} TableElementConditionEffect", -+ std::to_string(ledWizNr), std::to_string(tcc->GetNumber()), std::to_string(settingNumber))); -+ conditionEffect->SetTargetEffectName(finalEffect->GetName()); -+ conditionEffect->SetCondition(tcs->GetCondition()); -+ MakeEffectNameUnique(conditionEffect, table); -+ table->GetEffects()->insert(std::make_pair(conditionEffect->GetName(), conditionEffect)); -+ AssignEffectToTableElements(table, conditionEffect->GetVariables(), conditionEffect); - } - break; - case OutputControlEnum::FixedOff: -@@ -1123,12 +1133,14 @@ void Configurator::AssignEffectToTableElements(Table* table, const std::vectorUpdateState(&elementData); - - for (TableElement* te : *tableElements) - { -- if (te->GetName() == elementName) -+ // VPE: element names are stored upper case. -+ if (te->GetName() == StringExtensions::ToUpper(elementName)) - { - tableElement = te; - break; -diff --git a/src/pinballsupport/AlarmHandler.cpp b/src/pinballsupport/AlarmHandler.cpp -index a9afb5a..5b6d3c8 100644 ---- a/src/pinballsupport/AlarmHandler.cpp -+++ b/src/pinballsupport/AlarmHandler.cpp -@@ -113,7 +113,7 @@ void AlarmHandler::RegisterIntervalAlarm(int intervalMs, AlarmCallback intervalA - std::lock_guard lock(m_intervalAlarmMutex); - - UnregisterIntervalAlarm(intervalAlarmHandler); -- m_intervalAlarmList.emplace_back(intervalMs, intervalAlarmHandler); -+ m_intervalAlarmList.emplace_back(intervalMs, intervalAlarmHandler, m_nextIntervalAlarmId++); - } - - void AlarmHandler::UnregisterIntervalAlarm(AlarmCallback intervalAlarmHandler) -@@ -152,17 +152,17 @@ AlarmHandler::TimePoint AlarmHandler::GetNextIntervalAlarm() - bool AlarmHandler::ProcessIntervalAlarms(TimePoint alarmTime) - { - std::vector toExecute; -- std::vector toUpdateIndices; -+ std::vector toUpdate; - - { - std::lock_guard lock(m_intervalAlarmMutex); - -- for (size_t i = 0; i < m_intervalAlarmList.size(); ++i) -+ for (const IntervalAlarmSetting& intervalAlarm : m_intervalAlarmList) - { -- if (m_intervalAlarmList[i].nextAlarm <= alarmTime) -+ if (intervalAlarm.nextAlarm <= alarmTime) - { -- toExecute.push_back(m_intervalAlarmList[i].intervalAlarmHandler); -- toUpdateIndices.push_back(i); -+ toExecute.push_back(intervalAlarm.intervalAlarmHandler); -+ toUpdate.push_back(intervalAlarm.id); - } - } - } -@@ -183,20 +183,16 @@ bool AlarmHandler::ProcessIntervalAlarms(TimePoint alarmTime) - { - std::lock_guard lock(m_intervalAlarmMutex); - -- for (size_t i : toUpdateIndices) -+ // As C# DOF: advance the registrations that fired. A handler that unregistered or re-registered itself during -+ // its call has a new registration (or none), which keeps the schedule it was given. -+ for (IntervalAlarmSetting& intervalAlarm : m_intervalAlarmList) - { -- if (i < m_intervalAlarmList.size()) -- { -- auto& intervalAlarm = m_intervalAlarmList[i]; -- if (intervalAlarm.nextAlarm + std::chrono::milliseconds(intervalAlarm.intervalMs) <= alarmTime) -- { -- intervalAlarm.nextAlarm = alarmTime + std::chrono::milliseconds(1); -- } -- else -- { -- intervalAlarm.nextAlarm = intervalAlarm.nextAlarm + std::chrono::milliseconds(intervalAlarm.intervalMs); -- } -- } -+ if (std::find(toUpdate.begin(), toUpdate.end(), intervalAlarm.id) == toUpdate.end()) -+ continue; -+ if (intervalAlarm.nextAlarm + std::chrono::milliseconds(intervalAlarm.intervalMs) <= alarmTime) -+ intervalAlarm.nextAlarm = alarmTime + std::chrono::milliseconds(1); -+ else -+ intervalAlarm.nextAlarm = intervalAlarm.nextAlarm + std::chrono::milliseconds(intervalAlarm.intervalMs); - } - } - -diff --git a/src/pinballsupport/AlarmHandler.h b/src/pinballsupport/AlarmHandler.h -index a21e29e..6cf343b 100644 ---- a/src/pinballsupport/AlarmHandler.h -+++ b/src/pinballsupport/AlarmHandler.h -@@ -1,5 +1,7 @@ - #pragma once +@@ -388,6 +395,10 @@ void GlobalConfig::SaveGlobalConfig(const std::string& globalConfigFilename) + if (StringExtensions::IsNullOrWhiteSpace(gcFileName)) + throw std::runtime_error("No filename for GlobalConfig file has been supplied. Looking up the filename from the property GlobalConfigFilename failed as well"); -+#include ++ // VPE: the backup below is a write too. ++ if (!PathConfinement::IsWriteAllowed(gcFileName)) ++ return; + - #include "DOF/DOF.h" - #include "Action.h" - #include -@@ -73,11 +75,14 @@ private: - int intervalMs; - TimePoint nextAlarm; - AlarmCallback intervalAlarmHandler; -+ // VPE: identifies the registration, so a handler that re-registers itself is not advanced twice. -+ uint64_t id; - -- IntervalAlarmSetting(int interval, AlarmCallback handler) -+ IntervalAlarmSetting(int interval, AlarmCallback handler, uint64_t registration) - : intervalMs(interval) -- , intervalAlarmHandler(handler) - , nextAlarm(std::chrono::steady_clock::now() + std::chrono::milliseconds(interval)) -+ , intervalAlarmHandler(handler) -+ , id(registration) - { - } - }; -@@ -86,6 +91,7 @@ private: - std::recursive_mutex m_intervalAlarmMutex; - std::vector m_alarmList; - std::vector m_intervalAlarmList; -+ uint64_t m_nextIntervalAlarmId = 1; - - TimePoint GetNextAlarm(); - TimePoint GetNextIntervalAlarm(); + if (FileInfo(gcFileName).Exists()) + { + auto now = std::chrono::system_clock::now(); diff --git a/src/table/Table.cpp b/src/table/Table.cpp index d6d677d..989bffa 100644 --- a/src/table/Table.cpp @@ -4967,40 +5144,3 @@ index d6d677d..989bffa 100644 std::string xml = ToXml(); std::ofstream file(filename); if (file.is_open()) -diff --git a/src/table/TableElementList.cpp b/src/table/TableElementList.cpp -index 425eb08..449f6a3 100644 ---- a/src/table/TableElementList.cpp -+++ b/src/table/TableElementList.cpp -@@ -39,9 +39,11 @@ void TableElementList::UpdateState(TableElementData* data) - - if (!data->m_name.empty()) - { -+ // VPE: element names are stored upper case. -+ std::string name = StringExtensions::ToUpper(data->m_name); - for (TableElement* element : *this) - { -- if (element && element->GetName() == data->m_name) -+ if (element && element->GetName() == name) - { - targetElement = element; - break; -@@ -49,7 +51,9 @@ void TableElementList::UpdateState(TableElementData* data) - } - } - -- if (!targetElement) -+ // VPE: a named element is found by its name only, and created with it. Upstream fell back to the type and number -+ // lookup and created a nameless element, so $name conditions and effects never found their element. -+ if (!targetElement && data->m_name.empty()) - { - for (TableElement* element : *this) - { -@@ -63,6 +67,8 @@ void TableElementList::UpdateState(TableElementData* data) - - if (targetElement) - targetElement->SetValue(data->m_value); -+ else if (!data->m_name.empty()) -+ push_back(new TableElement(data->m_name, data->m_value)); - else - { - TableElement* newElement = new TableElement(data->m_tableElementType, data->m_number, data->m_value); diff --git a/native/release-check.py b/native/release-check.py index 4db9dcf..402a2f0 100644 --- a/native/release-check.py +++ b/native/release-check.py @@ -11,6 +11,8 @@ another package's copies. On macOS each architecture is checked. - It imports only libraries of the operating system: no C/C++ runtime DLLs on Windows (static CRT), no libstdc++ or libgcc_s on Linux (linked statically), only libSystem, libc++, libobjc and system frameworks on macOS. +- Its vpe_dof_abi_version returns the VPE_DOF_ABI_VERSION of the header, so a library built from older sources with the + same exports does not pass. The library is loaded for that: run the check on the platform it is built for. - Linux: the newest glibc symbol version it needs (--max-glibc fails above that). macOS: the architectures it contains (--archs) and the minimum macOS version of each (--min-macos fails above that). - --unity-meta: the library has its Unity import settings next to it, and its folder too, as native/unity has them @@ -23,6 +25,7 @@ """ import argparse +import ctypes import fnmatch import os import re @@ -61,6 +64,32 @@ def declared_functions(header): return set(re.findall(r"^VPE_DOF_API\b[^;(]*?\b(vpe_dof_\w+)\s*\(", text, re.MULTILINE)) +def header_abi_version(header): + with open(header, encoding="utf-8") as file: + match = re.search(r"^#define\s+VPE_DOF_ABI_VERSION\s+(\d+)", file.read(), re.MULTILINE) + return int(match.group(1)) if match else None + + +# The platform that can load a library of each kind. +LOADERS = {"PE": "win32", "ELF": "linux", "Mach-O": "darwin"} + + +def check_abi_version(library, kind, header): + expected = header_abi_version(header) + if expected is None: + return [("{} defines no VPE_DOF_ABI_VERSION".format(header), False)] + if not sys.platform.startswith(LOADERS[kind]): + return [("cannot load a {} library on {} to check its ABI version".format(kind, sys.platform), False)] + try: + function = ctypes.CDLL(os.path.abspath(library)).vpe_dof_abi_version + except (OSError, AttributeError) as error: + return [("cannot call vpe_dof_abi_version: {}".format(error), False)] + function.restype = ctypes.c_int32 + function.argtypes = [] + version = function() + return [("ABI version {} (the header's is {})".format(version, expected), version == expected)] + + def nm_symbol(line): """The name of a symbol line of nm ("
"); None for headings and other lines.""" fields = line.split() @@ -217,6 +246,7 @@ def main(): return 1 exports, imports, bad_imports, notes = check(args.library, args) + notes += check_abi_version(args.library, kind, args.header) if args.unity_meta: notes += check_unity_meta(args.library) declared = declared_functions(args.header) diff --git a/native/src/vpe_dof.cpp b/native/src/vpe_dof.cpp index 7dd0da0..c20c9af 100644 --- a/native/src/vpe_dof.cpp +++ b/native/src/vpe_dof.cpp @@ -558,7 +558,7 @@ VPE_DOF_API int64_t VPE_DOF_CALL vpe_dof_latch_output_gate(vpe_dof* dof) } } -VPE_DOF_API int32_t VPE_DOF_CALL vpe_dof_gate_state(vpe_dof* dof, int64_t generation, int32_t* confirmed, int32_t* pending, int32_t* failed) +VPE_DOF_API int32_t VPE_DOF_CALL vpe_dof_gate_state(vpe_dof* dof, int64_t generation, int32_t* confirmed, int32_t* pending, int32_t* failed, int32_t* untouched) { if (confirmed) *confirmed = 0; @@ -566,19 +566,23 @@ VPE_DOF_API int32_t VPE_DOF_CALL vpe_dof_gate_state(vpe_dof* dof, int64_t genera *pending = 0; if (failed) *failed = 0; + if (untouched) + *untouched = 0; if (!dof || generation < 0) return 0; try { DOF::OutputGate& gate = DOF::OutputGate::Instance(); - int c = 0, p = 0, f = 0; - DOF::OutputGate::Status status = gate.GetState(generation, c, p, f); + DOF::OutputGate::Counts counts; + DOF::OutputGate::Status status = gate.GetState(generation, counts); if (confirmed) - *confirmed = c; + *confirmed = counts.confirmed; if (pending) - *pending = p; + *pending = counts.pending; if (failed) - *failed = f; + *failed = counts.failed; + if (untouched) + *untouched = counts.untouched; switch (status) { case DOF::OutputGate::Status::Applied: return 1; diff --git a/native/tests/internal.cpp b/native/tests/internal.cpp new file mode 100644 index 0000000..87ffab6 --- /dev/null +++ b/native/tests/internal.cpp @@ -0,0 +1,463 @@ +// Visual Pinball Engine +// Copyright (C) 2026 freezy and VPE Team +// +// SPDX-License-Identifier: GPL-3.0-or-later + +// Tests of libdof's internals that no configuration reaches through the C ABI: effects that were never started, a toy +// that fails while an effect starts, schedules, the order of host commands and input, and the output gate's +// accounting, with the steps other threads can come between run one at a time. Exits non-zero if a check fails; a crash is a failure too. + +#include +#include +#include +#include +#include +#include + +#include "Pinball.h" +#include "cab/Cabinet.h" +#include "cab/out/Output.h" +#include "cab/out/OutputGate.h" +#include "cab/schedules/ScheduledSettings.h" +#include "cab/toys/IMatrixToy.h" +#include "cab/toys/ToyList.h" +#include "fx/EffectBase.h" +#include "fx/EffectList.h" +#include "fx/matrixfx/RGBAMatrixShiftEffect.h" +#include "fx/timmedfx/DelayEffect.h" +#include "general/color/RGBAColor.h" +#include "pinballsupport/InputQueue.h" +#include "table/Table.h" +#include "table/TableElementData.h" + +using namespace DOF; + +namespace DOF +{ + +// Runs the steps of the gate that other threads can come between, one at a time. +class OutputGateTestAccess +{ +public: + // Request, with a latch on another thread between reserving the generation and recording it. + static int64_t RequestWithLatchInBetween(OutputGate& gate, bool open, int64_t& latch) + { + std::lock_guard lock(gate.m_mutex); + bool latched; + int64_t generation = gate.Reserve(latched); + latch = gate.Latch(); + gate.Record(generation, open && !latched, false); + return generation; + } + + static int64_t BeginLatch(OutputGate& gate) { return gate.BeginLatch(); } + static void FinishLatch(OutputGate& gate, int64_t generation) { gate.FinishLatch(generation); } + static int64_t LatchGeneration(const OutputGate& gate) { return gate.m_latchGeneration.load(); } +}; + +// Queues host commands the way Pinball::Post does and takes the main thread's work one item at a time. +class PinballTestAccess +{ +public: + static void Post(Pinball& pinball) + { + std::lock_guard lock(pinball.m_mainThreadMutex); + pinball.m_commands.push_back({ pinball.m_inputQueue->Count(), [] { } }); + } + + // 'C' for a command, 'I' for input, '-' for nothing. + static std::string Take(Pinball& pinball, int count) + { + std::string order; + for (int i = 0; i < count; i++) + { + std::function command; + TableElementData data; + Pinball::Work work = pinball.TakeWork(false, command, data); + order += work == Pinball::Work::Command ? 'C' : work == Pinball::Work::Input ? 'I' : '-'; + } + return order; + } +}; + +} + +static int failures = 0; + +#define CHECK(condition, message) \ + do \ + { \ + if (!(condition)) \ + { \ + std::fprintf(stderr, "FAIL: %s\n", message); \ + failures++; \ + } \ + } while (0) + +namespace +{ + +// A matrix toy that cannot give a layer, as one whose layer does not fit in memory. +class FailingMatrix : public IMatrixToy +{ +public: + void Init(Cabinet*) override { } + void Reset() override { } + void Finish() override { } + RGBAColor* GetLayer(int) override { throw std::runtime_error("no layer"); } + int GetHeight() const override { return 1; } + int GetWidth() const override { return 1; } + RGBAColor GetElement(int, int, int) override { return RGBAColor(); } + void SetElement(int, int, int, const RGBAColor&) override { } +}; + +// A table whose start failed before it started its effects (a cabinet that failed to start) deletes them unstarted. +void EffectsThatNeverStartedAreNotFinished() +{ + Table* table = new Table(); + DelayEffect* delay = new DelayEffect(); + delay->SetName("delay"); + table->GetEffects()->Add(delay); + delete table; + + EffectList* effects = new EffectList(); + DelayEffect* other = new DelayEffect(); + other->SetName("delay"); + effects->Add(other); + effects->Finish(); + delete effects; +} + +// An effect whose toy fails while it starts is finished with the table, which it has to know by then. +void MatrixEffectWhoseToyFailsIsFinished() +{ + Pinball pinball; + FailingMatrix* toy = new FailingMatrix(); + toy->SetName("matrix"); + pinball.GetCabinet()->GetToys()->AddToy(toy); + + Table table; + RGBAMatrixShiftEffect* shift = new RGBAMatrixShiftEffect(); + shift->SetName("shift"); + shift->SetToyName("matrix"); + table.GetEffects()->Add(static_cast(shift)); + + bool failed = false; + try + { + table.Init(&pinball); + } + catch (const std::exception&) + { + failed = true; + } + CHECK(failed, "the effect whose toy fails does not start"); + table.Finish(); +} + +void UntouchedUnitsAreCountedApart() +{ + OutputGate& gate = OutputGate::Instance(); + gate.BeginSession(); + OutputGate::Unit* used = gate.Register("used"); + OutputGate::Unit* unused = gate.Register("unused"); + + int64_t open = gate.Request(true); + CHECK(gate.Apply(true), "the gate opens"); + gate.Publish(open); + OutputGate::Snapshot snapshot = gate.Current(); + used->Ack(snapshot); + unused->Untouched(snapshot); + OutputGate::Counts counts; + CHECK(gate.GetState(open, counts) == OutputGate::Status::Applied, "the opening is applied"); + CHECK(counts.confirmed == 1 && counts.untouched == 1 && counts.pending == 0 && counts.failed == 0, "a unit DOF leaves alone is untouched, not confirmed"); + CHECK(gate.GetPending(open).empty(), "an untouched unit is not pending"); + + int64_t closed = gate.Request(false); + gate.Apply(false); + gate.Publish(closed); + snapshot = gate.Current(); + used->Ack(snapshot); + unused->Untouched(snapshot); + CHECK(gate.GetState(closed, counts) == OutputGate::Status::Applied, "the closing is applied"); + CHECK(counts.confirmed == 1 && counts.untouched == 0 && counts.pending == 1, "a closing goes to every unit"); + std::vector pending = gate.GetPending(closed); + CHECK(pending.size() == 1 && pending[0] == "unused", "the unused unit has to write the closing"); +} + +void LatchOvertakesAQueuedOpening() +{ + OutputGate& gate = OutputGate::Instance(); + gate.BeginSession(); + OutputGate::Unit* unit = gate.Register("unit"); + int64_t closed = gate.Request(false); + gate.Apply(false); + gate.Publish(closed); + unit->Ack(gate.Current()); + + // The opening is queued for DOF's main thread when the latch comes; the main thread applies it afterwards. + int64_t open = gate.Request(true); + int64_t latched = gate.Latch(); + CHECK(latched > open, "the latch gets a later generation"); + CHECK(!gate.IsOpen(), "the latch closes at once"); + CHECK(!gate.Apply(true), "an opening applied after the latch is a closing"); + CHECK(!gate.IsOpen(), "and leaves the gate closed"); + gate.Publish(open); + OutputGate::Snapshot snapshot = gate.Current(); + CHECK(snapshot.generation == latched && !snapshot.open, "the overtaken opening is not published"); + + OutputGate::Counts counts; + CHECK(gate.GetState(open, counts) == OutputGate::Status::Superseded, "the overtaken opening is superseded"); + unit->Ack(snapshot); + CHECK(gate.GetState(latched, counts) == OutputGate::Status::Applied && counts.confirmed == 1, "the latch is confirmed"); + CHECK(gate.GetState(open, counts) == OutputGate::Status::Superseded, "superseded stays superseded"); + + int64_t later = gate.Request(true); + CHECK(!gate.Apply(true), "a later opening is a closing"); + gate.Publish(later); + unit->Ack(gate.Current()); + CHECK(gate.GetState(later, counts) == OutputGate::Status::Applied && counts.confirmed == 1 && counts.untouched == 0, "and confirms the closed state"); + + gate.BeginSession(); + CHECK(gate.IsOpen() && !gate.IsLatched(), "a new session is not latched"); +} + +// A command runs after the input queued before it and before the input queued after it: a closing followed by an on +// sends no on, and an off followed by an opening does not send the on that came before. +void CommandsAndInputKeepTheirOrder() +{ + Pinball pinball; + PinballTestAccess::Post(pinball); + pinball.ReceiveData('S', 1, 1); + CHECK(PinballTestAccess::Take(pinball, 3) == "CI-", "a closing followed by an on"); + + pinball.ReceiveData('S', 1, 0); + PinballTestAccess::Post(pinball); + CHECK(PinballTestAccess::Take(pinball, 3) == "IC-", "an off followed by an opening"); + + pinball.ReceiveData('S', 1, 1); + PinballTestAccess::Post(pinball); + pinball.ReceiveData('S', 1, 0); + PinballTestAccess::Post(pinball); + pinball.ReceiveData('S', 1, 1); + CHECK(PinballTestAccess::Take(pinball, 6) == "ICICI-", "interleaved"); +} + +// A schedule applies to the outputs its device lists. One that lists none changes no output, as in DOF: a 0% schedule +// would otherwise turn off the whole device. +void ScheduleAppliesToTheOutputsItLists() +{ + // Gated outputs report 0 while the gate is closed. + OutputGate::Instance().BeginSession(); + tinyxml2::XMLDocument doc; + doc.Parse( + "all daytrue00000000" + "" + "10" + "220" + ""); + ScheduledSettings& schedules = ScheduledSettings::GetInstance(); + CHECK(schedules.FromXml(doc.FirstChildElement("ScheduledSettings")) && schedules.size() == 1, "the schedule loads"); + + auto strength = [&schedules](int device, int number) { + Output output; + output.SetNumber(number); + output.SetOutput(200); + IOutput* result = schedules.GetNewRecalculatedOutput(&output, 1, device - 1); + int value = result->GetOutput(); + if (result != &output) + delete result; + return value; + }; + CHECK(strength(1, 1) == 200 && strength(1, 2) == 200, "a device without outputs keeps its strength"); + CHECK(strength(2, 2) == 0, "a listed output gets the schedule's strength"); + CHECK(strength(2, 3) == 200, "an output that is not listed keeps its strength"); + schedules.Clear(); +} + +// The names GetPending returns are the units GetState counts as pending or failed. +bool NamesAgree(int64_t generation) +{ + OutputGate::Counts counts; + OutputGate::Instance().GetState(generation, counts); + return OutputGate::Instance().GetPending(generation).size() == static_cast(counts.pending + counts.failed); +} + +void OpeningReservedBeforeALatchIsSuperseded() +{ + OutputGate& gate = OutputGate::Instance(); + gate.BeginSession(); + OutputGate::Unit* unit = gate.Register("unit"); + int64_t closed = gate.Request(false); + gate.Apply(false); + gate.Publish(closed); + unit->Ack(gate.Current()); + + int64_t latched = 0; + int64_t open = OutputGateTestAccess::RequestWithLatchInBetween(gate, true, latched); + CHECK(latched > open, "the latch comes after the opening's generation"); + CHECK(!gate.Apply(true), "the opening applies as a closing"); + gate.Publish(open); + unit->Ack(gate.Current()); + + OutputGate::Counts counts; + CHECK(gate.GetState(open, counts) == OutputGate::Status::Superseded, "the opening the latch overtook is superseded"); + CHECK(counts.confirmed == 0, "and does not claim the latch's writes"); + CHECK(gate.GetState(latched, counts) == OutputGate::Status::Applied && counts.confirmed == 1, "the latch is confirmed"); + CHECK(NamesAgree(open) && NamesAgree(latched), "names agree with the counts"); + + // The main thread publishes the opening while the latch is half done: it goes out as a closing. + gate.BeginSession(); + unit = gate.Register("unit"); + open = gate.Request(true); + latched = OutputGateTestAccess::BeginLatch(gate); + CHECK(!gate.Apply(true), "the opening applies as a closing"); + gate.Publish(open); + OutputGate::Snapshot snapshot = gate.Current(); + CHECK(snapshot.generation == open && !snapshot.open, "it is published closed"); + OutputGateTestAccess::FinishLatch(gate, latched); + unit->Ack(gate.Current()); + CHECK(gate.GetState(open, counts) == OutputGate::Status::Superseded && counts.confirmed == 0, "it is still superseded"); + CHECK(gate.GetState(latched, counts) == OutputGate::Status::Applied && counts.confirmed == 1, "the latch is confirmed"); +} + +void EarliestLatchDecides() +{ + OutputGate& gate = OutputGate::Instance(); + gate.BeginSession(); + OutputGate::Unit* unit = gate.Register("unit"); + int64_t first = OutputGateTestAccess::BeginLatch(gate); + int64_t second = OutputGateTestAccess::BeginLatch(gate); + OutputGateTestAccess::FinishLatch(gate, second); + OutputGateTestAccess::FinishLatch(gate, first); + CHECK(OutputGateTestAccess::LatchGeneration(gate) == first, "the earlier latch is the session's latch"); + unit->Ack(gate.Current()); + + OutputGate::Counts counts; + CHECK(gate.GetState(first, counts) == OutputGate::Status::Applied && counts.confirmed == 1, "the earlier latch is confirmed"); + CHECK(gate.GetState(second, counts) == OutputGate::Status::Applied && counts.confirmed == 1, "the later latch is confirmed"); + + // An opening requested between two overlapping latches: what it reports while the first is not done stays so. + gate.BeginSession(); + unit = gate.Register("unit"); + first = OutputGateTestAccess::BeginLatch(gate); + int64_t open = gate.Request(true); + CHECK(!gate.Apply(true), "the opening applies as a closing"); + gate.Publish(open); + second = OutputGateTestAccess::BeginLatch(gate); + OutputGateTestAccess::FinishLatch(gate, second); + unit->Ack(gate.Current()); + OutputGate::Status before = gate.GetState(open, counts); + CHECK(before == OutputGate::Status::Applied && counts.confirmed == 1, "the opening is a closing, confirmed"); + OutputGateTestAccess::FinishLatch(gate, first); + CHECK(gate.GetState(open, counts) == before && counts.confirmed == 1, "and stays so once the first latch is done"); + CHECK(gate.GetState(first, counts) == OutputGate::Status::Applied && counts.confirmed == 1, "the first latch is confirmed"); + + // A latch that pauses after taking its generation, while openings (one requested before it, one after) and a closing + // are applied: what they report then stays so once it is done. + gate.BeginSession(); + unit = gate.Register("unit"); + int64_t earlier = gate.Request(true); + first = OutputGateTestAccess::BeginLatch(gate); + open = gate.Request(true); + CHECK(!gate.Apply(true), "the earlier opening applies as a closing"); + gate.Publish(earlier); + CHECK(!gate.Apply(true), "the later opening applies as a closing"); + gate.Publish(open); + int64_t closed = gate.Request(false); + gate.Apply(false); + gate.Publish(closed); + unit->Ack(gate.Current()); + const int64_t changes[] = { earlier, open, closed }; + OutputGate::Status states[3]; + int confirmed[3]; + for (int i = 0; i < 3; i++) + { + states[i] = gate.GetState(changes[i], counts); + confirmed[i] = counts.confirmed; + } + CHECK(states[0] == OutputGate::Status::Superseded && confirmed[0] == 0, "the earlier opening is superseded"); + CHECK(states[1] == OutputGate::Status::Applied && confirmed[1] == 1, "the later opening is a closing, confirmed"); + OutputGateTestAccess::FinishLatch(gate, first); + for (int i = 0; i < 3; i++) + CHECK(gate.GetState(changes[i], counts) == states[i] && counts.confirmed == confirmed[i], "the paused latch changes nothing"); +} + +void PermanentFailureOutranksAnAck() +{ + OutputGate& gate = OutputGate::Instance(); + gate.BeginSession(); + OutputGate::Unit* unit = gate.Register("unit"); + int64_t closed = gate.Request(false); + gate.Apply(false); + gate.Publish(closed); + unit->Ack(gate.Current()); + OutputGate::Counts counts; + CHECK(gate.GetState(closed, counts) == OutputGate::Status::Applied && counts.confirmed == 1, "the closing is confirmed"); + + unit->Die(); + gate.GetState(closed, counts); + CHECK(counts.confirmed == 0 && counts.failed == 1, "a unit whose updater died is failed"); + std::vector pending = gate.GetPending(closed); + CHECK(pending.size() == 1 && pending[0] == "unit", "and listed"); +} + +void CleanFinishKeepsTheSettledResult() +{ + OutputGate& gate = OutputGate::Instance(); + gate.BeginSession(); + OutputGate::Unit* used = gate.Register("used"); + OutputGate::Unit* unused = gate.Register("unused"); + OutputGate::Unit* failing = gate.Register("failing"); + int64_t open = gate.Request(true); + gate.Apply(true); + gate.Publish(open); + OutputGate::Snapshot snapshot = gate.Current(); + used->Ack(snapshot); + unused->Untouched(snapshot); + failing->Untouched(snapshot); + failing->Fail(snapshot.generation); + + OutputGate::Counts counts; + gate.GetState(open, counts); + CHECK(counts.confirmed == 1 && counts.untouched == 1 && counts.failed == 1, "a unit that failed after it was left alone is failed"); + std::vector pending = gate.GetPending(open); + CHECK(pending.size() == 1 && pending[0] == "failing", "and listed"); + + used->Stop(); + unused->Stop(); + failing->Stop(); + gate.GetState(open, counts); + CHECK(counts.confirmed == 1 && counts.untouched == 1 && counts.failed == 1 && counts.pending == 0, "a clean finish keeps what was settled"); + CHECK(NamesAgree(open), "names agree with the counts"); + + int64_t closed = gate.Request(false); + gate.Apply(false); + gate.Publish(closed); + gate.GetState(closed, counts); + CHECK(counts.failed == 3, "finished units fail later generations"); + CHECK(NamesAgree(closed), "names agree with the counts"); +} + +} + +int main() +{ + EffectsThatNeverStartedAreNotFinished(); + MatrixEffectWhoseToyFailsIsFinished(); + UntouchedUnitsAreCountedApart(); + LatchOvertakesAQueuedOpening(); + OpeningReservedBeforeALatchIsSuperseded(); + EarliestLatchDecides(); + PermanentFailureOutranksAnAck(); + CleanFinishKeepsTheSettledResult(); + ScheduleAppliesToTheOutputsItLists(); + CommandsAndInputKeepTheirOrder(); + if (failures) + { + std::fprintf(stderr, "%d check(s) failed\n", failures); + return 1; + } + std::printf("ok\n"); + return 0; +} diff --git a/native/tests/smoke.c b/native/tests/smoke.c index 1c2cd3e..265ea51 100644 --- a/native/tests/smoke.c +++ b/native/tests/smoke.c @@ -10,8 +10,24 @@ #include #include +#ifdef _WIN32 +#include +#else +#include +#endif + #include "vpe_dof.h" +static void SleepMs(int ms) +{ +#ifdef _WIN32 + Sleep((DWORD)ms); +#else + struct timespec delay = { ms / 1000, (long)(ms % 1000) * 1000000L }; + nanosleep(&delay, NULL); +#endif +} + static int failures = 0; #define CHECK(condition, message) \ @@ -48,8 +64,10 @@ static void RunSession(const char* basePath, const char* table, const char* rom) int64_t closed = vpe_dof_set_output_gate(dof, 0); CHECK(closed > 0, "gate closes before init"); - int32_t confirmed, pending, failed; - CHECK(vpe_dof_gate_state(dof, closed, &confirmed, &pending, &failed) == 1, "gate applied before init"); + int32_t confirmed, pending, failed, untouched; + CHECK(vpe_dof_gate_state(dof, closed, &confirmed, &pending, &failed, &untouched) == 1, "gate applied before init"); + CHECK(confirmed == 0 && pending == 0 && failed == 0 && untouched == 0, "no units before init"); + CHECK(vpe_dof_gate_state(dof, closed, NULL, NULL, NULL, NULL) == 1, "the counts are optional"); CHECK(vpe_dof_set_connect_tests(NULL, 0) == VPE_DOF_INVALID_ARGUMENT, "connect tests need an instance"); CHECK(vpe_dof_set_connect_tests(dof, 0) == VPE_DOF_OK, "connect tests turned off before init"); @@ -68,7 +86,19 @@ static void RunSession(const char* basePath, const char* table, const char* rom) int64_t latched = vpe_dof_latch_output_gate(dof); CHECK(latched > open, "gate latches closed"); - CHECK(vpe_dof_set_output_gate(dof, 1) > latched, "an opening after the latch still gets a generation"); + int64_t after = vpe_dof_set_output_gate(dof, 1); + CHECK(after > latched, "an opening after the latch still gets a generation"); + // The opening after the latch applies as a closing: every unit writes it, none is left alone. + int32_t gateStatus = 0; + for (int i = 0; i < 400; i++) + { + gateStatus = vpe_dof_gate_state(dof, after, &confirmed, &pending, &failed, &untouched); + if (gateStatus == 1 && pending == 0) + break; + SleepMs(5); + } + CHECK(gateStatus == 1 && pending == 0, "the opening after the latch settles"); + CHECK(untouched == 0, "a closing leaves no unit untouched"); result = vpe_dof_finish(dof, error, (int32_t)sizeof(error)); CHECK(result == VPE_DOF_OK, error[0] ? error : "finish"); diff --git a/third-party/libdof b/third-party/libdof index d92f8fc..5e90261 160000 --- a/third-party/libdof +++ b/third-party/libdof @@ -1 +1 @@ -Subproject commit d92f8fc5f2709af17ba82bcc15b316a7280b7ea8 +Subproject commit 5e90261c23b211b845b286f5a7acec7d2ffccb36 From faedc2c46954e2e3bee8c780f17efb7320b987bf Mon Sep 17 00:00:00 2001 From: freezy Date: Thu, 26 Nov 2026 22:06:35 +0100 Subject: [PATCH 2/6] dof: build on upstream libdof 49b6947 and fix the gate at its causes libdof master now has confirmed transfers and strict setup, so the submodule moves to 49b6947 and the patch keeps only what upstream lacks: the output gate, path confinement, the log-file switch, the PinOne serial options, table-config removal, the Dude's Cab handle fixes and the Pico report bound. The gate is fixed once at each cause instead of per driver: - A transfer is bound to the gate state read together with the output values under the value lock, and every driver checks for a latch at its actual write point (PinOne after it holds the shared port). - A generation's outcome is recorded when it is published, and a latch reserves its generation and flag in one compare-and-swap. - Every unit registers before its first write (UMX before its connect test), and a final blackout that got through confirms the closing before the unit stops, also for a unit that died. - A Dude's Cab board keeps its handle for the session and until a new one is open, so its final blackout always has a handle. - One gate per session; Finish takes no opening once it starts, and a gate change is published even when an effect throws. - Path confinement refuses a path lexically before touching the file system, and lookups and config saves go through it. - release-check probes every slice of a universal macOS library. - A UMX device added late whose config throws is freed again. The tests now assert their preconditions, the backlog helper really leaves input queued, the session fixture stops leftover sessions, and build-windows.cmd fails when a test crashes. --- THIRD-PARTY-NOTICES.md | 2 +- .../DofInstanceTests.cs | 19 +- .../DofSessionIntegrationTests.cs | 27 +- VisualPinball.Engine.DOF/DofInstance.cs | 28 +- native/CMakeLists.txt | 2 + native/build-windows.cmd | 4 +- native/include/vpe_dof.h | 31 +- native/patches/0001-vpe-libdof.patch | 4002 +++++++---------- native/release-check.py | 35 +- native/src/vpe_dof.cpp | 24 +- native/tests/internal.cpp | 659 ++- third-party/libdof | 2 +- 12 files changed, 2335 insertions(+), 2500 deletions(-) diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index 239ee2a..b38c256 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -6,7 +6,7 @@ The complete corresponding source of every release is attached to the release as | Component | Version | Licence | Licence text | | --- | --- | --- | --- | -| [libdof](https://github.com/vpinball/libdof), C++ port of the [DirectOutput Framework](https://github.com/DirectOutput/DirectOutput), with VPE's patches (`native/patches`) | 0.5.4 (5e90261) | GPL-3.0-or-later | `third-party/libdof/LICENSE` | +| [libdof](https://github.com/vpinball/libdof), C++ port of the [DirectOutput Framework](https://github.com/DirectOutput/DirectOutput), with VPE's patches (`native/patches`) | 0.5.4 (49b6947) | GPL-3.0-or-later | `third-party/libdof/LICENSE` | | [hidapi](https://github.com/libusb/hidapi) | 0.15.0 (d6b2a97) | BSD-3-Clause (one of its three licence options, chosen here) | `third-party/hidapi/LICENSE-bsd.txt`, below | | [libusb](https://github.com/libusb/libusb) | 1.0.29 (15a7ebb) | LGPL-2.1-or-later | `third-party/libusb/COPYING` | | [libserialport](https://github.com/sigrokproject/libserialport) | 21b3dfe | LGPL-3.0-or-later | `third-party/libserialport/COPYING` | diff --git a/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs b/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs index 3441a9f..89f90f4 100644 --- a/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs +++ b/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs @@ -714,9 +714,15 @@ public void FinishDoesNotSendAnOffQueuedBeforeAnOpeningAsOn() // Finish right after the opening: the input queued before it still goes first. Backlog(dof); dof.Data('S', 1, 0); - dof.SetOutputGate(true); + var queued = dof.PendingInput; + var open = dof.SetOutputGate(true); dof.Finish(); Thread.Sleep(100); + // What the test is about: the opening came with input still queued before it, and finish applied it. + Assert.That(queued, Is.GreaterThan(0), "input was queued before the opening"); + Assert.That(open, Is.GreaterThanOrEqualTo(0), "the opening was accepted"); + var opening = dof.GetGateState(open); + Assert.That((opening.Applied, opening.Superseded), Is.EqualTo((true, false)), "finish applied the opening: " + opening); var after = _capture.Frames(unit.Universe).Skip(mark).ToList(); Assert.That(after, Is.Not.Empty, "finish sends a final frame"); Assert.That(after.All(f => f[0] == 0), Is.True, "S1 was off before the gate opened: " + string.Join(",", after.Select(f => f[0]))); @@ -776,10 +782,15 @@ public void UnusedUnitIsUntouchedWhileOpen() dof.Finish(); } + private static int _backlogNames; + + /// Queues input faster than DOF's main thread takes it, so some is still queued when this returns. private static void Backlog(DofInstance dof) { - for (var i = 0; i < 3000; i++) { - dof.Data('L', 1 + i % 64, i & 1); + // Numbered input is taken as fast as it is queued. A named element DOF does not know is added to the table, and + // every named input is looked up through all of them, so the main thread falls further behind with each one. + for (var i = 0; i < 4000; i++) { + dof.DataNamed("Backlog" + Interlocked.Increment(ref _backlogNames), 1); } } @@ -789,6 +800,8 @@ private static void WaitForInput(DofInstance dof) while (dof.PendingInput > 0 && watch.ElapsedMilliseconds < 2000) { Thread.Sleep(5); } + Assert.That(dof.PendingInput, Is.Zero, "DOF's main thread processed the queued input"); + // The last change taken from the queue is processed and sent. Thread.Sleep(100); } diff --git a/VisualPinball.Engine.DOF.Test/DofSessionIntegrationTests.cs b/VisualPinball.Engine.DOF.Test/DofSessionIntegrationTests.cs index 4ba5005..b4f42e8 100644 --- a/VisualPinball.Engine.DOF.Test/DofSessionIntegrationTests.cs +++ b/VisualPinball.Engine.DOF.Test/DofSessionIntegrationTests.cs @@ -4,6 +4,7 @@ // SPDX-License-Identifier: GPL-3.0-or-later using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; @@ -25,6 +26,9 @@ public class DofSessionIntegrationTests private ArtNetCapture _capture; private string _dir; + // Every session a test starts, so one that a failed assertion left running is stopped before the next test, + // which would otherwise find DOF's single instance busy. + private readonly List _sessions = new List(); [OneTimeSetUp] public void SetUpCapture() @@ -46,6 +50,12 @@ public void SetUp() [TearDown] public void TearDown() { + foreach (var session in _sessions) { + if (!session.StopAsync().Wait(Timeout)) { + TestContext.Out.WriteLine("A session did not stop within " + Timeout); + } + } + _sessions.Clear(); try { Directory.Delete(_dir, true); } catch (IOException) { @@ -86,12 +96,17 @@ private static DofRevisionLease Import(string dir, int universe, string row) return store.Acquire(); } - private static DofSession Session(DofRevision revision, bool waitForSnapshot = true) => new DofSession(new DofSessionOptions { - BasePath = revision.BasePath, - RomName = "vpetest_l1", - GameSession = Game, - WaitForSnapshot = waitForSnapshot, - }); + private DofSession Session(DofRevision revision, bool waitForSnapshot = true) + { + var session = new DofSession(new DofSessionOptions { + BasePath = revision.BasePath, + RomName = "vpetest_l1", + GameSession = Game, + WaitForSnapshot = waitForSnapshot, + }); + _sessions.Add(session); + return session; + } [Test] public void NamedEventsDriveNamedElementsOnly() diff --git a/VisualPinball.Engine.DOF/DofInstance.cs b/VisualPinball.Engine.DOF/DofInstance.cs index 0700b3d..a0b9675 100644 --- a/VisualPinball.Engine.DOF/DofInstance.cs +++ b/VisualPinball.Engine.DOF/DofInstance.cs @@ -12,12 +12,12 @@ namespace VisualPinball.Engine.DOF /// The state of one output gate change, from . public readonly struct DofGateState { - /// DOF's main thread has applied the change. + /// The change was published to the controllers: by DOF's main thread, or at once for a latch. public bool Applied { get; } /// - /// A later change that reached the controllers set the other state, or this is an opening that a latch overtook - /// (requested before the latch, applied after it), which never reaches them as an opening. The latest change is - /// the one to wait for. A superseded change stays superseded. + /// This is an opening that a latch overtook (requested before the latch, applied after it), which never reaches + /// the controllers as an opening, or an applied change that a later change reaching the controllers with the + /// other state replaced. The latest change is the one to wait for. A superseded change stays superseded. /// /// /// Only the latest change's counts tell what the outputs show. For an older change they are what each unit wrote @@ -217,7 +217,8 @@ public void Finish() /// Closes or opens the output gate. While closed, every output sends 0 and keeps the value effects set for when it /// opens again. Before it applies at once; afterwards it is applied by DOF's main thread and this /// returns at once. It never waits for DOF's main thread or a device, only for short internal locks. A change made - /// just before is still applied. + /// just before is still applied, after the table element changes made before it; once finish + /// started, an opening returns -1 and a closing latches the gate (). ///
/// The gate generation to pass to , or -1 while init or finish runs or after finish. public long SetOutputGate(bool open) @@ -237,13 +238,16 @@ public long SetOutputGate(bool open) /// /// Any thread, in any state until disposed: closes the output gate at once and latches it closed for the rest of /// the instance. An opening requested before the latch that DOF's main thread has not applied yet never reaches - /// the controllers as an opening and reports ; every change requested after - /// it applies as a closing and reports the closed state. When latches race, the first to start decides, and a - /// state once reported does not change when a later latch returns. The closing reaches the controllers without - /// waiting for DOF's main thread: an idle updater checks the gate every 50 ms, its polling interval, which bounds - /// how long it takes to notice; a busy one sends it after the write in progress (a PacLed64 or PacUIO drops the - /// rest of an opening's update, a UMX one the rest of the frame it is sending). Takes no lock and never allocates, so the simulation thread or a fault handler may call it. - /// Once it returned, the gate reports closed, also to an opening DOF's main thread is applying at that moment. + /// the controllers as an opening: it is not applied until DOF's main thread gets to it, then reports + /// . Every change requested after the latch applies as a closing and reports + /// the closed state. When latches race, every change requested after the first one, the other latches included, + /// is a closing, and a state once reported does not change when a later latch returns. The closing reaches the + /// controllers without waiting for DOF's main thread: an idle updater checks the gate every 50 ms, its polling + /// interval, which bounds how long it takes to notice; a busy one stops the opening's transfer before its next + /// write to the device (each report, packet, command or retry), so nothing of the opening goes out after the + /// latch returned, and then sends the closing to every output. Takes no lock and never allocates, so the + /// simulation thread or a fault handler may call it. Once it returned, the gate reports closed, also to an + /// opening DOF's main thread is applying at that moment. It never reaches a later instance's gate. /// /// The closing's generation, or -1 after . public long LatchOutputGate() diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 5a39f8d..6e41d6a 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -67,6 +67,8 @@ endif() file(GLOB_RECURSE LIBDOF_SOURCES "${LIBDOF}/src/*.cpp") list(FILTER LIBDOF_SOURCES EXCLUDE REGEX "/src/tools/") +# PinOne's named pipe server is not used by libdof (it would create and unlink a pipe under /tmp). +list(FILTER LIBDOF_SOURCES EXCLUDE REGEX "/src/cab/out/pinone/NamedPipeServer\.cpp$") list(APPEND LIBDOF_SOURCES "${LIBDOF}/third-party/include/tinyxml2/tinyxml2.cpp") # --------------------------------------------------------------------------------------------------------------------- diff --git a/native/build-windows.cmd b/native/build-windows.cmd index 4c68bcd..68db142 100644 --- a/native/build-windows.cmd +++ b/native/build-windows.cmd @@ -25,13 +25,13 @@ if "%VPE_DOF_GENERATOR%"=="" ( ) cmake --build "%BUILD%" --config %CONFIG% --parallel || exit /b 1 "%BUILD%\%CONFIG%\vpe_dof_smoke.exe" "%~dp0tests\fixtures\artnet" "%~dp0tests\fixtures\artnet\tables\smoke.vpx" vpetest > "%BUILD%\smoke.log" 2>&1 -if errorlevel 1 ( +if not "%errorlevel%"=="0" ( type "%BUILD%\smoke.log" echo The native smoke test failed. exit /b 1 ) "%BUILD%\%CONFIG%\vpe_dof_internal.exe" > "%BUILD%\internal.log" 2>&1 -if errorlevel 1 ( +if not "%errorlevel%"=="0" ( type "%BUILD%\internal.log" echo The native internal tests failed. exit /b 1 diff --git a/native/include/vpe_dof.h b/native/include/vpe_dof.h index 9371827..d08fdad 100644 --- a/native/include/vpe_dof.h +++ b/native/include/vpe_dof.h @@ -96,7 +96,9 @@ VPE_DOF_API void VPE_DOF_CALL vpe_dof_destroy(vpe_dof* dof); /// so a session can start closed; after init it runs on DOF's main thread and returns at once. Returns the gate /// generation, which vpe_dof_gate_state reports against, or -1 while init or finish runs and after finish. It never /// waits for DOF's main thread or a device; it only takes short internal locks. A change queued before finish is still -/// applied. The gate opens with every new instance; after vpe_dof_latch_output_gate a change applies as a closing. +/// applied, after the table element changes queued before it; once finish started, an opening returns -1 and a closing +/// latches the gate (vpe_dof_latch_output_gate). Every instance has a gate of its own, open when it is created; after +/// vpe_dof_latch_output_gate a change applies as a closing. VPE_DOF_API int64_t VPE_DOF_CALL vpe_dof_set_output_gate(vpe_dof* dof, int32_t open); /// Turns the controllers' connect test sequences (TestOnConnect of Wemos D1 and UMX controllers) off (allowed = 0) for /// the rest of the instance, or on again. They run only while the gate is open anyway; turned off, they do not run when @@ -106,19 +108,22 @@ VPE_DOF_API int64_t VPE_DOF_CALL vpe_dof_set_output_gate(vpe_dof* dof, int32_t o VPE_DOF_API int32_t VPE_DOF_CALL vpe_dof_set_connect_tests(vpe_dof* dof, int32_t allowed); /// Closes the output gate at once, from any thread and in any state, and latches it closed for the rest of the /// instance. An opening requested before the latch that DOF's main thread has not applied yet never reaches the -/// controllers as an opening and reports 2 (superseded); every change requested after it applies as a closing and -/// reports the closed state. When latches race, the first to start decides: every change requested after it started, -/// the other latches included, is a closing, and a result a caller saw does not change when a later latch returns. -/// The closing is published to the controllers at once and every controller's updater sends it without -/// DOF's main thread: an idle updater checks the gate every 50 ms, its polling interval, which bounds how long it takes -/// to notice; a busy one sends it after the write in progress (a PacLed64 or PacUIO drops the rest of an opening's -/// update, a UMX one the rest of the frame it is sending, and sends every line on its next update). Returns the closing's generation, or -1 if `dof` is NULL. Safe to call -/// from a realtime thread or a fault handler: it takes no lock and never allocates. Once it returned, the gate reports -/// closed to every caller, also to an opening DOF's main thread is applying at that moment. +/// controllers as an opening: it reports 0 until DOF's main thread gets to it, then 2 (superseded). Every change +/// requested after the latch applies as a closing and reports the closed state. When latches race, every change +/// requested after the first one reserved its generation, the other latches included, is a closing, and a result a +/// caller saw does not change when a later latch returns. The closing is published to the controllers at once and every +/// controller's updater sends it without DOF's main thread: an idle updater checks the gate every 50 ms, its polling +/// interval, which bounds how long it takes to notice; a busy one stops the opening's transfer before its next write to +/// the device (each report, packet, command or retry), so nothing of the opening goes out after the latch returned, and +/// then sends the closing to every output. Returns the closing's generation, or -1 if `dof` is NULL. Safe to call from a +/// realtime thread or a fault handler: it takes no lock and never allocates. Once it returned, the gate reports closed +/// to every caller, also to an opening DOF's main thread is applying at that moment. It only ever reaches this +/// instance's gate, never a later instance's. VPE_DOF_API int64_t VPE_DOF_CALL vpe_dof_latch_output_gate(vpe_dof* dof); -/// Reports a gate change: 0 until DOF's main thread applied it, then 1, or 2 (superseded) if a later change that reached -/// the controllers set the other state, or if it is an opening a latch overtook (see vpe_dof_latch_output_gate). 2 is -/// final. Also how many controller units confirmed the state: a transfer to their device carried it, or a later change +/// Reports a gate change: 0 until it was published to the controllers (by DOF's main thread; a latch publishes its own +/// closing at once), then 1, or 2 (superseded) if it is an opening a latch overtook (see vpe_dof_latch_output_gate). A 1 +/// becomes 2 once a later change that reached the controllers set the other state; 2 is final. Every change the host +/// requested is applied in turn, none is dropped, so a change reports 0 only until DOF's main thread gets to it. Also how many controller units confirmed the state: a transfer to their device carried it, or a later change /// to the same state. How many have not yet, how many failed (device missing, write failed, or the updater ended on its /// own, which outranks what it confirmed before; a unit that finished cleanly keeps what it confirmed or left alone and /// fails later changes), and how many are untouched: units DOF never used, which it leaves alone while the gate is diff --git a/native/patches/0001-vpe-libdof.patch b/native/patches/0001-vpe-libdof.patch index 01b90f2..26be847 100644 --- a/native/patches/0001-vpe-libdof.patch +++ b/native/patches/0001-vpe-libdof.patch @@ -1,8 +1,8 @@ diff --git a/src/Pinball.cpp b/src/Pinball.cpp -index fca1659..8e9771b 100644 +index 389786b..1cad703 100644 --- a/src/Pinball.cpp +++ b/src/Pinball.cpp -@@ -11,6 +11,9 @@ +@@ -12,6 +12,9 @@ #include "cab/ICabinetOwner.h" #include "cab/CabinetOwner.h" #include "cab/out/OutputControllerList.h" @@ -12,23 +12,15 @@ index fca1659..8e9771b 100644 #include "cab/overrides/TableOverrideSettings.h" #include "cab/schedules/ScheduledSettings.h" #include "cab/sequencer/SequentialOutputSettings.h" -@@ -66,12 +69,11 @@ void Pinball::Setup(const std::string& globalConfigFileName, const std::string& - { - FileInfo* globalConfigFile = new FileInfo(globalConfigFileName); - GlobalConfig* newGlobalConfig = GlobalConfig::GetGlobalConfigFromConfigXmlFile(globalConfigFile->FullName()); -+ // VPE: a global config that was named but cannot be read is an error, not a reason to use the defaults. - if (!newGlobalConfig) - { -- Log::Write("No global config file loaded"); -- globalConfigLoaded = false; -- -- newGlobalConfig = new GlobalConfig(); -+ delete globalConfigFile; -+ throw std::runtime_error("the global config " + globalConfigFileName + " could not be loaded"); - } - delete m_globalConfig; - m_globalConfig = newGlobalConfig; -@@ -95,19 +97,8 @@ void Pinball::Setup(const std::string& globalConfigFileName, const std::string& +@@ -50,6 +53,7 @@ Pinball::Pinball() + , m_inputQueue(new InputQueue()) + , m_keepMainThreadAlive(false) + , m_mainThreadDoWork(false) ++ , m_gate(&OutputGate::Instance()) + , m_cabinetOwner(nullptr) + { + } +@@ -114,19 +118,8 @@ void Pinball::Setup(const std::string& globalConfigFileName, const std::string& Log::SetFilename(m_globalConfig->GetLogFilename(!StringExtensions::IsNullOrWhiteSpace(tableFilename) ? FileInfo(tableFilename).FullName() : "", romName)); Log::SetInstrumentations(m_globalConfig->GetInstrumentation()); @@ -50,38 +42,7 @@ index fca1659..8e9771b 100644 Log::Init(m_globalConfig->IsEnableLogging()); } -@@ -175,15 +166,30 @@ void Pinball::Setup(const std::string& globalConfigFileName, const std::string& - } - catch (const std::exception& e) - { -+ // VPE: a cabinet config that cannot be used fails the setup. Falling back to AutoConfig would drive -+ // whatever hardware is connected with a configuration nobody chose. - Log::Exception(StringExtensions::Build("An exception occured when loading cabinet config file: {0} - {1}", cabinetConfigFile->FullName(), e.what())); -+ std::string name = cabinetConfigFile->FullName(); -+ delete cabinetConfigFile; -+ throw std::runtime_error(StringExtensions::Build("the cabinet config {0} could not be loaded: {1}", name, e.what())); - } - } - else - { - Log::Warning(StringExtensions::Build("Cabinet config file {0} does not exist.", cabinetConfigFile->FullName())); -+ std::string name = cabinetConfigFile->FullName(); -+ delete cabinetConfigFile; -+ throw std::runtime_error(StringExtensions::Build("the cabinet config {0} does not exist", name)); - } - delete cabinetConfigFile; - } -+ else if (!StringExtensions::IsNullOrWhiteSpace(m_globalConfig->GetCabinetConfigFilePattern().GetPattern())) -+ { -+ // VPE: a configured cabinet that matches no file fails as well. AutoConfig is only used without one. -+ std::string pattern = m_globalConfig->GetCabinetConfigFilePattern().GetPattern(); -+ Log::Warning(StringExtensions::Build("No cabinet config file matches {0}.", pattern)); -+ throw std::runtime_error(StringExtensions::Build("the cabinet config {0} does not exist", pattern)); -+ } - if (m_cabinet == nullptr) - { - Log::Write("No cabinet config file loaded. Will use AutoConfig."); -@@ -209,9 +215,10 @@ void Pinball::Setup(const std::string& globalConfigFileName, const std::string& +@@ -248,9 +241,10 @@ void Pinball::Setup(const std::string& globalConfigFileName, const std::string& Log::Write(StringExtensions::Build("Will load table config from {0}", tableConfigFile->FullName())); try { @@ -94,7 +55,7 @@ index fca1659..8e9771b 100644 delete m_table; m_table = newTable; m_table->SetTableConfigurationFilename(tableConfigFile->FullName()); -@@ -269,32 +276,6 @@ void Pinball::Setup(const std::string& globalConfigFileName, const std::string& +@@ -308,32 +302,6 @@ void Pinball::Setup(const std::string& globalConfigFileName, const std::string& c->SetEffectRGBMinDurationMs(m_globalConfig->GetLedControlMinimumRGBEffectDurationMs()); c->Setup(l, m_table, m_cabinet, romName); delete c; @@ -127,7 +88,20 @@ index fca1659..8e9771b 100644 } delete l; } -@@ -460,19 +441,23 @@ void Pinball::MainThreadDoIt() +@@ -402,6 +370,12 @@ void Pinball::Init() + + void Pinball::Finish() + { ++ // VPE: from here on the session takes no opening (SetOutputGate). Set before anything is finished, and kept: an opening ++ // accepted later would be applied by no main thread, or after the final blackout. ++ { ++ std::lock_guard lock(m_mainThreadMutex); ++ m_stopping = true; ++ } + Log::Write("Finishing framework"); + std::string errors; + bool failed = false; +@@ -499,19 +473,23 @@ void Pinball::MainThreadDoIt() bool updateRequired = false; auto start = std::chrono::steady_clock::now(); @@ -163,7 +137,7 @@ index fca1659..8e9771b 100644 } if (m_keepMainThreadAlive) -@@ -507,12 +492,12 @@ void Pinball::MainThreadDoIt() +@@ -546,12 +524,12 @@ void Pinball::MainThreadDoIt() std::unique_lock lock(m_mainThreadMutex); @@ -178,7 +152,7 @@ index fca1659..8e9771b 100644 now = std::chrono::steady_clock::now(); nextAlarm = m_alarms->GetNextAlarmTime(); -@@ -525,6 +510,89 @@ void Pinball::MainThreadDoIt() +@@ -564,6 +542,89 @@ void Pinball::MainThreadDoIt() { Log::Exception(StringExtensions::Build("An unexpected exception occured in the DirectOutput MainThread: {0}", e.what())); } @@ -268,7 +242,7 @@ index fca1659..8e9771b 100644 } void Pinball::ReceiveData(char type, int number, int value) -@@ -545,4 +613,68 @@ void Pinball::ReceiveData(const TableElementData& tableElementData) +@@ -584,4 +645,94 @@ void Pinball::ReceiveData(const TableElementData& tableElementData) MainThreadSignal(); } @@ -288,27 +262,53 @@ index fca1659..8e9771b 100644 +int64_t Pinball::SetOutputGate(bool open) +{ + std::lock_guard lock(m_mainThreadMutex); ++ if (m_stopping) ++ // A closing still goes out without the main thread, before or with the final blackout. ++ return open ? -1 : m_gate->Latch(); + if (!m_keepMainThreadAlive || !IsMainThreadActive()) + return -1; -+ int64_t generation = OutputGate::Instance().Request(open); ++ int64_t generation = m_gate->Request(open); + m_commands.push_back({ m_inputQueue->Count(), [this, open, generation]() { ApplyOutputGate(open, generation); } }); + m_mainThreadDoWork = true; + m_mainThreadCV.notify_one(); + return generation; +} + ++namespace ++{ ++ ++// Runs one step of a gate change and logs what it throws, so the other steps still run: every output is re-raised and ++// the generation is published whatever one effect, toy or controller does. ++template void RunGateStep(const char* what, Step&& step) ++{ ++ try ++ { ++ step(); ++ } ++ catch (const std::exception& e) ++ { ++ Log::Exception(StringExtensions::Build("An exception occured while applying the output gate ({0}): {1}", what, e.what())); ++ } ++ catch (...) ++ { ++ Log::Exception(StringExtensions::Build("An exception occured while applying the output gate ({0})", what)); ++ } ++} ++ ++} ++ +void Pinball::ApplyOutputGate(bool open, int64_t generation) +{ -+ OutputGate& gate = OutputGate::Instance(); ++ OutputGate& gate = *m_gate; + bool wasOpen = gate.IsOpen(); + // The toys get the input processed before this change. An opening updates them while the gate is still closed, a + // closing once it is closed, so neither sends a value the gate should hold back. + if (open && m_cabinet && m_cabinet->GetToys()) -+ m_cabinet->GetToys()->UpdateOutputs(); ++ RunGateStep("toys", [this]() { m_cabinet->GetToys()->UpdateOutputs(); }); + // A latched gate applies an opening as a closing. + open = gate.Apply(open); + if (!open && m_cabinet && m_cabinet->GetToys()) -+ m_cabinet->GetToys()->UpdateOutputs(); ++ RunGateStep("toys", [this]() { m_cabinet->GetToys()->UpdateOutputs(); }); + if (wasOpen != open) + { + // Outputs with a value now report another one: tell their controllers. Outputs at 0 report 0 either way. @@ -323,7 +323,7 @@ index fca1659..8e9771b 100644 + for (IOutput* output : *outputs) + { + if (output && output->IsGated() && output->GetRequestedOutput() != 0) -+ output->RaiseValueChanged(); ++ RunGateStep("outputs", [output]() { output->RaiseValueChanged(); }); + } + } + } @@ -338,7 +338,7 @@ index fca1659..8e9771b 100644 + } diff --git a/src/Pinball.h b/src/Pinball.h -index 4bf85b5..d45e4df 100644 +index 4bf85b5..350018a 100644 --- a/src/Pinball.h +++ b/src/Pinball.h @@ -3,9 +3,12 @@ @@ -354,15 +354,24 @@ index 4bf85b5..d45e4df 100644 #include "DOF/DOF.h" -@@ -42,7 +45,18 @@ public: +@@ -19,6 +22,7 @@ class GlobalConfig; + class InputQueue; + class TableElementData; + class CabinetOwner; ++class OutputGate; + + class Pinball + { +@@ -42,7 +46,19 @@ public: void ReceiveData(const std::string& tableElementName, int value); void ReceiveData(const TableElementData& tableElementData); + // Runs `command` on DOF's main thread, between input processing and the cabinet update. Returns false if the main + // thread is not running. + bool Post(std::function command); -+ // Closes or opens the output gate (see OutputGate) on the main thread. Returns the generation, or -1 if the main -+ // thread is not running. ++ // Closes or opens the output gate (see OutputGate) of the session this was created in, on the main thread. Returns the ++ // generation, or -1 if the main thread is not running. Once Finish started, an opening returns -1 and a closing latches ++ // the gate (its generation is the latch's). + int64_t SetOutputGate(bool open); + // Table element changes received but not processed yet. + int GetPendingInputCount() const; @@ -373,7 +382,7 @@ index 4bf85b5..d45e4df 100644 void SetAlarms(AlarmHandler* alarms) { m_alarms = alarms; } void SetGlobalConfig(GlobalConfig* globalConfig) { m_globalConfig = globalConfig; } -@@ -61,6 +75,29 @@ private: +@@ -61,7 +77,34 @@ private: std::condition_variable m_mainThreadCV; std::atomic m_keepMainThreadAlive; std::atomic m_mainThreadDoWork; @@ -401,10 +410,15 @@ index 4bf85b5..d45e4df 100644 + // When the main thread stops: runs the commands still queued, each after the input that was queued before it. + void DrainCommands(); ++ // The gate of the session this was created in. ++ OutputGate* m_gate; ++ // Set when Finish starts, under m_mainThreadMutex, and never cleared. ++ bool m_stopping = false; bool m_tableStarted = false; bool m_alarmsStarted = false; + CabinetOwner* m_cabinetOwner; diff --git a/src/cab/Cabinet.cpp b/src/cab/Cabinet.cpp -index 75f454d..d528403 100644 +index c8986a5..5eeed79 100644 --- a/src/cab/Cabinet.cpp +++ b/src/cab/Cabinet.cpp @@ -4,6 +4,7 @@ @@ -425,50 +439,6 @@ index 75f454d..d528403 100644 std::string xml = GetConfigXml(); if (xml.empty()) { -@@ -387,20 +391,6 @@ bool Cabinet::FromXml(const tinyxml2::XMLElement* element) - m_autoConfigEnabled = (autoConfigText == "true"); - } - -- const tinyxml2::XMLElement* scheduledElement = element->FirstChildElement("ScheduledSettings"); -- if (scheduledElement) -- { -- ScheduledSettings& scheduledSettings = ScheduledSettings::GetInstance(); -- scheduledSettings.FromXml(scheduledElement); -- } -- -- const tinyxml2::XMLElement* sequentialElement = element->FirstChildElement("SequentialOutputSettings"); -- if (sequentialElement) -- { -- SequentialOutputSettings& sequentialSettings = SequentialOutputSettings::GetInstance(); -- sequentialSettings.FromXml(sequentialElement); -- } -- - const tinyxml2::XMLElement* controllersElement = element->FirstChildElement("OutputControllers"); - if (controllersElement && m_outputControllers) - { -@@ -460,6 +450,22 @@ bool Cabinet::FromXml(const tinyxml2::XMLElement* element) - } - } - -+ // VPE: the process-wide settings go in last, so a cabinet config that fails while its controllers or toys load does -+ // not leave its schedules behind. -+ const tinyxml2::XMLElement* scheduledElement = element->FirstChildElement("ScheduledSettings"); -+ if (scheduledElement) -+ { -+ ScheduledSettings& scheduledSettings = ScheduledSettings::GetInstance(); -+ scheduledSettings.FromXml(scheduledElement); -+ } -+ -+ const tinyxml2::XMLElement* sequentialElement = element->FirstChildElement("SequentialOutputSettings"); -+ if (sequentialElement) -+ { -+ SequentialOutputSettings& sequentialSettings = SequentialOutputSettings::GetInstance(); -+ sequentialSettings.FromXml(sequentialElement); -+ } -+ - return true; - } - diff --git a/src/cab/out/IOutput.cpp b/src/cab/out/IOutput.cpp index 3dfbcf7..2715d56 100644 --- a/src/cab/out/IOutput.cpp @@ -489,29 +459,24 @@ index 3dfbcf7..2715d56 100644 } diff --git a/src/cab/out/IOutput.h b/src/cab/out/IOutput.h -index 1a00ca7..639e8f2 100644 +index 1a00ca7..2b6e9b1 100644 --- a/src/cab/out/IOutput.h +++ b/src/cab/out/IOutput.h -@@ -36,8 +36,17 @@ public: +@@ -36,8 +36,12 @@ public: IOutput(); virtual ~IOutput(); - virtual uint8_t GetOutput() const { return m_value; } -+ // The value sent to the hardware: the value set, or 0 while the output gate is closed and the output belongs to an -+ // output controller. + virtual uint8_t GetOutput() const; virtual void SetOutput(uint8_t value) { m_value = value; } -+ // The value set, whatever the output gate. + uint8_t GetRequestedOutput() const { return m_value; } -+ // Tells the controller about the output's value again, after the output gate changed. + void RaiseValueChanged() { OnValueChanged(); } -+ // Set when the output is added to an output controller's list; temporary outputs used for calculations stay ungated. + void SetGated(bool gated) { m_gated = gated; } + bool IsGated() const { return m_gated; } int GetNumber() const { return m_number; } void SetNumber(int number) { m_number = number; } -@@ -49,6 +58,7 @@ protected: +@@ -49,6 +53,7 @@ protected: private: uint8_t m_value; int m_number; @@ -533,7 +498,7 @@ index f222f0c..bdd8bf0 100644 } diff --git a/src/cab/out/OutputControllerCompleteBase.cpp b/src/cab/out/OutputControllerCompleteBase.cpp -index f4958df..101b3cb 100644 +index 2b1478c..a1ad8bd 100644 --- a/src/cab/out/OutputControllerCompleteBase.cpp +++ b/src/cab/out/OutputControllerCompleteBase.cpp @@ -1,5 +1,6 @@ @@ -543,19 +508,13 @@ index f4958df..101b3cb 100644 #include "../../Log.h" #include "../../general/StringExtensions.h" #include -@@ -32,14 +33,28 @@ void OutputControllerCompleteBase::Init(Cabinet* cabinet) - throw; - } - -+ // VPE: the gate unit exists before the updater starts, so a gate change made right after init counts this -+ // controller, and a controller that cannot start counts as failed. -+ std::string unitName = StringExtensions::Build("{0} {1}", GetXmlElementName(), GetName()); +@@ -36,16 +37,37 @@ void OutputControllerCompleteBase::Init(Cabinet* cabinet) if (settingsValid) { SetupOutputs(); ++ RegisterGateUnit(); + m_finishError.clear(); - InitUpdaterThread(); -+ m_gateUnit = OutputGate::Instance().Register(unitName); -+ m_finishError.clear(); + try + { + InitUpdaterThread(); @@ -569,24 +528,26 @@ index f4958df..101b3cb 100644 } else { -+ OutputGate::Instance().RegisterFailed(unitName); ++ // A unit registered before (a connect test) fails as well. ++ RegisterGateUnit(); ++ m_gateUnit->Die(); Log::Warning(StringExtensions::Build("Settings for {0} {1} are not correct. Cannot initialize.", GetXmlElementName(), GetName())); } } -@@ -48,6 +63,12 @@ void OutputControllerCompleteBase::Finish() + ++OutputGate::Unit* OutputControllerCompleteBase::RegisterGateUnit() ++{ ++ // VPE: units belong to a session's gate; a controller that a connect test registered already keeps its unit. ++ OutputGate& gate = OutputGate::Instance(); ++ if (!m_gateUnit || !m_gateUnit->BelongsTo(gate)) ++ m_gateUnit = gate.Register(StringExtensions::Build("{0} {1}", GetXmlElementName(), GetName())); ++ return m_gateUnit; ++} ++ + void OutputControllerCompleteBase::Finish() { FinishUpdaterThread(); - Log::Write(StringExtensions::Build("{0} {1} finished and updater thread stopped.", GetXmlElementName(), GetName())); -+ if (!m_finishError.empty()) -+ { -+ std::string error = m_finishError; -+ m_finishError.clear(); -+ throw std::runtime_error(error); -+ } - } - - void OutputControllerCompleteBase::Update() -@@ -261,6 +282,7 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() +@@ -269,6 +291,7 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() { Log::Write(StringExtensions::Build("Updater thread started for {0} {1}", GetXmlElementName(), GetName())); @@ -594,7 +555,7 @@ index f4958df..101b3cb 100644 try { try -@@ -277,19 +299,29 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() +@@ -285,6 +308,7 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() catch (...) { } @@ -602,132 +563,100 @@ index f4958df..101b3cb 100644 m_updaterThreadFinished = true; return; } - - Log::Write(StringExtensions::Build("Updater thread connected to {0} {1}", GetXmlElementName(), GetName())); - -+ bool died = false; -+ // VPE: the outputs were turned off by the blackout sent while reconnecting, the last thing a unit that died got. -+ bool offWhenDied = false; +@@ -295,13 +319,20 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() + bool fullTransferRequired = true; while (m_keepUpdaterThreadAlive) { -+ // The generation and its state are read together, before the values: the main thread stores the values of a -+ // gate change before it publishes the generation. -+ OutputGate::Snapshot gate = gateUnit->Observe(); ++ // VPE: the generation is read with the values, under the lock they are set with: a value set once a later ++ // generation was published is never sent as part of this one. ++ OutputGate::Snapshot gate; std::vector valuesToSend; { std::lock_guard lock(m_valueChangeMutex); ++ gate = gateUnit->Observe(); valuesToSend = m_outputValues; } -+ // Values set through SetValues (LED strips) are not gated at their outputs: hold them back here. + if (!gate.open) + std::fill(valuesToSend.begin(), valuesToSend.end(), 0); bool updateOK = true; ++ bool cancelled = false; try -@@ -302,18 +334,27 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() + { + if (m_inUseState == InUseState::ValueChanged) +@@ -312,14 +343,28 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() m_inUseState = InUseState::Running; } -- if (m_inUseState == InUseState::Running) -- UpdateOutputs(valuesToSend); +- if (m_inUseState == InUseState::Running && Transfer(valuesToSend, fullTransferRequired)) +- fullTransferRequired = false; + if (m_inUseState == InUseState::Running || !gate.open) + { -+ if (Transfer(valuesToSend, !gateUnit->IsAcked(gate))) ++ if (Transfer(valuesToSend, fullTransferRequired || !gateUnit->IsAcked(gate), gate)) ++ { ++ fullTransferRequired = false; + gateUnit->Ack(gate); ++ } ++ else if (m_transferCancelled) ++ { ++ fullTransferRequired = true; ++ cancelled = true; ++ } + } + else -+ // Open, and DOF never used this controller: it leaves the hardware alone, so there is nothing to send, and -+ // nothing is confirmed either. + gateUnit->Untouched(gate); } catch (const std::exception& e) { Log::Exception(StringExtensions::Build("Could not send update: {0}. Will try again.", e.what())); updateOK = false; + fullTransferRequired = true; + gateUnit->Fail(gate.generation); } if (!updateOK) - { - Log::Warning("Trying to reconnect to controller..."); -+ m_disconnectSentZeros = false; - try - { - DisconnectFromController(); -@@ -328,6 +369,8 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() - } - catch (...) - { -+ offWhenDied = m_disconnectSentZeros; -+ died = true; - break; - } +@@ -345,7 +390,7 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() Log::Write("Reconnected to controller"); -@@ -341,33 +384,93 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() + } + +- if (m_keepUpdaterThreadAlive) ++ if (m_keepUpdaterThreadAlive && !cancelled) + { + std::unique_lock lock(m_conditionMutex); + m_updateCondition.wait_for(lock, std::chrono::milliseconds(50), [this] { return !m_keepUpdaterThreadAlive || m_updateRequired; }); +@@ -353,17 +398,18 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() m_updateRequired = false; } -+ // Whether the final transfer is skipped: open, and DOF never used the controller. -+ bool untouched = m_inUseState == InUseState::Startup && OutputGate::Instance().IsOpen(); -+ // VPE: read before the zeros go out, so a closing published just before Finish is confirmed by them. + OutputGate::Snapshot finalGate = gateUnit->Observe(); -+ bool zerosSent = false; -+ bool finalFailed = false; + bool turnedOff = false; try { - if (m_inUseState != InUseState::Startup) -+ if (died) -+ { -+ if (!untouched && !offWhenDied) -+ m_finishError = StringExtensions::Build("{0} {1} lost its connection; its outputs may still be on", GetXmlElementName(), GetName()); -+ } -+ else if (!untouched) ++ if (m_inUseState != InUseState::Startup || !finalGate.open) { - std::vector zeroValues(m_outputValues.size(), 0); -- UpdateOutputs(zeroValues); -+ zerosSent = Transfer(zeroValues, true); -+ if (!zerosSent) -+ { -+ m_finishError = StringExtensions::Build("{0} {1} could not send its final update", GetXmlElementName(), GetName()); -+ finalFailed = true; -+ } - } - } - catch (const std::exception& e) - { - Log::Exception(StringExtensions::Build("Exception occurred while trying to turn off all outputs: {0}", e.what())); -+ m_finishError = StringExtensions::Build("{0} {1} could not turn its outputs off: {2}", GetXmlElementName(), GetName(), e.what()); -+ finalFailed = true; - } - - try - { -+ m_disconnectSentZeros = false; - DisconnectFromController(); -+ // VPE: a blackout the disconnect sent turns the outputs off as well. One that sends nothing changes nothing. -+ if (m_disconnectSentZeros) -+ { -+ zerosSent = true; -+ if (finalFailed || died) -+ m_finishError.clear(); -+ } -+ } -+ catch (const std::exception& e) -+ { -+ // VPE: without a final transfer, what the controller sends as it disconnects (a blackout) is the last word. -+ Log::Exception(StringExtensions::Build("Disconnecting from {0} {1} failed: {2}", GetXmlElementName(), GetName(), e.what())); -+ if (untouched && !died && m_finishError.empty()) -+ m_finishError = StringExtensions::Build("{0} {1} could not turn its outputs off: {2}", GetXmlElementName(), GetName(), e.what()); - } + if (died) + m_finishError = StringExtensions::Build("{0} {1} lost its connection, its outputs may still be on", GetXmlElementName(), GetName()); + else + { + std::vector zeroValues(m_outputValues.size(), 0); +- turnedOff = Transfer(zeroValues, true); ++ turnedOff = Transfer(zeroValues, true, { finalGate.generation, false }); + if (!turnedOff) + m_finishError = StringExtensions::Build("{0} {1} could not send its final update", GetXmlElementName(), GetName()); + } +@@ -390,20 +436,40 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() catch (...) { } -+ if (died) ++ // VPE: a unit that lost its connection fails, unless the blackout still got to its device: then it ends like one ++ // that finished, with the closing confirmed and nothing delivered later. ++ if (died && !m_disconnectTurnedOff) + gateUnit->Die(); + else + { -+ if (zerosSent && !finalGate.open) -+ gateUnit->Ack(finalGate); ++ if (turnedOff || m_disconnectTurnedOff) ++ gateUnit->AckOff(finalGate); + gateUnit->Stop(); + } Log::Write("Updater thread disconnected and will terminate"); @@ -736,103 +665,99 @@ index f4958df..101b3cb 100644 { Log::Exception(StringExtensions::Build("Exception occurred in updater thread: {0}", e.what())); + gateUnit->Die(); -+ m_finishError = StringExtensions::Build("{0} {1} failed: {2}", GetXmlElementName(), GetName(), e.what()); + m_finishError = StringExtensions::Build("{0} {1} failed: {2}", GetXmlElementName(), GetName(), e.what()); } m_updaterThreadFinished = true; } -+bool OutputControllerCompleteBase::Transfer(const std::vector& values, bool full) -+{ -+ m_forceFullTransfer = full; -+ m_transferSkipped = false; -+ try +-bool OutputControllerCompleteBase::Transfer(const std::vector& values, bool full) ++bool OutputControllerCompleteBase::Transfer(const std::vector& values, bool full, const OutputGate::Snapshot& gate) + { + m_forceFullTransfer = full; + m_transferSkipped = false; ++ m_transferCancelled = false; ++ // VPE: the transfer is bound to the snapshot its values were copied with; every write point asks TransferCancelled. ++ OutputGate::Transfer transfer(m_gateUnit, gate); ++ if (TransferCancelled()) + { -+ UpdateOutputs(values); ++ m_forceFullTransfer = false; ++ m_transferCancelled = true; ++ return false; + } -+ catch (...) + try + { + UpdateOutputs(values); +@@ -411,10 +477,19 @@ bool OutputControllerCompleteBase::Transfer(const std::vector& values, + catch (...) + { + m_forceFullTransfer = false; +- throw; ++ // A write point that stopped for the latch may report it as a failed write: it is not one. ++ if (!transfer.Cancelled()) ++ throw; + } + m_forceFullTransfer = false; ++ if (transfer.Cancelled()) + { -+ m_forceFullTransfer = false; -+ throw; ++ m_transferCancelled = true; ++ return false; + } -+ m_forceFullTransfer = false; -+ return !m_transferSkipped; -+} + return !m_transferSkipped; + } + ++bool OutputControllerCompleteBase::TransferCancelled() { return OutputGate::TransferCancelled(); } + } diff --git a/src/cab/out/OutputControllerCompleteBase.h b/src/cab/out/OutputControllerCompleteBase.h -index 48b8eb9..7d04351 100644 +index e625193..5e6ccd4 100644 --- a/src/cab/out/OutputControllerCompleteBase.h +++ b/src/cab/out/OutputControllerCompleteBase.h -@@ -3,8 +3,10 @@ +@@ -3,6 +3,7 @@ #include "DOF/DOF.h" #include "OutputControllerBase.h" #include "ISupportsSetValues.h" +#include "OutputGate.h" #include #include -+#include - #include - #include + #include +@@ -31,6 +32,8 @@ public: -@@ -44,7 +46,15 @@ protected: - virtual bool VerifySettings() = 0; - virtual void ConnectToController() = 0; - virtual void DisconnectFromController() = 0; -+ // Sends the values to the hardware and throws if they did not get there. While m_forceFullTransfer is set it sends -+ // every output, whatever it remembers of earlier transfers; if it sends nothing (a rate limit), it sets -+ // m_transferSkipped and the updater tries again soon. - virtual void UpdateOutputs(const std::vector& outputValues) = 0; -+ bool m_forceFullTransfer = false; -+ bool m_transferSkipped = false; -+ // VPE: set by a DisconnectFromController that turned every output off (a blackout that got to the device), which -+ // counts as the final update the updater sends when it ends. -+ bool m_disconnectSentZeros = false; + protected: + void SetupOutputs(); ++ // VPE: the controller's unit in the current session's gate, registered before anything is sent to the device. ++ OutputGate::Unit* RegisterGateUnit(); + void RenameOutputs(); + + virtual int GetNumberOfConfiguredOutputs() = 0; +@@ -49,6 +52,9 @@ protected: + bool m_forceFullTransfer = false; + bool m_transferSkipped = false; + bool m_disconnectTurnedOff = false; ++ // VPE: asked right before each write to the device; true once a latch overtook the transfer (OutputGate::Transfer), ++ // which then stops without writing. ++ bool TransferCancelled(); void InitUpdaterThread(); -@@ -72,7 +82,12 @@ private: +@@ -76,9 +82,11 @@ private: mutable std::mutex m_conditionMutex; bool m_keepUpdaterThreadAlive; std::atomic m_updaterThreadFinished { false }; + OutputGate::Unit* m_gateUnit = nullptr; -+ // Set by the updater when the outputs could not be turned off at the end; Finish reports it. -+ std::string m_finishError; + std::string m_finishError; ++ bool m_transferCancelled = false; void UpdaterThreadDoIt(); -+ // Returns whether a transfer happened. -+ bool Transfer(const std::vector& values, bool full); +- bool Transfer(const std::vector& values, bool full); ++ bool Transfer(const std::vector& values, bool full, const OutputGate::Snapshot& gate); }; } -diff --git a/src/cab/out/OutputControllerList.cpp b/src/cab/out/OutputControllerList.cpp -index 89138e9..4c92600 100644 ---- a/src/cab/out/OutputControllerList.cpp -+++ b/src/cab/out/OutputControllerList.cpp -@@ -215,7 +215,18 @@ bool OutputControllerList::FromXml(const tinyxml2::XMLElement* element) - - if (controller) - { -- if (controller->FromXml(controllerElement)) -+ // VPE: a controller whose settings throw is freed before the error goes on. -+ bool loaded; -+ try -+ { -+ loaded = controller->FromXml(controllerElement); -+ } -+ catch (...) -+ { -+ delete controller; -+ throw; -+ } -+ if (loaded) - { - push_back(controller); - Log::Write(StringExtensions::Build("Loaded output controller: {0} ({1})", controller->GetName(), typeName)); diff --git a/src/cab/out/OutputGate.cpp b/src/cab/out/OutputGate.cpp new file mode 100644 -index 0000000..41909e6 +index 0000000..1ad550a --- /dev/null +++ b/src/cab/out/OutputGate.cpp -@@ -0,0 +1,291 @@ +@@ -0,0 +1,342 @@ +#include "OutputGate.h" + +#include @@ -851,9 +776,19 @@ index 0000000..41909e6 + } +} + ++std::mutex s_sessionMutex; ++ ++std::atomic& CurrentSession() ++{ ++ static std::atomic current { nullptr }; ++ return current; ++} ++ ++thread_local OutputGate::Transfer* t_transfer = nullptr; ++ +} + -+OutputGate::Snapshot OutputGate::Unit::Observe() const { return OutputGate::Instance().Current(); } ++OutputGate::Snapshot OutputGate::Unit::Observe() const { return m_gate->Current(); } + +bool OutputGate::Unit::IsAcked(const Snapshot& snapshot) const +{ @@ -863,6 +798,16 @@ index 0000000..41909e6 + +void OutputGate::Unit::Ack(const Snapshot& snapshot) { RaiseTo(snapshot.open ? m_ackedOpen : m_ackedClosed, snapshot.generation); } + ++void OutputGate::Unit::AckOff(const Snapshot& before) ++{ ++ if (!before.open) ++ Ack(before); ++ // Nothing is sent after the blackout, so a closing published while it was sent is what the hardware shows too. ++ Snapshot after = Observe(); ++ if (!after.open) ++ Ack(after); ++} ++ +void OutputGate::Unit::Untouched(const Snapshot& snapshot) +{ + if (snapshot.open) @@ -879,45 +824,76 @@ index 0000000..41909e6 + +void OutputGate::Unit::Stop() { m_stopped.store(true, std::memory_order_release); } + ++OutputGate::Transfer::Transfer(const Unit* unit, const Snapshot& snapshot) ++ : m_gate(unit ? unit->m_gate : nullptr) ++ , m_open(snapshot.open) ++ , m_previous(t_transfer) ++{ ++ t_transfer = this; ++} ++ ++OutputGate::Transfer::~Transfer() { t_transfer = m_previous; } ++ ++bool OutputGate::TransferCancelled() ++{ ++ Transfer* transfer = t_transfer; ++ if (!transfer || !transfer->m_open || !transfer->m_gate || !transfer->m_gate->IsLatched()) ++ return false; ++ transfer->m_cancelled = true; ++ return true; ++} ++ ++OutputGate::OutputGate(int64_t lastGeneration) ++{ ++ // The session's first generation, open and published. ++ int64_t generation = lastGeneration + 1; ++ m_requested.store(generation << 1, std::memory_order_relaxed); ++ m_published.store(Pack(generation, true), std::memory_order_relaxed); ++ Entry entry; ++ entry.open = true; ++ entry.decided = true; ++ entry.publishedOpen = true; ++ entry.raised = true; ++ Record(generation, entry); ++} ++ +OutputGate& OutputGate::Instance() +{ -+ static OutputGate instance; -+ return instance; ++ OutputGate* gate = CurrentSession().load(std::memory_order_acquire); ++ if (gate) ++ return *gate; ++ std::lock_guard lock(s_sessionMutex); ++ gate = CurrentSession().load(std::memory_order_acquire); ++ if (!gate) ++ { ++ gate = new OutputGate(0); ++ CurrentSession().store(gate, std::memory_order_release); ++ } ++ return *gate; +} + -+OutputGate::Snapshot OutputGate::Current() const ++OutputGate& OutputGate::BeginSession() +{ -+ int64_t word = m_published.load(std::memory_order_acquire); -+ return { word >> 1, (word & 1) != 0 }; ++ OutputGate& previous = Instance(); ++ std::lock_guard lock(s_sessionMutex); ++ // Never freed: a latch, a unit or a hung updater thread of the ended session may still use it. ++ OutputGate* gate = new OutputGate(previous.m_requested.load(std::memory_order_acquire) >> 1); ++ CurrentSession().store(gate, std::memory_order_release); ++ return *gate; +} + -+void OutputGate::BeginSession() ++OutputGate::Snapshot OutputGate::Current() const +{ -+ std::lock_guard lock(m_mutex); -+ m_session++; -+ m_history.clear(); -+ // The new session's first generation, with the latch flag cleared. -+ int64_t generation = (m_requested.load(std::memory_order_acquire) >> 1) + 1; -+ m_requested.store(generation << 1, std::memory_order_release); -+ Record(generation, true, true); -+ m_latched.store(false, std::memory_order_release); -+ m_latchGeneration.store(0, std::memory_order_release); -+ m_open.store(true, std::memory_order_release); -+ m_connectTests.store(true, std::memory_order_release); -+ m_published.store(Pack(generation, true), std::memory_order_release); -+ // Units of earlier sessions stay allocated, since a hung updater thread of an abandoned session may still use its -+ // unit, but they are no longer scanned. -+ for (auto& unit : m_units) -+ m_retired.push_back(std::move(unit)); -+ m_units.clear(); ++ int64_t word = m_published.load(std::memory_order_acquire); ++ return { word >> 1, (word & 1) != 0 && !m_latched.load(std::memory_order_acquire) }; +} + +OutputGate::Unit* OutputGate::Register(const std::string& name) +{ + std::lock_guard lock(m_mutex); + auto unit = std::make_unique(); ++ unit->m_gate = this; + unit->m_name = name; -+ unit->m_session = m_session; + Unit* result = unit.get(); + m_units.push_back(std::move(unit)); + return result; @@ -927,8 +903,8 @@ index 0000000..41909e6 + +int64_t OutputGate::Reserve(bool& latched) +{ -+ // The latch flag shares the word with the counter, so a generation is taken either before the session's first latch -+ // or after it, never in between. ++ // The latch flag shares the word with the counter, so a generation is taken either before the session's latch or ++ // after it, never in between. + int64_t word = m_requested.fetch_add(2, std::memory_order_acq_rel); + latched = (word & 1) != 0; + return (word >> 1) + 1; @@ -939,15 +915,17 @@ index 0000000..41909e6 + std::lock_guard lock(m_mutex); + bool latched; + int64_t generation = Reserve(latched); -+ // A change requested once a latch took its generation is a closing, from the start. One taken before stays what it -+ // asked for, also when a latch comes before it is recorded. -+ Record(generation, open && !latched, false); ++ // A change reserved once the session latched is a closing, from the start. One reserved before stays what it asked ++ // for, and Publish decides whether it got to the units as that. ++ Entry entry; ++ entry.open = open && !latched; ++ Record(generation, entry); + return generation; +} + -+void OutputGate::Record(int64_t generation, bool open, bool published) ++void OutputGate::Record(int64_t generation, const Entry& entry) +{ -+ m_history[generation] = { open, published }; ++ m_history[generation] = entry; + while (m_history.size() > MaxHistory) + m_history.erase(m_history.begin()); +} @@ -972,7 +950,7 @@ index 0000000..41909e6 + m_latched.store(true, std::memory_order_release); + m_open.store(false, std::memory_order_release); + // Takes the generation and sets the latch flag in one step: every generation taken after it is recorded as a closing -+ // (Request), so what a change reports does not depend on when this latch gets to install its generation below. ++ // (Request), whenever this latch publishes. + int64_t word = m_requested.load(std::memory_order_acquire); + while (!m_requested.compare_exchange_weak(word, (((word >> 1) + 1) << 1) | 1, std::memory_order_acq_rel, std::memory_order_acquire)) + { @@ -982,23 +960,15 @@ index 0000000..41909e6 + +void OutputGate::FinishLatch(int64_t generation) +{ -+ // The earliest latch generation of the session, whichever latch gets here first. Only latch generations are decided -+ // by it: requested ones carry their state in the history. Until it is installed, the latch's generation is not -+ // published either, so it reports as not applied. -+ int64_t current = m_latchGeneration.load(std::memory_order_acquire); -+ while ((current == 0 || current > generation) -+ && !m_latchGeneration.compare_exchange_weak(current, generation, std::memory_order_acq_rel, std::memory_order_acquire)) -+ { -+ } -+ // Published at once, so the updaters send zeros without waiting for the main thread. ++ // Published at once, so the updaters send zeros without waiting for the main thread. Until then the latch's ++ // generation reports as not applied; it is a closing either way. + RaisePublished(generation, false); +} + +int64_t OutputGate::Latch() +{ -+ // No lock: a fault handler may run while another thread holds the gate's mutex. The history is not touched; the -+ // latch generation tells which generations are closings (StateOf), and an opening that the main thread applies after -+ // this is not published as an opening. ++ // No lock: a fault handler may run while another thread holds the gate's mutex. The history is not touched: a ++ // generation the history does not hold is a latch's (see m_history). + int64_t generation = BeginLatch(); + FinishLatch(generation); + return generation; @@ -1010,7 +980,7 @@ index 0000000..41909e6 + int64_t word = Pack(generation, open); + while ((current >> 1) < generation) + { -+ if (m_published.compare_exchange_weak(current, word, std::memory_order_release, std::memory_order_relaxed)) ++ if (m_published.compare_exchange_weak(current, word, std::memory_order_acq_rel, std::memory_order_relaxed)) + return true; + } + return false; @@ -1022,41 +992,29 @@ index 0000000..41909e6 + auto it = m_history.find(generation); + bool requested = it != m_history.end() ? it->second.open : m_open.load(std::memory_order_acquire); + bool open = requested && !m_latched.load(std::memory_order_acquire); -+ // Only a generation that became the published one with the state it asked for counts as published: an opening a -+ // latch turned into a closing, or one a latch overtook, never reached a unit as an opening. -+ if (RaisePublished(generation, open) && it != m_history.end() && open == requested) -+ it->second.published = true; -+} -+ -+bool OutputGate::StateOf(int64_t generation, bool& open) const -+{ -+ int64_t latchGeneration = m_latchGeneration.load(std::memory_order_acquire); -+ if (latchGeneration > 0 && generation >= latchGeneration) ++ bool raised = RaisePublished(generation, open); ++ // What it reports is decided here, from what was published, and kept: nothing installed later changes it. ++ if (it != m_history.end() && !it->second.decided) + { -+ open = false; -+ return true; ++ it->second.decided = true; ++ it->second.publishedOpen = open; ++ it->second.raised = raised; + } -+ auto it = m_history.find(generation); -+ if (it == m_history.end()) -+ return false; -+ open = it->second.open; -+ return true; +} + +bool OutputGate::IsSuperseded(int64_t generation, bool open, int64_t applied) const +{ -+ // An opening the latch overtook. -+ int64_t latchGeneration = m_latchGeneration.load(std::memory_order_acquire); -+ if (open && latchGeneration > generation && latchGeneration <= applied) -+ return true; -+ // Only changes that were published supersede: one that never reached a unit changed nothing. ++ // Only changes that reached the units supersede: one that never became the published generation changed nothing. ++ int64_t recorded = 0; + for (auto it = m_history.upper_bound(generation); it != m_history.end() && it->first <= applied; ++it) + { -+ bool state; -+ if (it->second.published && StateOf(it->first, state) && state != open) ++ if (it->second.raised && it->second.publishedOpen != open) + return true; ++ recorded++; + } -+ return false; ++ // The generations in between that the history does not hold are latches': closings, each published or overtaken by ++ // a later published one, which is a closing too. ++ return open && applied - generation > recorded; +} + +OutputGate::UnitState OutputGate::Classify(const Unit& unit, int64_t generation, bool open, bool known) const @@ -1077,59 +1035,77 @@ index 0000000..41909e6 + return UnitState::Pending; +} + -+OutputGate::Status OutputGate::GetState(int64_t generation, Counts& counts) const ++OutputGate::Status OutputGate::Evaluate(int64_t generation, Counts& counts, std::vector* names) const +{ + counts = Counts(); -+ std::lock_guard lock(m_mutex); + int64_t applied = Applied(); ++ int64_t oldest = m_history.empty() ? 0 : m_history.begin()->first; ++ auto it = m_history.find(generation); ++ ++ Status status; + bool open = false; -+ bool recorded = StateOf(generation, open); -+ bool known = recorded && generation <= applied; ++ bool known = false; ++ if (it != m_history.end()) ++ { ++ const Entry& entry = it->second; ++ open = entry.open; ++ known = entry.decided; ++ if (!entry.decided) ++ status = Status::NotApplied; ++ else if (entry.open && !entry.publishedOpen) ++ // An opening a latch overtook: it went out as a closing. ++ status = Status::Superseded; ++ else ++ status = IsSuperseded(generation, open, applied) ? Status::Superseded : Status::Applied; ++ } ++ else if (generation > oldest && generation <= (m_requested.load(std::memory_order_acquire) >> 1)) ++ { ++ // A latch's generation: a closing, applied once it or a later generation was published. ++ known = generation <= applied; ++ status = known ? Status::Applied : Status::NotApplied; ++ } ++ else ++ // Never taken, or forgotten long ago. ++ status = generation > applied ? Status::NotApplied : Status::Superseded; ++ + for (const auto& unit : m_units) + { -+ if (unit->m_session != m_session) -+ continue; -+ switch (Classify(*unit, generation, open, known)) ++ UnitState state = Classify(*unit, generation, open, known); ++ switch (state) + { + case UnitState::Confirmed: counts.confirmed++; break; + case UnitState::Failed: counts.failed++; break; + case UnitState::Untouched: counts.untouched++; break; + default: counts.pending++; break; + } ++ if (names && (state == UnitState::Pending || state == UnitState::Failed)) ++ names->push_back(unit->m_name); + } -+ if (!recorded) -+ // Never requested, or forgotten long ago. -+ return generation > applied ? Status::NotApplied : Status::Superseded; -+ if (!known) -+ return Status::NotApplied; -+ return IsSuperseded(generation, open, applied) ? Status::Superseded : Status::Applied; ++ return status; ++} ++ ++OutputGate::Status OutputGate::GetState(int64_t generation, Counts& counts) const ++{ ++ std::lock_guard lock(m_mutex); ++ return Evaluate(generation, counts, nullptr); +} + +std::vector OutputGate::GetPending(int64_t generation) const +{ + std::vector names; ++ Counts counts; + std::lock_guard lock(m_mutex); -+ int64_t applied = Applied(); -+ bool open = false; -+ bool known = StateOf(generation, open) && generation <= applied; -+ for (const auto& unit : m_units) -+ { -+ if (unit->m_session != m_session) -+ continue; -+ UnitState state = Classify(*unit, generation, open, known); -+ if (state == UnitState::Pending || state == UnitState::Failed) -+ names.push_back(unit->m_name); -+ } ++ Evaluate(generation, counts, &names); + return names; +} + +} diff --git a/src/cab/out/OutputGate.h b/src/cab/out/OutputGate.h new file mode 100644 -index 0000000..b7480e3 +index 0000000..0913671 --- /dev/null +++ b/src/cab/out/OutputGate.h -@@ -0,0 +1,188 @@ +@@ -0,0 +1,233 @@ +#pragma once + +#include @@ -1143,13 +1119,17 @@ index 0000000..b7480e3 +namespace DOF +{ + -+// Process-wide switch between the effects and the hardware, added for hosts that must be able to turn every output off -+// without losing the effect state (pause, faults). While the gate is closed, every output reports and sends 0; the -+// values the effects set are kept and sent again when it opens. ++// Switch between the effects and the hardware, added for hosts that must be able to turn every output off without ++// losing the effect state (pause, faults). While the gate is closed, every output reports and sends 0; the values the ++// effects set are kept and sent again when it opens. +// +// A gate change gets a generation. DOF's main thread applies it (Pinball::SetOutputGate), and every output controller +// unit acknowledges the state of a generation once a transfer to its hardware carried that state, so the host can tell +// when the outputs are really off. ++// ++// Each session (one DOF instance, from its creation on) has its own gate object. Instance() is the current session's; ++// one that ended stays allocated, so a latch, a unit or a hung updater thread of an ended session only ever reaches its ++// own session, never the next one. +class OutputGate +{ +public: @@ -1162,12 +1142,12 @@ index 0000000..b7480e3 + + enum class Status + { -+ // The generation was not applied by DOF's main thread yet. ++ // DOF's main thread did not apply the generation yet (a latch's own generation: it was not published yet). + NotApplied, + Applied, -+ // A later generation that was published set the other state, or the generation is an opening that a latch -+ // overtook (requested before the latch, applied after it), which never reaches a unit as an opening. This does not -+ // change any more: only the latest generation's state tells what the outputs show. ++ // The generation never reached a unit as what it asked for: it is an opening applied after a latch, or a later ++ // generation that reached the units set the other state. This does not change any more: only the latest ++ // generation's state tells what the outputs show. + Superseded, + }; + @@ -1186,26 +1166,31 @@ index 0000000..b7480e3 + class Unit + { + public: -+ // Called by the unit's updater before it copies the values it sends. ++ // Called by the unit's updater before it copies the values it sends, under the lock the values are set with. + Snapshot Observe() const; + // Whether the hardware already got the state of `snapshot`, or the gate is open at a unit DOF leaves alone; until + // then the updater transfers every output. + bool IsAcked(const Snapshot& snapshot) const; + // A transfer to the hardware carried the state of `snapshot`. + void Ack(const Snapshot& snapshot); ++ // A blackout that ends the unit's session got to the hardware: it confirms the closing observed before it was ++ // sent (`before`) and one published while it was sent. Then Stop. ++ void AckOff(const Snapshot& before); + // The gate is open at `snapshot` and DOF never used the unit, so nothing was written to its hardware. + void Untouched(const Snapshot& snapshot); + // The unit could not deliver `generation` (no device, failed write). + void Fail(int64_t generation); + // The unit's updater ended without being asked to: it fails every generation, also those it confirmed before. + void Die(); -+ // The unit was finished: it delivers nothing any more. What it confirmed stays confirmed. ++ // The unit was finished, after its last transfer: it delivers nothing any more. What it confirmed stays confirmed. + void Stop(); ++ // Whether the unit belongs to `gate`'s session. ++ bool BelongsTo(const OutputGate& gate) const { return m_gate == &gate; } + + private: + friend class OutputGate; ++ OutputGate* m_gate = nullptr; + std::string m_name; -+ uint64_t m_session = 0; + std::atomic m_ackedClosed { 0 }; + std::atomic m_ackedOpen { 0 }; + std::atomic m_untouched { 0 }; @@ -1214,7 +1199,38 @@ index 0000000..b7480e3 + std::atomic m_stopped { false }; + }; + ++ // A transfer of the values observed at `snapshot`, made by the calling thread while this exists. A latch overtakes ++ // the transfer of an opening: from then on TransferCancelled() is true, and every write point stops before it writes, ++ // so no value of the opening goes out after the latch. The transfer then stays unconfirmed and the updater sends the ++ // closing in full next. ++ class Transfer ++ { ++ public: ++ Transfer(const Unit* unit, const Snapshot& snapshot); ++ ~Transfer(); ++ Transfer(const Transfer&) = delete; ++ Transfer& operator=(const Transfer&) = delete; ++ // Whether a write point stopped because a latch overtook the transfer. ++ bool Cancelled() const { return m_cancelled; } ++ ++ private: ++ friend class OutputGate; ++ const OutputGate* m_gate; ++ bool m_open; ++ bool m_cancelled = false; ++ Transfer* m_previous; ++ }; ++ ++ // Asked by every write point of an output controller right before it writes to its device (each report, each retry, ++ // after acknowledgements and handle acquisition): true once a latch overtook the calling thread's transfer, which ++ // must then stop without writing. False outside a transfer and for a closing. ++ static bool TransferCancelled(); ++ ++ // The current session's gate. + static OutputGate& Instance(); ++ // Starts a new session with an open gate and returns it; Instance() returns it from now on. Generations go on from ++ // the previous session's. The previous session's gate stays allocated (see above). ++ static OutputGate& BeginSession(); + + // The state outputs report. It changes before the generation that set it is published. The latch decides on its own, + // so an Apply that raced it cannot report the gate open again. @@ -1223,34 +1239,37 @@ index 0000000..b7480e3 + // session that turned them off, such as a port test, where a controller that connects late or reconnects would light + // its whole strip. + bool AllowsConnectTests() const { return IsOpen() && m_connectTests.load(std::memory_order_acquire); } -+ // Turns the connect test sequences off, or on again, for the current session. Every new session allows them. ++ // Turns the connect test sequences off, or on again, for this session. Every new session allows them. + void SetConnectTests(bool allowed) { m_connectTests.store(allowed, std::memory_order_release); } ++ // The published generation and the state the units send for it: closed once latched, also before the latch's own ++ // generation is published. + Snapshot Current() const; + -+ // Starts a new session: opens the gate and forgets the units and generations of the previous one. -+ void BeginSession(); -+ // Registers an output controller unit of the current session, before its updater starts. The returned unit lives -+ // until the process ends. ++ // Registers an output controller unit of this session, before anything is sent to its device. The returned unit ++ // lives until the process ends. + Unit* Register(const std::string& name); + // Registers a configured unit that cannot deliver anything, such as a device that is not connected. + void RegisterFailed(const std::string& name); + -+ // Reserves the generation of a change to `open` and records the requested state. Generations from the session's -+ // first latch on are closings. ++ // Reserves the generation of a change to `open` and records the requested state. Generations reserved once the ++ // session latched are closings. + int64_t Request(bool open); + // On DOF's main thread, in the order of the generations: sets the state outputs report and returns it, closed once + // latched. The caller re-raises the output values, then publishes the generation. + bool Apply(bool open); ++ // Publishes `generation` and decides what it reports (see GetState), once. ++ void Publish(int64_t generation); + // Any thread, at once: closes the gate for the rest of the session and publishes the closing, which every unit's -+ // updater sends within its polling interval, without DOF's main thread. Openings with an earlier generation that -+ // were not applied yet are never published as openings and report as superseded; every later change applies as a -+ // closing and reports the closed state. When latches race, the earliest generation is the session's latch, whatever -+ // order the threads finish in. Returns the closing's generation. It takes no lock and never allocates. ++ // updater sends within its polling interval, without DOF's main thread. The latch flag is set in the same step that ++ // reserves its generation, so every change reserved after it is a closing, whichever latch finishes first. Openings ++ // reserved before it that DOF's main thread applies after it never reach a unit as openings and report as superseded. ++ // Returns the closing's generation. It takes no lock and never allocates. + int64_t Latch(); + bool IsLatched() const { return m_latched.load(std::memory_order_acquire); } -+ void Publish(int64_t generation); + int64_t Applied() const { return Current().generation; } + ++ // What a generation reports. It is decided when the generation is published, and never from what happens later, ++ // except that an applied one becomes superseded once a later generation that reached the units sets the other state. + Status GetState(int64_t generation, Counts& counts) const; + // The units GetState counts as pending or failed for `generation`. + std::vector GetPending(int64_t generation) const; @@ -1268,48 +1287,50 @@ index 0000000..b7480e3 + + struct Entry + { ++ // The state the generation asked for; a closing if it was reserved once the session latched. + bool open; -+ // Whether the generation became the published one. One that a latch overtook never does. -+ bool published; ++ // Publish ran for it. ++ bool decided = false; ++ // The state it was published with: closed once latched. ++ bool publishedOpen = false; ++ // It became the published generation (not when a later one was published before it). ++ bool raised = false; + }; + -+ OutputGate() = default; ++ explicit OutputGate(int64_t lastGeneration); + + static int64_t Pack(int64_t generation, bool open) { return (generation << 1) | (open ? 1 : 0); } + -+ // The two halves of Latch: closes at once and reserves the generation with the latch flag, then installs and -+ // publishes it. ++ // The two halves of Latch: closes at once and reserves the generation with the latch flag, then publishes it. + int64_t BeginLatch(); + void FinishLatch(int64_t generation); -+ // Takes the next generation; `latched`: a latch took one before. ++ // Takes the next generation; `latched`: the session latched before. + int64_t Reserve(bool& latched); + + // Called with m_mutex held. -+ bool StateOf(int64_t generation, bool& open) const; -+ // What `unit` reports for `generation`, for both the counts and the names. `known`: the generation was applied and -+ // its state is `open`. ++ Status Evaluate(int64_t generation, Counts& counts, std::vector* names) const; ++ // What `unit` reports for `generation`, for both the counts and the names. `known`: the generation was published ++ // and set `open`. + UnitState Classify(const Unit& unit, int64_t generation, bool open, bool known) const; ++ // Whether a generation after `generation`, up to `applied`, reached the units with the other state. + bool IsSuperseded(int64_t generation, bool open, int64_t applied) const; + // Records the state of a generation and forgets the oldest ones. -+ void Record(int64_t generation, bool open, bool published); ++ void Record(int64_t generation, const Entry& entry); + // Publishes `generation` unless a later one was published already. Lock-free. + bool RaisePublished(int64_t generation, bool open); + + std::atomic m_open { true }; + std::atomic m_connectTests { true }; + std::atomic m_latched { false }; -+ // The earliest latch generation of the session, 0 before it: it and every later generation are closings. -+ std::atomic m_latchGeneration { 0 }; + // The last published generation and its state: (generation << 1) | open. -+ std::atomic m_published { Pack(0, true) }; -+ // The last generation taken, and whether a latch took one in this session: (generation << 1) | latched. ++ std::atomic m_published { 0 }; ++ // The last generation taken, and whether the session latched: (generation << 1) | latched. + std::atomic m_requested { 0 }; -+ uint64_t m_session = 0; + mutable std::mutex m_mutex; -+ // The state each generation set, the latest ones only. ++ // The state each generation reserved by Request set, the latest ones only. A latch's generation is not in it (the ++ // latch takes no lock): a generation that is not, newer than the oldest one recorded, is a latch's, a closing. + std::map m_history; + std::vector> m_units; -+ std::vector> m_retired; + + static constexpr size_t MaxHistory = 4096; + @@ -1331,7 +1352,7 @@ index 47b36ec..9e608ae 100644 output->ValueChanged += [this](void* sender, const OutputEventArgs& args) { OutputValueChanged.Invoke(this, args); }; } diff --git a/src/cab/out/adressableledstrip/DirectStripController.cpp b/src/cab/out/adressableledstrip/DirectStripController.cpp -index d9a5f85..48e1c5b 100644 +index d9a5f85..085c22f 100644 --- a/src/cab/out/adressableledstrip/DirectStripController.cpp +++ b/src/cab/out/adressableledstrip/DirectStripController.cpp @@ -1,5 +1,6 @@ @@ -1341,16 +1362,15 @@ index d9a5f85..48e1c5b 100644 #include "../../Cabinet.h" #include "../../../Log.h" #include "../../../general/StringExtensions.h" -@@ -116,6 +117,8 @@ void DirectStripController::AddOutputs() +@@ -116,6 +117,7 @@ void DirectStripController::AddOutputs() void DirectStripController::Init(Cabinet* cabinet) { AddOutputs(); -+ // VPE: the gate unit exists before the updater starts. + m_gateUnit = OutputGate::Instance().Register(StringExtensions::Build("{0} {1}", GetXmlElementName(), GetName())); InitUpdaterThread(); Log::Write(StringExtensions::Build("DirectStripController {0} with number {1} initialized and updaterthread started.", GetName(), std::to_string(m_controllerNumber))); } -@@ -190,6 +193,7 @@ bool DirectStripController::IsUpdaterThreadActive() const { return m_updaterThre +@@ -190,6 +192,7 @@ bool DirectStripController::IsUpdaterThreadActive() const { return m_updaterThre void DirectStripController::UpdaterThreadDoIt() { @@ -1358,7 +1378,7 @@ index d9a5f85..48e1c5b 100644 if (!m_controller) { m_controller = new DirectStripControllerApi(m_controllerNumber); -@@ -198,6 +202,7 @@ void DirectStripController::UpdaterThreadDoIt() +@@ -198,6 +201,7 @@ void DirectStripController::UpdaterThreadDoIt() Log::Warning(StringExtensions::Build("WS2811 Strip Controller Nr. {0} is not present. Will not send updates.", std::to_string(m_controllerNumber))); delete m_controller; m_controller = nullptr; @@ -1366,16 +1386,21 @@ index d9a5f85..48e1c5b 100644 m_updaterThreadFinished = true; return; } -@@ -214,12 +219,16 @@ void DirectStripController::UpdaterThreadDoIt() +@@ -214,20 +218,33 @@ void DirectStripController::UpdaterThreadDoIt() while (m_keepUpdaterThreadAlive) { - if (m_updateRequired) -+ OutputGate::Snapshot gate = gateUnit->Observe(); -+ if (m_updateRequired || !gateUnit->IsAcked(gate)) ++ // VPE: the generation is read with the values, under the lock they are set with (SetValues is not gated). ++ OutputGate::Snapshot gate; ++ bool update; { ++ std::lock_guard lock(m_updateLocker); ++ gate = gateUnit->Observe(); ++ update = m_updateRequired || !gateUnit->IsAcked(gate); ++ if (update) { - std::lock_guard lock(m_updateLocker); +- std::lock_guard lock(m_updateLocker); m_updateRequired = false; - std::memcpy(m_outputLedData.data(), m_ledData.data(), m_ledData.size()); + if (gate.open) @@ -1383,9 +1408,16 @@ index d9a5f85..48e1c5b 100644 + else + std::fill(m_outputLedData.begin(), m_outputLedData.end(), 0); } - - if (m_controller) -@@ -228,6 +237,7 @@ void DirectStripController::UpdaterThreadDoIt() +- +- if (m_controller) ++ } ++ if (update && m_controller) ++ { ++ // VPE: an opening a latch overtook is not written; the next pass sends the closing. ++ OutputGate::Transfer transfer(gateUnit, gate); ++ if (!OutputGate::TransferCancelled()) + { + if (m_packData) m_controller->SetAndDisplayPackedData(m_outputLedData); else m_controller->SetAndDisplayData(m_outputLedData); @@ -1393,7 +1425,7 @@ index d9a5f85..48e1c5b 100644 } } -@@ -250,6 +260,7 @@ void DirectStripController::UpdaterThreadDoIt() +@@ -250,6 +267,7 @@ void DirectStripController::UpdaterThreadDoIt() delete m_controller; m_controller = nullptr; } @@ -1422,8 +1454,31 @@ index e112579..175fad3 100644 } \ No newline at end of file +diff --git a/src/cab/out/adressableledstrip/TeensyStripController.cpp b/src/cab/out/adressableledstrip/TeensyStripController.cpp +index d3678e4..b70ae6a 100644 +--- a/src/cab/out/adressableledstrip/TeensyStripController.cpp ++++ b/src/cab/out/adressableledstrip/TeensyStripController.cpp +@@ -245,6 +245,9 @@ void TeensyStripController::UpdateOutputs(const std::vector& outputValu + int targetPosition = i * m_numberOfLedsPerChannel; + + std::vector stripData(outputValues.begin() + sourcePosition * 3, outputValues.begin() + sourcePosition * 3 + nrOfLedsOnStrip * 3); ++ // VPE: a latch that overtook the transfer stops it before the next write (each strip, then the output command). ++ if (TransferCancelled()) ++ return; + SendLedstripData(stripData, targetPosition); + + bytesRead = -1; +@@ -270,6 +273,8 @@ void TeensyStripController::UpdateOutputs(const std::vector& outputValu + } + + commandData = { (uint8_t)'O' }; ++ if (TransferCancelled()) ++ return; + enum sp_return result = sp_blocking_write(m_comPort, commandData.data(), 1, m_comPortTimeOutMs); + if (result < 0) + throw std::runtime_error(StringExtensions::Build("Failed to write output command: {0}", sp_last_error_message())); diff --git a/src/cab/out/adressableledstrip/UMXController.cpp b/src/cab/out/adressableledstrip/UMXController.cpp -index d460fbd..a0ef66d 100644 +index 9cbe817..427556d 100644 --- a/src/cab/out/adressableledstrip/UMXController.cpp +++ b/src/cab/out/adressableledstrip/UMXController.cpp @@ -1,4 +1,5 @@ @@ -1432,220 +1487,99 @@ index d460fbd..a0ef66d 100644 #include "UMXControllerAutoConfigurator.h" #include "../../Cabinet.h" #include "../OutputControllerList.h" -@@ -47,7 +48,18 @@ int UMXController::GetNumberOfConfiguredOutputs() { return m_dev ? m_dev->NumOut +@@ -98,7 +99,11 @@ void UMXController::UpdateOutputs(const std::vector& outputValues) - void UMXController::ConnectToController() - { -- DisconnectFromController(); -+ // A unit that cannot be turned off before the reconnect is still reconnected. -+ try -+ { -+ DisconnectFromController(); -+ } -+ catch (const std::exception& e) -+ { -+ Log::Warning(StringExtensions::Build("UMX controller {0} could not turn its outputs off before connecting: {1}", GetName(), e.what())); -+ } -+ // VPE: a device that cannot come back ends the updater instead of failing on every pass. -+ if (m_dev && m_dev->IsLost()) -+ throw std::runtime_error(StringExtensions::Build("UMX controller {0} lost its device", GetName())); - if (m_dev) - m_dev->ResetDataLines(); - } -@@ -55,7 +67,11 @@ void UMXController::ConnectToController() - void UMXController::DisconnectFromController() - { - if (m_inUseState == InUseState::Running && m_dev) + if (!m_dev) + throw std::runtime_error(StringExtensions::Build("UMX controller {0} has no device", GetName())); +- m_dev->UpdateOutputs(outputValues, m_forceFullTransfer); ++ if (TransferCancelled() || !m_dev->UpdateOutputs(outputValues, m_forceFullTransfer, [this]() { return TransferCancelled(); })) + { - m_dev->SendCommand(UMXDevice::UMXCommand::UMX_AllOff); -+ // VPE: SendCommand throws when the command did not get to the device, so the outputs are off now. -+ m_disconnectSentZeros = true; ++ m_dev->ResetDataLines(); ++ return; + } + m_lastTime = std::chrono::steady_clock::now(); + m_lastTimeInit = true; } +@@ -122,20 +127,26 @@ void UMXController::UpdateCabinetFromConfig(Cabinet* cabinet) + return; + } - bool UMXController::VerifySettings() -@@ -74,17 +90,32 @@ void UMXController::UpdateOutputs(const std::vector& outputValues) - auto now = std::chrono::steady_clock::now(); - int delay = m_lastTimeInit ? static_cast(std::chrono::duration_cast(now - m_lastTime).count()) : 0; - -- if (!m_lastTimeInit || delay >= m_longestDataLineDelayMs) -+ if (m_lastTimeInit && delay < m_longestDataLineDelayMs) +- if (m_dev->m_testOnConnect != UMXDevice::TestMode::None) ++ if (m_dev->m_testOnConnect != UMXDevice::TestMode::None && OutputGate::Instance().AllowsConnectTests()) { -- if (m_dev) -- m_dev->UpdateOutputs(outputValues); -- m_lastTime = std::chrono::steady_clock::now(); -- m_lastTimeInit = true; -+ std::this_thread::sleep_for(std::chrono::milliseconds(m_longestDataLineDelayMs - delay)); -+ // VPE: nothing was sent; the updater sends again after this wait. A full transfer (the final all-off among them) -+ // is sent once the wait is over instead. -+ if (!m_forceFullTransfer) -+ { -+ m_transferSkipped = true; -+ return; -+ } - } -- else -+ -+ if (!m_dev) -+ throw std::runtime_error(StringExtensions::Build("UMX controller {0} has no device", GetName())); -+ // VPE: values copied before a latch that came during the wait, or while the frame was built, are not sent: the -+ // transfer stays unconfirmed, and the updater sends the closing in full next. -+ auto stale = [&outputValues]() { -+ return OutputGate::Instance().IsLatched() && std::any_of(outputValues.begin(), outputValues.end(), [](uint8_t value) { return value != 0; }); -+ }; -+ if (stale() || !m_dev->UpdateOutputs(outputValues, m_forceFullTransfer, stale)) - { -- std::this_thread::sleep_for(std::chrono::milliseconds(m_longestDataLineDelayMs - delay)); -+ m_transferSkipped = true; -+ return; - } -+ m_lastTime = std::chrono::steady_clock::now(); -+ m_lastTimeInit = true; - } - - void UMXController::UpdateCabinetFromConfig(Cabinet* cabinet) -@@ -106,6 +137,26 @@ void UMXController::UpdateCabinetFromConfig(Cabinet* cabinet) - return; - } - -+ // VPE: the connect test runs before the controller is added. A device lost by a failed test write is not added (the -+ // auto-configurator lets it go); after another failure the controller is added and its next write opens it again. -+ if (m_dev->m_testOnConnect != UMXDevice::TestMode::None && OutputGate::Instance().AllowsConnectTests()) -+ { -+ std::vector parameters = { -+ static_cast(m_dev->m_testOnConnect), -+ m_dev->m_testOnConnectDuration, -+ }; -+ try -+ { -+ m_dev->SendCommand(UMXDevice::UMXCommand::UMX_StartTest, parameters); -+ } -+ catch (const std::exception& e) -+ { -+ if (m_dev->IsLost()) -+ throw; -+ Log::Warning(StringExtensions::Build("UMX controller {0} could not start its connect test: {1}", GetName(), e.what())); -+ } -+ } -+ - Log::Write(StringExtensions::Build("Detected and added UMX Controller Nr. {0} with name {1}", std::to_string(m_number), GetName())); - cabinet->GetOutputControllers()->push_back(this); - -@@ -211,15 +262,6 @@ void UMXController::UpdateCabinetFromConfig(Cabinet* cabinet) - lwe->GetOutputs().AddOutput(lweo); + std::vector parameters = { + static_cast(m_dev->m_testOnConnect), + m_dev->m_testOnConnectDuration, + }; ++ OutputGate::Unit* gateUnit = RegisterGateUnit(); + try + { +- m_dev->SendCommand(UMXDevice::UMXCommand::UMX_StartTest, parameters); ++ if (!m_dev->SendCommand(UMXDevice::UMXCommand::UMX_StartTest, parameters, []() { return !OutputGate::Instance().AllowsConnectTests(); })) ++ Log::Write(StringExtensions::Build("UMX controller {0} does not start its connect test, the output gate is closed", GetName())); + } + catch (const std::exception& e) + { + if (m_dev->IsLost()) ++ { ++ // The unit registered above stays the controller's only one: it fails. ++ gateUnit->Die(); + throw; ++ } + Log::Warning(StringExtensions::Build("UMX controller {0} could not start its connect test: {1}", GetName(), e.what())); } } -- -- if (m_dev->m_testOnConnect != UMXDevice::TestMode::None) -- { -- std::vector parameters = { -- static_cast(m_dev->m_testOnConnect), -- m_dev->m_testOnConnectDuration, -- }; -- m_dev->SendCommand(UMXDevice::UMXCommand::UMX_StartTest, parameters); -- } - } - - tinyxml2::XMLElement* UMXController::ToXml(tinyxml2::XMLDocument& doc) const diff --git a/src/cab/out/adressableledstrip/UMXControllerAutoConfigurator.cpp b/src/cab/out/adressableledstrip/UMXControllerAutoConfigurator.cpp -index 6ae1dfa..6e37c51 100644 +index 385851c..c9e4536 100644 --- a/src/cab/out/adressableledstrip/UMXControllerAutoConfigurator.cpp +++ b/src/cab/out/adressableledstrip/UMXControllerAutoConfigurator.cpp -@@ -4,10 +4,41 @@ - #include "../OutputControllerList.h" - #include "../../../Log.h" - #include "../../../general/StringExtensions.h" -+#include +@@ -24,20 +24,30 @@ void UMXControllerAutoConfigurator::AddUMXDevice(UMXDevice* dev) + dev->m_unitNo = static_cast(s_devices.size() + 1); + s_devices.push_back(dev); - namespace DOF - { - -+namespace -+{ -+ -+// VPE: adds a controller for `device`. A device whose configuration cannot be read (an MX handshake that times out, a -+// connect test that lost the device) is skipped, so the other devices and the later auto-configurators still run: its -+// controller is deleted unless the cabinet holds it already, and the device is let go. Returns false then. -+bool AddController(Cabinet* cabinet, UMXDevice* device) -+{ -+ UMXController* umxC = new UMXController(); -+ try -+ { -+ umxC->SetNumber(device->UnitNo()); -+ umxC->UpdateCabinetFromConfig(cabinet); -+ } -+ catch (const std::exception& e) -+ { -+ Log::Exception(StringExtensions::Build("UMX device {0} could not be configured and is skipped: {1}", device->m_name, e.what())); -+ OutputControllerList* controllers = cabinet->GetOutputControllers(); -+ if (std::find(controllers->begin(), controllers->end(), umxC) == controllers->end()) -+ { -+ delete umxC; -+ device->Release(); -+ return false; -+ } -+ } -+ return true; -+} -+ -+} -+ - std::vector UMXControllerAutoConfigurator::s_devices; - bool UMXControllerAutoConfigurator::s_inited = false; - Cabinet* UMXControllerAutoConfigurator::s_cabinet = nullptr; -@@ -27,11 +58,8 @@ void UMXControllerAutoConfigurator::AddUMXDevice(UMXDevice* dev) +- try ++ if (s_inited && s_cabinet != nullptr) { - if (s_inited && s_cabinet != nullptr) +- if (s_inited && s_cabinet != nullptr) ++ UMXController* umxC = new UMXController(); ++ try { - UMXController* umxC = new UMXController(); -- umxC->SetNumber(dev->UnitNo()); -- Log::Instrumentation( -- "UMX", StringExtensions::Build("Adding new device {0} & controller {1} to cabinet after UMXControllerAutoConfigurator initialization", dev->m_name, umxC->GetName())); -- umxC->UpdateCabinetFromConfig(s_cabinet); -+ Log::Instrumentation("UMX", StringExtensions::Build("Adding new device {0} to cabinet after UMXControllerAutoConfigurator initialization", dev->m_name)); -+ AddController(s_cabinet, dev); - } - } - catch (const std::exception& e) -@@ -70,8 +98,9 @@ void UMXControllerAutoConfigurator::AutoConfig(Cabinet* cabinet) - preconfigured.push_back(umxC->GetNumber()); - } - -- for (auto* device : s_devices) -+ for (auto deviceIt = s_devices.begin(); deviceIt != s_devices.end();) - { -+ UMXDevice* device = *deviceIt; - bool found = false; - for (int num : preconfigured) - { -@@ -82,12 +111,14 @@ void UMXControllerAutoConfigurator::AutoConfig(Cabinet* cabinet) - } + umxC->SetNumber(dev->UnitNo()); + Log::Instrumentation( + "UMX", StringExtensions::Build("Adding new device {0} & controller {1} to cabinet after UMXControllerAutoConfigurator initialization", dev->m_name, umxC->GetName())); + umxC->UpdateCabinetFromConfig(s_cabinet); } - -- if (!found) -+ // VPE: a device that was let go leaves the list, so the next session does not ask its closed handle again. -+ if (!found && !AddController(cabinet, device)) - { -- UMXController* umxC = new UMXController(); -- umxC->SetNumber(device->UnitNo()); -- umxC->UpdateCabinetFromConfig(cabinet); -+ deviceIt = s_devices.erase(deviceIt); -+ delete device; -+ continue; - } -+ ++deviceIt; +- } +- catch (const std::exception& e) +- { +- Log::Exception(e.what()); ++ catch (const std::exception& e) ++ { ++ // VPE: as in AutoConfig, a device added later that cannot be configured is dropped with its controller, unless the ++ // cabinet holds the controller already. ++ Log::Exception(StringExtensions::Build("UMX device {0} could not be configured and is skipped: {1}", dev->m_name, e.what())); ++ OutputControllerList* controllers = s_cabinet->GetOutputControllers(); ++ if (std::find(controllers->begin(), controllers->end(), umxC) == controllers->end()) ++ { ++ delete umxC; ++ dev->Release(); ++ s_devices.erase(std::find(s_devices.begin(), s_devices.end(), dev)); ++ delete dev; ++ } ++ } } + } - s_inited = true; diff --git a/src/cab/out/adressableledstrip/UMXDevice.cpp b/src/cab/out/adressableledstrip/UMXDevice.cpp -index dc50fe2..4626a8e 100644 +index 5c13a01..5e515eb 100644 --- a/src/cab/out/adressableledstrip/UMXDevice.cpp +++ b/src/cab/out/adressableledstrip/UMXDevice.cpp @@ -83,10 +83,10 @@ void UMXDevice::ResetDataLines() line.m_oldValues.assign(line.m_nbValues, 255); } --void UMXDevice::UpdateOutputs(const std::vector& outputValues) +-void UMXDevice::UpdateOutputs(const std::vector& outputValues, bool full) +bool UMXDevice::UpdateOutputs(const std::vector& outputValues, bool full, const std::function& cancel) { if (!m_enabled) @@ -1654,45 +1588,26 @@ index dc50fe2..4626a8e 100644 for (auto& line : m_dataLines) { -@@ -115,7 +115,7 @@ void UMXDevice::UpdateOutputs(const std::vector& outputValues) - auto& line = m_dataLines[numLine]; - if (line.m_nbLeds > 0) - { -- if (line.m_values != line.m_oldValues) -+ if (full || line.m_values != line.m_oldValues) - { - nbChangedLines++; - sendBuffer.push_back(static_cast(numLine)); -@@ -141,7 +141,6 @@ void UMXDevice::UpdateOutputs(const std::vector& outputValues) - sendBuffer.insert(sendBuffer.end(), line.m_values.begin(), line.m_values.end()); - } - -- line.m_oldValues = line.m_values; - } - } - } -@@ -150,9 +149,18 @@ void UMXDevice::UpdateOutputs(const std::vector& outputValues) +@@ -148,7 +148,8 @@ void UMXDevice::UpdateOutputs(const std::vector& outputValues, bool ful { std::vector buffer = { nbChangedLines }; buffer.insert(buffer.end(), sendBuffer.begin(), sendBuffer.end()); - SendCommand(UMXCommand::UMX_SendStripsData, buffer); -+ // VPE: the device asks `cancel` before each of its writes, so a latch holds back the rest of the frame. + if (!SendCommand(UMXCommand::UMX_SendStripsData, buffer, cancel)) + return false; WaitAck(static_cast(UMXCommand::UMX_SendStripsData)); } -+ // VPE: the lines remember what the device got, after it got it (SendCommand throws otherwise). -+ for (auto& line : m_dataLines) -+ { -+ if (line.m_nbLeds > 0) -+ line.m_oldValues = line.m_values; -+ } + for (auto& line : m_dataLines) +@@ -156,6 +157,7 @@ void UMXDevice::UpdateOutputs(const std::vector& outputValues, bool ful + if (line.m_nbLeds > 0) + line.m_oldValues = line.m_values; + } + return true; } std::vector UMXDevice::CompressDataLineValues(const std::vector& values) diff --git a/src/cab/out/adressableledstrip/UMXDevice.h b/src/cab/out/adressableledstrip/UMXDevice.h -index 81af672..47a30ac 100644 +index 4475b47..07e2e83 100644 --- a/src/cab/out/adressableledstrip/UMXDevice.h +++ b/src/cab/out/adressableledstrip/UMXDevice.h @@ -3,6 +3,7 @@ @@ -1703,18 +1618,15 @@ index 81af672..47a30ac 100644 #include "../../toys/layer/RGBOrderEnum.h" #include "../../toys/layer/StripArrangementEnum.h" #include "../../../general/Curve.h" -@@ -97,11 +98,25 @@ public: +@@ -97,10 +98,17 @@ public: void ComputeNumOutputs(); void CreateDataLines(); void ResetDataLines(); -- void UpdateOutputs(const std::vector& outputValues); -+ // VPE: `full` sends every data line, whatever was sent before. Throws if the device did not get the data. -+ // Returns false if `cancel` said so before the data was all out; the device may then have part of the frame. +- void UpdateOutputs(const std::vector& outputValues, bool full = false); + bool UpdateOutputs(const std::vector& outputValues, bool full = false, const std::function& cancel = nullptr); virtual void Initialize() = 0; virtual void SendCommand(UMXCommand command, const std::vector& parameters = { }) = 0; -+ // VPE: SendCommand that asks `cancel` before each write to the device and stops when it says so; returns false then. + virtual bool SendCommand(UMXCommand command, const std::vector& parameters, const std::function& cancel) + { + if (cancel && cancel()) @@ -1723,338 +1635,208 @@ index 81af672..47a30ac 100644 + return true; + } virtual void WaitAck(uint8_t command) = 0; -+ // VPE: whether the device failed and cannot be opened again during the session. -+ virtual bool IsLost() const { return false; } -+ // VPE: lets go of a device no controller uses, such as one whose configuration could not be read. -+ virtual void Release() { } - - std::vector m_ledStrips; - std::vector m_dataLines; + virtual bool IsLost() const { return false; } + virtual void Release() { } diff --git a/src/cab/out/adressableledstrip/WemosD1StripController.cpp b/src/cab/out/adressableledstrip/WemosD1StripController.cpp -index 1832b60..a3d04f4 100644 +index cb013c8..51cf2b9 100644 --- a/src/cab/out/adressableledstrip/WemosD1StripController.cpp +++ b/src/cab/out/adressableledstrip/WemosD1StripController.cpp -@@ -1,4 +1,5 @@ +@@ -1,5 +1,6 @@ #include "WemosD1StripController.h" + #include "DOF/Config.h" +#include "../OutputGate.h" #include "../../../Log.h" #include "../../../general/StringExtensions.h" #include -@@ -64,7 +65,7 @@ void WemosD1MPStripController::SetupController() +@@ -66,10 +67,11 @@ void WemosD1MPStripController::SetupController() } } - if (m_testOnConnect) ++ if (m_testOnConnect && OutputGate::Instance().AllowsConnectTests()) ++ Log::Write("Send a test request to the controller"); + if (m_testOnConnect && OutputGate::Instance().AllowsConnectTests()) { commandData = { (uint8_t)'T' }; - Log::Write("Send a test request to the controller"); +- Log::Write("Send a test request to the controller"); + + enum sp_return result = sp_blocking_write(GetComPort(), commandData.data(), 1, GetComPortTimeOutMs()); + if (result < 0) diff --git a/src/cab/out/comport/PinControl.cpp b/src/cab/out/comport/PinControl.cpp -index 592fda0..4a195b5 100644 +index 2b16bd5..605b5ce 100644 --- a/src/cab/out/comport/PinControl.cpp +++ b/src/cab/out/comport/PinControl.cpp -@@ -69,7 +69,7 @@ void PinControl::UpdateOutputs(const std::vector& outputValues) - - for (int i = 0; i < 7 && i < static_cast(outputValues.size()); i++) - { -- if (m_oldValues == nullptr || m_oldValues[i] != outputValues[i]) -+ if (m_forceFullTransfer || m_oldValues == nullptr || m_oldValues[i] != outputValues[i]) - { - std::string command; - if (i == 0 && outputValues[i] != 0) -@@ -77,7 +77,7 @@ void PinControl::UpdateOutputs(const std::vector& outputValues) +@@ -77,7 +77,8 @@ void PinControl::UpdateOutputs(const std::vector& outputValues) else command = StringExtensions::Build("{0},{1}#", std::to_string(i + 1), outputValues[i] == 0 ? "2" : "1"); -- sp_blocking_write(m_port, command.c_str(), command.length(), 1000); -+ WriteCommand(command); +- WriteCommand(command); ++ if (!WriteCommand(command)) ++ return; } } -@@ -85,7 +85,7 @@ void PinControl::UpdateOutputs(const std::vector& outputValues) - bool isBlack = true; - for (int i = 7; i < 10 && i < static_cast(outputValues.size()); i++) - { -- if (m_oldValues == nullptr || m_oldValues[i] != outputValues[i]) -+ if (m_forceFullTransfer || m_oldValues == nullptr || m_oldValues[i] != outputValues[i]) - colorChanged = true; - if (outputValues[i] != 0) - isBlack = false; -@@ -100,7 +100,7 @@ void PinControl::UpdateOutputs(const std::vector& outputValues) +@@ -100,7 +101,8 @@ void PinControl::UpdateOutputs(const std::vector& outputValues) command = StringExtensions::Build("9,1,{0},{1},{2}#", outputValues.size() > 7 ? std::to_string(outputValues[7]) : "0", outputValues.size() > 8 ? std::to_string(outputValues[8]) : "0", outputValues.size() > 9 ? std::to_string(outputValues[9]) : "0"); -- sp_blocking_write(m_port, command.c_str(), command.length(), 1000); -+ WriteCommand(command); +- WriteCommand(command); ++ if (!WriteCommand(command)) ++ return; } if (m_oldValues == nullptr) -@@ -113,6 +113,14 @@ void PinControl::UpdateOutputs(const std::vector& outputValues) +@@ -113,11 +115,15 @@ void PinControl::UpdateOutputs(const std::vector& outputValues) throw std::runtime_error(StringExtensions::Build("COM port {0} is not initialized for {1} {2}.", m_comPort, "PinControl", GetName())); } -+// VPE: a command that did not go out completely is an error, so the values are sent again. -+void PinControl::WriteCommand(const std::string& command) -+{ -+ sp_return written = sp_blocking_write(m_port, command.c_str(), command.length(), 1000); -+ if (written < 0 || static_cast(written) != command.length()) -+ throw std::runtime_error(StringExtensions::Build("Writing to COM port {0} failed for {1} {2}.", m_comPort, "PinControl", GetName())); -+} -+ - void PinControl::ConnectToController() +-void PinControl::WriteCommand(const std::string& command) ++bool PinControl::WriteCommand(const std::string& command) { - std::lock_guard lock(m_portLocker); ++ // VPE: each command is a write; once a latch overtook the transfer, the rest of it is not sent. ++ if (TransferCancelled()) ++ return false; + sp_return written = sp_blocking_write(m_port, command.c_str(), command.length(), 1000); + if (written < 0 || static_cast(written) != command.length()) + throw std::runtime_error(StringExtensions::Build("Writing to COM port {0} failed for {1} {2}.", m_comPort, "PinControl", GetName())); ++ return true; + } + + void PinControl::ConnectToController() diff --git a/src/cab/out/comport/PinControl.h b/src/cab/out/comport/PinControl.h -index d76a7d8..1bebe23 100644 +index 1bebe23..980636d 100644 --- a/src/cab/out/comport/PinControl.h +++ b/src/cab/out/comport/PinControl.h -@@ -27,6 +27,7 @@ protected: +@@ -27,7 +27,7 @@ protected: virtual int GetNumberOfConfiguredOutputs() override; virtual bool VerifySettings() override; virtual void UpdateOutputs(const std::vector& outputValues) override; -+ void WriteCommand(const std::string& command); +- void WriteCommand(const std::string& command); ++ bool WriteCommand(const std::string& command); virtual void ConnectToController() override; virtual void DisconnectFromController() override; diff --git a/src/cab/out/dmx/ArtNet.cpp b/src/cab/out/dmx/ArtNet.cpp -index 44d0e43..ad4faf3 100644 +index b7516b8..25936a5 100644 --- a/src/cab/out/dmx/ArtNet.cpp +++ b/src/cab/out/dmx/ArtNet.cpp -@@ -28,7 +28,8 @@ void ArtNet::UpdateOutputs(const std::vector& outputValues) - { +@@ -29,7 +29,12 @@ void ArtNet::UpdateOutputs(const std::vector& outputValues) if (outputValues.size() == DMX_CHANNELS) { -- m_engine->SendDMX(m_broadcastAddress, m_universe, outputValues, DMX_CHANNELS); -+ if (!m_engine->SendDMX(m_broadcastAddress, m_universe, outputValues, DMX_CHANNELS)) -+ throw std::runtime_error("the Art-Net packet was not sent"); + if (!m_engine->SendDMX(m_broadcastAddress, m_universe, outputValues, DMX_CHANNELS)) ++ { ++ // VPE: not sent because a latch overtook the transfer, which is not an error. ++ if (TransferCancelled()) ++ return; + throw std::runtime_error("the Art-Net packet was not sent"); ++ } } else { -@@ -79,21 +80,17 @@ void ArtNet::ConnectToController() - - void ArtNet::DisconnectFromController() - { -- try -- { -- if (m_engine != nullptr) -- { -- std::vector zeroData(DMX_CHANNELS, 0); -- m_engine->SendDMX(m_broadcastAddress, m_universe, zeroData, DMX_CHANNELS); -- } -- } -- catch (...) -- { -- } -- -- if (m_engine != nullptr) -+ // VPE: a blackout that did not go out is reported. For a controller DOF never used, it is the only one sent at the -+ // end of the session. -+ Engine* engine = m_engine; -+ m_engine = nullptr; -+ if (engine != nullptr) - { -- m_engine = nullptr; -+ std::vector zeroData(DMX_CHANNELS, 0); -+ if (!engine->SendDMX(m_broadcastAddress, m_universe, zeroData, DMX_CHANNELS)) -+ throw std::runtime_error(StringExtensions::Build( -+ "{0} {1} (Universe: {2}, Broadcast Address: {3}) could not send its blackout", { GetXmlElementName(), GetName(), std::to_string(m_universe), m_broadcastAddress })); -+ m_disconnectSentZeros = true; - } - } - diff --git a/src/cab/out/dmx/artnetengine/Engine.cpp b/src/cab/out/dmx/artnetengine/Engine.cpp -index d95af44..302baa3 100644 +index 302baa3..22ce37c 100644 --- a/src/cab/out/dmx/artnetengine/Engine.cpp +++ b/src/cab/out/dmx/artnetengine/Engine.cpp -@@ -141,14 +141,14 @@ uint8_t Engine::LoByte(int value) const { return static_cast(value & 0x - - uint8_t Engine::HiByte(int value) const { return static_cast((value >> 8) & 0xFF); } - --void Engine::SendDMX(const std::string& broadcastAddress, short universe, const std::vector& data, int dataLength) -+bool Engine::SendDMX(const std::string& broadcastAddress, short universe, const std::vector& data, int dataLength) - { - std::lock_guard lock(m_udpMutex); - - if (!m_socketInitialized || m_socket < 0) - { - Log::Exception("ArtNet engine socket not initialized"); -- return; -+ return false; +@@ -1,4 +1,5 @@ + #include "Engine.h" ++#include "../../OutputGate.h" + #include "../../../../Log.h" + #include "../../../../general/StringExtensions.h" + #include +@@ -180,6 +181,10 @@ bool Engine::SendDMX(const std::string& broadcastAddress, short universe, const + return false; } - std::vector packet(0x12 + dataLength); -@@ -177,7 +177,7 @@ void Engine::SendDMX(const std::string& broadcastAddress, short universe, const - catch (const std::exception& e) - { - Log::Exception(StringExtensions::Build("Exception occurred copying DMX data in ArtNet Engine: {0}", e.what())); -- return; ++ // VPE: the engine is shared and its lock can take a while; an opening a latch overtook meanwhile is not sent. ++ if (OutputGate::TransferCancelled()) + return false; - } - ++ if (m_socketInitialized && m_socket >= 0) -@@ -198,7 +198,7 @@ void Engine::SendDMX(const std::string& broadcastAddress, short universe, const - if (inet_pton(AF_INET, broadcastAddress.c_str(), &addr.sin_addr) <= 0) - { - Log::Exception(StringExtensions::Build("Invalid broadcast address for ArtNet: {0}", broadcastAddress)); -- return; -+ return false; - } - } - -@@ -220,6 +220,7 @@ void Engine::SendDMX(const std::string& broadcastAddress, short universe, const - } - - m_sendExceptionCount = 0; -+ return true; - } - catch (const std::exception& e) - { -@@ -237,6 +238,7 @@ void Engine::SendDMX(const std::string& broadcastAddress, short universe, const - } - } - } -+ return false; - } - - } -\ No newline at end of file -diff --git a/src/cab/out/dmx/artnetengine/Engine.h b/src/cab/out/dmx/artnetengine/Engine.h -index 84b1c02..006cb28 100644 ---- a/src/cab/out/dmx/artnetengine/Engine.h -+++ b/src/cab/out/dmx/artnetengine/Engine.h -@@ -13,7 +13,8 @@ class Engine - public: - static Engine* GetInstance(); - -- void SendDMX(const std::string& broadcastAddress, short universe, const std::vector& data, int dataLength); -+ // VPE: returns false if the packet was not sent. -+ bool SendDMX(const std::string& broadcastAddress, short universe, const std::vector& data, int dataLength); - bool Reopen(); - - private: + { + try diff --git a/src/cab/out/dudescab/DudesCab.cpp b/src/cab/out/dudescab/DudesCab.cpp -index 77e90f9..d10030d 100644 +index b9a8fd5..ba9fc08 100644 --- a/src/cab/out/dudescab/DudesCab.cpp +++ b/src/cab/out/dudescab/DudesCab.cpp -@@ -25,6 +25,8 @@ namespace DOF +@@ -25,6 +25,7 @@ namespace DOF { std::vector DudesCab::s_devices; +std::vector DudesCab::s_mxDevices; -+bool DudesCab::s_discovered = false; + bool DudesCab::s_discovered = false; const DudesCab::Device::Version DudesCab::Device::s_minimalMxVersion(1, 9, 0); - const DudesCab::Device::Version DudesCab::Device::s_newProtocolVersion(1, 9, 0); -@@ -88,16 +90,23 @@ void DudesCab::Init(Cabinet* cabinet) - - void DudesCab::Finish() { OutputControllerFlexCompleteBase::Finish(); } - --bool DudesCab::VerifySettings() { return true; } -+// VPE: a configured unit without its device cannot start, so it counts as failed instead of as written. -+bool DudesCab::VerifySettings() -+{ -+ if (m_dev == nullptr) -+ ConnectToController(); -+ return m_dev != nullptr; -+} - - void DudesCab::Instrumentation(const std::string& message) { Log::Instrumentation("DudesCab", message); } +@@ -109,7 +110,7 @@ void DudesCab::Instrumentation(const std::string& message) { Log::Instrumentatio void DudesCab::UpdateOutputs(const std::vector& newOutputValues) { - if (m_dev == nullptr) -- return; -+ throw std::runtime_error(StringExtensions::Build("Dude's Cab {0} is not connected", GetName())); +- if (m_dev == nullptr) ++ if (m_dev == nullptr || !m_connected) + throw std::runtime_error(StringExtensions::Build("Dude's Cab {0} is not connected", GetName())); -- if (newOutputValues != m_oldOutputValues) -+ const bool fullTransfer = m_forceFullTransfer || m_cacheInvalid; -+ if (fullTransfer || newOutputValues != m_oldOutputValues) - { - m_outputBuffer.clear(); - m_outputBuffer.push_back(0); -@@ -110,7 +119,7 @@ void DudesCab::UpdateOutputs(const std::vector& newOutputValues) + const bool fullTransfer = m_forceFullTransfer || m_cacheInvalid; +@@ -178,7 +179,11 @@ void DudesCab::UpdateOutputs(const std::vector& newOutputValues) - for (int numDofOutput = 0; numDofOutput < static_cast(newOutputValues.size()); numDofOutput++) - { -- if (m_oldOutputValues.size() <= static_cast(numDofOutput) || newOutputValues[numDofOutput] != m_oldOutputValues[numDofOutput]) -+ if (fullTransfer || m_oldOutputValues.size() <= static_cast(numDofOutput) || newOutputValues[numDofOutput] != m_oldOutputValues[numDofOutput]) - { - uint8_t extNum = static_cast(numDofOutput / m_dev->m_pwmMaxOutputsPerExtension); - uint8_t outputNum = static_cast(numDofOutput % m_dev->m_pwmMaxOutputsPerExtension); -@@ -163,8 +172,15 @@ void DudesCab::UpdateOutputs(const std::vector& newOutputValues) Instrumentation(StringExtensions::Build("{0} Dof Values to send to Dude's cab", std::to_string(nbValuesToSend))); - m_dev->SendCommand(Device::HIDReportType::RT_PWM_OUTPUTS, m_outputBuffer); -+ // VPE: the cache only learns what the device got. -+ if (m_dev->LastWriteFailed()) +- m_dev->SendCommand(Device::HIDReportType::RT_PWM_OUTPUTS, m_outputBuffer); ++ if (TransferCancelled() || !m_dev->SendCommand(Device::HIDReportType::RT_PWM_OUTPUTS, m_outputBuffer, [this]() { return TransferCancelled(); })) + { + m_cacheInvalid = true; -+ throw std::runtime_error(StringExtensions::Build("Writing to Dude's Cab {0} failed", GetName())); ++ return; + } + if (m_dev->LastWriteFailed()) + { + m_cacheInvalid = true; +@@ -202,19 +207,23 @@ void DudesCab::UpdateDelay() - m_oldOutputValues = newOutputValues; -+ m_cacheInvalid = false; - } - } - -@@ -178,21 +194,53 @@ void DudesCab::UpdateDelay() - m_lastUpdate = std::chrono::steady_clock::now(); - } - --void DudesCab::ConnectToController() { DisconnectFromController(); } -+// VPE: upstream disconnected here, so a reconnect never bound the device again. -+void DudesCab::ConnectToController() -+{ -+ // Without auto-configuration nothing has listed the devices yet. -+ std::vector devices = AllDevices(); -+ auto it = std::find_if(devices.begin(), devices.end(), [this](Device* d) { return d->UnitNo() == m_number; }); -+ if (it == devices.end()) -+ return; -+ // A blackout that went through on the old handle does not make it usable again: only a reopen does. -+ if ((*it)->NeedsReopen() && !(*it)->Reopen()) -+ { -+ m_dev = nullptr; -+ m_cacheInvalid = true; -+ // A board without a serial number is not opened again during the session: the updater gives up on it instead of -+ // trying again on every pass. -+ if (!(*it)->CanReopen()) -+ throw std::runtime_error(StringExtensions::Build("Dude's Cab {0} has no serial number and cannot be opened again", GetName())); -+ return; + void DudesCab::ConnectToController() + { +- std::vector devices = AllDevices(); +- auto it = std::find_if(devices.begin(), devices.end(), [this](Device* d) { return d->UnitNo() == m_number; }); +- if (it == devices.end()) +- return; +- if ((*it)->NeedsReopen() && !(*it)->Reopen()) ++ if (!m_dev) + { +- m_dev = nullptr; +- m_cacheInvalid = true; +- if (!(*it)->HasSerial()) ++ std::vector devices = AllDevices(); ++ auto it = std::find_if(devices.begin(), devices.end(), [this](Device* d) { return d->UnitNo() == m_number; }); ++ if (it == devices.end()) ++ return; ++ m_dev = *it; + } -+ m_dev = *it; -+ // Setting up the outputs again takes their values from the Output objects, which values set in bulk (SetValues) are -+ // not in: a reconnect keeps the requested values. -+ if (GetNumberOfOutputs() != m_dev->NumOutputs()) -+ SetNumberOfOutputs(m_dev->NumOutputs()); -+ m_oldOutputValues.assign(GetNumberOfOutputs(), 0); ++ m_connected = false; + m_cacheInvalid = true; -+} - - void DudesCab::DisconnectFromController() ++ if (!m_dev->EnsureOpen()) ++ { ++ if (!m_dev->HasSerial()) + throw std::runtime_error(StringExtensions::Build("Dude's Cab {0} reports no serial number and cannot be opened again", GetName())); + return; + } +- m_dev = *it; ++ m_connected = true; + if (GetNumberOfOutputs() != m_dev->NumOutputs()) + SetNumberOfOutputs(m_dev->NumOutputs()); + m_oldOutputValues.assign(GetNumberOfOutputs(), 0); +@@ -225,9 +234,12 @@ void DudesCab::DisconnectFromController() { if (m_inUseState == InUseState::Running && m_dev) { -- m_dev->AllOff(); -+ // VPE: a blackout that got to the board counts as the final update. -+ if (m_dev->AllOff()) -+ m_disconnectSentZeros = true; - m_dev = nullptr; -+ m_cacheInvalid = true; +- m_disconnectTurnedOff = m_dev->AllOff(); +- m_dev = nullptr; ++ // The board stays bound: whatever failed before, the blackout goes to it, through a handle opened again if it ++ // could be, else the one it has. ++ m_connected = false; + m_cacheInvalid = true; ++ m_dev->EnsureOpen(); ++ m_disconnectTurnedOff = m_dev->AllOff(); } } - std::vector DudesCab::AllDevices() - { -- if (s_devices.empty()) -+ if (!s_discovered) -+ { - s_devices = FindDevices(); -+ s_discovered = true; -+ } - return s_devices; - } - -@@ -200,13 +248,20 @@ void DudesCab::ClearDevices() +@@ -245,14 +257,20 @@ void DudesCab::ClearDevices() { for (Device* device : s_devices) delete device; @@ -2063,7 +1845,7 @@ index 77e90f9..d10030d 100644 s_devices.clear(); + s_mxDevices.clear(); -+ s_discovered = false; + s_discovered = false; } std::vector DudesCab::FindDevices() @@ -2075,273 +1857,118 @@ index 77e90f9..d10030d 100644 std::vector dudedevices; std::vector devices; -@@ -286,21 +341,36 @@ std::vector DudesCab::FindDevices() - - if (!alreadyEnumerated) - { -- Device* newDevice = new Device(deviceRid, cur_dev->path, productName, serialNumber, cur_dev->vendor_id, cur_dev->product_id, cur_dev->release_number); -- dudedevices.push_back(newDevice); -- -- if (deviceRid == Device::RIDType::RIDOutputs) -+ // VPE: a device that does not answer is skipped instead of ending the discovery. -+ Device* newDevice = nullptr; -+ try -+ { -+ newDevice = new Device(deviceRid, cur_dev->path, productName, serialNumber, cur_dev->vendor_id, cur_dev->product_id, cur_dev->release_number); -+ if (deviceRid == Device::RIDType::RIDOutputs) -+ newDevice->ReadPwmOutputsConfig(); -+ } -+ catch (const std::exception& e) - { -- newDevice->ReadPwmOutputsConfig(); -- devices.push_back(newDevice); -+ Log::Exception(StringExtensions::Build("Dude's Cab {0} did not answer and is skipped: {1}", productName, e.what())); -+ delete newDevice; -+ newDevice = nullptr; - } -- else if (deviceRid == Device::RIDType::RIDOutputsMx) -+ -+ if (newDevice) - { -- if (newDevice->SupportMx()) -+ dudedevices.push_back(newDevice); -+ -+ if (deviceRid == Device::RIDType::RIDOutputs) -+ devices.push_back(newDevice); -+ else if (deviceRid == Device::RIDType::RIDOutputsMx) +@@ -354,6 +372,7 @@ std::vector DudesCab::FindDevices() + devices.push_back(newDevice); + else if (deviceRid == Device::RIDType::RIDOutputsMx) { -- UMXDudesCabDevice* dudeUMX = new UMXDudesCabDevice(); -- dudeUMX->SetDevice(newDevice); -- UMXControllerAutoConfigurator::AddUMXDevice(dudeUMX); + s_mxDevices.push_back(newDevice); -+ if (newDevice->SupportMx()) -+ { -+ UMXDudesCabDevice* dudeUMX = new UMXDudesCabDevice(); -+ dudeUMX->SetDevice(newDevice); -+ UMXControllerAutoConfigurator::AddUMXDevice(dudeUMX); -+ } - } - } - } -@@ -331,8 +401,24 @@ DudesCab::Device::Device(RIDType rid, const std::string& path, const std::string - , m_hidDevice(nullptr) - { - m_hidDevice = hid_open_path(path.c_str()); -+ // VPE: an interface that went away or is not accessible is not a device: discovery skips it. - if (!m_hidDevice) -- return; -+ throw std::runtime_error(StringExtensions::Build("could not open {0}", path)); -+ -+ // VPE: a handshake that throws leaves no destructor to close the handle. -+ struct CloseOnThrow -+ { -+ hid_device*& handle; -+ bool armed; -+ ~CloseOnThrow() -+ { -+ if (armed && handle) -+ { -+ hid_close(handle); -+ handle = nullptr; -+ } -+ } -+ } closeOnThrow { m_hidDevice, true }; - - std::vector answer; - -@@ -394,6 +480,7 @@ DudesCab::Device::Device(RIDType rid, const std::string& path, const std::string - m_configVersion = info[5]; - } - } -+ closeOnThrow.armed = false; - } + if (newDevice->SupportMx()) + { + UMXDudesCabDevice* dudeUMX = new UMXDudesCabDevice(); +@@ -494,14 +513,14 @@ std::string HidString(const wchar_t* text) - DudesCab::Device::~Device() -@@ -402,6 +489,84 @@ DudesCab::Device::~Device() - hid_close(m_hidDevice); } -+namespace -+{ -+ -+std::string HidString(const wchar_t* text) -+{ -+ std::string result; -+ if (!text) -+ return result; -+#ifdef _WIN32 -+ int size = WideCharToMultiByte(CP_UTF8, 0, text, -1, nullptr, 0, nullptr, nullptr); -+ if (size > 0) -+ { -+ result.resize(size - 1); -+ WideCharToMultiByte(CP_UTF8, 0, text, -1, &result[0], size, nullptr, nullptr); -+ } -+#else -+ while (*text) -+ result += static_cast(*text++); -+#endif -+ return result; -+} -+ -+} -+ -+// The path of a device that was unplugged can belong to another device once it is back (hidraw nodes are reused), so -+// the interface is looked up again by what identifies it: the serial number, the product name and the interface FindDevices -+// chose. Until that interface opens, the device stays failed and has no handle. -+bool DudesCab::Device::Reopen() -+{ -+ m_lastWriteFailed = true; -+ m_needsReopen = true; -+ // Without a serial number nothing tells this board from another one plugged in its place, so it is not reopened -+ // during the session; it stays failed until the next one enumerates the devices again. Its handle is kept, so the -+ // blackout at the end of the session can still try it. -+ if (!CanReopen()) -+ return false; -+ -+ if (m_hidDevice) -+ hid_close(m_hidDevice); -+ m_hidDevice = nullptr; -+ const char* candidate = nullptr; -+ struct hid_device_info* devs = hid_enumerate(m_vendorID, m_productID); -+ for (struct hid_device_info* cur = devs; cur; cur = cur->next) -+ { -+ std::string serial = cur->serial_number ? HidString(cur->serial_number) : ""; -+ if (serial != m_serial || HidString(cur->product_string) != m_devicename) -+ continue; -+ RIDType rid = RIDType::None; -+ if (m_devicename == "DudesCab Outputs") -+ rid = RIDType::RIDOutputs; -+ else if (m_devicename == "DudesCab Outputs MX") -+ rid = RIDType::RIDOutputsMx; -+#if defined(__linux__) || defined(__APPLE__) -+ else if (m_devicename == "DudesCab" && cur->interface_number == 3) -+ rid = RIDType::RIDOutputs; -+ else if (m_devicename == "DudesCab" && cur->interface_number == 4) -+ rid = RIDType::RIDOutputsMx; -+#endif -+ if (rid != m_deviceRid) -+ continue; -+ candidate = cur->path; -+ break; -+ } -+ if (candidate) -+ { -+ m_hidDevice = hid_open_path(candidate); -+ if (m_hidDevice) -+ m_path = candidate; -+ } -+ hid_free_enumeration(devs); ++bool DudesCab::Device::EnsureOpen() { return !m_needsReopen || Reopen(); } + -+ if (!m_hidDevice) -+ return false; -+ m_lastWriteFailed = false; -+ m_needsReopen = false; -+ return true; -+} -+ - std::string DudesCab::Device::ToString() const { return StringExtensions::Build("{0} (name: {1} unit:{2})", m_devicename, m_name, std::to_string(m_unitNo)); } - - void DudesCab::Device::ReadPwmOutputsConfig() -@@ -466,7 +631,19 @@ bool DudesCab::Device::HasOutputEnabled(uint8_t extNum, uint8_t outputNum) - - bool DudesCab::Device::SupportMx() { return m_firmwareVersion >= s_minimalMxVersion; } - --void DudesCab::Device::AllOff() { SendCommand(HIDReportType::RT_PWM_ALLOFF); } -+bool DudesCab::Device::AllOff() -+{ -+ SendCommand(HIDReportType::RT_PWM_ALLOFF); -+ return !m_lastWriteFailed; -+} -+ -+void DudesCab::Device::Close() -+{ -+ if (m_hidDevice) -+ hid_close(m_hidDevice); -+ m_hidDevice = nullptr; -+ m_needsReopen = true; -+} - - std::vector DudesCab::Device::ReadUSB(uint8_t command) + bool DudesCab::Device::Reopen() { -@@ -475,7 +652,12 @@ std::vector DudesCab::Device::ReadUSB(uint8_t command) - try +- if (m_hidDevice) +- hid_close(m_hidDevice); +- m_hidDevice = nullptr; + m_lastWriteFailed = true; + m_needsReopen = true; +- ++ // VPE: without a serial number nothing tells this board from another one plugged in its place, so it is not opened ++ // again. Its handle is kept for the blackout. + if (!HasSerial()) + return false; + const char* candidate = nullptr; +@@ -527,15 +546,35 @@ bool DudesCab::Device::Reopen() + candidate = cur->path; + break; + } ++ // VPE: the handle the board has is kept until another one is open, so a board that is there but does not open again ++ // still gets the blackout through it. ++ hid_device* opened = nullptr; + if (candidate) { - while (answer.size() < 2 || answer[1] != remapCommand) +- m_hidDevice = hid_open_path(candidate); +- if (m_hidDevice) ++ opened = hid_open_path(candidate); ++#ifdef __APPLE__ ++ // hidapi opens a device exclusively on macOS: the board only opens again once the handle it has is closed. If it ++ // still does not, it is opened again where it was, for the blackout. ++ if (!opened && m_hidDevice) + { - answer = ReadUSB(); -+ // VPE: a read that timed out returns nothing; without this, a device that does not answer is asked forever. -+ if (answer.empty()) -+ throw std::runtime_error("timed out"); ++ hid_close(m_hidDevice); ++ m_hidDevice = nullptr; ++ opened = hid_open_path(candidate); ++ if (!opened) ++ m_hidDevice = hid_open_path(m_path.c_str()); ++ } ++#endif ++ if (opened) ++ { ++ if (m_hidDevice) ++ hid_close(m_hidDevice); ++ m_hidDevice = opened; + m_path = candidate; + } } - catch (const std::exception& ex) - { -@@ -488,6 +670,9 @@ std::vector DudesCab::Device::ReadUSB(uint8_t command) - std::vector DudesCab::Device::ReadUSB() - { - std::vector incomingData; -+ // VPE: a device that is not open has nothing to read. -+ if (!m_hidDevice) -+ return incomingData; - uint8_t receivedCommand = 0; - auto startRead = std::chrono::steady_clock::now(); - -@@ -528,8 +713,9 @@ bool DudesCab::Device::WriteUSB(const std::vector& data) - { - if (m_hidDevice && !data.empty()) - { -+ // Windows hidapi pads a short report to the device's report length and returns the padded count. - int result = hid_write(m_hidDevice, data.data(), data.size()); -- return result >= 0; -+ return result >= static_cast(data.size()); - } - return false; - } -@@ -547,10 +733,22 @@ void DudesCab::Device::SendCommand(HIDReportTypeMx command, const std::vector(command), parameters); } -void DudesCab::Device::SendCommand(RIDType rid, uint8_t command, const std::vector& parameters) ++bool DudesCab::Device::SendCommand(HIDReportType command, const std::vector& parameters, const std::function& cancel) ++{ ++ return SendCommand(m_deviceRid, static_cast(RemapPwmCommand(command)), parameters, cancel); ++} ++ +bool DudesCab::Device::SendCommand(HIDReportTypeMx command, const std::vector& parameters, const std::function& cancel) - { ++{ + if (!SupportMx()) + return true; + return SendCommand(m_deviceRid, static_cast(command), parameters, cancel); +} + +bool DudesCab::Device::SendCommand(RIDType rid, uint8_t command, const std::vector& parameters, const std::function& cancel) -+{ -+ m_lastWriteFailed = true; + { + m_lastWriteFailed = true; if (!m_hidDevice) + { + m_needsReopen = true; - return; -+ { -+ m_needsReopen = true; + return true; -+ } -+ m_lastWriteFailed = false; + } + m_lastWriteFailed = false; - if (rid == RIDType::RIDOutputs) - Log::Instrumentation("DudesCab", StringExtensions::Build("DudesCab SendCommand: {0}", std::to_string(static_cast(command)))); -@@ -581,8 +779,16 @@ void DudesCab::Device::SendCommand(RIDType rid, uint8_t command, const std::vect +@@ -744,12 +795,15 @@ void DudesCab::Device::SendCommand(RIDType rid, uint8_t command, const std::vect sendData.insert(sendData.end(), data.begin() + startPos, data.begin() + startPos + toSend); } -- WriteUSB(sendData); -+ // VPE: a latch that came during the earlier reports holds back the rest of the command. + if (cancel && cancel()) + return false; -+ if (!WriteUSB(sendData)) -+ { -+ m_lastWriteFailed = true; -+ m_needsReopen = true; -+ } + if (!WriteUSB(sendData)) + { + m_lastWriteFailed = true; + m_needsReopen = true; + } } + return true; } DudesCab::Device::HIDCommonReportType DudesCab::Device::RemapCommonCommand(HIDCommonReportType command) diff --git a/src/cab/out/dudescab/DudesCab.h b/src/cab/out/dudescab/DudesCab.h -index b2b1f6c..6514666 100644 +index a42d974..9b2749c 100644 --- a/src/cab/out/dudescab/DudesCab.h +++ b/src/cab/out/dudescab/DudesCab.h @@ -5,6 +5,7 @@ @@ -2352,28 +1979,27 @@ index b2b1f6c..6514666 100644 #include -@@ -129,7 +130,10 @@ public: - int NumOutputs() const { return m_numOutputs; } +@@ -130,6 +131,10 @@ public: const std::string& GetSerial() const { return m_serial; } -- void AllOff(); -+ // VPE: returns whether the command got to the board. -+ bool AllOff(); -+ // VPE: closes the HID handle of a board that is not used. -+ void Close(); - void ReadPwmOutputsConfig(); - bool HasOutputEnabled(uint8_t extNum, uint8_t outputNum); - bool SupportMx(); -@@ -137,6 +141,8 @@ public: + bool AllOff(); ++ // VPE: opens the device again after a failed write when it can (a board with a serial number). Returns whether it ++ // takes updates. Every board keeps the handle it has until another one is open, so the blackout at the end of the ++ // session still tries it. ++ bool EnsureOpen(); + bool Reopen(); + void Close(); + bool LastWriteFailed() const { return m_lastWriteFailed; } +@@ -143,6 +148,8 @@ public: void SendCommand(HIDCommonReportType command, const std::vector& parameters = { }); void SendCommand(HIDReportType command, const std::vector& parameters = { }); void SendCommand(HIDReportTypeMx command, const std::vector& parameters = { }); -+ // VPE: asks `cancel` before each report it writes and stops when it says so; returns false then. ++ bool SendCommand(HIDReportType command, const std::vector& parameters, const std::function& cancel); + bool SendCommand(HIDReportTypeMx command, const std::vector& parameters, const std::function& cancel); std::vector ReadUSB(uint8_t command); -@@ -159,9 +165,24 @@ public: +@@ -165,7 +172,7 @@ public: uint8_t m_configVersion; private: @@ -2381,76 +2007,32 @@ index b2b1f6c..6514666 100644 + bool SendCommand(RIDType rid, uint8_t command, const std::vector& parameters = { }, const std::function& cancel = nullptr); std::vector ReadUSB(); bool WriteUSB(const std::vector& data); -+ bool m_lastWriteFailed = false; -+ // VPE: a write failed since the device was opened: only Reopen clears it, not a later write that went through. -+ bool m_needsReopen = false; -+ -+ public: -+ // VPE: whether a part of the last command could not be written. -+ bool LastWriteFailed() const { return m_lastWriteFailed; } -+ // VPE: whether a write failed since the device was last opened, so the handle has to be opened again. -+ bool NeedsReopen() const { return m_needsReopen; } -+ // VPE: opens the device again after a transport failure, such as after it was unplugged and plugged in again. -+ bool Reopen(); -+ // VPE: whether Reopen can find this board again, which takes a serial number. -+ bool CanReopen() const { return !m_serial.empty() && m_serial != ""; } -+ -+ private: - HIDCommonReportType RemapCommonCommand(HIDCommonReportType command); - HIDReportType RemapPwmCommand(HIDReportType command); -@@ -197,6 +218,8 @@ private: +@@ -204,7 +211,10 @@ private: + int m_minCommandIntervalMs; bool m_minCommandIntervalMsSet; ++ // VPE: the board of this unit number, bound for the whole session. A board that failed blocks updates (m_connected), ++ // never the blackout, which always goes to the board it was bound to. Device* m_dev; -+ // VPE: the device's outputs may differ from the cache (after a failed write or all-off), so the next update sends all. -+ bool m_cacheInvalid = true; ++ bool m_connected = false; + bool m_cacheInvalid = true; std::vector m_oldOutputValues; std::vector m_outputBuffer; - -@@ -206,6 +229,11 @@ private: +@@ -215,6 +225,8 @@ private: static std::vector FindDevices(); static std::vector s_devices; -+ // VPE: the MX interfaces, which the UMX devices use, are owned here too, and the devices are listed once until -+ // ClearDevices: a cabinet with an MX interface but no PWM one would otherwise list them again on every lookup and -+ // delete the UMX devices its controllers still use. ++ // VPE: the MX interfaces, owned here: the UMX devices only use them. + static std::vector s_mxDevices; -+ static bool s_discovered; + static bool s_discovered; }; - } -diff --git a/src/cab/out/dudescab/DudesCabAutoConfigurator.cpp b/src/cab/out/dudescab/DudesCabAutoConfigurator.cpp -index ecf905a..84147f9 100644 ---- a/src/cab/out/dudescab/DudesCabAutoConfigurator.cpp -+++ b/src/cab/out/dudescab/DudesCabAutoConfigurator.cpp -@@ -18,7 +18,20 @@ void DudesCabAutoConfigurator::AutoConfig(Cabinet* cabinet) - - for (DudesCab::Device* device : devices) - { -- if (device->UnitNo() >= 1 && device->UnitNo() <= 5) -+ // VPE: a controller binds by unit number, so a unit any Dude's Cab controller of the cabinet uses is skipped, as in -+ // C#: two updaters on one board would overwrite each other's frames. -+ bool preconfigured = false; -+ for (IOutputController* controller : *cabinet->GetOutputControllers()) -+ { -+ DudesCab* existing = dynamic_cast(controller); -+ if (existing && existing->GetNumber() == device->UnitNo()) -+ { -+ preconfigured = true; -+ break; -+ } -+ } -+ -+ if (!preconfigured && device->UnitNo() >= 1 && device->UnitNo() <= 5) - { - std::string controllerName = StringExtensions::Build("DudesCab Controller {0:00}", std::to_string(device->UnitNo())); - diff --git a/src/cab/out/dudescab/UMXDudesCabDevice.cpp b/src/cab/out/dudescab/UMXDudesCabDevice.cpp -index 7bd8055..3dc6c35 100644 +index 25fb108..62587ea 100644 --- a/src/cab/out/dudescab/UMXDudesCabDevice.cpp +++ b/src/cab/out/dudescab/UMXDudesCabDevice.cpp -@@ -109,14 +109,31 @@ void UMXDudesCabDevice::Initialize() +@@ -109,14 +109,18 @@ void UMXDudesCabDevice::Initialize() } } @@ -2459,48 +2041,33 @@ index 7bd8055..3dc6c35 100644 + +bool UMXDudesCabDevice::SendCommand(UMXCommand command, const std::vector& parameters, const std::function& cancel) { -+ // VPE: a retry after a failed write goes to the device found again, not to the stale handle. -+ if (m_device->NeedsReopen()) -+ m_device->Reopen(); +- if (m_device->NeedsReopen() && !m_device->Reopen() && m_device->IsLost()) ++ // VPE: a lost board takes no updates, but the blackout still tries the handle it has. ++ if (!m_device->EnsureOpen() && m_device->IsLost() && command != UMXCommand::UMX_AllOff) + throw std::runtime_error(StringExtensions::Build("{0} reports no serial number and cannot be opened again", m_name)); auto dudeCommand = UMXToDudeCommand(command); - m_device->SendCommand(dudeCommand, parameters); + bool sent = m_device->SendCommand(dudeCommand, parameters, cancel); -+ // VPE: a command that did not get to the device is an error. -+ if (m_device->LastWriteFailed()) -+ throw std::runtime_error(StringExtensions::Build("Sending UMX command {0} failed", std::to_string(static_cast(command)))); + if (m_device->LastWriteFailed()) + throw std::runtime_error(StringExtensions::Build("Sending UMX command {0} failed", std::to_string(static_cast(command)))); + return sent; } void UMXDudesCabDevice::WaitAck(uint8_t command) { } - -+bool UMXDudesCabDevice::IsLost() const { return m_device && m_device->NeedsReopen() && !m_device->CanReopen(); } -+ -+void UMXDudesCabDevice::Release() -+{ -+ if (m_device) -+ m_device->Close(); -+} -+ - DudesCab::Device::HIDReportTypeMx UMXDudesCabDevice::UMXToDudeCommand(UMXCommand command) - { - switch (command) diff --git a/src/cab/out/dudescab/UMXDudesCabDevice.h b/src/cab/out/dudescab/UMXDudesCabDevice.h -index f981906..6f13772 100644 +index 4a73aec..e24fc86 100644 --- a/src/cab/out/dudescab/UMXDudesCabDevice.h +++ b/src/cab/out/dudescab/UMXDudesCabDevice.h -@@ -16,7 +16,10 @@ public: +@@ -16,6 +16,7 @@ public: void Initialize() override; void SendCommand(UMXCommand command, const std::vector& parameters = { }) override; + bool SendCommand(UMXCommand command, const std::vector& parameters, const std::function& cancel) override; void WaitAck(uint8_t command) override; -+ bool IsLost() const override; -+ void Release() override; - - DudesCab::Device* GetDevice() const { return m_device; } - void SetDevice(DudesCab::Device* device) { m_device = device; } + bool IsLost() const override { return m_device && m_device->IsLost(); } + void Release() override; diff --git a/src/cab/out/ftdichip/FT245RBitbangController.cpp b/src/cab/out/ftdichip/FT245RBitbangController.cpp -index d698a04..2215df1 100644 +index 4c0f5f7..4448662 100644 --- a/src/cab/out/ftdichip/FT245RBitbangController.cpp +++ b/src/cab/out/ftdichip/FT245RBitbangController.cpp @@ -7,6 +7,7 @@ @@ -2511,11 +2078,10 @@ index d698a04..2215df1 100644 #include #include #include -@@ -40,12 +41,17 @@ void FT245RBitbangController::SetId(int value) +@@ -40,13 +41,16 @@ void FT245RBitbangController::SetId(int value) void FT245RBitbangController::Init(Cabinet* cabinet) { -+ // VPE: the gate unit exists before the updater starts; a controller that cannot start counts as failed. + std::string unitName = StringExtensions::Build("FT245RBitbangController {0}", GetName()); if (StringExtensions::IsNullOrWhiteSpace(m_serialNumber)) { @@ -2524,25 +2090,12 @@ index d698a04..2215df1 100644 return; } AddOutputs(); -+ m_finishError.clear(); + m_finishError.clear(); + m_gateUnit = OutputGate::Instance().Register(unitName); InitUpdaterThread(); Log::Write(StringExtensions::Build("FT245RBitbangController {0} with serial number {1} has been initialized and the updater thread has been started.", GetName(), m_serialNumber)); } -@@ -54,6 +60,12 @@ void FT245RBitbangController::Finish() - { - FinishUpdaterThread(); - Log::Write(StringExtensions::Build("FT245RBitbangController {0} with serial number {1} has been finished and the updater thread has been terminated.", GetName(), m_serialNumber)); -+ if (!m_finishError.empty()) -+ { -+ std::string error = m_finishError; -+ m_finishError.clear(); -+ throw std::runtime_error(error); -+ } - } - - void FT245RBitbangController::Update() -@@ -185,10 +197,12 @@ void FT245RBitbangController::UpdaterThreadSignal() +@@ -192,10 +196,12 @@ void FT245RBitbangController::UpdaterThreadSignal() void FT245RBitbangController::UpdaterThreadDoIt() { @@ -2555,37 +2108,34 @@ index d698a04..2215df1 100644 m_updaterThreadFinished = true; return; } -@@ -200,18 +214,27 @@ void FT245RBitbangController::UpdaterThreadDoIt() - catch (const std::exception&) - { - Log::Exception(StringExtensions::Build("Could not send initial update to FTDI chip {0}. Updater thread will terminate.", m_serialNumber)); -- Disconnect(); -+ // VPE: Disconnect tries to turn the outputs off once more; when that fails too, Finish reports it. -+ std::string error; -+ if (!Disconnect(&error)) -+ m_finishError = StringExtensions::Build("FT245RBitbangController {0} could not turn its outputs off: {1}", GetName(), error); -+ gateUnit->Die(); - m_updaterThreadFinished = true; - return; +@@ -211,13 +217,24 @@ void FT245RBitbangController::UpdaterThreadDoIt() + started = false; } -+ bool died = false; - while (m_keepUpdaterThreadAlive) ++ bool died = !started; + while (started && m_keepUpdaterThreadAlive) { -+ // The whole byte goes out on every pass, so a pass that sends confirms the gate state it observed. -+ OutputGate::Snapshot gate = gateUnit->Observe(); - m_currentValue = m_newValue.load(); +- m_currentValue = m_newValue.load(); ++ OutputGate::Snapshot gate; ++ { ++ // VPE: the gate is read with the values it goes out with, as in OutputControllerCompleteBase. ++ std::lock_guard lock(m_valueChangeLocker); ++ gate = gateUnit->Observe(); ++ m_currentValue = m_newValue.load(); ++ } try { - SendUpdate(m_currentValue); -+ // The observed state governs what is sent: a gate that opens restores the values before it publishes. ++ // VPE: SendUpdate does not write an opening a latch overtook; the next pass sends the closing. ++ OutputGate::Transfer transfer(gateUnit, gate); + SendUpdate(gate.open ? m_currentValue.load() : static_cast(0)); -+ gateUnit->Ack(gate); ++ if (!transfer.Cancelled()) ++ gateUnit->Ack(gate); } catch (const std::exception& e) { -@@ -233,6 +256,7 @@ void FT245RBitbangController::UpdaterThreadDoIt() +@@ -239,6 +256,7 @@ void FT245RBitbangController::UpdaterThreadDoIt() catch (const std::exception& ec) { Log::Exception(StringExtensions::Build("Could not send update to FTDI chip {0}. Tried to reconnect to device but failed. Updater thread will terminate.", m_serialNumber)); @@ -2593,16 +2143,21 @@ index d698a04..2215df1 100644 break; } -@@ -240,18 +264,24 @@ void FT245RBitbangController::UpdaterThreadDoIt() +@@ -246,19 +264,28 @@ void FT245RBitbangController::UpdaterThreadDoIt() { try { +- m_currentValue = m_newValue.load(); - SendUpdate(m_currentValue); -+ // VPE: the values and gate state as they are now, not as they were before the reconnect. -+ gate = gateUnit->Observe(); -+ m_currentValue = m_newValue.load(); ++ { ++ std::lock_guard lock(m_valueChangeLocker); ++ gate = gateUnit->Observe(); ++ m_currentValue = m_newValue.load(); ++ } ++ OutputGate::Transfer transfer(gateUnit, gate); + SendUpdate(gate.open ? m_currentValue.load() : static_cast(0)); -+ gateUnit->Ack(gate); ++ if (!transfer.Cancelled()) ++ gateUnit->Ack(gate); } catch (const std::exception& ee) { @@ -2619,86 +2174,52 @@ index d698a04..2215df1 100644 break; } } -@@ -263,15 +293,36 @@ void FT245RBitbangController::UpdaterThreadDoIt() +@@ -270,18 +297,32 @@ void FT245RBitbangController::UpdaterThreadDoIt() } } -+ // VPE: the outputs are off when either the final update or the one Disconnect sends got there. Taken before the -+ // final update, so the zeros confirm the closing that was published when the updater ended. + OutputGate::Snapshot finalGate = gateUnit->Observe(); -+ bool off = false; -+ std::string error; + std::string finishError; ++ bool zerosSent = false; try { SendUpdate(0); -+ off = true; ++ zerosSent = m_ftdi != nullptr; } catch (const std::exception& e) { Log::Exception(StringExtensions::Build("Final update to turn off all output for FTDI chip {0} failed.", m_serialNumber)); -+ error = e.what(); -+ } -+ std::string disconnectError; -+ if (Disconnect(&disconnectError)) -+ off = true; -+ else if (error.empty()) -+ error = disconnectError; -+ if (!off) -+ m_finishError = StringExtensions::Build("FT245RBitbangController {0} could not turn its outputs off: {1}", GetName(), error); -+ if (died) + finishError = StringExtensions::Build("FT245RBitbangController {0} could not turn its outputs off: {1}", GetName(), e.what()); + } +- if (!Disconnect() && !finishError.empty()) ++ bool disconnectTurnedOff = Disconnect(); ++ if (!disconnectTurnedOff && !finishError.empty()) + m_finishError = finishError; ++ // VPE: as in OutputControllerCompleteBase, an updater that ended on its own fails every generation unless its blackout ++ // got through, which confirms the closing. ++ if (died && !zerosSent && !disconnectTurnedOff) + gateUnit->Die(); + else + { -+ if (off && !finalGate.open) -+ gateUnit->Ack(finalGate); ++ if (zerosSent || disconnectTurnedOff) ++ gateUnit->AckOff(finalGate); + gateUnit->Stop(); - } -- Disconnect(); ++ } m_updaterThreadFinished = true; } -@@ -349,20 +400,27 @@ void FT245RBitbangController::SendUpdate(uint8_t outputData) - "Wrong number of written bytes (expected 1, received {0}) was returned when sending data to the FTDI chip {1}", std::to_string(numBytes), m_serialNumber)); - } - } -+ else -+ // VPE: nothing was sent, which is not a success. -+ throw std::runtime_error(StringExtensions::Build("FTDI chip {0} is not connected", m_serialNumber)); - } - --void FT245RBitbangController::Disconnect() -+bool FT245RBitbangController::Disconnect(std::string* error) +@@ -342,6 +383,9 @@ void FT245RBitbangController::Connect() + void FT245RBitbangController::SendUpdate(uint8_t outputData) { std::lock_guard lock(m_ftdiLocker); ++ // VPE: the lock can take a while (a reconnect); an opening a latch overtook meanwhile is not written. ++ if (OutputGate::TransferCancelled()) ++ return; -+ bool off = false; if (m_ftdi) { - try - { - SendUpdate(0); -+ off = true; - } -- catch (...) -+ catch (const std::exception& e) - { -+ if (error) -+ *error = e.what(); - } - - if (m_ftdi->IsOpen()) -@@ -380,6 +438,9 @@ void FT245RBitbangController::Disconnect() - m_ftdi = nullptr; - Log::Write(StringExtensions::Build("Connection to FTDI chip {0} closed.", m_serialNumber)); - } -+ else if (error) -+ *error = StringExtensions::Build("FTDI chip {0} is not connected", m_serialNumber); -+ return off; - } - - tinyxml2::XMLElement* FT245RBitbangController::ToXml(tinyxml2::XMLDocument& doc) const diff --git a/src/cab/out/ftdichip/FT245RBitbangController.h b/src/cab/out/ftdichip/FT245RBitbangController.h -index de1b98d..bbe3c05 100644 +index b90b458..fba2a65 100644 --- a/src/cab/out/ftdichip/FT245RBitbangController.h +++ b/src/cab/out/ftdichip/FT245RBitbangController.h @@ -2,6 +2,7 @@ @@ -2709,28 +2230,16 @@ index de1b98d..bbe3c05 100644 #include "FTDI.h" #include #include -@@ -63,6 +64,8 @@ private: +@@ -63,6 +64,7 @@ private: std::condition_variable m_updaterThreadCondition; std::atomic m_keepUpdaterThreadAlive; std::atomic m_updaterThreadFinished; + OutputGate::Unit* m_gateUnit = nullptr; -+ std::string m_finishError; + std::string m_finishError; int m_firstTryFailCnt; - std::recursive_mutex m_ftdiLocker; -@@ -70,7 +73,8 @@ private: - - void Connect(); - void SendUpdate(uint8_t outputData); -- void Disconnect(); -+ // Returns whether it turned the outputs off before closing; when not, the reason is in `error`. -+ bool Disconnect(std::string* error = nullptr); - }; - - } -\ No newline at end of file diff --git a/src/cab/out/lw/LedWiz.cpp b/src/cab/out/lw/LedWiz.cpp -index c136d75..a597cd8 100644 +index 21cda40..60eaab0 100644 --- a/src/cab/out/lw/LedWiz.cpp +++ b/src/cab/out/lw/LedWiz.cpp @@ -1,5 +1,6 @@ @@ -2740,67 +2249,54 @@ index c136d75..a597cd8 100644 #include "../../../Log.h" #include "../../../general/MathExtensions.h" #include "../../../general/StringExtensions.h" -@@ -114,8 +115,9 @@ void LedWiz::Finish() - { - Log::Write(StringExtensions::Build("Finishing LedWiz Nr. {0:00}", std::to_string(m_number))); - s_ledWizUnits.at(m_number)->Finish(); -- s_ledWizUnits.at(m_number)->ShutdownLighting(); - Log::Write(StringExtensions::Build("LedWiz Nr. {0:00} finished and updater thread stopped.", std::to_string(m_number))); -+ if (s_ledWizUnits.at(m_number)->ShutdownFailed()) -+ throw std::runtime_error(StringExtensions::Build("LedWiz Nr. {0:00} could not turn its outputs off", std::to_string(m_number))); - } - - void LedWiz::AddOutputs() -@@ -484,13 +486,48 @@ LedWiz::LedWizUnit::~LedWizUnit() +@@ -485,15 +486,46 @@ LedWiz::LedWizUnit::~LedWizUnit() void LedWiz::LedWizUnit::Init(Cabinet* cabinet, int minCommandIntervalMs) { m_minCommandIntervalMs = minCommandIntervalMs; -+ // VPE: the gate unit exists before the updater starts, so a gate change made right after init counts it. + if (!IsUpdaterThreadAlive()) + { -+ ResetState(); ++ { ++ std::lock_guard lock(m_valueChangeLocker); ++ m_newOutputValues.fill(49); ++ m_currentOutputValues.fill(0); ++ m_newAfterValueSwitches.fill(0); ++ m_newBeforeValueSwitches.fill(0); ++ m_currentAfterValueSwitches.fill(0); ++ m_currentBeforeValueSwitches.fill(0); ++ m_newValueUpdateRequired = true; ++ m_newSwitchUpdateBeforeValueUpdateRequired = true; ++ m_newSwitchUpdateAfterValueUpdateRequired = true; ++ m_currentValueUpdateRequired = true; ++ m_currentSwitchUpdateBeforeValueUpdateRequired = true; ++ m_currentSwitchUpdateAfterValueUpdateRequired = true; ++ m_updateRequired = true; ++ m_inUseState = InUseStates::Startup; ++ } ++ m_pbaTime = std::chrono::steady_clock::time_point(); + m_gateUnit = OutputGate::Instance().Register(StringExtensions::Build("LedWiz {0:00}", std::to_string(m_number))); + } StartLedWizUpdaterThread(); } -+void LedWiz::LedWizUnit::ResetState() -+{ -+ std::lock_guard lock(m_valueChangeLocker); -+ m_newOutputValues.fill(49); -+ m_currentOutputValues.fill(0); -+ m_newAfterValueSwitches.fill(0); -+ m_newBeforeValueSwitches.fill(0); -+ m_currentAfterValueSwitches.fill(0); -+ m_currentBeforeValueSwitches.fill(0); -+ m_newValueUpdateRequired = true; -+ m_newSwitchUpdateBeforeValueUpdateRequired = true; -+ m_newSwitchUpdateAfterValueUpdateRequired = true; -+ m_currentValueUpdateRequired = true; -+ m_currentSwitchUpdateBeforeValueUpdateRequired = true; -+ m_currentSwitchUpdateAfterValueUpdateRequired = true; -+ m_updateRequired = true; -+ m_inUseState = InUseStates::Startup; -+ m_pbaTime = std::chrono::steady_clock::time_point(); -+} -+ void LedWiz::LedWizUnit::Finish() { TerminateLedWizUpdaterThread(); -+ // Taken before the zeros, so they confirm the closing that was published when the updater ended. -+ OutputGate::Snapshot finalGate {}; ++ OutputGate::Snapshot gate {}; + if (m_gateUnit) -+ finalGate = m_gateUnit->Observe(); -+ m_writeFailed = false; ++ gate = m_gateUnit->Observe(); + m_writeFailed = false; ShutdownLighting(); -+ // A unit that was found but whose handle never opened could not turn its outputs off either. -+ m_shutdownFailed = m_writeFailed && (m_fp != nullptr || IsPresent()); -+ if (m_gateUnit && !m_writeFailed && !finalGate.open) -+ m_gateUnit->Ack(finalGate); + m_shutdownFailed = m_writeFailed && (m_fp != nullptr || IsPresent()); ++ if (m_gateUnit) ++ { ++ if (!m_writeFailed && m_fp) ++ m_gateUnit->AckOff(gate); ++ m_gateUnit->Stop(); ++ } } void LedWiz::LedWizUnit::UpdateValue(LedWizOutput* ledWizOutput) -@@ -613,9 +650,15 @@ void LedWiz::LedWizUnit::LedWizUpdaterDoIt() +@@ -616,10 +648,16 @@ void LedWiz::LedWizUnit::LedWizUpdaterDoIt() { Log::Write(StringExtensions::Build("Updater thread for LedWiz {0:00} started.", std::to_string(m_number))); @@ -2808,35 +2304,40 @@ index c136d75..a597cd8 100644 int failCnt = 0; while (m_keepLedWizUpdaterAlive) { -+ // Until the hardware has the gate state, every update sends the complete state (both SBAs and the PBA). + OutputGate::Snapshot gate = gateUnit->Observe(); + if (!gateUnit->IsAcked(gate)) + ForceFullUpdate(); -+ m_writeFailed = false; + m_writeFailed = false; ++ bool cancelled = false; ++ bool stale = false; try { if (IsPresent()) -@@ -630,14 +673,36 @@ void LedWiz::LedWizUnit::LedWizUpdaterDoIt() +@@ -634,17 +672,39 @@ void LedWiz::LedWizUnit::LedWizUpdaterDoIt() m_inUseState = InUseStates::Running; } - if (m_inUseState == InUseStates::Running) -+ // The observed state governs what is sent. Closed: all off, whatever the values (a gate that opens restores -+ // them before it publishes); they go out in full once the opened generation is observed. +- SendLedWizUpdate(); + bool wrote = true; + if (!gate.open) + ShutdownLighting(); + else if (m_inUseState == InUseStates::Running) - SendLedWizUpdate(); ++ { ++ // VPE: WriteUSB stops before each write once a latch overtook this opening's transfer. ++ OutputGate::Transfer transfer(gateUnit, gate); ++ stale = !SendLedWizUpdate(gate); ++ cancelled = transfer.Cancelled(); ++ } + else -+ // Open and never used: DOF leaves the hardware alone, there is nothing to send and nothing to confirm. + wrote = false; -+ if (m_writeFailed) + if (m_writeFailed) + { -+ // The values that did not get there are sent again. + ForceFullUpdate(); + gateUnit->Fail(gate.generation); + } ++ else if (cancelled || stale) + ForceFullUpdate(); + else if (wrote) + gateUnit->Ack(gate); + else @@ -2849,67 +2350,104 @@ index c136d75..a597cd8 100644 catch (const std::exception& e) { Log::Exception(StringExtensions::Build("A error occurred when updating LedWiz Nr. {0}: {1}", std::to_string(m_number), e.what())); -+ ForceFullUpdate(); + ForceFullUpdate(); + gateUnit->Fail(gate.generation); failCnt++; if (failCnt > MAX_UPDATE_FAIL_COUNT) { -@@ -649,17 +714,38 @@ void LedWiz::LedWizUnit::LedWizUpdaterDoIt() +@@ -654,13 +714,14 @@ void LedWiz::LedWizUnit::LedWizUpdaterDoIt() + } + } - if (m_keepLedWizUpdaterAlive) +- if (m_keepLedWizUpdaterAlive) ++ if (m_keepLedWizUpdaterAlive && !cancelled && !stale) { -+ // A write that did not get through is tried again after the timeout, even when nothing changes (a paused game -+ // sends no updates, and its all-off must still reach the board). A new gate generation is sent without waiting -+ // for DOF's main thread, which a latch from another thread may not wake while it is busy. -+ const bool retry = m_writeFailed; + const bool retry = m_writeFailed; std::unique_lock lock(m_ledWizUpdaterThreadLocker); while (!m_triggerUpdate && m_keepLedWizUpdaterAlive) -- m_updateCondition.wait_for(lock, std::chrono::milliseconds(50)); -+ { + { +- if (m_updateCondition.wait_for(lock, std::chrono::milliseconds(50)) == std::cv_status::timeout && retry) + if (m_updateCondition.wait_for(lock, std::chrono::milliseconds(50)) == std::cv_status::timeout -+ && (retry || OutputGate::Instance().Current().generation != gate.generation)) -+ break; -+ } ++ && (retry || gateUnit->Observe().generation != gate.generation)) + break; + } } - m_triggerUpdate = false; +@@ -668,6 +729,33 @@ void LedWiz::LedWizUnit::LedWizUpdaterDoIt() } Log::Write(StringExtensions::Build("Updater thread for LedWiz {0:00} terminated.", std::to_string(m_number))); ++ // VPE: an updater that gave up turns the outputs off at once, as OutputControllerCompleteBase does: the unit fails every ++ // generation unless that blackout got through, which confirms the closing. One that finished cleanly stops after its ++ // final blackout (Finish). + if (failCnt > MAX_UPDATE_FAIL_COUNT) -+ gateUnit->Die(); -+ else -+ gateUnit->Stop(); ++ { ++ OutputGate::Snapshot before = gateUnit->Observe(); ++ m_writeFailed = false; ++ bool off = false; ++ try ++ { ++ if (IsPresent() && m_fp) ++ { ++ ShutdownLighting(); ++ off = !m_writeFailed; ++ } ++ } ++ catch (const std::exception&) ++ { ++ } ++ if (off) ++ { ++ gateUnit->AckOff(before); ++ gateUnit->Stop(); ++ } ++ else ++ gateUnit->Die(); ++ } m_updaterThreadFinished = true; } -+void LedWiz::LedWizUnit::ForceFullUpdate() -+{ -+ { -+ std::lock_guard lock(m_valueChangeLocker); -+ m_updateRequired = true; -+ } -+ m_pbaTime = std::chrono::steady_clock::time_point(); -+} -+ - void LedWiz::LedWizUnit::UpdateDelay() +@@ -688,15 +776,20 @@ void LedWiz::LedWizUnit::UpdateDelay() + m_lastUpdate = std::chrono::steady_clock::now(); + } + +-void LedWiz::LedWizUnit::SendLedWizUpdate() ++bool LedWiz::LedWizUnit::SendLedWizUpdate(const OutputGate::Snapshot& gate) { - int ms = static_cast(std::chrono::duration_cast(std::chrono::steady_clock::now() - m_lastUpdate).count()); -@@ -727,9 +813,13 @@ void LedWiz::LedWizUnit::WriteUSB(const uint8_t* buf, size_t length) - std::this_thread::sleep_for(std::chrono::milliseconds(s_retryWait[tries])); + if (MathExtensions::IsBetween(m_number, 1, 16)) + { + std::lock_guard updateLock(m_ledWizUpdateLocker); + { + std::lock_guard valueLock(m_valueChangeLocker); ++ // VPE: the values are copied under the gate state they are sent and confirmed with, as in ++ // OutputControllerCompleteBase: once the gate changed, they go out with the new state on the next pass. ++ OutputGate::Snapshot current = m_gateUnit->Observe(); ++ if (current.generation != gate.generation || current.open != gate.open) ++ return false; + if (!m_updateRequired) +- return; ++ return true; + CopyNewToCurrent(); + m_updateRequired = false; } - Log::Error(StringExtensions::Build("LedWiz {0} WriteUSB failed after {1} retries", std::to_string(m_number), std::to_string(std::size(s_retryWait)))); -+ m_writeFailed = true; +@@ -711,6 +804,7 @@ void LedWiz::LedWizUnit::SendLedWizUpdate() + if (m_currentSwitchUpdateAfterValueUpdateRequired || (m_currentSwitchUpdateBeforeValueUpdateRequired && !m_currentValueUpdateRequired) || pbaTimeout) + SBA(m_currentAfterValueSwitches.data()); } - else -+ { - Log::Error(StringExtensions::Build("LedWiz {0} WriteUSB has no file handle", std::to_string(m_number))); -+ m_writeFailed = true; -+ } ++ return true; } - bool LedWiz::LedWizUnit::IsPresent() const + void LedWiz::LedWizUnit::ShutdownLighting() +@@ -742,6 +836,8 @@ void LedWiz::LedWizUnit::WriteUSB(const uint8_t* buf, size_t length) + UpdateDelay(); + for (int tries = 0; tries < static_cast(std::size(s_retryWait)); ++tries) + { ++ if (OutputGate::TransferCancelled()) ++ return; + if (hid_write(m_fp, buf, length) == static_cast(length)) + return; + std::this_thread::sleep_for(std::chrono::milliseconds(s_retryWait[tries])); diff --git a/src/cab/out/lw/LedWiz.h b/src/cab/out/lw/LedWiz.h -index 9f42dc1..7c3c3a0 100644 +index 31bd9ca..1110829 100644 --- a/src/cab/out/lw/LedWiz.h +++ b/src/cab/out/lw/LedWiz.h @@ -1,6 +1,7 @@ @@ -2920,28 +2458,26 @@ index 9f42dc1..7c3c3a0 100644 #include #include #include -@@ -157,6 +158,19 @@ private: - std::chrono::steady_clock::time_point m_lastUpdate; +@@ -118,7 +119,8 @@ private: + + void LedWizUpdaterDoIt(); + void UpdateDelay(); +- void SendLedWizUpdate(); ++ // VPE: false when the gate changed from `gate` before the values were copied: they are sent with the new state. ++ bool SendLedWizUpdate(const OutputGate::Snapshot& gate); + void SBA(const uint8_t* b, uint8_t globalFlashSpeed = 2); + void PBA(const uint8_t* b); + void WriteUSB(const uint8_t* buf, size_t length); +@@ -158,6 +160,7 @@ private: int m_minCommandIntervalMs; std::chrono::steady_clock::time_point m_pbaTime; -+ bool m_writeFailed = false; + bool m_writeFailed = false; + OutputGate::Unit* m_gateUnit = nullptr; -+ bool m_shutdownFailed = false; -+ -+ public: -+ // VPE: whether the outputs could not be turned off when the unit finished. -+ bool ShutdownFailed() const { return m_shutdownFailed; } -+ -+ private: -+ void ForceFullUpdate(); -+ // VPE: the units outlive sessions. A new session starts from all off and unused, so it never sends what the -+ // previous one had requested (a latch sent zeros but kept the values). -+ void ResetState(); - }; - }; + bool m_shutdownFailed = false; + public: diff --git a/src/cab/out/pac/PacDrive.cpp b/src/cab/out/pac/PacDrive.cpp -index 1a2be63..ef76acd 100644 +index e13a317..d40d4de 100644 --- a/src/cab/out/pac/PacDrive.cpp +++ b/src/cab/out/pac/PacDrive.cpp @@ -1,5 +1,6 @@ @@ -2951,35 +2487,8 @@ index 1a2be63..ef76acd 100644 #include "../../../Log.h" #include "../../../general/StringExtensions.h" #include "../../Cabinet.h" -@@ -34,12 +35,15 @@ void PacDrive::Init(Cabinet* cabinet) - - void PacDrive::Finish() - { -+ bool shutdownFailed = false; - if (s_pacDriveInstance) - { - s_pacDriveInstance->Finish(); -- s_pacDriveInstance->ShutdownLighting(); -+ shutdownFailed = !s_pacDriveInstance->ShutdownLighting(); - } - Log::Write("PacDrive finished and updater thread stopped."); -+ if (shutdownFailed) -+ throw std::runtime_error("PacDrive could not turn its outputs off"); - } - - void PacDrive::Update() -@@ -129,23 +133,25 @@ PacDrive::PacDriveUnit::~PacDriveUnit() { TerminatePacDriveUpdaterThread(); } - void PacDrive::PacDriveUnit::Init(Cabinet* cabinet) - { - m_index = PacDriveSingleton::GetInstance().PacDriveGetIndex(); -+ // VPE: the unit outlives a session; the next one starts from all off, not from the last game's outputs. - { - std::lock_guard lock(m_valueChangeLocker); - m_newValue = 0; - m_currentValue = 0; - m_updateRequired = true; +@@ -140,8 +141,12 @@ void PacDrive::PacDriveUnit::Init(Cabinet* cabinet) } -+ // VPE: the gate unit exists before the updater starts; a PacDrive that is not connected counts as failed. if (m_index >= 0) { + if (!IsUpdaterThreadAlive()) @@ -2990,40 +2499,27 @@ index 1a2be63..ef76acd 100644 + OutputGate::Instance().RegisterFailed("PacDrive"); } --void PacDrive::PacDriveUnit::Finish() --{ -- TerminatePacDriveUpdaterThread(); -- ShutdownLighting(); --} -+void PacDrive::PacDriveUnit::Finish() { TerminatePacDriveUpdaterThread(); } - - void PacDrive::PacDriveUnit::UpdateValue(IOutput* output) - { -@@ -177,13 +183,21 @@ void PacDrive::PacDriveUnit::TriggerPacDriveUpdaterThread() - m_updateCondition.notify_one(); - } - --void PacDrive::PacDriveUnit::ShutdownLighting() -+bool PacDrive::PacDriveUnit::ShutdownLighting() - { -+ bool ok = true; + void PacDrive::PacDriveUnit::Finish() { TerminatePacDriveUpdaterThread(); } +@@ -181,7 +186,18 @@ bool PacDrive::PacDriveUnit::ShutdownLighting() + bool ok = true; if (m_index >= 0) { -- PacDriveSetLEDStates(0); -+ // Taken before the zeros, so they confirm the closing that was published when the updater ended. -+ OutputGate::Snapshot finalGate {}; ++ // VPE: the final blackout confirms the closing published before it; the unit stops after it, not before, so it ++ // is not counted as failed while the blackout is sent. ++ OutputGate::Snapshot before {}; + if (m_gateUnit) -+ finalGate = m_gateUnit->Observe(); -+ ok = PacDriveSetLEDStates(0); -+ if (ok && m_gateUnit && !finalGate.open) -+ m_gateUnit->Ack(finalGate); ++ before = m_gateUnit->Observe(); + ok = PacDriveSetLEDStates(0); ++ if (m_gateUnit) ++ { ++ if (ok) ++ m_gateUnit->AckOff(before); ++ m_gateUnit->Stop(); ++ } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } -+ return ok; - } - - void PacDrive::PacDriveUnit::StartPacDriveUpdaterThread() -@@ -220,19 +234,34 @@ void PacDrive::PacDriveUnit::TerminatePacDriveUpdaterThread() + return ok; +@@ -221,19 +237,36 @@ void PacDrive::PacDriveUnit::TerminatePacDriveUpdaterThread() void PacDrive::PacDriveUnit::PacDriveUpdaterDoIt() { @@ -3031,20 +2527,22 @@ index 1a2be63..ef76acd 100644 int failCount = 0; while (m_keepPacDriveUpdaterAlive) { -+ // Until the hardware has the gate state, every pass writes the outputs. + OutputGate::Snapshot gate = gateUnit->Observe(); -+ if (!gateUnit->IsAcked(gate)) -+ { -+ std::lock_guard lock(m_valueChangeLocker); -+ m_updateRequired = true; -+ } try { if (m_index >= 0) { - SendPacDriveUpdate(); -+ // VPE: a failed write is reported and retried on the next pass, without ending the updater. -+ if (SendPacDriveUpdate(gate.open)) ++ bool cancelled = false; ++ bool sent = SendPacDriveUpdate(gate, cancelled); ++ // VPE: an opening a latch overtook is not a failed write; it is sent again in full. ++ if (cancelled) ++ { ++ std::lock_guard lock(m_valueChangeLocker); ++ m_updateRequired = true; ++ continue; ++ } ++ if (sent) + gateUnit->Ack(gate); + else + gateUnit->Fail(gate.generation); @@ -3059,20 +2557,22 @@ index 1a2be63..ef76acd 100644 Log::Exception(StringExtensions::Build("Error occurred when updating PacDrive: {0}", e.what())); failCount++; -@@ -250,27 +279,39 @@ void PacDrive::PacDriveUnit::PacDriveUpdaterDoIt() +@@ -251,31 +284,46 @@ void PacDrive::PacDriveUnit::PacDriveUpdaterDoIt() } m_triggerUpdate = false; } -+ if (failCount > MAX_UPDATE_FAIL_COUNT) ++ // VPE: an updater that gave up turns the outputs off at once, as OutputControllerCompleteBase does: the unit fails every ++ // generation unless that blackout got through, which confirms the closing (ShutdownLighting). One that finished ++ // cleanly stops after its final blackout. ++ if (failCount > MAX_UPDATE_FAIL_COUNT && (m_index < 0 || !ShutdownLighting())) + gateUnit->Die(); -+ else -+ gateUnit->Stop(); m_updaterThreadFinished = true; } -void PacDrive::PacDriveUnit::SendPacDriveUpdate() -+bool PacDrive::PacDriveUnit::SendPacDriveUpdate(bool open) ++bool PacDrive::PacDriveUnit::SendPacDriveUpdate(OutputGate::Snapshot& gate, bool& cancelled) { ++ cancelled = false; if (m_index < 0) - return; + return false; @@ -3080,24 +2580,32 @@ index 1a2be63..ef76acd 100644 std::lock_guard updateLock(m_pacDriveUpdateLocker); uint16_t data; { -+ // VPE: the values are copied under the lock and written without it, so a slow device never holds up the -+ // main thread's value changes (and with them a gate change for the other controllers). std::lock_guard valueLock(m_valueChangeLocker); ++ // VPE: the gate is read with the values it goes out with, as in OutputControllerCompleteBase. Until the hardware has ++ // its state, the outputs are sent. ++ gate = m_gateUnit->Observe(); ++ if (!m_gateUnit->IsAcked(gate)) ++ m_updateRequired = true; if (!m_updateRequired) - return; -- + return true; + CopyNewToCurrent(); m_updateRequired = false; data = m_currentValue; } -- PacDriveSetLEDStates(data); -+ // VPE: the observed gate state governs what is sent; an opening gate restores the values before it publishes. -+ if (PacDriveSetLEDStates(open ? data : 0)) +- if (!PacDriveSetLEDStates(data)) +- { +- std::lock_guard valueLock(m_valueChangeLocker); +- m_updateRequired = true; +- } ++ OutputGate::Transfer transfer(m_gateUnit, gate); ++ bool written = PacDriveSetLEDStates(gate.open ? data : 0); ++ cancelled = transfer.Cancelled(); ++ if (written) + return true; + -+ // VPE: sent again on the next pass. + std::lock_guard valueLock(m_valueChangeLocker); + m_updateRequired = true; + return false; @@ -3105,7 +2613,7 @@ index 1a2be63..ef76acd 100644 void PacDrive::PacDriveUnit::CopyNewToCurrent() { m_currentValue = m_newValue; } diff --git a/src/cab/out/pac/PacDrive.h b/src/cab/out/pac/PacDrive.h -index e9e1876..55fd93c 100644 +index e04bb5c..472bd91 100644 --- a/src/cab/out/pac/PacDrive.h +++ b/src/cab/out/pac/PacDrive.h @@ -1,6 +1,7 @@ @@ -3116,17 +2624,7 @@ index e9e1876..55fd93c 100644 #include #include #include -@@ -45,7 +46,8 @@ private: - void Finish(); - void UpdateValue(IOutput* output); - void TriggerPacDriveUpdaterThread(); -- void ShutdownLighting(); -+ // Returns false if the write failed. -+ bool ShutdownLighting(); - - bool GetUpdateRequired() const { return m_updateRequired; } - -@@ -56,6 +58,7 @@ private: +@@ -56,6 +57,7 @@ private: uint16_t m_currentValue; std::atomic m_updateRequired; int m_index; @@ -3134,21 +2632,37 @@ index e9e1876..55fd93c 100644 std::mutex m_pacDriveUpdateLocker; std::mutex m_valueChangeLocker; -@@ -70,7 +73,8 @@ private: +@@ -70,7 +72,8 @@ private: void StartPacDriveUpdaterThread(); void TerminatePacDriveUpdaterThread(); void PacDriveUpdaterDoIt(); - void SendPacDriveUpdate(); -+ // Returns false if the write failed; the update is then sent again on the next pass. -+ bool SendPacDriveUpdate(bool open); ++ // VPE: reads the gate (`gate`) with the values it sends, under the value lock. `cancelled`: a latch overtook it. ++ bool SendPacDriveUpdate(OutputGate::Snapshot& gate, bool& cancelled); void CopyNewToCurrent(); bool IsUpdaterThreadAlive() const; bool PacDriveSetLEDStates(uint16_t data); diff --git a/src/cab/out/pac/PacDriveSingleton.cpp b/src/cab/out/pac/PacDriveSingleton.cpp -index b5b88a6..c53d5b3 100644 +index a1fc064..8a44c19 100644 --- a/src/cab/out/pac/PacDriveSingleton.cpp +++ b/src/cab/out/pac/PacDriveSingleton.cpp -@@ -374,8 +374,10 @@ std::vector PacDriveSingleton::PacUIOGetIdList() +@@ -1,4 +1,5 @@ + #include "PacDriveSingleton.h" ++#include "../OutputGate.h" + #include "../../../Log.h" + #include "../../../general/StringExtensions.h" + #include +@@ -310,7 +311,8 @@ bool PacDriveSingleton::PacDriveUHIDSetLEDStates(int index, uint16_t data) + return false; + + libusb_device_handle* usbDevice = GetUsbDevice(index); +- if (!usbDevice) ++ // VPE: opening the device takes a while; a latch that came meanwhile stops an opening's transfer before it writes. ++ if (!usbDevice || OutputGate::TransferCancelled()) + return false; + + uint8_t message[4] = { 0, 0, 0, 0 }; +@@ -374,8 +376,10 @@ std::vector PacDriveSingleton::PacUIOGetIdList() return idList; } @@ -3160,99 +2674,56 @@ index b5b88a6..c53d5b3 100644 if (index < 0 || index >= static_cast(m_devices.size())) return false; -@@ -389,26 +391,30 @@ bool PacDriveSingleton::PacLed64SetLEDIntensities(int index, const uint8_t* data - - bool success = true; - int maxLeds = (device.type == DeviceType::PacLED64) ? 64 : 96; -+ int interfaceNumber = (device.type == DeviceType::IPACIO) ? GetUsbInterface(index) : 0; +@@ -395,6 +399,12 @@ bool PacDriveSingleton::PacLed64SetLEDIntensities(int index, const uint8_t* data + int interfaceNumber = GetUsbInterface(index); + for (int i = 0; i < maxLeds; i++) + { ++ if (cancel && cancel()) ++ { ++ if (cancelled) ++ *cancelled = true; ++ return success; ++ } + if (!SendUltimateIOCommand(usbDevice, interfaceNumber, static_cast(i), data[i])) + success = false; + } +@@ -403,6 +413,12 @@ bool PacDriveSingleton::PacLed64SetLEDIntensities(int index, const uint8_t* data -- if (device.type == DeviceType::IPACIO) -+ for (int i = 0; i < maxLeds; i++) + for (int i = 0; i < maxLeds; i++) { -- int interfaceNumber = GetUsbInterface(index); -- for (int i = 0; i < maxLeds; i++) -+ // VPE: one transfer per port, so a full update takes a while; the caller can end it between two ports, also on -+ // an Ultimate I/O. + if (cancel && cancel()) + { + if (cancelled) + *cancelled = true; + return success; + } -+ if (device.type == DeviceType::IPACIO) - { - if (!SendUltimateIOCommand(usbDevice, interfaceNumber, static_cast(i), data[i])) - success = false; -+ continue; - } -- return success; -- } -- -- for (int i = 0; i < maxLeds; i++) -- { uint8_t ledData[2]; ledData[0] = static_cast(i); ledData[1] = data[i]; +@@ -431,7 +447,7 @@ bool PacDriveSingleton::PacLed64SetLEDIntensity(int index, int port, uint8_t int + return false; - int result = libusb_control_transfer(usbDevice, 0x21, 9, 0x0200, 0, ledData, 2, 2000); -- if (result < 0) -+ if (result != 2) - { - success = false; - } -@@ -443,7 +449,7 @@ bool PacDriveSingleton::PacLed64SetLEDIntensity(int index, int port, uint8_t int - - int result = libusb_control_transfer(usbDevice, 0x21, 9, 0x0200, 0, data, 2, 2000); - -- return (result >= 0); -+ return (result == 2); - } - - bool PacDriveSingleton::PacLed64SetLEDStates(int index, int group, uint8_t data) -@@ -486,7 +492,7 @@ bool PacDriveSingleton::PacLed64SetLEDStates(int index, int group, uint8_t data) - ledData[1] = 0; // intensity = 0 - - int result = libusb_control_transfer(usbDevice, 0x21, 9, 0x0200, 0, ledData, 2, 2000); -- if (result < 0) -+ if (result != 2) - { - success = false; - } -@@ -507,7 +513,7 @@ bool PacDriveSingleton::PacLed64SetLEDStates(int index, int group, uint8_t data) - ledData[1] = intensity; - - int result = libusb_control_transfer(usbDevice, 0x21, 9, 0x0200, 0, ledData, 2, 2000); -- if (result < 0) -+ if (result != 2) - { - success = false; - } -@@ -540,7 +546,7 @@ bool PacDriveSingleton::PacLed64SetLEDFadeTime(int index, uint8_t fadeTime) - - int result = libusb_control_transfer(usbDevice, 0x21, 9, 0x0300, 0, data, 2, 2000); - -- return (result >= 0); -+ return (result == 2); - } + libusb_device_handle* usbDevice = GetUsbDevice(index); +- if (!usbDevice) ++ if (!usbDevice || OutputGate::TransferCancelled()) + return false; - hid_device* PacDriveSingleton::GetHidDevice(int index) + if (device.type == DeviceType::IPACIO) diff --git a/src/cab/out/pac/PacDriveSingleton.h b/src/cab/out/pac/PacDriveSingleton.h -index c71dc9d..2fbebff 100644 +index c71dc9d..01698a1 100644 --- a/src/cab/out/pac/PacDriveSingleton.h +++ b/src/cab/out/pac/PacDriveSingleton.h -@@ -38,7 +38,9 @@ public: +@@ -38,7 +38,7 @@ public: std::vector PacLed64GetIdList(); int PacLed64GetIndexForDeviceId(int id); int PacLed64GetDeviceId(int index); - bool PacLed64SetLEDIntensities(int index, const uint8_t* data); -+ // VPE: if given, cancel is asked before each port's transfer; once it returns true, the remaining ports are not sent -+ // and *cancelled is set (the ports sent before have their new intensity). + bool PacLed64SetLEDIntensities(int index, const uint8_t* data, bool (*cancel)() = nullptr, bool* cancelled = nullptr); bool PacLed64SetLEDIntensity(int index, int port, uint8_t intensity); bool PacLed64SetLEDStates(int index, int group, uint8_t data); bool PacLed64SetLEDFadeTime(int index, uint8_t fadeTime); diff --git a/src/cab/out/pac/PacLed64.cpp b/src/cab/out/pac/PacLed64.cpp -index 3a4215f..74f62da 100644 +index 71fcd00..1ea552f 100644 --- a/src/cab/out/pac/PacLed64.cpp +++ b/src/cab/out/pac/PacLed64.cpp @@ -1,4 +1,5 @@ @@ -3273,17 +2744,16 @@ index 3a4215f..74f62da 100644 namespace DOF { -+// VPE: ends an opening's transfer once the gate is latched. -+static bool GateLatched() { return OutputGate::Instance().IsLatched(); } ++// VPE: asked before each port of an opening's transfer: true once a latch overtook it. ++static bool GateLatched() { return OutputGate::TransferCancelled(); } + std::map PacLed64::s_pacLed64Units; bool PacLed64::s_unitsInitialized = false; -@@ -221,14 +226,19 @@ void PacLed64::PacLed64Unit::Init(Cabinet* cabinet) +@@ -221,14 +226,18 @@ void PacLed64::PacLed64Unit::Init(Cabinet* cabinet) { m_index = PacDriveSingleton::GetInstance().PacLed64GetIndexForDeviceId(m_id); -+ // VPE: the gate unit exists before the updater starts; a PacLed64 that is not connected counts as failed. + std::string unitName = StringExtensions::Build("PacLed64 {0}", std::to_string(m_id)); if (m_index >= 0) { @@ -3299,40 +2769,36 @@ index 3a4215f..74f62da 100644 Log::Warning(StringExtensions::Build("PacLed64 device {0} not found", std::to_string(m_id))); } } -@@ -236,7 +246,15 @@ void PacLed64::PacLed64Unit::Init(Cabinet* cabinet) +@@ -236,16 +245,27 @@ void PacLed64::PacLed64Unit::Init(Cabinet* cabinet) void PacLed64::PacLed64Unit::Finish() { TerminatePacLed64UpdaterThread(); -- ShutdownLighting(); -+ try -+ { -+ ShutdownLighting(); -+ } -+ catch (...) -+ { -+ m_index = -1; -+ throw; -+ } - - m_index = -1; - } -@@ -274,7 +292,14 @@ void PacLed64::PacLed64Unit::ShutdownLighting() - if (IsPresent()) ++ // VPE: the final blackout confirms the closing published before it; the unit stops after it, not before, so it is not ++ // counted as failed while the blackout is sent. ++ bool present = IsPresent() && m_gateUnit; ++ OutputGate::Snapshot before {}; ++ if (present) ++ before = m_gateUnit->Observe(); + try { - EnforceMinUpdateInterval(); -- PacDriveSingleton::GetInstance().PacLed64SetLEDStates(m_index, 0, 0); -+ // Taken before the zeros, so they confirm the closing that was published when the updater ended. -+ OutputGate::Snapshot finalGate {}; -+ if (m_gateUnit) -+ finalGate = m_gateUnit->Observe(); -+ if (!PacDriveSingleton::GetInstance().PacLed64SetLEDStates(m_index, 0, 0)) -+ throw std::runtime_error("PacLed64: turning the outputs off failed"); -+ if (m_gateUnit && !finalGate.open) -+ m_gateUnit->Ack(finalGate); - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - std::fill(m_lastStateSent.begin(), m_lastStateSent.end(), false); + ShutdownLighting(); ++ if (present) ++ m_gateUnit->AckOff(before); } -@@ -314,6 +339,7 @@ void PacLed64::PacLed64Unit::TerminatePacLed64UpdaterThread() + catch (...) + { ++ if (present) ++ m_gateUnit->Stop(); + m_index = -1; + throw; + } +- ++ if (present) ++ m_gateUnit->Stop(); + m_index = -1; + } + +@@ -323,6 +343,7 @@ void PacLed64::PacLed64Unit::TerminatePacLed64UpdaterThread() void PacLed64::PacLed64Unit::PacLed64UpdaterDoIt() { @@ -3340,7 +2806,7 @@ index 3a4215f..74f62da 100644 try { ResetFadeTime(); -@@ -321,6 +347,7 @@ void PacLed64::PacLed64Unit::PacLed64UpdaterDoIt() +@@ -330,6 +351,7 @@ void PacLed64::PacLed64Unit::PacLed64UpdaterDoIt() catch (const std::exception& e) { Log::Exception(StringExtensions::Build("Exception occurred while setting fade time for PacLed64 {0} to 0: {1}", std::to_string(m_index), e.what())); @@ -3348,27 +2814,22 @@ index 3a4215f..74f62da 100644 m_updaterThreadFinished = true; return; } -@@ -328,16 +355,34 @@ void PacLed64::PacLed64Unit::PacLed64UpdaterDoIt() +@@ -337,16 +359,27 @@ void PacLed64::PacLed64Unit::PacLed64UpdaterDoIt() int failCount = 0; while (m_keepPacLed64UpdaterAlive) { -+ // Until the hardware has the gate state, every pass sends all intensities. + OutputGate::Snapshot gate = gateUnit->Observe(); -+ if (!gateUnit->IsAcked(gate)) -+ { -+ m_forceFullUpdate = true; -+ m_updateRequired = true; -+ } try { if (IsPresent()) { - SendPacLed64Update(); -+ // VPE: a failed write is reported and retried on the next pass, without ending the updater. + bool failed = false; -+ if (SendPacLed64Update(gate.open, failed)) ++ bool cancelled = false; ++ if (SendPacLed64Update(gate, failed, cancelled)) + gateUnit->Ack(gate); -+ else if (failed) ++ // VPE: an opening a latch overtook is not a failed write; it is sent again in full. ++ else if (failed && !cancelled) + gateUnit->Fail(gate.generation); } + else @@ -3377,78 +2838,115 @@ index 3a4215f..74f62da 100644 } catch (const std::exception& e) { -+ // VPE: what was sent before the failure is not known: the next pass sends everything. -+ m_forceFullUpdate = true; -+ m_updateRequired = true; ++ RequestFullUpdate(); + gateUnit->Fail(gate.generation); Log::Exception(StringExtensions::Build("Error occurred when updating PacLed64 {0}: {1}", std::to_string(m_id), e.what())); failCount++; -@@ -356,72 +401,109 @@ void PacLed64::PacLed64Unit::PacLed64UpdaterDoIt() +@@ -365,30 +398,78 @@ void PacLed64::PacLed64Unit::PacLed64UpdaterDoIt() } m_triggerUpdate = false; } ++ // VPE: an updater that gave up turns the outputs off at once, as OutputControllerCompleteBase does: the unit fails every ++ // generation unless that blackout got through, which confirms the closing. One that finished cleanly stops after its ++ // final blackout (Finish). + if (failCount > MAX_UPDATE_FAIL_COUNT) -+ gateUnit->Die(); -+ else -+ gateUnit->Stop(); ++ { ++ OutputGate::Snapshot before = gateUnit->Observe(); ++ bool off = false; ++ try ++ { ++ if (IsPresent()) ++ { ++ ShutdownLighting(); ++ off = true; ++ } ++ } ++ catch (const std::exception&) ++ { ++ } ++ if (off) ++ { ++ gateUnit->AckOff(before); ++ gateUnit->Stop(); ++ } ++ else ++ gateUnit->Die(); ++ } m_updaterThreadFinished = true; } -void PacLed64::PacLed64Unit::SendPacLed64Update() -+bool PacLed64::PacLed64Unit::SendPacLed64Update(bool open, bool& failed) ++void PacLed64::PacLed64Unit::RequestFullUpdate() ++{ ++ std::lock_guard valueLock(m_valueChangeLocker); ++ m_forceFullUpdate = true; ++ m_updateRequired = true; ++} ++ ++bool PacLed64::PacLed64Unit::SendPacLed64Update(OutputGate::Snapshot& gate, bool& failed, bool& cancelled) { + failed = false; ++ cancelled = false; if (!IsPresent()) - return; + return true; std::lock_guard updateLock(m_pacLed64UpdateLocker); + std::array target {}; -+ bool full; { -+ // VPE: the values are copied under the lock and written without it, so a slow device never holds up the main -+ // thread's value changes (and with them a gate change for the other controllers). std::lock_guard valueLock(m_valueChangeLocker); ++ // VPE: the gate is read with the values it goes out with, as in OutputControllerCompleteBase. Until the hardware has ++ // its state, every output is sent. ++ gate = m_gateUnit->Observe(); ++ if (!m_gateUnit->IsAcked(gate)) ++ { ++ m_forceFullUpdate = true; ++ m_updateRequired = true; ++ } if (!m_updateRequired && !m_forceFullUpdate) - return; -- + return true; + CopyNewToCurrent(); m_updateRequired = false; -+ full = m_forceFullUpdate; -+ // VPE: the observed gate state governs what is sent; an opening gate restores the values before it publishes. -+ if (open) ++ if (gate.open) + std::copy_n(m_currentValue.begin(), 64, target.begin()); } ++ const bool open = gate.open; ++ OutputGate::Transfer transfer(m_gateUnit, gate); -- int updatesRequired = 0; -- if (!m_forceFullUpdate) -+ int changed = 0; -+ for (int o = 0; o < 64; o++) + int updatesRequired = 0; + if (!m_forceFullUpdate) { -- for (int o = 0; o < 64; o++) -- { + for (int o = 0; o < 64; o++) + { - if (m_currentValue[o] != m_lastValueSent[o] || (m_currentValue[o] > 0) != m_lastStateSent[o]) -- updatesRequired++; -- } -+ if (target[o] != m_lastValueSent[o] || (target[o] > 0) != m_lastStateSent[o]) -+ changed++; ++ if (target[o] != m_lastValueSent[o] || (target[o] > 0) != m_lastStateSent[o]) + updatesRequired++; + } } - -- if (m_forceFullUpdate || updatesRequired > m_fullUpdateThreshold) -+ if (full || changed > m_fullUpdateThreshold) +@@ -396,41 +477,56 @@ void PacLed64::PacLed64Unit::SendPacLed64Update() + if (m_forceFullUpdate || updatesRequired > m_fullUpdateThreshold) { EnforceMinUpdateInterval(); - bool written = PacDriveSingleton::GetInstance().PacLed64SetLEDIntensities(m_index, m_currentValue.data()); -+ // VPE: a latch before or during the transfer makes this opening's update obsolete (see below); the ports it -+ // reached are not known to the next pass, which sends all of them. -+ bool cancelled = false; + bool written = PacDriveSingleton::GetInstance().PacLed64SetLEDIntensities(m_index, target.data(), open ? GateLatched : nullptr, &cancelled); m_lastCommand = std::chrono::steady_clock::now(); -- -- if (written) + if (cancelled) ++ { ++ RequestFullUpdate(); ++ return false; ++ } ++ if (!written) ++ { ++ RequestFullUpdate(); ++ failed = true; ++ return false; ++ } + +- if (written) ++ for (int i = 0; i < 64; i++) { - m_lastValueSent = m_currentValue; - for (int i = 0; i < 64; i++) @@ -3456,84 +2954,52 @@ index 3a4215f..74f62da 100644 - m_lastStateSent[i] = (m_lastValueSent[i] > 0); - } - m_forceFullUpdate = false; -+ std::lock_guard valueLock(m_valueChangeLocker); -+ m_forceFullUpdate = true; -+ m_updateRequired = true; -+ return false; ++ m_lastValueSent[i] = target[i]; ++ m_lastStateSent[i] = (target[i] > 0); } - else -+ if (!written) -+ { -+ std::lock_guard valueLock(m_valueChangeLocker); - m_forceFullUpdate = true; -- } -- else -- { -+ m_updateRequired = true; -+ failed = true; -+ return false; -+ } +- m_forceFullUpdate = true; ++ std::lock_guard valueLock(m_valueChangeLocker); ++ m_forceFullUpdate = false; + } + else + { for (int o = 0; o < 64; o++) { - if (m_currentValue[o] == m_lastValueSent[o] && (m_currentValue[o] > 0) == m_lastStateSent[o]) -- continue; -- -- EnforceMinUpdateInterval(); ++ if (target[o] == m_lastValueSent[o] && (target[o] > 0) == m_lastStateSent[o]) + continue; + + EnforceMinUpdateInterval(); - bool written = PacDriveSingleton::GetInstance().PacLed64SetLEDIntensity(m_index, o, m_currentValue[o]); -- m_lastCommand = std::chrono::steady_clock::now(); -- if (!written) -- { ++ if (open && GateLatched()) ++ { ++ RequestFullUpdate(); ++ cancelled = true; ++ return false; ++ } ++ bool written = PacDriveSingleton::GetInstance().PacLed64SetLEDIntensity(m_index, o, target[o]); + m_lastCommand = std::chrono::steady_clock::now(); + if (!written) + { - m_forceFullUpdate = true; -- continue; -- } -+ m_lastValueSent[o] = target[o]; -+ m_lastStateSent[o] = target[o] > 0; -+ } -+ std::lock_guard valueLock(m_valueChangeLocker); -+ m_forceFullUpdate = false; -+ return true; -+ } ++ RequestFullUpdate(); ++ failed = true; + continue; + } - m_lastValueSent[o] = m_currentValue[o]; - m_lastStateSent[o] = (m_currentValue[o] > 0); -+ for (int o = 0; o < 64; o++) -+ { -+ if (target[o] == m_lastValueSent[o] && (target[o] > 0) == m_lastStateSent[o]) -+ continue; -+ EnforceMinUpdateInterval(); -+ // VPE: each write waits for the minimum interval, so an update of many ports takes a while. Once the gate is -+ // latched, the rest of an opening's update is obsolete: the next pass sends the closing in full instead. -+ if (open && OutputGate::Instance().IsLatched()) -+ { -+ std::lock_guard valueLock(m_valueChangeLocker); -+ m_forceFullUpdate = true; -+ m_updateRequired = true; -+ return false; -+ } -+ bool written = PacDriveSingleton::GetInstance().PacLed64SetLEDIntensity(m_index, o, target[o]); -+ m_lastCommand = std::chrono::steady_clock::now(); -+ if (!written) -+ { -+ failed = true; -+ continue; ++ m_lastValueSent[o] = target[o]; ++ m_lastStateSent[o] = (target[o] > 0); } -+ m_lastValueSent[o] = target[o]; -+ m_lastStateSent[o] = target[o] > 0; } -+ if (failed) -+ { -+ // VPE: what a failed port has is not known: the next pass sends everything. -+ std::lock_guard valueLock(m_valueChangeLocker); -+ m_forceFullUpdate = true; -+ m_updateRequired = true; -+ return false; -+ } -+ return true; ++ return !failed; } void PacLed64::PacLed64Unit::CopyNewToCurrent() { m_currentValue = m_newValue; } diff --git a/src/cab/out/pac/PacLed64.h b/src/cab/out/pac/PacLed64.h -index 640daa8..173532d 100644 +index 640daa8..da670ef 100644 --- a/src/cab/out/pac/PacLed64.h +++ b/src/cab/out/pac/PacLed64.h @@ -1,6 +1,7 @@ @@ -3552,19 +3018,20 @@ index 640daa8..173532d 100644 std::vector m_newValue; std::vector m_currentValue; -@@ -105,7 +107,9 @@ private: +@@ -105,7 +107,10 @@ private: void StartPacLed64UpdaterThread(); void TerminatePacLed64UpdaterThread(); void PacLed64UpdaterDoIt(); - void SendPacLed64Update(); -+ // Returns false if a latch of the gate ended an opening's update early; the next pass sends everything. -+ // Returns true once the update is sent. `failed` is set when a write failed; the next pass sends everything. -+ bool SendPacLed64Update(bool open, bool& failed); ++ // VPE: reads the gate (`gate`) with the values it sends, under the value lock. `cancelled`: a latch overtook it. ++ bool SendPacLed64Update(OutputGate::Snapshot& gate, bool& failed, bool& cancelled); ++ // VPE: the next pass sends every output. Takes the value lock. ++ void RequestFullUpdate(); void CopyNewToCurrent(); void ResetFadeTime(); void EnforceMinUpdateInterval(); diff --git a/src/cab/out/pac/PacUIO.cpp b/src/cab/out/pac/PacUIO.cpp -index 894e0ed..74c3cf3 100644 +index e35bbf8..c6616c0 100644 --- a/src/cab/out/pac/PacUIO.cpp +++ b/src/cab/out/pac/PacUIO.cpp @@ -1,5 +1,6 @@ @@ -3578,27 +3045,13 @@ index 894e0ed..74c3cf3 100644 namespace DOF { -+// VPE: ends an opening's transfer once the gate is latched. -+static bool GateLatched() { return OutputGate::Instance().IsLatched(); } ++// VPE: asked before each port of an opening's transfer: true once a latch overtook it. ++static bool GateLatched() { return OutputGate::TransferCancelled(); } + std::map PacUIO::s_pacUIOUnits; bool PacUIO::s_unitsInitialized = false; -@@ -64,7 +68,6 @@ void PacUIO::Finish() - { - InitializeUnits(); - s_pacUIOUnits.at(m_id)->Finish(); -- s_pacUIOUnits.at(m_id)->ShutdownLighting(); - Log::Write(StringExtensions::Build("PacUIO Id:{0} finished and updater thread stopped.", std::to_string(m_id))); - } - -@@ -159,17 +162,30 @@ PacUIO::PacUIOUnit::~PacUIOUnit() { TerminatePacUIOUpdaterThread(); } - - void PacUIO::PacUIOUnit::Init(Cabinet* cabinet) - { -+ // VPE: the units live as long as the process. Each session finds the device again and starts from nothing, so -+ // values and the enumeration index of an earlier session are never sent. - if (!IsUpdaterThreadAlive()) +@@ -162,13 +166,23 @@ void PacUIO::PacUIOUnit::Init(Cabinet* cabinet) { m_pdSingleton = &PacDriveSingleton::GetInstance(); m_index = m_pdSingleton->PacUIOGetIndexForDeviceId(m_id); @@ -3615,8 +3068,8 @@ index 894e0ed..74c3cf3 100644 + std::fill_n(m_currentValue, 96, 0); + std::fill_n(m_lastValueSent, 96, 0); + std::fill_n(m_lastStateSent, 96, false); -+ m_forceFullUpdate = true; + m_updateRequired = true; ++ m_forceFullUpdate = true; + } + std::string unitName = StringExtensions::Build("PacUIO {0}", std::to_string(m_id)); + if (!IsPresent()) @@ -3626,21 +3079,38 @@ index 894e0ed..74c3cf3 100644 + return; + } + m_gateUnit = OutputGate::Instance().Register(unitName); -+ m_started = true; } StartPacUIOUpdaterThread(); } -@@ -177,6 +193,9 @@ void PacUIO::PacUIOUnit::Init(Cabinet* cabinet) +@@ -176,7 +190,26 @@ void PacUIO::PacUIOUnit::Init(Cabinet* cabinet) void PacUIO::PacUIOUnit::Finish() { TerminatePacUIOUpdaterThread(); -+ if (!m_started) -+ return; -+ m_started = false; - ShutdownLighting(); +- ShutdownLighting(); ++ // VPE: the final blackout confirms the closing published before it; the unit stops after it, not before, so it is not ++ // counted as failed while the blackout is sent. ++ bool present = IsPresent() && m_gateUnit; ++ OutputGate::Snapshot before {}; ++ if (present) ++ before = m_gateUnit->Observe(); ++ try ++ { ++ ShutdownLighting(); ++ if (present) ++ m_gateUnit->AckOff(before); ++ } ++ catch (...) ++ { ++ if (present) ++ m_gateUnit->Stop(); ++ throw; ++ } ++ if (present) ++ m_gateUnit->Stop(); } -@@ -238,6 +257,7 @@ void PacUIO::PacUIOUnit::TriggerPacUIOUpdaterThread() + void PacUIO::PacUIOUnit::UpdateValue(IOutput* output) +@@ -237,6 +270,7 @@ void PacUIO::PacUIOUnit::TriggerPacUIOUpdaterThread() void PacUIO::PacUIOUnit::PacUIOUpdaterDoIt() { @@ -3648,7 +3118,7 @@ index 894e0ed..74c3cf3 100644 try { ResetFadeTime(); -@@ -245,6 +265,7 @@ void PacUIO::PacUIOUnit::PacUIOUpdaterDoIt() +@@ -244,6 +278,7 @@ void PacUIO::PacUIOUnit::PacUIOUpdaterDoIt() catch (const std::exception& e) { Log::Exception(StringExtensions::Build("A exception occurred while setting the fadetime for PacUIO {0} to 0.", std::to_string(m_index))); @@ -3656,28 +3126,22 @@ index 894e0ed..74c3cf3 100644 m_updaterThreadFinished = true; return; } -@@ -252,16 +273,38 @@ void PacUIO::PacUIOUnit::PacUIOUpdaterDoIt() +@@ -251,16 +286,27 @@ void PacUIO::PacUIOUnit::PacUIOUpdaterDoIt() int failCnt = 0; while (m_keepPacUIOUpdaterAlive.load()) { -+ // Until the hardware has the gate state, every pass sends all intensities. + OutputGate::Snapshot gate = gateUnit->Observe(); -+ if (!gateUnit->IsAcked(gate)) -+ { -+ std::lock_guard lock(m_valueChangeLocker); -+ m_forceFullUpdate = true; -+ m_updateRequired = true; -+ } try { if (IsPresent()) { - SendPacUIOUpdate(); -+ // VPE: a failed write is reported and retried on the next pass, without ending the updater. + bool failed = false; -+ if (SendPacUIOUpdate(gate.open, failed)) ++ bool cancelled = false; ++ if (SendPacUIOUpdate(gate, failed, cancelled)) + gateUnit->Ack(gate); -+ else if (failed) ++ // VPE: an opening a latch overtook is not a failed write; it is sent again in full. ++ else if (failed && !cancelled) + gateUnit->Fail(gate.generation); } + else @@ -3686,35 +3150,61 @@ index 894e0ed..74c3cf3 100644 } catch (const std::exception& e) { -+ // VPE: what was sent before the failure is not known: the next pass sends everything. -+ { -+ std::lock_guard lock(m_valueChangeLocker); -+ m_forceFullUpdate = true; -+ m_updateRequired = true; -+ } ++ RequestFullUpdate(); + gateUnit->Fail(gate.generation); Log::Exception(StringExtensions::Build("A error occurred when updating PacUIO {0}", std::to_string(m_id))); failCnt++; -@@ -280,68 +323,101 @@ void PacUIO::PacUIOUnit::PacUIOUpdaterDoIt() +@@ -279,68 +325,129 @@ void PacUIO::PacUIOUnit::PacUIOUpdaterDoIt() } m_triggerUpdate.store(false); } ++ // VPE: an updater that gave up turns the outputs off at once, as OutputControllerCompleteBase does: the unit fails every ++ // generation unless that blackout got through, which confirms the closing. One that finished cleanly stops after its ++ // final blackout (Finish). + if (failCnt > MAX_UPDATE_FAIL_COUNT) -+ gateUnit->Die(); -+ else -+ gateUnit->Stop(); ++ { ++ OutputGate::Snapshot before = gateUnit->Observe(); ++ bool off = false; ++ try ++ { ++ if (IsPresent()) ++ { ++ ShutdownLighting(); ++ off = true; ++ } ++ } ++ catch (const std::exception&) ++ { ++ } ++ if (off) ++ { ++ gateUnit->AckOff(before); ++ gateUnit->Stop(); ++ } ++ else ++ gateUnit->Die(); ++ } m_updaterThreadFinished = true; } -void PacUIO::PacUIOUnit::SendPacUIOUpdate() -+bool PacUIO::PacUIOUnit::SendPacUIOUpdate(bool open, bool& failed) ++void PacUIO::PacUIOUnit::RequestFullUpdate() ++{ ++ std::lock_guard valueLock(m_valueChangeLocker); ++ m_forceFullUpdate = true; ++ m_updateRequired = true; ++} ++ ++bool PacUIO::PacUIOUnit::SendPacUIOUpdate(OutputGate::Snapshot& gate, bool& failed, bool& cancelled) { + failed = false; ++ cancelled = false; if (!IsPresent()) { - m_forceFullUpdate = true; +- m_forceFullUpdate = true; - return; ++ RequestFullUpdate(); + return true; } @@ -3723,38 +3213,40 @@ index 894e0ed..74c3cf3 100644 + uint8_t target[96] = {}; { std::lock_guard valueLock(m_valueChangeLocker); ++ // VPE: the gate is read with the values it goes out with, as in OutputControllerCompleteBase. Until the hardware has ++ // its state, every output is sent. ++ gate = m_gateUnit->Observe(); ++ if (!m_gateUnit->IsAcked(gate)) ++ { ++ m_forceFullUpdate = true; ++ m_updateRequired = true; ++ } if (!m_updateRequired && !m_forceFullUpdate) - return; + return true; CopyNewToCurrent(); m_updateRequired = false; -+ // VPE: the observed gate state governs what is sent; an opening gate restores the values before it publishes. -+ if (open) ++ if (gate.open) + std::copy(m_currentValue, m_currentValue + 96, target); } ++ const bool open = gate.open; ++ OutputGate::Transfer transfer(m_gateUnit, gate); -- int updatesRequired = 0; -- if (!m_forceFullUpdate) -+ int changed = 0; -+ for (int o = 0; o < 96; o++) + int updatesRequired = 0; + if (!m_forceFullUpdate) { -- for (int o = 0; o < 96; o++) -- { + for (int o = 0; o < 96; o++) + { - if (m_currentValue[o] != m_lastValueSent[o] || (m_currentValue[o] > 0) != m_lastStateSent[o]) -- updatesRequired++; -- } -+ if (target[o] != m_lastValueSent[o] || (target[o] > 0) != m_lastStateSent[o]) -+ changed++; ++ if (target[o] != m_lastValueSent[o] || (target[o] > 0) != m_lastStateSent[o]) + updatesRequired++; + } } -- if (m_forceFullUpdate || updatesRequired > 50) -+ if (m_forceFullUpdate || changed > 50) + if (m_forceFullUpdate || updatesRequired > 50) { - if (m_pdSingleton->PacLed64SetLEDIntensities(m_index, m_currentValue)) -+ // VPE: a latch before or during the transfer makes this opening's update obsolete; the ports it reached are not -+ // known to the next pass, which sends all of them. -+ bool cancelled = false; + bool written = m_pdSingleton->PacLed64SetLEDIntensities(m_index, target, open ? GateLatched : nullptr, &cancelled); + if (cancelled) { @@ -3764,125 +3256,57 @@ index 894e0ed..74c3cf3 100644 - m_lastStateSent[i] = (m_lastValueSent[i] > 0); - } - m_forceFullUpdate = false; -+ std::lock_guard valueLock(m_valueChangeLocker); -+ m_forceFullUpdate = true; -+ m_updateRequired = true; ++ RequestFullUpdate(); + return false; } - else +- m_forceFullUpdate = true; + if (!written) + { -+ std::lock_guard valueLock(m_valueChangeLocker); - m_forceFullUpdate = true; -+ m_updateRequired = true; ++ RequestFullUpdate(); + failed = true; + return false; + } + std::copy(target, target + 96, m_lastValueSent); + for (int i = 0; i < 96; i++) + m_lastStateSent[i] = (m_lastValueSent[i] > 0); -+ // VPE: upstream never cleared it, so every update was a full one. ++ std::lock_guard valueLock(m_valueChangeLocker); + m_forceFullUpdate = false; -+ return true; } -- else -+ -+ for (int o = 0; o < 96; o++) + else { -- for (int o = 0; o < 96; o++) -+ if (target[o] == m_lastValueSent[o] && (target[o] > 0) == m_lastStateSent[o]) -+ continue; -+ // VPE: once the gate is latched, the rest of an opening's update is obsolete: the next pass sends the closing. -+ if (open && OutputGate::Instance().IsLatched()) + for (int o = 0; o < 96; o++) { - if (m_currentValue[o] == m_lastValueSent[o] && (m_currentValue[o] > 0) == m_lastStateSent[o]) -- continue; -- ++ if (target[o] == m_lastValueSent[o] && (target[o] > 0) == m_lastStateSent[o]) + continue; + - if (!m_pdSingleton->PacLed64SetLEDIntensity(m_index, o, m_currentValue[o])) -- { ++ if (open && GateLatched()) ++ { ++ RequestFullUpdate(); ++ cancelled = true; ++ return false; ++ } ++ if (!m_pdSingleton->PacLed64SetLEDIntensity(m_index, o, target[o])) + { - m_forceFullUpdate = true; -- continue; -- } ++ RequestFullUpdate(); ++ failed = true; + continue; + } - m_lastValueSent[o] = m_currentValue[o]; - m_lastStateSent[o] = (m_currentValue[o] > 0); -+ std::lock_guard valueLock(m_valueChangeLocker); -+ m_forceFullUpdate = true; -+ m_updateRequired = true; -+ return false; -+ } -+ if (!m_pdSingleton->PacLed64SetLEDIntensity(m_index, o, target[o])) -+ { -+ failed = true; -+ continue; ++ m_lastValueSent[o] = target[o]; ++ m_lastStateSent[o] = (target[o] > 0); } -+ m_lastValueSent[o] = target[o]; -+ m_lastStateSent[o] = target[o] > 0; } -+ if (failed) -+ { -+ // VPE: what a failed port has is not known: the next pass sends everything. -+ std::lock_guard valueLock(m_valueChangeLocker); -+ m_forceFullUpdate = true; -+ m_updateRequired = true; -+ return false; -+ } -+ return true; ++ return !failed; } void PacUIO::PacUIOUnit::ShutdownLighting() -@@ -349,7 +425,14 @@ void PacUIO::PacUIOUnit::ShutdownLighting() - Log::Write("PacUIO.ShutdownLighting"); - if (!IsPresent()) - return; -- m_pdSingleton->PacLed64SetLEDStates(m_index, 0, 0); -+ // Taken before the zeros, so they confirm the closing that was published when the updater ended. -+ OutputGate::Snapshot finalGate {}; -+ if (m_gateUnit) -+ finalGate = m_gateUnit->Observe(); -+ if (!m_pdSingleton->PacLed64SetLEDStates(m_index, 0, 0)) -+ throw std::runtime_error("PacUIO: turning the outputs off failed"); -+ if (m_gateUnit && !finalGate.open) -+ m_gateUnit->Ack(finalGate); - std::fill_n(m_lastStateSent, 96, false); - } - -@@ -366,24 +449,19 @@ bool PacUIO::PacUIOUnit::IsPresent() - return m_index >= 0; - } - -+// Nothing calls the hot-plug handlers yet: a board plugged in again during a session stays dark until the next one. - void PacUIO::PacUIOUnit::OnPacAttached(int index) - { -- m_index = m_pdSingleton->PacLed64GetIndexForDeviceId(m_id); -- InitUnit(); -- TriggerPacUIOUpdaterThread(); --} -- --void PacUIO::PacUIOUnit::OnPacRemoved(int index) { m_index = m_pdSingleton->PacLed64GetIndexForDeviceId(m_id); } -- --void PacUIO::PacUIOUnit::InitUnit() --{ -- if (m_index >= 0) -+ m_index = m_pdSingleton->PacUIOGetIndexForDeviceId(m_id); -+ // VPE: a board plugged in again gets the complete current state, through the gate, from the updater. - { -- std::fill_n(m_lastValueSent, 96, 0); -- m_pdSingleton->PacLed64SetLEDIntensities(m_index, m_lastValueSent); -- std::fill_n(m_lastStateSent, 96, false); -- std::fill_n(m_lastValueSent, 96, 0); -+ std::lock_guard lock(m_valueChangeLocker); -+ m_forceFullUpdate = true; -+ m_updateRequired = true; - } -+ TriggerPacUIOUpdaterThread(); - } - -+void PacUIO::PacUIOUnit::OnPacRemoved(int index) { m_index = m_pdSingleton->PacUIOGetIndexForDeviceId(m_id); } -+ - } -\ No newline at end of file diff --git a/src/cab/out/pac/PacUIO.h b/src/cab/out/pac/PacUIO.h -index 0da2310..60f089b 100644 +index 0da2310..1be7c1a 100644 --- a/src/cab/out/pac/PacUIO.h +++ b/src/cab/out/pac/PacUIO.h @@ -1,6 +1,7 @@ @@ -3901,61 +3325,27 @@ index 0da2310..60f089b 100644 class PacDriveSingleton* m_pdSingleton = nullptr; uint8_t m_newValue[96]; -@@ -54,6 +56,8 @@ private: - - bool m_updateRequired = true; - bool m_forceFullUpdate = false; -+ // VPE: whether this session started the unit, so only a started unit's board is turned off when it finishes. -+ bool m_started = false; - - std::mutex m_pacUIOUpdateLocker; - std::mutex m_valueChangeLocker; -@@ -82,9 +86,10 @@ private: +@@ -82,7 +84,10 @@ private: private: void CopyNewToCurrent(); void PacUIOUpdaterDoIt(); - void SendPacUIOUpdate(); -+ // VPE: false if a latch ended an opening's update early (the gate's opening was then not sent). -+ // Returns true once the update is sent. `failed` is set when a write failed; the next pass sends everything. -+ bool SendPacUIOUpdate(bool open, bool& failed); ++ // VPE: reads the gate (`gate`) with the values it sends, under the value lock. `cancelled`: a latch overtook it. ++ bool SendPacUIOUpdate(OutputGate::Snapshot& gate, bool& failed, bool& cancelled); ++ // VPE: the next pass sends every output. Takes the value lock. ++ void RequestFullUpdate(); void ResetFadeTime(); -- void InitUnit(); + void InitUnit(); - bool IsPresent(); - void OnPacAttached(int index); diff --git a/src/cab/out/pinone/PinOne.cpp b/src/cab/out/pinone/PinOne.cpp -index 0cce88a..cc59c9d 100644 +index 4fedb04..c329712 100644 --- a/src/cab/out/pinone/PinOne.cpp +++ b/src/cab/out/pinone/PinOne.cpp -@@ -172,7 +172,7 @@ void PinOne::UpdateOutputs(const std::vector& newOutputValues) - int lim = std::min(i + 7, count); - for (int j = i; j < lim; ++j) - { -- if (newOutputValues[j] != m_oldOutputValues[j]) -+ if (m_forceFullTransfer || newOutputValues[j] != m_oldOutputValues[j]) - { - UpdateDelay(); - std::vector buf(9); -@@ -180,13 +180,16 @@ void PinOne::UpdateOutputs(const std::vector& newOutputValues) - buf[1] = pfx; - std::copy(newOutputValues.begin() + i, newOutputValues.begin() + lim, buf.begin() + 2); - -+ // VPE: the cache only learns what the device got. - if (m_comPort == HidSentinel) - { -- if (m_hidDevice) -- m_hidDevice->WriteUSB(buf); -+ if (!m_hidDevice || !m_hidDevice->WriteUSB(buf)) -+ throw std::runtime_error(StringExtensions::Build("Writing to {0} {1} failed", "PinOne", GetName())); - } - else if (m_pinOneCommunication) - m_pinOneCommunication->Write(buf); -+ else -+ throw std::runtime_error(StringExtensions::Build("{0} {1} is not connected", "PinOne", GetName())); +@@ -241,18 +241,13 @@ void PinOne::ConnectToController() + if (m_pinOneCommunication) + DisconnectFromController(); - std::copy(newOutputValues.begin() + i, newOutputValues.begin() + lim, m_oldOutputValues.begin() + i); - break; -@@ -239,15 +242,9 @@ void PinOne::ConnectToController() ++ // VPE: the port is opened in this process (PinOneCommunication); there is no pipe server to create. m_pinOneCommunication = new PinOneCommunication(m_comPort); if (!m_pinOneCommunication->ConnectToServer()) { @@ -3975,7 +3365,7 @@ index 0cce88a..cc59c9d 100644 } catch (const std::exception& e) diff --git a/src/cab/out/pinone/PinOneAutoConfigurator.cpp b/src/cab/out/pinone/PinOneAutoConfigurator.cpp -index 782f4ec..f3ea435 100644 +index 912cb2e..1ced542 100644 --- a/src/cab/out/pinone/PinOneAutoConfigurator.cpp +++ b/src/cab/out/pinone/PinOneAutoConfigurator.cpp @@ -98,6 +98,19 @@ std::string PinOneAutoConfigurator::GetDevice() @@ -4007,12 +3397,13 @@ index 782f4ec..f3ea435 100644 std::string PinOneAutoConfigurator::FindLegacyComPort(bool& wmiAvailable) diff --git a/src/cab/out/pinone/PinOneCommunication.cpp b/src/cab/out/pinone/PinOneCommunication.cpp -index a753188..0db3257 100644 +index e789d26..514a660 100644 --- a/src/cab/out/pinone/PinOneCommunication.cpp +++ b/src/cab/out/pinone/PinOneCommunication.cpp -@@ -1,26 +1,40 @@ +@@ -1,26 +1,41 @@ #include "PinOneCommunication.h" -#include "NamedPipeServer.h" ++#include "../OutputGate.h" +#include "../../../Log.h" #include "../../../general/StringExtensions.h" -#include @@ -4067,7 +3458,7 @@ index a753188..0db3257 100644 PinOneCommunication::PinOneCommunication(const std::string& comPort) : m_comPort(comPort) { -@@ -30,20 +44,7 @@ PinOneCommunication::~PinOneCommunication() +@@ -30,20 +45,7 @@ PinOneCommunication::~PinOneCommunication() { try { @@ -4089,7 +3480,7 @@ index a753188..0db3257 100644 } catch (...) { -@@ -52,202 +53,91 @@ PinOneCommunication::~PinOneCommunication() +@@ -52,202 +54,98 @@ PinOneCommunication::~PinOneCommunication() bool PinOneCommunication::ConnectToServer() { @@ -4235,53 +3626,37 @@ index a753188..0db3257 100644 - return false; - } - return false; --} -- ++ return true; + } + -bool PinOneCommunication::IsComPortConnected() -{ - SendPipeMessage("CHECK"); - std::string response = ReadMessage(); - return response == "TRUE"; -+ return true; - } - +-} +- -void PinOneCommunication::Disconnect() { SendPipeMessage("DISCONNECT"); } +bool PinOneCommunication::IsComPortConnected() { return m_port && m_port->port; } - void PinOneCommunication::Write(const std::vector& bytesToWrite) + bool PinOneCommunication::Write(const std::vector& bytesToWrite) { - std::string base64Bytes = StringExtensions::ToBase64(bytesToWrite); - SendPipeMessage("WRITE " + base64Bytes); -- ReadMessage(); -+ if (!m_port) -+ throw std::runtime_error(StringExtensions::Build("Serial port {0} is not open", m_comPort)); -+ std::lock_guard io(m_port->io); -+ if (bytesToWrite.empty()) -+ return; -+ sp_return written = sp_blocking_write(m_port->port, bytesToWrite.data(), bytesToWrite.size(), WriteTimeoutMs); -+ if (written < 0 || static_cast(written) != bytesToWrite.size()) -+ throw std::runtime_error(StringExtensions::Build("Writing to serial port {0} failed", m_comPort)); - } - - std::string PinOneCommunication::ReadLine() - { +- return ReadMessage() == "OK"; +-} +- +-std::string PinOneCommunication::ReadLine() +-{ - SendPipeMessage("READLINE"); -- return ReadMessage(); -+ if (!m_port) -+ return ""; -+ std::lock_guard io(m_port->io); -+ char buffer[256]; -+ sp_return read = sp_blocking_read(m_port->port, buffer, sizeof(buffer) - 1, ReadTimeoutMs); -+ if (read <= 0) -+ return ""; -+ return std::string(buffer, static_cast(read)); - } - +- return ReadMessage(); +-} +- -std::string PinOneCommunication::GetCOMPort() -{ - SendPipeMessage("COMPORT"); - return ReadMessage(); - } +-} - -void PinOneCommunication::SendPipeMessage(const std::string& message) -{ @@ -4302,7 +3677,17 @@ index a753188..0db3257 100644 -#endif - } - catch (...) -- { ++ if (!m_port) ++ return false; ++ std::lock_guard io(m_port->io); ++ if (bytesToWrite.empty()) ++ return true; ++ // VPE: asked once the port is ours: another PinOne on the same port may have held it for a while. ++ if (OutputGate::TransferCancelled()) ++ return false; ++ sp_return written = sp_blocking_write(m_port->port, bytesToWrite.data(), bytesToWrite.size(), WriteTimeoutMs); ++ if (written < 0 || static_cast(written) != bytesToWrite.size()) + { - if (CreateServer() && ConnectToServer()) - { -#ifdef _WIN32 @@ -4317,11 +3702,15 @@ index a753188..0db3257 100644 - } - else - throw std::runtime_error("Unable to connect to board"); -- } --} -- ++ Log::Warning(StringExtensions::Build("Writing to serial port {0} failed", m_comPort)); ++ return false; + } ++ return true; + } + -std::string PinOneCommunication::ReadMessage() --{ ++std::string PinOneCommunication::ReadLine() + { - try - { - std::vector response(1024); @@ -4349,12 +3738,21 @@ index a753188..0db3257 100644 - else - return ""; - } --} -- ++ if (!m_port) ++ return ""; ++ std::lock_guard io(m_port->io); ++ char buffer[256]; ++ sp_return read = sp_blocking_read(m_port->port, buffer, sizeof(buffer) - 1, ReadTimeoutMs); ++ if (read <= 0) ++ return ""; ++ return std::string(buffer, static_cast(read)); + } + -} \ No newline at end of file ++} diff --git a/src/cab/out/pinone/PinOneCommunication.h b/src/cab/out/pinone/PinOneCommunication.h -index 0536494..4fa07c7 100644 +index 04edf39..98d5f0c 100644 --- a/src/cab/out/pinone/PinOneCommunication.h +++ b/src/cab/out/pinone/PinOneCommunication.h @@ -7,33 +7,32 @@ @@ -4388,8 +3786,8 @@ index 0536494..4fa07c7 100644 bool IsComPortConnected(); - void Disconnect(); + void Disconnect() { DisconnectFromServer(); } -+ // Throws unless every byte was written. - void Write(const std::vector& bytesToWrite); ++ // Returns whether every byte was written. + bool Write(const std::vector& bytesToWrite); std::string ReadLine(); - std::string GetCOMPort(); + std::string GetCOMPort() { return m_comPort; } @@ -4406,282 +3804,159 @@ index 0536494..4fa07c7 100644 -} \ No newline at end of file +} -diff --git a/src/cab/out/ps/Pinscape.cpp b/src/cab/out/ps/Pinscape.cpp -index 698dccc..4cf24b0 100644 ---- a/src/cab/out/ps/Pinscape.cpp -+++ b/src/cab/out/ps/Pinscape.cpp -@@ -75,7 +75,16 @@ void Pinscape::SetNumber(int value) - } - } - --bool Pinscape::VerifySettings() { return true; } -+bool Pinscape::VerifySettings() -+{ -+ // VPE: without its device the controller cannot deliver anything; it counts as failed instead of starting. -+ if (!m_dev) -+ { -+ Log::Warning(StringExtensions::Build("{0} was not found.", GetName())); -+ return false; -+ } -+ return true; -+} - - void Pinscape::SetMinCommandIntervalMs(int value) - { -@@ -101,19 +110,22 @@ void Pinscape::Init(Cabinet* cabinet) - OutputControllerFlexCompleteBase::Init(cabinet); - } - --void Pinscape::Finish() --{ -- if (m_dev) -- m_dev->AllOff(); -- OutputControllerFlexCompleteBase::Finish(); --} -+// VPE: the all-off goes out on the updater's way out (DisconnectFromController), after its last transfer and checked; -+// a failure reaches the caller through the base class once the updater has ended. -+void Pinscape::Finish() { OutputControllerFlexCompleteBase::Finish(); } - - void Pinscape::ConnectToController() { } - - void Pinscape::DisconnectFromController() - { -- if (m_dev && m_inUseState == InUseState::Running) -- m_dev->AllOff(); -+ // VPE: also for a controller DOF never used, whose blackout is the only update it gets at the end of the session. -+ if (m_dev) -+ { -+ m_cacheInvalid = true; -+ if (!m_dev->AllOff()) -+ throw std::runtime_error(StringExtensions::Build("{0} could not turn its outputs off", GetName())); -+ m_disconnectSentZeros = true; -+ } - } +diff --git a/src/cab/out/pinone/PinOneHidCommunication.cpp b/src/cab/out/pinone/PinOneHidCommunication.cpp +index c26b815..b4d7c33 100644 +--- a/src/cab/out/pinone/PinOneHidCommunication.cpp ++++ b/src/cab/out/pinone/PinOneHidCommunication.cpp +@@ -1,4 +1,5 @@ + #include "PinOneHidCommunication.h" ++#include "../OutputGate.h" + #include "../../../Log.h" + #include + #include +@@ -41,6 +42,9 @@ bool PinOneHidDevice::WriteUSB(const std::vector& payload) - void Pinscape::AllOff() -@@ -132,15 +144,20 @@ int Pinscape::GetNumberOfOutputs() const { return m_dev ? m_dev->GetNumOutputs() - void Pinscape::UpdateOutputs(const std::vector& newOutputValues) - { - if (!m_dev) -- return; -+ throw std::runtime_error("the Pinscape device is not connected"); -+ if (static_cast(m_oldOutputValues.size()) < GetNumberOfOutputs()) -+ m_oldOutputValues.resize(GetNumberOfOutputs(), 255); - -+ // VPE: every bank goes out until one complete transfer got there after a forced one or a failure. -+ bool full = m_forceFullTransfer || m_cacheInvalid; - uint8_t pfx = 200; - for (int i = 0; i < GetNumberOfOutputs(); i += 7, ++pfx) + for (int tries = 0; tries < 3; ++tries) { - int lim = std::min(i + 7, GetNumberOfOutputs()); - for (int j = i; j < lim; ++j) ++ // VPE: also before a retry after the handle was opened again. ++ if (OutputGate::TransferCancelled()) ++ return false; + int actual = m_fp ? hid_write(m_fp, buf.data(), buf.size()) : -1; + if (actual < 0) { -- if (j < static_cast(newOutputValues.size()) && newOutputValues[j] != m_oldOutputValues[j]) -+ // VPE: a forced transfer sends every bank, whatever was sent before. -+ if (j < static_cast(newOutputValues.size()) && (full || newOutputValues[j] != m_oldOutputValues[j])) +diff --git a/src/cab/out/ps/Pinscape.cpp b/src/cab/out/ps/Pinscape.cpp +index f257bbe..3a0edd5 100644 +--- a/src/cab/out/ps/Pinscape.cpp ++++ b/src/cab/out/ps/Pinscape.cpp +@@ -155,6 +155,11 @@ void Pinscape::UpdateOutputs(const std::vector& newOutputValues) + if (j < static_cast(newOutputValues.size()) && (full || newOutputValues[j] != m_oldOutputValues[j])) { UpdateDelay(); - -@@ -151,7 +168,12 @@ void Pinscape::UpdateOutputs(const std::vector& newOutputValues) - int copySize = std::min(lim - i, static_cast(newOutputValues.size()) - i); - memcpy(buf + 2, newOutputValues.data() + i, copySize); - -- m_dev->WriteUSB(buf); -+ // VPE: the cache only learns what the device really got. -+ if (!m_dev->WriteUSB(buf)) ++ if (TransferCancelled()) + { + m_cacheInvalid = true; -+ throw std::runtime_error("Pinscape USB write failed"); ++ return; + } - memcpy(m_oldOutputValues.data() + i, newOutputValues.data() + i, copySize); - -@@ -159,6 +181,7 @@ void Pinscape::UpdateOutputs(const std::vector& newOutputValues) - } - } - } -+ m_cacheInvalid = false; - } - - void Pinscape::UpdateDelay() -@@ -349,7 +372,7 @@ bool Pinscape::Device::ReadUSB(uint8_t* pBuf) - return true; - } - --void Pinscape::Device::AllOff() { SpecialRequest(0x05); } -+bool Pinscape::Device::AllOff() { return SpecialRequest(0x05); } - - bool Pinscape::Device::SpecialRequest(uint8_t id) - { -diff --git a/src/cab/out/ps/Pinscape.h b/src/cab/out/ps/Pinscape.h -index ee1ca84..8b7a11e 100644 ---- a/src/cab/out/ps/Pinscape.h -+++ b/src/cab/out/ps/Pinscape.h -@@ -56,7 +56,7 @@ private: - int GetNumOutputs() const { return m_numOutputs; } - bool IsLedWizEmulator(int unitNum); - bool ReadUSB(uint8_t* buf); -- void AllOff(); -+ bool AllOff(); - bool SpecialRequest(uint8_t id); - bool WriteUSB(uint8_t* buf); - void UpdateOutputs(uint8_t* NewOutputValues); -@@ -79,6 +79,8 @@ private: - int m_minCommandIntervalMs; - bool m_minCommandIntervalMsSet; - std::vector m_oldOutputValues; -+ // VPE: the device may not have what the cache says (a failed write, or the all-off of a disconnect). -+ bool m_cacheInvalid = true; - std::chrono::steady_clock::time_point m_lastUpdate; - static std::vector s_devices; - Device* m_dev; + uint8_t buf[9] = { 0 }; + buf[0] = 0; diff --git a/src/cab/out/pspico/PinscapePico.cpp b/src/cab/out/pspico/PinscapePico.cpp -index 6cdcc74..8b85dc7 100644 +index 8beea61..9630287 100644 --- a/src/cab/out/pspico/PinscapePico.cpp +++ b/src/cab/out/pspico/PinscapePico.cpp -@@ -7,6 +7,7 @@ - #include - #include - #include -+#include +@@ -1,4 +1,5 @@ + #include "PinscapePico.h" ++#include "../OutputGate.h" + + #include + #include +@@ -10,6 +11,7 @@ #include #include #include -@@ -95,13 +96,16 @@ bool PinscapePico::VerifySettings() - return false; - } - -- return true; -+ // VPE: a configured unit without its device cannot start, so it counts as failed instead of as written. -+ return std::any_of(s_devices.begin(), s_devices.end(), [this](auto device) { return device->UnitNo() == m_number; }); - } ++#include - void PinscapePico::ConnectToController() - { - if (!VerifySettings()) - return; -+ if (m_dev && m_dev->IsOpen()) -+ return; + #ifdef _WIN32 + #define WIN32_LEAN_AND_MEAN +@@ -141,7 +143,7 @@ public: + virtual int PacketCount() const = 0; + virtual int PortCount() const = 0; + virtual void Add(int port, int value, bool changed) = 0; +- virtual void Send(PinscapePico* psp) = 0; ++ virtual bool Send(PinscapePico* psp) = 0; + }; - for (auto device : s_devices) - { -@@ -124,7 +128,11 @@ void PinscapePico::DisconnectFromController() - { - if (m_dev) - { -- m_dev->AllOff(); -+ m_cacheInvalid = true; -+ // VPE: the blackout is the last word for a unit DOF never used: one that did not get there is an error. -+ if (!m_dev->AllOff()) -+ throw std::runtime_error(StringExtensions::Build("Pinscape Pico {0} could not turn its outputs off", GetName())); -+ m_disconnectSentZeros = true; + class RandomAccessOutputList +@@ -190,10 +192,12 @@ public: + } } - } -@@ -188,7 +196,9 @@ public: +- void Send(PinscapePico* psp) override ++ bool Send(PinscapePico* psp) override { for (const auto& l : list) { -- uint8_t buf[64] = { 0 }; -+ // VPE: the report is as long as the device says, which can be more than 64 bytes. -+ std::vector report(std::max(64, psp->m_dev->GetOutputReportLength()), 0); -+ uint8_t* buf = report.data(); ++ if (psp->TransferCancelled()) ++ return false; + uint8_t buf[64] = { 0 }; buf[0] = psp->m_dev->GetOutputReportId(); buf[1] = 0x22; - buf[2] = static_cast(l.outputs.size()); -@@ -199,7 +209,8 @@ public: - buf[idx++] = static_cast(output.second); - } +@@ -208,6 +212,7 @@ public: + if (!psp->m_dev->WriteUSB("SET OUTPUT PORTS", buf, 100)) + throw std::runtime_error("PinscapePico SET OUTPUT PORTS failed"); + } ++ return true; + } -- psp->m_dev->WriteUSB("SET OUTPUT PORTS", buf, 100); -+ if (!psp->m_dev->WriteUSB("SET OUTPUT PORTS", buf, 100)) -+ throw std::runtime_error("PinscapePico SET OUTPUT PORTS failed"); + private: +@@ -280,10 +285,12 @@ public: } } -@@ -277,7 +288,8 @@ public: +- void Send(PinscapePico* psp) override ++ bool Send(PinscapePico* psp) override { for (const auto& l : list) { -- uint8_t buf[64] = { 0 }; -+ std::vector report(std::max(64, psp->m_dev->GetOutputReportLength()), 0); -+ uint8_t* buf = report.data(); ++ if (psp->TransferCancelled()) ++ return false; + uint8_t buf[64] = { 0 }; buf[0] = psp->m_dev->GetOutputReportId(); buf[1] = 0x21; - buf[2] = static_cast(l.numToSend); -@@ -286,7 +298,8 @@ public: - for (const auto& output : l.outputs) - buf[idx++] = static_cast(output); - -- psp->m_dev->WriteUSB("SET OUTPUT PORT BLOCK", buf, 100); -+ if (!psp->m_dev->WriteUSB("SET OUTPUT PORT BLOCK", buf, 100)) -+ throw std::runtime_error("PinscapePico SET OUTPUT PORT BLOCK failed"); +@@ -296,6 +303,7 @@ public: + if (!psp->m_dev->WriteUSB("SET OUTPUT PORT BLOCK", buf, 100)) + throw std::runtime_error("PinscapePico SET OUTPUT PORT BLOCK failed"); } ++ return true; } -@@ -301,7 +314,7 @@ private: - void PinscapePico::UpdateOutputs(const std::vector& newOutputValues) - { - if (!m_dev) -- return; -+ throw std::runtime_error(StringExtensions::Build("PinscapePico {0} is not connected", GetName())); - - ContiguousOutputListGroup contiguousGroup; - RandomAccessOutputListGroup randomGroup; -@@ -314,7 +327,7 @@ void PinscapePico::UpdateOutputs(const std::vector& newOutputValues) - for (int i = 0; i < count; ++i) - { - int val = newOutputValues[i]; -- bool changed = (newOutputValues[i] != m_oldOutputValues[i]); -+ bool changed = m_forceFullTransfer || m_cacheInvalid || newOutputValues[i] != m_oldOutputValues[i]; - - contiguousGroup.Add(i, val, changed); - randomGroup.Add(i, val, changed); -@@ -327,10 +340,12 @@ void PinscapePico::UpdateOutputs(const std::vector& newOutputValues) - } + private: +@@ -336,10 +344,13 @@ void PinscapePico::UpdateOutputs(const std::vector& newOutputValues) } -+ m_cacheInvalid = true; + m_cacheInvalid = true; ++ bool sent; if (contiguousGroup.PacketCount() < randomGroup.PacketCount() || (contiguousGroup.PacketCount() <= randomGroup.PacketCount() && contiguousGroup.PortCount() < randomGroup.PortCount())) - contiguousGroup.Send(this); +- contiguousGroup.Send(this); ++ sent = contiguousGroup.Send(this); else - randomGroup.Send(this); -+ m_cacheInvalid = false; +- randomGroup.Send(this); ++ sent = randomGroup.Send(this); ++ if (!sent) ++ return; + m_cacheInvalid = false; if (firstChangedIndex >= 0) - { -@@ -700,7 +715,7 @@ void PinscapePico::Device::Close() - } +@@ -647,11 +658,17 @@ uint8_t* PinscapePico::Device::ReadUSB(uint32_t timeoutMs) + return nullptr; } --void PinscapePico::Device::AllOff() { DeviceRequest("ALL PORTS OFF", 0x20); } -+bool PinscapePico::Device::AllOff() { return DeviceRequest("ALL PORTS OFF", 0x20); } - - bool PinscapePico::Device::DeviceRequest(const std::string& desc, uint8_t commandId) +-bool PinscapePico::Device::WriteUSB(const std::string& desc, uint8_t* buf, uint32_t timeoutMs) ++bool PinscapePico::Device::WriteUSB(const std::string& desc, uint8_t* data, uint32_t timeoutMs) { -diff --git a/src/cab/out/pspico/PinscapePico.h b/src/cab/out/pspico/PinscapePico.h -index e78cf9c..f529cc1 100644 ---- a/src/cab/out/pspico/PinscapePico.h -+++ b/src/cab/out/pspico/PinscapePico.h -@@ -68,7 +68,7 @@ public: - bool Open(); - uint8_t* ReadUSB(uint32_t timeoutMs); - void Close(); -- void AllOff(); -+ bool AllOff(); - bool WriteUSB(const std::string& desc, uint8_t* buf, uint32_t timeoutMs); - bool DeviceRequest(const std::string& desc, uint8_t commandId); - -@@ -108,6 +108,8 @@ private: - std::chrono::steady_clock::time_point m_lastUpdate; - static std::vector s_devices; - Device* m_dev; -+ // VPE: the device's outputs may differ from the cache (after all-off or a failed write), so the next update sends all. -+ bool m_cacheInvalid = true; - }; +- if (!m_fp || !buf) ++ if (!m_fp || !data) + return false; - } -\ No newline at end of file ++ // VPE: the callers fill 64 bytes, and the device's output report can be longer: the report is padded here instead ++ // of being read past the caller's buffer. ++ std::vector report(std::max(m_outputReportLength, 1), 0); ++ std::memcpy(report.data(), data, std::min(report.size(), 64)); ++ uint8_t* buf = report.data(); ++ + std::string hexString; + for (size_t i = 0; i < m_outputReportLength; ++i) + { +@@ -666,6 +683,9 @@ bool PinscapePico::Device::WriteUSB(const std::string& desc, uint8_t* buf, uint3 + uint32_t actual = 0; + for (int tries = 0; tries < 3; ++tries) + { ++ // VPE: also before a retry: once a latch overtook the transfer, nothing more of it is written. ++ if (OutputGate::TransferCancelled()) ++ return false; + int result = hid_write(m_fp, buf, m_outputReportLength); + if (result == static_cast(m_outputReportLength)) + return true; diff --git a/src/fx/matrixfx/bitmapshapes/ShapeDefinitions.cpp b/src/fx/matrixfx/bitmapshapes/ShapeDefinitions.cpp index 303936f..afd013f 100644 --- a/src/fx/matrixfx/bitmapshapes/ShapeDefinitions.cpp @@ -4702,7 +3977,7 @@ index 303936f..afd013f 100644 std::ofstream file(fileName); if (file.is_open()) diff --git a/src/general/DirectoryInfo.cpp b/src/general/DirectoryInfo.cpp -index 920f2e3..93dcfc2 100644 +index 920f2e3..6f887d1 100644 --- a/src/general/DirectoryInfo.cpp +++ b/src/general/DirectoryInfo.cpp @@ -1,4 +1,5 @@ @@ -4711,7 +3986,16 @@ index 920f2e3..93dcfc2 100644 #include #include -@@ -19,6 +20,8 @@ bool DirectoryInfo::Exists() const { return std::filesystem::exists(m_path) && s +@@ -15,10 +16,16 @@ std::string DirectoryInfo::Name() const { return m_path.filename().string(); } + + std::string DirectoryInfo::FullName() const { return m_path.string(); } + +-bool DirectoryInfo::Exists() const { return std::filesystem::exists(m_path) && std::filesystem::is_directory(m_path); } ++// VPE: a folder outside the configuration folder is not looked up: it does not exist for libdof, and is not listed. ++bool DirectoryInfo::Exists() const ++{ ++ return PathConfinement::IsLookupAllowed(m_path.string()) && std::filesystem::exists(m_path) && std::filesystem::is_directory(m_path); ++} bool DirectoryInfo::Create() const { @@ -4720,7 +4004,7 @@ index 920f2e3..93dcfc2 100644 std::error_code ec; bool ok = std::filesystem::create_directory(m_path, ec); return ok && !ec; -@@ -26,6 +29,8 @@ bool DirectoryInfo::Create() const +@@ -26,6 +33,8 @@ bool DirectoryInfo::Create() const bool DirectoryInfo::Delete(bool recursive) const { @@ -4729,38 +4013,56 @@ index 920f2e3..93dcfc2 100644 std::error_code ec; if (recursive) std::filesystem::remove_all(m_path, ec); -@@ -37,16 +42,24 @@ bool DirectoryInfo::Delete(bool recursive) const - std::vector DirectoryInfo::GetFiles(const std::string& pattern) const - { - std::vector result; -- if (!Exists()) -+ // VPE: a folder outside the configuration folder is not even listed. -+ if (!PathConfinement::IsReadAllowed(m_path.string()) || !Exists()) - return result; +@@ -42,11 +51,19 @@ std::vector DirectoryInfo::GetFiles(const std::string& pattern) const std::regex rx(WildcardToRegex(pattern), std::regex::ECMAScript | std::regex::icase); for (auto const& entry : std::filesystem::directory_iterator(m_path)) { - if (entry.is_regular_file()) + try ++ { ++ if (entry.is_regular_file()) ++ { ++ auto name = entry.path().filename().string(); ++ // VPE: an entry that leads outside (a symbolic link) is not listed. ++ if (std::regex_match(name, rx) && PathConfinement::IsLookupAllowed(entry.path().string())) ++ result.emplace_back(entry.path().string()); ++ } ++ } ++ catch (...) { - auto name = entry.path().filename().string(); - if (std::regex_match(name, rx)) - result.emplace_back(entry.path().string()); -+ if (entry.is_regular_file()) ++ // VPE: a name the narrow encoding cannot hold is skipped. + } + } + return result; +@@ -62,11 +79,19 @@ std::vector DirectoryInfo::GetDirectories(const std::string& patt + std::regex rx(WildcardToRegex(pattern), std::regex::ECMAScript | std::regex::icase); + for (auto const& entry : std::filesystem::directory_iterator(m_path)) + { +- if (entry.is_directory()) ++ try ++ { ++ if (entry.is_directory()) + { + auto name = entry.path().filename().string(); -+ if (std::regex_match(name, rx) && PathConfinement::IsReadAllowed(entry.path().string())) ++ // VPE: an entry that leads outside (a symbolic link) is not listed. ++ if (std::regex_match(name, rx) && PathConfinement::IsLookupAllowed(entry.path().string())) + result.emplace_back(entry.path().string()); + } + } + catch (...) -+ { + { +- auto name = entry.path().filename().string(); +- if (std::regex_match(name, rx)) +- result.emplace_back(entry.path().string()); + // VPE: a name the narrow encoding cannot hold is skipped. } } return result; diff --git a/src/general/FileInfo.cpp b/src/general/FileInfo.cpp -index be1ad30..37d8d77 100644 +index be1ad30..1ce2188 100644 --- a/src/general/FileInfo.cpp +++ b/src/general/FileInfo.cpp @@ -1,4 +1,5 @@ @@ -4769,46 +4071,33 @@ index be1ad30..37d8d77 100644 #include "DirectoryInfo.h" -@@ -20,7 +21,7 @@ std::string FileInfo::FullName() const { return m_path.string(); } +@@ -10,9 +11,15 @@ FileInfo::FileInfo(const std::string& path) + { + } - std::string FileInfo::Extension() const { return m_path.extension().string(); } +-bool FileInfo::Exists() const { return std::filesystem::exists(m_path); } ++// VPE: a path outside the configuration folder is not looked up: it does not exist for libdof. ++bool FileInfo::Exists() const { return PathConfinement::IsLookupAllowed(m_path.string()) && std::filesystem::exists(m_path); } --bool FileInfo::Delete() const { return std::filesystem::remove(m_path); } -+bool FileInfo::Delete() const { return PathConfinement::IsWriteAllowed(m_path.string()) && std::filesystem::remove(m_path); } +-uintmax_t FileInfo::Length() const { return std::filesystem::file_size(m_path); } ++uintmax_t FileInfo::Length() const ++{ ++ if (!PathConfinement::IsLookupAllowed(m_path.string())) ++ throw std::filesystem::filesystem_error("outside the configuration folder", m_path, std::make_error_code(std::errc::permission_denied)); ++ return std::filesystem::file_size(m_path); ++} - DirectoryInfo FileInfo::Directory() const { return DirectoryInfo(m_path.parent_path().string()); } + std::string FileInfo::Name() const { return m_path.filename().string(); } -diff --git a/src/general/FilePattern.cpp b/src/general/FilePattern.cpp -index 510af7a..ee16022 100644 ---- a/src/general/FilePattern.cpp -+++ b/src/general/FilePattern.cpp -@@ -1,9 +1,11 @@ - #include "FilePattern.h" -+#include "PathConfinement.h" +@@ -20,7 +27,7 @@ std::string FileInfo::FullName() const { return m_path.string(); } - #include "DirectoryInfo.h" - #include "Path.h" - #include "StringExtensions.h" + std::string FileInfo::Extension() const { return m_path.extension().string(); } -+#include - #include +-bool FileInfo::Delete() const { return std::filesystem::remove(m_path); } ++bool FileInfo::Delete() const { return PathConfinement::IsWriteAllowed(m_path.string()) && std::filesystem::remove(m_path); } - namespace DOF -@@ -51,10 +53,11 @@ std::vector FilePattern::GetMatchingFiles(const std::unordered_map(); -+ std::vector files = filesDirectory.GetFiles(Path::GetFileName(p)); -+ files.erase(std::remove_if(files.begin(), files.end(), [](const FileInfo& f) { return !PathConfinement::IsReadAllowed(f.FullName()); }), files.end()); -+ return files; - } - catch (...) - { diff --git a/src/general/FileReader.cpp b/src/general/FileReader.cpp index b6baeda..6b7ca12 100644 --- a/src/general/FileReader.cpp @@ -4830,14 +4119,17 @@ index b6baeda..6b7ca12 100644 diff --git a/src/general/PathConfinement.cpp b/src/general/PathConfinement.cpp new file mode 100644 -index 0000000..be98f3c +index 0000000..d713659 --- /dev/null +++ b/src/general/PathConfinement.cpp -@@ -0,0 +1,155 @@ +@@ -0,0 +1,189 @@ +#include "PathConfinement.h" + +#include +#include ++#ifdef _WIN32 ++#include ++#endif + +#include "../Log.h" + @@ -4856,6 +4148,9 @@ index 0000000..be98f3c + // The root resolved; until it does, nothing is allowed. + bool valid = false; + fs::path path; ++ // The root as written, made absolute and normalized without the file system: a path written through it (and not ++ // through the resolved form) passes the lexical check too. ++ fs::path lexical; + // As given, so that a root that did not resolve (a folder not created yet) is looked up again on the next access. + std::string given; +}; @@ -4865,6 +4160,17 @@ index 0000000..be98f3c +thread_local bool t_hasRoot = false; +thread_local Root t_root; + ++// Absolute and normalized, from the path as written and the current folder only. On Windows, absolute() is ++// GetFullPathNameW, which does not touch the file system either. ++fs::path Lexical(const std::string& path) ++{ ++ std::error_code ec; ++ fs::path absolute = fs::absolute(fs::path(path), ec); ++ if (ec) ++ return fs::path(); ++ return absolute.lexically_normal(); ++} ++ +Root MakeRoot(const std::string& root) +{ + Root r; @@ -4878,6 +4184,7 @@ index 0000000..be98f3c + { + r.valid = true; + r.path = canonical; ++ r.lexical = Lexical(root); + } + return r; +} @@ -4896,28 +4203,26 @@ index 0000000..be98f3c + return s_root; +} + -+// Resolves symbolic links and dot components of the parts that exist; the rest is normalized lexically. The result -+// stays a path: converting it to a narrow string can fail on Windows (a long name behind a short 8.3 path). -+bool Resolve(const std::string& path, fs::path& resolved) -+{ -+ std::error_code ec; -+ fs::path absolute = fs::absolute(fs::path(path), ec); -+ if (ec) -+ return false; -+ resolved = fs::weakly_canonical(absolute, ec); -+ return !ec && !resolved.empty(); -+} -+ +// Compares whole components, so neither a sibling with the same prefix ("config-other") nor a component that contains -+// a backslash on POSIX passes. Components compare exactly: canonical paths have the case of the file system. -+bool IsWithin(const fs::path& path, const fs::path& root) ++// a backslash on POSIX passes. Resolved paths compare exactly, since canonical paths have the case of the file system; ++// paths as written compare without case on Windows, whose file systems ignore it. ++bool IsWithin(const fs::path& path, const fs::path& root, bool ignoreCase) +{ ++ auto same = [ignoreCase](const fs::path& a, const fs::path& b) { ++#ifdef _WIN32 ++ if (ignoreCase) ++ return _wcsicmp(a.native().c_str(), b.native().c_str()) == 0; ++#else ++ (void)ignoreCase; ++#endif ++ return a == b; ++ }; + auto p = path.begin(); + for (auto r = root.begin(); r != root.end(); ++r) + { + if (r->empty()) + continue; -+ if (p == path.end() || *p != *r) ++ if (p == path.end() || !same(*p, *r)) + return false; + ++p; + } @@ -4929,6 +4234,37 @@ index 0000000..be98f3c + return true; +} + ++// The decision for a path: first on the path as written, made absolute and normalized without the file system, so a ++// path outside the root (a network share, a device) is refused before anything looks it up. Only a path inside is ++// resolved, which follows its symbolic links, and must still be inside. The resolved path stays a path: converting it ++// to a narrow string can fail on Windows (a long name behind a short 8.3 path). ++bool IsInside(const std::string& path, const Root& root) ++{ ++ fs::path lexical = Lexical(path); ++ if (lexical.empty() || !(IsWithin(lexical, root.lexical, true) || IsWithin(lexical, root.path, true))) ++ return false; ++ std::error_code ec; ++ fs::path resolved = fs::weakly_canonical(lexical, ec); ++ return !ec && !resolved.empty() && IsWithin(resolved, root.path, false); ++} ++ ++bool IsAllowed(const std::string& path) ++{ ++ Root root = CurrentRoot(); ++ if (!root.set) ++ return true; ++ if (!root.valid || path.empty()) ++ return false; ++ try ++ { ++ return IsInside(path, root); ++ } ++ catch (...) ++ { ++ return false; ++ } ++} ++ +} + +void PathConfinement::SetRoot(const std::string& root) @@ -4959,27 +4295,14 @@ index 0000000..be98f3c + +bool PathConfinement::IsReadAllowed(const std::string& path) +{ -+ Root root = CurrentRoot(); -+ if (!root.set) -+ return true; -+ bool allowed = false; -+ if (root.valid && !path.empty()) -+ { -+ try -+ { -+ fs::path resolved; -+ allowed = Resolve(path, resolved) && IsWithin(resolved, root.path); -+ } -+ catch (...) -+ { -+ allowed = false; -+ } -+ } ++ bool allowed = IsAllowed(path); + if (!allowed) + Log::Warning("Not reading " + path + ": it is outside the configuration folder."); + return allowed; +} + ++bool PathConfinement::IsLookupAllowed(const std::string& path) { return IsAllowed(path); } ++ +bool PathConfinement::IsWriteAllowed(const std::string& path) +{ + if (!HasRoot()) @@ -4991,10 +4314,10 @@ index 0000000..be98f3c +} diff --git a/src/general/PathConfinement.h b/src/general/PathConfinement.h new file mode 100644 -index 0000000..00a6e77 +index 0000000..7df1473 --- /dev/null +++ b/src/general/PathConfinement.h -@@ -0,0 +1,34 @@ +@@ -0,0 +1,40 @@ +#pragma once + +#include @@ -5004,6 +4327,8 @@ index 0000000..00a6e77 + +// VPE: keeps libdof's file access inside one folder. Configurations are imported from elsewhere, and their paths and +// placeholders must not make libdof read files outside the folder they were imported into, or write or delete any file. ++// The file classes (FileInfo, DirectoryInfo, FileReader) ask it before every access, so a path outside the folder is ++// neither read nor looked up. +class PathConfinement +{ +public: @@ -5011,8 +4336,12 @@ index 0000000..00a6e77 + // refused while a root is set. A root that does not resolve allows nothing, and is looked up again on every access. + static void SetRoot(const std::string& root); + static bool HasRoot(); -+ // Whether the path, with its symbolic links and dot components resolved, lies inside the root. Any error denies. ++ // Whether the path lies inside the root. It is decided on the path as written first, without touching the file ++ // system, so a path outside (a network share among them) is refused without being looked up; a path inside is then ++ // resolved (symbolic links, dot components) and must still be inside. Any error denies. Logs a refusal. + static bool IsReadAllowed(const std::string& path); ++ // The same check without the log line, for lookups (whether a file exists, its size, a folder's entries). ++ static bool IsLookupAllowed(const std::string& path); + static bool IsWriteAllowed(const std::string& path); + + // Confines the calling thread to another root while it exists (catalog queries next to a running session). @@ -5068,10 +4397,10 @@ index 023ce64..c2f72fd 100644 if (!file) { diff --git a/src/globalconfiguration/GlobalConfig.cpp b/src/globalconfiguration/GlobalConfig.cpp -index 96ea59f..f55b488 100644 +index 96ea59f..7f23bf5 100644 --- a/src/globalconfiguration/GlobalConfig.cpp +++ b/src/globalconfiguration/GlobalConfig.cpp -@@ -6,9 +6,11 @@ +@@ -6,6 +6,7 @@ #include "../general/DirectoryInfo.h" #include "../general/Path.h" #include "../general/StringExtensions.h" @@ -5079,22 +4408,18 @@ index 96ea59f..f55b488 100644 #include -+#include - #include - #include - #include -@@ -86,7 +88,9 @@ std::unordered_map GlobalConfig::GetIniFilesDictionary(const std: +@@ -86,7 +87,9 @@ std::unordered_map GlobalConfig::GetIniFilesDictionary(const std: { } - lookupPaths.push_back(std::filesystem::current_path().string()); ++ // VPE: not the process's current folder, which is outside the configuration folder. + if (!PathConfinement::HasRoot()) + lookupPaths.push_back(std::filesystem::current_path().string()); -+ lookupPaths.erase(std::remove_if(lookupPaths.begin(), lookupPaths.end(), [](const std::string& path) { return !PathConfinement::IsReadAllowed(path); }), lookupPaths.end()); std::unordered_map iniFiles; -@@ -184,11 +188,14 @@ FileInfo* GlobalConfig::GetShapeDefinitionFile(const std::string& tableFilename, +@@ -184,11 +187,14 @@ FileInfo* GlobalConfig::GetShapeDefinitionFile(const std::string& tableFilename, return fi; delete fi; } @@ -5114,7 +4439,16 @@ index 96ea59f..f55b488 100644 return nullptr; } -@@ -388,6 +395,10 @@ void GlobalConfig::SaveGlobalConfig(const std::string& globalConfigFilename) +@@ -359,7 +365,7 @@ GlobalConfig* GlobalConfig::GetGlobalConfigFromConfigXmlFile(const std::string& + { + try + { +- if (std::filesystem::exists(globalConfigFileName)) ++ if (FileInfo(globalConfigFileName).Exists()) + { + std::string xml = FileReader::ReadFileToString(globalConfigFileName); + +@@ -388,6 +394,10 @@ void GlobalConfig::SaveGlobalConfig(const std::string& globalConfigFilename) if (StringExtensions::IsNullOrWhiteSpace(gcFileName)) throw std::runtime_error("No filename for GlobalConfig file has been supplied. Looking up the filename from the property GlobalConfigFilename failed as well"); @@ -5126,16 +4460,17 @@ index 96ea59f..f55b488 100644 { auto now = std::chrono::system_clock::now(); diff --git a/src/table/Table.cpp b/src/table/Table.cpp -index d6d677d..989bffa 100644 +index d6d677d..39e891b 100644 --- a/src/table/Table.cpp +++ b/src/table/Table.cpp -@@ -1,4 +1,5 @@ +@@ -1,4 +1,6 @@ #include "Table.h" ++#include "../general/FileInfo.h" +#include "../general/PathConfinement.h" #include "../Log.h" #include "../general/StringExtensions.h" -@@ -209,6 +210,8 @@ void Table::SaveConfigXmlFile(const std::string& filename) +@@ -209,6 +211,8 @@ void Table::SaveConfigXmlFile(const std::string& filename) { try { @@ -5144,3 +4479,12 @@ index d6d677d..989bffa 100644 std::string xml = ToXml(); std::ofstream file(filename); if (file.is_open()) +@@ -232,7 +236,7 @@ Table* Table::GetTableFromConfigXmlFile(const std::string& filename) + { + try + { +- if (std::filesystem::exists(filename)) ++ if (FileInfo(filename).Exists()) + { + std::string xml = FileReader::ReadFileToString(filename); + Table* table = FromXml(xml); diff --git a/native/release-check.py b/native/release-check.py index 402a2f0..251e20b 100644 --- a/native/release-check.py +++ b/native/release-check.py @@ -12,7 +12,9 @@ - It imports only libraries of the operating system: no C/C++ runtime DLLs on Windows (static CRT), no libstdc++ or libgcc_s on Linux (linked statically), only libSystem, libc++, libobjc and system frameworks on macOS. - Its vpe_dof_abi_version returns the VPE_DOF_ABI_VERSION of the header, so a library built from older sources with the - same exports does not pass. The library is loaded for that: run the check on the platform it is built for. + same exports does not pass. The library is loaded for that: run the check on the platform it is built for. On macOS + every architecture's slice is loaded, each by a Python started under that architecture (arch -); a slice that + cannot be loaded (an x86_64 slice without Rosetta) fails the check. - Linux: the newest glibc symbol version it needs (--max-glibc fails above that). macOS: the architectures it contains (--archs) and the minimum macOS version of each (--min-macos fails above that). - --unity-meta: the library has its Unity import settings next to it, and its folder too, as native/unity has them @@ -74,12 +76,43 @@ def header_abi_version(header): LOADERS = {"PE": "win32", "ELF": "linux", "Mach-O": "darwin"} +# Loads the library given as the argument and prints its ABI version. +ABI_PROBE = """import ctypes, sys +function = ctypes.CDLL(sys.argv[1]).vpe_dof_abi_version +function.restype = ctypes.c_int32 +function.argtypes = [] +print(function()) +""" + + +def check_slice_abi_versions(library, expected): + """Each architecture of a Mach-O library: a process loads only the slice of its own architecture, so every slice is + asked from a process started under that architecture. A slice that cannot be asked (no Rosetta, say) fails.""" + notes = [] + for arch in run(["lipo", "-archs", library]).split(): + try: + result = subprocess.run(["arch", "-" + arch, "/usr/bin/python3", "-c", ABI_PROBE, os.path.abspath(library)], + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) + output = result.stdout.strip() + except OSError as error: + result, output = None, str(error) + last = output.splitlines()[-1] if output else "" + if result is None or result.returncode != 0 or not re.fullmatch(r"-?\d+", last): + notes.append(("{}: cannot call vpe_dof_abi_version: {}".format(arch, output or "exit {}".format(result.returncode)), False)) + continue + version = int(last) + notes.append(("{} ABI version {} (the header's is {})".format(arch, version, expected), version == expected)) + return notes + + def check_abi_version(library, kind, header): expected = header_abi_version(header) if expected is None: return [("{} defines no VPE_DOF_ABI_VERSION".format(header), False)] if not sys.platform.startswith(LOADERS[kind]): return [("cannot load a {} library on {} to check its ABI version".format(kind, sys.platform), False)] + if kind == "Mach-O": + return check_slice_abi_versions(library, expected) try: function = ctypes.CDLL(os.path.abspath(library)).vpe_dof_abi_version except (OSError, AttributeError) as error: diff --git a/native/src/vpe_dof.cpp b/native/src/vpe_dof.cpp index c20c9af..1543ae3 100644 --- a/native/src/vpe_dof.cpp +++ b/native/src/vpe_dof.cpp @@ -64,6 +64,8 @@ enum class State struct vpe_dof { DOF::Pinball* pinball = nullptr; + // The gate of the session this instance began. It outlives the instance (OutputGate::BeginSession). + DOF::OutputGate* gate = nullptr; std::string basePath; std::atomic state { State::Created }; std::mutex lifecycle; @@ -321,7 +323,10 @@ VPE_DOF_API vpe_dof* VPE_DOF_CALL vpe_dof_create(const char* base_path, int32_t* dof->basePath = base_path; DOF::Config::GetInstance()->SetBasePath(base_path); DOF::PathConfinement::SetRoot(base_path); - DOF::OutputGate::Instance().BeginSession(); + // A configuration that cannot be used fails init instead of falling back to defaults or auto-configuring + // whatever hardware is connected. + DOF::Config::GetInstance()->SetStrictSetup(true); + dof->gate = &DOF::OutputGate::BeginSession(); { std::lock_guard hid(VpeDofHidLock()); DOF::IOConfigurator::Initialize(); @@ -514,7 +519,7 @@ VPE_DOF_API int64_t VPE_DOF_CALL vpe_dof_set_output_gate(vpe_dof* dof, int32_t o if (!lock.owns_lock() || dof->state.load() != State::Created) return -1; // No outputs exist yet: the state applies to everything init creates. - DOF::OutputGate& gate = DOF::OutputGate::Instance(); + DOF::OutputGate& gate = *dof->gate; int64_t generation = gate.Request(open != 0); gate.Apply(open != 0); gate.Publish(generation); @@ -532,8 +537,8 @@ VPE_DOF_API int32_t VPE_DOF_CALL vpe_dof_set_connect_tests(vpe_dof* dof, int32_t return VPE_DOF_INVALID_ARGUMENT; try { - // Process-wide, as the gate is; the session that create began allows them, so this lasts for the instance. - DOF::OutputGate::Instance().SetConnectTests(allowed != 0); + // The session that create began allows them, so this lasts for the instance. + dof->gate->SetConnectTests(allowed != 0); return VPE_DOF_OK; } catch (...) @@ -548,9 +553,10 @@ VPE_DOF_API int64_t VPE_DOF_CALL vpe_dof_latch_output_gate(vpe_dof* dof) return -1; try { - // The gate is process-wide and latches at once in every state, without DOF's main thread: the controllers' - // updaters send the closing. Init keeps it (the session began at create), and finish turns everything off anyway. - return DOF::OutputGate::Instance().Latch(); + // Latches the instance's session at once in every state, without DOF's main thread: the controllers' updaters send + // the closing. Init keeps it (the session began at create), and finish turns everything off anyway. A later + // instance has a session of its own, which this never reaches. + return dof->gate->Latch(); } catch (...) { @@ -572,7 +578,7 @@ VPE_DOF_API int32_t VPE_DOF_CALL vpe_dof_gate_state(vpe_dof* dof, int64_t genera return 0; try { - DOF::OutputGate& gate = DOF::OutputGate::Instance(); + DOF::OutputGate& gate = *dof->gate; DOF::OutputGate::Counts counts; DOF::OutputGate::Status status = gate.GetState(generation, counts); if (confirmed) @@ -602,7 +608,7 @@ VPE_DOF_API int32_t VPE_DOF_CALL vpe_dof_gate_pending(vpe_dof* dof, int64_t gene return VPE_DOF_INVALID_ARGUMENT; try { - for (const std::string& name : DOF::OutputGate::Instance().GetPending(generation)) + for (const std::string& name : dof->gate->GetPending(generation)) callback(Sanitize(name).c_str(), user); return VPE_DOF_OK; } diff --git a/native/tests/internal.cpp b/native/tests/internal.cpp index 87ffab6..c575c3e 100644 --- a/native/tests/internal.cpp +++ b/native/tests/internal.cpp @@ -4,19 +4,28 @@ // SPDX-License-Identifier: GPL-3.0-or-later // Tests of libdof's internals that no configuration reaches through the C ABI: effects that were never started, a toy -// that fails while an effect starts, schedules, the order of host commands and input, and the output gate's -// accounting, with the steps other threads can come between run one at a time. Exits non-zero if a check fails; a crash is a failure too. - +// that fails while an effect starts, schedules, the order of host commands and input, path confinement, and the output +// gate: its accounting and sessions, with the steps other threads can come between run one at a time, and a scripted +// controller whose writes a latch overtakes or whose device is lost. Exits non-zero if a check fails; a crash is a +// failure too. + +#include +#include +#include #include +#include #include #include #include #include +#include #include #include "Pinball.h" #include "cab/Cabinet.h" #include "cab/out/Output.h" +#include "cab/out/OutputControllerCompleteBase.h" +#include "cab/out/OutputControllerList.h" #include "cab/out/OutputGate.h" #include "cab/schedules/ScheduledSettings.h" #include "cab/toys/IMatrixToy.h" @@ -25,6 +34,8 @@ #include "fx/EffectList.h" #include "fx/matrixfx/RGBAMatrixShiftEffect.h" #include "fx/timmedfx/DelayEffect.h" +#include "general/FileInfo.h" +#include "general/PathConfinement.h" #include "general/color/RGBAColor.h" #include "pinballsupport/InputQueue.h" #include "table/Table.h" @@ -46,13 +57,15 @@ class OutputGateTestAccess bool latched; int64_t generation = gate.Reserve(latched); latch = gate.Latch(); - gate.Record(generation, open && !latched, false); + OutputGate::Entry entry; + entry.open = open && !latched; + gate.Record(generation, entry); return generation; } + // The two halves of a latch: closes and takes its generation, then publishes it. static int64_t BeginLatch(OutputGate& gate) { return gate.BeginLatch(); } static void FinishLatch(OutputGate& gate, int64_t generation) { gate.FinishLatch(generation); } - static int64_t LatchGeneration(const OutputGate& gate) { return gate.m_latchGeneration.load(); } }; // Queues host commands the way Pinball::Post does and takes the main thread's work one item at a time. @@ -78,6 +91,20 @@ class PinballTestAccess } return order; } + + // Applies a gate change as DOF's main thread runs it, through RunCommand. + static void Apply(Pinball& pinball, bool open, int64_t generation) + { + std::function command = [&pinball, open, generation]() { pinball.ApplyOutputGate(open, generation); }; + pinball.RunCommand(command); + } + + // What Finish does first. + static void Stop(Pinball& pinball) + { + std::lock_guard lock(pinball.m_mainThreadMutex); + pinball.m_stopping = true; + } }; } @@ -155,10 +182,114 @@ void MatrixEffectWhoseToyFailsIsFinished() table.Finish(); } +// The names GetPending returns are the units GetState counts as pending or failed. +bool NamesAgree(OutputGate& gate, int64_t generation) +{ + OutputGate::Counts counts; + gate.GetState(generation, counts); + return gate.GetPending(generation).size() == static_cast(counts.pending + counts.failed); +} + +// A change applied and published the way DOF's main thread does it. +int64_t Change(OutputGate& gate, bool open) +{ + int64_t generation = gate.Request(open); + gate.Apply(open); + gate.Publish(generation); + return generation; +} + +bool WaitFor(const std::function& condition) +{ + auto start = std::chrono::steady_clock::now(); + while (!condition()) + { + if (std::chrono::steady_clock::now() - start > std::chrono::seconds(2)) + return false; + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + return true; +} + +// A controller whose device takes one report per output, and logs what got to it. A hook runs before each report. +class ScriptedController : public OutputControllerCompleteBase +{ +public: + std::string GetXmlElementName() const override { return "ScriptedController"; } + + void Set(uint8_t first, uint8_t second) + { + uint8_t values[2] = { first, second }; + SetValues(0, values, 2); + Update(); + } + + void Note(const std::string& what) + { + std::lock_guard lock(m_logMutex); + m_log.push_back(what); + } + + std::vector Written() + { + std::lock_guard lock(m_logMutex); + return m_log; + } + + bool HasWritten(const std::string& what) + { + std::vector log = Written(); + return std::find(log.begin(), log.end(), what) != log.end(); + } + + std::function&)> beforeReport; + std::atomic failNextWrite { false }; + std::atomic failReconnect { false }; + std::atomic blackoutWorks { true }; + std::atomic connects { 0 }; + std::atomic blackouts { 0 }; + +protected: + int GetNumberOfConfiguredOutputs() override { return 2; } + bool VerifySettings() override { return true; } + + void ConnectToController() override + { + if (connects++ > 0 && failReconnect) + throw std::runtime_error("the device is gone"); + } + + void DisconnectFromController() override + { + if (m_inUseState != InUseState::Running) + return; + blackouts++; + m_disconnectTurnedOff = blackoutWorks; + Note("blackout"); + } + + void UpdateOutputs(const std::vector& values) override + { + if (failNextWrite.exchange(false)) + throw std::runtime_error("the write failed"); + for (int i = 0; i < 2 && i < static_cast(values.size()); i++) + { + if (beforeReport) + beforeReport(i, values); + if (TransferCancelled()) + return; + Note(std::to_string(i) + "=" + std::to_string(values[i])); + } + } + +private: + std::mutex m_logMutex; + std::vector m_log; +}; + void UntouchedUnitsAreCountedApart() { - OutputGate& gate = OutputGate::Instance(); - gate.BeginSession(); + OutputGate& gate = OutputGate::BeginSession(); OutputGate::Unit* used = gate.Register("used"); OutputGate::Unit* unused = gate.Register("unused"); @@ -173,9 +304,7 @@ void UntouchedUnitsAreCountedApart() CHECK(counts.confirmed == 1 && counts.untouched == 1 && counts.pending == 0 && counts.failed == 0, "a unit DOF leaves alone is untouched, not confirmed"); CHECK(gate.GetPending(open).empty(), "an untouched unit is not pending"); - int64_t closed = gate.Request(false); - gate.Apply(false); - gate.Publish(closed); + int64_t closed = Change(gate, false); snapshot = gate.Current(); used->Ack(snapshot); unused->Untouched(snapshot); @@ -187,27 +316,25 @@ void UntouchedUnitsAreCountedApart() void LatchOvertakesAQueuedOpening() { - OutputGate& gate = OutputGate::Instance(); - gate.BeginSession(); + OutputGate& gate = OutputGate::BeginSession(); OutputGate::Unit* unit = gate.Register("unit"); - int64_t closed = gate.Request(false); - gate.Apply(false); - gate.Publish(closed); + Change(gate, false); unit->Ack(gate.Current()); // The opening is queued for DOF's main thread when the latch comes; the main thread applies it afterwards. int64_t open = gate.Request(true); int64_t latched = gate.Latch(); + OutputGate::Counts counts; CHECK(latched > open, "the latch gets a later generation"); CHECK(!gate.IsOpen(), "the latch closes at once"); + CHECK(gate.GetState(open, counts) == OutputGate::Status::NotApplied, "the overtaken opening is not applied until DOF's main thread gets to it"); CHECK(!gate.Apply(true), "an opening applied after the latch is a closing"); CHECK(!gate.IsOpen(), "and leaves the gate closed"); gate.Publish(open); OutputGate::Snapshot snapshot = gate.Current(); CHECK(snapshot.generation == latched && !snapshot.open, "the overtaken opening is not published"); - OutputGate::Counts counts; - CHECK(gate.GetState(open, counts) == OutputGate::Status::Superseded, "the overtaken opening is superseded"); + CHECK(gate.GetState(open, counts) == OutputGate::Status::Superseded, "then it is superseded"); unit->Ack(snapshot); CHECK(gate.GetState(latched, counts) == OutputGate::Status::Applied && counts.confirmed == 1, "the latch is confirmed"); CHECK(gate.GetState(open, counts) == OutputGate::Status::Superseded, "superseded stays superseded"); @@ -218,79 +345,16 @@ void LatchOvertakesAQueuedOpening() unit->Ack(gate.Current()); CHECK(gate.GetState(later, counts) == OutputGate::Status::Applied && counts.confirmed == 1 && counts.untouched == 0, "and confirms the closed state"); - gate.BeginSession(); - CHECK(gate.IsOpen() && !gate.IsLatched(), "a new session is not latched"); -} - -// A command runs after the input queued before it and before the input queued after it: a closing followed by an on -// sends no on, and an off followed by an opening does not send the on that came before. -void CommandsAndInputKeepTheirOrder() -{ - Pinball pinball; - PinballTestAccess::Post(pinball); - pinball.ReceiveData('S', 1, 1); - CHECK(PinballTestAccess::Take(pinball, 3) == "CI-", "a closing followed by an on"); - - pinball.ReceiveData('S', 1, 0); - PinballTestAccess::Post(pinball); - CHECK(PinballTestAccess::Take(pinball, 3) == "IC-", "an off followed by an opening"); - - pinball.ReceiveData('S', 1, 1); - PinballTestAccess::Post(pinball); - pinball.ReceiveData('S', 1, 0); - PinballTestAccess::Post(pinball); - pinball.ReceiveData('S', 1, 1); - CHECK(PinballTestAccess::Take(pinball, 6) == "ICICI-", "interleaved"); -} - -// A schedule applies to the outputs its device lists. One that lists none changes no output, as in DOF: a 0% schedule -// would otherwise turn off the whole device. -void ScheduleAppliesToTheOutputsItLists() -{ - // Gated outputs report 0 while the gate is closed. - OutputGate::Instance().BeginSession(); - tinyxml2::XMLDocument doc; - doc.Parse( - "all daytrue00000000" - "" - "10" - "220" - ""); - ScheduledSettings& schedules = ScheduledSettings::GetInstance(); - CHECK(schedules.FromXml(doc.FirstChildElement("ScheduledSettings")) && schedules.size() == 1, "the schedule loads"); - - auto strength = [&schedules](int device, int number) { - Output output; - output.SetNumber(number); - output.SetOutput(200); - IOutput* result = schedules.GetNewRecalculatedOutput(&output, 1, device - 1); - int value = result->GetOutput(); - if (result != &output) - delete result; - return value; - }; - CHECK(strength(1, 1) == 200 && strength(1, 2) == 200, "a device without outputs keeps its strength"); - CHECK(strength(2, 2) == 0, "a listed output gets the schedule's strength"); - CHECK(strength(2, 3) == 200, "an output that is not listed keeps its strength"); - schedules.Clear(); -} - -// The names GetPending returns are the units GetState counts as pending or failed. -bool NamesAgree(int64_t generation) -{ - OutputGate::Counts counts; - OutputGate::Instance().GetState(generation, counts); - return OutputGate::Instance().GetPending(generation).size() == static_cast(counts.pending + counts.failed); + OutputGate& next = OutputGate::BeginSession(); + CHECK(next.IsOpen() && !next.IsLatched(), "a new session is not latched"); + CHECK(gate.IsLatched(), "the ended one stays latched"); } void OpeningReservedBeforeALatchIsSuperseded() { - OutputGate& gate = OutputGate::Instance(); - gate.BeginSession(); + OutputGate& gate = OutputGate::BeginSession(); OutputGate::Unit* unit = gate.Register("unit"); - int64_t closed = gate.Request(false); - gate.Apply(false); - gate.Publish(closed); + Change(gate, false); unit->Ack(gate.Current()); int64_t latched = 0; @@ -304,73 +368,107 @@ void OpeningReservedBeforeALatchIsSuperseded() CHECK(gate.GetState(open, counts) == OutputGate::Status::Superseded, "the opening the latch overtook is superseded"); CHECK(counts.confirmed == 0, "and does not claim the latch's writes"); CHECK(gate.GetState(latched, counts) == OutputGate::Status::Applied && counts.confirmed == 1, "the latch is confirmed"); - CHECK(NamesAgree(open) && NamesAgree(latched), "names agree with the counts"); + CHECK(NamesAgree(gate, open) && NamesAgree(gate, latched), "names agree with the counts"); +} - // The main thread publishes the opening while the latch is half done: it goes out as a closing. - gate.BeginSession(); - unit = gate.Register("unit"); - open = gate.Request(true); - latched = OutputGateTestAccess::BeginLatch(gate); +// The main thread publishes an opening while a latch is half done (its generation taken, not published yet): it goes +// out as a closing, and what it reports does not change when the latch is done. +void OpeningPublishedDuringALatchIsSuperseded() +{ + OutputGate& gate = OutputGate::BeginSession(); + OutputGate::Unit* unit = gate.Register("unit"); + int64_t open = gate.Request(true); + int64_t latched = OutputGateTestAccess::BeginLatch(gate); CHECK(!gate.Apply(true), "the opening applies as a closing"); gate.Publish(open); OutputGate::Snapshot snapshot = gate.Current(); CHECK(snapshot.generation == open && !snapshot.open, "it is published closed"); + OutputGate::Counts counts; + CHECK(gate.GetState(open, counts) == OutputGate::Status::Superseded, "it is superseded"); OutputGateTestAccess::FinishLatch(gate, latched); unit->Ack(gate.Current()); CHECK(gate.GetState(open, counts) == OutputGate::Status::Superseded && counts.confirmed == 0, "it is still superseded"); CHECK(gate.GetState(latched, counts) == OutputGate::Status::Applied && counts.confirmed == 1, "the latch is confirmed"); } +// What a change reports is decided when it is published, from what was published: an opening published before a +// latch is applied while the latch is half done, and superseded once the latch reached the units; the latch is not +// applied until it published itself. +void ResultsAreDecidedWhenPublished() +{ + OutputGate& gate = OutputGate::BeginSession(); + OutputGate::Unit* unit = gate.Register("unit"); + int64_t open = Change(gate, true); + unit->Ack(gate.Current()); + OutputGate::Counts counts; + CHECK(gate.GetState(open, counts) == OutputGate::Status::Applied && counts.confirmed == 1, "the opening is applied"); + int64_t latched = OutputGateTestAccess::BeginLatch(gate); + CHECK(gate.GetState(open, counts) == OutputGate::Status::Applied && counts.confirmed == 1, "a latch that is half done changes nothing reported"); + CHECK(gate.GetState(latched, counts) == OutputGate::Status::NotApplied, "nor is it applied"); + CHECK(!gate.Current().open, "but the units send the closing already"); + OutputGateTestAccess::FinishLatch(gate, latched); + CHECK(gate.GetState(latched, counts) == OutputGate::Status::Applied, "a latch publishes itself"); + CHECK(gate.GetState(open, counts) == OutputGate::Status::Superseded, "the opening is superseded once the latch reached the units"); + unit->Ack(gate.Current()); + CHECK(gate.GetState(latched, counts) == OutputGate::Status::Applied && counts.confirmed == 1, "the latch is confirmed"); +} + void EarliestLatchDecides() { - OutputGate& gate = OutputGate::Instance(); - gate.BeginSession(); + OutputGate& gate = OutputGate::BeginSession(); OutputGate::Unit* unit = gate.Register("unit"); int64_t first = OutputGateTestAccess::BeginLatch(gate); int64_t second = OutputGateTestAccess::BeginLatch(gate); + CHECK(second > first, "latches take their generations in order"); OutputGateTestAccess::FinishLatch(gate, second); OutputGateTestAccess::FinishLatch(gate, first); - CHECK(OutputGateTestAccess::LatchGeneration(gate) == first, "the earlier latch is the session's latch"); unit->Ack(gate.Current()); OutputGate::Counts counts; CHECK(gate.GetState(first, counts) == OutputGate::Status::Applied && counts.confirmed == 1, "the earlier latch is confirmed"); CHECK(gate.GetState(second, counts) == OutputGate::Status::Applied && counts.confirmed == 1, "the later latch is confirmed"); +} - // An opening requested between two overlapping latches: what it reports while the first is not done stays so. - gate.BeginSession(); - unit = gate.Register("unit"); - first = OutputGateTestAccess::BeginLatch(gate); +// An opening requested between two overlapping latches is a closing: what it reports while the first is not done +// stays so. +void OpeningBetweenTwoLatchesIsAClosing() +{ + OutputGate& gate = OutputGate::BeginSession(); + OutputGate::Unit* unit = gate.Register("unit"); + int64_t first = OutputGateTestAccess::BeginLatch(gate); int64_t open = gate.Request(true); CHECK(!gate.Apply(true), "the opening applies as a closing"); gate.Publish(open); - second = OutputGateTestAccess::BeginLatch(gate); + int64_t second = OutputGateTestAccess::BeginLatch(gate); OutputGateTestAccess::FinishLatch(gate, second); unit->Ack(gate.Current()); + OutputGate::Counts counts; OutputGate::Status before = gate.GetState(open, counts); CHECK(before == OutputGate::Status::Applied && counts.confirmed == 1, "the opening is a closing, confirmed"); OutputGateTestAccess::FinishLatch(gate, first); CHECK(gate.GetState(open, counts) == before && counts.confirmed == 1, "and stays so once the first latch is done"); CHECK(gate.GetState(first, counts) == OutputGate::Status::Applied && counts.confirmed == 1, "the first latch is confirmed"); +} - // A latch that pauses after taking its generation, while openings (one requested before it, one after) and a closing - // are applied: what they report then stays so once it is done. - gate.BeginSession(); - unit = gate.Register("unit"); +// A latch that pauses after taking its generation, while openings (one requested before it, one after) and a closing +// are applied: what they report then stays so once it is done. +void PausedLatchChangesNothingReported() +{ + OutputGate& gate = OutputGate::BeginSession(); + OutputGate::Unit* unit = gate.Register("unit"); int64_t earlier = gate.Request(true); - first = OutputGateTestAccess::BeginLatch(gate); - open = gate.Request(true); + int64_t first = OutputGateTestAccess::BeginLatch(gate); + int64_t open = gate.Request(true); CHECK(!gate.Apply(true), "the earlier opening applies as a closing"); gate.Publish(earlier); CHECK(!gate.Apply(true), "the later opening applies as a closing"); gate.Publish(open); - int64_t closed = gate.Request(false); - gate.Apply(false); - gate.Publish(closed); + int64_t closed = Change(gate, false); unit->Ack(gate.Current()); const int64_t changes[] = { earlier, open, closed }; OutputGate::Status states[3]; int confirmed[3]; + OutputGate::Counts counts; for (int i = 0; i < 3; i++) { states[i] = gate.GetState(changes[i], counts); @@ -383,14 +481,171 @@ void EarliestLatchDecides() CHECK(gate.GetState(changes[i], counts) == states[i] && counts.confirmed == confirmed[i], "the paused latch changes nothing"); } +// A latch reaches its own session only: an ended session's latch neither closes the current one nor cancels its +// transfers, and a unit keeps the session it registered in. +void LatchesStayInTheirSession() +{ + OutputGate& ended = OutputGate::BeginSession(); + OutputGate::Unit* old = ended.Register("old"); + OutputGate& current = OutputGate::BeginSession(); + OutputGate::Unit* unit = current.Register("unit"); + CHECK(&OutputGate::Instance() == ¤t, "the new session is the current one"); + CHECK(old->BelongsTo(ended) && !old->BelongsTo(current), "a unit keeps its session"); + { + OutputGate::Transfer transfer(unit, unit->Observe()); + ended.Latch(); + CHECK(!OutputGate::TransferCancelled(), "an ended session's latch does not cancel the current session's transfer"); + } + CHECK(current.IsOpen() && !current.IsLatched() && unit->Observe().open, "nor close it"); + { + OutputGate::Transfer transfer(old, old->Observe()); + CHECK(!OutputGate::TransferCancelled(), "a transfer of the ended session's closing goes on"); + } + CHECK(current.Apply(true), "the current session still opens"); +} + +// A latch overtakes the transfer of an opening at its next write point; a closing's transfer goes on. +void LatchCancelsTheTransferOfAnOpening() +{ + OutputGate& gate = OutputGate::BeginSession(); + OutputGate::Unit* unit = gate.Register("unit"); + CHECK(!OutputGate::TransferCancelled(), "nothing to cancel outside a transfer"); + { + OutputGate::Transfer transfer(unit, unit->Observe()); + CHECK(!OutputGate::TransferCancelled() && !transfer.Cancelled(), "an opening's transfer goes on while the gate is open"); + gate.Latch(); + CHECK(OutputGate::TransferCancelled() && transfer.Cancelled(), "a latch stops it at the next write point"); + } + CHECK(!OutputGate::TransferCancelled(), "the transfer is over"); + { + OutputGate::Transfer transfer(unit, unit->Observe()); + CHECK(!OutputGate::TransferCancelled() && !transfer.Cancelled(), "the closing's transfer goes on"); + } +} + +// Once a latch returned, no value of the opening that was being sent reaches the device: the transfer stops before +// its next write, stays unconfirmed, and the closing goes to every output next. +void LatchStopsAControllerAtTheNextWrite() +{ + OutputGate& gate = OutputGate::BeginSession(); + ScriptedController controller; + controller.SetName("scripted"); + std::atomic latched { -1 }; + controller.beforeReport = [&gate, &controller, &latched](int report, const std::vector& values) { + if (report == 1 && values[1] == 255 && latched.load() < 0) + { + latched = gate.Latch(); + controller.Note("latch"); + } + }; + controller.Init(nullptr); + controller.Set(255, 255); + bool confirmed = WaitFor([&gate, &latched]() { + OutputGate::Counts counts; + return latched.load() >= 0 && gate.GetState(latched.load(), counts) == OutputGate::Status::Applied && counts.confirmed == 1; + }); + CHECK(confirmed, "the latch is confirmed"); + try + { + controller.Finish(); + } + catch (const std::exception&) + { + CHECK(false, "the controller finishes"); + } + std::vector log = controller.Written(); + auto mark = std::find(log.begin(), log.end(), "latch"); + CHECK(mark != log.end(), "the latch came during the opening's transfer"); + CHECK(std::none_of(mark, log.end(), [](const std::string& write) { return write.find("=255") != std::string::npos; }), "no value of the opening goes out after the latch"); + CHECK(std::find(mark, log.end(), "0=0") != log.end() && std::find(mark, log.end(), "1=0") != log.end(), "the closing goes to every output"); +} + +// A final blackout confirms the closing observed before it was sent and one published while it was sent, and the +// unit stops after it, keeping that. It confirms no opening. +void FinalBlackoutConfirmsTheClosing() +{ + OutputGate& gate = OutputGate::BeginSession(); + OutputGate::Unit* unit = gate.Register("unit"); + int64_t closed = Change(gate, false); + OutputGate::Snapshot before = unit->Observe(); + int64_t latched = gate.Latch(); + unit->AckOff(before); + unit->Stop(); + OutputGate::Counts counts; + CHECK(gate.GetState(closed, counts) == OutputGate::Status::Applied && counts.confirmed == 1 && counts.failed == 0, "the closing before the blackout is confirmed"); + CHECK(gate.GetState(latched, counts) == OutputGate::Status::Applied && counts.confirmed == 1 && counts.failed == 0, "and the one published while it was sent"); + CHECK(NamesAgree(gate, latched), "names agree with the counts"); + + OutputGate& next = OutputGate::BeginSession(); + OutputGate::Unit* other = next.Register("unit"); + int64_t open = Change(next, true); + other->AckOff(other->Observe()); + other->Stop(); + CHECK(next.GetState(open, counts) == OutputGate::Status::Applied && counts.confirmed == 0 && counts.failed == 1, "a blackout confirms no opening"); +} + +// A unit whose device was lost blocks its updates, never its blackout: the blackout at the end still goes to the +// device, and once it got there the unit finishes cleanly instead of failing. +void LostDeviceStillGetsItsBlackout() +{ + for (bool works : { true, false }) + { + OutputGate& gate = OutputGate::BeginSession(); + ScriptedController controller; + controller.SetName("scripted"); + controller.failReconnect = true; + controller.blackoutWorks = works; + controller.Init(nullptr); + controller.Set(255, 0); + CHECK(WaitFor([&controller]() { return controller.HasWritten("0=255"); }), "the opening's value goes out"); + int64_t open = gate.Applied(); + controller.failNextWrite = true; + controller.Set(128, 0); + CHECK(WaitFor([&controller]() { return controller.blackouts.load() >= 2; }), "the updater ends after the reconnect failed"); + std::string error; + try + { + controller.Finish(); + } + catch (const std::exception& e) + { + error = e.what(); + } + CHECK(controller.blackouts.load() == 2, "the blackout is tried again at the end"); + OutputGate::Counts counts; + gate.GetState(open, counts); + if (works) + { + CHECK(error.empty(), "a blackout that got to the device finishes cleanly"); + CHECK(counts.confirmed == 1 && counts.failed == 0, "and keeps what the unit confirmed"); + } + else + { + CHECK(error.find("lost its connection") != std::string::npos, "a blackout that did not get there fails the finish"); + CHECK(counts.failed == 1, "and the unit"); + } + } +} + +// Once Finish started, the session takes no opening; a closing latches the gate. +void FinishTakesNoOpening() +{ + OutputGate& gate = OutputGate::BeginSession(); + Pinball pinball; + PinballTestAccess::Stop(pinball); + CHECK(pinball.SetOutputGate(true) == -1 && gate.IsOpen(), "an opening is refused and changes nothing"); + int64_t closed = pinball.SetOutputGate(false); + OutputGate::Counts counts; + CHECK(closed >= 0 && gate.IsLatched() && !gate.IsOpen(), "a closing latches the gate"); + CHECK(gate.GetState(closed, counts) == OutputGate::Status::Applied, "and is published at once"); + CHECK(pinball.SetOutputGate(true) == -1 && !gate.IsOpen(), "the gate stays closed"); +} + void PermanentFailureOutranksAnAck() { - OutputGate& gate = OutputGate::Instance(); - gate.BeginSession(); + OutputGate& gate = OutputGate::BeginSession(); OutputGate::Unit* unit = gate.Register("unit"); - int64_t closed = gate.Request(false); - gate.Apply(false); - gate.Publish(closed); + int64_t closed = Change(gate, false); unit->Ack(gate.Current()); OutputGate::Counts counts; CHECK(gate.GetState(closed, counts) == OutputGate::Status::Applied && counts.confirmed == 1, "the closing is confirmed"); @@ -404,14 +659,11 @@ void PermanentFailureOutranksAnAck() void CleanFinishKeepsTheSettledResult() { - OutputGate& gate = OutputGate::Instance(); - gate.BeginSession(); + OutputGate& gate = OutputGate::BeginSession(); OutputGate::Unit* used = gate.Register("used"); OutputGate::Unit* unused = gate.Register("unused"); OutputGate::Unit* failing = gate.Register("failing"); - int64_t open = gate.Request(true); - gate.Apply(true); - gate.Publish(open); + int64_t open = Change(gate, true); OutputGate::Snapshot snapshot = gate.Current(); used->Ack(snapshot); unused->Untouched(snapshot); @@ -429,14 +681,163 @@ void CleanFinishKeepsTheSettledResult() failing->Stop(); gate.GetState(open, counts); CHECK(counts.confirmed == 1 && counts.untouched == 1 && counts.failed == 1 && counts.pending == 0, "a clean finish keeps what was settled"); - CHECK(NamesAgree(open), "names agree with the counts"); + CHECK(NamesAgree(gate, open), "names agree with the counts"); - int64_t closed = gate.Request(false); - gate.Apply(false); - gate.Publish(closed); + int64_t closed = Change(gate, false); gate.GetState(closed, counts); CHECK(counts.failed == 3, "finished units fail later generations"); - CHECK(NamesAgree(closed), "names agree with the counts"); + CHECK(NamesAgree(gate, closed), "names agree with the counts"); +} + +// Path confinement decides on the path as written first: a path outside the root, a network share among them, is +// refused without being looked up, and the lookups (whether a file exists, its size) go through the check. +void LookupsOutsideTheRootAreRefused() +{ + std::filesystem::path root = std::filesystem::temp_directory_path() / "vpe-dof-internal-confinement"; + std::filesystem::create_directories(root); + std::string inside = (root / "inside.ini").string(); + FILE* file = std::fopen(inside.c_str(), "wb"); + if (file) + std::fclose(file); +#ifdef _WIN32 + const std::string share = "\\\\192.0.2.1\\dof\\directoutputconfig.ini"; + const std::string outside = "C:\\Windows\\win.ini"; +#else + const std::string share = "//192.0.2.1/dof/directoutputconfig.ini"; + const std::string outside = "/etc/hosts"; +#endif + PathConfinement::SetRoot(root.string()); + auto start = std::chrono::steady_clock::now(); + bool shareAllowed = PathConfinement::IsLookupAllowed(share) || FileInfo(share).Exists(); + auto elapsed = std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count(); + CHECK(!shareAllowed, "a network share outside the root is refused"); + CHECK(elapsed < 1000, "without being looked up"); + CHECK(!FileInfo(outside).Exists(), "a file outside the root does not exist for libdof"); + bool threw = false; + try + { + FileInfo(outside).Length(); + } + catch (const std::exception&) + { + threw = true; + } + CHECK(threw, "nor has it a size"); + CHECK(!FileInfo((root / ".." / "elsewhere.ini").string()).Exists(), "a path leading out of the root is refused"); + CHECK(FileInfo(inside).Exists(), "a file inside the root is found"); + PathConfinement::SetRoot(""); + std::error_code ec; + std::filesystem::remove_all(root, ec); +} + +// A command runs after the input queued before it and before the input queued after it: a closing followed by an on +// sends no on, and an off followed by an opening does not send the on that came before. +void CommandsAndInputKeepTheirOrder() +{ + Pinball pinball; + PinballTestAccess::Post(pinball); + pinball.ReceiveData('S', 1, 1); + CHECK(PinballTestAccess::Take(pinball, 3) == "CI-", "a closing followed by an on"); + + pinball.ReceiveData('S', 1, 0); + PinballTestAccess::Post(pinball); + CHECK(PinballTestAccess::Take(pinball, 3) == "IC-", "an off followed by an opening"); + + pinball.ReceiveData('S', 1, 1); + PinballTestAccess::Post(pinball); + pinball.ReceiveData('S', 1, 0); + PinballTestAccess::Post(pinball); + pinball.ReceiveData('S', 1, 1); + CHECK(PinballTestAccess::Take(pinball, 6) == "ICICI-", "interleaved"); +} + +// A controller whose first output throws when it is told about a change, as a failing effect or device can. +class RaisingController : public OutputControllerBase +{ +public: + std::vector raised; + std::string GetXmlElementName() const override { return "RaisingController"; } + tinyxml2::XMLElement* ToXml(tinyxml2::XMLDocument&) const override { return nullptr; } + bool FromXml(const tinyxml2::XMLElement*) override { return true; } + void Init(Cabinet*) override { } + void Finish() override { } + void Update() override { } + +protected: + void OnOutputValueChanged(IOutput* output) override + { + if (output->GetNumber() == 1) + throw std::runtime_error("an effect failed"); + raised.push_back(output->GetNumber()); + } +}; + +// A gate change reaches every output and is published whatever one of them throws: a closing that stayed unpublished +// would report not applied forever, with the outputs after the one that threw left on. +void GateChangeIsPublishedWhateverAnOutputThrows() +{ + OutputGate& gate = OutputGate::BeginSession(); + Pinball pinball; + RaisingController* controller = new RaisingController(); + for (int number = 1; number <= 3; number++) + { + Output* output = new Output(); + output->SetNumber(number); + output->SetName("Output" + std::to_string(number)); + output->SetGated(true); + output->SetOutput(255); + controller->GetOutputs()->Add(output); + } + OutputControllerList* controllers = pinball.GetCabinet()->GetOutputControllers(); + controllers->push_back(controller); + + int64_t closing = gate.Request(false); + PinballTestAccess::Apply(pinball, false, closing); + OutputGate::Counts counts; + CHECK(gate.GetState(closing, counts) == OutputGate::Status::Applied, "the closing is published"); + CHECK(!gate.IsOpen(), "the gate is closed"); + CHECK(controller->raised == std::vector({ 2, 3 }), "the outputs after the one that threw are told"); + + controller->raised.clear(); + int64_t opening = gate.Request(true); + PinballTestAccess::Apply(pinball, true, opening); + CHECK(gate.GetState(opening, counts) == OutputGate::Status::Applied, "the opening is published"); + CHECK(controller->raised == std::vector({ 2, 3 }), "and reaches the other outputs"); + + controllers->erase(std::find(controllers->begin(), controllers->end(), static_cast(controller))); + delete controller; +} + +// A schedule applies to the outputs its device lists. One that lists none changes no output, as in DOF: a 0% schedule +// would otherwise turn off the whole device. +void ScheduleAppliesToTheOutputsItLists() +{ + // Gated outputs report 0 while the gate is closed. + OutputGate::BeginSession(); + tinyxml2::XMLDocument doc; + doc.Parse( + "all daytrue00000000" + "" + "10" + "220" + ""); + ScheduledSettings& schedules = ScheduledSettings::GetInstance(); + CHECK(schedules.FromXml(doc.FirstChildElement("ScheduledSettings")) && schedules.size() == 1, "the schedule loads"); + + auto strength = [&schedules](int device, int number) { + Output output; + output.SetNumber(number); + output.SetOutput(200); + IOutput* result = schedules.GetNewRecalculatedOutput(&output, 1, device - 1); + int value = result->GetOutput(); + if (result != &output) + delete result; + return value; + }; + CHECK(strength(1, 1) == 200 && strength(1, 2) == 200, "a device without outputs keeps its strength"); + CHECK(strength(2, 2) == 0, "a listed output gets the schedule's strength"); + CHECK(strength(2, 3) == 200, "an output that is not listed keeps its strength"); + schedules.Clear(); } } @@ -448,11 +849,23 @@ int main() UntouchedUnitsAreCountedApart(); LatchOvertakesAQueuedOpening(); OpeningReservedBeforeALatchIsSuperseded(); + OpeningPublishedDuringALatchIsSuperseded(); + ResultsAreDecidedWhenPublished(); EarliestLatchDecides(); + OpeningBetweenTwoLatchesIsAClosing(); + PausedLatchChangesNothingReported(); + LatchesStayInTheirSession(); + LatchCancelsTheTransferOfAnOpening(); + LatchStopsAControllerAtTheNextWrite(); + FinalBlackoutConfirmsTheClosing(); + LostDeviceStillGetsItsBlackout(); + FinishTakesNoOpening(); PermanentFailureOutranksAnAck(); CleanFinishKeepsTheSettledResult(); ScheduleAppliesToTheOutputsItLists(); CommandsAndInputKeepTheirOrder(); + GateChangeIsPublishedWhateverAnOutputThrows(); + LookupsOutsideTheRootAreRefused(); if (failures) { std::fprintf(stderr, "%d check(s) failed\n", failures); diff --git a/third-party/libdof b/third-party/libdof index 5e90261..49b6947 160000 --- a/third-party/libdof +++ b/third-party/libdof @@ -1 +1 @@ -Subproject commit 5e90261c23b211b845b286f5a7acec7d2ffccb36 +Subproject commit 49b69470f0f940743cf9294cc982440e3bfb3fb5 From cc4d9e8ed9316a4b95395dd22aded7f7e8ba999f Mon Sep 17 00:00:00 2001 From: freezy Date: Fri, 27 Nov 2026 00:55:48 +0100 Subject: [PATCH 3/6] dof: close the gate and confinement gaps from the second review round - The gate is shared-owned by the session, the instance, Pinball and a handle per unit, so ended sessions are freed while a hung updater keeps its own gate alive. - The latch bit lives in the published word, so whether a generation went out open is decided in the same step that publishes it. - Every session starts dark: a unit keeps receiving the starting closing until it has written or failed it, and a connect test runs at most once, never after a closing, a latch or a reconnect. - At most one write per controller already past its check follows a latch: strip controllers send a frame as one checked write, and the LedWiz startup sequence goes out inside the opening's transfer. - A closing during finish latches the gate; an opening is refused. - Path confinement decides on Windows by volume identity and the canonical path as written, so every spelling of the root works and no other share or device path is looked up. On POSIX the path is resolved as written, so a link followed by .. is checked where it leads. - An output controller whose settings libdof refuses is skipped with a warning, whether its parser fails or throws, and hardware selectors must be whole numbers. LedWiz opens its devices at Init, not while its settings are read. - A connect test counts as use, so finish sends the blackout; Wemos counts it once the port took the command. - PAC units shared by several entries are set up and finished once, by their first and last user, and always stop after their final blackout. - A table directory outside the configuration root still names table XML inside it. - build-windows.cmd reads each test's exit code directly, and the tests use their own temporary folders and deterministic ordering. --- README.md | 2 +- .../DofInstanceTests.cs | 46 +- .../DofSessionIntegrationTests.cs | 121 +- VisualPinball.Engine.DOF/DofInstance.cs | 37 +- native/build-windows.cmd | 8 +- native/include/vpe_dof.h | 37 +- native/patches/0001-vpe-libdof.patch | 1447 ++++++++++++++--- native/src/vpe_dof.cpp | 18 +- native/tests/internal.cpp | 576 ++++++- 9 files changed, 2023 insertions(+), 269 deletions(-) diff --git a/README.md b/README.md index 83900e8..e8aff73 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ libdof is used as upstream has it, except for what `native/patches/0001-vpe-libd - **Output gate.** A process-wide gate that turns all outputs off while the game is paused or stopping, whatever effects are running. For each change it reports which controllers have sent it, which failed, and whether a later change replaced it before every controller had it. A stop or a fault latches it closed from any thread, without allocating: every controller's updater sends the closing without DOF's main thread (an idle updater checks the gate every 50 ms, its polling interval, which bounds how long it takes to notice; a PacLed64 or PacUIO drops the rest of an opening's update, a UMX one the rest of the frame it is sending). An opening still queued for that thread never goes out and reports as superseded, any later change applies as a closing, and when latches race the first one to start counts. A controller whose updater ended on its own reports failed, even for a change it had sent. - **File confinement.** libdof reads only files inside the configuration folder it was given, and never writes or deletes files. Its log goes to the host instead of a file. -- **Sessions.** `Setup` fails instead of falling back to defaults when the global config cannot be loaded, and instead of auto-configuring when the configured cabinet config is missing or invalid (without a configured cabinet, auto-configuration works as before). Controllers that outlive a session (LedWiz, PacDrive, PacLed64, PacUIO) start the next one from all off and unused. `Finish` applies changes still queued, and fails when a controller could not turn its outputs off, neither with its final update nor with its disconnect blackout. +- **Sessions.** `Setup` fails instead of falling back to defaults when the global config cannot be loaded, and instead of auto-configuring when the configured cabinet config is missing or invalid (without a configured cabinet, auto-configuration works as before). An output controller it cannot read is skipped, as toys are, so the others still start. Controllers that outlive a session (LedWiz, PacDrive, PacLed64, PacUIO) start the next one from all off and unused. `Finish` applies changes still queued, and fails when a controller could not turn its outputs off, neither with its final update nor with its disconnect blackout. - **Controllers.** A controller reports a change as sent only after a complete transfer; failed transfers are reported and retried. PinOne owns its serial port inside the process instead of sharing it through a named pipe or socket. Auto-configuration never opens a serial port: the host leases only the ports the configuration names, so a serial PinOne is used where the cabinet configuration names its port, and the auto-configurator neither probes the legacy PinOne port nor scans the others (on Linux it does not even list them, since listing opens some ports). HID PinOne boards are still found. A Dude's Cab board is opened again after a failed write until that works, and one without a serial number stops instead; a UMX device whose configuration cannot be read is skipped, so the other controllers are still set up. - **Parity with C# DOF.** The differences the parity harness found are fixed in libdof itself. They are listed in the parity [README](Tools~/parity/README.md#differences-found). diff --git a/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs b/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs index 89f90f4..a308134 100644 --- a/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs +++ b/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs @@ -10,6 +10,7 @@ using System.IO; using System.Linq; using System.Threading; +using System.Threading.Tasks; using NUnit.Framework; namespace VisualPinball.Engine.DOF.Test @@ -711,15 +712,16 @@ public void FinishDoesNotSendAnOffQueuedBeforeAnOpeningAsOn() Expect(unit.Universe, f => f[0] == 0, "closed", start); var mark = _capture.Count(unit.Universe); - // Finish right after the opening: the input queued before it still goes first. + // Finish right after the opening: the input queued before it still goes first. Whether that input is still + // queued when the opening comes depends on how fast DOF's main thread is, so the backlog makes it likely and + // the test asserts only what holds either way: finish applies the opening, and S1 is off when it does. The + // order itself is decided by the queue and tested with the input held in place, natively + // (FinishRunsTheInputQueuedBeforeAnOpening in native/tests/internal.cpp). Backlog(dof); dof.Data('S', 1, 0); - var queued = dof.PendingInput; var open = dof.SetOutputGate(true); dof.Finish(); Thread.Sleep(100); - // What the test is about: the opening came with input still queued before it, and finish applied it. - Assert.That(queued, Is.GreaterThan(0), "input was queued before the opening"); Assert.That(open, Is.GreaterThanOrEqualTo(0), "the opening was accepted"); var opening = dof.GetGateState(open); Assert.That((opening.Applied, opening.Superseded), Is.EqualTo((true, false)), "finish applied the opening: " + opening); @@ -728,6 +730,42 @@ public void FinishDoesNotSendAnOffQueuedBeforeAnOpeningAsOn() Assert.That(after.All(f => f[0] == 0), Is.True, "S1 was off before the gate opened: " + string.Join(",", after.Select(f => f[0]))); } + [Test] + public void ClosingDuringFinishLatchesTheGate() + { + var unit = Unit("ArtNetA"); + using var config = new TestConfig().GlobalConfig().Cabinet(8, unit).Ini(1, "vpetest,S1"); + using var dof = Start(config); + dof.Data('S', 1, 1); + Expect(unit.Universe, f => f[0] == 255, "S1 on"); + + // Finish is held at its first log line, once it started, while the gate is changed. + using var finishing = new ManualResetEventSlim(); + using var release = new ManualResetEventSlim(); + DofLibrary.SetLog((level, message) => { + _log.Enqueue($"[{level}] {message}"); + if (message.Contains("Finishing framework")) { + finishing.Set(); + release.Wait(5000); + } + }, DofLogLevel.Debug); + try { + var finish = Task.Run(() => dof.Finish()); + Assert.That(finishing.Wait(5000), Is.True, "finish started"); + var opening = dof.SetOutputGate(true); + var closing = dof.SetOutputGate(false); + release.Set(); + Assert.That(finish.Wait(10000), Is.True, "finish ended"); + Assert.That(opening, Is.EqualTo(-1), "an opening is refused once finish started"); + Assert.That(closing, Is.GreaterThan(0), "a closing latches the gate"); + var state = dof.GetGateState(closing); + Assert.That((state.Applied, state.Superseded, state.Written, state.Failed), Is.EqualTo((true, false, 1, 0)), state.ToString()); + } finally { + release.Set(); + DofLibrary.SetLog((level, message) => _log.Enqueue($"[{level}] {message}"), DofLogLevel.Debug); + } + } + [Test] public void OnQueuedAfterAClosingIsNotSent() { diff --git a/VisualPinball.Engine.DOF.Test/DofSessionIntegrationTests.cs b/VisualPinball.Engine.DOF.Test/DofSessionIntegrationTests.cs index b4f42e8..3ed188c 100644 --- a/VisualPinball.Engine.DOF.Test/DofSessionIntegrationTests.cs +++ b/VisualPinball.Engine.DOF.Test/DofSessionIntegrationTests.cs @@ -80,12 +80,12 @@ private void Expect(int universe, Func match, string what, int aft /// Imports an Art-Net cabinet on one universe and a row for the ROM, the way the player does. private DofRevisionLease Import(int universe, string row) => Import(_dir, universe, row); - private static DofRevisionLease Import(string dir, int universe, string row) + private static DofRevisionLease Import(string dir, int universe, string row, string otherControllers = "") { var source = Path.Combine(dir, "source"); Directory.CreateDirectory(source); File.WriteAllText(Path.Combine(source, "Cabinet.xml"), "\r\nTestfalse" - + $"ArtNet 1{universe}127.0.0.1" + + $"ArtNet 1{universe}127.0.0.1{otherControllers}" + "LedWizEquivalent 11" + string.Concat(Enumerable.Range(1, 8).Select(p => $"ArtNet 1.{p:00}{p}")) + "\r\n"); @@ -208,6 +208,123 @@ public void RunsFromAFolderWithANonAsciiName() Wait(session.StopAsync()); } + [Test] + public void ACabinetWithAControllerLibdofCannotReadStartsTheOthers() + { + // The import accepts the cabinet without libdof reading it, so setup must not refuse it as a whole. + const int universe = 305; + using var lease = Import(_dir, universe, "vpetest,S1", + "ArtNet 2unset127.0.0.1"); + var session = Session(lease.Revision, false); + var started = Wait(session.StartAsync()); + Assert.That(started.Started, Is.True, started.Error); + Assert.That(started.Cabinet.Controllers.Select(c => c.Name), Is.EqualTo(new[] { "ArtNet 1" }), "the controller libdof cannot read is skipped"); + session.Publish(Game, DofElementKind.Solenoid, 1, 255); + Expect(universe, f => f[0] == 255, "the other controller works"); + Wait(session.StopAsync()); + } + + [Test] + public void ACabinetWithAControllerWhoseSettingsLibdofRefusesStartsTheOthers() + { + // libdof throws for some settings out of range (a PAC Id), and needs an Id or a number that some entries + // leave out; each such controller is skipped, as one it cannot read is. + const int universe = 307; + using var lease = Import(_dir, universe, "vpetest,S1", + "" + + "No number"); + var session = Session(lease.Revision, false); + var started = Wait(session.StartAsync()); + Assert.That(started.Started, Is.True, started.Error); + Assert.That(started.Cabinet.Controllers.Select(c => c.Name), Is.EqualTo(new[] { "ArtNet 1" }), "the controllers libdof refuses are skipped"); + session.Publish(Game, DofElementKind.Solenoid, 1, 255); + Expect(universe, f => f[0] == 255, "the other controller works"); + Wait(session.StopAsync()); + } + + [Test, Platform("Win")] + public void ReopensAStoreThroughAnotherPathToItsFolder() + { + // The import writes the store's folder into the generated config as it was given, here through a junction. A + // session given the same folder through another junction reads it: what counts is the folder, not its path. + const int universe = 308; + var dir = Path.Combine(_dir, "real"); + Directory.CreateDirectory(dir); + var imported = Path.Combine(_dir, "imported through"); + var reopened = Path.Combine(_dir, "reopened through"); + Junction(imported, dir); + try { + Junction(reopened, dir); + using var lease = Import(imported, universe, "vpetest,S1"); + var basePath = Path.Combine(reopened, Path.GetRelativePath(imported, lease.Revision.BasePath)); + var session = new DofSession(new DofSessionOptions { + BasePath = basePath, + RomName = "vpetest_l1", + GameSession = Game, + WaitForSnapshot = false, + }); + _sessions.Add(session); + var started = Wait(session.StartAsync()); + Assert.That(started.Started, Is.True, started.Error); + Assert.That(started.Cabinet.Controllers.Select(c => c.Name), Is.EqualTo(new[] { "ArtNet 1" }), "the imported cabinet"); + session.Publish(Game, DofElementKind.Solenoid, 1, 255); + Expect(universe, f => f[0] == 255, "the outputs work"); + Wait(session.StopAsync()); + } finally { + // Removes the junctions, not the folder they point to. + if (Directory.Exists(reopened)) { + Directory.Delete(reopened); + } + Directory.Delete(imported); + } + } + + private static void Junction(string link, string target) + { + using var mklink = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("cmd.exe", $"/c mklink /J \"{link}\" \"{target}\"") { + UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, + }); + mklink.WaitForExit(); + Assert.That(mklink.ExitCode, Is.EqualTo(0), "the junction is created"); + } + + [Test, Platform("Win")] + public void RunsAUnicodeStoreReachedThroughAJunction() + { + // The import writes the store's 8.3 spelling into the generated config; the root is given through the junction. + const int universe = 306; + var dir = Path.Combine(_dir, "Jürgen"); + Directory.CreateDirectory(dir); + try { + DofPaths.ToNative(dir); + } catch (DofException) { + Assert.Ignore("This volume has no short (8.3) names, so libdof cannot open a non-ASCII folder on Windows."); + } + using var lease = Import(dir, universe, "vpetest,S1"); + var link = Path.Combine(_dir, "link"); + Junction(link, dir); + try { + var basePath = Path.Combine(link, Path.GetRelativePath(dir, lease.Revision.BasePath)); + Assert.That(DofPaths.IsAscii(basePath), Is.True); + var session = new DofSession(new DofSessionOptions { + BasePath = basePath, + RomName = "vpetest_l1", + GameSession = Game, + WaitForSnapshot = false, + }); + _sessions.Add(session); + var started = Wait(session.StartAsync()); + Assert.That(started.Started, Is.True, started.Error); + Assert.That(started.Cabinet.Controllers.Select(c => c.Name), Is.EqualTo(new[] { "ArtNet 1" }), "the imported cabinet"); + session.Publish(Game, DofElementKind.Solenoid, 1, 255); + Expect(universe, f => f[0] == 255, "the outputs work"); + Wait(session.StopAsync()); + } finally { + // Removes the junction, not the folder it points to. + Directory.Delete(link); + } + } + [Test] public void RunsAGameFromSnapshotToStop() { diff --git a/VisualPinball.Engine.DOF/DofInstance.cs b/VisualPinball.Engine.DOF/DofInstance.cs index a0b9675..bf76a68 100644 --- a/VisualPinball.Engine.DOF/DofInstance.cs +++ b/VisualPinball.Engine.DOF/DofInstance.cs @@ -214,13 +214,18 @@ public void Finish() } /// - /// Closes or opens the output gate. While closed, every output sends 0 and keeps the value effects set for when it - /// opens again. Before it applies at once; afterwards it is applied by DOF's main thread and this - /// returns at once. It never waits for DOF's main thread or a device, only for short internal locks. A change made - /// just before is still applied, after the table element changes made before it; once finish - /// started, an opening returns -1 and a closing latches the gate (). + /// Closes or opens the output gate. While closed, every output sends 0 and keeps the value effects set for when + /// it opens again. Before it applies at once, so a session can start closed: every + /// controller then turns its outputs off before an opening reaches it, also one whose first update comes after + /// the gate opened. Afterwards it is applied by DOF's main thread and this returns at once. It never waits for + /// DOF's main thread or a device, only for short internal locks. A change made just before + /// is still applied, after the table element changes made before it; once finish started, a closing latches the + /// gate () and returns the latch's generation. /// - /// The gate generation to pass to , or -1 while init or finish runs or after finish. + /// + /// The gate generation to pass to , or -1 while init runs, for an opening once finish + /// started, and after finish. + /// public long SetOutputGate(bool open) { var handle = _handle; @@ -228,10 +233,12 @@ public long SetOutputGate(bool open) } /// - /// Turns the controllers' connect test sequences (TestOnConnect of Wemos D1 and UMX controllers) off for the rest - /// of the instance, or on again. They run only while the output gate is open; turned off, a controller that - /// connects late or reconnects while the gate is open does not light its whole strip. Call before - /// to cover the controllers it connects. Every new instance allows them. + /// Turns the controllers' connect test sequences (TestOnConnect of Wemos D1 and UMX controllers) off for the + /// rest of the instance, or on again. They run only while the output gate is open for the controller (one + /// connected while it was closed turned its outputs off first), and once: a test the gate skipped does not run + /// on a reconnect. Turned off, a controller that connects late or reconnects while the gate is open does not + /// light its whole strip. Call before to cover the controllers it connects. Every new + /// instance allows them. /// public void SetConnectTests(bool allowed) => DofException.ThrowIfFailed(DofNative.SetConnectTests(Handle, allowed ? 1 : 0), "Setting DOF's connect tests"); @@ -244,10 +251,12 @@ public long SetOutputGate(bool open) /// is a closing, and a state once reported does not change when a later latch returns. The closing reaches the /// controllers without waiting for DOF's main thread: an idle updater checks the gate every 50 ms, its polling /// interval, which bounds how long it takes to notice; a busy one stops the opening's transfer before its next - /// write to the device (each report, packet, command or retry), so nothing of the opening goes out after the - /// latch returned, and then sends the closing to every output. Takes no lock and never allocates, so the - /// simulation thread or a fault handler may call it. Once it returned, the gate reports closed, also to an - /// opening DOF's main thread is applying at that moment. It never reaches a later instance's gate. + /// write to the device (each report, packet, command or retry), and then sends the closing to every output. A + /// write that was already past that check when the latch came can still reach the device after the latch returned: + /// at most that one write per controller, followed by the closing. Nothing else of the opening goes out. Takes no + /// lock and never allocates, so the simulation thread or a fault handler may call it. Once it returned, the gate + /// reports closed, also to an opening DOF's main thread is applying at that moment. It never reaches a later + /// instance's gate. /// /// The closing's generation, or -1 after . public long LatchOutputGate() diff --git a/native/build-windows.cmd b/native/build-windows.cmd index 68db142..38a3c21 100644 --- a/native/build-windows.cmd +++ b/native/build-windows.cmd @@ -24,14 +24,14 @@ if "%VPE_DOF_GENERATOR%"=="" ( cmake -S "%~dp0." -B "%BUILD%" -G "%VPE_DOF_GENERATOR%" -A x64 -DVPE_DOF_OUTPUT_DIR="%OUT%" || exit /b 1 ) cmake --build "%BUILD%" --config %CONFIG% --parallel || exit /b 1 -"%BUILD%\%CONFIG%\vpe_dof_smoke.exe" "%~dp0tests\fixtures\artnet" "%~dp0tests\fixtures\artnet\tables\smoke.vpx" vpetest > "%BUILD%\smoke.log" 2>&1 -if not "%errorlevel%"=="0" ( +rem "||" reads the exit code itself: a crash exits below 0, which "if errorlevel 1" misses, and an ERRORLEVEL variable +rem inherited from the environment would hide it from %errorlevel%. +"%BUILD%\%CONFIG%\vpe_dof_smoke.exe" "%~dp0tests\fixtures\artnet" "%~dp0tests\fixtures\artnet\tables\smoke.vpx" vpetest > "%BUILD%\smoke.log" 2>&1 || ( type "%BUILD%\smoke.log" echo The native smoke test failed. exit /b 1 ) -"%BUILD%\%CONFIG%\vpe_dof_internal.exe" > "%BUILD%\internal.log" 2>&1 -if not "%errorlevel%"=="0" ( +"%BUILD%\%CONFIG%\vpe_dof_internal.exe" > "%BUILD%\internal.log" 2>&1 || ( type "%BUILD%\internal.log" echo The native internal tests failed. exit /b 1 diff --git a/native/include/vpe_dof.h b/native/include/vpe_dof.h index d08fdad..c5b99d4 100644 --- a/native/include/vpe_dof.h +++ b/native/include/vpe_dof.h @@ -91,20 +91,22 @@ VPE_DOF_API int32_t VPE_DOF_CALL vpe_dof_finish(vpe_dof* dof, char* error, int32 /// Frees the instance. Calls finish first if it was not called. VPE_DOF_API void VPE_DOF_CALL vpe_dof_destroy(vpe_dof* dof); -/// Closes (open = 0) or opens (open = 1) the output gate. While closed, every output sends 0 and keeps the value effects -/// set for when it opens again; controllers also skip their connect test sequences. Before init it applies at once, -/// so a session can start closed; after init it runs on DOF's main thread and returns at once. Returns the gate -/// generation, which vpe_dof_gate_state reports against, or -1 while init or finish runs and after finish. It never -/// waits for DOF's main thread or a device; it only takes short internal locks. A change queued before finish is still -/// applied, after the table element changes queued before it; once finish started, an opening returns -1 and a closing -/// latches the gate (vpe_dof_latch_output_gate). Every instance has a gate of its own, open when it is created; after -/// vpe_dof_latch_output_gate a change applies as a closing. +/// Closes (open = 0) or opens (open = 1) the output gate. While closed, every output sends 0 and keeps the value +/// effects set for when it opens again; controllers also skip their connect test sequences. Before init it applies at +/// once, so a session can start closed: every controller then turns its outputs off before an opening reaches it, also +/// one whose first update comes after the gate opened. After init it runs on DOF's main thread and returns at once. +/// Returns the gate generation, which vpe_dof_gate_state reports against, or -1 while init runs, for an opening once +/// finish started, and after finish. It never waits for DOF's main thread or a device; it only takes short internal +/// locks. A change queued before finish is still applied, after the table element changes queued before it; once finish +/// started, a closing latches the gate (vpe_dof_latch_output_gate) and returns the latch's generation. Every instance +/// has a gate of its own, open when it is created; after vpe_dof_latch_output_gate a change applies as a closing. VPE_DOF_API int64_t VPE_DOF_CALL vpe_dof_set_output_gate(vpe_dof* dof, int32_t open); /// Turns the controllers' connect test sequences (TestOnConnect of Wemos D1 and UMX controllers) off (allowed = 0) for -/// the rest of the instance, or on again. They run only while the gate is open anyway; turned off, they do not run when -/// the gate opens either, so a controller that connects late or reconnects while the gate is open, as in a port test, -/// does not light its whole strip. Call before init to cover the controllers init connects. Every new instance allows -/// them. VPE_DOF_INVALID_ARGUMENT if `dof` is NULL. +/// the rest of the instance, or on again. They run only while the gate is open for the controller anyway (one connected +/// while it was closed turned its outputs off first), and once: a test the gate skipped does not run on a reconnect. +/// Turned off, they do not run when the gate opens either, so a controller that connects late or reconnects while the +/// gate is open, as in a port test, does not light its whole strip. Call before init to cover the controllers init +/// connects. Every new instance allows them. VPE_DOF_INVALID_ARGUMENT if `dof` is NULL. VPE_DOF_API int32_t VPE_DOF_CALL vpe_dof_set_connect_tests(vpe_dof* dof, int32_t allowed); /// Closes the output gate at once, from any thread and in any state, and latches it closed for the rest of the /// instance. An opening requested before the latch that DOF's main thread has not applied yet never reaches the @@ -114,11 +116,12 @@ VPE_DOF_API int32_t VPE_DOF_CALL vpe_dof_set_connect_tests(vpe_dof* dof, int32_t /// caller saw does not change when a later latch returns. The closing is published to the controllers at once and every /// controller's updater sends it without DOF's main thread: an idle updater checks the gate every 50 ms, its polling /// interval, which bounds how long it takes to notice; a busy one stops the opening's transfer before its next write to -/// the device (each report, packet, command or retry), so nothing of the opening goes out after the latch returned, and -/// then sends the closing to every output. Returns the closing's generation, or -1 if `dof` is NULL. Safe to call from a -/// realtime thread or a fault handler: it takes no lock and never allocates. Once it returned, the gate reports closed -/// to every caller, also to an opening DOF's main thread is applying at that moment. It only ever reaches this -/// instance's gate, never a later instance's. +/// the device (each report, packet, command or retry), and then sends the closing to every output. A write that was +/// already past that check when the latch came can still reach the device after the latch returned: at most that one +/// write per controller, followed by the closing. Nothing else of the opening goes out. Returns the closing's +/// generation, or -1 if `dof` is NULL. Safe to call from a realtime thread or a fault handler: it takes no lock and +/// never allocates. Once it returned, the gate reports closed to every caller, also to an opening DOF's main thread is +/// applying at that moment. It only ever reaches this instance's gate, never a later instance's. VPE_DOF_API int64_t VPE_DOF_CALL vpe_dof_latch_output_gate(vpe_dof* dof); /// Reports a gate change: 0 until it was published to the controllers (by DOF's main thread; a latch publishes its own /// closing at once), then 1, or 2 (superseded) if it is an opening a latch overtook (see vpe_dof_latch_output_gate). A 1 diff --git a/native/patches/0001-vpe-libdof.patch b/native/patches/0001-vpe-libdof.patch index 26be847..a42db12 100644 --- a/native/patches/0001-vpe-libdof.patch +++ b/native/patches/0001-vpe-libdof.patch @@ -1,5 +1,5 @@ diff --git a/src/Pinball.cpp b/src/Pinball.cpp -index 389786b..1cad703 100644 +index 389786b..303c2ff 100644 --- a/src/Pinball.cpp +++ b/src/Pinball.cpp @@ -12,6 +12,9 @@ @@ -16,7 +16,7 @@ index 389786b..1cad703 100644 , m_inputQueue(new InputQueue()) , m_keepMainThreadAlive(false) , m_mainThreadDoWork(false) -+ , m_gate(&OutputGate::Instance()) ++ , m_gate(OutputGate::Instance().shared_from_this()) , m_cabinetOwner(nullptr) { } @@ -338,23 +338,24 @@ index 389786b..1cad703 100644 + } diff --git a/src/Pinball.h b/src/Pinball.h -index 4bf85b5..350018a 100644 +index 4bf85b5..1bd1a59 100644 --- a/src/Pinball.h +++ b/src/Pinball.h -@@ -3,9 +3,12 @@ +@@ -3,9 +3,13 @@ #include #include #include +#include +#include #include ++#include #include #include +#include #include "DOF/DOF.h" -@@ -19,6 +22,7 @@ class GlobalConfig; +@@ -19,6 +23,7 @@ class GlobalConfig; class InputQueue; class TableElementData; class CabinetOwner; @@ -362,7 +363,7 @@ index 4bf85b5..350018a 100644 class Pinball { -@@ -42,7 +46,19 @@ public: +@@ -42,7 +47,19 @@ public: void ReceiveData(const std::string& tableElementName, int value); void ReceiveData(const TableElementData& tableElementData); @@ -382,7 +383,7 @@ index 4bf85b5..350018a 100644 void SetAlarms(AlarmHandler* alarms) { m_alarms = alarms; } void SetGlobalConfig(GlobalConfig* globalConfig) { m_globalConfig = globalConfig; } -@@ -61,7 +77,34 @@ private: +@@ -61,7 +78,35 @@ private: std::condition_variable m_mainThreadCV; std::atomic m_keepMainThreadAlive; std::atomic m_mainThreadDoWork; @@ -411,7 +412,8 @@ index 4bf85b5..350018a 100644 + void DrainCommands(); + // The gate of the session this was created in. -+ OutputGate* m_gate; ++ // Kept while the Pinball lives, whichever session is current. ++ std::shared_ptr m_gate; + // Set when Finish starts, under m_mainThreadMutex, and never cleared. + bool m_stopping = false; bool m_tableStarted = false; @@ -498,7 +500,7 @@ index f222f0c..bdd8bf0 100644 } diff --git a/src/cab/out/OutputControllerCompleteBase.cpp b/src/cab/out/OutputControllerCompleteBase.cpp -index 2b1478c..a1ad8bd 100644 +index 2b1478c..ed9ce2d 100644 --- a/src/cab/out/OutputControllerCompleteBase.cpp +++ b/src/cab/out/OutputControllerCompleteBase.cpp @@ -1,5 +1,6 @@ @@ -508,11 +510,13 @@ index 2b1478c..a1ad8bd 100644 #include "../../Log.h" #include "../../general/StringExtensions.h" #include -@@ -36,16 +37,37 @@ void OutputControllerCompleteBase::Init(Cabinet* cabinet) +@@ -36,16 +37,53 @@ void OutputControllerCompleteBase::Init(Cabinet* cabinet) if (settingsValid) { SetupOutputs(); + RegisterGateUnit(); ++ // VPE: a connect test is used up here when the unit registered under a closing (TakeConnectTest). ++ m_connectTestEligible = m_gateUnit->Observe().open; m_finishError.clear(); - InitUpdaterThread(); + try @@ -535,7 +539,21 @@ index 2b1478c..a1ad8bd 100644 } } -+OutputGate::Unit* OutputControllerCompleteBase::RegisterGateUnit() ++void OutputControllerCompleteBase::ConnectTestSent(const OutputGate::Snapshot& gate) ++{ ++ m_deviceUsed = true; ++ if (m_gateUnit && gate.open) ++ m_gateUnit->Ack(gate); ++} ++ ++OutputGate::Snapshot OutputControllerCompleteBase::ObserveGate() const { return m_gateUnit ? m_gateUnit->Observe() : OutputGate::Instance().Current(); } ++ ++bool OutputControllerCompleteBase::TakeConnectTest() ++{ ++ return m_connectTestEligible.exchange(false) && m_gateUnit && ObserveGate().open && OutputGate::Instance().AllowsConnectTests(); ++} ++ ++OutputGate::UnitHandle OutputControllerCompleteBase::RegisterGateUnit() +{ + // VPE: units belong to a session's gate; a controller that a connect test registered already keeps its unit. + OutputGate& gate = OutputGate::Instance(); @@ -547,23 +565,56 @@ index 2b1478c..a1ad8bd 100644 void OutputControllerCompleteBase::Finish() { FinishUpdaterThread(); -@@ -269,6 +291,7 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() +@@ -269,15 +307,37 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() { Log::Write(StringExtensions::Build("Updater thread started for {0} {1}", GetXmlElementName(), GetName())); -+ OutputGate::Unit* gateUnit = m_gateUnit; ++ OutputGate::UnitHandle gateUnit = m_gateUnit; try { try -@@ -285,6 +308,7 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() + { + ConnectToController(); ++ // VPE: a connect test belongs to the first connect only, also when it did not get that far (a failed ++ // handshake the controller returns from): a reconnect during the session never sends one. ++ m_connectTestEligible = false; + } + catch (const std::exception& e) + { ++ m_connectTestEligible = false; + Log::Exception(StringExtensions::Build("Could not connect to controller. Thread will quit: {0}", e.what())); ++ // VPE: a connect that fails after the device took a connect test, which may light it, ends as a session does: ++ // with the blackout, and with an error unless the blackout got through. ++ bool turnedOff = false; ++ if (m_deviceUsed) ++ { ++ OutputGate::Snapshot finalGate = gateUnit->Observe(); ++ try ++ { ++ std::vector zeroValues(m_outputValues.size(), 0); ++ turnedOff = Transfer(zeroValues, true, { finalGate.generation, false }); ++ } ++ catch (const std::exception& blackout) ++ { ++ Log::Exception(StringExtensions::Build("Exception occurred while trying to turn off all outputs: {0}", blackout.what())); ++ } ++ } ++ m_disconnectTurnedOff = false; + try + { + DisconnectFromController(); +@@ -285,6 +345,10 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() catch (...) { } ++ if (m_deviceUsed && !turnedOff && !m_disconnectTurnedOff) ++ m_finishError = StringExtensions::Build("{0} {1} could not connect after its connect test, its outputs may still be on: {2}", GetXmlElementName(), GetName(), e.what()); ++ m_deviceUsed = false; + gateUnit->Die(); m_updaterThreadFinished = true; return; } -@@ -295,13 +319,20 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() +@@ -295,13 +359,20 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() bool fullTransferRequired = true; while (m_keepUpdaterThreadAlive) { @@ -584,7 +635,7 @@ index 2b1478c..a1ad8bd 100644 try { if (m_inUseState == InUseState::ValueChanged) -@@ -312,14 +343,28 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() +@@ -312,14 +383,30 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() m_inUseState = InUseState::Running; } @@ -604,6 +655,8 @@ index 2b1478c..a1ad8bd 100644 + } + } + else ++ // VPE: nothing is written while no value changed. A connect test confirmed the opening it went out with ++ // (ConnectTestSent), not this one. + gateUnit->Untouched(gate); } catch (const std::exception& e) @@ -615,7 +668,7 @@ index 2b1478c..a1ad8bd 100644 } if (!updateOK) -@@ -345,7 +390,7 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() +@@ -345,7 +432,7 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() Log::Write("Reconnected to controller"); } @@ -624,7 +677,7 @@ index 2b1478c..a1ad8bd 100644 { std::unique_lock lock(m_conditionMutex); m_updateCondition.wait_for(lock, std::chrono::milliseconds(50), [this] { return !m_keepUpdaterThreadAlive || m_updateRequired; }); -@@ -353,17 +398,18 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() +@@ -353,18 +440,23 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() m_updateRequired = false; } @@ -633,7 +686,7 @@ index 2b1478c..a1ad8bd 100644 try { - if (m_inUseState != InUseState::Startup) -+ if (m_inUseState != InUseState::Startup || !finalGate.open) ++ if (m_inUseState != InUseState::Startup || !finalGate.open || m_deviceUsed) { if (died) m_finishError = StringExtensions::Build("{0} {1} lost its connection, its outputs may still be on", GetXmlElementName(), GetName()); @@ -641,11 +694,17 @@ index 2b1478c..a1ad8bd 100644 { std::vector zeroValues(m_outputValues.size(), 0); - turnedOff = Transfer(zeroValues, true); +- if (!turnedOff) + turnedOff = Transfer(zeroValues, true, { finalGate.generation, false }); - if (!turnedOff) ++ // VPE: confirmed at the blackout itself. A closing published later, while the controller disconnects, ++ // was not carried by it, and fails as one published after the unit stopped does. ++ if (turnedOff) ++ gateUnit->AckOff(finalGate); ++ else m_finishError = StringExtensions::Build("{0} {1} could not send its final update", GetXmlElementName(), GetName()); } -@@ -390,20 +436,40 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() + } +@@ -390,20 +482,42 @@ void OutputControllerCompleteBase::UpdaterThreadDoIt() catch (...) { } @@ -655,10 +714,12 @@ index 2b1478c..a1ad8bd 100644 + gateUnit->Die(); + else + { -+ if (turnedOff || m_disconnectTurnedOff) ++ // A blackout the disconnect sent (UMX_AllOff) is the last write, and confirms there. ++ if (m_disconnectTurnedOff) + gateUnit->AckOff(finalGate); + gateUnit->Stop(); + } ++ m_deviceUsed = false; Log::Write("Updater thread disconnected and will terminate"); } catch (const std::exception& e) @@ -687,7 +748,7 @@ index 2b1478c..a1ad8bd 100644 try { UpdateOutputs(values); -@@ -411,10 +477,19 @@ bool OutputControllerCompleteBase::Transfer(const std::vector& values, +@@ -411,10 +525,19 @@ bool OutputControllerCompleteBase::Transfer(const std::vector& values, catch (...) { m_forceFullTransfer = false; @@ -709,7 +770,7 @@ index 2b1478c..a1ad8bd 100644 + } diff --git a/src/cab/out/OutputControllerCompleteBase.h b/src/cab/out/OutputControllerCompleteBase.h -index e625193..5e6ccd4 100644 +index e625193..6fb346a 100644 --- a/src/cab/out/OutputControllerCompleteBase.h +++ b/src/cab/out/OutputControllerCompleteBase.h @@ -3,6 +3,7 @@ @@ -725,25 +786,45 @@ index e625193..5e6ccd4 100644 protected: void SetupOutputs(); + // VPE: the controller's unit in the current session's gate, registered before anything is sent to the device. -+ OutputGate::Unit* RegisterGateUnit(); ++ OutputGate::UnitHandle RegisterGateUnit(); void RenameOutputs(); virtual int GetNumberOfConfiguredOutputs() = 0; -@@ -49,6 +52,9 @@ protected: +@@ -49,6 +52,27 @@ protected: bool m_forceFullTransfer = false; bool m_transferSkipped = false; bool m_disconnectTurnedOff = false; ++ // VPE: set once the device took a connect test (ConnectTestSent), which may light it before any value changed: the ++ // session ends with the blackout, also if no value ever changed, and so does a connect that fails after it. ++ std::atomic m_deviceUsed { false }; ++ // VPE: a connect test the device's transport accepted, sent with the gate state `gate` (ObserveGate, read before it ++ // was sent, and open: a test is not sent otherwise). The unit counts as having written that opening, and no later ++ // one: an opening after a closing is written again before it counts. ++ void ConnectTestSent(const OutputGate::Snapshot& gate); ++ // VPE: the gate state the unit sends now (OutputGate::Unit::Observe), which a connect test goes out with. ++ OutputGate::Snapshot ObserveGate() const; ++ // VPE: whether the controller sends its connect test, asked where it would be sent; true once at most. A connect test ++ // runs only during the first connect after Init, only if the unit registered while the gate was open (a session that ++ // starts closed runs none, also not on a reconnect once it opened), and only while the gate is open for the unit and ++ // allows connect tests. The caller checks the gate again right before the write (TransferCancelled), as for every ++ // other write. ++ bool TakeConnectTest(); ++ // VPE: this controller's unit of the session's gate (RegisterGateUnit), for a write outside Transfer, such as a ++ // connect test, to be bound to (OutputGate::Transfer). ++ const OutputGate::UnitHandle& GateUnit() const { return m_gateUnit; } + // VPE: asked right before each write to the device; true once a latch overtook the transfer (OutputGate::Transfer), + // which then stops without writing. + bool TransferCancelled(); void InitUpdaterThread(); -@@ -76,9 +82,11 @@ private: +@@ -76,9 +100,13 @@ private: mutable std::mutex m_conditionMutex; bool m_keepUpdaterThreadAlive; std::atomic m_updaterThreadFinished { false }; -+ OutputGate::Unit* m_gateUnit = nullptr; ++ OutputGate::UnitHandle m_gateUnit; ++ // VPE: see TakeConnectTest. ++ std::atomic m_connectTestEligible { false }; std::string m_finishError; + bool m_transferCancelled = false; void UpdaterThreadDoIt(); @@ -752,12 +833,80 @@ index e625193..5e6ccd4 100644 }; } +diff --git a/src/cab/out/OutputControllerList.cpp b/src/cab/out/OutputControllerList.cpp +index 0d7a194..45b44d2 100644 +--- a/src/cab/out/OutputControllerList.cpp ++++ b/src/cab/out/OutputControllerList.cpp +@@ -212,32 +212,39 @@ bool OutputControllerList::FromXml(const tinyxml2::XMLElement* element) + while (controllerElement) + { + std::string typeName = controllerElement->Name(); +- IOutputController* controller = CreateController(typeName); +- +- if (controller) ++ // VPE: a controller whose configuration cannot be used is skipped, in strict setup too, as toys that cannot be ++ // read are, so the rest of the cabinet starts: whether its XML is unreadable (FromXml returns false) or a setting ++ // is refused (a setter throws, such as an Id out of range). VPE imports cabinets without libdof reading them (that ++ // would open their devices), and must not activate one that setup then refuses as a whole. Nothing a skipped ++ // controller is made of opens a device or registers with the output gate; that happens in Init. ++ IOutputController* controller = nullptr; ++ bool loaded = false; ++ std::string error; ++ try + { +- bool loaded; +- try +- { +- loaded = controller->FromXml(controllerElement); +- } +- catch (...) +- { +- delete controller; +- throw; +- } +- if (loaded) +- { +- push_back(controller); +- Log::Write(StringExtensions::Build("Loaded output controller: {0} ({1})", controller->GetName(), typeName)); +- } +- else +- { ++ controller = CreateController(typeName); ++ loaded = controller && controller->FromXml(controllerElement); ++ } ++ catch (const std::exception& e) ++ { ++ error = e.what(); ++ } ++ catch (...) ++ { ++ error = "unknown error"; ++ } ++ if (controller && loaded) ++ { ++ push_back(controller); ++ Log::Write(StringExtensions::Build("Loaded output controller: {0} ({1})", controller->GetName(), typeName)); ++ } ++ else if (controller || !error.empty()) ++ { ++ if (error.empty()) + Log::Warning(StringExtensions::Build("Failed to load output controller from XML: {0}", typeName)); +- delete controller; +- if (Config::GetInstance()->IsStrictSetup()) +- throw std::runtime_error(StringExtensions::Build("the output controller {0} could not be loaded", typeName)); +- } ++ else ++ Log::Warning(StringExtensions::Build("Failed to load output controller from XML: {0}: {1}", typeName, error)); ++ delete controller; + } + + controllerElement = controllerElement->NextSiblingElement(); diff --git a/src/cab/out/OutputGate.cpp b/src/cab/out/OutputGate.cpp new file mode 100644 -index 0000000..1ad550a +index 0000000..316d022 --- /dev/null +++ b/src/cab/out/OutputGate.cpp -@@ -0,0 +1,342 @@ +@@ -0,0 +1,379 @@ +#include "OutputGate.h" + +#include @@ -778,17 +927,35 @@ index 0000000..1ad550a + +std::mutex s_sessionMutex; + ++// The current session's gate, read without a lock by Instance(). +std::atomic& CurrentSession() +{ + static std::atomic current { nullptr }; + return current; +} + ++// What keeps the current session's gate; replaced, under s_sessionMutex, when the next session begins. Never destroyed, ++// so a thread that ends after the static destructors still finds its gate. ++std::shared_ptr& CurrentOwner() ++{ ++ static std::shared_ptr* owner = new std::shared_ptr(); ++ return *owner; ++} ++ +thread_local OutputGate::Transfer* t_transfer = nullptr; + +} + -+OutputGate::Snapshot OutputGate::Unit::Observe() const { return m_gate->Current(); } ++OutputGate::Snapshot OutputGate::Unit::Observe() const ++{ ++ Snapshot current = m_gate->Current(); ++ // The closing in force when the unit registered stays in force for it until it confirmed or failed it: a session ++ // that starts closed starts dark on every unit, also on one whose first update comes after the gate opened. ++ int64_t closed = m_closedAtRegistration; ++ if (current.open && closed != 0 && m_ackedClosed.load(std::memory_order_acquire) < closed && m_failed.load(std::memory_order_acquire) < closed) ++ return { closed, false }; ++ return current; ++} + +bool OutputGate::Unit::IsAcked(const Snapshot& snapshot) const +{ @@ -848,7 +1015,7 @@ index 0000000..1ad550a + // The session's first generation, open and published. + int64_t generation = lastGeneration + 1; + m_requested.store(generation << 1, std::memory_order_relaxed); -+ m_published.store(Pack(generation, true), std::memory_order_relaxed); ++ m_published.store(Pack(generation, true, false), std::memory_order_relaxed); + Entry entry; + entry.open = true; + entry.decided = true; @@ -866,7 +1033,8 @@ index 0000000..1ad550a + gate = CurrentSession().load(std::memory_order_acquire); + if (!gate) + { -+ gate = new OutputGate(0); ++ CurrentOwner() = std::shared_ptr(new OutputGate(0)); ++ gate = CurrentOwner().get(); + CurrentSession().store(gate, std::memory_order_release); + } + return *gate; @@ -876,27 +1044,34 @@ index 0000000..1ad550a +{ + OutputGate& previous = Instance(); + std::lock_guard lock(s_sessionMutex); -+ // Never freed: a latch, a unit or a hung updater thread of the ended session may still use it. -+ OutputGate* gate = new OutputGate(previous.m_requested.load(std::memory_order_acquire) >> 1); -+ CurrentSession().store(gate, std::memory_order_release); ++ std::shared_ptr gate(new OutputGate(previous.m_requested.load(std::memory_order_acquire) >> 1)); ++ CurrentSession().store(gate.get(), std::memory_order_release); ++ // The previous gate is freed here unless its instance, its Pinball or a unit handle (a controller, an updater thread ++ // that still runs) holds it. ++ CurrentOwner() = gate; + return *gate; +} + +OutputGate::Snapshot OutputGate::Current() const +{ ++ // The state comes from the published word alone, so it is the state Publish recorded for the generation. + int64_t word = m_published.load(std::memory_order_acquire); -+ return { word >> 1, (word & 1) != 0 && !m_latched.load(std::memory_order_acquire) }; ++ return { word >> 2, (word & OpenBit) != 0 && (word & LatchedBit) == 0 }; +} + -+OutputGate::Unit* OutputGate::Register(const std::string& name) ++OutputGate::UnitHandle OutputGate::Register(const std::string& name) +{ + std::lock_guard lock(m_mutex); + auto unit = std::make_unique(); + unit->m_gate = this; + unit->m_name = name; ++ Snapshot current = Current(); ++ if (!current.open) ++ unit->m_closedAtRegistration = current.generation; + Unit* result = unit.get(); + m_units.push_back(std::move(unit)); -+ return result; ++ // Shares the gate's ownership: the gate owns its units, the handle keeps the gate. ++ return UnitHandle(shared_from_this(), result); +} + +void OutputGate::RegisterFailed(const std::string& name) { Register(name)->Die(); } @@ -949,6 +1124,9 @@ index 0000000..1ad550a +{ + m_latched.store(true, std::memory_order_release); + m_open.store(false, std::memory_order_release); ++ // From here on every generation is published closed, and Current() reports closed: in one step with a publication ++ // that raced it, so an opening is either published before this, open, or after it, closed. ++ m_published.fetch_or(LatchedBit, std::memory_order_acq_rel); + // Takes the generation and sets the latch flag in one step: every generation taken after it is recorded as a closing + // (Request), whenever this latch publishes. + int64_t word = m_requested.load(std::memory_order_acquire); @@ -962,7 +1140,8 @@ index 0000000..1ad550a +{ + // Published at once, so the updaters send zeros without waiting for the main thread. Until then the latch's + // generation reports as not applied; it is a closing either way. -+ RaisePublished(generation, false); ++ bool sent; ++ RaisePublished(generation, false, sent); +} + +int64_t OutputGate::Latch() @@ -974,15 +1153,20 @@ index 0000000..1ad550a + return generation; +} + -+bool OutputGate::RaisePublished(int64_t generation, bool open) ++bool OutputGate::RaisePublished(int64_t generation, bool open, bool& sent) +{ -+ int64_t current = m_published.load(std::memory_order_relaxed); -+ int64_t word = Pack(generation, open); -+ while ((current >> 1) < generation) ++ int64_t current = m_published.load(std::memory_order_acquire); ++ while ((current >> 2) < generation) + { -+ if (m_published.compare_exchange_weak(current, word, std::memory_order_acq_rel, std::memory_order_relaxed)) ++ // The latched bit is carried over: once set, it stays. ++ bool latched = (current & LatchedBit) != 0; ++ if (m_published.compare_exchange_weak(current, Pack(generation, open && !latched, latched), std::memory_order_acq_rel, std::memory_order_acquire)) ++ { ++ sent = open && !latched; + return true; ++ } + } ++ sent = open && (current & LatchedBit) == 0; + return false; +} + @@ -991,8 +1175,10 @@ index 0000000..1ad550a + std::lock_guard lock(m_mutex); + auto it = m_history.find(generation); + bool requested = it != m_history.end() ? it->second.open : m_open.load(std::memory_order_acquire); -+ bool open = requested && !m_latched.load(std::memory_order_acquire); -+ bool raised = RaisePublished(generation, open); ++ // Whether the session latched is decided in the step that publishes, not read before it: a latch that began in ++ // between makes it go out closed. ++ bool open; ++ bool raised = RaisePublished(generation, requested, open); + // What it reports is decided here, from what was published, and kept: nothing installed later changes it. + if (it != m_history.end() && !it->second.decided) + { @@ -1102,10 +1288,10 @@ index 0000000..1ad550a +} diff --git a/src/cab/out/OutputGate.h b/src/cab/out/OutputGate.h new file mode 100644 -index 0000000..0913671 +index 0000000..7ea71ed --- /dev/null +++ b/src/cab/out/OutputGate.h -@@ -0,0 +1,233 @@ +@@ -0,0 +1,256 @@ +#pragma once + +#include @@ -1127,10 +1313,12 @@ index 0000000..0913671 +// unit acknowledges the state of a generation once a transfer to its hardware carried that state, so the host can tell +// when the outputs are really off. +// -+// Each session (one DOF instance, from its creation on) has its own gate object. Instance() is the current session's; -+// one that ended stays allocated, so a latch, a unit or a hung updater thread of an ended session only ever reaches its -+// own session, never the next one. -+class OutputGate ++// Each session (one DOF instance, from its creation on) has its own gate object. Instance() is the current session's. ++// A gate is shared: the current session slot, the host's instance, Pinball and every unit handle (held by its controller ++// and copied by its updater thread) keep it, and it is freed with its history and units once none does. So a latch, a ++// unit or a hung updater thread of an ended session only ever reaches its own session, never the next one, and a host ++// that runs many sessions keeps only the gates something still uses. ++class OutputGate : public std::enable_shared_from_this +{ +public: + // A generation and the state it set, read together. @@ -1166,7 +1354,9 @@ index 0000000..0913671 + class Unit + { + public: -+ // Called by the unit's updater before it copies the values it sends, under the lock the values are set with. ++ // Called by the unit's updater before it copies the values it sends, under the lock the values are set with. A unit ++ // registered while the gate was closed gets that closing until it confirmed or failed it, also once the gate ++ // opened: its device, which an earlier session may have left lit, is turned off before any opening reaches it. + Snapshot Observe() const; + // Whether the hardware already got the state of `snapshot`, or the gate is open at a unit DOF leaves alone; until + // then the updater transfers every output. @@ -1197,16 +1387,26 @@ index 0000000..0913671 + std::atomic m_failed { 0 }; + std::atomic m_dead { false }; + std::atomic m_stopped { false }; ++ // The closing the gate was at when the unit registered, or 0 if it was open. ++ int64_t m_closedAtRegistration = 0; + }; + ++ // A unit, and with it its session's gate: the gate lives as long as any handle to one of its units. ++ using UnitHandle = std::shared_ptr; ++ + // A transfer of the values observed at `snapshot`, made by the calling thread while this exists. A latch overtakes -+ // the transfer of an opening: from then on TransferCancelled() is true, and every write point stops before it writes, -+ // so no value of the opening goes out after the latch. The transfer then stays unconfirmed and the updater sends the -+ // closing in full next. ++ // the transfer of an opening: from then on TransferCancelled() is true, and every write point stops before it writes. ++ // A write already past its check when the latch came still goes out: at most that one write per controller, whose ++ // updater has one transfer at a time; no later one does. The transfer then stays unconfirmed and the updater sends ++ // the closing in full next. + class Transfer + { + public: + Transfer(const Unit* unit, const Snapshot& snapshot); ++ Transfer(const UnitHandle& unit, const Snapshot& snapshot) ++ : Transfer(unit.get(), snapshot) ++ { ++ } + ~Transfer(); + Transfer(const Transfer&) = delete; + Transfer& operator=(const Transfer&) = delete; @@ -1226,10 +1426,11 @@ index 0000000..0913671 + // must then stop without writing. False outside a transfer and for a closing. + static bool TransferCancelled(); + -+ // The current session's gate. ++ // The current session's gate, kept by the session slot until the next session begins. + static OutputGate& Instance(); + // Starts a new session with an open gate and returns it; Instance() returns it from now on. Generations go on from -+ // the previous session's. The previous session's gate stays allocated (see above). ++ // the previous session's. The slot lets go of the previous session's gate, which lives on while anything else holds ++ // it (see above). A caller that uses the gate beyond the session holds it with shared_from_this(). + static OutputGate& BeginSession(); + + // The state outputs report. It changes before the generation that set it is published. The latch decides on its own, @@ -1245,9 +1446,10 @@ index 0000000..0913671 + // generation is published. + Snapshot Current() const; + -+ // Registers an output controller unit of this session, before anything is sent to its device. The returned unit -+ // lives until the process ends. -+ Unit* Register(const std::string& name); ++ // Registers an output controller unit of this session, before anything is sent to its device. The unit and the ++ // gate live as long as the returned handle or one of its copies. Registered while the gate is closed, the unit sends ++ // that closing before any later opening (Unit::Observe). ++ UnitHandle Register(const std::string& name); + // Registers a configured unit that cannot deliver anything, such as a device that is not connected. + void RegisterFailed(const std::string& name); + @@ -1299,7 +1501,10 @@ index 0000000..0913671 + + explicit OutputGate(int64_t lastGeneration); + -+ static int64_t Pack(int64_t generation, bool open) { return (generation << 1) | (open ? 1 : 0); } ++ // The published word: the generation, whether the session latched, and the state the units send for it. ++ static constexpr int64_t OpenBit = 1; ++ static constexpr int64_t LatchedBit = 2; ++ static int64_t Pack(int64_t generation, bool open, bool latched) { return (generation << 2) | (latched ? LatchedBit : 0) | (open ? OpenBit : 0); } + + // The two halves of Latch: closes at once and reserves the generation with the latch flag, then publishes it. + int64_t BeginLatch(); @@ -1316,13 +1521,17 @@ index 0000000..0913671 + bool IsSuperseded(int64_t generation, bool open, int64_t applied) const; + // Records the state of a generation and forgets the oldest ones. + void Record(int64_t generation, const Entry& entry); -+ // Publishes `generation` unless a later one was published already. Lock-free. -+ bool RaisePublished(int64_t generation, bool open); ++ // Publishes `generation` unless a later one was published already, and returns whether it did. Lock-free. It goes ++ // out closed once the published word says latched, in the same step that publishes it: `sent` is the state it was ++ // published with, what Current() gave the units for it. ++ bool RaisePublished(int64_t generation, bool open, bool& sent); + + std::atomic m_open { true }; + std::atomic m_connectTests { true }; + std::atomic m_latched { false }; -+ // The last published generation and its state: (generation << 1) | open. ++ // The last published generation, whether the session latched, and the state the units send: Pack. The latch sets ++ // its bit before it reserves its generation, so a generation is published either before the latch began, open if it ++ // asked to, or after, closed: what Publish records is what Current() gave the units. + std::atomic m_published { 0 }; + // The last generation taken, and whether the session latched: (generation << 1) | latched. + std::atomic m_requested { 0 }; @@ -1352,7 +1561,7 @@ index 47b36ec..9e608ae 100644 output->ValueChanged += [this](void* sender, const OutputEventArgs& args) { OutputValueChanged.Invoke(this, args); }; } diff --git a/src/cab/out/adressableledstrip/DirectStripController.cpp b/src/cab/out/adressableledstrip/DirectStripController.cpp -index d9a5f85..085c22f 100644 +index d9a5f85..61b94f7 100644 --- a/src/cab/out/adressableledstrip/DirectStripController.cpp +++ b/src/cab/out/adressableledstrip/DirectStripController.cpp @@ -1,5 +1,6 @@ @@ -1374,7 +1583,7 @@ index d9a5f85..085c22f 100644 void DirectStripController::UpdaterThreadDoIt() { -+ OutputGate::Unit* gateUnit = m_gateUnit; ++ OutputGate::UnitHandle gateUnit = m_gateUnit; if (!m_controller) { m_controller = new DirectStripControllerApi(m_controllerNumber); @@ -1433,8 +1642,20 @@ index d9a5f85..085c22f 100644 m_updaterThreadFinished = true; } +@@ -267,7 +285,10 @@ bool DirectStripController::FromXml(const tinyxml2::XMLElement* element) + { + try + { +- int controllerNumber = std::stoi(controllerNumberElement->GetText()); ++ // VPE: the whole text is the number; one that only starts with a number ("1old", "2.5") selects no board. ++ int controllerNumber = 0; ++ if (!StringExtensions::TryParseInt(controllerNumberElement->GetText(), controllerNumber)) ++ return false; + SetControllerNumber(controllerNumber); + } + catch (...) diff --git a/src/cab/out/adressableledstrip/DirectStripController.h b/src/cab/out/adressableledstrip/DirectStripController.h -index e112579..175fad3 100644 +index e112579..6ce43dc 100644 --- a/src/cab/out/adressableledstrip/DirectStripController.h +++ b/src/cab/out/adressableledstrip/DirectStripController.h @@ -4,6 +4,7 @@ @@ -1449,26 +1670,54 @@ index e112579..175fad3 100644 std::atomic m_updaterThreadFinished { false }; DirectStripControllerApi* m_controller; -+ OutputGate::Unit* m_gateUnit = nullptr; ++ OutputGate::UnitHandle m_gateUnit; }; } \ No newline at end of file diff --git a/src/cab/out/adressableledstrip/TeensyStripController.cpp b/src/cab/out/adressableledstrip/TeensyStripController.cpp -index d3678e4..b70ae6a 100644 +index d3678e4..c502afc 100644 --- a/src/cab/out/adressableledstrip/TeensyStripController.cpp +++ b/src/cab/out/adressableledstrip/TeensyStripController.cpp -@@ -245,6 +245,9 @@ void TeensyStripController::UpdateOutputs(const std::vector& outputValu +@@ -213,18 +213,20 @@ bool TeensyStripController::VerifySettings() + return true; + } + +-void TeensyStripController::SendLedstripData(const std::vector& outputValues, int targetPosition) ++bool TeensyStripController::SendLedstripData(const std::vector& outputValues, int targetPosition) + { + int nrOfLeds = static_cast(outputValues.size()) / 3; + std::vector commandData = { (uint8_t)'R', (uint8_t)(targetPosition >> 8), (uint8_t)(targetPosition & 255), (uint8_t)(nrOfLeds >> 8), (uint8_t)(nrOfLeds & 255) }; ++ // VPE: the command and the values are one write, the same bytes on the line: a latch can let at most that one write ++ // through, never a header without its values or values after a stopped header. ++ commandData.insert(commandData.end(), outputValues.begin(), outputValues.end()); ++ if (TransferCancelled()) ++ return false; + +- enum sp_return result = sp_blocking_write(m_comPort, commandData.data(), 5, m_comPortTimeOutMs); +- if (result < 0) +- throw std::runtime_error(StringExtensions::Build("Failed to write command data: {0}", sp_last_error_message())); +- +- result = sp_blocking_write(m_comPort, outputValues.data(), outputValues.size(), m_comPortTimeOutMs); ++ enum sp_return result = sp_blocking_write(m_comPort, commandData.data(), commandData.size(), m_comPortTimeOutMs); + if (result < 0) + throw std::runtime_error(StringExtensions::Build("Failed to write output values: {0}", sp_last_error_message())); ++ return true; + } + + void TeensyStripController::UpdateOutputs(const std::vector& outputValues) +@@ -245,7 +247,9 @@ void TeensyStripController::UpdateOutputs(const std::vector& outputValu int targetPosition = i * m_numberOfLedsPerChannel; std::vector stripData(outputValues.begin() + sourcePosition * 3, outputValues.begin() + sourcePosition * 3 + nrOfLedsOnStrip * 3); +- SendLedstripData(stripData, targetPosition); + // VPE: a latch that overtook the transfer stops it before the next write (each strip, then the output command). -+ if (TransferCancelled()) ++ if (!SendLedstripData(stripData, targetPosition)) + return; - SendLedstripData(stripData, targetPosition); bytesRead = -1; -@@ -270,6 +273,8 @@ void TeensyStripController::UpdateOutputs(const std::vector& outputValu + answerData = std::vector(1); +@@ -270,6 +274,8 @@ void TeensyStripController::UpdateOutputs(const std::vector& outputValu } commandData = { (uint8_t)'O' }; @@ -1477,8 +1726,23 @@ index d3678e4..b70ae6a 100644 enum sp_return result = sp_blocking_write(m_comPort, commandData.data(), 1, m_comPortTimeOutMs); if (result < 0) throw std::runtime_error(StringExtensions::Build("Failed to write output command: {0}", sp_last_error_message())); +diff --git a/src/cab/out/adressableledstrip/TeensyStripController.h b/src/cab/out/adressableledstrip/TeensyStripController.h +index e910f68..51c6565 100644 +--- a/src/cab/out/adressableledstrip/TeensyStripController.h ++++ b/src/cab/out/adressableledstrip/TeensyStripController.h +@@ -107,7 +107,9 @@ protected: + virtual void DisconnectFromController() override; + virtual void UpdateOutputs(const std::vector& outputValues) override; + +- virtual void SendLedstripData(const std::vector& outputValues, int targetPosition); ++ // VPE: sends the strip's command and values in one write, checked once they are prepared; false if a latch that ++ // overtook the transfer stopped it before that write. ++ virtual bool SendLedstripData(const std::vector& outputValues, int targetPosition); + virtual void SetupController(); + int ReadPortWait(uint8_t* buffer, int bufferOffset, int numberOfBytes); + diff --git a/src/cab/out/adressableledstrip/UMXController.cpp b/src/cab/out/adressableledstrip/UMXController.cpp -index 9cbe817..427556d 100644 +index 9cbe817..cb58397 100644 --- a/src/cab/out/adressableledstrip/UMXController.cpp +++ b/src/cab/out/adressableledstrip/UMXController.cpp @@ -1,4 +1,5 @@ @@ -1487,7 +1751,31 @@ index 9cbe817..427556d 100644 #include "UMXControllerAutoConfigurator.h" #include "../../Cabinet.h" #include "../OutputControllerList.h" -@@ -98,7 +99,11 @@ void UMXController::UpdateOutputs(const std::vector& outputValues) +@@ -47,9 +48,12 @@ int UMXController::GetNumberOfConfiguredOutputs() { return m_dev ? m_dev->NumOut + + void UMXController::ConnectToController() + { ++ // VPE: only a controller that ran turns its outputs off here (a reconnect), so a connect test that started before ++ // the first connect is not cut short; the session's end turns it off. + try + { +- DisconnectFromController(); ++ if (m_inUseState == InUseState::Running) ++ DisconnectFromController(); + } + catch (const std::exception& e) + { +@@ -63,7 +67,8 @@ void UMXController::ConnectToController() + + void UMXController::DisconnectFromController() + { +- if (m_inUseState == InUseState::Running && m_dev) ++ // VPE: also after a connect test that started, which may still light the strip when the session ends. ++ if ((m_inUseState == InUseState::Running || m_deviceUsed) && m_dev) + { + m_dev->SendCommand(UMXDevice::UMXCommand::UMX_AllOff); + m_disconnectTurnedOff = true; +@@ -98,7 +103,11 @@ void UMXController::UpdateOutputs(const std::vector& outputValues) if (!m_dev) throw std::runtime_error(StringExtensions::Build("UMX controller {0} has no device", GetName())); @@ -1500,7 +1788,7 @@ index 9cbe817..427556d 100644 m_lastTime = std::chrono::steady_clock::now(); m_lastTimeInit = true; } -@@ -122,20 +127,26 @@ void UMXController::UpdateCabinetFromConfig(Cabinet* cabinet) +@@ -122,20 +131,32 @@ void UMXController::UpdateCabinetFromConfig(Cabinet* cabinet) return; } @@ -1511,12 +1799,18 @@ index 9cbe817..427556d 100644 static_cast(m_dev->m_testOnConnect), m_dev->m_testOnConnectDuration, }; -+ OutputGate::Unit* gateUnit = RegisterGateUnit(); ++ OutputGate::UnitHandle gateUnit = RegisterGateUnit(); ++ // VPE: the test goes out with the gate as this unit sends it, and confirms that opening only (ConnectTestSent). ++ OutputGate::Snapshot gate = ObserveGate(); try { - m_dev->SendCommand(UMXDevice::UMXCommand::UMX_StartTest, parameters); -+ if (!m_dev->SendCommand(UMXDevice::UMXCommand::UMX_StartTest, parameters, []() { return !OutputGate::Instance().AllowsConnectTests(); })) ++ // VPE: the cancel check runs right before the write: a closing or a latch since the gate was observed skips it. ++ if (!gate.open ++ || !m_dev->SendCommand(UMXDevice::UMXCommand::UMX_StartTest, parameters, [this]() { return !OutputGate::Instance().AllowsConnectTests() || !ObserveGate().open; })) + Log::Write(StringExtensions::Build("UMX controller {0} does not start its connect test, the output gate is closed", GetName())); ++ else ++ ConnectTestSent(gate); } catch (const std::exception& e) { @@ -1529,6 +1823,18 @@ index 9cbe817..427556d 100644 Log::Warning(StringExtensions::Build("UMX controller {0} could not start its connect test: {1}", GetName(), e.what())); } } +@@ -269,7 +290,10 @@ bool UMXController::FromXml(const tinyxml2::XMLElement* element) + { + try + { +- int number = std::stoi(numberElement->GetText()); ++ // VPE: the whole text is the number; one that only starts with a number ("1old", "2.5") selects no board. ++ int number = 0; ++ if (!StringExtensions::TryParseInt(numberElement->GetText(), number)) ++ return false; + SetNumber(number); + } + catch (...) diff --git a/src/cab/out/adressableledstrip/UMXControllerAutoConfigurator.cpp b/src/cab/out/adressableledstrip/UMXControllerAutoConfigurator.cpp index 385851c..c9e4536 100644 --- a/src/cab/out/adressableledstrip/UMXControllerAutoConfigurator.cpp @@ -1638,7 +1944,7 @@ index 4475b47..07e2e83 100644 virtual bool IsLost() const { return false; } virtual void Release() { } diff --git a/src/cab/out/adressableledstrip/WemosD1StripController.cpp b/src/cab/out/adressableledstrip/WemosD1StripController.cpp -index cb013c8..51cf2b9 100644 +index cb013c8..81f5327 100644 --- a/src/cab/out/adressableledstrip/WemosD1StripController.cpp +++ b/src/cab/out/adressableledstrip/WemosD1StripController.cpp @@ -1,5 +1,6 @@ @@ -1648,20 +1954,105 @@ index cb013c8..51cf2b9 100644 #include "../../../Log.h" #include "../../../general/StringExtensions.h" #include -@@ -66,10 +67,11 @@ void WemosD1MPStripController::SetupController() +@@ -66,14 +67,38 @@ void WemosD1MPStripController::SetupController() } } - if (m_testOnConnect) -+ if (m_testOnConnect && OutputGate::Instance().AllowsConnectTests()) -+ Log::Write("Send a test request to the controller"); -+ if (m_testOnConnect && OutputGate::Instance().AllowsConnectTests()) ++ // VPE: the test is decided once (TakeConnectTest): never on a reconnect, nor in a session that starts closed, which ++ // starts dark. It goes out with the gate as this unit sends it, checked again right before the write as every other ++ // write is, so a closing or a latch since (also one during the log line) skips it, and its 2 s wait. ++ bool test = m_testOnConnect && TakeConnectTest(); ++ m_testOnConnect = false; ++ if (test) + { +- commandData = { (uint8_t)'T' }; + Log::Write("Send a test request to the controller"); +- +- enum sp_return result = sp_blocking_write(GetComPort(), commandData.data(), 1, GetComPortTimeOutMs()); +- if (result < 0) +- throw std::runtime_error(StringExtensions::Build("Failed to write test command: {0}", sp_last_error_message())); ++ OutputGate::Snapshot gate = ObserveGate(); ++ bool sent = false; ++ if (gate.open && OutputGate::Instance().AllowsConnectTests()) ++ { ++ OutputGate::Transfer transfer(GateUnit(), gate); ++ if (!TransferCancelled()) ++ { ++ commandData = { (uint8_t)'T' }; ++ enum sp_return result = sp_blocking_write(GetComPort(), commandData.data(), 1, GetComPortTimeOutMs()); ++ if (result < 0) ++ throw std::runtime_error(StringExtensions::Build("Failed to write test command: {0}", sp_last_error_message())); ++ if (result == 0) ++ throw std::runtime_error("Failed to write test command: the port took nothing within its timeout"); ++ // VPE: the port took the test, which may light the strip whatever the controller answers: the session ends ++ // with the blackout from here on, also if the setup fails below. ++ sent = true; ++ ConnectTestSent(gate); ++ } ++ } ++ if (!sent) ++ { ++ Log::Write("The test request is not sent, the output gate closed"); ++ return; ++ } + + std::this_thread::sleep_for(std::chrono::milliseconds(2000)); + +@@ -95,12 +120,10 @@ void WemosD1MPStripController::SetupController() + throw std::runtime_error(StringExtensions::Build( + "Expected a Ack (A) after requesting a test sequence, but received no answer or a unexpected answer ({0}). Will not send data to the controller.", std::string(1, receivedChar))); + } +- +- m_testOnConnect = false; + } + } + +-void WemosD1MPStripController::SendLedstripData(const std::vector& outputValues, int targetPosition) ++bool WemosD1MPStripController::SendLedstripData(const std::vector& outputValues, int targetPosition) + { + if (m_useCompression) + { +@@ -148,18 +171,22 @@ void WemosD1MPStripController::SendLedstripData(const std::vector& outp + + std::vector commandData = { (uint8_t)'Q', (uint8_t)(targetPosition >> 8), (uint8_t)(targetPosition & 255), (uint8_t)(nbData >> 8), (uint8_t)(nbData & 255), + (uint8_t)(nbLeds >> 8), (uint8_t)(nbLeds & 255) }; ++ // VPE: as in TeensyStripController, one write, checked once the values are compressed. ++ commandData.insert(commandData.end(), m_compressedData.begin(), m_compressedData.end()); ++ if (TransferCancelled()) ++ return false; + +- sp_blocking_write(GetComPort(), commandData.data(), 7, GetComPortTimeOutMs()); +- sp_blocking_write(GetComPort(), m_compressedData.data(), m_compressedData.size(), GetComPortTimeOutMs()); ++ sp_blocking_write(GetComPort(), commandData.data(), commandData.size(), GetComPortTimeOutMs()); ++ return true; + } + else + { +- TeensyStripController::SendLedstripData(outputValues, targetPosition); ++ return TeensyStripController::SendLedstripData(outputValues, targetPosition); + } + } + else { - commandData = { (uint8_t)'T' }; -- Log::Write("Send a test request to the controller"); +- TeensyStripController::SendLedstripData(outputValues, targetPosition); ++ return TeensyStripController::SendLedstripData(outputValues, targetPosition); + } + } + +diff --git a/src/cab/out/adressableledstrip/WemosD1StripController.h b/src/cab/out/adressableledstrip/WemosD1StripController.h +index 4b18a5d..b063812 100644 +--- a/src/cab/out/adressableledstrip/WemosD1StripController.h ++++ b/src/cab/out/adressableledstrip/WemosD1StripController.h +@@ -29,7 +29,7 @@ public: + + protected: + virtual void SetupController() override; +- virtual void SendLedstripData(const std::vector& outputValues, int targetPosition) override; ++ virtual bool SendLedstripData(const std::vector& outputValues, int targetPosition) override; - enum sp_return result = sp_blocking_write(GetComPort(), commandData.data(), 1, GetComPortTimeOutMs()); - if (result < 0) + protected: + std::vector m_compressedData; diff --git a/src/cab/out/comport/PinControl.cpp b/src/cab/out/comport/PinControl.cpp index 2b16bd5..605b5ce 100644 --- a/src/cab/out/comport/PinControl.cpp @@ -1717,7 +2108,7 @@ index 1bebe23..980636d 100644 virtual void DisconnectFromController() override; diff --git a/src/cab/out/dmx/ArtNet.cpp b/src/cab/out/dmx/ArtNet.cpp -index b7516b8..25936a5 100644 +index b7516b8..f1285c0 100644 --- a/src/cab/out/dmx/ArtNet.cpp +++ b/src/cab/out/dmx/ArtNet.cpp @@ -29,7 +29,12 @@ void ArtNet::UpdateOutputs(const std::vector& outputValues) @@ -1733,6 +2124,18 @@ index b7516b8..25936a5 100644 } else { +@@ -109,7 +114,10 @@ bool ArtNet::FromXml(const tinyxml2::XMLElement* element) + { + try + { +- int universe = std::stoi(universeElement->GetText()); ++ // VPE: the whole text is the number; one that only starts with a number ("1old", "2.5") selects no board. ++ int universe = 0; ++ if (!StringExtensions::TryParseInt(universeElement->GetText(), universe)) ++ return false; + SetUniverse(static_cast(universe)); + } + catch (...) diff --git a/src/cab/out/dmx/artnetengine/Engine.cpp b/src/cab/out/dmx/artnetengine/Engine.cpp index 302baa3..22ce37c 100644 --- a/src/cab/out/dmx/artnetengine/Engine.cpp @@ -1755,7 +2158,7 @@ index 302baa3..22ce37c 100644 { try diff --git a/src/cab/out/dudescab/DudesCab.cpp b/src/cab/out/dudescab/DudesCab.cpp -index b9a8fd5..ba9fc08 100644 +index b9a8fd5..8f6d8de 100644 --- a/src/cab/out/dudescab/DudesCab.cpp +++ b/src/cab/out/dudescab/DudesCab.cpp @@ -25,6 +25,7 @@ namespace DOF @@ -1967,6 +2370,18 @@ index b9a8fd5..ba9fc08 100644 } DudesCab::Device::HIDCommonReportType DudesCab::Device::RemapCommonCommand(HIDCommonReportType command) +@@ -832,7 +886,10 @@ bool DudesCab::FromXml(const tinyxml2::XMLElement* element) + { + try + { +- int number = std::stoi(numberElement->GetText()); ++ // VPE: the whole text is the number; one that only starts with a number ("1old", "2.5") selects no board. ++ int number = 0; ++ if (!StringExtensions::TryParseInt(numberElement->GetText(), number)) ++ return false; + SetNumber(number); + } + catch (...) diff --git a/src/cab/out/dudescab/DudesCab.h b/src/cab/out/dudescab/DudesCab.h index a42d974..9b2749c 100644 --- a/src/cab/out/dudescab/DudesCab.h @@ -2067,7 +2482,7 @@ index 4a73aec..e24fc86 100644 bool IsLost() const override { return m_device && m_device->IsLost(); } void Release() override; diff --git a/src/cab/out/ftdichip/FT245RBitbangController.cpp b/src/cab/out/ftdichip/FT245RBitbangController.cpp -index 4c0f5f7..4448662 100644 +index 4c0f5f7..adb5973 100644 --- a/src/cab/out/ftdichip/FT245RBitbangController.cpp +++ b/src/cab/out/ftdichip/FT245RBitbangController.cpp @@ -7,6 +7,7 @@ @@ -2099,7 +2514,7 @@ index 4c0f5f7..4448662 100644 void FT245RBitbangController::UpdaterThreadDoIt() { -+ OutputGate::Unit* gateUnit = m_gateUnit; ++ OutputGate::UnitHandle gateUnit = m_gateUnit; Connect(); if (!m_ftdi) { @@ -2218,8 +2633,20 @@ index 4c0f5f7..4448662 100644 if (m_ftdi) { +@@ -460,7 +504,10 @@ bool FT245RBitbangController::FromXml(const tinyxml2::XMLElement* element) + { + try + { +- int id = std::stoi(idElement->GetText()); ++ // VPE: the whole text is the number; one that only starts with a number ("1old", "2.5") selects no board. ++ int id = 0; ++ if (!StringExtensions::TryParseInt(idElement->GetText(), id)) ++ return false; + SetId(id); + } + catch (...) diff --git a/src/cab/out/ftdichip/FT245RBitbangController.h b/src/cab/out/ftdichip/FT245RBitbangController.h -index b90b458..fba2a65 100644 +index b90b458..52afc27 100644 --- a/src/cab/out/ftdichip/FT245RBitbangController.h +++ b/src/cab/out/ftdichip/FT245RBitbangController.h @@ -2,6 +2,7 @@ @@ -2234,12 +2661,12 @@ index b90b458..fba2a65 100644 std::condition_variable m_updaterThreadCondition; std::atomic m_keepUpdaterThreadAlive; std::atomic m_updaterThreadFinished; -+ OutputGate::Unit* m_gateUnit = nullptr; ++ OutputGate::UnitHandle m_gateUnit; std::string m_finishError; int m_firstTryFailCnt; diff --git a/src/cab/out/lw/LedWiz.cpp b/src/cab/out/lw/LedWiz.cpp -index 21cda40..60eaab0 100644 +index 21cda40..24d0b1c 100644 --- a/src/cab/out/lw/LedWiz.cpp +++ b/src/cab/out/lw/LedWiz.cpp @@ -1,5 +1,6 @@ @@ -2249,7 +2676,100 @@ index 21cda40..60eaab0 100644 #include "../../../Log.h" #include "../../../general/MathExtensions.h" #include "../../../general/StringExtensions.h" -@@ -485,15 +486,46 @@ LedWiz::LedWizUnit::~LedWizUnit() +@@ -51,9 +52,18 @@ LedWiz::LedWiz() + , m_minCommandIntervalMs(10) + , m_minCommandIntervalMsSet(false) + { ++} ++ ++void LedWiz::Startup() ++{ ++ // VPE: the devices are opened when the controller is initialized, not when it is made, so a controller that is ++ // skipped because its configuration cannot be read opens none. ++ if (m_startedUp) ++ return; + InitializeUnits(); + Log::Write(StringExtensions::Build("Opening {0}-bit LedWiz driver...", sizeof(void*) == 8 ? "64" : "32")); + StartupLedWiz(); ++ m_startedUp = true; + } + + LedWiz::LedWiz(int number) +@@ -65,7 +75,8 @@ LedWiz::LedWiz(int number) + LedWiz::~LedWiz() + { + Log::Debug(StringExtensions::Build("Disposing LedWiz instance {0:00}.", std::to_string(m_number))); +- TerminateLedWiz(); ++ if (m_startedUp) ++ TerminateLedWiz(); + } + + void LedWiz::SetNumber(int value) +@@ -89,7 +100,12 @@ void LedWiz::SetMinCommandIntervalMs(int value) + m_minCommandIntervalMsSet = true; + } + +-void LedWiz::Update() { s_ledWizUnits.at(m_number)->TriggerLedWizUpdaterThread(); } ++void LedWiz::Update() ++{ ++ auto unit = s_ledWizUnits.find(m_number); ++ if (m_startedUp && unit != s_ledWizUnits.end()) ++ unit->second->TriggerLedWizUpdaterThread(); ++} + + void LedWiz::Init(Cabinet* cabinet) + { +@@ -106,6 +122,7 @@ void LedWiz::Init(Cabinet* cabinet) + { + } + } ++ Startup(); + s_ledWizUnits.at(m_number)->Init(cabinet, m_minCommandIntervalMs); + Log::Write(StringExtensions::Build("LedWiz Nr. {0:00} initialized and updater thread initialized.", std::to_string(m_number))); + } +@@ -160,7 +177,10 @@ void LedWiz::OnOutputValueChanged(IOutput* output) + return; + } + +- LedWizUnit* s = s_ledWizUnits.at(m_number); ++ auto unit = s_ledWizUnits.find(m_number); ++ if (!m_startedUp || unit == s_ledWizUnits.end()) ++ return; ++ LedWizUnit* s = unit->second; + + IOutput* recalculatedOutput = ScheduledSettings::GetInstance().GetNewRecalculatedOutput(output, 1, m_number - 1); + LedWizOutput recalculatedLedWizOutput(lwo->GetLedWizOutputNumber()); +@@ -409,17 +429,20 @@ bool LedWiz::FromXml(const tinyxml2::XMLElement* element) + if (nameElement && nameElement->GetText()) + SetName(nameElement->GetText()); + ++ // VPE: the number selects the unit; without one the controller would drive no unit and fail its Init, which fails ++ // the whole cabinet, so it is not read. The whole text is the number: one that only starts with a number ("2.5") ++ // selects no unit. + const tinyxml2::XMLElement* numberElement = element->FirstChildElement("Number"); +- if (numberElement && numberElement->GetText()) ++ int number = 0; ++ if (!numberElement || !numberElement->GetText() || !StringExtensions::TryParseInt(numberElement->GetText(), number)) ++ return false; ++ try + { +- try +- { +- SetNumber(std::stoi(numberElement->GetText())); +- } +- catch (...) +- { +- return false; +- } ++ SetNumber(number); ++ } ++ catch (...) ++ { ++ return false; + } + + const tinyxml2::XMLElement* intervalElement = element->FirstChildElement("MinCommandIntervalMs"); +@@ -485,15 +508,59 @@ LedWiz::LedWizUnit::~LedWizUnit() void LedWiz::LedWizUnit::Init(Cabinet* cabinet, int minCommandIntervalMs) { m_minCommandIntervalMs = minCommandIntervalMs; @@ -2285,7 +2805,21 @@ index 21cda40..60eaab0 100644 + if (m_gateUnit) + gate = m_gateUnit->Observe(); m_writeFailed = false; - ShutdownLighting(); +- ShutdownLighting(); ++ // VPE: a blackout that throws is a failed one, and the unit still stops below. ++ try ++ { ++ ShutdownLighting(); ++ } ++ catch (const std::exception& e) ++ { ++ Log::Exception(StringExtensions::Build("Turning the outputs of LedWiz Nr. {0:00} off failed: {1}", std::to_string(m_number), e.what())); ++ m_writeFailed = true; ++ } ++ catch (...) ++ { ++ m_writeFailed = true; ++ } m_shutdownFailed = m_writeFailed && (m_fp != nullptr || IsPresent()); + if (m_gateUnit) + { @@ -2296,11 +2830,11 @@ index 21cda40..60eaab0 100644 } void LedWiz::LedWizUnit::UpdateValue(LedWizOutput* ledWizOutput) -@@ -616,10 +648,16 @@ void LedWiz::LedWizUnit::LedWizUpdaterDoIt() +@@ -616,35 +683,67 @@ void LedWiz::LedWizUnit::LedWizUpdaterDoIt() { Log::Write(StringExtensions::Build("Updater thread for LedWiz {0:00} started.", std::to_string(m_number))); -+ OutputGate::Unit* gateUnit = m_gateUnit; ++ OutputGate::UnitHandle gateUnit = m_gateUnit; int failCnt = 0; while (m_keepLedWizUpdaterAlive) { @@ -2313,22 +2847,41 @@ index 21cda40..60eaab0 100644 try { if (IsPresent()) -@@ -634,17 +672,39 @@ void LedWiz::LedWizUnit::LedWizUpdaterDoIt() - m_inUseState = InUseStates::Running; - } - -- if (m_inUseState == InUseStates::Running) -- SendLedWizUpdate(); + { +- if (m_inUseState == InUseStates::ValueChanged) + bool wrote = true; + if (!gate.open) + ShutdownLighting(); -+ else if (m_inUseState == InUseStates::Running) -+ { -+ // VPE: WriteUSB stops before each write once a latch overtook this opening's transfer. ++ else if (m_inUseState != InUseStates::Startup) + { +- const uint8_t sba[4] = { 0, 0, 0, 0 }; +- SBA(sba); +- std::array pba; +- pba.fill(49); +- PBA(pba.data()); +- m_inUseState = InUseStates::Running; ++ // VPE: WriteUSB stops before each write once a latch overtook this opening's transfer. The startup ++ // sequence goes out with the first opening that has values, in its transfer too; the unit runs once the ++ // sequence got through, and sends it again on the next pass otherwise. + OutputGate::Transfer transfer(gateUnit, gate); -+ stale = !SendLedWizUpdate(gate); ++ if (m_inUseState == InUseStates::ValueChanged) ++ { ++ const uint8_t sba[4] = { 0, 0, 0, 0 }; ++ SBA(sba); ++ std::array pba; ++ pba.fill(49); ++ if (!m_writeFailed && !transfer.Cancelled()) ++ PBA(pba.data()); ++ if (!m_writeFailed && !transfer.Cancelled()) ++ m_inUseState = InUseStates::Running; ++ } ++ if (m_inUseState == InUseStates::Running && !m_writeFailed && !transfer.Cancelled()) ++ stale = !SendLedWizUpdate(gate); + cancelled = transfer.Cancelled(); -+ } + } +- +- if (m_inUseState == InUseStates::Running) +- SendLedWizUpdate(); + else + wrote = false; if (m_writeFailed) @@ -2355,7 +2908,7 @@ index 21cda40..60eaab0 100644 failCnt++; if (failCnt > MAX_UPDATE_FAIL_COUNT) { -@@ -654,13 +714,14 @@ void LedWiz::LedWizUnit::LedWizUpdaterDoIt() +@@ -654,13 +753,14 @@ void LedWiz::LedWizUnit::LedWizUpdaterDoIt() } } @@ -2372,7 +2925,7 @@ index 21cda40..60eaab0 100644 break; } } -@@ -668,6 +729,33 @@ void LedWiz::LedWizUnit::LedWizUpdaterDoIt() +@@ -668,6 +768,33 @@ void LedWiz::LedWizUnit::LedWizUpdaterDoIt() } Log::Write(StringExtensions::Build("Updater thread for LedWiz {0:00} terminated.", std::to_string(m_number))); @@ -2406,7 +2959,7 @@ index 21cda40..60eaab0 100644 m_updaterThreadFinished = true; } -@@ -688,15 +776,20 @@ void LedWiz::LedWizUnit::UpdateDelay() +@@ -688,15 +815,20 @@ void LedWiz::LedWizUnit::UpdateDelay() m_lastUpdate = std::chrono::steady_clock::now(); } @@ -2429,7 +2982,7 @@ index 21cda40..60eaab0 100644 CopyNewToCurrent(); m_updateRequired = false; } -@@ -711,6 +804,7 @@ void LedWiz::LedWizUnit::SendLedWizUpdate() +@@ -711,6 +843,7 @@ void LedWiz::LedWizUnit::SendLedWizUpdate() if (m_currentSwitchUpdateAfterValueUpdateRequired || (m_currentSwitchUpdateBeforeValueUpdateRequired && !m_currentValueUpdateRequired) || pbaTimeout) SBA(m_currentAfterValueSwitches.data()); } @@ -2437,7 +2990,7 @@ index 21cda40..60eaab0 100644 } void LedWiz::LedWizUnit::ShutdownLighting() -@@ -742,6 +836,8 @@ void LedWiz::LedWizUnit::WriteUSB(const uint8_t* buf, size_t length) +@@ -742,6 +875,8 @@ void LedWiz::LedWizUnit::WriteUSB(const uint8_t* buf, size_t length) UpdateDelay(); for (int tries = 0; tries < static_cast(std::size(s_retryWait)); ++tries) { @@ -2447,7 +3000,7 @@ index 21cda40..60eaab0 100644 return; std::this_thread::sleep_for(std::chrono::milliseconds(s_retryWait[tries])); diff --git a/src/cab/out/lw/LedWiz.h b/src/cab/out/lw/LedWiz.h -index 31bd9ca..1110829 100644 +index 31bd9ca..7bfc481 100644 --- a/src/cab/out/lw/LedWiz.h +++ b/src/cab/out/lw/LedWiz.h @@ -1,6 +1,7 @@ @@ -2458,7 +3011,17 @@ index 31bd9ca..1110829 100644 #include #include #include -@@ -118,7 +119,8 @@ private: +@@ -73,6 +74,9 @@ private: + static std::mutex s_startupLocker; + static void StartupLedWiz(); + static void TerminateLedWiz(); ++ // VPE: opens the devices for this controller, once (Init). ++ void Startup(); ++ bool m_startedUp = false; + static std::string GetDeviceProductName(hid_device_info* dev); + static std::string GetDeviceManufacturerName(hid_device_info* dev); + static int GetOutputReportByteLength(hid_device* dev); +@@ -118,7 +122,8 @@ private: void LedWizUpdaterDoIt(); void UpdateDelay(); @@ -2468,16 +3031,16 @@ index 31bd9ca..1110829 100644 void SBA(const uint8_t* b, uint8_t globalFlashSpeed = 2); void PBA(const uint8_t* b); void WriteUSB(const uint8_t* buf, size_t length); -@@ -158,6 +160,7 @@ private: +@@ -158,6 +163,7 @@ private: int m_minCommandIntervalMs; std::chrono::steady_clock::time_point m_pbaTime; bool m_writeFailed = false; -+ OutputGate::Unit* m_gateUnit = nullptr; ++ OutputGate::UnitHandle m_gateUnit; bool m_shutdownFailed = false; public: diff --git a/src/cab/out/pac/PacDrive.cpp b/src/cab/out/pac/PacDrive.cpp -index e13a317..d40d4de 100644 +index e13a317..7c7f915 100644 --- a/src/cab/out/pac/PacDrive.cpp +++ b/src/cab/out/pac/PacDrive.cpp @@ -1,5 +1,6 @@ @@ -2487,7 +3050,58 @@ index e13a317..d40d4de 100644 #include "../../../Log.h" #include "../../../general/StringExtensions.h" #include "../../Cabinet.h" -@@ -140,8 +141,12 @@ void PacDrive::PacDriveUnit::Init(Cabinet* cabinet) +@@ -17,7 +18,12 @@ PacDrive::PacDriveUnit* PacDrive::s_pacDriveInstance = nullptr; + + PacDrive::PacDrive() { SetName("PacDrive"); } + +-PacDrive::~PacDrive() { } ++PacDrive::~PacDrive() ++{ ++ // VPE: one that was never finished (its cabinet failed) does not keep the unit in use for the next session. ++ if (m_usesUnit && s_pacDriveInstance) ++ s_pacDriveInstance->RemoveUser(); ++} + + void PacDrive::Init(Cabinet* cabinet) + { +@@ -28,7 +34,15 @@ void PacDrive::Init(Cabinet* cabinet) + s_pacDriveInstance = new PacDriveUnit(); + } + +- s_pacDriveInstance->Init(cabinet); ++ // VPE: the physical unit is initialized once, by its first user: it registers with the gate once, as present or ++ // as missing, however many entries share it. ++ if (!s_pacDriveInstance->InUse()) ++ s_pacDriveInstance->Init(cabinet); ++ if (!m_usesUnit) ++ { ++ m_usesUnit = true; ++ s_pacDriveInstance->AddUser(); ++ } + Log::Write("PacDrive initialized and updater thread started."); + } + +@@ -37,8 +51,19 @@ void PacDrive::Finish() + bool shutdownFailed = false; + if (s_pacDriveInstance) + { ++ if (m_usesUnit) ++ { ++ m_usesUnit = false; ++ s_pacDriveInstance->RemoveUser(); ++ } ++ if (s_pacDriveInstance->InUse()) ++ { ++ Log::Write("PacDrive finished; another PacDrive entry still uses the unit, which finishes with it."); ++ return; ++ } + s_pacDriveInstance->Finish(); + shutdownFailed = !s_pacDriveInstance->ShutdownLighting(); ++ s_pacDriveInstance->ReleaseGateUnit(); + } + Log::Write("PacDrive finished and updater thread stopped."); + if (shutdownFailed) +@@ -140,8 +165,12 @@ void PacDrive::PacDriveUnit::Init(Cabinet* cabinet) } if (m_index >= 0) { @@ -2500,16 +3114,30 @@ index e13a317..d40d4de 100644 } void PacDrive::PacDriveUnit::Finish() { TerminatePacDriveUpdaterThread(); } -@@ -181,7 +186,18 @@ bool PacDrive::PacDriveUnit::ShutdownLighting() +@@ -181,7 +210,31 @@ bool PacDrive::PacDriveUnit::ShutdownLighting() bool ok = true; if (m_index >= 0) { +- ok = PacDriveSetLEDStates(0); + // VPE: the final blackout confirms the closing published before it; the unit stops after it, not before, so it -+ // is not counted as failed while the blackout is sent. ++ // is not counted as failed while the blackout is sent. It stops whatever the blackout does: one that throws (the ++ // USB claim) is a failed blackout. + OutputGate::Snapshot before {}; + if (m_gateUnit) + before = m_gateUnit->Observe(); - ok = PacDriveSetLEDStates(0); ++ try ++ { ++ ok = PacDriveSetLEDStates(0); ++ } ++ catch (const std::exception& e) ++ { ++ Log::Exception(StringExtensions::Build("Turning the PacDrive outputs off failed: {0}", e.what())); ++ ok = false; ++ } ++ catch (...) ++ { ++ ok = false; ++ } + if (m_gateUnit) + { + if (ok) @@ -2519,11 +3147,11 @@ index e13a317..d40d4de 100644 std::this_thread::sleep_for(std::chrono::milliseconds(100)); } return ok; -@@ -221,19 +237,36 @@ void PacDrive::PacDriveUnit::TerminatePacDriveUpdaterThread() +@@ -221,19 +274,36 @@ void PacDrive::PacDriveUnit::TerminatePacDriveUpdaterThread() void PacDrive::PacDriveUnit::PacDriveUpdaterDoIt() { -+ OutputGate::Unit* gateUnit = m_gateUnit; ++ OutputGate::UnitHandle gateUnit = m_gateUnit; int failCount = 0; while (m_keepPacDriveUpdaterAlive) { @@ -2557,7 +3185,7 @@ index e13a317..d40d4de 100644 Log::Exception(StringExtensions::Build("Error occurred when updating PacDrive: {0}", e.what())); failCount++; -@@ -251,31 +284,46 @@ void PacDrive::PacDriveUnit::PacDriveUpdaterDoIt() +@@ -251,31 +321,46 @@ void PacDrive::PacDriveUnit::PacDriveUpdaterDoIt() } m_triggerUpdate = false; } @@ -2613,7 +3241,7 @@ index e13a317..d40d4de 100644 void PacDrive::PacDriveUnit::CopyNewToCurrent() { m_currentValue = m_newValue; } diff --git a/src/cab/out/pac/PacDrive.h b/src/cab/out/pac/PacDrive.h -index e04bb5c..472bd91 100644 +index e04bb5c..b2c7d04 100644 --- a/src/cab/out/pac/PacDrive.h +++ b/src/cab/out/pac/PacDrive.h @@ -1,6 +1,7 @@ @@ -2624,15 +3252,40 @@ index e04bb5c..472bd91 100644 #include #include #include -@@ -56,6 +57,7 @@ private: +@@ -34,6 +35,8 @@ private: + static PacDriveUnit* s_pacDriveInstance; + + void AddOutputs(); ++ // VPE: this controller was initialized and counts as a user of the unit until it is finished. ++ bool m_usesUnit = false; + + class PacDriveUnit + { +@@ -46,6 +49,14 @@ private: + void UpdateValue(IOutput* output); + void TriggerPacDriveUpdaterThread(); + bool ShutdownLighting(); ++ // VPE: after the final blackout, so the session's gate is not kept until the next session registers. ++ void ReleaseGateUnit() { m_gateUnit.reset(); } ++ // VPE: the controllers configured for this unit (every PacDrive entry shares the one unit) that were initialized and not ++ // finished yet. The unit is finished with the last of them, so it keeps sending and confirming the gate's state ++ // until then, and its gate unit is stopped and released once. ++ void AddUser() { m_users++; } ++ void RemoveUser() { m_users--; } ++ bool InUse() const { return m_users > 0; } + + bool GetUpdateRequired() const { return m_updateRequired; } + +@@ -56,6 +67,8 @@ private: uint16_t m_currentValue; std::atomic m_updateRequired; int m_index; -+ OutputGate::Unit* m_gateUnit = nullptr; ++ OutputGate::UnitHandle m_gateUnit; ++ int m_users = 0; std::mutex m_pacDriveUpdateLocker; std::mutex m_valueChangeLocker; -@@ -70,7 +72,8 @@ private: +@@ -70,7 +83,8 @@ private: void StartPacDriveUpdaterThread(); void TerminatePacDriveUpdaterThread(); void PacDriveUpdaterDoIt(); @@ -2723,7 +3376,7 @@ index c71dc9d..01698a1 100644 bool PacLed64SetLEDStates(int index, int group, uint8_t data); bool PacLed64SetLEDFadeTime(int index, uint8_t fadeTime); diff --git a/src/cab/out/pac/PacLed64.cpp b/src/cab/out/pac/PacLed64.cpp -index 71fcd00..1ea552f 100644 +index 71fcd00..9841c6c 100644 --- a/src/cab/out/pac/PacLed64.cpp +++ b/src/cab/out/pac/PacLed64.cpp @@ -1,4 +1,5 @@ @@ -2750,7 +3403,81 @@ index 71fcd00..1ea552f 100644 std::map PacLed64::s_pacLed64Units; bool PacLed64::s_unitsInitialized = false; -@@ -221,14 +226,18 @@ void PacLed64::PacLed64Unit::Init(Cabinet* cabinet) +@@ -46,7 +51,13 @@ PacLed64::PacLed64(int id) + SetId(id); + } + +-PacLed64::~PacLed64() { } ++PacLed64::~PacLed64() ++{ ++ // VPE: one that was never finished (its cabinet failed) does not keep the unit in use for the next session. ++ auto unit = s_pacLed64Units.find(m_id); ++ if (m_usesUnit && unit != s_pacLed64Units.end()) ++ unit->second->RemoveUser(); ++} + + void PacLed64::SetId(int value) + { +@@ -94,17 +105,36 @@ void PacLed64::Init(Cabinet* cabinet) + InitializeUnits(); + s_pacLed64Units.at(m_id)->SetFullUpdateThreshold(m_fullUpdateThreshold); + s_pacLed64Units.at(m_id)->SetMinUpdateInterval(std::chrono::milliseconds(m_minUpdateIntervalMs)); +- s_pacLed64Units.at(m_id)->Init(cabinet); ++ // VPE: the physical unit is initialized once, by its first user: it registers with the gate once, as present or ++ // as missing, however many entries share it. ++ if (!s_pacLed64Units.at(m_id)->InUse()) ++ s_pacLed64Units.at(m_id)->Init(cabinet); ++ if (!m_usesUnit) ++ { ++ m_usesUnit = true; ++ s_pacLed64Units.at(m_id)->AddUser(); ++ } + + Log::Write(StringExtensions::Build("PacLed64 Id:{0} initialized and updater thread started.", std::to_string(m_id))); + } + + void PacLed64::Finish() + { +- if (s_pacLed64Units.find(m_id) != s_pacLed64Units.end()) ++ auto unit = s_pacLed64Units.find(m_id); ++ if (unit != s_pacLed64Units.end()) + { +- s_pacLed64Units[m_id]->Finish(); +- s_pacLed64Units[m_id]->ShutdownLighting(); ++ if (m_usesUnit) ++ { ++ m_usesUnit = false; ++ unit->second->RemoveUser(); ++ } ++ if (unit->second->InUse()) ++ { ++ Log::Write(StringExtensions::Build("PacLed64 Id:{0} finished; another entry with the Id still uses the unit, which finishes with it.", std::to_string(m_id))); ++ return; ++ } ++ unit->second->Finish(); ++ unit->second->ShutdownLighting(); + } + Log::Write(StringExtensions::Build("PacLed64 Id:{0} finished and updater thread stopped.", std::to_string(m_id))); + } +@@ -183,9 +213,14 @@ bool PacLed64::FromXml(const tinyxml2::XMLElement* element) + if (name) + SetName(name); + +- int id = element->IntAttribute("Id", -1); +- if (id != -1) +- SetId(id); ++ // VPE: the Id selects the unit; without one (or with one that is not a number) the controller would drive no unit ++ // and fail its Init, which fails the whole cabinet, so it is not read. The whole text is the number: one that only ++ // starts with a number ("0.5", "1old") selects no unit. ++ const char* idText = element->Attribute("Id"); ++ int id = -1; ++ if (!idText || !StringExtensions::TryParseInt(idText, id)) ++ return false; ++ SetId(id); + + int minInterval = element->IntAttribute("MinUpdateIntervalMs", -1); + if (minInterval != -1) +@@ -221,14 +256,18 @@ void PacLed64::PacLed64Unit::Init(Cabinet* cabinet) { m_index = PacDriveSingleton::GetInstance().PacLed64GetIndexForDeviceId(m_id); @@ -2769,7 +3496,7 @@ index 71fcd00..1ea552f 100644 Log::Warning(StringExtensions::Build("PacLed64 device {0} not found", std::to_string(m_id))); } } -@@ -236,16 +245,27 @@ void PacLed64::PacLed64Unit::Init(Cabinet* cabinet) +@@ -236,16 +275,30 @@ void PacLed64::PacLed64Unit::Init(Cabinet* cabinet) void PacLed64::PacLed64Unit::Finish() { TerminatePacLed64UpdaterThread(); @@ -2789,24 +3516,27 @@ index 71fcd00..1ea552f 100644 { + if (present) + m_gateUnit->Stop(); ++ m_gateUnit.reset(); m_index = -1; throw; } - + if (present) + m_gateUnit->Stop(); ++ // VPE: the unit outlives the session; it does not keep the session's gate until the next session registers. ++ m_gateUnit.reset(); m_index = -1; } -@@ -323,6 +343,7 @@ void PacLed64::PacLed64Unit::TerminatePacLed64UpdaterThread() +@@ -323,6 +376,7 @@ void PacLed64::PacLed64Unit::TerminatePacLed64UpdaterThread() void PacLed64::PacLed64Unit::PacLed64UpdaterDoIt() { -+ OutputGate::Unit* gateUnit = m_gateUnit; ++ OutputGate::UnitHandle gateUnit = m_gateUnit; try { ResetFadeTime(); -@@ -330,6 +351,7 @@ void PacLed64::PacLed64Unit::PacLed64UpdaterDoIt() +@@ -330,6 +384,7 @@ void PacLed64::PacLed64Unit::PacLed64UpdaterDoIt() catch (const std::exception& e) { Log::Exception(StringExtensions::Build("Exception occurred while setting fade time for PacLed64 {0} to 0: {1}", std::to_string(m_index), e.what())); @@ -2814,7 +3544,7 @@ index 71fcd00..1ea552f 100644 m_updaterThreadFinished = true; return; } -@@ -337,16 +359,27 @@ void PacLed64::PacLed64Unit::PacLed64UpdaterDoIt() +@@ -337,16 +392,27 @@ void PacLed64::PacLed64Unit::PacLed64UpdaterDoIt() int failCount = 0; while (m_keepPacLed64UpdaterAlive) { @@ -2843,7 +3573,7 @@ index 71fcd00..1ea552f 100644 Log::Exception(StringExtensions::Build("Error occurred when updating PacLed64 {0}: {1}", std::to_string(m_id), e.what())); failCount++; -@@ -365,30 +398,78 @@ void PacLed64::PacLed64Unit::PacLed64UpdaterDoIt() +@@ -365,30 +431,78 @@ void PacLed64::PacLed64Unit::PacLed64UpdaterDoIt() } m_triggerUpdate = false; } @@ -2926,7 +3656,7 @@ index 71fcd00..1ea552f 100644 updatesRequired++; } } -@@ -396,41 +477,56 @@ void PacLed64::PacLed64Unit::SendPacLed64Update() +@@ -396,41 +510,56 @@ void PacLed64::PacLed64Unit::SendPacLed64Update() if (m_forceFullUpdate || updatesRequired > m_fullUpdateThreshold) { EnforceMinUpdateInterval(); @@ -2999,7 +3729,7 @@ index 71fcd00..1ea552f 100644 void PacLed64::PacLed64Unit::CopyNewToCurrent() { m_currentValue = m_newValue; } diff --git a/src/cab/out/pac/PacLed64.h b/src/cab/out/pac/PacLed64.h -index 640daa8..da670ef 100644 +index 640daa8..7a6da19 100644 --- a/src/cab/out/pac/PacLed64.h +++ b/src/cab/out/pac/PacLed64.h @@ -1,6 +1,7 @@ @@ -3010,15 +3740,38 @@ index 640daa8..da670ef 100644 #include "../IOutputController.h" #include #include -@@ -85,6 +86,7 @@ private: +@@ -51,6 +52,8 @@ private: + bool m_minUpdateIntervalMsSet; + int m_minUpdateIntervalMs; + int m_fullUpdateThreshold; ++ // VPE: this controller was initialized and counts as a user of its unit until it is finished. ++ bool m_usesUnit = false; + + static std::map s_pacLed64Units; + static bool s_unitsInitialized; +@@ -74,6 +77,12 @@ private: + void TriggerPacLed64UpdaterThread(); + bool IsPresent() const; + void ShutdownLighting(); ++ // VPE: the controllers configured for this unit (entries with the same Id share it) that were initialized and not ++ // finished yet. The unit is finished with the last of them, so it keeps sending and confirming the gate's state ++ // until then, and its gate unit is stopped and released once. ++ void AddUser() { m_users++; } ++ void RemoveUser() { m_users--; } ++ bool InUse() const { return m_users > 0; } + + bool GetUpdateRequired() const { return m_updateRequired; } + +@@ -85,6 +94,8 @@ private: std::chrono::milliseconds m_minUpdateInterval; std::chrono::steady_clock::time_point m_lastCommand; int m_index; -+ OutputGate::Unit* m_gateUnit = nullptr; ++ OutputGate::UnitHandle m_gateUnit; ++ int m_users = 0; std::vector m_newValue; std::vector m_currentValue; -@@ -105,7 +107,10 @@ private: +@@ -105,7 +116,10 @@ private: void StartPacLed64UpdaterThread(); void TerminatePacLed64UpdaterThread(); void PacLed64UpdaterDoIt(); @@ -3031,7 +3784,7 @@ index 640daa8..da670ef 100644 void ResetFadeTime(); void EnforceMinUpdateInterval(); diff --git a/src/cab/out/pac/PacUIO.cpp b/src/cab/out/pac/PacUIO.cpp -index e35bbf8..c6616c0 100644 +index e35bbf8..d2635df 100644 --- a/src/cab/out/pac/PacUIO.cpp +++ b/src/cab/out/pac/PacUIO.cpp @@ -1,5 +1,6 @@ @@ -3051,7 +3804,77 @@ index e35bbf8..c6616c0 100644 std::map PacUIO::s_pacUIOUnits; bool PacUIO::s_unitsInitialized = false; -@@ -162,13 +166,23 @@ void PacUIO::PacUIOUnit::Init(Cabinet* cabinet) +@@ -56,14 +60,34 @@ void PacUIO::Init(Cabinet* cabinet) + { + AddOutputs(); + InitializeUnits(); +- s_pacUIOUnits.at(m_id)->Init(cabinet); ++ PacUIOUnit* unit = s_pacUIOUnits.at(m_id); ++ // VPE: the physical unit is initialized once, by its first user: it registers with the gate once, as present or ++ // as missing, however many entries share it. ++ if (!unit->InUse()) ++ unit->Init(cabinet); ++ if (!m_usesUnit) ++ { ++ m_usesUnit = true; ++ unit->AddUser(); ++ } + Log::Write(StringExtensions::Build("PacUIO Id:{0} initialized and updater thread started.", std::to_string(m_id))); + } + + void PacUIO::Finish() + { + InitializeUnits(); +- s_pacUIOUnits.at(m_id)->Finish(); ++ PacUIOUnit* unit = s_pacUIOUnits.at(m_id); ++ if (m_usesUnit) ++ { ++ m_usesUnit = false; ++ unit->RemoveUser(); ++ } ++ if (unit->InUse()) ++ { ++ Log::Write(StringExtensions::Build("PacUIO Id:{0} finished; another entry with the Id still uses the unit, which finishes with it.", std::to_string(m_id))); ++ return; ++ } ++ unit->Finish(); + Log::Write(StringExtensions::Build("PacUIO Id:{0} finished and updater thread stopped.", std::to_string(m_id))); + } + +@@ -112,7 +136,13 @@ PacUIO::PacUIO() { } + + PacUIO::PacUIO(int id) { SetId(id); } + +-PacUIO::~PacUIO() { } ++PacUIO::~PacUIO() ++{ ++ // VPE: one that was never finished (its cabinet failed) does not keep the unit in use for the next session. ++ auto unit = s_pacUIOUnits.find(m_id); ++ if (m_usesUnit && unit != s_pacUIOUnits.end()) ++ unit->second->RemoveUser(); ++} + + tinyxml2::XMLElement* PacUIO::ToXml(tinyxml2::XMLDocument& doc) const + { +@@ -135,9 +165,14 @@ bool PacUIO::FromXml(const tinyxml2::XMLElement* element) + if (name) + SetName(name); + +- int id = element->IntAttribute("Id", -1); +- if (id != -1) +- SetId(id); ++ // VPE: the Id selects the unit; without one (or with one that is not a number) the controller would drive no unit ++ // and fail its Init, which fails the whole cabinet, so it is not read. The whole text is the number: one that only ++ // starts with a number ("0.5", "1old") selects no unit. ++ const char* idText = element->Attribute("Id"); ++ int id = -1; ++ if (!idText || !StringExtensions::TryParseInt(idText, id)) ++ return false; ++ SetId(id); + + return true; + } +@@ -162,13 +197,23 @@ void PacUIO::PacUIOUnit::Init(Cabinet* cabinet) { m_pdSingleton = &PacDriveSingleton::GetInstance(); m_index = m_pdSingleton->PacUIOGetIndexForDeviceId(m_id); @@ -3082,7 +3905,7 @@ index e35bbf8..c6616c0 100644 } StartPacUIOUpdaterThread(); } -@@ -176,7 +190,26 @@ void PacUIO::PacUIOUnit::Init(Cabinet* cabinet) +@@ -176,7 +221,29 @@ void PacUIO::PacUIOUnit::Init(Cabinet* cabinet) void PacUIO::PacUIOUnit::Finish() { TerminatePacUIOUpdaterThread(); @@ -3103,22 +3926,25 @@ index e35bbf8..c6616c0 100644 + { + if (present) + m_gateUnit->Stop(); ++ m_gateUnit.reset(); + throw; + } + if (present) + m_gateUnit->Stop(); ++ // VPE: the unit outlives the session; it does not keep the session's gate until the next session registers. ++ m_gateUnit.reset(); } void PacUIO::PacUIOUnit::UpdateValue(IOutput* output) -@@ -237,6 +270,7 @@ void PacUIO::PacUIOUnit::TriggerPacUIOUpdaterThread() +@@ -237,6 +304,7 @@ void PacUIO::PacUIOUnit::TriggerPacUIOUpdaterThread() void PacUIO::PacUIOUnit::PacUIOUpdaterDoIt() { -+ OutputGate::Unit* gateUnit = m_gateUnit; ++ OutputGate::UnitHandle gateUnit = m_gateUnit; try { ResetFadeTime(); -@@ -244,6 +278,7 @@ void PacUIO::PacUIOUnit::PacUIOUpdaterDoIt() +@@ -244,6 +312,7 @@ void PacUIO::PacUIOUnit::PacUIOUpdaterDoIt() catch (const std::exception& e) { Log::Exception(StringExtensions::Build("A exception occurred while setting the fadetime for PacUIO {0} to 0.", std::to_string(m_index))); @@ -3126,7 +3952,7 @@ index e35bbf8..c6616c0 100644 m_updaterThreadFinished = true; return; } -@@ -251,16 +286,27 @@ void PacUIO::PacUIOUnit::PacUIOUpdaterDoIt() +@@ -251,16 +320,27 @@ void PacUIO::PacUIOUnit::PacUIOUpdaterDoIt() int failCnt = 0; while (m_keepPacUIOUpdaterAlive.load()) { @@ -3155,7 +3981,7 @@ index e35bbf8..c6616c0 100644 Log::Exception(StringExtensions::Build("A error occurred when updating PacUIO {0}", std::to_string(m_id))); failCnt++; -@@ -279,68 +325,129 @@ void PacUIO::PacUIOUnit::PacUIOUpdaterDoIt() +@@ -279,68 +359,129 @@ void PacUIO::PacUIOUnit::PacUIOUpdaterDoIt() } m_triggerUpdate.store(false); } @@ -3190,14 +4016,14 @@ index e35bbf8..c6616c0 100644 -void PacUIO::PacUIOUnit::SendPacUIOUpdate() +void PacUIO::PacUIOUnit::RequestFullUpdate() -+{ + { + std::lock_guard valueLock(m_valueChangeLocker); + m_forceFullUpdate = true; + m_updateRequired = true; +} + +bool PacUIO::PacUIOUnit::SendPacUIOUpdate(OutputGate::Snapshot& gate, bool& failed, bool& cancelled) - { ++{ + failed = false; + cancelled = false; if (!IsPresent()) @@ -3306,7 +4132,7 @@ index e35bbf8..c6616c0 100644 void PacUIO::PacUIOUnit::ShutdownLighting() diff --git a/src/cab/out/pac/PacUIO.h b/src/cab/out/pac/PacUIO.h -index 0da2310..1be7c1a 100644 +index 0da2310..2d7cb23 100644 --- a/src/cab/out/pac/PacUIO.h +++ b/src/cab/out/pac/PacUIO.h @@ -1,6 +1,7 @@ @@ -3317,15 +4143,38 @@ index 0da2310..1be7c1a 100644 #include #include #include -@@ -45,6 +46,7 @@ private: +@@ -16,6 +17,8 @@ class PacUIO : public OutputControllerBase + private: + std::mutex m_idUpdateLocker; + int m_id = -1; ++ // VPE: this controller was initialized and counts as a user of its unit until it is finished. ++ bool m_usesUnit = false; + + public: + int GetId() const { return m_id; } +@@ -45,6 +48,8 @@ private: static const int MAX_UPDATE_FAIL_COUNT = 5; int m_id; int m_index = -1; -+ OutputGate::Unit* m_gateUnit = nullptr; ++ OutputGate::UnitHandle m_gateUnit; ++ int m_users = 0; class PacDriveSingleton* m_pdSingleton = nullptr; uint8_t m_newValue[96]; -@@ -82,7 +84,10 @@ private: +@@ -74,6 +79,12 @@ private: + void UpdateValue(class IOutput* output); + void TriggerPacUIOUpdaterThread(); + void ShutdownLighting(); ++ // VPE: the controllers configured for this unit (entries with the same Id share it) that were initialized and not ++ // finished yet. The unit is finished with the last of them, so it keeps sending and confirming the gate's state ++ // until then, and its gate unit is stopped and released once. ++ void AddUser() { m_users++; } ++ void RemoveUser() { m_users--; } ++ bool InUse() const { return m_users > 0; } + + bool IsUpdaterThreadAlive(); + void StartPacUIOUpdaterThread(); +@@ -82,7 +93,10 @@ private: private: void CopyNewToCurrent(); void PacUIOUpdaterDoIt(); @@ -3338,7 +4187,7 @@ index 0da2310..1be7c1a 100644 void InitUnit(); diff --git a/src/cab/out/pinone/PinOne.cpp b/src/cab/out/pinone/PinOne.cpp -index 4fedb04..c329712 100644 +index 4fedb04..de74817 100644 --- a/src/cab/out/pinone/PinOne.cpp +++ b/src/cab/out/pinone/PinOne.cpp @@ -241,18 +241,13 @@ void PinOne::ConnectToController() @@ -3364,6 +4213,18 @@ index 4fedb04..c329712 100644 } } catch (const std::exception& e) +@@ -296,7 +291,10 @@ bool PinOne::FromXml(const tinyxml2::XMLElement* element) + { + try + { +- int number = std::stoi(numberElement->GetText()); ++ // VPE: the whole text is the number; one that only starts with a number ("1old", "2.5") selects no board. ++ int number = 0; ++ if (!StringExtensions::TryParseInt(numberElement->GetText(), number)) ++ return false; + SetNumber(number); + } + catch (...) diff --git a/src/cab/out/pinone/PinOneAutoConfigurator.cpp b/src/cab/out/pinone/PinOneAutoConfigurator.cpp index 912cb2e..1ced542 100644 --- a/src/cab/out/pinone/PinOneAutoConfigurator.cpp @@ -3825,7 +4686,7 @@ index c26b815..b4d7c33 100644 if (actual < 0) { diff --git a/src/cab/out/ps/Pinscape.cpp b/src/cab/out/ps/Pinscape.cpp -index f257bbe..3a0edd5 100644 +index f257bbe..ef90abb 100644 --- a/src/cab/out/ps/Pinscape.cpp +++ b/src/cab/out/ps/Pinscape.cpp @@ -155,6 +155,11 @@ void Pinscape::UpdateOutputs(const std::vector& newOutputValues) @@ -3840,8 +4701,20 @@ index f257bbe..3a0edd5 100644 uint8_t buf[9] = { 0 }; buf[0] = 0; +@@ -274,7 +279,10 @@ bool Pinscape::FromXml(const tinyxml2::XMLElement* element) + { + try + { +- int number = std::stoi(numberElement->GetText()); ++ // VPE: the whole text is the number; one that only starts with a number ("1old", "2.5") selects no board. ++ int number = 0; ++ if (!StringExtensions::TryParseInt(numberElement->GetText(), number)) ++ return false; + SetNumber(number); + } + catch (...) diff --git a/src/cab/out/pspico/PinscapePico.cpp b/src/cab/out/pspico/PinscapePico.cpp -index 8beea61..9630287 100644 +index 8beea61..7ca843f 100644 --- a/src/cab/out/pspico/PinscapePico.cpp +++ b/src/cab/out/pspico/PinscapePico.cpp @@ -1,4 +1,5 @@ @@ -3927,7 +4800,19 @@ index 8beea61..9630287 100644 m_cacheInvalid = false; if (firstChangedIndex >= 0) -@@ -647,11 +658,17 @@ uint8_t* PinscapePico::Device::ReadUSB(uint32_t timeoutMs) +@@ -482,7 +493,10 @@ bool PinscapePico::FromXml(const tinyxml2::XMLElement* element) + { + try + { +- int number = std::stoi(numberElement->GetText()); ++ // VPE: the whole text is the number; one that only starts with a number ("1old", "2.5") selects no board. ++ int number = 0; ++ if (!StringExtensions::TryParseInt(numberElement->GetText(), number)) ++ return false; + SetNumber(number); + } + catch (...) +@@ -647,11 +661,17 @@ uint8_t* PinscapePico::Device::ReadUSB(uint32_t timeoutMs) return nullptr; } @@ -3947,7 +4832,7 @@ index 8beea61..9630287 100644 std::string hexString; for (size_t i = 0; i < m_outputReportLength; ++i) { -@@ -666,6 +683,9 @@ bool PinscapePico::Device::WriteUSB(const std::string& desc, uint8_t* buf, uint3 +@@ -666,6 +686,9 @@ bool PinscapePico::Device::WriteUSB(const std::string& desc, uint8_t* buf, uint3 uint32_t actual = 0; for (int tries = 0; tries < 3; ++tries) { @@ -4119,16 +5004,20 @@ index b6baeda..6b7ca12 100644 diff --git a/src/general/PathConfinement.cpp b/src/general/PathConfinement.cpp new file mode 100644 -index 0000000..d713659 +index 0000000..cf5c187 --- /dev/null +++ b/src/general/PathConfinement.cpp -@@ -0,0 +1,189 @@ +@@ -0,0 +1,339 @@ +#include "PathConfinement.h" + +#include +#include ++#include +#ifdef _WIN32 ++#include ++#include +#include ++#include +#endif + +#include "../Log.h" @@ -4148,9 +5037,15 @@ index 0000000..d713659 + // The root resolved; until it does, nothing is allowed. + bool valid = false; + fs::path path; -+ // The root as written, made absolute and normalized without the file system: a path written through it (and not -+ // through the resolved form) passes the lexical check too. -+ fs::path lexical; ++#ifdef _WIN32 ++ // The volumes of the root as given and as resolved (VolumeOf). Only a path on one of them is looked up. ++ std::vector volumes; ++#else ++ // The root as given (made absolute and normalized without the file system, so through the link the root was given ++ // through) and as resolved. Only a path written through one of them is looked up: a POSIX path does not tell whether ++ // it is on a network mount. ++ std::vector spellings; ++#endif + // As given, so that a root that did not resolve (a folder not created yet) is looked up again on the next access. + std::string given; +}; @@ -4171,6 +5066,126 @@ index 0000000..d713659 + return absolute.lexically_normal(); +} + ++#ifdef _WIN32 ++bool SameName(const std::wstring& a, const std::wstring& b) { return _wcsicmp(a.c_str(), b.c_str()) == 0; } ++ ++// The volume a drive letter ("C:") names, from the object manager alone: QueryDosDevice does not touch the volume, so ++// a mapped network drive that is gone does not block. A subst drive is followed to the drive it points into. Empty when ++// it is not a drive letter or names nothing. ++std::wstring Volume(const std::wstring& rootName) ++{ ++ std::wstring drive = rootName; ++ for (int depth = 0; depth < 8; depth++) ++ { ++ if (drive.size() != 2 || drive[1] != L':' || !iswalpha(drive[0])) ++ return std::wstring(); ++ wchar_t target[1024]; ++ if (QueryDosDeviceW(drive.c_str(), target, static_cast(std::size(target))) == 0) ++ return std::wstring(); ++ std::wstring device(target); ++ // A subst drive: \??\C:\folder. ++ if (device.size() >= 6 && device.compare(0, 4, L"\\??\\") == 0 && device[5] == L':') ++ { ++ drive = device.substr(4, 2); ++ continue; ++ } ++ return device; ++ } ++ return std::wstring(); ++} ++ ++bool StartsWith(const std::wstring& text, const wchar_t* prefix, bool ignoreCase = false) ++{ ++ size_t length = wcslen(prefix); ++ if (text.size() < length) ++ return false; ++ return ignoreCase ? _wcsnicmp(text.c_str(), prefix, length) == 0 : text.compare(0, length, prefix) == 0; ++} ++ ++// "server\share" of a UNC path after its leading backslashes, both required. ++std::wstring Share(const std::wstring& text) ++{ ++ size_t server = text.find(L'\\'); ++ if (server == 0 || server == std::wstring::npos) ++ return std::wstring(); ++ size_t share = text.find(L'\\', server + 1); ++ std::wstring name = text.substr(0, share); ++ if (name.size() == server + 1) ++ return std::wstring(); ++ return L"share:" + name; ++} ++ ++std::wstring Drive(const std::wstring& text) ++{ ++ if (text.size() < 2 || text[1] != L':' || !iswalpha(text[0]) || (text.size() > 2 && text[2] != L'\\')) ++ return std::wstring(); ++ std::wstring drive = text.substr(0, 2); ++ std::wstring volume = Volume(drive); ++ return volume.empty() ? L"drive:" + drive : L"volume:" + volume; ++} ++ ++// The volume an absolute path is on, from the path alone, so that nothing is looked up on a volume the root is not on: ++// the volume a drive letter names (a subst drive followed), or a share (server and share) for a UNC path. Paths in the ++// device namespaces are classified explicitly: "\\?\C:\" is drive C and "\\?\UNC\server\share\" that share; every other ++// one ("\\.\", "\??\", "\\?\Volume{...}\", "\\?\GLOBALROOT\") has none. Empty when the path has none, which refuses it. ++std::wstring Backslashed(const fs::path& path) ++{ ++ std::wstring text = path.native(); ++ for (wchar_t& c : text) ++ { ++ if (c == L'/') ++ c = L'\\'; ++ } ++ return text; ++} ++ ++std::wstring VolumeOf(const fs::path& path) ++{ ++ std::wstring text = Backslashed(path); ++ if (StartsWith(text, L"\\\\?\\")) ++ { ++ std::wstring rest = text.substr(4); ++ if (StartsWith(rest, L"UNC\\", true)) ++ return Share(rest.substr(4)); ++ return Drive(rest); ++ } ++ if (StartsWith(text, L"\\\\.\\") || StartsWith(text, L"\\??\\")) ++ return std::wstring(); ++ if (StartsWith(text, L"\\\\")) ++ return Share(text.substr(2)); ++ return Drive(text); ++} ++ ++void AddVolume(Root& r, const fs::path& path) ++{ ++ std::wstring volume = VolumeOf(path); ++ if (volume.empty()) ++ return; ++ for (const std::wstring& known : r.volumes) ++ { ++ if (SameName(known, volume)) ++ return; ++ } ++ r.volumes.push_back(volume); ++} ++ ++// Whether a path is on the volume of the root (as given or as resolved), decided without touching the file system. ++// Refuses other shares, also on the root's server, other volumes, and the device namespaces that name no volume, so ++// only a path that can be inside the root is looked up. ++bool OnRootVolume(const fs::path& lexical, const Root& root) ++{ ++ std::wstring volume = VolumeOf(lexical); ++ if (volume.empty()) ++ return false; ++ for (const std::wstring& known : root.volumes) ++ { ++ if (SameName(known, volume)) ++ return true; ++ } ++ return false; ++} ++#endif ++ +Root MakeRoot(const std::string& root) +{ + Root r; @@ -4184,7 +5199,17 @@ index 0000000..d713659 + { + r.valid = true; + r.path = canonical; -+ r.lexical = Lexical(root); ++ fs::path given = Lexical(root); ++#ifdef _WIN32 ++ AddVolume(r, given); ++ AddVolume(r, canonical); ++#else ++ for (const fs::path& spelling : { given, canonical }) ++ { ++ if (!spelling.empty() && spelling.is_absolute()) ++ r.spellings.push_back(spelling); ++ } ++#endif + } + return r; +} @@ -4204,25 +5229,15 @@ index 0000000..d713659 +} + +// Compares whole components, so neither a sibling with the same prefix ("config-other") nor a component that contains -+// a backslash on POSIX passes. Resolved paths compare exactly, since canonical paths have the case of the file system; -+// paths as written compare without case on Windows, whose file systems ignore it. -+bool IsWithin(const fs::path& path, const fs::path& root, bool ignoreCase) ++// a backslash on POSIX passes. Exactly: resolved paths have the spelling and case of the file system. ++bool IsWithin(const fs::path& path, const fs::path& root) +{ -+ auto same = [ignoreCase](const fs::path& a, const fs::path& b) { -+#ifdef _WIN32 -+ if (ignoreCase) -+ return _wcsicmp(a.native().c_str(), b.native().c_str()) == 0; -+#else -+ (void)ignoreCase; -+#endif -+ return a == b; -+ }; + auto p = path.begin(); + for (auto r = root.begin(); r != root.end(); ++r) + { + if (r->empty()) + continue; -+ if (p == path.end() || !same(*p, *r)) ++ if (p == path.end() || *p != *r) + return false; + ++p; + } @@ -4234,18 +5249,38 @@ index 0000000..d713659 + return true; +} + -+// The decision for a path: first on the path as written, made absolute and normalized without the file system, so a -+// path outside the root (a network share, a device) is refused before anything looks it up. Only a path inside is -+// resolved, which follows its symbolic links, and must still be inside. The resolved path stays a path: converting it -+// to a narrow string can fail on Windows (a long name behind a short 8.3 path). ++// The decision for a path. First on the path as written, made absolute and normalized without the file system: a path ++// that must not be looked up is refused (see PathConfinement::IsReadAllowed). Then by identity: the path ++// is resolved and must be inside the resolved root. Two paths name the same folder when they resolve to the same path, ++// whatever their spelling (8.3 or long names per component, case, junctions, links, subst drives), so no spelling is ++// compared. What is resolved is the path the caller opens, not its normalized form: on POSIX a ".." after a symbolic ++// link leaves the link's target ("link/../x" is next to the target, not next to the link), so the normalized path can ++// be inside while the file opened is not. Resolving the path as written follows its links in the order the system does ++// when it opens it. The resolved path stays a path: converting it to a narrow string can fail on Windows (a long name ++// behind a short 8.3 path). +bool IsInside(const std::string& path, const Root& root) +{ + fs::path lexical = Lexical(path); -+ if (lexical.empty() || !(IsWithin(lexical, root.lexical, true) || IsWithin(lexical, root.path, true))) ++ if (lexical.empty()) ++ return false; ++#ifdef _WIN32 ++ // "\??\" is the NT namespace, checked on the path as written: GetFullPathName takes it for a folder on the current ++ // drive, while the file is opened through it. ++ if (StartsWith(Backslashed(fs::path(path)), L"\\??\\") || !OnRootVolume(lexical, root)) ++ return false; ++#else ++ bool written = false; ++ for (const fs::path& spelling : root.spellings) ++ written = written || IsWithin(lexical, spelling); ++ if (!written) + return false; ++#endif + std::error_code ec; -+ fs::path resolved = fs::weakly_canonical(lexical, ec); -+ return !ec && !resolved.empty() && IsWithin(resolved, root.path, false); ++ fs::path absolute = fs::absolute(fs::path(path), ec); ++ if (ec || absolute.empty()) ++ return false; ++ fs::path resolved = fs::weakly_canonical(absolute, ec); ++ return !ec && !resolved.empty() && IsWithin(resolved, root.path); +} + +bool IsAllowed(const std::string& path) @@ -4314,10 +5349,10 @@ index 0000000..d713659 +} diff --git a/src/general/PathConfinement.h b/src/general/PathConfinement.h new file mode 100644 -index 0000000..7df1473 +index 0000000..d0402db --- /dev/null +++ b/src/general/PathConfinement.h -@@ -0,0 +1,40 @@ +@@ -0,0 +1,44 @@ +#pragma once + +#include @@ -4336,9 +5371,13 @@ index 0000000..7df1473 + // refused while a root is set. A root that does not resolve allows nothing, and is looked up again on every access. + static void SetRoot(const std::string& root); + static bool HasRoot(); -+ // Whether the path lies inside the root. It is decided on the path as written first, without touching the file -+ // system, so a path outside (a network share among them) is refused without being looked up; a path inside is then -+ // resolved (symbolic links, dot components) and must still be inside. Any error denies. Logs a refusal. ++ // Whether the path names a file or folder inside the root. Some paths are refused from the path as written, without ++ // being looked up, so a network share is never touched: on Windows one on another volume or share (server and share ++ // compared, "\\?\" and "\\?\UNC\" paths by the drive or share they name) or in a device namespace that names neither ++ // ("\\.\"), on POSIX, where a path does not tell whether it is on a network mount, one not written through the root ++ // as given or as resolved. Every other path is resolved (symbolic links, junctions, dot components, on Windows also ++ // 8.3 short names and case) and must be inside the resolved root: any spelling of the root's folder counts. Any error ++ // denies. Logs a refusal. + static bool IsReadAllowed(const std::string& path); + // The same check without the log line, for lookups (whether a file exists, its size, a folder's entries). + static bool IsLookupAllowed(const std::string& path); @@ -4397,7 +5436,7 @@ index 023ce64..c2f72fd 100644 if (!file) { diff --git a/src/globalconfiguration/GlobalConfig.cpp b/src/globalconfiguration/GlobalConfig.cpp -index 96ea59f..7f23bf5 100644 +index 96ea59f..0c5dcd3 100644 --- a/src/globalconfiguration/GlobalConfig.cpp +++ b/src/globalconfiguration/GlobalConfig.cpp @@ -6,6 +6,7 @@ @@ -4439,7 +5478,19 @@ index 96ea59f..7f23bf5 100644 return nullptr; } -@@ -359,7 +365,7 @@ GlobalConfig* GlobalConfig::GetGlobalConfigFromConfigXmlFile(const std::string& +@@ -314,7 +320,10 @@ std::unordered_map GlobalConfig::GetReplaceValuesDicti + { + FileInfo fi(tableFilename); + DirectoryInfo tableDir = fi.Directory(); +- if (tableDir.Exists()) ++ // VPE: a table folder outside the configuration folder is not looked up; its names come from the filename, and a ++ // file a pattern makes of them is checked when it is looked up or read. ++ bool confined = PathConfinement::HasRoot() && !PathConfinement::IsLookupAllowed(tableDir.FullName()); ++ if (confined ? !tableDir.Name().empty() : tableDir.Exists()) + { + d.emplace("TableDirectory", tableDir.FullName()); + d.emplace("TableDir", tableDir.FullName()); +@@ -359,7 +368,7 @@ GlobalConfig* GlobalConfig::GetGlobalConfigFromConfigXmlFile(const std::string& { try { @@ -4448,7 +5499,7 @@ index 96ea59f..7f23bf5 100644 { std::string xml = FileReader::ReadFileToString(globalConfigFileName); -@@ -388,6 +394,10 @@ void GlobalConfig::SaveGlobalConfig(const std::string& globalConfigFilename) +@@ -388,6 +397,10 @@ void GlobalConfig::SaveGlobalConfig(const std::string& globalConfigFilename) if (StringExtensions::IsNullOrWhiteSpace(gcFileName)) throw std::runtime_error("No filename for GlobalConfig file has been supplied. Looking up the filename from the property GlobalConfigFilename failed as well"); diff --git a/native/src/vpe_dof.cpp b/native/src/vpe_dof.cpp index 1543ae3..6d8edca 100644 --- a/native/src/vpe_dof.cpp +++ b/native/src/vpe_dof.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -64,8 +65,9 @@ enum class State struct vpe_dof { DOF::Pinball* pinball = nullptr; - // The gate of the session this instance began. It outlives the instance (OutputGate::BeginSession). - DOF::OutputGate* gate = nullptr; + // The gate of the session this instance began, held until the instance is freed. The controllers' unit handles keep + // it too, so an updater thread that still runs never reaches a freed gate. + std::shared_ptr gate; std::string basePath; std::atomic state { State::Created }; std::mutex lifecycle; @@ -324,9 +326,10 @@ VPE_DOF_API vpe_dof* VPE_DOF_CALL vpe_dof_create(const char* base_path, int32_t* DOF::Config::GetInstance()->SetBasePath(base_path); DOF::PathConfinement::SetRoot(base_path); // A configuration that cannot be used fails init instead of falling back to defaults or auto-configuring - // whatever hardware is connected. + // whatever hardware is connected. An output controller that cannot be read is skipped (the patch), as the + // importer, which does not have libdof read cabinets, cannot tell. DOF::Config::GetInstance()->SetStrictSetup(true); - dof->gate = &DOF::OutputGate::BeginSession(); + dof->gate = DOF::OutputGate::BeginSession().shared_from_this(); { std::lock_guard hid(VpeDofHidLock()); DOF::IOConfigurator::Initialize(); @@ -512,8 +515,13 @@ VPE_DOF_API int64_t VPE_DOF_CALL vpe_dof_set_output_gate(vpe_dof* dof, int32_t o return -1; try { - if (dof->state.load() == State::Running) + State state = dof->state.load(); + if (state == State::Running) return dof->pinball->SetOutputGate(open != 0); + // Once finish started, DOF's main thread takes no change: a closing latches the gate, which the controllers send + // without it and the final blackout confirms, and an opening is refused. + if (state == State::Finishing) + return open ? -1 : dof->gate->Latch(); // Never waits for a running init or finish. std::unique_lock lock(dof->lifecycle, std::try_to_lock); if (!lock.owns_lock() || dof->state.load() != State::Created) diff --git a/native/tests/internal.cpp b/native/tests/internal.cpp index c575c3e..6eed755 100644 --- a/native/tests/internal.cpp +++ b/native/tests/internal.cpp @@ -11,14 +11,19 @@ #include #include +#include #include #include +#include #include #include +#include #include +#include #include #include #include +#include #include #include "Pinball.h" @@ -30,17 +35,26 @@ #include "cab/schedules/ScheduledSettings.h" #include "cab/toys/IMatrixToy.h" #include "cab/toys/ToyList.h" +#include "DOF/Config.h" #include "fx/EffectBase.h" #include "fx/EffectList.h" #include "fx/matrixfx/RGBAMatrixShiftEffect.h" #include "fx/timmedfx/DelayEffect.h" #include "general/FileInfo.h" +#include "general/FilePattern.h" +#include "general/FileReader.h" #include "general/PathConfinement.h" +#include "globalconfiguration/GlobalConfig.h" #include "general/color/RGBAColor.h" #include "pinballsupport/InputQueue.h" #include "table/Table.h" #include "table/TableElementData.h" +#include +#ifdef _WIN32 +#include +#endif + using namespace DOF; namespace DOF @@ -78,15 +92,16 @@ class PinballTestAccess pinball.m_commands.push_back({ pinball.m_inputQueue->Count(), [] { } }); } - // 'C' for a command, 'I' for input, '-' for nothing. - static std::string Take(Pinball& pinball, int count) + // 'C' for a command, 'I' for input, '-' for nothing. `drain`: as the main thread takes its work once asked to stop + // (DrainCommands), only what the queued commands wait for. + static std::string Take(Pinball& pinball, int count, bool drain = false) { std::string order; for (int i = 0; i < count; i++) { std::function command; TableElementData data; - Pinball::Work work = pinball.TakeWork(false, command, data); + Pinball::Work work = pinball.TakeWork(drain, command, data); order += work == Pinball::Work::Command ? 'C' : work == Pinball::Work::Input ? 'I' : '-'; } return order; @@ -243,11 +258,20 @@ class ScriptedController : public OutputControllerCompleteBase } std::function&)> beforeReport; + std::function onDisconnect; std::atomic failNextWrite { false }; std::atomic failReconnect { false }; std::atomic blackoutWorks { true }; std::atomic connects { 0 }; std::atomic blackouts { 0 }; + // The connect sends a connect test as the Wemos D1 controller does: decided by TakeConnectTest, and checked again + // at the write. failAfterTest makes the connect fail once the device took it (the controller did not answer); + // beforeTest runs between the decision and the write (the log line). handshakeFailsOnce makes the first connect + // return before the test, as a failed Teensy handshake does, keeping testOnConnect for a reconnect. + std::atomic testOnConnect { false }; + std::atomic failAfterTest { false }; + std::atomic handshakeFailsOnce { false }; + std::function beforeTest; protected: int GetNumberOfConfiguredOutputs() override { return 2; } @@ -255,12 +279,33 @@ class ScriptedController : public OutputControllerCompleteBase void ConnectToController() override { - if (connects++ > 0 && failReconnect) + int attempt = connects++; + if (attempt > 0 && failReconnect) throw std::runtime_error("the device is gone"); + if (attempt == 0 && handshakeFailsOnce) + return; + bool test = testOnConnect && TakeConnectTest(); + testOnConnect = false; + if (!test) + return; + if (beforeTest) + beforeTest(); + OutputGate::Snapshot gate = ObserveGate(); + if (!gate.open) + return; + OutputGate::Transfer transfer(GateUnit(), gate); + if (TransferCancelled()) + return; + Note("test"); + ConnectTestSent(gate); + if (failAfterTest) + throw std::runtime_error("the device does not answer"); } void DisconnectFromController() override { + if (onDisconnect) + onDisconnect(); if (m_inUseState != InUseState::Running) return; blackouts++; @@ -290,8 +335,8 @@ class ScriptedController : public OutputControllerCompleteBase void UntouchedUnitsAreCountedApart() { OutputGate& gate = OutputGate::BeginSession(); - OutputGate::Unit* used = gate.Register("used"); - OutputGate::Unit* unused = gate.Register("unused"); + OutputGate::UnitHandle used = gate.Register("used"); + OutputGate::UnitHandle unused = gate.Register("unused"); int64_t open = gate.Request(true); CHECK(gate.Apply(true), "the gate opens"); @@ -317,7 +362,7 @@ void UntouchedUnitsAreCountedApart() void LatchOvertakesAQueuedOpening() { OutputGate& gate = OutputGate::BeginSession(); - OutputGate::Unit* unit = gate.Register("unit"); + OutputGate::UnitHandle unit = gate.Register("unit"); Change(gate, false); unit->Ack(gate.Current()); @@ -353,7 +398,7 @@ void LatchOvertakesAQueuedOpening() void OpeningReservedBeforeALatchIsSuperseded() { OutputGate& gate = OutputGate::BeginSession(); - OutputGate::Unit* unit = gate.Register("unit"); + OutputGate::UnitHandle unit = gate.Register("unit"); Change(gate, false); unit->Ack(gate.Current()); @@ -376,7 +421,7 @@ void OpeningReservedBeforeALatchIsSuperseded() void OpeningPublishedDuringALatchIsSuperseded() { OutputGate& gate = OutputGate::BeginSession(); - OutputGate::Unit* unit = gate.Register("unit"); + OutputGate::UnitHandle unit = gate.Register("unit"); int64_t open = gate.Request(true); int64_t latched = OutputGateTestAccess::BeginLatch(gate); CHECK(!gate.Apply(true), "the opening applies as a closing"); @@ -397,7 +442,7 @@ void OpeningPublishedDuringALatchIsSuperseded() void ResultsAreDecidedWhenPublished() { OutputGate& gate = OutputGate::BeginSession(); - OutputGate::Unit* unit = gate.Register("unit"); + OutputGate::UnitHandle unit = gate.Register("unit"); int64_t open = Change(gate, true); unit->Ack(gate.Current()); OutputGate::Counts counts; @@ -416,7 +461,7 @@ void ResultsAreDecidedWhenPublished() void EarliestLatchDecides() { OutputGate& gate = OutputGate::BeginSession(); - OutputGate::Unit* unit = gate.Register("unit"); + OutputGate::UnitHandle unit = gate.Register("unit"); int64_t first = OutputGateTestAccess::BeginLatch(gate); int64_t second = OutputGateTestAccess::BeginLatch(gate); CHECK(second > first, "latches take their generations in order"); @@ -434,7 +479,7 @@ void EarliestLatchDecides() void OpeningBetweenTwoLatchesIsAClosing() { OutputGate& gate = OutputGate::BeginSession(); - OutputGate::Unit* unit = gate.Register("unit"); + OutputGate::UnitHandle unit = gate.Register("unit"); int64_t first = OutputGateTestAccess::BeginLatch(gate); int64_t open = gate.Request(true); CHECK(!gate.Apply(true), "the opening applies as a closing"); @@ -455,7 +500,7 @@ void OpeningBetweenTwoLatchesIsAClosing() void PausedLatchChangesNothingReported() { OutputGate& gate = OutputGate::BeginSession(); - OutputGate::Unit* unit = gate.Register("unit"); + OutputGate::UnitHandle unit = gate.Register("unit"); int64_t earlier = gate.Request(true); int64_t first = OutputGateTestAccess::BeginLatch(gate); int64_t open = gate.Request(true); @@ -486,9 +531,9 @@ void PausedLatchChangesNothingReported() void LatchesStayInTheirSession() { OutputGate& ended = OutputGate::BeginSession(); - OutputGate::Unit* old = ended.Register("old"); + OutputGate::UnitHandle old = ended.Register("old"); OutputGate& current = OutputGate::BeginSession(); - OutputGate::Unit* unit = current.Register("unit"); + OutputGate::UnitHandle unit = current.Register("unit"); CHECK(&OutputGate::Instance() == ¤t, "the new session is the current one"); CHECK(old->BelongsTo(ended) && !old->BelongsTo(current), "a unit keeps its session"); { @@ -508,7 +553,7 @@ void LatchesStayInTheirSession() void LatchCancelsTheTransferOfAnOpening() { OutputGate& gate = OutputGate::BeginSession(); - OutputGate::Unit* unit = gate.Register("unit"); + OutputGate::UnitHandle unit = gate.Register("unit"); CHECK(!OutputGate::TransferCancelled(), "nothing to cancel outside a transfer"); { OutputGate::Transfer transfer(unit, unit->Observe()); @@ -565,7 +610,7 @@ void LatchStopsAControllerAtTheNextWrite() void FinalBlackoutConfirmsTheClosing() { OutputGate& gate = OutputGate::BeginSession(); - OutputGate::Unit* unit = gate.Register("unit"); + OutputGate::UnitHandle unit = gate.Register("unit"); int64_t closed = Change(gate, false); OutputGate::Snapshot before = unit->Observe(); int64_t latched = gate.Latch(); @@ -577,7 +622,7 @@ void FinalBlackoutConfirmsTheClosing() CHECK(NamesAgree(gate, latched), "names agree with the counts"); OutputGate& next = OutputGate::BeginSession(); - OutputGate::Unit* other = next.Register("unit"); + OutputGate::UnitHandle other = next.Register("unit"); int64_t open = Change(next, true); other->AckOff(other->Observe()); other->Stop(); @@ -627,6 +672,160 @@ void LostDeviceStillGetsItsBlackout() } } +// A connect test lights the device before any value changed: the unit confirmed the opening it went out with, not as +// untouched, and the session ends with the blackout. It confirms that opening only: after a closing turned the device +// off, a later opening it wrote nothing for is untouched. +void ConnectTestCountsAsUse() +{ + OutputGate& gate = OutputGate::BeginSession(); + int64_t open = Change(gate, true); + ScriptedController controller; + controller.SetName("scripted"); + controller.testOnConnect = true; + controller.Init(nullptr); + OutputGate::Counts counts; + CHECK(WaitFor([&]() { return gate.GetState(open, counts) == OutputGate::Status::Applied && counts.confirmed == 1; }), "the opening counts the tested unit as used"); + CHECK(controller.HasWritten("test") && counts.untouched == 0, "not as untouched"); + int64_t closed = Change(gate, false); + CHECK(WaitFor([&]() { return gate.GetState(closed, counts) == OutputGate::Status::Applied && counts.confirmed == 1; }), "the closing is written"); + size_t written = controller.Written().size(); + int64_t reopened = Change(gate, true); + CHECK(WaitFor([&]() { return gate.GetState(reopened, counts) == OutputGate::Status::Applied && counts.pending == 0; }), "the opening after it is settled"); + CHECK(counts.untouched == 1 && counts.confirmed == 0, "the test does not confirm an opening after a closing"); + CHECK(controller.Written().size() == written, "nothing was written for it"); + controller.Finish(); + CHECK(controller.HasWritten("0=0") && controller.HasWritten("1=0"), "the session ends with the blackout"); +} + +// A connect that fails after the device took its connect test ends as a session does: with the blackout, and with an +// error unless the blackout got there. The unit fails either way. +void ConnectThatFailsAfterItsTestEndsDark() +{ + for (bool blackoutWorks : { true, false }) + { + OutputGate& gate = OutputGate::BeginSession(); + int64_t open = Change(gate, true); + ScriptedController controller; + controller.SetName("scripted"); + controller.testOnConnect = true; + controller.failAfterTest = true; + controller.failNextWrite = !blackoutWorks; + controller.Init(nullptr); + OutputGate::Counts counts; + CHECK(WaitFor([&]() { return gate.GetState(open, counts) == OutputGate::Status::Applied && counts.failed == 1; }), "the unit fails"); + std::string error; + try + { + controller.Finish(); + } + catch (const std::exception& e) + { + error = e.what(); + } + std::vector log = controller.Written(); + auto test = std::find(log.begin(), log.end(), "test"); + CHECK(test != log.end(), "the test was sent"); + if (blackoutWorks) + { + CHECK(std::find(test, log.end(), "0=0") != log.end() && std::find(test, log.end(), "1=0") != log.end(), "the blackout follows it"); + CHECK(error.empty(), "a blackout that got there finishes cleanly"); + } + else + CHECK(error.find("after its connect test") != std::string::npos, "one that did not fails the finish"); + } +} + +// A unit registered while the gate is closed turns its device off first, also when the gate opened before its first +// update: a session that starts closed starts dark on every unit, whatever an earlier one left lit. A connect test +// does not go out before that. +void SessionThatStartsClosedStartsDark() +{ + OutputGate& gate = OutputGate::BeginSession(); + int64_t closed = Change(gate, false); + ScriptedController controller; + controller.SetName("scripted"); + controller.testOnConnect = true; + controller.Init(nullptr); + int64_t open = Change(gate, true); + OutputGate::Counts counts; + // The opening supersedes the closing; the unit still has to confirm it. + CHECK(WaitFor([&]() { + gate.GetState(closed, counts); + return counts.confirmed == 1; + }), + "the closing the unit was registered under is written"); + CHECK(controller.HasWritten("0=0") && controller.HasWritten("1=0"), "to every output"); + CHECK(WaitFor([&]() { return gate.GetState(open, counts) == OutputGate::Status::Applied && counts.pending == 0; }) && counts.untouched == 1, "the opening after it leaves the unit alone"); + CHECK(!controller.HasWritten("test"), "no connect test went out before the closing was written"); + controller.Finish(); +} + +// A session that starts closed sends no connect test, also not on a reconnect once the gate opened: the test was used +// up when the unit registered under the closing, though the first connect never got to it. +void SessionThatStartsClosedTestsOnNoReconnect() +{ + OutputGate& gate = OutputGate::BeginSession(); + Change(gate, false); + ScriptedController controller; + controller.SetName("scripted"); + controller.testOnConnect = true; + controller.handshakeFailsOnce = true; + controller.failNextWrite = true; + controller.Init(nullptr); + Change(gate, true); + controller.Set(255, 0); + CHECK(WaitFor([&controller]() { return controller.connects.load() >= 2 && controller.HasWritten("0=255"); }), "the controller reconnects and writes"); + CHECK(!controller.HasWritten("test"), "without a connect test"); + controller.Finish(); +} + +// A connect test is checked again at its write: a latch between the decision and the write (one in the log line) +// keeps it from going out. +void LatchBeforeTheConnectTestSkipsIt() +{ + OutputGate& gate = OutputGate::BeginSession(); + Change(gate, true); + ScriptedController controller; + controller.SetName("scripted"); + controller.testOnConnect = true; + int64_t latched = -1; + controller.beforeTest = [&]() { latched = gate.Latch(); }; + controller.Init(nullptr); + OutputGate::Counts counts; + CHECK(WaitFor([&]() { return latched >= 0 && gate.GetState(latched, counts) == OutputGate::Status::Applied && counts.confirmed == 1; }), "the latch is written"); + CHECK(!controller.HasWritten("test"), "the test after it is not"); + controller.Finish(); +} + +// The final blackout confirms the closings published before and while it was sent, at the blackout: a closing published +// later, while the controller disconnects, was not carried by it and fails as one after the unit stopped does, unless +// the disconnect sends a blackout of its own after it. +void BlackoutConfirmsWhereItIsSent() +{ + for (bool disconnectBlackout : { false, true }) + { + OutputGate& gate = OutputGate::BeginSession(); + ScriptedController controller; + controller.SetName("scripted"); + controller.blackoutWorks = disconnectBlackout; + controller.Init(nullptr); + controller.Set(255, 0); + CHECK(WaitFor([&controller]() { return controller.HasWritten("0=255"); }), "the opening's value goes out"); + int64_t latched = -1; + controller.onDisconnect = [&]() { + if (latched < 0) + latched = gate.Latch(); + }; + controller.Finish(); + OutputGate::Counts counts; + CHECK(latched >= 0 && gate.GetState(latched, counts) == OutputGate::Status::Applied, "the latch came while the controller disconnected"); + if (disconnectBlackout) + CHECK(counts.confirmed == 1 && counts.failed == 0, "a blackout the disconnect sends after it confirms it"); + else + CHECK(counts.confirmed == 0 && counts.failed == 1, "the final blackout before it does not"); + } +} + // Once Finish started, the session takes no opening; a closing latches the gate. void FinishTakesNoOpening() { @@ -644,7 +843,7 @@ void FinishTakesNoOpening() void PermanentFailureOutranksAnAck() { OutputGate& gate = OutputGate::BeginSession(); - OutputGate::Unit* unit = gate.Register("unit"); + OutputGate::UnitHandle unit = gate.Register("unit"); int64_t closed = Change(gate, false); unit->Ack(gate.Current()); OutputGate::Counts counts; @@ -660,9 +859,9 @@ void PermanentFailureOutranksAnAck() void CleanFinishKeepsTheSettledResult() { OutputGate& gate = OutputGate::BeginSession(); - OutputGate::Unit* used = gate.Register("used"); - OutputGate::Unit* unused = gate.Register("unused"); - OutputGate::Unit* failing = gate.Register("failing"); + OutputGate::UnitHandle used = gate.Register("used"); + OutputGate::UnitHandle unused = gate.Register("unused"); + OutputGate::UnitHandle failing = gate.Register("failing"); int64_t open = Change(gate, true); OutputGate::Snapshot snapshot = gate.Current(); used->Ack(snapshot); @@ -689,12 +888,28 @@ void CleanFinishKeepsTheSettledResult() CHECK(NamesAgree(gate, closed), "names agree with the counts"); } +// A folder this run created, so the test writes and removes nothing it did not make. Empty if none could be created. +std::filesystem::path NewTempDirectory(const std::string& prefix) +{ + std::random_device random; + for (int attempt = 0; attempt < 100; attempt++) + { + std::filesystem::path path = std::filesystem::temp_directory_path() / (prefix + "-" + std::to_string(random()) + std::to_string(random())); + std::error_code ec; + if (std::filesystem::create_directory(path, ec) && !ec) + return path; + } + return std::filesystem::path(); +} + // Path confinement decides on the path as written first: a path outside the root, a network share among them, is // refused without being looked up, and the lookups (whether a file exists, its size) go through the check. void LookupsOutsideTheRootAreRefused() { - std::filesystem::path root = std::filesystem::temp_directory_path() / "vpe-dof-internal-confinement"; - std::filesystem::create_directories(root); + std::filesystem::path root = NewTempDirectory("vpe-dof-internal-confinement"); + CHECK(!root.empty(), "the test has a folder of its own"); + if (root.empty()) + return; std::string inside = (root / "inside.ini").string(); FILE* file = std::fopen(inside.c_str(), "wb"); if (file) @@ -730,6 +945,307 @@ void LookupsOutsideTheRootAreRefused() std::filesystem::remove_all(root, ec); } +// The check decides on the path the reader opens. On POSIX a ".." after a symbolic link leaves the link's target, so +// "link/../secret.ini" opens the file next to the target, outside the root, while its normalized form ("secret.ini" in +// the root) is inside. Windows removes ".." from a path before it follows any link, as the check does, and creating a +// link needs a privilege there, so this runs on POSIX only. +void PathThroughALinkIsCheckedAsItIsOpened() +{ +#ifndef _WIN32 + std::filesystem::path root = NewTempDirectory("vpe-dof-internal-root"); + std::filesystem::path outside = NewTempDirectory("vpe-dof-internal-outside"); + CHECK(!root.empty() && !outside.empty(), "the test has folders of its own"); + if (root.empty() || outside.empty()) + return; + std::error_code ec; + std::filesystem::create_directory(outside / "target", ec); + for (const std::filesystem::path& file : { outside / "secret.ini", root / "secret.ini" }) + { + FILE* handle = std::fopen(file.c_str(), "wb"); + if (handle) + { + std::fputs(file == root / "secret.ini" ? "inside" : "outside", handle); + std::fclose(handle); + } + } + std::filesystem::create_directory_symlink(outside / "target", root / "link", ec); + CHECK(!ec, "the link is created"); + const std::string through = (root / "link" / ".." / "secret.ini").string(); + PathConfinement::SetRoot(root.string()); + CHECK(!PathConfinement::IsLookupAllowed(through), "a path that leaves the root through a link is refused"); + CHECK(!FileInfo(through).Exists(), "and does not exist for libdof"); + std::string read; + try + { + read = FileReader::ReadFileToString(through); + } + catch (const std::exception&) + { + } + CHECK(read.empty(), "nor is it read"); + CHECK(FileReader::ReadFileToString((root / "secret.ini").string()) == "inside", "the file inside the root still is"); + PathConfinement::SetRoot(""); + std::filesystem::remove_all(root, ec); + std::filesystem::remove_all(outside, ec); +#endif +} + +// A path inside the root is read whatever its spelling: through the junction the root was given through or another +// one, in 8.3 or long names per component, in any case (non-ASCII too). A path on another share, in a device namespace +// or a UNC path is refused without being looked up, also when it names a file inside. Windows only, and the 8.3 checks +// only where the volume has short names. +void RootSpellingsAreOneFolder() +{ +#ifdef _WIN32 + std::filesystem::path base = NewTempDirectory("vpe-dof-internal-spellings"); + CHECK(!base.empty(), "the test has a folder of its own"); + if (base.empty()) + return; + std::filesystem::path store = base / std::filesystem::path(L"St\u00f6re Unic\u00f8de"); + std::error_code ec; + std::filesystem::create_directories(store / "rev" / "config", ec); + for (const std::filesystem::path& file : { store / "rev" / "config" / "Cabinet.xml", base / "outside.xml" }) + { + FILE* handle = _wfopen(file.c_str(), L"wb"); + if (handle) + std::fclose(handle); + } + bool junction = true; + for (const char* name : { "link", "other" }) + { + std::wstring command = L"cmd /c mklink /J \"" + (base / name).wstring() + L"\" \"" + store.wstring() + L"\" >nul"; + junction = junction && _wsystem(command.c_str()) == 0 && std::filesystem::exists(base / name / "rev"); + } + CHECK(junction, "the junctions are created"); + auto shortForm = [](const std::filesystem::path& path) { + wchar_t buffer[2048]; + DWORD length = GetShortPathNameW(path.c_str(), buffer, 2048); + return length && length < 2048 ? std::wstring(buffer, length) : std::wstring(); + }; + auto ascii = [](const std::wstring& text) { + std::string result; + for (wchar_t c : text) + { + if (c > 0x7F) + return std::string(); + result += static_cast(c); + } + return result; + }; + std::string shortRoot = ascii(shortForm(store / "rev")); + std::string shortCabinet = ascii(shortForm(store / "rev" / "config" / "Cabinet.xml")); + std::string shortOutside = ascii(shortForm(base / "outside.xml")); + std::string junctionRoot = ascii((base / "link" / "rev").wstring()); + std::string junctionCabinet = junctionRoot + "\\config\\Cabinet.xml"; + std::string otherCabinet = ascii((base / "other" / "rev" / "config" / "Cabinet.xml").wstring()); + // The folder in 8.3, the junction and what is inside it long: spellings mixed per component. + std::string shortBase = ascii(shortForm(base)); + auto upper = [](std::string text) { + for (char& c : text) + c = static_cast(std::toupper(static_cast(c))); + return text; + }; + if (junction && !junctionRoot.empty()) + { + PathConfinement::SetRoot(junctionRoot); + CHECK(FileInfo(junctionCabinet).Exists(), "a file through the junction the root was given through is found"); + CHECK(FileInfo(upper(junctionCabinet)).Exists(), "in any case"); + CHECK(!FileInfo(junctionRoot + "\\..\\..\\outside.xml").Exists(), "a path leading out of it is refused"); + if (!shortCabinet.empty()) + { + CHECK(FileInfo(shortCabinet).Exists(), "a file through the 8.3 spelling of the resolved root is found"); + CHECK(!FileInfo(shortRoot + "\\..\\..\\outside.xml").Exists(), "a path leading out of that spelling is refused"); + } + if (!shortOutside.empty()) + CHECK(!FileInfo(shortOutside).Exists(), "an 8.3 path outside the root is refused"); + CHECK(FileInfo(otherCabinet).Exists(), "a file through another junction to the root is found"); + CHECK(!FileInfo(ascii((base / "other" / "rev").wstring()) + "\\..\\..\\outside.xml").Exists(), "a path leading out of it is refused"); + if (!shortBase.empty() && shortBase != ascii(base.wstring())) + { + CHECK(FileInfo(shortBase + "\\link\\rev\\config\\Cabinet.xml").Exists(), "a file through an 8.3 folder above a long one is found"); + PathConfinement::SetRoot(shortBase + "\\link\\rev"); + CHECK(FileInfo(junctionCabinet).Exists(), "and with that root, the long spelling"); + PathConfinement::SetRoot(junctionRoot); + } + // The same file, written so that only the volume it is on decides: refused without being looked up. + std::string drive = junctionCabinet.substr(0, 1); + std::string rest = junctionCabinet.substr(2); + for (const std::string& written : { "\\\\.\\" + junctionCabinet, "\\??\\" + junctionCabinet,"\\\\localhost\\" + drive + "$" + rest, "\\\\?\\UNC\\localhost\\" + drive + "$" + rest }) + CHECK(!FileInfo(written).Exists(), ("a device or UNC path to a file inside is refused: " + written).c_str()); + // An extended-length path names its drive: it is checked as the drive's path is. + CHECK(FileInfo("\\\\?\\" + junctionCabinet).Exists(), "an extended-length path inside is found"); + CHECK(!FileInfo("\\\\?\\" + junctionRoot + "\\..\\..\\outside.xml").Exists(), "one leading out is refused"); + DWORD drives = GetLogicalDrives(); + for (char letter = 'A'; letter <= 'Z'; letter++) + { + if (letter == std::toupper(static_cast(drive[0])) || !(drives & (1u << (letter - 'A')))) + continue; + std::string other = std::string(1, letter) + ":" + rest; + CHECK(!FileInfo(other).Exists(), ("a path on another drive is refused: " + other).c_str()); + CHECK(!FileInfo("\\\\?\\" + other).Exists(), ("also extended-length: " + other).c_str()); + break; + } + } + // A folder with a non-ASCII name, given and read in another case. Paths are narrow strings in the active code page, + // so only where it has the name. + std::filesystem::path accented = base / std::filesystem::path(L"\u00e9t\u00e9"); + std::filesystem::create_directories(accented / "config", ec); + FILE* accentedFile = _wfopen((accented / "config" / "Cabinet.xml").c_str(), L"wb"); + if (accentedFile) + std::fclose(accentedFile); + auto narrow = [](const std::wstring& text) { + char buffer[2048]; + BOOL lossy = FALSE; + int length = WideCharToMultiByte(CP_ACP, 0, text.c_str(), static_cast(text.size()), buffer, sizeof(buffer), nullptr, GetACP() == CP_UTF8 ? nullptr : &lossy); + return length > 0 && !lossy ? std::string(buffer, length) : std::string(); + }; + std::string accentedRoot = narrow(accented.wstring()); + std::string accentedUpper = narrow((base / std::filesystem::path(L"\u00c9T\u00c9") / "config" / "Cabinet.xml").wstring()); + if (!accentedRoot.empty() && !accentedUpper.empty()) + { + PathConfinement::SetRoot(accentedRoot); + CHECK(FileInfo(accentedUpper).Exists(), "a non-ASCII root finds its files in another case"); + } + else + std::printf("RootSpellingsAreOneFolder: the code page has no accented names, their case not checked\n"); + if (!shortRoot.empty() && !shortCabinet.empty()) + { + PathConfinement::SetRoot(shortRoot); + CHECK(FileInfo(shortCabinet).Exists(), "a root given in 8.3 finds its files in 8.3"); + CHECK(FileInfo(upper(shortCabinet)).Exists(), "in any case"); + } + else + std::printf("RootSpellingsAreOneFolder: no 8.3 names on this volume, short spellings not checked\n"); + PathConfinement::SetRoot(""); + std::filesystem::remove(base / "link", ec); + std::filesystem::remove(base / "other", ec); + std::filesystem::remove_all(base, ec); +#endif +} + +// A table folder outside the configuration folder is not looked up, but its names still make the table config's path, +// which is checked as any other. +void TableFolderNamesComeFromTheFilename() +{ + std::filesystem::path root = NewTempDirectory("vpe-dof-internal-tableroot"); + std::filesystem::path tables = NewTempDirectory("vpe-dof-internal-tables"); + CHECK(!root.empty() && !tables.empty(), "the test has folders of its own"); + if (root.empty() || tables.empty()) + return; + std::string name = tables.filename().string(); + FILE* handle = std::fopen((root / (name + ".xml")).string().c_str(), "wb"); + if (handle) + std::fclose(handle); + handle = std::fopen((tables / "Table.xml").string().c_str(), "wb"); + if (handle) + std::fclose(handle); + std::string table = (tables / "Table.vpx").string(); + PathConfinement::SetRoot(root.string()); + GlobalConfig config; + std::unordered_map values = config.GetReplaceValuesDictionary(table); + CHECK(values.count("TableDirName") && values["TableDirName"] == name, "the table folder's name comes from the filename"); + config.GetTableConfigFilePatterns().push_back(FilePattern((root / "{TableDirName}.xml").string())); + FileInfo* inside = config.GetTableConfigFile(table); + CHECK(inside != nullptr, "a table config it names inside the root is found"); + delete inside; + config.GetTableConfigFilePatterns().clear(); + config.GetTableConfigFilePatterns().push_back(FilePattern((tables / "{TableName}.xml").string())); + FileInfo* outside = config.GetTableConfigFile(table); + CHECK(outside == nullptr, "one outside the root is not, though it exists"); + delete outside; + PathConfinement::SetRoot(""); + std::error_code ec; + std::filesystem::remove_all(root, ec); + std::filesystem::remove_all(tables, ec); +} + +// A controller libdof cannot read is skipped in strict setup too, as a toy is, and the others load: VPE activates +// cabinets without libdof reading them, so setup must not refuse one as a whole for it. +void UnreadableControllerIsSkipped() +{ + bool strict = Config::GetInstance()->IsStrictSetup(); + Config::GetInstance()->SetStrictSetup(true); + tinyxml2::XMLDocument doc; + // Unreadable XML (FromXml returns false), a setting a setter refuses (it throws), and a unit selector that is missing or + // not a number, which would fail Init and so the whole cabinet. + doc.Parse("unsetunset" + "" + "" + "no number" + "bad numberone" + "" + "fraction2.5" + "suffix1old" + "valid1"); + OutputControllerList controllers; + bool threw = false; + try + { + controllers.FromXml(doc.RootElement()); + } + catch (const std::exception&) + { + threw = true; + } + CHECK(!threw, "setup does not refuse the cabinet"); + CHECK(controllers.size() == 1 && controllers.front()->GetName() == "valid", "the readable controller loads"); + Config::GetInstance()->SetStrictSetup(strict); +} + +// A session's gate is freed, with its history and units, once nothing holds it: not when the next session begins while +// a unit handle (a controller, an updater thread that still runs) or an instance holds it, and as soon as the last one +// lets go. A host that runs many sessions keeps no gate nothing uses. +void EndedSessionsAreFreed() +{ + std::weak_ptr ended; + OutputGate::UnitHandle handle; + { + OutputGate& gate = OutputGate::BeginSession(); + ended = gate.shared_from_this(); + handle = gate.Register("updater"); + for (int i = 0; i < 100; i++) + gate.Publish(gate.Request(i % 2 == 0)); + } + std::weak_ptr current = OutputGate::BeginSession().shared_from_this(); + CHECK(!ended.expired(), "a gate stays while a unit handle holds it"); + handle->Ack(handle->Observe()); + CHECK(handle->Observe().generation > 0, "and its unit still works"); + handle.reset(); + CHECK(ended.expired(), "and is freed with the last handle"); + CHECK(!current.expired(), "the current session's gate stays"); + + std::shared_ptr instance = OutputGate::Instance().shared_from_this(); + OutputGate::BeginSession(); + CHECK(!current.expired(), "an instance keeps its gate after the next session began"); + instance.reset(); + CHECK(current.expired(), "and frees it"); + + // Many sessions keep only the current one. + std::vector> sessions; + for (int i = 0; i < 1000; i++) + { + OutputGate& gate = OutputGate::BeginSession(); + gate.Register("unit")->Stop(); + gate.Publish(gate.Request(false)); + sessions.push_back(gate.shared_from_this()); + } + CHECK(std::count_if(sessions.begin(), sessions.end(), [](const std::weak_ptr& gate) { return !gate.expired(); }) == 1, "only the current session's gate is kept"); +} + +// Finish drains what the main thread has left the same way: an opening that came with input still queued before it, as +// one posted right before finish, runs after that input, and input queued after the last command is left. The order is +// decided by the queue, not by how fast the main thread takes it, so this holds the input in place instead of racing it. +void FinishRunsTheInputQueuedBeforeAnOpening() +{ + Pinball pinball; + pinball.ReceiveData('S', 1, 0); + pinball.ReceiveData('S', 2, 0); + PinballTestAccess::Post(pinball); + pinball.ReceiveData('S', 1, 1); + PinballTestAccess::Stop(pinball); + CHECK(PinballTestAccess::Take(pinball, 4, true) == "IIC-", "the input before the opening first, the input after it left"); +} + // A command runs after the input queued before it and before the input queued after it: a closing followed by an on // sends no on, and an off followed by an opening does not send the on that came before. void CommandsAndInputKeepTheirOrder() @@ -860,12 +1376,24 @@ int main() FinalBlackoutConfirmsTheClosing(); LostDeviceStillGetsItsBlackout(); FinishTakesNoOpening(); + ConnectTestCountsAsUse(); + ConnectThatFailsAfterItsTestEndsDark(); + SessionThatStartsClosedStartsDark(); + SessionThatStartsClosedTestsOnNoReconnect(); + LatchBeforeTheConnectTestSkipsIt(); + BlackoutConfirmsWhereItIsSent(); PermanentFailureOutranksAnAck(); CleanFinishKeepsTheSettledResult(); ScheduleAppliesToTheOutputsItLists(); CommandsAndInputKeepTheirOrder(); + FinishRunsTheInputQueuedBeforeAnOpening(); GateChangeIsPublishedWhateverAnOutputThrows(); LookupsOutsideTheRootAreRefused(); + PathThroughALinkIsCheckedAsItIsOpened(); + RootSpellingsAreOneFolder(); + TableFolderNamesComeFromTheFilename(); + UnreadableControllerIsSkipped(); + EndedSessionsAreFreed(); if (failures) { std::fprintf(stderr, "%d check(s) failed\n", failures); From 198c0b8e5d77e064ff147a3e719d5c30dc2033d7 Mon Sep 17 00:00:00 2001 From: freezy Date: Fri, 27 Nov 2026 01:17:30 +0100 Subject: [PATCH 4/6] dof: keep the starting blackout until it is written, check strip writes - A unit whose first blackout failed keeps receiving that closing until it is written, so a device that comes back gets its zeros even when nothing changes afterwards; the openings after it report failed in the meantime instead of pending. - Teensy and Wemos command writes require the full byte count, and a short write fails the update so the controller reconnects. The combined strip write gets the time the two separate writes had. - Tests: Finish's blackout is checked in what Finish wrote, the opening is published while the updater is held in its first connect, the latch generation shared with the updater is atomic, the finish task is joined before the instance is disposed, and the junction tests work in a non-ASCII temporary folder. --- .../DofInstanceTests.cs | 8 +- .../DofSessionIntegrationTests.cs | 8 +- native/patches/0001-vpe-libdof.patch | 158 ++++++++++++++---- native/tests/internal.cpp | 58 ++++++- 4 files changed, 189 insertions(+), 43 deletions(-) diff --git a/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs b/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs index a308134..e6b86a8 100644 --- a/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs +++ b/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs @@ -749,8 +749,9 @@ public void ClosingDuringFinishLatchesTheGate() release.Wait(5000); } }, DofLogLevel.Debug); + Task finish = null; try { - var finish = Task.Run(() => dof.Finish()); + finish = Task.Run(() => dof.Finish()); Assert.That(finishing.Wait(5000), Is.True, "finish started"); var opening = dof.SetOutputGate(true); var closing = dof.SetOutputGate(false); @@ -762,6 +763,11 @@ public void ClosingDuringFinishLatchesTheGate() Assert.That((state.Applied, state.Superseded, state.Written, state.Failed), Is.EqualTo((true, false, 1, 0)), state.ToString()); } finally { release.Set(); + // Finish ends before the instance is disposed, also when an assertion above failed. + try { + finish?.Wait(TimeSpan.FromSeconds(30)); + } catch (AggregateException) { + } DofLibrary.SetLog((level, message) => _log.Enqueue($"[{level}] {message}"), DofLogLevel.Debug); } } diff --git a/VisualPinball.Engine.DOF.Test/DofSessionIntegrationTests.cs b/VisualPinball.Engine.DOF.Test/DofSessionIntegrationTests.cs index 3ed188c..1089a85 100644 --- a/VisualPinball.Engine.DOF.Test/DofSessionIntegrationTests.cs +++ b/VisualPinball.Engine.DOF.Test/DofSessionIntegrationTests.cs @@ -250,6 +250,11 @@ public void ReopensAStoreThroughAnotherPathToItsFolder() const int universe = 308; var dir = Path.Combine(_dir, "real"); Directory.CreateDirectory(dir); + try { + DofPaths.ToNative(dir); + } catch (DofException) { + Assert.Ignore("The temporary folder has a non-ASCII name and this volume no short (8.3) names, so libdof cannot open it on Windows."); + } var imported = Path.Combine(_dir, "imported through"); var reopened = Path.Combine(_dir, "reopened through"); Junction(imported, dir); @@ -304,7 +309,8 @@ public void RunsAUnicodeStoreReachedThroughAJunction() var link = Path.Combine(_dir, "link"); Junction(link, dir); try { - var basePath = Path.Combine(link, Path.GetRelativePath(dir, lease.Revision.BasePath)); + // The temporary folder may have a non-ASCII name too: its 8.3 spelling, still through the junction. + var basePath = Path.Combine(DofPaths.ToNative(link), Path.GetRelativePath(dir, lease.Revision.BasePath)); Assert.That(DofPaths.IsAscii(basePath), Is.True); var session = new DofSession(new DofSessionOptions { BasePath = basePath, diff --git a/native/patches/0001-vpe-libdof.patch b/native/patches/0001-vpe-libdof.patch index a42db12..6fbbebd 100644 --- a/native/patches/0001-vpe-libdof.patch +++ b/native/patches/0001-vpe-libdof.patch @@ -903,10 +903,10 @@ index 0d7a194..45b44d2 100644 controllerElement = controllerElement->NextSiblingElement(); diff --git a/src/cab/out/OutputGate.cpp b/src/cab/out/OutputGate.cpp new file mode 100644 -index 0000000..316d022 +index 0000000..e4adec1 --- /dev/null +++ b/src/cab/out/OutputGate.cpp -@@ -0,0 +1,379 @@ +@@ -0,0 +1,385 @@ +#include "OutputGate.h" + +#include @@ -949,14 +949,16 @@ index 0000000..316d022 +OutputGate::Snapshot OutputGate::Unit::Observe() const +{ + Snapshot current = m_gate->Current(); -+ // The closing in force when the unit registered stays in force for it until it confirmed or failed it: a session -+ // that starts closed starts dark on every unit, also on one whose first update comes after the gate opened. -+ int64_t closed = m_closedAtRegistration; -+ if (current.open && closed != 0 && m_ackedClosed.load(std::memory_order_acquire) < closed && m_failed.load(std::memory_order_acquire) < closed) -+ return { closed, false }; ++ // The closing in force when the unit registered stays in force for it until it confirmed it: a session that starts ++ // closed starts dark on every unit, also on one whose first update comes after the gate opened, and on one whose ++ // first blackout failed, which sends it again once its device is back (Classify reports the openings failed meanwhile). ++ if (current.open && HeldClosed()) ++ return { m_closedAtRegistration, false }; + return current; +} + ++bool OutputGate::Unit::HeldClosed() const { return m_closedAtRegistration != 0 && m_ackedClosed.load(std::memory_order_acquire) < m_closedAtRegistration; } ++ +bool OutputGate::Unit::IsAcked(const Snapshot& snapshot) const +{ + const std::atomic& acked = snapshot.open ? m_ackedOpen : m_ackedClosed; @@ -1213,6 +1215,10 @@ index 0000000..316d022 + return UnitState::Confirmed; + if (unit.m_failed.load(std::memory_order_acquire) >= generation) + return UnitState::Failed; ++ // A unit still held at the closing it registered under (Unit::Observe) that failed it delivers no later change before ++ // that closing got through: it fails them, as a unit that failed them itself does. ++ if (unit.HeldClosed() && generation > unit.m_closedAtRegistration && unit.m_failed.load(std::memory_order_acquire) >= unit.m_closedAtRegistration) ++ return UnitState::Failed; + if (known && open && unit.m_untouched.load(std::memory_order_acquire) >= generation) + return UnitState::Untouched; + // Finished cleanly: what it confirmed or left alone stays so, and it delivers nothing later. @@ -1288,10 +1294,10 @@ index 0000000..316d022 +} diff --git a/src/cab/out/OutputGate.h b/src/cab/out/OutputGate.h new file mode 100644 -index 0000000..7ea71ed +index 0000000..ec0236e --- /dev/null +++ b/src/cab/out/OutputGate.h -@@ -0,0 +1,256 @@ +@@ -0,0 +1,259 @@ +#pragma once + +#include @@ -1355,8 +1361,9 @@ index 0000000..7ea71ed + { + public: + // Called by the unit's updater before it copies the values it sends, under the lock the values are set with. A unit -+ // registered while the gate was closed gets that closing until it confirmed or failed it, also once the gate -+ // opened: its device, which an earlier session may have left lit, is turned off before any opening reaches it. ++ // registered while the gate was closed gets that closing until it confirmed it, also once the gate opened and also ++ // after a write of it failed: its device, which an earlier session may have left lit, is turned off before any ++ // opening reaches it. + Snapshot Observe() const; + // Whether the hardware already got the state of `snapshot`, or the gate is open at a unit DOF leaves alone; until + // then the updater transfers every output. @@ -1389,6 +1396,8 @@ index 0000000..7ea71ed + std::atomic m_stopped { false }; + // The closing the gate was at when the unit registered, or 0 if it was open. + int64_t m_closedAtRegistration = 0; ++ // Whether the unit registered under a closing it has not confirmed yet. ++ bool HeldClosed() const; + }; + + // A unit, and with it its session's gate: the gate lives as long as any handle to one of its units. @@ -1676,10 +1685,10 @@ index e112579..6ce43dc 100644 } \ No newline at end of file diff --git a/src/cab/out/adressableledstrip/TeensyStripController.cpp b/src/cab/out/adressableledstrip/TeensyStripController.cpp -index d3678e4..c502afc 100644 +index d3678e4..fe6213e 100644 --- a/src/cab/out/adressableledstrip/TeensyStripController.cpp +++ b/src/cab/out/adressableledstrip/TeensyStripController.cpp -@@ -213,18 +213,20 @@ bool TeensyStripController::VerifySettings() +@@ -213,18 +213,28 @@ bool TeensyStripController::VerifySettings() return true; } @@ -1697,16 +1706,24 @@ index d3678e4..c502afc 100644 - enum sp_return result = sp_blocking_write(m_comPort, commandData.data(), 5, m_comPortTimeOutMs); - if (result < 0) - throw std::runtime_error(StringExtensions::Build("Failed to write command data: {0}", sp_last_error_message())); -- ++ // VPE: as two writes, the command and the values had a timeout each; the one write keeps that time. ++ WritePort(commandData.data(), commandData.size(), 2 * m_comPortTimeOutMs, "output values"); ++ return true; ++} + - result = sp_blocking_write(m_comPort, outputValues.data(), outputValues.size(), m_comPortTimeOutMs); -+ enum sp_return result = sp_blocking_write(m_comPort, commandData.data(), commandData.size(), m_comPortTimeOutMs); ++void TeensyStripController::WritePort(const uint8_t* data, size_t size, int timeoutMs, const std::string& what) const ++{ ++ enum sp_return result = sp_blocking_write(m_comPort, data, size, static_cast(timeoutMs)); if (result < 0) - throw std::runtime_error(StringExtensions::Build("Failed to write output values: {0}", sp_last_error_message())); -+ return true; +- throw std::runtime_error(StringExtensions::Build("Failed to write output values: {0}", sp_last_error_message())); ++ throw std::runtime_error(StringExtensions::Build("Failed to write {0}: {1}", what, sp_last_error_message())); ++ if (static_cast(result) != size) ++ throw std::runtime_error(StringExtensions::Build("Failed to write {0}: the port took {1} of {2} bytes in time", what, std::to_string(result), std::to_string(size))); } void TeensyStripController::UpdateOutputs(const std::vector& outputValues) -@@ -245,7 +247,9 @@ void TeensyStripController::UpdateOutputs(const std::vector& outputValu +@@ -245,7 +255,9 @@ void TeensyStripController::UpdateOutputs(const std::vector& outputValu int targetPosition = i * m_numberOfLedsPerChannel; std::vector stripData(outputValues.begin() + sourcePosition * 3, outputValues.begin() + sourcePosition * 3 + nrOfLedsOnStrip * 3); @@ -1717,20 +1734,68 @@ index d3678e4..c502afc 100644 bytesRead = -1; answerData = std::vector(1); -@@ -270,6 +274,8 @@ void TeensyStripController::UpdateOutputs(const std::vector& outputValu +@@ -270,9 +282,9 @@ void TeensyStripController::UpdateOutputs(const std::vector& outputValu } commandData = { (uint8_t)'O' }; +- enum sp_return result = sp_blocking_write(m_comPort, commandData.data(), 1, m_comPortTimeOutMs); +- if (result < 0) +- throw std::runtime_error(StringExtensions::Build("Failed to write output command: {0}", sp_last_error_message())); + if (TransferCancelled()) + return; - enum sp_return result = sp_blocking_write(m_comPort, commandData.data(), 1, m_comPortTimeOutMs); - if (result < 0) - throw std::runtime_error(StringExtensions::Build("Failed to write output command: {0}", sp_last_error_message())); ++ WritePort(commandData.data(), 1, m_comPortTimeOutMs, "output command"); + + bytesRead = -1; + answerData = std::vector(1); +@@ -296,9 +308,7 @@ void TeensyStripController::UpdateOutputs(const std::vector& outputValu + void TeensyStripController::SetupController() + { + uint8_t command = 'M'; +- enum sp_return result = sp_blocking_write(m_comPort, &command, 1, m_comPortTimeOutMs); +- if (result < 0) +- throw std::runtime_error(StringExtensions::Build("Failed to write max leds query: {0}", sp_last_error_message())); ++ WritePort(&command, 1, m_comPortTimeOutMs, "max leds query"); + + std::vector receiveData(3); + int bytesRead = -1; +@@ -340,9 +350,7 @@ void TeensyStripController::SetupController() + uint16_t nrOfLeds = (uint16_t)m_numberOfLedsPerChannel; + std::vector commandData = { (uint8_t)'L', (uint8_t)(nrOfLeds >> 8), (uint8_t)(nrOfLeds & 255) }; + +- result = sp_blocking_write(m_comPort, commandData.data(), 3, m_comPortTimeOutMs); +- if (result < 0) +- throw std::runtime_error(StringExtensions::Build("Failed to write leds per channel command: {0}", sp_last_error_message())); ++ WritePort(commandData.data(), 3, m_comPortTimeOutMs, "leds per channel command"); + + receiveData.resize(1); + bytesRead = -1; +@@ -493,9 +501,7 @@ void TeensyStripController::ConnectToController() + std::vector commandData; + + commandData = { (uint8_t)'C' }; +- result = sp_blocking_write(m_comPort, commandData.data(), 1, m_comPortTimeOutMs); +- if (result < 0) +- throw std::runtime_error(StringExtensions::Build("Failed to write clear command: {0}", sp_last_error_message())); ++ WritePort(commandData.data(), 1, m_comPortTimeOutMs, "clear command"); + + receiveData.resize(1); + bytesRead = -1; +@@ -517,9 +523,7 @@ void TeensyStripController::ConnectToController() + } + + commandData = { (uint8_t)'O' }; +- result = sp_blocking_write(m_comPort, commandData.data(), 1, m_comPortTimeOutMs); +- if (result < 0) +- throw std::runtime_error(StringExtensions::Build("Failed to write output command: {0}", sp_last_error_message())); ++ WritePort(commandData.data(), 1, m_comPortTimeOutMs, "output command"); + + receiveData.resize(1); + bytesRead = -1; diff --git a/src/cab/out/adressableledstrip/TeensyStripController.h b/src/cab/out/adressableledstrip/TeensyStripController.h -index e910f68..51c6565 100644 +index e910f68..30a1cae 100644 --- a/src/cab/out/adressableledstrip/TeensyStripController.h +++ b/src/cab/out/adressableledstrip/TeensyStripController.h -@@ -107,7 +107,9 @@ protected: +@@ -107,13 +107,19 @@ protected: virtual void DisconnectFromController() override; virtual void UpdateOutputs(const std::vector& outputValues) override; @@ -1741,6 +1806,16 @@ index e910f68..51c6565 100644 virtual void SetupController(); int ReadPortWait(uint8_t* buffer, int bufferOffset, int numberOfBytes); + const std::vector& GetNumberOfLedsPerStrip() const { return m_numberOfLedsPerStrip; } + int GetNumberOfLedsPerChannel() const { return m_numberOfLedsPerChannel; } + struct sp_port* GetComPort() const { return m_comPort; } ++ // VPE: writes all `size` bytes within `timeoutMs`, or throws. A write the port took only part of leaves the device ++ // waiting for the rest of a command, so it fails the update, and the controller reconnects (a new handshake) rather ++ // than wait for an answer to a command the device did not get. ++ void WritePort(const uint8_t* data, size_t size, int timeoutMs, const std::string& what) const; + + private: + std::string m_comPortName; diff --git a/src/cab/out/adressableledstrip/UMXController.cpp b/src/cab/out/adressableledstrip/UMXController.cpp index 9cbe817..cb58397 100644 --- a/src/cab/out/adressableledstrip/UMXController.cpp @@ -1944,7 +2019,7 @@ index 4475b47..07e2e83 100644 virtual bool IsLost() const { return false; } virtual void Release() { } diff --git a/src/cab/out/adressableledstrip/WemosD1StripController.cpp b/src/cab/out/adressableledstrip/WemosD1StripController.cpp -index cb013c8..81f5327 100644 +index cb013c8..c9ffd8a 100644 --- a/src/cab/out/adressableledstrip/WemosD1StripController.cpp +++ b/src/cab/out/adressableledstrip/WemosD1StripController.cpp @@ -1,5 +1,6 @@ @@ -1954,7 +2029,18 @@ index cb013c8..81f5327 100644 #include "../../../Log.h" #include "../../../general/StringExtensions.h" #include -@@ -66,14 +67,38 @@ void WemosD1MPStripController::SetupController() +@@ -37,9 +38,7 @@ void WemosD1MPStripController::SetupController() + + Log::Write(StringExtensions::Build("Resize ledstrip {0} to {1} leds.", std::to_string(numled), std::to_string(nbleds))); + +- enum sp_return result = sp_blocking_write(GetComPort(), commandData.data(), 5, GetComPortTimeOutMs()); +- if (result < 0) +- throw std::runtime_error(StringExtensions::Build("Failed to write ledstrip resize command: {0}", sp_last_error_message())); ++ WritePort(commandData.data(), 5, GetComPortTimeOutMs(), "ledstrip resize command"); + + receiveData = std::vector(1); + bytesRead = -1; +@@ -66,14 +65,34 @@ void WemosD1MPStripController::SetupController() } } @@ -1980,11 +2066,7 @@ index cb013c8..81f5327 100644 + if (!TransferCancelled()) + { + commandData = { (uint8_t)'T' }; -+ enum sp_return result = sp_blocking_write(GetComPort(), commandData.data(), 1, GetComPortTimeOutMs()); -+ if (result < 0) -+ throw std::runtime_error(StringExtensions::Build("Failed to write test command: {0}", sp_last_error_message())); -+ if (result == 0) -+ throw std::runtime_error("Failed to write test command: the port took nothing within its timeout"); ++ WritePort(commandData.data(), 1, GetComPortTimeOutMs(), "test command"); + // VPE: the port took the test, which may light the strip whatever the controller answers: the session ends + // with the blackout from here on, also if the setup fails below. + sent = true; @@ -1999,7 +2081,7 @@ index cb013c8..81f5327 100644 std::this_thread::sleep_for(std::chrono::milliseconds(2000)); -@@ -95,12 +120,10 @@ void WemosD1MPStripController::SetupController() +@@ -95,12 +114,10 @@ void WemosD1MPStripController::SetupController() throw std::runtime_error(StringExtensions::Build( "Expected a Ack (A) after requesting a test sequence, but received no answer or a unexpected answer ({0}). Will not send data to the controller.", std::string(1, receivedChar))); } @@ -2013,18 +2095,20 @@ index cb013c8..81f5327 100644 { if (m_useCompression) { -@@ -148,18 +171,22 @@ void WemosD1MPStripController::SendLedstripData(const std::vector& outp +@@ -148,18 +165,23 @@ void WemosD1MPStripController::SendLedstripData(const std::vector& outp std::vector commandData = { (uint8_t)'Q', (uint8_t)(targetPosition >> 8), (uint8_t)(targetPosition & 255), (uint8_t)(nbData >> 8), (uint8_t)(nbData & 255), (uint8_t)(nbLeds >> 8), (uint8_t)(nbLeds & 255) }; +- +- sp_blocking_write(GetComPort(), commandData.data(), 7, GetComPortTimeOutMs()); +- sp_blocking_write(GetComPort(), m_compressedData.data(), m_compressedData.size(), GetComPortTimeOutMs()); + // VPE: as in TeensyStripController, one write, checked once the values are compressed. + commandData.insert(commandData.end(), m_compressedData.begin(), m_compressedData.end()); + if (TransferCancelled()) + return false; - -- sp_blocking_write(GetComPort(), commandData.data(), 7, GetComPortTimeOutMs()); -- sp_blocking_write(GetComPort(), m_compressedData.data(), m_compressedData.size(), GetComPortTimeOutMs()); -+ sp_blocking_write(GetComPort(), commandData.data(), commandData.size(), GetComPortTimeOutMs()); ++ ++ // VPE: the command and the values had a timeout each as two writes, and a short write was not noticed. ++ WritePort(commandData.data(), commandData.size(), 2 * GetComPortTimeOutMs(), "compressed output values"); + return true; } else diff --git a/native/tests/internal.cpp b/native/tests/internal.cpp index 6eed755..c14f073 100644 --- a/native/tests/internal.cpp +++ b/native/tests/internal.cpp @@ -272,6 +272,10 @@ class ScriptedController : public OutputControllerCompleteBase std::atomic failAfterTest { false }; std::atomic handshakeFailsOnce { false }; std::function beforeTest; + // Runs at the start of the first connect, before the updater observes the gate for the first time. + std::function onFirstConnect; + // Every write fails while it is set; reconnects still work. + std::atomic failWrites { false }; protected: int GetNumberOfConfiguredOutputs() override { return 2; } @@ -280,6 +284,8 @@ class ScriptedController : public OutputControllerCompleteBase void ConnectToController() override { int attempt = connects++; + if (attempt == 0 && onFirstConnect) + onFirstConnect(); if (attempt > 0 && failReconnect) throw std::runtime_error("the device is gone"); if (attempt == 0 && handshakeFailsOnce) @@ -315,7 +321,7 @@ class ScriptedController : public OutputControllerCompleteBase void UpdateOutputs(const std::vector& values) override { - if (failNextWrite.exchange(false)) + if (failNextWrite.exchange(false) || failWrites) throw std::runtime_error("the write failed"); for (int i = 0; i < 2 && i < static_cast(values.size()); i++) { @@ -694,7 +700,9 @@ void ConnectTestCountsAsUse() CHECK(counts.untouched == 1 && counts.confirmed == 0, "the test does not confirm an opening after a closing"); CHECK(controller.Written().size() == written, "nothing was written for it"); controller.Finish(); - CHECK(controller.HasWritten("0=0") && controller.HasWritten("1=0"), "the session ends with the blackout"); + std::vector log = controller.Written(); + auto finished = log.begin() + static_cast(written); + CHECK(std::find(finished, log.end(), "0=0") != log.end() && std::find(finished, log.end(), "1=0") != log.end(), "the session ends with the blackout"); } // A connect that fails after the device took its connect test ends as a session does: with the blackout, and with an @@ -745,8 +753,17 @@ void SessionThatStartsClosedStartsDark() ScriptedController controller; controller.SetName("scripted"); controller.testOnConnect = true; + // The updater is held in its first connect, before it observes the gate, until the opening is published. + std::atomic opened { false }; + std::atomic held { false }; + controller.onFirstConnect = [&]() { + held = true; + WaitFor([&opened]() { return opened.load(); }); + }; controller.Init(nullptr); + CHECK(WaitFor([&held]() { return held.load(); }), "the updater is held in its first connect"); int64_t open = Change(gate, true); + opened = true; OutputGate::Counts counts; // The opening supersedes the closing; the unit still has to confirm it. CHECK(WaitFor([&]() { @@ -779,6 +796,34 @@ void SessionThatStartsClosedTestsOnNoReconnect() controller.Finish(); } +// A unit whose startup blackout failed sends it again once the device is back, before anything else, also when the gate +// opened meanwhile and no value changed: the device an earlier session left lit is turned off. Until then the unit +// fails the openings after that closing, rather than leaving them pending. +void FailedStartupBlackoutIsSentAgain() +{ + OutputGate& gate = OutputGate::BeginSession(); + int64_t closed = Change(gate, false); + ScriptedController controller; + controller.SetName("scripted"); + controller.failWrites = true; + std::atomic opened { false }; + controller.onFirstConnect = [&opened]() { WaitFor([&opened]() { return opened.load(); }); }; + controller.Init(nullptr); + int64_t open = Change(gate, true); + opened = true; + OutputGate::Counts counts; + CHECK(WaitFor([&]() { return controller.connects.load() >= 2 && gate.GetState(open, counts) == OutputGate::Status::Applied && counts.failed == 1; }), "the opening fails while the device takes nothing"); + controller.failWrites = false; + CHECK(WaitFor([&]() { + gate.GetState(closed, counts); + return counts.confirmed == 1; + }), + "the closing is written once the device is back"); + CHECK(controller.HasWritten("0=0") && controller.HasWritten("1=0"), "to every output"); + CHECK(WaitFor([&]() { return gate.GetState(open, counts) == OutputGate::Status::Applied && counts.untouched == 1; }), "then the opening leaves the unit alone"); + controller.Finish(); +} + // A connect test is checked again at its write: a latch between the decision and the write (one in the log line) // keeps it from going out. void LatchBeforeTheConnectTestSkipsIt() @@ -788,11 +833,15 @@ void LatchBeforeTheConnectTestSkipsIt() ScriptedController controller; controller.SetName("scripted"); controller.testOnConnect = true; - int64_t latched = -1; + std::atomic latched { -1 }; controller.beforeTest = [&]() { latched = gate.Latch(); }; controller.Init(nullptr); OutputGate::Counts counts; - CHECK(WaitFor([&]() { return latched >= 0 && gate.GetState(latched, counts) == OutputGate::Status::Applied && counts.confirmed == 1; }), "the latch is written"); + CHECK(WaitFor([&]() { + int64_t generation = latched.load(); + return generation >= 0 && gate.GetState(generation, counts) == OutputGate::Status::Applied && counts.confirmed == 1; + }), + "the latch is written"); CHECK(!controller.HasWritten("test"), "the test after it is not"); controller.Finish(); } @@ -1381,6 +1430,7 @@ int main() SessionThatStartsClosedStartsDark(); SessionThatStartsClosedTestsOnNoReconnect(); LatchBeforeTheConnectTestSkipsIt(); + FailedStartupBlackoutIsSentAgain(); BlackoutConfirmsWhereItIsSent(); PermanentFailureOutranksAnAck(); CleanFinishKeepsTheSettledResult(); From e906d16a5419cabf0891353a9f392e347e6bab1e Mon Sep 17 00:00:00 2001 From: freezy Date: Fri, 27 Nov 2026 01:41:46 +0100 Subject: [PATCH 5/6] dof: keep a closing after a failed startup blackout pending until tried A unit held at a startup closing it failed reported every later change as failed. Only openings are held back there; a later closing is written, so it now stays pending until that write gets through or fails, or the unit stops. The tests' updater holds now record whether they were reached in time and check it once the updater is joined, so a hold that times out fails the test instead of passing it. --- native/patches/0001-vpe-libdof.patch | 11 +++--- native/tests/internal.cpp | 51 ++++++++++++++++++++++++++-- 2 files changed, 55 insertions(+), 7 deletions(-) diff --git a/native/patches/0001-vpe-libdof.patch b/native/patches/0001-vpe-libdof.patch index 6fbbebd..9a5503f 100644 --- a/native/patches/0001-vpe-libdof.patch +++ b/native/patches/0001-vpe-libdof.patch @@ -903,10 +903,10 @@ index 0d7a194..45b44d2 100644 controllerElement = controllerElement->NextSiblingElement(); diff --git a/src/cab/out/OutputGate.cpp b/src/cab/out/OutputGate.cpp new file mode 100644 -index 0000000..e4adec1 +index 0000000..d5d7bbc --- /dev/null +++ b/src/cab/out/OutputGate.cpp -@@ -0,0 +1,385 @@ +@@ -0,0 +1,386 @@ +#include "OutputGate.h" + +#include @@ -1215,9 +1215,10 @@ index 0000000..e4adec1 + return UnitState::Confirmed; + if (unit.m_failed.load(std::memory_order_acquire) >= generation) + return UnitState::Failed; -+ // A unit still held at the closing it registered under (Unit::Observe) that failed it delivers no later change before -+ // that closing got through: it fails them, as a unit that failed them itself does. -+ if (unit.HeldClosed() && generation > unit.m_closedAtRegistration && unit.m_failed.load(std::memory_order_acquire) >= unit.m_closedAtRegistration) ++ // A unit still held at the closing it registered under (Unit::Observe) that failed it delivers no later opening before ++ // that closing got through: it fails them, as a unit that failed them itself does. A later closing is not held: the ++ // unit writes it, and it stays pending until that write got through or failed. ++ if (open && unit.HeldClosed() && generation > unit.m_closedAtRegistration && unit.m_failed.load(std::memory_order_acquire) >= unit.m_closedAtRegistration) + return UnitState::Failed; + if (known && open && unit.m_untouched.load(std::memory_order_acquire) >= generation) + return UnitState::Untouched; diff --git a/native/tests/internal.cpp b/native/tests/internal.cpp index c14f073..64005eb 100644 --- a/native/tests/internal.cpp +++ b/native/tests/internal.cpp @@ -756,9 +756,10 @@ void SessionThatStartsClosedStartsDark() // The updater is held in its first connect, before it observes the gate, until the opening is published. std::atomic opened { false }; std::atomic held { false }; + std::atomic heldUntilOpened { false }; controller.onFirstConnect = [&]() { held = true; - WaitFor([&opened]() { return opened.load(); }); + heldUntilOpened = WaitFor([&opened]() { return opened.load(); }); }; controller.Init(nullptr); CHECK(WaitFor([&held]() { return held.load(); }), "the updater is held in its first connect"); @@ -775,6 +776,7 @@ void SessionThatStartsClosedStartsDark() CHECK(WaitFor([&]() { return gate.GetState(open, counts) == OutputGate::Status::Applied && counts.pending == 0; }) && counts.untouched == 1, "the opening after it leaves the unit alone"); CHECK(!controller.HasWritten("test"), "no connect test went out before the closing was written"); controller.Finish(); + CHECK(heldUntilOpened, "the updater first observed the gate once the opening was published"); } // A session that starts closed sends no connect test, also not on a reconnect once the gate opened: the test was used @@ -807,7 +809,8 @@ void FailedStartupBlackoutIsSentAgain() controller.SetName("scripted"); controller.failWrites = true; std::atomic opened { false }; - controller.onFirstConnect = [&opened]() { WaitFor([&opened]() { return opened.load(); }); }; + std::atomic heldUntilOpened { false }; + controller.onFirstConnect = [&]() { heldUntilOpened = WaitFor([&opened]() { return opened.load(); }); }; controller.Init(nullptr); int64_t open = Change(gate, true); opened = true; @@ -822,6 +825,49 @@ void FailedStartupBlackoutIsSentAgain() CHECK(controller.HasWritten("0=0") && controller.HasWritten("1=0"), "to every output"); CHECK(WaitFor([&]() { return gate.GetState(open, counts) == OutputGate::Status::Applied && counts.untouched == 1; }), "then the opening leaves the unit alone"); controller.Finish(); + CHECK(heldUntilOpened, "the updater first observed the gate once the opening was published"); +} + +// A closing after a failed startup blackout is the unit's to write, not a change it fails for the blackout it still owes: +// it stays pending until the unit tried it, fails when that write fails, and is confirmed once it gets through. +void ClosingAfterAFailedStartupBlackoutIsTried() +{ + OutputGate& gate = OutputGate::BeginSession(); + int64_t closed = Change(gate, false); + ScriptedController controller; + controller.SetName("scripted"); + controller.failWrites = true; + // The updater is held in the disconnect after the failed startup blackout, before it observes the gate again. + std::atomic holdOnce { true }; + std::atomic held { false }; + std::atomic released { false }; + std::atomic heldUntilReleased { true }; + controller.onDisconnect = [&]() { + if (!holdOnce.exchange(false)) + return; + held = true; + heldUntilReleased = WaitFor([&released]() { return released.load(); }); + }; + controller.Init(nullptr); + OutputGate::Counts counts; + CHECK(WaitFor([&held]() { return held.load(); }), "the updater is held after its startup blackout failed"); + gate.GetState(closed, counts); + CHECK(counts.failed == 1, "the startup blackout failed"); + int64_t latched = gate.Latch(); + CHECK(gate.GetState(latched, counts) == OutputGate::Status::Applied && counts.pending == 1 && counts.failed == 0, "the latch is pending before the unit tried it"); + released = true; + CHECK(WaitFor([&]() { return controller.connects.load() >= 3 && gate.GetState(latched, counts) == OutputGate::Status::Applied && counts.failed == 1; }), "it fails when its own write fails"); + controller.failWrites = false; + CHECK(WaitFor([&]() { + gate.GetState(latched, counts); + return counts.confirmed == 1; + }), + "it is confirmed once the device is back"); + gate.GetState(closed, counts); + CHECK(counts.confirmed == 1, "with the startup blackout"); + CHECK(controller.HasWritten("0=0") && controller.HasWritten("1=0"), "to every output"); + controller.Finish(); + CHECK(heldUntilReleased, "the updater was held until the latch was classified"); } // A connect test is checked again at its write: a latch between the decision and the write (one in the log line) @@ -1431,6 +1477,7 @@ int main() SessionThatStartsClosedTestsOnNoReconnect(); LatchBeforeTheConnectTestSkipsIt(); FailedStartupBlackoutIsSentAgain(); + ClosingAfterAFailedStartupBlackoutIsTried(); BlackoutConfirmsWhereItIsSent(); PermanentFailureOutranksAnAck(); CleanFinishKeepsTheSettledResult(); From 3d47b8c868c06a2d915711efddbdc96176f42bd2 Mon Sep 17 00:00:00 2001 From: freezy Date: Fri, 27 Nov 2026 02:26:10 +0100 Subject: [PATCH 6/6] dof: admit calls into an instance so dispose never frees it under one Every DofInstance member read the native handle and then called libdof with it, so a Dispose on another thread could free the instance in between. Calls are now admitted through an interlocked count that Dispose drains: it stops admitting calls, waits until the admitted ones have returned (a running Finish too), and only then destroys the instance on its own thread. A second Dispose waits for that. So no call runs libdof's shutdown, and the members that return at once keep their no-op, -1 or 0 after a dispose without throwing or allocating. --- .../DofInstanceTests.cs | 138 +++++++++++- VisualPinball.Engine.DOF/DofInstance.cs | 212 ++++++++++++++---- 2 files changed, 305 insertions(+), 45 deletions(-) diff --git a/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs b/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs index e6b86a8..872382c 100644 --- a/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs +++ b/VisualPinball.Engine.DOF.Test/DofInstanceTests.cs @@ -376,6 +376,137 @@ public void OnlyOneInstanceAtATime() using var next = DofInstance.Create(config.Root); } + [Test] + public void DisposeWaitsForTheCallsInFlight() + { + var unit = Unit("ArtNetA"); + using var config = StandardConfig(unit); + for (var round = 0; round < 5; round++) { + var dof = DofInstance.Create(config.Root); + // Init is held in libdof at its first log line on its own thread, while callers keep calling the members that + // return at once and two threads dispose the instance. libdof's shutdown says goodbye on the thread that runs it. + var initThread = 0; + var held = 0; + using var inside = new ManualResetEventSlim(); + using var release = new ManualResetEventSlim(); + using var disposing = new ManualResetEventSlim(); + var shutdownThreads = new ConcurrentQueue(); + DofLibrary.SetLog((level, message) => { + _log.Enqueue($"[{level}] {message}"); + var thread = Environment.CurrentManagedThreadId; + if (message.Contains("Bye and thanks for using!")) { + shutdownThreads.Enqueue(thread); + } + if (thread == Volatile.Read(ref initThread) && Interlocked.Exchange(ref held, 1) == 0) { + inside.Set(); + release.Wait(30000); + } + }, DofLogLevel.Debug); + var stop = 0; + var unexpected = new ConcurrentQueue(); + var callerThreads = new ConcurrentDictionary(); + var callers = Enumerable.Range(0, 4).Select(index => new Thread(() => { + callerThreads[Environment.CurrentManagedThreadId] = true; + while (Volatile.Read(ref stop) == 0) { + try { + switch (index) { + case 0: + dof.Data('S', 1, 1); + dof.Data('S', 1, 0); + break; + case 1: + dof.DataNamed("vpe_named", 1); + _ = dof.PendingInput; + break; + case 2: + dof.SetOutputGate(true); + break; + default: + if (dof.LatchOutputGate() == -1) { + disposing.Set(); + } + break; + } + } catch (Exception e) { + // These members do not throw, disposed or not. + unexpected.Enqueue(e); + } + } + }) { IsBackground = true }).ToList(); + var init = new Thread(() => { + Volatile.Write(ref initThread, Environment.CurrentManagedThreadId); + callerThreads[Environment.CurrentManagedThreadId] = true; + try { + dof.Init(config.TableFile, "vpetest"); + } catch (Exception e) { + unexpected.Enqueue(e); + } + }) { IsBackground = true }; + var disposerThreads = new ConcurrentDictionary(); + var disposers = Enumerable.Range(0, 2).Select(_ => new Thread(() => { + disposerThreads[Environment.CurrentManagedThreadId] = true; + dof.Dispose(); + }) { IsBackground = true }).ToList(); + try { + callers.ForEach(t => t.Start()); + init.Start(); + Assert.That(inside.Wait(10000), Is.True, "init is held in libdof"); + disposers.ForEach(t => t.Start()); + Assert.That(disposing.Wait(10000), Is.True, "the callers see the dispose"); + Assert.That(disposers.Any(t => t.Join(0)), Is.False, "no disposer returns while a call is in flight"); + release.Set(); + Assert.That(init.Join(30000), Is.True, "init returned"); + Assert.That(disposers.All(t => t.Join(30000)), Is.True, "both disposers returned"); + } finally { + release.Set(); + Volatile.Write(ref stop, 1); + Assert.That(callers.All(t => t.Join(10000)), Is.True, "the callers ended"); + DofLibrary.SetLog((level, message) => _log.Enqueue($"[{level}] {message}"), DofLogLevel.Debug); + } + Assert.That(unexpected, Is.Empty, string.Join("\n", unexpected)); + Assert.That(shutdownThreads.Count, Is.EqualTo(1), "libdof shut down once"); + Assert.That(shutdownThreads.All(disposerThreads.ContainsKey), Is.True, "on a disposing thread"); + Assert.That(shutdownThreads.Any(callerThreads.ContainsKey), Is.False, "never on a caller's"); + + // Each member does what it does on a disposed instance. + Assert.That(dof.SetOutputGate(true), Is.EqualTo(-1), "no gate after dispose"); + Assert.That(dof.LatchOutputGate(), Is.EqualTo(-1), "no latch after dispose"); + Assert.That(dof.PendingInput, Is.Zero, "no input after dispose"); + dof.Data('S', 1, 1); + dof.DataNamed("vpe_named", 1); + Assert.Throws(() => dof.GetGateState(1)); + Assert.Throws(() => dof.Finish()); + dof.Dispose(); + // The instance is gone once Dispose returned: the next one can be created. + using (DofInstance.Create(config.Root)) { + } + } + } + + [Test] + public void HotPathDoesNotAllocate() + { + var unit = Unit("ArtNetA"); + using var config = StandardConfig(unit); + using var dof = Start(config); + long Measure() + { + var before = GC.GetAllocatedBytesForCurrentThread(); + for (var i = 0; i < 1000; i++) { + dof.Data('S', 1, i & 1); + dof.SetOutputGate(true); + } + _ = dof.PendingInput; + dof.LatchOutputGate(); + return GC.GetAllocatedBytesForCurrentThread() - before; + } + Measure(); + Assert.That(Measure(), Is.Zero, "the handle is held for each call without allocating"); + dof.Finish(); + dof.Dispose(); + Assert.That(Measure(), Is.Zero, "nor once disposed"); + } + [Test] public void FailedInitLeavesTheProcessUsable() { @@ -763,11 +894,8 @@ public void ClosingDuringFinishLatchesTheGate() Assert.That((state.Applied, state.Superseded, state.Written, state.Failed), Is.EqualTo((true, false, 1, 0)), state.ToString()); } finally { release.Set(); - // Finish ends before the instance is disposed, also when an assertion above failed. - try { - finish?.Wait(TimeSpan.FromSeconds(30)); - } catch (AggregateException) { - } + // The hook is taken off before the events go: SetLog returns once no line is in it. Disposing the instance + // waits for a finish still running, also when an assertion above failed. DofLibrary.SetLog((level, message) => _log.Enqueue($"[{level}] {message}"), DofLogLevel.Debug); } } diff --git a/VisualPinball.Engine.DOF/DofInstance.cs b/VisualPinball.Engine.DOF/DofInstance.cs index bf76a68..01109b2 100644 --- a/VisualPinball.Engine.DOF/DofInstance.cs +++ b/VisualPinball.Engine.DOF/DofInstance.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; +using System.Threading; using VisualPinball.Engine.DOF.Native; namespace VisualPinball.Engine.DOF @@ -114,22 +115,35 @@ internal DofCabinetDescription(IReadOnlyList controllers, IReadOn /// a time; throws while another one is alive. /// /// - /// Calls may come from any thread, but must not run concurrently with another call on the same - /// instance: the owner serialises them (the session worker does). blocks until libdof's threads - /// stopped, which can take as long as the slowest device; call it from a thread that can wait. + /// Calls may come from any thread, included. Each call into libdof is admitted first and counted + /// until it returned; Dispose stops admitting calls, waits for the admitted ones to return, and then destroys the + /// instance on its own thread, so a call never runs libdof's shutdown. It returns once the instance is destroyed, so a + /// new instance can be created then; a second Dispose waits for that too. A call that is not admitted any more does + /// what that member does on a disposed instance. Dispose from inside a call (a log line it writes on the calling + /// thread), which would wait for itself, is not supported. blocks until libdof's threads stopped, + /// which can take as long as the slowest device; call it from a thread that can wait. /// public sealed class DofInstance : IDisposable { private const int ErrorSize = 1024; - private IntPtr _handle; + private const int Alive = 0; + private const int Disposing = 1; + private const int Destroyed = 2; + + private readonly IntPtr _dof; + // The calls admitted into libdof (Enter) that have not returned yet. + private int _calls; + private int _state = Alive; + // Dispose waits on it for the admitted calls to return, and a second Dispose for the destruction. + private readonly object _disposeLock = new object(); /// The folder that contains directoutputconfig/; libdof reads no file outside it. public string BasePath { get; } - private DofInstance(IntPtr handle, string basePath) + private DofInstance(IntPtr dof, string basePath) { - _handle = handle; + _dof = dof; BasePath = basePath; } @@ -158,8 +172,14 @@ public static DofInstance Create(string basePath) public void Init(string tableFile, string romName) { var error = new byte[ErrorSize]; - var status = DofNative.Init(Handle, Utf8.Encode(tableFile == null ? string.Empty : DofPaths.ToNative(tableFile)), - Utf8.Encode(romName ?? string.Empty), error, error.Length); + EnterOrThrow(); + int status; + try { + status = DofNative.Init(_dof, Utf8.Encode(tableFile == null ? string.Empty : DofPaths.ToNative(tableFile)), + Utf8.Encode(romName ?? string.Empty), error, error.Length); + } finally { + Leave(); + } DofException.ThrowIfFailed(status, "Initialising DOF", Utf8.DecodeBuffer(error)); } @@ -169,9 +189,13 @@ public void Init(string tableFile, string romName) /// 'S' solenoid, 'L' lamp, 'G' GI string, 'W' switch, 'N' mech, 'D' display, 'E' event. public void Data(char type, int number, int value) { - var handle = _handle; - if (handle != IntPtr.Zero) { - DofNative.Data(handle, (byte)type, number, value); + if (!Enter()) { + return; + } + try { + DofNative.Data(_dof, (byte)type, number, value); + } finally { + Leave(); } } @@ -184,9 +208,13 @@ public void DataNamed(string name, int value) if (string.IsNullOrEmpty(name)) { return; } - var handle = _handle; - if (handle != IntPtr.Zero) { - DofNative.DataNamed(handle, Utf8.Encode(NativeName(name)), value); + if (!Enter()) { + return; + } + try { + DofNative.DataNamed(_dof, Utf8.Encode(NativeName(name)), value); + } finally { + Leave(); } } @@ -200,8 +228,14 @@ public void DataNamed(string name, int value) public int PendingInput { get { - var handle = _handle; - return handle == IntPtr.Zero ? 0 : DofNative.PendingInput(handle); + if (!Enter()) { + return 0; + } + try { + return DofNative.PendingInput(_dof); + } finally { + Leave(); + } } } @@ -209,7 +243,13 @@ public int PendingInput public void Finish() { var error = new byte[ErrorSize]; - var status = DofNative.Finish(Handle, error, error.Length); + EnterOrThrow(); + int status; + try { + status = DofNative.Finish(_dof, error, error.Length); + } finally { + Leave(); + } DofException.ThrowIfFailed(status, "Finishing DOF", Utf8.DecodeBuffer(error)); } @@ -228,8 +268,14 @@ public void Finish() /// public long SetOutputGate(bool open) { - var handle = _handle; - return handle == IntPtr.Zero ? -1 : DofNative.SetOutputGate(handle, open ? 1 : 0); + if (!Enter()) { + return -1; + } + try { + return DofNative.SetOutputGate(_dof, open ? 1 : 0); + } finally { + Leave(); + } } /// @@ -240,7 +286,17 @@ public long SetOutputGate(bool open) /// light its whole strip. Call before to cover the controllers it connects. Every new /// instance allows them. /// - public void SetConnectTests(bool allowed) => DofException.ThrowIfFailed(DofNative.SetConnectTests(Handle, allowed ? 1 : 0), "Setting DOF's connect tests"); + public void SetConnectTests(bool allowed) + { + EnterOrThrow(); + int status; + try { + status = DofNative.SetConnectTests(_dof, allowed ? 1 : 0); + } finally { + Leave(); + } + DofException.ThrowIfFailed(status, "Setting DOF's connect tests"); + } /// /// Any thread, in any state until disposed: closes the output gate at once and latches it closed for the rest of @@ -254,28 +310,45 @@ public long SetOutputGate(bool open) /// write to the device (each report, packet, command or retry), and then sends the closing to every output. A /// write that was already past that check when the latch came can still reach the device after the latch returned: /// at most that one write per controller, followed by the closing. Nothing else of the opening goes out. Takes no - /// lock and never allocates, so the simulation thread or a fault handler may call it. Once it returned, the gate + /// lock and never allocates, so the simulation thread or a fault handler may call it (the last call to return while + /// a Dispose waits for the calls takes its lock to wake it). Once it returned, the gate /// reports closed, also to an opening DOF's main thread is applying at that moment. It never reaches a later /// instance's gate. /// /// The closing's generation, or -1 after . public long LatchOutputGate() { - var handle = _handle; - return handle == IntPtr.Zero ? -1 : DofNative.LatchOutputGate(handle); + if (!Enter()) { + return -1; + } + try { + return DofNative.LatchOutputGate(_dof); + } finally { + Leave(); + } } public DofGateState GetGateState(long generation) { - var status = DofNative.GateState(Handle, generation, out var written, out var pending, out var failed, out var untouched); + EnterOrThrow(); + int status, written, pending, failed, untouched; + try { + status = DofNative.GateState(_dof, generation, out written, out pending, out failed, out untouched); + } finally { + Leave(); + } return new DofGateState(status == 1, written, pending, failed, status == 2, untouched); } /// The names of the controller units that have not written yet, or failed. public IReadOnlyList GetGatePending(long generation) { - var handle = Handle; - return StringCollector.Collect(user => DofNative.GatePending(handle, generation, StringCollector.Callback, user), out _); + EnterOrThrow(); + try { + return StringCollector.Collect(user => DofNative.GatePending(_dof, generation, StringCollector.Callback, user), out _); + } finally { + Leave(); + } } /// @@ -286,13 +359,27 @@ public IReadOnlyList GetGatePending(long generation) /// if the device or port does not exist or the port names a toy instead of /// a controller output; before init or after finish. /// - public DofStatus TestOutput(int device, int port, int value) => (DofStatus)DofNative.TestOutput(Handle, device, port, value); + public DofStatus TestOutput(int device, int port, int value) + { + EnterOrThrow(); + try { + return (DofStatus)DofNative.TestOutput(_dof, device, port, value); + } finally { + Leave(); + } + } /// The output controllers and toys, after . public DofCabinetDescription Describe() { - var handle = Handle; - var lines = StringCollector.Collect(user => DofNative.Describe(handle, StringCollector.Callback, user), out var status); + IReadOnlyList lines; + int status; + EnterOrThrow(); + try { + lines = StringCollector.Collect(user => DofNative.Describe(_dof, StringCollector.Callback, user), out status); + } finally { + Leave(); + } DofException.ThrowIfFailed(status, "Describing the DOF cabinet"); var controllers = new List(); var toys = new List(); @@ -307,24 +394,69 @@ public DofCabinetDescription Describe() return new DofCabinetDescription(controllers, toys); } - /// Frees the instance, finishing it first if needed, so a new one can be created. + /// + /// Frees the instance, finishing it first if needed, so a new one can be created. Stops admitting calls, waits for + /// the admitted ones to return (a running too), destroys the instance on this thread and + /// returns. A Dispose while another one runs returns once that one destroyed the instance. + /// public void Dispose() { - var handle = _handle; - _handle = IntPtr.Zero; - if (handle != IntPtr.Zero) { - DofNative.Destroy(handle); + if (Interlocked.CompareExchange(ref _state, Disposing, Alive) != Alive) { + lock (_disposeLock) { + while (Volatile.Read(ref _state) != Destroyed) { + Monitor.Wait(_disposeLock); + } + } + return; + } + lock (_disposeLock) { + while (Volatile.Read(ref _calls) != 0) { + Monitor.Wait(_disposeLock); + } + } + try { + DofNative.Destroy(_dof); + } finally { + lock (_disposeLock) { + Volatile.Write(ref _state, Destroyed); + Monitor.PulseAll(_disposeLock); + } } } - private IntPtr Handle + /// + /// Admits a call into libdof, or returns false once Dispose started. No allocation, no lock: an interlocked count + /// that Dispose drains before it destroys the instance. + /// + private bool Enter() { - get { - var handle = _handle; - if (handle == IntPtr.Zero) { - throw new ObjectDisposedException(nameof(DofInstance)); + // Once disposing, callers that keep calling do not touch the count, so they never hold the drain up. + if (Volatile.Read(ref _state) != Alive) { + return false; + } + Interlocked.Increment(ref _calls); + // Checked again after the count, both full fences: either Dispose sees this call, or this call sees Dispose. + if (Volatile.Read(ref _state) != Alive) { + Leave(); + return false; + } + return true; + } + + private void EnterOrThrow() + { + if (!Enter()) { + throw new ObjectDisposedException(nameof(DofInstance)); + } + } + + /// Ends an admitted call; the last one to return while Dispose waits wakes it. + private void Leave() + { + if (Interlocked.Decrement(ref _calls) == 0 && Volatile.Read(ref _state) == Disposing) { + lock (_disposeLock) { + Monitor.PulseAll(_disposeLock); } - return handle; } } }