Developing Power Aware Applications Using D-Bus

Introduction


Computer power consumption has become a passionate subject; hardware engineers trying to minimize the power consumed by devices, and software engineers trying to optimize their code to reduce the power consumed by their applications. Power is an even more important issue with Mobile Internet Devices (MIDs) since the small form factor limits the size of the battery. Applications running on MID's must therefore be very sensitive to power, and use power information to make smart decisions. For example, before beginning a lengthy transaction (such as downloading a video, or running an update), an application should check to see if the device is running on external power, and if not, determine whether or not there is sufficient power remaining to complete the transaction.

Background on D-Bus


D-Bus is a fast, lightweight message bus system which allows applications to communicate each other (Inter-process communication) [2]. It has a so-called D-Bus message bus (dbus daemon) which can accept messages from multiples applications and forward messages to them. D-Bus can be used as low-level API or higher level binding, such as Qt, Python*, Java*, C#, or Perl. This paper shows an application written in C using Glib bindings. Glib is the base library of GNOME, it provides an object system, object-based and event-driven programming.

Two buses are defined in D-Bus: system bus and session bus. The system bus allows communication between an application and the operating system while the session bus is designed to serve the communication between two applications.

In order to use D-Bus, we need to explore some concepts about D-Bus. First, an object is an endpoint on the bus, an object is created by an application in the context that the application's connection to the bus (either system bus or session bus). Objects have names, and these names are called object paths. A proxy is an object on the bus that can be accessed through references. We can find an object by searching the bus name and the object living in that bus connection. Once we find it, we usually keep a proxy to that object so we can refer to that object again without searching again.

An object can perform some specific operations. Each operation is referred as method. Thus, a client can send a request to an object and ask the object to invoke a method. The object then executes the method (if the method exists) and the result is sent back to the client. If a method requires input parameters, these parameters have to be passed with the request. The result can be one or more output parameters, these parameters are sent back to the client in the reply message.

An object can also emit an event, or signal. When a signal is generated by an object, it will be broadcasted to any observers who are interested in that particular signal. Signals can carry parameters too. Methods and Signals are embedded members of an object. They can be grouped. An Interface of an object is just a group of its members. An object can declare one or many interfaces - its members are then classified in these interfaces.

Instead of forming a D-Bus method call message and sending to the remote object using Glib bindings, one can instantiate a proxy object representing the remote object and then just invoke the methods of that object.

In order to generate dbus-glib binding code, we can use a tool called dbus-binding-tool. We first create an XML file, referred as Introspection XML file, in which we describe the methods and signals. An example of the introspection XML is shown below:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE node PUBLIC 
"-//freedesktop//DTD D-Bus Object Introspection 1.0//EN"
"http://standards.freedesktop.org/dbus/1.0/introspect.dtd">
<node name="/org/moblin/Platform">
  <interface name="org.moblin.Platform.Power">
       <annotation name="org.freedesktop.DBus.GLib.CSymbol" value="org_moblin_platform_power"/>
    <method name="IsUsingExternalPowerSource">
       <annotation name="org.freedesktop.DBus.GLib.CSymbol" value="isUsingExternalPowerSource" />
       <arg type="b" name="usingExternalPowerSource" direction="out" />
    </method>
    <method name="GetTimeRemaining">
       <annotation name="org.freedesktop.DBus.GLib.CSymbol" value="getTimeRemaining"/>
       <arg type="i" name="minutesRemaining" direction="out" />
    </method>
    <method name="GetPercentRemaining">
       <annotation name="org.freedesktop.DBus.GLib.CSymbol" value="getPercentRemaining"/>
       <arg type="u" name="percentRemaining" direction="out" />
    </method>
  </interface>
</node>



In this introspection XML file (named MIDPlatformSvcInterfaceDefinition.xml), an interface called org.moblin.Platform.Power defines three methods: IsUsingExternalPowerSource, GetTimeRemaining and GetPerCentRemaining. The output of the first method is a Boolean value. The output of the second method is an integer value representing the value in minutes, while the output of the third method is an unsigned integer value representing the percentage.

Below are primary steps to implement a service with methods to be exposed. More details are explained in [3].

  • Run dbus-binding-tool for an introspection XML file to generate dbus-glib binding code
  • Create a simple GObject for D-Bus
  • Implement the instance initialization
  • Implement the methods
  • Register the object to the D-Bus

