android TP实现距离感应

调用过程中涉及到的文件

Driver:           ft5x0x.cà  

HAL:             SensorGTP.cpp  à sensors.cpp  à  SensorDevice.cpp à

Framework:  SensorService.cppàSensorManager.cppà  android_hardware_SensorManager.cpp  à 

SensorManager.java à PowerManagerService.java

 

本文分几个部分:

1、驱动层:tp驱动中实现感应开关

2、HAL层:打开/dev/proximity字符设备,并实现感应开关操作,相当于linux应用程序开发层。

3、framework层:涉及到SensorManager.java与PowerManagerService.java两个文件,主要是负责背光亮灭与sensor开启关闭。

4、app层:主要是PhoneApp接通电话开关感应。


关于android分层架构都应该知道:如下图


第一部分:TP驱动实现距离感应开关实现代码

1、  首先在probe函数中增加一段程序,组要是注册一个混杂字符设备

  1. #include <linux/miscdevice.h>  
  2. #include <linux/wakelock.h>  
  3. //#include <linux/eventstore.h>  
  4. #include <linux/fs.h>  
  5. //#include <linux/miscdevice.h>  
  6. #include <linux/ioctl.h>  
  7.   
  8. #define GTP_PROXIMITY     1 //宏开关  
  9. static int gtp_proximity_start = 0; /* 0 is stop, 1 is start */  
  10.   
  11. #define GTP_IOCTL_MAGIC         0x5D  
  12. #define GTP_IOCTL_PROX_ON       _IO(GTP_IOCTL_MAGIC, 7)  
  13. #define GTP_IOCTL_PROX_OFF      _IO(GTP_IOCTL_MAGIC, 8)  
  14. #define FT5X0X_SENSOR_NAME      "gtp_proximity"    //新增字符设备名称  
  15.   
  16. #if GTP_PROXIMITY     
  17.     err = misc_register(>p_proximity_misc);  
  18.     if (err < 0)  
  19.     {  
  20.         pr_err("%s: could not register misc device\n", __func__);  
  21.     }  
  22. #endif  
  23.   
  24. static struct miscdevice gtp_proximity_misc = {  
  25.         .minor = MISC_DYNAMIC_MINOR,  
  26.         .name = FT5X0X_SENSOR_NAME,       
  27.         .fops = >p_proximity_fops,  
  28. };  
  29.   
  30.   
  31.   
  32. static const struct file_operations gtp_proximity_fops = {  
  33.         .owner = THIS_MODULE,  
  34.         .open = <span style="font-family: Arial, Helvetica, sans-serif;">FT5X0X</span><span style="font-family: Arial, Helvetica, sans-serif;">_proximity_open,</span>  
  35.         .release = NULL,//_proximity_release,  
  36.         .ioctl = FT5X0X_proximity_ioctl,  
  37.         /*.ioctl = FT5X0x_proximity_ioctl,unlocked_ioctl*/  
  38. };  
  39.   
  40. static int ft5x0x_proximity_open(struct inode *inode, struct file *file)  
  41. {  
  42.     int err;  
  43.     err = nonseekable_open(inode, file);  
  44.     if (err < 0)  
  45.         return err;  
  46.   
  47.     file->private_data = i2c_get_clientdata(this_client);  
  48.     printk("ft5x0x_proximity_open-file->private_data=%x\r\n",file->private_data);  
  49.     return 0;  
  50.   
  51. }  
  52. HAL层会根据幻数调用ft5x0x_proximity_ioctl中是否打开距离感应。  
  53. static int ft5x0x_proximity_ioctl(struct inode *inode, struct file *file,unsigned int cmd, unsigned long arg)  
  54. {  
  55.     //printk("ft5x0x_proximity_ioctl");  
  56.     switch (cmd) {  
  57.     case GTP_IOCTL_PROX_ON:  
  58.         //gtp_proximity_open();  
  59.         ft5x0x_proximity_set_enable(1);  
  60.         gtp_proximity_start = 1;    /* 0 is stop, 1 is start */  
  61.         printk("ft5x0x_proximity_ioctl--on\r\n");  
  62.         break;  
  63.     case GTP_IOCTL_PROX_OFF:  
  64.         //gtp_proximity_release();  
  65.         ft5x0x_proximity_set_enable(0);  
  66.         gtp_proximity_start = 0;  
  67.         printk("ft5x0x_proximity_ioctl--off\r\n");  
  68.         break;  
  69.     default:  
  70.         //pr_err("%s: invalid cmd %d\n", __func__, _IOC_NR(cmd));  
  71.         printk("ft5x0x_proximity_ioctl--error\r\n");  
  72.         return -EINVAL;  
  73.     }  
  74.     return 0;  
  75. }  

关于如何判断是否接近,可以向FAE咨询,让他们提供说明文档,改哪些寄存器的值实现。

 

ft5x0x 类型的TP实现:Enable 脸部接近感应功能,拨出电话并且已经开始连线时或者是来电接通电话时启

动此项功能,手机启动触摸IC进入大面积感应发出的I2C指令如下:Write(0xB0,0x01)

