46  ::: {style=“overflow-x: auto;”}

title: “Wi-Fi HTTP & WebSocket” difficulty: intermediate —

In 60 Seconds

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.

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!”

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}\]

  • HTTP GET request: ~250 bytes (headers only)
  • HTTP response: ~220 bytes (headers) + 26 bytes (JSON payload {"temp":23.5})
  • Total per reading: \(250 + 220 + 26 = 496\ \text{bytes}\)

Total for 1 hour: \[3600 \times 496 = 1,785,600\ \text{bytes} = 1.7\ \text{MB}\]

WebSocket (persistent connection):

  • Initial HTTP upgrade handshake: ~500 bytes (once per session)
  • WebSocket frame header: 6 bytes per message
  • Payload per message: 26 bytes
  • Total per reading: \(6 + 26 = 32\ \text{bytes}\)

Total for 1 hour: \[500 + (3600 \times 32) = 115,700\ \text{bytes} = 113\ \text{KB}\]

Bandwidth savings: \[\frac{1,785,600 - 115,700}{1,785,600} \times 100\% = 93.5\%\]

Radio-on time (at 1 Mbps Wi-Fi PHY):

  • HTTP: \(\frac{1,785,600 \times 8}{1,000,000} = 14.3\ \text{seconds}\)
  • WebSocket: \(\frac{115,700 \times 8}{1,000,000} = 0.93\ \text{seconds}\)

Battery life impact (120 mA TX current, 10 mA idle):

  • HTTP: \((14.3 \times 120) + (3585.7 \times 10) = 37,573\ \text{mAs/hour}\) = 10.4 mAh/hour
  • WebSocket: \((0.93 \times 120) + (3599.07 \times 10) = 36,103\ \text{mAs/hour}\) = 10.0 mAh/hour

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

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:

46.3 HTTP REST API on ESP32

Interactive Calculator: HTTP vs WebSocket Bandwidth Comparison

Calculate the bandwidth difference between HTTP polling and WebSocket streaming for your IoT application.

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:

  1. Click Start Simulation
  2. Wait for “HTTP server started” message
  3. Note the IP address (simulated: 192.168.1.100)
  4. See GET/POST requests being processed
  5. Observe JSON responses with sensor data

Learning Points

What You Will Observe:

  1. HTTP Methods - GET for reading, POST for actions, PUT for updates
  2. JSON Responses - Structured data format for IoT
  3. RESTful Design - Resource-based URLs (/api/temperature)
  4. Stateless Protocol - Each request independent
  5. CORS Headers - Cross-origin resource sharing for web apps

HTTP Request/Response Cycle:

1. Client sends HTTP request
   GET /api/temperature HTTP/1.1
   Host: 192.168.1.100
   Accept: application/json

2. ESP32 processes request
   - Parse URL path
   - Execute handler function
   - Read DHT22 sensor
   - Format JSON response

3. ESP32 sends HTTP response
   HTTP/1.1 200 OK
   Content-Type: application/json
   Content-Length: 25

   {"temperature":23.5}

4. Client receives and parses JSON

REST API Design Principles:

Principle Example Why Important
Resource-based URLs /api/sensors/temp Clear hierarchy
HTTP methods GET (read), POST (create) Standard semantics
Status codes 200 OK, 404 Not Found Error handling
JSON format {“temp”:23.5} Universal parsing
Stateless Each request complete Scalability

HTTP Status Codes for IoT:

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:

  1. Smart Home - Control lights, thermostats via web interface
  2. Industrial IoT - Factory machines with HTTP APIs for monitoring
  3. Agriculture - Soil sensors providing data to web dashboards
  4. Building Management - HVAC systems with RESTful control
  5. Energy Monitoring - Smart meters with HTTP data export

Experiments to Try:

  1. Add New Endpoints - Implement /api/humidity, /api/pressure
  2. Authentication - Add API key validation (Authorization header)
  3. Rate Limiting - Limit requests to 10/minute per client
  4. WebSocket Upgrade - Add real-time streaming endpoint
  5. mDNS Discovery - Enable http://esp32-sensor.local/

HTTP vs MQTT for IoT:

Feature HTTP REST MQTT
Pattern Request/Response Pub/Sub
Overhead High (headers) Low (binary)
Power Medium-High Low
Discovery URLs Topics
Real-time Polling required Push notifications
Complexity Simple, universal Requires broker
Best for On-demand queries Event streams

Use HTTP when: Direct device access, web integration, infrequent updates