To call the methods implemented on a remote object, a client needs to follow the following steps:

  • Connect to the bus
  • Create a proxy object
  • Invoke the methods on the proxy object

Using D-Bus as a Communication Channel


We designed the power service application which uses D-Bus as a communication channel to send information on battery. Other applications which are interested in power awareness can use D-Bus to get power information by querying the methods that the power service provided. These applications can also listen for the events that the power service generated. Figure 1 illustrates the usage model:

Figure 1. Usage Model: A Client Registers to D-Bus to Get the Information Provided by the MISPlatformSvc



Gathering Battery Information


We will present the implementation of three methods that are part of a simple library that provides battery information. The first method queries the percent of battery power remaining (getPercentRemaining). This method returns the percent of power currently available in the battery.

The second method queries the time remaining until the MID runs out of battery power (getTimeRemaining). This method returns the remaining time in minutes.

The third method queries whether or not the MID is using an external power source (IsUsingExternalPowerSource). This method returns a Boolean: TRUE means the MID is currently using an external power source (e.g., AC), FALSE means that the MID is using its battery (DC).

The first method calculates the percent of battery power remaining in a MID. In Linux, the file /proc/acpi/ contains power-related information. In particular, the file /proc/acpi/battery/BAT1/state contains the current remaining capacity in the field "remaining capacity". The file /proc/acpi/battery/BAT1/info contains the maximum capacity information in the "last full capacity" field. From these entries, we can deduce the percent of power remaining as shown below:

gboolean computePercentPowerRemaining(guint *result)
{
       DIR *d;
       struct dirent *de;
       char *acpi_path  = "/proc/acpi";
       char *device_type  = "battery";
       char *stateFile = "state";
       char *infoFile = "info";
       FILE *file;
       char filename[PATH_LENGTH];
       char line[LINE_LENGTH];
       *result = 0;
       double power_left = 0.0;
       double power_full = 0.0;
       gboolean rc = FALSE;
 
       // First, check if the ACPI path exists
       if (chdir(acpi_path) < 0) 
       {
              dbg("ACPI is not supported (\"%s\").n", acpi_path);
              return rc;
       }
       else
              dbg("Path %s is found n", acpi_path);
 
       // Check if battery directory exists
       if (chdir(device_type) < 0) 
       {
              dbg("No support for device type: %sn", device_type);
              return rc;
       }
       else
              dbg("Device %s is supported n", device_type);
       
       // /proc/acpi/battery is found. Now search for available batteries
       d = opendir(".");
       if (!d) {
              dbg("Cannot open directory!n");
              return rc;
       }
 
       while ((de = readdir(d))) {
              // Search for real directory ("BAT0", ...), not ".", ".."
              if (!strcmp(de->d_name, "."))
                     continue;
 
              if (!strcmp(de->d_name, ".."))
                     continue;
 
              dbg("device found: %sn", de->d_name);
 
              // Open file "state".
              sprintf(filename, "%s/%s/%s/%s", acpi_path, device_type, de->d_name, stateFile);
              file = fopen(filename, "r");
              if (!file)
              {
                     closedir(d);
                     return rc;
              }
 
              memset(line, 0, LINE_LENGTH);
              while (fgets(line, LINE_LENGTH, file) != NULL) {
                     if (strstr(line, "remaining capacity:") && 
                           (strstr(line, "mWh") || strstr(line, "mAh")))
                     {
                           // Search the value
                           char *c;
 
                           c = strchr(line, ':');
                           c++;
 
                           power_left = strtoull(c, NULL, 10);      // in mWh or mAh
 
                           // Cannot perform conversion
                           if ((0 == power_left) && (EINVAL == errno))
                           {
                                  closedir(d);
                                  return rc;                 
                           }
                           break;
                     }
              }
 
              fclose(file);
 
              // Open file "info".
              sprintf(filename, "%s/%s/%s/%s", acpi_path, device_type, de->d_name, infoFile);
              file = fopen(filename, "r");
              if (!file)
              {
                     closedir(d);
                     return rc;
              }
 
              memset(line, 0, LINE_LENGTH);
              while (fgets(line, LINE_LENGTH, file) != NULL) {
                     if (strstr(line, "last full capacity:") && 
                            (strstr(line, "mWh") || strstr(line, "mAh")))
                     {
                           // Search the value
                           char *c;
 
                           c = strchr(line, ':');
                           c++;
 
                           power_full = strtoull(c, NULL, 10);      // in mWh or mAh
 
                           // Cannot perform conversion
                           if (0 == power_full)
                           {
                                  closedir(d);
                                  return rc;                 
                           }
 
                           *result = (power_left/power_full)*100;  // in %
                           break;
                     }
              }
 
              rc = TRUE;
              fclose(file);
 
              // Exit while loop
              break;
       }
       closedir(d);
 
       return rc;
}



