Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Linux] More tolerant battery detection #2220

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
46 changes: 40 additions & 6 deletions psutil/_pslinux.py
Original file line number Diff line number Diff line change
Expand Up @@ -1548,17 +1548,45 @@ def multi_bcat(*paths):
return ret.strip()
return None

def detect_battery_path(*expected_files):
"""Find the device path having the maximum number of files
that are to be excepted for a battery. If no path has the
expected files, return None. Used as a fallback for when
the usual prefixes don't find a match.
"""
highest_score, final_battery = 0, None
for battery in os.listdir(POWER_SUPPLY_PATH):
battery_path = os.path.join(POWER_SUPPLY_PATH, battery)

actual_files = os.listdir(battery_path)
current_score = len([
f for f in actual_files if f in expected_files
])

if current_score > highest_score:
highest_score, final_battery = current_score, battery

return final_battery

bats = [
x
for x in os.listdir(POWER_SUPPLY_PATH)
if x.startswith('BAT') or 'battery' in x.lower()
]
if not bats:
return None
# Get the first available battery. Usually this is "BAT0", except
# some rare exceptions:
# https://github.com/giampaolo/psutil/issues/1238
root = os.path.join(POWER_SUPPLY_PATH, sorted(bats)[0])
if bats:
# Get the first available battery. Usually this is "BAT0", except
# some rare exceptions:
# https://github.com/giampaolo/psutil/issues/1238
root = os.path.join(POWER_SUPPLY_PATH, sorted(bats)[0])
else:
# Fallback to handle the rare exceptions
root = detect_battery_path(
"energy_now", "charge_now", "power_now", "current_now",
"energy_full", "charge_full", "capacity", "time_to_empty_now"
)

if root is None:
return

# Base metrics.
energy_now = multi_bcat(root + "/energy_now", root + "/charge_now")
Expand Down Expand Up @@ -1586,6 +1614,12 @@ def multi_bcat(*paths):
os.path.join(POWER_SUPPLY_PATH, "AC0/online"),
os.path.join(POWER_SUPPLY_PATH, "AC/online"),
)
if online is None:
# Fallback for when 'AC' and 'AC0' don't exist
online = multi_bcat(
detect_battery_path("online")
)

if online is not None:
power_plugged = online == 1
else:
Expand Down