Compare commits

...

3 Commits
master ... rtic

Author SHA1 Message Date
topquark12 7e314410a0 rustfmt, squash warnings, add bmp support 2022-11-02 17:18:33 +08:00
topquark12 dab73c3fec working ethernet 2022-11-01 11:16:55 +08:00
topquark12 ca0453df54 rtic implementation 2022-10-23 20:07:44 +08:00
15 changed files with 783 additions and 105 deletions

View File

@ -1,5 +1,5 @@
[target.thumbv7em-none-eabihf]
runner = "gdb -q -x openocd.gdb"
runner = "gdb -batch -q -x bmp.gdb"
rustflags = [
"-C", "link-arg=-Tlink.x",
]

2
.gitignore vendored
View File

@ -1,4 +1,4 @@
target/
result
.vscode*
*.jdebug*

327
Cargo.lock generated
View File

@ -2,6 +2,15 @@
# It is not intended for manual editing.
version = 3
[[package]]
name = "aho-corasick"
version = "0.7.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4f55bd91a0978cbfd91c457a164bab8b4001c833b7f323132c0a4e1922dd44e"
dependencies = [
"memchr",
]
[[package]]
name = "aligned"
version = "0.3.5"
@ -41,6 +50,15 @@ dependencies = [
"stable_deref_trait",
]
[[package]]
name = "atomic-polyfill"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c041a8d9751a520ee19656232a18971f18946a7900f1520ee4400002244dd89"
dependencies = [
"critical-section",
]
[[package]]
name = "autocfg"
version = "1.1.0"
@ -53,7 +71,7 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5deb64efa5bd81e31fcd1938615a6d98c82eafcbcd787162b6f63b91d6bac5b3"
dependencies = [
"rustc_version",
"rustc_version 0.2.3",
]
[[package]]
@ -62,6 +80,12 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fe8f5a8a398345e52358e18ff07cc17a568fbca5c6f73873d3a62056309603"
[[package]]
name = "bit_field"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dcb6dd1c2376d2e096796e234a70e17e94cc2d5d54ff8ce42b28cef1d0d359a4"
[[package]]
name = "bitfield"
version = "0.13.2"
@ -142,6 +166,34 @@ dependencies = [
"syn",
]
[[package]]
name = "cortex-m-rtic"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6b82f1c39acd6c3a35c2013b6110c20f5bc534522791fabadeed49ccada2dce"
dependencies = [
"bare-metal 1.0.0",
"cortex-m 0.7.6",
"cortex-m-rtic-macros",
"heapless",
"rtic-core",
"rtic-monotonic",
"version_check",
]
[[package]]
name = "cortex-m-rtic-macros"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e8e9645ef54bec1cf70ac33e9bf9566e6507ab5b41ae6baf3735662194e8607"
dependencies = [
"proc-macro-error",
"proc-macro2",
"quote",
"rtic-syntax",
"syn",
]
[[package]]
name = "cortex-m-semihosting"
version = "0.3.7"
@ -160,6 +212,47 @@ dependencies = [
"cortex-m 0.7.6",
]
[[package]]
name = "critical-section"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95da181745b56d4bd339530ec393508910c909c784e8962d15d722bacf0bcbcd"
dependencies = [
"bare-metal 1.0.0",
"cfg-if",
"cortex-m 0.7.6",
"riscv",
]
[[package]]
name = "defmt"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3a0ae7494d9bff013d7b89471f4c424356a71e9752e0c78abe7e6c608a16bb3"
dependencies = [
"bitflags",
"defmt-macros",
]
[[package]]
name = "defmt-macros"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8500cbe4cca056412efce4215a63d0bc20492942aeee695f23b624a53e0a6854"
dependencies = [
"defmt-parser",
"proc-macro-error",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "defmt-parser"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0db23d29972d99baa3de2ee2ae3f104c10564a6d05a346eb3f4c4f2c0525a06e"
[[package]]
name = "embedded-dma"
version = "0.2.0"
@ -250,6 +343,53 @@ dependencies = [
"version_check",
]
[[package]]
name = "hash32"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0c35f58762feb77d74ebe43bdbc3210f09be9fe6742234d573bacc26ed92b67"
dependencies = [
"byteorder",
]
[[package]]
name = "hashbrown"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
[[package]]
name = "heapless"
version = "0.7.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db04bc24a18b9ea980628ecf00e6c0264f3c1426dac36c00cb49b6fbad8b0743"
dependencies = [
"atomic-polyfill",
"hash32",
"rustc_version 0.4.0",
"spin",
"stable_deref_trait",
]
[[package]]
name = "ieee802_3_miim"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa6fe9a9feafccff3129a8ada9271d7f710a960be2b7c124583f7a3a5de3443e"
dependencies = [
"bitflags",
]
[[package]]
name = "indexmap"
version = "1.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10a35a97730320ffe8e2d410b5d3b69279b98d2c14bdb8b70ea89ecf7888d41e"
dependencies = [
"autocfg",
"hashbrown",
]
[[package]]
name = "kirdy"
version = "0.0.0"
@ -258,8 +398,10 @@ dependencies = [
"cortex-m 0.7.6",
"cortex-m-log",
"cortex-m-rt",
"cortex-m-rtic",
"cortex-m-semihosting 0.5.0",
"fugit",
"ieee802_3_miim",
"log",
"nb 1.0.0",
"num-traits",
@ -268,15 +410,22 @@ dependencies = [
"smoltcp",
"stm32-eth",
"stm32f4xx-hal",
"systick-monotonic",
"usb-device",
"usbd-serial",
]
[[package]]
name = "libc"
version = "0.2.135"
name = "lazy_static"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68783febc7782c6c5cb401fbda4de5a9898be1762314da0bb2c10ced61f18b0c"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libc"
version = "0.2.137"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc7fcc620a3bff7cdd7a365be3376c97191aeaccc2a603e600951e452615bf89"
[[package]]
name = "libm"
@ -284,6 +433,16 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "292a948cd991e376cf75541fe5b97a1081d713c618b4f1b9500f8844e49eb565"
[[package]]
name = "lock_api"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "435011366fe56583b16cf956f9df0095b405b82d76425bc8981c0e22e60ec4df"
dependencies = [
"autocfg",
"scopeguard",
]
[[package]]
name = "log"
version = "0.4.17"
@ -299,6 +458,12 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ca88d725a0a943b096803bd34e73a4437208b6077654cc4ecb2947a5f91618d"
[[package]]
name = "memchr"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
[[package]]
name = "nb"
version = "0.1.3"
@ -345,6 +510,30 @@ version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1de2e551fb905ac83f73f7aedf2f0cb4a0da7e35efa24a202a936269f1f18e1"
[[package]]
name = "proc-macro-error"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"
dependencies = [
"proc-macro-error-attr",
"proc-macro2",
"quote",
"syn",
"version_check",
]
[[package]]
name = "proc-macro-error-attr"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"
dependencies = [
"proc-macro2",
"quote",
"version_check",
]
[[package]]
name = "proc-macro2"
version = "1.0.47"
@ -369,6 +558,68 @@ version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
[[package]]
name = "regex"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c4eb3267174b8c6c2f654116623910a0fef09c4753f8dd83db29c48a0df988b"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.6.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a3f87b73ce11b1619a3c6332f45341e0047173771e8b8b73f87bfeefb7b56244"
[[package]]
name = "riscv"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6907ccdd7a31012b70faf2af85cd9e5ba97657cc3987c4f13f8e4d2c2a088aba"
dependencies = [
"bare-metal 1.0.0",
"bit_field",
"riscv-target",
]
[[package]]
name = "riscv-target"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88aa938cda42a0cf62a20cfe8d139ff1af20c2e681212b5b34adb5a58333f222"
dependencies = [
"lazy_static",
"regex",
]
[[package]]
name = "rtic-core"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9369355b04d06a3780ec0f51ea2d225624db777acbc60abd8ca4832da5c1a42"
[[package]]
name = "rtic-monotonic"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb8b0b822d1a366470b9cea83a1d4e788392db763539dc4ba022bcc787fece82"
[[package]]
name = "rtic-syntax"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ad3ae243dd8d0a1b064615f664d4fa7e63929939074c564cbe5efdc4c503065"
dependencies = [
"indexmap",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "rtt-target"
version = "0.3.1"
@ -385,9 +636,24 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a"
dependencies = [
"semver",
"semver 0.9.0",
]
[[package]]
name = "rustc_version"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366"
dependencies = [
"semver 1.0.14",
]
[[package]]
name = "scopeguard"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
[[package]]
name = "semver"
version = "0.9.0"
@ -397,6 +663,12 @@ dependencies = [
"semver-parser",
]
[[package]]
name = "semver"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e25dfac463d778e353db5be2449d1cce89bd6fd23c9f1ea21310ce6e5a1b29c4"
[[package]]
name = "semver-parser"
version = "0.7.0"
@ -411,10 +683,18 @@ checksum = "72165c4af59f5f19c7fb774b88b95660591b612380305b5f4503157341a9f7ee"
dependencies = [
"bitflags",
"byteorder",
"log",
"managed",
]
[[package]]
name = "spin"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f6002a767bff9e83f8eeecf883ecb8011875a21ae8da43bffb817a57e78cc09"
dependencies = [
"lock_api",
]
[[package]]
name = "stable_deref_trait"
version = "1.2.0"
@ -424,11 +704,13 @@ checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"
[[package]]
name = "stm32-eth"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09f6e20fd0f89dcf5637782090e654de814eecfb83c66ba41c2d64ce7f211b31"
source = "git+https://github.com/stm32-rs/stm32-eth#34243c92efbea19414fab27f34e282a2a4121190"
dependencies = [
"aligned 0.4.1",
"cortex-m 0.7.6",
"defmt",
"ieee802_3_miim",
"smoltcp",
"stm32f4xx-hal",
"volatile-register",
]
@ -463,6 +745,7 @@ dependencies = [
"fugit-timer",
"nb 1.0.0",
"rand_core",
"rtic-monotonic",
"stm32f4",
"synopsys-usb-otg",
"time",
@ -471,9 +754,9 @@ dependencies = [
[[package]]
name = "syn"
version = "1.0.102"
version = "1.0.103"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fcd952facd492f9be3ef0d0b7032a6e442ee9b361d4acc2b1d0c4aaa5f613a1"
checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d"
dependencies = [
"proc-macro2",
"quote",
@ -492,15 +775,33 @@ dependencies = [
]
[[package]]
name = "time"
version = "0.3.15"
name = "systick-monotonic"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d634a985c4d4238ec39cacaed2e7ae552fbd3c476b552c1deac3021b7d7eaf0c"
checksum = "57e71d8e4587d8f434b88b9aef901987f46164df813a3a1d6bdf3a58debf67f0"
dependencies = [
"cortex-m 0.7.6",
"fugit",
"rtic-monotonic",
]
[[package]]
name = "time"
version = "0.3.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fab5c8b9980850e06d92ddbe3ab839c062c801f3927c0fb8abd6fc8e918fbca"
dependencies = [
"libc",
"num_threads",
"time-core",
]
[[package]]
name = "time-core"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd"
[[package]]
name = "typenum"
version = "1.15.0"

View File

@ -22,17 +22,20 @@ log = "0.4.17"
bare-metal = "1"
nb = "1"
cortex-m-log = { version = "0.7.0", features = ["log-integration", "semihosting"] }
stm32f4xx-hal = { version = "0.13.2", features = ["rt", "stm32f407", "usb_fs"] }
stm32-eth = { version = "0.3.0", features = ["stm32f407"] }
smoltcp = { version = "0.8.0", default-features = false, features = ["proto-ipv4", "socket-tcp", "log", "medium-ethernet"] }
stm32f4xx-hal = { version = "0.13.2", features = ["rt", "stm32f407", "usb_fs", "rtic-monotonic"] }
stm32-eth = { git = "https://github.com/stm32-rs/stm32-eth", features = ["stm32f407", "smoltcp-phy", "smoltcp"] }
smoltcp = { version = "0.8.1", default-features = false, features = ["proto-ipv4", "socket-tcp", "medium-ethernet"] }
ieee802_3_miim = "0.7.2"
num-traits = { version = "0.2.15", default-features = false, features = ["libm"] }
usb-device = "0.2.9"
usbd-serial = "0.1.1"
fugit = "0.3.6"
rtt-target = { version = "0.3.1", features = ["cortex-m"] }
cortex-m-rtic = "1.0.0"
systick-monotonic = "1.0.0"
[features]
default = ["RTT"]
semihosting = ["cortex-m-log/semihosting"]
RTT = []

6
bmp.gdb Normal file
View File

@ -0,0 +1,6 @@
target extended-remote /dev/ttyBmpGdb
monitor swdp_scan
attach 1
load
compare-sections
kill

View File

@ -66,7 +66,7 @@
buildInputs = with pkgs; [
rustPlatform.rust.rustc
rustPlatform.rust.cargo
openocd dfu-util glibc
openocd dfu-util glibc picocom gdb
] ++ (with python3Packages; [
numpy matplotlib pyqtgraph
]);

View File

@ -1,5 +1,7 @@
use super::{gpio, sys_timer, usb};
use super::{delay, gpio, usb};
use crate::laser_diode::current_sources::*;
use crate::network::network;
use crate::network::network::EthernetPeripherals;
use fugit::ExtU32;
use log::info;
use stm32f4xx_hal::{
@ -8,13 +10,22 @@ use stm32f4xx_hal::{
time::MegaHertz,
watchdog::IndependentWatchdog,
};
use systick_monotonic::Systick;
#[cfg(not(feature = "semihosting"))]
const WATCHDOG_PERIOD: u32 = 1000;
#[cfg(feature = "semihosting")]
const WATCHDOG_PERIOD: u32 = 30000;
pub fn bootup(mut core_perif: CorePeripherals, perif: Peripherals) -> IndependentWatchdog {
pub fn bootup(
mut core_perif: CorePeripherals,
perif: Peripherals,
server_storage: &'static mut network::ServerStorage,
) -> (
IndependentWatchdog,
Systick<1000_u32>,
network::ServerHandle,
) {
core_perif.SCB.enable_icache();
core_perif.SCB.enable_dcache(&mut core_perif.CPUID);
@ -29,21 +40,29 @@ pub fn bootup(mut core_perif: CorePeripherals, perif: Peripherals) -> Independen
.pclk2(MegaHertz::from_raw(64).convert())
.freeze();
sys_timer::setup(core_perif.SYST, clocks);
let systick = Systick::new(core_perif.SYST, clocks.hclk().to_Hz());
let delay = delay::AsmDelay::new(clocks.sysclk().to_Hz());
let (_eth_pins, usb, current_source_phy) = gpio::setup(
let (eth_pins, usb, current_source_phy, mdio, mdc) = gpio::setup(
clocks,
perif.GPIOA,
perif.GPIOB,
perif.GPIOC,
perif.GPIOD,
perif.GPIOG,
perif.SPI2,
perif.OTG_FS_GLOBAL,
perif.OTG_FS_DEVICE,
perif.OTG_FS_PWRCLK,
);
let ethernet = EthernetPeripherals {
dma: perif.ETHERNET_DMA,
mac: perif.ETHERNET_MAC,
mmc: perif.ETHERNET_MMC,
};
let server = network::ServerHandle::new(eth_pins, ethernet, clocks, server_storage, mdio, mdc);
// let (serverhandle, iface) = network::setup(eth_pins, ethernet, clocks);
usb::State::setup(usb);
let mut laser = CurrentSource {
@ -53,7 +72,7 @@ pub fn bootup(mut core_perif: CorePeripherals, perif: Peripherals) -> Independen
},
};
laser.setup();
laser.setup(delay);
laser.set_current(0.1).unwrap();
let mut wd = IndependentWatchdog::new(perif.IWDG);
@ -62,5 +81,5 @@ pub fn bootup(mut core_perif: CorePeripherals, perif: Peripherals) -> Independen
info!("Kirdy setup complete");
wd
(wd, systick, server)
}

46
src/device/delay.rs Normal file
View File

@ -0,0 +1,46 @@
//! Basic blocking delay
//!
//! This module provides a basic asm-based blocking delay.
//! Borrowed from our good friends at Quartiq:
//! https://github.com/quartiq/stabilizer/blob/master/src/hardware/delay.rs
//!
use stm32f4xx_hal::hal::blocking::delay::{DelayMs, DelayUs};
// use stm32f4xx_hal::block;
/// A basic delay implementation.
pub struct AsmDelay {
frequency_us: u32,
frequency_ms: u32,
}
impl AsmDelay {
/// Create a new delay.
///
/// # Args
/// * `freq` - The CPU core frequency.
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

@ -2,16 +2,15 @@ use crate::laser_diode::current_sources::*;
use fugit::RateExtU32;
use stm32_eth::EthPins;
use stm32f4xx_hal::{
gpio::{gpioa::*, gpiob::*, gpioc::*, gpiog::*, GpioExt, Input},
gpio::{Alternate, GpioExt, Speed},
otg_fs::USB,
pac::{GPIOA, GPIOB, GPIOC, GPIOD, GPIOG, OTG_FS_DEVICE, OTG_FS_GLOBAL, OTG_FS_PWRCLK, SPI2},
pac::{GPIOA, GPIOB, GPIOC, GPIOD, OTG_FS_DEVICE, OTG_FS_GLOBAL, OTG_FS_PWRCLK, SPI2},
rcc::Clocks,
spi,
spi::{NoMiso, Spi},
};
pub type EthernetPins =
EthPins<PA1<Input>, PA7<Input>, PB11<Input>, PG13<Input>, PB13<Input>, PC4<Input>, PC5<Input>>;
use crate::network::network::EthernetPins;
pub fn setup(
clocks: Clocks,
@ -19,7 +18,6 @@ pub fn setup(
gpiob: GPIOB,
gpioc: GPIOC,
gpiod: GPIOD,
gpiog: GPIOG,
spi2: SPI2,
otg_fs_global: OTG_FS_GLOBAL,
otg_fs_device: OTG_FS_DEVICE,
@ -28,14 +26,14 @@ pub fn setup(
EthernetPins,
USB,
CurrentSourcePhyConstruct<CurrentSourcePhyCh0>,
// photo_diode_phy,
// thermostat_phy
stm32f4xx_hal::gpio::PA2<Alternate<11>>,
stm32f4xx_hal::gpio::PC1<Alternate<11>>, // photo_diode_phy,
// thermostat_phy
) {
let gpioa = gpioa.split();
let gpiob = gpiob.split();
let gpioc = gpioc.split();
let gpiod = gpiod.split();
let gpiog = gpiog.split();
let usb = USB {
usb_global: otg_fs_global,
@ -50,12 +48,17 @@ pub fn setup(
ref_clk: gpioa.pa1,
crs: gpioa.pa7,
tx_en: gpiob.pb11,
tx_d0: gpiog.pg13,
tx_d0: gpiob.pb12,
tx_d1: gpiob.pb13,
rx_d0: gpioc.pc4,
rx_d1: gpioc.pc5,
};
let mut mdio = gpioa.pa2.into_alternate::<11>();
let mut mdc = gpioc.pc1.into_alternate::<11>();
mdio.set_speed(Speed::VeryHigh);
mdc.set_speed(Speed::VeryHigh);
let current_source_phy = CurrentSourcePhyConstruct {
max5719_spi: Spi::new(
spi2,
@ -77,5 +80,5 @@ pub fn setup(
current_source_short: gpioa.pa4.into_push_pull_output(),
};
(eth_pins, usb, current_source_phy)
(eth_pins, usb, current_source_phy, mdio, mdc)
}

View File

@ -1,6 +1,6 @@
pub mod boot;
pub mod delay;
pub mod gpio;
pub mod log_setup;
pub mod rtt_logger;
pub mod sys_timer;
pub mod usb;

View File

@ -1,43 +0,0 @@
use core::cell::RefCell;
use core::ops::Deref;
use cortex_m::interrupt::Mutex;
use cortex_m::peripheral::syst::SystClkSource;
use cortex_m_rt::exception;
use stm32f4xx_hal::{pac::SYST, rcc::Clocks};
/// Rate in Hz
const TIMER_RATE: u32 = 1000;
/// Interval duration in milliseconds
const TIMER_DELTA: u32 = 1000 / TIMER_RATE;
/// Elapsed time in milliseconds
static TIMER_MS: Mutex<RefCell<u32>> = Mutex::new(RefCell::new(0));
/// Setup SysTick exception
pub fn setup(mut syst: SYST, clocks: Clocks) {
syst.set_clock_source(SystClkSource::Core);
syst.set_reload(clocks.hclk().to_Hz() / TIMER_RATE - 1);
syst.enable_counter();
syst.enable_interrupt();
}
/// SysTick exception (Timer)
#[exception]
fn SysTick() {
cortex_m::interrupt::free(|cs| {
*TIMER_MS.borrow(cs).borrow_mut() += TIMER_DELTA;
});
}
/// Obtain current time in milliseconds
pub fn now() -> u32 {
cortex_m::interrupt::free(|cs| *TIMER_MS.borrow(cs).borrow().deref())
}
/// block for `amount` milliseconds
pub fn sleep(amount: u32) {
if amount == 0 {
return;
}
let start = now();
while now() - start <= amount - 1 {}
}

View File

@ -1,3 +1,4 @@
use cortex_m::prelude::_embedded_hal_blocking_delay_DelayMs;
use stm32f4xx_hal::{
gpio::{gpioa::*, gpiob::*, gpiod::*, Alternate, Output, PushPull, PD9},
hal::{blocking::spi::Write, digital::v2::OutputPin},
@ -5,7 +6,6 @@ use stm32f4xx_hal::{
spi::{NoMiso, Spi, TransferModeNormal},
};
use crate::device::sys_timer::sleep;
pub trait CurrentSourcePhy {
type CurrentSourceLdoEn: OutputPin;
type CurrentSourceShort: OutputPin;
@ -40,14 +40,16 @@ impl CurrentSourcePhy for CurrentSourcePhyCh0 {
Spi<SPI2, (PB10<Alternate<5>>, NoMiso, PB15<Alternate<5>>), TransferModeNormal>;
}
use crate::device::delay;
impl<C: CurrentSourcePhy> CurrentSource<C> {
pub fn setup(&mut self) {
pub fn setup(&mut self, mut delay: delay::AsmDelay) {
let _ = self.phy.max5719_load.set_high();
let _ = self.phy.max5719_cs.set_high();
let _ = self.phy.current_source_ldo_en.set_high();
sleep(10_u32);
delay.delay_ms(10_u32);
let _ = self.phy.current_source_short.set_high();
sleep(10_u32);
delay.delay_ms(10_u32);
}
pub fn set_current(

View File

@ -1,20 +1,14 @@
#![no_main]
#![no_std]
use cortex_m_rt::entry;
use log::info;
use stm32f4xx_hal::pac::{CorePeripherals, Peripherals};
use rtic::app;
mod device;
mod laser_diode;
use device::{boot::bootup, log_setup, sys_timer};
mod network;
// If RTT is used, print panic info through RTT
#[cfg(feature = "RTT")]
use {
core::panic::PanicInfo,
rtt_target::rprintln,
};
use {core::panic::PanicInfo, rtt_target::rprintln};
#[cfg(feature = "RTT")]
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
@ -25,20 +19,70 @@ fn panic(info: &PanicInfo) -> ! {
#[cfg(not(feature = "RTT"))]
use panic_halt as _;
#[entry]
fn main() -> ! {
log_setup::init_log();
info!("Kirdy init");
// #[entry]
#[app(device = stm32f4xx_hal::pac, peripherals = true, dispatchers = [TIM8_CC, TIM8_BRK_TIM12])]
mod app {
let core_perif = CorePeripherals::take().unwrap();
let perif = Peripherals::take().unwrap();
use crate::device::{boot::bootup, log_setup};
use crate::network::network;
use fugit::ExtU32;
use log::info;
use stm32f4xx_hal::watchdog::IndependentWatchdog;
use systick_monotonic::Systick;
let mut wd = bootup(core_perif, perif);
#[monotonic(binds = SysTick, default = true)]
type SystickTimer = Systick<1000>;
loop {
#[shared]
struct Shared {}
#[local]
struct Local {
wd: IndependentWatchdog,
// server_storage: network::network::ServerStorage::new(),
server_handle: network::ServerHandle,
}
#[init( local = [server_storage: network::ServerStorage = network::ServerStorage::new()] )]
fn init(cx: init::Context) -> (Shared, Local, init::Monotonics) {
log_setup::init_log();
info!("Kirdy init");
let core_perif = cx.core;
let perif = cx.device;
let server_storage = cx.local.server_storage;
let (wd, systick, server_handle) = bootup(core_perif, perif, server_storage);
wd_feed::spawn().unwrap();
// server_poll::spawn().unwrap();
(
Shared {},
Local { wd, server_handle },
init::Monotonics(systick),
)
}
#[task(priority = 5, local = [wd])]
fn wd_feed(cx: wd_feed::Context) {
let start = monotonics::now();
let wd = cx.local.wd;
// info!("feed wd");
wd.feed();
info!("looping");
sys_timer::sleep(10);
wd_feed::spawn_at(start + 10_u32.millis()).unwrap();
}
#[task(binds = ETH, priority = 2, local = [server_handle, data: [u8; 512] = [0u8; 512]])]
fn server_poll(cx: server_poll::Context) {
let data = cx.local.data;
let server_handle = cx.local.server_handle;
server_handle.poll(data);
// server_poll::spawn_at(start + 10_u32.millis()).unwrap();
}
#[idle]
fn idle(_: idle::Context) -> ! {
loop {
cortex_m::asm::nop();
}
}
}

1
src/network/mod.rs Normal file
View File

@ -0,0 +1 @@
pub mod network;

296
src/network/network.rs Normal file
View File

@ -0,0 +1,296 @@
// Modified by Wong Tat Hang (aw@m-labs.hk), with original source from
// https://github.com/stm32-rs/stm32-eth/blob/master/examples/rtic-echo.rs
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use log::{info, warn};
use smoltcp::{
iface::{
Interface, InterfaceBuilder, Neighbor, NeighborCache, Route, SocketHandle, SocketStorage,
},
socket::{TcpSocket, TcpSocketBuffer, TcpState},
wire::{EthernetAddress, IpAddress, IpCidr, Ipv4Address, Ipv4Cidr},
};
use stm32_eth::stm32::{ETHERNET_DMA, ETHERNET_MAC, ETHERNET_MMC};
use stm32_eth::*;
use stm32f4xx_hal::{
gpio::{gpioa::*, gpiob::*, gpioc::*, Alternate, Input},
rcc::Clocks,
};
use crate::app::monotonics;
pub type EthernetPins =
EthPins<PA1<Input>, PA7<Input>, PB11<Input>, PB12<Input>, PB13<Input>, PC4<Input>, PC5<Input>>;
pub type EthInterface = Interface<'static, &'static mut EthernetDMA<'static, 'static>>;
const IPV4_ADDR: (u8, u8, u8, u8) = (192, 168, 1, 132);
const ADDRESS: (IpAddress, u16) = (
IpAddress::Ipv4(Ipv4Address::new(
IPV4_ADDR.0,
IPV4_ADDR.1,
IPV4_ADDR.2,
IPV4_ADDR.3,
)),
1337,
);
const MAC: [u8; 6] = [0x02, 0x5f, 0x25, 0x37, 0x93, 0x0e];
pub struct EthernetPeripherals {
pub dma: ETHERNET_DMA,
pub mac: ETHERNET_MAC,
pub mmc: ETHERNET_MMC,
}
pub struct ServerHandle {
// storage: &'static mut ServerStorage,
socket_handle: SocketHandle,
iface: EthInterface,
}
pub struct ServerStorage {
rx_ring: [RxRingEntry; 8],
tx_ring: [TxRingEntry; 2],
storage: NetworkStorage,
dma: core::mem::MaybeUninit<EthernetDMA<'static, 'static>>,
}
impl ServerStorage {
pub const fn new() -> Self {
ServerStorage {
rx_ring: [
RxRingEntry::new(),
RxRingEntry::new(),
RxRingEntry::new(),
RxRingEntry::new(),
RxRingEntry::new(),
RxRingEntry::new(),
RxRingEntry::new(),
RxRingEntry::new(),
],
tx_ring: [TxRingEntry::new(), TxRingEntry::new()],
storage: NetworkStorage::new(),
dma: core::mem::MaybeUninit::uninit(),
}
}
}
/// All storage required for networking
pub struct NetworkStorage {
pub ip_addrs: [IpCidr; 1],
pub sockets: [SocketStorage<'static>; 1],
pub tcp_socket_storage: TcpSocketStorage,
pub neighbor_cache: [Option<(IpAddress, Neighbor)>; 8],
pub routes_cache: [Option<(IpCidr, Route)>; 8],
}
impl NetworkStorage {
const IP_INIT: IpCidr = IpCidr::Ipv4(Ipv4Cidr::new(
Ipv4Address::new(IPV4_ADDR.0, IPV4_ADDR.1, IPV4_ADDR.2, IPV4_ADDR.3),
24,
));
pub const fn new() -> Self {
NetworkStorage {
ip_addrs: [Self::IP_INIT],
neighbor_cache: [None; 8],
routes_cache: [None; 8],
sockets: [SocketStorage::EMPTY; 1],
tcp_socket_storage: TcpSocketStorage::new(),
}
}
}
/// Storage of TCP sockets
#[derive(Copy, Clone)]
pub struct TcpSocketStorage {
rx_storage: [u8; 2048],
tx_storage: [u8; 2048],
}
impl TcpSocketStorage {
const fn new() -> Self {
Self {
rx_storage: [0; 2048],
tx_storage: [0; 2048],
}
}
}
fn now_fn() -> smoltcp::time::Instant {
let time = monotonics::now().duration_since_epoch().to_millis();
smoltcp::time::Instant::from_millis(time as i64)
}
impl ServerHandle {
pub fn new(
eth_pins: EthernetPins,
ethernet: EthernetPeripherals,
clocks: Clocks,
storage: &'static mut ServerStorage,
mdio: stm32f4xx_hal::gpio::PA2<Alternate<11>>,
mdc: stm32f4xx_hal::gpio::PC1<Alternate<11>>,
) -> ServerHandle {
let (dma, mac) = stm32_eth::new_with_mii(
ethernet.mac,
ethernet.mmc,
ethernet.dma,
&mut storage.rx_ring[..],
&mut storage.tx_ring[..],
clocks,
eth_pins,
mdio,
mdc,
)
.unwrap();
let mut routes = smoltcp::iface::Routes::new(&mut storage.storage.routes_cache[..]);
routes
.add_default_ipv4_route(Ipv4Address::new(192, 168, 1, 1))
.ok();
let dma = storage.dma.write(dma);
dma.enable_interrupt();
let rx_buffer =
TcpSocketBuffer::new(&mut storage.storage.tcp_socket_storage.rx_storage[..]);
let tx_buffer =
TcpSocketBuffer::new(&mut storage.storage.tcp_socket_storage.tx_storage[..]);
let socket = TcpSocket::new(rx_buffer, tx_buffer);
let mut iface = InterfaceBuilder::new(dma, &mut storage.storage.sockets[..])
.hardware_addr(EthernetAddress(MAC).into())
.ip_addrs(&mut storage.storage.ip_addrs[..])
.neighbor_cache(NeighborCache::new(&mut storage.storage.neighbor_cache[..]))
.routes(routes)
.finalize();
let mut server = ServerHandle {
socket_handle: iface.add_socket(socket),
iface: iface,
};
let socket = server.iface.get_socket::<TcpSocket>(server.socket_handle);
socket.listen(ADDRESS).ok();
server.iface.poll(now_fn()).ok();
if let Ok(mut phy) = EthernetPhy::from_miim(mac, 0) {
info!(
"Resetting PHY as an extra step. Type: {}",
phy.ident_string()
);
phy.phy_init();
} else {
info!("Not resetting unsupported PHY.");
}
server
}
pub fn poll(&mut self, buffer: &mut [u8]) {
self.iface.poll(now_fn()).ok();
let socket = self.iface.get_socket::<TcpSocket>(self.socket_handle);
if let Ok(recv_bytes) = socket.recv_slice(buffer) {
if recv_bytes > 0 {
socket.send_slice(&buffer[..recv_bytes]).ok();
info!("Echoed {} bytes.", recv_bytes);
}
}
if !socket.is_listening() && !socket.is_open() || socket.state() == TcpState::CloseWait {
socket.abort();
socket.listen(ADDRESS).ok();
warn!("Disconnected... Reopening listening socket.");
}
self.iface.poll(now_fn()).ok();
}
}
use ieee802_3_miim::{
phy::{
lan87xxa::{LAN8720A, LAN8742A},
BarePhy, KSZ8081R,
},
Miim, Pause, Phy,
};
/// An ethernet PHY
pub enum EthernetPhy<M: Miim> {
/// LAN8720A
LAN8720A(LAN8720A<M>),
/// LAN8742A
LAN8742A(LAN8742A<M>),
/// KSZ8081R
KSZ8081R(KSZ8081R<M>),
}
impl<M: Miim> Phy<M> for EthernetPhy<M> {
fn best_supported_advertisement(&self) -> ieee802_3_miim::AutoNegotiationAdvertisement {
unimplemented!()
}
fn get_miim(&mut self) -> &mut M {
match self {
EthernetPhy::LAN8720A(phy) => phy.get_miim(),
EthernetPhy::LAN8742A(phy) => phy.get_miim(),
EthernetPhy::KSZ8081R(phy) => phy.get_miim(),
}
}
fn get_phy_addr(&self) -> u8 {
match self {
EthernetPhy::LAN8720A(phy) => phy.get_phy_addr(),
EthernetPhy::LAN8742A(phy) => phy.get_phy_addr(),
EthernetPhy::KSZ8081R(phy) => phy.get_phy_addr(),
}
}
}
impl<M: Miim> EthernetPhy<M> {
/// Attempt to create one of the known PHYs from the given
/// MIIM.
///
/// Returns an error if the PHY does not support the extended register
/// set, or if the PHY's identifier does not correspond to a known PHY.
pub fn from_miim(miim: M, phy_addr: u8) -> Result<Self, ()> {
let mut bare = BarePhy::new(miim, phy_addr, Pause::NoPause);
let phy_ident = bare.phy_ident().ok_or(())?;
let miim = bare.release();
match phy_ident & 0xFFFFFFF0 {
0x0007C0F0 => Ok(Self::LAN8720A(LAN8720A::new(miim, phy_addr))),
0x0007C130 => Ok(Self::LAN8742A(LAN8742A::new(miim, phy_addr))),
0x00221560 => Ok(Self::KSZ8081R(KSZ8081R::new(miim, phy_addr))),
_ => Err(()),
}
}
/// Get a string describing the type of PHY
pub const fn ident_string(&self) -> &'static str {
match self {
EthernetPhy::LAN8720A(_) => "LAN8720A",
EthernetPhy::LAN8742A(_) => "LAN8742A",
EthernetPhy::KSZ8081R(_) => "KSZ8081R",
}
}
/// Initialize the PHY
pub fn phy_init(&mut self) {
match self {
EthernetPhy::LAN8720A(phy) => phy.phy_init(),
EthernetPhy::LAN8742A(phy) => phy.phy_init(),
EthernetPhy::KSZ8081R(phy) => {
phy.set_autonegotiation_advertisement(phy.best_supported_advertisement());
}
}
}
}