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/Looper.h> 22 23 using namespace android; 24 25 static nsecs_t sStartTime = 0; 26 27 28 int receiver(int fd, int events, void* data) 29 { 30 sp<SensorEventQueue> q((SensorEventQueue*)data); 31 ssize_t n; 32 ASensorEvent buffer[8]; 33 34 static nsecs_t oldTimeStamp = 0; 35 36 while ((n = q->read(buffer, 8)) > 0) { 37 for (int i=0 ; i<n ; i++) { 38 float t; 39 if (oldTimeStamp) { 40 t = float(buffer[i].timestamp - oldTimeStamp) / s2ns(1); 41 } else { 42 t = float(buffer[i].timestamp - sStartTime) / s2ns(1); 43 } 44 oldTimeStamp = buffer[i].timestamp; 45 46 if (buffer[i].type == Sensor::TYPE_ACCELEROMETER) { 47 printf("%lld\t%8f\t%8f\t%8f\t%f\n", 48 buffer[i].timestamp, 49 buffer[i].data[0], buffer[i].data[1], buffer[i].data[2], 50 1.0/t); 51 } 52 53 } 54 } 55 if (n<0 && n != -EAGAIN) { 56 printf("error reading events (%s)\n", strerror(-n)); 57 } 58 return 1; 59 } 60 61 62 int main(int argc, char** argv) 63 { 64 SensorManager& mgr(SensorManager::getInstance()); 65 66 Sensor const* const* list; 67 ssize_t count = mgr.getSensorList(&list); 68 printf("numSensors=%d\n", int(count)); 69 70 sp<SensorEventQueue> q = mgr.createEventQueue(); 71 printf("queue=%p\n", q.get()); 72 73 Sensor const* accelerometer = mgr.getDefaultSensor(Sensor::TYPE_ACCELEROMETER); 74 printf("accelerometer=%p (%s)\n", 75 accelerometer, accelerometer->getName().string()); 76 77 sStartTime = systemTime(); 78 79 q->enableSensor(accelerometer); 80 81 q->setEventRate(accelerometer, ms2ns(10)); 82 83 sp<Looper> loop = new Looper(false); 84 loop->addFd(q->getFd(), 0, ALOOPER_EVENT_INPUT, receiver, q.get()); 85 86 do { 87 //printf("about to poll...\n"); 88 int32_t ret = loop->pollOnce(-1); 89 switch (ret) { 90 case ALOOPER_POLL_WAKE: 91 //("ALOOPER_POLL_WAKE\n"); 92 break; 93 case ALOOPER_POLL_CALLBACK: 94 //("ALOOPER_POLL_CALLBACK\n"); 95 break; 96 case ALOOPER_POLL_TIMEOUT: 97 printf("ALOOPER_POLL_TIMEOUT\n"); 98 break; 99 case ALOOPER_POLL_ERROR: 100 printf("ALOOPER_POLL_TIMEOUT\n"); 101 break; 102 default: 103 printf("ugh? poll returned %d\n", ret); 104 break; 105 } 106 } while (1); 107 108 109 return 0; 110 } 111