top | item 32468359

(no title)

Nephx | 3 years ago

Simple command line utility to display charging (or discharging) rate in watts on linux. You might have to modify battery_directory and the status/current_now/voltage_now names based on laptop brand, but Lenovo, Dell and Samsung seems to use this convention.

    #!/usr/bin/python3

    battery_directory = "/sys/class/power_supply/BAT1/"

    with open(battery_directory + "status", "r") as f:
        state = f.read().strip()

    with open(battery_directory + "current_now", "r") as f:
        current = int(f.read().strip())

    with open(battery_directory + "voltage_now", "r") as f:
        voltage = int(f.read().strip())

    wattage = (voltage / 10**6) * (current / 10**6)
    wattage_formatted = f"{'-' if state == 'Discharging' else ''}{wattage:.2f}W"

    if state in ["Charging", "Discharging", "Not charging"]:
        print(f"{state}: {wattage_formatted}")

Output:

Charging: 32.15W

Discharging: -5.15W

discuss

order

chrismorgan|3 years ago

My ASUS Zephyrus G15 has a BAT0 with power_now (in microwatts) instead of current_now and voltage_now.

I have in my shell history which I occasionally use:

  while true; do echo -n '^[[34m'; date --iso-8601=seconds | tr -d '\n'; echo -n '^[[m: battery contains ^[[31m'; echo "scale=3;$(cat /sys/class/power_supply/BAT0/energy_now)/1000000" | bc | tr -d '\n'; echo -n 'Wh^[[m, '; [ "$(cat /sys/class/power_supply/BAT0/status)" = "Discharging" ] && echo -n 'consuming' || echo -n 'charging at'; echo -n ' ^[[32m'; echo "scale=3;$(cat /sys/class/power_supply/BAT0/power_now)/1000000" | bc | tr -d '\n'; echo 'W^[[m'; sleep 60; done
(With ^[ being actual escape, entered via Ctrl-V Escape, because I find writing the escape codes literally easier and more consistent than using echo -e or whatever else.)

It’ll show lines like this every minute (with nice colouring):

  2022-08-16T01:07:31+10:00: battery contains 76.968Wh, charging at 0W
My PinePhone has an axp20x-battery with current_now and voltage_now, like your various laptops except that while discharging it gets a negative current_now, which makes perfect sense to me but which doesn’t seem to match your laptops (since you add the negative sign manually in your script) or my laptop’s power_now (which is likewise still positive while discharging).