The second method queries the time remaining until the MID is out battery power (getTimeRemaining). This method returns the remaining time in minutes. As mentioned above, the file /proc/acpi/battery/BAT1/state contains the current remaining capacity in the "remaining capacity" field. The "present rate" field in the same file contains the rate at which the battery capacity is changing. This field is significant only if the battery is discharging. From this information, we can deduce the remaining time in minutes as shown below:

int computeTimeRemaining(void)
{
       DIR *d;
       struct dirent *de;
 
       char *acpi_path  = "/proc/acpi";
       char *device_type  = "battery";
       char *stateFile = "state";
 
       FILE *file;
       char filename[PATH_LENGTH];
       char line[LINE_LENGTH];
       int result = -1;
       double power_left = 0.0;
       double power_full = 0.0;
       double dischargeRate = 0.0;
       int find = 0;
 
       // First, check if the ACPI path exists
       if (chdir(acpi_path) < 0) 
       {
              dbg("ACPI is not supported (\"%s\").n", acpi_path);
              return result;
       }
       else
              dbg("Path %s is found n", acpi_path);
 
       // Check if battery directory exists
       if (chdir(device_type) < 0) 
       {
              dbg("No support for device type: %sn", device_type);
              return result;
       }
       else
              dbg("Device %s is supported n", device_type);
       
       // /proc/acpi/battery is found. Now search for available batteries
       d = opendir(".");
       if (!d) {
              dbg("Cannot open directory!n");
              return result;
       }
 
       while ((de = readdir(d))) {
              // Search for real directory ("BAT0", ...), not ".", ".."
              if (!strcmp(de->d_name, "."))
                     continue;
 
              if (!strcmp(de->d_name, ".."))
                     continue;
 
              dbg("device found: %sn", de->d_name);
 
              // Open file "state".
              sprintf(filename, "%s/%s/%s/%s", acpi_path, device_type, de->d_name, stateFile);
              file = fopen(filename, "r");
              if (!file)
              {
                     closedir(d);
                     return result;
              }
 
              memset(line, 0, LINE_LENGTH);
 
              while (fgets(line, LINE_LENGTH, file) != NULL) {
                     if (strstr(line, "charging state:") &&
                           strstr(line, "discharging"))
                     {
                           find++;
                     }
 
                     if (strstr(line, "present rate:") &&
                           (strstr(line, "mW") || strstr(line, "mA")))
                     {
                           // Search the value
                           char *c;
 
                           c = strchr(line, ':');
                           c++;
 
                           dischargeRate = strtoull(c, NULL, 10);   // in mW or mA
 
                           // Cannot perform conversion
                           if ((0 == dischargeRate) && (EINVAL == errno))
                           {
                                  closedir(d);
                                  return result;                    
                           }
 
                           find++;
                     }
 
                     if (strstr(line, "remaining capacity:") && 
                           (strstr(line, "mWh") || strstr(line, "mAh")))
                     {
                           // Search the value
                           char *c;
 
                           c = strchr(line, ':');
                           c++;
 
                           power_left = strtoull(c, NULL, 10);      // in mWh or mAh
 
                           // Cannot perform conversion
                           if ((0 == power_left) && (EINVAL == errno))
                           {
                                  closedir(d);
                                  return result;                    
                           }
 
                           find++;
                     }
 
 
              }
 
              fclose(file);
 
              // Exit while loop
              break;
       }
       closedir(d);
 
       if (find == 3)
       {
              result = 0;
 
              if (dischargeRate > 0)
                     result = (power_left/dischargeRate)*60;  // convert to minutes
       }
 
       return result;
}



