ProjekinAja. Embedded Systems Stage 4 · Power & Wireless Lesson 4.7
● Stage 4 · Lesson 4.7

Wi-Fi, MQTT, and When Not to Use Wi-Fi

Wi-Fi is the fastest way to send a byte and the slowest way to save a microamp.

⏱ ~25 min read 🌐 Networking 📐 Worked numbers

🎯 By the end you'll understand

Where the energy in a Wi-Fi transaction actually goes — scan, authenticate, associate, DHCP, TLS handshake, publish — measured in millicoulombs rather than milliamps, and which of those phases you can delete. How MQTT works, what each quality-of-service level costs in round trips, and why QoS 2 is almost never the answer. What TLS costs a microcontroller in time, RAM, and flash, and the two shortcuts people take that quietly remove all its value. The crossover calculation that decides whether to stay associated or reconnect each time. And the architectural conclusion that falls out of the arithmetic: battery devices speak BLE, powered gateways speak Wi-Fi, and that is not a preference.

KEY INSIGHTThe transmission is free; the joining is not

Fourteen bytes. Nine hundred nanoseconds of actual data at 11 Mbit/s. To deliver them the device scanned thirteen channels, authenticated, associated, asked for an address, negotiated a TLS session, connected to a broker, published, and disconnected — three seconds with the radio on. The payload was 0.0000003 of the energy.

Wi-Fi is not expensive because it is fast; it is expensive because it is a relationship. Before a station can send anything it has to find an access point, prove it is allowed on the network, be given a place on it, obtain an address, and then — if the data is going anywhere over the public internet — establish a cryptographic session with a server. Every one of those steps is a round trip or several, each round trip is milliseconds of waiting with the receiver powered, and the receiver costs about as much as the transmitter. The bytes you actually care about are lost in the noise of getting permission to send them.

🔑 Hold onto this

Beacon's whole BLE report — boot, sensors, three advertising packets — costs 1.8 mC. The same report over Wi-Fi with a cold association, TLS, and MQTT costs somewhere around 260 mC: a factor of roughly 147. Applying every legitimate optimisation (cached access point, static IP, resumed TLS session, QoS 0) gets that down to about 57 mC, which is still a factor of 31. No amount of tuning closes a two-orders-of-magnitude gap. When the arithmetic says that, the answer is not a better implementation; it is a different architecture. That architecture is the gateway.

HOW IT WORKSWhat an association actually costs, phase by phase

Here is a Wi-Fi report broken into the operations a station performs, with each priced as a charge. Treat the individual figures as illustrative — they are in the class of what an ESP32-family part draws, and the ratios between them are the part that matters — but do measure your own, because a slow access point or a distant broker can double any of them.

PhaseRoughlyChargeCan you delete it?
Radio and PHY bring-up150 ms @ 80 mA12 mCNo. This is the price of turning the radio on.
Scan — active, all 13 channels1500 ms @ 100 mA150 mCYes. Cache the BSSID and channel and probe only that one: ~12 mC.
Authenticate + associate + WPA2 handshake80 ms @ 100 mA8 mCNo, though a good AP makes it quicker.
DHCP DISCOVER / OFFER / REQUEST / ACK300 ms @ 60 mA18 mCYes. A static address removes it entirely.
TLS handshake, full900 ms @ 70 mA63 mCPartly. Session resumption cuts it to roughly 14 mC.
MQTT CONNECT, PUBLISH (QoS 1), DISCONNECT200 ms @ 60 mA12 mCA little: QoS 0 removes the PUBACK round trip.
Boot from deep sleep + read the sensors38 ms1.5 mCNo — this is the same wake cost BLE pays (Lesson 4.3).
Cold total≈ 3.2 s of radio≈ 264 mC
Fully optimised total≈ 0.7 s of radio≈ 57 mC

Two things jump out of that table. The scan is the single largest item, and it is entirely avoidable: an active scan probes every channel and waits for responses, and on a device that connects to the same access point in the same room every time, that is 150 mC spent rediscovering a fact you already knew. Store the BSSID and channel in NVS after the first successful connection and connect directly. The second is that TLS is the second largest item and it is not avoidable in the way people wish it were — you can resume a session, you can choose cheaper ciphersuites, but you cannot skip it and still claim the data is protected.

📖 Staying associated: the other architecture, and where it wins

Instead of reconnecting every report, a station can stay associated and let the Wi-Fi power-save mechanism handle the idle time. The station tells the access point it is in power save; the AP buffers traffic for it and signals buffered data in its beacons. The station sleeps between beacons and wakes for the DTIM beacon — the one that flags buffered broadcast and multicast traffic — at whatever interval the AP is configured for. The result is an average current in the region of one milliamp for the whole radio, plus whatever your traffic costs.

