BT San Technology

28 August 2026

A device offline is not a zero reading: separate online status, and alarms that do not repeat

20 min read · Automation

Illustration: a monitor showing three tank tiles, the middle one greyed with a broken-link icon instead of a zero, a real elevated tank seen through the window
AI-generated illustration

A water tank on a hill in a village water supply has a level sensor that reports every minute. One morning the power to the sensor cabinet went out at 08:00. The system recorded the gap as 0, the chart dropped to zero, and a low-level alarm fired at once. The operator called a technician to go and check the pump, even though for all 41 minutes the tank held 64% to 68%.

About an hour earlier, the level had fallen to around the 40% alarm line and was swinging up and down by less than two percentage points. The system raised an alarm every time the value crossed the line downward: 5 alarms in half an hour. Together with the power cut, that made 6 alarms in one morning. When alarms come this often, people stop reading them, and on the day the water really runs out nobody will hurry.

This article fixes both problems with TypeScript code that Node 24 runs directly, with nothing to install. The first fix separates the device status (online / stale / offline) from the measured value, using the time of the last data together with the MQTT last will. The second is a low-level alarm with an on-delay and a deadband, so a value hovering near the line raises one alarm only. Every step has a real run result to look at.

The real problem: a missing value and a zero look the same on the screen

The three situations below are hypothetical cases that are common in remote site monitoring. They are not any customer's project.

  • Filling in 0 when there is no data: some databases or charts fill gaps with zero by themselves, or the code reads a missing value as 0. Water level, pressure or power then drops to zero every time the signal is lost, and the alarm fires for the wrong reason.
  • Freezing the last value without saying so: the opposite of the first case. The screen shows a steady 68% for three hours although the sensor died long ago. If the water really ran out during that time, nobody would know.
  • Alarming every time the line is crossed: a value swinging around the alarm line makes the alarm raise and clear dozens of times. The chat group fills up with alarm messages, and people mute it.

The common fix is to separate two questions: is the device still sending data, and what does the value it sent say. The alarm logic then uses only values that actually arrived, never a value filled in for a gap.

What the documents say, and what this example chooses by itself

TopicWhat the document saysEffect on our example
Keep AliveThe client must send a packet within the Keep Alive period. If the server receives nothing within one and a half times this period, it must close the connection (MQTT 3.1.1 section 3.1.2.10)The example assumes a keep alive of 5 minutes, so the broker learns the device is gone about 7.5 minutes after the last data
Will MessageThe client leaves a message when it connects. The server sends it when the connection ends abnormally, for example when there is no communication within the Keep Alive time, and discards it when the client sends DISCONNECT (MQTT 3.1.1 section 3.1.2.5)The will is used as an offline signal that is faster than waiting for the data to age. On a normal shutdown, the device must publish the offline status itself
Will Delay IntervalMQTT 5.0 lets the server wait the configured time (in seconds) before sending the will. If the client reconnects before that time is up, the will is not sent. The default 0 means no wait (section 3.1.3.2.2)The simulated example uses 3.1.1, so this is not used. With MQTT 5, this value reduces online/offline flicker during short network drops
HysteresisElectronic circuits often include hysteresis on purpose, to prevent unwanted rapid switching back and forth (Wikipedia: Hysteresis)The alarm uses the same principle: alarm below 40%, clear only above 45%
Alarm floodWikipedia (Alarm management) calls a situation where so many alarms arrive at once that people cannot keep up an alarm flood, and cites the ISA 18.2 and EEMUA 191 standardsThe author did not read either standard in full. The on-delay and deadband values in the example do not come from the standards
Stale / offline times, on-delay, deadbandNo central standard defines them3 minutes, 15 minutes, 3 and 5 percent are values the author picked to make the effect visible. Set them from the real site
Documents read on 2026-11-23. MQTT sections are cited from the OASIS 3.1.1 and 5.0 versions

Every number in this article is hypothetical. The water level comes from a formula in the code, not from a real tank or sensor.

Files in the example

