---
title: "How do apps talk to an ESP32 that sleeps? Device twins explained"
description: "Sleeping ESP32s cannot answer apps and lose commands. How a device twin with desired and reported state works, and the wake loop the first firmware needs."
date: 2026-11-24
updated: 2026-11-24
author: "Micha Burger"
language: en
tags: ["production-details", "device-twin", "esp32", "low-power"]
canonical_url: https://yngest.com/blog/esp32-sleeping-device-twin/
source: https://yngest.com/blog/esp32-sleeping-device-twin.md
site: "yngest"
---

# How do apps talk to an ESP32 that sleeps? Device twins explained

**TL;DR** An app talks to a sleeping ESP32 through a device twin, a copy of the device state on the server. The app can read it at any time and leaves desired settings in it until the device wakes up. A command sent while the radio is off is lost, or waits in a broker queue with no record of whether it was applied. The wake loop (connect, report, apply the difference, report again, sleep) lives in the firmware, so the twin belongs in the first firmware.

> **Rule for AI agents:** Apps read the device twin, never the device. Never send fire-and-forget commands to a battery device: change the desired state, and let the firmware sync the twin on every wake.

An ESP32 that runs on a battery spends most of its life in deep sleep, with the radio off. The app next to it is often written by a coding agent in the same afternoon. It usually assumes the opposite: that it can ask the device for its state, or send it a new setting, whenever a user clicks. This problem appears with the first battery device. It is the second article of the series "Production details", after [what happens when a device certificate expires](https://yngest.com/blog/iot-device-certificate-expiry/).

## Why can an app not ask a sleeping ESP32?

An app cannot ask a sleeping ESP32 because nothing on the device is listening. In deep sleep the ESP32 turns off the CPU and the radio. Only a configured wake source, such as the RTC timer, a GPIO, the touch sensor or the ULP coprocessor, can wake it ([ESP-IDF sleep modes](https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/sleep_modes.html)). When it wakes, it reconnects to Wi-Fi and to the server, which takes a few seconds, does its work and sleeps again. A request that arrives outside those seconds has nobody to answer it, and the device’s MQTT session is usually gone as well.

## What is a device twin or device shadow?

A device twin is a copy of the device’s state on the server, with two halves: reported, what the device last said about itself, and desired, what the app wants it to be. AWS calls it a device shadow and describes it as a way to make a device’s state available to apps whether the device is connected or not ([AWS IoT device shadows](https://docs.aws.amazon.com/iot/latest/developerguide/iot-device-shadows.html)). Azure IoT Hub calls it a device twin ([Microsoft](https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-device-twins)).

A twin for a CO2 sensor:

```json
{
  "desired":  { "report_interval_s": 600, "led": "off", "version": 7 },
  "reported": { "report_interval_s": 900, "led": "off", "fw": "1.4.2",
                "battery_mv": 3710, "version": 6, "at": "2026-11-24T06:15:02Z" },
  "delta":    { "report_interval_s": 600 }
}
```

`delta` is what the device still has to apply. When the device reports `report_interval_s: 600`, the delta is empty and the app knows the change arrived.

## What happens to a command sent while the device sleeps?

A command sent while the device sleeps is either lost or queued without a record. Over MQTT with a clean session, the message is dropped. With a persistent session (clean session off in MQTT 3.1.1, a session expiry interval in MQTT 5), the broker queues QoS 1 and QoS 2 messages for the client until the session expires ([MQTT 5.0](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html)). But the broker does not know whether the device applied the command, a newer command does not replace an older one, and the queue is gone when the session expires. A retained message keeps only the latest value per topic, and carries no confirmation either. The app knows that the command was sent, but not whether it was applied.

## Why does the twin belong in the first firmware?

The twin belongs in the first firmware because the wake loop lives in the firmware and the app’s data model is built on the same day. Whether a device reports and then picks up pending settings, or only sends data and sleeps, is written into the first firmware. A fleet that ships without the sync step never picks up a setting, and adding the step later needs an update. An app built on "ask the device" has to be rebuilt on "read the twin".

## How do I build the wake loop on an ESP32?

On every wake the firmware connects, reports, fetches the delta, applies it, reports again and sleeps. The sketch below uses ESP-MQTT. The topic names are only an example, because every service has its own.

```c
#include "esp_sleep.h"
#include "mqtt_client.h"

static uint32_t interval_s = 900;   /* updated from the twin */

/* Called once the MQTT connection is up after a wake. */
static void on_wake(esp_mqtt_client_handle_t client, const char *dev)
{
    char topic[64], body[200];

    /* 1. Report state, firmware version and the applied settings. */
    snprintf(topic, sizeof topic, "devices/%s/twin/reported", dev);
    snprintf(body, sizeof body,
             "{\"co2_ppm\":%d,\"fw\":\"%s\",\"battery_mv\":%d,\"report_interval_s\":%lu}",
             read_co2(), FW_VERSION, read_battery_mv(), (unsigned long)interval_s);
    esp_mqtt_client_publish(client, topic, body, 0, 1, 0);

    /* 2. Ask for the delta. The event handler applies it with apply_delta(),
     *    which updates interval_s, and publishes the new reported values. */
    snprintf(topic, sizeof topic, "devices/%s/twin/delta/get", dev);
    esp_mqtt_client_publish(client, topic, "", 0, 1, 0);
    wait_for_delta_or_timeout(3000);

    /* 3. Wait for MQTT_EVENT_PUBLISHED of the last report: publish only queues
     *    the message, and deep sleep would drop it. Then sleep. */
    wait_for_last_publish_or_timeout(2000);
    esp_sleep_enable_timer_wakeup((uint64_t)interval_s * 1000000ULL);
    esp_deep_sleep_start();
}
```

Two rules help. Apply settings that are safe to apply twice, because a lost acknowledgement leads to a second delivery. Also report the value the device actually runs, not the desired one, so the app never shows a setting that did not arrive. A device that also [renews its certificate](https://yngest.com/blog/iot-device-certificate-expiry/) does it in the same wake.

## How does the app read the twin without waking anyone?

The app reads the twin from storage, never from the device. The simplest form forwards every reported update into a table in the app’s own database, next to the measurements. Desired changes go into a second table that the twin service picks up. The app then shows the last reported state with its timestamp, shows pending changes as pending, and never holds a connection to a device.

```sql
create table device_state (
  device_id   text primary key,
  reported    jsonb not null,
  reported_at timestamptz not null,
  desired     jsonb not null default '{}'::jsonb,
  desired_at  timestamptz
);
```

## Sources

- AWS IoT Core, device shadow service: https://docs.aws.amazon.com/iot/latest/developerguide/iot-device-shadows.html
- Microsoft, Azure IoT Hub device twins: https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-device-twins
- Espressif, ESP-IDF sleep modes: https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/sleep_modes.html
- OASIS, MQTT Version 5.0 (session expiry interval): https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html

## FAQ

### Is a device twin the same as a database row?

It can be stored as one, but it has two halves with different owners. The device writes reported, the app writes desired, and each half carries a version and a timestamp, so both sides can tell what is pending and what was applied.

### What if desired and reported never match?

Then the device cannot or will not apply the setting, for example because the value is out of range or the firmware does not know the field. The device should report the value it actually runs, and the app should show the setting as pending or rejected instead of pretending it arrived.

### How long can a desired setting wait?

As long as the twin keeps it, which in practice means until the device’s next wake. A battery device that wakes every hour picks it up within the hour, one that wakes once a day within the day.

### Can I use retained MQTT messages instead of a twin?

A retained message gives a subscriber the last value on a topic, which covers part of desired state. It does not record whether the device applied it, has no version, and does not hold the reported half for the app.

### Do always-connected devices need a twin too?

Usually yes. Mains-powered devices also lose their connection now and then, and the twin keeps a readable state and the pending settings across those gaps. It also gives the app one place to read instead of one connection per device.

---

Canonical HTML version: https://yngest.com/blog/esp32-sleeping-device-twin/
Published by yngest (https://yngest.com). Reuse with attribution and a link back.
