#![no_std]
#![no_main]

use dht_sensor::*;
use esp32_hal::{
    clock::ClockControl,
    peripherals::Peripherals,
    prelude::*,
    timer::TimerGroup,
    Delay,
    Rtc,
    IO,
};
use xtensa_lx_rt::entry;
use esp_backtrace as _;
use esp_println::println;

#[entry]
fn main() -> ! {
    let peripherals = Peripherals::take();
    let system = peripherals.DPORT.split();
    let clocks = ClockControl::boot_defaults(system.clock_control).freeze();

    let mut rtc = Rtc::new(peripherals.RTC_CNTL);
    let mut delay = Delay::new(&clocks);

    let timer_group0 = TimerGroup::new(peripherals.TIMG0, &clocks);
    let mut wdt0 = timer_group0.wdt;
    let timer_group1 = TimerGroup::new(peripherals.TIMG1, &clocks);
    let mut wdt1 = timer_group1.wdt;

    rtc.rwdt.disable();
    wdt0.disable();
    wdt1.disable();

    let io = IO::new(peripherals.GPIO, peripherals.IO_MUX);
    let mut led = io.pins.gpio2.into_push_pull_output();
    let mut dht_pin = io.pins.gpio4.into_open_drain_output();

    dht_pin.set_high().ok();
    delay.delay_ms(1000u32);

    loop {
        led.toggle().unwrap();
        println!("Leyendo DHT22...");

        match dht22::Reading::read(&mut delay, &mut dht_pin) {
            Ok(dht22::Reading { temperature, relative_humidity }) => {
                println!("Temperatura: {}°C, Humedad: {}%", temperature, relative_humidity);
            }
            Err(e) => {
                println!("Error al leer DHT22: {:?}", e);
            }
        }

        delay.delay_ms(2000u32);
    }
}