OptrisOptrisDocumentation

Documentation/OTC SDK/Optris.Sdk — C# API referencev12.0

Sdk

public static class Sdk

The SDK itself: finding cameras, and asking what version is loaded.

Everything else in this package hangs off a ThermalCamera. This type is only for the two things that happen before there is one.

Sdk: properties

public static uint ApiVersion { get; }

The API version the loaded native library implements.

A single integer that increases when the SDK's declared surface changes in a way a compiled caller can observe. It is separate from Sdk.Version, which is the product version and moves on its own schedule.

There is one API version number, not one per language: this is the same value as OPTRIS_SDK_API_VERSION in C++ and OPTRIS_SDK_C_ABI_VERSION in the flat C ABI. The SDK's own API version history says what changed at each version.

Of interest when diagnosing a mismatch between this assembly and a native library it did not ship with. In a released package they always match.

Example

Console.WriteLine($"API version {Sdk.ApiVersion}");
public static SdkBuildInfo BuildInfo { get; }

Which build of the native SDK is loaded: commit, branch, build date and platform, not just the release number.

  • Throws OptrisSdkException: The loaded native library is older than this assembly and does not have the call. In a released package they ship together and this cannot happen.

Sdk.Version says which release. This says which build of it, and that is what identifies a binary when a fault has to be traced back to the code that produced it. It is the first thing support asks for and the one thing a version number cannot answer.

Put it on an About page and include it in any diagnostics bundle you upload. SdkBuildInfo.ToString formats the lot as one line.

Reads constants compiled into the native library. It touches no camera, no file and no network, and works before any camera has been opened -- which matters, because the interesting case is a machine where opening one does not work.

Example

Console.WriteLine(Sdk.BuildInfo);

// or field by field, for a diagnostics bundle
SdkBuildInfo build = Sdk.BuildInfo;
report["sdk.version"] = build.Version;
report["sdk.commit"]  = build.CommitHash;
report["sdk.branch"]  = build.Branch;
public static SdkGpuInfo GpuInfo { get; }

The GPU the SDK would use for its processing pipeline, or the reason there is not one.

  • Throws OptrisSdkException: The query itself failed.

Answerable with no camera attached, which is the question an About page asks. The SDK keeps one shared GPU context for every camera in the process, so there is exactly one answer here however many cameras are open -- and whether a given camera actually uses it is ThermalCamera.PipelineInfo's question.

The first call probes for an adapter, which builds and releases a GPU context and is not instant. The answer is then cached for the life of the process, because it cannot change.

public static bool HasLogHandler { get; }

Whether a log handler is installed.

Diagnostic.

public static bool IsWatchingDevices { get; }

Whether the hotplug monitor is currently running.

Diagnostic. The monitor is started by Sdk.WatchDevicesAsync(…) and stopped when the last caller stops watching.

public static uint NativeAbiVersion { get; }

The API version, under the name this property had before the number was given one spelling across all three surfaces.

Identical to Sdk.ApiVersion -- the same number, read the same way. Prefer Sdk.ApiVersion in new code.

public static TemperatureUnit TemperatureUnit { get; set; }

The temperature unit of the whole SDK, for this process.

  • Throws SdkConfigurationException: The value is not one of the two units; the unit stays what it was.

TemperatureUnit.Celsius is the default, so a program that never sets it sees nothing change. With TemperatureUnit.Fahrenheit, every temperature the SDK takes or returns is in degrees Fahrenheit and every temperature difference in Fahrenheit degrees: frames, region statistics, alarm limits and events, the colour range, camera settings, process-interface channels, values read back from a recording or a snapshot. A member whose name says Celsius or C follows the unit as well; the name is older than this property.

The SDK keeps storing and computing in Celsius and converts where a value crosses the API, so a setting made in one unit keeps its meaning after a change and reads back in the new unit, and every file the SDK writes stays Celsius, byte for byte the same in either unit. CsvOptions.TemperatureUnit keeps its own choice for a CSV snapshot. The raw samples (ThermalFrame.ToCelsius(…)) are Celsius by definition.

