A home automation system that turns electrical appliances into smart devices using ESP32 microcontrollers and a cloud-based WebSocket server.
SwitchBot allows you to control up to 8 electrical relays remotely via a REST API or WebSocket connection. The system consists of two parts:
- Hardware (ESP32 Firmware) - Arduino sketch that runs on ESP32, handles relay control, manual switches, and WebSocket communication
- Backend Server (Python) - Async web server using aiohttp that manages device connections and provides REST API endpoints
- Control up to 8 relays per device
- Manual switch override support (physical buttons)
- WiFi configuration via captive portal (WiFiManager)
- Secure WebSocket communication (SSL/TLS)
- REST API for integration with other services
- Persistent state storage using ESP32 Preferences
- Factory reset functionality
- Real-time bidirectional communication
- ESP32 microcontroller
- Arduino framework
- Libraries:
- WiFiManager - Captive portal for WiFi setup
- WebSocketsClient - WebSocket communication
- ArduinoJson - JSON parsing
- Preferences - Non-volatile storage
- Python 3
- aiohttp - Async HTTP/WebSocket server
- aiohttp-jinja2 - Template rendering
- Cerberus - Data validation
| Function | Pins |
|---|---|
| Relay Outputs | GPIO 23, 22, 21, 19, 18, 5, 25, 26 |
| Switch Inputs | GPIO 13, 12, 14, 27, 33, 32, 15, 4 |
| Board LED | GPIO 2 |
| Reset Button | GPIO 17 |
Returns the current state of all relays for a device.
Response:
{
"relay_1": true,
"relay_2": false,
...
}Update relay states for a device.
Request Body:
{
"relay_1": true,
"relay_2": false
}Response:
{
"status": true,
"data": { "relay_1": true, "relay_2": false }
}Real-time bidirectional communication for device control and state updates.
- Flash the Arduino sketch to your ESP32
- On first boot, connect to the "SwitchBot" WiFi network
- Configure your WiFi credentials and SwitchBot username/password
- The device will connect to the server automatically
-
Install dependencies:
pip install -r requirements.txt
-
Run the server:
python -m app
- Device Boot: ESP32 loads stored credentials or starts captive portal for configuration
- Connection: Device establishes SSL WebSocket connection to the server
- Registration: Server registers the device in
ACTIVE_DEVICESdictionary - Control: Users send commands via REST API or WebSocket
- Execution: Server forwards commands to the device via WebSocket
- Feedback: Device reports state changes back to the server
- Manual Override: Physical switches can toggle relays locally, state syncs to server
┌─────────────┐ WebSocket ┌─────────────┐ REST API ┌─────────────┐
│ ESP32 │◄──────────────────►│ Server │◄─────────────────►│ Client │
│ (Device) │ (SSL) │ (aiohttp) │ │ (App/Web) │
└─────────────┘ └─────────────┘ └─────────────┘
│ │
│ Manual │ State
│ Switches │ Storage
▼ ▼
┌─────────────┐ ┌─────────────┐
│ Relays │ │ Database │
│ (Appliances)│ │ │
└─────────────┘ └─────────────┘
GPL-3.0