OptrisOptrisDocumentation

Documentation/OTC SDK/Overviewv12.0

Alarms

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

A rule watches one signal, applies a condition, and runs actions when its state changes. There is one alarm model.

Rules live on Imager::Alarms() (a RuleEngine); regions on Imager::Regions() (a RegionEngine). A Player has both, so a recording is alarmed exactly like a live camera.

A signal is a region's statistic, camera telemetry, a PIF channel, or a value your own application publishes. Region, PIF and application alarms are one mechanism, differing only in which signal the rule names.

optris::sdk::Rule rule;
rule.name = "over temp";
rule.input = optris::sdk::SignalId::Region(0, optris::sdk::SignalField::kMax);
rule.condition.compare = optris::sdk::Compare::kAbove;
rule.condition.alarm.high = 60.0f;
const auto rule_id = imager->Alarms().Add(region_id, std::move(rule));

Add() returns 0 when the region or the rule is invalid, and logs why as a warning that names the part refused: a region that does not exist, or an input, inhibit or reference that cannot be evaluated. The C function's last error and the C#, Python and Rust exceptions carry the same reason. Rules attached to a region belong to it and are removed with it. Other rules live in a flat set on the imager.

For the regions themselves, see Regions.

Signals

A SignalId is a (domain, field, index) triple.

Domain Index means Fields
kRegion the region's signal slot kMin, kMax, kMean, kMedian, kStdDev, kCoverage, kArea, kHotSpotX/Y, kColdSpotX/Y, kBlobCount, kThresholdShare, kP01, kP05, kP95, kP99
kDevice unused kFlagTemp, kBoxTemp, kChipTemp, kFpaTemp, kAmbientTemp, kSceneMin, kSceneMax, kFocusPosition, kFrameRate, kDroppedFrames, kFlagOpen, kNucInProgress, kConnected, kProbeTemp, kDeliveryShare
kPif PIF channel kDigitalIn, kDigitalOut, kAnalogIn, kAnalogOut, kFlag, kFailSafe
kMotion motion zone id kMotionBlobCount, kMotionArea, kMotionVelocity
kUser your slot kValue

kFlagOpen and kNucInProgress

Both come from the shutter, not from frame metadata, and change on the transition itself. A live camera dispatches no frame while its shutter is closed, so an inhibit of the shape "silence this alarm while the shutter is closed" holds for the 1–2 s the cycle lasts: the rules carrying it are re-evaluated at each transition, without waiting for the next frame. kNucInProgress is high from the start of closing until the shutter is open again. On playback both come from the recorded frame.

Fields with no producer

Four device fields have no producer yet: kFpaTemp, kFocusPosition, kFrameRate and kDroppedFrames. A rule on one is accepted and then reports kOrphaned for ever. Nothing refuses it and nothing logs. scripts/check_alarm_signal_producers.py fails the build if an enumerator is unproduced and undeclared, if a declared one turns out to be published after all, or if a declared one does not say so on its own declaration in alarm.h, sdk_c.h and Enums.cs.

kDroppedFrames, and kDeliveryShare instead

kDroppedFrames is the field most likely to be reached for. Three quantities could claim the name, so no one-line change closes it:

Candidate Where it stands
the pull queue's own discards GetDroppedFrameCount() reports it, and a frame-callback application accrues it on essentially every frame: that queue is fed whether or not anyone pulls
frames the camera sent that never arrived counted below the hardware abstraction layer, unreadable above it, absent entirely on several shipping camera paths
the share of the camera's own frames that reached the pipeline the sound measurement, but a share and not a count

SDK 11 shipped one counter meaning all three at once, so it meant none. SDK 12 removed it.

The third is published as kDeliveryShare: 0 to 1, 1 being every frame the camera took, so a rule reading below 0.9 is "this host is losing more than one frame in ten". It is measured against the camera's own frame counter, not a clock. Every rate the SDK publishes is measured where frames arrive, so a host receiving one frame in three measures a third of the rate and reports a perfectly healthy camera running slowly. It is counted ahead of the frame-rate reducer and the 9 Hz export restriction, so a camera subsampled to 4 Hz reads 1, not 0.125; otherwise every export-restricted camera and every reduced stream would alarm.

It reports kOrphaned rather than comparing its limits against a zero on a camera whose frames carry no counter, one that has not yet delivered two frames whose telemetry decoded, and one whose counter jumped further than a stream legitimately can. A share of 0 is a reading, a host receiving nothing, not a sentinel. A Player and a StillSource read as unmeasured: a recording does not carry the live host's delivery health.

kDroppedFrames is kept, not removed. It is number 109, the tenth of fifteen device fields, and the numbers are on disk (a saved region writes SignalField as its raw integer). Deleting it would load every stored rule naming kFlagOpen, kNucInProgress, kConnected or kProbeTemp against the quantity below the one it was saved against. Removal is safe for a block's last enumerator only.

kFlag, kConnected and kAmbientTemp

SignalField::kFlag in the PIF domain does have a producer. It is published while a PIF input owns the shutter flag and not otherwise, so a rule on it reads kOrphaned rather than a confident 0: "nothing is holding the flag" is not "no input is configured to hold it". It is indexed by the channel driving it. kFlagOpen answers a different question: the shutter is in the way, whoever put it there.

kConnected has a producer but is only ever published as true, so a rule on it never sees a disconnect. kAmbientTemp is published on every frame carrying a valid ambient temperature, in both modes: the estimate while estimate_ambient is set, the configured ambient_temp_c when it is not.

