Skip to main content

ch32_hal/eth/v1/
smi.rs

1#[cfg(emac)]
2use crate::pac::emac::Eth as EthRegs;
3#[cfg(not(emac))]
4use crate::pac::eth::Eth as EthRegs;
5
6// ============================================================================
7// PHY management via SMI (Station Management Interface)
8// ============================================================================
9
10// Bound register polling without requiring an Embassy time driver. This is a
11// polling budget, not a wall-clock deadline.
12const BUSY_POLL_LIMIT: usize = 10_000;
13
14/// An error during a PHY management transaction.
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum SmiError {
17    /// The MAC management interface did not become idle, or the PHY did not
18    /// leave reset, within the polling budget.
19    Timeout,
20}
21
22/// Station Management Interface for MII PHY register access.
23pub struct Smi {
24    regs: EthRegs,
25    clock_range: u8,
26}
27
28impl Smi {
29    pub(super) fn new(regs: EthRegs, clock_range: u8) -> Self {
30        Self { clock_range, regs }
31    }
32
33    fn wait_until_idle(&self) -> Result<(), SmiError> {
34        for _ in 0..BUSY_POLL_LIMIT {
35            if !self.regs.macmiiar().read().mb() {
36                return Ok(());
37            }
38        }
39        Err(SmiError::Timeout)
40    }
41
42    /// Read a PHY register.
43    ///
44    /// Returns [`SmiError::Timeout`] if the management interface remains busy.
45    pub fn read(&mut self, phy_addr: u8, reg: u8) -> Result<u16, SmiError> {
46        self.wait_until_idle()?;
47        self.regs.macmiiar().write(|w| {
48            w.set_pa(phy_addr & 0x1F);
49            w.set_mr(reg & 0x1F);
50            w.set_cr(self.clock_range);
51            w.set_mw(false);
52            w.set_mb(true);
53        });
54        self.wait_until_idle()?;
55        Ok(self.regs.macmiidr().read().md())
56    }
57
58    /// Write a PHY register.
59    ///
60    /// Returns [`SmiError::Timeout`] if the management interface remains busy.
61    pub fn write(&mut self, phy_addr: u8, reg: u8, val: u16) -> Result<(), SmiError> {
62        self.wait_until_idle()?;
63        self.regs.macmiidr().write(|w| w.set_md(val));
64        self.regs.macmiiar().write(|w| {
65            w.set_pa(phy_addr & 0x1F);
66            w.set_mr(reg & 0x1F);
67            w.set_cr(self.clock_range);
68            w.set_mw(true);
69            w.set_mb(true);
70        });
71        self.wait_until_idle()
72    }
73}