Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
237 changes: 232 additions & 5 deletions components/esp_websocket_client/examples/target/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,42 @@
# Websocket Sample application

This example will shows how to set up and communicate over a websocket.
This example shows how to set up and communicate over a websocket.

## Table of Contents

- [Hardware Required](#hardware-required)
- [Configure the project](#configure-the-project)
- [Pre-configured SDK Configurations](#pre-configured-sdk-configurations)
- [Server Certificate Verification](#server-certificate-verification)
- [Generating Self-signed Certificates](#generating-a-self-signed-certificates-with-openssl)
- [Build and Flash](#build-and-flash)
- [Testing with pytest](#testing-with-pytest)
- [Example Output](#example-output)
- [WebSocket Test Server](#websocket-test-server)
- [Python Flask Echo Server](#alternative-python-flask-echo-server)

## Quick Start

1. **Install dependencies:**
```bash
pip install -r esp-protocols/ci/requirements.txt
```

2. **Configure and build:**
```bash
idf.py menuconfig # Configure WiFi/Ethernet and WebSocket URI
idf.py build
```

3. **Flash and monitor:**
```bash
idf.py -p PORT flash monitor
```

4. **Run tests:**
```bash
pytest .
```

## How to Use Example

Expand All @@ -15,6 +51,27 @@ This example can be executed on any ESP32 board, the only required interface is
* 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)
* 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.

### Pre-configured SDK Configurations

This example includes several pre-configured `sdkconfig.ci.*` files for different testing scenarios:

* **sdkconfig.ci** - Default configuration with WebSocket over Ethernet (IP101 PHY, ESP32, IPv6) and hardcoded URI.
* **sdkconfig.ci.plain_tcp** - WebSocket over plain TCP (no TLS, URI from stdin) using Ethernet (IP101 PHY, ESP32, IPv6).
* **sdkconfig.ci.mutual_auth** - WebSocket with mutual TLS authentication (client/server certificate verification, skips CN check) and URI from stdin.
* **sdkconfig.ci.dynamic_buffer** - WebSocket with dynamic buffer allocation, Ethernet (IP101 PHY, ESP32, IPv6), and hardcoded URI.

To use a specific configuration for building:
```
rm sdkconfig
cp sdkconfig.ci.plain_tcp sdkconfig
idf.py build
```

Or specify it directly when building:
```
idf.py -DSDKCONFIG_DEFAULTS="sdkconfig.ci.plain_tcp" build
```

### Server Certificate Verification

* 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.
Expand All @@ -26,7 +83,7 @@ This example can be executed on any ESP32 board, the only required interface is
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.
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

### Generating a self signed Certificates with OpenSSL
### Generating a self signed Certificates with OpenSSL manually
* 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:

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

### Certificate Generation Options

#### Option 1: Manual OpenSSL Commands
Follow the step-by-step process in the section above to understand certificate generation.

#### Option 2: Automated Script
**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:

```bash
chmod +x generate_certs.sh
./generate_certs.sh
```

This script automatically generates all required certificates in the correct directories and cleans up temporary files.

#### Option 3: Online Certificate Generators
- **mkcert**: `install mkcert` then `mkcert -install` and `mkcert localhost`
- **Let's Encrypt**: For production certificates (free, automated renewal)
- **Online generators**: Search for "self-signed certificate generator" online

### Build and Flash

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

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

See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects.
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.

## Testing with pytest

### Install Dependencies

Before running the pytest tests, you need to install the required Python packages:

```
pip install -r esp-protocols/ci/requirements.txt
```

### Run pytest

After installing the dependencies, you can run the pytest tests:

Run all tests in current directory:
```
pytest .
```

Run specific test file:
```
pytest pytest_websocket.py
```

To specify the target device or serial port, use:
```
pytest --target esp32 --port /dev/ttyUSB0
```

## Example Output

Expand Down Expand Up @@ -105,9 +211,101 @@ W (9162) WEBSOCKET: Received=hello 0003
```


## Python Flask echo server
## WebSocket Test Server

### Standalone Test Server

This example includes a standalone WebSocket test server (`websocket_server.py`) that can be used for testing your ESP32 WebSocket client:

#### Quick Start

**Plain WebSocket (No TLS):**
```bash
# Plain WebSocket server (no encryption)
python websocket_server.py

# Custom port
python websocket_server.py --port 9000
```

**Server-Only Authentication:**
```bash
# TLS WebSocket server (ESP32 verifies server)
python websocket_server.py --tls

# Custom port with TLS
python websocket_server.py --port 9000 --tls
```

**Mutual Authentication:**
```bash
# TLS with client certificate verification (both verify each other)
python websocket_server.py --tls --client-verify

# Custom port with mutual authentication
python websocket_server.py --port 9000 --tls --client-verify
```

#### Server Features
- **Echo functionality** - Automatically echoes back received messages
- **TLS support** - Secure WebSocket (WSS) connections
- **Client certificate verification** - Mutual authentication support
- **Binary and text messages** - Handles both data types
- **Auto IP detection** - Shows connection URL with your local IP

#### Verification Modes

**Plain WebSocket (No TLS):**
- No certificate verification on either side
- Use for local testing or trusted networks
- Configuration: `CONFIG_WS_OVER_TLS_MUTUAL_AUTH=n` and `CONFIG_WS_OVER_TLS_SERVER_AUTH=n`

**Server-Only Authentication (`--tls` without `--client-verify`):**
- ESP32 verifies the server's certificate
- Server does NOT verify the ESP32's certificate
- Use when you trust the client but want to verify the server
- Configuration: `CONFIG_WS_OVER_TLS_SERVER_AUTH=y`

**Mutual Authentication (`--tls --client-verify`):**
- ESP32 verifies the server's certificate
- Server verifies the ESP32's certificate
- Use when both parties need to authenticate each other
- Configuration: `CONFIG_WS_OVER_TLS_MUTUAL_AUTH=y`

#### Usage Examples

**Plain WebSocket (No TLS or Client Verification):**
```bash
# Basic server (port 8080)
python websocket_server.py

# Custom port
python websocket_server.py --port 9000
```

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
**Server-Only Authentication (ESP32 verifies server, server doesn't verify ESP32):**
```bash
# TLS server without client verification
python websocket_server.py --tls

# Custom port with TLS
python websocket_server.py --port 9000 --tls
```

**Mutual Authentication (Both ESP32 and server verify each other's certificates):**
```bash
# TLS server with client certificate verification
python websocket_server.py --tls --client-verify

# Custom port with mutual authentication
python websocket_server.py --port 9000 --tls --client-verify
```

The server will display the connection URL (e.g., `wss://192.168.1.100:8080`) that you can use in your ESP32 configuration.

### Alternative: Python Flask Echo Server

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

```
pip install flask-sock
Expand Down Expand Up @@ -135,3 +333,32 @@ if __name__ == '__main__':
# gunicorn -b 0.0.0.0:5000 --workers 4 --threads 100 module:app
app.run(host="0.0.0.0", debug=True)
```

## Troubleshooting

### Common Issues

**Connection failed:**
- Verify WiFi/Ethernet configuration in `idf.py menuconfig`
- Check if the WebSocket server is running and accessible
- Ensure the URI is correct (use `wss://` for TLS, `ws://` for plain TCP)

**TLS certificate errors:**
- For self-signed certificates, ensure `CONFIG_WS_OVER_TLS_SKIP_COMMON_NAME_CHECK=y` is enabled
- Verify certificate files are properly formatted and accessible

**Build errors:**
- Clean build: `idf.py fullclean`
- Check ESP-IDF version compatibility
- Verify all dependencies are installed

**Test failures:**
- Ensure the device is connected and accessible via the specified port
- Check that the target device matches the configuration (`--target esp32`)
- Verify pytest dependencies are installed correctly

### Getting Help

- Check the [ESP-IDF documentation](https://docs.espressif.com/projects/esp-idf/)
- Review the [WebSocket client component documentation](../../README.md)
- Report issues on the [ESP Protocols repository](https://github.com/espressif/esp-protocols)
31 changes: 31 additions & 0 deletions components/esp_websocket_client/examples/target/generate_certs.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#!/bin/bash
# Generate CA, Server, and Client certificates automatically

# Create directories if they don't exist
mkdir -p main/certs/server

echo "Generating CA certificate..."
openssl genrsa -out main/certs/ca_key.pem 2048
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"

echo "Generating Server certificate..."
openssl genrsa -out main/certs/server/server_key.pem 2048
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"
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

echo "Generating Client certificate..."
openssl genrsa -out main/certs/client_key.pem 2048
openssl req -new -key main/certs/client_key.pem -out client_csr.pem -subj "/C=US/ST=State/L=City/O=Organization/CN=TestClient"
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

# Clean up CSR files
rm server_csr.pem client_csr.pem

echo "Certificates generated successfully!"
echo "Generated files:"
echo " - main/certs/ca_cert.pem (CA certificate)"
echo " - main/certs/ca_key.pem (CA private key)"
echo " - main/certs/client_cert.pem (Client certificate)"
echo " - main/certs/client_key.pem (Client private key)"
echo " - main/certs/server/server_cert.pem (Server certificate)"
echo " - main/certs/server/server_key.pem (Server private key)"
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* SPDX-FileCopyrightText: 2022-2024 Espressif Systems (Shanghai) CO LTD
* SPDX-FileCopyrightText: 2022-2025 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Unlicense OR CC0-1.0
*/
Expand Down Expand Up @@ -142,7 +142,11 @@ static void websocket_app_start(void)
#if CONFIG_WEBSOCKET_URI_FROM_STDIN
char line[128];

ESP_LOGI(TAG, "Please enter uri of websocket endpoint");
ESP_LOGI(TAG, "Please enter WebSocket endpoint URI");
ESP_LOGI(TAG, "Examples:");
ESP_LOGI(TAG, " ws://192.168.1.100:8080 (plain WebSocket)");
ESP_LOGI(TAG, " wss://192.168.1.100:8080 (secure WebSocket)");
ESP_LOGI(TAG, " wss://echo.websocket.org (public test server)");
get_string(line, sizeof(line));

websocket_cfg.uri = line;
Expand Down
Loading
Loading