Evgenii Legotckoi
April 1, 2017, 10:16 p.m.

Qt Linux - Lesson 003. Checking the battery level of the laptop using libacpi

On the forum we to talk about checking the battery level of the laptop under Linux using the Qt library. In fact, Qt does not currently provide a class that would allow you to check the battery charge. But such functionality can be implemented with the help of third-party libraries, for example libacpi.

Let's try to create an application that will take at least some data, and it will look like this:


libacpi

The library itself is written in C and has the following functions and data structures of interest:

  • global_t - A global data structure that stores the number of fans, batteries and thermal zones, as well as a structure with a power adapter.
  • init_acpi_batt(global_t *globals) - Initializing battery data
  • init_acpi_acadapt(global_t *globals) - Initializing adapter data
  • init_acpi_fan(global_t *globals) - Initializing fan data
  • init_acpi_thermal(global_t *globals) - Initialization of data on thermal zones
  • read_acpi_batt(int num) - Battery data reading
  • read_acpi_zone(int num, global_t *globals) - Reading of data on thermal zones
  • read_acpi_fan(int num) - Read fan data
  • battery_t - Battery data structure
  • fans_t - Fan data structure
  • thermal_t - Structure of data on the thermal zone
  • battery_t batteries [MAX_ITEMS] - Array of batteries, it stores the data when called read_acpi_batt
  • thermal_t thermals [MAX_ITEMS] - Array of thermal zones, it stores data when called read_acpi_zone
  • fan_t fans [MAX_ITEMS] - Array of fans, it stores data when called read_acpi_fan

Using the Library

To use a library in a project on Qt, you must:

  1. Install the library from the repository:
  1. sudo apt-get install libacpi-dev
  1. Connect the library to the project pro file:
  1. LIBS += -lacpi
  1. Connect the library header file to the source file where it will receive battery charge data:
  1. #ifdef __cplusplus
  2. extern "C" {
  3. #endif
  4.  
  5. #include <libacpi.h>
  6.  
  7. #ifdef __cplusplus
  8. }
  9. #endif

Main application window

The main application window is the Widget class, which is made using a ui file and whose interface is made through a graphical designer. It has ScrollArea, which contains an object for the vertical placement of elements, widgets, which will be created dynamically, depending on what the library could find. And also there is a button for starting the data reading by the library.

widget.h

In the header file, vectors with widgets for batteries, fans and thermal zones are declared. Also, a pointer to the widget with the power adapter is declared. All widgets are custom classes. A little further on is an example of the code of one of the widgets.

  1. #ifndef WIDGET_H
  2. #define WIDGET_H
  3.  
  4. #include <QWidget>
  5.  
  6. #include "batterywidget.h"
  7. #include "adapterwidget.h"
  8. #include "fanwidget.h"
  9. #include "thermalwidget.h"
  10.  
  11. namespace Ui {
  12. class Widget;
  13. }
  14.  
  15. class Widget : public QWidget
  16. {
  17. Q_OBJECT
  18.  
  19. public:
  20. explicit Widget(QWidget *parent = 0);
  21. ~Widget();
  22.  
  23. private slots:
  24. void on_pushButton_clicked();
  25.  
  26. private:
  27. Ui::Widget *ui;
  28. QVector<BatteryWidget*> m_butteryWidgetList; // Vector widget with batteries
  29. QVector<FanWidget*> m_fanWidgetList; // Vector of widgets with fans
  30. QVector<ThermalWidget*> m_thermalWidgetList; // Vector of widgets with thermal zones
  31. AdapterWidget* m_adapterWidget; // Widget for power adapter is always one
  32. };
  33.  
  34. #endif // WIDGET_H

widget.cpp

Since the library is written in C, it has a procedural style of code execution. And also there is one little trick. The matter is that in library there are some global variables in which the data are written down. These are arrays with fans, heat zones and batteries.

That is, when you call a function read_acpi_batt(1) , then you write down the data structure battery_t into the cell of the array batteries[1].