Fields published only on request

Seven fields are published only on request, and report kOrphaned rather than a plausible-looking zero when nothing asked.

Field Published while Carries
kThresholdShare that region was added with Region::threshold enabled the fraction 0..1 of the region past its threshold
kMedian, kP01, kP05, kP95, kP99 Region::want_percentiles is set all five come out of the one pass it pays for, so they exist together or not at all
kProbeTemp a frame's PIF telemetry carries a reading and the PIF is declared kTemperatureProbe the external temperature probe's reading in degrees Celsius

kProbeTemp is a device field, not a PIF-channel one: one probe per camera, no channel index. A rule on it sits orphaned on a camera with no probe fitted, including one whose probe bus never answers: presence is decided at the frame decode, per camera family, by the bus answering validly, so an unpopulated connector orphans the rule rather than firing it at a full-scale 511.9375 °C, and a Compare::kInvalid watchdog beside it fires.

How to compare each field

  • kFlagOpen, kNucInProgress and kConnected carry 0.0 or 1.0. Compare them with kEqual, not kAbove.
  • kArea is a pixel count, not a physical area.
  • kP99 is the robust hot value: a few noisy or dead pixels do not trip it the way they trip kMax, and on a small region it is not the same number as kMax. A spot, a hot spot and a cold spot report these over the pixels their aperture reached, nine for a 3×3.
  • kBlobCount means two things by kind: on a kBlobGroup, the blobs detected this frame; on every other kind, all of a region's children, not only blobs.

A region rule's slot is filled in for you

For a region rule added through Alarms().Add(region_id, rule) the slot is filled in for you: pass 0, or use the one-argument SignalId::Region(field). It is filled in again on every Alarms().Update(), so a rule rebuilt from the thresholds on screen and written back stays on its own region, with no read-back needed.

RegisterSignal and PublishSignal

Application values are registered by name and published whenever you have one. Rules on them are evaluated immediately, so a free alarm works on a camera that is not even streaming:

const auto slot = imager->Alarms().RegisterSignal("line pressure");
imager->Alarms().PublishSignal(slot, 4.2);

ReadSignal

Any signal can be read back, whatever its domain:

const auto value = imager->Alarms().ReadSignal(
    optris::sdk::SignalId::Device(optris::sdk::SignalField::kChipTemp));
if (value.valid) { /* value.value */ }

A region's slot is generational

Removing a region invalidates it, so a rule still holding it reads back nothing rather than binding to whatever region reuses the slot. Generations start at 1, so a packed slot of 0 never names a live region. It means "not resolved yet", and a signal left that way reports kOrphaned.

Naming a different region

Point an inhibit (or, later, a comparison) at a region other than the rule's own by asking the camera for that region's slot:

const auto door = imager->Regions().SignalSlot(furnace_door_id);
if (!door)
  return;  // the region is gone

optris::sdk::Rule bearing;
bearing.input = optris::sdk::SignalId::Region(optris::sdk::SignalField::kMax);
bearing.condition.compare = optris::sdk::Compare::kAbove;
bearing.condition.alarm.high = 90.0F;

// Silence it while the furnace door region is above 200 C.
optris::sdk::Inhibit while_open;
while_open.signal =
    optris::sdk::SignalId::Region(*door, optris::sdk::SignalField::kMax);
while_open.condition.compare = optris::sdk::Compare::kAbove;
while_open.condition.alarm.high = 200.0F;
bearing.inhibit.push_back(while_open);

imager->Alarms().Add(bearing_id, bearing);

An inhibit whose slot is still 0 means "this rule's own region" and is resolved with the input. One carrying a slot is left exactly as you set it, on Add and on Update alike.

The slot is a runtime handle, not an identity: it changes when a region is removed and re-added, and means nothing on another camera. Resolve it where you use it rather than storing it beside the rule. In C it is optris_sdk_imager_get_region_signal_slot(), in .NET ThermalCamera.GetRegionSignalSlot().

A replay removes and re-creates a recording's own regions by itself, when it passes a frame they were not on: a seek back past where the take drew a region, or a loop wrap past where it deleted one. That is not a region removed and re-added by you. The rules on it are kept, and when the region comes back under its recorded id every rule input and inhibit that named its old slot is moved onto the new one, so the rule reads it again from the next frame. See A seek and a loop rebuild the measuring areas.

Motion zones

A motion zone publishes what it detects, so an alarm on motion is an ordinary rule:

optris::sdk::MotionZone zone;
zone.temp_min_c = 30.0f;    // only movement in this band counts
zone.temp_max_c = 90.0f;
imager->Motion().SetZone(1, zone);

optris::sdk::Rule intruder;
intruder.name = "motion in zone 1";
intruder.input = optris::sdk::SignalId::Motion(
    1, optris::sdk::SignalField::kMotionBlobCount);
intruder.condition.compare = optris::sdk::Compare::kAbove;
intruder.condition.alarm.high = 0.0f;    // any blob at all
intruder.condition.on_delay = std::chrono::milliseconds(100);
intruder.actions.push_back(
    {optris::sdk::ActionTrigger::kOnActivate,
     optris::sdk::RecordingAction{}});
imager->Alarms().Add(std::move(intruder));

Removing a zone does not clear the rules watching it. Their signals stop being published, so a rule holds whatever it last saw, including a latched kActive that nothing will now clear. Remove or disable those rules alongside the zone.

