Skip to content

.NET client library

The TriggerGate client library connects a .NET 11 application to a TriggerGate hub on a Windows service, an Advantech UNO or an ESP32 board. It keeps the connection up, maps the hub's inputs to your application's own trigger keys, raises an event when one fires, and wraps every hub command in a typed method: faceoffs and pre-faceoff lockouts, trigger actions, configuration, clock information and diagnostics. The Windows package adds WPF templates for a settings row (with the platform and device selector), a device header, a commands row and a compact monitor row. This page is for developers of show applications; the protocol underneath is described in Hub API.

Packages

Package Target Use it for
GameshowPro.TriggerGate.Client net11.0 Any .NET 11 application, on any operating system. No user interface.
GameshowPro.TriggerGate.Client.Windows net11.0-windows A WPF application. The same client, plus the templates described in WPF templates.

Each package brings the matching contract package (GameshowPro.TriggerGate.Common or GameshowPro.TriggerGate.Common.Windows), which holds the request, response and report types the hub uses, and with it GameshowPro.Common, GameshowPro.Mdns, GameshowPro.Osc and the SignalR client with its MessagePack protocol.

TriggerGate is in pre-release and the packages are supplied on request: get in touch.

Define your triggers

An application names its triggers with an enum. Each member is one trigger: give it a TriggerParameters attribute with a display name and a filter, and, to map it to an input by default, a TriggerDefaultSpecification for each client index that should have it.

using GameshowPro.Common.Model;
using GameshowPro.TriggerGate.Client;

public enum Buzzer
{
    [TriggerParameters("Red", TriggerFilter.FirstOnly), TriggerDefaultSpecification<TriggerClient<Buzzer>>(0, 0)]
    Red,
    [TriggerParameters("Blue", TriggerFilter.FirstOnly), TriggerDefaultSpecification<TriggerClient<Buzzer>>(0, 1)]
    Blue,
    [TriggerParameters("Reset", TriggerFilter.All), TriggerDefaultSpecification<TriggerClient<Buzzer>>(0, 7)]
    Reset,
}

TriggerDefaultSpecification<TriggerClient<Buzzer>>(0, 7) maps Reset to input 7 on the client with index 0. A member with no default for a client starts disabled there until it is given an input. Each trigger's Setting holds what the user can change, and what your application saves in Settings.TriggerSettings:

Setting member Meaning
Id The input index on the hub, 0-based.
TriggerEdge true (the default) to fire when the input goes active (the button going down), false when it is released.
IsEnabled A disabled trigger never fires and is left out of faceoffs started by key.
TriggerFilter Set by the attribute. All fires on every press. FirstOnly fires only when the input wins a faceoff (its entry is 1st). None never fires.

Connect

Create one TriggerClient<TTriggerKey> per TriggerGate, with its settings and a logger factory. GameshowPro.Common's property change filters need a logger factory assigned once per process, before the first client is created; a GameshowPro host application usually does this already.

using GameshowPro.Common.Model;
using GameshowPro.TriggerGate.Client;
using Settings = GameshowPro.TriggerGate.Client.Settings;

PropertyChangeFilters.AssignLoggerFactory(loggerFactory);
Settings settings = new() { Host = "studio-pc" };
TriggerClient<Buzzer> client = new(0, settings, loggerFactory, cancellationToken);

For several TriggerGates, TriggerClient<Buzzer>.GetDevices(settingsList, loggerFactory, cancellationToken) creates one client per settings object, with indexes 0, 1 and so on, in an IncomingTriggerDevices collection whose Items are the clients. Cancel the token to stop them.

What the client does:

  • It connects to http://<Host>:9090/TriggerGate with SignalR's MessagePack protocol. Settings.Host is a host name or an IP address, without a port. When it is blank or not a valid host name, the client does not connect and IsConfigured is false.
  • It keeps trying until the hub answers, and reconnects by itself, once a second, whenever the connection drops. Changing Host, Platform or DeviceIndex closes the connection and opens a new one.
  • Each time it opens a connection it reads the hub's configuration, then sends its own status output and OSC defaults (see Configuration).
  • Every command returns a TriggerCommandResponse<T> with Success, StatusDescription and Payload. A command never throws for a server-side problem: when the client is not connected, when the hub refuses, when the hub does not know the command (a server without that command), or when no answer comes within 5 seconds, the response has Success false and the reason in StatusDescription.

