OptrisOptrisDocumentation

Documentation/OTC SDK/Overviewv12.0

Device Enumeration

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

Device enumeration uses the free function EnumerateDevices() in namespace optris::sdk. It detects Optris cameras connected via USB and optionally on the network, returning a std::vector<DeviceInfo> with connection details, serial number, model, and capabilities.

Prerequisites

USB devices are detected out of the box. Ethernet devices require minimum firmware revisions:

Device Type Minimum Firmware
Xi 80 3031
Xi 320 MT 3351
Xi 410 3824
Xi 1M 4020

Use PixConnect 3 to check and update firmware. The SDK does not support firmware updates.

Basic Enumeration

Call EnumerateDevices() with no arguments to detect all USB-connected cameras. The network is not searched unless asked for: broadcasting and waiting for replies is the entire cost of an enumeration, and a USB application should not pay it.

#include <optrissdk.h>

auto devices = optris::sdk::EnumerateDevices();
for (const auto& d : devices) {
  std::println("{} S/N {} ({})",
               optris::sdk::DeviceTypeToString(d.type),
               d.serial,
               optris::sdk::ConnectionTypeToString(
                   d.connection));
}

An empty list is a successful search and not an error: no camera attached is an ordinary state of the world. The call talks to the USB bus and blocks while it does, so keep it off a thread that draws.

Finding Network Cameras

Set include_network to broadcast for cameras on every network this host is attached to:

optris::sdk::EnumerationOptions opts;
opts.include_network = true;
opts.network_discovery_timeout = std::chrono::seconds{3};

for (const auto &d : optris::sdk::EnumerateDevices(opts)) {
  std::println("{} S/N {} at {}",
               d.model,
               d.serial,
               d.address.empty() ? "USB" : d.address);
}

A network camera comes back with connection == ConnectionType::kNetwork and its address filled in: the address it answered from. Pass the whole DeviceInfo to Imager::Create() to open it. A caller that keeps only the serial throws the address away and cannot get it back for a camera on another subnet.

Note: Discovery is a broadcast, so it finds cameras on this host's own segments and no others. A camera behind a router is invisible to it however healthy it is, and has to be opened by address instead; see Device Communication.

Asking One Address

ProbeNetworkDevice() is the unicast counterpart of EnumerateDevices(): the same discovery exchange, sent to one host instead of to a broadcast address. A unicast datagram is routed, so it reaches a camera behind a router that no broadcast can find. Use it when an operator has typed an address and the serial is not known yet.

optris::sdk::NetworkProbe probe;
probe.address = "10.0.0.21";
probe.timeout = std::chrono::seconds{3};

if (const auto found = optris::sdk::ProbeNetworkDevice(probe)) {
  std::println("{} S/N {} at {}", found->model, found->serial, found->address);
  auto imager = optris::sdk::Imager::Create(*found);
} else {
  std::println("nothing answered at {}", probe.address);
}

Nothing answering is an empty answer rather than an error, because an operator mistypes an address every day, and it costs the probe's own timeout (three seconds by default) rather than the operating system's connect timeout, which on Linux is a little over two minutes.

Opening by address never falls back to USB. A caller that asks for a camera at an address and silently gets a different one over USB has no way to tell.

It returns a full DeviceInfo, so what it found can be listed and then opened without asking twice. Leave NetworkProbe::serial empty to accept whatever answers, or set it to accept only that camera: an address that answers with a different serial comes back empty, not as that other camera. It opens nothing and claims nothing, so it does not disturb a camera another process is streaming from. An empty address throws ConfigException. In C: optris_sdk_probe_network() over an optris_sdk_network_target.

Where a Camera Is

A camera found on the network reports the address it answered discovery from and the UDP port it streams to, on the DeviceInfo itself.

optris::sdk::EnumerationOptions opts;
opts.include_network = true;

