power_monitor/
powerd.rs

1// Copyright 2024 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Bindings for the ChromeOS `powerd` D-Bus API.
6//!
7//! <https://chromium.googlesource.com/chromiumos/platform2/+/HEAD/power_manager/README.md>
8
9use crate::protos::power_supply_properties::power_supply_properties;
10use crate::protos::power_supply_properties::PowerSupplyProperties;
11use crate::BatteryData;
12use crate::BatteryStatus;
13use crate::PowerData;
14
15// Interface name from power_manager/dbus_bindings/org.chromium.PowerManager.xml.
16pub const POWER_INTERFACE_NAME: &str = "org.chromium.PowerManager";
17// Object path from power_manager/dbus_bindings/org.chromium.PowerManager.xml.
18pub const POWER_OBJECT_PATH: &str = "/org/chromium/PowerManager";
19
20pub mod client;
21pub mod monitor;
22
23impl From<PowerSupplyProperties> for PowerData {
24    fn from(props: PowerSupplyProperties) -> Self {
25        let ac_online = if props.has_external_power() {
26            props.external_power() != power_supply_properties::ExternalPower::DISCONNECTED
27        } else {
28            false
29        };
30
31        let battery = if props.has_battery_state()
32            && props.battery_state() != power_supply_properties::BatteryState::NOT_PRESENT
33        {
34            let status = match props.battery_state() {
35                power_supply_properties::BatteryState::FULL => BatteryStatus::NotCharging,
36                power_supply_properties::BatteryState::CHARGING => BatteryStatus::Charging,
37                power_supply_properties::BatteryState::DISCHARGING => BatteryStatus::Discharging,
38                _ => BatteryStatus::Unknown,
39            };
40
41            let percent = std::cmp::min(100, props.battery_percent().round() as u32);
42            // Convert from volts to microvolts.
43            let voltage = (props.battery_voltage() * 1_000_000f64).round() as u32;
44            // Convert from amps to microamps.
45            let current = (props.battery_current() * 1_000_000f64).round() as u32;
46            // Convert from ampere-hours to micro ampere-hours.
47            let charge_counter = (props.battery_charge() * 1_000_000f64).round() as u32;
48            let charge_full = (props.battery_charge_full() * 1_000_000f64).round() as u32;
49
50            Some(BatteryData {
51                status,
52                percent,
53                voltage,
54                current,
55                charge_counter,
56                charge_full,
57            })
58        } else {
59            None
60        };
61
62        Self { ac_online, battery }
63    }
64}