ServiceState shows the client's health as a tree with three entries: "Connection to TriggerGate", "GPIO System" (the state the hub reports for its device) and "Clock" (the server's clock). The overall state combines the first two only; the clock entry is information. ServerInformation gives the server's Version, BuildDate, TriggerGatePlatform and HostName while connected, and is null otherwise.

Find TriggerGates on the network

Windows services, UNOs and ESP32 boards advertise their hub over mDNS as _gp-triggergate._tcp. Give the application's GameshowPro.Mdns ServiceFinder the profile TriggerGateDiscovery.s_mdnsSearchProfile, along with any other profiles it searches for, and pass the finder to the client:

using GameshowPro.Mdns;

ServiceFinder finder = new([TriggerGateDiscovery.s_mdnsSearchProfile], logger, cancellationToken);
TriggerClient<Buzzer> client = new(0, settings, finder, loggerFactory, cancellationToken);

GetDevices has the same overload with a finder. The client then exposes the discovered services as ServicesMonitor; in the WPF settings row this is the find button beside the host box, and choosing a service there sets Settings.Host. Without a finder, ServicesMonitor is null and the button is not shown.

Choose a platform and a device

A Windows service can run X-keys and Advantech at once, and drive several X-keys devices. A connection is bound to one platform and one device for its lifetime. Platforms and devices explains the choices; the client exposes them like this:

Member Meaning
Settings.Platform The platform to bind to. Null (the default) lets the server choose.
Settings.DeviceIndex The device on that platform, 0-based. Null (the default) means index 0.
AvailablePlatforms Every platform the server runs.
AvailableDevices Every device the server offers, as PlatformDevice entries (Platform, Index, Name, ProductId, SortKey, IsPresent). Updated without reconnecting when a device is plugged in or removed.
BoundPlatform, BoundDeviceIndex What this connection is bound to. Null while not connected, and when the requested platform or device is not available.
TargetOptions One list of choices built from the two lists: one per platform with a single device ("Advantech"), one per device otherwise ("X-keys: XK-24"). Each TargetOption has a Label, Platform, DeviceIndex and IsPresent.
SelectedTarget, SelectTarget(option) The choice the connection is bound to; selecting another sets Platform and DeviceIndex together and reconnects once.

Show the list only when TargetOptions.ShowChoice(client.TargetOptions.Length) is true, that is, when there is more than one choice. The lists are kept while the connection is down and cleared when Host changes.

If the requested platform or device is not available, the hub still accepts the connection: "GPIO System" is disconnected with a message that says why, no edges arrive, and every command fails with the same message. The ESP32 firmware has one platform and one device; it sends no lists, so AvailablePlatforms, AvailableDevices and TargetOptions stay empty and BoundPlatform is Esp32.

Receive triggers

client.Triggers holds one TriggerGateIncomingTrigger per enum member. Subscribe to its Triggered event:

TriggerGateIncomingTrigger red = client.Triggers[Buzzer.Red];
red.Triggered += (_, _) => Console.WriteLine($"Red: place {red.Ordinal + 1}, {red.Time}, tied {red.IsTied}");

The client raises Triggered on a thread-pool thread, as soon as the report arrives. Keep handlers short and dispatch user-interface work to the UI thread.