That gives you a clean crossover. Reconnecting costs C millicoulombs per report and nothing in between; staying associated costs about 1 mA continuously and a couple of millicoulombs per publish. Setting them equal, the break-even period is roughly C − 2.6 seconds: about 260 s for a cold reconnect and about 54 s for a fully optimised one. Report more often than that and you should stay associated; less often and you should reconnect. Both are still catastrophic against a six-month requirement, which is the point of the next section — but if you are building a mains-adjacent device that must use Wi-Fi, this is the calculation that decides the architecture.

HOW IT WORKSMQTT: topics, quality of service, and the will

MQTT is a publish/subscribe protocol designed for exactly this job: many small devices, unreliable links, a central broker. A client connects to a broker and publishes messages to a topic — a slash-separated string such as beacon/a3f1/telemetry. Other clients subscribe to topics, optionally with wildcards: + matches one level, # matches the rest. Publishers and subscribers never know about each other, which is the whole appeal.

QoSGuaranteeRound tripsUse it when
0 — at most onceFire and forget. The broker may never receive it and nobody finds out.0High-rate telemetry where the next sample is along shortly and loss is visible another way.
1 — at least oncePUBLISH then PUBACK. Delivered, possibly more than once.1The default correct answer for telemetry. Duplicates are cheap to handle if your payload carries a sequence number.
2 — exactly oncePUBLISH, PUBREC, PUBREL, PUBCOMP.2 (four messages)Almost never on a battery device. Four messages and broker-side state to remove a duplicate that a sequence number would have removed for free.

Two features are worth knowing because they solve problems people otherwise solve badly. A retained message is stored by the broker and delivered immediately to any new subscriber, so a dashboard that starts up sees the last known state of every tag without waiting for the next report. And the Last Will and Testament is a message the client registers at connect time and the broker publishes if the client disappears without a clean disconnect — which is how a fleet dashboard learns that a gateway has died rather than that all its tags simultaneously went quiet.

The keepalive interval is the third thing to get right. The client promises to send something at least that often, and sends a PINGREQ if it has nothing else to say. On a mains-powered gateway a 60-second keepalive is fine. On a battery device that stays associated, every PINGREQ is a wake, and the keepalive quietly becomes your dominant traffic — another reason a battery device should not be holding an MQTT session open.

CORE CONCEPTTLS on a microcontroller: time, RAM, and two bad shortcuts

Sending telemetry unencrypted across a network you do not control is not an option worth discussing, so the real question is what TLS costs. Three resources.

1

Time, which is energy

A full handshake is two round trips before any application data flows, plus asymmetric cryptography at each end. The ESP32-C3 has hardware acceleration for the symmetric and hash primitives and for the big-integer arithmetic behind RSA and elliptic-curve operations, so the maths is not usually the bottleneck — the network round trips are. Which means the handshake cost depends on how far away and how loaded your broker is, and the number you measure on a laptop-hosted broker on the same LAN is not the number you will get in the field.

2

RAM, which is the hard limit

An mbedTLS session with default settings allocates input and output buffers sized for the maximum TLS record — 16 KB each — and that, plus the session state and certificate parsing, puts a single connection in the tens of kilobytes of heap. On a part with a few hundred kilobytes of SRAM that is survivable but not free, and it is the reason a device that runs fine on the bench runs out of memory when you add a second feature. The lever is CONFIG_MBEDTLS_SSL_MAX_CONTENT_LEN, which shrinks those buffers, and the RFC 6066 maximum-fragment-length extension, which lets the client ask the server to keep records small. Both require the server to cooperate; shrink the buffer without the negotiation and you get a connection that works with one broker and fails with another.

3

Flash, for the trust anchors

You need at least the CA certificate that signs your broker, embedded in the image. Shipping a full browser-style root bundle is a hundred kilobytes or more and is almost always wrong for an embedded device that talks to exactly one server: pin the single CA you actually use, or the server's own certificate. That is smaller, faster to parse, and a materially stronger security posture — but it does mean an OTA is required when that certificate is rotated, which belongs in your operational plan rather than as a surprise.

✗ The two shortcuts that delete TLS while appearing to keep it

Disabling certificate verification. It appears as one flag during debugging, it makes the connection work immediately, and it converts TLS from "a private channel to a server I have authenticated" into "a private channel to whoever answered". An attacker on the path presents any certificate and reads and rewrites everything. It is not a weakened protection; it is no protection with encryption overhead. If it goes in during bring-up, it must come out with a test that fails when it comes back.

