Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 100 additions & 1 deletion VisualPinball.Engine.DOF.Test/DofInstanceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ private void BoundedCleanup(DofInstance dof)
[Test]
public void ReportsAbiAndLibdofVersion()
{
Assert.That(DofLibrary.NativeAbiVersion, Is.EqualTo(8));
Assert.That(DofLibrary.NativeAbiVersion, Is.EqualTo(9));
Assert.That(DofLibrary.LibdofVersion, Does.Match(@"^\d+\.\d+\.\d+"));
}

Expand Down Expand Up @@ -474,6 +474,105 @@ public void PortTestGoesThroughTheGate()
dof.Finish();
}

[Test]
public void PortTestLightsTheToyAPortNames()
{
var unit = Unit("ArtNetA");
var strip = Unit("ArtNetStrip");
strip.Ports = false;
// Port 9 names an LED strip of 4 x 2 LEDs on a controller of its own, port 10 the equivalent itself, which no test
// lights. Entries numbered 0, as one without a number is, and -1 are no ports, though they name the strip and an output.
var ports = new Dictionary<int, string> { [9] = "Matrix1", [10] = "LedWizEquivalent 1", [0] = "Matrix1", [-1] = "ArtNetA.03" };
using var config = new TestConfig().GlobalConfig().Cabinet(8, ports, TestConfig.LedStrip("Matrix1", strip, 4, 2), unit, strip);
using var dof = DofInstance.Create(config.Root);
// as the port test runs DOF: dark, without connect tests and without a table
dof.SetOutputGate(false);
dof.SetConnectTests(false);
dof.Init(null, null);
var cabinet = dof.Describe();
Assert.That(cabinet.Devices.Single().KindOf(9), Is.EqualTo(DofPortKind.Toy));
Assert.That(cabinet.Toys.Select(t => (t.Type, t.Name)), Does.Contain(("LedStrip", "Matrix1")));

Assert.That(dof.TestToy(1, 9, 255, out var toy), Is.EqualTo(DofStatus.Ok));
Assert.That((toy.Type, toy.Name), Is.EqualTo(("LedStrip", "Matrix1")));
// DOF's main thread runs the test before a closing requested after it
WaitSettled(dof, dof.SetOutputGate(false));
ExpectFrameAfter(strip.Universe, 0, "a frame of the strip while closed");
var opening = _capture.Mark(strip.Universe);
Assert.That(FramesBetween(strip.Universe, 0, opening).All(f => f.All(v => v == 0)), Is.True, "the strip stays dark while the gate is closed");

Assert.That(WaitSettled(dof, dof.SetOutputGate(true)).Written, Is.GreaterThanOrEqualTo(1));
var lit = ExpectIndex(strip.Universe, f => f.Take(24).All(v => v == 64), "every LED of the strip in dim white", opening);
Assert.That(_capture.Frames(strip.Universe)[lit].Skip(24).All(v => v == 0), Is.True, "nothing past the strip's LEDs");
Assert.That(_capture.Frames(unit.Universe).All(f => f.Take(8).All(v => v == 0)), Is.True, "no controller output");

WaitSettled(dof, dof.SetOutputGate(false));
ExpectIndex(strip.Universe, f => f.All(v => v == 0), "the strip dark once the gate closed", lit + 1);
Assert.That(dof.TestToy(1, 9, 0, out _), Is.EqualTo(DofStatus.Ok));
// cleared before the gate opens again: the strip shows nothing
WaitSettled(dof, dof.SetOutputGate(true));
var cleared = _capture.Mark(strip.Universe);
ExpectFrameAfter(strip.Universe, cleared, "a frame of the strip after it was cleared");
Assert.That(FramesBetween(strip.Universe, cleared).All(f => f.All(v => v == 0)), Is.True, "a cleared strip is dark");

Assert.That(dof.TestToy(1, 10, 255, out toy), Is.EqualTo(DofStatus.NotSupported), "a toy a test can't light");
Assert.That((toy.Type, toy.Name), Is.EqualTo(("LedWizEquivalent", "LedWizEquivalent 1")));
Assert.That(dof.TestToy(1, 1, 255, out toy), Is.EqualTo(DofStatus.InvalidArgument), "a port that drives a controller output");
Assert.That(toy.Name, Is.Null);
Assert.That(dof.TestToy(1, 99, 255, out _), Is.EqualTo(DofStatus.InvalidArgument), "unknown port");
Assert.That(dof.TestToy(2, 9, 255, out _), Is.EqualTo(DofStatus.InvalidArgument), "unknown device");
Assert.That(dof.TestOutput(1, 9, 255), Is.EqualTo(DofStatus.InvalidArgument), "the output test doesn't set a toy");
Assert.That(dof.TestToy(1, 0, 255, out toy), Is.EqualTo(DofStatus.InvalidArgument), "port 0");
Assert.That(toy.Name, Is.Null);
Assert.That(dof.TestOutput(1, 0, 255), Is.EqualTo(DofStatus.InvalidArgument), "port 0 of the output test");
Assert.That(dof.TestOutput(1, -1, 255), Is.EqualTo(DofStatus.InvalidArgument), "a negative port of the output test");
Assert.That(dof.Describe().Devices.Single().Count, Is.EqualTo(10), "the description starts at port 1");
dof.Finish();
Assert.That(dof.TestToy(1, 9, 255, out _), Is.EqualTo(DofStatus.InvalidState), "after finish");
}