Trigger member Meaning
IsDown The input's current level, from the polled reports. Also follows level updates that carry no edge.
Ordinal The trigger's place in the current faceoff, as a zero-based number: 0 for the winner (1st), 1 for 2nd, and so on. Null or negative when it has no place.
Time Its faceoff time: how long after the faceoff started its entry came.
IsTied True when another input has the same faceoff time, which is how the server marks a tie whose order it chose at random. Set when the partner's report arrives.
IsTest True when the last report was a test edge from TriggerRandom.
MonotonicTime, AbsoluteTime The last report's own time on the server's monotonic clock and wall clock (UTC). Null when the server did not send one. See Clocks and time.
LastTriggerDateTime When the trigger last fired, on this computer's clock.
LastLockoutDateTime When a qualifying press started or restarted a pre-faceoff or carried faceoff lockout, on this computer's clock. A locked-out press does not fire the trigger.

On an input that raises interrupts, the hub reports each change twice, once by interrupt and once by polling. The client fires from the interrupt report on the inputs in InterruptInputs (those the server always reports by interrupt) and from the polled report on every other input, so a trigger never fires twice for one press. Test edges always fire.

Faceoffs

A faceoff decides which of its inputs was first. Start one with the keys of the triggers taking part, and end it with no keys:

await client.ResetFaceoff([Buzzer.Red, Buzzer.Blue]);   // start
await client.ResetFaceoff();                            // end

Each participant's first edge arrives with its Ordinal (its place) and Time, a FirstOnly trigger fires for the winner, and IsTied marks a tie. How the server decides the order, and what a tie means, is in Triggers and faceoffs.

Overload Returns
ResetFaceoff(IEnumerable<TTriggerKey>? keys) Task. Disabled triggers are left out; null ends the faceoff.
ResetFaceoff(IEnumerable<TriggerGateIncomingTrigger>? inputs) Task.
ResetFaceoff(IEnumerable<TriggerDefinition>? inputs, bool? usePolling = null) The response. A TriggerDefinition is an input index and whether its rising edge counts.
ResetFaceoff(keys, IDictionary<TTriggerKey, TriggerActionsByResult>? triggerActions) The response. See Trigger actions.
ResetFaceoff(inputs, IDictionary<int, TriggerActionsByResult>? triggerActions, bool? usePolling = null) The response.
ResetFaceoff() Task. Ends the faceoff.
ResetFaceoff(ResetFaceoffRequest request) The response, for a request you build yourself.

The response's payload is a ResetFaceoffResponse. When a participant is already at its active level (a button held down), the hub refuses the request and changes nothing; HeldInputs lists those inputs. Use a response-returning overload and check Success before advancing your show's state; completing a Task-only convenience call does not mean the server accepted the request:

TriggerCommandResponse<ResetFaceoffResponse> response = await client.ResetFaceoff(
    [new TriggerDefinition(0, true), new TriggerDefinition(1, true)]);
if (!response.Success)
{
    Console.WriteLine($"Refused: {response.StatusDescription}; held: {string.Join(", ", response.Payload?.HeldInputs ?? [])}");
}

The built-in WPF commands show faceoff and pre-faceoff failures through the bindable ArmingFailure property, including held inputs. This also covers calls through the convenience methods. A successful retry clears the message; it is separate from connection health.

When a faceoff ends, the client raises FaceoffHealthReported with a FaceoffHealthReport: how much stray activity each input produced while it ran (see Input diagnostics). FaceoffCancelled is raised with a FaceoffCancellation (Reason, Generation) when the server cancels a faceoff itself, for example because input events were lost.

Pre-faceoff lockouts

Before a faceoff starts, a pre-faceoff locks out any participant that presses early. A qualifying press starts or restarts that input's full lockout duration, and a faceoff started while an input is locked out carries the lockout into it. A qualifying press while still locked out in the faceoff restarts the duration and reports the full new value. A press less than 200 ms after that input's last detected change in either direction is ignored before it can restart the lockout; the change still updates debounce history. Releases never restart a lockout.

await client.PrepareFaceoff([Buzzer.Red, Buzzer.Blue], TimeSpan.FromSeconds(0.25));

The overloads mirror ResetFaceoff: by keys, by TriggerGateIncomingTrigger, by TriggerDefinition with an optional usePolling (returning a PrepareFaceoffResponse, which also has HeldInputs), and with a PrepareFaceoffRequest. Null inputs end the pre-faceoff. A qualifying press during a lockout arrives as an edge carrying the renewed full duration; it updates the trigger's LastLockoutDateTime and does not fire it.