操作说明:主控向TP的0xB0 单元写0x01 数据,写入成功后TP即进入脸部接近感应功能;

  1. static void ft5x0x_proximity_set_enable(int enable)  
  2. {  
  3.     if(enable == 1)  
  4.     {  
  5.         gtp_proximity_start = 1;  
  6.     }else{  
  7.         gtp_proximity_start = 0;  
  8.     }  
  9.   
  10.     ft5x0x_write_reg(0xB0, enable);  
  11. }  
  12.   
  13. 在probe函数中  
  14. INIT_WORK(&ft5x0x_ts->pen_event_work, ft5x0x_ts_pen_irq_work);  
  15.   
  16. static void ft5x0x_ts_pen_irq_work(struct work_struct *work)  
  17. {  
  18. #if 1  
  19.     int ret = -1;  
  20. //  printk("==work 1=\n");  
  21. #ifdef GTP_PROXIMITY  
  22.     printk("_ts_pen_irq_work---\r\n");  
  23.     ft5x0x_ts_proximity_work();  
  24. #endif  
  25.     ret = ft5x0x_read_data();     
  26.     if (ret == 0) {   
  27.         ft5x0x_report_value();  
  28.     }  
  29. //  else printk("data package read error\n");  
  30. //  printk("==work 2=\n");  
  31. //      msleep(1);  
  32. #endif  
  33.     enable_irq(this_client->irq);  
  34.   
  35. }  

2,TP当在手机“Enable脸部接近接触感应”模式时:

2.1 听筒端靠近人体距离小于8mm时(具体距离以实测为准),主机端会收到如下数据包:

I2C start +I2C地址+0x00+0xc0+其它相关数据+ I2Cstop(0xc0 是以手势码的形式发出的)

2.2 听筒端移开人体超过8mm时(具体距离以实测为准),主机端会收到如下数据包:

I2C start + I2C地址+0x00+0xe0+其它相关数据+ I2Cstop(0xe0 是以手势码的形式发出的)

3,Disable脸部接近感应(预设) 结束通话时退出大面积感应功能。手机发出的I2C数据:

Write(0xb0,0x00)

操作说明:主机向从机0xb0 地址写0x00数据,写入成功后退出大面积感应功能。

mso- Wat����ily:宋体;mso-fareast-theme-font:minor-fareast;mso-hansi-font-family:Calibri;mso-hansi-theme-font:minor-latin'>开启关闭。

4、app层:主要是PhoneApp接通电话开关感应。

  1. static void ft5x0x_ts_proximity_work(void)  
  2. {  
  3.     static int value_temp = 0;  
  4.     int value;  
  5.     char buffer[30]={0};  
  6.   
  7.     struct ft5x0x_ts_data *data = i2c_get_clientdata(this_client);  
  8.   
  9.     i2c_smbus_read_i2c_block_data(this_client, 0x00, 8, &(buffer[0]));  
  10.     printk("-ft5x0x_ts_proximity_work-buffer[1] =-%x\n", buffer[1]);  
  11.     if(gtp_proximity_start == 1)  
  12.     {  
  13.         if (buffer[1]==0xC0)  
  14.         {  
  15.             input_report_abs(data->input_dev, ABS_DISTANCE, 0);  //report far  
  16.             //input_sync(data->input_dev);  
  17.             //value_temp = value;  
  18.             printk("-ft5x0x_ts_proximity_work--near\r\n");  
  19.         }  
  20.         else if(buffer[1]==0xE0)  
  21.         {  
  22.             input_report_abs(data->input_dev, ABS_DISTANCE, 1);  //report far  
  23.             printk("-ft5x0x_ts_proximity_work--far\r\n");  
  24.         }  
  25.     }}  
  26.   
  27.   
  28. 在suspend与resume不走tp正常流程。  
  29. static void ft5x0x_ts_suspend(struct early_suspend *handler)  
  30. {  
  31.     #if GTP_PROXIMITY  
  32.         if (gtp_proximity_start == 1)  
  33.         return;  
  34. #endif  
  35. … …  
  36. }  
  37.   
  38.   
  39. static void ft5x0x_ts_resume(struct early_suspend *handler)  
  40. {     
  41.     printk("==%s==\n", __FUNCTION__);  
  42. #if GTP_PROXIMITY  
  43.     if (gtp_proximity_start == 1)  
  44.     return;  
  45. #endif  
  46.  … …  
  47. }  

TP驱动层距离感应已经实现,下一步就是HAL层调用驱动了。

 

 

