The Optris SDK from C#
Optris.Sdk is a hand-written .NET package over the SDK's flat C ABI: async/await, IAsyncEnumerable frame streams, IDisposable handles and a typed exception hierarchy. It is not a generated wrapper and it does not mirror the C++ class layout.
In Fahrenheit: with the SDK switched to Fahrenheit (Sdk.TemperatureUnit, see Temperatures in Fahrenheit), every temperature on this page is read and written in Fahrenheit, and every difference in Fahrenheit degrees; the samples are unchanged.
It reaches 663 of the SDK's 689 C entry points, and each of the other 26 is offered another way, which is counted by scripts/check_binding_parity.py on every build rather than claimed here. Language Bindings says what is in the gap.
This page is what is true of C# and of no other surface. Everything about the SDK itself is in the topic chapters, each of which carries a C# sample beside its C++, C, Python and Rust ones.
Adding it to a project
Add the package from nuget.org. In your project's directory:
dotnet add package Optris.Sdk
That writes the reference below into your project file, or write it yourself; see Installation for what the package contains. It also carries the version 11 compatible interface, namespace Optris.OtcSdk, so existing code needs no second package.
<ItemGroup> <PackageReference Include="Optris.Sdk" Version="12.0.*" /> </ItemGroup>
That is everything. The package carries the native SDK for each supported runtime, under runtimes/<rid>/native, so there is nothing else to install and no LD_LIBRARY_PATH to set. The package's own resolver looks in the application's output directory first, which is what keeps an older copy installed system-wide from winning; see Troubleshooting for what it looks like when that goes wrong.
Two things ride along beside the native library, and both are found relative to it rather than to the working directory:
- the palette CSVs, in the Library folder rather than the working folder (The Palette Library says why that matters for a service or a
.desktoplaunch); - the udev rule on Linux, under
tools/udev, which USB cameras need so the device nodes are readable without root.
The v12 interface (Optris.Sdk) and the version 11 compatible one (Optris.OtcSdk) come in the same package and load the same native library, so a solution can migrate one project, or one file, at a time.
A first program
A complete program. It needs no hardware.
using System.Numerics; using Optris.Sdk; await using ThermalCamera camera = ThermalCamera.OpenSimulated(); using Region region = Region.Rect(centre: new Vector2(0.5f, 0.375f), size: new Vector2(0.4f, 0.3f)); region.Name = "middle"; ulong id = camera.AddRegion(region); camera.Start(); using var stopping = new CancellationTokenSource(TimeSpan.FromSeconds(5)); try { await foreach (ThermalFrame frame in camera.FramesAsync(stopping.Token)) { using (frame) { // Frames from before the startup calibration has finished // arrive too, and are not measurements. if (frame.Metadata.IsThermalDataReliable) { Console.WriteLine($"{frame.MinTemperature:F1} to " + $"{frame.MaxTemperature:F1} C"); } } } } catch (OperationCanceledException) { // Cancelling the token is how the loop ends. } RegionStats stats = camera.GetRegionStats(id); Console.WriteLine($"region mean {stats.Mean:F1} C");
Three things in there are the three that catch people out:
await using, notusing. Disposal stops the camera and waits for its threads; doing that asynchronously keeps it off your thread.using (frame)on every frame. A frame holds native memory. See Disposal.catch (OperationCanceledException). Cancelling the token is the supported way to end the loop, and it surfaces as a cancellation rather than as the loop quietly finishing.
The API, chapter by chapter
The SDK's subjects are one chapter each, and each chapter's samples include the C# one. This table is the map; nothing below it repeats a chapter.
| Chapter | What is in it |
|---|---|
| Device Enumeration | Which cameras there are, where they are, claims, and being told when one comes or goes |
| Device Communication | Opening one, the two timeouts, the seven open phases, and whether it is calibrated |
| Ethernet Cameras | Reaching one over the network, and changing the address it holds |
| Dropped Connections | Noticing a drop, and what survives one |
| Calibration File Acquisition | Where calibration comes from, and a machine with no route out |
| Virtual Imager (Simulated) | Developing and testing with no camera attached |
| Using the API | Frames by push and by pull, reading temperatures out of one, and the processing outputs |
| Lifetimes | Who owns what, and for how long |
| Logging | The SDK's own log into your application's |
| Error Handling | Which exception means what |
| Regions · Region Statistics · Region Examples | Measuring an area, and what comes back |
| Alarms | One signal, one condition, and what to do about it |
| Colour Palettes · Colour Range · The Canvas | The picture: palette, range, and where it sits |
| Operation Modes | The operating point, and reading a setting back |
| Thermal Measurement Basics | Emissivity, transmissivity and ambient, and what they do |
| Recording · A Running Recording · Playback | Writing a camera to a file, what it reports, and reading one back |
| Snapshots and Interval Capture · Snapshot File Formats · Recording Attachments | One frame to a file, what the file is, and carrying your own files inside it |
| Process Interface (PIF) · Fail Safe | Industrial I/O on the camera, and the watchdog |
| Migration Guide: v11 to v12 | Moving an application off the v11 API |
The reference is IntelliSense
There is no type-by-type reference page, and that is deliberate. The package carries the XML documentation for every public type and member, so what your editor shows comes out of the assembly you are compiling against rather than out of something somebody wrote down once. CS1591 is an error in this package's build, which is what keeps it complete.
That is the same arrangement the other two bindings have, where the member-by-member reference is help() and cargo doc. The chapters are the how; the tooltips are the what.
Opening a camera
Five ways in, all returning a ThermalCamera you dispose when finished.
// The first camera the SDK can find. using ThermalCamera any = ThermalCamera.Open(); // A specific one, from enumeration. using ThermalCamera specific = ThermalCamera.Open(device); // One at a known address, for a camera enumeration cannot reach. using ThermalCamera remote = ThermalCamera.Open( new NetworkTarget { Address = "10.0.0.99" }); // No hardware at all. This is the supported way to develop and test. using ThermalCamera simulated = ThermalCamera.OpenSimulated(); // A recording, replayed as if it were a camera. using ThermalCamera playback = ThermalCamera.OpenRecording("run.mkv");
All five block. OpenAsync is the same call with two additions: it reports which phase the open has reached (The seven open phases lists the seven) and it takes a cancellation token. OpenSimulatedAsync has the same shape, so the plumbing can be exercised without hardware.
Progress<T> posts to the context it was constructed on, so a handler that touches a user interface is safe, and the consequence is that on a busy UI thread a report can arrive after the open has already finished. Any other IProgress<OpenPhase> is called inline on the SDK's opening thread instead, so a slow handler slows the open down and a blocking one holds it open. A handler that throws loses its report and nothing else.
Cancelling OpenAsync stops you waiting; it does not stop the SDK. Abandoning the wait does not stop the open has the SDK half, including the window in which reopening that same camera fails. The .NET half is this: the camera that eventually finishes opening is disposed automatically. It is never returned, never handed a callback and never left claimed indefinitely. OpenAsync also occupies a thread-pool thread for the whole open, cancelled or not, so do not fan out concurrent opens.
Frames arrive as an async stream
.NET takes no callback for frames, and that is the one structural difference from the C++ surface: FramesAsync hands back an IAsyncEnumerable<ThermalFrame> and AcquireFrameAsync a Task<ThermalFrame>, so nothing of yours ever runs on an SDK thread and the "no callback may destroy the camera" rule cannot be broken. The events (connection status, shutter, alarms, recording, action failures) are callbacks and async streams as in every other binding.
FramesAsync(...) |
AcquireFrameAsync(...) |
|
|---|---|---|
| Shape | IAsyncEnumerable<ThermalFrame> |
Task<ThermalFrame> |
| Who sets the pace | the camera | you |
| If you fall behind | oldest frames are dropped | oldest frames are dropped |
| How deep before that | 16 frames (configurable) | 4 frames (fixed) |
| What counts the loss | BufferedFrameDropCount |
DroppedFrameCount |
| Good for | live display, continuous processing | request and response, stepping |
The deeper buffer is this package's own, which is why it has its own counter. Sixteen frames is half a second at 32 Hz: deep enough to ride out a garbage collection and shallow enough that falling behind costs freshness rather than memory. The capacity is fixed for the life of the camera, so the first call decides it.
Console.WriteLine($"{camera.BufferedFrameDropCount} frames dropped");
If that number is climbing, the loop body is slower than the camera and the fix is on your side of the boundary. The two counters are different numbers and adding them together means nothing: DroppedFrameCount belongs to the SDK's four-deep acquisition queue and BufferedFrameDropCount to the .NET buffer in front of it, and a given frame can only be lost on one of the two.
One consumer. Several enumerators over one camera share a buffer and compete for frames rather than each seeing all of them.
try { using ThermalFrame frame = await camera.AcquireFrameAsync( TimeSpan.FromSeconds(2), token); } catch (FrameTimeoutException) { // The camera has stopped producing. This is a fault. } catch (OperationCanceledException) { // We asked it to stop. This is not. }
A timeout and a cancellation are different things and the API keeps them apart deliberately: FrameTimeoutException is the camera having stopped producing, which is a fault, and OperationCanceledException is you having asked it to stop, which is not.
Disposal
Lifetimes is the rule for every binding. Four things are .NET's own:
await using, notusing, for a camera.DisposeAsync()stops the camera and waits for its threads without holding the calling thread;Dispose()does the same work synchronously. On a user-interface thread that is the difference between a pause and a freeze.- Every native handle is a
SafeHandle. The runtime knows a handle is in use for the duration of a P/Invoke, so one cannot be finalised while native code still holds it, and a handle nobody disposed is released eventually rather than never. Passing raw pointers around and hopingDisposeis called is what generated bindings get wrong here. - No GC pressure is registered for a frame's native memory. So the collector cannot see how much a frame is holding, and at 32 frames a second it has no reason to run often enough: memory climbs while nothing looks wrong.
usingon every frame is the whole fix. - After disposal every member throws
ObjectDisposedException, and disposing twice is safe.
await using (var camera = ThermalCamera.OpenSimulated()) { camera.Start(); // ... } // stopped and joined here
frame.Pixels is a ReadOnlySpan<short>, a ref struct, so the compiler refuses to let you store it in a field. That is the one lifetime rule in this SDK that C# enforces rather than documents.
Which calls block, and which thread yours runs on
The things the type system cannot tell you, in one place.
| Your loop body | a thread-pool thread, never an SDK thread. However slow it is, it is not what holds the camera up. |
FramesAsync |
one consumer. Several enumerators share one buffer and compete. |
ThermalCamera |
safe from several threads: properties and measurement calls take the SDK's own locks. |
ThermalFrame |
not thread-safe. Frames are handed out one per consumer, so sharing one is not a pattern the API leads you into. |
AcquireFrameAsync |
occupies a thread-pool thread for the whole wait. The native call blocks and cannot be interrupted, so it runs under Task.Run in 100 ms slices and cancellation lands within one slice rather than instantly. Measured: 24 concurrent waits cost FramesAsync +0 pool threads and AcquireFrameAsync +6, the other 18 queued waiting for the pool to grow. Fine for request and response; do not fan out. |
FramesAsync, by contrast |
parks with no thread at all. |
OpenAsync |
occupies a thread-pool thread for the whole open, cancelled or not. |
Stop() |
blocks until any callback in flight has returned. |
DisposeAsync() |
stops the camera, waits for its threads, and releases every buffered frame. |
OnRecording, OnColorImage, OnShutterState, OnInputDecoded |
run on an SDK thread. Do not call back into the camera and do not dispose it from one; marshal to your own thread. |
Sdk.SetLogHandler |
runs on whichever thread emitted the message, including yours, and possibly several at once. The only callback here not handed a thread-pool thread: see Threading. |
Exceptions
One model: exceptions, in a hierarchy rooted at OptrisSdkException.
Which type you get is decided by the status the C ABI returned, and the mapping is in one place, SdkStatus.ToException. Reading it as a table of statuses rather than of types is the honest shape, because that is the direction the binding works in, and because three C++ exception types have no .NET type of their own.
| C ABI status | .NET exception | Derives from |
|---|---|---|
BUSY |
DeviceBusyException, carrying what refused it |
ThermalDeviceException |
DEVICE, NOT_CONNECTED |
ThermalDeviceException |
OptrisSdkException |
CALIBRATION |
CalibrationException |
OptrisSdkException |
ALREADY_EXISTS |
PathExistsException |
SdkConfigurationException |
INSUFFICIENT_SPACE |
InsufficientSpaceException |
SdkConfigurationException |
CONFIGURATION, INVALID_ARGUMENT, OUT_OF_RANGE |
SdkConfigurationException |
OptrisSdkException |
CAPTURE |
FrameCaptureException |
OptrisSdkException |
TIMEOUT |
FrameTimeoutException |
FrameCaptureException |
IO |
SdkIOException |
OptrisSdkException |
NOT_SUPPORTED |
FeatureNotSupportedException |
OptrisSdkException |
NOT_FOUND |
SdkObjectNotFoundException |
OptrisSdkException |
INVALID_STATE |
InvalidOperationException, the runtime's own |
SystemException |
| anything else | OptrisSdkException |
Exception |
Two more are raised directly rather than through that mapping: ConnectTimeoutException (a ThermalDeviceException) when an open gives up, and ConfigurationLoadException (an SdkConfigurationException) when a configuration import is refused, carrying the report that says what it refused.
try { using ThermalCamera camera = ThermalCamera.Open(); camera.Start(); } catch (OptrisSdkException error) { Console.Error.WriteLine($"camera unavailable: {error.Message}"); }
OptrisSdkException.Status carries the underlying native code. It is there for logs and support tickets: branch on the exception type, and quote the number.
Three C++ types have no .NET counterpart
Recording, Playback and Snapshots lists which rec::RecordError becomes which C++ exception, and four rows of that table do not cross into .NET under their own names:
InvalidStateExceptionarrives as the runtime'sInvalidOperationException. Asking a stopped camera for a frame, or starting a second recording while one runs, is that one. Acatch (InvalidStateException)does not compile here and a broadcatch (OptrisSdkException)does not catch it either, because it is not in this hierarchy at all. That is the one place where catching the root type is not enough.FileTooLargeExceptioncrosses asOUT_OF_RANGE, so it arrives asSdkConfigurationException.InvalidArgumentExceptioncrosses the same way, andIoExceptionarrives asSdkIOException.
The runtime's own exceptions are used where they fit rather than being duplicated: ObjectDisposedException for a disposed handle, ArgumentOutOfRangeException for a pixel outside the frame, InvalidOperationException as above, and OperationCanceledException for a cancelled wait.
Where Try appears instead
Only where a failure is genuinely routine, because TryParse is native C# idiom and costs the caller nothing:
TryAcquireFrame: no frame has arrived yetTryOpenProcessInterface: a simulated camera or a recording, so there is no hardware behind it.OpenProcessInterface()is the throwing form, for when its absence really is an errorTryReadDigitalInput/TryReadAnalogInput: the interface may be unpluggedTryGetRegionId: the region may legitimately be absentTryReadSignal:falseis "nothing published this"RemoveRegionreturnsfalserather than throwing
Everything else throws.
Durations
Every TimeSpan you set crosses into the SDK as a whole number of milliseconds, and a few, such as an alarm's recording action, as whole seconds. A TimeSpan is finer than both, so the binding narrows it, and it does so by rounding, never by cutting short.
A duration above TimeSpan.Zero never arrives as zero: anything smaller than one millisecond is carried as one millisecond. That matters because on most of these settings zero is a sentinel rather than a small number.
| Setting | What zero means there |
|---|---|
RecordingOptions.Duration |
run until stopped |
RecordingOptions.MaxSegmentDuration |
no segmenting |
CameraOptions.ConnectionTimeout |
use this camera's saved configuration |
FailSafeConfiguration.Period |
step on every passed check: no rate limit |
ColorScaleDynamics.CloseTime / .OpenTime |
no damping |
ReconnectConfig.MaxDelay |
no ceiling; every attempt waits InitialDelay |
AlarmCondition.OnDelay / .OffDelay |
react on the first observation |
So a truncated sub-millisecond value would not arrive slightly short; it would arrive as a different instruction, and "record for half a millisecond" would mean "record for ever". It does not. TimeSpan.Zero still means zero: asking for zero and asking for a very small amount are different requests and get different answers.
A few calls refuse a zero outright, where a floor is the honest answer: EnablePreRoll, StartRecording(path, duration), StartIntervalCapture, ThermalCamera.ConnectionTimeout and ReconnectConfig.InitialDelay.
Several parts of one application can watch at once
Several parts of an application can watch at once and each sees every change, even though the underlying monitor is process-wide. That is this package's own multiplexing: the SDK's own monitor is one per process, and a second StartDeviceMonitor() in C++ does nothing, so an application written against the C ABI has to fan out for itself. Cancel the token to stop; the native monitor is shut down when the last watcher goes away.
The same holds for AlarmEventsAsync, ActionFailed and MotionEventsAsync.
Which build am I running?
Sdk.Version says which release. Sdk.BuildInfo says which build of it, which is the question a version number cannot answer: two builds of 12.0.0 can be weeks of commits apart.
Console.WriteLine(Sdk.BuildInfo); // Optris SDK 12.0.0 (Release) commit 0a1b2c3d4 on release/12.0, // built 2026-09-08T15:03:12.0000000+00:00 for Linux amd64
| Property | Example | What it is |
|---|---|---|
Version |
"12.0.0" |
the product version, same value as Sdk.VersionString |
CommitHash |
"0a1b2c3d4" |
the commit the native library was built from |
Branch |
"release/12.0" |
the branch it was built from |
BuildDate |
2026-09-08T15:03:12+00:00 |
when it was compiled, UTC, DateTimeOffset? |
CommitDate |
2026-09-08T16:57:15+02:00 |
when that commit was made, DateTimeOffset? |
BuildType |
"Release" |
or "Debug" |
Os |
"Linux" |
what it was built for, not what it is running on |
Platform |
"amd64" |
likewise |
SdkBuildInfo build = Sdk.BuildInfo; report["sdk.version"] = build.Version; report["sdk.commit"] = build.CommitHash; report["sdk.branch"] = build.Branch; report["sdk.built"] = build.BuildDate?.ToString("O") ?? "unknown";
It reads constants compiled into the native library: no camera, no file, no network, and it works before any camera has been opened, which matters because the machine you want this from is usually the one where opening a camera does not work.
No string property is ever empty. A value the build could not determine reads exactly "unknown", and code reporting these should pass that through rather than blanking it. An empty string is indistinguishable from a field nobody filled in, and a plausible but wrong commit is worse still: it sends support to code that is not in the binary. The two dates are DateTimeOffset? for the same reason, because DateTimeOffset has no spelling for "not recorded".
A CommitHash ending in -dirty means the working tree differed from that commit when the library was built, so the hash names a commit whose source is not what was compiled. Released packages are built from clean checkouts and never carry it.
The same information is optris::sdk::GetBuildInfo() in C++ and optris_sdk_get_build_info() in C, all three reading one source, and otc_version prints the lot without any code being written (Command Line Tools).
Troubleshooting
Troubleshooting is the SDK's own list. These four are .NET's.
DllNotFoundException naming otcsdk
The native SDK is not beside the application. In a package build it always is, so this almost always means a publish that dropped runtimes/<rid>/native.
EntryPointNotFoundException on the first call
The native library loaded, but it is the wrong one: almost always an older SDK installed system-wide, typically /usr/lib/libotcsdk.so. Both files are called the same thing, so the symptom is a missing entry point rather than a missing library, which reads like a broken build. The package's resolver looks in the application's own directory first precisely to avoid this, so seeing it means the local copy is missing as well.
ls -la libotcsdk*.so # in the output directory /sbin/ldconfig -p | grep otcsdk
Memory climbing while streaming
A frame was not disposed. Every frame from FramesAsync and AcquireFrameAsync is yours and holds native memory. See Disposal for why the collector does not save you.
BufferedFrameDropCount climbing
The loop body is slower than the camera. That is what the bounded buffer is for and nothing is broken, but you are seeing every nth frame. Make the body faster, move the work off the loop, or switch to AcquireFrameAsync and set the pace yourself.
Moving from Optris.OtcSdk
Both interfaces come in the Optris.Sdk package, so a solution can move one project, or one file, at a time. A project that referenced the separate Optris.OtcSdk package of earlier releases references Optris.Sdk instead and compiles unchanged. Both namespaces have a class named Sdk, so a file that uses both needs an alias for one of them, for example using V12 = Optris.Sdk;.
Optris.OtcSdk (SWIG, v11) |
Optris.Sdk (v12) |
|---|---|
IRImager |
ThermalCamera |
IRImagerFactory / Create* |
ThermalCamera.Open* |
IRImagerClient callbacks |
await foreach (var f in camera.FramesAsync(token)) |
polling with getFrame |
await camera.AcquireFrameAsync(token) |
ThermalFrame + manual index maths |
ThermalFrame.Pixels / GetTemperature(x, y) |
raw IntPtr wrappers |
SafeHandle, released even if you forget |
status codes and SDKException |
a typed exception hierarchy |
MeasurementField / ROI / alarm channels |
Region, one model (Regions) |
ProcessInterface variant classes |
ProcessInterface + PifChannel records |
Sdk.getVersionInfo() |
Sdk.Version and Sdk.BuildInfo |
Sdk.setLogCallback(cb, exclusive) |
Sdk.SetLogHandler(cb, minimum) (Moving from Sdk::setLogCallback) |
| pixel-space ROI coordinates | frame-normalised isotropic coordinates: not a field-by-field copy |
ConnectionEvent.accessInternet |
CameraOptions.AllowCalibrationDownload |
Sdk.setCalibrationFileSourceDirectory |
CameraOptions.CalibrationDirectory |
getDeviceNetworkConfig / setDeviceNetworkConfig |
ThermalCamera.NetworkConfiguration / ApplyNetworkConfiguration |
IpAddress, Port |
plain string and ushort |
Three differences are not renames:
Coordinates. The old ROI model normalised y by the frame height; this one normalises both axes by the frame width. Porting a region field by field misplaces every one of them by the aspect ratio. Coordinates has the rule.
Measurement fields, ROIs and alarm channels are one thing now. A measuring field is a Region, its statistics are RegionStats, and its alarm is a rule on the region.
The network dialog loses two fields and gains a result. There is no DHCP and no gateway, because the camera has neither; what the old binding called Gateway was editing the stream destination all along. A dialog ported field by field will not compile, which is the intended outcome. There is no DHCP, and no gateway has the measurement behind that.
Migrating a SWIG C# Application covers the SWIG surface's own five removed members, and Migration Guide: v11 to v12 the rest of the move.
What is not bound
A pre-flight calibration check. There is no way to ask "are this camera's calibration files already on this machine?" without opening the camera, and that is not an oversight: the answer depends on which video formats the camera offers, which is not knowable from a serial number, so a check taking only a serial would be guessing. Open the camera and ask it (When It Fails).
ApplyConfig in its v11 shape, a struct of settings, is deliberately absent and will stay so: a struct cannot carry regions, and the call replaces the regions, the alarm rules and the canvas wholesale, so binding it that way would silently delete a caller's measuring areas. The capability is not missing: GetConfiguration() and ApplyConfiguration() do this in memory over an opaque CameraConfiguration that can carry regions, and SaveConfiguration / LoadConfiguration are the same pair through a file.
The v11 ROI model (AddRoi, SetRois and the rest) is not bound and will not be. A Region supersedes it: an ROI carried one threshold and a flag, where a region carries a full alarm rule.
rec::Recorder and rec::Player are not bound and will not be. Recording, playback and snapshots are driven through the camera instead, which is what an application needs, so a second way in would be a second lifetime to get wrong.
Bound and reachable through IntelliSense rather than through a chapter of their own: VideoExport (over rec::VideoExporter), RecordingSession and SessionPlayer, RecordingFile, FrameIndex, ContinuousRecording, Snapshot, and Canvas / CanvasMap / Placement.