Interrupt or polled edges

On an Advantech card, an input can be reported by hardware interrupt as well as by polling, and a faceoff or pre-faceoff is decided by one kind or the other. The choice is always explicit: the hub refuses a request its inputs cannot meet, and never quietly uses the other kind.

Member Meaning
Settings.FaceoffsUsePolling false (the default) asks for interrupt edges; true asks for polled edges. Used by every overload without a usePolling argument.
usePolling argument true or false overrides the setting for one request; null uses it.
InterruptCapableInputs The inputs that can take part in an interrupt faceoff.
SupportsInterrupts False when the server has no such input. The client then always asks for polled edges, whatever the setting.
InterruptInputs The inputs the server always reports by interrupt.

X-keys, the UNO and the ESP32 report only polled edges on the wire, so faceoffs on them always use polling.

Test triggers

TriggerRandom() asks the hub to send test edges for the enabled FirstOnly triggers, as if they had been pressed in a faceoff, at random times between 1 and 4 seconds from now: the client library's default window (the web page's dialog has its own default). TriggerRandom(IEnumerable<TriggerDefinition> inputs) does the same for chosen inputs with the same window, and TriggerRandom(TriggerRandomRequest) sets the window too, from 0 up to 4 seconds. Test edges have IsTest set and fire triggers like real ones. The hub refuses them while a button health check holds the device.

Trigger actions

A faceoff can carry actions that the server runs itself the moment an input wins or loses, so a light or sound cue does not wait for a round trip through your application. Trigger actions describes what the server does with them.

using GameshowPro.Osc;
using GameshowPro.TriggerGate.Model;

static TriggerActions Cue(string address) => new(new OscAction(new OscMessage(address).ToArray()), null);

Dictionary<Buzzer, TriggerActionsByResult> actions = new()
{
    [Buzzer.Red] = new(Winner: Cue("/show/red/win"), Loser: Cue("/show/red/lose")),
    [Buzzer.Blue] = new(Winner: Cue("/show/blue/win"), Loser: Cue("/show/blue/lose")),
};
await client.ResetFaceoff([Buzzer.Red, Buzzer.Blue], actions);
  • TriggerActionsByResult(Winner, Loser): the winner actions run on the input's 1st-place edge, the loser actions on any later edge. Either may be null.
  • TriggerActions(Osc, Lighting): an OscAction and a LightingAction, either of which may be null.
  • OscAction(Packet, Destination, SourceSubnet): a complete OSC packet as bytes, sent as it is. A null destination or source subnet uses the server's settings.
  • LightingAction(StartIndex, Data): a patch to a lighting universe. The server logs it; it has no lighting output.

Ending a faceoff with actions (keys null) runs every action supplied at once, which sets a "faceoff over" state in one call. To test playback settings, RunOsc(OscPacket packet, IPEndPoint? destination = null, IPNetwork? sourceSubnet = null) sends one packet now through the same path, and RunAction(LightingAction) applies one patch; RunOsc(OscAction) and the request overloads are there too. RunTestOscCommand sends an OSC message with no arguments to Settings.OscTestAddress; null or blank uses /triggergate/test. The built-in WPF TriggerClient.SettingsEdit template provides a "Test OSC address" field for this setting.

The ESP32 firmware has no trigger actions: it refuses a faceoff that carries any, and does not have RunOsc or RunAction.

Configuration

The client holds three settings that it sends to the hub for the platform instance it is bound to:

Settings member Meaning
StatusOutputPin The output that shows input activity, 0-based. Null for none.
OscDestination Where the server sends an OSC action that names no destination. Null keeps the server's default.
OscSourceSubnet The server's subnet whose network interface sends OSC. Null lets the server's operating system choose.