for (const auto &device : optris::sdk::EnumerateDevices(opts)) {
  if (device.address.empty()) {
    std::println("{} ({}) on {}", device.model, device.serial,
                 optris::sdk::ConnectionTypeToString(device.connection));
  } else {
    std::println("{} ({}) at {}:{}", device.model, device.serial,
                 device.address, device.port);
  }
}

Both come from enumeration, so they are readable before the camera is opened, and that is the case they exist for: showing the address on a tile, checking that an operator is not adding an address something else already uses, and writing it into a saved layout so the same camera is recognised next time. Reading it back off an open camera's network configuration answers none of those, because all three happen first.

The address is absent rather than blank for a camera that has none: every camera on USB, and the simulated one. It is never "" and never "0.0.0.0". A placeholder would pass the duplicate-address check this field exists for, and two cameras with no address would collide with each other. The port is 0 in the same case, so test the address for absence rather than the port for zero.

control_path (ControlPath in .NET) is the platform control node, a /dev path or a Windows device interface, and is empty for a network camera. It is not a stand-in for the address.

Filtering

Pass EnumerationOptions to filter results. In C#, write it as Optris.Sdk.EnumerationOptions, or add using EnumerationOptions = Optris.Sdk.EnumerationOptions; at the top of the file: the implicit usings a new .NET project has switched on import System.IO.EnumerationOptions as well, and the short name is then ambiguous (error CS0104).

optris::sdk::EnumerationOptions opts;
opts.include_simulated = true;          // include simulated devices
opts.include_network = true;            // scan the network
opts.device_type_filter = optris::sdk::DeviceType::kPi640;
opts.connection_type_filter = optris::sdk::ConnectionType::kUsb;
opts.network_discovery_timeout =
    std::chrono::milliseconds(5000);

auto devices = optris::sdk::EnumerateDevices(opts);
Option Default Description
include_simulated false Append synthetic cameras, with ConnectionType::kSimulated. See below.
device_type_filter nullopt Only return devices of this exact model. It is one DeviceType, not a family: kXi80 returns Xi 80s and not Xi 400s.
connection_type_filter nullopt Only return devices with this connection type.
include_network false Also scan the network for Ethernet devices via UDP broadcast.
network_discovery_timeout 3000 ms How long to wait for Ethernet device responses.

Warning: include_simulated means the list is never empty. It appends whatever RegisterSimulatedDevice() has been given, and if nothing has been registered it appends one built-in device, a PI 160 on serial 9990001. So devices.empty() is not a "no cameras attached" test once this is set, and devices[0] may be a synthetic camera rather than the one on the desk. Check connection != ConnectionType::kSimulated when what you want is hardware. See Virtual Imager for registering scenes of your own.

