Error Handling
In Fahrenheit: with the SDK switched to Fahrenheit (SetTemperatureUnit() and its counterparts, 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.
Overview
The SDK uses two complementary error reporting mechanisms:
- Exceptions for synchronous errors (construction failures, configuration errors, capture timeouts).
- Error callback for a failure of the SDK's processing thread, which happens outside any call of yours.
Losing the camera is neither: it is a connection status. See Noticing a Dropped Connection.
Every exception the SDK raises on its own behalf inherits from optris::sdk::SdkException, which inherits from std::exception, so catching SdkException handles them generically while a subclass handles one case in particular. A handful of calls reject their arguments with std::invalid_argument instead; those are listed under Exception Hierarchy and a top-level handler should catch std::exception to be complete.
Note: The whole C++ surface throws, and pif::PifController was the last part of it that did not. Through API version 33 its fifteen fallible calls returned a value-or-error type instead; API version 34 converted them, so there is now one error convention in C++ and no exception to describe. A PIF refusal arrives as pif::PifException, which inherits from SdkException like every other, and carries code(), a PifError saying which refusal it was. One type with a code rather than nine types, because the nine are answers from one device about one request: branch on code(), and read what() for the specifics.
Note: A poll loop still does not need to be a try block, which was the original argument for the old shape and survives the conversion intact. On an interface whose inputs arrive with frames, reading before the first frame is not a refusal: ReadDigitalInput() answers DigitalState::Unknown, ReadAnalogInput() answers NaN, and ReadAll() reports inputs_known false. What throws is a wrong request, which is a wiring fault rather than a per-frame outcome.
pif::PifException is the one type declared outside optris/sdk/exception.h on purpose beside ConfigLoadException: it lives in optris/sdk/pif/pif_controller.h, next to the PifError enumeration its code() returns, because that enumeration is what gives it its meaning. It crosses the C ABI as whatever status its code maps to, which is the same status each PifError has always produced there.
The low-level recording types in optris/sdk/rec/ all throw: Recorder, Player, Snapshot, ContinuousRecorder, SessionRecorder, SessionPlayer, RecordingController, FrameIndex, VideoExporter, OpenSeries() and the metadata parsers, exactly as Imager::Recorder() and Player do. A RecordError decides which exception: see the table below.
Exception Hierarchy
Every class below is defined in optris/sdk/exception.h, with the single exception of ConfigLoadException, which is declared in optris/sdk/config_io.h because it carries a ConfigLoadReport:
std::exception └── optris::sdk::SdkException ├── optris::sdk::DeviceException │ ├── optris::sdk::ConnectTimeoutException │ └── optris::sdk::DeviceBusyException ├── optris::sdk::CalibrationException ├── optris::sdk::ConfigException │ └── optris::sdk::ConfigLoadException (config_io.h) ├── optris::sdk::CaptureException ├── optris::sdk::IoException ├── optris::sdk::InvalidStateException ├── optris::sdk::FeatureNotSupportedException ├── optris::sdk::PathExistsException ├── optris::sdk::InvalidArgumentException ├── optris::sdk::FileTooLargeException └── optris::sdk::InsufficientSpaceException
The last four are deliberately under SdkException directly rather than under ConfigException or IoException, which would have read more naturally. Each says why at its own declaration, and the reason is the same one every time: a catch (SdkException &) already written keeps catching them, while ConfigException's and IoException's status codes are not what the C ABI documents for these cases.
| Exception | When Thrown |
|---|---|
SdkException |
Base class. Carries a message() string. Catch this to handle all SDK errors generically. |
DeviceException |
Device not found, not accessible, refused, or failed while being operated. Carries an optional serial() identifying the device. |
ConnectTimeoutException |
Opening a network camera ran out of network.connect_timeout: nothing answered. Derives from DeviceException, so catch it first to tell it apart from a refusal. Only the network transport raises it. |
DeviceBusyException |
The camera would not carry the operation out, and may next time. Derives from DeviceException, so catch it first to tell it from a device that is gone. It is the one exception here where repeating the same call unchanged is a sensible response: an Xi 400 refuses an operation-mode switch with EIO while the previous stream is still tearing down, and the SDK reports "not now" rather than "not valid" after four retries over five seconds. |
CalibrationException |
The open failed, and calibration files were missing along the way. A camera whose files are merely missing still opens; see Calibration File Acquisition. |
ConfigException |
Invalid configuration: a temperature range or operation mode this camera does not have, a calibration_path that does not exist, an invalid serial. |
ConfigLoadException |
A ConfigException from LoadConfig() or the reporting ApplyConfig(): the file or record was refused for this camera, or applied only in part. report() names exactly which sections took effect and which did not. |
CaptureException |
Frame acquisition failure, for example a timeout in AcquireFrame(). |
IoException |
File I/O error: a recording that cannot be opened, a configuration file that cannot be written. |
InvalidStateException |
The call is well formed, but not now: starting a recording while one is already running, for instance. Distinct from ConfigException, which means the request itself is wrong, and from FeatureNotSupportedException, which means this camera can never do it. Stop the recording and the same call succeeds. |
FeatureNotSupportedException |
The request is reasonable, but this camera or source does not implement it: a focus position on a camera with no focus motor, for instance. Catching it is how a user interface greys a feature out. |
PathExistsException |
Every argument was well formed and the destination is already taken: StartRecording() on a path that exists refuses rather than overwriting. The remedy is one std::filesystem::remove(), or another name. Distinct from IoException because nothing was read or written; the SDK deliberately did not try. |
InvalidArgumentException |
The request itself is wrong and the message names which part: a continuous recording asked for with no retention bound, a clip whose out point precedes its in point, an empty output directory. Distinct from InvalidStateException, which is the same call being wrong only now. |
FileTooLargeException |
The result would be larger than the destination can hold in one file, which some file systems cap far below the volume's free space. Distinct from IoException and from InsufficientSpaceException because more free space does not help: the remedy is another destination or a smaller attachment. No camera-surface path raises it today, and it is mapped anyway, so the answer cannot change meaning the day one does. |
InsufficientSpaceException |
The destination has less free space than the caller itself asked to keep, so the recording was not started: rec::RecordingOptions::min_free_bytes is set and the volume is below it. The message names both numbers. It is a refusal at the start only; a volume that fills up while a recording runs does not produce it. |
A few calls validate their arguments with std::invalid_argument rather than a type from this hierarchy: SetConnectionTimeout() on a non-positive timeout, Radiometry().SetReferenceTemperature() on a temperature at or below -100, Display().SetColorWindow() on an inverted band. Catching SdkException alone does not catch those.
Across the C ABI each of these is a status code (OPTRIS_SDK_ERROR_DEVICE, OPTRIS_SDK_ERROR_TIMEOUT, OPTRIS_SDK_ERROR_BUSY, OPTRIS_SDK_ERROR_CALIBRATION, OPTRIS_SDK_ERROR_CONFIGURATION, OPTRIS_SDK_ERROR_CAPTURE, OPTRIS_SDK_ERROR_IO, OPTRIS_SDK_ERROR_INVALID_STATE, OPTRIS_SDK_ERROR_NOT_SUPPORTED, OPTRIS_SDK_ERROR_ALREADY_EXISTS, OPTRIS_SDK_ERROR_INVALID_ARGUMENT, OPTRIS_SDK_ERROR_OUT_OF_RANGE, OPTRIS_SDK_ERROR_INSUFFICIENT_SPACE), with the message in optris_sdk_last_error_message() and the stable ASCII name of the code in optris_sdk_status_name().
In .NET the same set is ThermalDeviceException (with ConnectTimeoutException and DeviceBusyException under it), CalibrationException, SdkConfigurationException (with ConfigurationLoadException, PathExistsException and InsufficientSpaceException under it), FrameCaptureException (with FrameTimeoutException under it), SdkIOException, SdkObjectNotFoundException and FeatureNotSupportedException, all deriving from OptrisSdkException. OPTRIS_SDK_ERROR_INVALID_ARGUMENT and OPTRIS_SDK_ERROR_OUT_OF_RANGE arrive as SdkConfigurationException rather than as types of their own, which is also what an AlreadyExists or an InsufficientSpace reads as to a broad handler, deliberately. OPTRIS_SDK_ERROR_INVALID_STATE is the one that gets no SDK type at all: it surfaces as .NET's own InvalidOperationException, which does not derive from OptrisSdkException, so a catch (OptrisSdkException) alone will not see it.
When Exceptions Are Thrown
Construction
Imager::Create() and its overloads throw on failure:
// Throws DeviceException if no camera is found or it cannot be opened. auto imager = optris::sdk::Imager::Create(); // Throws ConfigException for a calibration_path that does not exist, // ConnectTimeoutException if a network camera does not answer in time. auto configured = optris::sdk::Imager::Create(config); // Throws IoException if the file cannot be opened. auto player = optris::sdk::Player::Open("/data/recording.mkv");
optris_sdk_imager *camera = NULL; optris_sdk_status status; /* There is nothing to catch: every call answers with a status. * OPTRIS_SDK_ERROR_DEVICE when no camera is found or it cannot be * opened, OPTRIS_SDK_ERROR_CONFIGURATION for a calibration path that * does not exist, OPTRIS_SDK_ERROR_TIMEOUT when a network camera does * not answer in time. */ status = optris_sdk_imager_create(&camera); if (status != OPTRIS_SDK_OK) { fprintf(stderr, "%s: %s\n", optris_sdk_status_name(status), optris_sdk_last_error_message()); }
// Throws ThermalDeviceException if no camera is found or it cannot be // opened, SdkConfigurationException for a calibration path that does // not exist, ConnectTimeoutException if a network camera does not // answer in time. using ThermalCamera opened = ThermalCamera.Open(); // Throws SdkIOException if the file cannot be opened. using ThermalCamera player = ThermalCamera.OpenRecording("/data/recording.mkv");
# Raises DeviceError if no camera is found or it cannot be opened, # ConfigurationError for a calibration path that does not exist, # TimeoutError if a network camera does not answer in time. opened = optris_sdk.Camera.open() # Raises IoError if the file cannot be opened. player = optris_sdk.Camera.open_recording('/data/recording.mkv')
// Err with Status::Device if no camera is found or it cannot be // opened, Status::Configuration for a calibration path that does not // exist, Status::Timeout if a network camera does not answer in time. // Nothing unwinds: this is the one binding where the compiler makes // you look at the failure. let opened = Camera::open()?; // Err with Status::Io if the file cannot be opened. let player = RecordingFile::open("/data/recording.mkv")?;
Construction is the primary failure point. If Create() succeeds, the imager is connected and ready to stream, but check GetCalibrationStatus() before trusting its temperatures.
Configuration
Methods that validate parameters throw ConfigException:
// Throws ConfigException if this camera has no such range. optris::sdk::TemperatureRange range; range.min_c = -500; range.max_c = 2000; imager->SetTemperatureRange(range);
/* OPTRIS_SDK_ERROR_CONFIGURATION if this camera has no such range. */ optris_sdk_status status = optris_sdk_imager_set_temperature_range(imager, -500, 2000); if (status == OPTRIS_SDK_ERROR_CONFIGURATION) { fprintf(stderr, "%s\n", optris_sdk_last_error_message()); }
// Throws SdkConfigurationException if this camera has no such range. camera.TemperatureRange = new TemperatureRange(-500, 2000);
# Raises ConfigurationError if this camera has no such range. try: camera.temperature_range = (-500, 2000) except optris_sdk.ConfigurationError as exc: print(exc.status_name, exc)
// Err with Status::Configuration if this camera has no such range. if let Err(e) = camera.set_temperature_range(-500, 2000) { assert_eq!(e.status(), Status::Configuration); eprintln!("{}", e.message()); }
Frame Acquisition
Pull-based methods throw CaptureException on timeout or error:
// Throws CaptureException on timeout. auto frame = imager->AcquireFrame(std::chrono::milliseconds(100));
optris_sdk_frame *pulled = NULL; /* OPTRIS_SDK_ERROR_TIMEOUT when nothing arrived in time. */ if (optris_sdk_imager_acquire_frame(imager, 100, &pulled) == OPTRIS_SDK_OK) { optris_sdk_frame_free(pulled); }
// Throws FrameTimeoutException on timeout, which derives from // FrameCaptureException. using ThermalFrame pulled = await camera.AcquireFrameAsync(TimeSpan.FromMilliseconds(100));
# Raises TimeoutError on timeout. try: pulled = camera.acquire(100) except optris_sdk.TimeoutError: pulled = None
// A timeout is Ok(None) rather than an error: the wait expiring is an // outcome of the call and not a failure of it, so Rust is the one // binding that does not raise here. if let Some(pulled) = camera.acquire_frame(100)? { let _ = pulled.info()?; }
TryAcquireFrame() does not block: it returns an empty std::optional when no frame is waiting. Across the ABI the same thing is a zero timeout, which answers OPTRIS_SDK_ERROR_WOULD_BLOCK when nothing is ready. .NET turns that into TryAcquireFrame(out frame) returning false and Python into try_acquire() returning None; from Rust, call acquire_frame(0) and read the status.
Camera Control
Hardware operations throw DeviceException on failure:
// Throws DeviceException if the shutter cycle cannot be triggered. // The shutter lives on Detector(), not Radiometry(). imager->Detector().TriggerShutter(); // Throws FeatureNotSupportedException on a camera with no focus motor, // DeviceException if the motor cannot be reached. imager->Optics().SetFocus(0.5F); // the middle of the travel // Throws DeviceBusyException when the camera declines for now and the // same call would succeed shortly -- on an Xi 400 a mode switch during // a stream teardown does exactly this. Catch it before DeviceException. imager->SetOperationMode(mode);
/* OPTRIS_SDK_ERROR_DEVICE if the cycle cannot be triggered. */ optris_sdk_imager_trigger_shutter(imager); /* OPTRIS_SDK_ERROR_NOT_SUPPORTED on a camera with no focus motor, * OPTRIS_SDK_ERROR_DEVICE if the motor cannot be reached. */ optris_sdk_imager_set_focus(imager, 0.5F); /* the middle of the travel */ /* OPTRIS_SDK_ERROR_BUSY when the camera declines for now and the same * call would succeed shortly. Test for it before treating a failure * as a device that is gone. */ optris_sdk_imager_set_active_operation_mode(imager, &mode);
// Throws ThermalDeviceException if the cycle cannot be triggered. camera.TriggerShutter(); // Throws FeatureNotSupportedException on a camera with no focus motor, // ThermalDeviceException if the motor cannot be reached. camera.SetFocus(0.5f); // the middle of the travel // Throws DeviceBusyException when the camera declines for now and the // same call would succeed shortly. It derives from // ThermalDeviceException, so catch it first. camera.ActiveOperationMode = mode;
# Raises DeviceError if the cycle cannot be triggered. camera.detector.trigger_shutter() # Raises NotSupportedError on a camera with no focus motor, # DeviceError if the motor cannot be reached. camera.optics.set_focus_fraction(0.5) # the middle of the travel # Raises BusyError when the camera declines for now and the same call # would succeed shortly. It is a sibling of DeviceError rather than a # subclass, so name it in its own except clause. camera.operation_mode = mode
// Err with Status::Device if the cycle cannot be triggered. camera.trigger_shutter()?; // Status::NotSupported on a camera with no focus motor, // Status::Device if the motor cannot be reached. camera.set_focus(0.5)?; // the middle of the travel // Status::Busy when the camera declines for now and the same call // would succeed shortly. One status, so match on it rather than on a // type. camera.set_operation_mode(&mode)?;
Recording, Playback and Snapshots
Everything under optris::sdk::rec throws, and the exception type says which refusal it was.
namespace rec = optris::sdk::rec; try { auto recorder = rec::Recorder::Create(global); recorder->AddVideoStream(stream); recorder->OpenOutput(); recorder->WriteFrame(frame); } catch (const optris::sdk::PathExistsException& e) { // That name is taken. One std::filesystem::remove(), or another // name; nothing was read or written. std::println(stderr, "{}", e.what()); } catch (const optris::sdk::InsufficientSpaceException& e) { // Your own min_free_bytes refused the start. Free space and retry. std::println(stderr, "{}", e.what()); } catch (const optris::sdk::SdkException& e) { std::println(stderr, "{}", e.what()); }
/* The flat ABI has no low-level recorder type: a binding records * through the camera handle, and the same refusals arrive as status * codes. */ optris_sdk_status status = optris_sdk_imager_start_recording(imager, "/data/run.mkv"); if (status == OPTRIS_SDK_ERROR_ALREADY_EXISTS) { /* That name is taken. One remove(), or another name; nothing was * read or written. */ fprintf(stderr, "%s\n", optris_sdk_last_error_message()); } else if (status == OPTRIS_SDK_ERROR_INSUFFICIENT_SPACE) { /* Your own min_free_bytes refused the start. Free space and retry. */ fprintf(stderr, "%s\n", optris_sdk_last_error_message()); } else if (status != OPTRIS_SDK_OK) { fprintf(stderr, "%s: %s\n", optris_sdk_status_name(status), optris_sdk_last_error_message()); }
try { camera.StartRecording("/data/run.mkv"); } catch (PathExistsException e) { // That name is taken. One File.Delete(), or another name; nothing // was read or written. Console.Error.WriteLine(e.Message); } catch (InsufficientSpaceException e) { // Your own MinFreeBytes refused the start. Free space and retry. Console.Error.WriteLine(e.Message); } catch (OptrisSdkException e) { Console.Error.WriteLine(e.Message); }
try: camera.start_recording('/data/run.mkv') except optris_sdk.PathExistsError as exc: # That name is taken. One os.remove(), or another name; nothing # was read or written. print(exc) except optris_sdk.InsufficientSpaceError as exc: # Your own min_free_bytes refused the start. Free space and retry. print(exc) except optris_sdk.SdkError as exc: print(exc.status_name, exc)
// One error type carrying a status, so this is a match rather than a // catch chain, and the compiler checks the arms are exhaustive. if let Err(e) = camera.start_recording("/data/run.mkv") { match e.status() { // That name is taken. One remove_file(), or another name; // nothing was read or written. Status::AlreadyExists => eprintln!("{}", e.message()), // Your own min_free_bytes refused the start. Free space and // retry. Status::InsufficientSpace => eprintln!("{}", e.message()), other => eprintln!("{other:?}: {}", e.message()), } }
Catch the derived types before SdkException, which is its base: catch order is source order in C++, so a base-class arm placed first swallows every one of them. Nothing reports that mistake: the compiler does not refuse it and there is no diagnostic at run time, so the arm you wrote for "that name is taken" simply never executes. That is the only ordering rule here: all eight types below derive from SdkException directly, with no sibling deriving from another, so there is no further precedence to get right. If you are replacing a switch on a code with a chain of catch clauses, write them in the order of the table below and keep SdkException last.
The rec::RecordError a refusal carries is what picks the type, and the mapping is one-to-one:
rec::RecordError |
Exception | Across the C ABI |
|---|---|---|
kInvalidState |
InvalidStateException |
OPTRIS_SDK_ERROR_INVALID_STATE |
kPathExists |
PathExistsException |
OPTRIS_SDK_ERROR_ALREADY_EXISTS |
kInvalidParameter |
InvalidArgumentException |
OPTRIS_SDK_ERROR_INVALID_ARGUMENT |
kIoError |
IoException |
OPTRIS_SDK_ERROR_IO |
kCodecNotFound |
FeatureNotSupportedException |
OPTRIS_SDK_ERROR_NOT_SUPPORTED |
kFileTooLarge |
FileTooLargeException |
OPTRIS_SDK_ERROR_OUT_OF_RANGE |
kInsufficientSpace |
InsufficientSpaceException |
OPTRIS_SDK_ERROR_INSUFFICIENT_SPACE |
kInternal |
SdkException |
OPTRIS_SDK_ERROR_UNKNOWN |
kInternal is the one that stays the base class, and that is honest rather than a gap: it means an FFmpeg or library failure with nothing a caller can do about it, which is the one case for which OPTRIS_SDK_ERROR_UNKNOWN is the right answer.
Note: The three SaveSnapshot() methods (on Imager::Recorder(), Player and StillSource) are the exception to the table. They raise std::invalid_argument for a rejected argument and IoException for a write failure, and have done since the two were split apart, so a catch (const std::invalid_argument&) already written keeps working. rec::Snapshot's own SavePng(), SaveTiff(), SaveJpeg() and SaveCsv() follow the table.
Callbacks Must Not Throw
A frame callback (SetThermalCallback, SetBgraCallback, etc.) runs on the SDK's processing thread, and an exception escaping it terminates the process. Catch everything inside your callback, and hand anything that needs handling to a thread of your own.
Error Callback
The error callback receives failures of the SDK's processing thread: errors that cannot be reported through exceptions, because they occur outside the caller's stack frame.
imager->SetErrorCallback( [](const std::string& message) { spdlog::error("SDK error: {}", message); });
/* Runs on the SDK's processing thread when that thread fails. The C * ABI has no closures, so the pair is a function and a context * pointer. */ static void OTC_SDK_C_CALL OnError(const char *message, void *user_data) { (void)user_data; fprintf(stderr, "SDK error: %s\n", message); } void OtcDocRegister(optris_sdk_imager *camera) { optris_sdk_imager_set_error_callback(camera, OnError, NULL); }
camera.OnError(message => Console.Error.WriteLine($"SDK error: {message}"));
camera.on_error(lambda message: print(f"SDK error: {message}"))
camera.on_error(|message| eprintln!("SDK error: {message}"))?;
When the processing thread fails, it stops: the message is logged, the error callback is called with it, and no further frames are processed. Recover by reconnecting (Imager::Reconnect()) or by destroying the imager and creating a new one.
A camera that is unplugged or stops sending is not reported here. Use SetConnectionStatusCallback() for that.
The error callback is called on the SDK's internal thread. Keep the handler fast and non-blocking. If you need to perform complex recovery, post the error to your application's main thread.
Thread Safety
- Exceptions are thrown on the calling thread (the thread that called
Create(),AcquireFrame(),TriggerShutter(), etc.). - Error callback is called on the SDK's internal processing thread.
- The error callback must be thread-safe. Do not access non-atomic shared state without synchronization.
DeviceException Details
DeviceException carries an optional serial number identifying the device that caused the error:
try { auto imager = optris::sdk::Imager::Create(config); } catch (const optris::sdk::DeviceException& e) { std::println(stderr, "Device error: {}", e.what()); if (!e.serial().empty()) { std::println(stderr, "Device serial: {}", e.serial()); } }
The serial is populated when the error is associated with a specific device (e.g., a named camera that could not be opened). It is empty when the error is not device-specific (e.g., "no cameras found").
This is the one thing on this page that is C++ only. The serial is a field of DeviceException, and the C ABI has no entry point that reports it: optris_sdk_last_error_message() returns the message and optris_sdk_last_error_status() the code, and neither carries the device. So .NET, Python and Rust cannot surface it however they are written. An application in those bindings that needs the serial as data has to use the serial it passed in.
Example
Complete error handling pattern covering all failure modes:
#include <optrissdk.h> #include <chrono> #include <print> #include <thread> int main() { std::unique_ptr<optris::sdk::Imager> imager; // Phase 1: Construction, handling all creation errors. try { imager = optris::sdk::Imager::Create(); } catch (const optris::sdk::DeviceException& e) { std::println(stderr, "No camera found: {}", e.what()); if (!e.serial().empty()) { std::println(stderr, "Failed device serial: {}", e.serial()); } return 1; } catch (const optris::sdk::CalibrationException& e) { std::println(stderr, "Calibration error: {}", e.what()); return 1; } catch (const optris::sdk::SdkException& e) { std::println(stderr, "SDK error: {}", e.what()); return 1; } // A camera without its calibration files still opens. if (!optris::sdk::IsCalibrated(imager->GetCalibrationStatus())) { std::println(stderr, "{}", imager->GetCalibrationDiagnosis()); } // Phase 2: Register error callback for async errors. imager->SetErrorCallback( [](const std::string& message) { std::println(stderr, "Async SDK error: {}", message); }); // Phase 3: Configure, handling parameter errors. try { optris::sdk::TemperatureRange range; range.min_c = 150; range.max_c = 900; imager->SetTemperatureRange(range); } catch (const optris::sdk::ConfigException& e) { std::println(stderr, "Config error: {}", e.what()); // Stay in whichever range the camera opened with. } // Phase 4: Stream, handling capture errors. imager->SetThermalCallback( [](const optris::sdk::ThermalFrame& f) { // Frames from before the startup calibration has finished arrive // too, and are not measurements. if (!f.GetMetadata().thermal_data_reliable) return; try { std::println("Max: {:.1f} C", f.GetMaxTemperature()); } catch (...) { // Never let an exception leave a frame callback. } }); imager->Start(); // Phase 5: File I/O, handling save errors. try { imager->SaveConfig("/tmp/camera_config.json"); } catch (const optris::sdk::IoException& e) { std::println(stderr, "Cannot save config: {}", e.what()); } std::this_thread::sleep_for(std::chrono::seconds(10)); imager->Stop(); }
#include <stdio.h> #include "optris/sdk_c.h" /* Phase 4: a frame callback. Nothing can be thrown out of it because * nothing is thrown at all; a C handler only has to not crash. */ static void OTC_SDK_C_CALL OnFrame(const optris_sdk_frame *f, void *user_data) { optris_sdk_frame_info info; (void)user_data; optris_sdk_frame_info_init(&info, sizeof(info)); /* Frames from before the startup calibration has finished arrive * too, and are not measurements. */ if (optris_sdk_frame_get_info(f, &info) == OPTRIS_SDK_OK && info.thermal_data_reliable) { printf("Max: %.1f C\n", (double)info.max_temp_c); } } /* Phase 2: failures of the SDK's own thread, which no status code of * yours could report. */ static void OTC_SDK_C_CALL OnError(const char *message, void *user_data) { (void)user_data; fprintf(stderr, "Async SDK error: %s\n", message); } int main(void) { optris_sdk_imager *camera = NULL; optris_sdk_calibration_status calibration; char diagnosis[OPTRIS_SDK_MAX_MESSAGE]; optris_sdk_status status; /* Phase 1: construction. One status, and the name of it. */ status = optris_sdk_imager_create(&camera); if (status != OPTRIS_SDK_OK) { fprintf(stderr, "%s: %s\n", optris_sdk_status_name(status), optris_sdk_last_error_message()); return 1; } /* A camera without its calibration files still opens. */ if (optris_sdk_imager_get_calibration_status(camera, &calibration) == OPTRIS_SDK_OK && calibration != OPTRIS_SDK_CALIBRATION_CALIBRATED && calibration != OPTRIS_SDK_CALIBRATION_ACQUIRED) { size_t written = 0; optris_sdk_imager_get_calibration_diagnosis(camera, diagnosis, sizeof(diagnosis), &written); fprintf(stderr, "%s\n", diagnosis); } optris_sdk_imager_set_error_callback(camera, OnError, NULL); /* Phase 3: configuration. A range this camera does not have is * OPTRIS_SDK_ERROR_CONFIGURATION; stay in the one it opened with. */ status = optris_sdk_imager_set_temperature_range(camera, 150, 900); if (status != OPTRIS_SDK_OK) { fprintf(stderr, "Config error: %s\n", optris_sdk_last_error_message()); } /* Phase 4: stream. */ optris_sdk_imager_set_thermal_callback(camera, OnFrame, NULL); optris_sdk_imager_start(camera); /* Phase 5: file I/O. */ status = optris_sdk_imager_save_config(camera, "/tmp/camera_config.json"); if (status != OPTRIS_SDK_OK) { fprintf(stderr, "Cannot save config: %s\n", optris_sdk_last_error_message()); } getchar(); /* stream until Enter is pressed */ optris_sdk_imager_stop(camera); optris_sdk_imager_destroy(camera); return 0; }
using Optris.Sdk; ThermalCamera camera; // Phase 1: construction, handling all creation errors. try { camera = ThermalCamera.Open(); } catch (ThermalDeviceException e) { Console.Error.WriteLine($"No camera found: {e.Message}"); return 1; } catch (CalibrationException e) { Console.Error.WriteLine($"Calibration error: {e.Message}"); return 1; } catch (OptrisSdkException e) { Console.Error.WriteLine($"SDK error: {e.Message}"); return 1; } await using (camera) { // A camera without its calibration files still opens. if (camera.CalibrationStatus is not CalibrationStatus.Calibrated and not CalibrationStatus.Acquired) { Console.Error.WriteLine(camera.CalibrationDiagnosis); } // Phase 2: register the error callback for failures of the // SDK's own threads, which no try/catch of yours can reach. An // exception thrown in here is swallowed, so handle what you // handle inside it. camera.OnError(message => Console.Error.WriteLine($"SDK error: {message}")); // Phase 3: configure, handling parameter errors. try { camera.TemperatureRange = new TemperatureRange(150, 900); } catch (SdkConfigurationException e) { Console.Error.WriteLine($"Config error: {e.Message}"); // Stay in whichever range the camera opened with. } // Phase 4: stream, handling capture errors. camera.Start(); // Phase 5: file I/O, handling save errors. try { camera.SaveConfiguration("/tmp/camera_config.json"); } catch (SdkIOException e) { Console.Error.WriteLine($"Cannot save config: {e.Message}"); } try { for (int i = 0; i < 100; i++) { using ThermalFrame f = await camera.AcquireFrameAsync(TimeSpan.FromSeconds(2)); // Frames from before the startup calibration has finished // arrive too, and are not measurements. if (f.Metadata.IsThermalDataReliable) { Console.WriteLine($"Max: {f.MaxTemperature:F1} C"); } } } catch (FrameTimeoutException e) { Console.Error.WriteLine($"The camera stopped producing: {e.Message}"); } camera.Stop(); } return 0;
import optris_sdk # Phase 1: construction, handling all creation errors. try: camera = optris_sdk.Camera.open() except optris_sdk.DeviceError as exc: raise SystemExit(f"No camera found: {exc}") except optris_sdk.CalibrationError as exc: raise SystemExit(f"Calibration error: {exc}") except optris_sdk.SdkError as exc: raise SystemExit(f"SDK error: {exc}") with camera: # A camera without its calibration files still opens. if camera.calibration_status not in ( optris_sdk.CALIBRATION_CALIBRATED, optris_sdk.CALIBRATION_ACQUIRED): print(camera.calibration_diagnosis) # Phase 2: register the error callback for failures of the SDK's # own thread. camera.on_error( lambda message: print(f"Async SDK error: {message}")) # Phase 3: configure, handling parameter errors. try: camera.temperature_range = (150, 900) except optris_sdk.ConfigurationError as exc: print(f"Config error: {exc}") # Stay in whichever range the camera opened with. # Phase 4: stream, handling capture errors. camera.start() # Phase 5: file I/O, handling save errors. try: camera.save_config('/tmp/camera_config.json') except optris_sdk.IoError as exc: print(f"Cannot save config: {exc}") try: for frame in camera.frames(100): # Frames from before the startup calibration has finished # arrive too, and are not measurements. if frame.thermal_data_reliable: print(f"Max: {frame.max_c:.1f} C") except optris_sdk.TimeoutError as exc: print(f"The camera stopped producing: {exc}") camera.stop()
use optris_sdk::{CalibrationStatus, Camera, Status}; fn main() { // Phase 1: construction. One error type, so the arms are a match // on its status rather than a chain of catch clauses. let mut camera = match Camera::open() { Ok(camera) => camera, Err(e) => { match e.status() { Status::Device => eprintln!("No camera found: {e}"), Status::Calibration => { eprintln!("Calibration error: {e}") } _ => eprintln!("SDK error: {e}"), } std::process::exit(1); } }; // A camera without its calibration files still opens. match camera.calibration_status() { Ok(CalibrationStatus::Calibrated) | Ok(CalibrationStatus::Acquired) => {} _ => { if let Ok(diagnosis) = camera.calibration_diagnosis() { eprintln!("{diagnosis}"); } } } // Phase 2: register the error callback for failures of the SDK's // own thread. camera .on_error(|message| eprintln!("Async SDK error: {message}")) .expect("registering the error callback"); // Phase 3: configure, handling parameter errors. if let Err(e) = camera.set_temperature_range(150, 900) { eprintln!("Config error: {e}"); // Stay in whichever range the camera opened with. } // Phase 4: stream, handling capture errors. camera.start().expect("starting the stream"); // Phase 5: file I/O, handling save errors. if let Err(e) = camera.save_config("/tmp/camera_config.json") { eprintln!("Cannot save config: {e}"); } for _ in 0..100 { match camera.acquire_frame(2000) { // A timeout is Ok(None) here, not an Err. Ok(None) => eprintln!("The camera stopped producing"), Ok(Some(frame)) => { // Frames from before the startup calibration has finished // arrive too, and are not measurements. if let Ok(info) = frame.info() { if info.thermal_data_reliable { println!("Max: {:.1} C", info.max_temp_c); } } } Err(e) => eprintln!("{e}"), } } camera.stop().ok(); }