This chapter covers two web communication protocols for IoT: HTTP REST APIs provide request/response access to sensor data using standard methods (GET for reading, POST for control) with JSON payloads and proper status codes, ideal for on-demand queries and web integration. WebSocket provides persistent bidirectional connections with 95% bandwidth reduction compared to HTTP polling (94 KB vs 1.87 MB for 1 hour of 1-second updates), ideal for real-time dashboards and low-latency control (<5 ms vs 50-100 ms). Choose HTTP for infrequent updates and WebSocket for continuous streaming; MQTT for pub/sub patterns.
Sensor Squad: HTTP vs WebSocket
Sammy the Sensor had two ways to share his readings, and each worked differently!
“HTTP REST is like a restaurant menu,” explained Max the Microcontroller. “The customer (browser) asks ‘What is the temperature?’ and I answer ‘23.5 degrees.’ Each question is separate – the customer has to ask again to get an update. I speak in JSON, which is like a universal language every computer understands: {\"temperature\": 23.5}.”
“WebSocket is like a phone call,” said Lila the LED. “Once you dial in, the line stays OPEN. I can push updates to you every second without you asking! The connection starts as HTTP (like dialing the number), then UPGRADES to WebSocket (like picking up the phone). After that, each message is only 6 bytes of overhead instead of 500 bytes!”
Bella the Battery did the math: “In one hour of readings every second, HTTP uses 1.87 MB but WebSocket uses only 94 KB – that is a 95% bandwidth saving! For battery devices, less data means less radio time means longer battery life!”
“Use HTTP when someone occasionally checks on me,” said Sammy. “Use WebSocket when they want a LIVE dashboard watching me in real-time!”
Putting Numbers to It
HTTP vs WebSocket bandwidth comparison:
For 1 hour of sensor readings at 1-second intervals (3,600 transmissions):
HTTP polling (request/response each second):
\[\text{HTTP overhead per cycle} = \text{Request headers} + \text{Response headers}\]
WebSocket saves 4% total power in this scenario (modest because idle dominates). Greater savings occur at higher data rates.
46.1 Learning Objectives
By the end of this chapter, you will be able to:
Construct HTTP REST APIs: Implement ESP32 web servers with RESTful endpoints for sensor data and device control using proper status codes and JSON payloads
Develop HTTP client workflows: Send HTTP GET/POST requests to cloud services and local servers with appropriate error handling
Implement WebSocket communication: Establish persistent bidirectional connections for real-time sensor data streaming
Evaluate protocol trade-offs: Justify the selection of HTTP, WebSocket, or MQTT for a given IoT scenario based on latency, bandwidth, and power constraints
Calculate network capacity: Estimate Wi-Fi throughput, device counts, and bandwidth savings when comparing HTTP polling against WebSocket streaming
For Beginners: HTTP vs WebSocket for IoT
What is this chapter? Web communication protocols for IoT - when to use HTTP REST APIs vs real-time WebSocket streaming.
HTTP REST (Request/Response): - Best for: On-demand queries, infrequent updates, web integration - Pattern: Client requests, server responds - Overhead: High (headers each request)
WebSocket (Persistent Connection): - Best for: Real-time dashboards, live sensor streaming, low-latency control - Pattern: Bidirectional frames - Overhead: Low (2-14 bytes per message)
Quick Decision Guide:
Scenario
Use HTTP
Use WebSocket
Read sensor on demand
Yes
No
Live sensor dashboard
No
Yes
Firmware update check
Yes
No
Remote control (<50ms)
No
Yes
Mobile app API
Yes
Either
46.2 Prerequisites
Before diving into this chapter, you should be familiar with:
Interactive Simulator: ESP32 Web Server (HTTP REST API)
What This Simulates: ESP32 hosting a web server with RESTful API for sensor data and device control
HTTP REST API Pattern:
Client (Browser/App) ESP32 Web Server
| |
|--- GET /api/temperature -->|
| | Read sensor
|<-- 200 OK {"temp":23.5} --|
| |
|--- POST /api/led --------->|
| {"state":"on"} | Control actuator
|<-- 200 OK {"status":"on"}-|
RESTful Endpoints:
GET /api/temperature - Read temperature value
GET /api/humidity - Read humidity value
POST /api/led - Control LED (on/off)
GET /api/status - Get device status
PUT /api/config - Update device configuration
How to Use:
Click Start Simulation
Wait for “HTTP server started” message
Note the IP address (simulated: 192.168.1.100)
See GET/POST requests being processed
Observe JSON responses with sensor data
Learning Points
What You Will Observe:
HTTP Methods - GET for reading, POST for actions, PUT for updates
200 OK - Request successful
201 Created - Resource created (POST)
204 No Content - Success with no response body
400 Bad Request - Invalid JSON or parameters
404 Not Found - Endpoint doesn't exist
405 Method Not Allowed - Wrong HTTP method
500 Internal Error - Sensor read failure
503 Service Unavailable - Device offline
Real-World Applications:
Smart Home - Control lights, thermostats via web interface
Industrial IoT - Factory machines with HTTP APIs for monitoring
Agriculture - Soil sensors providing data to web dashboards
Building Management - HVAC systems with RESTful control
Energy Monitoring - Smart meters with HTTP data export
Experiments to Try:
Add New Endpoints - Implement /api/humidity, /api/pressure
Authentication - Add API key validation (Authorization header)
Rate Limiting - Limit requests to 10/minute per client
Figure 46.7: Average slot time equation for 802.11 CSMA/CA (Bianchi-style model)
Figure 46.8: 802.11 throughput equation using idle/busy slot time model
Text Version of CSMA/CA Model Equations
For accessibility, here is one common Bianchi-style saturated DCF model form. Symbol choices vary across sources, so focus on the structure and assumptions (saturation traffic, fixed frame sizes, and simplified timing).
\[
S = \frac{P_{\text{s}}\,L}{\mathbb{E}[\text{Slot}]}
\]
Where \(n\) is the number of contending stations, \(\tau\) is the per-slot transmission probability per station, \(L\) is payload length (bits), \(\sigma\) is the idle slot duration, \(T_{\text{s}}\) is the time for a successful transmission, and \(T_{\text{c}}\) is the time lost in a collision. Use this as an intuition-building model; validate capacity with real measurements (airtime utilization, retries, throughput, and latency).
What to Measure (recommended):
Airtime utilization and retry rate (from AP/controller if available)
End-to-end latency/jitter and packet loss (ping or application-level probes)
Application-layer throughput (e.g., iperf3 or representative traffic)
Roaming/handoff behavior if devices move
Example Output Format (illustrative):
=== Wi-Fi Capacity Check ===
Clients: <N>
Observed throughput: <Mbps>
Latency (p50/p95): <ms>
Retry rate: <percent> (if available)
Recommendations:
- If airtime is high: add AP capacity, reduce client count per AP, or use a wider plan (more APs, better placement)
- If retries are high: improve RSSI/SNR (placement/antennas), reduce interference, or change channels/bands
- If roaming is unstable: increase overlap, tune thresholds, and use fast-roaming features where supported
Key Concepts Demonstrated:
PHY rate vs usable throughput: overhead, retries, and contention reduce application throughput
Contention effects: more active stations increase backoff and collision probability under load
Capacity planning: design around airtime and worst-case locations, not just headline Mbps
Measurement-first workflow: validate with iperf3, latency probes, and AP stats
Interactive Calculator: Wi-Fi Capacity Estimator
Estimate how many IoT devices a single Wi-Fi access point can support based on your traffic pattern.
Explore these AI-generated figures that illustrate Wi-Fi implementation concepts for IoT devices.
46.7 Wi-Fi Module Architecture
Wi-Fi Module
Figure 46.9: Wi-Fi module architecture for IoT implementations showing integrated processor and radio.
46.8 Wi-Fi Roaming and Handoff
Wi-Fi Roaming
Figure 46.10: Wi-Fi roaming enables IoT devices to maintain connectivity while moving between access points.
46.9 Wi-Fi Mesh Network Topology
Wi-Fi Mesh Network
Figure 46.11: Wi-Fi mesh extends coverage for IoT deployments through multi-hop wireless backhaul connections.
Worked Example: Designing a Real-Time Industrial Dashboard with WebSocket
Scenario: A manufacturing plant monitors 50 CNC machines with vibration sensors reporting status every second. The operations team needs a live dashboard showing real-time vibration levels with <5 second latency. Compare HTTP polling vs WebSocket implementation.
Given:
50 CNC machines, each with vibration sensor
Update rate: 1 reading per second per machine
Dashboard: Web browser displaying all 50 machines simultaneously
Per second (50 machines): - Data: 50 × 630 = 31,500 bytes = 31.5 KB/sec - Per hour: 31.5 × 3,600 = 113 MB/hour - Per 8-hour shift: 113 × 8 = 905 MB/shift
Latency breakdown: - HTTP connection: 20-30 ms (TCP handshake + TLS if HTTPS) - Request/response: 10-20 ms - Total: 30-50 ms per poll
Problems: 1. High bandwidth: 905 MB/shift for 4 KB of actual data 2. Connection overhead: 50 new TCP connections every second 3. Stale data: Up to 1 second latency between updates 4. Server load: 180,000 HTTP requests/hour (50 machines × 3,600 seconds)
Key Insight: WebSocket provides 7-30x bandwidth reduction for continuous streaming by eliminating per-request HTTP headers. The break-even point is ~3-5 updates per connection lifetime. For real-time dashboards updating every second, WebSocket pays back the initial handshake overhead within 5 seconds and provides sub-5ms latency thereafter. The pattern is: HTTP for on-demand queries, WebSocket for live streaming, MQTT for pub/sub IoT networks.
Interactive Calculator: Battery Life Impact Calculator
Compare power consumption between HTTP polling and WebSocket for battery-powered IoT devices.
1. Using HTTP for Real-Time Bidirectional IoT Communication
HTTP is request-response only; the server cannot send data to the device without a device-initiated request. For real-time commands or alerts from cloud to device, use WebSocket (persistent bidirectional connection) or MQTT (publish-subscribe with broker). HTTP polling at frequent intervals (every second) wastes 10-100x more power and bandwidth.
2. Not Handling WebSocket Disconnections Gracefully
WebSocket connections can be silently terminated by NAT firewalls after inactivity periods (typically 60-300 seconds). Without a ping/pong keepalive mechanism and automatic reconnection, devices silently lose bidirectional communication. Implement both application-level pings and automatic reconnection with exponential backoff.
3. Ignoring HTTP Response Processing for IoT Devices
IoT devices that POST sensor data to REST APIs must process the HTTP response to detect server errors (429 Too Many Requests, 503 Service Unavailable). Silently discarding error responses causes data loss when the server is overloaded. Always parse HTTP status codes and implement retry logic for 5xx server errors.
4. Not Setting HTTP Connection Timeouts
HTTP requests without timeouts block indefinitely if the server is unreachable. A 30-second or 60-second connection timeout prevents the IoT device from hanging and ensures it retries or reports an error. Always configure both connection timeout and response read timeout for HTTP operations.
🏷️ Label the Diagram
💻 Code Challenge
46.12 Summary
This chapter covered HTTP and WebSocket communication for Wi-Fi IoT:
HTTP REST APIs: Building ESP32 web servers with RESTful endpoints for sensor data and device control, including proper status codes and JSON formatting
HTTP Client Communication: Sending GET/POST requests to cloud services and local servers with timeout handling
WebSocket Real-Time Streaming: Persistent bidirectional connections with 95% bandwidth reduction compared to HTTP polling
Protocol Selection: When to use HTTP (on-demand, infrequent) vs WebSocket (real-time, continuous) vs MQTT (pub/sub, low power)
Network Capacity Analysis: Understanding throughput, contention, and capacity planning for IoT Wi-Fi deployments