// src/bin/main.rs
#![no_std]
#![no_main]

use defmt::*;
use embassy_executor::Spawner;
use embassy_time::{Duration, Timer};
use embassy_stm32::usart::{Config, Uart};
use embassy_stm32::bind_interrupts;
use embassy_stm32::usart::{BufferedUart, BufferedInterruptHandler};
use embassy_stm32::mode::Async;
use embedded_io_async::{Read, Write};
use embassy_stm32::peripherals;
use static_cell::StaticCell;
use {defmt_rtt as _, panic_probe as _};

bind_interrupts!(
    struct Irqs {
        USART1 => BufferedInterruptHandler<peripherals::USART1>;
    }
);

#[embassy_executor::task]
async fn receive_uart(mut uart: BufferedUart<'static>) {
    let mut buf = [0u8; 1];
    loop {
        unwrap!(uart.read(&mut buf).await);
        unwrap!(uart.write(&buf).await);
        unwrap!(uart.write(b"a\r\n").await);
        info!("uart received {}", buf[0]);
    }
}

#[embassy_executor::main]
async fn main(spawner: Spawner) {
    info!("tititititi");
    let p = embassy_stm32::init(Default::default());

    static TX_BUF: StaticCell<[u8; 256]> = StaticCell::new();
    static RX_BUF: StaticCell<[u8; 256]> = StaticCell::new();
    let tx_buf = TX_BUF.init([0; 256]);
    let rx_buf = RX_BUF.init([0; 256]);

    let mut cfg = Config::default();
    cfg.baudrate = 230_400;

    let config = Config::default();
    let usart = BufferedUart::new(
        p.USART1,
        p.PA10, // RX
        p.PA9,  // TX
        tx_buf,
        rx_buf,
        Irqs,
        cfg,
    ).unwrap();

    info!("starting echo");
    spawner.spawn(receive_uart(usart)).unwrap();

    let mut counter: u8 = 230;
    loop {
        counter = counter.wrapping_add(1);
        info!("CPU doing other work: {}", counter);
        Timer::after(Duration::from_millis(300)).await;
    }
}
