pounder_test/src/main.rs

1269 lines
46 KiB
Rust
Raw Normal View History

2020-11-10 22:13:57 +08:00
#![deny(warnings)]
#![allow(clippy::missing_safety_doc)]
2019-03-18 19:56:26 +08:00
#![no_std]
#![no_main]
2019-10-22 21:43:49 +08:00
#![cfg_attr(feature = "nightly", feature(asm))]
2019-03-18 19:56:26 +08:00
// Enable returning `!`
2019-10-22 21:43:49 +08:00
#![cfg_attr(feature = "nightly", feature(never_type))]
#![cfg_attr(feature = "nightly", feature(core_intrinsics))]
2019-03-18 19:56:26 +08:00
2019-06-07 17:26:24 +08:00
#[inline(never)]
#[panic_handler]
2019-10-22 21:43:49 +08:00
#[cfg(all(feature = "nightly", not(feature = "semihosting")))]
2019-06-07 17:26:24 +08:00
fn panic(_info: &core::panic::PanicInfo) -> ! {
2020-06-09 00:36:29 +08:00
let gpiod = unsafe { &*hal::stm32::GPIOD::ptr() };
2019-11-24 22:09:52 +08:00
gpiod.odr.modify(|_, w| w.odr6().high().odr12().high()); // FP_LED_1, FP_LED_3
2020-11-26 21:19:09 +08:00
#[cfg(feature = "nightly")]
core::intrinsics::abort();
#[cfg(not(feature = "nightly"))]
2019-11-24 22:09:52 +08:00
unsafe {
core::intrinsics::abort();
}
2019-06-07 17:26:24 +08:00
}
2019-03-18 19:56:26 +08:00
#[cfg(feature = "semihosting")]
extern crate panic_semihosting;
2019-10-22 21:43:49 +08:00
#[cfg(not(any(feature = "nightly", feature = "semihosting")))]
extern crate panic_halt;
2019-03-18 19:56:26 +08:00
#[macro_use]
extern crate log;
2021-01-06 22:04:06 +08:00
#[allow(unused_imports)]
2021-01-06 21:59:01 +08:00
use core::convert::TryInto;
2019-06-03 23:06:11 +08:00
// use core::sync::atomic::{AtomicU32, AtomicBool, Ordering};
2020-06-16 22:22:12 +08:00
use cortex_m_rt::exception;
2020-06-17 18:20:45 +08:00
use rtic::cyccnt::{Instant, U32Ext};
2020-04-19 19:37:03 +08:00
use stm32h7xx_hal as hal;
2020-06-16 22:22:12 +08:00
use stm32h7xx_hal::prelude::*;
2020-04-19 19:37:03 +08:00
2020-06-21 20:30:49 +08:00
use embedded_hal::digital::v2::{InputPin, OutputPin};
2019-03-18 19:56:26 +08:00
2020-10-26 23:58:29 +08:00
use hal::{
2020-11-03 16:36:03 +08:00
dma::{
2020-11-03 23:09:00 +08:00
config::Priority,
2020-11-03 16:41:45 +08:00
dma::{DMAReq, DmaConfig},
2020-11-11 18:57:14 +08:00
traits::TargetAddress,
2020-11-03 16:41:45 +08:00
MemoryToPeripheral, PeripheralToMemory, Transfer,
2020-11-03 16:36:03 +08:00
},
2020-10-28 23:14:48 +08:00
ethernet::{self, PHY},
2020-10-26 23:58:29 +08:00
};
use smoltcp as net;
2020-10-30 19:16:28 +08:00
use smoltcp::iface::Routes;
2020-10-30 20:32:47 +08:00
use smoltcp::wire::Ipv4Address;
2020-06-16 22:22:12 +08:00
use heapless::{consts::*, String};
2020-06-09 01:13:55 +08:00
// The number of ticks in the ADC sampling timer. The timer runs at 100MHz, so the step size is
// equal to 10ns per tick.
2021-01-05 01:09:16 +08:00
// Currently, the sample rate is equal to: Fsample = 100/256 MHz = 390.625 KHz
const ADC_SAMPLE_TICKS_LOG2: u16 = 8;
const ADC_SAMPLE_TICKS: u16 = 1 << ADC_SAMPLE_TICKS_LOG2;
2020-11-03 17:52:37 +08:00
2020-11-13 17:47:44 +08:00
// The desired ADC sample processing buffer size.
const SAMPLE_BUFFER_SIZE_LOG2: usize = 3;
const SAMPLE_BUFFER_SIZE: usize = 1 << SAMPLE_BUFFER_SIZE_LOG2;
2020-11-13 17:47:44 +08:00
// The number of cascaded IIR biquads per channel. Select 1 or 2!
const IIR_CASCADE_LENGTH: usize = 1;
// Frequency scaling factor for lock-in harmonic demodulation.
const HARMONIC: u32 = 1;
// Phase offset applied to the lock-in demodulation signal.
const PHASE_OFFSET: u32 = 0;
#[link_section = ".sram3.eth"]
static mut DES_RING: ethernet::DesRing = ethernet::DesRing::new();
2019-05-24 00:57:00 +08:00
2020-11-03 16:36:03 +08:00
mod adc;
mod afe;
2020-11-03 16:41:45 +08:00
mod dac;
2020-11-25 00:09:36 +08:00
mod design_parameters;
2020-12-08 00:58:36 +08:00
mod digital_input_stamper;
2019-11-24 22:09:52 +08:00
mod eeprom;
2020-12-08 00:58:36 +08:00
mod hrtimer;
mod pounder;
2020-06-09 01:13:55 +08:00
mod server;
2020-12-08 00:58:36 +08:00
mod timers;
2019-09-05 07:54:00 +08:00
2020-11-26 17:58:11 +08:00
use adc::{Adc0Input, Adc1Input};
2020-11-26 18:16:08 +08:00
use dac::{Dac0Output, Dac1Output};
use dsp::{
iir, iir_int,
reciprocal_pll::TimestampHandler,
trig::{atan2, cossin},
2021-01-18 05:19:14 +08:00
Complex,
};
2020-12-03 00:01:40 +08:00
use pounder::DdsOutput;
2020-11-03 16:36:03 +08:00
2019-03-18 19:56:26 +08:00
#[cfg(not(feature = "semihosting"))]
fn init_log() {}
#[cfg(feature = "semihosting")]
fn init_log() {
2019-11-24 22:09:52 +08:00
use cortex_m_log::log::{init as init_log, Logger};
use cortex_m_log::printer::semihosting::{hio::HStdout, InterruptOk};
2019-03-18 19:56:26 +08:00
use log::LevelFilter;
static mut LOGGER: Option<Logger<InterruptOk<HStdout>>> = None;
let logger = Logger {
2019-04-13 00:13:18 +08:00
inner: InterruptOk::<_>::stdout().unwrap(),
2019-03-18 19:56:26 +08:00
level: LevelFilter::Info,
};
2019-11-24 22:09:52 +08:00
let logger = unsafe { LOGGER.get_or_insert(logger) };
2019-03-18 19:56:26 +08:00
2019-05-31 00:03:48 +08:00
init_log(logger).unwrap();
2019-03-18 19:56:26 +08:00
}
// Pull in build information (from `built` crate)
mod build_info {
#![allow(dead_code)]
2019-05-24 00:57:00 +08:00
// include!(concat!(env!("OUT_DIR"), "/built.rs"));
2019-03-18 19:56:26 +08:00
}
pub struct NetStorage {
ip_addrs: [net::wire::IpCidr; 1],
neighbor_cache: [Option<(net::wire::IpAddress, net::iface::Neighbor)>; 8],
2020-10-30 20:33:59 +08:00
routes_storage: [Option<(smoltcp::wire::IpCidr, smoltcp::iface::Route)>; 1],
}
static mut NET_STORE: NetStorage = NetStorage {
// Placeholder for the real IP address, which is initialized at runtime.
2020-06-16 22:22:12 +08:00
ip_addrs: [net::wire::IpCidr::Ipv6(
net::wire::Ipv6Cidr::SOLICITED_NODE_PREFIX,
)],
neighbor_cache: [None; 8],
2020-10-30 19:16:28 +08:00
2020-10-30 20:33:59 +08:00
routes_storage: [None; 1],
};
const SCALE: f32 = ((1 << 15) - 1) as f32;
2019-06-03 23:06:11 +08:00
// static ETHERNET_PENDING: AtomicBool = AtomicBool::new(true);
2019-04-30 19:42:05 +08:00
const TCP_RX_BUFFER_SIZE: usize = 8192;
const TCP_TX_BUFFER_SIZE: usize = 8192;
type AFE0 = afe::ProgrammableGainAmplifier<
hal::gpio::gpiof::PF2<hal::gpio::Output<hal::gpio::PushPull>>,
2020-06-16 22:22:12 +08:00
hal::gpio::gpiof::PF5<hal::gpio::Output<hal::gpio::PushPull>>,
>;
type AFE1 = afe::ProgrammableGainAmplifier<
hal::gpio::gpiod::PD14<hal::gpio::Output<hal::gpio::PushPull>>,
2020-06-16 22:22:12 +08:00
hal::gpio::gpiod::PD15<hal::gpio::Output<hal::gpio::PushPull>>,
>;
macro_rules! route_request {
2020-06-03 22:53:25 +08:00
($request:ident,
readable_attributes: [$($read_attribute:tt: $getter:tt),*],
modifiable_attributes: [$($write_attribute:tt: $TYPE:ty, $setter:tt),*]) => {
2020-06-09 20:16:01 +08:00
match $request.req {
server::AccessRequest::Read => {
match $request.attribute {
$(
2020-06-09 20:16:01 +08:00
$read_attribute => {
2020-11-26 23:24:42 +08:00
#[allow(clippy::redundant_closure_call)]
let value = match $getter() {
Ok(data) => data,
2020-06-09 20:16:01 +08:00
Err(_) => return server::Response::error($request.attribute,
2020-06-12 00:09:01 +08:00
"Failed to read attribute"),
};
let encoded_data: String<U256> = match serde_json_core::to_string(&value) {
Ok(data) => data,
2020-06-09 20:16:01 +08:00
Err(_) => return server::Response::error($request.attribute,
"Failed to encode attribute value"),
};
server::Response::success($request.attribute, &encoded_data)
},
)*
2020-06-09 20:16:01 +08:00
_ => server::Response::error($request.attribute, "Unknown attribute")
}
},
2020-06-09 20:16:01 +08:00
server::AccessRequest::Write => {
match $request.attribute {
$(
2020-06-09 20:16:01 +08:00
$write_attribute => {
let new_value = match serde_json_core::from_str::<$TYPE>(&$request.value) {
Ok(data) => data,
2020-06-09 20:16:01 +08:00
Err(_) => return server::Response::error($request.attribute,
"Failed to decode value"),
};
2020-11-26 23:24:42 +08:00
#[allow(clippy::redundant_closure_call)]
match $setter(new_value) {
Ok(_) => server::Response::success($request.attribute, &$request.value),
2020-06-09 20:16:01 +08:00
Err(_) => server::Response::error($request.attribute,
"Failed to set attribute"),
}
}
)*
2020-06-09 20:16:01 +08:00
_ => server::Response::error($request.attribute, "Unknown attribute")
}
}
}
}
}
2020-06-08 15:36:28 +08:00
2020-06-17 18:20:45 +08:00
#[rtic::app(device = stm32h7xx_hal::stm32, peripherals = true, monotonic = rtic::cyccnt::CYCCNT)]
2019-05-31 00:03:48 +08:00
const APP: () = {
2019-08-26 21:47:42 +08:00
struct Resources {
2020-11-26 18:33:08 +08:00
afes: (AFE0, AFE1),
2020-11-26 17:58:11 +08:00
adcs: (Adc0Input, Adc1Input),
2020-11-26 18:16:08 +08:00
dacs: (Dac0Output, Dac1Output),
input_stamper: digital_input_stamper::InputStamper,
timestamp_handler: TimestampHandler,
iir_lockin: iir_int::IIR,
iir_state_lockin: [iir_int::IIRState; 2],
2020-11-03 23:09:00 +08:00
eeprom_i2c: hal::i2c::I2c<hal::stm32::I2C2>,
2020-04-19 19:37:03 +08:00
2020-11-17 21:23:56 +08:00
dds_output: Option<DdsOutput>,
2020-11-09 22:16:44 +08:00
2020-06-21 19:36:45 +08:00
// Note: It appears that rustfmt generates a format that GDB cannot recognize, which
2020-10-28 22:41:27 +08:00
// results in GDB breakpoints being set improperly.
#[rustfmt::skip]
2020-06-16 22:22:12 +08:00
net_interface: net::iface::EthernetInterface<
'static,
'static,
'static,
2020-10-28 22:41:27 +08:00
ethernet::EthernetDMA<'static>>,
2020-10-28 23:14:48 +08:00
eth_mac: ethernet::phy::LAN8742A<ethernet::EthernetMAC>,
mac_addr: net::wire::EthernetAddress,
2020-11-09 19:30:02 +08:00
pounder: Option<pounder::PounderDevices>,
2021-01-06 20:29:19 +08:00
pounder_stamper: Option<pounder::timestamp::Timestamper>,
2020-06-09 00:20:10 +08:00
// Format: iir_state[ch][cascade-no][coeff]
#[init([[[0.; 5]; IIR_CASCADE_LENGTH]; 2])]
iir_state: [[iir::IIRState; IIR_CASCADE_LENGTH]; 2],
#[init([[iir::IIR { ba: [1., 0., 0., 0., 0.], y_offset: 0., y_min: -SCALE - 1., y_max: SCALE }; IIR_CASCADE_LENGTH]; 2])]
iir_ch: [[iir::IIR; IIR_CASCADE_LENGTH]; 2],
2019-08-26 21:47:42 +08:00
}
2019-05-31 00:03:48 +08:00
#[init]
2019-05-31 00:03:48 +08:00
fn init(c: init::Context) -> init::LateResources {
2020-04-19 19:37:03 +08:00
let dp = c.device;
let mut cp = c.core;
2020-04-19 19:37:03 +08:00
let pwr = dp.PWR.constrain();
let vos = pwr.freeze();
2020-10-19 23:12:02 +08:00
// Enable SRAM3 for the ethernet descriptor ring.
dp.RCC.ahb2enr.modify(|_, w| w.sram3en().set_bit());
// Clear reset flags.
dp.RCC.rsr.write(|w| w.rmvf().set_bit());
// Select the PLLs for SPI.
dp.RCC
.d2ccip1r
.modify(|_, w| w.spi123sel().pll2_p().spi45sel().pll2_q());
2020-04-19 19:37:03 +08:00
let rcc = dp.RCC.constrain();
2020-10-28 22:51:08 +08:00
let ccdr = rcc
2020-06-21 20:39:23 +08:00
.use_hse(8.mhz())
2020-04-19 19:37:03 +08:00
.sysclk(400.mhz())
.hclk(200.mhz())
.per_ck(100.mhz())
.pll2_p_ck(100.mhz())
.pll2_q_ck(100.mhz())
.freeze(vos, &dp.SYSCFG);
2020-06-09 20:16:49 +08:00
init_log();
2020-10-28 22:51:08 +08:00
let mut delay = hal::delay::Delay::new(cp.SYST, ccdr.clocks);
2020-04-22 01:02:52 +08:00
2020-10-28 22:51:08 +08:00
let gpioa = dp.GPIOA.split(ccdr.peripheral.GPIOA);
let gpiob = dp.GPIOB.split(ccdr.peripheral.GPIOB);
let gpioc = dp.GPIOC.split(ccdr.peripheral.GPIOC);
let gpiod = dp.GPIOD.split(ccdr.peripheral.GPIOD);
let gpioe = dp.GPIOE.split(ccdr.peripheral.GPIOE);
let gpiof = dp.GPIOF.split(ccdr.peripheral.GPIOF);
2020-11-09 22:16:44 +08:00
let mut gpiog = dp.GPIOG.split(ccdr.peripheral.GPIOG);
2020-04-19 19:37:03 +08:00
let afe0 = {
let a0_pin = gpiof.pf2.into_push_pull_output();
let a1_pin = gpiof.pf5.into_push_pull_output();
afe::ProgrammableGainAmplifier::new(a0_pin, a1_pin)
};
let afe1 = {
let a0_pin = gpiod.pd14.into_push_pull_output();
let a1_pin = gpiod.pd15.into_push_pull_output();
afe::ProgrammableGainAmplifier::new(a0_pin, a1_pin)
};
2020-11-03 16:41:45 +08:00
let dma_streams =
hal::dma::dma::StreamsTuple::new(dp.DMA1, ccdr.peripheral.DMA1);
2020-10-26 23:58:29 +08:00
// Configure timer 2 to trigger conversions for the ADC
let mut sampling_timer = {
// The timer frequency is manually adjusted below, so the 1KHz setting here is a
// dont-care.
let mut timer2 =
dp.TIM2.timer(1.khz(), ccdr.peripheral.TIM2, &ccdr.clocks);
// Configure the timer to count at the designed tick rate. We will manually set the
// period below.
timer2.pause();
2021-01-12 20:29:15 +08:00
timer2.reset_counter();
2021-01-05 00:12:24 +08:00
timer2.set_tick_freq(design_parameters::TIMER_FREQUENCY);
let mut sampling_timer = timers::SamplingTimer::new(timer2);
sampling_timer.set_period_ticks((ADC_SAMPLE_TICKS - 1) as u32);
// The sampling timer is used as the master timer for the shadow-sampling timer. Thus,
// it generates a trigger whenever it is enabled.
sampling_timer
};
let mut shadow_sampling_timer = {
// The timer frequency is manually adjusted below, so the 1KHz setting here is a
// dont-care.
let mut timer3 =
dp.TIM3.timer(1.khz(), ccdr.peripheral.TIM3, &ccdr.clocks);
// Configure the timer to count at the designed tick rate. We will manually set the
// period below.
timer3.pause();
2021-01-12 20:29:15 +08:00
timer3.reset_counter();
timer3.set_tick_freq(design_parameters::TIMER_FREQUENCY);
let mut shadow_sampling_timer =
timers::ShadowSamplingTimer::new(timer3);
shadow_sampling_timer.set_period_ticks(ADC_SAMPLE_TICKS - 1);
// The shadow sampling timer is a slave-mode timer to the sampling timer. It should
// always be in-sync - thus, we configure it to operate in slave mode using "Trigger
// mode".
// For TIM3, TIM2 can be made the internal trigger connection using ITR1. Thus, the
// SamplingTimer start now gates the start of the ShadowSamplingTimer.
shadow_sampling_timer.set_slave_mode(
timers::TriggerSource::Trigger1,
timers::SlaveMode::Trigger,
);
shadow_sampling_timer
};
let sampling_timer_channels = sampling_timer.channels();
let shadow_sampling_timer_channels = shadow_sampling_timer.channels();
2020-12-08 00:58:36 +08:00
let mut timestamp_timer = {
// The timer frequency is manually adjusted below, so the 1KHz setting here is a
// dont-care.
let mut timer5 =
dp.TIM5.timer(1.khz(), ccdr.peripheral.TIM5, &ccdr.clocks);
// Configure the timer to count at the designed tick rate. We will manually set the
// period below.
timer5.pause();
2021-01-05 00:12:24 +08:00
timer5.set_tick_freq(design_parameters::TIMER_FREQUENCY);
2021-01-08 01:49:23 +08:00
// The timestamp timer must run at exactly a multiple of the sample timer based on the
2021-01-05 00:12:24 +08:00
// batch size. To accomodate this, we manually set the prescaler identical to the sample
// timer, but use a period that is longer.
let mut timer = timers::TimestampTimer::new(timer5);
2021-01-05 01:04:01 +08:00
let period =
digital_input_stamper::calculate_timestamp_timer_period();
2021-01-05 00:12:24 +08:00
timer.set_period_ticks(period);
2020-12-08 00:58:36 +08:00
timer
2020-12-08 00:58:36 +08:00
};
let timestamp_timer_channels = timestamp_timer.channels();
2020-04-19 19:37:03 +08:00
// Configure the SPI interfaces to the ADCs and DACs.
2020-11-03 23:09:00 +08:00
let adcs = {
let adc0 = {
let spi_miso = gpiob
.pb14
.into_alternate_af5()
.set_speed(hal::gpio::Speed::VeryHigh);
let spi_sck = gpiob
.pb10
.into_alternate_af5()
.set_speed(hal::gpio::Speed::VeryHigh);
let _spi_nss = gpiob
.pb9
.into_alternate_af5()
.set_speed(hal::gpio::Speed::VeryHigh);
2020-04-19 19:37:03 +08:00
2020-11-03 23:09:00 +08:00
let config = hal::spi::Config::new(hal::spi::Mode {
polarity: hal::spi::Polarity::IdleHigh,
phase: hal::spi::Phase::CaptureOnSecondTransition,
})
.manage_cs()
.suspend_when_inactive()
.communication_mode(hal::spi::CommunicationMode::Receiver)
2020-11-25 00:09:36 +08:00
.cs_delay(design_parameters::ADC_SETUP_TIME);
2020-04-19 19:37:03 +08:00
2020-11-03 23:09:00 +08:00
let spi: hal::spi::Spi<_, _, u16> = dp.SPI2.spi(
(spi_sck, spi_miso, hal::spi::NoMosi),
config,
2021-01-05 00:12:24 +08:00
design_parameters::ADC_DAC_SCK_MAX,
2020-11-03 23:09:00 +08:00
ccdr.peripheral.SPI2,
&ccdr.clocks,
);
2020-04-19 19:37:03 +08:00
Adc0Input::new(
spi,
dma_streams.0,
dma_streams.1,
dma_streams.2,
sampling_timer_channels.ch1,
shadow_sampling_timer_channels.ch1,
)
2020-11-03 23:09:00 +08:00
};
2020-04-19 19:37:03 +08:00
2020-11-03 23:09:00 +08:00
let adc1 = {
let spi_miso = gpiob
.pb4
.into_alternate_af6()
.set_speed(hal::gpio::Speed::VeryHigh);
let spi_sck = gpioc
.pc10
.into_alternate_af6()
.set_speed(hal::gpio::Speed::VeryHigh);
let _spi_nss = gpioa
.pa15
.into_alternate_af6()
.set_speed(hal::gpio::Speed::VeryHigh);
2020-04-19 19:37:03 +08:00
2020-11-03 23:09:00 +08:00
let config = hal::spi::Config::new(hal::spi::Mode {
polarity: hal::spi::Polarity::IdleHigh,
phase: hal::spi::Phase::CaptureOnSecondTransition,
})
.manage_cs()
.suspend_when_inactive()
.communication_mode(hal::spi::CommunicationMode::Receiver)
2020-11-25 00:09:36 +08:00
.cs_delay(design_parameters::ADC_SETUP_TIME);
2020-11-03 23:09:00 +08:00
let spi: hal::spi::Spi<_, _, u16> = dp.SPI3.spi(
(spi_sck, spi_miso, hal::spi::NoMosi),
config,
2021-01-05 00:12:24 +08:00
design_parameters::ADC_DAC_SCK_MAX,
2020-11-03 23:09:00 +08:00
ccdr.peripheral.SPI3,
&ccdr.clocks,
);
2020-04-19 19:37:03 +08:00
Adc1Input::new(
spi,
dma_streams.3,
dma_streams.4,
dma_streams.5,
sampling_timer_channels.ch2,
shadow_sampling_timer_channels.ch2,
)
2020-11-03 23:09:00 +08:00
};
2020-11-26 17:58:11 +08:00
(adc0, adc1)
2020-04-19 19:37:03 +08:00
};
2020-11-03 23:09:00 +08:00
let dacs = {
let _dac_clr_n =
gpioe.pe12.into_push_pull_output().set_high().unwrap();
let _dac0_ldac_n =
gpioe.pe11.into_push_pull_output().set_low().unwrap();
let _dac1_ldac_n =
gpioe.pe15.into_push_pull_output().set_low().unwrap();
2020-06-23 20:13:55 +08:00
2020-11-03 16:36:03 +08:00
let dac0_spi = {
let spi_miso = gpioe
.pe5
.into_alternate_af5()
.set_speed(hal::gpio::Speed::VeryHigh);
let spi_sck = gpioe
.pe2
.into_alternate_af5()
.set_speed(hal::gpio::Speed::VeryHigh);
let _spi_nss = gpioe
.pe4
.into_alternate_af5()
.set_speed(hal::gpio::Speed::VeryHigh);
2020-06-23 20:13:55 +08:00
2020-11-03 16:36:03 +08:00
let config = hal::spi::Config::new(hal::spi::Mode {
polarity: hal::spi::Polarity::IdleHigh,
phase: hal::spi::Phase::CaptureOnSecondTransition,
})
.manage_cs()
.suspend_when_inactive()
.communication_mode(hal::spi::CommunicationMode::Transmitter)
.swap_mosi_miso();
2020-04-19 19:37:03 +08:00
2020-11-03 16:36:03 +08:00
dp.SPI4.spi(
(spi_sck, spi_miso, hal::spi::NoMosi),
config,
2021-01-05 00:12:24 +08:00
design_parameters::ADC_DAC_SCK_MAX,
2020-11-03 16:36:03 +08:00
ccdr.peripheral.SPI4,
&ccdr.clocks,
)
};
2020-04-19 19:37:03 +08:00
2020-11-03 16:36:03 +08:00
let dac1_spi = {
let spi_miso = gpiof
.pf8
.into_alternate_af5()
.set_speed(hal::gpio::Speed::VeryHigh);
let spi_sck = gpiof
.pf7
.into_alternate_af5()
.set_speed(hal::gpio::Speed::VeryHigh);
let _spi_nss = gpiof
.pf6
.into_alternate_af5()
.set_speed(hal::gpio::Speed::VeryHigh);
2020-04-19 19:37:03 +08:00
2020-11-03 16:36:03 +08:00
let config = hal::spi::Config::new(hal::spi::Mode {
polarity: hal::spi::Polarity::IdleHigh,
phase: hal::spi::Phase::CaptureOnSecondTransition,
})
.manage_cs()
.communication_mode(hal::spi::CommunicationMode::Transmitter)
.suspend_when_inactive()
.swap_mosi_miso();
dp.SPI5.spi(
(spi_sck, spi_miso, hal::spi::NoMosi),
config,
2021-01-05 00:12:24 +08:00
design_parameters::ADC_DAC_SCK_MAX,
2020-11-03 16:36:03 +08:00
ccdr.peripheral.SPI5,
&ccdr.clocks,
)
};
2020-06-16 22:22:12 +08:00
2020-11-13 17:47:44 +08:00
let dac0 = Dac0Output::new(
dac0_spi,
dma_streams.6,
2020-11-13 17:47:44 +08:00
sampling_timer_channels.ch3,
2020-11-03 23:09:00 +08:00
);
2020-11-13 17:47:44 +08:00
let dac1 = Dac1Output::new(
dac1_spi,
dma_streams.7,
2020-11-13 17:47:44 +08:00
sampling_timer_channels.ch4,
);
2020-11-26 18:16:08 +08:00
(dac0, dac1)
};
2020-04-19 19:37:03 +08:00
let mut fp_led_0 = gpiod.pd5.into_push_pull_output();
let mut fp_led_1 = gpiod.pd6.into_push_pull_output();
let mut fp_led_2 = gpiog.pg4.into_push_pull_output();
let mut fp_led_3 = gpiod.pd12.into_push_pull_output();
fp_led_0.set_low().unwrap();
fp_led_1.set_low().unwrap();
fp_led_2.set_low().unwrap();
fp_led_3.set_low().unwrap();
2020-06-21 20:30:49 +08:00
// Measure the Pounder PGOOD output to detect if pounder is present on Stabilizer.
let pounder_pgood = gpiob.pb13.into_pull_down_input();
delay.delay_ms(2u8);
2020-11-17 21:23:56 +08:00
let (pounder_devices, dds_output) = if pounder_pgood.is_high().unwrap()
{
let ad9959 = {
2020-06-09 00:20:10 +08:00
let qspi_interface = {
// Instantiate the QUADSPI pins and peripheral interface.
2020-10-19 23:12:02 +08:00
let qspi_pins = {
let _qspi_ncs = gpioc
.pc11
.into_alternate_af9()
.set_speed(hal::gpio::Speed::VeryHigh);
let clk = gpiob
.pb2
.into_alternate_af9()
.set_speed(hal::gpio::Speed::VeryHigh);
let io0 = gpioe
.pe7
.into_alternate_af10()
.set_speed(hal::gpio::Speed::VeryHigh);
let io1 = gpioe
.pe8
.into_alternate_af10()
.set_speed(hal::gpio::Speed::VeryHigh);
let io2 = gpioe
.pe9
.into_alternate_af10()
.set_speed(hal::gpio::Speed::VeryHigh);
let io3 = gpioe
.pe10
.into_alternate_af10()
.set_speed(hal::gpio::Speed::VeryHigh);
(clk, io0, io1, io2, io3)
};
2020-10-28 22:41:27 +08:00
let qspi = hal::qspi::Qspi::bank2(
dp.QUADSPI,
qspi_pins,
2021-01-05 01:04:01 +08:00
design_parameters::POUNDER_QSPI_FREQUENCY,
2020-10-28 22:51:08 +08:00
&ccdr.clocks,
ccdr.peripheral.QSPI,
2020-10-28 22:41:27 +08:00
);
2020-06-09 00:20:10 +08:00
pounder::QspiInterface::new(qspi).unwrap()
};
2021-01-06 20:29:19 +08:00
#[cfg(feature = "pounder_v1_1")]
let reset_pin = gpiog.pg6.into_push_pull_output();
2021-01-06 20:29:19 +08:00
#[cfg(not(feature = "pounder_v1_1"))]
let reset_pin = gpioa.pa0.into_push_pull_output();
let mut io_update = gpiog.pg7.into_push_pull_output();
2020-11-07 18:01:48 +08:00
2021-01-06 21:59:01 +08:00
let ref_clk: hal::time::Hertz =
design_parameters::DDS_REF_CLK.into();
2020-11-09 22:16:44 +08:00
let ad9959 = ad9959::Ad9959::new(
2020-06-16 22:22:12 +08:00
qspi_interface,
2020-12-03 00:01:40 +08:00
reset_pin,
2020-11-09 22:16:44 +08:00
&mut io_update,
2020-11-09 19:30:02 +08:00
&mut delay,
2020-06-16 22:22:12 +08:00
ad9959::Mode::FourBitSerial,
2021-01-06 21:59:01 +08:00
ref_clk.0 as f32,
design_parameters::DDS_MULTIPLIER,
2020-06-16 22:22:12 +08:00
)
2020-11-09 22:16:44 +08:00
.unwrap();
// Return IO_Update
gpiog.pg7 = io_update.into_analog();
ad9959
2020-06-09 00:20:10 +08:00
};
2020-06-21 20:30:49 +08:00
let io_expander = {
let sda = gpiob.pb7.into_alternate_af4().set_open_drain();
let scl = gpiob.pb8.into_alternate_af4().set_open_drain();
2020-10-28 22:41:27 +08:00
let i2c1 = dp.I2C1.i2c(
(scl, sda),
100.khz(),
2020-10-28 22:51:08 +08:00
ccdr.peripheral.I2C1,
&ccdr.clocks,
2020-10-28 22:41:27 +08:00
);
2020-06-21 20:30:49 +08:00
mcp23017::MCP23017::default(i2c1).unwrap()
};
2020-06-09 00:20:10 +08:00
let spi = {
2020-06-16 22:22:12 +08:00
let spi_mosi = gpiod
.pd7
.into_alternate_af5()
.set_speed(hal::gpio::Speed::VeryHigh);
let spi_miso = gpioa
.pa6
.into_alternate_af5()
.set_speed(hal::gpio::Speed::VeryHigh);
let spi_sck = gpiog
.pg11
.into_alternate_af5()
.set_speed(hal::gpio::Speed::VeryHigh);
let config = hal::spi::Config::new(hal::spi::Mode {
polarity: hal::spi::Polarity::IdleHigh,
phase: hal::spi::Phase::CaptureOnSecondTransition,
2020-10-19 23:12:02 +08:00
});
2020-06-09 00:20:10 +08:00
// The maximum frequency of this SPI must be limited due to capacitance on the MISO
// line causing a long RC decay.
2020-06-16 22:22:12 +08:00
dp.SPI1.spi(
(spi_sck, spi_miso, spi_mosi),
config,
5.mhz(),
2020-10-28 22:51:08 +08:00
ccdr.peripheral.SPI1,
&ccdr.clocks,
2020-06-16 22:22:12 +08:00
)
2020-06-09 00:20:10 +08:00
};
2020-10-19 23:12:02 +08:00
let (adc1, adc2) = {
2020-10-28 22:41:27 +08:00
let (mut adc1, mut adc2) = hal::adc::adc12(
dp.ADC1,
dp.ADC2,
&mut delay,
2020-10-28 22:51:08 +08:00
ccdr.peripheral.ADC12,
&ccdr.clocks,
2020-10-28 22:41:27 +08:00
);
2020-06-09 00:20:10 +08:00
2020-10-19 23:12:02 +08:00
let adc1 = {
adc1.calibrate();
adc1.enable()
};
2020-06-09 00:20:10 +08:00
2020-10-19 23:12:02 +08:00
let adc2 = {
adc2.calibrate();
adc2.enable()
};
2020-06-09 00:20:10 +08:00
2020-10-19 23:12:02 +08:00
(adc1, adc2)
2020-06-09 00:20:10 +08:00
};
let adc1_in_p = gpiof.pf11.into_analog();
let adc2_in_p = gpiof.pf14.into_analog();
2020-11-17 21:23:56 +08:00
let pounder_devices = pounder::PounderDevices::new(
io_expander,
spi,
adc1,
adc2,
adc1_in_p,
adc2_in_p,
2020-06-16 22:22:12 +08:00
)
2020-11-17 21:23:56 +08:00
.unwrap();
let dds_output = {
let io_update_trigger = {
let _io_update = gpiog
.pg7
.into_alternate_af2()
.set_speed(hal::gpio::Speed::VeryHigh);
// Configure the IO_Update signal for the DDS.
let mut hrtimer = hrtimer::HighResTimerE::new(
dp.HRTIM_TIME,
dp.HRTIM_MASTER,
dp.HRTIM_COMMON,
ccdr.clocks,
ccdr.peripheral.HRTIM,
);
2020-11-09 19:30:02 +08:00
2021-01-05 01:04:01 +08:00
// IO_Update occurs after a fixed delay from the QSPI write. Note that the timer
// is triggered after the QSPI write, which can take approximately 120nS, so
// there is additional margin.
2020-11-17 21:23:56 +08:00
hrtimer.configure_single_shot(
hrtimer::Channel::Two,
2021-01-05 01:04:01 +08:00
design_parameters::POUNDER_IO_UPDATE_DURATION,
design_parameters::POUNDER_IO_UPDATE_DELAY,
2020-11-17 21:23:56 +08:00
);
2020-11-09 19:30:02 +08:00
2020-11-17 21:23:56 +08:00
// Ensure that we have enough time for an IO-update every sample.
2021-01-06 19:24:09 +08:00
let sample_frequency = {
let timer_frequency: hal::time::Hertz =
design_parameters::TIMER_FREQUENCY.into();
timer_frequency.0 as f32 / ADC_SAMPLE_TICKS as f32
};
let sample_period = 1.0 / sample_frequency;
2021-01-05 01:04:01 +08:00
assert!(
sample_period
> design_parameters::POUNDER_IO_UPDATE_DELAY
);
2020-11-09 19:30:02 +08:00
2020-11-17 21:23:56 +08:00
hrtimer
};
2020-11-09 22:16:44 +08:00
2020-12-03 01:08:49 +08:00
let (qspi, config) = ad9959.freeze();
2020-12-03 00:01:40 +08:00
DdsOutput::new(qspi, io_update_trigger, config)
2020-11-09 19:30:02 +08:00
};
2020-11-17 21:23:56 +08:00
(Some(pounder_devices), Some(dds_output))
2020-06-20 22:43:07 +08:00
} else {
2020-11-17 21:23:56 +08:00
(None, None)
2020-06-09 00:20:10 +08:00
};
let mut eeprom_i2c = {
2020-04-19 19:37:03 +08:00
let sda = gpiof.pf0.into_alternate_af4().set_open_drain();
let scl = gpiof.pf1.into_alternate_af4().set_open_drain();
2020-10-28 22:41:27 +08:00
dp.I2C2.i2c(
(scl, sda),
100.khz(),
2020-10-28 22:51:08 +08:00
ccdr.peripheral.I2C2,
&ccdr.clocks,
2020-10-28 22:41:27 +08:00
)
2020-04-19 19:37:03 +08:00
};
// Configure ethernet pins.
{
// Reset the PHY before configuring pins.
let mut eth_phy_nrst = gpioe.pe3.into_push_pull_output();
eth_phy_nrst.set_low().unwrap();
2020-06-09 20:16:01 +08:00
delay.delay_us(200u8);
eth_phy_nrst.set_high().unwrap();
2020-06-16 22:22:12 +08:00
let _rmii_ref_clk = gpioa
.pa1
.into_alternate_af11()
.set_speed(hal::gpio::Speed::VeryHigh);
let _rmii_mdio = gpioa
.pa2
.into_alternate_af11()
.set_speed(hal::gpio::Speed::VeryHigh);
let _rmii_mdc = gpioc
.pc1
.into_alternate_af11()
.set_speed(hal::gpio::Speed::VeryHigh);
let _rmii_crs_dv = gpioa
.pa7
.into_alternate_af11()
.set_speed(hal::gpio::Speed::VeryHigh);
let _rmii_rxd0 = gpioc
.pc4
.into_alternate_af11()
.set_speed(hal::gpio::Speed::VeryHigh);
let _rmii_rxd1 = gpioc
.pc5
.into_alternate_af11()
.set_speed(hal::gpio::Speed::VeryHigh);
let _rmii_tx_en = gpiob
.pb11
.into_alternate_af11()
.set_speed(hal::gpio::Speed::VeryHigh);
let _rmii_txd0 = gpiob
.pb12
.into_alternate_af11()
.set_speed(hal::gpio::Speed::VeryHigh);
let _rmii_txd1 = gpiog
.pg14
.into_alternate_af11()
.set_speed(hal::gpio::Speed::VeryHigh);
}
let mac_addr = match eeprom::read_eui48(&mut eeprom_i2c) {
Err(_) => {
info!("Could not read EEPROM, using default MAC address");
net::wire::EthernetAddress([0x10, 0xE2, 0xD5, 0x00, 0x03, 0x00])
}
Ok(raw_mac) => net::wire::EthernetAddress(raw_mac),
};
2020-04-22 01:02:52 +08:00
let (network_interface, eth_mac) = {
// Configure the ethernet controller
let (eth_dma, eth_mac) = unsafe {
2020-10-19 23:12:02 +08:00
ethernet::new_unchecked(
2020-06-16 22:22:12 +08:00
dp.ETHERNET_MAC,
dp.ETHERNET_MTL,
dp.ETHERNET_DMA,
&mut DES_RING,
2020-11-26 23:24:42 +08:00
mac_addr,
2020-10-28 22:51:08 +08:00
ccdr.peripheral.ETH1MAC,
&ccdr.clocks,
2020-06-16 22:22:12 +08:00
)
};
2020-10-28 23:14:48 +08:00
// Reset and initialize the ethernet phy.
let mut lan8742a =
ethernet::phy::LAN8742A::new(eth_mac.set_phy_addr(0));
lan8742a.phy_reset();
lan8742a.phy_init();
2020-06-09 20:16:01 +08:00
unsafe { ethernet::enable_interrupt() };
let store = unsafe { &mut NET_STORE };
2020-06-16 22:22:12 +08:00
store.ip_addrs[0] = net::wire::IpCidr::new(
net::wire::IpAddress::v4(10, 0, 16, 99),
24,
);
2020-10-30 20:32:47 +08:00
let default_v4_gw = Ipv4Address::new(10, 0, 16, 1);
2020-10-30 19:16:28 +08:00
let mut routes = Routes::new(&mut store.routes_storage[..]);
routes.add_default_ipv4_route(default_v4_gw).unwrap();
2020-06-16 22:22:12 +08:00
let neighbor_cache =
net::iface::NeighborCache::new(&mut store.neighbor_cache[..]);
let interface = net::iface::EthernetInterfaceBuilder::new(eth_dma)
2020-06-16 22:22:12 +08:00
.ethernet_addr(mac_addr)
.neighbor_cache(neighbor_cache)
.ip_addrs(&mut store.ip_addrs[..])
2020-10-30 19:16:28 +08:00
.routes(routes)
2020-06-16 22:22:12 +08:00
.finalize();
2020-10-28 23:14:48 +08:00
(interface, lan8742a)
};
2020-04-19 19:37:03 +08:00
cp.SCB.enable_icache();
2019-05-31 00:03:48 +08:00
// info!("Version {} {}", build_info::PKG_VERSION, build_info::GIT_VERSION.unwrap());
// info!("Built on {}", build_info::BUILT_TIME_UTC);
// info!("{} {}", build_info::RUSTC_VERSION, build_info::TARGET);
2020-06-17 18:20:45 +08:00
// Utilize the cycle counter for RTIC scheduling.
cp.DWT.enable_cycle_counter();
2020-12-08 23:14:27 +08:00
let mut input_stamper = {
2020-12-08 00:58:36 +08:00
let trigger = gpioa.pa3.into_alternate_af2();
digital_input_stamper::InputStamper::new(
trigger,
2020-12-08 00:58:36 +08:00
timestamp_timer_channels.ch4,
)
};
2021-01-06 20:29:19 +08:00
#[cfg(feature = "pounder_v1_1")]
2020-12-09 20:44:26 +08:00
let pounder_stamper = {
let dma2_streams =
hal::dma::dma::StreamsTuple::new(dp.DMA2, ccdr.peripheral.DMA2);
2020-12-09 20:44:26 +08:00
let etr_pin = gpioa.pa0.into_alternate_af3();
// The frequency in the constructor is dont-care, as we will modify the period + clock
// source manually below.
let tim8 =
dp.TIM8.timer(1.khz(), ccdr.peripheral.TIM8, &ccdr.clocks);
let mut timestamp_timer = timers::PounderTimestampTimer::new(tim8);
2021-01-06 19:59:24 +08:00
// Pounder is configured to generate a 500MHz reference clock, so a 125MHz sync-clock is
// output. As a result, dividing the 125MHz sync-clk provides a 31.25MHz tick rate for
// the timestamp timer. 31.25MHz corresponds with a 32ns tick rate.
timestamp_timer.set_external_clock(timers::Prescaler::Div4);
timestamp_timer.start();
// We want the pounder timestamp timer to overflow once per batch.
2021-01-06 21:59:01 +08:00
let tick_ratio = {
let sync_clk_mhz: f32 = design_parameters::DDS_SYSTEM_CLK.0
as f32
/ design_parameters::DDS_SYNC_CLK_DIV as f32;
sync_clk_mhz / design_parameters::TIMER_FREQUENCY.0 as f32
};
let period = (tick_ratio
* ADC_SAMPLE_TICKS as f32
* SAMPLE_BUFFER_SIZE as f32) as u32
/ 4;
2021-01-06 21:59:01 +08:00
timestamp_timer.set_period_ticks((period - 1).try_into().unwrap());
let tim8_channels = timestamp_timer.channels();
2021-01-06 20:29:19 +08:00
let stamper = pounder::timestamp::Timestamper::new(
timestamp_timer,
dma2_streams.0,
tim8_channels.ch1,
&mut sampling_timer,
2020-12-09 20:44:26 +08:00
etr_pin,
2021-01-06 20:29:19 +08:00
);
Some(stamper)
2020-12-09 20:44:26 +08:00
};
2021-01-06 20:29:19 +08:00
#[cfg(not(feature = "pounder_v1_1"))]
let pounder_stamper = None;
let timestamp_handler = TimestampHandler::new(
4,
3,
ADC_SAMPLE_TICKS_LOG2 as usize,
SAMPLE_BUFFER_SIZE_LOG2,
);
2021-01-18 05:19:14 +08:00
let iir_lockin = iir_int::IIR::default();
let iir_state_lockin = [iir_int::IIRState::default(); 2];
// Start sampling ADCs.
sampling_timer.start();
2020-12-08 00:58:36 +08:00
timestamp_timer.start();
2020-12-08 23:14:27 +08:00
input_stamper.start();
2020-06-08 15:36:28 +08:00
2019-05-31 04:57:41 +08:00
init::LateResources {
2020-11-26 18:33:08 +08:00
afes: (afe0, afe1),
2020-11-03 23:09:00 +08:00
adcs,
dacs,
input_stamper,
dds_output,
2020-06-09 00:20:10 +08:00
pounder: pounder_devices,
2020-12-09 20:44:26 +08:00
pounder_stamper,
timestamp_handler,
iir_lockin,
iir_state_lockin,
eeprom_i2c,
net_interface: network_interface,
eth_mac,
mac_addr,
2019-05-31 04:57:41 +08:00
}
}
/// Main DSP processing routine for Stabilizer.
///
/// # Note
/// Processing time for the DSP application code is bounded by the following constraints:
///
/// DSP application code starts after the ADC has generated a batch of samples and must be
/// completed by the time the next batch of ADC samples has been acquired (plus the FIFO buffer
/// time). If this constraint is not met, firmware will panic due to an ADC input overrun.
///
/// The DSP application code must also fill out the next DAC output buffer in time such that the
/// DAC can switch to it when it has completed the current buffer. If this constraint is not met
/// it's possible that old DAC codes will be generated on the output and the output samples will
/// be delayed by 1 batch.
///
/// Because the ADC and DAC operate at the same rate, these two constraints actually implement
/// the same time bounds, meeting one also means the other is also met.
#[task(binds=DMA1_STR4, resources=[pounder_stamper, adcs, dacs, iir_state, iir_ch, dds_output, input_stamper, timestamp_handler, iir_lockin, iir_state_lockin], priority=2)]
2020-11-26 18:29:16 +08:00
fn process(c: process::Context) {
2021-01-06 20:29:19 +08:00
if let Some(stamper) = c.resources.pounder_stamper {
let pounder_timestamps = stamper.acquire_buffer();
info!("{:?}", pounder_timestamps);
}
2020-11-26 18:29:16 +08:00
let adc_samples = [
c.resources.adcs.0.acquire_buffer(),
c.resources.adcs.1.acquire_buffer(),
2020-11-26 18:29:16 +08:00
];
2020-11-26 18:29:16 +08:00
let dac_samples = [
c.resources.dacs.0.acquire_buffer(),
c.resources.dacs.1.acquire_buffer(),
2020-11-26 18:29:16 +08:00
];
let iir_lockin = c.resources.iir_lockin;
let iir_state_lockin = c.resources.iir_state_lockin;
let iir_ch = c.resources.iir_ch;
let iir_state = c.resources.iir_state;
2021-01-18 05:19:14 +08:00
let (pll_phase, pll_frequency) = c
.resources
.timestamp_handler
.update(c.resources.input_stamper.latest_timestamp());
let frequency = pll_frequency.wrapping_mul(HARMONIC);
let mut phase =
PHASE_OFFSET.wrapping_add(pll_phase.wrapping_mul(HARMONIC));
2021-01-20 21:07:57 +08:00
for i in 0..adc_samples[0].len() {
let m = cossin((phase as i32).wrapping_neg());
phase = phase.wrapping_add(frequency);
let signal = Complex(
iir_lockin.update(
&mut iir_state_lockin[0],
((adc_samples[0][i] as i64 * m.0 as i64) >> 16) as _,
),
iir_lockin.update(
&mut iir_state_lockin[1],
((adc_samples[0][i] as i64 * m.1 as i64) >> 16) as _,
),
);
2021-01-18 05:19:14 +08:00
2021-01-20 21:07:57 +08:00
let mut magnitude =
(signal.0 * signal.0 + signal.1 * signal.1) as _;
let mut phase = atan2(signal.1, signal.0) as _;
2021-01-20 21:07:57 +08:00
for j in 0..iir_state[0].len() {
magnitude =
iir_ch[0][j].update(&mut iir_state[0][j], magnitude);
phase = iir_ch[1][j].update(&mut iir_state[1][j], phase);
}
2021-01-20 21:07:57 +08:00
// Note(unsafe): range clipping to i16 is ensured by IIR filters above.
unsafe {
dac_samples[0][i] =
magnitude.to_int_unchecked::<i16>() as u16 ^ 0x8000;
dac_samples[1][i] =
phase.to_int_unchecked::<i16>() as u16 ^ 0x8000;
}
}
2021-01-13 02:45:34 +08:00
2020-11-17 21:23:56 +08:00
if let Some(dds_output) = c.resources.dds_output {
2020-12-03 00:01:40 +08:00
let builder = dds_output.builder().update_channels(
&[pounder::Channel::Out0.into()],
Some(u32::MAX / 4),
None,
2020-11-17 21:23:56 +08:00
None,
);
2020-12-03 00:01:40 +08:00
builder.write_profile();
2020-11-03 16:36:03 +08:00
}
}
2020-11-26 18:33:08 +08:00
#[idle(resources=[net_interface, pounder, mac_addr, eth_mac, iir_state, iir_ch, afes])]
fn idle(mut c: idle::Context) -> ! {
let mut socket_set_entries: [_; 8] = Default::default();
2020-06-16 22:22:12 +08:00
let mut sockets =
net::socket::SocketSet::new(&mut socket_set_entries[..]);
let mut rx_storage = [0; TCP_RX_BUFFER_SIZE];
let mut tx_storage = [0; TCP_TX_BUFFER_SIZE];
2020-06-09 01:13:55 +08:00
let tcp_handle = {
2020-06-16 22:22:12 +08:00
let tcp_rx_buffer =
net::socket::TcpSocketBuffer::new(&mut rx_storage[..]);
let tcp_tx_buffer =
net::socket::TcpSocketBuffer::new(&mut tx_storage[..]);
let tcp_socket =
net::socket::TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer);
sockets.add(tcp_socket)
};
2020-04-29 01:26:43 +08:00
let mut server = server::Server::new();
2020-04-29 01:15:00 +08:00
let mut time = 0u32;
let mut next_ms = Instant::now();
// TODO: Replace with reference to CPU clock from CCDR.
next_ms += 400_000.cycles();
loop {
let tick = Instant::now() > next_ms;
if tick {
next_ms += 400_000.cycles();
time += 1;
}
2019-05-31 04:57:41 +08:00
{
2019-11-24 22:09:52 +08:00
let socket =
2020-06-09 01:13:55 +08:00
&mut *sockets.get::<net::socket::TcpSocket>(tcp_handle);
2019-06-03 23:06:11 +08:00
if socket.state() == net::socket::TcpState::CloseWait {
socket.close();
} else if !(socket.is_open() || socket.is_listening()) {
2019-11-24 22:09:52 +08:00
socket
.listen(1235)
.unwrap_or_else(|e| warn!("TCP listen error: {:?}", e));
2019-05-31 04:57:41 +08:00
} else {
server.poll(socket, |req| {
info!("Got request: {:?}", req);
2020-06-03 22:53:25 +08:00
route_request!(req,
readable_attributes: [
"stabilizer/iir/state": (|| {
2020-06-03 23:04:09 +08:00
let state = c.resources.iir_state.lock(|iir_state|
server::Status {
t: time,
x0: iir_state[0][0][0],
y0: iir_state[0][0][2],
x1: iir_state[1][0][0],
y1: iir_state[1][0][2],
2020-06-03 23:04:09 +08:00
});
Ok::<server::Status, ()>(state)
}),
// "_b" means cascades 2nd IIR
"stabilizer/iir_b/state": (|| {
let state = c.resources.iir_state.lock(|iir_state|
server::Status {
t: time,
x0: iir_state[0][IIR_CASCADE_LENGTH-1][0],
y0: iir_state[0][IIR_CASCADE_LENGTH-1][2],
x1: iir_state[1][IIR_CASCADE_LENGTH-1][0],
y1: iir_state[1][IIR_CASCADE_LENGTH-1][2],
2020-06-03 23:04:09 +08:00
});
Ok::<server::Status, ()>(state)
}),
2020-11-26 18:33:08 +08:00
"stabilizer/afe0/gain": (|| c.resources.afes.0.get_gain()),
2020-12-08 00:29:36 +08:00
"stabilizer/afe1/gain": (|| c.resources.afes.1.get_gain())
],
2020-06-03 23:04:09 +08:00
modifiable_attributes: [
"stabilizer/iir0/state": server::IirRequest, (|req: server::IirRequest| {
2020-06-03 23:15:57 +08:00
c.resources.iir_ch.lock(|iir_ch| {
if req.channel > 1 {
return Err(());
}
iir_ch[req.channel as usize][0] = req.iir;
2020-06-03 23:15:57 +08:00
Ok::<server::IirRequest, ()>(req)
})
}),
"stabilizer/iir1/state": server::IirRequest, (|req: server::IirRequest| {
2020-06-03 23:15:57 +08:00
c.resources.iir_ch.lock(|iir_ch| {
if req.channel > 1 {
return Err(());
}
iir_ch[req.channel as usize][0] = req.iir;
Ok::<server::IirRequest, ()>(req)
})
}),
"stabilizer/iir_b0/state": server::IirRequest, (|req: server::IirRequest| {
c.resources.iir_ch.lock(|iir_ch| {
if req.channel > 1 {
return Err(());
}
iir_ch[req.channel as usize][IIR_CASCADE_LENGTH-1] = req.iir;
Ok::<server::IirRequest, ()>(req)
})
}),
"stabilizer/iir_b1/state": server::IirRequest,(|req: server::IirRequest| {
c.resources.iir_ch.lock(|iir_ch| {
if req.channel > 1 {
return Err(());
}
iir_ch[req.channel as usize][IIR_CASCADE_LENGTH-1] = req.iir;
2020-06-03 23:15:57 +08:00
Ok::<server::IirRequest, ()>(req)
})
}),
"stabilizer/afe0/gain": afe::Gain, (|gain| {
c.resources.afes.0.set_gain(gain);
2020-11-26 23:24:42 +08:00
Ok::<(), ()>(())
}),
"stabilizer/afe1/gain": afe::Gain, (|gain| {
c.resources.afes.1.set_gain(gain);
2020-11-26 23:24:42 +08:00
Ok::<(), ()>(())
})
]
)
2019-06-03 23:06:11 +08:00
});
2019-05-31 04:57:41 +08:00
}
}
2020-06-16 22:22:12 +08:00
let sleep = match c.resources.net_interface.poll(
&mut sockets,
net::time::Instant::from_millis(time as i64),
) {
2020-11-26 23:24:42 +08:00
Ok(changed) => !changed,
2019-05-31 04:57:41 +08:00
Err(net::Error::Unrecognized) => true,
2019-11-24 22:09:52 +08:00
Err(e) => {
info!("iface poll error: {:?}", e);
true
}
2020-04-29 01:15:00 +08:00
};
if sleep {
cortex_m::asm::wfi();
2019-05-31 04:57:41 +08:00
}
2019-05-31 00:03:48 +08:00
}
}
2019-04-28 19:37:14 +08:00
2020-06-09 20:16:01 +08:00
#[task(binds = ETH, priority = 1)]
fn eth(_: eth::Context) {
unsafe { ethernet::interrupt_handler() }
2019-05-31 00:03:48 +08:00
}
#[task(binds = SPI2, priority = 3)]
2020-11-03 16:36:03 +08:00
fn spi2(_: spi2::Context) {
panic!("ADC0 input overrun");
}
#[task(binds = SPI3, priority = 3)]
2020-11-03 16:36:03 +08:00
fn spi3(_: spi3::Context) {
panic!("ADC0 input overrun");
}
#[task(binds = SPI4, priority = 3)]
2020-11-11 19:09:27 +08:00
fn spi4(_: spi4::Context) {
panic!("DAC0 output error");
}
#[task(binds = SPI5, priority = 3)]
2020-11-11 19:09:27 +08:00
fn spi5(_: spi5::Context) {
panic!("DAC1 output error");
}
2019-05-31 00:03:48 +08:00
extern "C" {
2020-06-17 18:20:45 +08:00
// hw interrupt handlers for RTIC to use for scheduling tasks
2019-05-31 04:57:41 +08:00
// one per priority
2019-05-31 00:03:48 +08:00
fn DCMI();
fn JPEG();
fn SDMMC();
}
};
2019-03-18 19:56:26 +08:00
#[exception]
fn HardFault(ef: &cortex_m_rt::ExceptionFrame) -> ! {
panic!("HardFault at {:#?}", ef);
}
#[exception]
fn DefaultHandler(irqn: i16) {
panic!("Unhandled exception (IRQn = {})", irqn);
}