Skip to content

Commit 6f87c26

Browse files
committed
feat(examples): enhance example with docs, pytest setup, and standalone test server
- Add comprehensive README with TOC and quick start - Add pytest setup and certificate generation scripts - Add standalone WebSocket test server with TLS support - Add troubleshooting and multiple testing approaches
1 parent 6f6237a commit 6f87c26

File tree

5 files changed

+421
-83
lines changed

5 files changed

+421
-83
lines changed

components/esp_websocket_client/examples/target/README.md

Lines changed: 232 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,42 @@
11
# Websocket Sample application
22

3-
This example will shows how to set up and communicate over a websocket.
3+
This example shows how to set up and communicate over a websocket.
4+
5+
## Table of Contents
6+
7+
- [Hardware Required](#hardware-required)
8+
- [Configure the project](#configure-the-project)
9+
- [Pre-configured SDK Configurations](#pre-configured-sdk-configurations)
10+
- [Server Certificate Verification](#server-certificate-verification)
11+
- [Generating Self-signed Certificates](#generating-a-self-signed-certificates-with-openssl)
12+
- [Build and Flash](#build-and-flash)
13+
- [Testing with pytest](#testing-with-pytest)
14+
- [Example Output](#example-output)
15+
- [WebSocket Test Server](#websocket-test-server)
16+
- [Python Flask Echo Server](#alternative-python-flask-echo-server)
17+
18+
## Quick Start
19+
20+
1. **Install dependencies:**
21+
```bash
22+
pip install -r esp-protocols/ci/requirements.txt
23+
```
24+
25+
2. **Configure and build:**
26+
```bash
27+
idf.py menuconfig # Configure WiFi/Ethernet and WebSocket URI
28+
idf.py build
29+
```
30+
31+
3. **Flash and monitor:**
32+
```bash
33+
idf.py -p PORT flash monitor
34+
```
35+
36+
4. **Run tests:**
37+
```bash
38+
pytest .
39+
```
440

541
## How to Use Example
642

@@ -15,6 +51,27 @@ This example can be executed on any ESP32 board, the only required interface is
1551
* Configure the websocket endpoint URI under "Example Configuration", if "WEBSOCKET_URI_FROM_STDIN" is selected then the example application will connect to the URI it reads from stdin (used for testing)
1652
* To test a WebSocket client example over TLS, please enable one of the following configurations: `CONFIG_WS_OVER_TLS_MUTUAL_AUTH` or `CONFIG_WS_OVER_TLS_SERVER_AUTH`. See the sections below for more details.
1753

54+
### Pre-configured SDK Configurations
55+
56+
This example includes several pre-configured `sdkconfig.ci.*` files for different testing scenarios:
57+
58+
* **sdkconfig.ci** - Default configuration with WebSocket over Ethernet (IP101 PHY, ESP32, IPv6) and hardcoded URI.
59+
* **sdkconfig.ci.plain_tcp** - WebSocket over plain TCP (no TLS, URI from stdin) using Ethernet (IP101 PHY, ESP32, IPv6).
60+
* **sdkconfig.ci.mutual_auth** - WebSocket with mutual TLS authentication (client/server certificate verification, skips CN check) and URI from stdin.
61+
* **sdkconfig.ci.dynamic_buffer** - WebSocket with dynamic buffer allocation, Ethernet (IP101 PHY, ESP32, IPv6), and hardcoded URI.
62+
63+
To use a specific configuration for building:
64+
```
65+
rm sdkconfig
66+
cp sdkconfig.ci.plain_tcp sdkconfig
67+
idf.py build
68+
```
69+
70+
Or specify it directly when building:
71+
```
72+
idf.py -DSDKCONFIG_DEFAULTS="sdkconfig.ci.plain_tcp" build
73+
```
74+
1875
### Server Certificate Verification
1976

2077
* Mutual Authentication: When `CONFIG_WS_OVER_TLS_MUTUAL_AUTH=y` is enabled, it's essential to provide valid certificates for both the server and client.
@@ -26,7 +83,7 @@ This example can be executed on any ESP32 board, the only required interface is
2683
Please note: This example represents an extremely simplified approach to generating self-signed certificates/keys with a single common CA, devoid of CN checks, lacking password protection, and featuring hardcoded key sizes and types. It is intended solely for testing purposes.
2784
In the outlined steps, we are omitting the configuration of the CN (Common Name) field due to the context of a testing environment. However, it's important to recognize that the CN field is a critical element of SSL/TLS certificates, significantly influencing the security and efficacy of HTTPS communications. This field facilitates the verification of a website's identity, enhancing trust and security in web interactions. In practical deployments beyond testing scenarios, ensuring the CN field is accurately set is paramount for maintaining the integrity and reliability of secure communications
2885

29-
### Generating a self signed Certificates with OpenSSL
86+
### Generating a self signed Certificates with OpenSSL manually
3087
* The example below outlines the process for creating new certificates for both the server and client using OpenSSL, a widely-used command line tool for implementing TLS protocol:
3188

3289
```
@@ -63,6 +120,26 @@ Please see the openssl man pages (man openssl) for more details.
63120
It is **strongly recommended** to not reuse the example certificate in your application;
64121
it is included only for demonstration.
65122

123+
### Certificate Generation Options
124+
125+
#### Option 1: Manual OpenSSL Commands
126+
Follow the step-by-step process in the section above to understand certificate generation.
127+
128+
#### Option 2: Automated Script
129+
**Note:** Test certificates are already available in the example. If you want to regenerate them or create new ones, use the provided `generate_certs.sh` script:
130+
131+
```bash
132+
chmod +x generate_certs.sh
133+
./generate_certs.sh
134+
```
135+
136+
This script automatically generates all required certificates in the correct directories and cleans up temporary files.
137+
138+
#### Option 3: Online Certificate Generators
139+
- **mkcert**: `install mkcert` then `mkcert -install` and `mkcert localhost`
140+
- **Let's Encrypt**: For production certificates (free, automated renewal)
141+
- **Online generators**: Search for "self-signed certificate generator" online
142+
66143
### Build and Flash
67144

68145
Build the project and flash it to the board, then run monitor tool to view serial output:
@@ -73,7 +150,36 @@ idf.py -p PORT flash monitor
73150

74151
(To exit the serial monitor, type ``Ctrl-]``.)
75152

76-
See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects.
153+
See the [ESP-IDF Getting Started Guide](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/get-started/index.html) for full steps to configure and use ESP-IDF to build projects.
154+
155+
## Testing with pytest
156+
157+
### Install Dependencies
158+
159+
Before running the pytest tests, you need to install the required Python packages:
160+
161+
```
162+
pip install -r esp-protocols/ci/requirements.txt
163+
```
164+
165+
### Run pytest
166+
167+
After installing the dependencies, you can run the pytest tests:
168+
169+
Run all tests in current directory:
170+
```
171+
pytest .
172+
```
173+
174+
Run specific test file:
175+
```
176+
pytest pytest_websocket.py
177+
```
178+
179+
To specify the target device or serial port, use:
180+
```
181+
pytest --target esp32 --port /dev/ttyUSB0
182+
```
77183

78184
## Example Output
79185

@@ -105,9 +211,101 @@ W (9162) WEBSOCKET: Received=hello 0003
105211
```
106212

107213

108-
## Python Flask echo server
214+
## WebSocket Test Server
215+
216+
### Standalone Test Server
217+
218+
This example includes a standalone WebSocket test server (`websocket_server.py`) that can be used for testing your ESP32 WebSocket client:
219+
220+
#### Quick Start
221+
222+
**Plain WebSocket (No TLS):**
223+
```bash
224+
# Plain WebSocket server (no encryption)
225+
python websocket_server.py
226+
227+
# Custom port
228+
python websocket_server.py --port 9000
229+
```
230+
231+
**Server-Only Authentication:**
232+
```bash
233+
# TLS WebSocket server (ESP32 verifies server)
234+
python websocket_server.py --tls
235+
236+
# Custom port with TLS
237+
python websocket_server.py --port 9000 --tls
238+
```
239+
240+
**Mutual Authentication:**
241+
```bash
242+
# TLS with client certificate verification (both verify each other)
243+
python websocket_server.py --tls --client-verify
244+
245+
# Custom port with mutual authentication
246+
python websocket_server.py --port 9000 --tls --client-verify
247+
```
248+
249+
#### Server Features
250+
- **Echo functionality** - Automatically echoes back received messages
251+
- **TLS support** - Secure WebSocket (WSS) connections
252+
- **Client certificate verification** - Mutual authentication support
253+
- **Binary and text messages** - Handles both data types
254+
- **Auto IP detection** - Shows connection URL with your local IP
255+
256+
#### Verification Modes
257+
258+
**Plain WebSocket (No TLS):**
259+
- No certificate verification on either side
260+
- Use for local testing or trusted networks
261+
- Configuration: `CONFIG_WS_OVER_TLS_MUTUAL_AUTH=n` and `CONFIG_WS_OVER_TLS_SERVER_AUTH=n`
262+
263+
**Server-Only Authentication (`--tls` without `--client-verify`):**
264+
- ESP32 verifies the server's certificate
265+
- Server does NOT verify the ESP32's certificate
266+
- Use when you trust the client but want to verify the server
267+
- Configuration: `CONFIG_WS_OVER_TLS_SERVER_AUTH=y`
268+
269+
**Mutual Authentication (`--tls --client-verify`):**
270+
- ESP32 verifies the server's certificate
271+
- Server verifies the ESP32's certificate
272+
- Use when both parties need to authenticate each other
273+
- Configuration: `CONFIG_WS_OVER_TLS_MUTUAL_AUTH=y`
274+
275+
#### Usage Examples
276+
277+
**Plain WebSocket (No TLS or Client Verification):**
278+
```bash
279+
# Basic server (port 8080)
280+
python websocket_server.py
281+
282+
# Custom port
283+
python websocket_server.py --port 9000
284+
```
109285

110-
By default, the `wss://echo.websocket.org` endpoint is used. You can setup a Python websocket echo server locally and try the `ws://<your-ip>:5000` endpoint. To do this, install Flask-sock Python package
286+
**Server-Only Authentication (ESP32 verifies server, server doesn't verify ESP32):**
287+
```bash
288+
# TLS server without client verification
289+
python websocket_server.py --tls
290+
291+
# Custom port with TLS
292+
python websocket_server.py --port 9000 --tls
293+
```
294+
295+
**Mutual Authentication (Both ESP32 and server verify each other's certificates):**
296+
```bash
297+
# TLS server with client certificate verification
298+
python websocket_server.py --tls --client-verify
299+
300+
# Custom port with mutual authentication
301+
python websocket_server.py --port 9000 --tls --client-verify
302+
```
303+
304+
The server will display the connection URL (e.g., `wss://192.168.1.100:8080`) that you can use in your ESP32 configuration.
305+
306+
### Alternative: Python Flask Echo Server
307+
308+
By default, the `wss://echo.websocket.org` endpoint is used. You can also setup a Python Flask websocket echo server locally and try the `ws://<your-ip>:5000` endpoint. To do this, install Flask-sock Python package
111309

112310
```
113311
pip install flask-sock
@@ -135,3 +333,32 @@ if __name__ == '__main__':
135333
# gunicorn -b 0.0.0.0:5000 --workers 4 --threads 100 module:app
136334
app.run(host="0.0.0.0", debug=True)
137335
```
336+
337+
## Troubleshooting
338+
339+
### Common Issues
340+
341+
**Connection failed:**
342+
- Verify WiFi/Ethernet configuration in `idf.py menuconfig`
343+
- Check if the WebSocket server is running and accessible
344+
- Ensure the URI is correct (use `wss://` for TLS, `ws://` for plain TCP)
345+
346+
**TLS certificate errors:**
347+
- For self-signed certificates, ensure `CONFIG_WS_OVER_TLS_SKIP_COMMON_NAME_CHECK=y` is enabled
348+
- Verify certificate files are properly formatted and accessible
349+
350+
**Build errors:**
351+
- Clean build: `idf.py fullclean`
352+
- Check ESP-IDF version compatibility
353+
- Verify all dependencies are installed
354+
355+
**Test failures:**
356+
- Ensure the device is connected and accessible via the specified port
357+
- Check that the target device matches the configuration (`--target esp32`)
358+
- Verify pytest dependencies are installed correctly
359+
360+
### Getting Help
361+
362+
- Check the [ESP-IDF documentation](https://docs.espressif.com/projects/esp-idf/)
363+
- Review the [WebSocket client component documentation](../../README.md)
364+
- Report issues on the [ESP Protocols repository](https://github.com/espressif/esp-protocols)
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#!/bin/bash
2+
# Generate CA, Server, and Client certificates automatically
3+
4+
# Create directories if they don't exist
5+
mkdir -p main/certs/server
6+
7+
echo "Generating CA certificate..."
8+
openssl genrsa -out main/certs/ca_key.pem 2048
9+
openssl req -new -x509 -days 3650 -key main/certs/ca_key.pem -out main/certs/ca_cert.pem -subj "/C=US/ST=State/L=City/O=Organization/CN=TestCA"
10+
11+
echo "Generating Server certificate..."
12+
openssl genrsa -out main/certs/server/server_key.pem 2048
13+
openssl req -new -key main/certs/server/server_key.pem -out server_csr.pem -subj "/C=US/ST=State/L=City/O=Organization/CN=localhost"
14+
openssl x509 -req -days 3650 -in server_csr.pem -CA main/certs/ca_cert.pem -CAkey main/certs/ca_key.pem -CAcreateserial -out main/certs/server/server_cert.pem
15+
16+
echo "Generating Client certificate..."
17+
openssl genrsa -out main/certs/client_key.pem 2048
18+
openssl req -new -key main/certs/client_key.pem -out client_csr.pem -subj "/C=US/ST=State/L=City/O=Organization/CN=TestClient"
19+
openssl x509 -req -days 3650 -in client_csr.pem -CA main/certs/ca_cert.pem -CAkey main/certs/ca_key.pem -CAcreateserial -out main/certs/client_cert.pem
20+
21+
# Clean up CSR files
22+
rm server_csr.pem client_csr.pem
23+
24+
echo "Certificates generated successfully!"
25+
echo "Generated files:"
26+
echo " - main/certs/ca_cert.pem (CA certificate)"
27+
echo " - main/certs/ca_key.pem (CA private key)"
28+
echo " - main/certs/client_cert.pem (Client certificate)"
29+
echo " - main/certs/client_key.pem (Client private key)"
30+
echo " - main/certs/server/server_cert.pem (Server certificate)"
31+
echo " - main/certs/server/server_key.pem (Server private key)"

components/esp_websocket_client/examples/target/main/websocket_example.c

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* SPDX-FileCopyrightText: 2022-2024 Espressif Systems (Shanghai) CO LTD
2+
* SPDX-FileCopyrightText: 2022-2025 Espressif Systems (Shanghai) CO LTD
33
*
44
* SPDX-License-Identifier: Unlicense OR CC0-1.0
55
*/
@@ -142,7 +142,11 @@ static void websocket_app_start(void)
142142
#if CONFIG_WEBSOCKET_URI_FROM_STDIN
143143
char line[128];
144144

145-
ESP_LOGI(TAG, "Please enter uri of websocket endpoint");
145+
ESP_LOGI(TAG, "Please enter WebSocket endpoint URI");
146+
ESP_LOGI(TAG, "Examples:");
147+
ESP_LOGI(TAG, " ws://192.168.1.100:8080 (plain WebSocket)");
148+
ESP_LOGI(TAG, " wss://192.168.1.100:8080 (secure WebSocket)");
149+
ESP_LOGI(TAG, " wss://echo.websocket.org (public test server)");
146150
get_string(line, sizeof(line));
147151

148152
websocket_cfg.uri = line;

0 commit comments

Comments
 (0)