Each time the client opens a connection (at start, and after a change of host, platform or device) it reads the hub's configuration, adopts the hub's OSC destination and subnet if it has none of its own, and then sends these three values with SetConfig. It sends them again whenever one of them changes. The Windows and UNO services apply them as they are, so a client's null StatusOutputPin turns the status output off; the ESP32 keeps its status output when the client sends null, and has no OSC settings.

Besides Host, Platform, DeviceIndex and FaceoffsUsePolling (described above), Settings has three members that stay in your application and are never sent to the hub:

Settings member Meaning
IsEnabled true by default. The device's on/off switch, shown as "GPIs enabled?" in the WPF templates. The client itself does not consult it: it stays connected and its triggers keep firing. GameshowPro.Common's composite triggers, which combine triggers from several devices, ignore this device's triggers while it is false.
NameSuffix An instance name that tells clients apart in your user interface: the "Instance name" box of the settings row, and the monitor row. Empty by default.
AllowDuplicateTriggerIds false by default: when two enabled triggers are mapped to the same input, only one of them receives the input's reports and the others are marked invalid (Setting.IdIsValid false). true lets several triggers share an input, and they all fire from it.

From the configuration it reads, the client also keeps:

Member Meaning
AvailableSourceSubnets The subnets of the server's network interfaces, as choices for OscSourceSubnet. Any other subnet can still be set.
OutputPinNames, HasOutputPinNames, StatusOutputPinChoices The names of the server's outputs where they are not numbered pins (X-keys: "Red light", "Green light"), and the choices for a status output picker ("None", then each name).
StatusOutputPinMaximum The highest status output a numeric picker should offer, one-based (0 when the platform has no outputs).
OutputsAreInputPins Whether an output number is also an input, so the status output cannot be an input.
InterruptInputs, InterruptCapableInputs, SupportsInterrupts See Interrupt or polled edges.
InterruptOrderingResolution, PolledOrderingResolution See Clocks and time.

For anything else, call the hub directly:

  • GetConfig() returns a GetConfigResponse: the platform's Settings (status output, input mapping, OSC defaults, NTP server), the available input and output pins, and Capabilities, which say whether this server can change its OSC defaults, its NTP server and its input mapping. The fields are in Hub API.
  • SetConfig(SetConfigRequest) writes settings. With ReplaceSettings true the request is a complete record, which can also unassign an input and change the NTP server where the server allows it. NtpServerValidation.IsValid(value) checks an NTP server value as the web page and the UNO do: one host name or IP address, without a port; blank is valid and means the default.
  • IdentifyDevice() flashes the status output, so you can see which device you are connected to. IdentifyDeviceCommand is enabled for servers from version 1.2.
  • Shutdown() powers off a UNO, and puts an ESP32 board to sleep until it is reset. The Windows service refuses it.

Clocks and time

Every edge from a Windows or UNO service carries the edge's own time on the server's monotonic clock and on its wall clock (UTC); the ESP32 sends the monotonic time, and the UTC time while its clock is synchronized. How to keep clocks synchronized, and what the figures promise, is in Clocks and time and Accuracy.

Member Meaning
ServerClock The server's ClockStatus: the identities of its monotonic and wall clocks, how well the wall clock is disciplined (Quality), its estimated error and its last step. Replaced whenever the server reports a change. Null while not connected.
HostClock This computer's own ClockStatus, shared by every client in the process.
ClockComparison An OrderingSeparation of the two clocks: SameMonotonicClock (the same computer, exactly comparable), SharedTimeSource (comparable within Separation) or NotComparable (with a Reason). For display and logs.
InterruptOrderingResolution, PolledOrderingResolution The smallest separation at which the bound instance can order two faceoff entries by interrupt or by polled edges; closer entries are tied. Null when unknown.
LastTimeSample, TimeSampled event The server's current time, pushed about once a second as a ClockTimeSample (MonotonicTicks, UtcTicks, Clock, Ptp, NtpDiagnostics). Null, and the event raised with null, when the connection goes.
GetTimeSample() Asks for one sample now.

