1use core::marker::PhantomData;
2
3use embedded_hal_async::spi::SpiDevice;
4
5use crate::chip::Chip;
6
7#[repr(u8)]
8enum Command {
9 Open = 0x01,
10 Send = 0x20,
11 Receive = 0x40,
12}
13
14#[repr(u8)]
15enum Interrupt {
16 Receive = 0b00100_u8,
17}
18
19#[derive(Debug)]
21#[cfg_attr(feature = "defmt", derive(defmt::Format))]
22pub(crate) struct WiznetDevice<C, SPI> {
23 spi: SPI,
24 _phantom: PhantomData<C>,
25}
26
27pub enum InitError<SE> {
29 SpiError(SE),
31 InvalidChipVersion {
33 expected: u8,
35 actual: u8,
37 },
38}
39
40impl<SE> From<SE> for InitError<SE> {
41 fn from(e: SE) -> Self {
42 InitError::SpiError(e)
43 }
44}
45
46impl<SE> core::fmt::Debug for InitError<SE>
47where
48 SE: core::fmt::Debug,
49{
50 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
51 match self {
52 InitError::SpiError(e) => write!(f, "SpiError({:?})", e),
53 InitError::InvalidChipVersion { expected, actual } => {
54 write!(f, "InvalidChipVersion {{ expected: {}, actual: {} }}", expected, actual)
55 }
56 }
57 }
58}
59
60#[cfg(feature = "defmt")]
61impl<SE> defmt::Format for InitError<SE>
62where
63 SE: defmt::Format,
64{
65 fn format(&self, f: defmt::Formatter) {
66 match self {
67 InitError::SpiError(e) => defmt::write!(f, "SpiError({})", e),
68 InitError::InvalidChipVersion { expected, actual } => {
69 defmt::write!(f, "InvalidChipVersion {{ expected: {}, actual: {} }}", expected, actual)
70 }
71 }
72 }
73}
74
75impl<C: Chip, SPI: SpiDevice> WiznetDevice<C, SPI> {
76 pub async fn new(spi: SPI, mac_addr: [u8; 6]) -> Result<Self, InitError<SPI::Error>> {
78 let mut this = Self {
79 spi,
80 _phantom: PhantomData,
81 };
82
83 this.bus_write(C::COMMON_MODE, &[0x80]).await?;
85
86 let mut version = [0];
88 this.bus_read(C::COMMON_VERSION, &mut version).await?;
89 if version[0] != C::CHIP_VERSION {
90 #[cfg(feature = "defmt")]
91 defmt::error!("invalid chip version: {} (expected {})", version[0], C::CHIP_VERSION);
92 return Err(InitError::InvalidChipVersion {
93 actual: version[0],
94 expected: C::CHIP_VERSION,
95 });
96 }
97
98 this.bus_write(C::COMMON_SOCKET_INTR, &[0x01]).await?;
100 this.bus_write(C::SOCKET_INTR_MASK, &[Interrupt::Receive as u8]).await?;
102
103 this.bus_write(C::COMMON_MAC, &mac_addr).await?;
105
106 let buf_kbs = (C::BUF_SIZE / 1024) as u8;
108 this.bus_write(C::SOCKET_TXBUF_SIZE, &[buf_kbs]).await?;
109 this.bus_write(C::SOCKET_RXBUF_SIZE, &[buf_kbs]).await?;
110
111 this.bus_write(C::SOCKET_MODE, &[C::SOCKET_MODE_VALUE]).await?;
113 this.command(Command::Open).await?;
114
115 Ok(this)
116 }
117
118 async fn bus_read(&mut self, address: C::Address, data: &mut [u8]) -> Result<(), SPI::Error> {
119 C::bus_read(&mut self.spi, address, data).await
120 }
121
122 async fn bus_write(&mut self, address: C::Address, data: &[u8]) -> Result<(), SPI::Error> {
123 C::bus_write(&mut self.spi, address, data).await
124 }
125
126 async fn reset_interrupt(&mut self, code: Interrupt) -> Result<(), SPI::Error> {
127 let data = [code as u8];
128 self.bus_write(C::SOCKET_INTR, &data).await
129 }
130
131 async fn get_tx_write_ptr(&mut self) -> Result<u16, SPI::Error> {
132 let mut data = [0u8; 2];
133 self.bus_read(C::SOCKET_TX_DATA_WRITE_PTR, &mut data).await?;
134 Ok(u16::from_be_bytes(data))
135 }
136
137 async fn set_tx_write_ptr(&mut self, ptr: u16) -> Result<(), SPI::Error> {
138 let data = ptr.to_be_bytes();
139 self.bus_write(C::SOCKET_TX_DATA_WRITE_PTR, &data).await
140 }
141
142 async fn get_rx_read_ptr(&mut self) -> Result<u16, SPI::Error> {
143 let mut data = [0u8; 2];
144 self.bus_read(C::SOCKET_RX_DATA_READ_PTR, &mut data).await?;
145 Ok(u16::from_be_bytes(data))
146 }
147
148 async fn set_rx_read_ptr(&mut self, ptr: u16) -> Result<(), SPI::Error> {
149 let data = ptr.to_be_bytes();
150 self.bus_write(C::SOCKET_RX_DATA_READ_PTR, &data).await
151 }
152
153 async fn command(&mut self, command: Command) -> Result<(), SPI::Error> {
154 let data = [command as u8];
155 self.bus_write(C::SOCKET_COMMAND, &data).await
156 }
157
158 async fn get_rx_size(&mut self) -> Result<u16, SPI::Error> {
159 loop {
160 let mut res0 = [0u8; 2];
162 self.bus_read(C::SOCKET_RECVD_SIZE, &mut res0).await?;
163 let mut res1 = [0u8; 2];
164 self.bus_read(C::SOCKET_RECVD_SIZE, &mut res1).await?;
165 if res0 == res1 {
166 break Ok(u16::from_be_bytes(res0));
167 }
168 }
169 }
170
171 async fn get_tx_free_size(&mut self) -> Result<u16, SPI::Error> {
172 let mut data = [0; 2];
173 self.bus_read(C::SOCKET_TX_FREE_SIZE, &mut data).await?;
174 Ok(u16::from_be_bytes(data))
175 }
176
177 async fn read_bytes(&mut self, read_ptr: &mut u16, buffer: &mut [u8]) -> Result<(), SPI::Error> {
179 if C::AUTO_WRAP {
180 self.bus_read(C::rx_addr(*read_ptr), buffer).await?;
181 } else {
182 let addr = *read_ptr % C::BUF_SIZE;
183 if addr as usize + buffer.len() <= C::BUF_SIZE as usize {
184 self.bus_read(C::rx_addr(addr), buffer).await?;
185 } else {
186 let n = C::BUF_SIZE - addr;
187 self.bus_read(C::rx_addr(addr), &mut buffer[..n as usize]).await?;
188 self.bus_read(C::rx_addr(0), &mut buffer[n as usize..]).await?;
189 }
190 }
191
192 *read_ptr = (*read_ptr).wrapping_add(buffer.len() as u16);
193
194 Ok(())
195 }
196
197 pub async fn read_frame(&mut self, frame: &mut [u8]) -> Result<usize, SPI::Error> {
199 let rx_size = self.get_rx_size().await? as usize;
200 if rx_size == 0 {
201 return Ok(0);
202 }
203
204 self.reset_interrupt(Interrupt::Receive).await?;
205
206 let mut read_ptr = self.get_rx_read_ptr().await?;
207
208 let expected_frame_size: usize = {
210 let mut frame_bytes = [0u8; 2];
211 self.read_bytes(&mut read_ptr, &mut frame_bytes).await?;
212 u16::from_be_bytes(frame_bytes) as usize - 2
213 };
214
215 self.read_bytes(&mut read_ptr, &mut frame[..expected_frame_size])
217 .await?;
218
219 self.set_rx_read_ptr(read_ptr).await?;
221 self.command(Command::Receive).await?;
222
223 Ok(expected_frame_size)
224 }
225
226 pub async fn write_frame(&mut self, frame: &[u8]) -> Result<usize, SPI::Error> {
228 while self.get_tx_free_size().await? < frame.len() as u16 {}
229 let write_ptr = self.get_tx_write_ptr().await?;
230
231 if C::AUTO_WRAP {
232 self.bus_write(C::tx_addr(write_ptr), frame).await?;
233 } else {
234 let addr = write_ptr % C::BUF_SIZE;
235 if addr as usize + frame.len() <= C::BUF_SIZE as usize {
236 self.bus_write(C::tx_addr(addr), frame).await?;
237 } else {
238 let n = C::BUF_SIZE - addr;
239 self.bus_write(C::tx_addr(addr), &frame[..n as usize]).await?;
240 self.bus_write(C::tx_addr(0), &frame[n as usize..]).await?;
241 }
242 }
243
244 self.set_tx_write_ptr(write_ptr.wrapping_add(frame.len() as u16))
245 .await?;
246 self.command(Command::Send).await?;
247 Ok(frame.len())
248 }
249
250 pub async fn is_link_up(&mut self) -> bool {
251 let mut link = [0];
252 self.bus_read(C::COMMON_PHY_CFG, &mut link).await.ok();
253 link[0] & 1 == 1
254 }
255}