Whereas to create a global structure that contains data on the number of all the above listed structures, you need to allocate memory.

  1. #include "widget.h"
  2. #include "ui_widget.h"
  3.  
  4. #ifdef __cplusplus
  5. extern "C" {
  6. #endif
  7.  
  8. #include <libacpi.h>
  9.  
  10. #ifdef __cplusplus
  11. }
  12. #endif
  13.  
  14. #include <QFileDialog>
  15.  
  16. Widget::Widget(QWidget *parent) :
  17. QWidget(parent),
  18. ui(new Ui::Widget),
  19. m_adapterWidget(nullptr)
  20. {
  21. ui->setupUi(this);
  22. }
  23.  
  24. Widget::~Widget()
  25. {
  26. delete ui;
  27. }
  28.  
  29. void Widget::on_pushButton_clicked()
  30. {
  31. // We allocate memory for the global data structure of the library
  32. global_t *global = static_cast<global_t*>(malloc(sizeof(global_t)));
  33.  
  34. // Initialize the structure for
  35. init_acpi_batt(global); // Batteries
  36. init_acpi_acadapt(global); // Power adapter
  37. init_acpi_fan(global); // Fans
  38. init_acpi_thermal(global); // Thermal zones
  39.  
  40. // Battery
  41. battery_t *binfo;
  42.  
  43. // If there were batteries, then we read the data in the loop and add widgets
  44. for(int i=0; i < global->batt_count; i++)
  45. {
  46. read_acpi_batt(i); // Read the data
  47. // Which are read into a special array of batteries - it is in the library itself
  48. binfo = &batteries[i];
  49.  
  50. BatteryWidget* butteryWidget;
  51. // Create a widget
  52. if (m_butteryWidgetList.count() <= i)
  53. {
  54. butteryWidget = new BatteryWidget(this);
  55. butteryWidget->setTitle(QString(binfo->name));
  56. m_butteryWidgetList.append(butteryWidget);
  57. ui->verticalLayout->addWidget(butteryWidget);
  58. }
  59. else
  60. {
  61. // Or we take it from the list of widgets
  62. butteryWidget = m_butteryWidgetList.at(i);
  63. }
  64.  
  65. // Set
  66. butteryWidget->setPercentage(binfo->percentage); // Percent charge
  67. butteryWidget->setChargeTime(binfo->charge_time); // Time to full charge
  68. butteryWidget->setRemainingTime(binfo->remaining_time); // Time to full discharge
  69.  
  70. // Determine the charge status
  71. switch (binfo->charge_state)
  72. {
  73. case C_CHARGE:
  74. butteryWidget->setChargeState("Charging");
  75. break;
  76. case C_DISCHARGE:
  77. butteryWidget->setChargeState("Discharging");
  78. case C_CHARGED:
  79. butteryWidget->setChargeState("Charged");
  80. case C_NOINFO:
  81. butteryWidget->setChargeState("No info");
  82. default:
  83. butteryWidget->setChargeState("Error");
  84. break;
  85. }
  86. }
  87.  
  88. // Adapter
  89. // Configuring the Widget for the Power Adapter
  90. adapter_t *ac = &global->adapt;
  91.  
  92. if (!m_adapterWidget)
  93. {
  94. m_adapterWidget = new AdapterWidget(this);
  95. ui->verticalLayout->addWidget(m_adapterWidget);
  96. }
  97.  
  98. // Here we check only whether it is connected or not
  99. switch (ac->ac_state)
  100. {
  101. case P_AC:
  102. m_adapterWidget->setStatus("Runs on AC");
  103. break;
  104. case P_BATT:
  105. m_adapterWidget->setStatus("Runs on battery");
  106. default:
  107. m_adapterWidget->setStatus("Error");
  108. break;
  109. }
  110.  
  111. // Fan
  112. fan_t *finfo;
  113.  
  114. // If there are fans, then we read the data in the loop and add widgets
  115. for(int i=0; i < global->fan_count; i++)
  116. {
  117. read_acpi_fan(i); // Read the data
  118. // Which are read into a special array of fans - it is in the library itself
  119. finfo = &fans[i];
  120. FanWidget* fanWidget;
  121.  
  122. // Create a widget
  123. if (m_fanWidgetList.count() <= i)
  124. {
  125. fanWidget = new FanWidget(this);
  126. fanWidget->setTitle(QString(finfo->name));
  127. m_fanWidgetList.append(fanWidget);
  128. ui->verticalLayout->addWidget(fanWidget);
  129. }
  130. else
  131. {
  132. // Or we take it from the list of widgets
  133. fanWidget = m_fanWidgetList.at(i);
  134. }
  135.  
  136. // Set the status, whether it is on or not
  137. switch (finfo->fan_state)
  138. {
  139. case F_ON:
  140. fanWidget->setStatus("ON");
  141. break;
  142. case F_OFF:
  143. fanWidget->setStatus("OFF");
  144. default:
  145. fanWidget->setStatus("Error");
  146. break;
  147. }
  148. }
  149.  
  150. // Thermal
  151. thermal_t *tinfo;
  152.  
  153. // If there are thermal zones, then we read the data in the cycle and add widgets
  154. for(int i=0; i < global->fan_count; i++)
  155. {
  156. read_acpi_zone(i, global); // Read the data
  157. // Which are read into a special array of thermals - it is in the library itself
  158. tinfo = &thermals[i];
  159. ThermalWidget* thermalWidget;
  160.  
  161. // Create a widget
  162. if (m_thermalWidgetList.count() <= i)
  163. {
  164. thermalWidget = new ThermalWidget(this);
  165. thermalWidget->setTitle(QString(tinfo->name));
  166. m_thermalWidgetList.append(thermalWidget);
  167. ui->verticalLayout->addWidget(thermalWidget);
  168. }
  169. else
  170. {
  171. // Or we take it from the list of widgets
  172. thermalWidget = m_thermalWidgetList.at(i);
  173. }
  174.  
  175. thermalWidget->setTemperature(tinfo->temperature); // Set the temperature
  176. thermalWidget->setFrequency(tinfo->frequency); // And frequency
  177. }
  178.  
  179. free(global);
  180. }