[Test]
public void PortTestKeepsTheStripsFadingCurve()
{
// An inverted curve is for LEDs that light at low values: the dim white of the test is 191 there, and off is 255.
var strip = Unit("ArtNetStrip");
strip.Ports = false;
using var config = new TestConfig().GlobalConfig()
.Cabinet(8, new Dictionary<int, string> { [1] = "Matrix1" }, TestConfig.LedStrip("Matrix1", strip, 2, 1, "InvertedLinear"), strip);
using var dof = DofInstance.Create(config.Root);
dof.SetOutputGate(false);
dof.SetConnectTests(false);
dof.Init(null, null);
Assert.That(dof.TestToy(1, 1, 255, out _), Is.EqualTo(DofStatus.Ok));
var opening = _capture.Mark(strip.Universe);
WaitSettled(dof, dof.SetOutputGate(true));
var lit = ExpectIndex(strip.Universe, f => f.Take(6).All(v => v == 191), "the strip's dim white through the inverted curve", opening);

WaitSettled(dof, dof.SetOutputGate(false));
Assert.That(dof.TestToy(1, 1, 0, out _), Is.EqualTo(DofStatus.Ok));
WaitSettled(dof, dof.SetOutputGate(true));
var cleared = _capture.Mark(strip.Universe);
ExpectFrameAfter(strip.Universe, Math.Max(cleared, lit + 1), "a frame of the strip after it was cleared");
Assert.That(FramesBetween(strip.Universe, cleared).All(f => f.Take(6).All(v => v == 255)), Is.True, "cleared, the strip sends the curve's off");
dof.Finish();
}

[Test]
public void ToyTestRefusesAGame()
{
// A table's effects could use the test's layer: a game instance takes no toy test.
var unit = Unit("ArtNetA");
var strip = Unit("ArtNetStrip");
strip.Ports = false;
using var config = new TestConfig().GlobalConfig()
.Cabinet(8, new Dictionary<int, string> { [9] = "Matrix1" }, TestConfig.LedStrip("Matrix1", strip, 4, 2), unit, strip).Ini(1, "vpetest,S1");
using var dof = Start(config);
Assert.That(dof.Describe().Devices.Single().KindOf(9), Is.EqualTo(DofPortKind.Toy));
Assert.That(dof.TestToy(1, 9, 255, out var toy), Is.EqualTo(DofStatus.InvalidState));
Assert.That(toy.Name, Is.Null);
dof.Finish();
}

[Test]
public void OnlyOneInstanceAtATime()
{
Expand Down
20 changes: 18 additions & 2 deletions VisualPinball.Engine.DOF.Test/TestConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace VisualPinball.Engine.DOF.Test
Expand All @@ -16,6 +17,8 @@ public sealed class ArtNetUnit
public string Name;
public int Universe;
public string Address = "127.0.0.1";
/// <summary>Whether ports of the LedWiz equivalent drive its channels; not for one only a toy uses, such as an LED strip.</summary>
public bool Ports = true;
}

