dwh 0.7.1

A library to use the digitronic protocol dwh
Documentation
use std::{process, sync::Arc, time::Duration};

use clap::{command, Parser};
use dwh::Dwh;
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use itertools::Itertools;

#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]

struct Args {
    source: String,
    host: String,
}

fn sanitize_mac(mut mac: String) -> anyhow::Result<String> {
    mac = mac.replace(":", "").to_uppercase().trim().to_string();
    let re = regex::Regex::new("^[0-9A-F]{12}$").expect("valid regex");
    if !(re.is_match(mac.as_str())) {
        return Err(anyhow::Error::msg(
            "Sie haben keine gültige Mac-Adresse eingegeben".to_string(),
        ));
    }
    let chunks = mac.chars().map(|s| s.to_string()).collect_vec();
    let chunks = chunks.chunks(2).collect_vec();
    mac = chunks.into_iter().map(|chunk| chunk.join("")).join(":");
    Ok(mac)
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    ctrlc::set_handler(|| {
        process::exit(1);
    })
    .ok();
    let args = Args::parse();
    let mut mac = String::new();
    println!("Enter the Mac Address :");
    //mac = "0011223344AC".to_owned();
    std::io::stdin().read_line(&mut mac).unwrap();
    mac = sanitize_mac(mac)?;
    println!("Mac: {}", mac);

    let mut dwh = Dwh::new(args.host.clone())?;
    while let Err(e) = dwh.fetch_i32("##000187").await {
        println!("can't reach the device. waiting.... {}", e);
        tokio::time::sleep(Duration::from_secs(2)).await;
    }
    println!("device reachable!");
    dwh.use_backdooor_and_login().await?;

    let m = MultiProgress::new();
    let sty = ProgressStyle::with_template(
        "{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes}",
    )
    .unwrap()
    .progress_chars("#>-");

    let pb_file = m.add(ProgressBar::new(0));
    pb_file.set_style(sty.clone());
    let pb_total = Arc::new(m.insert_after(&pb_file, ProgressBar::new(0)));
    pb_total.set_style(sty.clone());
    //zip_extract::extract(zip_file, "./out").await?;
    //m.clear()
    dwh::update::Update::new(
        dwh,
        move |event| match event {
            dwh::update::UpdateEvent::UpdateProgress(progress) => {
                if pb_total.length().unwrap() == 0 {
                    pb_total.set_length(progress.total as u64);
                }
                pb_total.set_position(progress.sent as u64);
            }
            dwh::update::UpdateEvent::File(path) => {
                pb_file.set_position(0);
                pb_file.set_length(0);
                m.println(format!("uploading file: {path}")).ok();
            }
            dwh::update::UpdateEvent::FileProgress(progress) => {
                if pb_file.length().unwrap() != progress.total as u64 {
                    pb_file.set_length(progress.total as u64);
                }
                pb_file.set_position(progress.sent as u64);
            }
            dwh::update::UpdateEvent::Dir(path) => {
                m.println(format!("Creating directory: {path}")).ok();
            }
            dwh::update::UpdateEvent::Err(err) => {
                m.println(format!("Error occurred: {err}")).ok();
            }
            dwh::update::UpdateEvent::Done => {
                m.println("files uploaded successful").ok();
            }
            dwh::update::UpdateEvent::Restart(duration) => {
                let secs = duration.as_secs();
                m.remove(&pb_file);
                m.remove(&pb_total);
                m.println(format!("Performing restart with timeout {secs}s"))
                    .ok();
            }
        },
        None,
        None,
    )
    .unwrap()
    .run(args.source)
    .await?;
    let mut dwh = Dwh::new(args.host)?;
    dwh.use_backdooor_and_login().await?;
    let seconds: i32 = (chrono::Utc::now()
        - chrono::NaiveDate::from_ymd_opt(1900, 1, 1)
            .unwrap()
            .and_hms_opt(0, 0, 0)
            .unwrap()
            .and_utc())
    .num_seconds() as i32;
    dwh.fetch_i32(format!("##000171:={seconds}")).await.ok();
    dwh.fetch_string(format!("#$000119:='rp.e-comptrol.com'"))
        .await?;
    println!("setting mac to {}", mac);
    dwh.fetch_string(format!("#$000151:='{mac}'")).await.ok();
    println!("success");
    Ok(())
}