This replaces the removed SetMotionAlarm(), which carried its own threshold model, fired on every frame the condition held rather than on a transition, and started recordings on the frame thread with a filename of its own choosing. As a rule it gets hysteresis, delay frames, latching, a warning band, inhibit sources and the action model like anything else.

Rules

struct Rule {
  uint64_t id;                    // assigned on Add
  std::string name;
  bool enabled = true;
  SignalId input;
  Condition condition;
  std::vector<Inhibit> inhibit;
  std::vector<Action> actions;
};

Rules are edited in place, validated before the edit is applied:

imager->Alarms().Update(rule_id, [](optris::sdk::Rule &r) {
  r.condition.alarm.high = 65.0f;
});

An invalid edit is rejected and the rule is left unchanged. It is reported the way an unknown rule is: Update() returns false in C++ and UpdateRule() in .NET, C returns OPTRIS_SDK_ERROR_NOT_FOUND, Python raises NotFoundError and Rust returns Status::NotFound, not the invalid-argument error a refused Add() gives. The message, or in C++ the logged warning, names the part that was refused.

Rules in a saved configuration

SaveConfig() writes every rule and LoadConfig() puts it back: a free rule with the file's rules, and a rule added to a region with that region, so it comes back on the same region under the id the region gets. The record GetConfig() returns holds the same rules, each region's in its Region::rules, and ApplyConfig() puts them back the same way. A rule that names its own region keeps naming it wherever the region's slot moves. What a record and a file carry of a comparison is in Comparing two signals.

A file saved by an earlier version holds no rules on its regions: those versions left every rule added to a region out of the record and the file. An earlier version reads a file with region rules and puts them back, comparing their input alone.

Being told

The event carries everything needed to describe the transition, so a handler never has to call back into the camera.

await foreach (AlarmEvent e in camera.AlarmEventsAsync(token))
{
    if (e.Current == AlarmState.Active)
    {
        Console.WriteLine($"{e.RuleName}: {e.Value:F1} crossed {e.Limit:F1}");
    }
}

Order events by sequence, not by timestamp. The timestamp's origin depends on what drove the evaluation: a rule on a region or on camera telemetry is evaluated on a frame and carries that frame's clock, which runs from the camera's start, while a rule on a value the application published is evaluated immediately and carries wall-clock time. Comparing the two gives an answer wrong by decades. The sequence number is consistent across all of them.

Unlike frames, this stream is unbounded: alarms are rare and each one matters, so dropping the oldest would be the wrong trade.

Suppressing without disabling

An inhibit source is just another signal, so an operator can silence alarms during a known disturbance without turning the rule off.

// Silence it while PIF digital input 0 is high.
optris::sdk::Inhibit during_blow_off;
during_blow_off.signal =
    optris::sdk::SignalId::Pif(0, optris::sdk::SignalField::kDigitalIn);
during_blow_off.condition.compare = optris::sdk::Compare::kAbove;
during_blow_off.condition.alarm.high = 0.5F;
rule.inhibit.push_back(during_blow_off);

If the suppressing signal stops arriving, the rule alarms. Suppression fails towards the alarm working, never towards silence.

Comparing two signals

A rule can compare its input with a second signal instead of with fixed limits: one bearing more than 15 K hotter than the housing beside it, a spot more than 5 K away from a reference region, a region's mean above a setpoint your application publishes. Set the rule's reference, and every band of its condition is tested against the input minus the reference.

So the limits are offsets:

You want Compare Limits
A more than 2 K above B kAbove high = 2
A more than 5 K below B kBelow low = -5
A within 5 K of B, either way kOutside low = -5, high = 5
A and B agree to 0.5 K kEqual high = 0, epsilon = 0.5

Everything else about a rule applies to the difference unchanged: the warning band, hysteresis, both delays, latching, inhibits and actions. The event's value is the difference, which is the number its limit was compared with, and its input is still the rule's input.

Either signal missing orphans the rule. A difference needs both readings, so the rule reports kOrphaned while the input or the reference is not being produced: a region removed, a percentile its region did not ask for, a replay that does not carry the signal, an application value nobody has published yet. That is the same state, with the same consequences, as a single-signal rule whose input is missing: a latch survives it, a held output holds, and when both readings are back the rule takes up the band's level at once. A kInvalid watchdog with a reference fires while either is missing.

The rule is evaluated when its input is (every frame for a region or camera input, each poll or publication for a PIF or application input) and reads the reference at its latest value, the same way it reads an inhibit. It works the same on a live camera and on a replay.

A region reference follows the inhibit rule for slots: one left at 0 means the rule's own region, so "this region's maximum more than 5 K above its own mean" needs no slot, and one naming another region carries that region's slot, as in Naming a different region. A reference that is the same signal as the input is refused, and so is a reference to "my region" on a rule attached to none. The refusal says which: the first reads "the reference signal is the rule's own input; a rule cannot compare a signal with itself".

// A bearing and the housing beside it.
auto bearing_area =
    optris::sdk::Region::Rect({0.30F, 0.50F}, {0.10F, 0.10F});
bearing_area.name = "bearing";
const uint64_t bearing = imager->Regions().Add(std::move(bearing_area));
auto housing_area =
    optris::sdk::Region::Rect({0.60F, 0.50F}, {0.20F, 0.20F});
housing_area.name = "housing";
const uint64_t housing = imager->Regions().Add(std::move(housing_area));

const auto housing_slot = imager->Regions().SignalSlot(housing);
if (!housing_slot)
  return;  // the region is gone

