Compare commits

...

15 Commits

Author SHA1 Message Date
51a67cb69a fix: expose less 2023-12-20 13:34:34 +01:00
b8777eaea2 better keep missing docs for into 2023-12-20 13:12:32 +01:00
b0583b17cb fix: make non-public instead 2023-12-20 13:08:06 +01:00
246c49621c docs: embassy-net-adin1110 2023-12-20 12:52:35 +01:00
52a801fdb7 Merge pull request #2329 from embassy-rs/apidoc-embassy-net-driver-channel
docs: document public apis of embassy-net-driver-channel
2023-12-20 09:08:55 +00:00
fc6e70caa5 docs: document public apis of embassy-net-driver-channel 2023-12-20 09:24:10 +01:00
97e919ea64 Merge pull request #2326 from embassy-rs/salty-update
Salty update
2023-12-19 21:30:32 +00:00
c7841a37fa boot: update ed25519-dalek in dev-dependencies. 2023-12-19 22:26:50 +01:00
589a16b255 Merge pull request #2327 from dragonnn/main
fix stm32 rtc year from 1970 base 2000 to make leap years work
2023-12-19 20:26:01 +00:00
4567b87482 cargo fmt 2023-12-19 21:21:52 +01:00
12de90e13d fix: update ed25519-dalek to new version 2023-12-19 21:20:30 +01:00
871ed538b1 fix stm32 rtc year from 1970 base 2000 2023-12-19 21:17:42 +01:00
efd5dbe019 fix: build warnings 2023-12-19 20:25:20 +01:00
9d46ee0758 fix: update salty to released version 2023-12-19 20:24:55 +01:00
e5912972ec Merge pull request #2325 from embassy-rs/stm32-docs
stm32: finish docs.
2023-12-19 17:07:53 +00:00
12 changed files with 98 additions and 43 deletions

View File

@ -26,25 +26,22 @@ features = ["defmt"]
defmt = { version = "0.3", optional = true } defmt = { version = "0.3", optional = true }
digest = "0.10" digest = "0.10"
log = { version = "0.4", optional = true } log = { version = "0.4", optional = true }
ed25519-dalek = { version = "1.0.1", default_features = false, features = ["u32_backend"], optional = true } ed25519-dalek = { version = "2", default_features = false, features = ["digest"], optional = true }
embassy-embedded-hal = { version = "0.1.0", path = "../../embassy-embedded-hal" } embassy-embedded-hal = { version = "0.1.0", path = "../../embassy-embedded-hal" }
embassy-sync = { version = "0.5.0", path = "../../embassy-sync" } embassy-sync = { version = "0.5.0", path = "../../embassy-sync" }
embedded-storage = "0.3.1" embedded-storage = "0.3.1"
embedded-storage-async = { version = "0.4.1" } embedded-storage-async = { version = "0.4.1" }
salty = { git = "https://github.com/ycrypto/salty.git", rev = "a9f17911a5024698406b75c0fac56ab5ccf6a8c7", optional = true } salty = { version = "0.3", optional = true }
signature = { version = "1.6.4", default-features = false } signature = { version = "2.0", default-features = false }
[dev-dependencies] [dev-dependencies]
log = "0.4" log = "0.4"
env_logger = "0.9" env_logger = "0.9"
rand = "0.7" # ed25519-dalek v1.0.1 depends on this exact version rand = "0.8"
futures = { version = "0.3", features = ["executor"] } futures = { version = "0.3", features = ["executor"] }
sha1 = "0.10.5" sha1 = "0.10.5"
critical-section = { version = "1.1.1", features = ["std"] } critical-section = { version = "1.1.1", features = ["std"] }
ed25519-dalek = { version = "2", default_features = false, features = ["std", "rand_core", "digest"] }
[dev-dependencies.ed25519-dalek]
default_features = false
features = ["rand", "std", "u32_backend"]
[features] [features]
ed25519-dalek = ["dep:ed25519-dalek", "_verify"] ed25519-dalek = ["dep:ed25519-dalek", "_verify"]

View File

