Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading Battery Status on Linux/Ubuntu using QT

I am currently developing an application using qt targeting a tablet running ubuntu 14.04

Since there is only a poor battery indicator on the device and the application will run fullscreen for prolonged time, I want to show an battery indicator inside the application. A search found mainly old results or calls to windows, android or ios apis.

Is there any way using just the Qt apis or an other comfortable way to get information about the battery state?

like image 551
Andreas Wilkes Avatar asked Oct 19 '22 09:10

Andreas Wilkes


2 Answers

Even if there is no such API in Qt, you can find a command line utility (for example upower) that does return the battery status details and execute it from your Qt application with QProcess. After the utility has finished the work, you can read its standard output and parse it to find all the necessary information.

For battery related command line tools in Ubuntu you can refer to, for example, this page.

like image 122
vahancho Avatar answered Oct 21 '22 23:10

vahancho


Even though user vahanchos answer was helpful for me, and probably is the way to go for others, I ended up with a different solution.

In my case I code for only one special device type and a known set of development machines. therefore I could just read the relevant files in sys/class/power_supply/. I can not guarantee that other devices will name their files there exactly the same. But it might be worth the try.

#include <QFile>

void refreshValues(){
    QFile acLine("/sys/class/power_supply/AC/online");
    QFile acAdp("/sys/class/power_supply/ADP0/online");
    QFile bCap("/sys/class/power_supply/BAT0/capacity");
    bool ac = false;
    int level = 0;
    if(acLine.exists()){
        acLine.open(QIODevice::ReadOnly | QIODevice::Text);
        if(QString(acLine.readAll()).toInt()){
            ac = true;
        }
        acLine.close();
    }else if(acAdp.exists()){
        acAdp.open(QIODevice::ReadOnly | QIODevice::Text);
        if(QString(acAdp.readAll()).toInt()){
            ac = true;
        }
        acAdp.close();
    }
    if(bCap.exists()){
        bCap.open(QIODevice::ReadOnly | QIODevice::Text);
        level = QString(bCap.readAll()).toInt();
        bCap.close();
    }
    setAcPowerActive(ac);
    setBatteryLevel(level);
}
like image 23
Andreas Wilkes Avatar answered Oct 21 '22 21:10

Andreas Wilkes