// The bearing's maximum more than 15 K above the housing's mean, with a
// pre-alarm at 10 K. Both limits and the dead-band are in kelvin of
// difference.
optris::sdk::Rule hotter;
hotter.name = "bearing hotter than housing";
hotter.input = optris::sdk::SignalId::Region(optris::sdk::SignalField::kMax);
hotter.condition.compare = optris::sdk::Compare::kAbove;
hotter.condition.alarm.high = 15.0F;
hotter.condition.alarm.hysteresis = 2.0F;
hotter.condition.warning = optris::sdk::Limits{};
hotter.condition.warning->high = 10.0F;

// The reference goes in with the rule, so the rule is never evaluated
// without it. 0 when the rule is refused: a reference naming the input
// itself, or a field that does not belong to its domain.
const auto housing_mean = optris::sdk::SignalId::Region(
    *housing_slot, optris::sdk::SignalField::kMean);
if (imager->Alarms().Add(bearing, hotter, housing_mean) == 0)
  return;

In C++ the reference is held by the rule set beside the rule, keyed by its id, rather than in Rule: add the rule with Alarms().Add(region_id, rule, reference) (or Add(rule, reference) for a rule attached to no region), and use SetReference(), ClearReference() and ReferenceOf() on an installed rule, or Update(rule_id, mutate, reference) to edit both in one step. In C, Python and Rust it is set on the rule being built, and in .NET it is AlarmRule.Reference.

To edit one back to a single-signal rule, clear the reference: Alarms().ClearReference(rule_id) in C++, optris_sdk_rule_clear_reference() on a rule read back with optris_sdk_imager_copy_rule() and handed to optris_sdk_imager_update_rule() in C, Reference = null in .NET, clear_reference() in Python and Rust.

A configuration saved with SaveConfig() carries each rule's reference, a region rule's included, and LoadConfig() puts it back. A reference or an inhibit that names another region by its slot is pointed at the slot that region has once the file is loaded, so it needs no looking up again; a file saved by an earlier version keeps the slot as it was written. An ImagerConfig taken with GetConfig() and handed back with ApplyConfig() in memory does not carry a reference: it holds each rule as a Rule, which has no place for a reference, so the rules come back comparing their input alone. Read each reference with ReferenceOf() before and set it again with SetReference() after, or go through SaveConfig() and LoadConfig(). A record has no place for a region's slot either, so after ApplyConfig() re-resolve a slot that names another region with SignalSlot() as A region's slot is generational describes.

Conditions

struct Condition {
  Compare compare = Compare::kAbove;
  Limits alarm;                     // low, high, hysteresis, delta, epsilon
  std::optional<Limits> warning;    // the pre-alarm band
  std::chrono::milliseconds on_delay{0};
  std::chrono::milliseconds off_delay{0};
  bool latching = false;
};

Compare:

Value Fires when
kAbove value > alarm.high
kBelow value < alarm.low
kOutside outside [alarm.low, alarm.high]
kInside inside [alarm.low, alarm.high]
kEqual within alarm.epsilon of alarm.high
kChanged the value moved by more than alarm.delta
kInvalid the signal stopped being produced: a watchdog

value is the rule's input, or the input minus its reference when it has one; see Comparing two signals.

Hysteresis is release-only

Entering uses the raw limit; leaving requires the value to come back hysteresis past it, which stops an alarm chattering on a value sitting on its threshold. It applies to the five comparisons that test a limit: kAbove, kBelow, kOutside, kInside and kEqual, where it widens epsilon on release. kChanged and kInvalid read neither limit and ignore it.

on_delay and off_delay are durations

The engine counts consecutive qualifying observations to reach them, and one that does not qualify resets the counter. on_delay and off_delay are independent, so an alarm slow to raise and quick to clear is expressible.

The delays are durations, not frame counts. A frame count is a duration only with a frame rate, and the frame rate belongs to the operation mode, which an operator can change at any time; a duration debounces the same half-second on every camera and in every mode.

The engine converts at evaluation time from the interval it observes between frames, not from the nominal rate, which is what a mode change moves. A mode change therefore re-derives every delay with no caller involvement. A delay shorter than one frame interval debounces one frame, not zero: rounding to zero would switch a debounce off the moment the camera moved to a slower mode. A rule driven by PublishSignal() has no frame interval, and there any non-zero delay debounces exactly one observation.

Latching, and StatusOf

Latching holds kActive after the condition releases, until Alarms().Acknowledge(rule_id) (or AcknowledgeAll()). Acknowledging an alarm whose condition still holds does not silence it: the state stays active and the latch re-arms.

Two situations therefore report the same kActive and want different user interfaces. Alarms().StatusOf(rule_id) says which:

const auto status = camera.Alarms().StatusOf(rule_id);
if (status.state == AlarmState::kActive && status.held_by_latch) {
  // The value is back inside the limits. Acknowledge clears it.
} else if (status.state == AlarmState::kActive) {
  // Still outside the limit. Acknowledge re-arms the latch and
  // changes nothing.
}

held_by_latch is false for a non-latching rule and for every state other than kActive. From a binding: optris_sdk_imager_get_alarm_runtime(), ThermalCamera.GetAlarmRuntime(), camera.alarms.runtime_of(), Camera::alarm_runtime(). There is no event for the moment the condition releases under a latch, because the state does not change and so there is no transition to report. Poll this alongside the state you already poll.

kChanged is momentary