第二部:HAL层实现调用驱动程序,向上层提供接口。

  1. SensorGTP.cpp  
  2.   
  3. #include <fcntl.h>  
  4. #include <errno.h>  
  5. #include <math.h>  
  6. #include <poll.h>  
  7. #include <unistd.h>  
  8. #include <dirent.h>  
  9. #include <sys/select.h>  
  10.   
  11. #include <cutils/log.h>  
  12.   
  13. #include "SensorGTP.h"  
  14. #include "sensors.h"  
  15.   
  16. #define ft5x0x_DEVICE_NAME                          "/dev/gtp_proximity"   //设备节点  
  17. #define GTP_IOCTL_MAGIC                         0x5D  
  18. #define GTP_IOCTL_GET_PFLAG                     _IOR(GTP_IOCTL_MAGIC, 1, int)  
  19. #define GTP_IOCTL_GET_LFLAG                     _IOR(GTP_IOCTL_MAGIC, 2, int)  
  20. #define GTP_IOCTL_SET_PFLAG                     _IOW(GTP_IOCTL_MAGIC, 3, int)  
  21. #define GTP_IOCTL_SET_LFLAG                     _IOW(GTP_IOCTL_MAGIC, 4, int)  
  22. #define GTP_IOCTL_GET_DATA                      _IOW(GTP_IOCTL_MAGIC, 5, unsigned char)  
  23. #define GTP_IOCTL_PROX_ON                                   _IO(GTP_IOCTL_MAGIC, 7)  
  24. #define GTP_IOCTL_PROX_OFF                                _IO(GTP_IOCTL_MAGIC, 8)  
  25.   
  26. /*****************************************************************************/  
  27. SensorGTP::SensorGTP()  
  28.   : SensorBase(ft5x0x_DEVICE_NAME, "ft5x0x_ts"),  
  29.     mEnabled(0),  
  30.     mPendingMask(0),  
  31.     mInputReader(32),  
  32.     mHasPendingEvent(false)  
  33. {  
  34.     memset(mPendingEvents, 0, sizeof(mPendingEvents));  
  35.       
  36.     mPendingEvents[Proximity].version = sizeof(sensors_event_t);  
  37.     mPendingEvents[Proximity].sensor = ID_P;  
  38.     mPendingEvents[Proximity].type = SENSOR_TYPE_PROXIMITY;  
  39.   
  40.     for (int i=0 ; i<numSensors ; i++)  
  41.         mDelays[i] = 200000000; // 200 ms by default      
  42. }  
  43.   
  44. SensorGTP::~SensorGTP()  
  45. {  
  46. }  
  47.   
  48. bool SensorGTP::hasPendingEvents() const  
  49. {  
  50.     return mHasPendingEvent;  
  51. }  
  52.   
  53. int SensorGTP::setDelay(int32_t handle, int64_t ns)  
  54. {  
  55.     return 0;  
  56. }  
  57.   
  58. int SensorGTP::setEnable(int32_t handle, int en)  
  59. {  
  60.     int what = -1;  
  61.     int cmd;  
  62.     int err = 0;  
  63.     int newState = en ? 1 : 0;  
  64.       
  65.     switch (handle) {  
  66.         case ID_P: what = Proximity; break;  
  67.     }  
  68.       
  69.     if (uint32_t(what) >= numSensors)  
  70.         return -EINVAL;  
  71.   
  72.     if (!mEnabled)  
  73.         open_device();  
  74.   
  75.     switch (what)  
  76.     {  
  77.         case Proximity: //将调用驱动层的ioctol实现开关距离感应  
  78.         if (newState)                     
  79.         {  
  80.             cmd = GTP_IOCTL_PROX_ON;  
  81.         }  
  82.         else      
  83.         {  
  84.             cmd = GTP_IOCTL_PROX_OFF;  
  85.         }                                 
  86.         break;  
  87.     }  
  88.   
  89.     int flags = newState;  
  90.   
  91.     err = ioctl(dev_fd, cmd, &flags);  
  92.   
  93.     LOGD("ioctl,err=%d\n",err);  
  94.     err = err < 0 ? -errno : 0;  
  95.   
  96.     LOGD("SensorGTP::enable what=%d; flags=%d; err=%d\n", what, flags, err);  
  97.   
  98.     LOGE_IF(err, "ECS_IOCTL_APP_SET_XXX failed (%s)", strerror(-err));  
  99.   
  100.     if (!err)  
  101.     {  
  102.         mEnabled &= ~(1 << what);  
  103.         mEnabled |= (uint32_t(flags) << what);  
  104.     }  
  105.   
  106.     LOGD("SensorGTP::mEnabled=0x%x\n", mEnabled);  
  107.   
  108.     if (!mEnabled)  
  109.         close_device();  
  110.   
  111.     return err;  
  112. }  
  113.   
  114. int SensorGTP::getEnable(int32_t handle)  
  115. {  
  116.     int enable=0;  
  117.     int what = -1;  
  118.     switch (handle) {  
  119.         case ID_P: what = Proximity; break;  
  120.     }  
  121.     if (uint32_t(what) >= numSensors)  
  122.         return -EINVAL;  
  123.   
  124.     enable = mEnabled & (1 << what);  
  125.   
  126.     if(enable > 0)  
  127.         enable = 1;  
  128.   
  129.     LOGD("SensorGTP::mEnabled=0x%x; enable=%d\n", mEnabled, enable);  
  130.   
  131.     return enable;  
  132. }  
  133.   
  134. int SensorGTP::readEvents(sensors_event_t* data, int count)  
  135. {  
  136.     if (count < 1)  
  137.         return -EINVAL;  
  138.   
  139.     ssize_t n = mInputReader.fill(data_fd);  
  140.     if (n < 0)  
  141.         return n;  
  142.   
  143.     int numEventReceived = 0;  
  144.     input_event const* event;  
  145.   
  146.     while (count && mInputReader.readEvent(&event)) {  
  147.         int type = event->type;  
  148.         if (type == EV_ABS) {  
  149.             processEvent(event->code, event->value);  
  150.             mInputReader.next();  
  151.         } else if (type == EV_SYN) {  
  152.             int64_t time = timevalToNano(event->time);  
  153.             for (int j=0 ; count && mPendingMask && j<numSensors ; j++) {  
  154.                 if (mPendingMask & (1<<j)) {  
  155.                     mPendingMask &= ~(1<<j);  
  156.                     mPendingEvents[j].timestamp = time;  
  157.                     if (mEnabled & (1<<j)) {  
  158.                         *data++ = mPendingEvents[j];  
  159.                         count--;  
  160.                         numEventReceived++;  
  161.                     }  
  162.                 }  
  163.             }  
  164.             if (!mPendingMask) {  
  165.                 mInputReader.next();  
  166.             }  
  167.         } else {  
  168.             LOGE("Apds9900Sensor: unknown event (type=%d, code=%d)",  
  169.                     type, event->code);  
  170.             mInputReader.next();  
  171.         }  
  172.     }  
  173.   
  174.     return numEventReceived;  
  175. }  
  176.   
  177. void SensorGTP::processEvent(int code, int value)  
  178. {  
  179.     switch (code) {  
  180.         case EVENT_TYPE_PROXIMITY:  
  181.             mPendingMask |= 1<<Proximity;  
  182.             mPendingEvents[Proximity].distance = value;  
  183.             LOGD("SensorGTP: mPendingEvents[Proximity].distance = %f",mPendingEvents[Proximity].distance);  
  184.             break;          
  185.          default:  
  186.             LOGD("SensorGTP: default value = %d",value);  
  187.             break;  
  188.     }  
  189. }  
  190. SensorGTP.h  
  191. #ifndef ANDROID_GTP_SENSOR_H  
  192. #define ANDROID_GTP_SENSOR_H  
  193.   
  194. #include <stdint.h>  
  195. #include <errno.h>  
  196. #include <sys/cdefs.h>  
  197. #include <sys/types.h>  
  198.   
  199.   
  200. #include "sensors.h"  
  201. #include "SensorBase.h"  
  202. #include "InputEventReader.h"  
  203.   
  204. /*****************************************************************************/  
  205.   
  206. struct input_event;  
  207.   
  208. class SensorGTP : public SensorBase  
  209. {  
  210. public:  
  211.     SensorGTP();  
  212.     virtual ~SensorGTP();  
  213.   
  214.     enum  
  215.     {  
  216.         Light   = 0,  
  217.         Proximity   = 1,  
  218.         numSensors  
  219.     };  
  220.   
  221.     virtual int setDelay(int32_t handle, int64_t ns);  
  222.     virtual int setEnable(int32_t handle, int enabled);  
  223.     virtual bool hasPendingEvents() const;  
  224.     virtual int readEvents(sensors_event_t* data, int count);  
  225.       virtual int getEnable(int32_t handle);  
  226.     void processEvent(int code, int value);  
  227. private:  
  228.     int update_delay();  
  229.     uint32_t mEnabled;  
  230.     bool mHasPendingEvent;  
  231.     uint32_t mPendingMask;  
  232.     InputEventCircularReader mInputReader;  
  233.     sensors_event_t mPendingEvents[numSensors];  
  234.     uint64_t mDelays[numSensors];  
  235. };  
  236.   
  237. /*****************************************************************************/  
  238.   
  239. #endif  // ANDROID_GT8XX_SENSOR_H  

