android 4.4 电池电量管理底层分析(C\C++层)

来源:互联网 发布:dota直播软件 编辑:程序博客网 时间:2024/06/10 20:31

转自http://blog.csdn.net/daweibalang717/article/details/41446993

参考文献:http://blog.csdn.net/wlwl0071986/article/details/38778897 

简介:

Linux电池驱动用于和PMIC交互、负责监听电池产生的相关事件,例如低电报警、电量发生变化、高温报警、USB插拔等等。

Android电池服务,用来监听内核上报的电池事件,并将最新的电池数据上报给系统,系统收到新数据后会去更新电池显示状态、剩余电量等信息。如果收到过温报警和低电报警,系统会自动触发关机流程,保护电池和机器不受到危害。

Android电池服务的启动和运行流程:


Android电源管理底层用的是Linux powersupply框架,从Android 4.4开始,Google专门提供了一个healthd来监控电源状态。它的路径在:system/core/healthd文件夹下,编译出来的文件为/sbin/healthd。


电池系统从底层向Framework层上报数据的流程:



这里我把文章框架按语言分成 C/C++ 层与Java层。(这篇介绍C/C++ 层, Java 层请看另外一篇博客http://blog.csdn.net/daweibalang717/article/details/40615453),

关于C/C++ 层与驱动交互的代码我不全部贴出,只给出路径,大家可以自己查找阅读,这里值讲述关键函数。


一、关系图:


二、Healthd

  包含两个文件:\system\core\healthd\healthd.h ,\system\core\healthd\healthd.cpp 

   简要说明:

    health.h 是个头文件,只要声明函数与变量,不做过多介绍。我们说下healthd.cpp ,

[cpp] view plain copy
  1. int main(int argc, char **argv) {  
  2.     int ch;  
  3.   
  4.     klog_set_level(KLOG_LEVEL);  
  5.   
  6.     while ((ch = getopt(argc, argv, "n")) != -1) {  
  7.         switch (ch) {  
  8.         case 'n':  
  9.             nosvcmgr = true;  
  10.             break;  
  11.         case '?':  
  12.         default:  
  13.             KLOG_WARNING(LOG_TAG, "Unrecognized healthd option: %c\n", ch);  
  14.         }  
  15.     }  
  16.   
  17.     healthd_board_init(&healthd_config);  
  18.     wakealarm_init();  
  19.     uevent_init();  
  20.     binder_init();  
  21.     gBatteryMonitor = new BatteryMonitor();  
  22.     gBatteryMonitor->init(&healthd_config, nosvcmgr);  
  23.   
  24.     healthd_mainloop();  
  25.     return 0;  
  26. }  

这是main函数,跟Java中的main是一样的,作为程序的入口。这里做一些初始化工作,获得BatteryMonitor的指针对象。我们索要关注的是healthd_mainloop()的调用,仅凭函数名就能知道会进入一个无限循环,这样也就能达到监控电源状态的目的了。下面我们看一下这个函数:

[cpp] view plain copy
  1. static void healthd_mainloop(void) {  
  2.     struct epoll_event ev;  
  3.     int epollfd;  
  4.     int maxevents = 0;  
  5.   
  6.     epollfd = epoll_create(MAX_EPOLL_EVENTS);  
  7.     if (epollfd == -1) {  
  8.         KLOG_ERROR(LOG_TAG,  
  9.                    "healthd_mainloop: epoll_create failed; errno=%d\n",  
  10.                    errno);  
  11.         return;  
  12.     }  
  13.   
  14.     if (uevent_fd >= 0) {  
  15.         ev.events = EPOLLIN;  
  16.         ev.data.ptr = (void *)uevent_event;  
  17.         if (epoll_ctl(epollfd, EPOLL_CTL_ADD, uevent_fd, &ev) == -1)  
  18.             KLOG_ERROR(LOG_TAG,  
  19.                        "healthd_mainloop: epoll_ctl for uevent_fd failed; errno=%d\n",  
  20.                        errno);  
  21.         else  
  22.             maxevents++;  
  23.     }  
  24.   
  25.     if (wakealarm_fd >= 0) {  
  26.         ev.events = EPOLLIN | EPOLLWAKEUP;  
  27.         ev.data.ptr = (void *)wakealarm_event;  
  28.         if (epoll_ctl(epollfd, EPOLL_CTL_ADD, wakealarm_fd, &ev) == -1)  
  29.             KLOG_ERROR(LOG_TAG,  
  30.                        "healthd_mainloop: epoll_ctl for wakealarm_fd failed; errno=%d\n",  
  31.                        errno);  
  32.         else  
  33.             maxevents++;  
  34.    }  
  35.   
  36.     if (binder_fd >= 0) {  
  37.         ev.events = EPOLLIN | EPOLLWAKEUP;  
  38.         ev.data.ptr= (void *)binder_event;  
  39.         if (epoll_ctl(epollfd, EPOLL_CTL_ADD, binder_fd, &ev) == -1)  
  40.             KLOG_ERROR(LOG_TAG,  
  41.                        "healthd_mainloop: epoll_ctl for binder_fd failed; errno=%d\n",  
  42.                        errno);  
  43.         else  
  44.             maxevents++;  
  45.    }  
  46.   
  47.     while (1) {  
  48.         struct epoll_event events[maxevents];  
  49.         int nevents;  
  50.   
  51.         IPCThreadState::self()->flushCommands();  
  52.         nevents = epoll_wait(epollfd, events, maxevents, awake_poll_interval);  
  53.   
  54.         if (nevents == -1) {  
  55.             if (errno == EINTR)  
  56.                 continue;  
  57.             KLOG_ERROR(LOG_TAG, "healthd_mainloop: epoll_wait failed\n");  
  58.             break;  
  59.         }  
  60.   
  61.         for (int n = 0; n < nevents; ++n) {  
  62.             if (events[n].data.ptr)  
  63.                 (*(void (*)())events[n].data.ptr)();  
  64.         }  
  65.   
  66.         if (!nevents)  
  67.             periodic_chores();  
  68.     }  
  69.   
  70.     return;  
  71. }  

我们来看一下这个函数都干了哪些事情呢?首先,代码:epollfd = epoll_create(MAX_EPOLL_EVENTS);创建一个 epoll 实例,并要求内核分配一个可以保存 size 个描述符的空间( 关于epoll,Linux中的字符设备驱动中有一个函数是poll,Linux 2.5.44版本后被epoll取代,请参考:http://baike.baidu.com/view/1385104.htm?fr=aladdin ), 然后把函数赋值 ev.data.ptr = (void *)uevent_event; 在while(1) 的 调用 nevents = epoll_wait(epollfd, events, maxevents, awake_poll_interval); 等待EPOLL事件的发生,相当于监听。当收到监听后,就是在
[java] view plain copy
  1. for (int n = 0; n < nevents; ++n) {  
  2.     if (events[n].data.ptr)  
  3.         (*(void (*)())events[n].data.ptr)();  
  4. }  

for循环中调用 事件赋值 ev.data.ptr = (void *)uevent_event; 所赋值的函数, 其实相当于Java中的回调接口。我们这里值关注uevent_event 函数。因为这个是跟电池属性相关的。uevent_event 函数如下:

[cpp] view plain copy
  1. static void uevent_event(void) {  
  2.     char msg[UEVENT_MSG_LEN+2];  
  3.     char *cp;  
  4.     int n;  
  5.   
  6.     n = uevent_kernel_multicast_recv(uevent_fd, msg, UEVENT_MSG_LEN);  
  7.     if (n <= 0)  
  8.         return;  
  9.     if (n >= UEVENT_MSG_LEN)   /* overflow -- discard */  
  10.         return;  
  11.   
  12.     msg[n] = '\0';  
  13.     msg[n+1] = '\0';  
  14.     cp = msg;  
  15.   
  16.     while (*cp) {  
  17.         if (!strcmp(cp, "SUBSYSTEM=" POWER_SUPPLY_SUBSYSTEM)) {  
  18.             battery_update();  
  19.             break;  
  20.         }  
  21.   
  22.         /* advance to after the next \0 */  
  23.         while (*cp++)  
  24.             ;  
  25.     }  
  26. }  

它会读取socket中的字符串,然后判断事件来源是否是由kernel的power_supply发出的,代码if (!strcmp(cp, "SUBSYSTEM=" POWER_SUPPLY_SUBSYSTEM)) ,如果是,那就调用battery_update()更新电源状态。下面来看看battery_update()是如何更新电源状态的:

[cpp] view plain copy
  1. static void battery_update(void) {  
  2.     // Fast wake interval when on charger (watch for overheat);  
  3.     // slow wake interval when on battery (watch for drained battery).  
  4.   
  5.    int new_wake_interval = gBatteryMonitor->update() ?  
  6.        healthd_config.periodic_chores_interval_fast :  
  7.            healthd_config.periodic_chores_interval_slow;  
  8.   
  9.     if (new_wake_interval != wakealarm_wake_interval)  
  10.             wakealarm_set_interval(new_wake_interval);  
  11.   
  12.     // During awake periods poll at fast rate.  If wake alarm is set at fast  
  13.     // rate then just use the alarm; if wake alarm is set at slow rate then  
  14.     // poll at fast rate while awake and let alarm wake up at slow rate when  
  15.     // asleep.  
  16.   
  17.     if (healthd_config.periodic_chores_interval_fast == -1)  
  18.         awake_poll_interval = -1;  
  19.     else  
  20.         awake_poll_interval =  
  21.             new_wake_interval == healthd_config.periodic_chores_interval_fast ?  
  22.                 -1 : healthd_config.periodic_chores_interval_fast * 1000;  
  23. }  
主要就是这一句:gBatteryMonitor->update() ,gBatteryMonitor 是在mian 函数中初始化的BatteryMonitor的指针对象。 看关系图,这里就由Healthd 跳到BatteryMonitor了。

下面,我们看一下BatteryMonitor


三、BatteryMonitor

  包含两个文件:\system\core\healthd\BatteryMonitor.h ,\system\core\healthd\BatteryMonitor.cpp

   简要说明:

    BatteryMonitor.h 是个头文件,只要声明函数与变量,不做过多介绍。我们说下BatteryMonitor.cpp

    上面说到,battery_update() 中会调用gBatteryMonitor->update() ,那BatteryMonitor.cpp 中的 update()都做了什么了?代码如下:

[cpp] view plain copy
  1. bool BatteryMonitor::update(void) {  
  2.     struct BatteryProperties props;  
  3.     bool logthis;  
  4.   
  5.     props.chargerAcOnline = false;  
  6.     props.chargerUsbOnline = false;  
  7.     props.chargerWirelessOnline = false;  
  8.     props.batteryStatus = BATTERY_STATUS_UNKNOWN;  
  9.     props.batteryHealth = BATTERY_HEALTH_UNKNOWN;  
  10.     props.batteryCurrentNow = INT_MIN;  
  11.     props.batteryChargeCounter = INT_MIN;  
  12.   
  13.     if (!mHealthdConfig->batteryPresentPath.isEmpty())  
  14.         props.batteryPresent = getBooleanField(mHealthdConfig->batteryPresentPath);  
  15.     else  
  16.         props.batteryPresent = true;  
  17.   
  18.     props.batteryLevel = getIntField(mHealthdConfig->batteryCapacityPath);  
  19.     props.batteryVoltage = getIntField(mHealthdConfig->batteryVoltagePath) / 1000;  
  20.   
  21.     if (!mHealthdConfig->batteryCurrentNowPath.isEmpty())  
  22.         props.batteryCurrentNow = getIntField(mHealthdConfig->batteryCurrentNowPath);  
  23.   
  24.     if (!mHealthdConfig->batteryChargeCounterPath.isEmpty())  
  25.         props.batteryChargeCounter = getIntField(mHealthdConfig->batteryChargeCounterPath);  
  26.   
  27.     props.batteryTemperature = getIntField(mHealthdConfig->batteryTemperaturePath);  
  28.   
  29.     const int SIZE = 128;  
  30.     char buf[SIZE];  
  31.     String8 btech;  
  32.   
  33.     if (readFromFile(mHealthdConfig->batteryStatusPath, buf, SIZE) > 0)  
  34.         props.batteryStatus = getBatteryStatus(buf);  
  35.   
  36.     if (readFromFile(mHealthdConfig->batteryHealthPath, buf, SIZE) > 0)  
  37.         props.batteryHealth = getBatteryHealth(buf);  
  38.   
  39.     if (readFromFile(mHealthdConfig->batteryTechnologyPath, buf, SIZE) > 0)  
  40.         props.batteryTechnology = String8(buf);  
  41.   
  42.     unsigned int i;  
  43.   
  44.     for (i = 0; i < mChargerNames.size(); i++) {  
  45.         String8 path;  
  46.         path.appendFormat("%s/%s/online", POWER_SUPPLY_SYSFS_PATH,  
  47.                           mChargerNames[i].string());  
  48.   
  49.         if (readFromFile(path, buf, SIZE) > 0) {  
  50.             if (buf[0] != '0') {  
  51.                 path.clear();  
  52.                 path.appendFormat("%s/%s/type", POWER_SUPPLY_SYSFS_PATH,  
  53.                                   mChargerNames[i].string());  
  54.                 switch(readPowerSupplyType(path)) {  
  55.                 case ANDROID_POWER_SUPPLY_TYPE_AC:  
  56.                     props.chargerAcOnline = true;  
  57.                     break;  
  58.                 case ANDROID_POWER_SUPPLY_TYPE_USB:  
  59.                     props.chargerUsbOnline = true;  
  60.                     break;  
  61.                 case ANDROID_POWER_SUPPLY_TYPE_WIRELESS:  
  62.                     props.chargerWirelessOnline = true;  
  63.                     break;  
  64.                 default:  
  65.                     KLOG_WARNING(LOG_TAG, "%s: Unknown power supply type\n",  
  66.                                  mChargerNames[i].string());  
  67.                 }  
  68.             }  
  69.         }  
  70.     }  
  71.   
  72.     logthis = !healthd_board_battery_update(&props);  
  73.   
  74.     if (logthis) {  
  75.         char dmesgline[256];  
  76.         snprintf(dmesgline, sizeof(dmesgline),  
  77.                  "battery l=%d v=%d t=%s%d.%d h=%d st=%d",  
  78.                  props.batteryLevel, props.batteryVoltage,  
  79.                  props.batteryTemperature < 0 ? "-" : "",  
  80.                  abs(props.batteryTemperature / 10),  
  81.                  abs(props.batteryTemperature % 10), props.batteryHealth,  
  82.                  props.batteryStatus);  
  83.   
  84.         if (!mHealthdConfig->batteryCurrentNowPath.isEmpty()) {  
  85.             char b[20];  
  86.   
  87.             snprintf(b, sizeof(b), " c=%d", props.batteryCurrentNow / 1000);  
  88.             strlcat(dmesgline, b, sizeof(dmesgline));  
  89.         }  
  90.   
  91.         KLOG_INFO(LOG_TAG, "%s chg=%s%s%s\n", dmesgline,  
  92.                   props.chargerAcOnline ? "a" : "",  
  93.                   props.chargerUsbOnline ? "u" : "",  
  94.                   props.chargerWirelessOnline ? "w" : "");  
  95.     }  
  96.   
  97.     if (mBatteryPropertiesRegistrar != NULL)  
  98.         mBatteryPropertiesRegistrar->notifyListeners(props);  
  99.   
  100.     return props.chargerAcOnline | props.chargerUsbOnline |  
  101.             props.chargerWirelessOnline;  
  102. }  
这个函数首先定义了BatteryProperties props; 这个属性集(为了减少介绍的复杂度,大家可以简单的认为只是一个包含各种属性的类),然后给这个属性集 props 里面的属性赋值。然后在最后会在最后判断有无注册监听 ,如果有的话,调用注册的监听,把属性传入监听:

[cpp] view plain copy
  1. if (mBatteryPropertiesRegistrar != NULL)  
  2.      mBatteryPropertiesRegistrar->notifyListeners(props);  
调用的就是上面的东西。 到目前为止,我们知道了health 里面有个无线循环,监控驱动事件,然后调用BatteryProperties中的update方法。 然后update会读取各种属性值,然后调用注册的监听。如下图


  那么问题来了------->挖掘机技术哪家强?哈哈,开个玩笑。下面我们就要分两个分支来讲述:

(1)这些属性是从哪里来的。 

(2)属性变化后调用的监听是谁注册的。




首先,(1)这些属性是从哪里来的。

     我们先看一下 上面的 healthd.cpp 的main 函数初始化 BatteryMonitor 时,调用了

[cpp] view plain copy
  1. gBatteryMonitor = new BatteryMonitor();  
  2.  gBatteryMonitor->init(&healthd_config, nosvcmgr);  
  这个init 初始化的时候都干了些什么呢

[cpp] view plain copy
  1. void BatteryMonitor::init(struct healthd_config *hc, bool nosvcmgr) {  
  2.     String8 path;  
  3.   
  4.     mHealthdConfig = hc;  
  5.     DIR* dir = opendir(POWER_SUPPLY_SYSFS_PATH);  
  6.     if (dir == NULL) {  
  7.         KLOG_ERROR(LOG_TAG, "Could not open %s\n", POWER_SUPPLY_SYSFS_PATH);  
  8.     } else {  
  9.         struct dirent* entry;  
  10.   
  11.         while ((entry = readdir(dir))) {  
  12.             const char* name = entry->d_name;  
  13.   
  14.             if (!strcmp(name, ".") || !strcmp(name, ".."))  
  15.                 continue;  
  16.   
  17.             char buf[20];  
  18.             // Look for "type" file in each subdirectory  
  19.             path.clear();  
  20.             path.appendFormat("%s/%s/type", POWER_SUPPLY_SYSFS_PATH, name);  
  21.             switch(readPowerSupplyType(path)) {  
  22.             case ANDROID_POWER_SUPPLY_TYPE_AC:  
  23.             case ANDROID_POWER_SUPPLY_TYPE_USB:  
  24.             case ANDROID_POWER_SUPPLY_TYPE_WIRELESS:  
  25.                 path.clear();  
  26.                 path.appendFormat("%s/%s/online", POWER_SUPPLY_SYSFS_PATH, name);  
  27.                 if (access(path.string(), R_OK) == 0)  
  28.                     mChargerNames.add(String8(name));  
  29.                 break;  
  30.   
  31.             case ANDROID_POWER_SUPPLY_TYPE_BATTERY:  
  32.                 if (mHealthdConfig->batteryStatusPath.isEmpty()) {  
  33.                     path.clear();  
  34.                     path.appendFormat("%s/%s/status", POWER_SUPPLY_SYSFS_PATH,  
  35.                                       name);  
  36.                     if (access(path, R_OK) == 0)  
  37.                         mHealthdConfig->batteryStatusPath = path;  
  38.                 }  
  39.   
  40.                 if (mHealthdConfig->batteryHealthPath.isEmpty()) {  
  41.                     path.clear();  
  42.                     path.appendFormat("%s/%s/health", POWER_SUPPLY_SYSFS_PATH,  
  43.                                       name);  
  44.                     if (access(path, R_OK) == 0)  
  45.                         mHealthdConfig->batteryHealthPath = path;  
  46.                 }  
  47.   
  48.                 if (mHealthdConfig->batteryPresentPath.isEmpty()) {  
  49.                     path.clear();  
  50.                     path.appendFormat("%s/%s/present", POWER_SUPPLY_SYSFS_PATH,  
  51.                                       name);  
  52.                     if (access(path, R_OK) == 0)  
  53.                         mHealthdConfig->batteryPresentPath = path;  
  54.                 }  
  55.   
  56.                 if (mHealthdConfig->batteryCapacityPath.isEmpty()) {  
  57.                     path.clear();  
  58.                     path.appendFormat("%s/%s/capacity", POWER_SUPPLY_SYSFS_PATH,  
  59.                                       name);  
  60.                     if (access(path, R_OK) == 0)  
  61.                         mHealthdConfig->batteryCapacityPath = path;  
  62.                 }  
  63.   
  64.                 if (mHealthdConfig->batteryVoltagePath.isEmpty()) {  
  65.                     path.clear();  
  66.                     path.appendFormat("%s/%s/voltage_now",  
  67.                                       POWER_SUPPLY_SYSFS_PATH, name);  
  68.                     if (access(path, R_OK) == 0) {  
  69.                         mHealthdConfig->batteryVoltagePath = path;  
  70.                     } else {  
  71.                         path.clear();  
  72.                         path.appendFormat("%s/%s/batt_vol",  
  73.                                           POWER_SUPPLY_SYSFS_PATH, name);  
  74.                         if (access(path, R_OK) == 0)  
  75.                             mHealthdConfig->batteryVoltagePath = path;  
  76.                     }  
  77.                 }  
  78.   
  79.                 if (mHealthdConfig->batteryCurrentNowPath.isEmpty()) {  
  80.                     path.clear();  
  81.                     path.appendFormat("%s/%s/current_now",  
  82.                                       POWER_SUPPLY_SYSFS_PATH, name);  
  83.                     if (access(path, R_OK) == 0)  
  84.                         mHealthdConfig->batteryCurrentNowPath = path;  
  85.                 }  
  86.   
  87.                 if (mHealthdConfig->batteryChargeCounterPath.isEmpty()) {  
  88.                     path.clear();  
  89.                     path.appendFormat("%s/%s/charge_counter",  
  90.                                       POWER_SUPPLY_SYSFS_PATH, name);  
  91.                     if (access(path, R_OK) == 0)  
  92.                         mHealthdConfig->batteryChargeCounterPath = path;  
  93.                 }  
  94.   
  95.                 if (mHealthdConfig->batteryTemperaturePath.isEmpty()) {  
  96.                     path.clear();  
  97.                     path.appendFormat("%s/%s/temp", POWER_SUPPLY_SYSFS_PATH,  
  98.                                       name);  
  99.                     if (access(path, R_OK) == 0) {  
  100.                         mHealthdConfig->batteryTemperaturePath = path;  
  101.                     } else {  
  102.                         path.clear();  
  103.                         path.appendFormat("%s/%s/batt_temp",  
  104.                                           POWER_SUPPLY_SYSFS_PATH, name);  
  105.                         if (access(path, R_OK) == 0)  
  106.                             mHealthdConfig->batteryTemperaturePath = path;  
  107.                     }  
  108.                 }  
  109.   
  110.                 if (mHealthdConfig->batteryTechnologyPath.isEmpty()) {  
  111.                     path.clear();  
  112.                     path.appendFormat("%s/%s/technology",  
  113.                                       POWER_SUPPLY_SYSFS_PATH, name);  
  114.                     if (access(path, R_OK) == 0)  
  115.                         mHealthdConfig->batteryTechnologyPath = path;  
  116.                 }  
  117.   
  118.                 break;  
  119.   
  120.             case ANDROID_POWER_SUPPLY_TYPE_UNKNOWN:  
  121.                 break;  
  122.             }  
  123.         }  
  124.         closedir(dir);  
  125.     }  
  126.   
  127.     if (!mChargerNames.size())  
  128.         KLOG_ERROR(LOG_TAG, "No charger supplies found\n");  
  129.     if (mHealthdConfig->batteryStatusPath.isEmpty())  
  130.         KLOG_WARNING(LOG_TAG, "BatteryStatusPath not found\n");  
  131.     if (mHealthdConfig->batteryHealthPath.isEmpty())  
  132.         KLOG_WARNING(LOG_TAG, "BatteryHealthPath not found\n");  
  133.     if (mHealthdConfig->batteryPresentPath.isEmpty())  
  134.         KLOG_WARNING(LOG_TAG, "BatteryPresentPath not found\n");  
  135.     if (mHealthdConfig->batteryCapacityPath.isEmpty())  
  136.         KLOG_WARNING(LOG_TAG, "BatteryCapacityPath not found\n");  
  137.     if (mHealthdConfig->batteryVoltagePath.isEmpty())  
  138.         KLOG_WARNING(LOG_TAG, "BatteryVoltagePath not found\n");  
  139.     if (mHealthdConfig->batteryTemperaturePath.isEmpty())  
  140.         KLOG_WARNING(LOG_TAG, "BatteryTemperaturePath not found\n");  
  141.     if (mHealthdConfig->batteryTechnologyPath.isEmpty())  
  142.         KLOG_WARNING(LOG_TAG, "BatteryTechnologyPath not found\n");  
  143.   
  144.     if (nosvcmgr == false) {  
  145.             mBatteryPropertiesRegistrar = new BatteryPropertiesRegistrar(this);  
  146.             mBatteryPropertiesRegistrar->publish();  
  147.     }  
  148. }  

在init()里会调用opendir(POWER_SUPPLY_SYSFS_PATH);  

opendir()函数的作用是:打开目录句柄,将返回一组目录流(一组目录字符串),说白了就是目录下的文件名。 

[cpp] view plain copy
  1. #define POWER_SUPPLY_SUBSYSTEM "power_supply"  
  2. #define POWER_SUPPLY_SYSFS_PATH "/sys/class/" POWER_SUPPLY_SUBSYSTEM  
其实 opendir 打开的就是 sys/class/power_supply ,并返回这个路径下的所有文件。文件如下:

比如ac (充电器就叫AC)目录下面都有什么呢:


然后我们看init()代码里面,其实就是把各种路径读取出来,然后把路径赋值。 我们知道了init()干了什么,然后回归到主题:update() 中的属性从哪里来的。

我们只举一个例子。在update()中如何读取的当前电量级别(其他属性获取都是类似的)。在 update()函数中,获取当前电量等级代码如下:

[cpp] view plain copy
  1. if (!mHealthdConfig->batteryCurrentNowPath.isEmpty())  
  2.     props.batteryCurrentNow = getIntField(mHealthdConfig->batteryCurrentNowPath);  
会用getIntField() 去读取当前电量值。而且传入的参数是我们init()时获取的文件路径。 从路径下读取的值是什么呢,大家看下截图就明白了。如下:


看到没,其实就是读取文件里面的值。 100 是我当前手机的电量,我的手机是满电状态。

到此,我们第一个问题:

BatteryMonitor 中 update 方面里面如何获取的属性已经解决。就是根据路径,读取文件获得的。



下面来看第二个问题:

(2)属性变化后调用谁注册的监听。

在BatteryMonitor.cpp中的init()函数末尾 有这么一句:

[cpp] view plain copy
  1. if (nosvcmgr == false) {  
  2.         mBatteryPropertiesRegistrar = new BatteryPropertiesRegistrar(this);  
  3.         mBatteryPropertiesRegistrar->publish();  
  4. }  

而在在BatteryMonitor.cpp中的update()函数末尾 有这么一句:

[cpp] view plain copy
  1. if (mBatteryPropertiesRegistrar != NULL)  
  2.     mBatteryPropertiesRegistrar->notifyListeners(props);  

由上面两个函数中的调用,我们很容易推测出 注册监听跟 BatteryPropertiesRegistrar有关。


我们来分析下 BatteryPropertiesRegistrar 有什么。


BatteryPropertiesRegistrar:

此类的相关文件有4个,具体路径:

\frameworks\native\include\batteryservice\IBatteryPropertiesRegistrar.h

\frameworks\native\services\batteryservice\IBatteryPropertiesRegistrar.cpp

\system\core\healthd\BatteryPropertiesRegistrar.cpp  

\system\core\healthd\BatteryPropertiesRegistrar.h




\frameworks\native\include\batteryservice\IBatteryPropertiesRegistrar.h文件内容:

[cpp] view plain copy
  1. #ifndef ANDROID_IBATTERYPROPERTIESREGISTRAR_H  
  2. #define ANDROID_IBATTERYPROPERTIESREGISTRAR_H  
  3.   
  4. #include <binder/IInterface.h>  
  5. #include <batteryservice/IBatteryPropertiesListener.h>  
  6.   
  7. namespace android {  
  8.   
  9. // must be kept in sync with interface defined in IBatteryPropertiesRegistrar.aidl  
  10. enum {  
  11.     REGISTER_LISTENER = IBinder::FIRST_CALL_TRANSACTION,  
  12.     UNREGISTER_LISTENER,  
  13. };  
  14.   
  15. class IBatteryPropertiesRegistrar : public IInterface {  
  16. public:  
  17.     DECLARE_META_INTERFACE(BatteryPropertiesRegistrar);  
  18.   
  19.     virtual void registerListener(const sp<IBatteryPropertiesListener>& listener) = 0;  
  20.     virtual void unregisterListener(const sp<IBatteryPropertiesListener>& listener) = 0;  
  21. };  
  22.   
  23. class BnBatteryPropertiesRegistrar : public BnInterface<IBatteryPropertiesRegistrar> {  
  24. public:  
  25.     virtual status_t onTransact(uint32_t code, const Parcel& data,  
  26.                                 Parcel* reply, uint32_t flags = 0);  
  27. };  
  28.   
  29. }; // namespace android  
  30.   
  31. #endif // ANDROID_IBATTERYPROPERTIESREGISTRAR_H  

咦,我们可以看到IBatteryPropertiesRegistrar 继承于  IInterface  ,还有一个类BnBatteryPropertiesRegistrar 继承于BnInterface。 而且还调用了
[cpp] view plain copy
  1. DECLARE_META_INTERFACE(BatteryPropertiesRegistrar);  
这个宏定义接口。如果你有看过我上篇 Binder 初解(http://blog.csdn.net/daweibalang717/article/details/41382603 )的话,你可以很轻易的看出这里是Binder的写法。而且明显是个 native service。 对于这四个文件的关系。你读完 Binder 初解后,就一目了然了。


\frameworks\native\services\batteryservice\IBatteryPropertiesRegistrar.cpp的内容

[cpp] view plain copy
  1. #define LOG_TAG "IBatteryPropertiesRegistrar"  
  2. //#define LOG_NDEBUG 0  
  3. #include <utils/Log.h>  
  4.   
  5. #include <batteryservice/IBatteryPropertiesListener.h>  
  6. #include <batteryservice/IBatteryPropertiesRegistrar.h>  
  7. #include <stdint.h>  
  8. #include <sys/types.h>  
  9. #include <binder/Parcel.h>  
  10.   
  11. namespace android {  
  12.   
  13. class BpBatteryPropertiesRegistrar : public BpInterface<IBatteryPropertiesRegistrar> {  
  14. public:  
  15.     BpBatteryPropertiesRegistrar(const sp<IBinder>& impl)  
  16.         : BpInterface<IBatteryPropertiesRegistrar>(impl) {}  
  17.   
  18.         void registerListener(const sp<IBatteryPropertiesListener>& listener) {  
  19.             Parcel data;  
  20.             data.writeInterfaceToken(IBatteryPropertiesRegistrar::getInterfaceDescriptor());  
  21.             data.writeStrongBinder(listener->asBinder());  
  22.             remote()->transact(REGISTER_LISTENER, data, NULL);  
  23.         }  
  24.   
  25.         void unregisterListener(const sp<IBatteryPropertiesListener>& listener) {  
  26.             Parcel data;  
  27.             data.writeInterfaceToken(IBatteryPropertiesRegistrar::getInterfaceDescriptor());  
  28.             data.writeStrongBinder(listener->asBinder());  
  29.             remote()->transact(UNREGISTER_LISTENER, data, NULL);  
  30.         }  
  31. };  
  32.   
  33. IMPLEMENT_META_INTERFACE(BatteryPropertiesRegistrar, "android.os.IBatteryPropertiesRegistrar");  
  34.   
  35. status_t BnBatteryPropertiesRegistrar::onTransact(uint32_t code,  
  36.                                                   const Parcel& data,  
  37.                                                   Parcel* reply,  
  38.                                                   uint32_t flags)  
  39. {  
  40.     switch(code) {  
  41.         case REGISTER_LISTENER: {  
  42.             CHECK_INTERFACE(IBatteryPropertiesRegistrar, data, reply);  
  43.             sp<IBatteryPropertiesListener> listener =  
  44.                 interface_cast<IBatteryPropertiesListener>(data.readStrongBinder());  
  45.             //这个方法并不是上面 BpBatteryPropertiesRegistrar中的registerListener(),他们就不是一个类。这个方法还未实现        
  46.             registerListener(listener);  
  47.             return OK;  
  48.         }  
  49.   
  50.         case UNREGISTER_LISTENER: {  
  51.             CHECK_INTERFACE(IBatteryPropertiesRegistrar, data, reply);  
  52.             sp<IBatteryPropertiesListener> listener =  
  53.                 interface_cast<IBatteryPropertiesListener>(data.readStrongBinder());  
  54.  //这个方法并不是上面 BpBatteryPropertiesRegistrar中的unregisterListener(),他们就不是一个类。这个方法还未实现   
  55.             unregisterListener(listener);  
  56.             return OK;  
  57.         }  
  58.     }  
  59.     return BBinder::onTransact(code, data, reply, flags);  
  60. };  
  61.   
  62. // ----------------------------------------------------------------------------  
  63.   
  64. }; // namespace android  

我们看到 这里是服务端与代理端的实现。 但是服务端 onTransact( )中调用的 registerListener(listener); 与unregisterListener(listener); 是没有实现的。这两个方法是在

\system\core\healthd\BatteryPropertiesRegistrar.cpp  中实现的。

 \system\core\healthd\BatteryPropertiesRegistrar.h 中的内容:

[cpp] view plain copy
  1. #ifndef HEALTHD_BATTERYPROPERTIES_REGISTRAR_H  
  2. #define HEALTHD_BATTERYPROPERTIES_REGISTRAR_H  
  3.   
  4. #include "BatteryMonitor.h"  
  5.   
  6. #include <binder/IBinder.h>  
  7. #include <utils/Mutex.h>  
  8. #include <utils/Vector.h>  
  9. #include <batteryservice/BatteryService.h>  
  10. #include <batteryservice/IBatteryPropertiesListener.h>  
  11. #include <batteryservice/IBatteryPropertiesRegistrar.h>  
  12.   
  13. namespace android {  
  14.   
  15. class BatteryMonitor;  
  16.   
  17. class BatteryPropertiesRegistrar : public BnBatteryPropertiesRegistrar,  
  18.                                    public IBinder::DeathRecipient {  
  19. public:  
  20.     BatteryPropertiesRegistrar(BatteryMonitor* monitor);  
  21.     void publish();  
  22.     void notifyListeners(struct BatteryProperties props);  
  23.   
  24. private:  
  25.     BatteryMonitor* mBatteryMonitor;  
  26.     Mutex mRegistrationLock;  
  27.     Vector<sp<IBatteryPropertiesListener> > mListeners;  
  28.   
  29.     void registerListener(const sp<IBatteryPropertiesListener>& listener);  
  30.     void unregisterListener(const sp<IBatteryPropertiesListener>& listener);  
  31.     void binderDied(const wp<IBinder>& who);  
  32. };  
  33.   
  34. };  // namespace android  
  35.   
  36. #endif // HEALTHD_BATTERYPROPERTIES_REGISTRAR_H  
这个类是对\frameworks\native\include\batteryservice\IBatteryPropertiesRegistrar.h 中的  BnBatteryPropertiesRegistrar的扩展,并继承于public IBinder::DeathRecipient

然后是\system\core\healthd\BatteryPropertiesRegistrar.cpp  的内容:

[cpp] view plain copy
  1. #include "BatteryPropertiesRegistrar.h"  
  2. #include <batteryservice/BatteryService.h>  
  3. #include <batteryservice/IBatteryPropertiesListener.h>  
  4. #include <batteryservice/IBatteryPropertiesRegistrar.h>  
  5. #include <binder/IServiceManager.h>  
  6. #include <utils/Errors.h>  
  7. #include <utils/Mutex.h>  
  8. #include <utils/String16.h>  
  9.   
  10. namespace android {  
  11.   
  12. BatteryPropertiesRegistrar::BatteryPropertiesRegistrar(BatteryMonitor* monitor) {  
  13.     mBatteryMonitor = monitor;  
  14. }  
  15.   
  16. void BatteryPropertiesRegistrar::publish() {  
  17.     defaultServiceManager()->addService(String16("batterypropreg"), this);  
  18. }  
  19.   
  20. void BatteryPropertiesRegistrar::notifyListeners(struct BatteryProperties props) {  
  21.     Mutex::Autolock _l(mRegistrationLock);  
  22.     for (size_t i = 0; i < mListeners.size(); i++) {  
  23.         mListeners[i]->batteryPropertiesChanged(props);  
  24.     }  
  25. }  
  26.   
  27. void BatteryPropertiesRegistrar::registerListener(const sp<IBatteryPropertiesListener>& listener) {  
  28.     {  
  29.         Mutex::Autolock _l(mRegistrationLock);  
  30.         // check whether this is a duplicate  
  31.         for (size_t i = 0; i < mListeners.size(); i++) {  
  32.             if (mListeners[i]->asBinder() == listener->asBinder()) {  
  33.                 return;  
  34.             }  
  35.         }  
  36.   
  37.         mListeners.add(listener);  
  38.         listener->asBinder()->linkToDeath(this);  
  39.     }  
  40.     mBatteryMonitor->update();  
  41. }  
  42.   
  43. void BatteryPropertiesRegistrar::unregisterListener(const sp<IBatteryPropertiesListener>& listener) {  
  44.     Mutex::Autolock _l(mRegistrationLock);  
  45.     for (size_t i = 0; i < mListeners.size(); i++) {  
  46.         if (mListeners[i]->asBinder() == listener->asBinder()) {  
  47.             mListeners[i]->asBinder()->unlinkToDeath(this);  
  48.             mListeners.removeAt(i);  
  49.             break;  
  50.         }  
  51.     }  
  52. }  
  53.   
  54. void BatteryPropertiesRegistrar::binderDied(const wp<IBinder>& who) {  
  55.     Mutex::Autolock _l(mRegistrationLock);  
  56.   
  57.     for (size_t i = 0; i < mListeners.size(); i++) {  
  58.         if (mListeners[i]->asBinder() == who) {  
  59.             mListeners.removeAt(i);  
  60.             break;  
  61.         }  
  62.     }  
  63. }  
  64.   
  65. }  // namespace android  

这个类是对 \system\core\healthd\BatteryPropertiesRegistrar.h 的实现。  真正 调用registerListener(listener); 与unregisterListener(listener); 的地方。


这个BatteryPropertiesRegistrar:其实就是注册监听的类,而且监听的接口叫IBatteryPropertiesListener。


IBatteryPropertiesListener :

文件路径:

\frameworks\native\include\batteryservice\IBatteryPropertiesListener.h

\frameworks\native\services\batteryservice\IBatteryPropertiesListener.cpp

文件内容:

IBatteryPropertiesListener.h 

[cpp] view plain copy
  1. #ifndef ANDROID_IBATTERYPROPERTIESLISTENER_H  
  2. #define ANDROID_IBATTERYPROPERTIESLISTENER_H  
  3.   
  4. #include <binder/IBinder.h>  
  5. #include <binder/IInterface.h>  
  6.   
  7. #include <batteryservice/BatteryService.h>  
  8.   
  9. namespace android {  
  10.   
  11. // must be kept in sync with interface defined in IBatteryPropertiesListener.aidl  
  12. enum {  
  13.         TRANSACT_BATTERYPROPERTIESCHANGED = IBinder::FIRST_CALL_TRANSACTION,  
  14. };  
  15.   
  16. // ----------------------------------------------------------------------------  
  17.   
  18. class IBatteryPropertiesListener : public IInterface {  
  19. public:  
  20.     DECLARE_META_INTERFACE(BatteryPropertiesListener);  
  21.   
  22.     virtual void batteryPropertiesChanged(struct BatteryProperties props) = 0;  
  23. };  
  24.   
  25. // ----------------------------------------------------------------------------  
  26.   
  27. }; // namespace android  
  28.   
  29. #endif   

咦,这个依然用的是Binder 机制。这里进行代理与服务端的声明。


IBatteryPropertiesListener.cpp:

[cpp] view plain copy
  1. #include <stdint.h>  
  2. #include <sys/types.h>  
  3. #include <batteryservice/IBatteryPropertiesListener.h>  
  4. #include <binder/Parcel.h>  
  5.   
  6. namespace android {  
  7.   
  8. class BpBatteryPropertiesListener : public BpInterface<IBatteryPropertiesListener>  
  9. {  
  10. public:  
  11.     BpBatteryPropertiesListener(const sp<IBinder>& impl)  
  12.         : BpInterface<IBatteryPropertiesListener>(impl)  
  13.     {  
  14.     }  
  15.   
  16.     void batteryPropertiesChanged(struct BatteryProperties props)  
  17.     {  
  18.         Parcel data, reply;  
  19.         data.writeInterfaceToken(IBatteryPropertiesListener::getInterfaceDescriptor());  
  20.         data.writeInt32(1);  
  21.         props.writeToParcel(&data);  
  22.         status_t err = remote()->transact(TRANSACT_BATTERYPROPERTIESCHANGED, data, &reply, IBinder::FLAG_ONEWAY);  
  23.     }  
  24. };  
  25.   
  26. IMPLEMENT_META_INTERFACE(BatteryPropertiesListener, "android.os.IBatteryPropertiesListener");  
  27.   
  28. // ----------------------------------------------------------------------------  
  29.   
  30. }; // namespace android  

这里进行代理的实现。 但是并没有对服务端进行实现。这个应该是在BatteryService.java 中的:

[java] view plain copy
  1. private final class BatteryListener extends IBatteryPropertiesListener.Stub {  
  2.     public void batteryPropertiesChanged(BatteryProperties props) {  
  3.         BatteryService.this.update(props);  
  4.    }  

中进行实现的。


到这里我们对于第二个问题:属性变化后调用谁注册的监听。 还没有解决, 只是了解下注册类与注册接口。那么真正注册在那呢? 是在\frameworks\base\services\java\com\android\server\BatteryService.java中:

这个BatteryService 继承于Binder 类,在他的构造函数中,是这么注册的:

[java] view plain copy
  1. mBatteryPropertiesListener = new BatteryListener();  
  2.   
  3. IBinder b = ServiceManager.getService("batterypropreg");  
  4. mBatteryPropertiesRegistrar = IBatteryPropertiesRegistrar.Stub.asInterface(b);  
  5.   
  6. try {  
  7.     mBatteryPropertiesRegistrar.registerListener(mBatteryPropertiesListener);  
  8. catch (RemoteException e) {  
  9.     // Should never happen.  
  10. }  

大家不禁要问了。这里是Java 代码呀,怎么掉的C++的呢,这就是Binder机制了。 而且上面所述的 IBatteryPropertiesListener  、IBatteryPropertiesRegistrar 在Java层都有对应的aidl 文件。目录:

\frameworks\base\core\java\android\os\IBatteryPropertiesListener.aidl  

[java] view plain copy
  1. package android.os;  
  2.   
  3. import android.os.BatteryProperties;  
  4.   
  5. /** 
  6.  * {@hide} 
  7.  */  
  8.   
  9. oneway interface IBatteryPropertiesListener {  
  10.     void batteryPropertiesChanged(in BatteryProperties props);  
  11. }  


\frameworks\base\core\java\android\os\IBatteryPropertiesRegistrar.aidl


[java] view plain copy
  1. package android.os;  
  2.   
  3. import android.os.IBatteryPropertiesListener;  
  4.   
  5. /** 
  6.  * {@hide} 
  7.  */  
  8.   
  9. interface IBatteryPropertiesRegistrar {  
  10.     void registerListener(IBatteryPropertiesListener listener);  
  11.     void unregisterListener(IBatteryPropertiesListener listener);  
  12. }  

当编译的时候会自动生成 IBatteryPropertiesListener.java  与 IBatteryPropertiesRegistrar.java 文件。这个我就不多赘述了。


好吧,我们总结下第二个问题:


1、在BatteryService.java 实现回调函数中的接口,并注册到BatteryPropertiesRegistrar 中。 

2、Healthd 中监控PMU 驱动,事件变更,调用BatteryMonitor中的update()函数中回调BatteryPropertiesRegistrar注册的接口,调用的就是BatteryService.java 实现的接口


阅读全文
0 0
原创粉丝点击