Set it once, at start, before opening a camera.

Example

Sdk.TemperatureUnit = TemperatureUnit.Fahrenheit;
public static Version Version { get; }

The version of the native SDK this process has loaded.

The managed assembly and the native library are versioned together and shipped together, so these agree in a released package. They can differ when a development build is picked up from a build tree, and this is how to check.

Example

Console.WriteLine($"Optris SDK {Sdk.Version}");
public static string VersionString { get; }

The native SDK's version as it prefers to display it.

Example

Console.WriteLine(Sdk.VersionString);   // "12.0.0"

Sdk: methods

public static void ClearSimulatedDevices()

Forget every registered simulated camera, reporting each removal to a running watcher.

Chiefly for tests: the registry is process-wide and outlives any one of them, so a test that left a device registered would change what the next one enumerates.

public static BroadcastNetworkReply ConfigureNetworkByBroadcast(BroadcastNetworkConfig config)

Set the network address of a camera by its MAC address, by broadcast, without knowing the address it has now.

  • config: Which camera and what to set.

Returns: The camera's answer.

  • Throws ArgumentNullException: config is null.
  • Throws SdkConfigurationException: The MAC address, an address, the mask or the gateway is not one, or BroadcastNetworkConfig.Attempts is 0. Nothing was sent.
  • Throws ThermalDeviceException: The request could not be sent, or OTC_SDK_NO_HARDWARE is set.

The request reaches every camera on this network segment (it does not cross a router); only the camera with the given MAC address acts on it, and that camera answers by broadcast, so the answer arrives whatever subnet the camera is in. Only cameras whose NetworkDiscoveryInfo.ProtocolVersion is 1001 or later understand it.

The camera checks the values itself. Every answer except BroadcastConfigStatus.Taken means nothing was stored, and no answer at all means no camera with that MAC address answered. No camera is opened or claimed.

Example

BroadcastNetworkReply reply = Sdk.ConfigureNetworkByBroadcast(
    new BroadcastNetworkConfig
    {
        MacAddress = "9C:43:1E:70:40:3E",
        Address = "10.0.2.213",
        SubnetMask = "255.255.240.0",
    });
Console.WriteLine(reply.Status);
public static IReadOnlyList<DeviceInfo> EnumerateDevices()

Find every connected Optris camera.

Returns: What was found, which may be empty. No cameras attached is a normal state of the world, not an error.

  • Throws OptrisSdkException: The search itself failed.

Example

IReadOnlyList<DeviceInfo> devices = Sdk.EnumerateDevices();

if (devices.Count == 0)
{
    Console.WriteLine("no cameras attached");
}

foreach (DeviceInfo device in devices)
{
    Console.WriteLine(device);
}
public static IReadOnlyList<DeviceInfo> EnumerateDevices(EnumerationOptions? options)

Find cameras, with filters.

  • options: What to look for, or null for the defaults.

Returns: What was found, which may be empty.

  • Throws OptrisSdkException: The search itself failed.

With EnumerationOptions.IncludeNetwork set this blocks for up to EnumerationOptions.NetworkDiscoveryTimeout while it waits for cameras to answer. It is a synchronous call because the underlying SDK's is; run it on a background thread if that wait matters to you.

Example

var options = new Optris.Sdk.EnumerationOptions
{
    ConnectionType = ConnectionType.Usb,
};

IReadOnlyList<DeviceInfo> usb = Sdk.EnumerateDevices(options);
public static NetworkDiscoveryInfo? GetNetworkDiscoveryInfo(string serial)

What the camera with this serial said the last time it answered discovery in this process.

  • serial: The camera's serial number.

Returns: The record, or null if this process has not heard the camera answer discovery.

  • Throws ArgumentNullException: serial is null.

Any discovery fills it in: Sdk.EnumerateDevices(…) with EnumerationOptions.IncludeNetwork, a device watcher on the network, Sdk.Probe(…). Nothing is sent by this call.