The third method queries whether or not the MID is using an external power source. The information in the file /proc/acpi/ac_adaptor/ACAD/state shows the status of the battery. Below shows the implementation.

int computePowerSource()
{
       DIR *d;
       struct dirent *de;
       char *acadaptor_path  = "/proc/acpi/ac_adapter";
       char *stateFile = "state";
       FILE *file;
       int result = -1;
       char filename[PATH_LENGTH];
 
       // First, check if the ac_adaptor path exists
       if (chdir(acadaptor_path) < 0) 
       {
              return result;
       }
 
       // /proc/acpi/ac_adaptor is found. Now search for available entry
       d = opendir(".");
       if (!d) {
              return result;
       }
 
       while ((de = readdir(d))) {
              char line[LINE_LENGTH];
              // Search for real directory (not ".", ".."
              if (!strcmp(de->d_name, "."))
                     continue;
 
              if (!strcmp(de->d_name, ".."))
                     continue;
 
              sprintf(filename, "%s/%s/%s", acadaptor_path, de->d_name, stateFile);
              file = fopen(filename, "r");
              if (!file)
              {
                     closedir(d);
                     return result;
              }
 
              memset(line, 0, LINE_LENGTH);
              while (fgets(line, LINE_LENGTH, file) != NULL) {
                     if (strstr(line, "state:") && strstr(line, "off-line"))
                           result = 0;   // AC (battery)
                     else if (strstr(line, "state:") && strstr(line, "on-line"))
                           result = 1;   // DC
              }
 
              fclose(file);
       }
 
       closedir(d);
 
       return result;
}



Putting Things Together


First, the introspection XML in previous section clearly defined the three methods for battery. We can now generate a D-Bus binding header file using the D-Bus binding tool.

% dbus-binding-tool --mode=glib-server -–prefix=MIDPlatformSvc --output=MIDPlatformSvc-dbus-glue.h MIDPlatformSvcInterfaceDefinition.xml



Then, we create a platform service object by following standard steps in [3]. We don't show it here since it is straightforward. In the final step, we just glue the three methods above to the implementation.

Each interface method has three parameters: the called object, the return value, and the error. Inside the interface method we glue the return value to its implementation.

gboolean getPercentRemaining(MIDPlatformSvc *obj, guint *percentRemaining, GError **error)
{
       gboolean rc = FALSE;
 
       rc = computePercentPowerRemaining(percentRemaining);
 
       if (rc) 
              return TRUE;
       else
       {
              g_set_error(error, 
                         G_FILE_ERROR,
                         G_FILE_ERROR_NOENT,
                         "Failed to open file /proc/acpi/battery");
              return FALSE;
       }
}
 
gboolean getTimeRemaining(MIDPlatformSvc *obj, gint *timeRemaining, GError **error)
{      
       *timeRemaining = computeTimeRemaining();
 
       if (*timeRemaining > 0)
       {
              return TRUE;
       }
       else if (*timeRemaining == 0)
       {
              g_set_error(error, 
                         G_FILE_ERROR,
                         G_FILE_ERROR_NOENT,
                         "Cannot determine since information is missing!");
              return FALSE;        
       }
       else
       {
              g_set_error(error, 
                         G_FILE_ERROR,
                         G_FILE_ERROR_NOENT,
                         "Failed to open file or directory");
              return FALSE;
       }
}
 
gboolean isUsingExternalPowerSource(MIDPlatformSvc *obj, gboolean *onExternalSource, GError **error)
{
       int t = computePowerSource();
 
       if (t == 0)
       {
              *onExternalSource = FALSE;
              return TRUE;
       }
       else if (t == 1)
       {
              *onExternalSource = TRUE;
              return TRUE;
       }
       else
       {
              g_set_error(error, 
                         G_FILE_ERROR,
                         G_FILE_ERROR_NOENT,
                         "Failed to open file or directory");

              return FALSE;
       }
}



A Test Client


To test the interface power, we write a simple test client using D-Bus as well. The test client invokes the remote methods of object MIDPlatformSvc in order to retrieve battery information on the MID.

#define PLATFORM_SERVICE          "org.moblin.Platform"
#define PLATFORM_PATH                    "/org/moblin/Platform"
#define PLATFORM_POWER_IF         "org.moblin.Platform.Power"
#define POWER_SRC_CHANGED_SIGNAL  "PowerSourceChanged"
 
