Compare commits

...

14 Commits

9 changed files with 368 additions and 453 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
/target
Cargo.lock

417
Cargo.lock generated
View File

@ -1,417 +0,0 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "aligned"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d39da9b88ae1a81c03c9c082b8db83f1d0e93914126041962af61034ab44c4a5"
[[package]]
name = "aligned"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb1ce8b3382016136ab1d31a1b5ce807144f8b7eb2d5f16b2108f0f07edceb94"
dependencies = [
"as-slice",
]
[[package]]
name = "as-slice"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37dfb65bc03b2bc85ee827004f14a6817e04160e3b1a28931986a666a9290e70"
dependencies = [
"generic-array 0.12.3",
"generic-array 0.13.2",
"stable_deref_trait",
]
[[package]]
name = "autocfg"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"
[[package]]
name = "bare-metal"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5deb64efa5bd81e31fcd1938615a6d98c82eafcbcd787162b6f63b91d6bac5b3"
dependencies = [
"rustc_version",
]
[[package]]
name = "bitflags"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693"
[[package]]
name = "byteorder"
version = "1.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08c48aae112d48ed9f069b33538ea9e3e90aa263cfa3d1c24309612b1f7472de"
[[package]]
name = "cast"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b9434b9a5aa1450faa3f9cb14ea0e8c53bb5d2b3c1bfd1ab4fc03e9f33fbfb0"
dependencies = [
"rustc_version",
]
[[package]]
name = "cfg-if"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"
[[package]]
name = "cortex-m"
version = "0.5.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c0b159a1e8306949579de3698c841dba58058197b65c60807194e4fa1e7a554"
dependencies = [
"aligned 0.2.0",
"bare-metal",
"cortex-m 0.6.2",
"volatile-register",
]
[[package]]
name = "cortex-m"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2954942fbbdd49996704e6f048ce57567c3e1a4e2dc59b41ae9fde06a01fc763"
dependencies = [
"aligned 0.3.2",
"bare-metal",
"volatile-register",
]
[[package]]
name = "cortex-m-rt"
version = "0.6.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00d518da72bba39496024b62607c1d8e37bcece44b2536664f1132a73a499a28"
dependencies = [
"cortex-m-rt-macros",
"r0",
]
[[package]]
name = "cortex-m-rt-macros"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4717562afbba06e760d34451919f5c3bf3ac15c7bb897e8b04862a7428378647"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "cortex-m-rtic"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b30efcb6b7920d9016182c485687f0012487032a14c415d2fce6e9862ef8260e"
dependencies = [
"cortex-m 0.6.2",
"cortex-m-rt",
"cortex-m-rtic-macros",
"heapless",
"rtic-core",
"version_check",
]
[[package]]
name = "cortex-m-rtic-macros"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a1a6a4c9550373038c0e21a78d44d529bd697c25bbf6b8004bddc6e63b119c7"
dependencies = [
"proc-macro2",
"quote",
"rtic-syntax",
"syn",
]
[[package]]
name = "embedded-hal"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa998ce59ec9765d15216393af37a58961ddcefb14c753b4816ba2191d865fcb"
dependencies = [
"nb",
"void",
]
[[package]]
name = "enc424j600"
version = "0.1.0"
dependencies = [
"aligned 0.3.2",
"cortex-m 0.5.10",
"cortex-m-rt",
"cortex-m-rtic",
"embedded-hal",
"log",
"panic-itm",
"smoltcp",
"stm32f4xx-hal",
"volatile-register",
]
[[package]]
name = "generic-array"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c68f0274ae0e023facc3c97b2e00f076be70e254bc851d972503b328db79b2ec"
dependencies = [
"typenum",
]
[[package]]
name = "generic-array"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ed1e761351b56f54eb9dcd0cfaca9fd0daecf93918e1cfc01c8a3d26ee7adcd"
dependencies = [
"typenum",
]
[[package]]
name = "hash32"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4041af86e63ac4298ce40e5cca669066e75b6f1aa3390fe2561ffa5e1d9f4cc"
dependencies = [
"byteorder",
]
[[package]]
name = "hashbrown"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7afe4a420e3fe79967a00898cc1f4db7c8a49a9333a29f8a4bd76a253d5cd04"
[[package]]
name = "heapless"
version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74911a68a1658cfcfb61bc0ccfbd536e3b6e906f8c2f7883ee50157e3e2184f1"
dependencies = [
"as-slice",
"generic-array 0.13.2",
"hash32",
"stable_deref_trait",
]
[[package]]
name = "indexmap"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55e2e4c765aa53a0424761bf9f41aa7a6ac1efa87238f59560640e27fca028f2"
dependencies = [
"autocfg",
"hashbrown",
]
[[package]]
name = "log"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7"
dependencies = [
"cfg-if",
]
[[package]]
name = "managed"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c75de51135344a4f8ed3cfe2720dc27736f7711989703a0b43aadf3753c55577"
[[package]]
name = "nb"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1411551beb3c11dedfb0a90a0fa256b47d28b9ec2cdff34c25a2fa59e45dbdc"
[[package]]
name = "panic-itm"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98830d17a95587207e41edaa3009b143d326ce134b0e3538ac98246a67d66cc3"
dependencies = [
"cortex-m 0.6.2",
]
[[package]]
name = "proc-macro2"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "beae6331a816b1f65d04c45b078fd8e6c93e8071771f41b8163255bbd8d7c8fa"
dependencies = [
"unicode-xid",
]
[[package]]
name = "quote"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa563d17ecb180e500da1cfd2b028310ac758de548efdd203e18f283af693f37"
dependencies = [
"proc-macro2",
]
[[package]]
name = "r0"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2a38df5b15c8d5c7e8654189744d8e396bddc18ad48041a500ce52d6948941f"
[[package]]
name = "rand_core"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19"
[[package]]
name = "rtic-core"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8bd58a6949de8ff797a346a28d9f13f7b8f54fa61bb5e3cb0985a4efb497a5ef"
[[package]]
name = "rtic-syntax"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8152fcaa845720d61e6cc570548b89144c2c307f18a480bbd97e55e9f6eeff04"
dependencies = [
"indexmap",
"proc-macro2",
"syn",
]
[[package]]
name = "rustc_version"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a"
dependencies = [
"semver",
]
[[package]]
name = "semver"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403"
dependencies = [
"semver-parser",
]
[[package]]
name = "semver-parser"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3"
[[package]]
name = "smoltcp"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fe46639fd2ec79eadf8fe719f237a7a0bd4dac5d957f1ca5bbdbc1c3c39e53a"
dependencies = [
"bitflags",
"byteorder",
"log",
"managed",
]
[[package]]
name = "stable_deref_trait"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dba1a27d3efae4351c8051072d619e3ade2820635c3958d826bfea39d59b54c8"
[[package]]
name = "stm32f4"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11460b4de3a84f072e2cf6e76306c64d27f405a0e83bace0a726f555ddf4bf33"
dependencies = [
"bare-metal",
"cortex-m 0.6.2",
"vcell",
]
[[package]]
name = "stm32f4xx-hal"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b3a2f044469d1e3aff2cd02bee8b2724f3d5d91f3175e5d1ec99770320d16192"
dependencies = [
"bare-metal",
"cast",
"cortex-m 0.6.2",
"cortex-m-rt",
"embedded-hal",
"nb",
"rand_core",
"stm32f4",
"void",
]
[[package]]
name = "syn"
version = "1.0.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8d5d96e8cbb005d6959f119f773bfaebb5684296108fb32600c00cde305b2cd"
dependencies = [
"proc-macro2",
"quote",
"unicode-xid",
]
[[package]]
name = "typenum"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "373c8a200f9e67a0c95e62a4f52fbf80c23b4381c05a17845531982fa99e6b33"
[[package]]
name = "unicode-xid"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564"
[[package]]
name = "vcell"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "876e32dcadfe563a4289e994f7cb391197f362b6315dc45e8ba4aa6f564a4b3c"
[[package]]
name = "version_check"
version = "0.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5a972e5669d67ba988ce3dc826706fb0a8b01471c088cb0b6110b805cc36aed"
[[package]]
name = "void"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d"
[[package]]
name = "volatile-register"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d67cb4616d99b940db1d6bd28844ff97108b498a6ca850e5b6191a532063286"
dependencies = [
"vcell",
]

