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));
optris_sdk_rule *rule = NULL; optris_sdk_signal_id input; optris_sdk_condition condition; uint64_t rule_id = 0; optris_sdk_rule_create(&rule); optris_sdk_rule_set_name(rule, "over temp"); optris_sdk_signal_id_init(&input, sizeof(input)); input.domain = OPTRIS_SDK_SIGNAL_DOMAIN_REGION; input.field = OPTRIS_SDK_FIELD_MAX; optris_sdk_rule_set_input(rule, &input); optris_sdk_condition_init(&condition, sizeof(condition)); condition.compare = OPTRIS_SDK_COMPARE_ABOVE; condition.alarm.high = 60.0F; optris_sdk_rule_set_condition(rule, &condition); /* The status says why on a refusal; there is no 0 to test for. */ optris_sdk_imager_add_rule(imager, region_id, rule, &rule_id); optris_sdk_rule_free(rule);
ulong overTemp = camera.AddRule(regionId, new AlarmRule { Name = "over temp", Input = SignalId.Region(SignalField.Max), Condition = AlarmCondition.Above(60.0f), });
rule = optris_sdk.Rule( name='over temp', input=optris_sdk.SignalId.region(optris_sdk.FIELD_MAX), condition=optris_sdk.Condition(compare=optris_sdk.COMPARE_ABOVE, alarm=optris_sdk.Limits(high=60.0))) rule_id = camera.alarms.add(rule, region_id=region_id)
let mut rule = Rule::new()?; rule.set_name("over temp")?; rule.set_input(SignalId::region(SignalField::Max))?; rule.set_condition(Condition::above(60.0, 0.0))?; let rule_id = camera.add_rule(region_id, &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,kNucInProgressandkConnectedcarry 0.0 or 1.0. Compare them withkEqual, notkAbove.kAreais a pixel count, not a physical area.kP99is the robust hot value: a few noisy or dead pixels do not trip it the way they tripkMax, and on a small region it is not the same number askMax. A spot, a hot spot and a cold spot report these over the pixels their aperture reached, nine for a 3×3.kBlobCountmeans two things by kind: on akBlobGroup, 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);
uint32_t slot = 0; optris_sdk_imager_register_signal(imager, "line pressure", &slot); optris_sdk_imager_publish_signal(imager, slot, 4.2);
uint pressureSlot = camera.RegisterSignal("line pressure"); camera.PublishSignal(pressureSlot, 4.2);
slot = camera.alarms.register_signal('line pressure') camera.alarms.publish_signal(slot, 4.2)
let slot = camera.register_signal("line pressure")?; camera.publish_signal(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 */ }
optris_sdk_signal_id which; double value = 0.0; int valid = 0; uint64_t when_us = 0; optris_sdk_signal_id_init(&which, sizeof(which)); which.domain = OPTRIS_SDK_SIGNAL_DOMAIN_DEVICE; which.field = OPTRIS_SDK_FIELD_CHIP_TEMP; /* Three out-parameters rather than a record: the value, whether * anything published it, and when. NULL for the timestamp if the * answer is all you want. */ optris_sdk_imager_read_signal(imager, &which, &value, &valid, &when_us); if (valid) { /* value */ }
// The Try- shape rather than a struct with a valid flag: false IS // "nothing published this". if (camera.TryReadSignal(SignalId.Device(SignalField.ChipTemperature), out double chip)) { Console.WriteLine(chip); }
# A (value, timestamp) pair, where the value is None rather than a # record with a valid flag beside it. chip, when = camera.alarms.read_signal( optris_sdk.SignalId.device(optris_sdk.FIELD_CHIP_TEMP)) if chip is not None: print(chip)
// Option rather than a struct with a valid flag. if let Some(chip) = camera.read_signal(SignalId::device(SignalField::ChipTemp))? { println!("{}", chip.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);
optris_sdk_rule *bearing = NULL; optris_sdk_signal_id input; optris_sdk_signal_id door_signal; optris_sdk_condition condition; optris_sdk_condition while_open; uint32_t door = 0; uint64_t rule_id = 0; /* NOT_FOUND when the region is gone. Zero is never a live slot. */ if (optris_sdk_imager_get_region_signal_slot(imager, furnace_door_id, &door) != OPTRIS_SDK_OK) { return; } optris_sdk_rule_create(&bearing); optris_sdk_signal_id_init(&input, sizeof(input)); input.domain = OPTRIS_SDK_SIGNAL_DOMAIN_REGION; input.field = OPTRIS_SDK_FIELD_MAX; optris_sdk_rule_set_input(bearing, &input); optris_sdk_condition_init(&condition, sizeof(condition)); condition.compare = OPTRIS_SDK_COMPARE_ABOVE; condition.alarm.high = 90.0F; optris_sdk_rule_set_condition(bearing, &condition); /* Silence it while the furnace door region is above 200 C. */ optris_sdk_signal_id_init(&door_signal, sizeof(door_signal)); door_signal.domain = OPTRIS_SDK_SIGNAL_DOMAIN_REGION; door_signal.field = OPTRIS_SDK_FIELD_MAX; door_signal.index = door; optris_sdk_condition_init(&while_open, sizeof(while_open)); while_open.compare = OPTRIS_SDK_COMPARE_ABOVE; while_open.alarm.high = 200.0F; optris_sdk_rule_add_inhibit(bearing, &door_signal, &while_open, 0); optris_sdk_imager_add_rule(imager, bearing_id, bearing, &rule_id); optris_sdk_rule_free(bearing);
// false when the region is gone. Zero is never a live slot. if (!camera.TryGetRegionSignalSlot(furnaceDoorId, out uint door)) { return; } var bearing = new AlarmRule { Input = SignalId.Region(SignalField.Max), Condition = AlarmCondition.Above(90.0f), }; // Silence it while the furnace door region is above 200 C. bearing.Inhibits.Add(new AlarmInhibit( SignalId.Region(door, SignalField.Max), AlarmCondition.Above(200.0f))); camera.AddRule(bearingId, bearing);
# Raises NotFoundError when the region is gone. Zero is never a live # slot, so there is no sentinel to test for. door = camera.alarms.region_signal_slot(furnace_door_id) bearing = optris_sdk.Rule( input=optris_sdk.SignalId.region(optris_sdk.FIELD_MAX), condition=optris_sdk.Condition(compare=optris_sdk.COMPARE_ABOVE, alarm=optris_sdk.Limits(high=90.0))) # Silence it while the furnace door region is above 200 C. The # three-argument SignalId names a region other than the rule's own. bearing.add_inhibit( optris_sdk.SignalId(optris_sdk.DOMAIN_REGION, optris_sdk.FIELD_MAX, door), optris_sdk.Condition(compare=optris_sdk.COMPARE_ABOVE, alarm=optris_sdk.Limits(high=200.0))) camera.alarms.add(bearing, region_id=bearing_id)
// Err when the region is gone. Zero is never a live slot. let door = camera.region_signal_slot(furnace_door_id)?; let mut bearing = Rule::new()?; bearing.set_input(SignalId::region(SignalField::Max))?; bearing.set_condition(Condition::above(90.0, 0.0))?; // Silence it while the furnace door region is above 200 C. `index` is // a public field, because SignalId::region() deliberately takes no // slot: a number there would read as if it identified the region. let mut door_signal = SignalId::new(SignalDomain::Region, SignalField::Max); door_signal.index = door; bearing.add_inhibit(door_signal, Condition::above(200.0, 0.0), false)?; camera.add_rule(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));
optris_sdk_motion_zone zone; optris_sdk_rule *intruder = NULL; optris_sdk_signal_id input; optris_sdk_condition condition; uint64_t rule_id = 0; optris_sdk_motion_zone_init(&zone, sizeof(zone)); zone.temp_min_c = 30.0F; /* only movement in this band counts */ zone.temp_max_c = 90.0F; optris_sdk_imager_set_motion_zone(imager, 1, &zone); optris_sdk_rule_create(&intruder); optris_sdk_rule_set_name(intruder, "motion in zone 1"); optris_sdk_signal_id_init(&input, sizeof(input)); input.domain = OPTRIS_SDK_SIGNAL_DOMAIN_MOTION; input.field = OPTRIS_SDK_FIELD_MOTION_BLOB_COUNT; input.index = 1; /* the zone */ optris_sdk_rule_set_input(intruder, &input); optris_sdk_condition_init(&condition, sizeof(condition)); condition.compare = OPTRIS_SDK_COMPARE_ABOVE; condition.alarm.high = 0.0F; /* any blob at all */ condition.on_delay_ms = 100; optris_sdk_rule_set_condition(intruder, &condition); optris_sdk_rule_add_recording_action(intruder, OPTRIS_SDK_ACTION_ON_ACTIVATE, OPTRIS_SDK_RECORDING_WHILE_ACTIVE, 0, NULL, NULL); /* Region id 0: a motion rule is not attached to a region. */ optris_sdk_imager_add_rule(imager, 0, intruder, &rule_id); optris_sdk_rule_free(intruder);
// only movement in this band counts camera.SetMotionZone(1, new MotionZone(MinimumTemperature: 30.0f, MaximumTemperature: 90.0f)); var intruder = new AlarmRule { Name = "motion in zone 1", Input = SignalId.Motion(zoneId: 1, SignalField.MotionBlobCount), Condition = AlarmCondition.Above(0.0f) with // any blob at all { OnDelay = TimeSpan.FromMilliseconds(100), }, }; intruder.Actions.Add(new RecordingAction()); camera.AddRule(intruder);
zone = optris_sdk.MotionZone(temp_min_c=30.0, # only this band counts temp_max_c=90.0) camera.set_motion_zone(1, zone) intruder = optris_sdk.Rule( name='motion in zone 1', input=optris_sdk.SignalId(optris_sdk.DOMAIN_MOTION, optris_sdk.FIELD_MOTION_BLOB_COUNT, 1), condition=optris_sdk.Condition( compare=optris_sdk.COMPARE_ABOVE, alarm=optris_sdk.Limits(high=0.0), # any blob at all on_delay_s=0.1)) intruder.add_recording_action(trigger=optris_sdk.ON_ACTIVATE) camera.alarms.add(intruder)
// The band is the constructor's whole argument list, because a zone // without one is not a zone. let zone = MotionZone::new(30.0, 90.0); camera.set_motion_zone(1, zone)?; let mut intruder = Rule::new()?; intruder.set_name("motion in zone 1")?; intruder.set_input(SignalId::motion(SignalField::MotionBlobCount, 1))?; intruder.set_condition( Condition::above(0.0, 0.0) // any blob at all .with_on_delay(Duration::from_millis(100)), )?; intruder.add_recording_action(ActionTrigger::OnActivate, RecordingActionMode::WhileActive, 0, None, None)?; // Region id 0: a motion rule is not attached to a region. camera.add_rule(0, &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; };
/* An opaque handle rather than a struct: every field has a setter, and * the id is the imager's answer to add_rule() rather than a member. */ optris_sdk_rule *rule = NULL; optris_sdk_signal_id input; optris_sdk_condition condition; optris_sdk_rule_create(&rule); optris_sdk_rule_set_name(rule, "over temp"); optris_sdk_rule_set_enabled(rule, true); optris_sdk_signal_id_init(&input, sizeof(input)); optris_sdk_rule_set_input(rule, &input); optris_sdk_condition_init(&condition, sizeof(condition)); optris_sdk_rule_set_condition(rule, &condition); /* optris_sdk_rule_add_inhibit() and the four add_*_action() calls take * the place of the two vectors. */ optris_sdk_rule_free(rule);
// The same seven things, as a class with collections rather than a // struct with vectors. There is no Id member: AddRule returns it. var shape = new AlarmRule { Name = "over temp", IsEnabled = true, Input = SignalId.Region(SignalField.Max), Condition = AlarmCondition.Above(60.0f), }; shape.Inhibits.Add(new AlarmInhibit(SignalId.Device(SignalField.FlagOpen), AlarmCondition.Above(0.5f))); shape.Actions.Add(new SnapshotAction());
# Name, input and condition are keywords; the inhibits and the actions # are methods, because each kind takes different arguments. There is no # id attribute: alarms.add() returns it. shape = optris_sdk.Rule( name='over temp', input=optris_sdk.SignalId.region(optris_sdk.FIELD_MAX), condition=optris_sdk.Condition(compare=optris_sdk.COMPARE_ABOVE, alarm=optris_sdk.Limits(high=60.0))) shape.set_enabled(True) shape.add_inhibit(optris_sdk.SignalId.device(optris_sdk.FIELD_FLAG_OPEN), optris_sdk.Condition( compare=optris_sdk.COMPARE_ABOVE, alarm=optris_sdk.Limits(high=0.5))) shape.add_snapshot_action()
// An owned handle with setters, and no `id` field: add_rule() answers // with the id. let mut shape = Rule::new()?; shape.set_name("over temp")?; shape.set_enabled(true)?; shape.set_input(SignalId::region(SignalField::Max))?; shape.set_condition(Condition::above(60.0, 0.0))?; shape.add_inhibit(SignalId::device(SignalField::FlagOpen), Condition::above(0.5, 0.0), false)?; shape.add_snapshot_action(ActionTrigger::OnActivate, SnapshotFormat::Png, None, None, 0)?;
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; });
optris_sdk_rule *editing = NULL; optris_sdk_condition condition; /* Read the rule back, change it, hand it in again: there is no * callback form, because C has no closures. */ if (optris_sdk_imager_copy_rule(imager, rule_id, &editing) == OPTRIS_SDK_OK) { optris_sdk_rule_get_condition(editing, &condition); condition.alarm.high = 65.0F; optris_sdk_rule_set_condition(editing, &condition); /* Returns OPTRIS_SDK_ERROR_NOT_FOUND on an invalid edit, as for an * unknown rule, and the rule is left unchanged. */ optris_sdk_imager_update_rule(imager, rule_id, editing); optris_sdk_rule_free(editing); }
// A nullable, because an unknown id is a question rather than a fault. if (camera.GetRule(ruleId) is AlarmRule editing) { editing.Condition = editing.Condition with { Alarm = editing.Condition.Alarm with { High = 65.0f }, }; // false on an invalid edit, and the rule is left unchanged. camera.UpdateRule(ruleId, editing); }
editing = camera.alarms.get(rule_id) editing.set_condition( optris_sdk.Condition(compare=editing.condition.compare, alarm=optris_sdk.Limits(high=65.0))) camera.alarms.update(rule_id, editing)
let mut editing = camera.rule(rule_id)?; let existing = editing.condition()?; editing.set_condition(Condition::above(65.0, existing.alarm.hysteresis))?; camera.update_rule(rule_id, &editing)?;
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);
optris_sdk_signal_id blow_off; optris_sdk_condition high; /* Silence it while PIF digital input 0 is high. */ optris_sdk_signal_id_init(&blow_off, sizeof(blow_off)); blow_off.domain = OPTRIS_SDK_SIGNAL_DOMAIN_PIF; blow_off.field = OPTRIS_SDK_FIELD_DIGITAL_IN; blow_off.index = 0; optris_sdk_condition_init(&high, sizeof(high)); high.compare = OPTRIS_SDK_COMPARE_ABOVE; high.alarm.high = 0.5F; optris_sdk_rule_add_inhibit(rule, &blow_off, &high, 0);
var rule = new AlarmRule { /* ... */ }; rule.Inhibits.Add(new AlarmInhibit( SignalId.ProcessInterface(0, SignalField.DigitalIn), AlarmCondition.Above(0.5f)));
# Silence it while PIF digital input 0 is high. rule.add_inhibit( optris_sdk.SignalId.pif(optris_sdk.FIELD_DIGITAL_IN, 0), optris_sdk.Condition(compare=optris_sdk.COMPARE_ABOVE, alarm=optris_sdk.Limits(high=0.5)))
// Silence it while PIF digital input 0 is high. rule.add_inhibit( SignalId::pif(SignalField::DigitalIn, 0), Condition::above(0.5, 0.0), false, )?;
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;
optris_sdk_region *area = NULL; optris_sdk_rule *hotter = NULL; optris_sdk_signal_id input; optris_sdk_signal_id reference; optris_sdk_condition condition; const optris_sdk_vec2 bearing_centre = {0.30F, 0.50F}; const optris_sdk_vec2 bearing_size = {0.10F, 0.10F}; const optris_sdk_vec2 housing_centre = {0.60F, 0.50F}; const optris_sdk_vec2 housing_size = {0.20F, 0.20F}; uint64_t bearing = 0; uint64_t housing = 0; uint32_t housing_slot = 0; uint64_t rule_id = 0; /* A bearing and the housing beside it. */ optris_sdk_region_create_rect(bearing_centre, bearing_size, 0.0F, &area); optris_sdk_imager_add_region(imager, area, &bearing); optris_sdk_region_free(area); optris_sdk_region_create_rect(housing_centre, housing_size, 0.0F, &area); optris_sdk_imager_add_region(imager, area, &housing); optris_sdk_region_free(area); if (optris_sdk_imager_get_region_signal_slot(imager, housing, &housing_slot) != OPTRIS_SDK_OK) { return; } /* The bearing's maximum more than 15 K above the housing's mean. The * input's index stays 0: add_rule() fills in the bearing's slot. */ optris_sdk_rule_create(&hotter); optris_sdk_rule_set_name(hotter, "bearing hotter than housing"); optris_sdk_signal_id_init(&input, sizeof(input)); input.domain = OPTRIS_SDK_SIGNAL_DOMAIN_REGION; input.field = OPTRIS_SDK_FIELD_MAX; optris_sdk_rule_set_input(hotter, &input); optris_sdk_signal_id_init(&reference, sizeof(reference)); reference.domain = OPTRIS_SDK_SIGNAL_DOMAIN_REGION; reference.field = OPTRIS_SDK_FIELD_MEAN; reference.index = housing_slot; optris_sdk_rule_set_reference(hotter, &reference); /* Offsets, in kelvin of difference, with a pre-alarm at 10 K. */ optris_sdk_condition_init(&condition, sizeof(condition)); condition.compare = OPTRIS_SDK_COMPARE_ABOVE; condition.alarm.high = 15.0F; condition.alarm.hysteresis = 2.0F; condition.has_warning = 1; condition.warning.high = 10.0F; optris_sdk_rule_set_condition(hotter, &condition); /* OPTRIS_SDK_ERROR_INVALID_ARGUMENT when the rule is refused. */ optris_sdk_imager_add_rule(imager, bearing, hotter, &rule_id); optris_sdk_rule_free(hotter);
// A bearing and the housing beside it. ulong bearing; using (Region area = Region.Rect(new Vector2(0.30f, 0.50f), new Vector2(0.10f, 0.10f))) { bearing = camera.AddRegion(area); } ulong housing; using (Region area = Region.Rect(new Vector2(0.60f, 0.50f), new Vector2(0.20f, 0.20f))) { housing = camera.AddRegion(area); } // 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. ulong ruleId = camera.AddRule(bearing, new AlarmRule { Name = "bearing hotter than housing", Input = SignalId.Region(SignalField.Max), Reference = SignalId.Region(camera.GetRegionSignalSlot(housing), SignalField.Mean), Condition = AlarmCondition.Above(15.0f, hysteresis: 2.0f) with { Warning = new AlarmLimits { High = 10.0f }, }, });
# A bearing and the housing beside it. bearing = camera.regions.add( optris_sdk.Region.rect((0.30, 0.50), (0.10, 0.10))) housing = camera.regions.add( optris_sdk.Region.rect((0.60, 0.50), (0.20, 0.20))) # 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. The three-argument SignalId names the housing's slot. hotter = optris_sdk.Rule( name='bearing hotter than housing', input=optris_sdk.SignalId.region(optris_sdk.FIELD_MAX), condition=optris_sdk.Condition( compare=optris_sdk.COMPARE_ABOVE, alarm=optris_sdk.Limits(high=15.0, hysteresis=2.0), warning=optris_sdk.Limits(high=10.0))) hotter.set_reference(optris_sdk.SignalId( optris_sdk.DOMAIN_REGION, optris_sdk.FIELD_MEAN, camera.alarms.region_signal_slot(housing))) hotter_id = camera.alarms.add(hotter, region_id=bearing) print(optris_sdk.state_name(camera.alarms.state_of(hotter_id)))
// A bearing and the housing beside it. let bearing = camera.add_region(&Region::rect((0.30, 0.50), (0.10, 0.10), 0.0)?)?; let housing = camera.add_region(&Region::rect((0.60, 0.50), (0.20, 0.20), 0.0)?)?; // The bearing's maximum more than 15 K above the housing's mean, with a // pre-alarm at 10 K. `index` is the housing's slot. let mut reference = SignalId::new(SignalDomain::Region, SignalField::Mean); reference.index = camera.region_signal_slot(housing)?; let mut hotter = Rule::new()?; hotter.set_name("bearing hotter than housing")?; hotter.set_input(SignalId::region(SignalField::Max))?; hotter.set_reference(reference)?; hotter.set_condition(Condition::above(15.0, 2.0).with_warning(Limits::above(10.0, 0.0)))?; let hotter_id = camera.add_rule(bearing, &hotter)?;
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; };
/* The same six, with the optional warning spelled as a flag beside the * band because C has no optional, and the two delays in whole * milliseconds because that is the ABI's unit. */ optris_sdk_condition condition; optris_sdk_condition_init(&condition, sizeof(condition)); condition.compare = OPTRIS_SDK_COMPARE_ABOVE; condition.alarm.high = 60.0F; /* low, high, hysteresis, delta */ condition.has_warning = 1; condition.warning.high = 55.0F; /* the pre-alarm band */ condition.on_delay_ms = 0; condition.off_delay_ms = 0; condition.latching = 0;
// A record. Warning is a nullable rather than a flag-and-band pair, // and the delays are TimeSpan. var shapeOfCondition = new AlarmCondition { Compare = AlarmCompare.Above, Alarm = new AlarmLimits { High = 60.0f }, Warning = new AlarmLimits { High = 55.0f }, OnDelay = TimeSpan.Zero, OffDelay = TimeSpan.Zero, IsLatching = false, };
# Keywords, with the delays in seconds as floats and `warning` simply # absent when there is none. shape_of_condition = optris_sdk.Condition( compare=optris_sdk.COMPARE_ABOVE, alarm=optris_sdk.Limits(high=60.0), warning=optris_sdk.Limits(high=55.0), on_delay_s=0.0, off_delay_s=0.0, latching=False)
// Public fields with a builder over them: `warning` is an // Option<Limits> and the delays are Durations. let shape_of_condition = Condition::above(60.0, 0.0) .with_warning(Limits::above(55.0, 0.0)) .with_on_delay(Duration::ZERO) .with_off_delay(Duration::ZERO) .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. }
optris_sdk_alarm_state state = OPTRIS_SDK_ALARM_UNKNOWN; int held_by_latch = 0; optris_sdk_imager_get_alarm_runtime(imager, rule_id, &state, &held_by_latch); if (state == OPTRIS_SDK_ALARM_ACTIVE && held_by_latch) { /* The value is back inside the limits. Acknowledge clears it. */ } else if (state == OPTRIS_SDK_ALARM_ACTIVE) { /* Still outside the limit. Acknowledge re-arms the latch and * changes nothing. */ }
AlarmRuntime runtime = camera.GetAlarmRuntime(ruleId); if (runtime.State == AlarmState.Active && runtime.IsHeldByLatch) { // The value is back inside the limits. Acknowledge clears it. } else if (runtime.State == AlarmState.Active) { // Still outside the limit. Acknowledge re-arms the latch and // changes nothing. }
state, held_by_latch = camera.alarms.runtime_of(rule_id) if state == optris_sdk.ALARM_ACTIVE and held_by_latch: pass # the value is back inside the limits; acknowledge clears it elif state == optris_sdk.ALARM_ACTIVE: pass # still outside; acknowledge re-arms the latch only
let (state, held_by_latch) = camera.alarm_runtime(rule_id)?; if state == AlarmState::Active && held_by_latch { // The value is back inside the limits. Acknowledge clears it. } else if state == AlarmState::Active { // 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);
optris_sdk_signal_id signal; optris_sdk_condition inhibit; optris_sdk_signal_id_init(&signal, sizeof(signal)); signal.domain = OPTRIS_SDK_SIGNAL_DOMAIN_PIF; signal.field = OPTRIS_SDK_FIELD_DIGITAL_IN; signal.index = 2; /* the channel */ optris_sdk_condition_init(&inhibit, sizeof(inhibit)); inhibit.compare = OPTRIS_SDK_COMPARE_EQUAL; inhibit.alarm.high = 1.0F; /* The last argument is `invert`. */ optris_sdk_rule_add_inhibit(rule, &signal, &inhibit, 0);
rule.Inhibits.Add(new AlarmInhibit( SignalId.ProcessInterface(channel: 2, SignalField.DigitalIn), new AlarmCondition { Compare = AlarmCompare.Equal, Alarm = new AlarmLimits { High = 1.0f }, }));
rule.add_inhibit( optris_sdk.SignalId.pif(optris_sdk.FIELD_DIGITAL_IN, 2), optris_sdk.Condition(compare=optris_sdk.COMPARE_EQUAL, alarm=optris_sdk.Limits(high=1.0)))
let mut asserted = Condition::new(); asserted.compare = Compare::Equal; asserted.alarm = Limits::above(1.0, 0.0); rule.add_inhibit(SignalId::pif(SignalField::DigitalIn, 2), asserted, false)?;
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; };
/* No variant: one add_*_action() per kind, each taking that kind's own * arguments, and the trigger first. */ optris_sdk_rule *rule = NULL; uint32_t slot = 0; optris_sdk_rule_create(&rule); optris_sdk_rule_add_callback_action(rule, OPTRIS_SDK_ACTION_ON_ACTIVATE, slot); optris_sdk_rule_add_pif_output_action(rule, OPTRIS_SDK_ACTION_ON_CLEAR, 0, 1, 1.0F, 0.0F); optris_sdk_rule_add_snapshot_action(rule, OPTRIS_SDK_ACTION_ON_WARN, OPTRIS_SDK_SNAPSHOT_PNG, NULL, NULL, 0); optris_sdk_rule_add_recording_action(rule, OPTRIS_SDK_ACTION_ON_ANY_CHANGE, OPTRIS_SDK_RECORDING_WHILE_ACTIVE, 0, NULL, NULL); optris_sdk_rule_free(rule);
// A record hierarchy rather than a variant: AlarmAction is abstract // and carries `On`, and the four kinds derive from it. A collection on // the rule takes the place of the vector. var withActions = new AlarmRule { Input = SignalId.Region(SignalField.Max), Condition = AlarmCondition.Above(60.0f), }; withActions.Actions.Add(new CallbackAction(Slot: 0) { On = ActionTrigger.OnActivate, }); withActions.Actions.Add(new PifOutputAction(Channel: 0) { On = ActionTrigger.OnClear, }); withActions.Actions.Add(new SnapshotAction(SnapshotFormat.Png) { On = ActionTrigger.OnWarn, }); withActions.Actions.Add(new RecordingAction(RecordingActionMode.WhileActive) { On = ActionTrigger.OnAnyChange, });
# One method per kind, each with that kind's own keywords and the # trigger among them. ON_ACTIVATE, ON_CLEAR, ON_WARN, ON_ANY_CHANGE. with_actions = optris_sdk.Rule( input=optris_sdk.SignalId.region(optris_sdk.FIELD_MAX), condition=optris_sdk.Condition(compare=optris_sdk.COMPARE_ABOVE, alarm=optris_sdk.Limits(high=60.0))) with_actions.add_callback_action(0, trigger=optris_sdk.ON_ACTIVATE) with_actions.add_pif_output_action(channel=0, active_value=1.0, trigger=optris_sdk.ON_CLEAR) with_actions.add_snapshot_action(trigger=optris_sdk.ON_WARN) with_actions.add_recording_action(trigger=optris_sdk.ON_ANY_CHANGE)
// One method per kind, the trigger first, and each returns &mut Self // so they chain. let mut with_actions = Rule::new()?; with_actions.set_input(SignalId::region(SignalField::Max))?; with_actions.set_condition(Condition::above(60.0, 0.0))?; with_actions.add_callback_action(ActionTrigger::OnActivate, 0)?; with_actions.add_pif_output_action(ActionTrigger::OnClear, 0, true, 1.0, 0.0)?; with_actions.add_snapshot_action(ActionTrigger::OnWarn, SnapshotFormat::Png, None, None, 0)?; with_actions.add_recording_action(ActionTrigger::OnAnyChange, RecordingActionMode::WhileActive, 0, None, None)?;
The four kinds
CallbackActioncalls the handler whoseslotwas returned byAlarms().RegisterCallback():optris_sdk_imager_register_alarm_callback()in C,ThermalCamera.RegisterAlarmCallback()in C#,camera.alarms.register_callback()in Python andregister_alarm_callback()in Rust. Only the rules that name a slot call its handler, where the alarm event stream sees every rule's transitions.PifOutputActiondrives 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.Orphanedis 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.SnapshotActionwrites 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, arec::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 withSaveCsvSnapshot().RecordingActionrecords for as long as the alarm lasts (kWhileActive, the default), for a fixedduration(kFixedDuration, 10 s by default), or stops one (kStop). AkWhileActiverecording 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, arec::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); });
optris_sdk_imager_set_action_error_callback(imager, OnActionError, NULL);
// An async stream rather than a callback, so nothing of yours runs on // the action thread. await foreach (ActionError e in camera.ActionFailed(CancellationToken.None)) { Log(e.RuleId, e.Path, e.Message); }
camera.alarms.on_action_error( lambda e: log(e.rule_id, e.path, e.message))
camera.on_action_error(|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 } });
optris_sdk_imager_set_action_completed_callback(imager, OnActionCompleted, NULL);
await foreach (ActionCompleted e in camera.ActionCompletedAsync(CancellationToken.None)) { switch (e.Outcome) { case ActionOutcome.Written: Log(e.RuleId, e.Path); // on disk, under this name break; case ActionOutcome.SkippedByMinimumInterval: Log(e.RuleId, "skipped: this action's own spacing"); break; case ActionOutcome.DroppedQueueFull: Log(e.RuleId, "no picture: the action queue was full"); break; case ActionOutcome.DroppedFrameBudget: Log(e.RuleId, "no picture: the frame that fired it was not kept"); break; case ActionOutcome.Unknown: break; // never delivered; what a zeroed struct holds } }
def on_completed(e): if e.outcome == optris_sdk.ACTION_OUTCOME_WRITTEN: log(e.rule_id, e.path) # on disk, under this name elif e.outcome == optris_sdk.ACTION_OUTCOME_SKIPPED_BY_MINIMUM_INTERVAL: log(e.rule_id, "skipped: this action's own spacing") elif e.outcome == optris_sdk.ACTION_OUTCOME_DROPPED_QUEUE_FULL: log(e.rule_id, 'no picture: the action queue was full') elif e.outcome == optris_sdk.ACTION_OUTCOME_DROPPED_FRAME_BUDGET: log(e.rule_id, 'no picture: the frame that fired it was not kept') # ACTION_OUTCOME_UNKNOWN is never delivered; it is what a zeroed # struct holds. e.was_written and e.outcome_name() are the two # shorthands for the whole of the above. camera.alarms.on_action_completed(on_completed)
camera.on_action_completed(|e| match e.outcome { ActionOutcome::Written => log(e.rule_id, &e.path), ActionOutcome::SkippedByMinimumInterval => log(e.rule_id, "skipped: this action's own spacing"), ActionOutcome::DroppedQueueFull => log(e.rule_id, "no picture: the action queue was full"), ActionOutcome::DroppedFrameBudget => log(e.rule_id, "no picture: the frame that fired it was not kept"), // Never delivered; it is what a zeroed struct holds. ActionOutcome::Unknown => {} })?;
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);
optris_sdk_action_drop_counts lost; optris_sdk_action_drop_counts_init(&lost, sizeof lost); if (optris_sdk_imager_get_action_drop_counts(imager, &lost) == OPTRIS_SDK_OK) { Log(lost.actions_dropped, lost.reports_dropped); }
ActionDropCounts lost = camera.GetActionDropCounts(); Log(lost.ActionsDropped, lost.ReportsDropped);
lost = camera.alarms.action_drop_counts() log(lost.actions_dropped, lost.reports_dropped)
let lost = camera.action_drop_counts()?; 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 owninputnames a generational slot, filled in byAdd(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 anoptris_sdk_actionwhosekindsays 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; });
// SET, not Add: the ABI holds one provider at a time, so a second call // replaces the first and there is no id to remove. camera.SetAttachmentProvider(request => [ new Attachment("process.json", CollectProcessContext()) { Mime = "application/json", }, ]);
camera.set_attachment_provider(lambda request: [ optris_sdk.Attachment('process.json', collect_process_context(), mime='application/json'), ])
// The provider is handed a SINK rather than returning a list, so a // payload is written once and never held twice. camera.set_attachment_provider(|_request, sink| { let _ = sink.add("process.json", "application/json", &collect_process_context(), true); })?;
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(); }
optris_sdk_alarm_state worst; if (optris_sdk_imager_get_worst_alarm_state(imager, &worst) == OPTRIS_SDK_OK && worst == OPTRIS_SDK_ALARM_ACTIVE) { SoundTheAlarm(); }
if (camera.WorstAlarmState == AlarmState.Active) { SoundTheAlarm(); }
if camera.alarms.worst_state() == optris_sdk.ALARM_ACTIVE: sound_the_alarm()
if camera.worst_alarm_state()? == AlarmState::Active { sound_the_alarm(); }
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
optris_sdk_alarm_state one = OPTRIS_SDK_ALARM_UNKNOWN; optris_sdk_alarm_state per_region = OPTRIS_SDK_ALARM_UNKNOWN; optris_sdk_alarm_state worst = OPTRIS_SDK_ALARM_UNKNOWN; optris_sdk_imager_get_alarm_state(imager, rule_id, &one); optris_sdk_imager_get_region_alarm_state(imager, region_id, &per_region); optris_sdk_imager_get_worst_alarm_state(imager, &worst);
AlarmState one = camera.GetAlarmState(ruleId); // one rule AlarmState perRegion = camera.GetRegionAlarmState(regionId); AlarmState worst = camera.WorstAlarmState; // everything
one = camera.alarms.state_of(rule_id) # one rule per_region = camera.alarms.region_state(region_id) # that region's rules worst = camera.alarms.worst_state() # everything
let one = camera.alarm_state(rule_id)?; // one rule let per_region = camera.region_alarm_state(region_id)?; let worst = camera.worst_alarm_state()?; // 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 });
/* 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 */ optris_sdk_imager_set_alarm_callback(imager, OnAlarm, NULL);
// e.RuleId, e.RuleName, e.RegionId, e.RegionName, // e.Previous -> e.Current, e.Input, // e.Value, e.Limit, e.LimitKind, // e.Sequence, e.Timestamp, e.HostTime await foreach (AlarmEvent e in camera.AlarmEventsAsync(CancellationToken.None)) { Console.WriteLine($"{e.RegionName} {e.Previous} -> {e.Current}"); }
def on_transition(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 pass camera.alarms.on_alarm(on_transition)
camera.on_alarm(|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 let _ = (&e.region_name, e.previous, e.current, e.value); })?;
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); });
optris_sdk_region *zone = NULL; optris_sdk_rule *hot = NULL; optris_sdk_signal_id input; optris_sdk_condition condition; uint64_t zone_id = 0; uint64_t hot_id = 0; optris_sdk_region_create_rect((optris_sdk_vec2){0.5F, 0.375F}, (optris_sdk_vec2){0.6F, 0.45F}, 0.0F, &zone); optris_sdk_region_set_name(zone, "Furnace"); optris_sdk_imager_add_region(imager, zone, &zone_id); optris_sdk_region_free(zone); optris_sdk_rule_create(&hot); optris_sdk_rule_set_name(hot, "over temp"); optris_sdk_signal_id_init(&input, sizeof(input)); input.domain = OPTRIS_SDK_SIGNAL_DOMAIN_REGION; input.field = OPTRIS_SDK_FIELD_MAX; optris_sdk_rule_set_input(hot, &input); optris_sdk_condition_init(&condition, sizeof(condition)); condition.compare = OPTRIS_SDK_COMPARE_ABOVE; condition.alarm.high = 50.0F; condition.alarm.hysteresis = 2.0F; condition.has_warning = 1; condition.warning.high = 45.0F; condition.on_delay_ms = 100; optris_sdk_rule_set_condition(hot, &condition); optris_sdk_rule_add_snapshot_action(hot, OPTRIS_SDK_ACTION_ON_ACTIVATE, OPTRIS_SDK_SNAPSHOT_PNG, NULL, NULL, 5000); optris_sdk_imager_add_rule(imager, zone_id, hot, &hot_id); optris_sdk_rule_free(hot); optris_sdk_imager_set_alarm_callback(imager, OnAlarm, NULL);
using Region furnace = Region.Rect(new Vector2(0.5f, 0.375f), new Vector2(0.6f, 0.45f)); furnace.Name = "Furnace"; ulong furnaceId = camera.AddRegion(furnace); var furnaceHot = new AlarmRule { Name = "over temp", Input = SignalId.Region(SignalField.Max), Condition = AlarmCondition.Above(50.0f, hysteresis: 2.0f) with { Warning = new AlarmLimits { High = 45.0f }, OnDelay = TimeSpan.FromMilliseconds(100), }, }; furnaceHot.Actions.Add(new SnapshotAction( MinimumInterval: TimeSpan.FromSeconds(5))); camera.AddRule(furnaceId, furnaceHot);
furnace = optris_sdk.Region.rect((0.5, 0.375), (0.6, 0.45)) furnace.set_name('Furnace') furnace_id = camera.regions.add(furnace) furnace_hot = optris_sdk.Rule( name='over temp', input=optris_sdk.SignalId.region(optris_sdk.FIELD_MAX), condition=optris_sdk.Condition( compare=optris_sdk.COMPARE_ABOVE, alarm=optris_sdk.Limits(high=50.0, hysteresis=2.0), warning=optris_sdk.Limits(high=45.0), on_delay_s=0.1)) furnace_hot.add_snapshot_action(trigger=optris_sdk.ON_ACTIVATE, min_interval_s=5.0) camera.alarms.add(furnace_hot, region_id=furnace_id) camera.alarms.on_alarm( lambda e: print(f'{e.region_name} ' f'{optris_sdk.state_name(e.previous)} -> ' f'{optris_sdk.state_name(e.current)} at ' f'{e.value:.1f} C'))
let mut furnace = Region::rect((0.5, 0.375), (0.6, 0.45), 0.0)?; furnace.set_name("Furnace")?; let furnace_id = camera.add_region(&furnace)?; let mut furnace_hot = Rule::new()?; furnace_hot.set_name("over temp")?; furnace_hot.set_input(SignalId::region(SignalField::Max))?; furnace_hot.set_condition( Condition::above(50.0, 2.0) .with_warning(Limits::above(45.0, 0.0)) .with_on_delay(Duration::from_millis(100)), )?; furnace_hot.add_snapshot_action(ActionTrigger::OnActivate, SnapshotFormat::Png, None, None, 5000)?; camera.add_rule(furnace_id, &furnace_hot)?; camera.on_alarm(|e| { println!("{} {:?} -> {:?} at {:.1} C", e.region_name, e.previous, 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().