Use MQTT when: Continuous streaming, low power, many-to-many communication

Interactive Calculator: HTTP Response Time Breakdown

Analyze the latency components of an HTTP request to understand why WebSocket provides lower latency.

Performance Metrics:

Metric Typical Value Optimization
Response Time 10-50 ms Keep handlers simple
Concurrent Requests 4-10 Use async web server
Memory Usage 8-16 KB Limit response size
Connection Time 100-200 ms Persistent connections
Throughput 1-10 req/s Hardware dependent

46.4 WebSocket Real-Time Communication

Interactive Simulator: WebSocket Real-Time Communication

What This Simulates: ESP32 WebSocket server providing real-time bidirectional sensor data streaming

WebSocket vs HTTP:

HTTP vs WebSocket protocol
Figure 46.1: HTTP Polling vs WebSocket Efficiency Comparison for IoT Data Streaming

WebSocket Handshake:

1. HTTP Upgrade Request:
   GET /ws HTTP/1.1
   Upgrade: websocket
   Connection: Upgrade
   Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==

2. Server Upgrade Response:
   HTTP/1.1 101 Switching Protocols
   Upgrade: websocket
   Connection: Upgrade
   Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

3. Bidirectional frames exchange:
   Server - {"temp":23.5,"time":1234567890}
   Client - {"command":"led_on"}
   Server - {"status":"led_on","success":true}

How to Use:

  1. Click Start Simulation
  2. WebSocket server starts on ws://192.168.1.100:81
  3. Watch real-time sensor data streaming every second
  4. See client commands being processed instantly
  5. Observe persistent connection (no reconnection overhead)

Learning Points

What You Will Observe:

  1. Persistent Connection - Once established, stays open for continuous data
  2. Low Latency - No HTTP overhead for each message (~1-5ms vs 50-100ms)
  3. Bidirectional - Both client and server can initiate messages
  4. Event-Driven - Push model instead of polling
  5. Binary/Text Frames - Efficient data encoding

WebSocket Message Types:

Frame Type Opcode Use Case
Text Frame 0x01 JSON, XML, plain text
Binary Frame 0x02 Protobuf, CBOR, raw data
Ping Frame 0x09 Keep-alive, latency test
Pong Frame 0x0A Response to ping
Close Frame 0x08 Graceful connection close

WebSocket Frame Structure:

WebSocket frame structure
Figure 46.2: WebSocket Frame Structure with Header Fields and Payload Components

Real-World Applications:

  1. Smart Home Dashboards - Real-time sensor graphs without page refresh
  2. Industrial Monitoring - Live factory machine data streams
  3. Healthcare - Continuous patient vital signs monitoring
  4. Robotics - Low-latency remote control commands
  5. Energy Management - Live power consumption graphs

Experiments to Try:

  1. Multiple Clients - Connect multiple browsers to same ESP32
  2. Broadcast Messages - Server sends data to all connected clients
  3. Binary Frames - Send sensor data as compact binary (not JSON)
  4. Ping/Pong - Implement heartbeat to detect disconnections
  5. Compression - Enable per-message deflate extension

WebSocket vs Other Protocols:

Protocol Latency Bandwidth Bidirectional Use Case
HTTP REST 50-100ms High No API queries
WebSocket 1-5ms Low Yes Real-time
MQTT 10-20ms Very Low Yes (pub/sub) IoT events
Server-Sent 20-40ms Medium No (one-way) Notifications
UDP <1ms Lowest Yes Raw data

Connection Lifecycle:

1. Initial HTTP GET with Upgrade header
2. 101 Switching Protocols response
3. Bidirectional frames (text/binary)
4. Periodic ping/pong (keep-alive)
5. Data exchange continues
6. Close frame when done (graceful shutdown)

Connection duration: Seconds to hours (long-lived)
Reconnection: Only if network failure occurs

Security Considerations:

wss:// (WebSocket Secure) = WebSocket over TLS/SSL
- Encrypted data frames
- Certificate validation
- Port 443 (standard HTTPS port)
- Prevents man-in-the-middle attacks

Authentication:
- Send token in initial HTTP headers
- Validate token before upgrade
- Close connection if unauthorized

Performance Metrics:

Metric Value Notes
Frame overhead 2-14 bytes vs 500+ for HTTP
Latency 1-5 ms vs 50-100 ms
Max connections (ESP32) 4-8 Hardware limited
Message rate 100-1000/s Depends on payload
Memory per connection ~8 KB Keep connections low

