Guide / Controls / Reference

Derive

Values the phone computes from other values, with no server and no code. A layout's top-level derive object is keyed by id; each entry is a small JSON op tree. A control shows one with a Sync entry of method: "derive".

Symbol
function
Docs
Docs complete

Fields

26 fields, each with what it does.

Fields
FieldTypeDefaultWhat it does
controlcontroltext—

Use another control's number

Reads whatever the control with this id is showing right now, from any source.

derivederivetext—

Use another calculated value

Reads the result of another derive entry, so formulas can build on each other.

clockclockon / off—

Use the current time

Reads now as epoch seconds; it makes the result refresh on a timer while the layout is open.

addaddlist—

Add numbers together

Shows the sum of all the arguments.

subsublist—

Subtract numbers

Shows the first argument minus each of the rest.

mulmullist—

Multiply numbers

Shows the product of all the arguments, e.g. volts times amps for watts.

divdivlist—

Divide numbers

Shows the first argument divided by each of the rest; stays empty if any divisor is 0.

minminlist—

Pick the smallest

Shows the smallest of the arguments.

maxmaxlist—

Pick the biggest

Shows the largest of the arguments.

avgavglist—

Average of numbers

Shows the mean of the arguments, e.g. the average of three sensors.

coalescecoalescelist—

First one that has a value

Shows the first argument that is not empty, as a number or text, skipping missing ones.

absabsobject—

Drop the minus sign

Shows the absolute value of one argument.

roundroundobject—

Round a number

Rounds the value to a number of decimals; a bare argument rounds to a whole number.

clampclampobject—

Keep a number in a range

Holds the value between a lowest and highest bound so it never goes past them.

scalescaleobject—

Convert from one range to another

Maps the value linearly from one range onto another, e.g. 0-100 onto 32-212; it is not clamped.

bandbandobject—

Turn a number into a word

Shows a label for the bucket the value falls into, e.g. cold, ok or warm.

sincesinceobject—

How long ago

Shows the time elapsed since a date, in the chosen unit.

untiluntilobject—

How long until

Shows the time remaining until a date, in the chosen unit; negative once it has passed.

sumsumlist—

Add numbers together

Works exactly like add: shows the sum of the arguments.

ofofobject—

The value to work on

Gives round, clamp, scale, band, since and until the number or date to process.

placesplacesnumber0–12step 1—

Digits after the point

Sets how many decimals round keeps, from 0 to 12.

fromfromlist—

The range you start from

Sets the source range [a, b] that scale reads the value against.

totolist—

The range you end in

Sets the target range [c, d] that scale maps the value onto.

stopsstopslist—

The cut-off points

Sets the ascending thresholds band uses to sort the value into buckets.

labelslabelslist—

The words for each bucket

Sets the text band shows for each bucket, one more than the number of stops.

unitunitchoiceone of 5—

Seconds, minutes, days...

Chooses the unit since and until report their result in; seconds if unset.

  • secondsthe elapsed or remaining time in seconds
  • minutesthe time in minutes
  • hoursthe time in hours
  • daysthe time in days
  • weeksthe time in weeks

Examples

3 examples, each one a control you can paste into a layout.

Power from volts and amps

Demonstrates mul with two control arguments: a gauge shows watts without any server math.

JSON 4 lines
{
  "derive": { "watts": { "mul": [ {"control": "volts"}, {"control": "amps"} ] } },
  "control": { "type": "gauge", "id": "wattsGauge", "min": 0, "max": 1800, "label": "Power", "sync": [ { "method": "derive", "from": "watts" } ] }
}

Tank percent with a comfort word

Demonstrates div, mul, clamp and round nested together, then band with labels turning a number into a word.

JSON 6 lines
{
  "derive": {
    "tankPct": { "round": { "of": { "clamp": { "of": { "mul": [ { "div": [ {"control": "level"}, 180 ] }, 100 ] }, "min": 0, "max": 100 } }, "places": 0 } },
    "tankState": { "band": { "of": {"derive": "tankPct"}, "stops": [20, 80], "labels": ["low", "ok", "full"] } }
  }
}

Temperature convert and days since

Demonstrates scale with from and to (Celsius to Fahrenheit) and since with unit: "days", which refreshes on its own clock tick.

JSON 7 lines
{
  "derive": {
    "tempF": { "scale": { "of": {"control": "tempC"}, "from": [0, 100], "to": [32, 212] } },
    "daysWatered": { "since": { "of": {"control": "lastWatered"}, "unit": "days" } },
    "reading": { "coalesce": [ {"control": "sensorA"}, {"control": "sensorB"}, 0 ] }
  }
}

Definition

