use std::thread;
use std::time::Duration;
use dht_sensor::dht22;
use esp_idf_svc::hal::{delay, gpio::PinDriver, peripherals::Peripherals};

fn main() {
    // It is necessary to call this function once. Otherwise some patches to the runtime
    // implemented by esp-idf-sys might not link properly. See https://github.com/esp-rs/esp-idf-template/issues/71
    esp_idf_svc::sys::link_patches();

    let peripherals = Peripherals::take().unwrap();
    // 
    let mut pin = PinDriver::input_output_od(peripherals.pins.gpio19).unwrap();

    // Pulling the pin high to avoid confusing the sensor when initializing
    pin.set_high().unwrap();
    // The DHT datasheet suggests waiting 1 second
    thread::sleep(Duration::from_millis(1000));

    println!("Hello world!");

    let mut d = delay::Ets;
    
    let mut iterations = 1000;
    while iterations > 0 {
        thread::sleep(Duration::from_secs(3));
        iterations -= 1;
        match dht22::read(&mut d, &mut pin) {
            Ok(r) => println!(
                "Temperature: {}\tHumidity: {}",
                r.temperature, r.relative_humidity
            ),
            Err(e) => println!("Failed with error: {:?}", e),
        }
    }

}