public static SensorDimensions GetSensorDimensions(DeviceType type)

The native frame size of a camera model, without a camera.

  • type: The model to ask about.

Returns: The model's native width and height in pixels.

Sdk.EnumerateDevices reports DeviceInfo.Width and DeviceInfo.Height for a camera that is attached. This answers from the model alone, which is what you have before a camera opens: a placeholder for a camera that is not plugged in, a window layout restored before enumeration ran, a tile that should not jump to its real size when the camera connects.

Use this instead of keeping your own table. The SDK held this one privately until now, so applications copied it, and a copy drifts: one application's copy disagreed with the SDK on eleven models (an Xi 80 as 80 × 64, the PI 1M and Xi 1M at 4:3, the Xi 400 and 410 as 396 × 300), and shipped every one of them.

This is the sensor's size, which is not always the size of the frames an open camera delivers: a camera opened in a clipped or binned operation mode streams that mode's shape. A tile sized from this still resizes once for such a model. Naming the mode to open in would remove that, and is not yet possible.

Example

SensorDimensions size = Sdk.GetSensorDimensions(DeviceType.Xi400);
Console.WriteLine($"{size.Width} x {size.Height}");   // 382 x 288
public static DeviceInfo? Probe(NetworkTarget target)

Ask one network address who is there, without opening the camera.

  • target: Where to look, and optionally which camera to accept.

Returns: The camera that answered, or null if nothing answered within NetworkTarget.DiscoveryTimeout, or if what answered was not NetworkTarget.Serial.

  • Throws ArgumentNullException: target is null.
  • Throws ArgumentException: NetworkTarget.Address is empty.

The unicast counterpart of Sdk.EnumerateDevices: the same discovery exchange, addressed to one host instead of broadcast. A unicast datagram is routed, so this reaches a camera a broadcast cannot: behind a router, or on a subnet this machine has no interface on.

Opens nothing and claims nothing, so probing a camera another process is streaming from does not disturb it. That is what makes it safe to call from a device list: it lets a user interface show what is at an address, including its serial and its DeviceInfo.IsClaimed state, before the operator commits to opening it.

Nothing answering is an ordinary result, not an exception. An operator mistypes an address every day, and it costs NetworkTarget.DiscoveryTimeout rather than the operating system's own connect timeout.

Example

DeviceInfo? found = Sdk.Probe(
    new NetworkTarget { Address = "10.0.0.99" });

Console.WriteLine(found is null
    ? "Nothing answered."
: $"{found.Model} ({found.Serial}), " +
      (found.IsClaimed ? "in use": "available"));
public static DeviceInfo RegisterSimulatedDevice(SimulatedCameraOptions options)

Add a simulated camera to this process's device list.

  • options: The scene the camera should produce. Leave SimulatedCameraOptions.Serial empty to have one assigned -- the lowest free serial from 9990001 up. Note that the property defaults to "9990001" rather than to empty, so registering two freshly constructed options collides and is refused; clear it to have serials assigned.

Returns: The device as it will appear in enumeration.

A camera made by ThermalCamera.OpenSimulated exists only as the handle that made it: it is not enumerated, no device watcher reports it, and a saved layout naming its serial cannot resolve. Registering one puts it in the device list instead, so it arrives, is opened and is watched by the same code as a camera on the end of a cable -- which is the point, since the alternative is every application keeping its own serial-to-scene table alongside the SDK's.

The device appears in Sdk.EnumerateDevices(…) when EnumerationOptions.IncludeSimulated is set, with ConnectionType.Simulated, and ThermalCamera.Open(deviceInfo) opens it with the scene registered here rather than with defaults. If a watcher is running, it sees an DeviceChangeKind.Arrived.

Example

var hotSpot = new SimulatedCameraOptions
{
    Serial = string.Empty,   // assign me one
    Pattern = TestPattern.HotSpot,
};

