//! This example shows how to communicate using i2c with external chips.
//!
//! Example written for the [`MCP23017 16-Bit I2C I/O Expander with Serial Interface`] chip.
//! (https://www.microchip.com/en-us/product/mcp23017)

#![no_std]
#![no_main]

use defmt::*;
use embassy_executor::Spawner;
use embassy_rp::i2c::{self, Config};
use embassy_time::Timer;
use embedded_hal_1::i2c::I2c;
use {defmt_rtt as _, panic_probe as _};

#[allow(dead_code)]
mod sdc41 {

    pub const ADDR: u8 = 0x62; // default addr

    
    pub const WAKE_UP: [u8; 2] = [0x36, 0xf6];
    pub const START_PERIODIC_MESUREMENT: [u8; 2] = [0x21, 0xb1];
    pub const READ_MEASUREMENT: [u8; 2] = [0xec, 0x05];
    pub const STOP_PERIODIC_MEASUREMENT: [u8; 2] = [0x3f, 0x86];
}

#[embassy_executor::main]
async fn main(_spawner: Spawner) {
    let p = embassy_rp::init(Default::default());

    let sda = p.PIN_10;
    let scl = p.PIN_11;

    info!("set up i2c ");
    let mut i2c = i2c::I2c::new_blocking(p.I2C1, scl, sda, Config::default());

    use sdc41::*;

    // info!("init mcp23017 config for IxpandO");
    // init - a outputs, b inputs
    // i2c.write(ADDR, &[IODIRA, 0x00]).unwrap();
    // i2c.write(ADDR, &[IODIRB, 0xff]).unwrap();
    // i2c.write(ADDR, &[GPPUB, 0xff]).unwrap(); // pullups

    // let mut val = 0xaa;
    loop {
        let mut response = [0u8; 3];
        Timer::after_secs(1).await;

        info!("wake_up");
        // i2c.write(ADDR, &WAKE_UP).unwrap();
        info!("starting");
        Timer::after_secs(1).await;

        i2c.write(ADDR, &START_PERIODIC_MESUREMENT).unwrap();
        info!("writing");
        Timer::after_secs(5).await;
        info!("writing reading start");

        i2c.write_read(ADDR, &READ_MEASUREMENT, &mut response).unwrap();
        info!("writing reading");
        i2c.write(ADDR, &STOP_PERIODIC_MEASUREMENT).unwrap();
        info!("stoping");


        info!("response = {:02x}", response[0]);

        Timer::after_secs(1).await;
    }
}