-1

I've searched for a while on how to do this without any special library or anything, and it took a while to find something that's working properly.

It's possible to use

/sys/class/power_supply/BAT0/subsystem/BAT0/charge_now
/sys/class/power_supply/BAT0/subsystem/BAT0/charge_full

I was wondering, is there a better way to get the battery status using C/C++ in Ubuntu 18.04?

Nir Geffen
  • 66
  • 1
  • 6
  • What problems are you having with this approach? – Sneftel Dec 17 '20 at 07:50
  • Can't you just read contents of the file in the folders using `C` or `C++` or even `bash` ? What is the application design you are looking for? You don't need anything more than `fopen(...)` and `printf(...)` . – Ilian Zapryanov Dec 17 '20 at 08:26
  • This works. The point of the post was to: a) raise the issue (and maybe search others some search time) b) inquire if there is a better approach – Nir Geffen Dec 18 '20 at 10:39

1 Answers1

0

In case this is never answered.. this is my solution:

#define PATH_BATT_CHARGE_NOW "/sys/class/power_supply/BAT0/subsystem/BAT0/charge_now"
#define PATH_BATT_CHARGE_FULL "/sys/class/power_supply/BAT0/subsystem/BAT0/charge_full"


int getBattState(void)
    {
        int chargedPercent = 0;

        FILE *battChargeNow;
        FILE *battChargeFull;
        long unsigned int battMax_mAh = 0;
        long unsigned int battRemain_mAh = 0;

        if (NULL == (battChargeNow = fopen(PATH_BATT_CHARGE_NOW, "r")))
        {
            fclose(battChargeNow);
            return -1;
        }
        if (NULL == (battChargeFull = fopen(PATH_BATT_CHARGE_FULL, "r")))
        {
            fclose(battChargeNow);
            fclose(battChargeFull);
            return -1;
        }

        fscanf((FILE *)battChargeFull, "%lu", &battMax_mAh);
        fscanf((FILE *)battChargeNow, "%lu", &battRemain_mAh);

        chargedPercent = 100.00 * ((float)battRemain_mAh / (float)battMax_mAh);
        return chargedPercent;
    }
Nir Geffen
  • 66
  • 1
  • 6