1
0
mirror of https://github.com/Llewellynvdm/conky.git synced 2025-01-16 04:02:15 +00:00

linux: Support power_now in sysfs for get_battery_power_draw()

Not all systems report current_now through the power supply sysfs
interface, but some do report power_now instead. Add support for these,
too.

The new implementation first tries power_now and then falls back to
computing power as the product of current and voltage. The new
implementation also reduces memory footprint on the stack by some 512k.
Also the old implementation potentially left files open under some
circumstances.
This commit is contained in:
Stefan Huber 2024-12-02 20:24:27 +01:00 committed by Brenden Matthews
parent 91250e6277
commit d0247218a8

View File

@ -2360,35 +2360,48 @@ void get_battery_short_status(char *buffer, unsigned int n, const char *bat) {
} }
void get_battery_power_draw(char *buffer, unsigned int n, const char *bat) { void get_battery_power_draw(char *buffer, unsigned int n, const char *bat) {
static int reported = 0; static int reported_power = 0;
char current_now_path[256], voltage_now_path[256], current_now_val[256], static int reported_other = 0;
voltage_now_val[256]; char path[256];
char *ptr; char value[256];
long current_now, voltage_now; FILE *fp;
FILE *current_now_file; char *ret;
FILE *voltage_now_file;
double result;
snprintf(current_now_path, 255, SYSFS_BATTERY_BASE_PATH "/%s/current_now", snprintf(path, 255, SYSFS_BATTERY_BASE_PATH "/%s/power_now", bat);
bat); fp = open_file(path, &reported_power);
snprintf(voltage_now_path, 255, SYSFS_BATTERY_BASE_PATH "/%s/voltage_now", if (fp != nullptr) {
bat); ret = fgets(value, 256, fp);
fclose(fp);
current_now_file = open_file(current_now_path, &reported); if (ret != nullptr) {
voltage_now_file = open_file(voltage_now_path, &reported); double result = strtol(value, NULL, 10) * 1e-6;
if (current_now_file != nullptr && voltage_now_file != nullptr) {
if (fgets(current_now_val, 256, current_now_file) &&
fgets(voltage_now_val, 256, voltage_now_file)) {
current_now = strtol(current_now_val, &ptr, 10);
voltage_now = strtol(voltage_now_val, &ptr, 10);
result = current_now * (voltage_now / 1e12);
snprintf(buffer, n, "%.1f", result); snprintf(buffer, n, "%.1f", result);
return;
} }
fclose(current_now_file);
fclose(voltage_now_file);
} }
snprintf(path, 255, SYSFS_BATTERY_BASE_PATH "/%s/current_now", bat);
fp = open_file(path, &reported_other);
if (fp == nullptr)
return;
ret = fgets(value, 256, fp);
fclose(fp);
if (ret == nullptr)
return;
double result = strtol(value, NULL, 10) * 1e-6;
snprintf(path, 255, SYSFS_BATTERY_BASE_PATH "/%s/voltage_now", bat);
fp = open_file(path, &reported_other);
if (fp == nullptr)
return;
ret = fgets(value, 256, fp);
fclose(fp);
if (fp == nullptr)
return;
result *= strtol(value, NULL, 10) * 1e-6;
snprintf(buffer, n, "%.1f", result);
} }
int _get_battery_perct(const char *bat) { int _get_battery_perct(const char *bat) {