It is true on the observation where the value moved, so with no on-delay it is one frame active and then clear. On a region, motion or device signal it requires a non-zero delta, and Alarms().Add() rejects it without one, because it would otherwise ring on any float wobble. On a PIF or application signal a zero delta is allowed: there a change really is a change.

States

kUnknown → no observation yet
kDisabled → Rule::enabled is false
kOrphaned → the input signal no longer exists
kInhibited → suppressed by an inhibit source
kClear / kWarning / kActive

Order of precedence: disabled beats orphaned beats inhibited beats the bands, and the alarm band always beats the warning band. A kInvalid watchdog is the one exception to the orphan step: a missing input is the condition it exists to test, so it is evaluated rather than orphaned.

kInhibited is distinct from kDisabled: an operator interface has to show "someone turned this off" differently from "a process signal is suppressing it right now".

Events fire on transition only, never once per frame while the state is unchanged.

Suppressing an alarm

A rule can name inhibit sources and is held clear while any of them holds. The usual case is a PIF digital input an operator asserts during a known disturbance:

optris::sdk::Inhibit inhibit;
inhibit.signal = optris::sdk::SignalId::Pif(2,
                                            optris::sdk::SignalField::kDigitalIn);
inhibit.condition.compare = optris::sdk::Compare::kEqual;
inhibit.condition.alarm.high = 1.0f;
rule.inhibit.push_back(inhibit);

Configure the input before it publishes anything: an unconfigured pin is silent, and a rule on a silent signal is kOrphaned. Configure it as kUncommittedValue, which watches the pin without letting it drive anything; see Process interface.

An inhibit source is just a signal, so it can equally be a device reading or an application value. Set invert to suppress while the signal is low.

An inhibit's Condition supplies the comparison and the limits only. It has no delay counters, no latch and no hysteresis state of its own, so on_delay, off_delay and latching on an inhibit are ignored.

Note: If a suppression signal stops arriving, the alarm rings. Suppression fails towards the alarm working, never towards silence, and that holds for an inverted inhibit too: invert flips the test applied to a signal that is there, and a signal that has stopped is not read as "low". A signal stops arriving when it was never published, or when its producer withdraws it, as a process interface does when it is unplugged or stops answering. The one inhibit a missing signal does hold is one you ask for: an inhibit whose compare is kInvalid, without invert, holds exactly when its signal stops.

Actions

struct Action {
  ActionTrigger on;   // kOnActivate, kOnClear, kOnWarn, kOnAnyChange
  std::variant<CallbackAction, PifOutputAction,
               SnapshotAction, RecordingAction> what;
};

The four kinds

  • CallbackAction calls the handler whose slot was returned by Alarms().RegisterCallback(): optris_sdk_imager_register_alarm_callback() in C, ThermalCamera.RegisterAlarmCallback() in C#, camera.alarms.register_callback() in Python and register_alarm_callback() in Rust. Only the rules that name a slot call its handler, where the alarm event stream sees every rule's transitions.
  • PifOutputAction drives a PIF output. The output follows the alarm, not the trigger: asserted while ringing, de-asserted when the alarm clears, when it is inhibited and when the rule is disabled. A cycle in which the rule had no reading is not one of those. Orphaned is no reading rather than a cleared condition, so a held output sits still through it and is still asserted when the reading comes back, as the latch does. A relay does not drop out for the length of every gap and come back inside one excursion. So a rule whose input never returns (its region deleted, a channel the camera does not have) holds its output until the rule is disabled, edited off the pin, removed, or the camera closed. There is no timeout.
  • SnapshotAction writes a still image: PNG, TIFF or CSV (format, PNG by default). A PNG is the colorized picture, so an alarm snapshot opens in a mail client or a browser without thermal tooling, and the measurement travels inside it. min_interval (1 s by default) stops a chattering alarm filling the disk. options, a rec::SnapshotOptions, says how the file is written: compression level, the 16-bit TIFF variant, the fixed Kelvin-per-count scale. An alarm's CSV is always in degrees Celsius and the default spelling (, and .); a CSV for a spreadsheet in another locale or in degrees Fahrenheit is written with SaveCsvSnapshot().
  • RecordingAction records for as long as the alarm lasts (kWhileActive, the default), for a fixed duration (kFixedDuration, 10 s by default), or stops one (kStop). A kWhileActive recording is a held state and follows the PIF output's rule above: it stays open through a cycle in which the rule had no reading, rather than closing and starting a second file for the same excursion. options, a rec::RecordingOptions, says how the file is written: segment limits and lossy settings.

options is the same struct the recorder takes

Set options to whatever the application uses for its own files. It is the same struct Recorder().SaveSnapshot() and Recorder().Start() take. A user whose tool cannot read float32 chose a 16-bit TIFF and wants alarm stills that tool can open too: two files of one frame must not differ by who asked for them.

Where a single file is capped, set options.max_segment_bytes. At zero (the default, and what every alarm recording did before this field existed) a recording never rolls over, so one onto a destination that caps a single file fails at that cap instead of continuing in a new part. Pass whatever the destination holds. An alarm recording is the one case where nobody is watching when that happens.

rec::RecordingOptions::duration is ignored on a RecordingAction: mode and duration above are the action's stop. A recording that stopped itself on the options field would not tell the alarm runner, which would go on believing the rule owned a recorder that had closed, so a kWhileActive recording would end early with nothing in the action-error channel saying why.

ActionTrigger: three of the four are wider than their names

