aboutsummaryrefslogtreecommitdiff
path: root/embassy-stm32-wpan/src
diff options
context:
space:
mode:
authorgoueslati <[email protected]>2023-06-12 12:27:51 +0100
committergoueslati <[email protected]>2023-06-12 12:27:51 +0100
commitca8957da435eb91242fa33eb986e80a33bbc4da0 (patch)
tree89b66bdff52630cd4ef1d609122c2b04417ccd73 /embassy-stm32-wpan/src
parentce1d72c609ae1e04410e68458ec3d6c36c7dae27 (diff)
stm32/ipcc: move tl_mbox into `embassy-stm32-wpan`
Diffstat (limited to 'embassy-stm32-wpan/src')
-rw-r--r--embassy-stm32-wpan/src/ble.rs82
-rw-r--r--embassy-stm32-wpan/src/channels.rs96
-rw-r--r--embassy-stm32-wpan/src/cmd.rs77
-rw-r--r--embassy-stm32-wpan/src/consts.rs55
-rw-r--r--embassy-stm32-wpan/src/evt.rs176
-rw-r--r--embassy-stm32-wpan/src/fmt.rs225
-rw-r--r--embassy-stm32-wpan/src/lib.rs266
-rw-r--r--embassy-stm32-wpan/src/mm.rs75
-rw-r--r--embassy-stm32-wpan/src/rc.rs50
-rw-r--r--embassy-stm32-wpan/src/shci.rs100
-rw-r--r--embassy-stm32-wpan/src/sys.rs70
-rw-r--r--embassy-stm32-wpan/src/tables.rs175
-rw-r--r--embassy-stm32-wpan/src/unsafe_linked_list.rs128
13 files changed, 1575 insertions, 0 deletions
diff --git a/embassy-stm32-wpan/src/ble.rs b/embassy-stm32-wpan/src/ble.rs
new file mode 100644
index 000000000..4546bde07
--- /dev/null
+++ b/embassy-stm32-wpan/src/ble.rs
@@ -0,0 +1,82 @@
1use core::mem::MaybeUninit;
2
3use embassy_stm32::ipcc::Ipcc;
4
5use crate::cmd::{CmdPacket, CmdSerial};
6use crate::consts::TlPacketType;
7use crate::evt::EvtBox;
8use crate::tables::BleTable;
9use crate::unsafe_linked_list::LinkedListNode;
10use crate::{
11 channels, BLE_CMD_BUFFER, CS_BUFFER, EVT_CHANNEL, EVT_QUEUE, HCI_ACL_DATA_BUFFER, TL_BLE_TABLE, TL_REF_TABLE,
12};
13
14pub struct Ble;
15
16impl Ble {
17 pub(super) fn enable() {
18 unsafe {
19 LinkedListNode::init_head(EVT_QUEUE.as_mut_ptr());
20
21 TL_BLE_TABLE = MaybeUninit::new(BleTable {
22 pcmd_buffer: BLE_CMD_BUFFER.as_mut_ptr().cast(),
23 pcs_buffer: CS_BUFFER.as_ptr().cast(),
24 pevt_queue: EVT_QUEUE.as_ptr().cast(),
25 phci_acl_data_buffer: HCI_ACL_DATA_BUFFER.as_mut_ptr().cast(),
26 });
27 }
28
29 Ipcc::c1_set_rx_channel(channels::cpu2::IPCC_BLE_EVENT_CHANNEL, true);
30 }
31
32 pub(super) fn evt_handler() {
33 unsafe {
34 let mut node_ptr = core::ptr::null_mut();
35 let node_ptr_ptr: *mut _ = &mut node_ptr;
36
37 while !LinkedListNode::is_empty(EVT_QUEUE.as_mut_ptr()) {
38 LinkedListNode::remove_head(EVT_QUEUE.as_mut_ptr(), node_ptr_ptr);
39
40 let event = node_ptr.cast();
41 let event = EvtBox::new(event);
42
43 EVT_CHANNEL.try_send(event).unwrap();
44 }
45 }
46
47 Ipcc::c1_clear_flag_channel(channels::cpu2::IPCC_BLE_EVENT_CHANNEL);
48 }
49
50 pub(super) fn acl_data_handler() {
51 Ipcc::c1_set_tx_channel(channels::cpu1::IPCC_HCI_ACL_DATA_CHANNEL, false);
52
53 // TODO: ACL data ack to the user
54 }
55
56 pub fn ble_send_cmd(buf: &[u8]) {
57 debug!("writing ble cmd");
58
59 unsafe {
60 let pcmd_buffer: *mut CmdPacket = (*TL_REF_TABLE.assume_init().ble_table).pcmd_buffer;
61 let pcmd_serial: *mut CmdSerial = &mut (*pcmd_buffer).cmdserial;
62 let pcmd_serial_buf: *mut u8 = pcmd_serial.cast();
63
64 core::ptr::copy(buf.as_ptr(), pcmd_serial_buf, buf.len());
65
66 let mut cmd_packet = &mut *(*TL_REF_TABLE.assume_init().ble_table).pcmd_buffer;
67 cmd_packet.cmdserial.ty = TlPacketType::BleCmd as u8;
68 }
69
70 Ipcc::c1_set_flag_channel(channels::cpu1::IPCC_BLE_CMD_CHANNEL);
71 }
72
73 #[allow(dead_code)] // Not used currently but reserved
74 pub(super) fn ble_send_acl_data() {
75 let mut cmd_packet = unsafe { &mut *(*TL_REF_TABLE.assume_init().ble_table).phci_acl_data_buffer };
76
77 cmd_packet.acl_data_serial.ty = TlPacketType::AclData as u8;
78
79 Ipcc::c1_set_flag_channel(channels::cpu1::IPCC_HCI_ACL_DATA_CHANNEL);
80 Ipcc::c1_set_tx_channel(channels::cpu1::IPCC_HCI_ACL_DATA_CHANNEL, true);
81 }
82}
diff --git a/embassy-stm32-wpan/src/channels.rs b/embassy-stm32-wpan/src/channels.rs
new file mode 100644
index 000000000..9a2be1cfa
--- /dev/null
+++ b/embassy-stm32-wpan/src/channels.rs
@@ -0,0 +1,96 @@
1//! CPU1 CPU2
2//! | (SYSTEM) |
3//! |----HW_IPCC_SYSTEM_CMD_RSP_CHANNEL-------------->|
4//! | |
5//! |<---HW_IPCC_SYSTEM_EVENT_CHANNEL-----------------|
6//! | |
7//! | (ZIGBEE) |
8//! |----HW_IPCC_ZIGBEE_CMD_APPLI_CHANNEL------------>|
9//! | |
10//! |----HW_IPCC_ZIGBEE_CMD_CLI_CHANNEL-------------->|
11//! | |
12//! |<---HW_IPCC_ZIGBEE_APPLI_NOTIF_ACK_CHANNEL-------|
13//! | |
14//! |<---HW_IPCC_ZIGBEE_CLI_NOTIF_ACK_CHANNEL---------|
15//! | |
16//! | (THREAD) |
17//! |----HW_IPCC_THREAD_OT_CMD_RSP_CHANNEL----------->|
18//! | |
19//! |----HW_IPCC_THREAD_CLI_CMD_CHANNEL-------------->|
20//! | |
21//! |<---HW_IPCC_THREAD_NOTIFICATION_ACK_CHANNEL------|
22//! | |
23//! |<---HW_IPCC_THREAD_CLI_NOTIFICATION_ACK_CHANNEL--|
24//! | |
25//! | (BLE) |
26//! |----HW_IPCC_BLE_CMD_CHANNEL--------------------->|
27//! | |
28//! |----HW_IPCC_HCI_ACL_DATA_CHANNEL---------------->|
29//! | |
30//! |<---HW_IPCC_BLE_EVENT_CHANNEL--------------------|
31//! | |
32//! | (BLE LLD) |
33//! |----HW_IPCC_BLE_LLD_CMD_CHANNEL----------------->|
34//! | |
35//! |<---HW_IPCC_BLE_LLD_RSP_CHANNEL------------------|
36//! | |
37//! |<---HW_IPCC_BLE_LLD_M0_CMD_CHANNEL---------------|
38//! | |
39//! | (MAC) |
40//! |----HW_IPCC_MAC_802_15_4_CMD_RSP_CHANNEL-------->|
41//! | |
42//! |<---HW_IPCC_MAC_802_15_4_NOTIFICATION_ACK_CHANNEL|
43//! | |
44//! | (BUFFER) |
45//! |----HW_IPCC_MM_RELEASE_BUFFER_CHANNE------------>|
46//! | |
47//! | (TRACE) |
48//! |<----HW_IPCC_TRACES_CHANNEL----------------------|
49//! | |
50//!
51
52pub mod cpu1 {
53 use embassy_stm32::ipcc::IpccChannel;
54
55 pub const IPCC_BLE_CMD_CHANNEL: IpccChannel = IpccChannel::Channel1;
56 pub const IPCC_SYSTEM_CMD_RSP_CHANNEL: IpccChannel = IpccChannel::Channel2;
57 pub const IPCC_THREAD_OT_CMD_RSP_CHANNEL: IpccChannel = IpccChannel::Channel3;
58 #[allow(dead_code)] // Not used currently but reserved
59 pub const IPCC_ZIGBEE_CMD_APPLI_CHANNEL: IpccChannel = IpccChannel::Channel3;
60 #[allow(dead_code)] // Not used currently but reserved
61 pub const IPCC_MAC_802_15_4_CMD_RSP_CHANNEL: IpccChannel = IpccChannel::Channel3;
62 #[allow(dead_code)] // Not used currently but reserved
63 pub const IPCC_MM_RELEASE_BUFFER_CHANNEL: IpccChannel = IpccChannel::Channel4;
64 pub const IPCC_THREAD_CLI_CMD_CHANNEL: IpccChannel = IpccChannel::Channel5;
65 #[allow(dead_code)] // Not used currently but reserved
66 pub const IPCC_LLDTESTS_CLI_CMD_CHANNEL: IpccChannel = IpccChannel::Channel5;
67 #[allow(dead_code)] // Not used currently but reserved
68 pub const IPCC_BLE_LLD_CMD_CHANNEL: IpccChannel = IpccChannel::Channel5;
69 pub const IPCC_HCI_ACL_DATA_CHANNEL: IpccChannel = IpccChannel::Channel6;
70}
71
72pub mod cpu2 {
73 use embassy_stm32::ipcc::IpccChannel;
74
75 pub const IPCC_BLE_EVENT_CHANNEL: IpccChannel = IpccChannel::Channel1;
76 pub const IPCC_SYSTEM_EVENT_CHANNEL: IpccChannel = IpccChannel::Channel2;
77 pub const IPCC_THREAD_NOTIFICATION_ACK_CHANNEL: IpccChannel = IpccChannel::Channel3;
78 #[allow(dead_code)] // Not used currently but reserved
79 pub const IPCC_ZIGBEE_APPLI_NOTIF_ACK_CHANNEL: IpccChannel = IpccChannel::Channel3;
80 #[allow(dead_code)] // Not used currently but reserved
81 pub const IPCC_MAC_802_15_4_NOTIFICATION_ACK_CHANNEL: IpccChannel = IpccChannel::Channel3;
82 #[allow(dead_code)] // Not used currently but reserved
83 pub const IPCC_LDDTESTS_M0_CMD_CHANNEL: IpccChannel = IpccChannel::Channel3;
84 #[allow(dead_code)] // Not used currently but reserved
85 pub const IPCC_BLE_LLDÇM0_CMD_CHANNEL: IpccChannel = IpccChannel::Channel3;
86 pub const IPCC_TRACES_CHANNEL: IpccChannel = IpccChannel::Channel4;
87 pub const IPCC_THREAD_CLI_NOTIFICATION_ACK_CHANNEL: IpccChannel = IpccChannel::Channel5;
88 #[allow(dead_code)] // Not used currently but reserved
89 pub const IPCC_LLDTESTS_CLI_RSP_CHANNEL: IpccChannel = IpccChannel::Channel5;
90 #[allow(dead_code)] // Not used currently but reserved
91 pub const IPCC_BLE_LLD_CLI_RSP_CHANNEL: IpccChannel = IpccChannel::Channel5;
92 #[allow(dead_code)] // Not used currently but reserved
93 pub const IPCC_BLE_LLD_RSP_CHANNEL: IpccChannel = IpccChannel::Channel5;
94 #[allow(dead_code)] // Not used currently but reserved
95 pub const IPCC_ZIGBEE_M0_REQUEST_CHANNEL: IpccChannel = IpccChannel::Channel5;
96}
diff --git a/embassy-stm32-wpan/src/cmd.rs b/embassy-stm32-wpan/src/cmd.rs
new file mode 100644
index 000000000..1f7dae7f7
--- /dev/null
+++ b/embassy-stm32-wpan/src/cmd.rs
@@ -0,0 +1,77 @@
1use crate::evt::{EvtPacket, EvtSerial};
2use crate::{PacketHeader, TL_EVT_HEADER_SIZE};
3
4#[derive(Copy, Clone)]
5#[repr(C, packed)]
6pub struct Cmd {
7 pub cmd_code: u16,
8 pub payload_len: u8,
9 pub payload: [u8; 255],
10}
11
12impl Default for Cmd {
13 fn default() -> Self {
14 Self {
15 cmd_code: 0,
16 payload_len: 0,
17 payload: [0u8; 255],
18 }
19 }
20}
21
22#[derive(Copy, Clone, Default)]
23#[repr(C, packed)]
24pub struct CmdSerial {
25 pub ty: u8,
26 pub cmd: Cmd,
27}
28
29#[derive(Copy, Clone, Default)]
30#[repr(C, packed)]
31pub struct CmdPacket {
32 pub header: PacketHeader,
33 pub cmdserial: CmdSerial,
34}
35
36impl CmdPacket {
37 /// Writes an underlying CmdPacket into the provided buffer.
38 /// Returns a number of bytes that were written.
39 /// Returns an error if event kind is unknown or if provided buffer size is not enough.
40 #[allow(clippy::result_unit_err)]
41 pub fn write(&self, buf: &mut [u8]) -> Result<usize, ()> {
42 unsafe {
43 let cmd_ptr: *const CmdPacket = self;
44 let self_as_evt_ptr: *const EvtPacket = cmd_ptr.cast();
45 let evt_serial: *const EvtSerial = &(*self_as_evt_ptr).evt_serial;
46
47 let acl_data: *const AclDataPacket = cmd_ptr.cast();
48 let acl_serial: *const AclDataSerial = &(*acl_data).acl_data_serial;
49 let acl_serial_buf: *const u8 = acl_serial.cast();
50
51 let len = (*evt_serial).evt.payload_len as usize + TL_EVT_HEADER_SIZE;
52 if len > buf.len() {
53 return Err(());
54 }
55
56 core::ptr::copy(acl_serial_buf, buf.as_mut_ptr(), len);
57
58 Ok(len)
59 }
60 }
61}
62
63#[derive(Copy, Clone)]
64#[repr(C, packed)]
65pub struct AclDataSerial {
66 pub ty: u8,
67 pub handle: u16,
68 pub length: u16,
69 pub acl_data: [u8; 1],
70}
71
72#[derive(Copy, Clone)]
73#[repr(C, packed)]
74pub struct AclDataPacket {
75 pub header: PacketHeader,
76 pub acl_data_serial: AclDataSerial,
77}
diff --git a/embassy-stm32-wpan/src/consts.rs b/embassy-stm32-wpan/src/consts.rs
new file mode 100644
index 000000000..caf26c06b
--- /dev/null
+++ b/embassy-stm32-wpan/src/consts.rs
@@ -0,0 +1,55 @@
1use core::convert::TryFrom;
2
3#[derive(Debug)]
4#[repr(C)]
5pub enum TlPacketType {
6 BleCmd = 0x01,
7 AclData = 0x02,
8 BleEvt = 0x04,
9
10 OtCmd = 0x08,
11 OtRsp = 0x09,
12 CliCmd = 0x0A,
13 OtNot = 0x0C,
14 OtAck = 0x0D,
15 CliNot = 0x0E,
16 CliAck = 0x0F,
17
18 SysCmd = 0x10,
19 SysRsp = 0x11,
20 SysEvt = 0x12,
21
22 LocCmd = 0x20,
23 LocRsp = 0x21,
24
25 TracesApp = 0x40,
26 TracesWl = 0x41,
27}
28
29impl TryFrom<u8> for TlPacketType {
30 type Error = ();
31
32 fn try_from(value: u8) -> Result<Self, Self::Error> {
33 match value {
34 0x01 => Ok(TlPacketType::BleCmd),
35 0x02 => Ok(TlPacketType::AclData),
36 0x04 => Ok(TlPacketType::BleEvt),
37 0x08 => Ok(TlPacketType::OtCmd),
38 0x09 => Ok(TlPacketType::OtRsp),
39 0x0A => Ok(TlPacketType::CliCmd),
40 0x0C => Ok(TlPacketType::OtNot),
41 0x0D => Ok(TlPacketType::OtAck),
42 0x0E => Ok(TlPacketType::CliNot),
43 0x0F => Ok(TlPacketType::CliAck),
44 0x10 => Ok(TlPacketType::SysCmd),
45 0x11 => Ok(TlPacketType::SysRsp),
46 0x12 => Ok(TlPacketType::SysEvt),
47 0x20 => Ok(TlPacketType::LocCmd),
48 0x21 => Ok(TlPacketType::LocRsp),
49 0x40 => Ok(TlPacketType::TracesApp),
50 0x41 => Ok(TlPacketType::TracesWl),
51
52 _ => Err(()),
53 }
54 }
55}
diff --git a/embassy-stm32-wpan/src/evt.rs b/embassy-stm32-wpan/src/evt.rs
new file mode 100644
index 000000000..b53fe506e
--- /dev/null
+++ b/embassy-stm32-wpan/src/evt.rs
@@ -0,0 +1,176 @@
1use core::mem::MaybeUninit;
2
3use super::cmd::{AclDataPacket, AclDataSerial};
4use super::consts::TlPacketType;
5use super::{PacketHeader, TL_EVT_HEADER_SIZE};
6use crate::mm;
7
8/**
9 * The payload of `Evt` for a command status event
10 */
11#[derive(Copy, Clone)]
12#[repr(C, packed)]
13pub struct CsEvt {
14 pub status: u8,
15 pub num_cmd: u8,
16 pub cmd_code: u16,
17}
18
19/**
20 * The payload of `Evt` for a command complete event
21 */
22#[derive(Copy, Clone, Default)]
23#[repr(C, packed)]
24pub struct CcEvt {
25 pub num_cmd: u8,
26 pub cmd_code: u16,
27 pub payload: [u8; 1],
28}
29
30impl CcEvt {
31 pub fn write(&self, buf: &mut [u8]) {
32 unsafe {
33 let len = core::mem::size_of::<CcEvt>();
34 assert!(buf.len() >= len);
35
36 let self_ptr: *const CcEvt = self;
37 let self_buf_ptr: *const u8 = self_ptr.cast();
38
39 core::ptr::copy(self_buf_ptr, buf.as_mut_ptr(), len);
40 }
41 }
42}
43
44#[derive(Copy, Clone, Default)]
45#[repr(C, packed)]
46pub struct AsynchEvt {
47 sub_evt_code: u16,
48 payload: [u8; 1],
49}
50
51#[derive(Copy, Clone, Default)]
52#[repr(C, packed)]
53pub struct Evt {
54 pub evt_code: u8,
55 pub payload_len: u8,
56 pub payload: [u8; 1],
57}
58
59#[derive(Copy, Clone, Default)]
60#[repr(C, packed)]
61pub struct EvtSerial {
62 pub kind: u8,
63 pub evt: Evt,
64}
65
66/// This format shall be used for all events (asynchronous and command response) reported
67/// by the CPU2 except for the command response of a system command where the header is not there
68/// and the format to be used shall be `EvtSerial`.
69///
70/// ### Note:
71/// Be careful that the asynchronous events reported by the CPU2 on the system channel do
72/// include the header and shall use `EvtPacket` format. Only the command response format on the
73/// system channel is different.
74#[derive(Copy, Clone, Default)]
75#[repr(C, packed)]
76pub struct EvtPacket {
77 pub header: PacketHeader,
78 pub evt_serial: EvtSerial,
79}
80
81impl EvtPacket {
82 pub fn kind(&self) -> u8 {
83 self.evt_serial.kind
84 }
85
86 pub fn evt(&self) -> &Evt {
87 &self.evt_serial.evt
88 }
89}
90
91/// smart pointer to the [`EvtPacket`] that will dispose of [`EvtPacket`] buffer automatically
92/// on [`Drop`]
93#[derive(Debug)]
94pub struct EvtBox {
95 ptr: *mut EvtPacket,
96}
97
98unsafe impl Send for EvtBox {}
99impl EvtBox {
100 pub(super) fn new(ptr: *mut EvtPacket) -> Self {
101 Self { ptr }
102 }
103
104 /// copies event data from inner pointer and returns an event structure
105 pub fn evt(&self) -> EvtPacket {
106 let mut evt = MaybeUninit::uninit();
107 unsafe {
108 self.ptr.copy_to(evt.as_mut_ptr(), 1);
109 evt.assume_init()
110 }
111 }
112
113 /// writes an underlying [`EvtPacket`] into the provided buffer.
114 /// Returns the number of bytes that were written.
115 /// Returns an error if event kind is unknown or if provided buffer size is not enough.
116 #[allow(clippy::result_unit_err)]
117 pub fn write(&self, buf: &mut [u8]) -> Result<usize, ()> {
118 unsafe {
119 let evt_kind = TlPacketType::try_from((*self.ptr).evt_serial.kind)?;
120
121 let evt_data: *const EvtPacket = self.ptr.cast();
122 let evt_serial: *const EvtSerial = &(*evt_data).evt_serial;
123 let evt_serial_buf: *const u8 = evt_serial.cast();
124
125 let acl_data: *const AclDataPacket = self.ptr.cast();
126 let acl_serial: *const AclDataSerial = &(*acl_data).acl_data_serial;
127 let acl_serial_buf: *const u8 = acl_serial.cast();
128
129 if let TlPacketType::AclData = evt_kind {
130 let len = (*acl_serial).length as usize + 5;
131 if len > buf.len() {
132 return Err(());
133 }
134
135 core::ptr::copy(evt_serial_buf, buf.as_mut_ptr(), len);
136
137 Ok(len)
138 } else {
139 let len = (*evt_serial).evt.payload_len as usize + TL_EVT_HEADER_SIZE;
140 if len > buf.len() {
141 return Err(());
142 }
143
144 core::ptr::copy(acl_serial_buf, buf.as_mut_ptr(), len);
145
146 Ok(len)
147 }
148 }
149 }
150
151 /// returns the size of a buffer required to hold this event
152 #[allow(clippy::result_unit_err)]
153 pub fn size(&self) -> Result<usize, ()> {
154 unsafe {
155 let evt_kind = TlPacketType::try_from((*self.ptr).evt_serial.kind)?;
156
157 let evt_data: *const EvtPacket = self.ptr.cast();
158 let evt_serial: *const EvtSerial = &(*evt_data).evt_serial;
159
160 let acl_data: *const AclDataPacket = self.ptr.cast();
161 let acl_serial: *const AclDataSerial = &(*acl_data).acl_data_serial;
162
163 if let TlPacketType::AclData = evt_kind {
164 Ok((*acl_serial).length as usize + 5)
165 } else {
166 Ok((*evt_serial).evt.payload_len as usize + TL_EVT_HEADER_SIZE)
167 }
168 }
169 }
170}
171
172impl Drop for EvtBox {
173 fn drop(&mut self) {
174 mm::MemoryManager::evt_drop(self.ptr);
175 }
176}
diff --git a/embassy-stm32-wpan/src/fmt.rs b/embassy-stm32-wpan/src/fmt.rs
new file mode 100644
index 000000000..066970813
--- /dev/null
+++ b/embassy-stm32-wpan/src/fmt.rs
@@ -0,0 +1,225 @@
1#![macro_use]
2#![allow(unused_macros)]
3
4#[cfg(all(feature = "defmt", feature = "log"))]
5compile_error!("You may not enable both `defmt` and `log` features.");
6
7macro_rules! assert {
8 ($($x:tt)*) => {
9 {
10 #[cfg(not(feature = "defmt"))]
11 ::core::assert!($($x)*);
12 #[cfg(feature = "defmt")]
13 ::defmt::assert!($($x)*);
14 }
15 };
16}
17
18macro_rules! assert_eq {
19 ($($x:tt)*) => {
20 {
21 #[cfg(not(feature = "defmt"))]
22 ::core::assert_eq!($($x)*);
23 #[cfg(feature = "defmt")]
24 ::defmt::assert_eq!($($x)*);
25 }
26 };
27}
28
29macro_rules! assert_ne {
30 ($($x:tt)*) => {
31 {
32 #[cfg(not(feature = "defmt"))]
33 ::core::assert_ne!($($x)*);
34 #[cfg(feature = "defmt")]
35 ::defmt::assert_ne!($($x)*);
36 }
37 };
38}
39
40macro_rules! debug_assert {
41 ($($x:tt)*) => {
42 {
43 #[cfg(not(feature = "defmt"))]
44 ::core::debug_assert!($($x)*);
45 #[cfg(feature = "defmt")]
46 ::defmt::debug_assert!($($x)*);
47 }
48 };
49}
50
51macro_rules! debug_assert_eq {
52 ($($x:tt)*) => {
53 {
54 #[cfg(not(feature = "defmt"))]
55 ::core::debug_assert_eq!($($x)*);
56 #[cfg(feature = "defmt")]
57 ::defmt::debug_assert_eq!($($x)*);
58 }
59 };
60}
61
62macro_rules! debug_assert_ne {
63 ($($x:tt)*) => {
64 {
65 #[cfg(not(feature = "defmt"))]
66 ::core::debug_assert_ne!($($x)*);
67 #[cfg(feature = "defmt")]
68 ::defmt::debug_assert_ne!($($x)*);
69 }
70 };
71}
72
73macro_rules! todo {
74 ($($x:tt)*) => {
75 {
76 #[cfg(not(feature = "defmt"))]
77 ::core::todo!($($x)*);
78 #[cfg(feature = "defmt")]
79 ::defmt::todo!($($x)*);
80 }
81 };
82}
83
84macro_rules! unreachable {
85 ($($x:tt)*) => {
86 {
87 #[cfg(not(feature = "defmt"))]
88 ::core::unreachable!($($x)*);
89 #[cfg(feature = "defmt")]
90 ::defmt::unreachable!($($x)*);
91 }
92 };
93}
94
95macro_rules! panic {
96 ($($x:tt)*) => {
97 {
98 #[cfg(not(feature = "defmt"))]
99 ::core::panic!($($x)*);
100 #[cfg(feature = "defmt")]
101 ::defmt::panic!($($x)*);
102 }
103 };
104}
105
106macro_rules! trace {
107 ($s:literal $(, $x:expr)* $(,)?) => {
108 {
109 #[cfg(feature = "log")]
110 ::log::trace!($s $(, $x)*);
111 #[cfg(feature = "defmt")]
112 ::defmt::trace!($s $(, $x)*);
113 #[cfg(not(any(feature = "log", feature="defmt")))]
114 let _ = ($( & $x ),*);
115 }
116 };
117}
118
119macro_rules! debug {
120 ($s:literal $(, $x:expr)* $(,)?) => {
121 {
122 #[cfg(feature = "log")]
123 ::log::debug!($s $(, $x)*);
124 #[cfg(feature = "defmt")]
125 ::defmt::debug!($s $(, $x)*);
126 #[cfg(not(any(feature = "log", feature="defmt")))]
127 let _ = ($( & $x ),*);
128 }
129 };
130}
131
132macro_rules! info {
133 ($s:literal $(, $x:expr)* $(,)?) => {
134 {
135 #[cfg(feature = "log")]
136 ::log::info!($s $(, $x)*);
137 #[cfg(feature = "defmt")]
138 ::defmt::info!($s $(, $x)*);
139 #[cfg(not(any(feature = "log", feature="defmt")))]
140 let _ = ($( & $x ),*);
141 }
142 };
143}
144
145macro_rules! warn {
146 ($s:literal $(, $x:expr)* $(,)?) => {
147 {
148 #[cfg(feature = "log")]
149 ::log::warn!($s $(, $x)*);
150 #[cfg(feature = "defmt")]
151 ::defmt::warn!($s $(, $x)*);
152 #[cfg(not(any(feature = "log", feature="defmt")))]
153 let _ = ($( & $x ),*);
154 }
155 };
156}
157
158macro_rules! error {
159 ($s:literal $(, $x:expr)* $(,)?) => {
160 {
161 #[cfg(feature = "log")]
162 ::log::error!($s $(, $x)*);
163 #[cfg(feature = "defmt")]
164 ::defmt::error!($s $(, $x)*);
165 #[cfg(not(any(feature = "log", feature="defmt")))]
166 let _ = ($( & $x ),*);
167 }
168 };
169}
170
171#[cfg(feature = "defmt")]
172macro_rules! unwrap {
173 ($($x:tt)*) => {
174 ::defmt::unwrap!($($x)*)
175 };
176}
177
178#[cfg(not(feature = "defmt"))]
179macro_rules! unwrap {
180 ($arg:expr) => {
181 match $crate::fmt::Try::into_result($arg) {
182 ::core::result::Result::Ok(t) => t,
183 ::core::result::Result::Err(e) => {
184 ::core::panic!("unwrap of `{}` failed: {:?}", ::core::stringify!($arg), e);
185 }
186 }
187 };
188 ($arg:expr, $($msg:expr),+ $(,)? ) => {
189 match $crate::fmt::Try::into_result($arg) {
190 ::core::result::Result::Ok(t) => t,
191 ::core::result::Result::Err(e) => {
192 ::core::panic!("unwrap of `{}` failed: {}: {:?}", ::core::stringify!($arg), ::core::format_args!($($msg,)*), e);
193 }
194 }
195 }
196}
197
198#[derive(Debug, Copy, Clone, Eq, PartialEq)]
199pub struct NoneError;
200
201pub trait Try {
202 type Ok;
203 type Error;
204 fn into_result(self) -> Result<Self::Ok, Self::Error>;
205}
206
207impl<T> Try for Option<T> {
208 type Ok = T;
209 type Error = NoneError;
210
211 #[inline]
212 fn into_result(self) -> Result<T, NoneError> {
213 self.ok_or(NoneError)
214 }
215}
216
217impl<T, E> Try for Result<T, E> {
218 type Ok = T;
219 type Error = E;
220
221 #[inline]
222 fn into_result(self) -> Self {
223 self
224 }
225}
diff --git a/embassy-stm32-wpan/src/lib.rs b/embassy-stm32-wpan/src/lib.rs
new file mode 100644
index 000000000..b3206428e
--- /dev/null
+++ b/embassy-stm32-wpan/src/lib.rs
@@ -0,0 +1,266 @@
1#![no_std]
2
3// This must go FIRST so that all the other modules see its macros.
4pub mod fmt;
5
6use core::mem::MaybeUninit;
7
8use cmd::CmdPacket;
9use embassy_cortex_m::interrupt::Interrupt;
10use embassy_futures::block_on;
11use embassy_hal_common::{into_ref, Peripheral, PeripheralRef};
12use embassy_stm32::interrupt;
13use embassy_stm32::ipcc::{Config, Ipcc};
14use embassy_stm32::peripherals::IPCC;
15use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
16use embassy_sync::channel::Channel;
17use embassy_sync::signal::Signal;
18use evt::{CcEvt, EvtBox};
19use tables::{
20 BleTable, DeviceInfoTable, Mac802_15_4Table, MemManagerTable, RefTable, SysTable, ThreadTable, TracesTable,
21 WirelessFwInfoTable,
22};
23use unsafe_linked_list::LinkedListNode;
24
25pub mod ble;
26pub mod channels;
27pub mod cmd;
28pub mod consts;
29pub mod evt;
30pub mod mm;
31pub mod rc;
32pub mod shci;
33pub mod sys;
34pub mod tables;
35pub mod unsafe_linked_list;
36
37/// Interrupt handler.
38pub struct ReceiveInterruptHandler {}
39
40impl interrupt::Handler<interrupt::IPCC_C1_RX> for ReceiveInterruptHandler {
41 unsafe fn on_interrupt() {
42 if Ipcc::is_rx_pending(channels::cpu2::IPCC_SYSTEM_EVENT_CHANNEL) {
43 debug!("RX SYS evt");
44 sys::Sys::evt_handler();
45 } else if Ipcc::is_rx_pending(channels::cpu2::IPCC_BLE_EVENT_CHANNEL) {
46 debug!("RX BLE evt");
47 ble::Ble::evt_handler();
48 }
49
50 STATE.signal(());
51 }
52}
53
54pub struct TransmitInterruptHandler {}
55
56impl interrupt::Handler<interrupt::IPCC_C1_TX> for TransmitInterruptHandler {
57 unsafe fn on_interrupt() {
58 if Ipcc::is_tx_pending(channels::cpu1::IPCC_SYSTEM_CMD_RSP_CHANNEL) {
59 debug!("TX SYS cmd rsp");
60 let cc = sys::Sys::cmd_evt_handler();
61
62 LAST_CC_EVT.signal(cc);
63 } else if Ipcc::is_tx_pending(channels::cpu1::IPCC_MM_RELEASE_BUFFER_CHANNEL) {
64 debug!("TX MM release");
65 mm::MemoryManager::free_buf_handler();
66 } else if Ipcc::is_tx_pending(channels::cpu1::IPCC_HCI_ACL_DATA_CHANNEL) {
67 debug!("TX HCI acl");
68 ble::Ble::acl_data_handler();
69 }
70
71 STATE.signal(());
72 }
73}
74
75#[link_section = "TL_REF_TABLE"]
76pub static mut TL_REF_TABLE: MaybeUninit<RefTable> = MaybeUninit::uninit();
77
78#[link_section = "MB_MEM1"]
79static mut TL_DEVICE_INFO_TABLE: MaybeUninit<DeviceInfoTable> = MaybeUninit::uninit();
80
81#[link_section = "MB_MEM1"]
82static mut TL_BLE_TABLE: MaybeUninit<BleTable> = MaybeUninit::uninit();
83
84#[link_section = "MB_MEM1"]
85static mut TL_THREAD_TABLE: MaybeUninit<ThreadTable> = MaybeUninit::uninit();
86
87#[link_section = "MB_MEM1"]
88static mut TL_SYS_TABLE: MaybeUninit<SysTable> = MaybeUninit::uninit();
89
90#[link_section = "MB_MEM1"]
91static mut TL_MEM_MANAGER_TABLE: MaybeUninit<MemManagerTable> = MaybeUninit::uninit();
92
93#[link_section = "MB_MEM1"]
94static mut TL_TRACES_TABLE: MaybeUninit<TracesTable> = MaybeUninit::uninit();
95
96#[link_section = "MB_MEM1"]
97static mut TL_MAC_802_15_4_TABLE: MaybeUninit<Mac802_15_4Table> = MaybeUninit::uninit();
98
99#[link_section = "MB_MEM2"]
100static mut FREE_BUF_QUEUE: MaybeUninit<LinkedListNode> = MaybeUninit::uninit();
101
102// Not in shared RAM
103static mut LOCAL_FREE_BUF_QUEUE: MaybeUninit<LinkedListNode> = MaybeUninit::uninit();
104
105#[allow(dead_code)] // Not used currently but reserved
106#[link_section = "MB_MEM2"]
107static mut TRACES_EVT_QUEUE: MaybeUninit<LinkedListNode> = MaybeUninit::uninit();
108
109type PacketHeader = LinkedListNode;
110
111const TL_PACKET_HEADER_SIZE: usize = core::mem::size_of::<PacketHeader>();
112const TL_EVT_HEADER_SIZE: usize = 3;
113const TL_CS_EVT_SIZE: usize = core::mem::size_of::<evt::CsEvt>();
114
115#[link_section = "MB_MEM2"]
116static mut CS_BUFFER: MaybeUninit<[u8; TL_PACKET_HEADER_SIZE + TL_EVT_HEADER_SIZE + TL_CS_EVT_SIZE]> =
117 MaybeUninit::uninit();
118
119#[link_section = "MB_MEM2"]
120static mut EVT_QUEUE: MaybeUninit<LinkedListNode> = MaybeUninit::uninit();
121
122#[link_section = "MB_MEM2"]
123static mut SYSTEM_EVT_QUEUE: MaybeUninit<LinkedListNode> = MaybeUninit::uninit();
124
125#[link_section = "MB_MEM2"]
126pub static mut SYS_CMD_BUF: MaybeUninit<CmdPacket> = MaybeUninit::uninit();
127
128/**
129 * Queue length of BLE Event
130 * This parameter defines the number of asynchronous events that can be stored in the HCI layer before
131 * being reported to the application. When a command is sent to the BLE core coprocessor, the HCI layer
132 * is waiting for the event with the Num_HCI_Command_Packets set to 1. The receive queue shall be large
133 * enough to store all asynchronous events received in between.
134 * When CFG_TLBLE_MOST_EVENT_PAYLOAD_SIZE is set to 27, this allow to store three 255 bytes long asynchronous events
135 * between the HCI command and its event.
136 * This parameter depends on the value given to CFG_TLBLE_MOST_EVENT_PAYLOAD_SIZE. When the queue size is to small,
137 * the system may hang if the queue is full with asynchronous events and the HCI layer is still waiting
138 * for a CC/CS event, In that case, the notification TL_BLE_HCI_ToNot() is called to indicate
139 * to the application a HCI command did not receive its command event within 30s (Default HCI Timeout).
140 */
141const CFG_TLBLE_EVT_QUEUE_LENGTH: usize = 5;
142const CFG_TLBLE_MOST_EVENT_PAYLOAD_SIZE: usize = 255;
143const TL_BLE_EVENT_FRAME_SIZE: usize = TL_EVT_HEADER_SIZE + CFG_TLBLE_MOST_EVENT_PAYLOAD_SIZE;
144
145const fn divc(x: usize, y: usize) -> usize {
146 ((x) + (y) - 1) / (y)
147}
148
149const POOL_SIZE: usize = CFG_TLBLE_EVT_QUEUE_LENGTH * 4 * divc(TL_PACKET_HEADER_SIZE + TL_BLE_EVENT_FRAME_SIZE, 4);
150
151#[link_section = "MB_MEM2"]
152static mut EVT_POOL: MaybeUninit<[u8; POOL_SIZE]> = MaybeUninit::uninit();
153
154#[link_section = "MB_MEM2"]
155static mut SYS_SPARE_EVT_BUF: MaybeUninit<[u8; TL_PACKET_HEADER_SIZE + TL_EVT_HEADER_SIZE + 255]> =
156 MaybeUninit::uninit();
157
158#[link_section = "MB_MEM2"]
159static mut BLE_SPARE_EVT_BUF: MaybeUninit<[u8; TL_PACKET_HEADER_SIZE + TL_EVT_HEADER_SIZE + 255]> =
160 MaybeUninit::uninit();
161
162#[link_section = "MB_MEM2"]
163static mut BLE_CMD_BUFFER: MaybeUninit<CmdPacket> = MaybeUninit::uninit();
164
165#[link_section = "MB_MEM2"]
166// fuck these "magic" numbers from ST ---v---v
167static mut HCI_ACL_DATA_BUFFER: MaybeUninit<[u8; TL_PACKET_HEADER_SIZE + 5 + 251]> = MaybeUninit::uninit();
168
169/// current event that is produced during IPCC IRQ handler execution
170/// on SYS channel
171static EVT_CHANNEL: Channel<CriticalSectionRawMutex, EvtBox, 32> = Channel::new();
172
173/// last received Command Complete event
174static LAST_CC_EVT: Signal<CriticalSectionRawMutex, CcEvt> = Signal::new();
175
176static STATE: Signal<CriticalSectionRawMutex, ()> = Signal::new();
177
178pub struct TlMbox<'d> {
179 _ipcc: PeripheralRef<'d, IPCC>,
180}
181
182impl<'d> TlMbox<'d> {
183 pub fn init(
184 ipcc: impl Peripheral<P = IPCC> + 'd,
185 _irqs: impl interrupt::Binding<interrupt::IPCC_C1_RX, ReceiveInterruptHandler>
186 + interrupt::Binding<interrupt::IPCC_C1_TX, TransmitInterruptHandler>,
187 config: Config,
188 ) -> Self {
189 into_ref!(ipcc);
190
191 unsafe {
192 TL_REF_TABLE = MaybeUninit::new(RefTable {
193 device_info_table: TL_DEVICE_INFO_TABLE.as_mut_ptr(),
194 ble_table: TL_BLE_TABLE.as_ptr(),
195 thread_table: TL_THREAD_TABLE.as_ptr(),
196 sys_table: TL_SYS_TABLE.as_ptr(),
197 mem_manager_table: TL_MEM_MANAGER_TABLE.as_ptr(),
198 traces_table: TL_TRACES_TABLE.as_ptr(),
199 mac_802_15_4_table: TL_MAC_802_15_4_TABLE.as_ptr(),
200 });
201
202 TL_SYS_TABLE = MaybeUninit::zeroed();
203 TL_DEVICE_INFO_TABLE = MaybeUninit::zeroed();
204 TL_BLE_TABLE = MaybeUninit::zeroed();
205 TL_THREAD_TABLE = MaybeUninit::zeroed();
206 TL_MEM_MANAGER_TABLE = MaybeUninit::zeroed();
207 TL_TRACES_TABLE = MaybeUninit::zeroed();
208 TL_MAC_802_15_4_TABLE = MaybeUninit::zeroed();
209
210 EVT_POOL = MaybeUninit::zeroed();
211 SYS_SPARE_EVT_BUF = MaybeUninit::zeroed();
212 BLE_SPARE_EVT_BUF = MaybeUninit::zeroed();
213
214 CS_BUFFER = MaybeUninit::zeroed();
215 BLE_CMD_BUFFER = MaybeUninit::zeroed();
216 HCI_ACL_DATA_BUFFER = MaybeUninit::zeroed();
217 }
218
219 Ipcc::enable(config);
220
221 sys::Sys::enable();
222 ble::Ble::enable();
223 mm::MemoryManager::enable();
224
225 // enable interrupts
226 interrupt::IPCC_C1_RX::unpend();
227 interrupt::IPCC_C1_TX::unpend();
228
229 unsafe { interrupt::IPCC_C1_RX::enable() };
230 unsafe { interrupt::IPCC_C1_TX::enable() };
231
232 STATE.reset();
233
234 Self { _ipcc: ipcc }
235 }
236
237 /// Returns CPU2 wireless firmware information (if present).
238 pub fn wireless_fw_info(&self) -> Option<WirelessFwInfoTable> {
239 let info = unsafe { &(*(*TL_REF_TABLE.as_ptr()).device_info_table).wireless_fw_info_table };
240
241 // Zero version indicates that CPU2 wasn't active and didn't fill the information table
242 if info.version != 0 {
243 Some(*info)
244 } else {
245 None
246 }
247 }
248
249 /// picks single [`EvtBox`] from internal event queue.
250 ///
251 /// Internal event queu is populated in IPCC_RX_IRQ handler
252 pub fn dequeue_event(&mut self) -> Option<EvtBox> {
253 EVT_CHANNEL.try_recv().ok()
254 }
255
256 /// retrieves last Command Complete event and removes it from mailbox
257 pub fn pop_last_cc_evt(&mut self) -> Option<CcEvt> {
258 if LAST_CC_EVT.signaled() {
259 let cc = block_on(LAST_CC_EVT.wait());
260 LAST_CC_EVT.reset();
261 Some(cc)
262 } else {
263 None
264 }
265 }
266}
diff --git a/embassy-stm32-wpan/src/mm.rs b/embassy-stm32-wpan/src/mm.rs
new file mode 100644
index 000000000..ed13b0dbf
--- /dev/null
+++ b/embassy-stm32-wpan/src/mm.rs
@@ -0,0 +1,75 @@
1//! Memory manager routines
2
3use core::mem::MaybeUninit;
4
5use embassy_stm32::ipcc::Ipcc;
6
7use crate::evt::EvtPacket;
8use crate::tables::MemManagerTable;
9use crate::unsafe_linked_list::LinkedListNode;
10use crate::{
11 channels, BLE_SPARE_EVT_BUF, EVT_POOL, FREE_BUF_QUEUE, LOCAL_FREE_BUF_QUEUE, POOL_SIZE, SYS_SPARE_EVT_BUF,
12 TL_MEM_MANAGER_TABLE, TL_REF_TABLE,
13};
14
15pub(super) struct MemoryManager;
16
17impl MemoryManager {
18 pub fn enable() {
19 unsafe {
20 LinkedListNode::init_head(FREE_BUF_QUEUE.as_mut_ptr());
21 LinkedListNode::init_head(LOCAL_FREE_BUF_QUEUE.as_mut_ptr());
22
23 TL_MEM_MANAGER_TABLE = MaybeUninit::new(MemManagerTable {
24 spare_ble_buffer: BLE_SPARE_EVT_BUF.as_ptr().cast(),
25 spare_sys_buffer: SYS_SPARE_EVT_BUF.as_ptr().cast(),
26 blepool: EVT_POOL.as_ptr().cast(),
27 blepoolsize: POOL_SIZE as u32,
28 pevt_free_buffer_queue: FREE_BUF_QUEUE.as_mut_ptr(),
29 traces_evt_pool: core::ptr::null(),
30 tracespoolsize: 0,
31 });
32 }
33 }
34
35 pub fn evt_drop(evt: *mut EvtPacket) {
36 unsafe {
37 let list_node = evt.cast();
38
39 LinkedListNode::insert_tail(LOCAL_FREE_BUF_QUEUE.as_mut_ptr(), list_node);
40
41 let channel_is_busy = Ipcc::c1_is_active_flag(channels::cpu1::IPCC_MM_RELEASE_BUFFER_CHANNEL);
42
43 // postpone event buffer freeing to IPCC interrupt handler
44 if channel_is_busy {
45 Ipcc::c1_set_tx_channel(channels::cpu1::IPCC_MM_RELEASE_BUFFER_CHANNEL, true);
46 } else {
47 Self::send_free_buf();
48 Ipcc::c1_set_flag_channel(channels::cpu1::IPCC_MM_RELEASE_BUFFER_CHANNEL);
49 }
50 }
51 }
52
53 /// gives free event buffers back to CPU2 from local buffer queue
54 pub fn send_free_buf() {
55 unsafe {
56 let mut node_ptr = core::ptr::null_mut();
57 let node_ptr_ptr: *mut _ = &mut node_ptr;
58
59 while !LinkedListNode::is_empty(LOCAL_FREE_BUF_QUEUE.as_mut_ptr()) {
60 LinkedListNode::remove_head(LOCAL_FREE_BUF_QUEUE.as_mut_ptr(), node_ptr_ptr);
61 LinkedListNode::insert_tail(
62 (*(*TL_REF_TABLE.as_ptr()).mem_manager_table).pevt_free_buffer_queue,
63 node_ptr,
64 );
65 }
66 }
67 }
68
69 /// free buffer channel interrupt handler
70 pub fn free_buf_handler() {
71 Ipcc::c1_set_tx_channel(channels::cpu1::IPCC_MM_RELEASE_BUFFER_CHANNEL, false);
72 Self::send_free_buf();
73 Ipcc::c1_set_flag_channel(channels::cpu1::IPCC_MM_RELEASE_BUFFER_CHANNEL);
74 }
75}
diff --git a/embassy-stm32-wpan/src/rc.rs b/embassy-stm32-wpan/src/rc.rs
new file mode 100644
index 000000000..aae2265ed
--- /dev/null
+++ b/embassy-stm32-wpan/src/rc.rs
@@ -0,0 +1,50 @@
1use crate::ble::Ble;
2use crate::consts::TlPacketType;
3use crate::{shci, TlMbox, STATE};
4
5pub struct RadioCoprocessor<'d> {
6 mbox: TlMbox<'d>,
7 rx_buf: [u8; 500],
8}
9
10impl<'d> RadioCoprocessor<'d> {
11 pub fn new(mbox: TlMbox<'d>) -> Self {
12 Self {
13 mbox,
14 rx_buf: [0u8; 500],
15 }
16 }
17
18 pub fn write(&self, buf: &[u8]) {
19 let cmd_code = buf[0];
20 let cmd = TlPacketType::try_from(cmd_code).unwrap();
21
22 match &cmd {
23 TlPacketType::BleCmd => Ble::ble_send_cmd(buf),
24 _ => todo!(),
25 }
26 }
27
28 pub async fn read(&mut self) -> &[u8] {
29 loop {
30 STATE.wait().await;
31
32 while let Some(evt) = self.mbox.dequeue_event() {
33 let event = evt.evt();
34
35 evt.write(&mut self.rx_buf).unwrap();
36
37 if event.kind() == 18 {
38 shci::shci_ble_init(Default::default());
39 self.rx_buf[0] = 0x04;
40 }
41 }
42
43 if self.mbox.pop_last_cc_evt().is_some() {
44 continue;
45 }
46
47 return &self.rx_buf;
48 }
49 }
50}
diff --git a/embassy-stm32-wpan/src/shci.rs b/embassy-stm32-wpan/src/shci.rs
new file mode 100644
index 000000000..4f4d08886
--- /dev/null
+++ b/embassy-stm32-wpan/src/shci.rs
@@ -0,0 +1,100 @@
1use super::cmd::CmdPacket;
2use super::consts::TlPacketType;
3use super::{sys, TL_CS_EVT_SIZE, TL_EVT_HEADER_SIZE, TL_PACKET_HEADER_SIZE, TL_SYS_TABLE};
4
5const SCHI_OPCODE_BLE_INIT: u16 = 0xfc66;
6
7#[derive(Debug, Clone, Copy)]
8#[repr(C, packed)]
9pub struct ShciBleInitCmdParam {
10 /// NOT USED CURRENTLY
11 pub p_ble_buffer_address: u32,
12
13 /// Size of the Buffer allocated in pBleBufferAddress
14 pub ble_buffer_size: u32,
15
16 pub num_attr_record: u16,
17 pub num_attr_serv: u16,
18 pub attr_value_arr_size: u16,
19 pub num_of_links: u8,
20 pub extended_packet_length_enable: u8,
21 pub pr_write_list_size: u8,
22 pub mb_lock_count: u8,
23
24 pub att_mtu: u16,
25 pub slave_sca: u16,
26 pub master_sca: u8,
27 pub ls_source: u8,
28 pub max_conn_event_length: u32,
29 pub hs_startup_time: u16,
30 pub viterbi_enable: u8,
31 pub ll_only: u8,
32 pub hw_version: u8,
33}
34
35impl Default for ShciBleInitCmdParam {
36 fn default() -> Self {
37 Self {
38 p_ble_buffer_address: 0,
39 ble_buffer_size: 0,
40 num_attr_record: 68,
41 num_attr_serv: 8,
42 attr_value_arr_size: 1344,
43 num_of_links: 2,
44 extended_packet_length_enable: 1,
45 pr_write_list_size: 0x3A,
46 mb_lock_count: 0x79,
47 att_mtu: 156,
48 slave_sca: 500,
49 master_sca: 0,
50 ls_source: 1,
51 max_conn_event_length: 0xFFFFFFFF,
52 hs_startup_time: 0x148,
53 viterbi_enable: 1,
54 ll_only: 0,
55 hw_version: 0,
56 }
57 }
58}
59
60#[derive(Debug, Clone, Copy, Default)]
61#[repr(C, packed)]
62pub struct ShciHeader {
63 metadata: [u32; 3],
64}
65
66#[derive(Debug, Clone, Copy)]
67#[repr(C, packed)]
68pub struct ShciBleInitCmdPacket {
69 header: ShciHeader,
70 param: ShciBleInitCmdParam,
71}
72
73pub const TL_BLE_EVT_CS_PACKET_SIZE: usize = TL_EVT_HEADER_SIZE + TL_CS_EVT_SIZE;
74#[allow(dead_code)] // Not used currently but reserved
75const TL_BLE_EVT_CS_BUFFER_SIZE: usize = TL_PACKET_HEADER_SIZE + TL_BLE_EVT_CS_PACKET_SIZE;
76
77pub fn shci_ble_init(param: ShciBleInitCmdParam) {
78 debug!("sending SHCI");
79
80 let mut packet = ShciBleInitCmdPacket {
81 header: ShciHeader::default(),
82 param,
83 };
84
85 let packet_ptr: *mut _ = &mut packet;
86
87 unsafe {
88 let cmd_ptr: *mut CmdPacket = packet_ptr.cast();
89
90 (*cmd_ptr).cmdserial.cmd.cmd_code = SCHI_OPCODE_BLE_INIT;
91 (*cmd_ptr).cmdserial.cmd.payload_len = core::mem::size_of::<ShciBleInitCmdParam>() as u8;
92
93 let mut p_cmd_buffer = &mut *(*TL_SYS_TABLE.as_mut_ptr()).pcmd_buffer;
94 core::ptr::write(p_cmd_buffer, *cmd_ptr);
95
96 p_cmd_buffer.cmdserial.ty = TlPacketType::SysCmd as u8;
97
98 sys::Sys::send_cmd();
99 }
100}
diff --git a/embassy-stm32-wpan/src/sys.rs b/embassy-stm32-wpan/src/sys.rs
new file mode 100644
index 000000000..a19d12d27
--- /dev/null
+++ b/embassy-stm32-wpan/src/sys.rs
@@ -0,0 +1,70 @@
1use core::mem::MaybeUninit;
2
3use embassy_stm32::ipcc::Ipcc;
4
5use crate::cmd::{CmdPacket, CmdSerial};
6use crate::evt::{CcEvt, EvtBox, EvtSerial};
7use crate::tables::SysTable;
8use crate::unsafe_linked_list::LinkedListNode;
9use crate::{channels, EVT_CHANNEL, SYSTEM_EVT_QUEUE, SYS_CMD_BUF, TL_SYS_TABLE};
10
11pub struct Sys;
12
13impl Sys {
14 pub fn enable() {
15 unsafe {
16 LinkedListNode::init_head(SYSTEM_EVT_QUEUE.as_mut_ptr());
17
18 TL_SYS_TABLE = MaybeUninit::new(SysTable {
19 pcmd_buffer: SYS_CMD_BUF.as_mut_ptr(),
20 sys_queue: SYSTEM_EVT_QUEUE.as_ptr(),
21 })
22 }
23
24 Ipcc::c1_set_rx_channel(channels::cpu2::IPCC_SYSTEM_EVENT_CHANNEL, true);
25 }
26
27 pub fn cmd_evt_handler() -> CcEvt {
28 Ipcc::c1_set_tx_channel(channels::cpu1::IPCC_SYSTEM_CMD_RSP_CHANNEL, false);
29
30 // ST's command response data structure is really convoluted.
31 //
32 // for command response events on SYS channel, the header is missing
33 // and one should:
34 // 1. interpret the content of CMD_BUFFER as CmdPacket
35 // 2. Access CmdPacket's cmdserial field and interpret its content as EvtSerial
36 // 3. Access EvtSerial's evt field (as Evt) and interpret its payload as CcEvt
37 // 4. CcEvt type is the actual SHCI response
38 // 5. profit
39 unsafe {
40 let pcmd: *const CmdPacket = (*TL_SYS_TABLE.as_ptr()).pcmd_buffer;
41 let cmd_serial: *const CmdSerial = &(*pcmd).cmdserial;
42 let evt_serial: *const EvtSerial = cmd_serial.cast();
43 let cc: *const CcEvt = (*evt_serial).evt.payload.as_ptr().cast();
44 *cc
45 }
46 }
47
48 pub fn evt_handler() {
49 unsafe {
50 let mut node_ptr = core::ptr::null_mut();
51 let node_ptr_ptr: *mut _ = &mut node_ptr;
52
53 while !LinkedListNode::is_empty(SYSTEM_EVT_QUEUE.as_mut_ptr()) {
54 LinkedListNode::remove_head(SYSTEM_EVT_QUEUE.as_mut_ptr(), node_ptr_ptr);
55
56 let event = node_ptr.cast();
57 let event = EvtBox::new(event);
58
59 EVT_CHANNEL.try_send(event).unwrap();
60 }
61 }
62
63 Ipcc::c1_clear_flag_channel(channels::cpu2::IPCC_SYSTEM_EVENT_CHANNEL);
64 }
65
66 pub fn send_cmd() {
67 Ipcc::c1_set_flag_channel(channels::cpu1::IPCC_SYSTEM_CMD_RSP_CHANNEL);
68 Ipcc::c1_set_tx_channel(channels::cpu1::IPCC_SYSTEM_CMD_RSP_CHANNEL, true);
69 }
70}
diff --git a/embassy-stm32-wpan/src/tables.rs b/embassy-stm32-wpan/src/tables.rs
new file mode 100644
index 000000000..151216958
--- /dev/null
+++ b/embassy-stm32-wpan/src/tables.rs
@@ -0,0 +1,175 @@
1use bit_field::BitField;
2
3use crate::cmd::{AclDataPacket, CmdPacket};
4use crate::unsafe_linked_list::LinkedListNode;
5
6#[derive(Debug, Copy, Clone)]
7#[repr(C, packed)]
8pub struct SafeBootInfoTable {
9 version: u32,
10}
11
12#[derive(Debug, Copy, Clone)]
13#[repr(C, packed)]
14pub struct RssInfoTable {
15 pub version: u32,
16 pub memory_size: u32,
17 pub rss_info: u32,
18}
19
20/**
21 * Version
22 * [0:3] = Build - 0: Untracked - 15:Released - x: Tracked version
23 * [4:7] = branch - 0: Mass Market - x: ...
24 * [8:15] = Subversion
25 * [16:23] = Version minor
26 * [24:31] = Version major
27 *
28 * Memory Size
29 * [0:7] = Flash ( Number of 4k sector)
30 * [8:15] = Reserved ( Shall be set to 0 - may be used as flash extension )
31 * [16:23] = SRAM2b ( Number of 1k sector)
32 * [24:31] = SRAM2a ( Number of 1k sector)
33 */
34#[derive(Debug, Copy, Clone)]
35#[repr(C, packed)]
36pub struct WirelessFwInfoTable {
37 pub version: u32,
38 pub memory_size: u32,
39 pub thread_info: u32,
40 pub ble_info: u32,
41}
42
43impl WirelessFwInfoTable {
44 pub fn version_major(&self) -> u8 {
45 let version = self.version;
46 (version.get_bits(24..31) & 0xff) as u8
47 }
48
49 pub fn version_minor(&self) -> u8 {
50 let version = self.version;
51 (version.clone().get_bits(16..23) & 0xff) as u8
52 }
53
54 pub fn subversion(&self) -> u8 {
55 let version = self.version;
56 (version.clone().get_bits(8..15) & 0xff) as u8
57 }
58
59 /// Size of FLASH, expressed in number of 4K sectors.
60 pub fn flash_size(&self) -> u8 {
61 let memory_size = self.memory_size;
62 (memory_size.clone().get_bits(0..7) & 0xff) as u8
63 }
64
65 /// Size of SRAM2a, expressed in number of 1K sectors.
66 pub fn sram2a_size(&self) -> u8 {
67 let memory_size = self.memory_size;
68 (memory_size.clone().get_bits(24..31) & 0xff) as u8
69 }
70
71 /// Size of SRAM2b, expressed in number of 1K sectors.
72 pub fn sram2b_size(&self) -> u8 {
73 let memory_size = self.memory_size;
74 (memory_size.clone().get_bits(16..23) & 0xff) as u8
75 }
76}
77
78#[derive(Debug, Clone)]
79#[repr(C, align(4))]
80pub struct DeviceInfoTable {
81 pub safe_boot_info_table: SafeBootInfoTable,
82 pub rss_info_table: RssInfoTable,
83 pub wireless_fw_info_table: WirelessFwInfoTable,
84}
85
86#[derive(Debug)]
87#[repr(C, align(4))]
88pub struct BleTable {
89 pub pcmd_buffer: *mut CmdPacket,
90 pub pcs_buffer: *const u8,
91 pub pevt_queue: *const u8,
92 pub phci_acl_data_buffer: *mut AclDataPacket,
93}
94
95#[derive(Debug)]
96#[repr(C, align(4))]
97pub struct ThreadTable {
98 pub nostack_buffer: *const u8,
99 pub clicmdrsp_buffer: *const u8,
100 pub otcmdrsp_buffer: *const u8,
101}
102
103// TODO: use later
104#[derive(Debug)]
105#[repr(C, align(4))]
106pub struct LldTestsTable {
107 pub clicmdrsp_buffer: *const u8,
108 pub m0cmd_buffer: *const u8,
109}
110
111// TODO: use later
112#[derive(Debug)]
113#[repr(C, align(4))]
114pub struct BleLldTable {
115 pub cmdrsp_buffer: *const u8,
116 pub m0cmd_buffer: *const u8,
117}
118
119// TODO: use later
120#[derive(Debug)]
121#[repr(C, align(4))]
122pub struct ZigbeeTable {
123 pub notif_m0_to_m4_buffer: *const u8,
124 pub appli_cmd_m4_to_m0_bufer: *const u8,
125 pub request_m0_to_m4_buffer: *const u8,
126}
127
128#[derive(Debug)]
129#[repr(C, align(4))]
130pub struct SysTable {
131 pub pcmd_buffer: *mut CmdPacket,
132 pub sys_queue: *const LinkedListNode,
133}
134
135#[derive(Debug)]
136#[repr(C, align(4))]
137pub struct MemManagerTable {
138 pub spare_ble_buffer: *const u8,
139 pub spare_sys_buffer: *const u8,
140
141 pub blepool: *const u8,
142 pub blepoolsize: u32,
143
144 pub pevt_free_buffer_queue: *mut LinkedListNode,
145
146 pub traces_evt_pool: *const u8,
147 pub tracespoolsize: u32,
148}
149
150#[derive(Debug)]
151#[repr(C, align(4))]
152pub struct TracesTable {
153 pub traces_queue: *const u8,
154}
155
156#[derive(Debug)]
157#[repr(C, align(4))]
158pub struct Mac802_15_4Table {
159 pub p_cmdrsp_buffer: *const u8,
160 pub p_notack_buffer: *const u8,
161 pub evt_queue: *const u8,
162}
163
164/// Reference table. Contains pointers to all other tables.
165#[derive(Debug, Copy, Clone)]
166#[repr(C)]
167pub struct RefTable {
168 pub device_info_table: *const DeviceInfoTable,
169 pub ble_table: *const BleTable,
170 pub thread_table: *const ThreadTable,
171 pub sys_table: *const SysTable,
172 pub mem_manager_table: *const MemManagerTable,
173 pub traces_table: *const TracesTable,
174 pub mac_802_15_4_table: *const Mac802_15_4Table,
175}
diff --git a/embassy-stm32-wpan/src/unsafe_linked_list.rs b/embassy-stm32-wpan/src/unsafe_linked_list.rs
new file mode 100644
index 000000000..52c106fa2
--- /dev/null
+++ b/embassy-stm32-wpan/src/unsafe_linked_list.rs
@@ -0,0 +1,128 @@
1//! Unsafe linked list.
2//! Translated from ST's C by `c2rust` tool.
3
4#![allow(
5 dead_code,
6 mutable_transmutes,
7 non_camel_case_types,
8 non_snake_case,
9 non_upper_case_globals,
10 unused_assignments,
11 unused_mut
12)]
13
14use cortex_m::interrupt;
15
16#[derive(Copy, Clone)]
17#[repr(C, packed(4))]
18pub struct LinkedListNode {
19 pub next: *mut LinkedListNode,
20 pub prev: *mut LinkedListNode,
21}
22
23impl Default for LinkedListNode {
24 fn default() -> Self {
25 LinkedListNode {
26 next: core::ptr::null_mut(),
27 prev: core::ptr::null_mut(),
28 }
29 }
30}
31
32impl LinkedListNode {
33 pub unsafe fn init_head(mut list_head: *mut LinkedListNode) {
34 (*list_head).next = list_head;
35 (*list_head).prev = list_head;
36 }
37
38 pub unsafe fn is_empty(mut list_head: *mut LinkedListNode) -> bool {
39 interrupt::free(|_| ((*list_head).next) == list_head)
40 }
41
42 pub unsafe fn insert_head(mut list_head: *mut LinkedListNode, mut node: *mut LinkedListNode) {
43 interrupt::free(|_| {
44 (*node).next = (*list_head).next;
45 (*node).prev = list_head;
46 (*list_head).next = node;
47 (*(*node).next).prev = node;
48 });
49 }
50
51 pub unsafe fn insert_tail(mut list_head: *mut LinkedListNode, mut node: *mut LinkedListNode) {
52 interrupt::free(|_| {
53 (*node).next = list_head;
54 (*node).prev = (*list_head).prev;
55 (*list_head).prev = node;
56 (*(*node).prev).next = node;
57 });
58 }
59
60 /// Remove `node` from the linked list
61 pub unsafe fn remove_node(mut node: *mut LinkedListNode) {
62 interrupt::free(|_| {
63 (*(*node).prev).next = (*node).next;
64 (*(*node).next).prev = (*node).prev;
65 });
66 }
67
68 /// Remove `list_head` into `node`
69 pub unsafe fn remove_head(mut list_head: *mut LinkedListNode, mut node: *mut *mut LinkedListNode) {
70 interrupt::free(|_| {
71 *node = (*list_head).next;
72 Self::remove_node((*list_head).next);
73 });
74 }
75
76 /// Remove `list_tail` into `node`
77 pub unsafe fn remove_tail(mut list_tail: *mut LinkedListNode, mut node: *mut *mut LinkedListNode) {
78 interrupt::free(|_| {
79 *node = (*list_tail).prev;
80 Self::remove_node((*list_tail).prev);
81 });
82 }
83
84 pub unsafe fn insert_node_after(mut node: *mut LinkedListNode, mut ref_node: *mut LinkedListNode) {
85 interrupt::free(|_| {
86 (*node).next = (*ref_node).next;
87 (*node).prev = ref_node;
88 (*ref_node).next = node;
89 (*(*node).next).prev = node;
90 });
91 }
92
93 pub unsafe fn insert_node_before(mut node: *mut LinkedListNode, mut ref_node: *mut LinkedListNode) {
94 interrupt::free(|_| {
95 (*node).next = ref_node;
96 (*node).prev = (*ref_node).prev;
97 (*ref_node).prev = node;
98 (*(*node).prev).next = node;
99 });
100 }
101
102 pub unsafe fn get_size(mut list_head: *mut LinkedListNode) -> usize {
103 interrupt::free(|_| {
104 let mut size = 0;
105 let mut temp: *mut LinkedListNode = core::ptr::null_mut::<LinkedListNode>();
106
107 temp = (*list_head).next;
108 while temp != list_head {
109 size += 1;
110 temp = (*temp).next
111 }
112
113 size
114 })
115 }
116
117 pub unsafe fn get_next_node(mut ref_node: *mut LinkedListNode, mut node: *mut *mut LinkedListNode) {
118 interrupt::free(|_| {
119 *node = (*ref_node).next;
120 });
121 }
122
123 pub unsafe fn get_prev_node(mut ref_node: *mut LinkedListNode, mut node: *mut *mut LinkedListNode) {
124 interrupt::free(|_| {
125 *node = (*ref_node).prev;
126 });
127 }
128}