Projects / Device heartbeat and offline alerts

Device heartbeat and offline alerts

Intermediate2.5 hGuided buildReviewed

Build it step by step

0 of 8 done
  1. ESP32Pi 4RASPBERR

    Set up the Pi

    Install Raspberry Pi OS and the broker.

  2. ESP32

    Test the broker

    Publish and subscribe from the command line.

  3. ESP32

    Fill in the placeholders

    Add Wi-Fi details and the Pi address.

  4. ESP32

    Flash both ESP32s

    Give each a different DEVICE name.

  5. ESP32

    Run the monitor

    See heartbeats arrive.

  6. ESP32RASPBERR

    Pull one device's power

    Watch the offline message appear.

  7. ESP32

    Freeze a device

    Test the silence alert.

  8. ESP32

    Plug it back in

    See the back-online message.

In short

How do you build a device heartbeat and offline alerts?

Every device sends a heartbeat with uptime and battery, and a server alerts you when one goes quiet. You need ESP32 DevKit V1 × 2, Raspberry Pi 4 Model B (4 GB), SanDisk microSD card 32 GB (A1, Class 10), Raspberry Pi 27 W USB-C power supply and Li-Po battery 3.7 V 1000 mAh × 2. It takes 8 steps and about 150 minutes.

Level
Intermediate
Time
About 150 min
Parts
5

Parts list

Tick what you already own. It saves to My Garage, so “Build with what I have” knows.

Wiring

FromToWhy
Li-po battery (each ESP32)ESP32 board's battery connector, if it has one, otherwise USB powerPower, observe polarity
Raspberry PiSame Wi-Fi network as the ESP32sRuns the MQTT broker and the monitor
Pi power supplyPi USB-CPower
microSD cardPiRaspberry Pi OS

Code

Each ESP32 sends a small message every minute with its uptime, signal strength and free memory. When it connects it also registers a last-will message with the broker: if the connection drops without a clean goodbye, the broker itself publishes offline for that device, which catches crashes and power cuts quickly. The Python monitor on the Pi also raises an alert if no heartbeat arrives for five minutes, which catches a device that is connected but stuck. Replace the print statements with an email or chat message to be told away from home. Name every device uniquely, add a password to the broker and keep it on your own network, and use placeholders for the Wi-Fi and broker address. Battery voltage needs a divider on an ADC pin; add it if your board has no gauge. Arduino IDE with the ESP32 boards package, board "ESP32 Dev Module".

Runs on a virtual ESP32 Dev Module in your browser, with sliders for the sensors. Happy with it? Verify and upload to your real board from the same page (Chrome or Edge on a computer).

// ESP32 side. Library: PubSubClient. Sends a heartbeat each minute; the broker publishes "offline" if it vanishes.
#include <WiFi.h>
#include <PubSubClient.h>

const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD";
const char* MQTT_HOST = "YOUR_PI_ADDRESS";
const char* DEVICE = "node1";                 // give each device its own name

WiFiClient net;
PubSubClient mqtt(net);
String statusTopic, hbTopic;
unsigned long last = 0;

void connectMqtt() {
  while (!mqtt.connected()) {
    // Last will: if the connection drops without a goodbye the broker sets status to "offline"
    if (mqtt.connect(DEVICE, nullptr, nullptr, statusTopic.c_str(), 1, true, "offline")) {
      mqtt.publish(statusTopic.c_str(), "online", true);
    } else delay(2000);
  }
}

void setup() {
  statusTopic = String("devices/") + DEVICE + "/status";
  hbTopic = String("devices/") + DEVICE + "/heartbeat";
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED) delay(300);
  mqtt.setServer(MQTT_HOST, 1883);
}

void loop() {
  if (!mqtt.connected()) connectMqtt();
  mqtt.loop();
  if (millis() - last > 60000) {
    last = millis();
    char m[96];
    snprintf(m, sizeof(m), "{\"uptime_s\":%lu,\"rssi\":%d,\"heap\":%u}", millis() / 1000, WiFi.RSSI(), ESP.getFreeHeap());
    mqtt.publish(hbTopic.c_str(), m);
  }
}

/* Raspberry Pi side. Install the broker and library:
     sudo apt install mosquitto mosquitto-clients python3-paho-mqtt
   Set a password for the broker before using it for anything beyond a trial (see the mosquitto docs).
   Save as monitor.py and run it under systemd or in a terminal.

import json, time
import paho.mqtt.client as mqtt

SILENCE_LIMIT = 300            # alert after 5 minutes without a heartbeat
last_seen = {}
alerted = set()

def on_message(client, userdata, msg):
    parts = msg.topic.split("/")
    name = parts[1]
    if parts[2] == "heartbeat":
        last_seen[name] = time.time()
        if name in alerted:
            alerted.discard(name)
            print(name, "is back online")
    elif parts[2] == "status" and msg.payload.decode() == "offline":
        print("ALERT:", name, "reported offline")

c = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
c.on_message = on_message
c.connect("localhost", 1883)
c.subscribe("devices/+/heartbeat")
c.subscribe("devices/+/status")
c.loop_start()

while True:
    now = time.time()
    for name, t in last_seen.items():
        if now - t > SILENCE_LIMIT and name not in alerted:
            alerted.add(name)
            print("ALERT:", name, "silent for", int(now - t), "seconds")   # replace with an email or chat message
    time.sleep(10)
*/

Test checklist

What you should see at each check. If a reading is far off, stop and use the troubleshooting list.

CheckExpected
Both devices runningHeartbeat each minute
Power removedOffline status almost at once
Device stuck but connectedSilence alert after 5 minutes
Power restoredBack-online message

If it does not work

No heartbeats

Check the broker address and port.

Offline never reported

Check the last will uses a retained message.

Duplicate names

Give each device a unique name.

Monitor crashes

Check the paho-mqtt version and the callback style.

Still stuck? Find the fault step by step with your multimeter →

Ask Lark AI

Common questions

What parts do I need for the device heartbeat and offline alerts?

ESP32 DevKit V1 × 2, Raspberry Pi 4 Model B (4 GB), SanDisk microSD card 32 GB (A1, Class 10), Raspberry Pi 27 W USB-C power supply and Li-Po battery 3.7 V 1000 mAh × 2.

How long does the device heartbeat and offline alerts take to build?

About 150 minutes for a intermediate maker, in 8 steps.

How do I know the device heartbeat and offline alerts works?

Both devices running: Heartbeat each minute. Power removed: Offline status almost at once. Device stuck but connected: Silence alert after 5 minutes.

No heartbeats: what should I check?

Check the broker address and port.

Offline never reported: what should I check?

Check the last will uses a retained message.

Duplicate names: what should I check?

Give each device a unique name.

Monitor crashes: what should I check?

Check the paho-mqtt version and the callback style.