Having no clock. Certificate validity dates cannot be checked without knowing the time, and a device fresh out of deep sleep does not know the time. The common non-solution is to skip expiry checking, which means a revoked or long-expired certificate is accepted forever. The real answer is to get the time — SNTP after association, before the TLS handshake, at the cost of one more round trip — and to accept that a device with no network and no real-time clock genuinely cannot fully validate a certificate chain, and to say so in the threat model rather than pretending otherwise.

SEE ITRadio cost comparison: the same fourteen bytes, four ways

Pick a transport, apply the optimisations, and set the report period. The upper chart prices each phase; the lower one puts all four transports on the same logarithmic current axis with the six-month line marked. That line sits at 38.0 µA — which is exactly where Beacon sits, because the canon's budget was built to land on the requirement rather than beside it. Try to move any Wi-Fi option to the left of it.

⚙ Interactive · Radio cost comparison

Phase charges are illustrative and in the class of an ESP32-family radio; the BLE advertising column is pinned to the canon's measured 1.8 mC window and 8 µA sleep floor. The six-month threshold is 1 000 000 µAh ÷ (6 × 4383 h) = 38.0 µA. Deterministic; no randomness.

BLE advertising burst
none
60 s
charge per report, by phase (mC) average current at this report period — log scale 10 µA100 µA1 mA10 mA 38 µA = six months, derated BLE adv BLE conn Wi-Fi reconnect Wi-Fi associated
Charge per report
—
Average current
—
Life on paper
—
Derated life vs R1
—
Versus BLE advertising
—
Stay-associated crossover
—

—

—

Three things to do with it. One: select Wi-Fi with reconnect and no optimisations, at Beacon's 60-second period. Nine or ten days on paper, under two derated — against a requirement of six months. Two: turn on all four optimisations. The charge per report falls by nearly 80 %, which is a genuinely excellent piece of engineering, and the derated life goes from under two days to about a week. Still twenty-five times short of the 38 µA the requirement allows. This is the most useful thing the widget teaches: a good optimisation on a bad architecture is still a bad architecture. Three: drag the period out to an hour and watch the Wi-Fi options finally approach the line, then notice what you gave up — a device that reports hourly is not a device that meets R4's two-second motion response. The requirements are coupled, and Wi-Fi loses on both at once.

IN PRACTICEThe gateway pattern, and its honest costs

The arithmetic above forces one conclusion: put the expensive protocol where the power is. Battery devices broadcast in the cheapest way available; a mains-powered gateway listens, translates, and takes on the association, the TLS, and the broker session on their behalf. This is not a compromise, it is the standard architecture for the entire sensor-tag industry, and it exists because the numbers leave no alternative.

battery · 38 µA mains powered infrastructure Beacon 01 Beacon 02 …up to 25 BLE adv 1.8 mC each Raspberry Pi Zero 2 W scan → decode → JSON beacon/<id> Wi-Fi + TLS MQTT broker CSV + status page All the expensive protocol work happens on the one device that is plugged into a wall. Cost of the pattern: coverage is now limited to gateway range, and a gateway outage loses data.
Beacon's gateway per the canon: a Raspberry Pi Zero 2 W scanning BLE and publishing JSON to beacon/<id>, with a forty-line Python subscriber writing CSV and serving a one-page status table. It exists so the pilot has data, and it is deliberately not the course's subject.

The pattern is not free, and a design review should hear the costs out loud.

1

You now own two products

The gateway needs its own firmware or software, its own updates, its own monitoring, and its own failure modes. For a 25-unit pilot that is a Raspberry Pi and a Python script; for a hundred sites it is a fleet-management problem you did not have before.

2

Coverage is now gateway range, not internet range

A Wi-Fi tag works anywhere there is Wi-Fi. A BLE tag works within the link budget of Lesson 4.5 — around ten metres through a wall. That converts a wireless problem into a site-survey problem, and it is why R2 exists as a requirement at all.

3

An outage loses data silently

Beacon does not buffer. If the gateway is down, the reports are shouted into an empty room and gone. The mitigation Beacon does have is the sequence number in the payload: the dashboard can see the gaps and say how many reports it missed, which turns silent loss into visible loss. Adding real buffering means adding flash writes, a queue, and a catch-up transmission mode — all of which cost energy and complexity, and none of which are worth it until a customer says the gaps matter.