此函数初始化将在sensors.cpp函数中实现,关于此阶段的说明,先来看下SensorDevice.cpp文件中的函数,此文件中实现了SensorDevice的初始化并且通过

hw_get_module(SENSORS_HARDWARE_MODULE_ID,(hw_module_tconst**)&mSensorModule);获取sensor模块,将sensor打开。

  1. SensorDevice::SensorDevice()  
  2.     :  mSensorDevice(0),  
  3.        mSensorModule(0)  
  4. {  
  5.     status_t err = hw_get_module(SENSORS_HARDWARE_MODULE_ID,  
  6.             (hw_module_t const**)&mSensorModule);  
  7.   
  8.     LOGE_IF(err, "couldn't load %s module (%s)",  
  9.             SENSORS_HARDWARE_MODULE_ID, strerror(-err));  
  10.   
  11.     if (mSensorModule) {  
  12.         err = sensors_open(&mSensorModule->common, &mSensorDevice);  
  13. //1、此函数将会调用sensors.cpp文件中的open_sensors函数。  
  14.         LOGE_IF(err, "couldn't open device for module %s (%s)",  
  15.                 SENSORS_HARDWARE_MODULE_ID, strerror(-err));  
  16.   
  17.         if (mSensorDevice) {  
  18.             sensor_t const* list;  
  19. //2、此函数将调用sensors.cpp中的sensors__get_sensors_list函数。   
  20.             ssize_t count = mSensorModule->get_sensors_list(mSensorModule, &list);  
  21.             mActivationCount.setCapacity(count);  
  22.             Info model;  
  23.             for (size_t i=0 ; i<size_t(count) ; i++) {  
  24.                 mActivationCount.add(list[i].handle, model);  
  25.                 mSensorDevice->activate(mSensorDevice, list[i].handle, 0);//3、  
  26.             }  
  27.         }  
  28.     }  
  29. }  
  30. 在上面一个函数标志1中函数将会调用:  
  31. struct sensors_module_t HAL_MODULE_INFO_SYM = {  
  32.         common: {  
  33.                 tag: HARDWARE_MODULE_TAG,  
  34.                 version_major: 1,  
  35.                 version_minor: 0,  
  36.                 id: SENSORS_HARDWARE_MODULE_ID,  
  37.                 name: "AKM Sensor module",  
  38.                 author: "Asahi Kasei Microdevices",  
  39.                 methods: &sensors_module_methods,  
  40.         },  
  41.         get_sensors_list: sensors__get_sensors_list,  
  42. };  
  43.   
  44. static struct hw_module_methods_t sensors_module_methods = {  
  45.         open: open_sensors  
  46. };  
  47.   
  48. static int open_sensors(const struct hw_module_t* module, const char* id,  
  49.                         struct hw_device_t** device)  
  50. {  
  51.         int status = -EINVAL;  
  52.         //new 一个sensors_poll_context_t并初始化  
  53.         sensors_poll_context_t *dev = new sensors_poll_context_t();  
  54.   
  55.         memset(&dev->device, 0, sizeof(sensors_poll_device_t));  
  56.   
  57.         dev->device.common.tag = HARDWARE_DEVICE_TAG;  
  58.         dev->device.common.version  = 0;  
  59.         dev->device.common.module   = const_cast<hw_module_t*>(module);  
  60.         dev->device.common.close    = poll__close;  
  61.         dev->device.activate        = poll__activate;  
  62.         dev->device.setDelay        = poll__setDelay;  
  63.         dev->device.poll            = poll__poll;  
  64.   
  65.         *device = &dev->device.common;  
  66.         status = 0;  
  67.   
  68.         return status;  
  69. }  
  70. 在sensors_poll_context_t *dev = new sensors_poll_context_t();函数中  
  71.   
  72.   
  73.   
  74.   
  75. sensors_poll_context_t::sensors_poll_context_t()  
  76. {  
  77.     //new 并初始化SensorGTP()  
  78.     mSensors[gtp_proximity] = new SensorGTP();  
  79.     mPollFds[gtp_proximity].fd = mSensors[gtp_proximity]->getFd();  
  80.     mPollFds[gtp_proximity].events = POLLIN;  
  81.     mPollFds[gtp_proximity].revents = 0;  
  82.   
  83.     int wakeFds[2];  
  84.     int result = pipe(wakeFds);  
  85.     LOGE_IF(result<0, "error creating wake pipe (%s)", strerror(errno));  
  86.     fcntl(wakeFds[0], F_SETFL, O_NONBLOCK);  
  87.     fcntl(wakeFds[1], F_SETFL, O_NONBLOCK);  
  88.     mWritePipeFd = wakeFds[1];  
  89.   
  90.     mPollFds[wake].fd = wakeFds[0];  
  91.     mPollFds[wake].events = POLLIN;  
  92.     mPollFds[wake].revents = 0;  
  93. }  
  94.   
  95.   
  96.   
  97. 3、在上一个函数中mSensorDevice->activate(mSensorDevice, list[i].handle, 0);  
  98. 此函数调用了:  
  99. int sensors_poll_context_t::activate(int handle, int enabled) {  
  100. /*将根据handle返回哪个sensor。Handle有ID_A:acc;ID_M:ID_O:mag;ID_L:ID_P: 
  101. gtp_proximity; al3006_pls;*/  
  102.     int drv = handleToDriver(handle);   
  103.     int err;  
  104.     err = mSensors[drv]->setEnable(handle, enabled);  
  105.     if (enabled && !err) {  
  106.         const char wakeMessage(WAKE_MESSAGE);  
  107.         int result = write(mWritePipeFd, &wakeMessage, 1);  
  108.         LOGE_IF(result<0, "error sending wake message (%s)", strerror(errno));  
  109.     }  
  110.     return err;  
  111. }  
  112.   
  113. err = mSensors[drv]->setEnable(handle, enabled);  
  114. 将调用int SensorGTP::setEnable(int32_t handle, int en)使能距离感应。  
  115.   
  116.   
  117.   
  118. 现在分析第二部分中的第2步:  
  119. SensorService.cppSensorManager.cpp  android_hardware_SensorManager.cpp  
  120. —> SensorManager.java   
  121.   
  122. 在SensorService.cpp中初始化SensorDevice是在如下函数中:  
  123. void SensorService::onFirstRef()  
  124. {  
  125.     LOGD("nuSensorService starting...");  
  126.   
  127.     SensorDevice& dev(SensorDevice::getInstance());  
  128.   
  129.   
  130. 在SensorManager.cpp中  
  131. SensorManager::SensorManager()  
  132.     : mSensorList(0)  
  133. {  
  134.     //获取sensorservice服务  
  135.     const String16 name("sensorservice");  
  136.     while (getService(name, &mSensorServer) != NO_ERROR) {  
  137.         usleep(250000);  
  138.     }  
  139.     //获取sensor项  
  140.     mSensors = mSensorServer->getSensorList();  
  141.     size_t count = mSensors.size();  
  142.     mSensorList = (Sensor const**)malloc(count * sizeof(Sensor*));  
  143.     for (size_t i=0 ; i<count ; i++) {  
  144.         mSensorList[i] = mSensors.array() + i;  
  145.     }  
  146. }  
  147.   
  148. JNI层android_hardware_SensorManager.cpp  
  149. framework层SensorManager.java  
  150.   
  151. 在PowerManagerService.java中  
  152.   
  153. public void acquireWakeLockLocked(int flags, IBinder lock, int uid, int pid, String tag,WorkSource ws) {  
  154. … …  
  155.         if (isScreenLock(flags)) {  
  156.             // if this causes a wakeup, we reactivate all of the locks and  
  157.             // set it to whatever they want.  otherwise, we modulate that  
  158.             // by the current state so we never turn it more on than  
  159.             // it already is.  
  160.             if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {  
  161.                 mProximityWakeLockCount++;  
  162.                 if (mProximityWakeLockCount == 1) {  
  163.                     enableProximityLockLocked();//打开距离感应函数  
  164.                 }  
  165.             } else {  
  166.                 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {  
  167.                     int oldWakeLockState = mWakeLockState;  
  168.                     mWakeLockState = mLocks.reactivateScreenLocksLocked();  
  169.   
  170.                     // Disable proximity sensor if if user presses power key while we are in the  
  171.                     // "waiting for proximity sensor to go negative" state.  
  172.                     if ((mWakeLockState & SCREEN_ON_BIT) != 0  
  173.                             && mProximitySensorActive && mProximityWakeLockCount == 0) {  
  174.                         mProximitySensorActive = false;  
  175.                     }  
  176.   
  177.                     if (mSpew) {  
  178.                         Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)  
  179.                                 + " mWakeLockState=0x"  
  180.                                 + Integer.toHexString(mWakeLockState)  
  181.                                 + " previous wakeLockState=0x"  
  182.                                 + Integer.toHexString(oldWakeLockState));  
  183.                     }  
  184.                 } else {  
  185.                     if (mSpew) {  
  186.                         Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)  
  187.                                 + " mLocks.gatherState()=0x"  
  188.                                 + Integer.toHexString(mLocks.gatherState())  
  189.                                 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));  
  190.                     }  
  191.                     mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();  
  192.                 }  
  193.                 setPowerState(mWakeLockState | mUserState);  
  194.             }  
  195.         }  
  196.         else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {  
  197.             if (newlock) {  
  198.                 mPartialCount++;  
  199.                 if (mPartialCount == 1) {  
  200.                     if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);  
  201.                 }  
  202.             }  
  203.             Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);  
  204.         }  
  205.   
  206.   
  207. 在函数中  
  208.     private void enableProximityLockLocked() {  
  209.         if (mDebugProximitySensor) {  
  210.             Slog.d(TAG, "enableProximityLockLocked");  
  211.         }  
  212.         if (!mProximitySensorEnabled) {  
  213.             // clear calling identity so sensor manager battery stats are accurate  
  214.             long identity = Binder.clearCallingIdentity();  
  215.             try {  
  216.             //注册监听器mProximityListener  
  217.                 mSensorManager.registerListener(mProximityListener, mProximitySensor,  
  218.                         SensorManager.SENSOR_DELAY_NORMAL);  
  219.                 mProximitySensorEnabled = true;  
  220.             } finally {  
  221.                 Binder.restoreCallingIdentity(identity);  
  222.             }  
  223.         }  
  224.     }  
  225.   
  226. 在函数中  
  227.     SensorEventListener mProximityListener = new SensorEventListener() {  
  228.         public void onSensorChanged(SensorEvent event) {  
  229.             long milliseconds = SystemClock.elapsedRealtime();  
  230.             synchronized (mLocks) {  
  231.                 float distance = event.values[0];  
  232.                 long timeSinceLastEvent = milliseconds - mLastProximityEventTime;  
  233.                 mLastProximityEventTime = milliseconds;  
  234.                 mHandler.removeCallbacks(mProximityTask);  
  235.                 boolean proximityTaskQueued = false;  
  236.   
  237.                 // compare against getMaximumRange to support sensors that only return 0 or 1  
  238.                 //比较接近距离,是否开启感应(0< distance < 5 cm&&)  
  239.                 boolean active = (distance >= 0.0 && distance < PROXIMITY_THRESHOLD &&  
  240.                         distance < mProximitySensor.getMaximumRange());  
  241.   
  242.                 if (mDebugProximitySensor) {  
  243.                     Slog.d(TAG, "mProximityListener.onSensorChanged active: " + active);  
  244.                 }  
  245.                 if (timeSinceLastEvent < PROXIMITY_SENSOR_DELAY) {  
  246.                     // enforce delaying atleast PROXIMITY_SENSOR_DELAY before processing  
  247.                     mProximityPendingValue = (active ? 1 : 0);  
  248.                     mHandler.postDelayed(mProximityTask, PROXIMITY_SENSOR_DELAY - timeSinceLastEvent);  
  249.                     proximityTaskQueued = true;  
  250.                 } else {  
  251.                     // process the value immediately  
  252.                     mProximityPendingValue = -1;  
  253.                     proximityChangedLocked(active);//改变距离感应状态  
  254.                 }  
  255.   
  256.                 // update mProximityPartialLock state  
  257.                 boolean held = mProximityPartialLock.isHeld();  
  258.                 if (!held && proximityTaskQueued) {  
  259.                     // hold wakelock until mProximityTask runs  
  260.                     mProximityPartialLock.acquire();  
  261.                 } else if (held && !proximityTaskQueued) {  
  262.                     mProximityPartialLock.release();  
  263.                 }  
  264.             }  
  265.         }  
  266.   
  267.         public void onAccuracyChanged(Sensor sensor, int accuracy) {  
  268.             // ignore  
  269.         }  
  270.     };  
  271.   
  272. 将会进入  
  273.   
  274.     private void proximityChangedLocked(boolean active) {  
  275.         if (mDebugProximitySensor) {  
  276.             Slog.d(TAG, "proximityChangedLocked, active: " + active);  
  277.         }  
  278.         if (!mProximitySensorEnabled) {  
  279.             Slog.d(TAG, "Ignoring proximity change after sensor is disabled");  
  280.             return;  
  281.         }  
  282.         if (active) {  
  283.             if (mDebugProximitySensor) {  
  284.                 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="  
  285.                         + mProxIgnoredBecauseScreenTurnedOff);  
  286.             }  
  287.             if (!mProxIgnoredBecauseScreenTurnedOff) {  
  288.             //会进入此函数  
  289.                 goToSleepLocked(SystemClock.uptimeMillis(),  
  290.                         WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR);  
  291.             }  
  292.             mProximitySensorActive = true;  
  293.         } else {  
  294.             // proximity sensor negative events trigger as user activity.  
  295.             // temporarily set mUserActivityAllowed to true so this will work  
  296.             // even when the keyguard is on.  
  297.             mProximitySensorActive = false;  
  298.             if (mDebugProximitySensor) {  
  299.                 Slog.d(TAG, "b mProxIgnoredBecauseScreenTurnedOff="  
  300.                         + mProxIgnoredBecauseScreenTurnedOff);  
  301.             }  
  302.             if (!mProxIgnoredBecauseScreenTurnedOff) {  
  303.                 forceUserActivityLocked();  
  304.             }  
  305.   
  306.             if (mProximityWakeLockCount == 0) {  
  307.                 // disable sensor if we have no listeners left after proximity negative  
  308.                 disableProximityLockLocked();  
  309.             }  
  310.         }  
  311.     }  
  312.   
  313.   
  314.     private void goToSleepLocked(long time, int reason) {  
  315.   
  316.         if (mLastEventTime <= time) {  
  317.             mLastEventTime = time;  
  318.             // cancel all of the wake locks  
  319.             mWakeLockState = SCREEN_OFF;  
  320.             int N = mLocks.size();  
  321.             int numCleared = 0;  
  322.             boolean proxLock = false;  
  323.             for (int i=0; i<N; i++) {  
  324.                 WakeLock wl = mLocks.get(i);  
  325.                 if (isScreenLock(wl.flags)) {  
  326.                     if (((wl.flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)  
  327.                             && reason == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) {  
  328.                         proxLock = true;  
  329.                     } else {  
  330.                         mLocks.get(i).activated = false;  
  331.                         numCleared++;  
  332.                     }  
  333.                 }  
  334.             }  
  335.             if (!proxLock) {  
  336.                 mProxIgnoredBecauseScreenTurnedOff = true;  
  337.                 if (mDebugProximitySensor) {  
  338.                     Slog.d(TAG, "setting mProxIgnoredBecauseScreenTurnedOff");  
  339.                 }  
  340.             }  
  341.             EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numCleared);  
  342.             mStillNeedSleepNotification = true;  
  343.             mUserState = SCREEN_OFF;  
  344.             //设置供电状态  
  345.             setPowerState(SCREEN_OFF, false, reason);  
  346.             cancelTimerLocked();  
  347.         }  
  348.     }  

