Fix powerapplet find battery in laptop
Forum member Vverve posted a fix for powerapplet_tray that finds the battery on his laptop:
https://forum.puppylinux.com/viewtopic.php?p=180195#p180195
I'm on a roll last couple of days with Claude AI, so gave it the source of powerapplet_tray v3.2, and asked:
This is a Linux tray application that monitors battery status
in a laptop, displays percentage charge and warns when battery
low. The problem is that it does not detect the battery on some
laptops. Can you suggest a change that will fix this?
Claude responded:
I've patched it so the applet finds the battery by what it is
rather than by name, but I haven't built or run it. This sandbox
has no GTK headers and no batteries, so I could only check the
new detection function on its own. Please run `./compile` and
try it on a laptop that failed before.
**The cause:** On modern kernels the `/sys` branch of `main()`
only looks for `/sys/class/power_supply/BAT0`, then `BAT1`. If
neither exists, it logs "Abort, unable to open … BAT0 or BAT1"
and exits. Some laptops name the battery `CMB0`, `BATT`, `BATC`
or `macsmc-battery` (Apple Silicon), so the applet never starts
there.
**The fix:** I added `find_sys_battery()`, which scans
`/sys/class/power_supply/` and picks the first entry that:
- has `type` = `Battery`, which skips AC adapters and USB
supplies;
- isn't a peripheral battery (`scope` = `Device`), such as a
wireless mouse or keyboard;
- has a `capacity` file;
- has `present` not equal to 0. A battery that reports absent is
used only as a last resort, so a dual-battery machine with an
empty bay still works.
The discovered name replaces the hard-coded `BAT0`/`BAT1` paths.
I also fixed three nearby problems:
- **Click dialog:** it ran `cat
/sys/class/power_supply/BAT[01]/uevent`, so the
click-for-details popup would have been blank on those same
machines. It now uses the detected battery.
- **Crash on unreadable files:** `Update()` called `fgets` on a
possibly NULL file pointer. It now returns quietly, so the timer
stays alive if the battery is unplugged or unreadable.
- **"Not charging" status:** this status (some laptops report it
at a charge threshold) is now treated as not charging, so the
icon isn't shown as charging when it isn't.
Compiling the isolated function with `-Wall` gave only harmless
`snprintf` truncation warnings. They can't trigger, because
names of 64 characters or more are skipped first.
Files are in `/home/claude`:
- battery-detect.patch
- powerapplet_tray.c
I have compiled it and created powerapplet_tray version 3.3. It
works the same on my laptop, detects BAT0. Remains to be seen how
works on others such as Vverve's laptop.
Tags: easy