diff --git a/embassy-net-adin1110/.gitignore b/embassy-net-adin1110/.gitignore new file mode 100644 index 00000000..c41cc9e3 --- /dev/null +++ b/embassy-net-adin1110/.gitignore @@ -0,0 +1 @@ +/target \ No newline at end of file diff --git a/embassy-net-adin1110/.vscode/settings.json b/embassy-net-adin1110/.vscode/settings.json new file mode 100644 index 00000000..daa2ccf0 --- /dev/null +++ b/embassy-net-adin1110/.vscode/settings.json @@ -0,0 +1,8 @@ +{ + "rust-analyzer.check.command": "clippy", + "rust-analyzer.showUnlinkedFileNotification": false, + "[rust]": { + "editor.defaultFormatter": "rust-lang.rust-analyzer", + "editor.formatOnSave": true + } +} \ No newline at end of file diff --git a/embassy-net-adin1110/Cargo.toml b/embassy-net-adin1110/Cargo.toml new file mode 100644 index 00000000..e74fb7cd --- /dev/null +++ b/embassy-net-adin1110/Cargo.toml @@ -0,0 +1,41 @@ +[package] +name = "embassy-net-adin1110" +version = "0.1.0" +description = "embassy-net driver for the ADIN1110 ethernet chip" +keywords = ["embedded", "ADIN1110", "embassy-net", "embedded-hal-async", "ethernet", "async"] +categories = ["embedded", "hardware-support", "no-std", "network-programming", "async"] +license = "MIT OR Apache-2.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +heapless = "0.7.16" +defmt = { version = "0.3", optional = true } +log = { version = "0.4.4", default-features = false, optional = true } +embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.1" } +embedded-hal-async = { version = "=1.0.0-rc.1" } +embedded-hal-bus = { version = "=0.1.0-rc.1", features = ["async"] } +embassy-net-driver-channel = { version = "0.1.0", path = "../embassy-net-driver-channel" } +embassy-time = { version = "0.1.0" } +embassy-futures = { version = "0.1.0", path = "../embassy-futures" } +bitfield = "0.14.0" + + +[dev-dependencies] +# reenable when https://github.com/dbrgn/embedded-hal-mock/pull/86 is merged. +#embedded-hal-mock = { git = "https://github.com/dbrgn/embedded-hal-mock", branch = "1-alpha", features = ["embedded-hal-async", "eh1"] }] } +embedded-hal-mock = { git = "https://github.com/newAM/embedded-hal-mock", branch = "eh1-rc.1", features = ["embedded-hal-async", "eh1"] } +crc = "3.0.1" +env_logger = "0.10" +critical-section = { version = "1.1.1", features = ["std"] } +futures-test = "0.3.17" + +[features] +default = [ ] +defmt = [ "dep:defmt" ] + +[package.metadata.embassy_docs] +src_base = "https://github.com/embassy-rs/embassy/blob/embassy-net-adin1110-v$VERSION/embassy-net-adin1110/src/" +src_base_git = "https://github.com/embassy-rs/embassy/blob/$COMMIT/embassy-net-adin1110/src/" +target = "thumbv7em-none-eabi" diff --git a/embassy-net-adin1110/README.md b/embassy-net-adin1110/README.md new file mode 100644 index 00000000..9b7b4e0e --- /dev/null +++ b/embassy-net-adin1110/README.md @@ -0,0 +1,55 @@ +# SPE ADIN1110 `embassy-net` integration + +[`embassy-net`](https://crates.io/crates/embassy-net) integration for the `Analog ADIN1110` SPI SPE ethernet chips. + +## What is SPE or Single Pair Ethernet / 10 BASE-T1L + +SPE is Single Pair Ethernet, what the names implies, it uses a single twisted/differancial pair (only 2 wires) to transmit ethernet packet in full-duplex. +SPE is still ethernet, only the phissical layer is different. + +SPE also supports [`PoDL(Power over Data Line)`](https://www.ti.com/lit/an/snla395/snla395.pdf), power delivery from 0.5 up to 50 Watts, similair to [`PoE`](https://en.wikipedia.org/wiki/Power_over_Ethernet), but additional hardware and handshake protocol is needed. + +SPE has many link speeds but only `10 BASE-T1L` is able to reach cable length up to 1000 meters in `2.4 Vpp` transmit amplitude. +Currently in 2023, none of the standards are compatiable with eachother. +So `10 BASE-T1L` don't work with a `10 BASE-T1S` or `100 BASE-T1`. + +In the industry SPE is also called [`APL(Advanced Physical Layer)`](https://www.ethernet-apl.org), it is based on the `10 BASE-T1L` standard. + +APL can be use in [`intrinsic safety applications/explosion hazardous areas`](https://en.wikipedia.org/wiki/Electrical_equipment_in_hazardous_areas) which has it's own name and standard [`2-WISE(2-wire intrinsically safe ethernet) IEC TS 60079-47:2021`](https://webstore.iec.ch/publication/64292). + +`10 BASE-T1L` and `ADIN1110` are designed to support intrinsic safety applications. The power supply energy is fixed and PDoL is not supported. + +## Supported SPI modes + +`ADIN1110` supports two SPI modes. `Generic` and [`OPEN Alliance 10BASE-T1x MAC-PHY serial interface`](https://opensig.org/download/document/OPEN_Alliance_10BASET1x_MAC-PHY_Serial_Interface_V1.1.pdf) + +Both modes support with and without additional CRC. +Currently only `Generic` SPI with or without CRC is supported. + +*NOTE:* SPI Mode is selected by the hardware pins `SPI_CFG0` and `SPI_CFG1`. Software can't detect nor change the mode. + +## Hardware + +- Testen on [`Analog Devices EVAL-ADIN1110EBZ`](https://www.analog.com/en/design-center/evaluation-hardware-and-software/evaluation-boards-kits/eval-adin1110.html) with a `STM32L4S5QII3P`, see [`spe_adin1110_http_server`](../examples/stm32l4/src/bin/spe_adin1110_http_server.rs) example. +- [`SparkFun MicroMod Single Pair Ethernet Function Board`](https://www.sparkfun.com/products/19038) or [`SparkFun MicroMod Single Pair Ethernet Kit`](https://www.sparkfun.com/products/19628), the kit supports multiple microcontrollers, please check if get the right microcontroller that is supported by Embassy! + +## Other SPE chips + +* [`Analog ADIN2111`](https://www.analog.com/en/products/adin2111.html) 2 Port SPI version. Can work with this driver. +* [`Analog ADIN1100`](https://www.analog.com/en/products/adin1100.html) RGMII version. + +## Testing + +ADIN1110 library can tested on the host with a mock SPI driver + +$ `cargo test --target x86_64-unknown-linux-gnu` + +## License + +This work is licensed under either of + +- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or + http://www.apache.org/licenses/LICENSE-2.0) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. diff --git a/embassy-net-adin1110/rust-toolchain.toml b/embassy-net-adin1110/rust-toolchain.toml new file mode 100644 index 00000000..d5f51a7f --- /dev/null +++ b/embassy-net-adin1110/rust-toolchain.toml @@ -0,0 +1,3 @@ +[toolchain] +channel = "nightly" +components = [ "rustfmt", "rustc-dev" ] diff --git a/embassy-net-adin1110/src/crc32.rs b/embassy-net-adin1110/src/crc32.rs new file mode 100644 index 00000000..75a7d65b --- /dev/null +++ b/embassy-net-adin1110/src/crc32.rs @@ -0,0 +1,101 @@ +pub const CRC32R_LOOKUP_TABLE: [u32; 256] = [ + 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, + 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, + 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, + 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, + 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, + 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, + 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, + 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, + 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, + 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, + 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, + 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, + 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, + 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, + 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, + 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, + 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, + 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, + 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, + 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, + 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, + 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, + 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, + 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, + 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, + 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, + 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, + 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, + 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D, +]; + +#[allow(non_camel_case_types)] +#[derive(Debug)] +pub struct ETH_FSC(pub u32); + +impl ETH_FSC { + pub const CRC32_OK: u32 = 0x2144df1c; + + pub fn new(data: &[u8]) -> Self { + let fsc = data.iter().fold(u32::MAX, |crc, byte| { + let idx = u8::try_from(crc & 0xFF).unwrap() ^ byte; + CRC32R_LOOKUP_TABLE[usize::from(idx)] ^ (crc >> 8) + }) ^ u32::MAX; + Self(fsc) + } + + pub fn crc_ok(&self) -> bool { + self.0 == Self::CRC32_OK + } + + pub fn hton_bytes(&self) -> [u8; 4] { + self.0.to_le_bytes() + } + + pub fn hton(&self) -> u32 { + self.0.to_le() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn crc32_ethernet_frame() { + let packet_a = &[ + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0xe0, 0x4c, 0x68, 0xee, 0xee, 0xff, 0x06, 0x00, 0x01, 0x08, 0x00, + 0x06, 0x04, 0x00, 0x01, 0x00, 0xe0, 0x4c, 0x68, 0x0e, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0xc0, 0xa8, 0x10, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf2, 0x65, 0x90, 0x3d, + ]; + + let packet_b = &[ + 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0x00, 0xe0, 0x4c, 0x68, 0xee, 0xee, 0xdd, 0x06, 0x00, 0x01, 0x08, 0x00, + 0x06, 0x04, 0x00, 0x02, 0x00, 0xe0, 0x4c, 0x68, 0x09, 0xde, 0xc0, 0xa8, 0x01, 0x02, 0x12, 0x34, 0x56, 0x78, + 0x9a, 0xbc, 0xc0, 0xa8, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x21, 0x3d, 0x67, 0x7c, + ]; + + // Packet A + let own_crc = ETH_FSC::new(&packet_a[0..60]); + let crc_bytes = own_crc.hton_bytes(); + println!("{:08x} {:02x?}", own_crc.0, crc_bytes); + assert_eq!(&crc_bytes, &packet_a[60..64]); + + let own_crc = ETH_FSC::new(packet_a); + println!("{:08x}", own_crc.0); + assert_eq!(own_crc.0, ETH_FSC::CRC32_OK); + + // Packet B + let own_crc = ETH_FSC::new(&packet_b[0..60]); + let crc_bytes = own_crc.hton_bytes(); + println!("{:08x} {:02x?}", own_crc.0, crc_bytes); + assert_eq!(&crc_bytes, &packet_b[60..64]); + + let own_crc = ETH_FSC::new(packet_b); + println!("{:08x}", own_crc.0); + assert_eq!(own_crc.0, ETH_FSC::CRC32_OK); + } +} diff --git a/embassy-net-adin1110/src/crc8.rs b/embassy-net-adin1110/src/crc8.rs new file mode 100644 index 00000000..7d20a740 --- /dev/null +++ b/embassy-net-adin1110/src/crc8.rs @@ -0,0 +1,53 @@ +/// CRC-8/ITU +const CRC8X_TABLE: [u8; 256] = [ + 0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15, 0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d, 0x70, 0x77, 0x7e, + 0x79, 0x6c, 0x6b, 0x62, 0x65, 0x48, 0x4f, 0x46, 0x41, 0x54, 0x53, 0x5a, 0x5d, 0xe0, 0xe7, 0xee, 0xe9, 0xfc, 0xfb, + 0xf2, 0xf5, 0xd8, 0xdf, 0xd6, 0xd1, 0xc4, 0xc3, 0xca, 0xcd, 0x90, 0x97, 0x9e, 0x99, 0x8c, 0x8b, 0x82, 0x85, 0xa8, + 0xaf, 0xa6, 0xa1, 0xb4, 0xb3, 0xba, 0xbd, 0xc7, 0xc0, 0xc9, 0xce, 0xdb, 0xdc, 0xd5, 0xd2, 0xff, 0xf8, 0xf1, 0xf6, + 0xe3, 0xe4, 0xed, 0xea, 0xb7, 0xb0, 0xb9, 0xbe, 0xab, 0xac, 0xa5, 0xa2, 0x8f, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9d, + 0x9a, 0x27, 0x20, 0x29, 0x2e, 0x3b, 0x3c, 0x35, 0x32, 0x1f, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0d, 0x0a, 0x57, 0x50, + 0x59, 0x5e, 0x4b, 0x4c, 0x45, 0x42, 0x6f, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7d, 0x7a, 0x89, 0x8e, 0x87, 0x80, 0x95, + 0x92, 0x9b, 0x9c, 0xb1, 0xb6, 0xbf, 0xb8, 0xad, 0xaa, 0xa3, 0xa4, 0xf9, 0xfe, 0xf7, 0xf0, 0xe5, 0xe2, 0xeb, 0xec, + 0xc1, 0xc6, 0xcf, 0xc8, 0xdd, 0xda, 0xd3, 0xd4, 0x69, 0x6e, 0x67, 0x60, 0x75, 0x72, 0x7b, 0x7c, 0x51, 0x56, 0x5f, + 0x58, 0x4d, 0x4a, 0x43, 0x44, 0x19, 0x1e, 0x17, 0x10, 0x05, 0x02, 0x0b, 0x0c, 0x21, 0x26, 0x2f, 0x28, 0x3d, 0x3a, + 0x33, 0x34, 0x4e, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5c, 0x5b, 0x76, 0x71, 0x78, 0x7f, 0x6a, 0x6d, 0x64, 0x63, 0x3e, + 0x39, 0x30, 0x37, 0x22, 0x25, 0x2c, 0x2b, 0x06, 0x01, 0x08, 0x0f, 0x1a, 0x1d, 0x14, 0x13, 0xae, 0xa9, 0xa0, 0xa7, + 0xb2, 0xb5, 0xbc, 0xbb, 0x96, 0x91, 0x98, 0x9f, 0x8a, 0x8d, 0x84, 0x83, 0xde, 0xd9, 0xd0, 0xd7, 0xc2, 0xc5, 0xcc, + 0xcb, 0xe6, 0xe1, 0xe8, 0xef, 0xfa, 0xfd, 0xf4, 0xf3, +]; + +/// Calculate the crc of a pease of data. +pub fn crc8(data: &[u8]) -> u8 { + data.iter().fold(0, |crc, &byte| CRC8X_TABLE[usize::from(byte ^ crc)]) +} + +#[cfg(test)] +mod tests { + use ::crc::{Crc, CRC_8_SMBUS}; + + use super::crc8; + + #[test] + fn spi_header_crc8() { + let data = &[0x80, 0x00]; + + let c = Crc::::new(&CRC_8_SMBUS); + let mut dig = c.digest(); + dig.update(data); + let sw_crc = dig.finalize(); + + let own_crc = crc8(data); + + assert_eq!(own_crc, sw_crc); + assert_eq!(own_crc, 182); + + let data = &[0x80, 0x01]; + let mut dig = c.digest(); + dig.update(data); + let sw_crc = dig.finalize(); + let own_crc = crc8(data); + + assert_eq!(own_crc, sw_crc); + assert_eq!(own_crc, 177); + } +} diff --git a/embassy-net-adin1110/src/lib.rs b/embassy-net-adin1110/src/lib.rs new file mode 100644 index 00000000..a4010d25 --- /dev/null +++ b/embassy-net-adin1110/src/lib.rs @@ -0,0 +1,1246 @@ +#![allow(clippy::pedantic)] +#![feature(type_alias_impl_trait)] +#![feature(async_fn_in_trait)] +#![cfg_attr(not(any(test, feature = "std")), no_std)] + +use ch::driver::LinkState; +use embassy_futures::select::{select, Either}; +use embassy_net_driver_channel as ch; +use embassy_time::{Duration, Timer}; +use embedded_hal_1::digital::OutputPin; +use embedded_hal_async::digital::Wait; +use embedded_hal_async::spi::{Operation, SpiDevice}; +use heapless::Vec; + +mod crc32; +mod crc8; +mod mdio; +mod phy; +mod regs; + +pub use crc32::ETH_FSC; +use crc8::crc8; +pub use mdio::MdioBus; +pub use phy::{Phy10BaseT1x, RegsC22, RegsC45}; +pub use regs::{Config0, Config2, SpiRegisters as sr, Status0, Status1}; + +use crate::regs::{LedCntrl, LedFunc, LedPol, LedPolarity, SpiHeader}; + +pub const PHYID: u32 = 0x0283BC91; + +/// Error values ADIN1110 +#[derive(Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[allow(non_camel_case_types)] +pub enum AdinError { + Spi(E), + SENDERROR, + READERROR, + CRC, + PACKET_TOO_BIG, + PACKET_TOO_SMALL, + MDIO_ACC_TIMEOUT, +} + +pub type AEResult = core::result::Result>; +pub const MDIO_PHY_ADDR: u8 = 0x01; +pub const MTU: usize = 1500; +/// Max SPI/Frame buffer size +pub const MAX_BUFF: usize = 2048; + +const DONT_CARE_BYTE: u8 = 0x00; +const TURN_AROUND_BYTE: u8 = 0x00; + +const FEC_LEN: usize = 4; +const FRAME_HEADER_LEN: usize = 2; +const WR_HEADER_LEN: usize = 2; + +// P1 = 0x00, P2 = 0x01 +const PORT_ID_BYTE: u8 = 0x00; + +pub type Packet = Vec; + +/// Type alias for the embassy-net driver for ADIN1110 +pub type Device<'d> = embassy_net_driver_channel::Device<'d, MTU>; + +/// Internal state for the embassy-net integration. +pub struct State { + ch_state: ch::State, +} +impl State { + /// Create a new `State`. + pub const fn new() -> Self { + Self { + ch_state: ch::State::new(), + } + } +} + +#[derive(Debug)] +pub struct ADIN1110 { + /// SPI bus + spi: SPI, + /// Enable CRC on SPI transfer. + /// This must match with the hardware pin SPI_CFG0 were 0 = CRC enable, 1 CRC disabled. + crc: bool, +} + +// Round size up the N u32; +pub(crate) fn size_align_u32(size: u32) -> u32 { + (size + 3) & 0xFFFF_FFFC +} + +impl ADIN1110 +where + SPI: SpiDevice, + SpiE: core::fmt::Debug, +{ + pub fn new(spi: SPI, crc: bool) -> Self { + Self { spi, crc } + } + + pub async fn read_reg(&mut self, reg: sr) -> AEResult { + let mut tx_buf = Vec::::new(); + + let mut spi_hdr = SpiHeader(0); + spi_hdr.set_control(true); + spi_hdr.set_addr(reg); + let _ = tx_buf.extend_from_slice(spi_hdr.0.to_be_bytes().as_slice()); + + if self.crc { + // Add CRC for header data + let _ = tx_buf.push(crc8(&tx_buf)); + } + + // Turn around byte, TODO: Unknown that this is. + let _ = tx_buf.push(TURN_AROUND_BYTE); + + let mut rx_buf = [0; 5]; + + let spi_read_len = if self.crc { rx_buf.len() } else { rx_buf.len() - 1 }; + + let mut spi_op = [Operation::Write(&tx_buf), Operation::Read(&mut rx_buf[0..spi_read_len])]; + + self.spi.transaction(&mut spi_op).await.map_err(AdinError::Spi)?; + + if self.crc { + let crc = crc8(&rx_buf[0..4]); + if crc != rx_buf[4] { + return Err(AdinError::CRC); + } + } + + let value = u32::from_be_bytes(rx_buf[0..4].try_into().unwrap()); + + #[cfg(feature = "defmt")] + defmt::trace!("REG Read {} = {:08x} SPI {:02x}", reg, value, &tx_buf); + + Ok(value) + } + + pub async fn write_reg(&mut self, reg: sr, value: u32) -> AEResult<(), SpiE> { + let mut tx_buf = Vec::::new(); + + let mut spi_hdr = SpiHeader(0); + spi_hdr.set_control(true); + spi_hdr.set_write(true); + spi_hdr.set_addr(reg); + let _ = tx_buf.extend_from_slice(spi_hdr.0.to_be_bytes().as_slice()); + + if self.crc { + // Add CRC for header data + let _ = tx_buf.push(crc8(&tx_buf)); + } + + let val = value.to_be_bytes(); + let _ = tx_buf.extend_from_slice(val.as_slice()); + + if self.crc { + // Add CRC for header data + let _ = tx_buf.push(crc8(val.as_slice())); + } + + #[cfg(feature = "defmt")] + defmt::trace!("REG Write {} = {:08x} SPI {:02x}", reg, value, &tx_buf); + + self.spi.write(&tx_buf).await.map_err(AdinError::Spi) + } + + // helper function for write to MDIO_ACC register and wait for ready! + async fn write_mdio_acc_reg(&mut self, mdio_acc_val: u32) -> AEResult { + self.write_reg(sr::MDIO_ACC, mdio_acc_val).await?; + + // TODO: Add proper timeout! + for _ in 0..100_000 { + let val = self.read_reg(sr::MDIO_ACC).await?; + if val & 0x8000_0000 != 0 { + return Ok(val); + } + } + + Err(AdinError::MDIO_ACC_TIMEOUT) + } + + pub async fn read_fifo(&mut self, packet: &mut [u8]) -> AEResult { + let mut tx_buf = Vec::::new(); + + // Size of the frame, also includes the appednded header. + let packet_size = self.read_reg(sr::RX_FSIZE).await?; + + // Packet read of write to the MAC packet buffer must be a multipul of 4! + let read_size = size_align_u32(packet_size); + + if packet_size < u32::try_from(FRAME_HEADER_LEN + FEC_LEN).unwrap() + || read_size > u32::try_from(packet.len()).unwrap() + { + return Err(AdinError::PACKET_TOO_BIG); + } + + let mut spi_hdr = SpiHeader(0); + spi_hdr.set_control(true); + spi_hdr.set_addr(sr::RX); + let _ = tx_buf.extend_from_slice(spi_hdr.0.to_be_bytes().as_slice()); + + if self.crc { + // Add CRC for header data + let _ = tx_buf.push(crc8(&tx_buf)); + } + + // Turn around byte, TODO: Unknown that this is. + let _ = tx_buf.push(TURN_AROUND_BYTE); + + let spi_packet = &mut packet[0..read_size as usize]; + + assert_eq!(spi_packet.len() & 0x03, 0x00); + + let mut pkt_header = [0, 0]; + + let mut spi_op = [ + Operation::Write(&tx_buf), + Operation::Read(&mut pkt_header), + Operation::Read(spi_packet), + ]; + + self.spi.transaction(&mut spi_op).await.map_err(AdinError::Spi)?; + + Ok(packet_size as usize) + } + + pub async fn write_fifo(&mut self, frame: &[u8]) -> AEResult<(), SpiE> { + let header_len = self.header_write_len(); + // if packet.len() < header_len { + // return Err(AdinError::PACKET_TOO_SMALL); + // } + + let mut packet = Packet::new(); + + let mut spi_hdr = SpiHeader(0); + spi_hdr.set_control(true); + spi_hdr.set_write(true); + spi_hdr.set_addr(sr::TX); + + packet + .extend_from_slice(spi_hdr.0.to_be_bytes().as_slice()) + .map_err(|_| AdinError::PACKET_TOO_BIG)?; + + if self.crc { + assert_eq!(header_len, 5); + // Add CRC for header data + packet + .push(crc8(&packet[0..2])) + .map_err(|_| AdinError::PACKET_TOO_BIG)?; + } + + // Add port number + // packet[header_len - FRAME_HEADER_LEN..header_len] + // .copy_from_slice(u16::from(PORT_ID_BYTE).to_be_bytes().as_slice()); + packet + .extend_from_slice(u16::from(PORT_ID_BYTE).to_be_bytes().as_slice()) + .map_err(|_| AdinError::PACKET_TOO_BIG)?; + + packet.extend_from_slice(frame).map_err(|_| AdinError::PACKET_TOO_BIG)?; + + // Pad data up to 64 + for _ in packet.len()..(64 - FEC_LEN + header_len) { + let _ = packet.push(0x00); + } + + // // add ethernet crc32 + let crc = ETH_FSC::new(&packet[header_len..]); + let _ = packet.extend_from_slice(crc.hton_bytes().as_slice()); + + let crc = ETH_FSC::new(&packet[header_len..]); + assert!(crc.crc_ok()); + + let send_len = packet.len() - header_len + FRAME_HEADER_LEN; + + // Packet read of write to the MAC packet buffer must be a multipul of 4! + while packet.len() & 0x3 != 0 { + let _ = packet.push(DONT_CARE_BYTE); + } + + #[cfg(feature = "defmt")] + defmt::trace!( + "TX: hdr {} [{}] {:02x} SIZE: {}", + header_len, + packet.len(), + &packet, + send_len, + ); + + self.write_reg(sr::TX_FSIZE, send_len as u32).await?; + + // Spi packet must be half word / even length + if send_len & 1 != 0 { + let _ = packet.push(0x00); + } + + self.spi.write(&packet).await.map_err(AdinError::Spi) + } + + pub fn header_write_len(&self) -> usize { + // u16 + [CRC] + PORT + WR_HEADER_LEN + FRAME_HEADER_LEN + usize::from(self.crc) + } + + pub fn header_len_read(&self) -> usize { + // u16 + [CRC] + u8 + WR_HEADER_LEN + 1 + usize::from(self.crc) + } + + /// Programs the mac address in the mac filters. + /// Also set the boardcast address. + /// The chip supports 2 priority queues but current code doesn't support this mode. + pub async fn set_mac_addr(&mut self, mac: &[u8; 6]) -> AEResult<(), SpiE> { + let mac_high_part = u16::from_be_bytes(mac[0..2].try_into().unwrap()); + let mac_low_part = u32::from_be_bytes(mac[2..6].try_into().unwrap()); + + // program our mac address in the mac address filter + self.write_reg(sr::ADDR_FILT_UPR0, (1 << 16) | (1 << 30) | u32::from(mac_high_part)) + .await?; + self.write_reg(sr::ADDR_FILT_LWR0, mac_low_part).await?; + + self.write_reg(sr::ADDR_MSK_UPR0, u32::from(mac_high_part)).await?; + self.write_reg(sr::ADDR_MSK_LWR0, mac_low_part).await?; + + // Also program broadcast address in the mac address filter + self.write_reg(sr::ADDR_FILT_UPR1, (1 << 16) | (1 << 30) | 0xFFFF) + .await?; + self.write_reg(sr::ADDR_FILT_LWR1, 0xFFFF_FFFF).await?; + self.write_reg(sr::ADDR_MSK_UPR1, 0xFFFF).await?; + self.write_reg(sr::ADDR_MSK_LWR1, 0xFFFF_FFFF).await?; + + Ok(()) + } +} + +impl mdio::MdioBus for ADIN1110 +where + SPI: SpiDevice, + SpiE: core::fmt::Debug, +{ + type Error = AdinError; + + /// Read from the PHY Registers as Clause 22. + async fn read_cl22(&mut self, phy_id: u8, reg: u8) -> Result { + let mdio_acc_val: u32 = + (0x1 << 28) | u32::from(phy_id & 0x1F) << 21 | u32::from(reg & 0x1F) << 16 | (0x3 << 26); + + self.write_mdio_acc_reg(mdio_acc_val).await.map(|val| val as u16) + } + + /// Read from the PHY Registers as Clause 45. + async fn read_cl45(&mut self, phy_id: u8, regc45: (u8, u16)) -> Result { + let mdio_acc_val: u32 = u32::from(phy_id & 0x1F) << 21 | u32::from(regc45.0 & 0x1F) << 16 | u32::from(regc45.1); + + self.write_mdio_acc_reg(mdio_acc_val).await?; + + let mdio_acc_val: u32 = u32::from(phy_id & 0x1F) << 21 | u32::from(regc45.0 & 0x1F) << 16 | (0x03 << 26); + + self.write_mdio_acc_reg(mdio_acc_val).await.map(|val| val as u16) + } + + /// Write to the PHY Registers as Clause 22. + async fn write_cl22(&mut self, phy_id: u8, reg: u8, val: u16) -> Result<(), Self::Error> { + let mdio_acc_val: u32 = + (0x1 << 28) | u32::from(phy_id & 0x1F) << 21 | u32::from(reg & 0x1F) << 16 | (0x1 << 26) | u32::from(val); + + self.write_mdio_acc_reg(mdio_acc_val).await.map(|_| ()) + } + + /// Write to the PHY Registers as Clause 45. + async fn write_cl45(&mut self, phy_id: u8, regc45: (u8, u16), value: u16) -> AEResult<(), SpiE> { + let phy_id = u32::from(phy_id & 0x1F) << 21; + let dev_addr = u32::from(regc45.0 & 0x1F) << 16; + let reg = u32::from(regc45.1); + + let mdio_acc_val: u32 = phy_id | dev_addr | reg; + self.write_mdio_acc_reg(mdio_acc_val).await?; + + let mdio_acc_val: u32 = phy_id | dev_addr | (0x01 << 26) | u32::from(value); + self.write_mdio_acc_reg(mdio_acc_val).await.map(|_| ()) + } +} + +/// Background runner for the ADIN110. +/// +/// You must call `.run()` in a background task for the ADIN1100 to operate. +pub struct Runner<'d, SPI, INT, RST> { + mac: ADIN1110, + ch: ch::Runner<'d, MTU>, + int: INT, + is_link_up: bool, + _reset: RST, +} + +impl<'d, SPI: SpiDevice, INT: Wait, RST: OutputPin> Runner<'d, SPI, INT, RST> { + pub async fn run(mut self) -> ! { + loop { + let (state_chan, mut rx_chan, mut tx_chan) = self.ch.split(); + + loop { + #[cfg(feature = "defmt")] + defmt::debug!("Waiting for interrupts"); + match select(self.int.wait_for_low(), tx_chan.tx_buf()).await { + Either::First(_) => { + let mut status1_clr = Status1(0); + let mut status1 = Status1(self.mac.read_reg(sr::STATUS1).await.unwrap()); + + while status1.p1_rx_rdy() { + #[cfg(feature = "defmt")] + defmt::debug!("alloc RX packet buffer"); + match select(rx_chan.rx_buf(), tx_chan.tx_buf()).await { + // Handle frames that needs to transmit from the wire. + // Note: rx_chan.rx_buf() channel donĀ“t accept new request + // when the tx_chan is full. So these will be handled + // automaticly. + Either::First(frame) => match self.mac.read_fifo(frame).await { + Ok(n) => { + rx_chan.rx_done(n); + } + Err(e) => match e { + AdinError::PACKET_TOO_BIG => { + #[cfg(feature = "defmt")] + defmt::error!("RX Packet to big, DROP"); + self.mac.write_reg(sr::FIFO_CLR, 1).await.unwrap(); + } + AdinError::Spi(_) => { + #[cfg(feature = "defmt")] + defmt::error!("RX Spi error") + } + _ => { + #[cfg(feature = "defmt")] + defmt::error!("RX Error") + } + }, + }, + Either::Second(frame) => { + // Handle frames that needs to transmit to the wire. + self.mac.write_fifo(frame).await.unwrap(); + tx_chan.tx_done(); + } + } + status1 = Status1(self.mac.read_reg(sr::STATUS1).await.unwrap()); + } + + let status0 = Status0(self.mac.read_reg(sr::STATUS0).await.unwrap()); + if status1.0 & !0x1b != 0 { + #[cfg(feature = "defmt")] + defmt::error!("SPE CHIP STATUS 0:{:08x} 1:{:08x}", status0.0, status1.0); + } + + if status1.tx_rdy() { + status1_clr.set_tx_rdy(true); + #[cfg(feature = "defmt")] + defmt::info!("TX_DONE"); + } + + if status1.link_change() { + let link = status1.p1_link_status(); + self.is_link_up = link; + + #[cfg(feature = "defmt")] + if link { + let link_status = self + .mac + .read_cl45(MDIO_PHY_ADDR, RegsC45::DA7::AN_STATUS_EXTRA.into()) + .await + .unwrap(); + + let volt = if link_status & (0b11 << 5) == (0b11 << 5) { + "2.4" + } else { + "1.0" + }; + + let mse = self + .mac + .read_cl45(MDIO_PHY_ADDR, RegsC45::DA1::MSE_VAL.into()) + .await + .unwrap(); + + defmt::info!("LINK Changed: Link Up, Volt: {} V p-p, MSE: {:0004}", volt, mse); + } else { + defmt::info!("LINK Changed: Link Down"); + } + + state_chan.set_link_state(if link { LinkState::Up } else { LinkState::Down }); + status1_clr.set_link_change(true); + } + + if status1.tx_ecc_err() { + #[cfg(feature = "defmt")] + defmt::error!("SPI TX_ECC_ERR error, CLEAR TX FIFO"); + self.mac.write_reg(sr::FIFO_CLR, 2).await.unwrap(); + status1_clr.set_tx_ecc_err(true); + } + + if status1.rx_ecc_err() { + #[cfg(feature = "defmt")] + defmt::error!("SPI RX_ECC_ERR error"); + status1_clr.set_rx_ecc_err(true); + } + + if status1.spi_err() { + #[cfg(feature = "defmt")] + defmt::error!("SPI SPI_ERR CRC error"); + status1_clr.set_spi_err(true); + } + + if status0.phyint() { + let crsm_irq_st = self + .mac + .read_cl45(MDIO_PHY_ADDR, RegsC45::DA1E::CRSM_IRQ_STATUS.into()) + .await + .unwrap(); + + let phy_irq_st = self + .mac + .read_cl45(MDIO_PHY_ADDR, RegsC45::DA1F::PHY_SYBSYS_IRQ_STATUS.into()) + .await + .unwrap(); + #[cfg(feature = "defmt")] + defmt::warn!( + "SPE CHIP PHY CRSM_IRQ_STATUS {:04x} PHY_SUBSYS_IRQ_STATUS {:04x}", + crsm_irq_st, + phy_irq_st + ); + } + + if status0.txfcse() { + #[cfg(feature = "defmt")] + defmt::error!("SPE CHIP PHY TX Frame CRC error"); + } + + // Clear status0 + self.mac.write_reg(sr::STATUS0, 0xFFF).await.unwrap(); + self.mac.write_reg(sr::STATUS1, status1_clr.0).await.unwrap(); + } + Either::Second(packet) => { + // Handle frames that needs to transmit to the wire. + self.mac.write_fifo(packet).await.unwrap(); + tx_chan.tx_done(); + } + } + } + } + } +} + +/// Obtain a driver for using the ADIN1110 with [`embassy-net`](crates.io/crates/embassy-net). +pub async fn new( + mac_addr: [u8; 6], + state: &'_ mut State, + spi_dev: SPI, + int: INT, + mut reset: RST, + crc: bool, +) -> (Device<'_>, Runner<'_, SPI, INT, RST>) { + use crate::regs::{IMask0, IMask1}; + + #[cfg(feature = "defmt")] + defmt::info!("INIT ADIN1110"); + + // Reset sequence + reset.set_low().unwrap(); + // Wait t1: 20-43mS + Timer::after(Duration::from_millis(30)).await; + + reset.set_high().unwrap(); + + // Wait t3: 50mS + Timer::after(Duration::from_millis(50)).await; + + // Create device + let mut mac = ADIN1110::new(spi_dev, crc); + + // Check PHYID + let id = mac.read_reg(sr::PHYID).await.unwrap(); + assert_eq!(id, PHYID); + + #[cfg(feature = "defmt")] + defmt::debug!("SPE: CHIP MAC/ID: {:08x}", id); + + #[cfg(feature = "defmt")] + let adin_phy = Phy10BaseT1x::default(); + #[cfg(feature = "defmt")] + let phy_id = adin_phy.get_id(&mut mac).await.unwrap(); + #[cfg(feature = "defmt")] + defmt::debug!("SPE: CHIP: PHY ID: {:08x}", phy_id); + + let mi_control = mac.read_cl22(MDIO_PHY_ADDR, RegsC22::CONTROL as u8).await.unwrap(); + #[cfg(feature = "defmt")] + defmt::println!("SPE CHIP PHY MI_CONTROL {:04x}", mi_control); + if mi_control & 0x0800 != 0 { + let val = mi_control & !0x0800; + #[cfg(feature = "defmt")] + defmt::println!("SPE CHIP PHY MI_CONTROL Disable PowerDown"); + mac.write_cl22(MDIO_PHY_ADDR, RegsC22::CONTROL as u8, val) + .await + .unwrap(); + } + + // Config2: CRC_APPEND + let mut config2 = Config2(0x00000800); + config2.set_crc_append(true); + mac.write_reg(sr::CONFIG2, config2.0).await.unwrap(); + + // Pin Mux Config 1 + let led_val = (0b11 << 6) | (0b11 << 4); // | (0b00 << 1); + mac.write_cl45(MDIO_PHY_ADDR, RegsC45::DA1E::DIGIO_PINMUX.into(), led_val) + .await + .unwrap(); + + let mut led_pol = LedPolarity(0); + led_pol.set_led1_polarity(LedPol::ActiveLow); + led_pol.set_led0_polarity(LedPol::ActiveLow); + + // Led Polarity Regisgere Active Low + mac.write_cl45(MDIO_PHY_ADDR, RegsC45::DA1E::LED_POLARITY.into(), led_pol.0) + .await + .unwrap(); + + // Led Both On + let mut led_cntr = LedCntrl(0x0); + + // LED1: Yellow + led_cntr.set_led1_en(true); + led_cntr.set_led1_function(LedFunc::TxLevel2P4); + // LED0: Green + led_cntr.set_led0_en(true); + led_cntr.set_led0_function(LedFunc::LinkupTxRxActicity); + + mac.write_cl45(MDIO_PHY_ADDR, RegsC45::DA1E::LED_CNTRL.into(), led_cntr.0) + .await + .unwrap(); + + // Set ADIN1110 Interrupts, RX_READY and LINK_CHANGE + // Enable interrupts LINK_CHANGE, TX_RDY, RX_RDY(P1), SPI_ERR + // Have to clear the mask the enable it. + let mut imask0_val = IMask0(0x0000_1FBF); + imask0_val.set_txfcsem(false); + imask0_val.set_phyintm(false); + imask0_val.set_txboem(false); + imask0_val.set_rxboem(false); + imask0_val.set_txpem(false); + + mac.write_reg(sr::IMASK0, imask0_val.0).await.unwrap(); + + // Set ADIN1110 Interrupts, RX_READY and LINK_CHANGE + // Enable interrupts LINK_CHANGE, TX_RDY, RX_RDY(P1), SPI_ERR + // Have to clear the mask the enable it. + let mut imask1_val = IMask1(0x43FA_1F1A); + imask1_val.set_link_change_mask(false); + imask1_val.set_p1_rx_rdy_mask(false); + imask1_val.set_spi_err_mask(false); + imask1_val.set_tx_ecc_err_mask(false); + imask1_val.set_rx_ecc_err_mask(false); + + mac.write_reg(sr::IMASK1, imask1_val.0).await.unwrap(); + + // Program mac address but also sets mac filters. + mac.set_mac_addr(&mac_addr).await.unwrap(); + + let (runner, device) = ch::new(&mut state.ch_state, ch::driver::HardwareAddress::Ethernet(mac_addr)); + ( + device, + Runner { + ch: runner, + mac, + int, + is_link_up: false, + _reset: reset, + }, + ) +} + +#[cfg(test)] +mod tests { + use core::convert::Infallible; + + use embedded_hal_1::digital::{ErrorType, OutputPin}; + use embedded_hal_async::delay::DelayUs; + use embedded_hal_bus::spi::ExclusiveDevice; + use embedded_hal_mock::eh1::spi::{Mock as SpiMock, Transaction as SpiTransaction}; + + #[derive(Debug, Default)] + struct CsPinMock { + pub high: u32, + pub low: u32, + } + impl OutputPin for CsPinMock { + fn set_low(&mut self) -> Result<(), Self::Error> { + self.low += 1; + Ok(()) + } + + fn set_high(&mut self) -> Result<(), Self::Error> { + self.high += 1; + Ok(()) + } + } + impl ErrorType for CsPinMock { + type Error = Infallible; + } + + use super::*; + + // TODO: This is currently a workaround unit `ExclusiveDevice` is moved to `embedded-hal-bus` + // see https://github.com/rust-embedded/embedded-hal/pull/462#issuecomment-1560014426 + struct MockDelay {} + + impl DelayUs for MockDelay { + async fn delay_us(&mut self, _us: u32) { + todo!() + } + + async fn delay_ms(&mut self, _ms: u32) { + todo!() + } + } + + #[futures_test::test] + async fn mac_read_registers_without_crc() { + // Configure expectations + let expectations = [ + // 1st + SpiTransaction::write_vec(vec![0x80, 0x01, TURN_AROUND_BYTE]), + SpiTransaction::read_vec(vec![0x02, 0x83, 0xBC, 0x91]), + SpiTransaction::flush(), + // 2nd + SpiTransaction::write_vec(vec![0x80, 0x02, TURN_AROUND_BYTE]), + SpiTransaction::read_vec(vec![0x00, 0x00, 0x06, 0xC3]), + SpiTransaction::flush(), + ]; + let mut spi = SpiMock::new(&expectations); + + let cs = CsPinMock::default(); + let delay = MockDelay {}; + let spi_dev = ExclusiveDevice::new(spi.clone(), cs, delay); + let mut spe = ADIN1110::new(spi_dev, false); + + // Read PHIID + match spe.read_reg(sr::PHYID).await { + Ok(val) => assert_eq!(val, 0x0283BC91), + Err(_e) => panic!("Error:"), + }; + + // Read CAPAVILITY + match spe.read_reg(sr::CAPABILITY).await { + Ok(val) => assert_eq!(val, 0x000006C3), + Err(_e) => panic!("Error:"), + }; + + spi.done(); + } + + #[futures_test::test] + async fn mac_read_registers_with_crc() { + // Configure expectations + let expectations = [ + // 1st + SpiTransaction::write_vec(vec![0x80, 0x01, 177, TURN_AROUND_BYTE]), + SpiTransaction::read_vec(vec![0x02, 0x83, 0xBC, 0x91, 215]), + SpiTransaction::flush(), + // 2nd + SpiTransaction::write_vec(vec![0x80, 0x02, 184, TURN_AROUND_BYTE]), + SpiTransaction::read_vec(vec![0x00, 0x00, 0x06, 0xC3, 57]), + SpiTransaction::flush(), + ]; + let mut spi = SpiMock::new(&expectations); + + let cs = CsPinMock::default(); + let delay = MockDelay {}; + let spi_dev = ExclusiveDevice::new(spi.clone(), cs, delay); + + let mut spe = ADIN1110::new(spi_dev, true); + + assert_eq!(crc8(0x0283BC91_u32.to_be_bytes().as_slice()), 215); + assert_eq!(crc8(0x000006C3_u32.to_be_bytes().as_slice()), 57); + + // Read PHIID + match spe.read_reg(sr::PHYID).await { + Ok(val) => assert_eq!(val, 0x0283BC91), + Err(e) => panic!("Error: {e:?}"), + }; + + // Read CAPAVILITY + match spe.read_reg(sr::CAPABILITY).await { + Ok(val) => assert_eq!(val, 0x000006C3), + Err(_e) => panic!("Error:"), + }; + + spi.done(); + } + + #[futures_test::test] + async fn mac_write_registers_without_crc() { + // Configure expectations + let expectations = [ + SpiTransaction::write_vec(vec![0xA0, 0x09, 0x12, 0x34, 0x56, 0x78]), + SpiTransaction::flush(), + ]; + let mut spi = SpiMock::new(&expectations); + + let cs = CsPinMock::default(); + let delay = MockDelay {}; + let spi_dev = ExclusiveDevice::new(spi.clone(), cs, delay); + + let mut spe = ADIN1110::new(spi_dev, false); + + // Write reg: 0x1FFF + assert!(spe.write_reg(sr::STATUS1, 0x1234_5678).await.is_ok()); + + spi.done(); + } + + #[futures_test::test] + async fn mac_write_registers_with_crc() { + // Configure expectations + let expectations = [ + SpiTransaction::write_vec(vec![0xA0, 0x09, 39, 0x12, 0x34, 0x56, 0x78, 28]), + SpiTransaction::flush(), + ]; + let mut spi = SpiMock::new(&expectations); + + let cs = CsPinMock::default(); + let delay = MockDelay {}; + let spi_dev = ExclusiveDevice::new(spi.clone(), cs, delay); + + let mut spe = ADIN1110::new(spi_dev, true); + + // Write reg: 0x1FFF + assert!(spe.write_reg(sr::STATUS1, 0x1234_5678).await.is_ok()); + + spi.done(); + } + + #[test] + fn align_size() { + assert_eq!(size_align_u32(1), 4); + assert_eq!(size_align_u32(2), 4); + assert_eq!(size_align_u32(3), 4); + assert_eq!(size_align_u32(4), 4); + assert_eq!(size_align_u32(5), 8); + assert_eq!(size_align_u32(6), 8); + assert_eq!(size_align_u32(7), 8); + assert_eq!(size_align_u32(8), 8); + } + + // #[test] + // fn write_packet_to_fifo_less_64b_with_crc() { + // // Configure expectations + // let mut expectations = vec![ + // // HEADER + // SpiTransaction::send(0xA0), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0x30), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(136), + // SpiTransaction::read(DONT_CARE_BYTE), + // // Frame Size + // SpiTransaction::send(0x00), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0x00), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0x00), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(66), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(201), + // SpiTransaction::read(DONT_CARE_BYTE), + // // HEADER + // SpiTransaction::send(0xA0), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0x31), + // SpiTransaction::read(DONT_CARE_BYTE), + // // Port + // SpiTransaction::send(0x00), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(PORT_ID_BYTE), + // SpiTransaction::read(DONT_CARE_BYTE), + // ]; + + // let mut packet = Packet::new(); + // packet.resize(64, 0).unwrap(); + + // for &byte in &packet[4..] { + // expectations.push(SpiTransaction::send(byte)); + // expectations.push(SpiTransaction::read(DONT_CARE_BYTE)); + // } + + // // padding + // for _ in packet.len() as u32..65 { + // expectations.push(SpiTransaction::send(0x00)); + // expectations.push(SpiTransaction::read(DONT_CARE_BYTE)); + // } + + // // fcs + // for &byte in &[8, 137, 18, 4] { + // expectations.push(SpiTransaction::send(byte)); + // expectations.push(SpiTransaction::read(DONT_CARE_BYTE)); + // } + + // let spi = SpiMock::new(&expectations); + + // let cs = CsPinMock {}; + // let mut spe = Adin1110::new(spi, cs, true); + + // assert!(spe.write_fifo(&mut packet).is_ok()); + // } + + // #[test] + // fn write_packet_to_fifo_less_64b_no_crc() { + // // Configure expectations + // let mut expectations = vec![ + // // HEADER + // SpiTransaction::send(0xA0), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0x30), + // SpiTransaction::read(DONT_CARE_BYTE), + // // Frame Size + // SpiTransaction::send(0x00), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0x00), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0x00), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(66), + // SpiTransaction::read(DONT_CARE_BYTE), + // // HEADER + // SpiTransaction::send(0xA0), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0x31), + // SpiTransaction::read(DONT_CARE_BYTE), + // // Port + // SpiTransaction::send(0x00), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(PORT_ID_BYTE), + // SpiTransaction::read(DONT_CARE_BYTE), + // ]; + + // let mut packet = Packet::new(); + // packet.resize(64, 0).unwrap(); + + // for &byte in &packet[4..] { + // expectations.push(SpiTransaction::send(byte)); + // expectations.push(SpiTransaction::read(DONT_CARE_BYTE)); + // } + + // // padding + // for _ in packet.len() as u32..64 { + // expectations.push(SpiTransaction::send(0x00)); + // expectations.push(SpiTransaction::read(DONT_CARE_BYTE)); + // } + + // // fcs + // for &byte in &[8, 137, 18, 4] { + // expectations.push(SpiTransaction::send(byte)); + // expectations.push(SpiTransaction::read(DONT_CARE_BYTE)); + // } + + // let spi = SpiMock::new(&expectations); + + // let cs = CsPinMock {}; + // let mut spe = Adin1110::new(spi, cs, false); + + // assert!(spe.write_fifo(&mut packet).is_ok()); + // } + + // #[test] + // fn write_packet_to_fifo_1500b() { + // // Configure expectations + // let mut expectations = vec![ + // // HEADER + // SpiTransaction::send(0xA0), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0x30), + // SpiTransaction::read(DONT_CARE_BYTE), + // // Frame Size + // SpiTransaction::send(0x00), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0x00), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0x05), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0xDE), + // SpiTransaction::read(DONT_CARE_BYTE), + // // HEADER + // SpiTransaction::send(0xA0), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0x31), + // SpiTransaction::read(DONT_CARE_BYTE), + // // Port + // SpiTransaction::send(0x00), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(PORT_ID_BYTE), + // SpiTransaction::read(DONT_CARE_BYTE), + // ]; + + // let mut packet = Packet::new(); + // packet.resize(1500, 0).unwrap(); + + // for &byte in &packet[4..] { + // expectations.push(SpiTransaction::send(byte)); + // expectations.push(SpiTransaction::read(DONT_CARE_BYTE)); + // } + + // // fcs + // for &byte in &[212, 114, 18, 50] { + // expectations.push(SpiTransaction::send(byte)); + // expectations.push(SpiTransaction::read(DONT_CARE_BYTE)); + // } + + // let spi = SpiMock::new(&expectations); + + // let cs = CsPinMock {}; + // let mut spe = Adin1110::new(spi, cs, false); + + // assert!(spe.write_fifo(&mut packet).is_ok()); + // } + + // #[test] + // fn write_packet_to_fifo_65b() { + // // Configure expectations + // let mut expectations = vec![ + // // HEADER + // SpiTransaction::send(0xA0), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0x30), + // SpiTransaction::read(DONT_CARE_BYTE), + // // Frame Size + // SpiTransaction::send(0x00), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0x00), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0x00), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(67), + // SpiTransaction::read(DONT_CARE_BYTE), + // // HEADER + // SpiTransaction::send(0xA0), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0x31), + // SpiTransaction::read(DONT_CARE_BYTE), + // // Port + // SpiTransaction::send(0x00), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(PORT_ID_BYTE), + // SpiTransaction::read(DONT_CARE_BYTE), + // ]; + + // let mut packet = Packet::new(); + // packet.resize(65, 0).unwrap(); + + // for &byte in &packet[4..] { + // expectations.push(SpiTransaction::send(byte)); + // expectations.push(SpiTransaction::read(DONT_CARE_BYTE)); + // } + + // // padding + // for _ in packet.len() as u32..64 { + // expectations.push(SpiTransaction::send(0x00)); + // expectations.push(SpiTransaction::read(DONT_CARE_BYTE)); + // } + + // // fcs + // for &byte in &[54, 117, 221, 220] { + // expectations.push(SpiTransaction::send(byte)); + // expectations.push(SpiTransaction::read(DONT_CARE_BYTE)); + // } + + // let spi = SpiMock::new(&expectations); + + // let cs = CsPinMock {}; + // let mut spe = Adin1110::new(spi, cs, false); + + // assert!(spe.write_fifo(&mut packet).is_ok()); + // } + + // #[test] + // fn write_packet_to_fifo_66b() { + // // Configure expectations + // let mut expectations = vec![ + // // HEADER + // SpiTransaction::send(0xA0), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0x30), + // SpiTransaction::read(DONT_CARE_BYTE), + // // Frame Size + // SpiTransaction::send(0x00), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0x00), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0x00), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(68), + // SpiTransaction::read(DONT_CARE_BYTE), + // // HEADER + // SpiTransaction::send(0xA0), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0x31), + // SpiTransaction::read(DONT_CARE_BYTE), + // // Port + // SpiTransaction::send(0x00), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(PORT_ID_BYTE), + // SpiTransaction::read(DONT_CARE_BYTE), + // ]; + + // let mut packet = Packet::new(); + // packet.resize(66, 0).unwrap(); + + // for &byte in &packet[4..] { + // expectations.push(SpiTransaction::send(byte)); + // expectations.push(SpiTransaction::read(DONT_CARE_BYTE)); + // } + + // // padding + // for _ in packet.len() as u32..64 { + // expectations.push(SpiTransaction::send(0x00)); + // expectations.push(SpiTransaction::read(DONT_CARE_BYTE)); + // } + + // // fcs + // for &byte in &[97, 167, 100, 29] { + // expectations.push(SpiTransaction::send(byte)); + // expectations.push(SpiTransaction::read(DONT_CARE_BYTE)); + // } + // let spi = SpiMock::new(&expectations); + + // let cs = CsPinMock {}; + // let mut spe = Adin1110::new(spi, cs, false); + + // assert!(spe.write_fifo(&mut packet).is_ok()); + // } + + // #[test] + // fn write_packet_to_fifo_67b() { + // // Configure expectations + // let mut expectations = vec![ + // // HEADER + // SpiTransaction::send(0xA0), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0x30), + // SpiTransaction::read(DONT_CARE_BYTE), + // // Frame Size + // SpiTransaction::send(0x00), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0x00), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0x00), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(69), + // SpiTransaction::read(DONT_CARE_BYTE), + // // HEADER + // SpiTransaction::send(0xA0), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(0x31), + // SpiTransaction::read(DONT_CARE_BYTE), + // // Port + // SpiTransaction::send(0x00), + // SpiTransaction::read(DONT_CARE_BYTE), + // SpiTransaction::send(PORT_ID_BYTE), + // SpiTransaction::read(DONT_CARE_BYTE), + // ]; + + // let mut packet = Packet::new(); + // packet.resize(67, 0).unwrap(); + + // for &byte in &packet[4..] { + // expectations.push(SpiTransaction::send(byte)); + // expectations.push(SpiTransaction::read(DONT_CARE_BYTE)); + // } + + // // padding + // for _ in packet.len() as u32..64 { + // expectations.push(SpiTransaction::send(0x00)); + // expectations.push(SpiTransaction::read(DONT_CARE_BYTE)); + // } + + // // fcs + // for &byte in &[228, 218, 170, 232] { + // expectations.push(SpiTransaction::send(byte)); + // expectations.push(SpiTransaction::read(DONT_CARE_BYTE)); + // } + // let spi = SpiMock::new(&expectations); + + // let cs = CsPinMock {}; + // let mut spe = Adin1110::new(spi, cs, false); + + // assert!(spe.write_fifo(&mut packet).is_ok()); + // } + + #[futures_test::test] + async fn write_packet_to_fifo_arp_46bytes() { + // Configure expectations + let mut expectations = vec![]; + + let mut packet = Packet::new(); + //arp packet; + packet + .extend_from_slice(&[ + 34, 51, 68, 85, 102, 119, 18, 52, 86, 120, 154, 188, 8, 6, 0, 1, 8, 0, 6, 4, 0, 2, 18, 52, 86, 120, + 154, 188, 192, 168, 16, 4, 34, 51, 68, 85, 102, 119, 192, 168, 16, 1, + ]) + .unwrap(); + + let mut spi_packet = Packet::new(); + + // Write TX_SIZE reg + expectations.push(SpiTransaction::write_vec(vec![160, 48, 136, 0, 0, 0, 66, 201])); + expectations.push(SpiTransaction::flush()); + + // Write TX reg. + // Header + spi_packet.extend_from_slice(&[160, 49, 143, 0, 0]).unwrap(); + // Packet data + spi_packet.extend_from_slice(&packet).unwrap(); + // Packet padding up to 60 (64 - FCS) + for _ in packet.len() as u32..60 { + spi_packet.push(0x00).unwrap(); + } + // Packet FCS + spi_packet.extend_from_slice(&[147, 149, 213, 68]).unwrap(); + + // SPI HEADER Padding of u32 + for _ in spi_packet.len() as u32..size_align_u32(spi_packet.len() as u32) { + spi_packet.push(0x00).unwrap(); + } + + expectations.push(SpiTransaction::write_vec(spi_packet.to_vec())); + expectations.push(SpiTransaction::flush()); + + let mut spi = SpiMock::new(&expectations); + + let cs = CsPinMock::default(); + let delay = MockDelay {}; + let spi_dev = ExclusiveDevice::new(spi.clone(), cs, delay); + + let mut spe = ADIN1110::new(spi_dev, true); + + assert!(spe.write_fifo(&mut packet).await.is_ok()); + + spi.done(); + } +} diff --git a/embassy-net-adin1110/src/mdio.rs b/embassy-net-adin1110/src/mdio.rs new file mode 100644 index 00000000..ab7629d3 --- /dev/null +++ b/embassy-net-adin1110/src/mdio.rs @@ -0,0 +1,174 @@ +/// PHY Address: (0..=0x1F), 5-bits long. +#[allow(dead_code)] +type PhyAddr = u8; + +/// PHY Register: (0..=0x1F), 5-bits long. +#[allow(dead_code)] +type RegC22 = u8; + +/// PHY Register Clause 45. +#[allow(dead_code)] +type RegC45 = u16; + +/// PHY Register Value +#[allow(dead_code)] +type RegVal = u16; + +#[allow(dead_code)] +const REG13: RegC22 = 13; +#[allow(dead_code)] +const REG14: RegC22 = 14; + +#[allow(dead_code)] +const PHYADDR_MASK: u8 = 0x1f; +#[allow(dead_code)] +const DEV_MASK: u8 = 0x1f; + +#[allow(dead_code)] +#[repr(u16)] +enum Reg13Op { + Addr = 0b00 << 14, + Write = 0b01 << 14, + PostReadIncAddr = 0b10 << 14, + Read = 0b11 << 14, +} +/// MdioBus trait +/// Driver needs to implemnt the Claus 22 +/// Optional Clause 45 is the device supports this. +/// +/// Claus 45 methodes are bases on https://www.ieee802.org/3/efm/public/nov02/oam/pannell_oam_1_1102.pdf +pub trait MdioBus { + type Error; + + /// Read, Clause 22 + async fn read_cl22(&mut self, phy_id: PhyAddr, reg: RegC22) -> Result; + + /// Write, Clause 22 + async fn write_cl22(&mut self, phy_id: PhyAddr, reg: RegC22, reg_val: RegVal) -> Result<(), Self::Error>; + + /// Read, Clause 45 + /// This is the default implementation. + /// Many hardware these days support direct Clause 45 operations. + /// Implement this function when your hardware supports it. + async fn read_cl45(&mut self, phy_id: PhyAddr, regc45: (u8, RegC45)) -> Result { + // Write FN + let val = (Reg13Op::Addr as RegVal) | (regc45.0 & DEV_MASK) as RegVal; + self.write_cl22(phy_id, REG13, val).await?; + // Write Addr + self.write_cl22(phy_id, REG14, regc45.1).await?; + + // Write FN + let val = (Reg13Op::Read as RegVal) | (regc45.0 & DEV_MASK) as RegVal; + self.write_cl22(phy_id, REG13, val).await?; + // Write Addr + self.read_cl22(phy_id, REG14).await + } + + /// Write, Clause 45 + /// This is the default implementation. + /// Many hardware these days support direct Clause 45 operations. + /// Implement this function when your hardware supports it. + async fn write_cl45(&mut self, phy_id: PhyAddr, regc45: (u8, RegC45), reg_val: RegVal) -> Result<(), Self::Error> { + let dev_addr = (regc45.0 & DEV_MASK) as RegVal; + let reg = regc45.1; + + // Write FN + let val = (Reg13Op::Addr as RegVal) | dev_addr; + self.write_cl22(phy_id, REG13, val).await?; + // Write Addr + self.write_cl22(phy_id, REG14, reg).await?; + + // Write FN + let val = (Reg13Op::Write as RegVal) | dev_addr; + self.write_cl22(phy_id, REG13, val).await?; + // Write Addr + self.write_cl22(phy_id, REG14, reg_val).await + } +} + +// #[cfg(test)] +// mod tests { +// use core::convert::Infallible; + +// use super::{MdioBus, PhyAddr, RegC22, RegVal}; + +// #[derive(Debug, PartialEq, Eq)] +// enum A { +// Read(PhyAddr, RegC22), +// Write(PhyAddr, RegC22, RegVal), +// } + +// struct MockMdioBus(Vec); + +// impl MockMdioBus { +// pub fn clear(&mut self) { +// self.0.clear(); +// } +// } + +// impl MdioBus for MockMdioBus { +// type Error = Infallible; + +// fn write_cl22( +// &mut self, +// phy_id: super::PhyAddr, +// reg: super::RegC22, +// reg_val: super::RegVal, +// ) -> Result<(), Self::Error> { +// self.0.push(A::Write(phy_id, reg, reg_val)); +// Ok(()) +// } + +// fn read_cl22( +// &mut self, +// phy_id: super::PhyAddr, +// reg: super::RegC22, +// ) -> Result { +// self.0.push(A::Read(phy_id, reg)); +// Ok(0) +// } +// } + +// #[test] +// fn read_test() { +// let mut mdiobus = MockMdioBus(Vec::with_capacity(20)); + +// mdiobus.clear(); +// mdiobus.read_cl22(0x01, 0x00).unwrap(); +// assert_eq!(mdiobus.0, vec![A::Read(0x01, 0x00)]); + +// mdiobus.clear(); +// mdiobus.read_cl45(0x01, (0xBB, 0x1234)).unwrap(); +// assert_eq!( +// mdiobus.0, +// vec![ +// #[allow(clippy::identity_op)] +// A::Write(0x01, 13, (0b00 << 14) | 27), +// A::Write(0x01, 14, 0x1234), +// A::Write(0x01, 13, (0b11 << 14) | 27), +// A::Read(0x01, 14) +// ] +// ); +// } + +// #[test] +// fn write_test() { +// let mut mdiobus = MockMdioBus(Vec::with_capacity(20)); + +// mdiobus.clear(); +// mdiobus.write_cl22(0x01, 0x00, 0xABCD).unwrap(); +// assert_eq!(mdiobus.0, vec![A::Write(0x01, 0x00, 0xABCD)]); + +// mdiobus.clear(); +// mdiobus.write_cl45(0x01, (0xBB, 0x1234), 0xABCD).unwrap(); +// assert_eq!( +// mdiobus.0, +// vec![ +// A::Write(0x01, 13, 27), +// A::Write(0x01, 14, 0x1234), +// A::Write(0x01, 13, (0b01 << 14) | 27), +// A::Write(0x01, 14, 0xABCD) +// ] +// ); +// } +// } diff --git a/embassy-net-adin1110/src/phy.rs b/embassy-net-adin1110/src/phy.rs new file mode 100644 index 00000000..78d3fdf7 --- /dev/null +++ b/embassy-net-adin1110/src/phy.rs @@ -0,0 +1,137 @@ +use crate::mdio::MdioBus; + +#[allow(dead_code, non_camel_case_types, clippy::upper_case_acronyms)] +#[repr(u8)] +/// Clause 22 Registers +pub enum RegsC22 { + /// MII Control Register + CONTROL = 0x00, + /// MII Status Register + STATUS = 0x01, + /// PHY Identifier 1 Register + PHY_ID1 = 0x02, + /// PHY Identifier 2 Register. + PHY_ID2 = 0x03, +} + +/// Clause 45 Registers +#[allow(non_snake_case, dead_code)] +pub mod RegsC45 { + /// Device Address: 0x01 + #[allow(non_camel_case_types, clippy::upper_case_acronyms)] + #[repr(u16)] + pub enum DA1 { + /// PMA/PMD Control 1 Register + PMA_PMD_CNTRL1 = 0x0000, + /// PMA/PMD Status 1 Register + PMA_PMD_STAT1 = 0x0001, + /// MSE Value Register + MSE_VAL = 0x830B, + } + + impl DA1 { + pub fn into(self) -> (u8, u16) { + (0x01, self as u16) + } + } + + /// Device Address: 0x03 + #[allow(non_camel_case_types, clippy::upper_case_acronyms)] + #[repr(u16)] + pub enum DA3 { + /// PCS Control 1 Register + PCS_CNTRL1 = 0x0000, + /// PCS Status 1 Register + PCS_STAT1 = 0x0001, + /// PCS Status 2 Register + PCS_STAT2 = 0x0008, + } + + impl DA3 { + pub fn into(self) -> (u8, u16) { + (0x03, self as u16) + } + } + + /// Device Address: 0x07 + #[allow(non_camel_case_types, clippy::upper_case_acronyms)] + #[repr(u16)] + pub enum DA7 { + /// Extra Autonegotiation Status Register + AN_STATUS_EXTRA = 0x8001, + } + + impl DA7 { + pub fn into(self) -> (u8, u16) { + (0x07, self as u16) + } + } + + /// Device Address: 0x1E + #[allow(non_camel_case_types, clippy::upper_case_acronyms)] + #[repr(u16)] + pub enum DA1E { + /// System Interrupt Status Register + CRSM_IRQ_STATUS = 0x0010, + /// System Interrupt Mask Register + CRSM_IRQ_MASK = 0x0020, + /// Pin Mux Configuration 1 Register + DIGIO_PINMUX = 0x8c56, + /// LED Control Register. + LED_CNTRL = 0x8C82, + /// LED Polarity Register + LED_POLARITY = 0x8C83, + } + + impl DA1E { + pub fn into(self) -> (u8, u16) { + (0x1e, self as u16) + } + } + + /// Device Address: 0x1F + #[allow(non_camel_case_types, clippy::upper_case_acronyms)] + #[repr(u16)] + pub enum DA1F { + /// PHY Subsystem Interrupt Status Register + PHY_SYBSYS_IRQ_STATUS = 0x0011, + /// PHY Subsystem Interrupt Mask Register + PHY_SYBSYS_IRQ_MASK = 0x0021, + } + + impl DA1F { + pub fn into(self) -> (u8, u16) { + (0x1f, self as u16) + } + } +} + +pub struct Phy10BaseT1x(u8); + +impl Default for Phy10BaseT1x { + fn default() -> Self { + Self(0x01) + } +} + +impl Phy10BaseT1x { + /// Get the both parts of the PHYID. + pub async fn get_id(&self, mdiobus: &mut MDIOBUS) -> Result + where + MDIOBUS: MdioBus, + MDE: core::fmt::Debug, + { + let mut phyid = (mdiobus.read_cl22(self.0, RegsC22::PHY_ID1 as u8).await? as u32) << 16; + phyid |= mdiobus.read_cl22(self.0, RegsC22::PHY_ID2 as u8).await? as u32; + Ok(phyid) + } + + /// Get the Mean Squared Error Value. + pub async fn get_sqi(&self, mdiobus: &mut MDIOBUS) -> Result + where + MDIOBUS: MdioBus, + MDE: core::fmt::Debug, + { + mdiobus.read_cl45(self.0, RegsC45::DA1::MSE_VAL.into()).await + } +} diff --git a/embassy-net-adin1110/src/regs.rs b/embassy-net-adin1110/src/regs.rs new file mode 100644 index 00000000..93ce812d --- /dev/null +++ b/embassy-net-adin1110/src/regs.rs @@ -0,0 +1,407 @@ +use bitfield::{bitfield, bitfield_bitrange, bitfield_fields}; + +#[allow(non_camel_case_types)] +#[derive(Debug, Copy, Clone)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[repr(u16)] +/// SPI REGISTER DETAILS +/// Table 38. +pub enum SpiRegisters { + IDVER = 0x00, + PHYID = 0x01, + CAPABILITY = 0x02, + RESET = 0x03, + CONFIG0 = 0x04, + CONFIG2 = 0x06, + STATUS0 = 0x08, + STATUS1 = 0x09, + IMASK0 = 0x0C, + IMASK1 = 0x0D, + MDIO_ACC = 0x20, + TX_FSIZE = 0x30, + TX = 0x31, + TX_SPACE = 0x32, + FIFO_CLR = 0x36, + ADDR_FILT_UPR0 = 0x50, + ADDR_FILT_LWR0 = 0x51, + ADDR_FILT_UPR1 = 0x52, + ADDR_FILT_LWR1 = 0x53, + ADDR_MSK_LWR0 = 0x70, + ADDR_MSK_UPR0 = 0x71, + ADDR_MSK_LWR1 = 0x72, + ADDR_MSK_UPR1 = 0x73, + RX_FSIZE = 0x90, + RX = 0x91, +} + +impl From for u16 { + fn from(val: SpiRegisters) -> Self { + val as u16 + } +} + +impl From for SpiRegisters { + fn from(value: u16) -> Self { + match value { + 0x00 => Self::IDVER, + 0x01 => Self::PHYID, + 0x02 => Self::CAPABILITY, + 0x03 => Self::RESET, + 0x04 => Self::CONFIG0, + 0x06 => Self::CONFIG2, + 0x08 => Self::STATUS0, + 0x09 => Self::STATUS1, + 0x0C => Self::IMASK0, + 0x0D => Self::IMASK1, + 0x20 => Self::MDIO_ACC, + 0x30 => Self::TX_FSIZE, + 0x31 => Self::TX, + 0x32 => Self::TX_SPACE, + 0x36 => Self::FIFO_CLR, + 0x50 => Self::ADDR_FILT_UPR0, + 0x51 => Self::ADDR_FILT_LWR0, + 0x52 => Self::ADDR_FILT_UPR1, + 0x53 => Self::ADDR_FILT_LWR1, + 0x70 => Self::ADDR_MSK_LWR0, + 0x71 => Self::ADDR_MSK_UPR0, + 0x72 => Self::ADDR_MSK_LWR1, + 0x73 => Self::ADDR_MSK_UPR1, + 0x90 => Self::RX_FSIZE, + 0x91 => Self::RX, + e => panic!("Unknown value {e}"), + } + } +} + +// Register definitions + +bitfield! { + /// Status0 Register bits + pub struct Status0(u32); + impl Debug; + u32; + /// Control Data Protection Error + pub cdpe, _ : 12; + /// Transmit Frame Check Squence Error + pub txfcse, _: 11; + /// Transmit Time Stamp Capture Available C + pub ttscac, _ : 10; + /// Transmit Time Stamp Capture Available B + pub ttscab, _ : 9; + /// Transmit Time Stamp Capture Available A + pub ttscaa, _ : 8; + /// PHY Interrupt for Port 1 + pub phyint, _ : 7; + /// Reset Complete + pub resetc, _ : 6; + /// Header error + pub hdre, _ : 5; + /// Loss of Frame Error + pub lofe, _ : 4; + /// Receiver Buffer Overflow Error + pub rxboe, _ : 3; + /// Host Tx FIFO Under Run Error + pub txbue, _ : 2; + /// Host Tx FIFO Overflow + pub txboe, _ : 1; + /// Transmit Protocol Error + pub txpe, _ : 0; +} + +bitfield! { + /// Status1 Register bits + pub struct Status1(u32); + impl Debug; + u32; + /// ECC Error on Reading the Frame Size from a Tx FIFO + pub tx_ecc_err, set_tx_ecc_err: 12; + /// ECC Error on Reading the Frame Size from an Rx FIFO + pub rx_ecc_err, set_rx_ecc_err : 11; + /// Detected an Error on an SPI Transaction + pub spi_err, set_spi_err: 10; + /// Rx MAC Interframe Gap Error + pub p1_rx_ifg_err, set_p1_rx_ifg_err : 8; + /// Port1 Rx Ready High Priority + pub p1_rx_rdy_hi, set_p1_rx_rdy_hi : 5; + /// Port 1 Rx FIFO Contains Data + pub p1_rx_rdy, set_p1_rx_rdy : 4; + /// Tx Ready + pub tx_rdy, set_tx_rdy : 3; + /// Link Status Changed + pub link_change, set_link_change : 1; + /// Port 1 Link Status + pub p1_link_status, _ : 0; +} + +bitfield! { + /// Config0 Register bits + pub struct Config0(u32); + impl Debug; + u32; + /// Configuration Synchronization + pub sync, set_sync : 15; + /// Transmit Frame Check Sequence Validation Enable + pub txfcsve, set_txfcsve : 14; + /// !CS Align Receive Frame Enable + pub csarfe, set_csarfe : 13; + /// Zero Align Receive Frame Enable + pub zarfe, set_zarfe : 12; + /// Transmit Credit Threshold + pub tcxthresh, set_tcxthresh : 11, 10; + /// Transmit Cut Through Enable + pub txcte, set_txcte : 9; + /// Receive Cut Through Enable + pub rxcte, set_rxcte : 8; + /// Frame Time Stamp Enable + pub ftse, set_ftse : 7; + /// Receive Frame Time Stamp Select + pub ftss, set_ftss : 6; + /// Enable Control Data Read Write Protection + pub prote, set_prote : 5; + /// Enable TX Data Chunk Sequence and Retry + pub seqe, set_seqe : 4; + /// Chunk Payload Selector (N). + pub cps, set_cps : 2, 0; +} + +bitfield! { + /// Config2 Register bits + pub struct Config2(u32); + impl Debug; + u32; + /// Assert TX_RDY When the Tx FIFO is Empty + pub tx_rdy_on_empty, set_tx_rdy_on_empty : 8; + /// Determines If the SFD is Detected in the PHY or MAC + pub sdf_detect_src, set_sdf_detect_src : 7; + /// Statistics Clear on Reading + pub stats_clr_on_rd, set_stats_clr_on_rd : 6; + /// Enable CRC Append + pub crc_append, set_crc_append : 5; + /// Admit Frames with IFG Errors on Port 1 (P1) + pub p1_rcv_ifg_err_frm, set_p1_rcv_ifg_err_frm : 4; + /// Forward Frames Not Matching Any MAC Address to the Host + pub p1_fwd_unk2host, set_p1_fwd_unk2host : 2; + /// SPI to MDIO Bridge MDC Clock Speed + pub mspeed, set_mspeed : 0; +} + +bitfield! { + /// IMASK0 Register bits + pub struct IMask0(u32); + impl Debug; + u32; + /// Control Data Protection Error Mask + pub cppem, set_cppem : 12; + /// Transmit Frame Check Sequence Error Mask + pub txfcsem, set_txfcsem : 11; + /// Transmit Time Stamp Capture Available C Mask + pub ttscacm, set_ttscacm : 10; + /// Transmit Time Stamp Capture Available B Mask + pub ttscabm, set_ttscabm : 9; + /// Transmit Time Stamp Capture Available A Mask + pub ttscaam, set_ttscaam : 8; + /// Physical Layer Interrupt Mask + pub phyintm, set_phyintm : 7; + /// RESET Complete Mask + pub resetcm, set_resetcm : 6; + /// Header Error Mask + pub hdrem, set_hdrem : 5; + /// Loss of Frame Error Mask + pub lofem, set_lofem : 4; + /// Receive Buffer Overflow Error Mask + pub rxboem, set_rxboem : 3; + /// Transmit Buffer Underflow Error Mask + pub txbuem, set_txbuem : 2; + /// Transmit Buffer Overflow Error Mask + pub txboem, set_txboem : 1; + /// Transmit Protocol Error Mask + pub txpem, set_txpem : 0; +} + +bitfield! { + /// IMASK1 Register bits + pub struct IMask1(u32); + impl Debug; + u32; + /// Mask Bit for TXF_ECC_ERR + pub tx_ecc_err_mask, set_tx_ecc_err_mask : 12; + /// Mask Bit for RXF_ECC_ERR + pub rx_ecc_err_mask, set_rx_ecc_err_mask : 11; + /// Mask Bit for SPI_ERR + /// This field is only used with the generic SPI protocol + pub spi_err_mask, set_spi_err_mask : 10; + /// Mask Bit for RX_IFG_ERR + pub p1_rx_ifg_err_mask, set_p1_rx_ifg_err_mask : 8; + /// Mask Bit for P1_RX_RDY + /// This field is only used with the generic SPI protocol + pub p1_rx_rdy_mask, set_p1_rx_rdy_mask : 4; + /// Mask Bit for TX_FRM_DONE + /// This field is only used with the generic SPI protocol + pub tx_rdy_mask, set_tx_rdy_mask : 3; + /// Mask Bit for LINK_CHANGE + pub link_change_mask, set_link_change_mask : 1; +} + +#[repr(u8)] +pub enum LedFunc { + LinkupTxRxActicity = 0, + LinkupTxActicity, + LinkupRxActicity, + LinkupOnly, + TxRxActivity, + TxActivity, + RxActivity, + LinkupRxEr, + LinkupRxTxEr, + RxEr, + RxTxEr, + TxSop, + RxSop, + On, + Off, + Blink, + TxLevel2P4, + TxLevel1P0, + Master, + Slave, + IncompatiableLinkCfg, + AnLinkGood, + AnComplete, + TsTimer, + LocRcvrStatus, + RemRcvrStatus, + Clk25Ref, + TxTCLK, + Clk120MHz, +} + +impl From for u8 { + fn from(val: LedFunc) -> Self { + val as u8 + } +} + +impl From for LedFunc { + fn from(value: u8) -> Self { + match value { + 0 => LedFunc::LinkupTxRxActicity, + 1 => LedFunc::LinkupTxActicity, + 2 => LedFunc::LinkupRxActicity, + 3 => LedFunc::LinkupOnly, + 4 => LedFunc::TxRxActivity, + 5 => LedFunc::TxActivity, + 6 => LedFunc::RxActivity, + 7 => LedFunc::LinkupRxEr, + 8 => LedFunc::LinkupRxTxEr, + 9 => LedFunc::RxEr, + 10 => LedFunc::RxTxEr, + 11 => LedFunc::TxSop, + 12 => LedFunc::RxSop, + 13 => LedFunc::On, + 14 => LedFunc::Off, + 15 => LedFunc::Blink, + 16 => LedFunc::TxLevel2P4, + 17 => LedFunc::TxLevel1P0, + 18 => LedFunc::Master, + 19 => LedFunc::Slave, + 20 => LedFunc::IncompatiableLinkCfg, + 21 => LedFunc::AnLinkGood, + 22 => LedFunc::AnComplete, + 23 => LedFunc::TsTimer, + 24 => LedFunc::LocRcvrStatus, + 25 => LedFunc::RemRcvrStatus, + 26 => LedFunc::Clk25Ref, + 27 => LedFunc::TxTCLK, + 28 => LedFunc::Clk120MHz, + e => panic!("Invalid value {e}"), + } + } +} + +/// LED Control Register +#[derive(Copy, Clone, PartialEq, Eq, Hash)] +pub struct LedCntrl(pub u16); +bitfield_bitrange! {struct LedCntrl(u16)} + +impl LedCntrl { + bitfield_fields! { + u8; + /// LED_0 Pin Function + pub from into LedFunc, led0_function, set_led0_function: 4, 0; + /// LED 0 Mode Selection + pub led0_mode, set_led0_mode: 5; + /// Qualify Certain LED 0 Options with Link Status. + pub led0_link_st_qualify, set_led0_link_st_qualify: 6; + /// LED 0 Enable + pub led0_en, set_led0_en: 7; + /// LED_1 Pin Function + pub from into LedFunc, led1_function, set_led1_function: 12, 8; + /// /// LED 1 Mode Selection + pub led1_mode, set_led1_mode: 13; + /// Qualify Certain LED 1 Options with Link Status. + pub led1_link_st_qualify, set_led1_link_st_qualify: 14; + /// LED 1 Enable + pub led1_en, set_led1_en: 15; + } + + pub fn new() -> Self { + LedCntrl(0) + } +} + +// #[allow(dead_code)] +#[repr(u8)] +pub enum LedPol { + AutoSense = 0, + ActiveHigh, + ActiveLow, +} + +impl From for u8 { + fn from(val: LedPol) -> Self { + val as u8 + } +} + +impl From for LedPol { + fn from(value: u8) -> Self { + match value { + 0 => LedPol::AutoSense, + 1 => LedPol::ActiveHigh, + 2 => LedPol::ActiveLow, + e => panic!("Invalid value {e}"), + } + } +} + +/// LED Control Register +#[derive(Copy, Clone, PartialEq, Eq, Hash)] +pub struct LedPolarity(pub u16); +bitfield_bitrange! {struct LedPolarity(u16)} + +impl LedPolarity { + bitfield_fields! { + u8; + /// LED 1 Polarity + pub from into LedPol, led1_polarity, set_led1_polarity: 3, 2; + /// LED_0 Polarity + pub from into LedPol, led0_polarity, set_led0_polarity: 1, 0; + } +} + +/// LED Control Register +#[derive(Copy, Clone, PartialEq, Eq, Hash)] +pub struct SpiHeader(pub u16); +bitfield_bitrange! {struct SpiHeader(u16)} + +impl SpiHeader { + bitfield_fields! { + u16; + /// Mask Bit for TXF_ECC_ERR + pub control, set_control : 15; + pub full_duplex, set_full_duplex : 14; + pub write, set_write : 13; + /// LED_0 Polarity + pub from into SpiRegisters, addr, set_addr: 11, 0; + } +}