aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorschphil <[email protected]>2023-06-23 10:19:30 +0200
committerGitHub <[email protected]>2023-06-23 10:19:30 +0200
commit71afa40a69c9a776ccb981c67cd159935228c46b (patch)
tree2e0d6be5a019fb65bcf09e60570983756e0d5dc8
parent89fbb02979c0abfac99b32e3676c140055f31c1e (diff)
parent6f17286c7525050a3acfdbb889915730913518b0 (diff)
Merge branch 'embassy-rs:main' into can-split
-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--embassy-stm32-wpan/Cargo.toml5
-rw-r--r--embassy-stm32-wpan/src/ble.rs24
-rw-r--r--embassy-stm32-wpan/src/cmd.rs4
-rw-r--r--embassy-stm32-wpan/src/consts.rs34
-rw-r--r--embassy-stm32-wpan/src/evt.rs99
-rw-r--r--embassy-stm32-wpan/src/lhci.rs111
-rw-r--r--embassy-stm32-wpan/src/lib.rs148
-rw-r--r--embassy-stm32-wpan/src/mac.rs111
-rw-r--r--embassy-stm32-wpan/src/mm.rs16
-rw-r--r--embassy-stm32-wpan/src/shci.rs350
-rw-r--r--embassy-stm32-wpan/src/sys.rs40
-rw-r--r--embassy-stm32-wpan/src/tables.rs97
-rw-r--r--embassy-stm32/src/ipcc.rs12
-rw-r--r--examples/nrf52840/Cargo.toml22
-rw-r--r--examples/nrf52840/src/bin/wifi_esp_hosted.rs139
-rw-r--r--examples/stm32wb/.cargo/config.toml2
-rw-r--r--examples/stm32wb/Cargo.toml21
-rw-r--r--examples/stm32wb/src/bin/eddystone_beacon.rs249
-rw-r--r--examples/stm32wb/src/bin/tl_mbox_ble.rs (renamed from examples/stm32wb/src/bin/tl_mbox_tx_rx.rs)4
-rw-r--r--examples/stm32wb/src/bin/tl_mbox_mac.rs64
-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
-rw-r--r--tests/stm32/Cargo.toml5
-rw-r--r--tests/stm32/src/bin/tl_mbox.rs221
33 files changed, 3726 insertions, 297 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/embassy-stm32-wpan/Cargo.toml b/embassy-stm32-wpan/Cargo.toml
index 1c1b57b36..6d78ca577 100644
--- a/embassy-stm32-wpan/Cargo.toml
+++ b/embassy-stm32-wpan/Cargo.toml
@@ -23,10 +23,15 @@ cortex-m = "0.7.6"
23heapless = "0.7.16" 23heapless = "0.7.16"
24 24
25bit_field = "0.10.2" 25bit_field = "0.10.2"
26stm32-device-signature = { version = "0.3.3", features = ["stm32wb5x"] }
27stm32wb-hci = { version = "0.1.2", features = ["version-5-0"], optional = true }
26 28
27[features] 29[features]
28defmt = ["dep:defmt", "embassy-sync/defmt", "embassy-embedded-hal/defmt", "embassy-hal-common/defmt"] 30defmt = ["dep:defmt", "embassy-sync/defmt", "embassy-embedded-hal/defmt", "embassy-hal-common/defmt"]
29 31
32ble = ["dep:stm32wb-hci"]
33mac = []
34
30stm32wb10cc = [ "embassy-stm32/stm32wb10cc" ] 35stm32wb10cc = [ "embassy-stm32/stm32wb10cc" ]
31stm32wb15cc = [ "embassy-stm32/stm32wb15cc" ] 36stm32wb15cc = [ "embassy-stm32/stm32wb15cc" ]
32stm32wb30ce = [ "embassy-stm32/stm32wb30ce" ] 37stm32wb30ce = [ "embassy-stm32/stm32wb30ce" ]
diff --git a/embassy-stm32-wpan/src/ble.rs b/embassy-stm32-wpan/src/ble.rs
index f0bd6f48c..619cd66a0 100644
--- a/embassy-stm32-wpan/src/ble.rs
+++ b/embassy-stm32-wpan/src/ble.rs
@@ -1,13 +1,14 @@
1use core::marker::PhantomData; 1use core::marker::PhantomData;
2 2
3use embassy_stm32::ipcc::Ipcc; 3use embassy_stm32::ipcc::Ipcc;
4use hci::Opcode;
4 5
6use crate::channels;
5use crate::cmd::CmdPacket; 7use crate::cmd::CmdPacket;
6use crate::consts::TlPacketType; 8use crate::consts::TlPacketType;
7use crate::evt::EvtBox; 9use crate::evt::EvtBox;
8use crate::tables::BleTable; 10use crate::tables::{BleTable, BLE_CMD_BUFFER, CS_BUFFER, EVT_QUEUE, HCI_ACL_DATA_BUFFER, TL_BLE_TABLE};
9use crate::unsafe_linked_list::LinkedListNode; 11use crate::unsafe_linked_list::LinkedListNode;
10use crate::{channels, BLE_CMD_BUFFER, CS_BUFFER, EVT_QUEUE, HCI_ACL_DATA_BUFFER, TL_BLE_TABLE};
11 12
12pub struct Ble { 13pub struct Ble {
13 phantom: PhantomData<Ble>, 14 phantom: PhantomData<Ble>,
@@ -29,7 +30,7 @@ impl Ble {
29 Self { phantom: PhantomData } 30 Self { phantom: PhantomData }
30 } 31 }
31 /// `HW_IPCC_BLE_EvtNot` 32 /// `HW_IPCC_BLE_EvtNot`
32 pub async fn read(&self) -> EvtBox { 33 pub async fn tl_read(&self) -> EvtBox {
33 Ipcc::receive(channels::cpu2::IPCC_BLE_EVENT_CHANNEL, || unsafe { 34 Ipcc::receive(channels::cpu2::IPCC_BLE_EVENT_CHANNEL, || unsafe {
34 if let Some(node_ptr) = LinkedListNode::remove_head(EVT_QUEUE.as_mut_ptr()) { 35 if let Some(node_ptr) = LinkedListNode::remove_head(EVT_QUEUE.as_mut_ptr()) {
35 Some(EvtBox::new(node_ptr.cast())) 36 Some(EvtBox::new(node_ptr.cast()))
@@ -41,7 +42,7 @@ impl Ble {
41 } 42 }
42 43
43 /// `TL_BLE_SendCmd` 44 /// `TL_BLE_SendCmd`
44 pub async fn write(&self, opcode: u16, payload: &[u8]) { 45 pub async fn tl_write(&self, opcode: u16, payload: &[u8]) {
45 Ipcc::send(channels::cpu1::IPCC_BLE_CMD_CHANNEL, || unsafe { 46 Ipcc::send(channels::cpu1::IPCC_BLE_CMD_CHANNEL, || unsafe {
46 CmdPacket::write_into(BLE_CMD_BUFFER.as_mut_ptr(), TlPacketType::BleCmd, opcode, payload); 47 CmdPacket::write_into(BLE_CMD_BUFFER.as_mut_ptr(), TlPacketType::BleCmd, opcode, payload);
47 }) 48 })
@@ -61,3 +62,18 @@ impl Ble {
61 .await; 62 .await;
62 } 63 }
63} 64}
65
66pub extern crate stm32wb_hci as hci;
67
68impl hci::Controller for Ble {
69 async fn controller_write(&mut self, opcode: Opcode, payload: &[u8]) {
70 self.tl_write(opcode.0, payload).await;
71 }
72
73 async fn controller_read_into(&self, buf: &mut [u8]) {
74 let evt_box = self.tl_read().await;
75 let evt_serial = evt_box.serial();
76
77 buf[..evt_serial.len()].copy_from_slice(evt_serial);
78 }
79}
diff --git a/embassy-stm32-wpan/src/cmd.rs b/embassy-stm32-wpan/src/cmd.rs
index edca82390..8428b6ffc 100644
--- a/embassy-stm32-wpan/src/cmd.rs
+++ b/embassy-stm32-wpan/src/cmd.rs
@@ -37,7 +37,7 @@ pub struct CmdSerialStub {
37} 37}
38 38
39#[derive(Copy, Clone, Default)] 39#[derive(Copy, Clone, Default)]
40#[repr(C, packed)] 40#[repr(C, packed(4))]
41pub struct CmdPacket { 41pub struct CmdPacket {
42 pub header: PacketHeader, 42 pub header: PacketHeader,
43 pub cmdserial: CmdSerial, 43 pub cmdserial: CmdSerial,
@@ -52,7 +52,7 @@ impl CmdPacket {
52 p_cmd_serial, 52 p_cmd_serial,
53 CmdSerialStub { 53 CmdSerialStub {
54 ty: packet_type as u8, 54 ty: packet_type as u8,
55 cmd_code: cmd_code, 55 cmd_code,
56 payload_len: payload.len() as u8, 56 payload_len: payload.len() as u8,
57 }, 57 },
58 ); 58 );
diff --git a/embassy-stm32-wpan/src/consts.rs b/embassy-stm32-wpan/src/consts.rs
index caf26c06b..9a107306c 100644
--- a/embassy-stm32-wpan/src/consts.rs
+++ b/embassy-stm32-wpan/src/consts.rs
@@ -1,5 +1,8 @@
1use core::convert::TryFrom; 1use core::convert::TryFrom;
2 2
3use crate::evt::CsEvt;
4use crate::PacketHeader;
5
3#[derive(Debug)] 6#[derive(Debug)]
4#[repr(C)] 7#[repr(C)]
5pub enum TlPacketType { 8pub enum TlPacketType {
@@ -53,3 +56,34 @@ impl TryFrom<u8> for TlPacketType {
53 } 56 }
54 } 57 }
55} 58}
59
60pub const TL_PACKET_HEADER_SIZE: usize = core::mem::size_of::<PacketHeader>();
61pub const TL_EVT_HEADER_SIZE: usize = 3;
62pub const TL_CS_EVT_SIZE: usize = core::mem::size_of::<CsEvt>();
63
64/**
65 * Queue length of BLE Event
66 * This parameter defines the number of asynchronous events that can be stored in the HCI layer before
67 * being reported to the application. When a command is sent to the BLE core coprocessor, the HCI layer
68 * is waiting for the event with the Num_HCI_Command_Packets set to 1. The receive queue shall be large
69 * enough to store all asynchronous events received in between.
70 * When CFG_TLBLE_MOST_EVENT_PAYLOAD_SIZE is set to 27, this allow to store three 255 bytes long asynchronous events
71 * between the HCI command and its event.
72 * This parameter depends on the value given to CFG_TLBLE_MOST_EVENT_PAYLOAD_SIZE. When the queue size is to small,
73 * the system may hang if the queue is full with asynchronous events and the HCI layer is still waiting
74 * for a CC/CS event, In that case, the notification TL_BLE_HCI_ToNot() is called to indicate
75 * to the application a HCI command did not receive its command event within 30s (Default HCI Timeout).
76 */
77pub const CFG_TL_BLE_EVT_QUEUE_LENGTH: usize = 5;
78pub const CFG_TL_BLE_MOST_EVENT_PAYLOAD_SIZE: usize = 255;
79pub const TL_BLE_EVENT_FRAME_SIZE: usize = TL_EVT_HEADER_SIZE + CFG_TL_BLE_MOST_EVENT_PAYLOAD_SIZE;
80
81pub const POOL_SIZE: usize = CFG_TL_BLE_EVT_QUEUE_LENGTH * 4 * divc(TL_PACKET_HEADER_SIZE + TL_BLE_EVENT_FRAME_SIZE, 4);
82
83pub const fn divc(x: usize, y: usize) -> usize {
84 (x + y - 1) / y
85}
86
87pub const TL_BLE_EVT_CS_PACKET_SIZE: usize = TL_EVT_HEADER_SIZE + TL_CS_EVT_SIZE;
88#[allow(dead_code)]
89pub const TL_BLE_EVT_CS_BUFFER_SIZE: usize = TL_PACKET_HEADER_SIZE + TL_BLE_EVT_CS_PACKET_SIZE;
diff --git a/embassy-stm32-wpan/src/evt.rs b/embassy-stm32-wpan/src/evt.rs
index 3a9d03576..25249a13a 100644
--- a/embassy-stm32-wpan/src/evt.rs
+++ b/embassy-stm32-wpan/src/evt.rs
@@ -1,7 +1,7 @@
1use core::{ptr, slice}; 1use core::{ptr, slice};
2 2
3use super::PacketHeader; 3use super::PacketHeader;
4use crate::mm; 4use crate::consts::TL_EVT_HEADER_SIZE;
5 5
6/** 6/**
7 * The payload of `Evt` for a command status event 7 * The payload of `Evt` for a command status event
@@ -46,15 +46,15 @@ pub struct AsynchEvt {
46 payload: [u8; 1], 46 payload: [u8; 1],
47} 47}
48 48
49#[derive(Copy, Clone, Default)] 49#[derive(Copy, Clone)]
50#[repr(C, packed)] 50#[repr(C, packed)]
51pub struct Evt { 51pub struct Evt {
52 pub evt_code: u8, 52 pub evt_code: u8,
53 pub payload_len: u8, 53 pub payload_len: u8,
54 pub payload: [u8; 1], 54 pub payload: [u8; 255],
55} 55}
56 56
57#[derive(Copy, Clone, Default)] 57#[derive(Copy, Clone)]
58#[repr(C, packed)] 58#[repr(C, packed)]
59pub struct EvtSerial { 59pub struct EvtSerial {
60 pub kind: u8, 60 pub kind: u8,
@@ -62,6 +62,7 @@ pub struct EvtSerial {
62} 62}
63 63
64#[derive(Copy, Clone, Default)] 64#[derive(Copy, Clone, Default)]
65#[repr(C, packed)]
65pub struct EvtStub { 66pub struct EvtStub {
66 pub kind: u8, 67 pub kind: u8,
67 pub evt_code: u8, 68 pub evt_code: u8,
@@ -75,7 +76,7 @@ pub struct EvtStub {
75/// Be careful that the asynchronous events reported by the CPU2 on the system channel do 76/// Be careful that the asynchronous events reported by the CPU2 on the system channel do
76/// include the header and shall use `EvtPacket` format. Only the command response format on the 77/// include the header and shall use `EvtPacket` format. Only the command response format on the
77/// system channel is different. 78/// system channel is different.
78#[derive(Copy, Clone, Default)] 79#[derive(Copy, Clone)]
79#[repr(C, packed)] 80#[repr(C, packed)]
80pub struct EvtPacket { 81pub struct EvtPacket {
81 pub header: PacketHeader, 82 pub header: PacketHeader,
@@ -114,7 +115,7 @@ impl EvtBox {
114 } 115 }
115 } 116 }
116 117
117 pub fn payload<'a>(&self) -> &'a [u8] { 118 pub fn payload<'a>(&'a self) -> &'a [u8] {
118 unsafe { 119 unsafe {
119 let p_payload_len = &(*self.ptr).evt_serial.evt.payload_len as *const u8; 120 let p_payload_len = &(*self.ptr).evt_serial.evt.payload_len as *const u8;
120 let p_payload = &(*self.ptr).evt_serial.evt.payload as *const u8; 121 let p_payload = &(*self.ptr).evt_serial.evt.payload as *const u8;
@@ -125,71 +126,35 @@ impl EvtBox {
125 } 126 }
126 } 127 }
127 128
128 // TODO: bring back acl 129 /// writes an underlying [`EvtPacket`] into the provided buffer.
129 130 /// Returns the number of bytes that were written.
130 // /// writes an underlying [`EvtPacket`] into the provided buffer. 131 /// Returns an error if event kind is unknown or if provided buffer size is not enough.
131 // /// Returns the number of bytes that were written. 132 pub fn serial<'a>(&'a self) -> &'a [u8] {
132 // /// Returns an error if event kind is unknown or if provided buffer size is not enough. 133 unsafe {
133 // #[allow(clippy::result_unit_err)] 134 let evt_serial: *const EvtSerial = &(*self.ptr).evt_serial;
134 // pub fn write(&self, buf: &mut [u8]) -> Result<usize, ()> { 135 let evt_serial_buf: *const u8 = evt_serial.cast();
135 // unsafe { 136
136 // let evt_kind = TlPacketType::try_from((*self.ptr).evt_serial.kind)?; 137 let len = (*evt_serial).evt.payload_len as usize + TL_EVT_HEADER_SIZE;
137 // 138
138 // let evt_data: *const EvtPacket = self.ptr.cast(); 139 slice::from_raw_parts(evt_serial_buf, len)
139 // let evt_serial: *const EvtSerial = &(*evt_data).evt_serial; 140 }
140 // let evt_serial_buf: *const u8 = evt_serial.cast(); 141 }
141 //
142 // let acl_data: *const AclDataPacket = self.ptr.cast();
143 // let acl_serial: *const AclDataSerial = &(*acl_data).acl_data_serial;
144 // let acl_serial_buf: *const u8 = acl_serial.cast();
145 //
146 // if let TlPacketType::AclData = evt_kind {
147 // let len = (*acl_serial).length as usize + 5;
148 // if len > buf.len() {
149 // return Err(());
150 // }
151 //
152 // core::ptr::copy(evt_serial_buf, buf.as_mut_ptr(), len);
153 //
154 // Ok(len)
155 // } else {
156 // let len = (*evt_serial).evt.payload_len as usize + TL_EVT_HEADER_SIZE;
157 // if len > buf.len() {
158 // return Err(());
159 // }
160 //
161 // core::ptr::copy(acl_serial_buf, buf.as_mut_ptr(), len);
162 //
163 // Ok(len)
164 // }
165 // }
166 // }
167 //
168 // /// returns the size of a buffer required to hold this event
169 // #[allow(clippy::result_unit_err)]
170 // pub fn size(&self) -> Result<usize, ()> {
171 // unsafe {
172 // let evt_kind = TlPacketType::try_from((*self.ptr).evt_serial.kind)?;
173 //
174 // let evt_data: *const EvtPacket = self.ptr.cast();
175 // let evt_serial: *const EvtSerial = &(*evt_data).evt_serial;
176 //
177 // let acl_data: *const AclDataPacket = self.ptr.cast();
178 // let acl_serial: *const AclDataSerial = &(*acl_data).acl_data_serial;
179 //
180 // if let TlPacketType::AclData = evt_kind {
181 // Ok((*acl_serial).length as usize + 5)
182 // } else {
183 // Ok((*evt_serial).evt.payload_len as usize + TL_EVT_HEADER_SIZE)
184 // }
185 // }
186 // }
187} 142}
188 143
189impl Drop for EvtBox { 144impl Drop for EvtBox {
190 fn drop(&mut self) { 145 fn drop(&mut self) {
191 trace!("evt box drop packet"); 146 #[cfg(feature = "ble")]
147 unsafe {
148 use crate::mm;
192 149
193 unsafe { mm::MemoryManager::drop_event_packet(self.ptr) }; 150 mm::MemoryManager::drop_event_packet(self.ptr)
151 };
152
153 #[cfg(feature = "mac")]
154 unsafe {
155 use crate::mac;
156
157 mac::Mac::drop_event_packet(self.ptr)
158 }
194 } 159 }
195} 160}
diff --git a/embassy-stm32-wpan/src/lhci.rs b/embassy-stm32-wpan/src/lhci.rs
new file mode 100644
index 000000000..62116a695
--- /dev/null
+++ b/embassy-stm32-wpan/src/lhci.rs
@@ -0,0 +1,111 @@
1use crate::cmd::CmdPacket;
2use crate::consts::{TlPacketType, TL_EVT_HEADER_SIZE};
3use crate::evt::{CcEvt, EvtPacket, EvtSerial};
4use crate::tables::{DeviceInfoTable, RssInfoTable, SafeBootInfoTable, WirelessFwInfoTable};
5use crate::TL_REF_TABLE;
6
7const TL_BLEEVT_CC_OPCODE: u8 = 0x0e;
8const LHCI_OPCODE_C1_DEVICE_INF: u16 = 0xfd62;
9
10const PACKAGE_DATA_PTR: *const u8 = 0x1FFF_7500 as _;
11const UID64_PTR: *const u32 = 0x1FFF_7580 as _;
12
13#[derive(Debug, Copy, Clone)]
14#[repr(C, packed)]
15pub struct LhciC1DeviceInformationCcrp {
16 pub status: u8,
17 pub rev_id: u16,
18 pub dev_code_id: u16,
19 pub package_type: u8,
20 pub device_type_id: u8,
21 pub st_company_id: u32,
22 pub uid64: u32,
23
24 pub uid96_0: u32,
25 pub uid96_1: u32,
26 pub uid96_2: u32,
27
28 pub safe_boot_info_table: SafeBootInfoTable,
29 pub rss_info_table: RssInfoTable,
30 pub wireless_fw_info_table: WirelessFwInfoTable,
31
32 pub app_fw_inf: u32,
33}
34
35impl Default for LhciC1DeviceInformationCcrp {
36 fn default() -> Self {
37 let DeviceInfoTable {
38 safe_boot_info_table,
39 rss_info_table,
40 wireless_fw_info_table,
41 } = unsafe { &*(*TL_REF_TABLE.as_ptr()).device_info_table }.clone();
42
43 let device_id = stm32_device_signature::device_id();
44 let uid96_0 = (device_id[3] as u32) << 24
45 | (device_id[2] as u32) << 16
46 | (device_id[1] as u32) << 8
47 | device_id[0] as u32;
48 let uid96_1 = (device_id[7] as u32) << 24
49 | (device_id[6] as u32) << 16
50 | (device_id[5] as u32) << 8
51 | device_id[4] as u32;
52 let uid96_2 = (device_id[11] as u32) << 24
53 | (device_id[10] as u32) << 16
54 | (device_id[9] as u32) << 8
55 | device_id[8] as u32;
56
57 let package_type = unsafe { *PACKAGE_DATA_PTR };
58 let uid64 = unsafe { *UID64_PTR };
59 let st_company_id = unsafe { *UID64_PTR.offset(1) } >> 8 & 0x00FF_FFFF;
60 let device_type_id = (unsafe { *UID64_PTR.offset(1) } & 0x000000FF) as u8;
61
62 LhciC1DeviceInformationCcrp {
63 status: 0,
64 rev_id: 0,
65 dev_code_id: 0,
66 package_type,
67 device_type_id,
68 st_company_id,
69 uid64,
70 uid96_0,
71 uid96_1,
72 uid96_2,
73 safe_boot_info_table,
74 rss_info_table,
75 wireless_fw_info_table,
76 app_fw_inf: (1 << 8), // 0.0.1
77 }
78 }
79}
80
81impl LhciC1DeviceInformationCcrp {
82 pub fn new() -> Self {
83 Self::default()
84 }
85
86 pub fn write(&self, cmd_packet: &mut CmdPacket) {
87 let self_size = core::mem::size_of::<LhciC1DeviceInformationCcrp>();
88
89 unsafe {
90 let cmd_packet_ptr: *mut CmdPacket = cmd_packet;
91 let evet_packet_ptr: *mut EvtPacket = cmd_packet_ptr.cast();
92
93 let evt_serial: *mut EvtSerial = &mut (*evet_packet_ptr).evt_serial;
94 let evt_payload = (*evt_serial).evt.payload.as_mut_ptr();
95 let evt_cc: *mut CcEvt = evt_payload.cast();
96 let evt_cc_payload_buf = (*evt_cc).payload.as_mut_ptr();
97
98 (*evt_serial).kind = TlPacketType::LocRsp as u8;
99 (*evt_serial).evt.evt_code = TL_BLEEVT_CC_OPCODE;
100 (*evt_serial).evt.payload_len = TL_EVT_HEADER_SIZE as u8 + self_size as u8;
101
102 (*evt_cc).cmd_code = LHCI_OPCODE_C1_DEVICE_INF;
103 (*evt_cc).num_cmd = 1;
104
105 let self_ptr: *const LhciC1DeviceInformationCcrp = self;
106 let self_buf = self_ptr.cast();
107
108 core::ptr::copy(self_buf, evt_cc_payload_buf, self_size);
109 }
110 }
111}
diff --git a/embassy-stm32-wpan/src/lib.rs b/embassy-stm32-wpan/src/lib.rs
index 833db0df3..bf0f0466e 100644
--- a/embassy-stm32-wpan/src/lib.rs
+++ b/embassy-stm32-wpan/src/lib.rs
@@ -1,4 +1,5 @@
1#![no_std] 1#![no_std]
2#![cfg_attr(feature = "ble", feature(async_fn_in_trait))]
2 3
3// This must go FIRST so that all the other modules see its macros. 4// This must go FIRST so that all the other modules see its macros.
4pub mod fmt; 5pub mod fmt;
@@ -6,148 +7,41 @@ pub mod fmt;
6use core::mem::MaybeUninit; 7use core::mem::MaybeUninit;
7use core::sync::atomic::{compiler_fence, Ordering}; 8use core::sync::atomic::{compiler_fence, Ordering};
8 9
9use ble::Ble;
10use cmd::CmdPacket;
11use embassy_hal_common::{into_ref, Peripheral, PeripheralRef}; 10use embassy_hal_common::{into_ref, Peripheral, PeripheralRef};
12use embassy_stm32::interrupt; 11use embassy_stm32::interrupt;
13use embassy_stm32::interrupt::typelevel::Interrupt;
14use embassy_stm32::ipcc::{Config, Ipcc, ReceiveInterruptHandler, TransmitInterruptHandler}; 12use embassy_stm32::ipcc::{Config, Ipcc, ReceiveInterruptHandler, TransmitInterruptHandler};
15use embassy_stm32::peripherals::IPCC; 13use embassy_stm32::peripherals::IPCC;
16use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
17use embassy_sync::channel::Channel;
18use embassy_sync::signal::Signal;
19use evt::{CcEvt, EvtBox};
20use mm::MemoryManager; 14use mm::MemoryManager;
21use sys::Sys; 15use sys::Sys;
22use tables::{ 16use tables::*;
23 BleTable, DeviceInfoTable, Mac802_15_4Table, MemManagerTable, RefTable, SysTable, ThreadTable, TracesTable,
24};
25use unsafe_linked_list::LinkedListNode; 17use unsafe_linked_list::LinkedListNode;
26 18
19#[cfg(feature = "ble")]
27pub mod ble; 20pub mod ble;
28pub mod channels; 21pub mod channels;
29pub mod cmd; 22pub mod cmd;
30pub mod consts; 23pub mod consts;
31pub mod evt; 24pub mod evt;
25pub mod lhci;
26#[cfg(feature = "mac")]
27pub mod mac;
32pub mod mm; 28pub mod mm;
33pub mod shci; 29pub mod shci;
34pub mod sys; 30pub mod sys;
35pub mod tables; 31pub mod tables;
36pub mod unsafe_linked_list; 32pub mod unsafe_linked_list;
37 33
38#[link_section = "TL_REF_TABLE"]
39pub static mut TL_REF_TABLE: MaybeUninit<RefTable> = MaybeUninit::uninit();
40
41#[link_section = "MB_MEM1"]
42static mut TL_DEVICE_INFO_TABLE: MaybeUninit<DeviceInfoTable> = MaybeUninit::uninit();
43
44#[link_section = "MB_MEM1"]
45static mut TL_BLE_TABLE: MaybeUninit<BleTable> = MaybeUninit::uninit();
46
47#[link_section = "MB_MEM1"]
48static mut TL_THREAD_TABLE: MaybeUninit<ThreadTable> = MaybeUninit::uninit();
49
50#[link_section = "MB_MEM1"]
51static mut TL_SYS_TABLE: MaybeUninit<SysTable> = MaybeUninit::uninit();
52
53#[link_section = "MB_MEM1"]
54static mut TL_MEM_MANAGER_TABLE: MaybeUninit<MemManagerTable> = MaybeUninit::uninit();
55
56#[link_section = "MB_MEM1"]
57static mut TL_TRACES_TABLE: MaybeUninit<TracesTable> = MaybeUninit::uninit();
58
59#[link_section = "MB_MEM1"]
60static mut TL_MAC_802_15_4_TABLE: MaybeUninit<Mac802_15_4Table> = MaybeUninit::uninit();
61
62#[link_section = "MB_MEM2"]
63static mut FREE_BUF_QUEUE: MaybeUninit<LinkedListNode> = MaybeUninit::uninit();
64
65// Not in shared RAM
66static mut LOCAL_FREE_BUF_QUEUE: MaybeUninit<LinkedListNode> = MaybeUninit::uninit();
67
68#[allow(dead_code)] // Not used currently but reserved
69#[link_section = "MB_MEM2"]
70static mut TRACES_EVT_QUEUE: MaybeUninit<LinkedListNode> = MaybeUninit::uninit();
71
72type PacketHeader = LinkedListNode; 34type PacketHeader = LinkedListNode;
73 35
74const TL_PACKET_HEADER_SIZE: usize = core::mem::size_of::<PacketHeader>();
75const TL_EVT_HEADER_SIZE: usize = 3;
76const TL_CS_EVT_SIZE: usize = core::mem::size_of::<evt::CsEvt>();
77
78#[link_section = "MB_MEM2"]
79static mut CS_BUFFER: MaybeUninit<[u8; TL_PACKET_HEADER_SIZE + TL_EVT_HEADER_SIZE + TL_CS_EVT_SIZE]> =
80 MaybeUninit::uninit();
81
82#[link_section = "MB_MEM2"]
83static mut EVT_QUEUE: MaybeUninit<LinkedListNode> = MaybeUninit::uninit();
84
85#[link_section = "MB_MEM2"]
86static mut SYSTEM_EVT_QUEUE: MaybeUninit<LinkedListNode> = MaybeUninit::uninit();
87
88#[link_section = "MB_MEM2"]
89pub static mut SYS_CMD_BUF: MaybeUninit<CmdPacket> = MaybeUninit::uninit();
90
91/**
92 * Queue length of BLE Event
93 * This parameter defines the number of asynchronous events that can be stored in the HCI layer before
94 * being reported to the application. When a command is sent to the BLE core coprocessor, the HCI layer
95 * is waiting for the event with the Num_HCI_Command_Packets set to 1. The receive queue shall be large
96 * enough to store all asynchronous events received in between.
97 * When CFG_TLBLE_MOST_EVENT_PAYLOAD_SIZE is set to 27, this allow to store three 255 bytes long asynchronous events
98 * between the HCI command and its event.
99 * This parameter depends on the value given to CFG_TLBLE_MOST_EVENT_PAYLOAD_SIZE. When the queue size is to small,
100 * the system may hang if the queue is full with asynchronous events and the HCI layer is still waiting
101 * for a CC/CS event, In that case, the notification TL_BLE_HCI_ToNot() is called to indicate
102 * to the application a HCI command did not receive its command event within 30s (Default HCI Timeout).
103 */
104const CFG_TLBLE_EVT_QUEUE_LENGTH: usize = 5;
105const CFG_TLBLE_MOST_EVENT_PAYLOAD_SIZE: usize = 255;
106const TL_BLE_EVENT_FRAME_SIZE: usize = TL_EVT_HEADER_SIZE + CFG_TLBLE_MOST_EVENT_PAYLOAD_SIZE;
107
108const fn divc(x: usize, y: usize) -> usize {
109 ((x) + (y) - 1) / (y)
110}
111
112const POOL_SIZE: usize = CFG_TLBLE_EVT_QUEUE_LENGTH * 4 * divc(TL_PACKET_HEADER_SIZE + TL_BLE_EVENT_FRAME_SIZE, 4);
113
114#[link_section = "MB_MEM2"]
115static mut EVT_POOL: MaybeUninit<[u8; POOL_SIZE]> = MaybeUninit::uninit();
116
117#[link_section = "MB_MEM2"]
118static mut SYS_SPARE_EVT_BUF: MaybeUninit<[u8; TL_PACKET_HEADER_SIZE + TL_EVT_HEADER_SIZE + 255]> =
119 MaybeUninit::uninit();
120
121#[link_section = "MB_MEM2"]
122static mut BLE_SPARE_EVT_BUF: MaybeUninit<[u8; TL_PACKET_HEADER_SIZE + TL_EVT_HEADER_SIZE + 255]> =
123 MaybeUninit::uninit();
124
125#[link_section = "MB_MEM2"]
126static mut BLE_CMD_BUFFER: MaybeUninit<CmdPacket> = MaybeUninit::uninit();
127
128#[link_section = "MB_MEM2"]
129// fuck these "magic" numbers from ST ---v---v
130static mut HCI_ACL_DATA_BUFFER: MaybeUninit<[u8; TL_PACKET_HEADER_SIZE + 5 + 251]> = MaybeUninit::uninit();
131
132// TODO: remove these items
133
134#[allow(dead_code)]
135/// current event that is produced during IPCC IRQ handler execution
136/// on SYS channel
137static EVT_CHANNEL: Channel<CriticalSectionRawMutex, EvtBox, 32> = Channel::new();
138
139#[allow(dead_code)]
140/// last received Command Complete event
141static LAST_CC_EVT: Signal<CriticalSectionRawMutex, CcEvt> = Signal::new();
142
143static STATE: Signal<CriticalSectionRawMutex, ()> = Signal::new();
144
145pub struct TlMbox<'d> { 36pub struct TlMbox<'d> {
146 _ipcc: PeripheralRef<'d, IPCC>, 37 _ipcc: PeripheralRef<'d, IPCC>,
147 38
148 pub sys_subsystem: Sys, 39 pub sys_subsystem: Sys,
149 pub mm_subsystem: MemoryManager, 40 pub mm_subsystem: MemoryManager,
150 pub ble_subsystem: Ble, 41 #[cfg(feature = "ble")]
42 pub ble_subsystem: ble::Ble,
43 #[cfg(feature = "mac")]
44 pub mac_subsystem: mac::Mac,
151} 45}
152 46
153impl<'d> TlMbox<'d> { 47impl<'d> TlMbox<'d> {
@@ -232,24 +126,14 @@ impl<'d> TlMbox<'d> {
232 126
233 Ipcc::enable(config); 127 Ipcc::enable(config);
234 128
235 let sys = sys::Sys::new();
236 let ble = ble::Ble::new();
237 let mm = mm::MemoryManager::new();
238
239 // enable interrupts
240 interrupt::typelevel::IPCC_C1_RX::unpend();
241 interrupt::typelevel::IPCC_C1_TX::unpend();
242
243 unsafe { interrupt::typelevel::IPCC_C1_RX::enable() };
244 unsafe { interrupt::typelevel::IPCC_C1_TX::enable() };
245
246 STATE.reset();
247
248 Self { 129 Self {
249 _ipcc: ipcc, 130 _ipcc: ipcc,
250 sys_subsystem: sys, 131 sys_subsystem: sys::Sys::new(),
251 ble_subsystem: ble, 132 #[cfg(feature = "ble")]
252 mm_subsystem: mm, 133 ble_subsystem: ble::Ble::new(),
134 #[cfg(feature = "mac")]
135 mac_subsystem: mac::Mac::new(),
136 mm_subsystem: mm::MemoryManager::new(),
253 } 137 }
254 } 138 }
255} 139}
diff --git a/embassy-stm32-wpan/src/mac.rs b/embassy-stm32-wpan/src/mac.rs
new file mode 100644
index 000000000..d2be1b85c
--- /dev/null
+++ b/embassy-stm32-wpan/src/mac.rs
@@ -0,0 +1,111 @@
1use core::future::poll_fn;
2use core::marker::PhantomData;
3use core::ptr;
4use core::sync::atomic::{AtomicBool, Ordering};
5use core::task::Poll;
6
7use embassy_futures::poll_once;
8use embassy_stm32::ipcc::Ipcc;
9use embassy_sync::waitqueue::AtomicWaker;
10
11use crate::channels;
12use crate::cmd::CmdPacket;
13use crate::consts::TlPacketType;
14use crate::evt::{EvtBox, EvtPacket};
15use crate::tables::{
16 Mac802_15_4Table, MAC_802_15_4_CMD_BUFFER, MAC_802_15_4_NOTIF_RSP_EVT_BUFFER, TL_MAC_802_15_4_TABLE,
17};
18
19static MAC_WAKER: AtomicWaker = AtomicWaker::new();
20static MAC_EVT_OUT: AtomicBool = AtomicBool::new(false);
21
22pub struct Mac {
23 phantom: PhantomData<Mac>,
24}
25
26impl Mac {
27 pub(crate) fn new() -> Self {
28 unsafe {
29 TL_MAC_802_15_4_TABLE.as_mut_ptr().write_volatile(Mac802_15_4Table {
30 p_cmdrsp_buffer: MAC_802_15_4_CMD_BUFFER.as_mut_ptr().cast(),
31 p_notack_buffer: MAC_802_15_4_NOTIF_RSP_EVT_BUFFER.as_mut_ptr().cast(),
32 evt_queue: ptr::null_mut(),
33 });
34 }
35
36 Self { phantom: PhantomData }
37 }
38
39 /// SAFETY: passing a pointer to something other than a managed event packet is UB
40 pub(crate) unsafe fn drop_event_packet(_: *mut EvtPacket) {
41 // Write the ack
42 CmdPacket::write_into(
43 MAC_802_15_4_NOTIF_RSP_EVT_BUFFER.as_mut_ptr() as *mut _,
44 TlPacketType::OtAck,
45 0,
46 &[],
47 );
48
49 // Clear the rx flag
50 let _ = poll_once(Ipcc::receive::<bool>(
51 channels::cpu2::IPCC_MAC_802_15_4_NOTIFICATION_ACK_CHANNEL,
52 || None,
53 ));
54
55 // Allow a new read call
56 MAC_EVT_OUT.store(false, Ordering::SeqCst);
57 MAC_WAKER.wake();
58 }
59
60 /// `HW_IPCC_MAC_802_15_4_EvtNot`
61 ///
62 /// This function will stall if the previous `EvtBox` has not been dropped
63 pub async fn read(&self) -> EvtBox {
64 // Wait for the last event box to be dropped
65 poll_fn(|cx| {
66 MAC_WAKER.register(cx.waker());
67 if MAC_EVT_OUT.load(Ordering::SeqCst) {
68 Poll::Pending
69 } else {
70 Poll::Ready(())
71 }
72 })
73 .await;
74
75 // Return a new event box
76 Ipcc::receive(channels::cpu2::IPCC_MAC_802_15_4_NOTIFICATION_ACK_CHANNEL, || unsafe {
77 // The closure is not async, therefore the closure must execute to completion (cannot be dropped)
78 // Therefore, the event box is guaranteed to be cleaned up if it's not leaked
79 MAC_EVT_OUT.store(true, Ordering::SeqCst);
80
81 Some(EvtBox::new(MAC_802_15_4_NOTIF_RSP_EVT_BUFFER.as_mut_ptr() as *mut _))
82 })
83 .await
84 }
85
86 /// `HW_IPCC_MAC_802_15_4_CmdEvtNot`
87 pub async fn write_and_get_response(&self, opcode: u16, payload: &[u8]) -> u8 {
88 self.write(opcode, payload).await;
89 Ipcc::flush(channels::cpu1::IPCC_SYSTEM_CMD_RSP_CHANNEL).await;
90
91 unsafe {
92 let p_event_packet = MAC_802_15_4_CMD_BUFFER.as_ptr() as *const EvtPacket;
93 let p_mac_rsp_evt = &((*p_event_packet).evt_serial.evt.payload) as *const u8;
94
95 ptr::read_volatile(p_mac_rsp_evt)
96 }
97 }
98
99 /// `TL_MAC_802_15_4_SendCmd`
100 pub async fn write(&self, opcode: u16, payload: &[u8]) {
101 Ipcc::send(channels::cpu1::IPCC_MAC_802_15_4_CMD_RSP_CHANNEL, || unsafe {
102 CmdPacket::write_into(
103 MAC_802_15_4_CMD_BUFFER.as_mut_ptr(),
104 TlPacketType::OtCmd,
105 opcode,
106 payload,
107 );
108 })
109 .await;
110 }
111}
diff --git a/embassy-stm32-wpan/src/mm.rs b/embassy-stm32-wpan/src/mm.rs
index 21f42409a..047fddcd4 100644
--- a/embassy-stm32-wpan/src/mm.rs
+++ b/embassy-stm32-wpan/src/mm.rs
@@ -1,22 +1,23 @@
1//! Memory manager routines 1//! Memory manager routines
2
3use core::future::poll_fn; 2use core::future::poll_fn;
4use core::marker::PhantomData; 3use core::marker::PhantomData;
4use core::mem::MaybeUninit;
5use core::task::Poll; 5use core::task::Poll;
6 6
7use cortex_m::interrupt; 7use cortex_m::interrupt;
8use embassy_stm32::ipcc::Ipcc; 8use embassy_stm32::ipcc::Ipcc;
9use embassy_sync::waitqueue::AtomicWaker; 9use embassy_sync::waitqueue::AtomicWaker;
10 10
11use crate::channels;
12use crate::consts::POOL_SIZE;
11use crate::evt::EvtPacket; 13use crate::evt::EvtPacket;
12use crate::tables::MemManagerTable; 14use crate::tables::{
13use crate::unsafe_linked_list::LinkedListNode; 15 MemManagerTable, BLE_SPARE_EVT_BUF, EVT_POOL, FREE_BUF_QUEUE, SYS_SPARE_EVT_BUF, TL_MEM_MANAGER_TABLE,
14use crate::{
15 channels, BLE_SPARE_EVT_BUF, EVT_POOL, FREE_BUF_QUEUE, LOCAL_FREE_BUF_QUEUE, POOL_SIZE, SYS_SPARE_EVT_BUF,
16 TL_MEM_MANAGER_TABLE,
17}; 16};
17use crate::unsafe_linked_list::LinkedListNode;
18 18
19static MM_WAKER: AtomicWaker = AtomicWaker::new(); 19static MM_WAKER: AtomicWaker = AtomicWaker::new();
20static mut LOCAL_FREE_BUF_QUEUE: MaybeUninit<LinkedListNode> = MaybeUninit::uninit();
20 21
21pub struct MemoryManager { 22pub struct MemoryManager {
22 phantom: PhantomData<MemoryManager>, 23 phantom: PhantomData<MemoryManager>,
@@ -42,7 +43,8 @@ impl MemoryManager {
42 Self { phantom: PhantomData } 43 Self { phantom: PhantomData }
43 } 44 }
44 45
45 /// SAFETY: passing a pointer to something other than an event packet is UB 46 #[allow(dead_code)]
47 /// SAFETY: passing a pointer to something other than a managed event packet is UB
46 pub(crate) unsafe fn drop_event_packet(evt: *mut EvtPacket) { 48 pub(crate) unsafe fn drop_event_packet(evt: *mut EvtPacket) {
47 interrupt::free(|_| unsafe { 49 interrupt::free(|_| unsafe {
48 LinkedListNode::insert_head(LOCAL_FREE_BUF_QUEUE.as_mut_ptr(), evt as *mut _); 50 LinkedListNode::insert_head(LOCAL_FREE_BUF_QUEUE.as_mut_ptr(), evt as *mut _);
diff --git a/embassy-stm32-wpan/src/shci.rs b/embassy-stm32-wpan/src/shci.rs
index cdf027d5e..30d689716 100644
--- a/embassy-stm32-wpan/src/shci.rs
+++ b/embassy-stm32-wpan/src/shci.rs
@@ -1,39 +1,346 @@
1use core::{mem, slice}; 1use core::{mem, slice};
2 2
3use super::{TL_CS_EVT_SIZE, TL_EVT_HEADER_SIZE, TL_PACKET_HEADER_SIZE}; 3use crate::consts::{TL_CS_EVT_SIZE, TL_EVT_HEADER_SIZE, TL_PACKET_HEADER_SIZE};
4 4
5pub const SCHI_OPCODE_BLE_INIT: u16 = 0xfc66; 5const SHCI_OGF: u16 = 0x3F;
6 6
7#[derive(Debug, Clone, Copy)] 7const fn opcode(ogf: u16, ocf: u16) -> isize {
8 ((ogf << 10) + ocf) as isize
9}
10
11#[allow(dead_code)]
12#[cfg_attr(feature = "defmt", derive(defmt::Format))]
13pub enum SchiCommandStatus {
14 ShciSuccess = 0x00,
15 ShciUnknownCmd = 0x01,
16 ShciMemoryCapacityExceededErrCode = 0x07,
17 ShciErrUnsupportedFeature = 0x11,
18 ShciErrInvalidHciCmdParams = 0x12,
19 ShciErrInvalidParams = 0x42, /* only used for release < v1.13.0 */
20 ShciErrInvalidParamsV2 = 0x92, /* available for release >= v1.13.0 */
21 ShciFusCmdNotSupported = 0xFF,
22}
23
24impl TryFrom<u8> for SchiCommandStatus {
25 type Error = ();
26
27 fn try_from(v: u8) -> Result<Self, Self::Error> {
28 match v {
29 x if x == SchiCommandStatus::ShciSuccess as u8 => Ok(SchiCommandStatus::ShciSuccess),
30 x if x == SchiCommandStatus::ShciUnknownCmd as u8 => Ok(SchiCommandStatus::ShciUnknownCmd),
31 x if x == SchiCommandStatus::ShciMemoryCapacityExceededErrCode as u8 => {
32 Ok(SchiCommandStatus::ShciMemoryCapacityExceededErrCode)
33 }
34 x if x == SchiCommandStatus::ShciErrUnsupportedFeature as u8 => {
35 Ok(SchiCommandStatus::ShciErrUnsupportedFeature)
36 }
37 x if x == SchiCommandStatus::ShciErrInvalidHciCmdParams as u8 => {
38 Ok(SchiCommandStatus::ShciErrInvalidHciCmdParams)
39 }
40 x if x == SchiCommandStatus::ShciErrInvalidParams as u8 => Ok(SchiCommandStatus::ShciErrInvalidParams), /* only used for release < v1.13.0 */
41 x if x == SchiCommandStatus::ShciErrInvalidParamsV2 as u8 => Ok(SchiCommandStatus::ShciErrInvalidParamsV2), /* available for release >= v1.13.0 */
42 x if x == SchiCommandStatus::ShciFusCmdNotSupported as u8 => Ok(SchiCommandStatus::ShciFusCmdNotSupported),
43 _ => Err(()),
44 }
45 }
46}
47
48#[allow(dead_code)]
49#[cfg_attr(feature = "defmt", derive(defmt::Format))]
50pub enum ShciOpcode {
51 // 0x50 reserved
52 // 0x51 reserved
53 FusGetState = opcode(SHCI_OGF, 0x52),
54 // 0x53 reserved
55 FusFirmwareUpgrade = opcode(SHCI_OGF, 0x54),
56 FusFirmwareDelete = opcode(SHCI_OGF, 0x55),
57 FusUpdateAuthKey = opcode(SHCI_OGF, 0x56),
58 FusLockAuthKey = opcode(SHCI_OGF, 0x57),
59 FusStoreUserKey = opcode(SHCI_OGF, 0x58),
60 FusLoadUserKey = opcode(SHCI_OGF, 0x59),
61 FusStartWirelessStack = opcode(SHCI_OGF, 0x5a),
62 // 0x5b reserved
63 // 0x5c reserved
64 FusLockUserKey = opcode(SHCI_OGF, 0x5d),
65 FusUnloadUserKey = opcode(SHCI_OGF, 0x5e),
66 FusActivateAntirollback = opcode(SHCI_OGF, 0x5f),
67 // 0x60 reserved
68 // 0x61 reserved
69 // 0x62 reserved
70 // 0x63 reserved
71 // 0x64 reserved
72 // 0x65 reserved
73 BleInit = opcode(SHCI_OGF, 0x66),
74 ThreadInit = opcode(SHCI_OGF, 0x67),
75 DebugInit = opcode(SHCI_OGF, 0x68),
76 FlashEraseActivity = opcode(SHCI_OGF, 0x69),
77 ConcurrentSetMode = opcode(SHCI_OGF, 0x6a),
78 FlashStoreData = opcode(SHCI_OGF, 0x6b),
79 FlashEraseData = opcode(SHCI_OGF, 0x6c),
80 RadioAllowLowPower = opcode(SHCI_OGF, 0x6d),
81 Mac802_15_4Init = opcode(SHCI_OGF, 0x6e),
82 ReInit = opcode(SHCI_OGF, 0x6f),
83 ZigbeeInit = opcode(SHCI_OGF, 0x70),
84 LldTestsInit = opcode(SHCI_OGF, 0x71),
85 ExtraConfig = opcode(SHCI_OGF, 0x72),
86 SetFlashActivityControl = opcode(SHCI_OGF, 0x73),
87 BleLldInit = opcode(SHCI_OGF, 0x74),
88 Config = opcode(SHCI_OGF, 0x75),
89 ConcurrentGetNextBleEvtTime = opcode(SHCI_OGF, 0x76),
90 ConcurrentEnableNext802_15_4EvtNotification = opcode(SHCI_OGF, 0x77),
91 Mac802_15_4DeInit = opcode(SHCI_OGF, 0x78),
92}
93
94pub const SHCI_C2_CONFIG_EVTMASK1_BIT0_ERROR_NOTIF_ENABLE: u8 = 1 << 0;
95pub const SHCI_C2_CONFIG_EVTMASK1_BIT1_BLE_NVM_RAM_UPDATE_ENABLE: u8 = 1 << 1;
96pub const SHCI_C2_CONFIG_EVTMASK1_BIT2_THREAD_NVM_RAM_UPDATE_ENABLE: u8 = 1 << 2;
97pub const SHCI_C2_CONFIG_EVTMASK1_BIT3_NVM_START_WRITE_ENABLE: u8 = 1 << 3;
98pub const SHCI_C2_CONFIG_EVTMASK1_BIT4_NVM_END_WRITE_ENABLE: u8 = 1 << 4;
99pub const SHCI_C2_CONFIG_EVTMASK1_BIT5_NVM_START_ERASE_ENABLE: u8 = 1 << 5;
100pub const SHCI_C2_CONFIG_EVTMASK1_BIT6_NVM_END_ERASE_ENABLE: u8 = 1 << 6;
101
102#[derive(Clone, Copy)]
103#[repr(C, packed)]
104pub struct ShciConfigParam {
105 pub payload_cmd_size: u8,
106 pub config: u8,
107 pub event_mask: u8,
108 pub spare: u8,
109 pub ble_nvm_ram_address: u32,
110 pub thread_nvm_ram_address: u32,
111 pub revision_id: u16,
112 pub device_id: u16,
113}
114
115impl ShciConfigParam {
116 pub fn payload<'a>(&'a self) -> &'a [u8] {
117 unsafe { slice::from_raw_parts(self as *const _ as *const u8, mem::size_of::<Self>()) }
118 }
119}
120
121impl Default for ShciConfigParam {
122 fn default() -> Self {
123 Self {
124 payload_cmd_size: (mem::size_of::<Self>() - 1) as u8,
125 config: 0,
126 event_mask: SHCI_C2_CONFIG_EVTMASK1_BIT0_ERROR_NOTIF_ENABLE
127 + SHCI_C2_CONFIG_EVTMASK1_BIT1_BLE_NVM_RAM_UPDATE_ENABLE
128 + SHCI_C2_CONFIG_EVTMASK1_BIT2_THREAD_NVM_RAM_UPDATE_ENABLE
129 + SHCI_C2_CONFIG_EVTMASK1_BIT3_NVM_START_WRITE_ENABLE
130 + SHCI_C2_CONFIG_EVTMASK1_BIT4_NVM_END_WRITE_ENABLE
131 + SHCI_C2_CONFIG_EVTMASK1_BIT5_NVM_START_ERASE_ENABLE
132 + SHCI_C2_CONFIG_EVTMASK1_BIT6_NVM_END_ERASE_ENABLE,
133 spare: 0,
134 ble_nvm_ram_address: 0,
135 thread_nvm_ram_address: 0,
136 revision_id: 0,
137 device_id: 0,
138 }
139 }
140}
141
142#[derive(Clone, Copy)]
8#[repr(C, packed)] 143#[repr(C, packed)]
9pub struct ShciBleInitCmdParam { 144pub struct ShciBleInitCmdParam {
10 /// NOT USED CURRENTLY 145 /// NOT USED - shall be set to 0
11 pub p_ble_buffer_address: u32, 146 pub p_ble_buffer_address: u32,
12 147 /// NOT USED - shall be set to 0
13 /// Size of the Buffer allocated in pBleBufferAddress
14 pub ble_buffer_size: u32, 148 pub ble_buffer_size: u32,
15 149 /// Maximum number of attribute records related to all the required characteristics (excluding the services)
150 /// that can be stored in the GATT database, for the specific BLE user application.
151 /// For each characteristic, the number of attribute records goes from two to five depending on the characteristic properties:
152 /// - minimum of two (one for declaration and one for the value)
153 /// - add one more record for each additional property: notify or indicate, broadcast, extended property.
154 /// The total calculated value must be increased by 9, due to the records related to the standard attribute profile and
155 /// GAP service characteristics, and automatically added when initializing GATT and GAP layers
156 /// - Min value: <number of user attributes> + 9
157 /// - Max value: depending on the GATT database defined by user application
16 pub num_attr_record: u16, 158 pub num_attr_record: u16,
159 /// Defines the maximum number of services that can be stored in the GATT database. Note that the GAP and GATT services
160 /// are automatically added at initialization so this parameter must be the number of user services increased by two.
161 /// - Min value: <number of user service> + 2
162 /// - Max value: depending GATT database defined by user application
17 pub num_attr_serv: u16, 163 pub num_attr_serv: u16,
164 /// NOTE: This parameter is ignored by the CPU2 when the parameter "Options" is set to "LL_only" ( see Options description in that structure )
165 ///
166 /// Size of the storage area for the attribute values.
167 /// Each characteristic contributes to the attrValueArrSize value as follows:
168 /// - Characteristic value length plus:
169 /// + 5 bytes if characteristic UUID is 16 bits
170 /// + 19 bytes if characteristic UUID is 128 bits
171 /// + 2 bytes if characteristic has a server configuration descriptor
172 /// + 2 bytes * NumOfLinks if the characteristic has a client configuration descriptor
173 /// + 2 bytes if the characteristic has extended properties
174 /// Each descriptor contributes to the attrValueArrSize value as follows:
175 /// - Descriptor length
18 pub attr_value_arr_size: u16, 176 pub attr_value_arr_size: u16,
177 /// Maximum number of BLE links supported
178 /// - Min value: 1
179 /// - Max value: 8
19 pub num_of_links: u8, 180 pub num_of_links: u8,
181 /// Disable/enable the extended packet length BLE 5.0 feature
182 /// - Disable: 0
183 /// - Enable: 1
20 pub extended_packet_length_enable: u8, 184 pub extended_packet_length_enable: u8,
21 pub pr_write_list_size: u8, 185 /// NOTE: This parameter is ignored by the CPU2 when the parameter "Options" is set to "LL_only" ( see Options description in that structure )
22 pub mb_lock_count: u8, 186 ///
23 187 /// Maximum number of supported "prepare write request"
188 /// - Min value: given by the macro DEFAULT_PREP_WRITE_LIST_SIZE
189 /// - Max value: a value higher than the minimum required can be specified, but it is not recommended
190 pub prepare_write_list_size: u8,
191 /// NOTE: This parameter is overwritten by the CPU2 with an hardcoded optimal value when the parameter "Options" is set to "LL_only"
192 /// ( see Options description in that structure )
193 ///
194 /// Number of allocated memory blocks for the BLE stack
195 /// - Min value: given by the macro MBLOCKS_CALC
196 /// - Max value: a higher value can improve data throughput performance, but uses more memory
197 pub block_count: u8,
198 /// NOTE: This parameter is ignored by the CPU2 when the parameter "Options" is set to "LL_only" ( see Options description in that structure )
199 ///
200 /// Maximum ATT MTU size supported
201 /// - Min value: 23
202 /// - Max value: 512
24 pub att_mtu: u16, 203 pub att_mtu: u16,
204 /// The sleep clock accuracy (ppm value) that used in BLE connected slave mode to calculate the window widening
205 /// (in combination with the sleep clock accuracy sent by master in CONNECT_REQ PDU),
206 /// refer to BLE 5.0 specifications - Vol 6 - Part B - chap 4.5.7 and 4.2.2
207 /// - Min value: 0
208 /// - Max value: 500 (worst possible admitted by specification)
25 pub slave_sca: u16, 209 pub slave_sca: u16,
210 /// The sleep clock accuracy handled in master mode. It is used to determine the connection and advertising events timing.
211 /// It is transmitted to the slave in CONNEC_REQ PDU used by the slave to calculate the window widening,
212 /// see SlaveSca and Bluetooth Core Specification v5.0 Vol 6 - Part B - chap 4.5.7 and 4.2.2
213 /// Possible values:
214 /// - 251 ppm to 500 ppm: 0
215 /// - 151 ppm to 250 ppm: 1
216 /// - 101 ppm to 150 ppm: 2
217 /// - 76 ppm to 100 ppm: 3
218 /// - 51 ppm to 75 ppm: 4
219 /// - 31 ppm to 50 ppm: 5
220 /// - 21 ppm to 30 ppm: 6
221 /// - 0 ppm to 20 ppm: 7
26 pub master_sca: u8, 222 pub master_sca: u8,
223 /// Some information for Low speed clock mapped in bits field
224 /// - bit 0:
225 /// - 1: Calibration for the RF system wakeup clock source
226 /// - 0: No calibration for the RF system wakeup clock source
227 /// - bit 1:
228 /// - 1: STM32W5M Module device
229 /// - 0: Other devices as STM32WBxx SOC, STM32WB1M module
230 /// - bit 2:
231 /// - 1: HSE/1024 Clock config
232 /// - 0: LSE Clock config
27 pub ls_source: u8, 233 pub ls_source: u8,
234 /// This parameter determines the maximum duration of a slave connection event. When this duration is reached the slave closes
235 /// the current connections event (whatever is the CE_length parameter specified by the master in HCI_CREATE_CONNECTION HCI command),
236 /// expressed in units of 625/256 µs (~2.44 µs)
237 /// - Min value: 0 (if 0 is specified, the master and slave perform only a single TX-RX exchange per connection event)
238 /// - Max value: 1638400 (4000 ms). A higher value can be specified (max 0xFFFFFFFF) but results in a maximum connection time
239 /// of 4000 ms as specified. In this case the parameter is not applied, and the predicted CE length calculated on slave is not shortened
28 pub max_conn_event_length: u32, 240 pub max_conn_event_length: u32,
241 /// Startup time of the high speed (16 or 32 MHz) crystal oscillator in units of 625/256 µs (~2.44 µs).
242 /// - Min value: 0
243 /// - Max value: 820 (~2 ms). A higher value can be specified, but the value that implemented in stack is forced to ~2 ms
29 pub hs_startup_time: u16, 244 pub hs_startup_time: u16,
245 /// Viterbi implementation in BLE LL reception.
246 /// - 0: Enable
247 /// - 1: Disable
30 pub viterbi_enable: u8, 248 pub viterbi_enable: u8,
31 pub ll_only: u8, 249 /// - bit 0:
250 /// - 1: LL only
251 /// - 0: LL + host
252 /// - bit 1:
253 /// - 1: no service change desc.
254 /// - 0: with service change desc.
255 /// - bit 2:
256 /// - 1: device name Read-Only
257 /// - 0: device name R/W
258 /// - bit 3:
259 /// - 1: extended advertizing supported
260 /// - 0: extended advertizing not supported
261 /// - bit 4:
262 /// - 1: CS Algo #2 supported
263 /// - 0: CS Algo #2 not supported
264 /// - bit 5:
265 /// - 1: Reduced GATT database in NVM
266 /// - 0: Full GATT database in NVM
267 /// - bit 6:
268 /// - 1: GATT caching is used
269 /// - 0: GATT caching is not used
270 /// - bit 7:
271 /// - 1: LE Power Class 1
272 /// - 0: LE Power Classe 2-3
273 /// - other bits: complete with Options_extension flag
274 pub options: u8,
275 /// Reserved for future use - shall be set to 0
32 pub hw_version: u8, 276 pub hw_version: u8,
277 // /**
278 // * Maximum number of connection-oriented channels in initiator mode.
279 // * Range: 0 .. 64
280 // */
281 // pub max_coc_initiator_nbr: u8,
282 //
283 // /**
284 // * Minimum transmit power in dBm supported by the Controller.
285 // * Range: -127 .. 20
286 // */
287 // pub min_tx_power: i8,
288 //
289 // /**
290 // * Maximum transmit power in dBm supported by the Controller.
291 // * Range: -127 .. 20
292 // */
293 // pub max_tx_power: i8,
294 //
295 // /**
296 // * RX model configuration
297 // * - bit 0: 1: agc_rssi model improved vs RF blockers 0: Legacy agc_rssi model
298 // * - other bits: reserved ( shall be set to 0)
299 // */
300 // pub rx_model_config: u8,
301 //
302 // /* Maximum number of advertising sets.
303 // * Range: 1 .. 8 with limitation:
304 // * This parameter is linked to max_adv_data_len such as both compliant with allocated Total memory computed with BLE_EXT_ADV_BUFFER_SIZE based
305 // * on Max Extended advertising configuration supported.
306 // * This parameter is considered by the CPU2 when Options has SHCI_C2_BLE_INIT_OPTIONS_EXT_ADV flag set
307 // */
308 // pub max_adv_set_nbr: u8,
309 //
310 // /* Maximum advertising data length (in bytes)
311 // * Range: 31 .. 1650 with limitation:
312 // * This parameter is linked to max_adv_set_nbr such as both compliant with allocated Total memory computed with BLE_EXT_ADV_BUFFER_SIZE based
313 // * on Max Extended advertising configuration supported.
314 // * This parameter is considered by the CPU2 when Options has SHCI_C2_BLE_INIT_OPTIONS_EXT_ADV flag set
315 // */
316 // pub max_adv_data_len: u16,
317 //
318 // /* RF TX Path Compensation Value (16-bit signed integer). Units: 0.1 dB.
319 // * Range: -1280 .. 1280
320 // */
321 // pub tx_path_compens: i16,
322 //
323 // /* RF RX Path Compensation Value (16-bit signed integer). Units: 0.1 dB.
324 // * Range: -1280 .. 1280
325 // */
326 // pub rx_path_compens: i16,
327 //
328 // /* BLE core specification version (8-bit unsigned integer).
329 // * values as: 11(5.2), 12(5.3)
330 // */
331 // pub ble_core_version: u8,
332 //
333 // /**
334 // * Options flags extension
335 // * - bit 0: 1: appearance Writable 0: appearance Read-Only
336 // * - bit 1: 1: Enhanced ATT supported 0: Enhanced ATT not supported
337 // * - other bits: reserved ( shall be set to 0)
338 // */
339 // pub options_extension: u8,
33} 340}
34 341
35impl ShciBleInitCmdParam { 342impl ShciBleInitCmdParam {
36 pub fn payload<'a>(&self) -> &'a [u8] { 343 pub fn payload<'a>(&'a self) -> &'a [u8] {
37 unsafe { slice::from_raw_parts(self as *const _ as *const u8, mem::size_of::<Self>()) } 344 unsafe { slice::from_raw_parts(self as *const _ as *const u8, mem::size_of::<Self>()) }
38 } 345 }
39} 346}
@@ -48,8 +355,8 @@ impl Default for ShciBleInitCmdParam {
48 attr_value_arr_size: 1344, 355 attr_value_arr_size: 1344,
49 num_of_links: 2, 356 num_of_links: 2,
50 extended_packet_length_enable: 1, 357 extended_packet_length_enable: 1,
51 pr_write_list_size: 0x3A, 358 prepare_write_list_size: 0x3A,
52 mb_lock_count: 0x79, 359 block_count: 0x79,
53 att_mtu: 156, 360 att_mtu: 156,
54 slave_sca: 500, 361 slave_sca: 500,
55 master_sca: 0, 362 master_sca: 0,
@@ -57,25 +364,12 @@ impl Default for ShciBleInitCmdParam {
57 max_conn_event_length: 0xFFFFFFFF, 364 max_conn_event_length: 0xFFFFFFFF,
58 hs_startup_time: 0x148, 365 hs_startup_time: 0x148,
59 viterbi_enable: 1, 366 viterbi_enable: 1,
60 ll_only: 0, 367 options: 0,
61 hw_version: 0, 368 hw_version: 0,
62 } 369 }
63 } 370 }
64} 371}
65 372
66#[derive(Debug, Clone, Copy, Default)]
67#[repr(C, packed)]
68pub struct ShciHeader {
69 metadata: [u32; 3],
70}
71
72#[derive(Debug, Clone, Copy)]
73#[repr(C, packed)]
74pub struct ShciBleInitCmdPacket {
75 pub header: ShciHeader,
76 pub param: ShciBleInitCmdParam,
77}
78
79pub const TL_BLE_EVT_CS_PACKET_SIZE: usize = TL_EVT_HEADER_SIZE + TL_CS_EVT_SIZE; 373pub const TL_BLE_EVT_CS_PACKET_SIZE: usize = TL_EVT_HEADER_SIZE + TL_CS_EVT_SIZE;
80#[allow(dead_code)] // Not used currently but reserved 374#[allow(dead_code)] // Not used currently but reserved
81const TL_BLE_EVT_CS_BUFFER_SIZE: usize = TL_PACKET_HEADER_SIZE + TL_BLE_EVT_CS_PACKET_SIZE; 375const TL_BLE_EVT_CS_BUFFER_SIZE: usize = TL_PACKET_HEADER_SIZE + TL_BLE_EVT_CS_PACKET_SIZE;
diff --git a/embassy-stm32-wpan/src/sys.rs b/embassy-stm32-wpan/src/sys.rs
index a185cd4f1..2b699b725 100644
--- a/embassy-stm32-wpan/src/sys.rs
+++ b/embassy-stm32-wpan/src/sys.rs
@@ -1,9 +1,11 @@
1use core::marker::PhantomData; 1use core::marker::PhantomData;
2use core::ptr;
2 3
3use crate::cmd::CmdPacket; 4use crate::cmd::CmdPacket;
4use crate::consts::TlPacketType; 5use crate::consts::TlPacketType;
5use crate::evt::EvtBox; 6use crate::evt::{CcEvt, EvtBox, EvtPacket};
6use crate::shci::{ShciBleInitCmdParam, SCHI_OPCODE_BLE_INIT}; 7#[allow(unused_imports)]
8use crate::shci::{SchiCommandStatus, ShciBleInitCmdParam, ShciOpcode};
7use crate::tables::{SysTable, WirelessFwInfoTable}; 9use crate::tables::{SysTable, WirelessFwInfoTable};
8use crate::unsafe_linked_list::LinkedListNode; 10use crate::unsafe_linked_list::LinkedListNode;
9use crate::{channels, Ipcc, SYSTEM_EVT_QUEUE, SYS_CMD_BUF, TL_DEVICE_INFO_TABLE, TL_SYS_TABLE}; 11use crate::{channels, Ipcc, SYSTEM_EVT_QUEUE, SYS_CMD_BUF, TL_DEVICE_INFO_TABLE, TL_SYS_TABLE};
@@ -39,21 +41,35 @@ impl Sys {
39 } 41 }
40 } 42 }
41 43
42 pub fn write(&self, opcode: u16, payload: &[u8]) { 44 pub async fn write(&self, opcode: ShciOpcode, payload: &[u8]) {
45 Ipcc::send(channels::cpu1::IPCC_SYSTEM_CMD_RSP_CHANNEL, || unsafe {
46 CmdPacket::write_into(SYS_CMD_BUF.as_mut_ptr(), TlPacketType::SysCmd, opcode as u16, payload);
47 })
48 .await;
49 }
50
51 /// `HW_IPCC_SYS_CmdEvtNot`
52 pub async fn write_and_get_response(&self, opcode: ShciOpcode, payload: &[u8]) -> SchiCommandStatus {
53 self.write(opcode, payload).await;
54 Ipcc::flush(channels::cpu1::IPCC_SYSTEM_CMD_RSP_CHANNEL).await;
55
43 unsafe { 56 unsafe {
44 CmdPacket::write_into(SYS_CMD_BUF.as_mut_ptr(), TlPacketType::SysCmd, opcode, payload); 57 let p_event_packet = SYS_CMD_BUF.as_ptr() as *const EvtPacket;
58 let p_command_event = &((*p_event_packet).evt_serial.evt.payload) as *const _ as *const CcEvt;
59 let p_payload = &((*p_command_event).payload) as *const u8;
60
61 ptr::read_volatile(p_payload).try_into().unwrap()
45 } 62 }
46 } 63 }
47 64
48 pub async fn shci_c2_ble_init(&self, param: ShciBleInitCmdParam) { 65 #[cfg(feature = "mac")]
49 debug!("sending SHCI"); 66 pub async fn shci_c2_mac_802_15_4_init(&self) -> SchiCommandStatus {
50 67 self.write_and_get_response(ShciOpcode::Mac802_15_4Init, &[]).await
51 Ipcc::send(channels::cpu1::IPCC_SYSTEM_CMD_RSP_CHANNEL, || { 68 }
52 self.write(SCHI_OPCODE_BLE_INIT, param.payload());
53 })
54 .await;
55 69
56 Ipcc::flush(channels::cpu1::IPCC_SYSTEM_CMD_RSP_CHANNEL).await; 70 #[cfg(feature = "ble")]
71 pub async fn shci_c2_ble_init(&self, param: ShciBleInitCmdParam) -> SchiCommandStatus {
72 self.write_and_get_response(ShciOpcode::BleInit, param.payload()).await
57 } 73 }
58 74
59 /// `HW_IPCC_SYS_EvtNot` 75 /// `HW_IPCC_SYS_EvtNot`
diff --git a/embassy-stm32-wpan/src/tables.rs b/embassy-stm32-wpan/src/tables.rs
index 151216958..3f26282c6 100644
--- a/embassy-stm32-wpan/src/tables.rs
+++ b/embassy-stm32-wpan/src/tables.rs
@@ -1,6 +1,9 @@
1use core::mem::MaybeUninit;
2
1use bit_field::BitField; 3use bit_field::BitField;
2 4
3use crate::cmd::{AclDataPacket, CmdPacket}; 5use crate::cmd::{AclDataPacket, CmdPacket};
6use crate::consts::{POOL_SIZE, TL_CS_EVT_SIZE, TL_EVT_HEADER_SIZE, TL_PACKET_HEADER_SIZE};
4use crate::unsafe_linked_list::LinkedListNode; 7use crate::unsafe_linked_list::LinkedListNode;
5 8
6#[derive(Debug, Copy, Clone)] 9#[derive(Debug, Copy, Clone)]
@@ -161,6 +164,9 @@ pub struct Mac802_15_4Table {
161 pub evt_queue: *const u8, 164 pub evt_queue: *const u8,
162} 165}
163 166
167#[repr(C, align(4))]
168pub struct AlignedData<const L: usize>([u8; L]);
169
164/// Reference table. Contains pointers to all other tables. 170/// Reference table. Contains pointers to all other tables.
165#[derive(Debug, Copy, Clone)] 171#[derive(Debug, Copy, Clone)]
166#[repr(C)] 172#[repr(C)]
@@ -173,3 +179,94 @@ pub struct RefTable {
173 pub traces_table: *const TracesTable, 179 pub traces_table: *const TracesTable,
174 pub mac_802_15_4_table: *const Mac802_15_4Table, 180 pub mac_802_15_4_table: *const Mac802_15_4Table,
175} 181}
182
183// --------------------- ref table ---------------------
184#[link_section = "TL_REF_TABLE"]
185pub static mut TL_REF_TABLE: MaybeUninit<RefTable> = MaybeUninit::uninit();
186
187#[link_section = "MB_MEM1"]
188pub static mut TL_DEVICE_INFO_TABLE: MaybeUninit<DeviceInfoTable> = MaybeUninit::uninit();
189
190#[link_section = "MB_MEM1"]
191pub static mut TL_BLE_TABLE: MaybeUninit<BleTable> = MaybeUninit::uninit();
192
193#[link_section = "MB_MEM1"]
194pub static mut TL_THREAD_TABLE: MaybeUninit<ThreadTable> = MaybeUninit::uninit();
195
196// #[link_section = "MB_MEM1"]
197// pub static mut TL_LLD_TESTS_TABLE: MaybeUninit<LldTestTable> = MaybeUninit::uninit();
198
199// #[link_section = "MB_MEM1"]
200// pub static mut TL_BLE_LLD_TABLE: MaybeUninit<BleLldTable> = MaybeUninit::uninit();
201
202#[link_section = "MB_MEM1"]
203pub static mut TL_SYS_TABLE: MaybeUninit<SysTable> = MaybeUninit::uninit();
204
205#[link_section = "MB_MEM1"]
206pub static mut TL_MEM_MANAGER_TABLE: MaybeUninit<MemManagerTable> = MaybeUninit::uninit();
207
208#[link_section = "MB_MEM1"]
209pub static mut TL_TRACES_TABLE: MaybeUninit<TracesTable> = MaybeUninit::uninit();
210
211#[link_section = "MB_MEM1"]
212pub static mut TL_MAC_802_15_4_TABLE: MaybeUninit<Mac802_15_4Table> = MaybeUninit::uninit();
213
214// #[link_section = "MB_MEM1"]
215// pub static mut TL_ZIGBEE_TABLE: MaybeUninit<ZigbeeTable> = MaybeUninit::uninit();
216
217// --------------------- tables ---------------------
218#[link_section = "MB_MEM1"]
219pub static mut FREE_BUF_QUEUE: MaybeUninit<LinkedListNode> = MaybeUninit::uninit();
220
221#[allow(dead_code)]
222#[link_section = "MB_MEM1"]
223pub static mut TRACES_EVT_QUEUE: MaybeUninit<LinkedListNode> = MaybeUninit::uninit();
224
225const CS_BUFFER_SIZE: usize = TL_PACKET_HEADER_SIZE + TL_EVT_HEADER_SIZE + TL_CS_EVT_SIZE;
226
227#[link_section = "MB_MEM2"]
228pub static mut CS_BUFFER: MaybeUninit<AlignedData<CS_BUFFER_SIZE>> = MaybeUninit::uninit();
229
230#[link_section = "MB_MEM2"]
231pub static mut EVT_QUEUE: MaybeUninit<LinkedListNode> = MaybeUninit::uninit();
232
233#[link_section = "MB_MEM2"]
234pub static mut SYSTEM_EVT_QUEUE: MaybeUninit<LinkedListNode> = MaybeUninit::uninit();
235
236// --------------------- app tables ---------------------
237#[cfg(feature = "mac")]
238#[link_section = "MB_MEM2"]
239pub static mut MAC_802_15_4_CMD_BUFFER: MaybeUninit<CmdPacket> = MaybeUninit::uninit();
240
241#[cfg(feature = "mac")]
242const MAC_802_15_4_NOTIF_RSP_EVT_BUFFER_SIZE: usize = TL_PACKET_HEADER_SIZE + TL_EVT_HEADER_SIZE + 255;
243
244#[cfg(feature = "mac")]
245#[link_section = "MB_MEM2"]
246pub static mut MAC_802_15_4_NOTIF_RSP_EVT_BUFFER: MaybeUninit<AlignedData<MAC_802_15_4_NOTIF_RSP_EVT_BUFFER_SIZE>> =
247 MaybeUninit::uninit();
248
249#[link_section = "MB_MEM2"]
250pub static mut EVT_POOL: MaybeUninit<[u8; POOL_SIZE]> = MaybeUninit::uninit();
251
252#[link_section = "MB_MEM2"]
253pub static mut SYS_CMD_BUF: MaybeUninit<CmdPacket> = MaybeUninit::uninit();
254
255const SYS_SPARE_EVT_BUF_SIZE: usize = TL_PACKET_HEADER_SIZE + TL_EVT_HEADER_SIZE + 255;
256
257#[link_section = "MB_MEM2"]
258pub static mut SYS_SPARE_EVT_BUF: MaybeUninit<AlignedData<SYS_SPARE_EVT_BUF_SIZE>> = MaybeUninit::uninit();
259
260#[link_section = "MB_MEM1"]
261pub static mut BLE_CMD_BUFFER: MaybeUninit<CmdPacket> = MaybeUninit::uninit();
262
263const BLE_SPARE_EVT_BUF_SIZE: usize = TL_PACKET_HEADER_SIZE + TL_EVT_HEADER_SIZE + 255;
264
265#[link_section = "MB_MEM2"]
266pub static mut BLE_SPARE_EVT_BUF: MaybeUninit<AlignedData<BLE_SPARE_EVT_BUF_SIZE>> = MaybeUninit::uninit();
267
268const HCI_ACL_DATA_BUFFER_SIZE: usize = TL_PACKET_HEADER_SIZE + 5 + 251;
269
270#[link_section = "MB_MEM2"]
271// fuck these "magic" numbers from ST ---v---v
272pub static mut HCI_ACL_DATA_BUFFER: MaybeUninit<[u8; HCI_ACL_DATA_BUFFER_SIZE]> = MaybeUninit::uninit();
diff --git a/embassy-stm32/src/ipcc.rs b/embassy-stm32/src/ipcc.rs
index 3062226c7..37f840c73 100644
--- a/embassy-stm32/src/ipcc.rs
+++ b/embassy-stm32/src/ipcc.rs
@@ -120,7 +120,6 @@ impl Ipcc {
120 let regs = IPCC::regs(); 120 let regs = IPCC::regs();
121 121
122 Self::flush(channel).await; 122 Self::flush(channel).await;
123 compiler_fence(Ordering::SeqCst);
124 123
125 f(); 124 f();
126 125
@@ -136,7 +135,7 @@ impl Ipcc {
136 135
137 // This is a race, but is nice for debugging 136 // This is a race, but is nice for debugging
138 if regs.cpu(0).sr().read().chf(channel as usize) { 137 if regs.cpu(0).sr().read().chf(channel as usize) {
139 trace!("ipcc: ch {}: wait for tx free", channel as u8); 138 trace!("ipcc: ch {}: wait for tx free", channel as u8);
140 } 139 }
141 140
142 poll_fn(|cx| { 141 poll_fn(|cx| {
@@ -165,7 +164,7 @@ impl Ipcc {
165 loop { 164 loop {
166 // This is a race, but is nice for debugging 165 // This is a race, but is nice for debugging
167 if !regs.cpu(1).sr().read().chf(channel as usize) { 166 if !regs.cpu(1).sr().read().chf(channel as usize) {
168 trace!("ipcc: ch {}: wait for rx occupied", channel as u8); 167 trace!("ipcc: ch {}: wait for rx occupied", channel as u8);
169 } 168 }
170 169
171 poll_fn(|cx| { 170 poll_fn(|cx| {
@@ -186,8 +185,7 @@ impl Ipcc {
186 }) 185 })
187 .await; 186 .await;
188 187
189 trace!("ipcc: ch {}: read data", channel as u8); 188 trace!("ipcc: ch {}: read data", channel as u8);
190 compiler_fence(Ordering::SeqCst);
191 189
192 match f() { 190 match f() {
193 Some(ret) => return ret, 191 Some(ret) => return ret,
@@ -237,7 +235,7 @@ pub(crate) mod sealed {
237 } 235 }
238 } 236 }
239 237
240 pub fn rx_waker_for(&self, channel: IpccChannel) -> &AtomicWaker { 238 pub const fn rx_waker_for(&self, channel: IpccChannel) -> &AtomicWaker {
241 match channel { 239 match channel {
242 IpccChannel::Channel1 => &self.rx_wakers[0], 240 IpccChannel::Channel1 => &self.rx_wakers[0],
243 IpccChannel::Channel2 => &self.rx_wakers[1], 241 IpccChannel::Channel2 => &self.rx_wakers[1],
@@ -248,7 +246,7 @@ pub(crate) mod sealed {
248 } 246 }
249 } 247 }
250 248
251 pub fn tx_waker_for(&self, channel: IpccChannel) -> &AtomicWaker { 249 pub const fn tx_waker_for(&self, channel: IpccChannel) -> &AtomicWaker {
252 match channel { 250 match channel {
253 IpccChannel::Channel1 => &self.tx_wakers[0], 251 IpccChannel::Channel1 => &self.tx_wakers[0],
254 IpccChannel::Channel2 => &self.tx_wakers[1], 252 IpccChannel::Channel2 => &self.tx_wakers[1],
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/examples/stm32wb/.cargo/config.toml b/examples/stm32wb/.cargo/config.toml
index d23fdc513..35317a297 100644
--- a/examples/stm32wb/.cargo/config.toml
+++ b/examples/stm32wb/.cargo/config.toml
@@ -1,6 +1,6 @@
1[target.'cfg(all(target_arch = "arm", target_os = "none"))'] 1[target.'cfg(all(target_arch = "arm", target_os = "none"))']
2# replace STM32WB55CCUx with your chip as listed in `probe-rs-cli chip list` 2# replace STM32WB55CCUx with your chip as listed in `probe-rs-cli chip list`
3# runner = "probe-rs-cli run --chip STM32WB55CCUx --speed 1000 --connect-under-reset" 3# runner = "probe-rs-cli run --chip STM32WB55RGVx --speed 1000 --connect-under-reset"
4runner = "teleprobe local run --chip STM32WB55RG --elf" 4runner = "teleprobe local run --chip STM32WB55RG --elf"
5 5
6[build] 6[build]
diff --git a/examples/stm32wb/Cargo.toml b/examples/stm32wb/Cargo.toml
index 83a443754..fbb2d918b 100644
--- a/examples/stm32wb/Cargo.toml
+++ b/examples/stm32wb/Cargo.toml
@@ -20,3 +20,24 @@ embedded-hal = "0.2.6"
20panic-probe = { version = "0.3", features = ["print-defmt"] } 20panic-probe = { version = "0.3", features = ["print-defmt"] }
21futures = { version = "0.3.17", default-features = false, features = ["async-await"] } 21futures = { version = "0.3.17", default-features = false, features = ["async-await"] }
22heapless = { version = "0.7.5", default-features = false } 22heapless = { version = "0.7.5", default-features = false }
23
24
25[features]
26default = ["ble"]
27mac = ["embassy-stm32-wpan/mac"]
28ble = ["embassy-stm32-wpan/ble"]
29
30[[bin]]
31name = "tl_mbox_ble"
32required-features = ["ble"]
33
34[[bin]]
35name = "tl_mbox_mac"
36required-features = ["mac"]
37
38[[bin]]
39name = "eddystone_beacon"
40required-features = ["ble"]
41
42[patch.crates-io]
43stm32wb-hci = { git = "https://github.com/OueslatiGhaith/stm32wb-hci", rev = "9f663be"} \ No newline at end of file
diff --git a/examples/stm32wb/src/bin/eddystone_beacon.rs b/examples/stm32wb/src/bin/eddystone_beacon.rs
new file mode 100644
index 000000000..fdd5be4a2
--- /dev/null
+++ b/examples/stm32wb/src/bin/eddystone_beacon.rs
@@ -0,0 +1,249 @@
1#![no_std]
2#![no_main]
3#![feature(type_alias_impl_trait)]
4
5use core::time::Duration;
6
7use defmt::*;
8use embassy_executor::Spawner;
9use embassy_stm32::bind_interrupts;
10use embassy_stm32::ipcc::{Config, ReceiveInterruptHandler, TransmitInterruptHandler};
11use embassy_stm32_wpan::ble::hci::host::uart::UartHci;
12use embassy_stm32_wpan::ble::hci::host::{AdvertisingFilterPolicy, EncryptionKey, HostHci, OwnAddressType};
13use embassy_stm32_wpan::ble::hci::types::AdvertisingType;
14use embassy_stm32_wpan::ble::hci::vendor::stm32wb::command::gap::{
15 AdvertisingDataType, DiscoverableParameters, GapCommands, Role,
16};
17use embassy_stm32_wpan::ble::hci::vendor::stm32wb::command::gatt::GattCommands;
18use embassy_stm32_wpan::ble::hci::vendor::stm32wb::command::hal::{ConfigData, HalCommands, PowerLevel};
19use embassy_stm32_wpan::ble::hci::BdAddr;
20use embassy_stm32_wpan::lhci::LhciC1DeviceInformationCcrp;
21use embassy_stm32_wpan::TlMbox;
22use {defmt_rtt as _, panic_probe as _};
23
24bind_interrupts!(struct Irqs{
25 IPCC_C1_RX => ReceiveInterruptHandler;
26 IPCC_C1_TX => TransmitInterruptHandler;
27});
28
29const BLE_GAP_DEVICE_NAME_LENGTH: u8 = 7;
30
31#[embassy_executor::main]
32async fn main(_spawner: Spawner) {
33 /*
34 How to make this work:
35
36 - Obtain a NUCLEO-STM32WB55 from your preferred supplier.
37 - Download and Install STM32CubeProgrammer.
38 - Download stm32wb5x_FUS_fw.bin, stm32wb5x_BLE_Stack_full_fw.bin, and Release_Notes.html from
39 gh:STMicroelectronics/STM32CubeWB@2234d97/Projects/STM32WB_Copro_Wireless_Binaries/STM32WB5x
40 - Open STM32CubeProgrammer
41 - On the right-hand pane, click "firmware upgrade" to upgrade the st-link firmware.
42 - Once complete, click connect to connect to the device.
43 - On the left hand pane, click the RSS signal icon to open "Firmware Upgrade Services".
44 - In the Release_Notes.html, find the memory address that corresponds to your device for the stm32wb5x_FUS_fw.bin file
45 - Select that file, the memory address, "verify download", and then "Firmware Upgrade".
46 - Once complete, in the Release_Notes.html, find the memory address that corresponds to your device for the
47 stm32wb5x_BLE_Stack_full_fw.bin file. It should not be the same memory address.
48 - Select that file, the memory address, "verify download", and then "Firmware Upgrade".
49 - Select "Start Wireless Stack".
50 - Disconnect from the device.
51 - In the examples folder for stm32wb, modify the memory.x file to match your target device.
52 - Run this example.
53
54 Note: extended stack versions are not supported at this time. Do not attempt to install a stack with "extended" in the name.
55 */
56
57 let p = embassy_stm32::init(Default::default());
58 info!("Hello World!");
59
60 let config = Config::default();
61 let mut mbox = TlMbox::init(p.IPCC, Irqs, config);
62
63 let sys_event = mbox.sys_subsystem.read().await;
64 info!("sys event: {}", sys_event.payload());
65
66 mbox.sys_subsystem.shci_c2_ble_init(Default::default()).await;
67
68 info!("resetting BLE...");
69 mbox.ble_subsystem.reset().await;
70 let response = mbox.ble_subsystem.read().await.unwrap();
71 defmt::info!("{}", response);
72
73 info!("config public address...");
74 mbox.ble_subsystem
75 .write_config_data(&ConfigData::public_address(get_bd_addr()).build())
76 .await;
77 let response = mbox.ble_subsystem.read().await.unwrap();
78 defmt::info!("{}", response);
79
80 info!("config random address...");
81 mbox.ble_subsystem
82 .write_config_data(&ConfigData::random_address(get_random_addr()).build())
83 .await;
84 let response = mbox.ble_subsystem.read().await.unwrap();
85 defmt::info!("{}", response);
86
87 info!("config identity root...");
88 mbox.ble_subsystem
89 .write_config_data(&ConfigData::identity_root(&get_irk()).build())
90 .await;
91 let response = mbox.ble_subsystem.read().await.unwrap();
92 defmt::info!("{}", response);
93
94 info!("config encryption root...");
95 mbox.ble_subsystem
96 .write_config_data(&ConfigData::encryption_root(&get_erk()).build())
97 .await;
98 let response = mbox.ble_subsystem.read().await.unwrap();
99 defmt::info!("{}", response);
100
101 info!("config tx power level...");
102 mbox.ble_subsystem.set_tx_power_level(PowerLevel::ZerodBm).await;
103 let response = mbox.ble_subsystem.read().await.unwrap();
104 defmt::info!("{}", response);
105
106 info!("GATT init...");
107 mbox.ble_subsystem.init_gatt().await;
108 let response = mbox.ble_subsystem.read().await.unwrap();
109 defmt::info!("{}", response);
110
111 info!("GAP init...");
112 mbox.ble_subsystem
113 .init_gap(Role::PERIPHERAL, false, BLE_GAP_DEVICE_NAME_LENGTH)
114 .await;
115 let response = mbox.ble_subsystem.read().await.unwrap();
116 defmt::info!("{}", response);
117
118 // info!("set scan response...");
119 // mbox.ble_subsystem.le_set_scan_response_data(&[]).await.unwrap();
120 // let response = mbox.ble_subsystem.read().await.unwrap();
121 // defmt::info!("{}", response);
122
123 info!("set discoverable...");
124 mbox.ble_subsystem
125 .set_discoverable(&DiscoverableParameters {
126 advertising_type: AdvertisingType::NonConnectableUndirected,
127 advertising_interval: Some((Duration::from_millis(250), Duration::from_millis(250))),
128 address_type: OwnAddressType::Public,
129 filter_policy: AdvertisingFilterPolicy::AllowConnectionAndScan,
130 local_name: None,
131 advertising_data: &[],
132 conn_interval: (None, None),
133 })
134 .await
135 .unwrap();
136
137 let response = mbox.ble_subsystem.read().await;
138 defmt::info!("{}", response);
139
140 // remove some advertisement to decrease the packet size
141 info!("delete tx power ad type...");
142 mbox.ble_subsystem
143 .delete_ad_type(AdvertisingDataType::TxPowerLevel)
144 .await;
145 let response = mbox.ble_subsystem.read().await.unwrap();
146 defmt::info!("{}", response);
147
148 info!("delete conn interval ad type...");
149 mbox.ble_subsystem
150 .delete_ad_type(AdvertisingDataType::PeripheralConnectionInterval)
151 .await;
152 let response = mbox.ble_subsystem.read().await.unwrap();
153 defmt::info!("{}", response);
154
155 info!("update advertising data...");
156 mbox.ble_subsystem
157 .update_advertising_data(&eddystone_advertising_data())
158 .await
159 .unwrap();
160 let response = mbox.ble_subsystem.read().await.unwrap();
161 defmt::info!("{}", response);
162
163 info!("update advertising data type...");
164 mbox.ble_subsystem
165 .update_advertising_data(&[3, AdvertisingDataType::UuidCompleteList16 as u8, 0xaa, 0xfe])
166 .await
167 .unwrap();
168 let response = mbox.ble_subsystem.read().await.unwrap();
169 defmt::info!("{}", response);
170
171 info!("update advertising data flags...");
172 mbox.ble_subsystem
173 .update_advertising_data(&[
174 2,
175 AdvertisingDataType::Flags as u8,
176 (0x02 | 0x04) as u8, // BLE general discoverable, without BR/EDR support
177 ])
178 .await
179 .unwrap();
180 let response = mbox.ble_subsystem.read().await.unwrap();
181 defmt::info!("{}", response);
182
183 cortex_m::asm::wfi();
184}
185
186fn get_bd_addr() -> BdAddr {
187 let mut bytes = [0u8; 6];
188
189 let lhci_info = LhciC1DeviceInformationCcrp::new();
190 bytes[0] = (lhci_info.uid64 & 0xff) as u8;
191 bytes[1] = ((lhci_info.uid64 >> 8) & 0xff) as u8;
192 bytes[2] = ((lhci_info.uid64 >> 16) & 0xff) as u8;
193 bytes[3] = lhci_info.device_type_id;
194 bytes[4] = (lhci_info.st_company_id & 0xff) as u8;
195 bytes[5] = (lhci_info.st_company_id >> 8 & 0xff) as u8;
196
197 BdAddr(bytes)
198}
199
200fn get_random_addr() -> BdAddr {
201 let mut bytes = [0u8; 6];
202
203 let lhci_info = LhciC1DeviceInformationCcrp::new();
204 bytes[0] = (lhci_info.uid64 & 0xff) as u8;
205 bytes[1] = ((lhci_info.uid64 >> 8) & 0xff) as u8;
206 bytes[2] = ((lhci_info.uid64 >> 16) & 0xff) as u8;
207 bytes[3] = 0;
208 bytes[4] = 0x6E;
209 bytes[5] = 0xED;
210
211 BdAddr(bytes)
212}
213
214const BLE_CFG_IRK: [u8; 16] = [
215 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0,
216];
217const BLE_CFG_ERK: [u8; 16] = [
218 0xfe, 0xdc, 0xba, 0x09, 0x87, 0x65, 0x43, 0x21, 0xfe, 0xdc, 0xba, 0x09, 0x87, 0x65, 0x43, 0x21,
219];
220
221fn get_irk() -> EncryptionKey {
222 EncryptionKey(BLE_CFG_IRK)
223}
224
225fn get_erk() -> EncryptionKey {
226 EncryptionKey(BLE_CFG_ERK)
227}
228
229fn eddystone_advertising_data() -> [u8; 24] {
230 const EDDYSTONE_URL: &[u8] = b"www.rust-lang.com";
231
232 let mut service_data = [0u8; 24];
233 let url_len = EDDYSTONE_URL.len();
234
235 service_data[0] = 6 + url_len as u8;
236 service_data[1] = AdvertisingDataType::ServiceData as u8;
237
238 // 16-bit eddystone uuid
239 service_data[2] = 0xaa;
240 service_data[3] = 0xFE;
241
242 service_data[4] = 0x10; // URL frame type
243 service_data[5] = 22_i8 as u8; // calibrated TX power at 0m
244 service_data[6] = 0x03; // eddystone url prefix = https
245
246 service_data[7..(7 + url_len)].copy_from_slice(EDDYSTONE_URL);
247
248 service_data
249}
diff --git a/examples/stm32wb/src/bin/tl_mbox_tx_rx.rs b/examples/stm32wb/src/bin/tl_mbox_ble.rs
index 439bd01ac..a511e89aa 100644
--- a/examples/stm32wb/src/bin/tl_mbox_tx_rx.rs
+++ b/examples/stm32wb/src/bin/tl_mbox_ble.rs
@@ -52,10 +52,10 @@ async fn main(_spawner: Spawner) {
52 mbox.sys_subsystem.shci_c2_ble_init(Default::default()).await; 52 mbox.sys_subsystem.shci_c2_ble_init(Default::default()).await;
53 53
54 info!("starting ble..."); 54 info!("starting ble...");
55 mbox.ble_subsystem.write(0x0c, &[]).await; 55 mbox.ble_subsystem.tl_write(0x0c, &[]).await;
56 56
57 info!("waiting for ble..."); 57 info!("waiting for ble...");
58 let ble_event = mbox.ble_subsystem.read().await; 58 let ble_event = mbox.ble_subsystem.tl_read().await;
59 59
60 info!("ble event: {}", ble_event.payload()); 60 info!("ble event: {}", ble_event.payload());
61 61
diff --git a/examples/stm32wb/src/bin/tl_mbox_mac.rs b/examples/stm32wb/src/bin/tl_mbox_mac.rs
new file mode 100644
index 000000000..afd319a41
--- /dev/null
+++ b/examples/stm32wb/src/bin/tl_mbox_mac.rs
@@ -0,0 +1,64 @@
1#![no_std]
2#![no_main]
3#![feature(type_alias_impl_trait)]
4
5use defmt::*;
6use embassy_executor::Spawner;
7use embassy_stm32::bind_interrupts;
8use embassy_stm32::ipcc::{Config, ReceiveInterruptHandler, TransmitInterruptHandler};
9use embassy_stm32_wpan::TlMbox;
10use {defmt_rtt as _, panic_probe as _};
11
12bind_interrupts!(struct Irqs{
13 IPCC_C1_RX => ReceiveInterruptHandler;
14 IPCC_C1_TX => TransmitInterruptHandler;
15});
16
17#[embassy_executor::main]
18async fn main(_spawner: Spawner) {
19 /*
20 How to make this work:
21
22 - Obtain a NUCLEO-STM32WB55 from your preferred supplier.
23 - Download and Install STM32CubeProgrammer.
24 - Download stm32wb5x_FUS_fw.bin, stm32wb5x_BLE_Stack_full_fw.bin, and Release_Notes.html from
25 gh:STMicroelectronics/STM32CubeWB@2234d97/Projects/STM32WB_Copro_Wireless_Binaries/STM32WB5x
26 - Open STM32CubeProgrammer
27 - On the right-hand pane, click "firmware upgrade" to upgrade the st-link firmware.
28 - Once complete, click connect to connect to the device.
29 - On the left hand pane, click the RSS signal icon to open "Firmware Upgrade Services".
30 - In the Release_Notes.html, find the memory address that corresponds to your device for the stm32wb5x_FUS_fw.bin file
31 - Select that file, the memory address, "verify download", and then "Firmware Upgrade".
32 - Once complete, in the Release_Notes.html, find the memory address that corresponds to your device for the
33 stm32wb5x_BLE_Stack_full_fw.bin file. It should not be the same memory address.
34 - Select that file, the memory address, "verify download", and then "Firmware Upgrade".
35 - Select "Start Wireless Stack".
36 - Disconnect from the device.
37 - In the examples folder for stm32wb, modify the memory.x file to match your target device.
38 - Run this example.
39
40 Note: extended stack versions are not supported at this time. Do not attempt to install a stack with "extended" in the name.
41 */
42
43 let p = embassy_stm32::init(Default::default());
44 info!("Hello World!");
45
46 let config = Config::default();
47 let mbox = TlMbox::init(p.IPCC, Irqs, config);
48
49 let sys_event = mbox.sys_subsystem.read().await;
50 info!("sys event: {}", sys_event.payload());
51
52 mbox.sys_subsystem.shci_c2_mac_802_15_4_init().await;
53 //
54 // info!("starting ble...");
55 // mbox.ble_subsystem.t_write(0x0c, &[]).await;
56 //
57 // info!("waiting for ble...");
58 // let ble_event = mbox.ble_subsystem.tl_read().await;
59 //
60 // info!("ble event: {}", ble_event.payload());
61
62 info!("Test OK");
63 cortex_m::asm::bkpt();
64}
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 ));
diff --git a/tests/stm32/Cargo.toml b/tests/stm32/Cargo.toml
index 365f631b7..c2422f7bc 100644
--- a/tests/stm32/Cargo.toml
+++ b/tests/stm32/Cargo.toml
@@ -30,7 +30,7 @@ embassy-executor = { version = "0.2.0", path = "../../embassy-executor", feature
30embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["defmt", "tick-hz-32_768", "defmt-timestamp-uptime"] } 30embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["defmt", "tick-hz-32_768", "defmt-timestamp-uptime"] }
31embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["nightly", "defmt", "unstable-pac", "memory-x", "time-driver-any"] } 31embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["nightly", "defmt", "unstable-pac", "memory-x", "time-driver-any"] }
32embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } 32embassy-futures = { version = "0.1.0", path = "../../embassy-futures" }
33embassy-stm32-wpan = { version = "0.1.0", path = "../../embassy-stm32-wpan", optional = true, features = ["defmt", "stm32wb55rg"] } 33embassy-stm32-wpan = { version = "0.1.0", path = "../../embassy-stm32-wpan", optional = true, features = ["defmt", "stm32wb55rg", "ble"] }
34 34
35defmt = "0.3.0" 35defmt = "0.3.0"
36defmt-rtt = "0.4" 36defmt-rtt = "0.4"
@@ -46,6 +46,9 @@ rand_chacha = { version = "0.3", default-features = false }
46 46
47chrono = { version = "^0.4", default-features = false, optional = true} 47chrono = { version = "^0.4", default-features = false, optional = true}
48 48
49[patch.crates-io]
50stm32wb-hci = { git = "https://github.com/OueslatiGhaith/stm32wb-hci", rev = "9f663be"}
51
49# BEGIN TESTS 52# BEGIN TESTS
50# Generated by gen_test.py. DO NOT EDIT. 53# Generated by gen_test.py. DO NOT EDIT.
51[[bin]] 54[[bin]]
diff --git a/tests/stm32/src/bin/tl_mbox.rs b/tests/stm32/src/bin/tl_mbox.rs
index f6641ae31..76c736a5b 100644
--- a/tests/stm32/src/bin/tl_mbox.rs
+++ b/tests/stm32/src/bin/tl_mbox.rs
@@ -6,43 +6,49 @@
6#[path = "../common.rs"] 6#[path = "../common.rs"]
7mod common; 7mod common;
8 8
9use core::mem; 9use core::time::Duration;
10 10
11use common::*; 11use common::*;
12use embassy_executor::Spawner; 12use embassy_executor::Spawner;
13use embassy_futures::poll_once;
14use embassy_stm32::bind_interrupts; 13use embassy_stm32::bind_interrupts;
15use embassy_stm32::ipcc::{Config, ReceiveInterruptHandler, TransmitInterruptHandler}; 14use embassy_stm32::ipcc::{Config, ReceiveInterruptHandler, TransmitInterruptHandler};
15use embassy_stm32_wpan::ble::hci::host::uart::UartHci;
16use embassy_stm32_wpan::ble::hci::host::{AdvertisingFilterPolicy, EncryptionKey, HostHci, OwnAddressType};
17use embassy_stm32_wpan::ble::hci::types::AdvertisingType;
18use embassy_stm32_wpan::ble::hci::vendor::stm32wb::command::gap::{
19 AdvertisingDataType, DiscoverableParameters, GapCommands, Role,
20};
21use embassy_stm32_wpan::ble::hci::vendor::stm32wb::command::gatt::GattCommands;
22use embassy_stm32_wpan::ble::hci::vendor::stm32wb::command::hal::{ConfigData, HalCommands, PowerLevel};
23use embassy_stm32_wpan::ble::hci::BdAddr;
24use embassy_stm32_wpan::lhci::LhciC1DeviceInformationCcrp;
16use embassy_stm32_wpan::{mm, TlMbox}; 25use embassy_stm32_wpan::{mm, TlMbox};
17use embassy_time::{Duration, Timer}; 26use {defmt_rtt as _, panic_probe as _};
18 27
19bind_interrupts!(struct Irqs{ 28bind_interrupts!(struct Irqs{
20 IPCC_C1_RX => ReceiveInterruptHandler; 29 IPCC_C1_RX => ReceiveInterruptHandler;
21 IPCC_C1_TX => TransmitInterruptHandler; 30 IPCC_C1_TX => TransmitInterruptHandler;
22}); 31});
23 32
33const BLE_GAP_DEVICE_NAME_LENGTH: u8 = 7;
34
24#[embassy_executor::task] 35#[embassy_executor::task]
25async fn run_mm_queue(memory_manager: mm::MemoryManager) { 36async fn run_mm_queue(memory_manager: mm::MemoryManager) {
26 memory_manager.run_queue().await; 37 memory_manager.run_queue().await;
27} 38}
28 39
29#[embassy_executor::main] 40#[embassy_executor::main]
30async fn main(spawner: Spawner) { 41async fn main(_spawner: Spawner) {
31 let p = embassy_stm32::init(config()); 42 let p = embassy_stm32::init(config());
32 info!("Hello World!"); 43 info!("Hello World!");
33 44
34 let config = Config::default(); 45 let config = Config::default();
35 let mbox = TlMbox::init(p.IPCC, Irqs, config); 46 let mut mbox = TlMbox::init(p.IPCC, Irqs, config);
36
37 spawner.spawn(run_mm_queue(mbox.mm_subsystem)).unwrap();
38 47
39 let ready_event = mbox.sys_subsystem.read().await; 48 // spawner.spawn(run_mm_queue(mbox.mm_subsystem)).unwrap();
40 let _ = poll_once(mbox.sys_subsystem.read()); // clear rx not
41 49
42 info!("coprocessor ready {}", ready_event.payload()); 50 let sys_event = mbox.sys_subsystem.read().await;
43 51 info!("sys event: {}", sys_event.payload());
44 // test memory manager
45 mem::drop(ready_event);
46 52
47 let fw_info = mbox.sys_subsystem.wireless_fw_info().unwrap(); 53 let fw_info = mbox.sys_subsystem.wireless_fw_info().unwrap();
48 let version_major = fw_info.version_major(); 54 let version_major = fw_info.version_major();
@@ -57,19 +63,188 @@ async fn main(spawner: Spawner) {
57 version_major, version_minor, subversion, sram2a_size, sram2b_size 63 version_major, version_minor, subversion, sram2a_size, sram2b_size
58 ); 64 );
59 65
60 Timer::after(Duration::from_millis(50)).await;
61
62 mbox.sys_subsystem.shci_c2_ble_init(Default::default()).await; 66 mbox.sys_subsystem.shci_c2_ble_init(Default::default()).await;
63 67
64 info!("starting ble..."); 68 info!("resetting BLE...");
65 mbox.ble_subsystem.write(0x0c, &[]).await; 69 mbox.ble_subsystem.reset().await;
70 let response = mbox.ble_subsystem.read().await.unwrap();
71 info!("{}", response);
72
73 info!("config public address...");
74 mbox.ble_subsystem
75 .write_config_data(&ConfigData::public_address(get_bd_addr()).build())
76 .await;
77 let response = mbox.ble_subsystem.read().await.unwrap();
78 info!("{}", response);
79
80 info!("config random address...");
81 mbox.ble_subsystem
82 .write_config_data(&ConfigData::random_address(get_random_addr()).build())
83 .await;
84 let response = mbox.ble_subsystem.read().await.unwrap();
85 info!("{}", response);
86
87 info!("config identity root...");
88 mbox.ble_subsystem
89 .write_config_data(&ConfigData::identity_root(&get_irk()).build())
90 .await;
91 let response = mbox.ble_subsystem.read().await.unwrap();
92 info!("{}", response);
93
94 info!("config encryption root...");
95 mbox.ble_subsystem
96 .write_config_data(&ConfigData::encryption_root(&get_erk()).build())
97 .await;
98 let response = mbox.ble_subsystem.read().await.unwrap();
99 info!("{}", response);
100
101 info!("config tx power level...");
102 mbox.ble_subsystem.set_tx_power_level(PowerLevel::ZerodBm).await;
103 let response = mbox.ble_subsystem.read().await.unwrap();
104 info!("{}", response);
105
106 info!("GATT init...");
107 mbox.ble_subsystem.init_gatt().await;
108 let response = mbox.ble_subsystem.read().await.unwrap();
109 info!("{}", response);
110
111 info!("GAP init...");
112 mbox.ble_subsystem
113 .init_gap(Role::PERIPHERAL, false, BLE_GAP_DEVICE_NAME_LENGTH)
114 .await;
115 let response = mbox.ble_subsystem.read().await.unwrap();
116 info!("{}", response);
117
118 // info!("set scan response...");
119 // mbox.ble_subsystem.le_set_scan_response_data(&[]).await.unwrap();
120 // let response = mbox.ble_subsystem.read().await.unwrap();
121 // info!("{}", response);
122
123 info!("set discoverable...");
124 mbox.ble_subsystem
125 .set_discoverable(&DiscoverableParameters {
126 advertising_type: AdvertisingType::NonConnectableUndirected,
127 advertising_interval: Some((Duration::from_millis(250), Duration::from_millis(250))),
128 address_type: OwnAddressType::Public,
129 filter_policy: AdvertisingFilterPolicy::AllowConnectionAndScan,
130 local_name: None,
131 advertising_data: &[],
132 conn_interval: (None, None),
133 })
134 .await
135 .unwrap();
136
137 let response = mbox.ble_subsystem.read().await;
138 info!("{}", response);
139
140 // remove some advertisement to decrease the packet size
141 info!("delete tx power ad type...");
142 mbox.ble_subsystem
143 .delete_ad_type(AdvertisingDataType::TxPowerLevel)
144 .await;
145 let response = mbox.ble_subsystem.read().await.unwrap();
146 info!("{}", response);
147
148 info!("delete conn interval ad type...");
149 mbox.ble_subsystem
150 .delete_ad_type(AdvertisingDataType::PeripheralConnectionInterval)
151 .await;
152 let response = mbox.ble_subsystem.read().await.unwrap();
153 info!("{}", response);
154
155 info!("update advertising data...");
156 mbox.ble_subsystem
157 .update_advertising_data(&eddystone_advertising_data())
158 .await
159 .unwrap();
160 let response = mbox.ble_subsystem.read().await.unwrap();
161 info!("{}", response);
162
163 info!("update advertising data type...");
164 mbox.ble_subsystem
165 .update_advertising_data(&[3, AdvertisingDataType::UuidCompleteList16 as u8, 0xaa, 0xfe])
166 .await
167 .unwrap();
168 let response = mbox.ble_subsystem.read().await.unwrap();
169 info!("{}", response);
170
171 info!("update advertising data flags...");
172 mbox.ble_subsystem
173 .update_advertising_data(&[
174 2,
175 AdvertisingDataType::Flags as u8,
176 (0x02 | 0x04) as u8, // BLE general discoverable, without BR/EDR support
177 ])
178 .await
179 .unwrap();
180 let response = mbox.ble_subsystem.read().await.unwrap();
181 info!("{}", response);
66 182
67 info!("waiting for ble...");
68 let ble_event = mbox.ble_subsystem.read().await;
69
70 info!("ble event: {}", ble_event.payload());
71
72 Timer::after(Duration::from_millis(150)).await;
73 info!("Test OK"); 183 info!("Test OK");
74 cortex_m::asm::bkpt(); 184 cortex_m::asm::bkpt();
75} 185}
186
187fn get_bd_addr() -> BdAddr {
188 let mut bytes = [0u8; 6];
189
190 let lhci_info = LhciC1DeviceInformationCcrp::new();
191 bytes[0] = (lhci_info.uid64 & 0xff) as u8;
192 bytes[1] = ((lhci_info.uid64 >> 8) & 0xff) as u8;
193 bytes[2] = ((lhci_info.uid64 >> 16) & 0xff) as u8;
194 bytes[3] = lhci_info.device_type_id;
195 bytes[4] = (lhci_info.st_company_id & 0xff) as u8;
196 bytes[5] = (lhci_info.st_company_id >> 8 & 0xff) as u8;
197
198 BdAddr(bytes)
199}
200
201fn get_random_addr() -> BdAddr {
202 let mut bytes = [0u8; 6];
203
204 let lhci_info = LhciC1DeviceInformationCcrp::new();
205 bytes[0] = (lhci_info.uid64 & 0xff) as u8;
206 bytes[1] = ((lhci_info.uid64 >> 8) & 0xff) as u8;
207 bytes[2] = ((lhci_info.uid64 >> 16) & 0xff) as u8;
208 bytes[3] = 0;
209 bytes[4] = 0x6E;
210 bytes[5] = 0xED;
211
212 BdAddr(bytes)
213}
214
215const BLE_CFG_IRK: [u8; 16] = [
216 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0,
217];
218const BLE_CFG_ERK: [u8; 16] = [
219 0xfe, 0xdc, 0xba, 0x09, 0x87, 0x65, 0x43, 0x21, 0xfe, 0xdc, 0xba, 0x09, 0x87, 0x65, 0x43, 0x21,
220];
221
222fn get_irk() -> EncryptionKey {
223 EncryptionKey(BLE_CFG_IRK)
224}
225
226fn get_erk() -> EncryptionKey {
227 EncryptionKey(BLE_CFG_ERK)
228}
229
230fn eddystone_advertising_data() -> [u8; 24] {
231 const EDDYSTONE_URL: &[u8] = b"www.rust-lang.com";
232
233 let mut service_data = [0u8; 24];
234 let url_len = EDDYSTONE_URL.len();
235
236 service_data[0] = 6 + url_len as u8;
237 service_data[1] = AdvertisingDataType::ServiceData as u8;
238
239 // 16-bit eddystone uuid
240 service_data[2] = 0xaa;
241 service_data[3] = 0xFE;
242
243 service_data[4] = 0x10; // URL frame type
244 service_data[5] = 22_i8 as u8; // calibrated TX power at 0m
245 service_data[6] = 0x03; // eddystone url prefix = https
246
247 service_data[7..(7 + url_len)].copy_from_slice(EDDYSTONE_URL);
248
249 service_data
250}