Repository navigation
Expand file tree
/
Copy pathhttp_ws_client.rs
More file actions
218 lines (193 loc) · 8.98 KB
/
Copy pathhttp_ws_client.rs
File metadata and controls
218 lines (193 loc) · 8.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
//! Simple websocket client example.
//!
//! This example connects to a websocket server that echoes messages,
//! sends a message, receives the same message, and closes the connection.
//!
//! See the comment below as to how to build the example with ESP IDF 5+.
#![allow(unknown_lints)]
#![allow(unexpected_cfgs)]
#[cfg(not(any(esp32h2, esp32h21, esp32h4, esp32p4)))]
fn main() {
example::main()
}
#[cfg(any(esp32h2, esp32h21, esp32h4, esp32p4))]
fn main() {
panic!("ESP32-H2, ESP32-H21, ESP32-H4 and ESP32-P4 do not have a Wifi radio (but you could enable the esp-wifi-remote component to use them with a WiFi co-processor)");
}
#[cfg(not(any(esp32h2, esp32h21, esp32h4, esp32p4)))]
mod example {
pub fn main() {
#[cfg(esp_idf_version_major = "4")]
example::main().unwrap();
// Note that the ESP IDF websocket client IS available on ESP IDF >= 5 too
// It is just that it is now an external component, so to use it, you need
// to put the following snippet at the end of the `Cargo.toml` file of your binary crate:
//
// ```toml
// [[package.metadata.esp-idf-sys.extra_components]]
// remote_component = { name = "espressif/esp_websocket_client", version = "1.1.0" }
// ```
#[cfg(not(esp_idf_version_major = "4"))]
panic!("This example only compiles on ESP IDF 4. Check the comments in the example how to compile it on ESP IDF 5+")
}
#[cfg(esp_idf_version_major = "4")]
pub mod example {
use core::time::Duration;
use esp_idf_svc::eventloop::EspSystemEventLoop;
use esp_idf_svc::hal::peripherals::Peripherals;
use esp_idf_svc::io::EspIOError;
use esp_idf_svc::log::EspLogger;
use esp_idf_svc::nvs::EspDefaultNvsPartition;
use esp_idf_svc::tls::X509;
use esp_idf_svc::wifi::*;
use esp_idf_svc::ws::client::{
EspWebSocketClient, EspWebSocketClientConfig, FrameType, WebSocketEvent,
WebSocketEventType,
};
use log::info;
use std::sync::mpsc;
const SSID: &str = env!("WIFI_SSID");
const PASSWORD: &str = env!("WIFI_PASS");
const ECHO_SERVER_URI: &str = "wss://echo.websocket.org";
/// The PEM-encoded ISRG Root X1 certificate at the end of the cert chain
/// for the websocket server at echo.websocket.org.
const SERVER_ROOT_CERT: &[u8] = b"
-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjx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8NwdC
jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
-----END CERTIFICATE-----\0";
/// The relevant events for this example as it connects to the server,
/// sends a message, receives the same message, and closes the connection.
#[derive(Debug, PartialEq)]
enum ExampleEvent {
Connected,
MessageReceived,
Closed,
}
pub fn main() -> anyhow::Result<()> {
esp_idf_svc::sys::link_patches();
EspLogger::initialize_default();
// Setup Wifi
let peripherals = Peripherals::take()?;
let sys_loop = EspSystemEventLoop::take()?;
let nvs = EspDefaultNvsPartition::take()?;
let mut wifi = BlockingWifi::wrap(
EspWifi::new(peripherals.modem, sys_loop.clone(), Some(nvs))?,
sys_loop,
)?;
connect_wifi(&mut wifi)?;
// Connect websocket
let config = EspWebSocketClientConfig {
server_cert: Some(X509::pem_until_nul(SERVER_ROOT_CERT)),
..Default::default()
};
let timeout = Duration::from_secs(10);
let (tx, rx) = mpsc::channel::<ExampleEvent>();
let mut client =
EspWebSocketClient::new(ECHO_SERVER_URI, &config, timeout, move |event| {
handle_event(&tx, event)
})?;
assert_eq!(rx.recv(), Ok(ExampleEvent::Connected));
assert!(client.is_connected());
// Send message and receive it back
let message = "Hello, World!";
info!("Websocket send, text: {message}");
client.send(FrameType::Text(false), message.as_bytes())?;
assert_eq!(rx.recv(), Ok(ExampleEvent::MessageReceived));
// Close websocket
drop(client);
assert_eq!(rx.recv(), Ok(ExampleEvent::Closed));
Ok(())
}
fn connect_wifi(wifi: &mut BlockingWifi<EspWifi<'static>>) -> anyhow::Result<()> {
let wifi_configuration: Configuration = Configuration::Client(ClientConfiguration {
ssid: SSID.try_into().unwrap(),
bssid: None,
auth_method: AuthMethod::WPA2Personal,
password: PASSWORD.try_into().unwrap(),
channel: None,
..Default::default()
});
wifi.set_configuration(&wifi_configuration)?;
wifi.start()?;
info!("Wifi started");
wifi.connect()?;
info!("Wifi connected");
wifi.wait_netif_up()?;
info!("Wifi netif up");
Ok(())
}
fn handle_event(
tx: &mpsc::Sender<ExampleEvent>,
event: &Result<WebSocketEvent, EspIOError>,
) {
if let Ok(event) = event {
match event.event_type {
WebSocketEventType::BeforeConnect => {
info!("Websocket before connect");
}
WebSocketEventType::Connected => {
info!("Websocket connected");
tx.send(ExampleEvent::Connected).ok();
}
WebSocketEventType::Disconnected => {
info!("Websocket disconnected");
}
WebSocketEventType::Close(reason) => {
info!("Websocket close, reason: {reason:?}");
}
WebSocketEventType::Closed => {
info!("Websocket closed");
tx.send(ExampleEvent::Closed).ok();
}
WebSocketEventType::Text(message) => {
// Messages larger than `buffer_size` arrive in several chunks,
// which this example does not reassemble
if let Some(Ok(text)) = message.complete_str() {
info!("Websocket recv, text: {text}");
if text == "Hello, World!" {
tx.send(ExampleEvent::MessageReceived).ok();
}
}
}
WebSocketEventType::Binary(message) => {
info!("Websocket recv, binary: {:?}", message.data());
}
WebSocketEventType::Ping => {
info!("Websocket ping");
}
WebSocketEventType::Pong => {
info!("Websocket pong");
}
}
}
}
}
}