network_discovery_timeout bounds the whole sweep, not each network. A host attached to several subnets asks each of them in turn (the detectors share one discovery socket, so their replies would land in each other's reads) and the sweep stops as soon as the budget is spent. Five network connections therefore cost the same as one, at the price of fewer rounds, so raise the timeout if a camera on a quiet segment is being missed. The overrun is at most one network's receive timeout, because a blocking read cannot be cut short once it has started. Each network is logged with its own duration at debug verbosity, which is how to find the expensive one.

Naming a Camera

A camera reports a model (PI 640i) and a serial number, and neither is what an operator calls it.

DeviceInfo::metadata carries what the user has recorded about a camera, the name first among it. Enumeration fills it in, so the name is there before anything is opened.

#include <optrissdk.h>

// Name a camera. This does not open it.
optris::sdk::SetDeviceName("21074191", "oven inlet");

for (const auto &device : optris::sdk::EnumerateDevices()) {
  const std::string name = device.metadata.Name();
  std::println("{:<20} {} S/N {}",
               name.empty() ? "(unnamed)" : name,
               device.model,
               device.serial);
}

What is guaranteed

It persists, keyed by serial. The serial is the only stable identity a camera has: move the plug to the next socket and the USB path changes while the camera does not. Names are stored on the host, in the SDK's configuration directory beside the per-camera configuration file: <user data>/Configs/<serial>.metadata.json. They survive a restart of your program and a re-plug of the camera.
Reading a name does not touch the camera. Naming a camera, and listing names, are file operations on this machine. They never claim the camera, they read the same for a camera another program is streaming from, and they add nothing to what a sweep already costs.
The sweep opens every attached Optris device, and always has. A serial number is a USB string descriptor and can only be read by opening the device. No interface is claimed and nothing is held: a camera another program is streaming from comes back marked DeviceInfo::is_claimed rather than being taken away. To avoid paying for it, EnumerationOptions::connection_type_filter decides which sources are read rather than filtering what they returned: ConnectionType::kNetwork broadcasts and does not read the local buses, and kSimulated is the one request in this API that touches no hardware at all.
Empty is the default. A camera nobody has named reports an empty string. The SDK never invents one, and a program that ignores metadata is unaffected.
Names need not be unique. Four cameras on one line may all legitimately be called oven; the SDK does not police it and will not silently rename anything. The serial remains the identity; use it, not the name, to decide which camera to open.

The name is one key among others

Metadata is an open key/value map, so a location, an asset tag or a line number needs no new API:

auto metadata = optris::sdk::ReadDeviceMetadata("21074191");
metadata.SetName("oven inlet");
metadata.Set("location", "hall 2");
metadata.Set("asset", "A-1174");
optris::sdk::WriteDeviceMetadata("21074191", metadata);

optris::sdk::kDeviceNameKey is the one key the SDK reads itself. Writing an empty value removes a key, and ClearDeviceMetadata() forgets a camera entirely.

Names in any script

Keys and values are UTF-8 everywhere (the C++ API, the C ABI and .NET), so a camera may be called 熔炉入口 or Ofeneinlauf as readily as oven inlet. What is stored is byte for byte what was supplied; nothing is escaped, transliterated or re-encoded on the way to disk or back.

  • The 63-byte limit is in bytes, not characters. That is 63 Latin letters, roughly 31 Greek or Cyrillic ones, and 21 Chinese or Japanese ones. Measure with Encoding.UTF8.GetByteCount(name) in .NET rather than name.Length.
  • An over-long name is refused, never truncated. Cutting UTF-8 to a byte count splits a multi-byte character and leaves invalid bytes.
  • Validation is about encoding, not alphabet. Ill-formed UTF-8 and control characters are rejected; nothing else is.
  • No Unicode normalisation is applied. Two names that look identical but differ in normal form (NFC against NFD) are two different values, and looking one up will not find the other. Normalise on the way in if you need them folded together.

If a name looks like nonsense in a Windows console, that is the console's code page and not the stored name; check the bytes rather than the terminal.

Enumeration order is not stable

Cameras do not come back in a fixed order, and the order can differ between two calls a second apart: USB and network devices are discovered by different means and arrive as they answer. Never identify a camera by its position. The name is attached to the serial, so a reordered list still shows each name against the right camera; but devices[0] is an arbitrary camera, not the same one as last time.

From a camera you already have open

Imager::Device() reaches the same store, so you need not carry the serial around:

imager->Device().SetName("oven inlet");
std::println("{}", imager->Device().GetName());

Imager::GetDeviceInfo().metadata is refreshed on connect, so it agrees with what enumeration showed.

From C and .NET

The C ABI carries the name in optris_sdk_device_info::name, and reads and writes it with optris_sdk_device_get_name(), optris_sdk_device_set_name() and the optris_sdk_device_metadata_* family. In .NET the name is DeviceInfo.Name, and the store is the static DeviceMetadata class. See Start Developing for how each binding is added to a project.

Ask The Camera What It Can Do

Read a camera's capabilities rather than inferring them from its model. A model table compiled into an application drifts from what the device actually answers, and that is how a feature comes to be offered in a user interface and then refused on the wire.

if (device.capabilities.has_pif) {
  // ...
}

Enumerating Off The Calling Thread

A network sweep waits out network_discovery_timeout, 3 seconds by default, whatever it finds, so run it on a thread of your own:

optris::sdk::EnumerationOptions opts;
opts.include_network = true;

std::jthread scan{[opts]() {
  auto devices = optris::sdk::EnumerateDevices(opts);
  std::println("Scan complete: {} total.", devices.size());
  // Hand `devices` back to your UI thread here -- it is a plain
  // vector of values, so there is nothing to keep alive.
}};

There is no callback-based form. The vector is returned by value: no handle to pass, no lifetime to manage across the hand-back, nothing to cancel or shut down.

For arrivals and departures rather than one sweep, use StartDeviceMonitor() (Hotplug Monitoring) instead of polling; that one owns its thread, because a monitor has to outlive the call that started it. For cameras on the network it needs DeviceMonitorOptions::watch_network set: without it the monitor reports USB only. See Watching for a camera on the network.

There is no EnumerateDevicesAsync()

Note: Three EnumerateDevicesAsync() overloads were declared and exported in the v12 headers before release, and never did anything: their bodies were empty from the commit that added them, so a call returned without sweeping and without calling either callback, and an application waiting on the completion callback waited for ever with no error to say why. They were removed rather than implemented, because the std::jthread above already is the answer. The EnumerationCallback and DeviceFoundCallback aliases went with them; nothing else used either.

Hotplug Monitoring

Monitor USB connect/disconnect events in real time:

optris::sdk::StartHotplugMonitor(
    [](const optris::sdk::DeviceInfo& d, bool added) {
      std::println("{}: {} S/N {}",
                   added ? "Connected" : "Disconnected",
                   optris::sdk::DeviceTypeToString(d.type),
                   d.serial);
    });

// ... later:
optris::sdk::StopHotplugMonitor();

StartHotplugMonitor() is USB only. It takes no options, so it has nowhere to put the poll interval a network search would need: the operating system pushes a bus event for a USB plug and nothing at all for a camera appearing on a network. StartDeviceMonitor() does both; see Watching for a camera on the network.

What an arrival carries, and what it does not

The DeviceInfo on a change comes from the hotplug event rather than from a full interrogation of the device, so the model may be empty and the width, height and capabilities may read zero or false. The serial is the field to act on: the SDK takes it from the operating system's own record, the serial the Linux kernel publishes in sysfs or the one in the Windows device-interface path, so neither platform has to open the camera to find out which one arrived. Enumerate when you need the full description.

The serial can still be empty, and a watcher has to cope. It is not promised to be set. Two cases produce an empty one: a camera whose USB descriptor carries no serial at all, or whose serial is not a number; and an arrival whose identity could not be read in the time the monitor allows, together with the removal that follows it, because a departure can only report what its arrival established and by then the device is gone. So treat an empty serial as unidentified rather than as a key. Two unnamed arrivals are two cameras: the SDK will not merge them and neither should a watcher, because both being unknown is not evidence that they are the same device.

Cameras already attached when you start watching arrive as arrivals too, so a watch loop opens them without a separate enumeration pass. If you enumerate as well, expect to see the same camera twice and deduplicate on the serial.

Which cameras are already in use

Each entry carries three claim fields.

Field Meaning
is_claimed Whether the camera can be opened. It includes your own program's claim: the claim is exclusive against every client, this process included, so opening a camera your program already has open is refused exactly as another program's open would be.
claimed_by_this_process Separates in use by me from in use by someone else; a camera list greys out the second and leaves the first alone. Do not parse claimed_by for your own process id instead, which is what claimed_by's own documentation has always said.
claimed_by Names the holder, optris-relay (pid 4711), on both platforms. On Linux it comes from the kernel's lock table; on Windows, where a sharing violation names nobody, from a small file the claiming process writes beside the lock. A claim taken by an older SDK version, or by another program, leaves no such file, so this can be empty for a camera that is definitely claimed, on either platform.
for (const auto &device : optris::sdk::EnumerateDevices()) {
  if (device.is_claimed) {
    std::println("{}: in use{}", device.model,
                 device.claimed_by.empty() ? ""
                                           : " by " + device.claimed_by);
  } else {
    std::println("{}: available", device.model);
  }
}

claimed_by_this_process can be false for a camera you are using. An Ethernet camera's claim state starts from the camera's own busy word, which says that someone is streaming and cannot say who, so a sweep that reads that word while you stream and reaches the claim file after you have let it go reports a claim with claimed_by_this_process == false. Read it as "known to be mine", not as "not mine".

All of it is a hint for a device list, never a promise. A camera can be claimed between the sweep that reported is_claimed == false and the Imager::Create() that follows. Grey out a row with it; never use it to decide that an open will succeed.

Watching for a claim

StartDeviceMonitor() is the superset: the same USB arrivals and removals as a DeviceChangeKind, plus kClaimed and kReleased when a camera is opened or let go with DeviceMonitorOptions::watch_claims set, plus cameras on the network with watch_network set. Claim watching is off by default because it costs a poll (claim_poll_interval, 1 s by default), and network watching for the same reason. There is one monitor per process: while one is running, a second StartHotplugMonitor() or StartDeviceMonitor() call does nothing, so stop the first before starting the other.

Your own opens and closes arrive here too, so the events do not mean another process. Use claimed_by_this_process on the device the change carries to tell them apart, rather than keeping your own record of which serials you have open.

optris::sdk::DeviceMonitorOptions monitor;
monitor.watch_claims = true;
optris::sdk::StartDeviceMonitor(monitor,
    [](const optris::sdk::DeviceInfo& d, optris::sdk::DeviceChangeKind kind) {
      if (kind != optris::sdk::DeviceChangeKind::kClaimed)
        return;
      if (d.claimed_by_this_process)
        return;  // we opened it ourselves
      std::println("S/N {} was opened by another process", d.serial);
    });

Watching for a camera on the network

Set DeviceMonitorOptions::watch_network and the monitor reports cameras on the network too. Without it there are no network events at all, and an application with only Ethernet cameras receives nothing:

optris::sdk::DeviceMonitorOptions monitor;
monitor.watch_network = true;
monitor.network_poll_interval = std::chrono::seconds{5};
monitor.network_discovery_timeout = std::chrono::seconds{2};
monitor.watch_claims = true;  // optional, and independent of the above

optris::sdk::StartDeviceMonitor(monitor,
    [](const optris::sdk::DeviceInfo& d, optris::sdk::DeviceChangeKind kind) {
      if (d.connection != optris::sdk::ConnectionType::kNetwork)
        return;  // the USB half, which arrives whether asked for or not
      if (kind == optris::sdk::DeviceChangeKind::kArrived)
        std::println("{} S/N {} answered at {}", d.model, d.serial, d.address);
      else if (kind == optris::sdk::DeviceChangeKind::kRemoved)
        std::println("S/N {} stopped answering", d.serial);
    });

A camera that answers discovery for the first time arrives as kArrived, carrying the same DeviceInfo an EnumerateDevices() with include_network would describe (address, port, model and claim state included), so pass it straight to Imager::Create() without a sweep of your own. One that stops answering leaves as kRemoved. With watch_claims also set, its claim transitions come from the camera's own busy word, which on Ethernet is the authoritative source.

Three things it is not:

  • It is not instant. A camera appears up to one network_poll_interval after it is powered, and leaves two intervals after it stops answering: one dropped UDP reply is not a camera leaving, so a removal needs consecutive silence. At the default 5 s interval a departure is seen around 10 s after the fact. No setting makes this immediate, because nothing on the host is told that a camera has appeared.
  • It is not every camera on the site. Discovery is a broadcast, and a broadcast reaches the local network segment only. A camera behind a router is invisible here however healthy it is; ProbeNetworkDevice() (Asking One Address) is the way to reach one you can name.
  • It is off by default, on cost. Nothing in the operating system reports a camera appearing on a network, so seeing one costs a broadcast and a wait, and silence takes as long to hear as an answer.

network_discovery_timeout is the budget one pass may spend waiting for replies, the same one EnumerationOptions applies to a single sweep. Keep it comfortably shorter than network_poll_interval or the poll never rests.

In C, the same three fields on optris_sdk_device_monitor_options: watch_network (a uint8_t), network_poll_interval_ms and network_discovery_timeout_ms. In .NET, DeviceWatchOptions.WatchNetwork and DeviceWatchOptions.NetworkPollInterval.

Auto-Reconnect

Prefer the imager's own methods: Imager::EnableAutoReconnect() and Imager::Reconnect(), described in Recovering. They say which camera.

The four functions here are the process-wide form: they apply to every camera this process has open, and to every one it opens afterwards.

optris::sdk::ReconnectConfig config;
config.max_attempts = 10;
config.initial_delay = std::chrono::milliseconds(500);
config.max_delay = std::chrono::seconds(30);
config.backoff_multiplier = 2.0f;

optris::sdk::EnableAutoReconnect(config);

// Check status.
bool active = optris::sdk::IsAutoReconnectEnabled();

// Re-open one camera now, once, with no backoff. Independent of
// whether automatic reconnection is on.
optris::sdk::TriggerReconnect("12345");

// Disable, on every open camera and any opened afterwards.
optris::sdk::DisableAutoReconnect();

Attempt n waits initial_delay * backoff_multiplier^(n-1), capped at max_delay. A max_attempts of zero or less means keep trying for as long as the camera is open.

EnableAutoReconnect() throws ConfigException for a configuration that is not a backoff: a multiplier below 1 shortens the wait after every failure, and an initial delay of zero is a retry loop with no wait in it. Both hammer a camera that is not there. TriggerReconnect() throws DeviceException, naming the serial, when this process has no such camera open. It re-opens a camera the program already has; it does not open one for the first time.

Complete Example

#include <optrissdk.h>
#include <print>
#include <thread>

using namespace optris::sdk;

int main() {
  // Real cameras only. Adding include_simulated here would make the
  // empty check below unreachable -- see the warning under Filtering.
  EnumerationOptions opts;
  opts.include_network = true;
  opts.network_discovery_timeout =
      std::chrono::milliseconds(5000);

  auto devices = EnumerateDevices(opts);
  if (devices.empty()) {
    std::println("No devices found.");
    return 1;
  }

  std::println("Found {} device(s):", devices.size());
  for (const auto& d : devices) {
    std::println("  {} S/N {} [{}] {}x{}{}",
                 DeviceTypeToString(d.type),
                 d.serial,
                 ConnectionTypeToString(d.connection),
                 d.width, d.height,
                 d.is_claimed ? "  (in use)" : "");
  }

  // Start hotplug monitoring.
  StartHotplugMonitor(
      [](const DeviceInfo& d, bool added) {
        std::println("Hotplug: {} {} S/N {}",
                     added ? "+" : "-",
                     DeviceTypeToString(d.type),
                     d.serial);
      });

  // Connect to the first device.
  auto imager = Imager::Create(devices[0]);
  imager->SetThermalCallback(
      [](const ThermalFrame& f) {
        // Frames from before the startup calibration has finished
        // arrive too, and are not measurements.
        if (!f.GetMetadata().thermal_data_reliable) return;
        std::println("{}x{} max={:.1f} C",
                     f.GetWidth(), f.GetHeight(),
                     f.GetMaxTemperature());
      });

  imager->Start();
  std::this_thread::sleep_for(std::chrono::seconds(10));
  imager->Stop();

  StopHotplugMonitor();
  return 0;
}