FilePurpose
status.tsReports online / stale / offline status from the last data time and the last will
alarm.tsLow-level alarm with an on-delay and a deadband
demo.tsSimulates a water-level sensor for 3 hours, with the value hovering near the alarm line for a while, then a 41-minute power cut. Compares the correct way with the zero-fill way
device-status.test.tsA suite of 5 tests using node:test
output.txtReal output of node demo.ts
README.mdHow to run it and the limits of the example
Everything is in the folder examples/device-offline-vs-zero/. Requires Node 22.6 or later (24 recommended). No npm install needed

Step 1: device status separate from the measured value

The status function uses two facts: the time the last data arrived, and the time the broker last sent this device's will. If no data has ever arrived, it counts as offline, because an unknown value is not zero. If the will arrived after the last data, it counts as offline immediately. Otherwise it looks at the age of the data: more than 3 minutes is stale, more than 15 minutes is offline. This is the same idea as a heartbeat in computer systems: a signal that arrives at regular intervals to say the device is still working. If it is missing for longer than the limit, something is wrong.

status.ts · lines 6–11
export function status(now: number, s: Seen, staleAfter: number, offlineAfter: number): Status {
  if (s.lastData === null) return "offline"; // never heard from it: not zero, unknown
  if (s.lastWill !== null && s.lastWill >= s.lastData) return "offline"; // broker says the link died
  const age = now - s.lastData;
  return age > offlineAfter ? "offline" : age > staleAfter ? "stale" : "online";
}
status.ts: status from data age and last will

Stale is for data that is a round or two late, which can happen normally. The screen may still show the last value, but it should be faded and show the time of that value. Offline means we stop trusting the last value, and the screen must say the current value is unknown.

On MQTT the usual method is this: right after connecting, the device publishes a retained online message to its own status topic, and sets the will to a retained offline message on the same topic. A screen opened later sees the latest status immediately. This example is not connected to a real broker, so it simulates the time the will arrives as a number.

Step 2: one alarm only, with an on-delay and a deadband

LowAlarm has three values. The alarm line is 40%. The on-delay is 3, meaning the value must stay below the line for three consecutive minutes before it alarms. The deadband is 5, meaning the alarm clears only when the value rises back above 45%. A value that dips below the line for one minute and comes back does not alarm, and a value hovering between 36 and 40 after the alarm has fired does not clear and then alarm again.

alarm.ts · lines 15–27
  // Feed fresh readings only. Never feed a placeholder for missing data.
  step(value: number): "raise" | "clear" | null {
    if (!this.active) {
      this.below = value < this.limit ? this.below + 1 : 0;
      if (this.below < this.delay) return null;
      this.active = true;
      this.below = 0;
      return "raise";
    }
    if (value <= this.limit + this.deadband) return null;
    this.active = false;
    return "clear";
  }
alarm.ts: step alarms after the value stays below the line for the on-delay, and clears once it is past the deadband

The comment above step is the most important part: feed it only values that actually arrived, and never a value in place of a missing slot. If the code feeds 0 for the power cut, the on-delay cannot help, because zero is below the line every minute, and after three minutes it alarms.

Step 3: simulate the same morning in two ways

demo.ts builds the water level from a formula. It falls from 70% until 06:29, hovers around the 40% line from 06:30 to 06:59, refills from 07:00 to 07:39, then falls slowly. The sensor sends no data from 08:00 to 08:40.

demo.ts · lines 14–19
const level = (t: number) =>
  t < 30 ? 70 - 0.8 * t
  : t < 60 ? 38 + (((t * 7) % 9) - 4) * 0.5 // hovering around the 40% limit
  : t < 100 ? 38 + 0.8 * (t - 60)
  : 70 - 0.1 * (t - 100);
const sends = (t: number) => t < POWER_OFF || t >= POWER_ON;
demo.ts: the hypothetical water level and the periods when the sensor sends data

The correct way follows this order every minute: update the last data time and the will time, work out the status, log it when it changes, and feed the alarm only when there is a real value and the device is online.

demo.ts · lines 28–45
  for (let t = 0; t < MINUTES; t++) {
    if (sends(t)) seen.lastData = t;
    if (t === willAt) seen.lastWill = t;
    const now = status(t, seen, STALE, OFFLINE);
    if (was !== null && now !== was) {
      const why =
        now === "online" ? "data again"
        : now === "stale" ? `no data since ${hhmm(seen.lastData!)}`
        : seen.lastWill !== null ? "last will from broker"
        : `no data for over ${OFFLINE} min`;
      log.push(`${hhmm(t)}  status ${now.padEnd(8)}${why}`);
    }
    was = now;
    if (sends(t) && now === "online") {
      const ev = alarm.step(level(t));
      if (ev) log.push(`${hhmm(t)}  alarm  ${ev.padEnd(8)}level ${pct(level(t))}`);
    }
  }