When to Use WebSocket:

  • Real-time dashboards
  • Live sensor streaming
  • Remote control (low latency)
  • Multi-user collaboration
  • NOT for: Infrequent updates (use HTTP REST)
  • NOT for: One-way notifications only (use SSE)
  • NOT for: Highly constrained devices (use MQTT)
Interactive Calculator: WebSocket Break-Even Point

Determine when WebSocket becomes more efficient than HTTP polling based on message frequency.

:::

46.5 Wi-Fi Network Capacity Analysis

46.5.1 Throughput and Performance

Throughput vs time
Figure 46.3: Wi-Fi throughput performance analysis - Scenario 1
Interference impact
Figure 46.4: Wi-Fi throughput performance analysis - Scenario 2
Distance degradation
Figure 46.5: Wi-Fi throughput performance analysis - Scenario 3
Upload vs download
Figure 46.6: Wi-Fi throughput performance analysis - Scenario 4

46.5.2 CSMA/CA Model Equations

Average slot time
Figure 46.7: Average slot time equation for 802.11 CSMA/CA (Bianchi-style model)
Throughput equation
Figure 46.8: 802.11 throughput equation using idle/busy slot time model

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).

Definitions:

\[ P_{\text{idle}} = (1 - \tau)^n \qquad P_{\text{tr}} = 1 - P_{\text{idle}} \qquad P_{\text{s}} = n\,\tau\,(1-\tau)^{n-1} \]

Average slot duration:

\[ \mathbb{E}[\text{Slot}] = P_{\text{idle}}\,\sigma + P_{\text{s}}\,T_{\text{s}} + (P_{\text{tr}} - P_{\text{s}})\,T_{\text{c}} \]

Throughput:

\[ 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.

46.7 Wi-Fi Module Architecture

46.8 Wi-Fi Roaming and Handoff

46.9 Wi-Fi Mesh Network Topology

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
  • Payload: 80 bytes JSON per reading (machine ID, timestamp, X/Y/Z vibration, temperature)
  • Network: Local Wi-Fi, 100 Mbps available bandwidth

Option 1: HTTP Polling (Naive Approach)

Dashboard polls each machine every second via HTTP GET:

// Dashboard JavaScript (runs in browser)
const machines = Array.from({length: 50}, (_, i) => i + 1);

function pollAllMachines() {
  machines.forEach(machineId => {
    fetch(`http://192.168.1.${100 + machineId}/api/vibration`)
      .then(response => response.json())
      .then(data => updateChart(machineId, data));
  });
}

setInterval(pollAllMachines, 1000);  // Poll every 1 second

HTTP Polling Analysis:

Per HTTP request overhead: - HTTP request headers: ~350 bytes (GET /api/vibration HTTP/1.1 + headers) - HTTP response headers: ~200 bytes (status + content-type + cors) - Payload: 80 bytes - Total: 630 bytes per request

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)

Option 2: WebSocket Real-Time Streaming (Optimized)

Each machine opens a WebSocket connection and pushes data:

// ESP32 WebSocket Server (runs on each CNC sensor)
#include <WiFi.h>
#include <WebSocketsServer.h>

WebSocketsServer webSocket(81);

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
  if (type == WStype_CONNECTED) {
    Serial.printf("Dashboard connected: client #%u\n", num);
  }
}

void setup() {
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) delay(500);

  webSocket.begin();
  webSocket.onEvent(webSocketEvent);
}

void loop() {
  webSocket.loop();

  // Read vibration sensor
  float vibX = readVibrationX();
  float vibY = readVibrationY();
  float vibZ = readVibrationZ();
  float temp = readTemperature();

  // Create JSON payload
  char json[128];
  snprintf(json, sizeof(json),
    "{\"id\":%d,\"x\":%.2f,\"y\":%.2f,\"z\":%.2f,\"temp\":%.1f,\"ts\":%lu}",
    MACHINE_ID, vibX, vibY, vibZ, temp, millis());

  // Broadcast to all connected dashboards
  webSocket.broadcastTXT(json);

  delay(1000);  // 1-second interval
}
// Dashboard JavaScript
const machines = Array.from({length: 50}, (_, i) => i + 1);
const sockets = [];

machines.forEach(machineId => {
  const ws = new WebSocket(`ws://192.168.1.${100 + machineId}:81`);

  ws.onmessage = (event) => {
    const data = JSON.parse(event.data);
    updateChart(machineId, data);  // Real-time update as data arrives
  };

  ws.onerror = (error) => {
    console.error(`Machine ${machineId} connection error`);
  };

  sockets.push(ws);
});