DeviceInfo device = Sdk.RegisterSimulatedDevice(hotSpot);
await using var camera = ThermalCamera.Open(device);
public static void SetLogHandler(Action<SdkLogLevel, string>? handler, SdkLogLevel minimum = 2)

Send the SDK's log output to handler.

  • handler: Called once per log line. null stops capturing and restores the SDK's own output.

  • minimum: Lines below this level are not delivered. The default is what is worth having in a diagnostics bundle; SdkLogLevel.Debug and SdkLogLevel.Trace are for reproducing a fault.

  • Throws OptrisSdkException: The handler could not be installed -- including when this is called from inside the handler itself.

The SDK logs what the camera path is doing: calibration fetches, flag cycles, USB re-enumeration, NUC, reconnects. In a diagnostics bundle those lines are usually the only record of what the hardware was doing when a customer hit a problem, so an application that keeps its own log wants them in it.

This replaces the SDK's own output. While a handler is installed the SDK's console and file output are silenced, and clearing it puts them back. An application that captures the log should not also be leaving a second copy in a file it never told the user about.

It is process-wide, like the hotplug monitor: there is one handler, and setting a second replaces the first. Lines are not attributed to a camera.

A deliberately plain Action rather than Microsoft.Extensions.Logging.ILogger, so that this package keeps no dependencies. Adapting it to an ILogger is three lines, and the example below is them.

Threading. Each of these is covered by a test:

  • Any thread. The handler runs on whichever thread emitted the message -- usually an SDK thread, but yours when a call you made logs before returning. Unlike Sdk.WatchDevicesAsync(…), this does not hand you a thread-pool thread.
  • Possibly concurrently. Two SDK threads logging at once call it at once, so it must be thread-safe. Most logging frameworks already are; a raw StreamWriter is not.
  • Promptly. The thread that logged waits for it. Time spent here is time the frame pump is not running, so queue the line rather than writing to a socket from inside it.
  • Exceptions are swallowed. Anything the handler throws is caught before it can reach native code -- a managed exception unwinding through a C++ frame would take the process down. The line is lost and the SDK carries on. Do not rely on it; catch your own.
  • Clearing waits. When this returns, the previous handler has finished and cannot be called again -- so whatever it captured is safe to dispose.
  • Do not call this from inside the handler. It waits for the handler to return, so it would wait for itself. It throws OptrisSdkException rather than deadlocking. If the handler logs, that nested line is dropped rather than delivered back into it.

Example Into an application's own log:

Sdk.SetLogHandler((level, message) =>
    MyLog.Write($"[optris] {level}: {message}"));

Into an ILogger, if the application already has one:

Sdk.SetLogHandler((level, message) => logger.Log(
    level switch
    {
        SdkLogLevel.Trace => LogLevel.Trace,
        SdkLogLevel.Debug => LogLevel.Debug,
        SdkLogLevel.Warning => LogLevel.Warning,
        SdkLogLevel.Error => LogLevel.Error,
        _ => LogLevel.Information,
    },
    "{Message}", message));

And to stop:

Sdk.SetLogHandler(null);
public static bool TryGetSensorDimensions(DeviceType type, out SensorDimensions dimensions)

The native frame size of a camera model, if the SDK knows it.

  • type: The model to ask about.
  • dimensions: The model's native size, or default when this returns false. It is never a zero size standing in for an unknown one: a model with no recorded size returns false, so a caller cannot mistake one for the other.

Returns: true if the SDK has a size for that model.

The same answer as Sdk.GetSensorDimensions(…) without the exception, for a caller holding a model it did not choose (a restored layout, a stored configuration) where "this SDK does not know that model" is a case to draw differently rather than a fault to report.

public static bool UnregisterSimulatedDevice(string serial)

Remove a simulated camera from this process's device list.

  • serial: The serial to remove.

Returns: true if a device was registered under that serial.

  • Throws ArgumentException: serial is null or empty.

