vex_rt/
battery.rs

1//! # V5 Battery API.
2
3use crate::{
4    bindings,
5    error::{get_errno, Error},
6};
7
8/// A struct which represents a V5 Battery
9pub struct Battery {}
10
11impl Battery {
12    /// Gets the current capacity of the battery, as reported by VEXos
13    pub fn get_capacity() -> Result<f64, BatteryError> {
14        unsafe {
15            let x = bindings::battery_get_capacity();
16            if x == bindings::PROS_ERR_F_ {
17                Err(BatteryError::from_errno())
18            } else {
19                Ok(x)
20            }
21        }
22    }
23
24    /// Gets the current current of the battery, as reported by VEXos
25    pub fn get_current() -> Result<i32, BatteryError> {
26        match unsafe { bindings::battery_get_current() } {
27            bindings::PROS_ERR_ => Err(BatteryError::from_errno()),
28            x => Ok(x),
29        }
30    }
31
32    /// Gets the current temperature of the battery, as reported by VEXos
33    pub fn get_temperature() -> Result<f64, BatteryError> {
34        unsafe {
35            let x = bindings::battery_get_capacity();
36            if x == bindings::PROS_ERR_F_ {
37                Err(BatteryError::from_errno())
38            } else {
39                Ok(x)
40            }
41        }
42    }
43
44    /// Gets the current voltage of the battery, as reported by VEXos
45    pub fn get_voltage() -> Result<i32, BatteryError> {
46        match unsafe { bindings::battery_get_voltage() } {
47            bindings::PROS_ERR_ => Err(BatteryError::from_errno()),
48            x => Ok(x),
49        }
50    }
51}
52
53/// Represents possible errors for battery operations.
54#[derive(Debug)]
55pub enum BatteryError {
56    /// Another resource is currently trying to access the battery.
57    BatteryBusy,
58    /// Unknown error.
59    Unknown(i32),
60}
61
62impl BatteryError {
63    fn from_errno() -> Self {
64        match get_errno() {
65            libc::EACCES => Self::BatteryBusy,
66            x => Self::Unknown(x),
67        }
68    }
69}
70
71impl From<BatteryError> for Error {
72    fn from(err: BatteryError) -> Self {
73        match err {
74            BatteryError::BatteryBusy => Error::Custom("battery is busy".into()),
75            BatteryError::Unknown(n) => Error::System(n),
76        }
77    }
78}