|
| 1 | +# Network Protocols for Embedded Systems |
| 2 | + |
| 3 | +Designing networked embedded devices requires balancing deterministic behavior, small memory footprints, and constrained CPU cycles while speaking interoperable protocols. This guide focuses on practical, production-oriented aspects for IPv4/IPv6, ICMP/ARP/ND, UDP/TCP, and application-layer IoT protocols. |
| 4 | + |
| 5 | +--- |
| 6 | + |
| 7 | +## Goals |
| 8 | +- Understand the TCP/IP stack in embedded contexts |
| 9 | +- Choose and configure lightweight stacks (e.g., lwIP) |
| 10 | +- Implement robust UDP/TCP clients/servers |
| 11 | +- Integrate IoT app protocols (MQTT/CoAP) |
| 12 | +- Diagnose problems with a structured checklist |
| 13 | + |
| 14 | +--- |
| 15 | + |
| 16 | +## TCP/IP Stack Overview |
| 17 | + |
| 18 | +- Network stack models: |
| 19 | + - OSI (7 layers) vs TCP/IP (4 layers). In practice, embedded stacks follow TCP/IP: Link → Internet → Transport → Application. |
| 20 | +- Common link layers: Ethernet, Wi‑Fi, PPP, LTE Cat-x, 802.15.4. |
| 21 | +- Internet layer: |
| 22 | + - IPv4 header (20 bytes min), IPv6 (40 bytes). IPv6 removes header checksum and uses Neighbor Discovery (ND) instead of ARP. |
| 23 | + - ICMPv4/ICMPv6 for diagnostics and error reporting. |
| 24 | +- Transport layer: |
| 25 | + - UDP: message boundaries preserved, lower overhead, no built-in retransmission. |
| 26 | + - TCP: connection-oriented, ordered, reliable stream, congestion and flow control. |
| 27 | +- Application layer: |
| 28 | + - IoT protocols: MQTT (pub/sub over TCP), CoAP (REST over UDP), HTTP/HTTPS, custom binary. |
| 29 | + |
| 30 | +--- |
| 31 | + |
| 32 | +## Addressing, Name Resolution, and Configuration |
| 33 | + |
| 34 | +- Address assignment: |
| 35 | + - Static IP, DHCPv4, SLAAC/DHCPv6 for IPv6. |
| 36 | +- Name resolution: |
| 37 | + - DNS (A/AAAA), mDNS for local discovery. |
| 38 | +- ARP (IPv4) and ND (IPv6) for L2 neighbor resolution. |
| 39 | +- NAT traversal considerations for outbound vs inbound connectivity (prefer client-initiated sessions for simplicity). |
| 40 | + |
| 41 | +--- |
| 42 | + |
| 43 | +## Embedded Network Stacks |
| 44 | + |
| 45 | +- Common choices: lwIP, uIP (legacy/very small), vendor stacks (e.g., STM32Cube, NXP SDK). |
| 46 | +- Key configuration levers (lwIP examples): |
| 47 | + - Memory pools: `MEM_SIZE`, `PBUF_POOL_SIZE`, `TCP_MSS`, `TCP_SND_BUF`, `TCP_WND`. |
| 48 | + - Features: enable only what you need (e.g., disable `LWIP_IPV6` if not used; disable `LWIP_DNS` if static names). |
| 49 | + - Threading: `tcpip_thread` priority vs application tasks; ensure input path is high priority and bounded work in callbacks. |
| 50 | + - Zero-copy path from driver to stack when possible (DMA-safe RX/TX buffers, proper cache maintenance on MCUs with cache). |
| 51 | + |
| 52 | +--- |
| 53 | + |
| 54 | +## UDP in Embedded Systems |
| 55 | + |
| 56 | +Use UDP when latency and simplicity outweigh guaranteed delivery. |
| 57 | + |
| 58 | +- Pros: small footprint, no connection state, multicast support. |
| 59 | +- Cons: no retransmission, ordering, or congestion control. |
| 60 | +- Design patterns: |
| 61 | + - App-level sequence numbers and ACK/NACK where needed. |
| 62 | + - Timeouts and retry policy with capped backoff. |
| 63 | + - Message authentication (HMAC) if security layer is not provided elsewhere. |
| 64 | + |
| 65 | +### Minimal UDP Echo (POSIX-like pseudo C) |
| 66 | + |
| 67 | +```c |
| 68 | +int sock = socket(AF_INET, SOCK_DGRAM, 0); |
| 69 | +struct sockaddr_in addr = { .sin_family = AF_INET, .sin_port = htons(9000), .sin_addr.s_addr = INADDR_ANY }; |
| 70 | +bind(sock, (struct sockaddr*)&addr, sizeof(addr)); |
| 71 | + |
| 72 | +for (;;) { |
| 73 | + uint8_t buf[1500]; |
| 74 | + struct sockaddr_in peer; socklen_t len = sizeof(peer); |
| 75 | + int n = recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr*)&peer, &len); |
| 76 | + if (n > 0) { |
| 77 | + sendto(sock, buf, n, 0, (struct sockaddr*)&peer, len); |
| 78 | + } |
| 79 | +} |
| 80 | +``` |
| 81 | + |
| 82 | +--- |
| 83 | + |
| 84 | +## TCP in Embedded Systems |
| 85 | + |
| 86 | +Use TCP for reliability and compatibility with cloud services. |
| 87 | + |
| 88 | +- Memory planning: |
| 89 | + - Each TCP PCB and each connection consumes buffers; set limits (`MEMP_NUM_TCP_PCB`, backlog). |
| 90 | + - Choose `TCP_MSS` appropriate to link MTU (Ethernet MTU 1500 → MSS 1460 for IPv4, 1440 for IPv6). |
| 91 | +- Nagle vs latency: |
| 92 | + - Disable Nagle (`TCP_NODELAY`) for request/response with small payloads to reduce latency. |
| 93 | + - Keep Nagle for bulk transfers; or coalesce at application layer. |
| 94 | +- Keepalive: |
| 95 | + - TCP keepalive timers detect dead peers; configure periods conservatively to avoid unnecessary network chatter on cellular. |
| 96 | + |
| 97 | +### Minimal TCP Client (POSIX-like pseudo C) |
| 98 | + |
| 99 | +```c |
| 100 | +int sock = socket(AF_INET, SOCK_STREAM, 0); |
| 101 | +struct sockaddr_in srv = { .sin_family = AF_INET, .sin_port = htons(1883), .sin_addr.s_addr = inet_addr("192.0.2.10") }; |
| 102 | +connect(sock, (struct sockaddr*)&srv, sizeof(srv)); |
| 103 | + |
| 104 | +const char hello[] = "ping"; |
| 105 | +send(sock, hello, sizeof(hello)-1, 0); |
| 106 | + |
| 107 | +uint8_t buf[1024]; |
| 108 | +int n = recv(sock, buf, sizeof(buf), 0); |
| 109 | +// handle response |
| 110 | +``` |
| 111 | +
|
| 112 | +--- |
| 113 | +
|
| 114 | +## IoT Application Protocols |
| 115 | +
|
| 116 | +### MQTT (over TCP) |
| 117 | +- Pub/Sub with broker; topics, QoS 0/1/2; retain and last will. |
| 118 | +- Embedded notes: persistent sessions reduce handshake cost; limit topic and payload size; batch publishes. |
| 119 | +
|
| 120 | +### CoAP (over UDP) |
| 121 | +- REST-like with confirmable/non-confirmable messages, observe, block-wise transfer. |
| 122 | +- Embedded notes: implement retransmission and token matching carefully; DTLS for security if required. |
| 123 | +
|
| 124 | +### HTTP/HTTPS |
| 125 | +- Ubiquitous, verbose; consider short timeouts and connection pooling if client. |
| 126 | +- Prefer HTTP/1.1 keep-alive; HTTP/2 is heavier for MCUs without proper libraries. |
| 127 | +
|
| 128 | +--- |
| 129 | +
|
| 130 | +## Performance Tuning Checklist |
| 131 | +
|
| 132 | +- Link MTU and MSS aligned; avoid IP fragmentation. |
| 133 | +- Pre-allocate RX/TX buffers; avoid heap in hot path. |
| 134 | +- Use DMA and zero-copy pbufs where supported. |
| 135 | +- Configure interrupt coalescing (if NIC supports) vs latency goals. |
| 136 | +- Pin high-priority threads; bound ISR work; defer to RTOS tasks. |
| 137 | +- Use DSCP/ToS to mark latency-sensitive traffic where network honors QoS. |
| 138 | +
|
| 139 | +--- |
| 140 | +
|
| 141 | +## Reliability and Robustness |
| 142 | +
|
| 143 | +- Exponential backoff with jitter for reconnects. |
| 144 | +- Dead-peer detection (keepalive, application heartbeats). |
| 145 | +- Validate all lengths and parse defensively (avoid buffer overruns). |
| 146 | +- Implement watchdog resets around networking stalls with recovery paths. |
| 147 | +- Persist credentials and broker endpoints in redundant storage. |
| 148 | +
|
| 149 | +--- |
| 150 | +
|
| 151 | +## Diagnostics |
| 152 | +
|
| 153 | +- Packet capture: |
| 154 | + - Mirror/SPAN port or inline hub; or software capture from the driver if feasible. |
| 155 | + - Use filters (examples): `arp`, `icmp`, `tcp.port == 1883`, `udp.port == 5683`. |
| 156 | +- Health metrics: |
| 157 | + - RX/TX drops, retransmits, RTT, DNS latency, reconnect counts. |
| 158 | +- Common issues: |
| 159 | + - ARP/ND resolution failures → check VLAN, gateway, and subnet masks |
| 160 | + - MSS/MTU mismatch → excessive fragmentation, PMTU black holes |
| 161 | + - Head-of-line blocking in single-threaded MQTT clients → worker thread separation |
| 162 | +
|
| 163 | +--- |
| 164 | +
|
| 165 | +## Security Notes |
| 166 | +
|
| 167 | +- Prefer TLS/DTLS with modern ciphersuites; validate certificates and time. |
| 168 | +- Use hardware RNG and secure key storage if available. |
| 169 | +- Restrict inbound listeners; favor outbound client connections. |
| 170 | +- Rate-limit and authenticate management endpoints. |
| 171 | +
|
| 172 | +--- |
| 173 | +
|
| 174 | +## Production Readiness Checklist |
| 175 | +
|
| 176 | +- IP configuration: static/DHCPv4/IPv6 SLAAC documented |
| 177 | +- DNS fallback and caching behavior defined |
| 178 | +- Robust reconnect and backoff strategy |
| 179 | +- Heartbeats and liveness probes implemented |
| 180 | +- TLS/DTLS configuration with strong RNG and key storage |
| 181 | +- Watchdog and brown-out recovery paths tested |
| 182 | +- Packet captures for success and failure cases recorded |
| 183 | +
|
| 184 | +
|
0 commit comments