Trigger logic

Learn how to write your own Signals triggers: where they live, what a rule sees and returns, every operator, and worked examples.

Learn how to write the rules Signals judges readings with.

A trigger is a rule Signals runs on a patient's readings of one code. It decides whether to raise an alert, resolve one, or do nothing. Its logic is JSON Logic: data, not code, run by Signals' rule engine. Write your own for your whole tenant or for one patient, beside or instead of the default triggers.

  • Your own algorithms: judge any code your devices send, with your own thresholds and messages.
  • Per patient: a clinician's rule for one patient wins over the tenant's rule for the same code.
  • No deploy: a trigger takes effect on the next reading.
A rule that fails raises no alert. Test every rule on a test patient before real patients depend on it.

Where triggers live

LevelReadWriteShape
Your tenant: every patientGET /tenant, orgSettings.triggersPATCH /tenant, orgSettings.triggersObject keyed by code
One patientGET /patient/{id}/settings, triggersPUT /patient/{id}/settings, triggersObject keyed by code
Many patients at oncePOST /patient/config, triggersArray, each trigger with its code

Every route is under /v1/signals/api. Call them as a Manager application or a project admin.

  • triggers is replaced whole on PATCH /tenant and PUT /patient/{id}/settings. Read the stored triggers first and send every one you keep.
  • POST /patient/config writes one code at a time. Each trigger replaces the patient's trigger for its code and leaves the others alone. "delete": true removes the patient's trigger for the code, and the patient's band for it.
  • A trigger without logic is refused, and the answer lists it.

Which trigger judges a code

For each code a reading carries, Signals runs one trigger:

  1. The patient's own trigger for the code, else the tenant's.
  2. Within each, a system|code key, such as http://loinc.org|8867-4, wins over the bare code.
  3. Failing both, the * trigger: the patient's, else the tenant's. It skips the tenant's informationalCodes.

Triggers run in ascending order.

From the read shape to the write shape

GET /tenant answers orgSettings.triggers as an object keyed by code. PATCH /tenant and PUT /patient/{id}/settings take that object as it is. POST /patient/config takes an array instead: each key becomes the entry's code, and the * key becomes "code": "*".

{
  "orgSettings": {
    "triggers": {
      "8867-4": {
        "display": "Heart rate",
        "constants": { "high": 110 },
        "logic": { "if": [{ ">": [{ "var": "value" }, { "var": "high" }] }, "Heart rate above 110 /min", false] }
      }
    }
  }
}

With jq, the conversion is .orgSettings.triggers | to_entries | map({code: .key} + .value).

Trigger fields

FieldMeaning
codeArray form only: the code the trigger judges, a system|code key, or *.
logicThe rule. A JSON object or array, or the same as JSON text. Signals stores it as sent; the default triggers are stored as text.
constantsNamed values the rule reads as variables, such as {"low": 50, "high": 110}.
valueKeyThe name the reading's value is read under. value when absent.
display, notesLabels for people. Signals does not read them.
orderWhere the trigger runs among one reading's triggers, ascending. 0 when absent.
everyReadingtrue runs it on every reading of the patient, even one that does not carry its code.
schedule{"at": "07:00", "timeZone": "Europe/Berlin"} runs it once a local day instead of on readings. UTC when you name no zone.
everyA number of seconds: runs it at most once in each such period instead of on readings. schedule wins when both are set.
onAck, onCloseLogic run when someone acknowledges an alert (onAck), or when Signals closes everything a patient has open, such as on discharge (onClose). It sees now, patient, state, and the alert or close reason, and may return remember, forget and note actions.
deletePOST /patient/config only: true removes the trigger.
metadataPOST /patient/config only: free-form labels kept with the trigger. Signals does not read them.

A scheduled run has no reading: tick is true, vitals is empty and there is no value.

What a rule sees

NameValue
valueThe reading's value for the code being judged: a number, or text. Under your valueKey when you set one. Absent when the reading has no value for the code.
vitalCodeThe code being judged, such as 8867-4.
Each key of constantsAs you set it. A constant never replaces value, code, valueQuantity or valueString.
code, valueQuantity, valueStringThe reading's FHIR coding and value for the code being judged.
vitalsEvery code the reading carries, with its value. Also under system|code when the reading names a system.
absentPer code without a value, its dataAbsentReason code.
samplesPer code sent as valueSampledData, its samples as [epochMs, value, …], oldest first.
sourceRefIdsPer code, the refId of the reading its value came from, or null.
observedAtThe reading's clinical time, ISO 8601.
lastSeenAtThe clinical time of the patient's newest reading before this one, or null.
nowWhen the rule runs, in epoch milliseconds.
ticktrue on a scheduled run.
patientThe patient's id, refId, tenantId and project.
stateWhat the patient's rules stored with remember.
settings.individual, settings.orgThe patient's own rule settings and the tenant's orgSettings: bands, outOfBed, triggers, and any other key you store there.
openThe patient's open alerts, each {"code", "variant"}.