Three of the four match more transitions than they sound like they do:

trigger fires on
kOnActivate any transition into kActive: from kClear and kWarning, and also from kOrphaned (the return from a cycle with no reading), kInhibited, kDisabled and kUnknown
kOnWarn any transition into kWarning: from kClear, and also from kActive, an alarm easing back down into the pre-alarm band
kOnClear leaving kWarning or kActive for any reason: a clean clear, and also becoming kOrphaned, kInhibited, kDisabled or kUnknown
kOnAnyChange every transition, with no filtering

kOnClear's width has two consequences. A pre-alarm that clears without ever becoming an alarm fires it, because kWarning -> kClear leaves a ringing state, so an action on this trigger acts on something an operator would not call an alarm. An alarm that merely stops being readable fires it too, and one unreliable frame orphans every rule on every region at once, so in a plant that is common rather than rare.

Nothing in ActionTrigger distinguishes "this alarm stopped being active" from either of those. Only the hold on a PifOutputAction or a kWhileActive RecordingAction follows the latch through a gap and is not released by it. The trigger still fires, and the event carries current == kOrphaned, so a handler can see which kind of leaving it was.

Where an action's file is written

The SDK owns the output path: directory (or Imager::Recorder().SetOutputDirectory(), or the current directory) plus name_pattern, {rule}_{timestamp} by default. {sequence}, {timestamp}, {timestamp_us}, {serial}, {model}, {rule} and {region} expand, {rule} and {region} falling back to the id when the name is empty; a token with nothing behind it expands to nothing rather than to itself. Existing files are never overwritten; a -1, -2 suffix is added.

The vocabulary is one table, shared with interval capture, so an application with a single file-name setting feeding both can promise its user a format; Snapshots and Interval Capture says what each token expands to. Two placeholders changed meaning on the alarm path to get there. {timestamp} was AlarmEvent::timestamp_us, a raw microsecond integer taken from the frame's capture clock, which on the Linux USB transports is steady_clock: microseconds since the host booted, not a date. That value is unchanged and still reachable, now as {timestamp_us}. And {sequence} was unpadded, which was the only thing stopping a folder sorting in capture order.

SetActionErrorCallback

A failed action never changes the alarm state. Failures arrive on a separate callback:

imager->Alarms().SetActionErrorCallback([](const optris::sdk::ActionError &e) {
  Log(e.rule_id, e.path, e.message);
});

Each failure carries sequence, the causing alarm event's. A still that could not be written has no file name, and two activations of one rule within the same second cannot be told apart by time, so match a failure to its activation on sequence rather than on the rule and a nearby time. ActionCompleted carries the same field.

A recording that fails to start leaves the state retryable, so the next activation tries again rather than believing it is already recording.

await foreach (ActionError failure in camera.ActionFailed(token))
{
    Console.Error.WriteLine(failure);
}

An alarm is a fact about the world; a snapshot that could not be written is a fact about the disk.

SetActionCompletedCallback

An action that did not fail says what it did. Four outcomes, and only one of them is a file:

imager->Alarms().SetActionCompletedCallback(
    [](const optris::sdk::ActionCompleted &e) {
      switch (e.outcome) {
        case optris::sdk::ActionOutcome::kWritten:
          Log(e.rule_id, e.path);  // complete on disk, under this name
          break;
        case optris::sdk::ActionOutcome::kSkippedByMinimumInterval:
          Log(e.rule_id, "skipped: this action's own spacing");
          break;
        case optris::sdk::ActionOutcome::kDroppedQueueFull:
          Log(e.rule_id, "no picture: the action queue was full");
          break;
        case optris::sdk::ActionOutcome::kDroppedFrameBudget:
          Log(e.rule_id, "no picture: the frame that fired it was not kept");
          break;
        case optris::sdk::ActionOutcome::kUnknown:
          break;  // never delivered; it is what a zeroed struct holds
      }
    });

The three middle outcomes are not errors. A chattering alarm's min_interval doing its job, a queue bound doing its job, and a bound on the frames waiting stills may hold doing its job all leave an activation without a picture, and before this event existed an application could not tell any of them from a failure, or from a rule that never fired. Only kWritten names a path: the file name is generated after those decisions and a dropped job is discarded before one is built, so for the other three there is no file to name rather than a name withheld.

kDroppedFrameBudget is a still that would otherwise have shown the wrong moment. Each still waiting to be written keeps the frame its rule fired on, so the file shows that frame and not whatever is newest by the time the still is written. Those frames are bounded in total, and past the bound the newest activations have no frame of their own left. Such a still is dropped and reported, never written from a later frame under this activation's name. A rule fired by a process-interface poll or a published value has no frame of its own, and its still is written from the newest frame, as it always was.

Do not read an attachment provider's call as a confirmation. The provider is asked while the still is being assembled, before any bytes are written, so it says the write was attempted. kWritten is reported after the writer has returned success.

This reaches a Player and a StillSource as well as a camera, since both run SnapshotActions for real.

GetActionDropCounts

Both callbacks above are best effort; these two totals are exact. A chattering alarm in front of a slow handler can outrun the bounded backlog of undelivered reports, and past it a report is lost. actions_dropped counts actions discarded from a full action queue, and reports_dropped counts error and outcome reports lost at that backlog:

optris::sdk::ActionDropCounts lost = imager->Alarms().GetActionDropCounts();
Log(lost.actions_dropped, lost.reports_dropped);