/// <summary>
Expand Down Expand Up @@ -64,7 +67,10 @@ public TestConfig GlobalConfig(string tableConfigPattern = null, string logPatte
/// </summary>
public TestConfig Cabinet(int perUnit, params ArtNetUnit[] units) => Cabinet(perUnit, null, units);

public TestConfig Cabinet(int perUnit, IDictionary<int, string> extraPorts, params ArtNetUnit[] units)
public TestConfig Cabinet(int perUnit, IDictionary<int, string> extraPorts, params ArtNetUnit[] units) => Cabinet(perUnit, extraPorts, null, units);

/// <param name="extraToys">More toys, as cabinet XML elements (<see cref="LedStrip"/>), after the equivalent.</param>
public TestConfig Cabinet(int perUnit, IDictionary<int, string> extraPorts, string extraToys, params ArtNetUnit[] units)
{
var xml = new StringBuilder();
xml.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
Expand All @@ -82,7 +88,7 @@ public TestConfig Cabinet(int perUnit, IDictionary<int, string> extraPorts, para
xml.AppendLine(" <LedWizNumber>1</LedWizNumber>");
xml.AppendLine(" <Outputs>");
var port = 1;
foreach (var unit in units) {
foreach (var unit in units.Where(u => u.Ports)) {
for (var channel = 1; channel <= perUnit; channel++, port++) {
xml.AppendLine($" <LedWizEquivalentOutput><OutputName>{unit.Name}.{channel:00}</OutputName><LedWizEquivalentOutputNumber>{port}</LedWizEquivalentOutputNumber></LedWizEquivalentOutput>");
}
Expand All @@ -94,11 +100,21 @@ public TestConfig Cabinet(int perUnit, IDictionary<int, string> extraPorts, para
}
xml.AppendLine(" </Outputs>");
xml.AppendLine(" </LedWizEquivalent>");
if (extraToys != null) {
xml.AppendLine(extraToys);
}
xml.AppendLine(" </Toys>");
xml.AppendLine("</Cabinet>");
return Write("Cabinet.xml", xml.ToString());
}

/// <summary>An LED strip of a cabinet, in RGB order, whose LEDs are the first channels of an Art-Net controller.</summary>
/// <param name="fadingCurve">Its fading curve, such as InvertedLinear; libdof's default (Linear) if null.</param>
public static string LedStrip(string name, ArtNetUnit unit, int width, int height, string fadingCurve = null)
=> $" <LedStrip><Name>{name}</Name><Width>{width}</Width><Height>{height}</Height><FirstLedNumber>1</FirstLedNumber>"
+ $"<ColorOrder>RGB</ColorOrder><OutputControllerName>{unit.Name}</OutputControllerName>"
+ (fadingCurve == null ? "" : $"<FadingCurveName>{fadingCurve}</FadingCurveName>") + "</LedStrip>";

/// <summary>An ini file (directoutputconfig.ini for device 1, directoutputconfigN.ini otherwise) with table rows.</summary>
public TestConfig Ini(int device, params string[] rows) => Write(device == 1 ? "directoutputconfig.ini" : $"directoutputconfig{device}.ini", IniText(rows));

Expand Down
80 changes: 66 additions & 14 deletions VisualPinball.Engine.DOF.Unity/Runtime/Player/DofHardware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
Expand Down Expand Up @@ -113,7 +114,7 @@ internal static bool TryParse(string id, out int device, out int port)
internal static string Id(int device, int port) => device + ":" + port;

/// <summary>
/// Opens DOF dark and waits until every unit confirmed it, sets the port, opens the gate for
/// Opens DOF dark and waits until every unit confirmed it, sets the port (or lights the toy it names), opens the gate for
/// <paramref name="duration"/> and closes it again before the port is turned off and DOF finishes. Runs on the
/// calling thread and blocks; call it from a worker.
/// </summary>
Expand All @@ -137,24 +138,30 @@ internal static (bool Success, string Message) Pulse(DofConfigStore store, Plugi
return (false, Cancelled);
}
if (!dark.Applied || dark.State.Pending > 0) {
return (false, $"{Units(dark.Units, "DOF")} did not confirm within {confirmTimeout.TotalSeconds:0.#} s that {Their(dark.Units)} outputs "
return (false, $"{Units(dark.Units, "DOF")} did not confirm within {Seconds(confirmTimeout, "0.#")} s that {Their(dark.Units)} outputs "
+ "are off, so nothing was turned on: a controller that is still connecting could run its own test.");
}
var devices = Devices(native);
if (dark.State.Written == 0) {
// most likely the board of the device isn't there; DOF says so before the gate would open
var devices = Devices(native);
if (devices != null && !devices.Any(d => d.Number == device)) {
return (false, NotSettable(devices, dark.HasCabinet, device, port, output));
}
return (false, dark.State.Failed > 0
? $"No controller can send the pulse: {Units(dark.Units, "every controller")} failed, so nothing was turned on."
: "No controller took part, so nothing was turned on.");
}
var status = native.TestOutput(device, port, 255);
// A port that names a toy, such as an LED strip, lights the toy instead of a controller output.
var isToy = devices != null && devices.Any(d => d.Number == device && d.KindOf(port) == DofPortKind.Toy);
DofToy toy = default;
var status = isToy ? native.TestToy(device, port, 255, out toy) : native.TestOutput(device, port, 255);
if (status != DofStatus.Ok) {
if (status == DofStatus.NotSupported) {
return (false, $"On device {device}, {What(port, output)} names {ToyName(toy)}, which a test can't light.");
}
return (false, status == DofStatus.InvalidArgument
? NotSettable(Devices(native), dark.HasCabinet, device, port, output)
: $"DOF could not set output {output} of device {device} ({status}).");
? NotSettable(devices, dark.HasCabinet, device, port, output)
: $"DOF could not {(isToy ? "light the toy on" : "set")} output {output} of device {device} ({status}).");
}
if (cancellation.IsCancellationRequested) {
return (false, Cancelled);
Expand All @@ -164,18 +171,33 @@ internal static (bool Success, string Message) Pulse(DofConfigStore store, Plugi
var cancelled = cancellation.WaitHandle.WaitOne(duration);
native.SetOutputGate(false);
var open = watch.Elapsed;
native.TestOutput(device, port, 0);
if (isToy) {
native.TestToy(device, port, 0, out _);
} else {
native.TestOutput(device, port, 0);
}
// The units that wrote the opening. Which of them drives the tested port is not known, so this counts the
// controllers that wrote the open gate, not that the port got the pulse; and a write can land after the count.
var wrote = opening >= 0 ? native.GetGateState(opening).Written : 0;
var failed = dark.State.Failed > 0 ? $" {Units(dark.Units, "A controller")} failed and took no part." : string.Empty;
// The times are the gate's, as requested: a controller writes the opening a little later and, when the
// gate closes early, maybe not at all.
if (isToy) {
var lit = $"{ToyName(toy)} on output {output} of device {device}";
if (cancelled) {
return (false, $"Cancelled after {Seconds(open)} s: {lit} was to be lit for {Seconds(duration)} s.{failed}");
}
// as for a port: which controller drives the toy is not known, so this counts every one that wrote the opening
var requestedLight = $"Requested to light {lit} for {Seconds(duration)} s";
return wrote > 0
? (true, $"{requestedLight}: {Controllers(wrote)} acknowledged the gate opening. Delivery to the toy is unconfirmed.{failed}")
: (false, $"{requestedLight}, but no controller confirmed writing it.{failed}");
}
if (cancelled) {
return (false, $"Cancelled after {open.TotalSeconds:0.##} s: the pulse to output {output} of device {device} was requested for "
+ $"{duration.TotalSeconds:0.##} s.{failed}");
return (false, $"Cancelled after {Seconds(open)} s: the pulse to output {output} of device {device} was requested for "
+ $"{Seconds(duration)} s.{failed}");
}
var requested = $"Requested a pulse of {duration.TotalSeconds:0.##} s on output {output} of device {device}";
var requested = $"Requested a pulse of {Seconds(duration)} s on output {output} of device {device}";
return wrote > 0
? (true, $"{requested}: {Controllers(wrote)} acknowledged the gate opening. Delivery to the selected port is unconfirmed.{failed}")
: (false, $"{requested}, but no controller confirmed writing it.{failed}");
Expand All @@ -184,6 +206,33 @@ internal static (bool Success, string Message) Pulse(DofConfigStore store, Plugi

private const string Cancelled = "Cancelled; nothing was turned on.";

// The messages are English: seconds with a decimal point, whatever the culture.
private static string Seconds(TimeSpan time, string format = "0.##") => time.TotalSeconds.ToString(format, CultureInfo.InvariantCulture);

/// <summary>A toy for a message, by its kind and name: "LED strip Matrix1".</summary>
internal static string ToyName(DofToy toy)
{
string kind;
switch (toy.Type) {
case "LedStrip": kind = "LED strip"; break;
case "RGBLed": kind = "RGB LED"; break;
case "RGBAToy": kind = "RGB toy"; break;
case "RGBAToyGroup": kind = "group of RGB toys"; break;
case "Lamp": kind = "lamp"; break;
case "Motor": kind = "motor"; break;
case "GearMotor": kind = "gear motor"; break;
case "Shaker": kind = "shaker"; break;
case "AnalogAlphaToyGroup": kind = "group of toys"; break;
case null:
case "":
case "AnalogAlphaToy": kind = "toy"; break;
default: kind = toy.Type; break;
}
return string.IsNullOrEmpty(toy.Name) ? kind : $"{kind} {toy.Name}";
}

private static string What(int port, int output) => output == port ? $"output {output}" : $"port {port} (wired to output {output})";

private static IReadOnlyList<DofDevicePorts> Devices(IDofTestNative native)
{
try {
Expand All @@ -194,14 +243,14 @@ private static IReadOnlyList<DofDevicePorts> Devices(IDofTestNative native)
}

/// <summary>
/// Why DOF can't set a port: it has no such device, the device has fewer ports, or the port drives a toy or nothing.
/// Why DOF can't set a port: it has no such device, the device has fewer ports, or the port drives nothing.
/// </summary>
/// <param name="devices">The devices DOF set up; null if unknown.</param>
/// <param name="hasCabinet">Whether the configuration has a cabinet file, which sets up the devices.</param>
/// <param name="output">The output the port drives, as the page shows it.</param>
internal static string NotSettable(IReadOnlyList<DofDevicePorts> devices, bool hasCabinet, int device, int port, int output)
{
var what = output == port ? $"output {output}" : $"port {port} (wired to output {output})";
var what = What(port, output);
if (devices == null) {
return $"Device {device} has no {what} DOF can set.";
}
Expand All @@ -227,7 +276,7 @@ internal static string NotSettable(IReadOnlyList<DofDevicePorts> devices, bool h
return $"Device {device} goes up to {(output == port ? "output" : "port")} {ports.Value.Count}, so there is no {what}. A game can't fire it either.";
}
return ports.Value.KindOf(port) == DofPortKind.Toy
? $"On device {device}, {what} names a toy, such as an LED strip, which a test can't turn on directly."
? $"On device {device}, {what} names a toy DOF can't find."
: $"On device {device}, {what} is connected to no controller output. A game can't fire it either.";
}

Expand Down Expand Up @@ -260,7 +309,7 @@ internal static (bool Success, string Message) AllOff(DofConfigStore store, Plug
}
string what;
if (!dark.Applied || dark.State.Failed == 0) {
what = $"did not confirm within {confirmTimeout.TotalSeconds:0.#} s that {Their(dark.Units)} outputs are off";
what = $"did not confirm within {Seconds(confirmTimeout, "0.#")} s that {Their(dark.Units)} outputs are off";
} else if (dark.State.Pending == 0) {
what = "failed";
} else {
Expand Down Expand Up @@ -433,6 +482,8 @@ internal interface IDofTestNative : IDisposable
DofGateState GetGateState(long generation);
IReadOnlyList<string> GetGatePending(long generation);
DofStatus TestOutput(int device, int port, int value);
/// <summary>Lights the toy a port names (<see cref="DofInstance.TestToy"/>), and clears it with 0.</summary>
DofStatus TestToy(int device, int port, int value, out DofToy toy);
void Finish();
}

Expand All @@ -450,6 +501,7 @@ internal sealed class DofTestInstance : IDofTestNative
public DofGateState GetGateState(long generation) => _instance.GetGateState(generation);
public IReadOnlyList<string> GetGatePending(long generation) => _instance.GetGatePending(generation);
public DofStatus TestOutput(int device, int port, int value) => _instance.TestOutput(device, port, value);
public DofStatus TestToy(int device, int port, int value, out DofToy toy) => _instance.TestToy(device, port, value, out toy);
public void Finish() => _instance.Finish();
public void Dispose() => _instance.Dispose();
}
Expand Down
Loading
Loading