From e2d8f58a1833686024b013de707c4786abce1279 Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Thu, 26 Jan 2017 20:46:08 +0100 Subject: #955: sensors_battery() / linux: implement secsleft --- docs/index.rst | 13 ++++++++++++- psutil/_pslinux.py | 10 ++++------ psutil/tests/test_linux.py | 6 ++++++ 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/docs/index.rst b/docs/index.rst index 8db5b111..52424b39 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -629,7 +629,18 @@ Sensors may also be :data:`psutil.POWER_TIME_UNKNOWN ` or :data:`psutil.POWER_TIME_UNLIMITED `. - If no battery is installed this function will return ``None``. + If no battery is installed this function will return ``None``. Example:: + + >>> def secs2hours(secs): + ... m, s = divmod(secs, 60) + ... h, m = divmod(m, 60) + ... return "%d:%02d:%02d" % (h, m, s) + ... + >>> batt = psutil.sensors_battery() + >>> batt + sbattery(percent=93, secsleft=16628) + >>> print("charge = %s%%, time left = %s" % (batt.percent, secs2hours(batt.secsleft))) + charge = 93%, time left = 4:37:08 Availability: Linux, Windows diff --git a/psutil/_pslinux.py b/psutil/_pslinux.py index 0fba0fa6..fff77aab 100644 --- a/psutil/_pslinux.py +++ b/psutil/_pslinux.py @@ -1069,13 +1069,11 @@ def sensors_battery(): if not os.path.exists(root.rstrip('/')): return None - # TODO: figure out the algorithm to calculate residual time. - # energy_now = int(cat(root + "energy_now")) - # power_now = int(cat(root + "power_now")) - # energy_full = int(cat(root + "energy_full")) - # secsleft = 3600 * energy_now / power_now + energy_now = int(cat(root + "energy_now")) + power_now = int(cat(root + "power_now")) percent = int(cat(root + "capacity")) - return _common.sbattery(percent, 0) + secsleft = int(energy_now / power_now * 3600) + return _common.sbattery(percent, secsleft) # ===================================================================== diff --git a/psutil/tests/test_linux.py b/psutil/tests/test_linux.py index 37352ecf..54d5e251 100755 --- a/psutil/tests/test_linux.py +++ b/psutil/tests/test_linux.py @@ -1024,6 +1024,12 @@ class TestMisc(unittest.TestCase): finally: t.stop() + def test_sensors_battery_percent(self): + out = sh("acpi -b") + acpi_value = int(out.split(",")[1].strip().replace('%', '')) + psutil_value = psutil.sensors_battery().percent + self.assertAlmostEqual(acpi_value, psutil_value, delta=1) + # ===================================================================== # test process -- cgit v1.2.1