Read a value with var and a dotted path, {"var": "settings.org.bands.8867-4"}, or with val and a list, {"val": ["settings", "org", "bands", {"var": "vitalCode"}]}. A val segment may be computed.

What a rule returns

ResultWhat Signals does
trueRaises an alert on the code, or refreshes the open one, with the message "<code> triggered at value <value>."
false, null or ""Resolves the code's open alert as recovered.
TextRaises an alert with the text as its message. Text that is JSON, such as "true", is read as that JSON.
{"alert": true, "value": 132, "message": "…"}Raises an alert with that value and message. Text in value is stored as the alert's payload. variant names the alert's kind, trigger when absent. {"alert": false} resolves as recovered.
An actionApplied.
A listEach item in turn. null items are skipped, so a list resolves nothing unless an item does.

Anything else, such as a number, fails the rule.

Logic inside an object literal does not run. Build an object from logic with eachKey.

Actions

Return an action to do more than raise or resolve. Each has an operator that builds it.

OperatorArgumentsWhat it does
fire[code, variant, message, value, payload, period, limitSeconds]Raises an alert on code. Only code is required; pass null to skip one. variant is trigger when absent, payload is text stored with the alert, period is {"start", "end"}, and limitSeconds is the limit in force.
resolve[code, reason]Resolves the open alert of code, a list of codes, or * for every open alert of the patient. reason is recovered, returned_to_bed, away, no_threshold or stale; any other fails the rule.
remember[key, value, key, value, …]Stores values in the patient's state for later evaluations.
forget[key] or [[key, …]]Removes keys from state.
record[code, value, components, period]Stores a computed number as a derived reading of code, sent as observation.derived. It is never judged.
note[name]Counts and logs a named condition. It changes nothing.

no_threshold closes the code's episode as THRESHOLD_CHANGED. See Alerts and episodes.

Operators

Signals runs rules on json-logic-engine 5.0.7, which reads an object it does not know as data. A misspelt operator therefore fails when the rule runs, not when you save it. Use only the operators below.

Standard and engine operators

GroupOperators
Datavar, val, exists, missing, missing_some, get, keys, length, preserve
Logicif (also ?:), and, or, !, !!, ??, try, throw
Comparison==, ===, !=, !==, <, <=, >, >=
Arithmetic+, -, *, /, %, max, min
Textcat, substr, in
Listsmap, filter, reduce, all (also every), some, none, merge, in
ObjectseachKey, pipe

These are not in the original JSONLogic specification:

OperatorExampleResult
val{"val": ["vitals", {"var": "vitalCode"}]}The value at a path given as a list.
exists{"exists": "lastSeenAt"}true when the path is present, even as null.
get{"get": [{"var": "band"}, "high", 110]}A key of an object, or the default.
keys{"keys": [{"var": "vitals"}]}An object's keys.
length{"length": {"var": "samples.8867-4"}}The length of a list or text, or an object's key count.
??{"??": [{"var": "individual"}, {"var": "org"}]}The first argument that is not null.
try{"try": [{">": [{"var": "value"}, 5]}, false]}The first argument that does not fail.
throw{"throw": "NO_BAND"}Fails the rule.
eachKey{"eachKey": {"value": {"var": "value"}, "alert": true}}An object with each value's logic run.
pipe{"pipe": [{"eachKey": …}, {"if": …}]}Runs each step on the previous step's result. The first step reads the rule's data.
  • Text and numbers: comparing text with a number, or doing arithmetic on text, fails the rule. Guard with try when a code can carry text.
  • null in comparisons: <, <=, > and >= read null as 0, so {">": [{"var": "value"}, null]} is true. Check a limit with !== null before you compare with it.

Signals operators

