eth ex: support tcp client

This commit is contained in:
occheung 2020-09-10 14:35:11 +08:00
parent 05b056d273
commit b954449ceb
4 changed files with 255 additions and 357 deletions

View File

@ -4,8 +4,8 @@
// extern crate cortex_m_rt as rt; // extern crate cortex_m_rt as rt;
use core::sync::atomic::{AtomicU32, Ordering}; use core::sync::atomic::{AtomicU32, Ordering};
//#[macro_use] #[macro_use]
//extern crate log; extern crate log;
// extern crate cortex_m; // extern crate cortex_m;
use panic_semihosting as _; use panic_semihosting as _;
@ -33,8 +33,6 @@ use stm32h7xx_hal::rcc::CoreClocks;
use stm32h7xx_hal::{pac, prelude::*, spi, stm32, stm32::interrupt}; use stm32h7xx_hal::{pac, prelude::*, spi, stm32, stm32::interrupt};
use Speed::*; use Speed::*;
use libm::round;
use core::{ use core::{
str, str,
fmt::Write fmt::Write
@ -48,6 +46,7 @@ use smoltcp::iface::{NeighborCache, EthernetInterfaceBuilder, Routes};
use smoltcp::socket::SocketSet; use smoltcp::socket::SocketSet;
use smoltcp::socket::{SocketHandle, TcpSocket, TcpSocketBuffer}; use smoltcp::socket::{SocketHandle, TcpSocket, TcpSocketBuffer};
use smoltcp::time::{Duration, Instant}; use smoltcp::time::{Duration, Instant};
// use smoltcp::log;
// Use embedded-nal to access smoltcp // Use embedded-nal to access smoltcp
use embedded_nal::TcpStack; use embedded_nal::TcpStack;
@ -101,6 +100,9 @@ use scpi::{
scpi_system, scpi_system,
}; };
#[path = "util/logger.rs"]
mod logger;
/// Configure SYSTICK for 1ms timebase /// Configure SYSTICK for 1ms timebase
fn systick_init(syst: &mut stm32::SYST, clocks: CoreClocks) { fn systick_init(syst: &mut stm32::SYST, clocks: CoreClocks) {
let c_ck_mhz = clocks.c_ck().0 / 1_000_000; let c_ck_mhz = clocks.c_ck().0 / 1_000_000;
@ -138,6 +140,8 @@ const BUFFER_SIZE: usize = 2048;
#[entry] #[entry]
fn main() -> ! { fn main() -> ! {
logger::semihosting_init();
let mut cp = cortex_m::Peripherals::take().unwrap(); let mut cp = cortex_m::Peripherals::take().unwrap();
let dp = pac::Peripherals::take().unwrap(); let dp = pac::Peripherals::take().unwrap();
@ -163,8 +167,6 @@ fn main() -> ! {
// Initialise system... // Initialise system...
cp.SCB.invalidate_icache(); cp.SCB.invalidate_icache();
cp.SCB.enable_icache(); cp.SCB.enable_icache();
// TODO: ETH DMA coherence issues
// cp.SCB.enable_dcache(&mut cp.CPUID);
cp.DWT.enable_cycle_counter(); cp.DWT.enable_cycle_counter();
// Initialise IO... // Initialise IO...
@ -175,21 +177,15 @@ fn main() -> ! {
let gpioe = dp.GPIOE.split(ccdr.peripheral.GPIOE); let gpioe = dp.GPIOE.split(ccdr.peripheral.GPIOE);
let gpiof = dp.GPIOF.split(ccdr.peripheral.GPIOF); let gpiof = dp.GPIOF.split(ccdr.peripheral.GPIOF);
let gpiog = dp.GPIOG.split(ccdr.peripheral.GPIOG); let gpiog = dp.GPIOG.split(ccdr.peripheral.GPIOG);
// let mut link_led = gpiob.pb0.into_push_pull_output(); // LED1, green
// let mut status_led = gpioe.pe1.into_push_pull_output(); // LD2, yellow
// let mut listen_led = gpiob.pb14.into_push_pull_output(); // LD3, red
// link_led.set_low().ok();
// status_led.set_low().ok();
// listen_led.set_low().ok();
// Setup CDONE for checking // Setup CDONE for checking
let fpga_cdone = gpiod.pd15.into_pull_up_input(); let fpga_cdone = gpiod.pd15.into_pull_up_input();
match fpga_cdone.is_high() { match fpga_cdone.is_high() {
Ok(true) => hprintln!("FPGA is ready."), Ok(true) => debug!("FPGA is ready."),
Ok(_) => hprintln!("FPGA is in reset state."), Ok(_) => debug!("FPGA is in reset state."),
Err(_) => hprintln!("Error: Cannot read C_DONE"), Err(_) => debug!("Error: Cannot read C_DONE"),
}.unwrap(); };
// Setup Urukul // Setup Urukul
/* /*
@ -279,18 +275,11 @@ fn main() -> ! {
let mut neighbor_storage = [None; 16]; let mut neighbor_storage = [None; 16];
let neighbor_cache = NeighborCache::new(&mut neighbor_storage[..]); let neighbor_cache = NeighborCache::new(&mut neighbor_storage[..]);
// Routes
let default_v4_gw = Ipv4Address::new(192, 168, 1, 1);
let mut routes_storage = [None; 8];
let mut routes = Routes::new(&mut routes_storage[..]);
routes.add_default_ipv4_route(default_v4_gw).unwrap();
// Device? _eth_dma, as it implements phy::device // Device? _eth_dma, as it implements phy::device
let mut iface = EthernetInterfaceBuilder::new(_eth_dma) let mut iface = EthernetInterfaceBuilder::new(_eth_dma)
.ethernet_addr(mac_addr) .ethernet_addr(mac_addr)
.neighbor_cache(neighbor_cache) .neighbor_cache(neighbor_cache)
.ip_addrs(&mut ip_addrs[..]) .ip_addrs(&mut ip_addrs[..])
.routes(routes)
.finalize(); .finalize();
// SCPI configs // SCPI configs
@ -354,9 +343,6 @@ fn main() -> ! {
let mut eth_up = false; let mut eth_up = false;
// Record activeness of silent socket, init as false
let mut silent_socket_active = false;
loop { loop {
let _time = TIME.load(Ordering::Relaxed); let _time = TIME.load(Ordering::Relaxed);
let eth_last = eth_up; let eth_last = eth_up;
@ -388,9 +374,9 @@ fn main() -> ! {
} }
let result = context.run(data, &mut buf); let result = context.run(data, &mut buf);
if let Err(err) = result { if let Err(err) = result {
writeln!(socket, "{}", str::from_utf8(err.get_message()).unwrap()); writeln!(socket, "{}", str::from_utf8(err.get_message()).unwrap()).unwrap();
} else { } else {
write!(socket, "{}", str::from_utf8(buf.as_slice()).unwrap()); write!(socket, "{}", str::from_utf8(buf.as_slice()).unwrap()).unwrap();
} }
} }
} }

View File

@ -1,6 +1,9 @@
#![no_std] #![no_std]
#![no_main] #![no_main]
#[macro_use]
extern crate log;
use smoltcp as net; use smoltcp as net;
use stm32h7xx_hal::ethernet; use stm32h7xx_hal::ethernet;
use stm32h7xx_hal::{gpio::Speed, prelude::*, spi, pac}; use stm32h7xx_hal::{gpio::Speed, prelude::*, spi, pac};
@ -18,7 +21,7 @@ use cortex_m_rt::{
}; };
use cortex_m_semihosting::hprintln; use cortex_m_semihosting::hprintln;
use panic_halt as _; // use panic_halt as _;
use rtic::cyccnt::{Instant, U32Ext}; use rtic::cyccnt::{Instant, U32Ext};
@ -31,6 +34,9 @@ use firmware::nal_tcp_client::{NetworkStack, NetStorage, NetworkInterface};
use firmware::{Urukul}; use firmware::{Urukul};
use firmware::cpld::{CPLD}; use firmware::cpld::{CPLD};
#[path = "util/logger.rs"]
mod logger;
static mut NET_STORE: NetStorage = NetStorage { static mut NET_STORE: NetStorage = NetStorage {
// Placeholder for the real IP address, which is initialized at runtime. // Placeholder for the real IP address, which is initialized at runtime.
ip_addrs: [net::wire::IpCidr::Ipv6( ip_addrs: [net::wire::IpCidr::Ipv6(
@ -61,6 +67,8 @@ macro_rules! add_socket {
#[entry] #[entry]
fn main() -> ! { fn main() -> ! {
// logger::semihosting_init();
let mut cp = cortex_m::Peripherals::take().unwrap(); let mut cp = cortex_m::Peripherals::take().unwrap();
let dp = pac::Peripherals::take().unwrap(); let dp = pac::Peripherals::take().unwrap();
@ -68,19 +76,24 @@ fn main() -> ! {
// Enable SRAM3 for the descriptor ring. // Enable SRAM3 for the descriptor ring.
dp.RCC.ahb2enr.modify(|_, w| w.sram3en().set_bit()); dp.RCC.ahb2enr.modify(|_, w| w.sram3en().set_bit());
// Reset RCC clock
dp.RCC.rsr.write(|w| w.rmvf().set_bit());
let rcc = dp.RCC.constrain();
let pwr = dp.PWR.constrain(); let pwr = dp.PWR.constrain();
let vos = pwr.freeze(); let vos = pwr.freeze();
let rcc = dp.RCC.constrain();
let ccdr = rcc let ccdr = rcc
.sysclk(400.mhz()) .use_hse(16.mhz())
.hclk(200.mhz()) .sysclk(400.mhz())
.per_ck(100.mhz()) .hclk(200.mhz())
.pll1_q_ck(48.mhz()) // for SPI .per_ck(100.mhz())
.pll2_p_ck(100.mhz()) .pll1_q_ck(48.mhz()) // for SPI
.pll2_q_ck(100.mhz()) .pll2_p_ck(100.mhz())
.freeze(vos, &dp.SYSCFG); .pll2_q_ck(100.mhz())
.freeze(vos, &dp.SYSCFG);
let mut delay = cp.SYST.delay(ccdr.clocks);
let gpioa = dp.GPIOA.split(ccdr.peripheral.GPIOA); let gpioa = dp.GPIOA.split(ccdr.peripheral.GPIOA);
let gpiob = dp.GPIOB.split(ccdr.peripheral.GPIOB); let gpiob = dp.GPIOB.split(ccdr.peripheral.GPIOB);
@ -94,6 +107,8 @@ fn main() -> ! {
yellow_led.set_low().unwrap(); yellow_led.set_low().unwrap();
let mut red_led = gpiob.pb14.into_push_pull_output(); let mut red_led = gpiob.pb14.into_push_pull_output();
red_led.set_high().unwrap(); red_led.set_high().unwrap();
let mut green_led = gpiob.pb0.into_push_pull_output();
green_led.set_low().unwrap();
// Configure ethernet IO // Configure ethernet IO
{ {
@ -177,6 +192,9 @@ fn main() -> ! {
cp.SCB.invalidate_icache(); cp.SCB.invalidate_icache();
cp.SCB.enable_icache(); cp.SCB.enable_icache();
// cp.SCB.clean_dcache(&mut cp.CPUID);
// cp.SCB.disable_dcache(&mut cp.CPUID);
// cp.SCB.enable_dcache(&mut cp.CPUID);
let mut time: u32 = 0; let mut time: u32 = 0;
let mut next_ms = Instant::now(); let mut next_ms = Instant::now();
@ -195,7 +213,27 @@ fn main() -> ! {
) )
.unwrap(); .unwrap();
delay.delay_ms(1000_u16);
client.network_stack.update(time);
green_led.set_high().unwrap();
loop { loop {
let tick = Instant::now() > next_ms;
if tick {
next_ms += 400_000.cycles();
time += 1;
}
client.network_stack.update(time);
client
.poll(|_client, topic, message, _properties| match topic {
_ => info!("On '{:?}', received: {:?}", topic, message),
})
.unwrap();
match client.is_connected() { match client.is_connected() {
true => { true => {
yellow_led.set_high().unwrap(); yellow_led.set_high().unwrap();
@ -207,19 +245,6 @@ fn main() -> ! {
}, },
}; };
client
.poll(|_client, topic, message, _properties| match topic {
_ => hprintln!("On '{:?}', received: {:?}", topic, message).unwrap(),
})
.unwrap();
let tick = Instant::now() > next_ms;
if tick {
next_ms += 400_000.cycles();
time += 1;
}
if tick && (time % 1000) == 0 { if tick && (time % 1000) == 0 {
client client
.publish("nucleo", "Hello, World!".as_bytes(), QoS::AtMostOnce, &[]) .publish("nucleo", "Hello, World!".as_bytes(), QoS::AtMostOnce, &[])
@ -227,10 +252,10 @@ fn main() -> ! {
} }
// Update the TCP stack. // Update the TCP stack.
let sleep = client.network_stack.update(time); // let sleep = client.network_stack.update(time);
if sleep { // if sleep {
//cortex_m::asm::wfi(); // //cortex_m::asm::wfi();
cortex_m::asm::nop(); // cortex_m::asm::nop();
} // }
} }
} }

View File

@ -1,180 +1,175 @@
#![no_main]
#![no_std] #![no_std]
#![no_main]
#[macro_use]
extern crate log;
#[macro_use]
extern crate lazy_static;
use smoltcp as net;
use stm32h7xx_hal::ethernet;
use stm32h7xx_hal::{gpio::Speed, prelude::*, spi, pac};
use embedded_hal::{
blocking::spi::Transfer,
digital::v2::OutputPin,
};
use core::sync::atomic::{AtomicU32, Ordering}; use core::sync::atomic::{AtomicU32, Ordering};
use core::fmt::Write;
use core::str;
// extern crate cortex_m; // use heapless::{consts, String};
use panic_semihosting as _;
use cortex_m; use cortex_m;
use cortex_m::asm::nop; use cortex_m::iprintln;
use cortex_m_rt::{ use cortex_m_rt::{
entry, entry,
exception, exception,
}; };
use cortex_m_semihosting::hprintln; // use cortex_m_semihosting::hprintln;
extern crate smoltcp; // use panic_halt as _;
use stm32h7xx_hal::ethernet; use rtic::cyccnt::{Instant, U32Ext};
use stm32h7xx_hal::gpio::Speed;
use stm32h7xx_hal::hal::digital::v2::{ use log::info;
OutputPin, use log::debug;
InputPin, use log::trace;
use nb::block;
use minimq::{
embedded_nal::{IpAddr, Ipv4Addr, TcpStack, SocketAddr, Mode},
MqttClient, QoS,
}; };
use stm32h7xx_hal::rcc::CoreClocks;
use stm32h7xx_hal::{pac, prelude::*, spi, stm32, stm32::interrupt};
use Speed::*;
use libm::round; use firmware::nal_tcp_client::{NetworkStack, NetStorage, NetworkInterface};
use firmware::{Urukul};
use firmware::cpld::{CPLD};
use core::{
str,
fmt::Write
};
use core::mem::uninitialized;
use smoltcp::wire::{EthernetAddress, IpAddress, IpCidr, Ipv4Address};
use smoltcp::iface::{NeighborCache, EthernetInterfaceBuilder, Routes};
use smoltcp::socket::SocketSet;
use smoltcp::socket::{SocketHandle, TcpSocket, TcpSocketBuffer};
use smoltcp::time::{Duration, Instant};
use embedded_nal::TcpStack;
use firmware;
use firmware::{
attenuator::Attenuator,
config_register::{
ConfigRegister,
CFGMask,
StatusMask,
},
dds::{
DDS,
DDSCFRMask,
},
cpld::{
CPLD,
},
Urukul,
};
use scpi::prelude::*;
/// Configure SYSTICK for 1ms timebase
fn systick_init(syst: &mut stm32::SYST, clocks: CoreClocks) {
let c_ck_mhz = clocks.c_ck().0 / 1_000_000;
let syst_calib = 0x3E8;
syst.set_clock_source(cortex_m::peripheral::syst::SystClkSource::Core);
syst.set_reload((syst_calib * c_ck_mhz) - 1);
syst.enable_interrupt();
syst.enable_counter();
}
/// ======================================================================
/// Entry point
/// ======================================================================
/// TIME is an atomic u32 that counts milliseconds. Although not used
/// here, it is very useful to have for network protocols
static TIME: AtomicU32 = AtomicU32::new(0);
/// Locally administered MAC address
const MAC_ADDRESS: [u8; 6] = [0x02, 0x00, 0x11, 0x22, 0x33, 0x44];
/// Ethernet descriptor rings are a global singleton
#[link_section = ".sram3.eth"] #[link_section = ".sram3.eth"]
static mut DES_RING: ethernet::DesRing = ethernet::DesRing::new(); static mut DES_RING: ethernet::DesRing = ethernet::DesRing::new();
// Theoratical maximum number of socket that can be handled // Logging setup
const SOCKET_COUNT: usize = 2; #[path = "util/logger.rs"]
mod logger;
#[path = "util/clock.rs"]
mod clock;
// End of logging setup
// Give buffer sizes of transmitting and receiving TCP packets // static TIME: AtomicU32 = AtomicU32::new(0);
const BUFFER_SIZE: usize = 2048;
// the program entry point
#[entry] #[entry]
fn main() -> ! { fn main() -> ! {
// logger::semihosting_init();
let clock = clock::Clock::new();
let mut cp = cortex_m::Peripherals::take().unwrap(); let mut cp = cortex_m::Peripherals::take().unwrap();
let dp = pac::Peripherals::take().unwrap(); let dp = pac::Peripherals::take().unwrap();
// Initialise power... cp.DWT.enable_cycle_counter();
// Enable SRAM3 for the descriptor ring.
dp.RCC.ahb2enr.modify(|_, w| w.sram3en().set_bit());
// Reset RCC clock
dp.RCC.rsr.write(|w| w.rmvf().set_bit());
let pwr = dp.PWR.constrain(); let pwr = dp.PWR.constrain();
let vos = pwr.freeze(); let vos = pwr.freeze();
// Initialise SRAM3
dp.RCC.ahb2enr.modify(|_, w| w.sram3en().set_bit());
// Initialise clocks...
let rcc = dp.RCC.constrain(); let rcc = dp.RCC.constrain();
let ccdr = rcc let ccdr = rcc
.sys_ck(200.mhz()) .use_hse(8.mhz())
.hclk(200.mhz()) .sysclk(400.mhz())
.pll1_r_ck(100.mhz()) // for TRACECK // .hclk(200.mhz())
.pll1_q_ck(48.mhz()) // for SPI // .per_ck(100.mhz())
.freeze(vos, &dp.SYSCFG); .pll1_q_ck(48.mhz()) // for SPI
// .pll1_r_ck(400.mhz()) // for TRACECK
// .pll2_p_ck(100.mhz())
// .pll2_q_ck(100.mhz())
.freeze(vos, &dp.SYSCFG);
// Get the delay provider. let mut delay = cp.SYST.delay(ccdr.clocks);
let delay = cp.SYST.delay(ccdr.clocks);
// Initialise system...
cp.SCB.invalidate_icache();
cp.SCB.enable_icache();
// TODO: ETH DMA coherence issues
// cp.SCB.enable_dcache(&mut cp.CPUID);
cp.DWT.enable_cycle_counter();
// Initialise IO...
let gpioa = dp.GPIOA.split(ccdr.peripheral.GPIOA); let gpioa = dp.GPIOA.split(ccdr.peripheral.GPIOA);
let gpiob = dp.GPIOB.split(ccdr.peripheral.GPIOB); let gpiob = dp.GPIOB.split(ccdr.peripheral.GPIOB);
let gpioc = dp.GPIOC.split(ccdr.peripheral.GPIOC); let gpioc = dp.GPIOC.split(ccdr.peripheral.GPIOC);
let gpiod = dp.GPIOD.split(ccdr.peripheral.GPIOD); let gpiod = dp.GPIOD.split(ccdr.peripheral.GPIOD);
let gpioe = dp.GPIOE.split(ccdr.peripheral.GPIOE); let gpioe = dp.GPIOE.split(ccdr.peripheral.GPIOE);
let gpiof = dp.GPIOF.split(ccdr.peripheral.GPIOF); let gpiof = dp.GPIOF.split(ccdr.peripheral.GPIOF);
let gpiog = dp.GPIOG.split(ccdr.peripheral.GPIOG); let gpiog = dp.GPIOG.split(ccdr.peripheral.GPIOG);
// let mut link_led = gpiob.pb0.into_push_pull_output(); // LED1, green
// let mut status_led = gpioe.pe1.into_push_pull_output(); // LD2, yellow
// let mut listen_led = gpiob.pb14.into_push_pull_output(); // LD3, red
// link_led.set_low().ok();
// status_led.set_low().ok();
// listen_led.set_low().ok();
// Setup CDONE for checking let mut yellow_led = gpioe.pe1.into_push_pull_output();
let fpga_cdone = gpiod.pd15.into_pull_up_input(); yellow_led.set_low().unwrap();
let mut red_led = gpiob.pb14.into_push_pull_output();
red_led.set_high().unwrap();
let mut green_led = gpiob.pb0.into_push_pull_output();
green_led.set_low().unwrap();
match fpga_cdone.is_high() { // Configure ethernet IO
Ok(true) => hprintln!("FPGA is ready."), {
Ok(_) => hprintln!("FPGA is in reset state."), let _rmii_refclk = gpioa.pa1.into_alternate_af11().set_speed(Speed::VeryHigh);
Err(_) => hprintln!("Error: Cannot read C_DONE"), let _rmii_mdio = gpioa.pa2.into_alternate_af11().set_speed(Speed::VeryHigh);
}.unwrap(); let _rmii_mdc = gpioc.pc1.into_alternate_af11().set_speed(Speed::VeryHigh);
let _rmii_crs_dv = gpioa.pa7.into_alternate_af11().set_speed(Speed::VeryHigh);
let _rmii_rxd0 = gpioc.pc4.into_alternate_af11().set_speed(Speed::VeryHigh);
let _rmii_rxd1 = gpioc.pc5.into_alternate_af11().set_speed(Speed::VeryHigh);
let _rmii_tx_en = gpiog.pg11.into_alternate_af11().set_speed(Speed::VeryHigh);
let _rmii_txd0 = gpiog.pg13.into_alternate_af11().set_speed(Speed::VeryHigh);
let _rmii_txd1 = gpiob.pb13.into_alternate_af11().set_speed(Speed::VeryHigh);
}
// Configure ethernet
let mac_addr = net::wire::EthernetAddress([0xAC, 0x6F, 0x7A, 0xDE, 0xD6, 0xC8]);
let (eth_dma, _eth_mac) = unsafe {
ethernet::new_unchecked(
dp.ETHERNET_MAC,
dp.ETHERNET_MTL,
dp.ETHERNET_DMA,
&mut DES_RING,
mac_addr.clone(),
)
};
unsafe { ethernet::enable_interrupt() }
// Setup Urukul let mut ip_addrs = [net::wire::IpCidr::new(net::wire::IpAddress::v4(192, 168, 1, 200), 24)];
/*
* Using SPI1, AF5
* SCLK -> PA5
* MOSI -> PB5
* MISO -> PA6
* CS -> 0: PB12, 1: PA15, 2: PC7
*/
let mut neighbor_cache_entries = [None; 8];
let mut neighbor_cache = net::iface::NeighborCache::new(&mut neighbor_cache_entries[..]);
// neighbor_cache.fill(
// net::wire::IpAddress::v4(192, 168, 1, 125),
// net::wire::EthernetAddress([0x2C, 0xF0, 0x5D, 0x26, 0xB8, 0x2F]),
// clock.elapsed(),
// );
let mut net_interface = net::iface::EthernetInterfaceBuilder::new(eth_dma)
.ethernet_addr(mac_addr)
.neighbor_cache(neighbor_cache)
.ip_addrs(&mut ip_addrs[..])
.finalize();
/*
* Using SPI1, AF5
* SCLK -> PA5
* MOSI -> PB5
* MISO -> PA6
* CS -> 0: PB12, 1: PA15, 2: PC7
* I/O_Update -> PB15
*/
let sclk = gpioa.pa5.into_alternate_af5(); let sclk = gpioa.pa5.into_alternate_af5();
let mosi = gpiob.pb5.into_alternate_af5(); let mosi = gpiob.pb5.into_alternate_af5();
let miso = gpioa.pa6.into_alternate_af5(); let miso = gpioa.pa6.into_alternate_af5();
let (cs0, cs1, cs2) = ( let (cs0, cs1, cs2) = (
gpiob.pb12.into_push_pull_output(), gpiob.pb12.into_push_pull_output(),
gpioa.pa15.into_push_pull_output(), gpioa.pa15.into_push_pull_output(),
gpioc.pc7.into_push_pull_output(), gpioc.pc7.into_push_pull_output(),
); );
/* let io_update = gpiob.pb15.into_push_pull_output();
* I/O_Update -> PB15
*/
let io_update = gpiob.pb15.into_push_pull_output();
let spi = dp.SPI1.spi( let spi = dp.SPI1.spi(
(sclk, miso, mosi), (sclk, miso, mosi),
@ -184,201 +179,93 @@ fn main() -> ! {
&ccdr.clocks, &ccdr.clocks,
); );
let switch = CPLD::new(spi, (cs0, cs1, cs2), io_update); let cpld = CPLD::new(spi, (cs0, cs1, cs2), io_update);
let parts = switch.split(); let parts = cpld.split();
let mut urukul = Urukul::new(
let urukul = Urukul::new(
parts.spi1, parts.spi2, parts.spi3, parts.spi4, parts.spi5, parts.spi6, parts.spi7, parts.spi1, parts.spi2, parts.spi3, parts.spi4, parts.spi5, parts.spi6, parts.spi7,
[25_000_000, 25_000_000, 25_000_000, 25_000_000] [25_000_000, 25_000_000, 25_000_000, 25_000_000]
); );
// Setup ethernet pins cp.SCB.invalidate_icache();
setup_ethernet_pins( cp.SCB.enable_icache();
gpioa.pa1, gpioa.pa2, gpioc.pc1, gpioa.pa7, gpioc.pc4,
gpioc.pc5, gpiog.pg11, gpiog.pg13, gpiob.pb13
);
// Initialise ethernet... // let mut time: u32 = 0;
assert_eq!(ccdr.clocks.hclk().0, 200_000_000); // HCLK 200MHz // let mut next_ms = Instant::now();
assert_eq!(ccdr.clocks.pclk1().0, 100_000_000); // PCLK 100MHz
assert_eq!(ccdr.clocks.pclk2().0, 100_000_000); // PCLK 100MHz
assert_eq!(ccdr.clocks.pclk4().0, 100_000_000); // PCLK 100MHz
let mac_addr = smoltcp::wire::EthernetAddress::from_bytes(&MAC_ADDRESS); // next_ms += 400_000.cycles();
let (_eth_dma, mut eth_mac) = unsafe {
ethernet::new_unchecked( let mut socket_set_entries: [_; 8] = Default::default();
dp.ETHERNET_MAC, let mut sockets = net::socket::SocketSet::new(&mut socket_set_entries[..]);
dp.ETHERNET_MTL,
dp.ETHERNET_DMA, let mut rx_storage = [0; 4096];
&mut DES_RING, let mut tx_storage = [0; 4096];
mac_addr.clone(),
) let tcp_socket = {
let tx_buffer = net::socket::TcpSocketBuffer::new(&mut tx_storage[..]);
let rx_buffer = net::socket::TcpSocketBuffer::new(&mut rx_storage[..]);
net::socket::TcpSocket::new(tx_buffer, rx_buffer)
}; };
unsafe { let handle = sockets.add(tcp_socket);
ethernet::enable_interrupt();
cp.NVIC.set_priority(stm32::Interrupt::ETH, 196); // Mid prio delay.delay_ms(2000_u16);
cortex_m::peripheral::NVIC::unmask(stm32::Interrupt::ETH); green_led.set_high().unwrap();
{
let mut socket = sockets.get::<net::socket::TcpSocket>(handle);
socket.connect((net::wire::IpAddress::v4(192, 168, 1, 125), 1883), 49500).unwrap();
debug!("connect!");
} }
// ---------------------------------------------------------- yellow_led.set_low().unwrap();
// Begin periodic tasks red_led.set_high().unwrap();
systick_init(&mut delay.free(), ccdr.clocks); let mut green = true;
unsafe {
cp.SCB.shpr[15 - 4].write(128);
} // systick exception priority
// ----------------------------------------------------------
// Main application loop
// Setup addresses, maybe not MAC?
// MAC is set up in prior
let local_addr = IpAddress::v4(192, 168, 1, 200);
let mut ip_addrs = [IpCidr::new(local_addr, 24)];
// let neighbor_cache = NeighborCache::new(BTreeMap::new());
let mut neighbor_storage = [None; 16];
let neighbor_cache = NeighborCache::new(&mut neighbor_storage[..]);
// Routes
let default_v4_gw = Ipv4Address::new(192, 168, 1, 1);
let mut routes_storage = [None; 8];
let mut routes = Routes::new(&mut routes_storage[..]);
routes.add_default_ipv4_route(default_v4_gw).unwrap();
// Device? _eth_dma, as it implements phy::device
let mut iface = EthernetInterfaceBuilder::new(_eth_dma)
.ethernet_addr(mac_addr)
.neighbor_cache(neighbor_cache)
.ip_addrs(&mut ip_addrs[..])
.routes(routes)
.finalize();
// SCPI configs
// Device was declared in prior
// let mut errors = ArrayErrorQueue::<[Error; 10]>::new();
// let mut context = Context::new(&mut urukul, &mut errors, TREE);
// //Response bytebuffer
// let mut buf = ArrayVecFormatter::<[u8; 256]>::new();
// SCPI configs END
// TCP socket
let server_socket = {
static mut server_rx_storage :[u8; BUFFER_SIZE] = [0; BUFFER_SIZE];
static mut server_tx_storage :[u8; BUFFER_SIZE] = [0; BUFFER_SIZE];
let server_rx_buffer = TcpSocketBuffer::new( unsafe { &mut server_rx_storage[..] } );
let server_tx_buffer = TcpSocketBuffer::new( unsafe { &mut server_tx_storage[..] } );
TcpSocket::new(server_rx_buffer, server_tx_buffer)
};
// Setup a silent socket
let client_socket = {
static mut client_rx_storage :[u8; BUFFER_SIZE] = [0; BUFFER_SIZE];
static mut client_tx_storage :[u8; BUFFER_SIZE] = [0; BUFFER_SIZE];
let client_rx_buffer = TcpSocketBuffer::new( unsafe { &mut client_rx_storage[..] } );
let client_tx_buffer = TcpSocketBuffer::new( unsafe { &mut client_tx_storage[..] } );
TcpSocket::new(client_rx_buffer, client_tx_buffer)
};
// Socket storage
let mut sockets_storage: [_; 2] = Default::default();
let mut socket_set = SocketSet::new(&mut sockets_storage[..]);
let server_handle = socket_set.add(server_socket);
let client_handle = socket_set.add(client_socket);
loop { loop {
let _time = TIME.load(Ordering::Relaxed); // let timestamp = net::time::Instant::from_millis(TIME.load(Ordering::Relaxed) as i64);
match iface.poll(&mut socket_set, Instant::from_millis(_time as i64)) { match net_interface.poll(&mut sockets, clock.elapsed()) {
Ok(_) => { Ok(_) => {},
// hprintln!("Ethernet up").unwrap();
},
Err(e) => { Err(e) => {
hprintln!("Ethernet down!").unwrap(); debug!("poll error: {}", e);
},
};
// Conenct to TCP server through port 49500
{
let mut socket = socket_set.get::<TcpSocket>(server_handle);
if !socket.is_active() && !socket.is_listening(){
socket.listen(7777).unwrap();
hprintln!("Server listening").unwrap();
}
// hprintln!("listener state :{}", socket.state()).unwrap();
if socket.can_recv() {
hprintln!("{:?}", str::from_utf8(socket.recv(|data| {
(data.len(), data)
}).unwrap()).unwrap()).unwrap();
} }
} }
{ {
let mut socket = socket_set.get::<TcpSocket>(client_handle); let mut socket = sockets.get::<net::socket::TcpSocket>(handle);
if !socket.is_open() {
socket.abort(); if socket.may_recv() {
yellow_led.set_high().unwrap();
red_led.set_low().unwrap();
let data = socket.recv(|data| {
(data.len(), data)
}).unwrap();
if socket.can_send() {
socket.send_slice("response".as_bytes()).unwrap();
}
}
if socket.may_send() {
yellow_led.set_high().unwrap();
red_led.set_low().unwrap();
debug!("close");
socket.close(); socket.close();
hprintln!("reset state: {}", socket.state()).unwrap();
socket.connect((IpAddress::v4(192, 168, 1, 200), 1883),
(IpAddress::Unspecified, 45000)).unwrap();
hprintln!("post connect state: {}", socket.state()).unwrap();
} }
}
// hprintln!("client state: {}", socket.state()).unwrap(); match net_interface.poll_delay(&sockets, clock.elapsed()) {
Some(net::time::Duration {millis :0}) => debug!("resuming"),
if socket.can_send() { Some(time_delay) => {
socket.send_slice(b"regards from socket").unwrap(); info!("sleeping for {} ms", time_delay);
} // green_led.set_low().unwrap();
// delay.delay_ms(time_delay.total_millis() as u32);
// green_led.set_high().unwrap();
clock.advance(time_delay)
},
None => {
// delay.delay_ms(1_u32);
clock.advance(net::time::Duration::from_millis(1))
},
} }
} }
} }
use stm32h7xx_hal::gpio::{
gpioa::{PA1, PA2, PA7},
gpiob::{PB13},
gpioc::{PC1, PC4, PC5},
gpiog::{PG11, PG13},
Speed::VeryHigh,
};
/*
* Migrated ethernet setup pins
*/
pub fn setup_ethernet_pins<REF_CLK, MDIO, MDC, CRS_DV, RXD0, RXD1, TX_EN, TXD0, TXD1>(
pa1: PA1<REF_CLK>, pa2: PA2<MDIO>, pc1: PC1<MDC>, pa7: PA7<CRS_DV>, pc4: PC4<RXD0>,
pc5: PC5<RXD1>, pg11: PG11<TX_EN>, pg13: PG13<TXD0>, pb13: PB13<TXD1>
) {
pa1.into_alternate_af11().set_speed(VeryHigh);
pa2.into_alternate_af11().set_speed(VeryHigh);
pc1.into_alternate_af11().set_speed(VeryHigh);
pa7.into_alternate_af11().set_speed(VeryHigh);
pc4.into_alternate_af11().set_speed(VeryHigh);
pc5.into_alternate_af11().set_speed(VeryHigh);
pg11.into_alternate_af11().set_speed(VeryHigh);
pg13.into_alternate_af11().set_speed(VeryHigh);
pb13.into_alternate_af11().set_speed(VeryHigh);
}
#[interrupt]
fn ETH() {
unsafe { ethernet::interrupt_handler() }
}
#[exception]
fn SysTick() {
TIME.fetch_add(1, Ordering::Relaxed);
}
#[exception]
fn HardFault(ef: &cortex_m_rt::ExceptionFrame) -> ! {
panic!("HardFault at {:#?}", ef);
}
#[exception]
fn DefaultHandler(irqn: i16) {
panic!("Unhandled exception (IRQn = {})", irqn);
}

View File

@ -86,7 +86,7 @@ use cortex_m_semihosting::hio::HStdout;
lazy_static! { lazy_static! {
static ref HLOGGER: Logger<Semihosting<InterruptOk, HStdout>> = Logger { static ref HLOGGER: Logger<Semihosting<InterruptOk, HStdout>> = Logger {
level: LevelFilter::Debug, level: LevelFilter::Trace,
inner: semihosting::InterruptOk::<_>::stdout().expect("Get Semihosting stdout"), inner: semihosting::InterruptOk::<_>::stdout().expect("Get Semihosting stdout"),
}; };
} }