Battery crate how to check battery_state over a treshold

Hi I would like to implement an application to check the battery's state, I found the battery crate, it gives me the state of the battery but I am not able to compare the result of battery.state_of_charge() with one or more threshold, if I try with if charge>10.0{ println!("charge is ok"); } I get this error message:
expected struct uom::si::Quantity, found floating-point number

This is because it is not returning a bare floating point number, but a value with a unit attached to it. Create a value of type Quantity, and you should be able to do the comparison if the units match.

sorry I do know how to do it:
I tried this: let L = Length::new::<meter>(1.0);
I know the unity is wrong, I just tried to declare a value of Quantity, now the problem is I do not know how to import Quantity and Length from the battery. this is what I have since now:

fn print_type_of<T>(_: &T) {
    println!("{}", std::any::type_name::<T>())
}
 use uom::si::Quantity::meter;
fn main() -> Result<(), battery::Error> {
    let manager = battery::Manager::new()?;


    for (idx, maybe_battery) in manager.batteries()?.enumerate() {
        let battery = maybe_battery?;
        let charge = battery.state_of_charge()*100.0;
        println!("Battery #{}:", idx);
        println!("Vendor: {:?}", battery.vendor());
        println!("Model: {:?}", battery.model());
        println!("State: {:?}", battery.state());
        println!("Time to full charge: {:?}", battery.time_to_full());
        println!("percentuale di carica: {:.2?}",charge);
        let L = Length::new::<meter>(1.0);



         print_type_of(&charge);







    }

    Ok(())
}

thanks in advance, this is my first program in rust

You can use .get::<percent>() to get the battery level as a percentage number:

use battery::units::ratio::percent;

let charge = battery.state_of_charge().get::<percent>();
if charge > 10.0 {
    println!("charge is ok");
}
1 Like

thank you

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.