sensorservicetest.cpp revision fc32881fcc68640d008c7515cdd1bcd866f72cd5
1/* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#include <android/sensor.h> 18#include <gui/Sensor.h> 19#include <gui/SensorManager.h> 20#include <gui/SensorEventQueue.h> 21#include <utils/PollLoop.h> 22 23using namespace android; 24 25bool receiver(int fd, int events, void* data) 26{ 27 sp<SensorEventQueue> q((SensorEventQueue*)data); 28 ssize_t n; 29 ASensorEvent buffer[8]; 30 while ((n = q->read(buffer, 8)) > 0) { 31 for (int i=0 ; i<n ; i++) { 32 if (buffer[i].type == Sensor::TYPE_ACCELEROMETER) { 33 printf("time=%lld, value=<%5.1f,%5.1f,%5.1f>\n", 34 buffer[i].timestamp, 35 buffer[i].acceleration.x, 36 buffer[i].acceleration.y, 37 buffer[i].acceleration.z); 38 } 39 } 40 } 41 if (n<0 && n != -EAGAIN) { 42 printf("error reading events (%s)\n", strerror(-n)); 43 } 44 return true; 45} 46 47 48int main(int argc, char** argv) 49{ 50 SensorManager& mgr(SensorManager::getInstance()); 51 52 Sensor const* const* list; 53 ssize_t count = mgr.getSensorList(&list); 54 printf("numSensors=%d\n", count); 55 56 sp<SensorEventQueue> q = mgr.createEventQueue(); 57 printf("queue=%p\n", q.get()); 58 59 Sensor const* accelerometer = mgr.getDefaultSensor(Sensor::TYPE_ACCELEROMETER); 60 printf("accelerometer=%p (%s)\n", 61 accelerometer, accelerometer->getName().string()); 62 q->enableSensor(accelerometer); 63 64 q->setEventRate(accelerometer, ms2ns(10)); 65 66 sp<PollLoop> loop = new PollLoop(false); 67 loop->setCallback(q->getFd(), POLLIN, receiver, q.get()); 68 69 do { 70 //printf("about to poll...\n"); 71 int32_t ret = loop->pollOnce(-1, 0, 0); 72 switch (ret) { 73 case ALOOPER_POLL_CALLBACK: 74 //("ALOOPER_POLL_CALLBACK\n"); 75 break; 76 case ALOOPER_POLL_TIMEOUT: 77 printf("ALOOPER_POLL_TIMEOUT\n"); 78 break; 79 case ALOOPER_POLL_ERROR: 80 printf("ALOOPER_POLL_TIMEOUT\n"); 81 break; 82 default: 83 printf("ugh? poll returned %d\n", ret); 84 break; 85 } 86 } while (1); 87 88 89 return 0; 90} 91