Dropped Connections
How the SDK reports a camera that has stopped sending frames, what it does about it, what survives a recovery, and how to test the handling without unplugging anything.
The device-communication chapter is three pages:
| Page | Question |
|---|---|
| Device Communication | What does opening a camera involve, what does it do over USB, and how long does it wait? |
| Ethernet Cameras | How do I reach one over the network, and set its address? |
| Dropped Connections | It dropped out. What does the SDK do, and what do I have to do? |
On this page
Noticing a dropped connection
The case that matters is not an unplugged camera. It is a host that sleeps and wakes: the camera is still open, the operating system still lists it as present and healthy, the SDK's own enumeration still finds it, and no frame ever arrives again. IsConnected() answers true throughout. ConnectionStatus::Stalled is how you find out.
imager->SetConnectionStatusCallback( [&](const ConnectionStatusChange& change) { // Transitions only: a link that is dead and stays dead reports // Stalled once, not once per timeout period. std::println("connection: {} -> {}{}", ToString(change.previous), ToString(change.current), change.message.empty() ? "" : " (" + change.message + ")"); switch (change.current) { case ConnectionStatus::Connected: ui.ShowLiveImage(); break; case ConnectionStatus::Stalled: // Still plugged in, may come back on its own. Stop calling // the picture live; the recovery gets its own transition. ui.ShowStaleImageWarning(); break; case ConnectionStatus::Lost: case ConnectionStatus::Failed: // Will not come back without being re-opened. ui.OfferReconnect(); break; default: break; } });
/* Transitions only: a link that is dead and stays dead reports * Stalled once, not once per timeout period. */ static void OTC_SDK_C_CALL OnStatus(optris_sdk_connection_status previous, optris_sdk_connection_status current, const char *message, void *user_data) { struct Ui *ui = (struct Ui *)user_data; (void)previous; (void)message; switch (current) { case OPTRIS_SDK_CONNECTION_CONNECTED: ShowLiveImage(ui); break; case OPTRIS_SDK_CONNECTION_STALLED: /* Still plugged in, may come back on its own. */ ShowStaleImageWarning(ui); break; case OPTRIS_SDK_CONNECTION_LOST: case OPTRIS_SDK_CONNECTION_FAILED: /* Will not come back without being re-opened. */ OfferReconnect(ui); break; default: break; } } optris_sdk_imager_set_connection_status_callback(imager, OnStatus, ui);
// Transitions only: a link that is dead and stays dead reports // Stalled once, not once per timeout period. camera.OnConnectionStatus(change => { switch (change.Current) { case ConnectionStatus.Connected: ui.ShowLiveImage(); break; case ConnectionStatus.Stalled: // Still plugged in, may come back on its own. ui.ShowStaleImageWarning(); break; case ConnectionStatus.Lost: case ConnectionStatus.Failed: // Will not come back without being re-opened. ui.OfferReconnect(); break; } });
def on_status(change): # Transitions only: a link that is dead and stays dead reports # stalled once, not once per timeout period. if change.current == optris_sdk.CONNECTION_CONNECTED: ui.show_live_image() elif change.current == optris_sdk.CONNECTION_STALLED: # Still plugged in, may come back on its own. ui.show_stale_image_warning() elif change.current in (optris_sdk.CONNECTION_LOST, optris_sdk.CONNECTION_FAILED): # Will not come back without being re-opened. ui.offer_reconnect() camera.on_connection_status(on_status)
// Transitions only: a link that is dead and stays dead reports // Stalled once, not once per timeout period. camera.on_connection_status(move |change| match change.current { ConnectionStatus::Connected => ui.show_live_image(), ConnectionStatus::Stalled => { // Still plugged in, may come back on its own. ui.show_stale_image_warning(); } ConnectionStatus::Lost | ConnectionStatus::Failed => { // Will not come back without being re-opened. ui.offer_reconnect(); } _ => {} })?;
Registering does not replay the status already in force, so seed the display once after registering:
ui.SetStatus(imager->GetConnectionStatus());
optris_sdk_connection_status status; optris_sdk_imager_get_connection_status(imager, &status); SetStatus(ui, status);
ui.SetStatus(camera.ConnectionStatus);
ui.set_status(camera.connection_status)
ui.set_status(camera.connection_status()?);
A network camera that is unplugged or switched off
Nothing reports a network camera gone. A USB camera that is unplugged is reported by the operating system, and the SDK publishes Lost at once. A camera on the network just stops sending, and from the stream alone that looks exactly like a stall from a camera that is still there. So the SDK asks the camera.
Once no frame has arrived for one second, the SDK sends the camera the identification request the camera search uses, at the address it was opened at, once a second. The request only asks the camera who it is: it opens no connection, writes no setting and does not move the camera's stream. An answer from a camera with another serial number counts as no answer.
- No answer to three requests in a row, and no frame for the connection timeout:
Lost, with a message that says the camera stopped answering. With the default connection timeout of ten seconds that is ten seconds after the last frame, and never sooner than about four. A camera that stops answering later, after it was already reportedStalled, moves toLostwithin about four seconds of its last answer. - The camera still answers:
Stalled, with the warning that the stream stalled while the device is still open, exactly as before.
IsConnected() still answers true in both cases: the imager is open until you close it or the SDK re-opens it.
An Xi 640 ETH that restarts while it is open, after a short power cut for example, comes back in its own temperature mode and goes on sending pictures to your computer, which the SDK would otherwise read as the raw sensor values it set the camera up for. The camera reports its operating mode once a second. As soon as that is not the mode the SDK set up, its pictures are no longer passed on, and after the second such report the status is Lost. A recovery then opens the camera from the start, startup calibration included.
A restarting camera can send pictures before its first report, so after any pause of one second or more in its pictures the ones that follow are held back until a report says the mode is still the one the SDK set up. After a short network interruption that costs the pictures of at most about one second. Pictures with no report for five seconds are Lost in the same way.
Recovering
Let the SDK do it
One call, and a camera that drops is re-opened and streaming again with the settings it had, without the application writing a recovery loop:
ReconnectConfig policy; // 10 attempts, 500 ms doubling to 30 s imager->EnableAutoReconnect(policy);
optris_sdk_reconnect_config policy; /* 10 attempts, 500 ms to 30 s */ optris_sdk_reconnect_config_init(&policy, sizeof(policy)); optris_sdk_imager_enable_auto_reconnect(imager, &policy);
// The defaults: 10 attempts, 500 ms doubling to 30 s. camera.EnableAutoReconnect();
# The defaults: 10 attempts, 500 ms doubling to 30 s. camera.enable_auto_reconnect()
// The defaults: 10 attempts, 500 ms doubling to 30 s. camera.enable_auto_reconnect(&ReconnectConfig::default())?;
Frame callbacks stop when the camera stops and resume when it comes back. The connection status transitions (Connected to Lost or Stalled, then Connecting, then Connected) are what a user interface shows, so the gap is honest to an operator rather than a frozen picture.
What counts as a drop
Lost, Stalled, Disconnected, and Failed after a session that worked. Failed is what an acquisition-thread error publishes, so it is the one drop no cable-pull produces; it is inside the trigger set, so no application needs a reopen loop of its own for that case alone. A Failed raised by the first open is deliberately left alone: your program asked for that open and is holding the error, and retrying it behind your back is not recovery.
A camera that never delivered a frame is left alone. Connected is published at the end of the open, before any frame, so an open on its own cannot tell a session that worked from one that merely opened. A camera that is being asked for frames and has never delivered one is therefore not recovered. The case is the firewalled one: the control connection succeeds, the format is read correctly, and no frame ever arrives, which stalls. Before this rule, that camera was recovered, stalled again, and spent the whole attempt budget on a re-open that cannot help it, because nothing a re-open does unblocks the port. Two things it does not withhold: a camera you opened and never started, which has no frame to wait for, and a camera that delivered frames and has since gone quiet or been stopped. One frame is enough, for the whole life of the camera; the question is whether it ever delivered, not whether it is delivering now.
Where a failed attempt comes to rest
At Failed, always. The sequence for one drop and one failed attempt is Lost or Stalled, then Connecting, then Disconnected, then Connecting, and finally Connected or Failed.
An absent or busy camera is waited for, not hammered
Before each attempt the SDK sweeps USB. A camera the sweep does not list, and a camera the sweep lists but another process holds, both produce ReconnectPhase::kWaitingForDevice: no attempt is made and no attempt is spent, so the budget is not burned on a camera that is away or on a claim that is going to refuse. The message says which of the two it is. The wait still backs off, so an absent camera is looked for every thirty seconds rather than ten times a second.
A lone camera is waited for too. The sweep answers a second question besides what it found: whether it was able to read the bus at all. An empty result from a bus it could read means the camera is absent, so it is waited for without spending attempts; a sweep that could not look is never read as the camera being present. Both platforms answer that question, and each asks the library its own enumeration runs on: Linux asks libusb for a device list, Windows reads it off the device interface sweep that produces its device list, whose SetupDiGetClassDevsW() call fails distinguishably where an empty list does not. It is deliberately not a separate probe on either, because two independently written looks could disagree about a bus one of them is interpreting the emptiness of. Where readability cannot be established the SDK concludes nothing and attempts anyway, exactly as it did before: the cost of being wrong that way is the wasted attempts this gate saves, while the cost of being wrong the other way is a camera that is present and openable never being re-opened.
A network camera is looked for by its serial number
Before each attempt the SDK looks for the camera on the network: first at the address it was at, with one identification request, then with the camera search's broadcast, matched on the serial number. Nothing is written to the camera. Found at another address, for example after a DHCP server gave it a new one, it is re-opened there. Found nowhere, it is waited for exactly like an unplugged USB camera: ReconnectPhase::kWaitingForDevice, with a message saying it does not answer on the network, and no attempt spent. The search runs on the reconnect thread and takes at most about four seconds. A camera that has never answered the identification request from this computer is attempted on the backoff schedule as before, because its silence proves nothing: a broadcast does not cross a router, and some networks drop the request.
A stall that heals on its own costs nothing. The connection status is re-read before every attempt, so a link that comes back during a backoff wait is not torn down and re-opened: no second startup calibration, and a running recording is left alone. That recovery reports kRecovered with attempt 0, which is how an application tells it from one that took work.
SetReconnectCallback() reports the attempts themselves, which the status alone cannot distinguish from a camera that is simply gone. Every event names the camera it is about: serial and model, cached before the first attempt, which is what makes them usable after kGaveUp. The engine underneath reports serial 0 once the camera is closed, so an identity read fresh at that point would name no camera. The cached DeviceInfo keeps the serial it had before the outage, and is refreshed only by a successful open, so GetDeviceInfo() still names the camera after a give-up.
imager->SetReconnectCallback([](const ReconnectEvent& event) { switch (event.phase) { case ReconnectPhase::kAttempting: ui.ShowReconnecting(event.serial, event.attempt, event.max_attempts); break; case ReconnectPhase::kWaitingForDevice: ui.ShowWaitingForCamera(event.serial); break; case ReconnectPhase::kRecovered: ui.ShowLiveImage(); break; case ReconnectPhase::kGaveUp: ui.ShowGaveUp(event.serial, event.message); break; default: break; } });
static void OTC_SDK_C_CALL OnReconnect(const optris_sdk_reconnect_event *event, void *user_data) { struct Ui *ui = (struct Ui *)user_data; switch (event->phase) { case OPTRIS_SDK_RECONNECT_ATTEMPTING: ShowReconnecting(ui, event->serial, event->attempt, event->max_attempts); break; case OPTRIS_SDK_RECONNECT_WAITING_FOR_DEVICE: ShowWaitingForCamera(ui, event->serial); break; case OPTRIS_SDK_RECONNECT_RECOVERED: ShowLiveImage(ui); break; case OPTRIS_SDK_RECONNECT_GAVE_UP: ShowGaveUp(ui, event->serial, event->message); break; default: break; } } optris_sdk_imager_set_reconnect_callback(imager, OnReconnect, ui);
camera.OnReconnect(e => { switch (e.Phase) { case ReconnectPhase.Attempting: ui.ShowReconnecting(e.Serial, e.Attempt, e.MaxAttempts); break; case ReconnectPhase.WaitingForDevice: ui.ShowWaitingForCamera(e.Serial); break; case ReconnectPhase.Recovered: ui.ShowLiveImage(); break; case ReconnectPhase.GaveUp: ui.ShowGaveUp(e.Serial, e.Message); break; } });
def on_reconnect(event): if event.phase == optris_sdk.RECONNECT_ATTEMPTING: ui.show_reconnecting(event.serial, event.attempt, event.max_attempts) elif event.phase == optris_sdk.RECONNECT_WAITING_FOR_DEVICE: ui.show_waiting_for_camera(event.serial) elif event.phase == optris_sdk.RECONNECT_RECOVERED: ui.show_live_image() elif event.phase == optris_sdk.RECONNECT_GAVE_UP: ui.show_gave_up(event.serial, event.message) camera.on_reconnect(on_reconnect)
camera.on_reconnect(move |event| match event.phase { ReconnectPhase::Attempting => { ui.show_reconnecting(&event.serial, event.attempt, event.max_attempts); } ReconnectPhase::WaitingForDevice => { ui.show_waiting_for_camera(&event.serial); } ReconnectPhase::Recovered => ui.show_live_image(), ReconnectPhase::GaveUp => { ui.show_gave_up(&event.serial, &event.message); } _ => {} })?;
Stopping the recovery
SetReconnectAttemptCallback() is asked before each attempt and can refuse it: for a device you have deliberately powered down, a tile the operator has closed, a camera you know has been re-addressed. Returning false stops the recovery altogether; the SDK publishes kGaveUp and stops, and a later EnableAutoReconnect() starts it again.
It is a yes or a no, and there is deliberately no "not now". false is final, not a skip, so a handler that refuses one attempt because the camera is briefly unreachable has ended the recovery rather than postponed it. Return true in that case. The deferral is already in the SDK: the presence gate above withholds attempts for an absent or foreign-held camera without spending any, reporting kWaitingForDevice, and it re-asks on every wait, so a camera unplugged over a weekend is still being looked for on Monday whether your handler knows it is absent or not. Keep the handler for the decisions only your application can make.
imager->SetReconnectAttemptCallback( [&](const DeviceInfo& device, int attempt, int max_attempts) { return !maintenance_mode.load(); });
static int OTC_SDK_C_CALL OnAttempt(const char *serial, const char *model, int32_t attempt, int32_t max_attempts, void *user_data) { (void)serial; (void)model; (void)attempt; (void)max_attempts; (void)user_data; return !maintenance_mode; } optris_sdk_imager_set_reconnect_attempt_callback(imager, OnAttempt, NULL);
camera.OnReconnectAttempt(attempt => !maintenanceMode);
camera.on_reconnect_attempt( lambda serial, model, attempt, max_attempts: not maintenance_mode)
camera.on_reconnect_attempt(move |_serial, _model, _attempt, _max| { !maintenance_mode.load(std::sync::atomic::Ordering::Relaxed) })?;
IsAutoReconnectEnabled() reports the state, not the request. It reads false once the SDK has given up, because at that point nothing is watching the camera. Switch it back on with another EnableAutoReconnect().
Testing without a cable
A simulated camera can be asked to pretend its link was lost, so a handler runs because a test asked it to:
optris_sdk_testing_fake_connection_event( imager, OPTRIS_SDK_CONNECTION_LOST, "the test pulled it");
using Optris.Sdk.Testing; FaultInjection.FakeConnectionLost(camera);
optris_sdk.faults.fake_connection_event( camera, optris_sdk.CONNECTION_LOST, 'the test pulled it')
optris_sdk::faults::fake_connection_event( &mut camera, ConnectionStatus::Lost, "the test pulled it")?;
In .NET it is Optris.Sdk.Testing.FaultInjection.FakeConnectionLost(camera), with FakeConnectionStalled and FakeConnectionFailed beside it and FakeConnectionEvent for the general form.
The naming is deliberate and so is the namespace. These are not things a camera does, they are things a test does to a camera, so they sit outside the ordinary call families in both surfaces: a C# file has to write using Optris.Sdk.Testing; before it can reach FaultInjection, and the C entry point is not in the optris_sdk_imager_* family. Nothing here works on a real camera: every call refuses one, which is the safety property rather than a limitation.
Two boundaries. It does not make a camera come back: a simulated camera has no device to re-open, so the attempts fail and the schedule runs to kGaveUp. That makes "what does my application show during an outage,
and when recovery is abandoned" testable, and leaves "what does it show
when the camera returns" needing hardware. And faking Connected or Connecting is refused, because those are the SDK's own answers about an open it performed; a handler told the camera is back when nothing opened has been misled in the direction that hides a fault.
Imager::Reconnect() does one attempt, synchronously, now, for a "Reconnect" button, and independent of whether automatic reconnection is switched on.
What survives a reconnect
Everything you set through the imager. The palette (built-in or custom), the colour range and auto-scale policy, the colour-scale dynamics, the temperature range and operation mode, the radiation parameters, the regions, the alarm rules, the colour windows, the orientation, the connection timeout, the process-interface configuration, and every registered callback. The imager object is the same object; it is the camera underneath that is replaced.
What does not survive is what belonged to the old session rather than to the configuration: the startup calibration runs again, and a recording in progress is stopped and finalized before the teardown. The file on disk is complete and playable, RecordingPhase::kStopped reaches the handler registered with Recorder::OnRecording(), and nothing is written into it afterwards. Open a second recording when you see kRecovered if that is what you want; one file per session is the only honest shape, because a file that silently hides a two-minute outage is worse than one that stops.
A time-lapse keeps running and writes nothing while the camera is away. The SDK drops its retained last frame with the link, so Recorder::SaveSnapshot() throws "no frame captured yet" and the interval writer skips, instead of writing the last live frame under a filename carrying the current timestamp, indistinguishable in the directory from an image that had just arrived.
Nothing is written to this machine's saved configuration for the camera. A recovery is not a decision about how to open it next time.
A reconnect is a re-open, not a retry
The device handle is genuinely invalidated by a suspend or a replug rather than made stale: on Windows the Media Foundation read fails with 0xc00d3ea2 and the asynchronous read chain is never re-armed, so there is nothing to resume. The SDK therefore destroys the whole session (streaming stopped, source reader destroyed, control channel closed, host claim released) and opens a fresh one. Expect a reconnect to cost what an open costs, startup calibration included, not what a resumed stream would.
One consequence: the camera is genuinely unclaimed for the width of the gap between the close and the open, so another process can take it. The attempt then fails and the next one tries again.
A reconnect is not considered successful until a frame has arrived, if the application had asked for frames when the link dropped. An open can succeed against a stream session the operating system has not finished tearing down, accept every read and complete none; an open that returns is therefore not a claim the SDK is willing to make on its own. A camera that was open and stopped is re-opened and left stopped, and kRecovered is published without waiting for a frame nobody asked for, so do not read that phase as "frames are flowing" unless you had started the stream.
Doing it yourself
If you would rather drive it, destroy the imager and create a new one. Everything the application had applied belongs to that imager and has to be applied again to its replacement: the SDK keeps no copy across a Create(), which is exactly what EnableAutoReconnect() spares you.
Warning: Not from inside the status handler, and not from inside the reconnect handler. A handler is the obvious place to put it, and it is the one place it cannot happen: the handler runs on an SDK thread that the recovery tears down, and it cannot wait for itself. Reconnect() throws rather than hanging, and destroying the imager from a status handler is refused with a line naming it.
The same goes for registering or clearing a handler from inside itself.
Set a flag in the handler, and recover on a thread of your own:
std::atomic<bool> recover{false}; imager->SetConnectionStatusCallback( [&](const ConnectionStatusChange& change) { switch (change.current) { case ConnectionStatus::Stalled: ui.ShowStaleImageWarning(); break; case ConnectionStatus::Lost: case ConnectionStatus::Failed: ui.OfferReconnect(); recover = true; // and nothing else from here break; default: break; } }); // Your own loop, your own thread. while (running) { if (recover.exchange(false)) { imager->Reconnect(); // settings kept, or: // imager.reset(); // the long way round // imager = Imager::Create(config); // ReapplyEverything(*imager); } std::this_thread::sleep_for(std::chrono::milliseconds(250)); }
Clearing the handler is a fence. Once SetConnectionStatusCallback({}) returns, no handler is still running, so anything the handler captured is safe to destroy. DisableAutoReconnect() is a fence in the same way.
In .NET: ThermalCamera.ConnectionStatus and ThermalCamera.OnConnectionStatus(Action<ConnectionStatusChange>?). In C: optris_sdk_imager_get_connection_status() and optris_sdk_imager_set_connection_status_callback(). There was an older optris_sdk_imager_set_connection_callback() that reduced all of it to a bool and could not distinguish a stall from a disconnect; it went at API version 30.
Reconnection in .NET: ThermalCamera.Reconnect() and ReconnectAsync(), EnableAutoReconnect(ReconnectConfig?), DisableAutoReconnect(), IsAutoReconnectEnabled, GetReconnectConfig(), OnReconnect(Action<ReconnectEvent>?) and OnReconnectAttempt(Func<ReconnectAttempt, bool>?). Prefer ReconnectAsync() from a UI thread, and from inside a status handler; a reconnect costs what an open costs, and the SDK thread the status handler runs on is one that must not perform it.
In C: optris_sdk_imager_reconnect(), optris_sdk_imager_enable_auto_reconnect() over optris_sdk_reconnect_config (initialise with optris_sdk_reconnect_config_init()), optris_sdk_imager_disable_auto_reconnect(), optris_sdk_imager_is_auto_reconnect_enabled(), optris_sdk_imager_get_reconnect_config(), optris_sdk_imager_set_reconnect_callback() and optris_sdk_imager_set_reconnect_attempt_callback().