//! Blinks an LED
//!
//! This assumes that a LED is connected to GPIO4.
//! Depending on your target and the board you are using you should change the pin.
//! If your board doesn't have on-board LEDs don't forget to add an appropriate resistor.
//!

use std::thread;
use std::time::Duration;

use esp_idf_sys::EspError;

use embedded_hal::digital::OutputPin;
use esp_idf_hal::gpio::PinDriver;
use esp_idf_hal::peripherals::Peripherals;

use esp_idf_hal::adc::config::Config;
use esp_idf_hal::adc::Atten11dB;
use esp_idf_hal::adc::*;

use esp_idf_hal::gpio::Gpio0;

fn main() -> anyhow::Result<()> {
    esp_idf_sys::link_patches();

    let peripherals = Peripherals::take().unwrap();
    
    let mut led = PinDriver::output(peripherals.pins.gpio7).unwrap();

    let mut adc = {

        let check = unsafe{
            esp_idf_sys::esp_adc_cal_check_efuse(
                esp_idf_sys::esp_adc_cal_value_t_ESP_ADC_CAL_VAL_EFUSE_VREF
            )
        };
        
        println!("a {}", &check);

        if check == esp_idf_sys::ESP_OK {
            AdcDriver::new(peripherals.adc1, &Config::new().calibration(true))
        } else {
            AdcDriver::new(peripherals.adc1, &Config::new())
        }
    }?;
    println!("a");
    let mut adc_pin: esp_idf_hal::adc::AdcChannelDriver<'_, Gpio0, Atten0dB<_>> =
        AdcChannelDriver::new(peripherals.pins.gpio0)?;
    
    println!("Hello, world!");
    loop {
        println!("ADC value: {}", adc.read(&mut adc_pin).unwrap());
        led.set_high()?;
        // we are using thread::sleep here to make sure the watchdog isn't triggered
        thread::sleep(Duration::from_millis(1000));
        
        led.set_low()?; 
        thread::sleep(Duration::from_millis(1000));
    }
}
esp:0
esp:1
esp:2
esp:3
esp:4
esp:5
esp:6
esp:7
esp:8
esp:9
esp:10
esp:18
esp:19
esp:GND.1
esp:3V3.1
esp:3V3.2
esp:GND.2
esp:RST
esp:GND.3
esp:GND.4
esp:5V.1
esp:5V.2
esp:GND.5
esp:GND.6
esp:GND.7
esp:GND.8
esp:GND.9
esp:RX
esp:TX
esp:GND.10
pot1:GND
pot1:SIG
pot1:VCC
led1:A
led1:C