ClockStatusChange.Describe(client.ServerClock) and ClockStatusChange.Describe(client.ClockComparison) put a status or a comparison into words.

PTP on the ESP32

An ESP32 board can follow a PTP master. GetPtpStatus() returns its PtpStatus (domain, grandmaster, timescale, whether it is locked, its estimated error), ServerPtpStatus holds the latest, and PtpStatusChanged is raised when it changes. A faceoff can also start at a PTP instant: build a ResetFaceoffRequest with Scheduled set to a ScheduledFaceoffStart (the instant in Seconds and Nanoseconds, the expected Domain, Grandmaster and Timescale, and optionally MaximumErrorNanoseconds) and pass it to ResetFaceoff. If the board loses or changes its clock source before or during that faceoff, it cancels it and the client raises FaceoffCancelled. Windows and UNO services do not have these commands and answer them with an unsuccessful response.

Diagnostics

Three features have their own pages, each with its .NET usage:

  • Input diagnostics: GetInputDiagnostics(), a snapshot of each input's activity and the event queue's health.
  • Button health check: a timed test that records every transition of chosen inputs, from StartButtonHealthCheck to AnalyzeButtonHealthCheck, with the ButtonHealthCheckChanged event.
  • Device log: GetDeviceLogInfo() and DownloadDeviceLog, which write the device's log between two times to a file.

WPF templates

The Windows package includes a resource dictionary of templates for a client, with the look and layout of the GPI Gateway client. Merge it after the MahApps and GameshowPro.Common dictionaries your application already uses:

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
    <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
    <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Themes/Dark.Steel.xaml" />
    <ResourceDictionary Source="pack://application:,,,/GameshowPro.Common;component/View/SharedStyles.xaml" />
    <ResourceDictionary Source="pack://application:,,,/GameshowPro.Common;component/View/RemoteService.xaml" />
    <ResourceDictionary Source="pack://application:,,,/GameshowPro.Common;component/View/IncomingTriggerDevice.xaml" />
    <ResourceDictionary Source="pack://application:,,,/GameshowPro.Common;component/View/Mdns.xaml" />
    <ResourceDictionary Source="pack://application:,,,/GameshowPro.TriggerGate.Client;component/View/Templates.xaml" />
</ResourceDictionary.MergedDictionaries>

Every template takes the client as its content and data context.

Template key What it shows
TriggerClient.SettingsEdit One settings row: status light, host box with the find button, instance name, the faceoff mode switch (interrupt or polling; replaced by "Faceoffs use polling" when the server has no interrupt inputs), the "Enable GPIs" switch, the status output, the OSC destination, the OSC source subnet (offering the server's subnets) and, when the server offers more than one choice, the platform selector. A device that is not connected stays in the selector, dimmed.
TriggerClient.Header The configured host, and the server's platform, version, build date and host name. GameshowPro.Common's IncomingTriggerDevice panel uses it.
TriggerClient.Commands A row of buttons: start the default faceoff (the FirstOnly triggers), cancel the faceoff, test triggers, shut down and identify, then the status output picker. The IncomingTriggerDevice panel shows it under the device's name.
TriggerClient.Commands.Custom Empty. Define a DataTemplate with this key in your own resources to add controls to the end of the commands row; its data context is the client.
TriggerClient.Monitor A compact status row: status light, name and host, the "Enable GPIs" switch and a shut-down button.

The dictionary also gives the "Clock" entry of the status tree its own light, which can be green, yellow, red or gray, with the clock details as a tooltip. A status panel that does not merge the dictionary shows the plain status light for it.

The commands behind the buttons are on the client, for your own controls: ResetFaceoffDefaultCommand, ResetFaceoffNoneCommand, TriggerRandomCommand, ShutdownCommand, IdentifyDeviceCommand and RunTestOscCommand. The converters the templates use are public in GameshowPro.TriggerGate.Client.View: IPEndPointStringConverter (address:port), IPNetworkStringConverter (address/prefix) and PlatformDisplayNameConverter ("Advantech", "X-keys", "ESP32", "Uno").

v2.0.62