They count from the moment the camera, recording or still was opened and are not reset by a reconnect. To tell a user that some reports never arrived, remember the last value you read and compare: a dropped action that was itself reported reached you as kDroppedQueueFull, so only reports_dropped names reports you never saw.

Reading a rule back

In C++ Alarms().Get(rule_id) hands back the whole Rule, actions and inhibits included. Through the ABI it is reached one accessor at a time, and two of them make a full read-back possible:

  • optris_sdk_imager_get_rule_region(): the region the rule was added to, or 0 for a free rule. A region rule's own input names a generational slot, filled in by Add(region_id, rule), and nothing on the rule carries the region id. Without this a rule read back was a condition on "some region".
  • optris_sdk_rule_get_action(): one action, as an optris_sdk_action whose kind says which of its fields carry meaning. The count was already available; the contents were not, so an application that read a rule and wrote it back silently dropped everything it did.

That matters most after LoadConfig(), where every rule on the camera was built by somebody else. ThermalCamera.GetRule() in .NET fills in AlarmRule.RegionId and AlarmRule.Actions; camera.alarms.get(), .ids() and .region_of() are new in Python, which had no rule readback at all; Camera::rule_region() and Rule::actions() are the Rust spelling.

Inhibit sources are still a count only. They are a second value type behind the same gap and will follow the same shape when they land.

Attaching your own files

An alarm-driven snapshot or recording can carry files of your own: a process context, a configuration dump, a reading from another system.

The mechanism is a pull: register a provider once, and the SDK asks it as it opens each file. Recording Attachments holds the whole contract; this section is the alarm half of it.

// Your own function, returning the bytes to attach.
std::vector<std::byte> CollectProcessContext();

const uint32_t provider = imager->Recorder().AddAttachmentProvider(
    [&](const optris::sdk::rec::AttachmentRequest &ctx) {
      std::vector<optris::sdk::rec::Attachment> out;
      out.push_back({.name = "process.json",
                     .mime = "application/json",
                     .data = CollectProcessContext(),
                     .compress = true});
      return out;
    });

Why it is a pull

It is a pull rather than a push because for a trigger-started recording your application never calls Recorder().Start(), so it has no moment at which to hand anything over. One provider serves a snapshot, a triggered recording and a manual Recorder().Start() or SaveSnapshot(). AddAttachmentProvider() returns an id for RemoveAttachmentProvider().

AttachmentRequest says which file is being opened: scope (snapshot, recording, or a follow-on recording segment), format (PNG, TIFF, CSV, JPEG or MKV), can_carry_attachments, path, segment_index, the capture timestamp_us of the frame that opened it, and, when an alarm caused the file, cause, the AlarmEvent that did, so a provider can attach different things for different alarms.

Gate on can_carry_attachments

Use format to decide what to attach rather than whether. A CSV and a JPEG have nowhere to put an attachment, so that flag is false for them; anything a provider returns for such a file is dropped, noted in the log, and the file is still written. Files you set on a SnapshotInfo by hand are refused for those two formats as well, because there the SDK never asked you. on_action_thread is not a reliable answer to "are my locks held": for anything other than a snapshot assume you are on an SDK thread whatever it says, and see the provider's contract for which thread that is.

The provider is called exactly once per file and returning an empty vector is normal.

Not called for a replay or a reopened still

It is a camera's registry, so it is not called for a snapshot saved from a replay or a reopened still. SaveSnapshot() works on those two and an alarm's snapshot action fires on them, but the provider list lives on a camera's Recorder and neither other source has one. Such a file carries the characteristic curve and the radiometry bundle its own source file carried, and nothing of yours; pass your files on the SnapshotInfo you hand the call.

Reading them back

Read a snapshot's attachments back with rec::Snapshot::ReadAttachments(path). It does not list the SDK's own records, so an empty list is routine: the measurement thermal.png, the characteristic curve and the radiometry bundle are all left out. Use Snapshot::LoadThermal() for the temperatures, and see What an attachment list leaves out for the whole rule and for where each record is stored.

Warning: The provider is called synchronously, as the file's header is written, on the thread that writes the recording, so it must be fast and anything slow has to be cached. Blocking there delays the recording but not the camera: the header is written on the recording's own thread, not the camera's frame thread, so a slow provider does not stall the frame rate. It must not call back into the imager's recording or snapshot methods, because the provider runs inside the write it is supplying the header for. A provider that throws is caught and treated as "no attachments"; a failed attachment never fails a recording.

The Worst State, For A Status Light

One value for a status light, without walking every region.

if (imager->Alarms().WorstState() == optris::sdk::AlarmState::kActive) {
  SoundTheAlarm();
}

Threading

  • Region statistics, signal publication and rule evaluation run on the frame callback thread, as part of work already being done there.
  • PIF signals publish and evaluate on the PifController::Poll() caller's thread, so a PIF alarm does not wait for a frame.
  • Actions and user callbacks run on a dedicated action thread. Snapshots and recordings do file I/O; neither belongs on a thread a camera is waiting for.

A snapshot action captures the frame that caused it at event time, so the pixels are correct even though the write happens a few milliseconds later.

Reading alarm state

imager->Alarms().StateOf(rule_id);          // one rule
imager->Alarms().StateOfRegion(region_id);  // worst across that region's rules
imager->Alarms().WorstState();              // worst across everything

WorstState() is the general form of what v11 called the composite alarm, and needs no separate subscription; it is a read, not an event.

For transitions, subscribe:

