1use core::fmt::Write;
6use core::panic::PanicInfo;
7use core::ptr::addr_of;
8use core::ptr::addr_of_mut;
9
10use kernel::debug;
11use kernel::debug::IoWrite;
12use kernel::hil::led;
13use kernel::hil::uart;
14use kernel::hil::uart::Configure;
15
16use stm32f401cc::chip_specs::Stm32f401Specs;
17use stm32f401cc::gpio::PinId;
18
19use crate::CHIP;
20use crate::PROCESSES;
21use crate::PROCESS_PRINTER;
22
23pub struct Writer {
25    initialized: bool,
26}
27
28pub static mut WRITER: Writer = Writer { initialized: false };
30
31impl Writer {
32    pub fn set_initialized(&mut self) {
35        self.initialized = true;
36    }
37}
38
39impl Write for Writer {
40    fn write_str(&mut self, s: &str) -> ::core::fmt::Result {
41        self.write(s.as_bytes());
42        Ok(())
43    }
44}
45
46impl IoWrite for Writer {
47    fn write(&mut self, buf: &[u8]) -> usize {
48        let rcc = stm32f401cc::rcc::Rcc::new();
49        let clocks: stm32f401cc::clocks::Clocks<Stm32f401Specs> =
50            stm32f401cc::clocks::Clocks::new(&rcc);
51        let uart = stm32f401cc::usart::Usart::new_usart2(&clocks);
52
53        if !self.initialized {
54            self.initialized = true;
55
56            let _ = uart.configure(uart::Parameters {
57                baud_rate: 115200,
58                stop_bits: uart::StopBits::One,
59                parity: uart::Parity::None,
60                hw_flow_control: false,
61                width: uart::Width::Eight,
62            });
63        }
64
65        for &c in buf {
66            uart.send_byte(c);
67        }
68        buf.len()
69    }
70}
71
72#[panic_handler]
74pub unsafe fn panic_fmt(info: &PanicInfo) -> ! {
75    let rcc = stm32f401cc::rcc::Rcc::new();
78    let clocks: stm32f401cc::clocks::Clocks<Stm32f401Specs> =
79        stm32f401cc::clocks::Clocks::new(&rcc);
80    let syscfg = stm32f401cc::syscfg::Syscfg::new(&clocks);
81    let exti = stm32f401cc::exti::Exti::new(&syscfg);
82    let pin = stm32f401cc::gpio::Pin::new(PinId::PC13, &exti);
83    let gpio_ports = stm32f401cc::gpio::GpioPorts::new(&clocks, &exti);
84    pin.set_ports_ref(&gpio_ports);
85    let led = &mut led::LedLow::new(&pin);
86
87    let writer = &mut *addr_of_mut!(WRITER);
88
89    debug::panic(
90        &mut [led],
91        writer,
92        info,
93        &cortexm4::support::nop,
94        PROCESSES.unwrap().as_slice(),
95        &*addr_of!(CHIP),
96        &*addr_of!(PROCESS_PRINTER),
97    )
98}