上述阶段是指LCD背光开灭状态控制。

下面来分析最后一个阶段PhoneApp如何调用。


  1. 在OnCreate()中  
  2.             // Wake lock used to control proximity sensor behavior.  
  3.             if ((pm.getSupportedWakeLockFlags()  
  4.                  & PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) != 0x0) {  
  5.                 mProximityWakeLock =  
  6.                         pm.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, LOG_TAG);  
  7.             }  
  8.             if (DBG) Log.d(LOG_TAG, "onCreate: mProximityWakeLock: " + mProximityWakeLock);  
  9.   
  10.             // create mAccelerometerListener only if we are using the proximity sensor  
  11.             if (proximitySensorModeEnabled()) {  
  12.                 mAccelerometerListener = new AccelerometerListener(thisthis);  
  13.             }  
  14.   
  15.   
  16.     /* package */ void setBeginningCall(boolean beginning) {  
  17.         // Note that we are beginning a new call, for proximity sensor support  
  18.         mBeginningCall = beginning;  
  19.         // Update the Proximity sensor based on mBeginningCall state  
  20.     //更新距离感应状态  
  21.         updateProximitySensorMode(mCM.getState());  
  22.     }  
  23.   
  24.   
  25.     /* package */ void updateProximitySensorMode(Phone.State state) {  
  26.         if (VDBG) Log.d(LOG_TAG, "updateProximitySensorMode: state = " + state);  
  27.   
  28.         if (proximitySensorModeEnabled()) {  
  29.             synchronized (mProximityWakeLock) {  
  30.                 // turn proximity sensor off and turn screen on immediately if  
  31.                 // we are using a headset, the keyboard is open, or the device  
  32.                 // is being held in a horizontal position.  
  33.                 boolean screenOnImmediately = (isHeadsetPlugged()  
  34.                             || PhoneUtils.isSpeakerOn(this)  
  35.                             || ((mBtHandsfree != null) && mBtHandsfree.isAudioOn())  
  36.                             || mIsHardKeyboardOpen);  
  37.                 // We do not keep the screen off when we are horizontal, but we do not force it  
  38.                 // on when we become horizontal until the proximity sensor goes negative.  
  39. //                boolean horizontal = (mOrientation == AccelerometerListener.ORIENTATION_HORIZONTAL);  
  40. //                && !horizontal  
  41.                 if ((((!PhoneUtils.isVideoCall()) && (state == Phone.State.OFFHOOK)) || mBeginningCall) && !screenOnImmediately ) {  
  42.                     // Phone is in use!  Arrange for the screen to turn off  
  43.                     // automatically when the sensor detects a close object.  
  44.                     if (!mProximityWakeLock.isHeld()) {  
  45.                         if (DBG) Log.d(LOG_TAG, "updateProximitySensorMode: acquiring...");  
  46.                         //注意此函数  
  47.                         mProximityWakeLock.acquire();  
  48.                     } else {  
  49.                         if (VDBG) Log.d(LOG_TAG, "updateProximitySensorMode: lock already held.");  
  50.                                                        
  51.                     }  
  52.                 } else {  
  53.                     // Phone is either idle, or ringing.  We don't want any  
  54.                     // special proximity sensor behavior in either case.  
  55.                     if (mProximityWakeLock.isHeld()) {  
  56.                         if (DBG) Log.d(LOG_TAG, "updateProximitySensorMode: releasing...");  
  57.                         // Wait until user has moved the phone away from his head if we are  
  58.                         // releasing due to the phone call ending.  
  59.                         // Qtherwise, turn screen on immediately  
  60.                           int flags =  
  61.                             (screenOnImmediately ? 0 : PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE);  
  62.                           mProximityWakeLock.release(flags);  
  63.                     } else {  
  64.                         if (VDBG) {  
  65.                             Log.d(LOG_TAG, "updateProximitySensorMode: lock already released.");  
  66.                         }  
  67.                     }  
  68.                 }  
  69.             }  
  70.         }  
  71.     }  
  72.   
  73.   
  74.   
  75. mProximityWakeLock.acquire();将调用PowerManagerService.java中的        public void acquire() {  
  76.             if (!mRefCounted || mCount++ == 0) {  
  77.                 long ident = Binder.clearCallingIdentity();  
  78.                 try {  
  79.                     PowerManagerService.this.acquireWakeLockLocked(mFlags, mToken,  
  80.                             MY_UID, MY_PID, mTag, null);  
  81.                     mHeld = true;  
  82.                 } finally {  
  83.                     Binder.restoreCallingIdentity(ident);  
  84.                 }  
  85.             }  
  86.         }  
  87.   
  88. 然后调用  
  89.   
  90.     public void acquireWakeLockLocked(int flags, IBinder lock, int uid, int pid, String tag,  
  91.             WorkSource ws) {  
  92.   
  93. … …  
  94.         if (isScreenLock(flags)) {  
  95.             // if this causes a wakeup, we reactivate all of the locks and  
  96.             // set it to whatever they want.  otherwise, we modulate that  
  97.             // by the current state so we never turn it more on than  
  98.             // it already is.  
  99.             if ((flags & LOCK_MASK) == PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK) {  
  100.                 mProximityWakeLockCount++;  
  101.                 if (mProximityWakeLockCount == 1) {  
  102.                     enableProximityLockLocked();  
  103.                 }  
  104.             } else {  
  105.                 if ((wl.flags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {  
  106.                     int oldWakeLockState = mWakeLockState;  
  107.                     mWakeLockState = mLocks.reactivateScreenLocksLocked();  
  108.                     if (mSpew) {  
  109.                         Slog.d(TAG, "wakeup here mUserState=0x" + Integer.toHexString(mUserState)  
  110.                                 + " mWakeLockState=0x"  
  111.                                 + Integer.toHexString(mWakeLockState)  
  112.                                 + " previous wakeLockState=0x"  
  113.                                 + Integer.toHexString(oldWakeLockState));  
  114.                     }  
  115.                 } else {  
  116.                     if (mSpew) {  
  117.                         Slog.d(TAG, "here mUserState=0x" + Integer.toHexString(mUserState)  
  118.                                 + " mLocks.gatherState()=0x"  
  119.                                 + Integer.toHexString(mLocks.gatherState())  
  120.                                 + " mWakeLockState=0x" + Integer.toHexString(mWakeLockState));  
  121.                     }  
  122.                     mWakeLockState = (mUserState | mWakeLockState) & mLocks.gatherState();  
  123.                 }  
  124.                 setPowerState(mWakeLockState | mUserState);  
  125.             }  
  126.         }  
  127.         else if ((flags & LOCK_MASK) == PowerManager.PARTIAL_WAKE_LOCK) {  
  128.             if (newlock) {  
  129.                 mPartialCount++;  
  130.                 if (mPartialCount == 1) {  
  131.                     if (LOG_PARTIAL_WL) EventLog.writeEvent(EventLogTags.POWER_PARTIAL_WAKE_STATE, 1, tag);  
  132.                 }  
  133.             }  
  134.             Power.acquireWakeLock(Power.PARTIAL_WAKE_LOCK,PARTIAL_NAME);  
  135.         }  
  136. … …  
  137. }  


既上面所说的。至此tp从底层驱动到上层app整个流程分析完毕。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值