Capture Motor On/Off Times
Marks the exact moment a motor (or any binary sensor) switches on or off, writing motorOnTs/motorOffTs attributes only on real transitions — never on a repeated reading.
Who it’s for
IoT engineers and solution builders who need to know exactly when a motor — or any binary on/off sensor — turned on or off, not just that telemetry arrived. Useful on its own for a “last turned on at / last turned off at” dashboard card, and as the building block for any runtime or duration calculation you build on top of it.
What it does
Reads the sensor’s own telemetry history through a Time series
rolling argument (30-day window, limited to the 2 most recent
readings) and compares the two. On a 0 → 1 transition it writes a
motorOnTs server-scope attribute; on a 1 → 0 transition it writes
motorOffTs. Either way, the attribute is stamped with the timestamp
of the reading that caused the transition.
If the two most recent readings are the same value — a repeated 1
or a repeated 0 — nothing is written at all. This is what makes the
timestamps reliable on devices that report periodically (heartbeat
telemetry) rather than strictly on change: a run of repeated 1s
never moves motorOnTs, and a run of repeated 0s never moves
motorOffTs, so each attribute always reflects the true first moment
of that state, however many repeats follow before the next real
transition.
How to set up
The state argument is a rolling-window argument, and rolling
arguments don’t fall back to a default value the way single-value
arguments can. That means the device must already have at least one
motor reading in its telemetry history before this field can
initialize — until then, the platform reports Required arguments
are missing: state and the field stays inactive. Send one telemetry
value first if the device is brand new, then the field activates
normally from the next reading onward.
How to customize
- To use this on a different device or sensor — change the
Time series key on the
stateargument frommotorto whatever key your device reports (a door contact, a pump, an occupancy sensor — any binary 0/1 signal). - To rename the output attributes — open the script and replace
motorOnTs/motorOffTsin the tworeturnstatements with the attribute names your dashboards and downstream fields expect. - To tolerate longer gaps between readings — increase the 30-day Time window if this device might go quiet longer than that between telemetry posts. In practice this rarely needs changing, since the field only ever needs the 2 most recent readings, whatever the gap between them.
Share Your Calculated Field with the Community
Built a useful data transformation? Export it as a JSON from ThingsBoard and publish it to the IoT Hub. Share it with thousands of ThingsBoard developers worldwide.