One more thing lives at this boundary: credentials. Something has to tell a device the Wi-Fi network's name and password. The options are a provisioning flow — ESP-IDF ships a provisioning manager that runs over SoftAP or BLE, with an encrypted session so the password is not broadcast in clear — or factory programming, where each unit is flashed with its credentials at manufacture. For 25 pilot units, factory programming is simpler and perfectly honest. The thing to avoid is the third option, which is hard-coding one SSID and password into the firmware image: it means every unit in the fleet shares one secret, anyone with a unit and a flash reader has it, and rotating it requires an OTA to all 25. Beacon stores credentials in NVS, which sets up the question Lesson 4.9 has to answer about what protects NVS.

BEACONBeacon: Wi-Fi, once, on purpose

Beacon has a Wi-Fi radio and uses it for exactly one thing: opt-in over-the-air updates, entered by holding the button at wake. Everything else goes out as a BLE advertisement. That is the whole of the architecture, and the numbers behind it are now concrete.

UseFrequencyChargeShare of a 1000 mAh cell
BLE reportEvery 60 s1.8 mC— (it is the 38 µA average)
Wi-Fi association for OTARarely, on demand≈ 264 mC0.007 %
Downloading a ~1 MB image over TLSSame event≈ 360 mC0.010 %
One complete OTA≈ 0.62 C ≈ 0.17 mAh0.017 %

Read those two rows together, because they are the whole lesson in one comparison. The same Wi-Fi association that is catastrophic at once a minute is negligible as a rare event — an entire firmware update costs less than two hundredths of one percent of the cell, roughly the energy of 340 ordinary BLE reports. Wi-Fi is not expensive. Wi-Fi per report is expensive. The design rule that falls out is not "avoid Wi-Fi", it is "never put a network association inside a periodic loop on a battery".

Two consequences for the rest of the project. The OTA path must be explicitly entered and cannot be triggered by a passing packet, because an attacker who can make 25 tags associate to Wi-Fi has an easy battery-drain attack — holding the button is a physical gate, which is the cheapest possible authentication and, for this threat, a proportionate one. And the download itself must be interruptible and resumable in the sense that a failure leaves the running firmware intact, which is what the two-partition scheme in Lesson 4.9 provides.

WEAKNESSWhere this bites

✗ "We'll add Wi-Fi later"

Adding Wi-Fi to a battery product is not a feature, it is a change of architecture, and it arrives late because it looks like a feature. The tell is a requirements document with a battery life in months and a connectivity line that says "Wi-Fi" without a report period next to it. Do the multiplication at requirements time: charge per report times reports per day times days. If the answer exceeds the cell, the product is either mains-powered, gateway-based, or reporting far less often than anyone has admitted — and finding that out in Stage 1 costs an afternoon, while finding it out in Stage 5 costs a board spin.

✗ Scanning all thirteen channels on every wake

The default connect path scans for the network every time, and on a device that wakes into the same room next to the same access point that is the largest single item in the energy budget — bigger than the TLS handshake, bigger than everything else combined. It survives because on a bench-powered prototype nobody notices an extra 1.5 seconds. Cache the BSSID and channel in NVS after a successful connection, connect directly, and fall back to a full scan only when the direct connect fails. And measure it: this is the optimisation with the largest ratio of benefit to effort in the whole lesson.

✗ Reaching for QoS 2, and for a keepalive you cannot afford

QoS 2 exists for messages where a duplicate would be genuinely harmful — a payment, a command to open something. Telemetry with a sequence number in it is not that: a duplicate is detected and dropped by the receiver at zero cost, and QoS 1 delivers it in one round trip instead of two. Choosing QoS 2 for sensor data doubles the round trips and adds broker-side state for a problem you have already solved in the payload. In the same family: a 30-second MQTT keepalive on a battery device that stays associated makes PINGREQ your dominant traffic, so the message you send twice an hour is dwarfed by the pings that prove you are still there.

KEY INSIGHTHow this connects

The gateway pattern is not a preference you can be talked out of. It is what a factor of a hundred looks like when you write it down.

GLOSSARYKey terms introduced