View File

@ -3,7 +3,7 @@ categories = ["embedded", "no-std"]
name = "enc424j600"
description = "Embbeded Rust Ethernet driver for ENC424J600 Ethernet controller with SPI interface, compatible with STM32F4xx"
authors = ["Harry Ho <hh@m-labs.hk>"]
version = "0.1.0"
version = "0.2.0"
keywords = ["ethernet", "eth", "enc424j600", "stm32", "stm32f4xx"]
repository = "https://git.m-labs.hk/M-Labs/ENC424J600"
edition = "2018"
@ -13,7 +13,7 @@ license = "BSD-2-Clause"
volatile-register = "0.2"
aligned = "0.3"
embedded-hal = "0.2"
smoltcp = { version = "0.6.0", default-features = false, features = ["proto-ipv4", "proto-ipv6", "socket-icmp", "socket-udp", "socket-tcp", "log", "verbose", "ethernet"], optional = true }
smoltcp = { version = "0.7.0", default-features = false, features = ["proto-ipv4", "proto-ipv6", "socket-icmp", "socket-udp", "socket-tcp", "log", "verbose", "ethernet"], optional = true }
# Optional dependencies for building examples
stm32f4xx-hal = { version = "0.8", optional = true }
cortex-m = { version = "0.5", optional = true }
@ -21,6 +21,9 @@ cortex-m-rt = { version = "0.6", optional = true }
cortex-m-rtic = { version = "0.5.3", optional = true }
panic-itm = { version = "0.4", optional = true }
log = { version = "0.4", optional = true }
# Optional dependencies for using NAL with somltcp and cortex_m
heapless = { version = "0.5.6", optional = true }
embedded-nal = { version = "0.1.0", optional = true }
[features]
smoltcp-phy = ["smoltcp"]
@ -31,6 +34,7 @@ smoltcp-phy-all = [
# Example-based features
tx_stm32f407 = ["stm32f4xx-hal/stm32f407", "cortex-m", "cortex-m-rtic", "panic-itm", "log"]
tcp_stm32f407 = ["stm32f4xx-hal/stm32f407", "cortex-m", "cortex-m-rt", "cortex-m-rtic", "smoltcp-phy-all", "smoltcp/log", "panic-itm", "log"]
nal = [ "smoltcp-phy", "heapless", "embedded-nal", "cortex-m", "cortex-m-rtic" ]
default = []
[[example]]

33
examples/delay.rs Normal file
View File

@ -0,0 +1,33 @@
use embedded_hal::blocking::delay::{DelayMs, DelayUs};
pub struct AsmDelay {
frequency_us: u32,
frequency_ms: u32,
}
impl AsmDelay {
pub fn new(freq: u32) -> AsmDelay {
AsmDelay {
frequency_us: (freq / 1_000_000),
frequency_ms: (freq / 1_000),
}
}
}
impl<U> DelayUs<U> for AsmDelay
where
U: Into<u32>,
{
fn delay_us(&mut self, us: U) {
cortex_m::asm::delay(self.frequency_us * us.into())
}
}
impl<U> DelayMs<U> for AsmDelay
where
U: Into<u32>,
{
fn delay_ms(&mut self, ms: U) {
cortex_m::asm::delay(self.frequency_ms * ms.into())
}
}

View File

@ -28,6 +28,9 @@ use smoltcp::socket::{SocketSet, TcpSocket, TcpSocketBuffer};
use core::str;
use core::fmt::Write;
mod delay;
use delay::AsmDelay;
/// Timer
use core::cell::RefCell;
use cortex_m::interrupt::Mutex;
@ -80,7 +83,9 @@ use stm32f4xx_hal::{
};
type BoosterSpiEth = enc424j600::SpiEth<
Spi<SPI1, (PA5<Alternate<AF5>>, PA6<Alternate<AF5>>, PA7<Alternate<AF5>>)>,
PA4<Output<PushPull>>>;
PA4<Output<PushPull>>,
AsmDelay
>;
pub struct NetStorage {
ip_addrs: [IpCidr; 1],
@ -99,8 +104,6 @@ static mut NET_STORE: NetStorage = NetStorage {
const APP: () = {
struct Resources {
eth_iface: EthernetInterface<
'static,
'static,
'static,
smoltcp_phy::SmoltcpDevice<BoosterSpiEth>>,
itm: ITM
@ -122,7 +125,8 @@ const APP: () = {
.pclk1(42.mhz())
.require_pll48clk()
.freeze();
let mut delay = Delay::new(c.core.SYST, clocks);
let asm_delay = AsmDelay::new(clocks.sysclk().0);
let mut hal_delay = Delay::new(c.core.SYST, clocks);
// Init ITM
let mut itm = c.core.ITM;
@ -142,7 +146,7 @@ const APP: () = {
// Map SPISEL: see Table 1, NIC100 Manual
let mut spisel = gpioa.pa1.into_push_pull_output();
spisel.set_high().unwrap();
delay.delay_ms(1_u32);
hal_delay.delay_ms(1_u32);
spisel.set_low().unwrap();
// Create SPI1 for HAL
@ -153,11 +157,11 @@ const APP: () = {
enc424j600::spi::interfaces::SPI_MODE,
Hertz(enc424j600::spi::interfaces::SPI_CLOCK_FREQ),
clocks);
enc424j600::SpiEth::new(spi_eth_port, spi1_nss)
enc424j600::SpiEth::new(spi_eth_port, spi1_nss, asm_delay)
};
// Init controller
match spi_eth.init_dev(&mut delay) {
match spi_eth.init_dev() {
Ok(_) => {
iprintln!(stim0, "Initializing Ethernet...")
}
@ -168,7 +172,7 @@ const APP: () = {
// Read MAC
let mut eth_mac_addr: [u8; 6] = [0; 6];
spi_eth.read_from_mac(&mut eth_mac_addr);
spi_eth.read_from_mac(&mut eth_mac_addr).unwrap();
for i in 0..6 {
let byte = eth_mac_addr[i];
match i {
@ -180,8 +184,8 @@ const APP: () = {
}
// Init Rx/Tx buffers
spi_eth.init_rxbuf();
spi_eth.init_txbuf();
spi_eth.init_rxbuf().unwrap();
spi_eth.init_txbuf().unwrap();
iprintln!(stim0, "Ethernet controller initialized");
// Init smoltcp interface
@ -205,7 +209,7 @@ const APP: () = {
// Setup SysTick after releasing SYST from Delay
// Reference to stm32-eth:examples/ip.rs
timer_setup(delay.free(), clocks);
timer_setup(hal_delay.free(), clocks);
iprintln!(stim0, "Timer initialized");
init::LateResources {

View File

@ -20,6 +20,9 @@ use stm32f4xx_hal::{
use enc424j600;
use enc424j600::EthController;
mod delay;
use delay::AsmDelay;
///
use stm32f4xx_hal::{
stm32::SPI1,
@ -30,7 +33,8 @@ use stm32f4xx_hal::{
};
type BoosterSpiEth = enc424j600::SpiEth<
Spi<SPI1, (PA5<Alternate<AF5>>, PA6<Alternate<AF5>>, PA7<Alternate<AF5>>)>,
PA4<Output<PushPull>>>;
PA4<Output<PushPull>>,
AsmDelay>;
#[rtic::app(device = stm32f4xx_hal::stm32, peripherals = true, monotonic = rtic::cyccnt::CYCCNT)]
const APP: () = {
@ -54,6 +58,7 @@ const APP: () = {
//.pclk2(64.mhz())
.require_pll48clk()
.freeze();
let asm_delay = AsmDelay::new(clocks.sysclk().0);
let mut delay = Delay::new(c.core.SYST, clocks);
// Init ITM
@ -82,11 +87,11 @@ const APP: () = {
enc424j600::spi::interfaces::SPI_MODE,
Hertz(enc424j600::spi::interfaces::SPI_CLOCK_FREQ),
clocks);
enc424j600::SpiEth::new(spi_eth_port, spi1_nss)
enc424j600::SpiEth::new(spi_eth_port, spi1_nss, asm_delay)
};
// Init
match spi_eth.init_dev(&mut delay) {
match spi_eth.init_dev() {
Ok(_) => {
iprintln!(stim0, "Initializing Ethernet...")
}
@ -97,7 +102,7 @@ const APP: () = {
// Read MAC
let mut eth_mac_addr: [u8; 6] = [0; 6];
spi_eth.read_from_mac(&mut eth_mac_addr);
spi_eth.read_from_mac(&mut eth_mac_addr).unwrap();
for i in 0..6 {
let byte = eth_mac_addr[i];
match i {
@ -109,8 +114,8 @@ const APP: () = {
}
// Init Rx/Tx buffers
spi_eth.init_rxbuf();
spi_eth.init_txbuf();
spi_eth.init_rxbuf().unwrap();
spi_eth.init_txbuf().unwrap();
iprintln!(stim0, "Ethernet controller initialized");
init::LateResources {
@ -152,7 +157,7 @@ const APP: () = {
_ => ()
};
}
c.resources.spi_eth.send_raw_packet(&eth_tx_packet);
c.resources.spi_eth.send_raw_packet(&eth_tx_packet).unwrap();
iprintln!(stim0, "Packet sent");
c.resources.delay.delay_ms(100_u32);
}

View File

@ -15,11 +15,14 @@ pub mod tx;
#[cfg(feature="smoltcp")]
pub mod smoltcp_phy;
#[cfg(all(feature="smoltcp", feature="nal"))]
pub mod nal;
/// Max raw frame array size
pub const RAW_FRAME_LENGTH_MAX: usize = 0x1000;
pub const RAW_FRAME_LENGTH_MAX: usize = 1518;
pub trait EthController {
fn init_dev(&mut self, delay: &mut impl DelayUs<u16>) -> Result<(), EthControllerError>;
fn init_dev(&mut self) -> Result<(), EthControllerError>;
fn init_rxbuf(&mut self) -> Result<(), EthControllerError>;
fn init_txbuf(&mut self) -> Result<(), EthControllerError>;
fn receive_next(&mut self, is_poll: bool) -> Result<rx::RxPacket, EthControllerError>;
@ -29,6 +32,7 @@ pub trait EthController {
}
/// TODO: Improve these error types
#[derive(Debug)]
pub enum EthControllerError {
SpiPortError,
GeneralError,
@ -44,17 +48,19 @@ impl From<spi::SpiPortError> for EthControllerError {
/// Ethernet controller using SPI interface
pub struct SpiEth<SPI: Transfer<u8>,
NSS: OutputPin> {
spi_port: spi::SpiPort<SPI, NSS>,
NSS: OutputPin,
Delay: DelayUs<u16>> {
spi_port: spi::SpiPort<SPI, NSS, Delay>,
rx_buf: rx::RxBuffer,
tx_buf: tx::TxBuffer
}
impl <SPI: Transfer<u8>,
NSS: OutputPin> SpiEth<SPI, NSS> {
pub fn new(spi: SPI, nss: NSS) -> Self {
NSS: OutputPin,
Delay: DelayUs<u16>> SpiEth<SPI, NSS, Delay> {
pub fn new(spi: SPI, nss: NSS, delay: Delay) -> Self {
SpiEth {
spi_port: spi::SpiPort::new(spi, nss),
spi_port: spi::SpiPort::new(spi, nss, delay),
rx_buf: rx::RxBuffer::new(),
tx_buf: tx::TxBuffer::new()
}
@ -62,8 +68,9 @@ impl <SPI: Transfer<u8>,
}
impl <SPI: Transfer<u8>,
NSS: OutputPin> EthController for SpiEth<SPI, NSS> {
fn init_dev(&mut self, delay: &mut impl DelayUs<u16>) -> Result<(), EthControllerError> {
NSS: OutputPin,
Delay: DelayUs<u16>> EthController for SpiEth<SPI, NSS, Delay> {
fn init_dev(&mut self) -> Result<(), EthControllerError> {
// Write 0x1234 to EUDAST
self.spi_port.write_reg_16b(spi::addrs::EUDAST, 0x1234)?;
// Verify that EUDAST is 0x1234
@ -80,14 +87,14 @@ impl <SPI: Transfer<u8>,
let econ2 = self.spi_port.read_reg_8b(spi::addrs::ECON2)?;
self.spi_port.write_reg_8b(spi::addrs::ECON2, 0x10 | (econ2 & 0b11101111))?;
// Wait for 25us
delay.delay_us(25_u16);
self.spi_port.delay_us(25_u16);
// Verify that EUDAST is 0x0000
eudast = self.spi_port.read_reg_16b(spi::addrs::EUDAST)?;
if eudast != 0x0000 {
return Err(EthControllerError::GeneralError)
}
// Wait for 256us
delay.delay_us(256_u16);
self.spi_port.delay_us(256_u16);
Ok(())
}

265
src/nal.rs Normal file
View File

@ -0,0 +1,265 @@
use core::cell::RefCell;
use heapless::{consts, Vec};
use embedded_nal as nal;
use nal::nb;
use smoltcp as net;
use embedded_hal::{
blocking::spi::Transfer,
blocking::delay::DelayUs,
digital::v2::OutputPin
};
use rtic::cyccnt::Instant;
#[derive(Debug)]
pub enum NetworkError {
NoSocket,
ConnectionFailure,
ReadFailure,
WriteFailure,
Unsupported,
}
pub type NetworkInterface<SPI, NSS, Delay> = net::iface::EthernetInterface<
'static,
crate::smoltcp_phy::SmoltcpDevice<
crate::SpiEth<SPI, NSS, Delay>
>,
>;
pub struct NetworkStack<'a, SPI, NSS, Delay>
where
SPI: 'static + Transfer<u8>,
NSS: 'static + OutputPin,
Delay: 'static + DelayUs<u16>
{
network_interface: RefCell<NetworkInterface<SPI, NSS, Delay>>,
sockets: RefCell<net::socket::SocketSet<'a>>,
next_port: RefCell<u16>,
unused_handles: RefCell<Vec<net::socket::SocketHandle, consts::U16>>,
time_ms: RefCell<u32>,
last_update_instant: RefCell<Option<Instant>>,
}
impl<'a, SPI, NSS, Delay> NetworkStack<'a, SPI, NSS, Delay>
where
SPI: Transfer<u8>,
NSS: OutputPin,
Delay: DelayUs<u16>
{
pub fn new(interface: NetworkInterface<SPI, NSS, Delay>, sockets: net::socket::SocketSet<'a>) -> Self {
let mut unused_handles: Vec<net::socket::SocketHandle, consts::U16> = Vec::new();
for socket in sockets.iter() {
unused_handles.push(socket.handle()).unwrap();
}
NetworkStack {
network_interface: RefCell::new(interface),
sockets: RefCell::new(sockets),
next_port: RefCell::new(49152),
unused_handles: RefCell::new(unused_handles),
time_ms: RefCell::new(0),
last_update_instant: RefCell::new(None),
}
}
// Include auto_time_update to allow Instant::now() to not be called
// Instant::now() is not safe to call in `init()` context
pub fn update(&self, auto_time_update: bool) -> bool {
if auto_time_update {
// Check if it is the first time the stack has updated the time itself
let now = match *self.last_update_instant.borrow() {
// If it is the first time, do not advance time
// Simply store the current instant to initiate time updating
None => Instant::now(),
// If it was updated before, advance time and update last_update_instant
Some(instant) => {
// Calculate elapsed time
let now = Instant::now();
let duration = now.duration_since(instant);
// Adjust duration into ms (note: decimal point truncated)
self.advance_time(duration.as_cycles() / 168_000);
now
}
};
self.last_update_instant.replace(Some(now));
}
match self.network_interface.borrow_mut().poll(
&mut self.sockets.borrow_mut(),
net::time::Instant::from_millis(*self.time_ms.borrow() as i64),
) {
Ok(changed) => changed == false,
Err(_e) => {
true
}
}
}
pub fn advance_time(&self, duration: u32) {
*self.time_ms.borrow_mut() += duration;
}
fn get_ephemeral_port(&self) -> u16 {
// Get the next ephemeral port
let current_port = self.next_port.borrow().clone();
let (next, wrap) = self.next_port.borrow().overflowing_add(1);
*self.next_port.borrow_mut() = if wrap { 49152 } else { next };
return current_port;
}
}
impl<'a, SPI, NSS, Delay> nal::TcpStack for NetworkStack<'a, SPI, NSS, Delay>
where
SPI: Transfer<u8>,
NSS: OutputPin,
Delay: DelayUs<u16>
{
type TcpSocket = net::socket::SocketHandle;
type Error = NetworkError;
fn open(&self, _mode: nal::Mode) -> Result<Self::TcpSocket, Self::Error> {
match self.unused_handles.borrow_mut().pop() {
Some(handle) => {
// Abort any active connections on the handle.
let mut sockets = self.sockets.borrow_mut();
let internal_socket: &mut net::socket::TcpSocket = &mut *sockets.get(handle);
internal_socket.abort();
Ok(handle)
}
None => Err(NetworkError::NoSocket),
}
}
// Ideally connect is only to be performed in `init()` of `main.rs`
// Calling `Instant::now()` of `rtic::cyccnt` would face correctness issue during `init()`
fn connect(
&self,
socket: Self::TcpSocket,
remote: nal::SocketAddr,
) -> Result<Self::TcpSocket, Self::Error> {
let address = {
let mut sockets = self.sockets.borrow_mut();
let internal_socket: &mut net::socket::TcpSocket = &mut *sockets.get(socket);
// If we're already in the process of connecting, ignore the request silently.
if internal_socket.is_open() {
return Ok(socket);
}
match remote.ip() {
nal::IpAddr::V4(addr) => {
let octets = addr.octets();
let address =
net::wire::Ipv4Address::new(octets[0], octets[1], octets[2], octets[3]);
internal_socket
.connect((address, remote.port()), self.get_ephemeral_port())
.map_err(|_| NetworkError::ConnectionFailure)?;
address
}
nal::IpAddr::V6(_) => {
// Match W5500 behavior: Reject the use of IPV6
return Err(NetworkError::Unsupported);
}
}
};
// Match W5500 behavior: Poll until connected
loop {
match self.is_connected(&socket) {
Ok(true) => break,
_ => {
let mut sockets = self.sockets.borrow_mut();
let internal_socket: &mut net::socket::TcpSocket = &mut *sockets.get(socket);
// If the connect got ACK->RST, it will end up in Closed TCP state
// Perform reconnection in this case
// In all other scenario, simply wait for TCP connection to be established
if internal_socket.state() == net::socket::TcpState::Closed {
internal_socket.close();
internal_socket
.connect((address, remote.port()), self.get_ephemeral_port())
.map_err(|_| NetworkError::ConnectionFailure)?;
}
}
}
// Avoid using Instant::now() and Advance time manually
self.update(false);
// Delay for 1 ms, minimum time unit of smoltcp
// TODO: Allow clock configuration, if supported in main
cortex_m::asm::delay(168_000_000 / 1_000);
{
self.advance_time(1);
}
}
Ok(socket)
}
fn is_connected(&self, socket: &Self::TcpSocket) -> Result<bool, Self::Error> {
let mut sockets = self.sockets.borrow_mut();
let socket: &mut net::socket::TcpSocket = &mut *sockets.get(*socket);
Ok(socket.may_send() && socket.may_recv())
}
fn write(&self, socket: &mut Self::TcpSocket, buffer: &[u8]) -> nb::Result<usize, Self::Error> {
let mut non_queued_bytes = &buffer[..];
while non_queued_bytes.len() != 0 {
let result = {
let mut sockets = self.sockets.borrow_mut();
let socket: &mut net::socket::TcpSocket = &mut *sockets.get(*socket);
let result = socket.send_slice(non_queued_bytes);
result
};
match result {
Ok(num_bytes) => {
// In case the buffer is filled up, push bytes into ethernet driver
if num_bytes != non_queued_bytes.len() {
self.update(true);
}
// Process the unwritten bytes again, if any
non_queued_bytes = &non_queued_bytes[num_bytes..]
}
Err(_) => return Err(nb::Error::Other(NetworkError::WriteFailure)),
}
}
Ok(buffer.len())
}
fn read(
&self,
socket: &mut Self::TcpSocket,
buffer: &mut [u8],
) -> nb::Result<usize, Self::Error> {
// Enqueue received bytes into the TCP socket buffer
self.update(true);
let mut sockets = self.sockets.borrow_mut();
let socket: &mut net::socket::TcpSocket = &mut *sockets.get(*socket);
let result = socket.recv_slice(buffer);
match result {
Ok(num_bytes) => Ok(num_bytes),
Err(_) => Err(nb::Error::Other(NetworkError::ReadFailure)),
}
}
fn close(&self, socket: Self::TcpSocket) -> Result<(), Self::Error> {
let mut sockets = self.sockets.borrow_mut();
let internal_socket: &mut net::socket::TcpSocket = &mut *sockets.get(socket);
internal_socket.close();
self.unused_handles.borrow_mut().push(socket).unwrap();
Ok(())
}
}

View File

@ -1,5 +1,5 @@
use embedded_hal::{
blocking::spi::Transfer,
blocking::{spi::Transfer, delay::DelayUs},
digital::v2::OutputPin,
};
@ -52,9 +52,11 @@ pub mod addrs {
/// Struct for SPI I/O interface on ENC424J600
/// Note: stm32f4xx_hal::spi's pins include: SCK, MISO, MOSI
pub struct SpiPort<SPI: Transfer<u8>,
NSS: OutputPin> {
NSS: OutputPin,
Delay: DelayUs<u16>> {
spi: SPI,
nss: NSS,
delay: Delay,
}
pub enum SpiPortError {
@ -63,14 +65,16 @@ pub enum SpiPortError {
#[allow(unused_must_use)]
impl <SPI: Transfer<u8>,
NSS: OutputPin> SpiPort<SPI, NSS> {
NSS: OutputPin,
Delay: DelayUs<u16>> SpiPort<SPI, NSS, Delay> {
// TODO: return as Result()
pub fn new(spi: SPI, mut nss: NSS) -> Self {
pub fn new(spi: SPI, mut nss: NSS, delay: Delay) -> Self {
nss.set_high();
SpiPort {
spi,
nss
nss,
delay
}
}
@ -115,6 +119,10 @@ impl <SPI: Transfer<u8>,
Ok(())
}
pub fn delay_us(&mut self, duration: u16) {
self.delay.delay_us(duration)
}
// TODO: Generalise transfer functions
// TODO: (Make data read/write as reference to array)
// Currently requires 1-byte addr, read/write data is only 1-byte
@ -131,13 +139,17 @@ impl <SPI: Transfer<u8>,
match self.spi.transfer(&mut buf) {
Ok(_) => {
// Disable chip select
self.delay_us(1);
self.nss.set_high();
self.delay_us(1);
Ok(buf[2])
},
// TODO: Maybe too naive?
Err(_) => {
// Disable chip select
self.delay_us(1);
self.nss.set_high();
self.delay_us(1);
Err(SpiPortError::TransferError)
}
}