Widgets

The program contains widgets for all the above structures. They serve only for displaying information and dynamic addition. Here is an example widget that displays information about the battery.

batterywidget.h

  1. #ifndef BATTERYWIDGET_H
  2. #define BATTERYWIDGET_H
  3.  
  4. #include <QWidget>
  5.  
  6. namespace Ui {
  7. class BatteryWidget;
  8. }
  9.  
  10. class BatteryWidget : public QWidget
  11. {
  12. Q_OBJECT
  13.  
  14. public:
  15. explicit BatteryWidget(QWidget *parent = 0);
  16. ~BatteryWidget();
  17.  
  18. void setTitle(QString title); // Battery name (as specified in Linux OS)
  19. void setPercentage(int percentage); // Percent charge
  20. void setChargeTime(int chargeTime); // Time to full charge in minutes
  21. void setRemainingTime(int remainingTime); // Time to full discharge in minutes
  22. void setChargeState(QString chargeState); // State
  23.  
  24. private:
  25. Ui::BatteryWidget *ui;
  26. };
  27.  
  28. #endif // BATTERYWIDGET_H

batterywidget.cpp

  1. #include "batterywidget.h"
  2. #include "ui_batterywidget.h"
  3.  
  4. BatteryWidget::BatteryWidget(QWidget *parent) :
  5. QWidget(parent),
  6. ui(new Ui::BatteryWidget)
  7. {
  8. ui->setupUi(this);
  9. }
  10.  
  11. BatteryWidget::~BatteryWidget()
  12. {
  13. delete ui;
  14. }
  15.  
  16. void BatteryWidget::setTitle(QString title)
  17. {
  18. ui->label_title->setText(title);
  19. }
  20.  
  21. void BatteryWidget::setPercentage(int percentage)
  22. {
  23. ui->label_percentage->setText(QString::number(percentage));
  24. }
  25.  
  26. void BatteryWidget::setChargeTime(int chargeTime)
  27. {
  28. ui->label_charge_time->setText(QString("%1:%2").arg(chargeTime / 60).arg(chargeTime % 60));
  29. }
  30.  
  31. void BatteryWidget::setRemainingTime(int remainingTime)
  32. {
  33. ui->label_remaining_time->setText(QString("%1:%2").arg(remainingTime / 60).arg(remainingTime % 60));
  34. }
  35.  
  36. void BatteryWidget::setChargeState(QString chargeState)
  37. {
  38. ui->label_charge_state->setText(chargeState);
  39. }

The result of the library

The result of the library I would call satisfactory, although it determines the percentage of battery charge, as well as the time for a full charge of the battery. But the time until the discharge, she did not determine. And also did not find any fans and thermal zones. I believe that on my laptop model this data is simply not available. Also, there were occasional drops of the application when trying to access certain parameters of structures.

The screenshot that appears at the beginning of the article displays the data that the library could find in my laptop. There, of course, not all the data are given, if you look at the library header file, you will find that the structures provide a richer selection of parameters. But to demonstrate the launch of the library I consider it sufficient.

Try to run the project at home, and if possible, write, if you have a laptop in this notebook will find thermal zones and fans.

Application project

Recommended articles on this topic

By article asked0question(s)

0

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html