"derive": {
  "watts":   { "mul": [ {"control": "volts"}, {"control": "amps"} ] },
  "avgC":    { "avg": [ {"control": "t1"}, {"control": "t2"}, {"control": "t3"} ] },
  "avgF":    { "scale": {"of": {"derive": "avgC"}, "from": [0, 100], "to": [32, 212]} },
  "tankPct": { "clamp": {"of": {"mul": [ {"div": [ {"control": "level"}, 180 ]}, 100 ]},
                         "min": 0, "max": 100} },
  "comfort": { "band": {"of": {"derive": "avgC"}, "stops": [18, 24],
                        "labels": ["cold", "ok", "warm"]} }
}
{ "type": "gauge", "id": "wattsGauge", "min": 0, "max": 1800, "formatValue": "integer",
  "sync": [ { "method": "derive", "from": "watts" } ] }

Formulas are JSON structure, never strings. Each node is an object with exactly one key: the op.

Arguments

An argument is one of four things:

Form Reads
42 a number literal
{"control": "volts"} whatever control volts currently displays, from any transport (meshsocket, MQTT, HTTP, sensor, local store) or a user gesture
{"derive": "watts"} another derive entry's result
a nested node {"div": [{"control": "level"}, 180]}

{"clock": true} is now, as epoch seconds.

Ops

Op Shape Result
add / sum [a, b, ...] a + b + ...
sub [a, b, ...] a − b − ...
mul [a, b, ...] a × b × ...
div [a, b, ...] a ÷ b ÷ ...; nil when any divisor is 0
min / max [a, b, ...] smallest / largest
avg [a, b, ...] mean
coalesce [a, b, ...] the first argument that is not nil, as-is (a number or a label)
abs a or [a] absolute value
round {"of": a, "places": 2} or a rounded to places decimals (0-12, default 0); half rounds away from zero
clamp {"of": a, "min": lo, "max": hi} a kept inside lo..hi; either bound may be omitted, not both; bounds may be arguments
scale {"of": a, "from": [0, 100], "to": [32, 212]} linear map, not clamped; nil when from has equal ends
band {"of": a, "stops": [20, 30], "labels": ["low", "ok", "high"]} labels[i] for the first stops[i] that a is below, else the last label; labels has one more entry than stops, stops strictly ascending
since {"of": date, "unit": "days"} or date time since date; unit seconds (default), minutes, hours, days, weeks
until {"of": date, "unit": "hours"} or date time until date, negative once it has passed

The n-ary ops need at least one argument. round is for maths such as "whole litres"; display formatting stays in formatValue. band pairs with colorMap / iconMap to turn a raw number into a Starting status.

A since / until date is an ISO-8601 or yyyy-MM-dd string, or an epoch number (seconds; milliseconds when larger than 10^11). Nodes that read the clock are re-evaluated on a coarse tick only while the layout is open: every second for seconds and clock, every 5 s for minutes, every minute otherwise.

Value rules

  • Coercion. Numbers pass through, true/false count as 1/0, and numeric strings parse (" 121.5 " is 121.5). Anything else is unreadable.
  • Nil propagates. An unreadable or missing input makes the node nil, and every node that reads it is nil too (except coalesce, which skips it). A control bound to a nil derive keeps its defaultValue.
  • Never infinite. Division by zero, or any result that is not finite, is nil, never inf.
  • Unknown ops fail closed. An op this app does not know evaluates to nil for that node and everything downstream. The layout still loads, so a newer layout degrades instead of failing. carterkit's validator flags it as an error.
  • No side effects. A derive never fires an action, never builds a string beyond a band label, and never loops.

Graph rules

A layout is refused at import (and an entry dropped when repaired from disk) when:

  • a derive id collides with a control id;
  • a {"control": id} or {"derive": id} names something that does not exist;
  • the graph has a cycle, including one through a binding: control X shows derive d and d reads X;
  • it is over the caps: 256 op nodes in the whole block, 16 levels of nesting, 32 arguments to one op.

A sync entry with method: "derive" needs from, naming a declared derive id.

Where the value lives

  • Per device. Derived values never go on the wire. Every device recomputes them from what it displays, so room members can briefly disagree while their inputs differ. Room snapshots and state sync leave derived consumers out.
  • What the user sees. While an ack'd command is pending, the graph reads the optimistic on-screen value, so derived tiles never tear.
  • Relay alerts cannot see derived values. Alerts are evaluated on the relay from server-readable frames; a derived value only exists on the phone.
  • Live Activities can disagree. A server-pushed Live Activity (bridge notify) never passes through the phone's graph, so it can show a different number from the on-screen derived tile. Point Glance Surfaces slots at the consuming control so the app-driven surfaces stay in step.
  • Older apps ignore derive; a consumer just shows its defaultValue. Pair a derive layout with requires (see Layout Config).
  • E2EE rooms. Evaluation happens after decryption on the device; the relay learns nothing new.

Notes

  • A derived value lives under its own id, so a visibility condition can watch it with {"control": "watts"} like any control (see Visibility).
  • carterkit ships a reference evaluator (carterkit.derive) and shared fixtures that the app's tests run too, so Python and Swift compute the same numbers.

Generated from ControlDocs/derive.md. Something unclear or missing? Tell me.