demo.ts: the loop of the correct way

The zero-fill way uses the short loop often seen in real systems: no value means use 0, below 40 alarms at once, and back up to 40 clears.

demo.ts · lines 52–63
// Naive: a missing reading is stored as 0, alarm the moment the value is under 40, no deadband.
let low = false;
const raised: string[] = [];
let zeros = 0;
for (let t = 0; t < MINUTES; t++) {
  const v = sends(t) ? level(t) : 0;
  if (!sends(t)) zeros++;
  if (!low && v < 40) {
    low = true;
    raised.push(hhmm(t));
  } else if (low && v >= 40) low = false;
}
demo.ts: the zero-fill way, with no on-delay and no deadband

Run it and read the result

output.txt
1) Proper handling: limit 40%, deadband 5, delay 3 readings, stale after 3 min, last will
06:35  alarm  raise   level 37.0%
07:09  alarm  clear   level 45.2%
08:03  status stale   no data since 07:59
08:07  status offline last will from broker
08:41  status online  data again

2) Naive handling of the same 180 minutes: missing = 0, alarm when < 40, no delay, no deadband
low-level alarms raised  6 at 06:30 06:33 06:42 06:51 07:00 08:00
minutes shown as 0%      41 (08:00-08:40), the tank really held 64.0%-68.0%

3) What the screen shows during the outage
naive    0.0%  "tank empty"
proper   68.1% from 07:59, greyed out, device offline

4) If the broker never sends the last will
08:03  status stale   no data since 07:59
08:15  status offline no data for over 15 min
08:41  status online  data again
Real output run on 2026-11-23 with node demo.ts (Node 24). All data is hypothetical

Part 1: the correct way alarms once, at 06:35 at 37.0%, after the value has been below the line for three minutes, and clears at 07:09 at 45.2% when it passes the deadband. During the power cut there is no low-level alarm at all, only status changes: stale at 08:03, three minutes after the last value at 07:59; offline at 08:07 when the broker sends the will; and online at 08:41 when data returns.

Part 2: the zero-fill way alarms 6 times. The first five happen while the value hovers around the line. The sixth, at 08:00, is a false alarm from the zero that was filled in. For the 41 minutes the screen showed 0%, the real tank held 64.0% to 68.0%.

Part 3 is what the person watching the screen sees during the power cut. One way says the tank is empty. The other says the last value was 68.1% at 07:59, shown faded, and that the device is offline. The second way sends people to check the right place: the power or the network at the sensor cabinet, not the pump or the tank.

Part 4: without a will, or if the will never arrives, the system can still tell from the age of the data, but later: it becomes offline at 08:15 instead of 08:07. So the will is a shortcut, not the only thing to depend on.

Test suite

The suite has 5 tests: status by data age; a will after the data means offline, and new data after the will means online; a value hovering below the alarm line alarms once; a dip shorter than the on-delay does not alarm; and the alarm clears only above the line plus the deadband.

device-status.test.ts · lines 21–31
test("a value hovering under the limit raises once", () => {
  assert.deepEqual(feed(new LowAlarm(40, 5, 3), [39, 38, 39, 38, 39, 38, 44, 39]), ["raise"]);
});

test("a dip shorter than the delay raises nothing", () => {
  assert.deepEqual(feed(new LowAlarm(40, 5, 3), [39, 38, 41, 39, 38, 41]), []);
});

test("clear only above limit + deadband", () => {
  assert.deepEqual(feed(new LowAlarm(40, 5, 3), [39, 39, 39, 45, 45.1]), ["raise", "clear"]);
});
device-status.test.ts: the three tests that check the alarm

Running node --test device-status.test.ts gave 5 passed, 0 failed on 2026-11-23.