imager->Alarms().SetCallback([](const optris::sdk::AlarmEvent &e) {
  // e.rule_id, e.rule_name, e.region_id, e.region_name,
  // e.previous -> e.current, e.input,
  // e.value, e.limit, e.limit_kind,
  // e.sequence, e.timestamp_us, e.host_time_us
});

AlarmEvent carries its own cause, so a subscriber never has to look anything up. Alarms().Log(n) returns the last n transitions, newest last, for a display that repaints faster than it subscribes. Every entry carries host_time_us, so a transition from before you subscribed still has a time of day on it.

Warning: The log is not a durable history. It is an in-memory ring of the last 256 transitions belonging to this imager object. Reading does not drain it, but two things empty it: the 257th transition pushes out the first, and destroying the imager discards the ring entirely. A reconnect that opens a new imager therefore starts with an empty log, and the transitions from before it are gone rather than merely undated. An application that has to survive a reconnect must persist what it reads.

Which of the two clocks to use

timestamp_us is the driving observation's own stamp, carried over unchanged, not a stamp taken at the transition. Which clock that is depends on the rule:

Rule timestamp_us is
region or device that frame's monotonic capture stamp, counting from the camera's start
PIF whatever the PIF poll stamped
driven by PublishSignal() wall-clock microseconds since the Unix epoch
a transition into kOrphaned before any input has arrived 0

None of those can be formatted as a time of day, and two of them are comparable only when both rules watch the same kind of signal.

host_time_us is wall-clock microseconds since the Unix epoch, from a real std::chrono::system_clock reading, never an offset added to the monotonic value. This is the field for a log row or an alarm history. It is sampled at the raise site, when the evaluation cycle produces its first event, so the queue latency between the transition and your callback is not in it, and every event of one cycle carries the same date. One frame is not always one cycle: region and device rules are one pass, motion rules a second after every zone has published, and PIF and user rules their own occasions again, so two events from one frame can differ here by microseconds.

host_time_us is not monotonic. NTP can step the system clock in either direction and an operator can set it, so consecutive events can go backwards or jump by hours. Order with sequence, measure an interval with timestamp_us, and display host_time_us. Never derive one from the other: they are read from two different clocks, at two different instants, on purpose. host_time_us is zero only if the SDK could not read the system clock.

The same pair reaches the bindings: optris_sdk_alarm_event::host_time_us in C, AlarmEvent.HostTime as a DateTimeOffset in .NET. ShutterEvent carries the same second stamp for the same reason.

Note: File-name patterns do not see the host clock. {timestamp} is the wall clock read as the file is written, and {timestamp_us} is AlarmEvent::timestamp_us verbatim, with whatever meaning the paragraph above gives it. Neither is host_time_us. See Actions.

Complete example

auto zone = optris::sdk::Region::Rect({0.5f, 0.375f}, {0.6f, 0.45f});
zone.name = "Furnace";
const auto zone_id = imager->Regions().Add(std::move(zone));

optris::sdk::Rule hot;
hot.name = "over temp";
hot.input = optris::sdk::SignalId::Region(0, optris::sdk::SignalField::kMax);
hot.condition.compare = optris::sdk::Compare::kAbove;
hot.condition.alarm = {.high = 50.0f, .hysteresis = 2.0f};
hot.condition.warning = optris::sdk::Limits{.high = 45.0f};
hot.condition.on_delay = std::chrono::milliseconds(100);

optris::sdk::SnapshotAction snapshot;
snapshot.min_interval = std::chrono::seconds{5};
hot.actions.push_back({optris::sdk::ActionTrigger::kOnActivate, snapshot});

imager->Alarms().Add(zone_id, std::move(hot));

imager->Alarms().SetCallback([](const optris::sdk::AlarmEvent &e) {
  std::println("{} {} -> {} at {:.1f} C",
               e.region_name, optris::sdk::ToString(e.previous),
               optris::sdk::ToString(e.current), e.value);
});

See examples/cpp/alarms/threshold_alarm.cc for a runnable version.

Migrating from alarm channels

Imager::AddAlarmChannel() and its AlarmChannelConfig, AlarmChannelStatus, AlarmInput, AlarmState and AlarmRangeRelation types were a carry-over of the v11 model and are removed from optris::sdk.

Version 11 applications are unaffected. The classic IRImager interface and its alarm channels keep working, and the v11 shape stays available unchanged under include/legacy/otcsdk/alarms/.

Was Now
createMeasurementField(...) a Region plus a Rule on SignalId::Region(slot, kMax\|kMin\|kMean)
createInternalTemperature(...) Rule on SignalId::Device(kBoxTemp)
createChipTemperature(...) Rule on SignalId::Device(kChipTemp)
createUncommittedValue(...) Rule on SignalId::Pif(n, kAnalogIn)
alarmRange (active when outside) Compare::kOutside with alarm.low / alarm.high
preAlarmRange Condition::warning
partOfComposite Alarms().WorstState()
pifAoIndices / pifDoIndices a PifOutputAction on the rule
AlarmState::PreActive AlarmState::kWarning
RoiAlarm{Above, 50.0f} a Rule with Compare::kAbove, alarm.high = 50
rec::TriggerConfig + AddTrigger() a Rule with a RecordingAction

Recording triggers in particular collapse: AlarmTrigger, PifDigitalTrigger, PifAnalogTrigger and ApiTrigger were four separate edge-detectors, and are now one rule with a recording action, or, for the API case, Imager::Recorder().Start().