Compare commits

...

2 Commits

12 changed files with 203 additions and 44 deletions

16
Cargo.lock generated
View File

@ -154,6 +154,21 @@ dependencies = [
"cortex-m", "cortex-m",
] ]
[[package]]
name = "crc"
version = "3.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86ec7a15cbe22e59248fc7eadb1907dab5ba09372595da4d73dd805ed4417dfe"
dependencies = [
"crc-catalog",
]
[[package]]
name = "crc-catalog"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5"
[[package]] [[package]]
name = "critical-section" name = "critical-section"
version = "1.1.2" version = "1.1.2"
@ -385,6 +400,7 @@ dependencies = [
"cortex-m-log", "cortex-m-log",
"cortex-m-rt", "cortex-m-rt",
"cortex-m-semihosting 0.5.0", "cortex-m-semihosting 0.5.0",
"crc",
"fugit", "fugit",
"ieee802_3_miim", "ieee802_3_miim",
"log", "log",

View File

@ -36,6 +36,7 @@ miniconf = "0.9.0"
serde = { version = "1.0.158", features = ["derive"], default-features = false } serde = { version = "1.0.158", features = ["derive"], default-features = false }
sfkv = "0.1" sfkv = "0.1"
bit_field = "0.10" bit_field = "0.10"
crc = "3.0.1"
byteorder = { version = "1", default-features = false } byteorder = { version = "1", default-features = false }
[features] [features]
semihosting = ["cortex-m-log/semihosting"] semihosting = ["cortex-m-log/semihosting"]

View File

@ -41,17 +41,19 @@ gdb target/thumbv7em-none-eabihf/release/kirdy
``` ```
## Flashing ## Flashing
There are several options for flashing kirdy. DFU requires only a USB-C connector, whereas OpenOCD needs a JTAG/SWD adapter. There are several options for flashing kirdy. DFU requires only a USB-C cable or RJ45 cable, whereas OpenOCD needs a JTAG/SWD adapter.
### dfu-util on Linux ### dfu-util on Linux
* Install the DFU USB tool (dfu-util). * Install the DFU USB tool (dfu-util).
* Convert firmware from ELF to BIN: `arm-none-eabi-objcopy -O binary kirdy kirdy.bin` (you can skip this step if using the BIN from Hydra) * Convert firmware from ELF to BIN: `arm-none-eabi-objcopy -O binary kirdy kirdy.bin` (you can skip this step if using the BIN from Hydra)
* Connect to the USB Type C connector to kirdy above the RJ45. * Put STM32 into DFU Mode. You can either
* Add jumper to kirdy v2.0 across 2-pin jumper adjacent to JTAG connector. * Connect to the USB Type C cable to kirdy next to the RJ45 Jack. After that, add BOOT0 jumper to kirdy near programming headers and then cycle board power to put it in DFU mode. OR
* Cycle board power to put it in DFU update mode * Plug in RJ45 cable, which connect to a network that is accessible by your computer and send the corresponding dfu json command via TCP Socket to kirdy. Please see the python test script for the command.
* Push firmware to flash: `dfu-util -a 0 -s 0x08000000:leave -D kirdy.bin` * Push firmware to flash: `dfu-util -a 0 -s 0x08000000:leave -D kirdy.bin`
* Remove jumper * If you plugged in the BOOT0 jumper, you will need to
* Cycle power to leave DFU update mode 1. Remove BOOT0 jumper
2. Cycle power to leave DFU update mode
* If you plugged in the RJ45 cable, the MCU would start its application code automatically. No power cycle is needed.
### st.com DfuSe tool on Windows ### st.com DfuSe tool on Windows
On a Windows machine install [st.com](https://st.com) DfuSe USB device firmware upgrade (DFU) software. [link](https://www.st.com/en/development-tools/stsw-stm32080.html). On a Windows machine install [st.com](https://st.com) DfuSe USB device firmware upgrade (DFU) software. [link](https://www.st.com/en/development-tools/stsw-stm32080.html).

View File

@ -14,6 +14,10 @@ import signal
HOST = "192.168.1.132" HOST = "192.168.1.132"
PORT = 1337 PORT = 1337
dfu_cmd = {
"device_cmd": "Dfu",
}
ld_cmd = { ld_cmd = {
"laser_diode_cmd": "SetI", "laser_diode_cmd": "SetI",
"data_f64": 0.0, "data_f64": 0.0,

View File

@ -43,7 +43,7 @@ pub fn bootup(
sys_timer::setup(core_perif.SYST, clocks); sys_timer::setup(core_perif.SYST, clocks);
let (eth_pins, eth_mgmt_pins, usb, current_source_phy, ad7172_phy, max1968_phy, pd_mon_phy) = gpio::setup( let (mut hw_rev, eth_pins, eth_mgmt_pins, usb, current_source_phy, ad7172_phy, max1968_phy, pd_mon_phy) = gpio::setup(
clocks, clocks,
perif.TIM4, perif.TIM4,
perif.GPIOA, perif.GPIOA,
@ -84,13 +84,14 @@ pub fn bootup(
let flash_store = flash_store::store(perif.FLASH); let flash_store = flash_store::store(perif.FLASH);
debug!("Setting up ETH"); debug!("Setting up ETH");
let mac_addr = hw_rev.get_mac_address();
let ethernet_parts_in = stm32_eth::PartsIn { let ethernet_parts_in = stm32_eth::PartsIn {
dma: perif.ETHERNET_DMA, dma: perif.ETHERNET_DMA,
mac: perif.ETHERNET_MAC, mac: perif.ETHERNET_MAC,
mmc: perif.ETHERNET_MMC, mmc: perif.ETHERNET_MMC,
ptp: perif.ETHERNET_PTP, ptp: perif.ETHERNET_PTP,
}; };
ServerHandle::new(eth_pins, eth_mgmt_pins, ethernet_parts_in, clocks); ServerHandle::new(eth_pins, eth_mgmt_pins, ethernet_parts_in, clocks, mac_addr);
debug!("Setting Watchdog"); debug!("Setting Watchdog");
let mut wd = IndependentWatchdog::new(perif.IWDG); let mut wd = IndependentWatchdog::new(perif.IWDG);

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

@ -0,0 +1,46 @@
use cortex_m_rt::pre_init;
use stm32f4xx_hal::pac::{RCC, SYSCFG};
use core::arch::asm;
const DFU_TRIG_MSG: u32 = 0xDECAFBAD;
extern "C" {
// This symbol comes from memory.x
static mut _dfu_msg: u32;
}
pub unsafe fn set_dfu_trigger() {
_dfu_msg = DFU_TRIG_MSG;
}
/// Called by reset handler in lib.rs immediately after reset.
/// This function should not be called outside of reset handler as
/// bootloader expects MCU to be in reset state when called.
#[cfg(target_arch = "arm")]
#[pre_init]
unsafe fn __pre_init() {
if _dfu_msg == DFU_TRIG_MSG {
_dfu_msg = 0x00000000;
// Enable system config controller clock
let rcc = &*RCC::ptr();
rcc.apb2enr.modify(|_, w| w.syscfgen().set_bit());
// Bypass BOOT pins and remap bootloader to 0x00000000
let syscfg = &*SYSCFG::ptr() ;
syscfg.memrm.write(|w| w.mem_mode().bits(0b01));
// Impose instruction and memory barriers
cortex_m::asm::isb();
cortex_m::asm::dsb();
asm!(
// Set stack pointer to bootloader location
"LDR R0, =0x1FFF0000",
"LDR SP,[R0, #0]",
// Jump to bootloader
"LDR R0,[R0, #4]",
"BX R0",
);
}
}

View File

@ -37,6 +37,7 @@ pub fn setup(
otg_fs_device: OTG_FS_DEVICE, otg_fs_device: OTG_FS_DEVICE,
otg_fs_pwrclk: OTG_FS_PWRCLK, otg_fs_pwrclk: OTG_FS_PWRCLK,
) -> ( ) -> (
HWRev,
EthernetPins, EthernetPins,
EthernetMgmtPins, EthernetMgmtPins,
USB, USB,
@ -158,5 +159,5 @@ pub fn setup(
gpioa.pa15.into_push_pull_output(), gpioa.pa15.into_push_pull_output(),
).unwrap(); ).unwrap();
(eth_pins, eth_mgmt_pins, usb, current_source_phy, ad7172_phy, max1968_phy, pd_mon_phy) (hw_rev, eth_pins, eth_mgmt_pins, usb, current_source_phy, ad7172_phy, max1968_phy, pd_mon_phy)
} }

View File

@ -1,5 +1,8 @@
use stm32f4xx_hal::gpio::{Input, Output, PushPull, PE10, PE11, PE8, PE9}; use stm32f4xx_hal::gpio::{Input, PE10, PE11, PE8, PE9};
use crate::device::sys_timer::sleep; use crate::device::sys_timer::sleep;
use stm32f4xx_hal::signature;
use crc::{Crc, CRC_24_BLE};
pub struct HwRevPins{ pub struct HwRevPins{
pub h0: PE8<Input>, pub h0: PE8<Input>,
pub h1: PE9<Input>, pub h1: PE9<Input>,
@ -32,4 +35,28 @@ impl HWRev {
sleep(5000); sleep(5000);
} }
} }
/// On Rev0_3, it lacks pre-allocated Mac Addresses accessible on PCB.
/// This functions generate a random Mac Address with 96bit unique UUID inside STM32
/// See Issue #36 on Kirdy Hw Repo
pub fn get_mac_address(&mut self) -> [u8; 6] {
if self.major == 0 && self.minor == 3 {
let uid = signature::Uid::get();
let mut uid_data: [u8; 12] = [0; 12];
uid_data[0] = uid.x() as u8;
uid_data[1] = (uid.x() >> 8) as u8;
uid_data[2] = uid.y() as u8;
uid_data[3] = (uid.y() >> 8) as u8;
uid_data[4..11].clone_from_slice(uid.lot_num().as_bytes());
let crc: Crc<u32> = Crc::<u32>::new(&CRC_24_BLE);
let mut digest = crc.digest();
digest.update(&uid_data);
let crc24 = digest.finalize();
[ 0x02, 0xE0, 0xD5, (crc24 >> 16) as u8, (crc24 >> 8) as u8, (crc24 as u8)]
} else {
unimplemented!()
}
}
} }

View File

@ -6,3 +6,4 @@ pub mod sys_timer;
pub mod usb; pub mod usb;
pub mod flash_store; pub mod flash_store;
pub mod hw_rev; pub mod hw_rev;
pub mod dfu;

View File

@ -18,6 +18,7 @@ use uom::si::power::milliwatt;
use uom::si::f64::{ElectricPotential, ElectricCurrent, Power, ThermodynamicTemperature}; use uom::si::f64::{ElectricPotential, ElectricCurrent, Power, ThermodynamicTemperature};
use serde::{Serialize, Deserialize}; use serde::{Serialize, Deserialize};
use stm32f4xx_hal::pac::SCB;
// If RTT is used, print panic info through RTT // If RTT is used, print panic info through RTT
#[cfg(all(feature = "RTT", not(test)))] #[cfg(all(feature = "RTT", not(test)))]
use {core::panic::PanicInfo, rtt_target::rprintln}; use {core::panic::PanicInfo, rtt_target::rprintln};
@ -77,41 +78,58 @@ fn main() -> ! {
let milli_amp_fmt = ElectricCurrent::format_args(milliampere, Abbreviation); let milli_amp_fmt = ElectricCurrent::format_args(milliampere, Abbreviation);
let milli_watt_fmt = Power::format_args(milliwatt, Abbreviation); let milli_watt_fmt = Power::format_args(milliwatt, Abbreviation);
let mut should_reset = false;
loop { loop {
wd.feed(); wd.feed();
let mut eth_is_pending = false; if !should_reset {
let mut eth_is_pending = false;
if thermostat.poll_adc_and_update_pid() { if thermostat.poll_adc_and_update_pid() {
info!("curr_dac_vfb: {:?}", volt_fmt.with(thermostat.get_dac_vfb())); info!("curr_dac_vfb: {:?}", volt_fmt.with(thermostat.get_dac_vfb()));
info!("curr_vref: {:?}", volt_fmt.with(thermostat.get_vref())); info!("curr_vref: {:?}", volt_fmt.with(thermostat.get_vref()));
info!("curr_tec_i: {:?}", amp_fmt.with(thermostat.get_tec_i())); info!("curr_tec_i: {:?}", amp_fmt.with(thermostat.get_tec_i()));
info!("curr_tec_v: {:?}", volt_fmt.with(thermostat.get_tec_v())); info!("curr_tec_v: {:?}", volt_fmt.with(thermostat.get_tec_v()));
info!("curr_ld_drive_cuurent: {:?}", milli_amp_fmt.with(laser.get_ld_drive_current())); info!("curr_ld_drive_cuurent: {:?}", milli_amp_fmt.with(laser.get_ld_drive_current()));
info!("pd_mon_v: {:?}", volt_fmt.with(laser.pd_mon_status().v)); info!("pd_mon_v: {:?}", volt_fmt.with(laser.pd_mon_status().v));
info!("power_excursion: {:?}", laser.pd_mon_status().pwr_excursion); info!("power_excursion: {:?}", laser.pd_mon_status().pwr_excursion);
info!("Termination Status: {:?}", laser.get_term_status()); info!("Termination Status: {:?}", laser.get_term_status());
} }
if net::net::eth_is_socket_active() { if net::net::eth_is_socket_active() {
cortex_m::interrupt::free(|cs| cortex_m::interrupt::free(|cs|
{ {
eth_is_pending = net::net::is_pending(cs); eth_is_pending = net::net::is_pending(cs);
}
);
if eth_is_pending {
unsafe{
cortex_m::interrupt::free(|cs| {
net::net::clear_pending(cs);
});
let bytes = net::net::eth_recv(&mut ETH_DATA_BUFFER);
debug!("Number of bytes recv: {:?}", bytes);
(laser, thermostat, should_reset) = net::cmd_handler::execute_cmd(&mut ETH_DATA_BUFFER, bytes, laser, thermostat);
}
} }
); }
} else {
// Should reset, close all TCP sockets.
let mut any_socket_alive = false;
if net::net::eth_is_socket_active() {
net::net::eth_close_socket();
any_socket_alive = true;
}
if eth_is_pending { // Must let loop run for one more cycle to poll server for RST to be sent,
unsafe{ // this makes sure system does not reset right after socket.abort() is called.
cortex_m::interrupt::free(|cs| { if !any_socket_alive {
net::net::clear_pending(cs); SCB::sys_reset();
});
let bytes = net::net::eth_recv(&mut ETH_DATA_BUFFER);
debug!("Number of bytes recv: {:?}", bytes);
(laser, thermostat) = net::cmd_handler::execute_cmd(&mut ETH_DATA_BUFFER, bytes, laser, thermostat);
}
} }
} }
} }

View File

@ -1,4 +1,4 @@
use core::fmt::Debug; use core::{default, fmt::Debug};
use miniconf::{JsonCoreSlash, Tree}; use miniconf::{JsonCoreSlash, Tree};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use uom::si::{ use uom::si::{
@ -10,8 +10,16 @@ use uom::si::{
use crate::{laser_diode::laser_diode::LdDrive, net::net, thermostat::thermostat::StatusReport}; use crate::{laser_diode::laser_diode::LdDrive, net::net, thermostat::thermostat::StatusReport};
use crate::thermostat::thermostat::Thermostat; use crate::thermostat::thermostat::Thermostat;
use crate::thermostat::pid_state::PidSettings::*; use crate::thermostat::pid_state::PidSettings::*;
use crate::device::dfu;
use log::info; use log::info;
#[derive(Deserialize, Serialize, Copy, Clone, Default, Debug)]
enum DeviceCmd {
#[default]
Reserved,
Dfu
}
#[derive(Deserialize, Serialize, Copy, Clone, Default, Debug)] #[derive(Deserialize, Serialize, Copy, Clone, Default, Debug)]
enum LdCmdEnum { enum LdCmdEnum {
#[default] #[default]
@ -70,6 +78,7 @@ enum ThermostatCmdEnum {
pub struct CmdJsonObj{ pub struct CmdJsonObj{
laser_diode_cmd: Option<LdCmdEnum>, laser_diode_cmd: Option<LdCmdEnum>,
thermostat_cmd: Option<ThermostatCmdEnum>, thermostat_cmd: Option<ThermostatCmdEnum>,
device_cmd: Option<DeviceCmd>,
data_f32: Option<f32>, data_f32: Option<f32>,
data_f64: Option<f64>, data_f64: Option<f64>,
} }
@ -83,7 +92,9 @@ pub struct StatusReportStruct {
json: StatusReport json: StatusReport
} }
pub fn execute_cmd(buffer: &mut [u8], buffer_size: usize, mut laser: LdDrive, mut tec: Thermostat)->(LdDrive, Thermostat){ pub fn execute_cmd(buffer: &mut [u8], buffer_size: usize, mut laser: LdDrive, mut tec: Thermostat)->(LdDrive, Thermostat, bool){
let mut should_reset = false;
let mut cmd = Cmd { let mut cmd = Cmd {
json: CmdJsonObj::default() json: CmdJsonObj::default()
}; };
@ -91,6 +102,20 @@ pub fn execute_cmd(buffer: &mut [u8], buffer_size: usize, mut laser: LdDrive, mu
Ok(_) => { Ok(_) => {
info!("############ Laser Diode Command Received {:?}", cmd.json.laser_diode_cmd); info!("############ Laser Diode Command Received {:?}", cmd.json.laser_diode_cmd);
info!("############ Thermostat Command Received {:?}", cmd.json.thermostat_cmd); info!("############ Thermostat Command Received {:?}", cmd.json.thermostat_cmd);
info!("############ Device Command Received {:?}", cmd.json.device_cmd);
match cmd.json.device_cmd {
Some(DeviceCmd::Dfu) => {
unsafe {
dfu::set_dfu_trigger();
}
should_reset = true;
}
None => { /* Do Nothing */}
_ => {
info!("Unimplemented Command")
}
}
match cmd.json.laser_diode_cmd { match cmd.json.laser_diode_cmd {
Some(LdCmdEnum::PowerUp) => { Some(LdCmdEnum::PowerUp) => {
@ -331,5 +356,5 @@ pub fn execute_cmd(buffer: &mut [u8], buffer_size: usize, mut laser: LdDrive, mu
info!("Invalid Command: {:?}", err); info!("Invalid Command: {:?}", err);
} }
} }
(laser, tec) (laser, tec, should_reset)
} }

View File

@ -35,7 +35,6 @@ const ADDRESS: (IpAddress, u16) = (
)), )),
1337, 1337,
); );
const MAC: [u8; 6] = [0x02, 0x5f, 0x25, 0x37, 0x93, 0x0e];
/// Interrupt pending flag: set by the `ETH` interrupt handler, should /// Interrupt pending flag: set by the `ETH` interrupt handler, should
/// be cleared before polling the interface. /// be cleared before polling the interface.
@ -88,6 +87,7 @@ impl ServerHandle {
eth_mgmt_pins: EthernetMgmtPins, eth_mgmt_pins: EthernetMgmtPins,
ethernet_parts_in: PartsIn, ethernet_parts_in: PartsIn,
clocks: Clocks, clocks: Clocks,
mac_addr: [u8; 6]
) { ) {
let rx_ring = unsafe { RX_RING.get_or_insert(Default::default()) }; let rx_ring = unsafe { RX_RING.get_or_insert(Default::default()) };
let tx_ring = unsafe { TX_RING.get_or_insert(Default::default()) }; let tx_ring = unsafe { TX_RING.get_or_insert(Default::default()) };
@ -119,9 +119,10 @@ impl ServerHandle {
let tx_buffer = SocketBuffer::new(&mut tcp_socket_storage.tx_storage[..]); let tx_buffer = SocketBuffer::new(&mut tcp_socket_storage.tx_storage[..]);
let socket = Socket::new(rx_buffer, tx_buffer); let socket = Socket::new(rx_buffer, tx_buffer);
let config = iface::Config::new(EthernetAddress::from_bytes(&MAC).into()); let config = iface::Config::new(EthernetAddress::from_bytes(&mac_addr).into());
let mut iface = Interface::new(config, &mut &mut dma, smoltcp::time::Instant::ZERO); let mut iface = Interface::new(config, &mut &mut dma, smoltcp::time::Instant::ZERO);
iface.set_hardware_addr(EthernetAddress(MAC).into()); iface.set_hardware_addr(EthernetAddress(mac_addr).into());
debug!("MAC ADDRESS: {:02X?}", EthernetAddress(mac_addr));
iface.update_ip_addrs(|addr| { iface.update_ip_addrs(|addr| {
addr.push(IP_INIT).unwrap(); addr.push(IP_INIT).unwrap();
@ -206,6 +207,11 @@ impl ServerHandle {
} }
return true; return true;
} }
pub fn close_socket(&mut self) {
let socket = self.socket_set.get_mut::<Socket>(self.socket_handle);
socket.abort();
}
} }
use ieee802_3_miim::{ use ieee802_3_miim::{
@ -348,6 +354,17 @@ pub fn eth_is_socket_active() -> bool {
} }
} }
pub fn eth_close_socket() {
unsafe {
if let Some(ref mut server_handle ) = SERVER_HANDLE {
server_handle.close_socket()
}
else {
panic!("eth_close_socket is called before init");
}
}
}
/// Potentially wake up from `wfi()`, set the interrupt pending flag, /// Potentially wake up from `wfi()`, set the interrupt pending flag,
/// clear interrupt flags. /// clear interrupt flags.
#[interrupt] #[interrupt]