@ -1,6 +1,6 @@
use digest::typenum::U64; use digest::typenum::U64;
use digest::{FixedOutput, HashMarker, OutputSizeUser, Update}; use digest::{FixedOutput, HashMarker, OutputSizeUser, Update};
use ed25519_dalek::Digest as _; use ed25519_dalek::Digest;
pub struct Sha512(ed25519_dalek::Sha512); pub struct Sha512(ed25519_dalek::Sha512);
@ -12,7 +12,7 @@ impl Default for Sha512 {
impl Update for Sha512 { impl Update for Sha512 {
fn update(&mut self, data: &[u8]) { fn update(&mut self, data: &[u8]) {
self.0.update(data) Digest::update(&mut self.0, data)
} }
} }

View File

@ -79,8 +79,8 @@ impl<'d, DFU: NorFlash, STATE: NorFlash> FirmwareUpdater<'d, DFU, STATE> {
#[cfg(feature = "_verify")] #[cfg(feature = "_verify")]
pub async fn verify_and_mark_updated( pub async fn verify_and_mark_updated(
&mut self, &mut self,
_public_key: &[u8], _public_key: &[u8; 32],
_signature: &[u8], _signature: &[u8; 64],
_update_len: u32, _update_len: u32,
) -> Result<(), FirmwareUpdaterError> { ) -> Result<(), FirmwareUpdaterError> {
assert!(_update_len <= self.dfu.capacity() as u32); assert!(_update_len <= self.dfu.capacity() as u32);
@ -89,14 +89,14 @@ impl<'d, DFU: NorFlash, STATE: NorFlash> FirmwareUpdater<'d, DFU, STATE> {
#[cfg(feature = "ed25519-dalek")] #[cfg(feature = "ed25519-dalek")]
{ {
use ed25519_dalek::{PublicKey, Signature, SignatureError, Verifier}; use ed25519_dalek::{Signature, SignatureError, Verifier, VerifyingKey};
use crate::digest_adapters::ed25519_dalek::Sha512; use crate::digest_adapters::ed25519_dalek::Sha512;
let into_signature_error = |e: SignatureError| FirmwareUpdaterError::Signature(e.into()); let into_signature_error = |e: SignatureError| FirmwareUpdaterError::Signature(e.into());
let public_key = PublicKey::from_bytes(_public_key).map_err(into_signature_error)?; let public_key = VerifyingKey::from_bytes(_public_key).map_err(into_signature_error)?;
let signature = Signature::from_bytes(_signature).map_err(into_signature_error)?; let signature = Signature::from_bytes(_signature);
let mut chunk_buf = [0; 2]; let mut chunk_buf = [0; 2];
let mut message = [0; 64]; let mut message = [0; 64];
@ -106,7 +106,6 @@ impl<'d, DFU: NorFlash, STATE: NorFlash> FirmwareUpdater<'d, DFU, STATE> {
} }
#[cfg(feature = "ed25519-salty")] #[cfg(feature = "ed25519-salty")]
{ {
use salty::constants::{PUBLICKEY_SERIALIZED_LENGTH, SIGNATURE_SERIALIZED_LENGTH};
use salty::{PublicKey, Signature}; use salty::{PublicKey, Signature};
use crate::digest_adapters::salty::Sha512; use crate::digest_adapters::salty::Sha512;
@ -115,10 +114,8 @@ impl<'d, DFU: NorFlash, STATE: NorFlash> FirmwareUpdater<'d, DFU, STATE> {
FirmwareUpdaterError::Signature(signature::Error::default()) FirmwareUpdaterError::Signature(signature::Error::default())
} }
let public_key: [u8; PUBLICKEY_SERIALIZED_LENGTH] = _public_key.try_into().map_err(into_signature_error)?; let public_key = PublicKey::try_from(_public_key).map_err(into_signature_error)?;
let public_key = PublicKey::try_from(&public_key).map_err(into_signature_error)?; let signature = Signature::try_from(_signature).map_err(into_signature_error)?;
let signature: [u8; SIGNATURE_SERIALIZED_LENGTH] = _signature.try_into().map_err(into_signature_error)?;
let signature = Signature::try_from(&signature).map_err(into_signature_error)?;
let mut message = [0; 64]; let mut message = [0; 64];
let mut chunk_buf = [0; 2]; let mut chunk_buf = [0; 2];

View File

@ -86,8 +86,8 @@ impl<'d, DFU: NorFlash, STATE: NorFlash> BlockingFirmwareUpdater<'d, DFU, STATE>
#[cfg(feature = "_verify")] #[cfg(feature = "_verify")]
pub fn verify_and_mark_updated( pub fn verify_and_mark_updated(
&mut self, &mut self,
_public_key: &[u8], _public_key: &[u8; 32],
_signature: &[u8], _signature: &[u8; 64],
_update_len: u32, _update_len: u32,
) -> Result<(), FirmwareUpdaterError> { ) -> Result<(), FirmwareUpdaterError> {
assert!(_update_len <= self.dfu.capacity() as u32); assert!(_update_len <= self.dfu.capacity() as u32);
@ -96,14 +96,14 @@ impl<'d, DFU: NorFlash, STATE: NorFlash> BlockingFirmwareUpdater<'d, DFU, STATE>
#[cfg(feature = "ed25519-dalek")] #[cfg(feature = "ed25519-dalek")]
{ {
use ed25519_dalek::{PublicKey, Signature, SignatureError, Verifier}; use ed25519_dalek::{Signature, SignatureError, Verifier, VerifyingKey};
use crate::digest_adapters::ed25519_dalek::Sha512; use crate::digest_adapters::ed25519_dalek::Sha512;
let into_signature_error = |e: SignatureError| FirmwareUpdaterError::Signature(e.into()); let into_signature_error = |e: SignatureError| FirmwareUpdaterError::Signature(e.into());
let public_key = PublicKey::from_bytes(_public_key).map_err(into_signature_error)?; let public_key = VerifyingKey::from_bytes(_public_key).map_err(into_signature_error)?;
let signature = Signature::from_bytes(_signature).map_err(into_signature_error)?; let signature = Signature::from_bytes(_signature);
let mut message = [0; 64]; let mut message = [0; 64];
let mut chunk_buf = [0; 2]; let mut chunk_buf = [0; 2];
@ -113,7 +113,6 @@ impl<'d, DFU: NorFlash, STATE: NorFlash> BlockingFirmwareUpdater<'d, DFU, STATE>
} }
#[cfg(feature = "ed25519-salty")] #[cfg(feature = "ed25519-salty")]
{ {
use salty::constants::{PUBLICKEY_SERIALIZED_LENGTH, SIGNATURE_SERIALIZED_LENGTH};
use salty::{PublicKey, Signature}; use salty::{PublicKey, Signature};
use crate::digest_adapters::salty::Sha512; use crate::digest_adapters::salty::Sha512;
@ -122,10 +121,8 @@ impl<'d, DFU: NorFlash, STATE: NorFlash> BlockingFirmwareUpdater<'d, DFU, STATE>
FirmwareUpdaterError::Signature(signature::Error::default()) FirmwareUpdaterError::Signature(signature::Error::default())
} }
let public_key: [u8; PUBLICKEY_SERIALIZED_LENGTH] = _public_key.try_into().map_err(into_signature_error)?; let public_key = PublicKey::try_from(_public_key).map_err(into_signature_error)?;
let public_key = PublicKey::try_from(&public_key).map_err(into_signature_error)?; let signature = Signature::try_from(_signature).map_err(into_signature_error)?;
let signature: [u8; SIGNATURE_SERIALIZED_LENGTH] = _signature.try_into().map_err(into_signature_error)?;
let signature = Signature::try_from(&signature).map_err(into_signature_error)?;
let mut message = [0; 64]; let mut message = [0; 64];
let mut chunk_buf = [0; 2]; let mut chunk_buf = [0; 2];

View File

@ -275,21 +275,19 @@ mod tests {
// The following key setup is based on: // The following key setup is based on:
// https://docs.rs/ed25519-dalek/latest/ed25519_dalek/#example // https://docs.rs/ed25519-dalek/latest/ed25519_dalek/#example
use ed25519_dalek::Keypair; use ed25519_dalek::{Digest, Sha512, Signature, Signer, SigningKey, VerifyingKey};
use rand::rngs::OsRng; use rand::rngs::OsRng;
let mut csprng = OsRng {}; let mut csprng = OsRng {};
let keypair: Keypair = Keypair::generate(&mut csprng); let keypair = SigningKey::generate(&mut csprng);
use ed25519_dalek::{Digest, Sha512, Signature, Signer};
let firmware: &[u8] = b"This are bytes that would otherwise be firmware bytes for DFU."; let firmware: &[u8] = b"This are bytes that would otherwise be firmware bytes for DFU.";
let mut digest = Sha512::new(); let mut digest = Sha512::new();
digest.update(&firmware); digest.update(&firmware);
let message = digest.finalize(); let message = digest.finalize();
let signature: Signature = keypair.sign(&message); let signature: Signature = keypair.sign(&message);
use ed25519_dalek::PublicKey; let public_key = keypair.verifying_key();
let public_key: PublicKey = keypair.public;
// Setup flash // Setup flash
let flash = BlockingTestFlash::new(BootLoaderConfig { let flash = BlockingTestFlash::new(BootLoaderConfig {

View File

@ -6,8 +6,7 @@ keywords = ["embedded", "ADIN1110", "embassy-net", "embedded-hal-async", "ethern
categories = ["embedded", "hardware-support", "no-std", "network-programming", "async"] categories = ["embedded", "hardware-support", "no-std", "network-programming", "async"]
license = "MIT OR Apache-2.0" license = "MIT OR Apache-2.0"
edition = "2021" edition = "2021"
repository = "https://github.com/embassy-rs/embassy"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
heapless = "0.8" heapless = "0.8"

View File

@ -1,3 +1,4 @@
/// CRC32 lookup table.
pub const CRC32R_LOOKUP_TABLE: [u32; 256] = [ pub const CRC32R_LOOKUP_TABLE: [u32; 256] = [
0x0000_0000, 0x0000_0000,
0x7707_3096, 0x7707_3096,
@ -263,8 +264,9 @@ pub const CRC32R_LOOKUP_TABLE: [u32; 256] = [
pub struct ETH_FCS(pub u32); pub struct ETH_FCS(pub u32);
impl ETH_FCS { impl ETH_FCS {
pub const CRC32_OK: u32 = 0x2144_df1c; const CRC32_OK: u32 = 0x2144_df1c;
/// Create a new frame check sequence from `data`.
#[must_use] #[must_use]
pub fn new(data: &[u8]) -> Self { pub fn new(data: &[u8]) -> Self {
let fcs = data.iter().fold(u32::MAX, |crc, byte| { let fcs = data.iter().fold(u32::MAX, |crc, byte| {
@ -274,6 +276,7 @@ impl ETH_FCS {
Self(fcs) Self(fcs)
} }
/// Update the frame check sequence with `data`.
#[must_use] #[must_use]
pub fn update(self, data: &[u8]) -> Self { pub fn update(self, data: &[u8]) -> Self {
let fcs = data.iter().fold(self.0 ^ u32::MAX, |crc, byte| { let fcs = data.iter().fold(self.0 ^ u32::MAX, |crc, byte| {
@ -283,16 +286,19 @@ impl ETH_FCS {
Self(fcs) Self(fcs)
} }
/// Check if the frame check sequence is correct.
#[must_use] #[must_use]
pub fn crc_ok(&self) -> bool { pub fn crc_ok(&self) -> bool {
self.0 == Self::CRC32_OK self.0 == Self::CRC32_OK
} }
/// Switch byte order.
#[must_use] #[must_use]
pub fn hton_bytes(&self) -> [u8; 4] { pub fn hton_bytes(&self) -> [u8; 4] {
self.0.to_le_bytes() self.0.to_le_bytes()
} }
/// Switch byte order as a u32.
#[must_use] #[must_use]
pub fn hton(&self) -> u32 { pub fn hton(&self) -> u32 {
self.0.to_le() self.0.to_le()

View File

@ -5,6 +5,7 @@
#![allow(clippy::missing_errors_doc)] #![allow(clippy::missing_errors_doc)]
#![allow(clippy::missing_panics_doc)] #![allow(clippy::missing_panics_doc)]
#![doc = include_str!("../README.md")] #![doc = include_str!("../README.md")]
#![warn(missing_docs)]
// must go first! // must go first!
mod fmt; mod fmt;
@ -26,8 +27,9 @@ use embedded_hal_async::digital::Wait;
use embedded_hal_async::spi::{Error, Operation, SpiDevice}; use embedded_hal_async::spi::{Error, Operation, SpiDevice};
use heapless::Vec; use heapless::Vec;
pub use mdio::MdioBus; pub use mdio::MdioBus;
pub use phy::{Phy10BaseT1x, RegsC22, RegsC45}; pub use phy::Phy10BaseT1x;
pub use regs::{Config0, Config2, SpiRegisters as sr, Status0, Status1}; use phy::{RegsC22, RegsC45};
use regs::{Config0, Config2, SpiRegisters as sr, Status0, Status1};
use crate::fmt::Bytes; use crate::fmt::Bytes;
use crate::regs::{LedCntrl, LedFunc, LedPol, LedPolarity, SpiHeader}; use crate::regs::{LedCntrl, LedFunc, LedPol, LedPolarity, SpiHeader};
@ -446,6 +448,7 @@ pub struct Runner<'d, SPI, INT, RST> {
} }
impl<'d, SPI: SpiDevice, INT: Wait, RST: OutputPin> Runner<'d, SPI, INT, RST> { impl<'d, SPI: SpiDevice, INT: Wait, RST: OutputPin> Runner<'d, SPI, INT, RST> {
/// Run the driver.
#[allow(clippy::too_many_lines)] #[allow(clippy::too_many_lines)]
pub async fn run(mut self) -> ! { pub async fn run(mut self) -> ! {
loop { loop {

View File

@ -39,6 +39,7 @@ enum Reg13Op {
/// ///
/// Clause 45 methodes are bases on <https://www.ieee802.org/3/efm/public/nov02/oam/pannell_oam_1_1102.pdf> /// Clause 45 methodes are bases on <https://www.ieee802.org/3/efm/public/nov02/oam/pannell_oam_1_1102.pdf>
pub trait MdioBus { pub trait MdioBus {
/// Error type.
type Error; type Error;
/// Read, Clause 22 /// Read, Clause 22

View File

@ -2,6 +2,7 @@ use core::fmt::{Debug, Display};
use bitfield::{bitfield, bitfield_bitrange, bitfield_fields}; use bitfield::{bitfield, bitfield_bitrange, bitfield_fields};
#[allow(missing_docs)]
#[allow(non_camel_case_types)] #[allow(non_camel_case_types)]
#[derive(Debug, Copy, Clone)] #[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))] #[cfg_attr(feature = "defmt", derive(defmt::Format))]

View File

@ -1,5 +1,6 @@
#![no_std] #![no_std]
#![doc = include_str!("../README.md")] #![doc = include_str!("../README.md")]
#![warn(missing_docs)]
// must go first! // must go first!
mod fmt; mod fmt;
@ -15,6 +16,9 @@ use embassy_sync::blocking_mutex::Mutex;
use embassy_sync::waitqueue::WakerRegistration; use embassy_sync::waitqueue::WakerRegistration;
use embassy_sync::zerocopy_channel; use embassy_sync::zerocopy_channel;
/// Channel state.
///
/// Holds a buffer of packets with size MTU, for both TX and RX.
pub struct State<const MTU: usize, const N_RX: usize, const N_TX: usize> { pub struct State<const MTU: usize, const N_RX: usize, const N_TX: usize> {
rx: [PacketBuf<MTU>; N_RX], rx: [PacketBuf<MTU>; N_RX],
tx: [PacketBuf<MTU>; N_TX], tx: [PacketBuf<MTU>; N_TX],
@ -24,6 +28,7 @@ pub struct State<const MTU: usize, const N_RX: usize, const N_TX: usize> {
impl<const MTU: usize, const N_RX: usize, const N_TX: usize> State<MTU, N_RX, N_TX> { impl<const MTU: usize, const N_RX: usize, const N_TX: usize> State<MTU, N_RX, N_TX> {
const NEW_PACKET: PacketBuf<MTU> = PacketBuf::new(); const NEW_PACKET: PacketBuf<MTU> = PacketBuf::new();
/// Create a new channel state.
pub const fn new() -> Self { pub const fn new() -> Self {
Self { Self {
rx: [Self::NEW_PACKET; N_RX], rx: [Self::NEW_PACKET; N_RX],
@ -39,33 +44,45 @@ struct StateInner<'d, const MTU: usize> {
shared: Mutex<NoopRawMutex, RefCell<Shared>>, shared: Mutex<NoopRawMutex, RefCell<Shared>>,
} }
/// State of the LinkState
struct Shared { struct Shared {
link_state: LinkState, link_state: LinkState,
waker: WakerRegistration, waker: WakerRegistration,
hardware_address: driver::HardwareAddress, hardware_address: driver::HardwareAddress,
} }
/// Channel runner.
///
/// Holds the shared state and the lower end of channels for inbound and outbound packets.
pub struct Runner<'d, const MTU: usize> { pub struct Runner<'d, const MTU: usize> {
tx_chan: zerocopy_channel::Receiver<'d, NoopRawMutex, PacketBuf<MTU>>, tx_chan: zerocopy_channel::Receiver<'d, NoopRawMutex, PacketBuf<MTU>>,
rx_chan: zerocopy_channel::Sender<'d, NoopRawMutex, PacketBuf<MTU>>, rx_chan: zerocopy_channel::Sender<'d, NoopRawMutex, PacketBuf<MTU>>,
shared: &'d Mutex<NoopRawMutex, RefCell<Shared>>, shared: &'d Mutex<NoopRawMutex, RefCell<Shared>>,
} }
/// State runner.
///
/// Holds the shared state of the channel such as link state.
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub struct StateRunner<'d> { pub struct StateRunner<'d> {
shared: &'d Mutex<NoopRawMutex, RefCell<Shared>>, shared: &'d Mutex<NoopRawMutex, RefCell<Shared>>,
} }
/// RX runner.
///
/// Holds the lower end of the channel for passing inbound packets up the stack.
pub struct RxRunner<'d, const MTU: usize> { pub struct RxRunner<'d, const MTU: usize> {
rx_chan: zerocopy_channel::Sender<'d, NoopRawMutex, PacketBuf<MTU>>, rx_chan: zerocopy_channel::Sender<'d, NoopRawMutex, PacketBuf<MTU>>,
} }
/// TX runner.
///
/// Holds the lower end of the channel for passing outbound packets down the stack.
pub struct TxRunner<'d, const MTU: usize> { pub struct TxRunner<'d, const MTU: usize> {
tx_chan: zerocopy_channel::Receiver<'d, NoopRawMutex, PacketBuf<MTU>>, tx_chan: zerocopy_channel::Receiver<'d, NoopRawMutex, PacketBuf<MTU>>,
} }
impl<'d, const MTU: usize> Runner<'d, MTU> { impl<'d, const MTU: usize> Runner<'d, MTU> {
/// Split the runner into separate runners for controlling state, rx and tx.
pub fn split(self) -> (StateRunner<'d>, RxRunner<'d, MTU>, TxRunner<'d, MTU>) { pub fn split(self) -> (StateRunner<'d>, RxRunner<'d, MTU>, TxRunner<'d, MTU>) {
( (
StateRunner { shared: self.shared }, StateRunner { shared: self.shared },
@ -74,6 +91,7 @@ impl<'d, const MTU: usize> Runner<'d, MTU> {
) )
} }
/// Split the runner into separate runners for controlling state, rx and tx borrowing the underlying state.
pub fn borrow_split(&mut self) -> (StateRunner<'_>, RxRunner<'_, MTU>, TxRunner<'_, MTU>) { pub fn borrow_split(&mut self) -> (StateRunner<'_>, RxRunner<'_, MTU>, TxRunner<'_, MTU>) {
( (
StateRunner { shared: self.shared }, StateRunner { shared: self.shared },
@ -86,10 +104,12 @@ impl<'d, const MTU: usize> Runner<'d, MTU> {
) )
} }
/// Create a state runner sharing the state channel.
pub fn state_runner(&self) -> StateRunner<'d> { pub fn state_runner(&self) -> StateRunner<'d> {
StateRunner { shared: self.shared } StateRunner { shared: self.shared }
} }
/// Set the link state.
pub fn set_link_state(&mut self, state: LinkState) { pub fn set_link_state(&mut self, state: LinkState) {
self.shared.lock(|s| { self.shared.lock(|s| {
let s = &mut *s.borrow_mut(); let s = &mut *s.borrow_mut();
@ -98,6 +118,7 @@ impl<'d, const MTU: usize> Runner<'d, MTU> {
}); });
} }
/// Set the hardware address.
pub fn set_hardware_address(&mut self, address: driver::HardwareAddress) { pub fn set_hardware_address(&mut self, address: driver::HardwareAddress) {
self.shared.lock(|s| { self.shared.lock(|s| {
let s = &mut *s.borrow_mut(); let s = &mut *s.borrow_mut();
@ -106,16 +127,19 @@ impl<'d, const MTU: usize> Runner<'d, MTU> {
}); });
} }
/// Wait until there is space for more inbound packets and return a slice they can be copied into.
pub async fn rx_buf(&mut self) -> &mut [u8] { pub async fn rx_buf(&mut self) -> &mut [u8] {
let p = self.rx_chan.send().await; let p = self.rx_chan.send().await;
&mut p.buf &mut p.buf
} }
/// Check if there is space for more inbound packets right now.
pub fn try_rx_buf(&mut self) -> Option<&mut [u8]> { pub fn try_rx_buf(&mut self) -> Option<&mut [u8]> {
let p = self.rx_chan.try_send()?; let p = self.rx_chan.try_send()?;
Some(&mut p.buf) Some(&mut p.buf)
} }
/// Polling the inbound channel if there is space for packets.
pub fn poll_rx_buf(&mut self, cx: &mut Context) -> Poll<&mut [u8]> { pub fn poll_rx_buf(&mut self, cx: &mut Context) -> Poll<&mut [u8]> {
match self.rx_chan.poll_send(cx) { match self.rx_chan.poll_send(cx) {
Poll::Ready(p) => Poll::Ready(&mut p.buf), Poll::Ready(p) => Poll::Ready(&mut p.buf),
@ -123,22 +147,26 @@ impl<'d, const MTU: usize> Runner<'d, MTU> {
} }
} }
/// Mark packet of len bytes as pushed to the inbound channel.
pub fn rx_done(&mut self, len: usize) { pub fn rx_done(&mut self, len: usize) {
let p = self.rx_chan.try_send().unwrap(); let p = self.rx_chan.try_send().unwrap();
p.len = len; p.len = len;
self.rx_chan.send_done(); self.rx_chan.send_done();
} }
/// Wait until there is space for more outbound packets and return a slice they can be copied into.
pub async fn tx_buf(&mut self) -> &mut [u8] { pub async fn tx_buf(&mut self) -> &mut [u8] {
let p = self.tx_chan.receive().await; let p = self.tx_chan.receive().await;
&mut p.buf[..p.len] &mut p.buf[..p.len]
} }
/// Check if there is space for more outbound packets right now.
pub fn try_tx_buf(&mut self) -> Option<&mut [u8]> { pub fn try_tx_buf(&mut self) -> Option<&mut [u8]> {
let p = self.tx_chan.try_receive()?; let p = self.tx_chan.try_receive()?;
Some(&mut p.buf[..p.len]) Some(&mut p.buf[..p.len])
} }
/// Polling the outbound channel if there is space for packets.
pub fn poll_tx_buf(&mut self, cx: &mut Context) -> Poll<&mut [u8]> { pub fn poll_tx_buf(&mut self, cx: &mut Context) -> Poll<&mut [u8]> {
match self.tx_chan.poll_receive(cx) { match self.tx_chan.poll_receive(cx) {
Poll::Ready(p) => Poll::Ready(&mut p.buf[..p.len]), Poll::Ready(p) => Poll::Ready(&mut p.buf[..p.len]),
@ -146,12 +174,14 @@ impl<'d, const MTU: usize> Runner<'d, MTU> {
} }
} }
/// Mark outbound packet as copied.
pub fn tx_done(&mut self) { pub fn tx_done(&mut self) {
self.tx_chan.receive_done(); self.tx_chan.receive_done();
} }
} }
impl<'d> StateRunner<'d> { impl<'d> StateRunner<'d> {
/// Set link state.
pub fn set_link_state(&self, state: LinkState) { pub fn set_link_state(&self, state: LinkState) {
self.shared.lock(|s| { self.shared.lock(|s| {
let s = &mut *s.borrow_mut(); let s = &mut *s.borrow_mut();
@ -160,6 +190,7 @@ impl<'d> StateRunner<'d> {
}); });
} }
/// Set the hardware address.
pub fn set_hardware_address(&self, address: driver::HardwareAddress) { pub fn set_hardware_address(&self, address: driver::HardwareAddress) {
self.shared.lock(|s| { self.shared.lock(|s| {
let s = &mut *s.borrow_mut(); let s = &mut *s.borrow_mut();
@ -170,16 +201,19 @@ impl<'d> StateRunner<'d> {
} }
impl<'d, const MTU: usize> RxRunner<'d, MTU> { impl<'d, const MTU: usize> RxRunner<'d, MTU> {
/// Wait until there is space for more inbound packets and return a slice they can be copied into.
pub async fn rx_buf(&mut self) -> &mut [u8] { pub async fn rx_buf(&mut self) -> &mut [u8] {
let p = self.rx_chan.send().await; let p = self.rx_chan.send().await;
&mut p.buf &mut p.buf
} }
/// Check if there is space for more inbound packets right now.
pub fn try_rx_buf(&mut self) -> Option<&mut [u8]> { pub fn try_rx_buf(&mut self) -> Option<&mut [u8]> {
let p = self.rx_chan.try_send()?; let p = self.rx_chan.try_send()?;
Some(&mut p.buf) Some(&mut p.buf)
} }
/// Polling the inbound channel if there is space for packets.
pub fn poll_rx_buf(&mut self, cx: &mut Context) -> Poll<&mut [u8]> { pub fn poll_rx_buf(&mut self, cx: &mut Context) -> Poll<&mut [u8]> {
match self.rx_chan.poll_send(cx) { match self.rx_chan.poll_send(cx) {
Poll::Ready(p) => Poll::Ready(&mut p.buf), Poll::Ready(p) => Poll::Ready(&mut p.buf),
@ -187,6 +221,7 @@ impl<'d, const MTU: usize> RxRunner<'d, MTU> {
} }
} }
/// Mark packet of len bytes as pushed to the inbound channel.
pub fn rx_done(&mut self, len: usize) { pub fn rx_done(&mut self, len: usize) {
let p = self.rx_chan.try_send().unwrap(); let p = self.rx_chan.try_send().unwrap();
p.len = len; p.len = len;
@ -195,16 +230,19 @@ impl<'d, const MTU: usize> RxRunner<'d, MTU> {
} }
impl<'d, const MTU: usize> TxRunner<'d, MTU> { impl<'d, const MTU: usize> TxRunner<'d, MTU> {
/// Wait until there is space for more outbound packets and return a slice they can be copied into.
pub async fn tx_buf(&mut self) -> &mut [u8] { pub async fn tx_buf(&mut self) -> &mut [u8] {
let p = self.tx_chan.receive().await; let p = self.tx_chan.receive().await;
&mut p.buf[..p.len] &mut p.buf[..p.len]
} }
/// Check if there is space for more outbound packets right now.
pub fn try_tx_buf(&mut self) -> Option<&mut [u8]> { pub fn try_tx_buf(&mut self) -> Option<&mut [u8]> {
let p = self.tx_chan.try_receive()?; let p = self.tx_chan.try_receive()?;
Some(&mut p.buf[..p.len]) Some(&mut p.buf[..p.len])
} }
/// Polling the outbound channel if there is space for packets.
pub fn poll_tx_buf(&mut self, cx: &mut Context) -> Poll<&mut [u8]> { pub fn poll_tx_buf(&mut self, cx: &mut Context) -> Poll<&mut [u8]> {
match self.tx_chan.poll_receive(cx) { match self.tx_chan.poll_receive(cx) {
Poll::Ready(p) => Poll::Ready(&mut p.buf[..p.len]), Poll::Ready(p) => Poll::Ready(&mut p.buf[..p.len]),
@ -212,11 +250,18 @@ impl<'d, const MTU: usize> TxRunner<'d, MTU> {
} }
} }
/// Mark outbound packet as copied.
pub fn tx_done(&mut self) { pub fn tx_done(&mut self) {
self.tx_chan.receive_done(); self.tx_chan.receive_done();
} }
} }
/// Create a channel.
///
/// Returns a pair of handles for interfacing with the peripheral and the networking stack.
///
/// The runner is interfacing with the peripheral at the lower part of the stack.
/// The device is interfacing with the networking stack on the layer above.
pub fn new<'d, const MTU: usize, const N_RX: usize, const N_TX: usize>( pub fn new<'d, const MTU: usize, const N_RX: usize, const N_TX: usize>(
state: &'d mut State<MTU, N_RX, N_TX>, state: &'d mut State<MTU, N_RX, N_TX>,
hardware_address: driver::HardwareAddress, hardware_address: driver::HardwareAddress,
@ -257,17 +302,22 @@ pub fn new<'d, const MTU: usize, const N_RX: usize, const N_TX: usize>(
) )
} }
/// Represents a packet of size MTU.
pub struct PacketBuf<const MTU: usize> { pub struct PacketBuf<const MTU: usize> {
len: usize, len: usize,
buf: [u8; MTU], buf: [u8; MTU],
} }
impl<const MTU: usize> PacketBuf<MTU> { impl<const MTU: usize> PacketBuf<MTU> {
/// Create a new packet buffer.
pub const fn new() -> Self { pub const fn new() -> Self {
Self { len: 0, buf: [0; MTU] } Self { len: 0, buf: [0; MTU] }
} }
} }
/// Channel device.
///
/// Holds the shared state and upper end of channels for inbound and outbound packets.
pub struct Device<'d, const MTU: usize> { pub struct Device<'d, const MTU: usize> {
rx: zerocopy_channel::Receiver<'d, NoopRawMutex, PacketBuf<MTU>>, rx: zerocopy_channel::Receiver<'d, NoopRawMutex, PacketBuf<MTU>>,
tx: zerocopy_channel::Sender<'d, NoopRawMutex, PacketBuf<MTU>>, tx: zerocopy_channel::Sender<'d, NoopRawMutex, PacketBuf<MTU>>,
@ -314,6 +364,9 @@ impl<'d, const MTU: usize> embassy_net_driver::Driver for Device<'d, MTU> {
} }
} }
/// A rx token.
///
/// Holds inbound receive channel and interfaces with embassy-net-driver.
pub struct RxToken<'a, const MTU: usize> { pub struct RxToken<'a, const MTU: usize> {
rx: zerocopy_channel::Receiver<'a, NoopRawMutex, PacketBuf<MTU>>, rx: zerocopy_channel::Receiver<'a, NoopRawMutex, PacketBuf<MTU>>,
} }
@ -331,6 +384,9 @@ impl<'a, const MTU: usize> embassy_net_driver::RxToken for RxToken<'a, MTU> {
} }
} }
/// A tx token.
///
/// Holds outbound transmit channel and interfaces with embassy-net-driver.
pub struct TxToken<'a, const MTU: usize> { pub struct TxToken<'a, const MTU: usize> {
tx: zerocopy_channel::Sender<'a, NoopRawMutex, PacketBuf<MTU>>, tx: zerocopy_channel::Sender<'a, NoopRawMutex, PacketBuf<MTU>>,
} }

View File

@ -130,7 +130,7 @@ impl RtcTimeProvider {
let weekday = day_of_week_from_u8(dr.wdu()).map_err(RtcError::InvalidDateTime)?; let weekday = day_of_week_from_u8(dr.wdu()).map_err(RtcError::InvalidDateTime)?;
let day = bcd2_to_byte((dr.dt(), dr.du())); let day = bcd2_to_byte((dr.dt(), dr.du()));
let month = bcd2_to_byte((dr.mt() as u8, dr.mu())); let month = bcd2_to_byte((dr.mt() as u8, dr.mu()));
let year = bcd2_to_byte((dr.yt(), dr.yu())) as u16 + 1970_u16; let year = bcd2_to_byte((dr.yt(), dr.yu())) as u16 + 2000_u16;
DateTime::from(year, month, day, weekday, hour, minute, second).map_err(RtcError::InvalidDateTime) DateTime::from(year, month, day, weekday, hour, minute, second).map_err(RtcError::InvalidDateTime)
}) })
@ -261,7 +261,7 @@ impl Rtc {
let (dt, du) = byte_to_bcd2(t.day() as u8); let (dt, du) = byte_to_bcd2(t.day() as u8);
let (mt, mu) = byte_to_bcd2(t.month() as u8); let (mt, mu) = byte_to_bcd2(t.month() as u8);
let yr = t.year() as u16; let yr = t.year() as u16;
let yr_offset = (yr - 1970_u16) as u8; let yr_offset = (yr - 2000_u16) as u8;
let (yt, yu) = byte_to_bcd2(yr_offset); let (yt, yu) = byte_to_bcd2(yr_offset);
use crate::pac::rtc::vals::Ampm; use crate::pac::rtc::vals::Ampm;