From d7bdafeff248a6aef6d06cc585ad55142ab0908b Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Wed, 3 Jun 2020 15:46:18 +0200 Subject: [PATCH 1/6] Adding wip changes to ethernet interface --- .cargo/config | 2 +- Cargo.toml | 2 +- src/afe.rs | 3 +- src/main.rs | 82 ++++++++++++++++++++++++++++++---- src/pounder/mod.rs | 4 +- src/server.rs | 109 ++++++++++++++++++++++++--------------------- 6 files changed, 136 insertions(+), 66 deletions(-) diff --git a/.cargo/config b/.cargo/config index 382c36e..a765d53 100644 --- a/.cargo/config +++ b/.cargo/config @@ -1,5 +1,5 @@ [target.'cfg(all(target_arch = "arm", target_os = "none"))'] -runner = "gdb-multiarch -q -x openocd.gdb" +runner = "gdb-multiarch -q -x bmp.gdb" rustflags = ["-C", "link-arg=-Tlink.x"] [build] diff --git a/Cargo.toml b/Cargo.toml index acaad2f..7522e17 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,7 +33,7 @@ log = "0.4" panic-semihosting = { version = "0.5", optional = true } panic-halt = "0.2" serde = { version = "1.0", features = ["derive"], default-features = false } -heapless = "0.5" +heapless = "0.5.4" serde-json-core = "0.1" cortex-m-rtfm = "0.5" embedded-hal = "0.2.3" diff --git a/src/afe.rs b/src/afe.rs index c3d9f3c..8dabf06 100644 --- a/src/afe.rs +++ b/src/afe.rs @@ -1,6 +1,7 @@ use embedded_hal; +use serde::{Serialize, Deserialize}; -#[derive(Copy, Clone, Debug)] +#[derive(Copy, Clone, Debug, Serialize, Deserialize)] pub enum Gain { G1 = 0b00, G2 = 0b01, diff --git a/src/main.rs b/src/main.rs index 4401bfe..e909af7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -39,6 +39,12 @@ use stm32h7xx_hal::{ prelude::*, stm32 as pac, }; +use pounder::Error; + +use heapless::{ + String, + consts::*, +}; use embedded_hal::{ digital::v2::OutputPin, @@ -111,12 +117,64 @@ type AFE2 = afe::ProgrammableGainAmplifier< hal::gpio::gpiod::PD14>, hal::gpio::gpiod::PD15>>; +macro_rules! route_request { + ($request:ident, $buffer:ident, + readable_attributes: [$(($read_attribute:tt, $getter:tt)),*], + modifiable_attributes: [$(($write_attribute:tt, $TYPE:ty, $setter:tt)),*]) => { + match $request { + server::Request::Read{attribute} => { + match attribute { + $( + &$read_attribute => { + let value = match $getter() { + Ok(data) => data, + Err(_) => return server::Response::error(attribute, + "Failed to set attribute"), + }; + + $buffer = match serde_json_core::to_string(&value) { + Ok(data) => data, + Err(_) => return server::Response::error(attribute, + "Failed to encode attribute value"), + }; + + server::Response::success(attribute, &$buffer) + }, + )* + _ => server::Response::error(attribute, "Unknown attribute") + } + }, + server::Request::Write{attribute, value} => { + match attribute { + $( + &$write_attribute => { + let new_value = match serde_json_core::from_str::<$TYPE>(value) { + Ok(data) => data, + Err(_) => return server::Response::error(attribute, + "Failed to decode value"), + }; + + match $setter(new_value) { + Ok(_) => server::Response::success(attribute, value), + Err(_) => server::Response::error(attribute, + "Failed to set attribute"), + } + } + )* + _ => server::Response::error(attribute, "Unknown attribute") + } + } + } + } +} + + #[rtfm::app(device = stm32h7xx_hal::stm32, peripherals = true, monotonic = rtfm::cyccnt::CYCCNT)] const APP: () = { struct Resources { adc1: hal::spi::Spi, dac1: hal::spi::Spi, - _afe1: AFE1, + afe1: AFE1, adc2: hal::spi::Spi, dac2: hal::spi::Spi, @@ -446,7 +504,7 @@ const APP: () = { dac1: dac1_spi, adc2: adc2_spi, dac2: dac2_spi, - _afe1: afe1, + afe1: afe1, _afe2: afe2, dbg_pin: debug_pin, @@ -504,7 +562,7 @@ const APP: () = { cortex_m::asm::bkpt(); } - #[idle(resources=[net_interface, mac_addr, iir_state, iir_ch])] + #[idle(resources=[net_interface, mac_addr, iir_state, iir_ch, afe1])] fn idle(mut c: idle::Context) -> ! { let mut socket_set_entries: [_; 8] = Default::default(); @@ -536,6 +594,8 @@ const APP: () = { // TODO: Replace with reference to CPU clock from CCDR. next_ms += 400_000.cycles(); + let buffer: String = String::new(); + loop { let tick = Instant::now() > next_ms; @@ -574,12 +634,16 @@ const APP: () = { .listen(1235) .unwrap_or_else(|e| warn!("TCP listen error: {:?}", e)); } else { - server.poll(socket, |req: &server::Request| { - if req.channel < 2 { - c.resources.iir_ch.lock(|iir_ch| { - iir_ch[req.channel as usize] = req.iir - }); - } + server.poll(socket, |req| { + info!("Got request: {:?}", req); + route_request!(req, buffer, + readable_attributes: [ + ("stabilizer/afe0/gain", (|| Ok::(c.resources.afe1.get_gain()))) + ], + modifiable_attributes: [ + ("stabilizer/afe0/gain", afe::Gain, (|gain| Ok::<(), ()>(c.resources.afe1.set_gain(gain)))) + ] + ) }); } } diff --git a/src/pounder/mod.rs b/src/pounder/mod.rs index b3ce19f..d1f445b 100644 --- a/src/pounder/mod.rs +++ b/src/pounder/mod.rs @@ -1,14 +1,14 @@ use mcp23017; use ad9959; -pub mod error; +mod error; pub mod attenuators; mod rf_power; pub mod types; use super::hal; -use error::Error; +pub use error::Error; use attenuators::AttenuatorInterface; use types::{DdsChannel, InputChannel}; use rf_power::PowerMeasurementInterface; diff --git a/src/server.rs b/src/server.rs index 8cd48ce..e2bf5e1 100644 --- a/src/server.rs +++ b/src/server.rs @@ -8,7 +8,6 @@ use core::fmt::Write; use serde::{ - de::DeserializeOwned, Deserialize, Serialize }; @@ -19,18 +18,43 @@ use serde_json_core::{ }; use super::net; -use super::iir::IIR; -#[derive(Deserialize, Serialize)] -pub struct Request { - pub channel: u8, - pub iir: IIR, +#[derive(Deserialize, Serialize, Debug)] +pub enum Request<'a, 'b> { + Read{attribute: &'a str}, + Write{attribute: &'a str, value: &'b str}, } #[derive(Serialize)] -pub struct Response<'a> { +pub struct Response<'a, 'b> { code: i32, - message: &'a str, + attribute: &'a str, + value: &'b str, +} + +impl<'a, 'b> Response<'a, 'b> { + pub fn success<'c, 'd>(attribute: &'c str, value: &'d str) -> Self + where + 'c: 'a, + 'd: 'b, + { + Self { code: 200, attribute: attribute, value: value} + } + + pub fn error<'c, 'd>(attribute: &'c str, message: &'d str) -> Self + where + 'c: 'a, + 'd: 'b, + { + Self { code: 400, attribute: attribute, value: message} + } + + pub fn custom<'c>(code: i32, message : &'c str) -> Self + where + 'c: 'b, + { + Self { code: code, attribute: "", value: message} + } } #[derive(Serialize)] @@ -61,73 +85,54 @@ impl Server { } } - pub fn poll( + pub fn poll<'a, 'b, F>( &mut self, socket: &mut net::socket::TcpSocket, f: F, - ) -> Option + ) where - T: DeserializeOwned, - F: FnOnce(&T) -> R, + F: FnOnce(&Request) -> Response<'a, 'b> { while socket.can_recv() { - let found = socket - .recv(|buf| { - let (len, found) = - match buf.iter().position(|&c| c as char == '\n') { - Some(end) => (end + 1, true), - None => (buf.len(), false), - }; - if self.data.len() + len >= self.data.capacity() { - self.discard = true; - self.data.clear(); - } else if !self.discard && len > 0 { - self.data.extend_from_slice(&buf[..len]).unwrap(); - } - (len, found) - }) - .unwrap(); + let found = socket.recv(|buf| { + let (len, found) = + match buf.iter().position(|&c| c as char == '\n') { + Some(end) => (end + 1, true), + None => (buf.len(), false), + }; + if self.data.len() + len >= self.data.capacity() { + self.discard = true; + self.data.clear(); + } else if !self.discard && len > 0 { + self.data.extend_from_slice(&buf[..len]).unwrap(); + } + (len, found) + }).unwrap(); + if found { if self.discard { self.discard = false; - json_reply( - socket, - &Response { - code: 520, - message: "command buffer overflow", - }, + json_reply(socket, &Response::custom(520, "command buffer overflow"), ); self.data.clear(); } else { - let r = from_slice::(&self.data[..self.data.len() - 1]); + let r = from_slice::(&self.data[..self.data.len() - 1]); self.data.clear(); match r { Ok(res) => { - let r = f(&res); - json_reply( - socket, - &Response { - code: 200, - message: "ok", - }, - ); - return Some(r); - } + let response = f(&res); + json_reply(socket, &response); + return; + }, Err(err) => { warn!("parse error {:?}", err); - json_reply( - socket, - &Response { - code: 550, - message: "parse error", - }, + json_reply(socket, &Response::custom(550, "parse error"), ); } } } } } - None } } From fa5b1aa152c9720c57c662e74b73df8ba222d9e5 Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Wed, 3 Jun 2020 16:53:25 +0200 Subject: [PATCH 2/6] Adding prototype ethernet interface --- Cargo.lock | 1 + Cargo.toml | 2 +- src/main.rs | 71 +++++++++++++++++++++++++-------------------------- src/server.rs | 44 ++++++++++++------------------- 4 files changed, 53 insertions(+), 65 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 44886bb..13e1a8c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -210,6 +210,7 @@ dependencies = [ "as-slice 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", "generic-array 0.13.2 (registry+https://github.com/rust-lang/crates.io-index)", "hash32 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.111 (registry+https://github.com/rust-lang/crates.io-index)", "stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)", ] diff --git a/Cargo.toml b/Cargo.toml index 7522e17..31e0403 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,7 +33,7 @@ log = "0.4" panic-semihosting = { version = "0.5", optional = true } panic-halt = "0.2" serde = { version = "1.0", features = ["derive"], default-features = false } -heapless = "0.5.4" +heapless = { version = "0.5.4", features = ["serde"] } serde-json-core = "0.1" cortex-m-rtfm = "0.5" embedded-hal = "0.2.3" diff --git a/src/main.rs b/src/main.rs index e909af7..fbe8d07 100644 --- a/src/main.rs +++ b/src/main.rs @@ -39,7 +39,6 @@ use stm32h7xx_hal::{ prelude::*, stm32 as pac, }; -use pounder::Error; use heapless::{ String, @@ -109,16 +108,16 @@ const SCALE: f32 = ((1 << 15) - 1) as f32; const TCP_RX_BUFFER_SIZE: usize = 8192; const TCP_TX_BUFFER_SIZE: usize = 8192; -type AFE1 = afe::ProgrammableGainAmplifier< +type AFE0 = afe::ProgrammableGainAmplifier< hal::gpio::gpiof::PF2>, hal::gpio::gpiof::PF5>>; -type AFE2 = afe::ProgrammableGainAmplifier< +type AFE1 = afe::ProgrammableGainAmplifier< hal::gpio::gpiod::PD14>, hal::gpio::gpiod::PD15>>; macro_rules! route_request { - ($request:ident, $buffer:ident, + ($request:ident, readable_attributes: [$(($read_attribute:tt, $getter:tt)),*], modifiable_attributes: [$(($write_attribute:tt, $TYPE:ty, $setter:tt)),*]) => { match $request { @@ -132,13 +131,13 @@ macro_rules! route_request { "Failed to set attribute"), }; - $buffer = match serde_json_core::to_string(&value) { + let encoded_data: String = match serde_json_core::to_string(&value) { Ok(data) => data, Err(_) => return server::Response::error(attribute, "Failed to encode attribute value"), }; - server::Response::success(attribute, &$buffer) + server::Response::success(attribute, &encoded_data) }, )* _ => server::Response::error(attribute, "Unknown attribute") @@ -172,13 +171,13 @@ macro_rules! route_request { #[rtfm::app(device = stm32h7xx_hal::stm32, peripherals = true, monotonic = rtfm::cyccnt::CYCCNT)] const APP: () = { struct Resources { - adc1: hal::spi::Spi, - dac1: hal::spi::Spi, - afe1: AFE1, + adc0: hal::spi::Spi, + dac0: hal::spi::Spi, + afe0: AFE0, - adc2: hal::spi::Spi, - dac2: hal::spi::Spi, - _afe2: AFE2, + adc1: hal::spi::Spi, + dac1: hal::spi::Spi, + afe1: AFE1, eeprom_i2c: hal::i2c::I2c, @@ -234,20 +233,20 @@ const APP: () = { let gpiof = dp.GPIOF.split(&mut clocks.ahb4); let gpiog = dp.GPIOG.split(&mut clocks.ahb4); - let afe1 = { + 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 afe2 = { + 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) }; // Configure the SPI interfaces to the ADCs and DACs. - let adc1_spi = { + let adc0_spi = { 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(); @@ -272,7 +271,7 @@ const APP: () = { spi }; - let adc2_spi = { + let adc1_spi = { 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(); @@ -296,7 +295,7 @@ const APP: () = { spi }; - let dac1_spi = { + let dac0_spi = { let spi_miso = gpioe.pe5.into_alternate_af5(); let spi_sck = gpioe.pe2.into_alternate_af5(); let _spi_nss = gpioe.pe4.into_alternate_af5(); @@ -313,7 +312,7 @@ const APP: () = { dp.SPI4.spi((spi_sck, spi_miso, hal::spi::NoMosi), config, 25.mhz(), &clocks) }; - let dac2_spi = { + let dac1_spi = { let spi_miso = gpiof.pf8.into_alternate_af5(); let spi_sck = gpiof.pf7.into_alternate_af5(); let _spi_nss = gpiof.pf6.into_alternate_af5(); @@ -500,12 +499,12 @@ const APP: () = { timer2.listen(hal::timer::Event::TimeOut); init::LateResources { + adc0: adc0_spi, + dac0: dac0_spi, adc1: adc1_spi, dac1: dac1_spi, - adc2: adc2_spi, - dac2: dac2_spi, + afe0: afe0, afe1: afe1, - _afe2: afe2, dbg_pin: debug_pin, dac_pin: dac_pin, @@ -519,19 +518,19 @@ const APP: () = { } } - #[task(binds = TIM2, resources = [dbg_pin, timer, adc1, adc2])] + #[task(binds = TIM2, resources = [dbg_pin, timer, adc0, adc1])] fn tim2(mut c: tim2::Context) { c.resources.timer.clear_uif_bit(); c.resources.dbg_pin.set_high().unwrap(); // Start a SPI transaction on ADC0 and ADC1 + c.resources.adc0.lock(|adc| adc.spi.cr1.modify(|_, w| w.cstart().set_bit())); c.resources.adc1.lock(|adc| adc.spi.cr1.modify(|_, w| w.cstart().set_bit())); - c.resources.adc2.lock(|adc| adc.spi.cr1.modify(|_, w| w.cstart().set_bit())); c.resources.dbg_pin.set_low().unwrap(); } - #[task(binds = SPI2, resources = [adc1, dac1, adc2, dac2, iir_state, iir_ch, dac_pin], priority = 2)] + #[task(binds = SPI2, resources = [adc0, dac0, adc1, dac1, iir_state, iir_ch, dac_pin], priority = 2)] fn adc_spi(c: adc_spi::Context) { #[cfg(feature = "bkpt")] cortex_m::asm::bkpt(); @@ -539,30 +538,30 @@ const APP: () = { c.resources.dac_pin.set_high().unwrap(); let output_ch1 = { - let a: u16 = c.resources.adc1.read().unwrap(); + let a: u16 = c.resources.adc0.read().unwrap(); let x0 = f32::from(a as i16); let y0 = c.resources.iir_ch[0].update(&mut c.resources.iir_state[0], x0); y0 as i16 as u16 ^ 0x8000 }; - c.resources.adc1.spi.ifcr.write(|w| w.eotc().set_bit()); + c.resources.adc0.spi.ifcr.write(|w| w.eotc().set_bit()); let output_ch2 = { - let a: u16 = nb::block!(c.resources.adc2.read()).unwrap(); + let a: u16 = nb::block!(c.resources.adc1.read()).unwrap(); let x0 = f32::from(a as i16); let y0 = c.resources.iir_ch[1].update(&mut c.resources.iir_state[1], x0); y0 as i16 as u16 ^ 0x8000 }; - c.resources.adc2.spi.ifcr.write(|w| w.eotc().set_bit()); + c.resources.adc1.spi.ifcr.write(|w| w.eotc().set_bit()); - c.resources.dac1.send(output_ch1).unwrap(); - c.resources.dac2.send(output_ch2).unwrap(); + c.resources.dac0.send(output_ch1).unwrap(); + c.resources.dac1.send(output_ch2).unwrap(); c.resources.dac_pin.set_low().unwrap(); #[cfg(feature = "bkpt")] cortex_m::asm::bkpt(); } - #[idle(resources=[net_interface, mac_addr, iir_state, iir_ch, afe1])] + #[idle(resources=[net_interface, mac_addr, iir_state, iir_ch, afe0, afe1])] fn idle(mut c: idle::Context) -> ! { let mut socket_set_entries: [_; 8] = Default::default(); @@ -594,8 +593,6 @@ const APP: () = { // TODO: Replace with reference to CPU clock from CCDR. next_ms += 400_000.cycles(); - let buffer: String = String::new(); - loop { let tick = Instant::now() > next_ms; @@ -636,12 +633,14 @@ const APP: () = { } else { server.poll(socket, |req| { info!("Got request: {:?}", req); - route_request!(req, buffer, + route_request!(req, readable_attributes: [ - ("stabilizer/afe0/gain", (|| Ok::(c.resources.afe1.get_gain()))) + ("stabilizer/afe0/gain", (|| Ok::(c.resources.afe0.get_gain()))), + ("stabilizer/afe1/gain", (|| Ok::(c.resources.afe1.get_gain()))) ], modifiable_attributes: [ - ("stabilizer/afe0/gain", afe::Gain, (|gain| Ok::<(), ()>(c.resources.afe1.set_gain(gain)))) + ("stabilizer/afe0/gain", afe::Gain, (|gain| Ok::<(), ()>(c.resources.afe0.set_gain(gain)))), + ("stabilizer/afe1/gain", afe::Gain, (|gain| Ok::<(), ()>(c.resources.afe1.set_gain(gain)))) ] ) }); diff --git a/src/server.rs b/src/server.rs index e2bf5e1..c0e46cd 100644 --- a/src/server.rs +++ b/src/server.rs @@ -26,34 +26,26 @@ pub enum Request<'a, 'b> { } #[derive(Serialize)] -pub struct Response<'a, 'b> { +pub struct Response { code: i32, - attribute: &'a str, - value: &'b str, + attribute: String, + value: String, } -impl<'a, 'b> Response<'a, 'b> { - pub fn success<'c, 'd>(attribute: &'c str, value: &'d str) -> Self - where - 'c: 'a, - 'd: 'b, +impl Response { + pub fn success<'a, 'b>(attribute: &'a str, value: &'b str) -> Self { - Self { code: 200, attribute: attribute, value: value} + Self { code: 200, attribute: String::from(attribute), value: String::from(value)} } - pub fn error<'c, 'd>(attribute: &'c str, message: &'d str) -> Self - where - 'c: 'a, - 'd: 'b, + pub fn error<'a, 'b>(attribute: &'a str, message: &'b str) -> Self { - Self { code: 400, attribute: attribute, value: message} + Self { code: 400, attribute: String::from(attribute), value: String::from(message)} } - pub fn custom<'c>(code: i32, message : &'c str) -> Self - where - 'c: 'b, + pub fn custom<'a>(code: i32, message : &'a str) -> Self { - Self { code: code, attribute: "", value: message} + Self { code: code, attribute: String::from(""), value: String::from(message)} } } @@ -85,13 +77,13 @@ impl Server { } } - pub fn poll<'a, 'b, F>( + pub fn poll( &mut self, socket: &mut net::socket::TcpSocket, - f: F, + mut f: F, ) where - F: FnOnce(&Request) -> Response<'a, 'b> + F: FnMut(&Request) -> Response { while socket.can_recv() { let found = socket.recv(|buf| { @@ -112,25 +104,21 @@ impl Server { if found { if self.discard { self.discard = false; - json_reply(socket, &Response::custom(520, "command buffer overflow"), - ); - self.data.clear(); + json_reply(socket, &Response::custom(520, "command buffer overflow")); } else { let r = from_slice::(&self.data[..self.data.len() - 1]); - self.data.clear(); match r { Ok(res) => { let response = f(&res); json_reply(socket, &response); - return; }, Err(err) => { warn!("parse error {:?}", err); - json_reply(socket, &Response::custom(550, "parse error"), - ); + json_reply(socket, &Response::custom(550, "parse error")); } } } + self.data.clear(); } } } From 7cb18cf19782038796a2dda580d055aab0782d8a Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Wed, 3 Jun 2020 17:04:09 +0200 Subject: [PATCH 3/6] Simplifying TCP sockets --- src/main.rs | 60 +++++++++++++++++++++++------------------------------ 1 file changed, 26 insertions(+), 34 deletions(-) diff --git a/src/main.rs b/src/main.rs index fbe8d07..06f99e4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -576,15 +576,6 @@ const APP: () = { sockets.add(tcp_socket) }; - let mut rx_storage2 = [0; TCP_RX_BUFFER_SIZE]; - let mut tx_storage2 = [0; TCP_TX_BUFFER_SIZE]; - let tcp_handle1 = { - let tcp_rx_buffer = net::socket::TcpSocketBuffer::new(&mut rx_storage2[..]); - let tcp_tx_buffer = net::socket::TcpSocketBuffer::new(&mut tx_storage2[..]); - let tcp_socket = net::socket::TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer); - sockets.add(tcp_socket) - }; - let mut server = server::Server::new(); let mut time = 0u32; @@ -601,29 +592,9 @@ const APP: () = { time += 1; } - { - let mut socket = sockets.get::(tcp_handle0); - if socket.state() == net::socket::TcpState::CloseWait { - socket.close(); - } else if !(socket.is_open() || socket.is_listening()) { - socket - .listen(1234) - .unwrap_or_else(|e| warn!("TCP listen error: {:?}", e)); - } else if tick && socket.can_send() { - let s = c.resources.iir_state.lock(|iir_state| server::Status { - t: time, - x0: iir_state[0][0], - y0: iir_state[0][2], - x1: iir_state[1][0], - y1: iir_state[1][2], - }); - server::json_reply(&mut socket, &s); - } - } - { let socket = - &mut *sockets.get::(tcp_handle1); + &mut *sockets.get::(tcp_handle0); if socket.state() == net::socket::TcpState::CloseWait { socket.close(); } else if !(socket.is_open() || socket.is_listening()) { @@ -635,12 +606,33 @@ const APP: () = { info!("Got request: {:?}", req); route_request!(req, readable_attributes: [ - ("stabilizer/afe0/gain", (|| Ok::(c.resources.afe0.get_gain()))), - ("stabilizer/afe1/gain", (|| Ok::(c.resources.afe1.get_gain()))) + ("stabilizer/iir/state", (|| { + let state = c.resources.iir_state.lock(|iir_state| + server::Status { + t: time, + x0: iir_state[0][0], + y0: iir_state[0][2], + x1: iir_state[1][0], + y1: iir_state[1][2], + }); + + Ok::(state) + })), + ("stabilizer/afe0/gain", (|| { + Ok::(c.resources.afe0.get_gain()) + })), + ("stabilizer/afe1/gain", (|| { + Ok::(c.resources.afe1.get_gain()) + })) ], + modifiable_attributes: [ - ("stabilizer/afe0/gain", afe::Gain, (|gain| Ok::<(), ()>(c.resources.afe0.set_gain(gain)))), - ("stabilizer/afe1/gain", afe::Gain, (|gain| Ok::<(), ()>(c.resources.afe1.set_gain(gain)))) + ("stabilizer/afe0/gain", afe::Gain, (|gain| { + Ok::<(), ()>(c.resources.afe0.set_gain(gain)) + })), + ("stabilizer/afe1/gain", afe::Gain, (|gain| { + Ok::<(), ()>(c.resources.afe1.set_gain(gain)) + })) ] ) }); From df5dcb3dc1e004a6baa297429819932848d56968 Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Wed, 3 Jun 2020 17:15:57 +0200 Subject: [PATCH 4/6] Adding support for modifying IIR state --- src/main.rs | 22 ++++++++++++++++++++++ src/server.rs | 7 +++++++ 2 files changed, 29 insertions(+) diff --git a/src/main.rs b/src/main.rs index 06f99e4..ce36e86 100644 --- a/src/main.rs +++ b/src/main.rs @@ -627,6 +627,28 @@ const APP: () = { ], modifiable_attributes: [ + ("stabilizer/iir0/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] = req.iir; + + Ok::(req) + }) + })), + ("stabilizer/iir1/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] = req.iir; + + Ok::(req) + }) + })), ("stabilizer/afe0/gain", afe::Gain, (|gain| { Ok::<(), ()>(c.resources.afe0.set_gain(gain)) })), diff --git a/src/server.rs b/src/server.rs index c0e46cd..68edafe 100644 --- a/src/server.rs +++ b/src/server.rs @@ -18,6 +18,7 @@ use serde_json_core::{ }; use super::net; +use super::iir; #[derive(Deserialize, Serialize, Debug)] pub enum Request<'a, 'b> { @@ -25,6 +26,12 @@ pub enum Request<'a, 'b> { Write{attribute: &'a str, value: &'b str}, } +#[derive(Serialize, Deserialize)] +pub struct IirRequest { + pub channel: u8, + pub iir: iir::IIR, +} + #[derive(Serialize)] pub struct Response { code: i32, From 7494ece6591d5388842190a2446d39158eea2027 Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Tue, 9 Jun 2020 14:16:01 +0200 Subject: [PATCH 5/6] Refactoring ethernet interface --- .cargo/config | 2 +- stabilizer/src/main.rs | 73 +++++++++++++++++++++++----------------- stabilizer/src/server.rs | 13 +++++-- 3 files changed, 53 insertions(+), 35 deletions(-) diff --git a/.cargo/config b/.cargo/config index a765d53..382c36e 100644 --- a/.cargo/config +++ b/.cargo/config @@ -1,5 +1,5 @@ [target.'cfg(all(target_arch = "arm", target_os = "none"))'] -runner = "gdb-multiarch -q -x bmp.gdb" +runner = "gdb-multiarch -q -x openocd.gdb" rustflags = ["-C", "link-arg=-Tlink.x"] [build] diff --git a/stabilizer/src/main.rs b/stabilizer/src/main.rs index a5eee0b..1cf6e4b 100644 --- a/stabilizer/src/main.rs +++ b/stabilizer/src/main.rs @@ -113,47 +113,59 @@ macro_rules! route_request { ($request:ident, readable_attributes: [$(($read_attribute:tt, $getter:tt)),*], modifiable_attributes: [$(($write_attribute:tt, $TYPE:ty, $setter:tt)),*]) => { - match $request { - server::Request::Read{attribute} => { - match attribute { + match $request.req { + server::AccessRequest::Read => { + match $request.attribute { $( - &$read_attribute => { + $read_attribute => { let value = match $getter() { Ok(data) => data, - Err(_) => return server::Response::error(attribute, + Err(_) => return server::Response::error($request.attribute, "Failed to set attribute"), }; let encoded_data: String = match serde_json_core::to_string(&value) { Ok(data) => data, - Err(_) => return server::Response::error(attribute, + Err(_) => return server::Response::error($request.attribute, "Failed to encode attribute value"), }; - server::Response::success(attribute, &encoded_data) + // Encoding data into a string surrounds it with qutotations. Because this + // value is then serialzed into another string, we remove the double + // quotations because they cannot be properly escaped. + server::Response::success($request.attribute, + &encoded_data[1..encoded_data.len()-1]) }, )* - _ => server::Response::error(attribute, "Unknown attribute") + _ => server::Response::error($request.attribute, "Unknown attribute") } }, - server::Request::Write{attribute, value} => { - match attribute { + server::AccessRequest::Write => { + match $request.attribute { $( - &$write_attribute => { - let new_value = match serde_json_core::from_str::<$TYPE>(value) { + $write_attribute => { + // To avoid sending double quotations in the request, they are eliminated on + // the sender side. However, to properly deserialize the data, quotes need + // to be added back. + let mut value: String = String::new(); + value.push('"').unwrap(); + value.push_str($request.value).unwrap(); + value.push('"').unwrap(); + + let new_value = match serde_json_core::from_str::<$TYPE>(value.as_str()) { Ok(data) => data, - Err(_) => return server::Response::error(attribute, + Err(_) => return server::Response::error($request.attribute, "Failed to decode value"), }; match $setter(new_value) { - Ok(_) => server::Response::success(attribute, value), - Err(_) => server::Response::error(attribute, + Ok(_) => server::Response::success($request.attribute, $request.value), + Err(_) => server::Response::error($request.attribute, "Failed to set attribute"), } } )* - _ => server::Response::error(attribute, "Unknown attribute") + _ => server::Response::error($request.attribute, "Unknown attribute") } } } @@ -176,7 +188,7 @@ const APP: () = { timer: hal::timer::Timer, net_interface: net::iface::EthernetInterface<'static, 'static, 'static, ethernet::EthernetDMA<'static>>, - _eth_mac: ethernet::EthernetMAC, + eth_mac: ethernet::EthernetMAC, mac_addr: net::wire::EthernetAddress, #[init([[0.; 5]; 2])] @@ -211,6 +223,8 @@ const APP: () = { clocks.rb.d2ccip1r.modify(|_, w| w.spi123sel().pll2_p().spi45sel().pll2_q()); + let mut delay = hal::delay::Delay::new(cp.SYST, clocks.clocks); + let gpioa = dp.GPIOA.split(&mut clocks); let gpiob = dp.GPIOB.split(&mut clocks); let gpioc = dp.GPIOC.split(&mut clocks); @@ -326,8 +340,8 @@ const APP: () = { 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 = gpiod.pd12.into_push_pull_output(); - let mut fp_led_3 = gpiog.pg4.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(); @@ -344,8 +358,8 @@ const APP: () = { { // Reset the PHY before configuring pins. let mut eth_phy_nrst = gpioe.pe3.into_push_pull_output(); - eth_phy_nrst.set_high().unwrap(); eth_phy_nrst.set_low().unwrap(); + delay.delay_us(200u8); eth_phy_nrst.set_high().unwrap(); 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); @@ -377,6 +391,8 @@ const APP: () = { mac_addr.clone()) }; + unsafe { ethernet::enable_interrupt() }; + let store = unsafe { &mut NET_STORE }; store.ip_addrs[0] = net::wire::IpCidr::new(net::wire::IpAddress::v4(10, 0, 16, 99), 24); @@ -394,7 +410,6 @@ const APP: () = { cp.SCB.enable_icache(); - init_log(); // 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); @@ -433,7 +448,7 @@ const APP: () = { eeprom_i2c: eeprom_i2c, net_interface: network_interface, - _eth_mac: eth_mac, + eth_mac: eth_mac, mac_addr: mac_addr, } } @@ -468,7 +483,7 @@ const APP: () = { c.resources.dac1.send(output).unwrap(); } - #[idle(resources=[net_interface, mac_addr, iir_state, iir_ch, afe1, afe2])] + #[idle(resources=[net_interface, mac_addr, eth_mac, iir_state, iir_ch, afe1, afe2])] fn idle(mut c: idle::Context) -> ! { let mut socket_set_entries: [_; 8] = Default::default(); @@ -566,7 +581,7 @@ const APP: () = { let sleep = match c.resources.net_interface.poll(&mut sockets, net::time::Instant::from_millis(time as i64)) { - Ok(changed) => changed, + Ok(changed) => changed == false, Err(net::Error::Unrecognized) => true, Err(e) => { info!("iface poll error: {:?}", e); @@ -580,14 +595,10 @@ const APP: () = { } } - /* - #[task(binds = ETH, resources = [net_interface], priority = 1)] - fn eth(c: eth::Context) { - let dma = &c.resources.net_interface.device(); - ETHERNET_PENDING.store(true, Ordering::Relaxed); - dma.interrupt_handler() + #[task(binds = ETH, priority = 1)] + fn eth(_: eth::Context) { + unsafe { ethernet::interrupt_handler() } } - */ extern "C" { // hw interrupt handlers for RTFM to use for scheduling tasks diff --git a/stabilizer/src/server.rs b/stabilizer/src/server.rs index 68edafe..adf2fdc 100644 --- a/stabilizer/src/server.rs +++ b/stabilizer/src/server.rs @@ -21,9 +21,16 @@ use super::net; use super::iir; #[derive(Deserialize, Serialize, Debug)] -pub enum Request<'a, 'b> { - Read{attribute: &'a str}, - Write{attribute: &'a str, value: &'b str}, +pub enum AccessRequest { + Read, + Write, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct Request<'a, 'b> { + pub req: AccessRequest, + pub attribute: &'a str, + pub value: &'b str, } #[derive(Serialize, Deserialize)] From 9ee39aa8a0ca91feb877be69c5160b12c97c04f4 Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Tue, 9 Jun 2020 14:16:49 +0200 Subject: [PATCH 6/6] Adding log initialization --- stabilizer/src/main.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/stabilizer/src/main.rs b/stabilizer/src/main.rs index 1cf6e4b..a815769 100644 --- a/stabilizer/src/main.rs +++ b/stabilizer/src/main.rs @@ -216,6 +216,8 @@ const APP: () = { .pll2_q_ck(100.mhz()) .freeze(vos, &dp.SYSCFG); + init_log(); + // Enable SRAM3 for the ethernet descriptor ring. clocks.rb.ahb2enr.modify(|_, w| w.sram3en().set_bit());