What else to check before real use

  • Store the gap as NULL or as no row at all, never 0, and set the chart to show a gap, not to connect across it or fill with zero.
  • Use a separate status topic. Publish online as retained when connecting, set the will to offline as retained, and publish offline yourself before DISCONNECT on a normal shutdown, because the broker does not send the will in that case.
  • If several devices sit behind one gateway, for example reading Modbus through a gateway, the will only says the gateway dropped. Each device needs its own status from the gateway, for example how many reads in a row failed.
  • Set the stale and offline times from each device's real sending interval. A device that sends every 15 minutes cannot use the same values as one that sends every minute.
  • With MQTT 5, set the Will Delay Interval longer than the short network drops that are normal, so the status does not flicker.
  • Separate the offline-device alarm from the abnormal-value alarm. Send it to whoever fixes power or network problems, and give it its own on-delay.
  • If a gateway sends buffered values late when the network returns (store and forward), those values should go into the history chart but should not feed the alarm logic as if they were current values.
  • Review the number of alarms per day from time to time. An alarm that sounds often but needs no action should have its line adjusted, its on-delay adjusted, or be removed.

Adapting it to your business

Water tanks and pump pits

A low-level alarm often leads to starting a pump or sending someone out. One false alarm costs the vehicle and a technician's trip. Set the alarm line from the time needed to fix the problem. For example, if a technician can arrive within 2 hours, the line must be high enough to leave 2 hours of water plus a margin.

Cold rooms and freezers

Temperature jumps every time a door opens. The on-delay should be longer than a normal door opening but shorter than the time it takes for the goods to start spoiling. A cold-room sensor that has been lost for a long time must be treated as just as urgent as a high temperature, because during that time nobody knows the real temperature.

Power meters and machines

Zero power means the machine has stopped, which is meaningful data. If you fill in 0 when the meter drops out, the report will say the machine stopped when it may have been running, and OEE and electricity cost per unit produced will be wrong as well. The report must be able to tell stopped from unknown.

Common mistakes

  • Letting the chart or database fill 0 in periods with no data
  • Freezing the last value without showing its time and without changing its color
  • Alarming the moment the value crosses the line, with no on-delay and no deadband
  • Relying on the will alone, forgetting that the broker does not send the will when the client disconnects normally
  • Not using retained, so a screen opened later does not know the status until a new message arrives
  • Setting the same offline time for every device, without looking at the real sending interval
  • Sending the offline-device alarm and the abnormal-value alarm to the same person with the same kind of message

Checklist before real use

  1. Cut the power to the sensor or gateway. Check that the screen shows the last value with its time, faded, and changes to offline at the set time, with no 0 appearing.
  2. Unplug the LAN cable or switch off the SIM, and time when the will actually arrives, compared with one and a half times the keep alive.
  3. Do a normal shutdown and check that the status becomes offline, because in this case the device must send it itself.
  4. Open a new screen while the device is offline. It must show the status at once from the retained message.
  5. Feed in a value hovering around the alarm line. Check that it alarms once and clears when it passes the deadband.
  6. Look at the history chart for the dropout period. It must be a gap, not a line down to zero.
  7. Count the alarms per day in the first week, then adjust the line and on-delay together with the people who receive the alarms.

Limits of the example: it is not connected to a real MQTT broker, the time the will arrives is calculated by hand, times are whole minutes, and there is only one kind of alarm, low level, with no severity levels, acknowledgement or temporary silencing, which a real system should have. Every value was chosen to make the effect visible.

References

  1. MQTT Version 3.1.1, OASIS Standard (หัวข้อ 3.1.2.5 Will Flag และ 3.1.2.10 Keep Alive) (accessed 2026-11-23)
  2. MQTT Version 5.0, OASIS Standard (หัวข้อ 3.1.3.2.2 Will Delay Interval) (accessed 2026-11-23)
  3. Hysteresis — Wikipedia (accessed 2026-11-23)
  4. Alarm management — Wikipedia (accessed 2026-11-23)
  5. ISA18, Instrument Signals and Alarms — ISA (accessed 2026-11-23)
  6. Heartbeat (computing) — Wikipedia (accessed 2026-11-23)
  7. Node.js — Test runner (node:test) (accessed 2026-11-23)

Add us on LINE

Scan with the LINE app on your phone

QR code to add LINE @Bankoos

LINE ID: @Bankoos

Open LINE on this computer