WebSocket Analysis:

Initial connection overhead (one-time): - HTTP Upgrade handshake: ~500 bytes - 50 machines: 25 KB total (amortized over session duration)

Per WebSocket frame: - Frame header: 6 bytes (FIN, opcode, mask, payload length) - Payload: 80 bytes - Total: 86 bytes per update

Per second (50 machines): - Data: 50 × 86 = 4,300 bytes = 4.3 KB/sec - Per hour: 4.3 × 3,600 = 15.5 MB/hour - Per 8-hour shift: 15.5 × 8 = 124 MB/shift

Latency: - WebSocket frame: 1-5 ms (no connection setup) - Total: 1-5 ms from sensor to dashboard

Comparison Summary:

Metric HTTP Polling WebSocket Improvement
Bandwidth/shift 905 MB 124 MB 7.3x reduction
Latency 30-50 ms 1-5 ms 10x faster
Requests/hour 180,000 0 (persistent) Eliminates server polling
Connection overhead 350+200 bytes 6 bytes 92% reduction
Update model Pull (dashboard polls) Push (sensor streams) Real-time

Real-World Deployment Metrics:

After deploying WebSocket solution: - Dashboard latency: <2 seconds from vibration spike to alert - Network utilization: 4.3 KB/sec vs 31.5 KB/sec (86% reduction) - Server CPU: 5% vs 45% (eliminated request parsing overhead) - Connection stability: 99.97% uptime (persistent connections auto-reconnect)

Advanced Optimization: Binary WebSocket Frames

For maximum efficiency, send binary data instead of JSON:

// Binary frame structure (16 bytes fixed)
struct VibrationData {
  uint16_t machineId;
  uint16_t timestamp;  // Seconds since boot
  float vibX;
  float vibY;
  float vibZ;
  float temp;
} __attribute__((packed));

void loop() {
  VibrationData data = {
    .machineId = MACHINE_ID,
    .timestamp = (uint16_t)(millis() / 1000),
    .vibX = readVibrationX(),
    .vibY = readVibrationY(),
    .vibZ = readVibrationZ(),
    .temp = readTemperature()
  };

  // Send as binary frame (opcode 0x02)
  webSocket.broadcastBIN((uint8_t*)&data, sizeof(data));

  delay(1000);
}

Binary frames: 16 bytes (payload) + 6 bytes (header) = 22 bytes/update - Per hour: 50 × 22 × 3,600 = 3.96 MB/hour (3.9x smaller than JSON WebSocket) - Per shift: 3.96 × 8 = 31.7 MB/shift (28x smaller than HTTP polling)

Decision Matrix: When to Use Each Protocol

Use Case Best Choice Reason
Live industrial dashboard WebSocket <5 ms latency, 7x bandwidth savings
User checks status once/hour HTTP REST No connection overhead for infrequent access
50+ sensors streaming 1/sec WebSocket Eliminates CSMA/CA contention
Mobile app (background refresh) HTTP REST + push notifications Mobile OS limits background WebSocket
Browser game (real-time) WebSocket Sub-10 ms latency critical
Firmware download (large file) HTTP Built-in resume support, better caching
SCADA system (plant-wide) MQTT Pub/sub scales better than 1000s of WebSockets

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.

46.10 Concept Relationships

Understanding how these concepts relate helps you choose the right protocol for your application:

Concept Depends On Enables Trade-off
HTTP REST API TCP/IP stack, web server Request/response pattern High overhead vs simplicity
WebSocket HTTP upgrade, TCP/IP Bidirectional streaming Connection management vs efficiency
IPHC Compression Shared prefix knowledge Reduced bandwidth State overhead vs payload size
CSMA/CA Carrier sensing, backoff Channel access fairness Overhead vs collision avoidance
OFDMA Resource unit allocation Parallel transmission Scheduling complexity vs efficiency

46.11 See Also

For deeper exploration of related topics:

Common Pitfalls

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.

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.

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.

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.

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

46.13 Knowledge Check

46.14 What’s Next

If you want to… Read this
Optimize power for Wi-Fi IoT devices Wi-Fi Power Optimization
Review complete implementation lab Wi-Fi Comprehensive Lab
Secure the Wi-Fi connection Wi-Fi Security and Provisioning
Understand MQTT for IoT MQTT Fundamentals
Compare with all IoT implementations Wi-Fi for IoT: Implementations