OperatorArgumentsResult
mean, stddev, rmssd[list]Of a list of numbers. Anything else in the list fails the rule.
median, sum, count, cv, sort[list]Of the list's numbers; anything else is dropped. cv is the coefficient of variation, standard deviation over mean; sort is ascending.
percentile[list, rank]The rank percentile, 0 to 100, of the list's numbers.
slope[list]The least-squares slope of [epochMs, value] points, such as window's, in value units per second.
beatIntervals, pulseIntervals[samples]The intervals between beats or pulses in [epochMs, value, …] samples.
round[value, decimals]Rounded, to whole numbers when decimals is absent.
floor, ceil, exp[value]As in mathematics.
pow[base, exponent]base to the power exponent.
clamp[value, low, high]value held between low and high.
since[time]Seconds from time (ISO 8601 or epoch ms) to now.
secondsBetween[from, to]Seconds from from to to.
localMinuteOfDay[time, timeZone]Minutes since local midnight in an IANA zone, such as Europe/Berlin.
clockMinutes["HH:MM"]Minutes since midnight.
window["code", seconds]The patient's live readings of code in the last seconds, as [epochMs, value], oldest first, the readings being judged included.
daily["code", days, aggregate, options]One {"day", "value", "count"} per local day, oldest first.
json[value]The value as JSON text.
compact[object]The object without its null keys, at every depth.
apply[logic, data]Runs logic against data.
fire, resolve, remember, forget, record, noteSee ActionsAn action.
  • Number operators answer null for null and for a result that is not a finite number.
  • window reaches back at most 28 days (2419200 seconds). daily takes 1 to 28 days, an aggregate of mean, min, max, sum, count, first, last or median, and options of category, timeZone, dayStartsAt ("HH:MM") and component.
  • window and daily arguments must be written out, or read from constants: Signals loads the readings before the rule runs. A computed argument fails the rule.

Examples

A threshold with constants

Raises an alert below 50 or above 110 beats per minute and resolves it in between. Change the limits in constants without touching the logic.

Trigger for 8867-4
{
  "code": "8867-4",
  "display": "Heart rate",
  "constants": { "low": 50, "high": 110 },
  "logic": {
    "if": [
      { "<": [{ "var": "value" }, { "var": "low" }] },
      { "eachKey": {
        "alert": true,
        "value": { "var": "value" },
        "message": { "cat": ["Heart rate below ", { "var": "low" }, " /min"] }
      } },
      { ">": [{ "var": "value" }, { "var": "high" }] },
      { "eachKey": {
        "alert": true,
        "value": { "var": "value" },
        "message": { "cat": ["Heart rate above ", { "var": "high" }, " /min"] }
      } },
      false
    ]
  }
}
ReadingResult
132Alert, value 132, "Heart rate above 110 /min"
42Alert, value 42, "Heart rate below 50 /min"
80The open alert resolves as recovered

Individual and tenant bands

Judges breathing rate against the patient's own band, else the tenant's, from settings.individual.bands and settings.org.bands. A band may set low, high or both; "NO_THRESHOLD" switches the code off.

Trigger for 9279-1
{
  "code": "9279-1",
  "display": "Breathing rate",
  "logic": {
    "pipe": [
      { "eachKey": {
        "code": { "var": "vitalCode" },
        "value": { "var": "value" },
        "band": { "??": [
          { "val": ["settings", "individual", "bands", { "var": "vitalCode" }] },
          { "val": ["settings", "org", "bands", { "var": "vitalCode" }] }
        ] }
      } },
      { "if": [
        { "===": [{ "var": "band" }, null] }, null,
        { "===": [{ "var": "band" }, "NO_THRESHOLD"] }, { "resolve": [{ "var": "code" }, "no_threshold"] },
        { "and": [
          { "!==": [{ "var": "band.low" }, null] },
          { "<": [{ "var": "value" }, { "var": "band.low" }] }
        ] },
        { "fire": [{ "var": "code" }, "low", { "cat": ["Below ", { "var": "band.low" }] }, { "var": "value" }] },
        { "and": [
          { "!==": [{ "var": "band.high" }, null] },
          { ">": [{ "var": "value" }, { "var": "band.high" }] }
        ] },
        { "fire": [{ "var": "code" }, "high", { "cat": ["Above ", { "var": "band.high" }] }, { "var": "value" }] },
        { "resolve": [{ "var": "code" }, "recovered"] }
      ] }
    ]
  }
}

The first step gathers what the second needs, because each pipe step reads only the step before it. With the tenant's band {"low": 8, "high": 25} and the patient's {"low": 10, "high": 30}:

ReadingResult
27The patient's band applies: resolves as recovered
9Alert, variant low, "Below 10"
27, with no band of the patient'sAlert, variant high, "Above 25"
Any, with the band "NO_THRESHOLD"Resolves as no_threshold

Set the bands with PATCH /tenant (orgSettings.bands) and PUT /patient/{id}/settings (bands). The default triggers read the same keys.

Best practices

  • Test on a test patient. Post readings in, out of and on the edge of the band with Prefer: respond-sync: the answer lists the alerts the rule raised.
  • Keep limits in constants or bands, not in the logic, so one rule serves every patient.
  • Guard every limit with !== null, and every comparison on a code that can carry text with try.
  • Start from a default trigger. Read them with GET /tenant; they use every pattern on this page.

See also

Last updated on

On this page