aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDario Nieuwenhuis <[email protected]>2023-06-22 19:18:01 +0000
committerGitHub <[email protected]>2023-06-22 19:18:01 +0000
commit70907d84f197d1c5d5d112ae1172e9070d41b730 (patch)
tree8d6e3085efad9758fc44b19194b5ea574aa38041
parent1f2be2dac5eeed739d2866b9b63ca06fdd84c276 (diff)
parent8bbfa6827cd68f67a50a89b13947542e632d5411 (diff)
Merge pull request #1546 from embassy-rs/esp-hosted
esp-hosted embassy-net driver.
-rwxr-xr-xci.sh2
-rw-r--r--embassy-net-esp-hosted/Cargo.toml20
-rw-r--r--embassy-net-esp-hosted/src/control.rs139
-rw-r--r--embassy-net-esp-hosted/src/esp_hosted_config.proto432
-rw-r--r--embassy-net-esp-hosted/src/fmt.rs257
-rw-r--r--embassy-net-esp-hosted/src/ioctl.rs123
-rw-r--r--embassy-net-esp-hosted/src/lib.rs337
-rw-r--r--embassy-net-esp-hosted/src/proto.rs652
-rw-r--r--examples/nrf52840/Cargo.toml22
-rw-r--r--examples/nrf52840/src/bin/wifi_esp_hosted.rs139
-rw-r--r--tests/nrf/Cargo.toml4
-rw-r--r--tests/nrf/src/bin/wifi_esp_hosted_perf.rs270
-rw-r--r--tests/rp/src/bin/cyw43-perf.rs9
13 files changed, 2395 insertions, 11 deletions
diff --git a/ci.sh b/ci.sh
index 3fe1b1ce8..a03efb856 100755
--- a/ci.sh
+++ b/ci.sh
@@ -3,7 +3,7 @@
3set -euo pipefail 3set -euo pipefail
4 4
5export RUSTFLAGS=-Dwarnings 5export RUSTFLAGS=-Dwarnings
6export DEFMT_LOG=trace,cyw43=info,cyw43_pio=info,smoltcp=info 6export DEFMT_LOG=trace,embassy_net_esp_hosted=debug,cyw43=info,cyw43_pio=info,smoltcp=info
7 7
8# needed by wifi examples 8# needed by wifi examples
9export WIFI_NETWORK=x 9export WIFI_NETWORK=x
diff --git a/embassy-net-esp-hosted/Cargo.toml b/embassy-net-esp-hosted/Cargo.toml
new file mode 100644
index 000000000..a7e18ee09
--- /dev/null
+++ b/embassy-net-esp-hosted/Cargo.toml
@@ -0,0 +1,20 @@
1[package]
2name = "embassy-net-esp-hosted"
3version = "0.1.0"
4edition = "2021"
5
6[dependencies]
7defmt = { version = "0.3", optional = true }
8log = { version = "0.4.14", optional = true }
9
10embassy-time = { version = "0.1.0", path = "../embassy-time" }
11embassy-sync = { version = "0.2.0", path = "../embassy-sync"}
12embassy-futures = { version = "0.1.0", path = "../embassy-futures"}
13embassy-net-driver-channel = { version = "0.1.0", path = "../embassy-net-driver-channel"}
14
15embedded-hal = { version = "1.0.0-alpha.10" }
16embedded-hal-async = { version = "=0.2.0-alpha.1" }
17
18noproto = { git="https://github.com/embassy-rs/noproto", default-features = false, features = ["derive"] }
19#noproto = { version = "0.1", path = "/home/dirbaio/noproto", default-features = false, features = ["derive"] }
20heapless = "0.7.16"
diff --git a/embassy-net-esp-hosted/src/control.rs b/embassy-net-esp-hosted/src/control.rs
new file mode 100644
index 000000000..fce82ade7
--- /dev/null
+++ b/embassy-net-esp-hosted/src/control.rs
@@ -0,0 +1,139 @@
1use ch::driver::LinkState;
2use defmt::Debug2Format;
3use embassy_net_driver_channel as ch;
4use heapless::String;
5
6use crate::ioctl::Shared;
7use crate::proto::{self, CtrlMsg};
8
9#[derive(Debug)]
10pub struct Error {
11 pub status: u32,
12}
13
14pub struct Control<'a> {
15 state_ch: ch::StateRunner<'a>,
16 shared: &'a Shared,
17}
18
19#[allow(unused)]
20enum WifiMode {
21 None = 0,
22 Sta = 1,
23 Ap = 2,
24 ApSta = 3,
25}
26
27impl<'a> Control<'a> {
28 pub(crate) fn new(state_ch: ch::StateRunner<'a>, shared: &'a Shared) -> Self {
29 Self { state_ch, shared }
30 }
31
32 pub async fn init(&mut self) {
33 debug!("wait for init event...");
34 self.shared.init_wait().await;
35
36 debug!("set wifi mode");
37 self.set_wifi_mode(WifiMode::Sta as _).await;
38
39 let mac_addr = self.get_mac_addr().await;
40 debug!("mac addr: {:02x}", mac_addr);
41 self.state_ch.set_ethernet_address(mac_addr);
42 }
43
44 pub async fn join(&mut self, ssid: &str, password: &str) {
45 let req = proto::CtrlMsg {
46 msg_id: proto::CtrlMsgId::ReqConnectAp as _,
47 msg_type: proto::CtrlMsgType::Req as _,
48 payload: Some(proto::CtrlMsgPayload::ReqConnectAp(proto::CtrlMsgReqConnectAp {
49 ssid: String::from(ssid),
50 pwd: String::from(password),
51 bssid: String::new(),
52 listen_interval: 3,
53 is_wpa3_supported: false,
54 })),
55 };
56 let resp = self.ioctl(req).await;
57 let proto::CtrlMsgPayload::RespConnectAp(resp) = resp.payload.unwrap() else { panic!("unexpected resp") };
58 debug!("======= {:?}", Debug2Format(&resp));
59 assert_eq!(resp.resp, 0);
60 self.state_ch.set_link_state(LinkState::Up);
61 }
62
63 async fn get_mac_addr(&mut self) -> [u8; 6] {
64 let req = proto::CtrlMsg {
65 msg_id: proto::CtrlMsgId::ReqGetMacAddress as _,
66 msg_type: proto::CtrlMsgType::Req as _,
67 payload: Some(proto::CtrlMsgPayload::ReqGetMacAddress(
68 proto::CtrlMsgReqGetMacAddress {
69 mode: WifiMode::Sta as _,
70 },
71 )),
72 };
73 let resp = self.ioctl(req).await;
74 let proto::CtrlMsgPayload::RespGetMacAddress(resp) = resp.payload.unwrap() else { panic!("unexpected resp") };
75 assert_eq!(resp.resp, 0);
76
77 // WHY IS THIS A STRING? WHYYYY
78 fn nibble_from_hex(b: u8) -> u8 {
79 match b {
80 b'0'..=b'9' => b - b'0',
81 b'a'..=b'f' => b + 0xa - b'a',
82 b'A'..=b'F' => b + 0xa - b'A',
83 _ => panic!("invalid hex digit {}", b),
84 }
85 }
86
87 let mac = resp.mac.as_bytes();
88 let mut res = [0; 6];
89 assert_eq!(mac.len(), 17);
90 for (i, b) in res.iter_mut().enumerate() {
91 *b = (nibble_from_hex(mac[i * 3]) << 4) | nibble_from_hex(mac[i * 3 + 1])
92 }
93 res
94 }
95
96 async fn set_wifi_mode(&mut self, mode: u32) {
97 let req = proto::CtrlMsg {
98 msg_id: proto::CtrlMsgId::ReqSetWifiMode as _,
99 msg_type: proto::CtrlMsgType::Req as _,
100 payload: Some(proto::CtrlMsgPayload::ReqSetWifiMode(proto::CtrlMsgReqSetMode { mode })),
101 };
102 let resp = self.ioctl(req).await;
103 let proto::CtrlMsgPayload::RespSetWifiMode(resp) = resp.payload.unwrap() else { panic!("unexpected resp") };
104 assert_eq!(resp.resp, 0);
105 }
106
107 async fn ioctl(&mut self, req: CtrlMsg) -> CtrlMsg {
108 debug!("ioctl req: {:?}", &req);
109
110 let mut buf = [0u8; 128];
111
112 let req_len = noproto::write(&req, &mut buf).unwrap();
113
114 struct CancelOnDrop<'a>(&'a Shared);
115
116 impl CancelOnDrop<'_> {
117 fn defuse(self) {
118 core::mem::forget(self);
119 }
120 }
121
122 impl Drop for CancelOnDrop<'_> {
123 fn drop(&mut self) {
124 self.0.ioctl_cancel();
125 }
126 }
127
128 let ioctl = CancelOnDrop(self.shared);
129
130 let resp_len = ioctl.0.ioctl(&mut buf, req_len).await;
131
132 ioctl.defuse();
133
134 let res = noproto::read(&buf[..resp_len]).unwrap();
135 debug!("ioctl resp: {:?}", &res);
136
137 res
138 }
139}
diff --git a/embassy-net-esp-hosted/src/esp_hosted_config.proto b/embassy-net-esp-hosted/src/esp_hosted_config.proto
new file mode 100644
index 000000000..aa1bfde64
--- /dev/null
+++ b/embassy-net-esp-hosted/src/esp_hosted_config.proto
@@ -0,0 +1,432 @@
1syntax = "proto3";
2
3/* Enums similar to ESP IDF */
4enum Ctrl_VendorIEType {
5 Beacon = 0;
6 Probe_req = 1;
7 Probe_resp = 2;
8 Assoc_req = 3;
9 Assoc_resp = 4;
10}
11
12enum Ctrl_VendorIEID {
13 ID_0 = 0;
14 ID_1 = 1;
15}
16
17enum Ctrl_WifiMode {
18 NONE = 0;
19 STA = 1;
20 AP = 2;
21 APSTA = 3;
22}
23
24enum Ctrl_WifiBw {
25 BW_Invalid = 0;
26 HT20 = 1;
27 HT40 = 2;
28}
29
30enum Ctrl_WifiPowerSave {
31 PS_Invalid = 0;
32 MIN_MODEM = 1;
33 MAX_MODEM = 2;
34}
35
36enum Ctrl_WifiSecProt {
37 Open = 0;
38 WEP = 1;
39 WPA_PSK = 2;
40 WPA2_PSK = 3;
41 WPA_WPA2_PSK = 4;
42 WPA2_ENTERPRISE = 5;
43 WPA3_PSK = 6;
44 WPA2_WPA3_PSK = 7;
45}
46
47/* enums for Control path */
48enum Ctrl_Status {
49 Connected = 0;
50 Not_Connected = 1;
51 No_AP_Found = 2;
52 Connection_Fail = 3;
53 Invalid_Argument = 4;
54 Out_Of_Range = 5;
55}
56
57
58enum CtrlMsgType {
59 MsgType_Invalid = 0;
60 Req = 1;
61 Resp = 2;
62 Event = 3;
63 MsgType_Max = 4;
64}
65
66enum CtrlMsgId {
67 MsgId_Invalid = 0;
68
69 /** Request Msgs **/
70 Req_Base = 100;
71
72 Req_GetMACAddress = 101;
73 Req_SetMacAddress = 102;
74 Req_GetWifiMode = 103;
75 Req_SetWifiMode = 104;
76
77 Req_GetAPScanList = 105;
78 Req_GetAPConfig = 106;
79 Req_ConnectAP = 107;
80 Req_DisconnectAP = 108;
81
82 Req_GetSoftAPConfig = 109;
83 Req_SetSoftAPVendorSpecificIE = 110;
84 Req_StartSoftAP = 111;
85 Req_GetSoftAPConnectedSTAList = 112;
86 Req_StopSoftAP = 113;
87
88 Req_SetPowerSaveMode = 114;
89 Req_GetPowerSaveMode = 115;
90
91 Req_OTABegin = 116;
92 Req_OTAWrite = 117;
93 Req_OTAEnd = 118;
94
95 Req_SetWifiMaxTxPower = 119;
96 Req_GetWifiCurrTxPower = 120;
97
98 Req_ConfigHeartbeat = 121;
99 /* Add new control path command response before Req_Max
100 * and update Req_Max */
101 Req_Max = 122;
102
103 /** Response Msgs **/
104 Resp_Base = 200;
105
106 Resp_GetMACAddress = 201;
107 Resp_SetMacAddress = 202;
108 Resp_GetWifiMode = 203;
109 Resp_SetWifiMode = 204;
110
111 Resp_GetAPScanList = 205;
112 Resp_GetAPConfig = 206;
113 Resp_ConnectAP = 207;
114 Resp_DisconnectAP = 208;
115
116 Resp_GetSoftAPConfig = 209;
117 Resp_SetSoftAPVendorSpecificIE = 210;
118 Resp_StartSoftAP = 211;
119 Resp_GetSoftAPConnectedSTAList = 212;
120 Resp_StopSoftAP = 213;
121
122 Resp_SetPowerSaveMode = 214;
123 Resp_GetPowerSaveMode = 215;
124
125 Resp_OTABegin = 216;
126 Resp_OTAWrite = 217;
127 Resp_OTAEnd = 218;
128
129 Resp_SetWifiMaxTxPower = 219;
130 Resp_GetWifiCurrTxPower = 220;
131
132 Resp_ConfigHeartbeat = 221;
133 /* Add new control path command response before Resp_Max
134 * and update Resp_Max */
135 Resp_Max = 222;
136
137 /** Event Msgs **/
138 Event_Base = 300;
139 Event_ESPInit = 301;
140 Event_Heartbeat = 302;
141 Event_StationDisconnectFromAP = 303;
142 Event_StationDisconnectFromESPSoftAP = 304;
143 /* Add new control path command notification before Event_Max
144 * and update Event_Max */
145 Event_Max = 305;
146}
147
148/* internal supporting structures for CtrlMsg */
149message ScanResult {
150 bytes ssid = 1;
151 uint32 chnl = 2;
152 int32 rssi = 3;
153 bytes bssid = 4;
154 Ctrl_WifiSecProt sec_prot = 5;
155}
156
157message ConnectedSTAList {
158 bytes mac = 1;
159 int32 rssi = 2;
160}
161
162
163/* Control path structures */
164/** Req/Resp structure **/
165message CtrlMsg_Req_GetMacAddress {
166 int32 mode = 1;
167}
168
169message CtrlMsg_Resp_GetMacAddress {
170 bytes mac = 1;
171 int32 resp = 2;
172}
173
174message CtrlMsg_Req_GetMode {
175}
176
177message CtrlMsg_Resp_GetMode {
178 int32 mode = 1;
179 int32 resp = 2;
180}
181
182message CtrlMsg_Req_SetMode {
183 int32 mode = 1;
184}
185
186message CtrlMsg_Resp_SetMode {
187 int32 resp = 1;
188}
189
190message CtrlMsg_Req_GetStatus {
191}
192
193message CtrlMsg_Resp_GetStatus {
194 int32 resp = 1;
195}
196
197message CtrlMsg_Req_SetMacAddress {
198 bytes mac = 1;
199 int32 mode = 2;
200}
201
202message CtrlMsg_Resp_SetMacAddress {
203 int32 resp = 1;
204}
205
206message CtrlMsg_Req_GetAPConfig {
207}
208
209message CtrlMsg_Resp_GetAPConfig {
210 bytes ssid = 1;
211 bytes bssid = 2;
212 int32 rssi = 3;
213 int32 chnl = 4;
214 Ctrl_WifiSecProt sec_prot = 5;
215 int32 resp = 6;
216}
217
218message CtrlMsg_Req_ConnectAP {
219 string ssid = 1;
220 string pwd = 2;
221 string bssid = 3;
222 bool is_wpa3_supported = 4;
223 int32 listen_interval = 5;
224}
225
226message CtrlMsg_Resp_ConnectAP {
227 int32 resp = 1;
228 bytes mac = 2;
229}
230
231message CtrlMsg_Req_GetSoftAPConfig {
232}
233
234message CtrlMsg_Resp_GetSoftAPConfig {
235 bytes ssid = 1;
236 bytes pwd = 2;
237 int32 chnl = 3;
238 Ctrl_WifiSecProt sec_prot = 4;
239 int32 max_conn = 5;
240 bool ssid_hidden = 6;
241 int32 bw = 7;
242 int32 resp = 8;
243}
244
245message CtrlMsg_Req_StartSoftAP {
246 string ssid = 1;
247 string pwd = 2;
248 int32 chnl = 3;
249 Ctrl_WifiSecProt sec_prot = 4;
250 int32 max_conn = 5;
251 bool ssid_hidden = 6;
252 int32 bw = 7;
253}
254
255message CtrlMsg_Resp_StartSoftAP {
256 int32 resp = 1;
257 bytes mac = 2;
258}
259
260message CtrlMsg_Req_ScanResult {
261}
262
263message CtrlMsg_Resp_ScanResult {
264 uint32 count = 1;
265 repeated ScanResult entries = 2;
266 int32 resp = 3;
267}
268
269message CtrlMsg_Req_SoftAPConnectedSTA {
270}
271
272message CtrlMsg_Resp_SoftAPConnectedSTA {
273 uint32 num = 1;
274 repeated ConnectedSTAList stations = 2;
275 int32 resp = 3;
276}
277
278message CtrlMsg_Req_OTABegin {
279}
280
281message CtrlMsg_Resp_OTABegin {
282 int32 resp = 1;
283}
284
285message CtrlMsg_Req_OTAWrite {
286 bytes ota_data = 1;
287}
288
289message CtrlMsg_Resp_OTAWrite {
290 int32 resp = 1;
291}
292
293message CtrlMsg_Req_OTAEnd {
294}
295
296message CtrlMsg_Resp_OTAEnd {
297 int32 resp = 1;
298}
299
300message CtrlMsg_Req_VendorIEData {
301 int32 element_id = 1;
302 int32 length = 2;
303 bytes vendor_oui = 3;
304 int32 vendor_oui_type = 4;
305 bytes payload = 5;
306}
307
308message CtrlMsg_Req_SetSoftAPVendorSpecificIE {
309 bool enable = 1;
310 Ctrl_VendorIEType type = 2;
311 Ctrl_VendorIEID idx = 3;
312 CtrlMsg_Req_VendorIEData vendor_ie_data = 4;
313}
314
315message CtrlMsg_Resp_SetSoftAPVendorSpecificIE {
316 int32 resp = 1;
317}
318
319message CtrlMsg_Req_SetWifiMaxTxPower {
320 int32 wifi_max_tx_power = 1;
321}
322
323message CtrlMsg_Resp_SetWifiMaxTxPower {
324 int32 resp = 1;
325}
326
327message CtrlMsg_Req_GetWifiCurrTxPower {
328}
329
330message CtrlMsg_Resp_GetWifiCurrTxPower {
331 int32 wifi_curr_tx_power = 1;
332 int32 resp = 2;
333}
334
335message CtrlMsg_Req_ConfigHeartbeat {
336 bool enable = 1;
337 int32 duration = 2;
338}
339
340message CtrlMsg_Resp_ConfigHeartbeat {
341 int32 resp = 1;
342}
343
344/** Event structure **/
345message CtrlMsg_Event_ESPInit {
346 bytes init_data = 1;
347}
348
349message CtrlMsg_Event_Heartbeat {
350 int32 hb_num = 1;
351}
352
353message CtrlMsg_Event_StationDisconnectFromAP {
354 int32 resp = 1;
355}
356
357message CtrlMsg_Event_StationDisconnectFromESPSoftAP {
358 int32 resp = 1;
359 bytes mac = 2;
360}
361
362message CtrlMsg {
363 /* msg_type could be req, resp or Event */
364 CtrlMsgType msg_type = 1;
365
366 /* msg id */
367 CtrlMsgId msg_id = 2;
368
369 /* union of all msg ids */
370 oneof payload {
371 /** Requests **/
372 CtrlMsg_Req_GetMacAddress req_get_mac_address = 101;
373 CtrlMsg_Req_SetMacAddress req_set_mac_address = 102;
374 CtrlMsg_Req_GetMode req_get_wifi_mode = 103;
375 CtrlMsg_Req_SetMode req_set_wifi_mode = 104;
376
377 CtrlMsg_Req_ScanResult req_scan_ap_list = 105;
378 CtrlMsg_Req_GetAPConfig req_get_ap_config = 106;
379 CtrlMsg_Req_ConnectAP req_connect_ap = 107;
380 CtrlMsg_Req_GetStatus req_disconnect_ap = 108;
381
382 CtrlMsg_Req_GetSoftAPConfig req_get_softap_config = 109;
383 CtrlMsg_Req_SetSoftAPVendorSpecificIE req_set_softap_vendor_specific_ie = 110;
384 CtrlMsg_Req_StartSoftAP req_start_softap = 111;
385 CtrlMsg_Req_SoftAPConnectedSTA req_softap_connected_stas_list = 112;
386 CtrlMsg_Req_GetStatus req_stop_softap = 113;
387
388 CtrlMsg_Req_SetMode req_set_power_save_mode = 114;
389 CtrlMsg_Req_GetMode req_get_power_save_mode = 115;
390
391 CtrlMsg_Req_OTABegin req_ota_begin = 116;
392 CtrlMsg_Req_OTAWrite req_ota_write = 117;
393 CtrlMsg_Req_OTAEnd req_ota_end = 118;
394
395 CtrlMsg_Req_SetWifiMaxTxPower req_set_wifi_max_tx_power = 119;
396 CtrlMsg_Req_GetWifiCurrTxPower req_get_wifi_curr_tx_power = 120;
397 CtrlMsg_Req_ConfigHeartbeat req_config_heartbeat = 121;
398
399 /** Responses **/
400 CtrlMsg_Resp_GetMacAddress resp_get_mac_address = 201;
401 CtrlMsg_Resp_SetMacAddress resp_set_mac_address = 202;
402 CtrlMsg_Resp_GetMode resp_get_wifi_mode = 203;
403 CtrlMsg_Resp_SetMode resp_set_wifi_mode = 204;
404
405 CtrlMsg_Resp_ScanResult resp_scan_ap_list = 205;
406 CtrlMsg_Resp_GetAPConfig resp_get_ap_config = 206;
407 CtrlMsg_Resp_ConnectAP resp_connect_ap = 207;
408 CtrlMsg_Resp_GetStatus resp_disconnect_ap = 208;
409
410 CtrlMsg_Resp_GetSoftAPConfig resp_get_softap_config = 209;
411 CtrlMsg_Resp_SetSoftAPVendorSpecificIE resp_set_softap_vendor_specific_ie = 210;
412 CtrlMsg_Resp_StartSoftAP resp_start_softap = 211;
413 CtrlMsg_Resp_SoftAPConnectedSTA resp_softap_connected_stas_list = 212;
414 CtrlMsg_Resp_GetStatus resp_stop_softap = 213;
415
416 CtrlMsg_Resp_SetMode resp_set_power_save_mode = 214;
417 CtrlMsg_Resp_GetMode resp_get_power_save_mode = 215;
418
419 CtrlMsg_Resp_OTABegin resp_ota_begin = 216;
420 CtrlMsg_Resp_OTAWrite resp_ota_write = 217;
421 CtrlMsg_Resp_OTAEnd resp_ota_end = 218;
422 CtrlMsg_Resp_SetWifiMaxTxPower resp_set_wifi_max_tx_power = 219;
423 CtrlMsg_Resp_GetWifiCurrTxPower resp_get_wifi_curr_tx_power = 220;
424 CtrlMsg_Resp_ConfigHeartbeat resp_config_heartbeat = 221;
425
426 /** Notifications **/
427 CtrlMsg_Event_ESPInit event_esp_init = 301;
428 CtrlMsg_Event_Heartbeat event_heartbeat = 302;
429 CtrlMsg_Event_StationDisconnectFromAP event_station_disconnect_from_AP = 303;
430 CtrlMsg_Event_StationDisconnectFromESPSoftAP event_station_disconnect_from_ESP_SoftAP = 304;
431 }
432}
diff --git a/embassy-net-esp-hosted/src/fmt.rs b/embassy-net-esp-hosted/src/fmt.rs
new file mode 100644
index 000000000..91984bde1
--- /dev/null
+++ b/embassy-net-esp-hosted/src/fmt.rs
@@ -0,0 +1,257 @@
1#![macro_use]
2#![allow(unused_macros)]
3
4use core::fmt::{Debug, Display, LowerHex};
5
6#[cfg(all(feature = "defmt", feature = "log"))]
7compile_error!("You may not enable both `defmt` and `log` features.");
8
9macro_rules! assert {
10 ($($x:tt)*) => {
11 {
12 #[cfg(not(feature = "defmt"))]
13 ::core::assert!($($x)*);
14 #[cfg(feature = "defmt")]
15 ::defmt::assert!($($x)*);
16 }
17 };
18}
19
20macro_rules! assert_eq {
21 ($($x:tt)*) => {
22 {
23 #[cfg(not(feature = "defmt"))]
24 ::core::assert_eq!($($x)*);
25 #[cfg(feature = "defmt")]
26 ::defmt::assert_eq!($($x)*);
27 }
28 };
29}
30
31macro_rules! assert_ne {
32 ($($x:tt)*) => {
33 {
34 #[cfg(not(feature = "defmt"))]
35 ::core::assert_ne!($($x)*);
36 #[cfg(feature = "defmt")]
37 ::defmt::assert_ne!($($x)*);
38 }
39 };
40}
41
42macro_rules! debug_assert {
43 ($($x:tt)*) => {
44 {
45 #[cfg(not(feature = "defmt"))]
46 ::core::debug_assert!($($x)*);
47 #[cfg(feature = "defmt")]
48 ::defmt::debug_assert!($($x)*);
49 }
50 };
51}
52
53macro_rules! debug_assert_eq {
54 ($($x:tt)*) => {
55 {
56 #[cfg(not(feature = "defmt"))]
57 ::core::debug_assert_eq!($($x)*);
58 #[cfg(feature = "defmt")]
59 ::defmt::debug_assert_eq!($($x)*);
60 }
61 };
62}
63
64macro_rules! debug_assert_ne {
65 ($($x:tt)*) => {
66 {
67 #[cfg(not(feature = "defmt"))]
68 ::core::debug_assert_ne!($($x)*);
69 #[cfg(feature = "defmt")]
70 ::defmt::debug_assert_ne!($($x)*);
71 }
72 };
73}
74
75macro_rules! todo {
76 ($($x:tt)*) => {
77 {
78 #[cfg(not(feature = "defmt"))]
79 ::core::todo!($($x)*);
80 #[cfg(feature = "defmt")]
81 ::defmt::todo!($($x)*);
82 }
83 };
84}
85
86#[cfg(not(feature = "defmt"))]
87macro_rules! unreachable {
88 ($($x:tt)*) => {
89 ::core::unreachable!($($x)*)
90 };
91}
92
93#[cfg(feature = "defmt")]
94macro_rules! unreachable {
95 ($($x:tt)*) => {
96 ::defmt::unreachable!($($x)*);
97 };
98}
99
100macro_rules! panic {
101 ($($x:tt)*) => {
102 {
103 #[cfg(not(feature = "defmt"))]
104 ::core::panic!($($x)*);
105 #[cfg(feature = "defmt")]
106 ::defmt::panic!($($x)*);
107 }
108 };
109}
110
111macro_rules! trace {
112 ($s:literal $(, $x:expr)* $(,)?) => {
113 {
114 #[cfg(feature = "log")]
115 ::log::trace!($s $(, $x)*);
116 #[cfg(feature = "defmt")]
117 ::defmt::trace!($s $(, $x)*);
118 #[cfg(not(any(feature = "log", feature="defmt")))]
119 let _ = ($( & $x ),*);
120 }
121 };
122}
123
124macro_rules! debug {
125 ($s:literal $(, $x:expr)* $(,)?) => {
126 {
127 #[cfg(feature = "log")]
128 ::log::debug!($s $(, $x)*);
129 #[cfg(feature = "defmt")]
130 ::defmt::debug!($s $(, $x)*);
131 #[cfg(not(any(feature = "log", feature="defmt")))]
132 let _ = ($( & $x ),*);
133 }
134 };
135}
136
137macro_rules! info {
138 ($s:literal $(, $x:expr)* $(,)?) => {
139 {
140 #[cfg(feature = "log")]
141 ::log::info!($s $(, $x)*);
142 #[cfg(feature = "defmt")]
143 ::defmt::info!($s $(, $x)*);
144 #[cfg(not(any(feature = "log", feature="defmt")))]
145 let _ = ($( & $x ),*);
146 }
147 };
148}
149
150macro_rules! warn {
151 ($s:literal $(, $x:expr)* $(,)?) => {
152 {
153 #[cfg(feature = "log")]
154 ::log::warn!($s $(, $x)*);
155 #[cfg(feature = "defmt")]
156 ::defmt::warn!($s $(, $x)*);
157 #[cfg(not(any(feature = "log", feature="defmt")))]
158 let _ = ($( & $x ),*);
159 }
160 };
161}
162
163macro_rules! error {
164 ($s:literal $(, $x:expr)* $(,)?) => {
165 {
166 #[cfg(feature = "log")]
167 ::log::error!($s $(, $x)*);
168 #[cfg(feature = "defmt")]
169 ::defmt::error!($s $(, $x)*);
170 #[cfg(not(any(feature = "log", feature="defmt")))]
171 let _ = ($( & $x ),*);
172 }
173 };
174}
175
176#[cfg(feature = "defmt")]
177macro_rules! unwrap {
178 ($($x:tt)*) => {
179 ::defmt::unwrap!($($x)*)
180 };
181}
182
183#[cfg(not(feature = "defmt"))]
184macro_rules! unwrap {
185 ($arg:expr) => {
186 match $crate::fmt::Try::into_result($arg) {
187 ::core::result::Result::Ok(t) => t,
188 ::core::result::Result::Err(e) => {
189 ::core::panic!("unwrap of `{}` failed: {:?}", ::core::stringify!($arg), e);
190 }
191 }
192 };
193 ($arg:expr, $($msg:expr),+ $(,)? ) => {
194 match $crate::fmt::Try::into_result($arg) {
195 ::core::result::Result::Ok(t) => t,
196 ::core::result::Result::Err(e) => {
197 ::core::panic!("unwrap of `{}` failed: {}: {:?}", ::core::stringify!($arg), ::core::format_args!($($msg,)*), e);
198 }
199 }
200 }
201}
202
203#[derive(Debug, Copy, Clone, Eq, PartialEq)]
204pub struct NoneError;
205
206pub trait Try {
207 type Ok;
208 type Error;
209 fn into_result(self) -> Result<Self::Ok, Self::Error>;
210}
211
212impl<T> Try for Option<T> {
213 type Ok = T;
214 type Error = NoneError;
215
216 #[inline]
217 fn into_result(self) -> Result<T, NoneError> {
218 self.ok_or(NoneError)
219 }
220}
221
222impl<T, E> Try for Result<T, E> {
223 type Ok = T;
224 type Error = E;
225
226 #[inline]
227 fn into_result(self) -> Self {
228 self
229 }
230}
231
232pub struct Bytes<'a>(pub &'a [u8]);
233
234impl<'a> Debug for Bytes<'a> {
235 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
236 write!(f, "{:#02x?}", self.0)
237 }
238}
239
240impl<'a> Display for Bytes<'a> {
241 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
242 write!(f, "{:#02x?}", self.0)
243 }
244}
245
246impl<'a> LowerHex for Bytes<'a> {
247 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
248 write!(f, "{:#02x?}", self.0)
249 }
250}
251
252#[cfg(feature = "defmt")]
253impl<'a> defmt::Format for Bytes<'a> {
254 fn format(&self, fmt: defmt::Formatter) {
255 defmt::write!(fmt, "{:02x}", self.0)
256 }
257}
diff --git a/embassy-net-esp-hosted/src/ioctl.rs b/embassy-net-esp-hosted/src/ioctl.rs
new file mode 100644
index 000000000..e2a6815aa
--- /dev/null
+++ b/embassy-net-esp-hosted/src/ioctl.rs
@@ -0,0 +1,123 @@
1use core::cell::RefCell;
2use core::future::poll_fn;
3use core::task::Poll;
4
5use embassy_sync::waitqueue::WakerRegistration;
6
7use crate::fmt::Bytes;
8
9#[derive(Clone, Copy)]
10pub struct PendingIoctl {
11 pub buf: *mut [u8],
12 pub req_len: usize,
13}
14
15#[derive(Clone, Copy)]
16enum IoctlState {
17 Pending(PendingIoctl),
18 Sent { buf: *mut [u8] },
19 Done { resp_len: usize },
20}
21
22pub struct Shared(RefCell<SharedInner>);
23
24struct SharedInner {
25 ioctl: IoctlState,
26 is_init: bool,
27 control_waker: WakerRegistration,
28 runner_waker: WakerRegistration,
29}
30
31impl Shared {
32 pub fn new() -> Self {
33 Self(RefCell::new(SharedInner {
34 ioctl: IoctlState::Done { resp_len: 0 },
35 is_init: false,
36 control_waker: WakerRegistration::new(),
37 runner_waker: WakerRegistration::new(),
38 }))
39 }
40
41 pub async fn ioctl_wait_complete(&self) -> usize {
42 poll_fn(|cx| {
43 let mut this = self.0.borrow_mut();
44 if let IoctlState::Done { resp_len } = this.ioctl {
45 Poll::Ready(resp_len)
46 } else {
47 this.control_waker.register(cx.waker());
48 Poll::Pending
49 }
50 })
51 .await
52 }
53
54 pub async fn ioctl_wait_pending(&self) -> PendingIoctl {
55 let pending = poll_fn(|cx| {
56 let mut this = self.0.borrow_mut();
57 if let IoctlState::Pending(pending) = this.ioctl {
58 Poll::Ready(pending)
59 } else {
60 this.runner_waker.register(cx.waker());
61 Poll::Pending
62 }
63 })
64 .await;
65
66 self.0.borrow_mut().ioctl = IoctlState::Sent { buf: pending.buf };
67 pending
68 }
69
70 pub fn ioctl_cancel(&self) {
71 self.0.borrow_mut().ioctl = IoctlState::Done { resp_len: 0 };
72 }
73
74 pub async fn ioctl(&self, buf: &mut [u8], req_len: usize) -> usize {
75 trace!("ioctl req bytes: {:02x}", Bytes(&buf[..req_len]));
76
77 {
78 let mut this = self.0.borrow_mut();
79 this.ioctl = IoctlState::Pending(PendingIoctl { buf, req_len });
80 this.runner_waker.wake();
81 }
82
83 self.ioctl_wait_complete().await
84 }
85
86 pub fn ioctl_done(&self, response: &[u8]) {
87 let mut this = self.0.borrow_mut();
88 if let IoctlState::Sent { buf } = this.ioctl {
89 trace!("ioctl resp bytes: {:02x}", Bytes(response));
90
91 // TODO fix this
92 (unsafe { &mut *buf }[..response.len()]).copy_from_slice(response);
93
94 this.ioctl = IoctlState::Done {
95 resp_len: response.len(),
96 };
97 this.control_waker.wake();
98 } else {
99 warn!("IOCTL Response but no pending Ioctl");
100 }
101 }
102
103 // // // // // // // // // // // // // // // // // // // //
104
105 pub fn init_done(&self) {
106 let mut this = self.0.borrow_mut();
107 this.is_init = true;
108 this.control_waker.wake();
109 }
110
111 pub async fn init_wait(&self) {
112 poll_fn(|cx| {
113 let mut this = self.0.borrow_mut();
114 if this.is_init {
115 Poll::Ready(())
116 } else {
117 this.control_waker.register(cx.waker());
118 Poll::Pending
119 }
120 })
121 .await
122 }
123}
diff --git a/embassy-net-esp-hosted/src/lib.rs b/embassy-net-esp-hosted/src/lib.rs
new file mode 100644
index 000000000..44dfbe89c
--- /dev/null
+++ b/embassy-net-esp-hosted/src/lib.rs
@@ -0,0 +1,337 @@
1#![no_std]
2
3use control::Control;
4use embassy_futures::select::{select3, Either3};
5use embassy_net_driver_channel as ch;
6use embassy_time::{Duration, Instant, Timer};
7use embedded_hal::digital::{InputPin, OutputPin};
8use embedded_hal_async::digital::Wait;
9use embedded_hal_async::spi::SpiDevice;
10use ioctl::Shared;
11use proto::CtrlMsg;
12
13use crate::ioctl::PendingIoctl;
14use crate::proto::CtrlMsgPayload;
15
16mod proto;
17
18// must be first
19mod fmt;
20
21mod control;
22mod ioctl;
23
24const MTU: usize = 1514;
25
26macro_rules! impl_bytes {
27 ($t:ident) => {
28 impl $t {
29 pub const SIZE: usize = core::mem::size_of::<Self>();
30
31 #[allow(unused)]
32 pub fn to_bytes(&self) -> [u8; Self::SIZE] {
33 unsafe { core::mem::transmute(*self) }
34 }
35
36 #[allow(unused)]
37 pub fn from_bytes(bytes: &[u8; Self::SIZE]) -> &Self {
38 let alignment = core::mem::align_of::<Self>();
39 assert_eq!(
40 bytes.as_ptr().align_offset(alignment),
41 0,
42 "{} is not aligned",
43 core::any::type_name::<Self>()
44 );
45 unsafe { core::mem::transmute(bytes) }
46 }
47
48 #[allow(unused)]
49 pub fn from_bytes_mut(bytes: &mut [u8; Self::SIZE]) -> &mut Self {
50 let alignment = core::mem::align_of::<Self>();
51 assert_eq!(
52 bytes.as_ptr().align_offset(alignment),
53 0,
54 "{} is not aligned",
55 core::any::type_name::<Self>()
56 );
57
58 unsafe { core::mem::transmute(bytes) }
59 }
60 }
61 };
62}
63
64#[repr(C, packed)]
65#[derive(Clone, Copy, Debug, Default)]
66struct PayloadHeader {
67 /// InterfaceType on lower 4 bits, number on higher 4 bits.
68 if_type_and_num: u8,
69
70 /// Flags.
71 ///
72 /// bit 0: more fragments.
73 flags: u8,
74
75 len: u16,
76 offset: u16,
77 checksum: u16,
78 seq_num: u16,
79 reserved2: u8,
80
81 /// Packet type for HCI or PRIV interface, reserved otherwise
82 hci_priv_packet_type: u8,
83}
84impl_bytes!(PayloadHeader);
85
86#[allow(unused)]
87#[repr(u8)]
88enum InterfaceType {
89 Sta = 0,
90 Ap = 1,
91 Serial = 2,
92 Hci = 3,
93 Priv = 4,
94 Test = 5,
95}
96
97const MAX_SPI_BUFFER_SIZE: usize = 1600;
98
99pub struct State {
100 shared: Shared,
101 ch: ch::State<MTU, 4, 4>,
102}
103
104impl State {
105 pub fn new() -> Self {
106 Self {
107 shared: Shared::new(),
108 ch: ch::State::new(),
109 }
110 }
111}
112
113pub type NetDriver<'a> = ch::Device<'a, MTU>;
114
115pub async fn new<'a, SPI, IN, OUT>(
116 state: &'a mut State,
117 spi: SPI,
118 handshake: IN,
119 ready: IN,
120 reset: OUT,
121) -> (NetDriver<'a>, Control<'a>, Runner<'a, SPI, IN, OUT>)
122where
123 SPI: SpiDevice,
124 IN: InputPin + Wait,
125 OUT: OutputPin,
126{
127 let (ch_runner, device) = ch::new(&mut state.ch, [0; 6]);
128 let state_ch = ch_runner.state_runner();
129
130 let mut runner = Runner {
131 ch: ch_runner,
132 shared: &state.shared,
133 next_seq: 1,
134 handshake,
135 ready,
136 reset,
137 spi,
138 };
139 runner.init().await;
140
141 (device, Control::new(state_ch, &state.shared), runner)
142}
143
144pub struct Runner<'a, SPI, IN, OUT> {
145 ch: ch::Runner<'a, MTU>,
146 shared: &'a Shared,
147
148 next_seq: u16,
149
150 spi: SPI,
151 handshake: IN,
152 ready: IN,
153 reset: OUT,
154}
155
156impl<'a, SPI, IN, OUT> Runner<'a, SPI, IN, OUT>
157where
158 SPI: SpiDevice,
159 IN: InputPin + Wait,
160 OUT: OutputPin,
161{
162 async fn init(&mut self) {}
163
164 pub async fn run(mut self) -> ! {
165 debug!("resetting...");
166 self.reset.set_low().unwrap();
167 Timer::after(Duration::from_millis(100)).await;
168 self.reset.set_high().unwrap();
169 Timer::after(Duration::from_millis(1000)).await;
170
171 let mut tx_buf = [0u8; MAX_SPI_BUFFER_SIZE];
172 let mut rx_buf = [0u8; MAX_SPI_BUFFER_SIZE];
173
174 loop {
175 self.handshake.wait_for_high().await.unwrap();
176
177 let ioctl = self.shared.ioctl_wait_pending();
178 let tx = self.ch.tx_buf();
179 let ev = async { self.ready.wait_for_high().await.unwrap() };
180
181 match select3(ioctl, tx, ev).await {
182 Either3::First(PendingIoctl { buf, req_len }) => {
183 tx_buf[12..24].copy_from_slice(b"\x01\x08\x00ctrlResp\x02");
184 tx_buf[24..26].copy_from_slice(&(req_len as u16).to_le_bytes());
185 tx_buf[26..][..req_len].copy_from_slice(&unsafe { &*buf }[..req_len]);
186
187 let mut header = PayloadHeader {
188 if_type_and_num: InterfaceType::Serial as _,
189 len: (req_len + 14) as _,
190 offset: PayloadHeader::SIZE as _,
191 seq_num: self.next_seq,
192 ..Default::default()
193 };
194 self.next_seq = self.next_seq.wrapping_add(1);
195
196 // Calculate checksum
197 tx_buf[0..12].copy_from_slice(&header.to_bytes());
198 header.checksum = checksum(&tx_buf[..26 + req_len]);
199 tx_buf[0..12].copy_from_slice(&header.to_bytes());
200 }
201 Either3::Second(packet) => {
202 tx_buf[12..][..packet.len()].copy_from_slice(packet);
203
204 let mut header = PayloadHeader {
205 if_type_and_num: InterfaceType::Sta as _,
206 len: packet.len() as _,
207 offset: PayloadHeader::SIZE as _,
208 seq_num: self.next_seq,
209 ..Default::default()
210 };
211 self.next_seq = self.next_seq.wrapping_add(1);
212
213 // Calculate checksum
214 tx_buf[0..12].copy_from_slice(&header.to_bytes());
215 header.checksum = checksum(&tx_buf[..12 + packet.len()]);
216 tx_buf[0..12].copy_from_slice(&header.to_bytes());
217
218 self.ch.tx_done();
219 }
220 Either3::Third(()) => {
221 tx_buf[..PayloadHeader::SIZE].fill(0);
222 }
223 }
224
225 if tx_buf[0] != 0 {
226 trace!("tx: {:02x}", &tx_buf[..40]);
227 }
228
229 self.spi.transfer(&mut rx_buf, &tx_buf).await.unwrap();
230
231 // The esp-hosted firmware deasserts the HANSHAKE pin a few us AFTER ending the SPI transfer
232 // If we check it again too fast, we'll see it's high from the previous transfer, and if we send it
233 // data it will get lost.
234 // Make sure we check it after 100us at minimum.
235 let delay_until = Instant::now() + Duration::from_micros(100);
236 self.handle_rx(&mut rx_buf);
237 Timer::at(delay_until).await;
238 }
239 }
240
241 fn handle_rx(&mut self, buf: &mut [u8]) {
242 trace!("rx: {:02x}", &buf[..40]);
243
244 let buf_len = buf.len();
245 let h = PayloadHeader::from_bytes_mut((&mut buf[..PayloadHeader::SIZE]).try_into().unwrap());
246
247 if h.len == 0 || h.offset as usize != PayloadHeader::SIZE {
248 return;
249 }
250
251 let payload_len = h.len as usize;
252 if buf_len < PayloadHeader::SIZE + payload_len {
253 warn!("rx: len too big");
254 return;
255 }
256
257 let if_type_and_num = h.if_type_and_num;
258 let want_checksum = h.checksum;
259 h.checksum = 0;
260 let got_checksum = checksum(&buf[..PayloadHeader::SIZE + payload_len]);
261 if want_checksum != got_checksum {
262 warn!("rx: bad checksum. Got {:04x}, want {:04x}", got_checksum, want_checksum);
263 return;
264 }
265
266 let payload = &mut buf[PayloadHeader::SIZE..][..payload_len];
267
268 match if_type_and_num & 0x0f {
269 // STA
270 0 => match self.ch.try_rx_buf() {
271 Some(buf) => {
272 buf[..payload.len()].copy_from_slice(payload);
273 self.ch.rx_done(payload.len())
274 }
275 None => warn!("failed to push rxd packet to the channel."),
276 },
277 // serial
278 2 => {
279 trace!("serial rx: {:02x}", payload);
280 if payload.len() < 14 {
281 warn!("serial rx: too short");
282 return;
283 }
284
285 let is_event = match &payload[..12] {
286 b"\x01\x08\x00ctrlResp\x02" => false,
287 b"\x01\x08\x00ctrlEvnt\x02" => true,
288 _ => {
289 warn!("serial rx: bad tlv");
290 return;
291 }
292 };
293
294 let len = u16::from_le_bytes(payload[12..14].try_into().unwrap()) as usize;
295 if payload.len() < 14 + len {
296 warn!("serial rx: too short 2");
297 return;
298 }
299 let data = &payload[14..][..len];
300
301 if is_event {
302 self.handle_event(data);
303 } else {
304 self.shared.ioctl_done(data);
305 }
306 }
307 _ => warn!("unknown iftype {}", if_type_and_num),
308 }
309 }
310
311 fn handle_event(&self, data: &[u8]) {
312 let Ok(event) = noproto::read::<CtrlMsg>(data) else {
313 warn!("failed to parse event");
314 return
315 };
316
317 debug!("event: {:?}", &event);
318
319 let Some(payload) = &event.payload else {
320 warn!("event without payload?");
321 return
322 };
323
324 match payload {
325 CtrlMsgPayload::EventEspInit(_) => self.shared.init_done(),
326 _ => {}
327 }
328 }
329}
330
331fn checksum(buf: &[u8]) -> u16 {
332 let mut res = 0u16;
333 for &b in buf {
334 res = res.wrapping_add(b as _);
335 }
336 res
337}
diff --git a/embassy-net-esp-hosted/src/proto.rs b/embassy-net-esp-hosted/src/proto.rs
new file mode 100644
index 000000000..8ceb1579d
--- /dev/null
+++ b/embassy-net-esp-hosted/src/proto.rs
@@ -0,0 +1,652 @@
1use heapless::{String, Vec};
2
3/// internal supporting structures for CtrlMsg
4
5#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
6#[cfg_attr(feature = "defmt", derive(defmt::Format))]
7pub struct ScanResult {
8 #[noproto(tag = "1")]
9 pub ssid: String<32>,
10 #[noproto(tag = "2")]
11 pub chnl: u32,
12 #[noproto(tag = "3")]
13 pub rssi: u32,
14 #[noproto(tag = "4")]
15 pub bssid: String<32>,
16 #[noproto(tag = "5")]
17 pub sec_prot: CtrlWifiSecProt,
18}
19
20#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
21#[cfg_attr(feature = "defmt", derive(defmt::Format))]
22pub struct ConnectedStaList {
23 #[noproto(tag = "1")]
24 pub mac: String<32>,
25 #[noproto(tag = "2")]
26 pub rssi: u32,
27}
28/// * Req/Resp structure *
29
30#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
31#[cfg_attr(feature = "defmt", derive(defmt::Format))]
32pub struct CtrlMsgReqGetMacAddress {
33 #[noproto(tag = "1")]
34 pub mode: u32,
35}
36
37#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
38#[cfg_attr(feature = "defmt", derive(defmt::Format))]
39pub struct CtrlMsgRespGetMacAddress {
40 #[noproto(tag = "1")]
41 pub mac: String<32>,
42 #[noproto(tag = "2")]
43 pub resp: u32,
44}
45
46#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
47#[cfg_attr(feature = "defmt", derive(defmt::Format))]
48pub struct CtrlMsgReqGetMode {}
49
50#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
51#[cfg_attr(feature = "defmt", derive(defmt::Format))]
52pub struct CtrlMsgRespGetMode {
53 #[noproto(tag = "1")]
54 pub mode: u32,
55 #[noproto(tag = "2")]
56 pub resp: u32,
57}
58
59#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
60#[cfg_attr(feature = "defmt", derive(defmt::Format))]
61pub struct CtrlMsgReqSetMode {
62 #[noproto(tag = "1")]
63 pub mode: u32,
64}
65
66#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
67#[cfg_attr(feature = "defmt", derive(defmt::Format))]
68pub struct CtrlMsgRespSetMode {
69 #[noproto(tag = "1")]
70 pub resp: u32,
71}
72
73#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
74#[cfg_attr(feature = "defmt", derive(defmt::Format))]
75pub struct CtrlMsgReqGetStatus {}
76
77#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
78#[cfg_attr(feature = "defmt", derive(defmt::Format))]
79pub struct CtrlMsgRespGetStatus {
80 #[noproto(tag = "1")]
81 pub resp: u32,
82}
83
84#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
85#[cfg_attr(feature = "defmt", derive(defmt::Format))]
86pub struct CtrlMsgReqSetMacAddress {
87 #[noproto(tag = "1")]
88 pub mac: String<32>,
89 #[noproto(tag = "2")]
90 pub mode: u32,
91}
92
93#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
94#[cfg_attr(feature = "defmt", derive(defmt::Format))]
95pub struct CtrlMsgRespSetMacAddress {
96 #[noproto(tag = "1")]
97 pub resp: u32,
98}
99
100#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
101#[cfg_attr(feature = "defmt", derive(defmt::Format))]
102pub struct CtrlMsgReqGetApConfig {}
103
104#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
105#[cfg_attr(feature = "defmt", derive(defmt::Format))]
106pub struct CtrlMsgRespGetApConfig {
107 #[noproto(tag = "1")]
108 pub ssid: String<32>,
109 #[noproto(tag = "2")]
110 pub bssid: String<32>,
111 #[noproto(tag = "3")]
112 pub rssi: u32,
113 #[noproto(tag = "4")]
114 pub chnl: u32,
115 #[noproto(tag = "5")]
116 pub sec_prot: CtrlWifiSecProt,
117 #[noproto(tag = "6")]
118 pub resp: u32,
119}
120
121#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
122#[cfg_attr(feature = "defmt", derive(defmt::Format))]
123pub struct CtrlMsgReqConnectAp {
124 #[noproto(tag = "1")]
125 pub ssid: String<32>,
126 #[noproto(tag = "2")]
127 pub pwd: String<32>,
128 #[noproto(tag = "3")]
129 pub bssid: String<32>,
130 #[noproto(tag = "4")]
131 pub is_wpa3_supported: bool,
132 #[noproto(tag = "5")]
133 pub listen_interval: u32,
134}
135
136#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
137#[cfg_attr(feature = "defmt", derive(defmt::Format))]
138pub struct CtrlMsgRespConnectAp {
139 #[noproto(tag = "1")]
140 pub resp: u32,
141 #[noproto(tag = "2")]
142 pub mac: String<32>,
143}
144
145#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
146#[cfg_attr(feature = "defmt", derive(defmt::Format))]
147pub struct CtrlMsgReqGetSoftApConfig {}
148
149#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
150#[cfg_attr(feature = "defmt", derive(defmt::Format))]
151pub struct CtrlMsgRespGetSoftApConfig {
152 #[noproto(tag = "1")]
153 pub ssid: String<32>,
154 #[noproto(tag = "2")]
155 pub pwd: String<32>,
156 #[noproto(tag = "3")]
157 pub chnl: u32,
158 #[noproto(tag = "4")]
159 pub sec_prot: CtrlWifiSecProt,
160 #[noproto(tag = "5")]
161 pub max_conn: u32,
162 #[noproto(tag = "6")]
163 pub ssid_hidden: bool,
164 #[noproto(tag = "7")]
165 pub bw: u32,
166 #[noproto(tag = "8")]
167 pub resp: u32,
168}
169
170#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
171#[cfg_attr(feature = "defmt", derive(defmt::Format))]
172pub struct CtrlMsgReqStartSoftAp {
173 #[noproto(tag = "1")]
174 pub ssid: String<32>,
175 #[noproto(tag = "2")]
176 pub pwd: String<32>,
177 #[noproto(tag = "3")]
178 pub chnl: u32,
179 #[noproto(tag = "4")]
180 pub sec_prot: CtrlWifiSecProt,
181 #[noproto(tag = "5")]
182 pub max_conn: u32,
183 #[noproto(tag = "6")]
184 pub ssid_hidden: bool,
185 #[noproto(tag = "7")]
186 pub bw: u32,
187}
188
189#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
190#[cfg_attr(feature = "defmt", derive(defmt::Format))]
191pub struct CtrlMsgRespStartSoftAp {
192 #[noproto(tag = "1")]
193 pub resp: u32,
194 #[noproto(tag = "2")]
195 pub mac: String<32>,
196}
197
198#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
199#[cfg_attr(feature = "defmt", derive(defmt::Format))]
200pub struct CtrlMsgReqScanResult {}
201
202#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
203#[cfg_attr(feature = "defmt", derive(defmt::Format))]
204pub struct CtrlMsgRespScanResult {
205 #[noproto(tag = "1")]
206 pub count: u32,
207 #[noproto(repeated, tag = "2")]
208 pub entries: Vec<ScanResult, 16>,
209 #[noproto(tag = "3")]
210 pub resp: u32,
211}
212
213#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
214#[cfg_attr(feature = "defmt", derive(defmt::Format))]
215pub struct CtrlMsgReqSoftApConnectedSta {}
216
217#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
218#[cfg_attr(feature = "defmt", derive(defmt::Format))]
219pub struct CtrlMsgRespSoftApConnectedSta {
220 #[noproto(tag = "1")]
221 pub num: u32,
222 #[noproto(repeated, tag = "2")]
223 pub stations: Vec<ConnectedStaList, 16>,
224 #[noproto(tag = "3")]
225 pub resp: u32,
226}
227
228#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
229#[cfg_attr(feature = "defmt", derive(defmt::Format))]
230pub struct CtrlMsgReqOtaBegin {}
231
232#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
233#[cfg_attr(feature = "defmt", derive(defmt::Format))]
234pub struct CtrlMsgRespOtaBegin {
235 #[noproto(tag = "1")]
236 pub resp: u32,
237}
238
239#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
240#[cfg_attr(feature = "defmt", derive(defmt::Format))]
241pub struct CtrlMsgReqOtaWrite {
242 #[noproto(tag = "1")]
243 pub ota_data: Vec<u8, 1024>,
244}
245
246#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
247#[cfg_attr(feature = "defmt", derive(defmt::Format))]
248pub struct CtrlMsgRespOtaWrite {
249 #[noproto(tag = "1")]
250 pub resp: u32,
251}
252
253#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
254#[cfg_attr(feature = "defmt", derive(defmt::Format))]
255pub struct CtrlMsgReqOtaEnd {}
256
257#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
258#[cfg_attr(feature = "defmt", derive(defmt::Format))]
259pub struct CtrlMsgRespOtaEnd {
260 #[noproto(tag = "1")]
261 pub resp: u32,
262}
263
264#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
265#[cfg_attr(feature = "defmt", derive(defmt::Format))]
266pub struct CtrlMsgReqVendorIeData {
267 #[noproto(tag = "1")]
268 pub element_id: u32,
269 #[noproto(tag = "2")]
270 pub length: u32,
271 #[noproto(tag = "3")]
272 pub vendor_oui: Vec<u8, 8>,
273 #[noproto(tag = "4")]
274 pub vendor_oui_type: u32,
275 #[noproto(tag = "5")]
276 pub payload: Vec<u8, 64>,
277}
278
279#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
280#[cfg_attr(feature = "defmt", derive(defmt::Format))]
281pub struct CtrlMsgReqSetSoftApVendorSpecificIe {
282 #[noproto(tag = "1")]
283 pub enable: bool,
284 #[noproto(tag = "2")]
285 pub r#type: CtrlVendorIeType,
286 #[noproto(tag = "3")]
287 pub idx: CtrlVendorIeid,
288 #[noproto(optional, tag = "4")]
289 pub vendor_ie_data: Option<CtrlMsgReqVendorIeData>,
290}
291
292#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
293#[cfg_attr(feature = "defmt", derive(defmt::Format))]
294pub struct CtrlMsgRespSetSoftApVendorSpecificIe {
295 #[noproto(tag = "1")]
296 pub resp: u32,
297}
298
299#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
300#[cfg_attr(feature = "defmt", derive(defmt::Format))]
301pub struct CtrlMsgReqSetWifiMaxTxPower {
302 #[noproto(tag = "1")]
303 pub wifi_max_tx_power: u32,
304}
305
306#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
307#[cfg_attr(feature = "defmt", derive(defmt::Format))]
308pub struct CtrlMsgRespSetWifiMaxTxPower {
309 #[noproto(tag = "1")]
310 pub resp: u32,
311}
312
313#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
314#[cfg_attr(feature = "defmt", derive(defmt::Format))]
315pub struct CtrlMsgReqGetWifiCurrTxPower {}
316
317#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
318#[cfg_attr(feature = "defmt", derive(defmt::Format))]
319pub struct CtrlMsgRespGetWifiCurrTxPower {
320 #[noproto(tag = "1")]
321 pub wifi_curr_tx_power: u32,
322 #[noproto(tag = "2")]
323 pub resp: u32,
324}
325
326#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
327#[cfg_attr(feature = "defmt", derive(defmt::Format))]
328pub struct CtrlMsgReqConfigHeartbeat {
329 #[noproto(tag = "1")]
330 pub enable: bool,
331 #[noproto(tag = "2")]
332 pub duration: u32,
333}
334
335#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
336#[cfg_attr(feature = "defmt", derive(defmt::Format))]
337pub struct CtrlMsgRespConfigHeartbeat {
338 #[noproto(tag = "1")]
339 pub resp: u32,
340}
341/// * Event structure *
342
343#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
344#[cfg_attr(feature = "defmt", derive(defmt::Format))]
345pub struct CtrlMsgEventEspInit {
346 #[noproto(tag = "1")]
347 pub init_data: Vec<u8, 64>,
348}
349
350#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
351#[cfg_attr(feature = "defmt", derive(defmt::Format))]
352pub struct CtrlMsgEventHeartbeat {
353 #[noproto(tag = "1")]
354 pub hb_num: u32,
355}
356
357#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
358#[cfg_attr(feature = "defmt", derive(defmt::Format))]
359pub struct CtrlMsgEventStationDisconnectFromAp {
360 #[noproto(tag = "1")]
361 pub resp: u32,
362}
363
364#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
365#[cfg_attr(feature = "defmt", derive(defmt::Format))]
366pub struct CtrlMsgEventStationDisconnectFromEspSoftAp {
367 #[noproto(tag = "1")]
368 pub resp: u32,
369 #[noproto(tag = "2")]
370 pub mac: String<32>,
371}
372
373#[derive(Debug, Default, Clone, Eq, PartialEq, noproto::Message)]
374#[cfg_attr(feature = "defmt", derive(defmt::Format))]
375pub struct CtrlMsg {
376 /// msg_type could be req, resp or Event
377 #[noproto(tag = "1")]
378 pub msg_type: CtrlMsgType,
379 /// msg id
380 #[noproto(tag = "2")]
381 pub msg_id: CtrlMsgId,
382 /// union of all msg ids
383 #[noproto(
384 oneof,
385 tags = "101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 301, 302, 303, 304"
386 )]
387 pub payload: Option<CtrlMsgPayload>,
388}
389
390/// union of all msg ids
391#[derive(Debug, Clone, Eq, PartialEq, noproto::Oneof)]
392#[cfg_attr(feature = "defmt", derive(defmt::Format))]
393pub enum CtrlMsgPayload {
394 /// * Requests *
395 #[noproto(tag = "101")]
396 ReqGetMacAddress(CtrlMsgReqGetMacAddress),
397 #[noproto(tag = "102")]
398 ReqSetMacAddress(CtrlMsgReqSetMacAddress),
399 #[noproto(tag = "103")]
400 ReqGetWifiMode(CtrlMsgReqGetMode),
401 #[noproto(tag = "104")]
402 ReqSetWifiMode(CtrlMsgReqSetMode),
403 #[noproto(tag = "105")]
404 ReqScanApList(CtrlMsgReqScanResult),
405 #[noproto(tag = "106")]
406 ReqGetApConfig(CtrlMsgReqGetApConfig),
407 #[noproto(tag = "107")]
408 ReqConnectAp(CtrlMsgReqConnectAp),
409 #[noproto(tag = "108")]
410 ReqDisconnectAp(CtrlMsgReqGetStatus),
411 #[noproto(tag = "109")]
412 ReqGetSoftapConfig(CtrlMsgReqGetSoftApConfig),
413 #[noproto(tag = "110")]
414 ReqSetSoftapVendorSpecificIe(CtrlMsgReqSetSoftApVendorSpecificIe),
415 #[noproto(tag = "111")]
416 ReqStartSoftap(CtrlMsgReqStartSoftAp),
417 #[noproto(tag = "112")]
418 ReqSoftapConnectedStasList(CtrlMsgReqSoftApConnectedSta),
419 #[noproto(tag = "113")]
420 ReqStopSoftap(CtrlMsgReqGetStatus),
421 #[noproto(tag = "114")]
422 ReqSetPowerSaveMode(CtrlMsgReqSetMode),
423 #[noproto(tag = "115")]
424 ReqGetPowerSaveMode(CtrlMsgReqGetMode),
425 #[noproto(tag = "116")]
426 ReqOtaBegin(CtrlMsgReqOtaBegin),
427 #[noproto(tag = "117")]
428 ReqOtaWrite(CtrlMsgReqOtaWrite),
429 #[noproto(tag = "118")]
430 ReqOtaEnd(CtrlMsgReqOtaEnd),
431 #[noproto(tag = "119")]
432 ReqSetWifiMaxTxPower(CtrlMsgReqSetWifiMaxTxPower),
433 #[noproto(tag = "120")]
434 ReqGetWifiCurrTxPower(CtrlMsgReqGetWifiCurrTxPower),
435 #[noproto(tag = "121")]
436 ReqConfigHeartbeat(CtrlMsgReqConfigHeartbeat),
437 /// * Responses *
438 #[noproto(tag = "201")]
439 RespGetMacAddress(CtrlMsgRespGetMacAddress),
440 #[noproto(tag = "202")]
441 RespSetMacAddress(CtrlMsgRespSetMacAddress),
442 #[noproto(tag = "203")]
443 RespGetWifiMode(CtrlMsgRespGetMode),
444 #[noproto(tag = "204")]
445 RespSetWifiMode(CtrlMsgRespSetMode),
446 #[noproto(tag = "205")]
447 RespScanApList(CtrlMsgRespScanResult),
448 #[noproto(tag = "206")]
449 RespGetApConfig(CtrlMsgRespGetApConfig),
450 #[noproto(tag = "207")]
451 RespConnectAp(CtrlMsgRespConnectAp),
452 #[noproto(tag = "208")]
453 RespDisconnectAp(CtrlMsgRespGetStatus),
454 #[noproto(tag = "209")]
455 RespGetSoftapConfig(CtrlMsgRespGetSoftApConfig),
456 #[noproto(tag = "210")]
457 RespSetSoftapVendorSpecificIe(CtrlMsgRespSetSoftApVendorSpecificIe),
458 #[noproto(tag = "211")]
459 RespStartSoftap(CtrlMsgRespStartSoftAp),
460 #[noproto(tag = "212")]
461 RespSoftapConnectedStasList(CtrlMsgRespSoftApConnectedSta),
462 #[noproto(tag = "213")]
463 RespStopSoftap(CtrlMsgRespGetStatus),
464 #[noproto(tag = "214")]
465 RespSetPowerSaveMode(CtrlMsgRespSetMode),
466 #[noproto(tag = "215")]
467 RespGetPowerSaveMode(CtrlMsgRespGetMode),
468 #[noproto(tag = "216")]
469 RespOtaBegin(CtrlMsgRespOtaBegin),
470 #[noproto(tag = "217")]
471 RespOtaWrite(CtrlMsgRespOtaWrite),
472 #[noproto(tag = "218")]
473 RespOtaEnd(CtrlMsgRespOtaEnd),
474 #[noproto(tag = "219")]
475 RespSetWifiMaxTxPower(CtrlMsgRespSetWifiMaxTxPower),
476 #[noproto(tag = "220")]
477 RespGetWifiCurrTxPower(CtrlMsgRespGetWifiCurrTxPower),
478 #[noproto(tag = "221")]
479 RespConfigHeartbeat(CtrlMsgRespConfigHeartbeat),
480 /// * Notifications *
481 #[noproto(tag = "301")]
482 EventEspInit(CtrlMsgEventEspInit),
483 #[noproto(tag = "302")]
484 EventHeartbeat(CtrlMsgEventHeartbeat),
485 #[noproto(tag = "303")]
486 EventStationDisconnectFromAp(CtrlMsgEventStationDisconnectFromAp),
487 #[noproto(tag = "304")]
488 EventStationDisconnectFromEspSoftAp(CtrlMsgEventStationDisconnectFromEspSoftAp),
489}
490
491/// Enums similar to ESP IDF
492#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord, noproto::Enumeration)]
493#[repr(u32)]
494#[cfg_attr(feature = "defmt", derive(defmt::Format))]
495pub enum CtrlVendorIeType {
496 #[default]
497 Beacon = 0,
498 ProbeReq = 1,
499 ProbeResp = 2,
500 AssocReq = 3,
501 AssocResp = 4,
502}
503
504#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord, noproto::Enumeration)]
505#[repr(u32)]
506#[cfg_attr(feature = "defmt", derive(defmt::Format))]
507pub enum CtrlVendorIeid {
508 #[default]
509 Id0 = 0,
510 Id1 = 1,
511}
512
513#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord, noproto::Enumeration)]
514#[repr(u32)]
515#[cfg_attr(feature = "defmt", derive(defmt::Format))]
516pub enum CtrlWifiMode {
517 #[default]
518 None = 0,
519 Sta = 1,
520 Ap = 2,
521 Apsta = 3,
522}
523
524#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord, noproto::Enumeration)]
525#[repr(u32)]
526#[cfg_attr(feature = "defmt", derive(defmt::Format))]
527pub enum CtrlWifiBw {
528 #[default]
529 BwInvalid = 0,
530 Ht20 = 1,
531 Ht40 = 2,
532}
533
534#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord, noproto::Enumeration)]
535#[repr(u32)]
536#[cfg_attr(feature = "defmt", derive(defmt::Format))]
537pub enum CtrlWifiPowerSave {
538 #[default]
539 PsInvalid = 0,
540 MinModem = 1,
541 MaxModem = 2,
542}
543
544#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord, noproto::Enumeration)]
545#[repr(u32)]
546#[cfg_attr(feature = "defmt", derive(defmt::Format))]
547pub enum CtrlWifiSecProt {
548 #[default]
549 Open = 0,
550 Wep = 1,
551 WpaPsk = 2,
552 Wpa2Psk = 3,
553 WpaWpa2Psk = 4,
554 Wpa2Enterprise = 5,
555 Wpa3Psk = 6,
556 Wpa2Wpa3Psk = 7,
557}
558
559/// enums for Control path
560#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord, noproto::Enumeration)]
561#[repr(u32)]
562#[cfg_attr(feature = "defmt", derive(defmt::Format))]
563pub enum CtrlStatus {
564 #[default]
565 Connected = 0,
566 NotConnected = 1,
567 NoApFound = 2,
568 ConnectionFail = 3,
569 InvalidArgument = 4,
570 OutOfRange = 5,
571}
572
573#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord, noproto::Enumeration)]
574#[repr(u32)]
575#[cfg_attr(feature = "defmt", derive(defmt::Format))]
576pub enum CtrlMsgType {
577 #[default]
578 MsgTypeInvalid = 0,
579 Req = 1,
580 Resp = 2,
581 Event = 3,
582 MsgTypeMax = 4,
583}
584
585#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord, noproto::Enumeration)]
586#[repr(u32)]
587#[cfg_attr(feature = "defmt", derive(defmt::Format))]
588pub enum CtrlMsgId {
589 #[default]
590 MsgIdInvalid = 0,
591 /// * Request Msgs *
592 ReqBase = 100,
593 ReqGetMacAddress = 101,
594 ReqSetMacAddress = 102,
595 ReqGetWifiMode = 103,
596 ReqSetWifiMode = 104,
597 ReqGetApScanList = 105,
598 ReqGetApConfig = 106,
599 ReqConnectAp = 107,
600 ReqDisconnectAp = 108,
601 ReqGetSoftApConfig = 109,
602 ReqSetSoftApVendorSpecificIe = 110,
603 ReqStartSoftAp = 111,
604 ReqGetSoftApConnectedStaList = 112,
605 ReqStopSoftAp = 113,
606 ReqSetPowerSaveMode = 114,
607 ReqGetPowerSaveMode = 115,
608 ReqOtaBegin = 116,
609 ReqOtaWrite = 117,
610 ReqOtaEnd = 118,
611 ReqSetWifiMaxTxPower = 119,
612 ReqGetWifiCurrTxPower = 120,
613 ReqConfigHeartbeat = 121,
614 /// Add new control path command response before Req_Max
615 /// and update Req_Max
616 ReqMax = 122,
617 /// * Response Msgs *
618 RespBase = 200,
619 RespGetMacAddress = 201,
620 RespSetMacAddress = 202,
621 RespGetWifiMode = 203,
622 RespSetWifiMode = 204,
623 RespGetApScanList = 205,
624 RespGetApConfig = 206,
625 RespConnectAp = 207,
626 RespDisconnectAp = 208,
627 RespGetSoftApConfig = 209,
628 RespSetSoftApVendorSpecificIe = 210,
629 RespStartSoftAp = 211,
630 RespGetSoftApConnectedStaList = 212,
631 RespStopSoftAp = 213,
632 RespSetPowerSaveMode = 214,
633 RespGetPowerSaveMode = 215,
634 RespOtaBegin = 216,
635 RespOtaWrite = 217,
636 RespOtaEnd = 218,
637 RespSetWifiMaxTxPower = 219,
638 RespGetWifiCurrTxPower = 220,
639 RespConfigHeartbeat = 221,
640 /// Add new control path command response before Resp_Max
641 /// and update Resp_Max
642 RespMax = 222,
643 /// * Event Msgs *
644 EventBase = 300,
645 EventEspInit = 301,
646 EventHeartbeat = 302,
647 EventStationDisconnectFromAp = 303,
648 EventStationDisconnectFromEspSoftAp = 304,
649 /// Add new control path command notification before Event_Max
650 /// and update Event_Max
651 EventMax = 305,
652}
diff --git a/examples/nrf52840/Cargo.toml b/examples/nrf52840/Cargo.toml
index 6627b7861..8c4175966 100644
--- a/examples/nrf52840/Cargo.toml
+++ b/examples/nrf52840/Cargo.toml
@@ -6,8 +6,24 @@ license = "MIT OR Apache-2.0"
6 6
7[features] 7[features]
8default = ["nightly"] 8default = ["nightly"]
9nightly = ["embassy-executor/nightly", "embassy-nrf/nightly", "embassy-net/nightly", "embassy-nrf/unstable-traits", "embassy-time/nightly", "embassy-time/unstable-traits", "static_cell/nightly", 9nightly = [
10 "embassy-usb", "embedded-io/async", "embassy-net", "embassy-lora", "lora-phy", "lorawan-device", "lorawan"] 10 "embedded-hal-async",
11 "embassy-executor/nightly",
12 "embassy-nrf/nightly",
13 "embassy-net/nightly",
14 "embassy-net-esp-hosted",
15 "embassy-nrf/unstable-traits",
16 "embassy-time/nightly",
17 "embassy-time/unstable-traits",
18 "static_cell/nightly",
19 "embassy-usb",
20 "embedded-io/async",
21 "embassy-net",
22 "embassy-lora",
23 "lora-phy",
24 "lorawan-device",
25 "lorawan",
26]
11 27
12[dependencies] 28[dependencies]
13embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } 29embassy-futures = { version = "0.1.0", path = "../../embassy-futures" }
@@ -22,6 +38,7 @@ embassy-lora = { version = "0.1.0", path = "../../embassy-lora", features = ["ti
22lora-phy = { version = "1", optional = true } 38lora-phy = { version = "1", optional = true }
23lorawan-device = { version = "0.10.0", default-features = false, features = ["async", "external-lora-phy"], optional = true } 39lorawan-device = { version = "0.10.0", default-features = false, features = ["async", "external-lora-phy"], optional = true }
24lorawan = { version = "0.7.3", default-features = false, features = ["default-crypto"], optional = true } 40lorawan = { version = "0.7.3", default-features = false, features = ["default-crypto"], optional = true }
41embassy-net-esp-hosted = { version = "0.1.0", path = "../../embassy-net-esp-hosted", features = ["defmt"], optional = true }
25 42
26defmt = "0.3" 43defmt = "0.3"
27defmt-rtt = "0.4" 44defmt-rtt = "0.4"
@@ -35,3 +52,4 @@ rand = { version = "0.8.4", default-features = false }
35embedded-storage = "0.3.0" 52embedded-storage = "0.3.0"
36usbd-hid = "0.6.0" 53usbd-hid = "0.6.0"
37serde = { version = "1.0.136", default-features = false } 54serde = { version = "1.0.136", default-features = false }
55embedded-hal-async = { version = "0.2.0-alpha.1", optional = true }
diff --git a/examples/nrf52840/src/bin/wifi_esp_hosted.rs b/examples/nrf52840/src/bin/wifi_esp_hosted.rs
new file mode 100644
index 000000000..4eb31b105
--- /dev/null
+++ b/examples/nrf52840/src/bin/wifi_esp_hosted.rs
@@ -0,0 +1,139 @@
1#![no_std]
2#![no_main]
3#![feature(type_alias_impl_trait)]
4
5use defmt::{info, unwrap, warn};
6use embassy_executor::Spawner;
7use embassy_net::tcp::TcpSocket;
8use embassy_net::{Stack, StackResources};
9use embassy_nrf::gpio::{AnyPin, Input, Level, Output, OutputDrive, Pin, Pull};
10use embassy_nrf::rng::Rng;
11use embassy_nrf::spim::{self, Spim};
12use embassy_nrf::{bind_interrupts, peripherals};
13use embedded_hal_async::spi::ExclusiveDevice;
14use embedded_io::asynch::Write;
15use static_cell::make_static;
16use {defmt_rtt as _, embassy_net_esp_hosted as hosted, panic_probe as _};
17
18bind_interrupts!(struct Irqs {
19 SPIM3 => spim::InterruptHandler<peripherals::SPI3>;
20 RNG => embassy_nrf::rng::InterruptHandler<peripherals::RNG>;
21});
22
23#[embassy_executor::task]
24async fn wifi_task(
25 runner: hosted::Runner<
26 'static,
27 ExclusiveDevice<Spim<'static, peripherals::SPI3>, Output<'static, peripherals::P0_31>>,
28 Input<'static, AnyPin>,
29 Output<'static, peripherals::P1_05>,
30 >,
31) -> ! {
32 runner.run().await
33}
34
35#[embassy_executor::task]
36async fn net_task(stack: &'static Stack<hosted::NetDriver<'static>>) -> ! {
37 stack.run().await
38}
39
40#[embassy_executor::main]
41async fn main(spawner: Spawner) {
42 info!("Hello World!");
43
44 let p = embassy_nrf::init(Default::default());
45
46 let miso = p.P0_28;
47 let sck = p.P0_29;
48 let mosi = p.P0_30;
49 let cs = Output::new(p.P0_31, Level::High, OutputDrive::HighDrive);
50 let handshake = Input::new(p.P1_01.degrade(), Pull::Up);
51 let ready = Input::new(p.P1_04.degrade(), Pull::None);
52 let reset = Output::new(p.P1_05, Level::Low, OutputDrive::Standard);
53
54 let mut config = spim::Config::default();
55 config.frequency = spim::Frequency::M32;
56 config.mode = spim::MODE_2; // !!!
57 let spi = spim::Spim::new(p.SPI3, Irqs, sck, miso, mosi, config);
58 let spi = ExclusiveDevice::new(spi, cs);
59
60 let (device, mut control, runner) = embassy_net_esp_hosted::new(
61 make_static!(embassy_net_esp_hosted::State::new()),
62 spi,
63 handshake,
64 ready,
65 reset,
66 )
67 .await;
68
69 unwrap!(spawner.spawn(wifi_task(runner)));
70
71 control.init().await;
72 control.join(env!("WIFI_NETWORK"), env!("WIFI_PASSWORD")).await;
73
74 let config = embassy_net::Config::dhcpv4(Default::default());
75 // let config = embassy_net::Config::ipv4_static(embassy_net::StaticConfigV4 {
76 // address: Ipv4Cidr::new(Ipv4Address::new(10, 42, 0, 61), 24),
77 // dns_servers: Vec::new(),
78 // gateway: Some(Ipv4Address::new(10, 42, 0, 1)),
79 // });
80
81 // Generate random seed
82 let mut rng = Rng::new(p.RNG, Irqs);
83 let mut seed = [0; 8];
84 rng.blocking_fill_bytes(&mut seed);
85 let seed = u64::from_le_bytes(seed);
86
87 // Init network stack
88 let stack = &*make_static!(Stack::new(
89 device,
90 config,
91 make_static!(StackResources::<2>::new()),
92 seed
93 ));
94
95 unwrap!(spawner.spawn(net_task(stack)));
96
97 // And now we can use it!
98
99 let mut rx_buffer = [0; 4096];
100 let mut tx_buffer = [0; 4096];
101 let mut buf = [0; 4096];
102
103 loop {
104 let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer);
105 socket.set_timeout(Some(embassy_time::Duration::from_secs(10)));
106
107 info!("Listening on TCP:1234...");
108 if let Err(e) = socket.accept(1234).await {
109 warn!("accept error: {:?}", e);
110 continue;
111 }
112
113 info!("Received connection from {:?}", socket.remote_endpoint());
114
115 loop {
116 let n = match socket.read(&mut buf).await {
117 Ok(0) => {
118 warn!("read EOF");
119 break;
120 }
121 Ok(n) => n,
122 Err(e) => {
123 warn!("read error: {:?}", e);
124 break;
125 }
126 };
127
128 info!("rxd {:02x}", &buf[..n]);
129
130 match socket.write_all(&buf[..n]).await {
131 Ok(()) => {}
132 Err(e) => {
133 warn!("write error: {:?}", e);
134 break;
135 }
136 };
137 }
138 }
139}
diff --git a/tests/nrf/Cargo.toml b/tests/nrf/Cargo.toml
index 9735c87d9..4f9ecc47a 100644
--- a/tests/nrf/Cargo.toml
+++ b/tests/nrf/Cargo.toml
@@ -13,6 +13,10 @@ embassy-executor = { version = "0.2.0", path = "../../embassy-executor", feature
13embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["defmt", "nightly", "defmt-timestamp-uptime"] } 13embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["defmt", "nightly", "defmt-timestamp-uptime"] }
14embassy-nrf = { version = "0.1.0", path = "../../embassy-nrf", features = ["defmt", "nightly", "unstable-traits", "nrf52840", "time-driver-rtc1", "gpiote", "unstable-pac"] } 14embassy-nrf = { version = "0.1.0", path = "../../embassy-nrf", features = ["defmt", "nightly", "unstable-traits", "nrf52840", "time-driver-rtc1", "gpiote", "unstable-pac"] }
15embedded-io = { version = "0.4.0", features = ["async"] } 15embedded-io = { version = "0.4.0", features = ["async"] }
16embassy-net = { version = "0.1.0", path = "../../embassy-net", features = ["defmt", "tcp", "dhcpv4", "medium-ethernet", "nightly"] }
17embassy-net-esp-hosted = { version = "0.1.0", path = "../../embassy-net-esp-hosted", features = ["defmt"] }
18embedded-hal-async = { version = "0.2.0-alpha.1" }
19static_cell = { version = "1.1", features = [ "nightly" ] }
16 20
17defmt = "0.3" 21defmt = "0.3"
18defmt-rtt = "0.4" 22defmt-rtt = "0.4"
diff --git a/tests/nrf/src/bin/wifi_esp_hosted_perf.rs b/tests/nrf/src/bin/wifi_esp_hosted_perf.rs
new file mode 100644
index 000000000..277b985c5
--- /dev/null
+++ b/tests/nrf/src/bin/wifi_esp_hosted_perf.rs
@@ -0,0 +1,270 @@
1#![no_std]
2#![no_main]
3#![feature(type_alias_impl_trait)]
4
5#[path = "../common.rs"]
6mod common;
7
8use defmt::{error, info, unwrap};
9use embassy_executor::Spawner;
10use embassy_futures::join::join;
11use embassy_net::tcp::TcpSocket;
12use embassy_net::{Config, Ipv4Address, Stack, StackResources};
13use embassy_nrf::gpio::{AnyPin, Input, Level, Output, OutputDrive, Pin, Pull};
14use embassy_nrf::rng::Rng;
15use embassy_nrf::spim::{self, Spim};
16use embassy_nrf::{bind_interrupts, peripherals};
17use embassy_time::{with_timeout, Duration, Timer};
18use embedded_hal_async::spi::ExclusiveDevice;
19use static_cell::make_static;
20use {defmt_rtt as _, embassy_net_esp_hosted as hosted, panic_probe as _};
21
22teleprobe_meta::timeout!(120);
23
24bind_interrupts!(struct Irqs {
25 SPIM3 => spim::InterruptHandler<peripherals::SPI3>;
26 RNG => embassy_nrf::rng::InterruptHandler<peripherals::RNG>;
27});
28
29#[embassy_executor::task]
30async fn wifi_task(
31 runner: hosted::Runner<
32 'static,
33 ExclusiveDevice<Spim<'static, peripherals::SPI3>, Output<'static, peripherals::P0_31>>,
34 Input<'static, AnyPin>,
35 Output<'static, peripherals::P1_05>,
36 >,
37) -> ! {
38 runner.run().await
39}
40
41type MyDriver = hosted::NetDriver<'static>;
42
43#[embassy_executor::task]
44async fn net_task(stack: &'static Stack<MyDriver>) -> ! {
45 stack.run().await
46}
47
48#[embassy_executor::main]
49async fn main(spawner: Spawner) {
50 info!("Hello World!");
51
52 let p = embassy_nrf::init(Default::default());
53
54 let miso = p.P0_28;
55 let sck = p.P0_29;
56 let mosi = p.P0_30;
57 let cs = Output::new(p.P0_31, Level::High, OutputDrive::HighDrive);
58 let handshake = Input::new(p.P1_01.degrade(), Pull::Up);
59 let ready = Input::new(p.P1_04.degrade(), Pull::None);
60 let reset = Output::new(p.P1_05, Level::Low, OutputDrive::Standard);
61
62 let mut config = spim::Config::default();
63 config.frequency = spim::Frequency::M32;
64 config.mode = spim::MODE_2; // !!!
65 let spi = spim::Spim::new(p.SPI3, Irqs, sck, miso, mosi, config);
66 let spi = ExclusiveDevice::new(spi, cs);
67
68 let (device, mut control, runner) = embassy_net_esp_hosted::new(
69 make_static!(embassy_net_esp_hosted::State::new()),
70 spi,
71 handshake,
72 ready,
73 reset,
74 )
75 .await;
76
77 unwrap!(spawner.spawn(wifi_task(runner)));
78
79 control.init().await;
80 control.join(WIFI_NETWORK, WIFI_PASSWORD).await;
81
82 // Generate random seed
83 let mut rng = Rng::new(p.RNG, Irqs);
84 let mut seed = [0; 8];
85 rng.blocking_fill_bytes(&mut seed);
86 let seed = u64::from_le_bytes(seed);
87
88 // Init network stack
89 let stack = &*make_static!(Stack::new(
90 device,
91 Config::dhcpv4(Default::default()),
92 make_static!(StackResources::<2>::new()),
93 seed
94 ));
95
96 unwrap!(spawner.spawn(net_task(stack)));
97
98 info!("Waiting for DHCP up...");
99 while stack.config_v4().is_none() {
100 Timer::after(Duration::from_millis(100)).await;
101 }
102 info!("IP addressing up!");
103
104 let down = test_download(stack).await;
105 let up = test_upload(stack).await;
106 let updown = test_upload_download(stack).await;
107
108 assert!(down > TEST_EXPECTED_DOWNLOAD_KBPS);
109 assert!(up > TEST_EXPECTED_UPLOAD_KBPS);
110 assert!(updown > TEST_EXPECTED_UPLOAD_DOWNLOAD_KBPS);
111
112 info!("Test OK");
113 cortex_m::asm::bkpt();
114}
115
116// Test-only wifi network, no internet access!
117const WIFI_NETWORK: &str = "EmbassyTest";
118const WIFI_PASSWORD: &str = "V8YxhKt5CdIAJFud";
119
120const TEST_DURATION: usize = 10;
121const TEST_EXPECTED_DOWNLOAD_KBPS: usize = 150;
122const TEST_EXPECTED_UPLOAD_KBPS: usize = 150;
123const TEST_EXPECTED_UPLOAD_DOWNLOAD_KBPS: usize = 150;
124const RX_BUFFER_SIZE: usize = 4096;
125const TX_BUFFER_SIZE: usize = 4096;
126const SERVER_ADDRESS: Ipv4Address = Ipv4Address::new(192, 168, 2, 2);
127const DOWNLOAD_PORT: u16 = 4321;
128const UPLOAD_PORT: u16 = 4322;
129const UPLOAD_DOWNLOAD_PORT: u16 = 4323;
130
131async fn test_download(stack: &'static Stack<MyDriver>) -> usize {
132 info!("Testing download...");
133
134 let mut rx_buffer = [0; RX_BUFFER_SIZE];
135 let mut tx_buffer = [0; TX_BUFFER_SIZE];
136 let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer);
137 socket.set_timeout(Some(Duration::from_secs(10)));
138
139 info!("connecting to {:?}:{}...", SERVER_ADDRESS, DOWNLOAD_PORT);
140 if let Err(e) = socket.connect((SERVER_ADDRESS, DOWNLOAD_PORT)).await {
141 error!("connect error: {:?}", e);
142 return 0;
143 }
144 info!("connected, testing...");
145
146 let mut rx_buf = [0; 4096];
147 let mut total: usize = 0;
148 with_timeout(Duration::from_secs(TEST_DURATION as _), async {
149 loop {
150 match socket.read(&mut rx_buf).await {
151 Ok(0) => {
152 error!("read EOF");
153 return 0;
154 }
155 Ok(n) => total += n,
156 Err(e) => {
157 error!("read error: {:?}", e);
158 return 0;
159 }
160 }
161 }
162 })
163 .await
164 .ok();
165
166 let kbps = (total + 512) / 1024 / TEST_DURATION;
167 info!("download: {} kB/s", kbps);
168 kbps
169}
170
171async fn test_upload(stack: &'static Stack<MyDriver>) -> usize {
172 info!("Testing upload...");
173
174 let mut rx_buffer = [0; RX_BUFFER_SIZE];
175 let mut tx_buffer = [0; TX_BUFFER_SIZE];
176 let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer);
177 socket.set_timeout(Some(Duration::from_secs(10)));
178
179 info!("connecting to {:?}:{}...", SERVER_ADDRESS, UPLOAD_PORT);
180 if let Err(e) = socket.connect((SERVER_ADDRESS, UPLOAD_PORT)).await {
181 error!("connect error: {:?}", e);
182 return 0;
183 }
184 info!("connected, testing...");
185
186 let buf = [0; 4096];
187 let mut total: usize = 0;
188 with_timeout(Duration::from_secs(TEST_DURATION as _), async {
189 loop {
190 match socket.write(&buf).await {
191 Ok(0) => {
192 error!("write zero?!??!?!");
193 return 0;
194 }
195 Ok(n) => total += n,
196 Err(e) => {
197 error!("write error: {:?}", e);
198 return 0;
199 }
200 }
201 }
202 })
203 .await
204 .ok();
205
206 let kbps = (total + 512) / 1024 / TEST_DURATION;
207 info!("upload: {} kB/s", kbps);
208 kbps
209}
210
211async fn test_upload_download(stack: &'static Stack<MyDriver>) -> usize {
212 info!("Testing upload+download...");
213
214 let mut rx_buffer = [0; RX_BUFFER_SIZE];
215 let mut tx_buffer = [0; TX_BUFFER_SIZE];
216 let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer);
217 socket.set_timeout(Some(Duration::from_secs(10)));
218
219 info!("connecting to {:?}:{}...", SERVER_ADDRESS, UPLOAD_DOWNLOAD_PORT);
220 if let Err(e) = socket.connect((SERVER_ADDRESS, UPLOAD_DOWNLOAD_PORT)).await {
221 error!("connect error: {:?}", e);
222 return 0;
223 }
224 info!("connected, testing...");
225
226 let (mut reader, mut writer) = socket.split();
227
228 let tx_buf = [0; 4096];
229 let mut rx_buf = [0; 4096];
230 let mut total: usize = 0;
231 let tx_fut = async {
232 loop {
233 match writer.write(&tx_buf).await {
234 Ok(0) => {
235 error!("write zero?!??!?!");
236 return 0;
237 }
238 Ok(_) => {}
239 Err(e) => {
240 error!("write error: {:?}", e);
241 return 0;
242 }
243 }
244 }
245 };
246
247 let rx_fut = async {
248 loop {
249 match reader.read(&mut rx_buf).await {
250 Ok(0) => {
251 error!("read EOF");
252 return 0;
253 }
254 Ok(n) => total += n,
255 Err(e) => {
256 error!("read error: {:?}", e);
257 return 0;
258 }
259 }
260 }
261 };
262
263 with_timeout(Duration::from_secs(TEST_DURATION as _), join(tx_fut, rx_fut))
264 .await
265 .ok();
266
267 let kbps = (total + 512) / 1024 / TEST_DURATION;
268 info!("upload+download: {} kB/s", kbps);
269 kbps
270}
diff --git a/tests/rp/src/bin/cyw43-perf.rs b/tests/rp/src/bin/cyw43-perf.rs
index 7a94ea191..9fc537a4b 100644
--- a/tests/rp/src/bin/cyw43-perf.rs
+++ b/tests/rp/src/bin/cyw43-perf.rs
@@ -63,20 +63,13 @@ async fn main(spawner: Spawner) {
63 .set_power_management(cyw43::PowerManagementMode::PowerSave) 63 .set_power_management(cyw43::PowerManagementMode::PowerSave)
64 .await; 64 .await;
65 65
66 let config = Config::dhcpv4(Default::default());
67 //let config = embassy_net::Config::Static(embassy_net::Config {
68 // address: Ipv4Cidr::new(Ipv4Address::new(192, 168, 69, 2), 24),
69 // dns_servers: Vec::new(),
70 // gateway: Some(Ipv4Address::new(192, 168, 69, 1)),
71 //});
72
73 // Generate random seed 66 // Generate random seed
74 let seed = 0x0123_4567_89ab_cdef; // chosen by fair dice roll. guarenteed to be random. 67 let seed = 0x0123_4567_89ab_cdef; // chosen by fair dice roll. guarenteed to be random.
75 68
76 // Init network stack 69 // Init network stack
77 let stack = &*make_static!(Stack::new( 70 let stack = &*make_static!(Stack::new(
78 net_device, 71 net_device,
79 config, 72 Config::dhcpv4(Default::default()),
80 make_static!(StackResources::<2>::new()), 73 make_static!(StackResources::<2>::new()),
81 seed 74 seed
82 )); 75 ));