Association
The sequence a Wi-Fi station performs to join a network: scan, authenticate, associate, complete the security handshake, obtain an address. Seconds of radio-on time, and the dominant energy cost of a Wi-Fi report.
BSSID caching
Storing the access point's MAC address and channel after a successful connection so subsequent connects skip the scan. The single largest saving available on a reconnecting Wi-Fi device.
DTIM
Delivery Traffic Indication Map — the beacon that signals buffered traffic to stations in power save. Its interval sets how often an associated station must wake, and therefore the floor current of the stay-associated architecture.
MQTT QoS
Quality of service: 0 is fire-and-forget, 1 adds a PUBACK for at-least-once delivery, 2 uses four messages for exactly-once. For telemetry with a sequence number, 1 is almost always the right answer.
Retained message
A message the broker stores per topic and delivers immediately to new subscribers, so a dashboard sees last-known state without waiting for the next report.
Last Will and Testament
A message registered at connect time that the broker publishes if the client disappears without disconnecting cleanly. How a fleet learns that a gateway died.
TLS session resumption
Re-establishing a previously negotiated session without repeating the full handshake, cutting the most expensive network phase after the scan by roughly three quarters.
Gateway pattern
Battery devices speak the cheapest protocol available; a mains-powered device does the protocol translation and carries the expensive network relationship. The architectural consequence of a hundredfold energy ratio.

ACTIVE RECALLCheck your understanding

Answer in your own words first, then reveal.

1A product manager asks why the tag cannot just have Wi-Fi, "since the ESP32-C3 already has it". Answer with arithmetic rather than opinion.›

The radio is there; the energy is not. A BLE report costs about 1.8 mC — boot, sensors, three advertising packets. The same report over Wi-Fi with a cold association, a TLS handshake, and an MQTT publish costs roughly 264 mC, because the payload is irrelevant next to the cost of joining the network: 150 mC to scan, 63 mC to handshake, 18 mC for DHCP, and so on.

At one report a minute, 264 mC per report is an average of about 4.4 mA. On a 1000 mAh cell that is around 226 hours — nine days on paper, under two days after the derating we apply to every other number in this project. The requirement is six months. Even applying every optimisation available, the figure lands near 57 mC per report, about a week derated, still thirty times short. That gap is not an implementation problem, so the tag broadcasts BLE and a plugged-in gateway does the Wi-Fi.

2You must build a Wi-Fi sensor that reports every 20 seconds from a wall socket-adjacent position. Should it reconnect each time or stay associated? Show the crossover.›

Compare the two average currents. Reconnecting costs C millicoulombs per report and essentially nothing in between, so its average is C/T milliamps with T in seconds. Staying associated costs roughly 1 mA continuously for the DTIM listen, plus about 2.6 mC per publish over the existing session, so its average is 1 + 2.6/T milliamps.

Setting them equal gives T = C − 2.6. With a cold reconnect at C ≈ 264 mC the crossover is about 260 seconds; with a fully optimised reconnect at C ≈ 57 mC it is about 54 seconds. A 20-second period is well below both, so stay associated: at 20 s a cold reconnect averages 13 mA while staying associated averages about 1.1 mA.

The general shape: frequent reporting favours staying associated because the join cost is amortised badly; infrequent reporting favours reconnecting because the idle floor dominates. And note that the crossover moves with your optimisations — improving the reconnect path pushes the crossover to shorter periods, which can flip the correct architecture.

3Beacon's OTA uses the same Wi-Fi association that this lesson calls catastrophic. Reconcile that.›

The association is expensive per event and irrelevant per lifetime, and which of those matters depends entirely on how often it happens. One association plus a one-megabyte image download is about 0.62 coulombs, or 0.17 mAh — roughly 0.017 % of a 1000 mAh cell, about the same as 340 ordinary BLE reports — not quite six hours of ordinary reporting, spent once. A device can afford dozens of firmware updates over its life without measurably shortening it.

The same 264 mC inside a once-a-minute loop is 4.4 mA of average current and kills the product in days. So the rule is not "Wi-Fi is expensive" — it is "never put a network association inside a periodic loop on a battery". Rare, deliberate, user-initiated network use is fine. Scheduled network use is the thing to design out.

4Name the two shortcuts that make a TLS connection appear to work while removing its protection, and say what the correct handling of each is.›

Disabling certificate verification. Encryption without authentication protects the channel to whoever happened to answer, which is exactly what an attacker on the path wants. The correct handling is to embed the specific CA that signs your broker — or pin the server certificate itself — rather than shipping a browser-sized root bundle, and to have a test in the build that fails if verification is ever turned off again. Accept the operational consequence: rotating that certificate requires an OTA, so put it in the plan.

Skipping expiry checking because the device has no clock. A device fresh from deep sleep does not know the date, so validity dates cannot be checked, and the usual workaround silently accepts certificates that expired years ago. The correct handling is to fetch the time over SNTP after associating and before the handshake, at the cost of one extra round trip. If the product genuinely cannot get a trusted time — no network before TLS, no real-time clock — then say so explicitly in the threat model and choose a mitigation such as certificate pinning, which does not depend on dates, rather than pretending the check happened.

Next: a radio that measures distance, and the multipath that makes it lie →