//! Serial interface loopback test
//!
//! You have to short the TX and RX pins to make this program work

// #![deny(unsafe_code)]
#![feature(uniform_paths)]
// #![deny(warnings)]
#![no_main]
#![no_std]

extern crate panic_halt;

use cortex_m::asm;

use nb::block;

use cortex_m_rt::entry;
// use stm32f4xx_hal::stm32f4::stm32f411 as device;

extern crate stm32f4xx_hal as hal;
// #[macro_use(block)]
// extern crate nb;

use crate::hal::prelude::*;
use crate::hal::serial::{config::Config, Serial};
//use crate::rt::ExceptionFrame;

#[entry]
fn main() -> ! {
    let p = hal::stm32::Peripherals::take().unwrap();

    let mut flash = p.FLASH.constrain();
    let mut rcc = p.RCC.constrain();

    let mut gpioa = p.GPIOA.split();
    // let mut gpioa = p.GPIOA.split(&mut rcc.ahb1)

    let clocks = rcc.cfgr.freeze(&mut flash.acr);

    let tx = gpioa.pa2.into_alternate_af7();
    let rx = gpioa.pa3.into_alternate_af7();

    let serial = Serial::usart2(
        p.USART2,
        (tx, rx),
        Config::default().baudrate(115_200.bps()),
        clocks,
    )
    .unwrap();

    // Separate out the sender and receiver of the serial port
    let (mut tx, mut rx) = serial.split();

    loop {
        // Read character and echo it back
        let received = block!(rx.read()).unwrap();
        block!(tx.write(received)).ok();
    }

    // let (mut tx, mut rx) = serial.split();

    // loop {
    //     //ipln!("wait");
    //     //spln!("wait");
    //     if let Ok(byte) = block!(rx.read()) {
    //         //ipln!("got {:?}", byte);
    //         //spln!("got {:?}", byte);
    //         block!(tx.write(byte)).ok();
    //     } else {
    //         //ipln!("buffer overflow");
    //         //spln!("buffer overflow");
    //     }
    // }

    //    loop {}
}