Removes the list entry, not any camera opened from it. A simulated camera that is currently open keeps running until it is disposed: it owns its own generator, and its holder is entitled to the frames it is midway through reading. Unregistering is an edit to a list, not a cable being pulled. What changes at once is that the serial stops being enumerated and can no longer be opened, so a later ThermalCamera.Open on a DeviceInfo kept from before will fail. If a watcher is running, it sees a DeviceChangeKind.Removed.

public static IAsyncEnumerable<DeviceChange> WatchDevicesAsync(CancellationToken cancellationToken = default)

Watch for cameras being plugged in and unplugged.

  • cancellationToken: Stops watching. This is the supported way to end the enumeration.

Returns: An async sequence of changes, one per camera arriving or leaving.

  • Throws ThermalDeviceException: The monitor could not be started.

Sdk.EnumerateDevices answers "what is attached now"; this answers "tell me when that changes", which is what an application that should survive a camera being unplugged actually needs.

Cameras that were already attached when you start watching are reported as DeviceChangeKind.Arrived too, so a loop that opens whatever arrives picks them up without a separate enumeration pass. If you also enumerate first, expect to see the same camera twice and deduplicate on DeviceInfo.Serial.

The DeviceInfo carried by a change is populated from the hotplug event rather than from a full device interrogation, so DeviceInfo.Model may be empty and DeviceInfo.Width, DeviceInfo.Height and DeviceInfo.Capabilities may read zero or false. DeviceInfo.Serial is what to act on; call Sdk.EnumerateDevices if you need the full description.

DeviceInfo.Serial is normally set: the SDK reads it out of the operating system's own record of the device rather than by opening the camera. It can still be empty: a camera whose USB descriptor carries no serial, and an arrival whose identity could not be read in time together with the removal that follows it. Check it before calling ThermalCamera.Open(…): an empty serial there means "the first camera found", not this one.

Your loop body runs on a thread pool thread, not on the SDK's hotplug thread. Several callers may watch at once; each sees every change.

Example

using var stopping = new CancellationTokenSource();

await foreach (DeviceChange change in Sdk.WatchDevicesAsync(stopping.Token))
{
    Console.WriteLine(change);

    if (change.Kind == DeviceChangeKind.Arrived)
    {
        using var camera = ThermalCamera.Open(change.Device);
    }
}
public static IAsyncEnumerable<DeviceChange> WatchDevicesAsync(DeviceWatchOptions? options, CancellationToken cancellationToken = default)

Watch for cameras being plugged in and unplugged, and optionally for them being claimed and released.

  • options: What to watch for, or null for arrivals and removals only.
  • cancellationToken: Stops watching.

Returns: An async sequence of changes.

With DeviceWatchOptions.WatchClaims set, a camera being opened arrives as DeviceChangeKind.Claimed and its release as DeviceChangeKind.Released, so a device list can grey a camera out and re-enable it without re-enumerating, and without the only alternative, which was polling ThermalCamera.Open(…) and reading the failure.

Your own opens and closes are reported too, which these remarks used to say was not the case. DeviceInfo.IsClaimedByThisProcess on the device the change carries is how to tell them apart; an application does not need to keep its own record of which serials it has open in order to ignore its own claims.

Cameras that were already claimed when watching started are not reported as DeviceChangeKind.Claimed. Only transitions are. Read DeviceInfo.IsClaimed from Sdk.EnumerateDevices for the starting state.

A claim change is still only a hint: another process can take a camera between the DeviceChangeKind.Released you saw and the open you attempt, so the open must still be allowed to fail.

Example

var options = new DeviceWatchOptions { WatchClaims = true };

await foreach (DeviceChange change in
               Sdk.WatchDevicesAsync(options, stopping.Token))
{
    switch (change.Kind)
    {
        case DeviceChangeKind.Claimed:
            if (change.Device.IsClaimedByThisProcess)
                break;   // we opened it ourselves
            ui.Disable(change.Device.Serial, change.Device.ClaimedBy);
            break;
        case DeviceChangeKind.Released:
            ui.Enable(change.Device.Serial);
            break;
    }
}