void queryMethod(char* param) 
{
       DBusGConnection* conn;
       GError *error;
       DBusGProxy *platformProxy;
       DBusError err;
 
       printf("Calling remote method: %sn", param);
 
       g_type_init();
       error = NULL;
       conn = dbus_g_bus_get(DBUS_BUS_SESSION, &error);
 
       // Create the proxy Platform
       platformProxy = dbus_g_proxy_new_for_name(conn,
             PLATFORM_SERVICE,    // target for the method call
                PLATFORM_PATH,    // object to call on
                PLATFORM_POWER_IF);      // interface to call on
 
       // Now call the metjod "IsUsingExternalPowerSource"
       if (param == "GetPercentRemaining")
       {
              uint result;
 
              if (!dbus_g_proxy_call(platformProxy, param, &error, 
                                   G_TYPE_INVALID,
                                   G_TYPE_UINT, &result,
                                   G_TYPE_INVALID))
              {
                     g_printerr("Failed to call remotely: %sn",
                                error->message);
                     g_error_free(error);
              }
              else
                     printf ("Remote call successes with returned value: %d%n", result);
       }
       else if (param == "GetTimeRemaining")
       {
              int result;
 
              if (!dbus_g_proxy_call(platformProxy, param, &error, 
                                  G_TYPE_INVALID,
                                 G_TYPE_INT, &result,
                                 G_TYPE_INVALID))
              {
                     g_printerr("Failed to call remotely: %sn",
                            error->message);
                     g_error_free(error);
              }
              else
              {
                     printf ("Remote call successes with returned value: %d minutesn",result);
              }
       }
       else if (param == "IsUsingExternalPowerSource")
       {
              gboolean result;
 
              if (!dbus_g_proxy_call(platformProxy, param, &error, 
                                  G_TYPE_INVALID,
                                 G_TYPE_BOOLEAN, &result,
                                 G_TYPE_INVALID))
              {
                     g_printerr("Failed to call remotely: %sn",
                            error->message);
                     g_error_free(error);
              }
              else
                     printf ("Remote call successes with returned value: %sn", result? "TRUE" : "FALSE");
       }
 
}
 
int main(int argc, char** argv)
{
       char* methodName[3] = {"GetPercentRemaining",
                           "GetTimeRemaining",
                            "IsUsingExternalPowerSource"};
 
       int i;
       
       for (i = 0; i <= 2; i++)
              queryMethod(methodName[i]);
 
       return 0;
}



Below is the result when running the test client.

Calling remote method: IsUsingExternalPowerSource
% ./clientTester
Calling remote method: GetPercentRemaining
Remote call successes with returned value: 96%
Calling remote method: GetTimeRemaining
Remote call successes with returned value: 235 minutes
Calling remote method: IsUsingExternalPowerSource
Remote call successes with returned value: FALSE



Conclusion


Because the MID form factor limits the size of the battery, applications that run on the platform must be aware of power state information in order to make smart decisions. Knowing how much power is remaining, how much time is remaining, and whether or not the system is running on external power can help software make wise use of the MID's resources. D-Bus is a lightweight Remote Procedure Call (RPC) which is suitable for many applications running on desktop. Because D-Bus is simple and relative small, yet powerful, we can adapt this technology for Mobile Internet Device (MID). In this paper, we introduced a platform service for MID using D-Bus technology. We showed how to implement three power-related methods provided by the MIDPlatformSvc. A sample test client is also shown to illustrate how we can use D-Bus to invoke these methods. As D-Bus not only supports methods, it can also support signals; we can also extend this application to include signals. In the feature, this platform service can be extended to include other interfaces such as network, location, CPU utilization...

References


[1] D-Bus, http://www.freedesktop.org/wiki/Software/dbus
[2] D-Bus Tutorial, http://dbus.freedesktop.org/doc/dbus-tutorial.html
[3] http://www.moblin.org/toolkits/basicDevGuides/mobLinux/toolkits_DevGds_mobLinux_createDBUS.php
[4] Mobile and Internet Linux Project, http://moblin.org/

For more complete information about compiler optimizations, see our Optimization Notice.