OSDN Git Service

android-2.1_r1 snapshot
[android-x86/sdk.git] / emulator / sensors / sensors_qemu.c
1 /*
2  * Copyright (C) 2009 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 /* this implements a sensors hardware library for the Android emulator.
18  * the following code should be built as a shared library that will be
19  * placed into /system/lib/hw/sensors.goldfish.so
20  *
21  * it will be loaded by the code in hardware/libhardware/hardware.c
22  * which is itself called from com_android_server_SensorService.cpp
23  */
24
25
26 /* we connect with the emulator through the "sensors" qemud service
27  */
28 #define  SENSORS_SERVICE_NAME "sensors"
29
30 #define LOG_TAG "QemuSensors"
31
32 #include <unistd.h>
33 #include <fcntl.h>
34 #include <errno.h>
35 #include <string.h>
36 #include <cutils/log.h>
37 #include <cutils/native_handle.h>
38 #include <cutils/sockets.h>
39 #include <hardware/sensors.h>
40
41 #if 0
42 #define  D(...)  LOGD(__VA_ARGS__)
43 #else
44 #define  D(...)  ((void)0)
45 #endif
46
47 #define  E(...)  LOGE(__VA_ARGS__)
48
49 #include <hardware/qemud.h>
50
51 /** SENSOR IDS AND NAMES
52  **/
53
54 #define MAX_NUM_SENSORS 4
55
56 #define SUPPORTED_SENSORS  ((1<<MAX_NUM_SENSORS)-1)
57
58 #define  ID_BASE           SENSORS_HANDLE_BASE
59 #define  ID_ACCELERATION   (ID_BASE+0)
60 #define  ID_MAGNETIC_FIELD (ID_BASE+1)
61 #define  ID_ORIENTATION    (ID_BASE+2)
62 #define  ID_TEMPERATURE    (ID_BASE+3)
63
64 #define  SENSORS_ACCELERATION   (1 << ID_ACCELERATION)
65 #define  SENSORS_MAGNETIC_FIELD  (1 << ID_MAGNETIC_FIELD)
66 #define  SENSORS_ORIENTATION     (1 << ID_ORIENTATION)
67 #define  SENSORS_TEMPERATURE     (1 << ID_TEMPERATURE)
68
69 #define  ID_CHECK(x)  ((unsigned)((x)-ID_BASE) < 4)
70
71 #define  SENSORS_LIST  \
72     SENSOR_(ACCELERATION,"acceleration") \
73     SENSOR_(MAGNETIC_FIELD,"magnetic-field") \
74     SENSOR_(ORIENTATION,"orientation") \
75     SENSOR_(TEMPERATURE,"temperature") \
76
77 static const struct {
78     const char*  name;
79     int          id; } _sensorIds[MAX_NUM_SENSORS] =
80 {
81 #define SENSOR_(x,y)  { y, ID_##x },
82     SENSORS_LIST
83 #undef  SENSOR_
84 };
85
86 static const char*
87 _sensorIdToName( int  id )
88 {
89     int  nn;
90     for (nn = 0; nn < MAX_NUM_SENSORS; nn++)
91         if (id == _sensorIds[nn].id)
92             return _sensorIds[nn].name;
93     return "<UNKNOWN>";
94 }
95
96 static int
97 _sensorIdFromName( const char*  name )
98 {
99     int  nn;
100
101     if (name == NULL)
102         return -1;
103
104     for (nn = 0; nn < MAX_NUM_SENSORS; nn++)
105         if (!strcmp(name, _sensorIds[nn].name))
106             return _sensorIds[nn].id;
107
108     return -1;
109 }
110
111 /** SENSORS CONTROL DEVICE
112  **
113  ** This one is used to send commands to the sensors drivers.
114  ** We implement this by sending directly commands to the emulator
115  ** through the QEMUD channel.
116  **/
117
118 typedef struct SensorControl {
119     struct sensors_control_device_t  device;
120     int                              fd;
121     uint32_t                         active_sensors;
122 } SensorControl;
123
124 /* this must return a file descriptor that will be used to read
125  * the sensors data (it is passed to data__data_open() below
126  */
127 static native_handle_t*
128 control__open_data_source(struct sensors_control_device_t *dev)
129 {
130     SensorControl*  ctl = (void*)dev;
131     native_handle_t* handle;
132
133     if (ctl->fd < 0) {
134         ctl->fd = qemud_channel_open(SENSORS_SERVICE_NAME);
135     }
136     D("%s: fd=%d", __FUNCTION__, ctl->fd);
137     handle = native_handle_create(1, 0);
138     handle->data[0] = ctl->fd;
139     return handle;
140 }
141
142 static int
143 control__activate(struct sensors_control_device_t *dev,
144                   int handle,
145                   int enabled)
146 {
147     SensorControl*  ctl = (void*)dev;
148     uint32_t        mask, sensors, active, new_sensors, changed;
149     char            command[128];
150     int             ret;
151
152     D("%s: handle=%s (%d) enabled=%d", __FUNCTION__,
153         _sensorIdToName(handle), handle, enabled);
154
155     if (!ID_CHECK(handle)) {
156         E("%s: bad handle ID", __FUNCTION__);
157         return -1;
158     }
159
160     mask    = (1<<handle);
161     sensors = enabled ? mask : 0;
162
163     active      = ctl->active_sensors;
164     new_sensors = (active & ~mask) | (sensors & mask);
165     changed     = active ^ new_sensors;
166
167     if (!changed)
168         return 0;
169
170     snprintf(command, sizeof command, "set:%s:%d",
171                 _sensorIdToName(handle), enabled != 0);
172
173     if (ctl->fd < 0) {
174         ctl->fd = qemud_channel_open(SENSORS_SERVICE_NAME);
175     }
176
177     ret = qemud_channel_send(ctl->fd, command, -1);
178     if (ret < 0)
179         return -1;
180
181     ctl->active_sensors = new_sensors;
182
183     return 0;
184 }
185
186 static int
187 control__set_delay(struct sensors_control_device_t *dev, int32_t ms)
188 {
189     SensorControl*  ctl = (void*)dev;
190     char            command[128];
191
192     D("%s: dev=%p delay-ms=%d", __FUNCTION__, dev, ms);
193
194     snprintf(command, sizeof command, "set-delay:%d", ms);
195
196     return qemud_channel_send(ctl->fd, command, -1);
197 }
198
199 /* this function is used to force-stop the blocking read() in
200  * data__poll. In order to keep the implementation as simple
201  * as possible here, we send a command to the emulator which
202  * shall send back an appropriate data block to the system.
203  */
204 static int
205 control__wake(struct sensors_control_device_t *dev)
206 {
207     SensorControl*  ctl = (void*)dev;
208     D("%s: dev=%p", __FUNCTION__, dev);
209     return qemud_channel_send(ctl->fd, "wake", -1);
210 }
211
212
213 static int
214 control__close(struct hw_device_t *dev) 
215 {
216     SensorControl*  ctl = (void*)dev;
217     close(ctl->fd);
218     free(ctl);
219     return 0;
220 }
221
222 /** SENSORS DATA DEVICE
223  **
224  ** This one is used to read sensor data from the hardware.
225  ** We implement this by simply reading the data from the
226  ** emulator through the QEMUD channel.
227  **/
228
229
230 typedef struct SensorData {
231     struct sensors_data_device_t  device;
232     sensors_data_t                sensors[MAX_NUM_SENSORS];
233     int                           events_fd;
234     uint32_t                      pendingSensors;
235     int64_t                       timeStart;
236     int64_t                       timeOffset;
237 } SensorData;
238
239 /* return the current time in nanoseconds */
240 static int64_t
241 data__now_ns(void)
242 {
243     struct timespec  ts;
244
245     clock_gettime(CLOCK_MONOTONIC, &ts);
246
247     return (int64_t)ts.tv_sec * 1000000000 + ts.tv_nsec;
248 }
249
250 static int
251 data__data_open(struct sensors_data_device_t *dev, native_handle_t* handle)
252 {
253     SensorData*  data = (void*)dev;
254     int i;
255     D("%s: dev=%p fd=%d", __FUNCTION__, dev, fd);
256     memset(&data->sensors, 0, sizeof(data->sensors));
257
258     for (i=0 ; i<MAX_NUM_SENSORS ; i++) {
259         data->sensors[i].vector.status = SENSOR_STATUS_ACCURACY_HIGH;
260     }
261     data->pendingSensors = 0;
262     data->timeStart      = 0;
263     data->timeOffset     = 0;
264
265     data->events_fd = dup(handle->data[0]);
266     native_handle_close(handle);
267     native_handle_delete(handle);
268     return 0;
269 }
270
271 static int
272 data__data_close(struct sensors_data_device_t *dev)
273 {
274     SensorData*  data = (void*)dev;
275     D("%s: dev=%p", __FUNCTION__, dev);
276     if (data->events_fd > 0) {
277         close(data->events_fd);
278         data->events_fd = -1;
279     }
280     return 0;
281 }
282
283 static int
284 pick_sensor(SensorData*      data,
285             sensors_data_t*  values)
286 {
287     uint32_t mask = SUPPORTED_SENSORS;
288     while (mask) {
289         uint32_t i = 31 - __builtin_clz(mask);
290         mask &= ~(1<<i);
291         if (data->pendingSensors & (1<<i)) {
292             data->pendingSensors &= ~(1<<i);
293             *values = data->sensors[i];
294             values->sensor = (1<<i);
295             LOGD_IF(0, "%s: %d [%f, %f, %f]", __FUNCTION__,
296                     (1<<i),
297                     values->vector.x,
298                     values->vector.y,
299                     values->vector.z);
300             return i;
301         }
302     }
303     LOGE("No sensor to return!!! pendingSensors=%08x", data->pendingSensors);
304     // we may end-up in a busy loop, slow things down, just in case.
305     usleep(100000);
306     return -1;
307 }
308
309 static int
310 data__poll(struct sensors_data_device_t *dev, sensors_data_t* values)
311 {
312     SensorData*  data = (void*)dev;
313     int fd = data->events_fd;
314
315     D("%s: data=%p", __FUNCTION__, dev);
316
317     // there are pending sensors, returns them now...
318     if (data->pendingSensors) {
319         return pick_sensor(data, values);
320     }
321
322     // wait until we get a complete event for an enabled sensor
323     uint32_t new_sensors = 0;
324
325     while (1) {
326         /* read the next event */
327         char     buff[256];
328         int      len = qemud_channel_recv(data->events_fd, buff, sizeof buff-1);
329         float    params[3];
330         int64_t  event_time;
331
332         if (len < 0)
333             continue;
334
335         buff[len] = 0;
336
337         /* "wake" is sent from the emulator to exit this loop. This shall
338          * really be because another thread called "control__wake" in this
339          * process.
340          */
341         if (!strcmp((const char*)data, "wake")) {
342             return 0x7FFFFFFF;
343         }
344
345         /* "acceleration:<x>:<y>:<z>" corresponds to an acceleration event */
346         if (sscanf(buff, "acceleration:%g:%g:%g", params+0, params+1, params+2) == 3) {
347             new_sensors |= SENSORS_ACCELERATION;
348             data->sensors[ID_ACCELERATION].acceleration.x = params[0];
349             data->sensors[ID_ACCELERATION].acceleration.y = params[1];
350             data->sensors[ID_ACCELERATION].acceleration.z = params[2];
351             continue;
352         }
353
354         /* "orientation:<azimuth>:<pitch>:<roll>" is sent when orientation changes */
355         if (sscanf(buff, "orientation:%g:%g:%g", params+0, params+1, params+2) == 3) {
356             new_sensors |= SENSORS_ORIENTATION;
357             data->sensors[ID_ORIENTATION].orientation.azimuth = params[0];
358             data->sensors[ID_ORIENTATION].orientation.pitch   = params[1];
359             data->sensors[ID_ORIENTATION].orientation.roll    = params[2];
360             continue;
361         }
362
363         /* "magnetic:<x>:<y>:<z>" is sent for the params of the magnetic field */
364         if (sscanf(buff, "magnetic:%g:%g:%g", params+0, params+1, params+2) == 3) {
365             new_sensors |= SENSORS_MAGNETIC_FIELD;
366             data->sensors[ID_MAGNETIC_FIELD].magnetic.x = params[0];
367             data->sensors[ID_MAGNETIC_FIELD].magnetic.y = params[1];
368             data->sensors[ID_MAGNETIC_FIELD].magnetic.z = params[2];
369             continue;
370         }
371
372         /* "temperature:<celsius>" */
373         if (sscanf(buff, "temperature:%g", params+0) == 2) {
374             new_sensors |= SENSORS_TEMPERATURE;
375             data->sensors[ID_TEMPERATURE].temperature = params[0];
376             continue;
377         }
378
379         /* "sync:<time>" is sent after a series of sensor events.
380          * where 'time' is expressed in micro-seconds and corresponds
381          * to the VM time when the real poll occured.
382          */
383         if (sscanf(buff, "sync:%lld", &event_time) == 1) {
384             if (new_sensors) {
385                 data->pendingSensors = new_sensors;
386                 int64_t t = event_time * 1000LL;  /* convert to nano-seconds */
387
388                 /* use the time at the first sync: as the base for later
389                  * time values */
390                 if (data->timeStart == 0) {
391                     data->timeStart  = data__now_ns();
392                     data->timeOffset = data->timeStart - t;
393                 }
394                 t += data->timeOffset;
395
396                 while (new_sensors) {
397                     uint32_t i = 31 - __builtin_clz(new_sensors);
398                     new_sensors &= ~(1<<i);
399                     data->sensors[i].time = t;
400                 }
401                 return pick_sensor(data, values);
402             } else {
403                 D("huh ? sync without any sensor data ?");
404             }
405             continue;
406         }
407         D("huh ? unsupported command");
408     }
409 }
410
411 static int
412 data__close(struct hw_device_t *dev) 
413 {
414     SensorData* data = (SensorData*)dev;
415     if (data) {
416         if (data->events_fd > 0) {
417             //LOGD("(device close) about to close fd=%d", data->events_fd);
418             close(data->events_fd);
419         }
420         free(data);
421     }
422     return 0;
423 }
424
425
426 /** MODULE REGISTRATION SUPPORT
427  **
428  ** This is required so that hardware/libhardware/hardware.c
429  ** will dlopen() this library appropriately.
430  **/
431
432 /*
433  * the following is the list of all supported sensors.
434  * this table is used to build sSensorList declared below
435  * according to which hardware sensors are reported as
436  * available from the emulator (see get_sensors_list below)
437  *
438  * note: numerical values for maxRange/resolution/power were
439  *       taken from the reference AK8976A implementation
440  */
441 static const struct sensor_t sSensorListInit[] = {
442         { .name       = "Goldfish 3-axis Accelerometer",
443           .vendor     = "The Android Open Source Project",
444           .version    = 1,
445           .handle     = ID_ACCELERATION,
446           .type       = SENSOR_TYPE_ACCELEROMETER,
447           .maxRange   = 2.8f,
448           .resolution = 1.0f/4032.0f,
449           .power      = 3.0f,
450           .reserved   = {}
451         },
452
453         { .name       = "Goldfish 3-axis Magnetic field sensor",
454           .vendor     = "The Android Open Source Project",
455           .version    = 1,
456           .handle     = ID_MAGNETIC_FIELD,
457           .type       = SENSOR_TYPE_MAGNETIC_FIELD,
458           .maxRange   = 2000.0f,
459           .resolution = 1.0f,
460           .power      = 6.7f,
461           .reserved   = {}
462         },
463
464         { .name       = "Goldfish Orientation sensor",
465           .vendor     = "The Android Open Source Project",
466           .version    = 1,
467           .handle     = ID_ORIENTATION,
468           .type       = SENSOR_TYPE_ORIENTATION,
469           .maxRange   = 360.0f,
470           .resolution = 1.0f,
471           .power      = 9.7f,
472           .reserved   = {}
473         },
474
475         { .name       = "Goldfish Temperature sensor",
476           .vendor     = "The Android Open Source Project",
477           .version    = 1,
478           .handle     = ID_TEMPERATURE,
479           .type       = SENSOR_TYPE_TEMPERATURE,
480           .maxRange   = 80.0f,
481           .resolution = 1.0f,
482           .power      = 0.0f,
483           .reserved   = {}
484         },
485 };
486
487 static struct sensor_t  sSensorList[MAX_NUM_SENSORS];
488
489 static uint32_t sensors__get_sensors_list(struct sensors_module_t* module,
490         struct sensor_t const** list) 
491 {
492     int  fd = qemud_channel_open(SENSORS_SERVICE_NAME);
493     char buffer[12];
494     int  mask, nn, count;
495
496     int  ret;
497     if (fd < 0) {
498         E("%s: no qemud connection", __FUNCTION__);
499         return 0;
500     }
501     ret = qemud_channel_send(fd, "list-sensors", -1);
502     if (ret < 0) {
503         E("%s: could not query sensor list: %s", __FUNCTION__,
504           strerror(errno));
505         close(fd);
506         return 0;
507     }
508     ret = qemud_channel_recv(fd, buffer, sizeof buffer-1);
509     if (ret < 0) {
510         E("%s: could not receive sensor list: %s", __FUNCTION__,
511           strerror(errno));
512         close(fd);
513         return 0;
514     }
515     buffer[ret] = 0;
516     close(fd);
517
518     /* the result is a integer used as a mask for available sensors */
519     mask  = atoi(buffer);
520     count = 0;
521     for (nn = 0; nn < MAX_NUM_SENSORS; nn++) {
522         if (((1 << nn) & mask) == 0)
523             continue;
524
525         sSensorList[count++] = sSensorListInit[nn];
526     }
527     D("%s: returned %d sensors (mask=%d)", __FUNCTION__, count, mask);
528     *list = sSensorList;
529     return count;
530 }
531
532
533 static int
534 open_sensors(const struct hw_module_t* module,
535              const char*               name,
536              struct hw_device_t*      *device)
537 {
538     int  status = -EINVAL;
539
540     D("%s: name=%s", __FUNCTION__, name);
541
542     if (!strcmp(name, SENSORS_HARDWARE_CONTROL))
543     {
544         SensorControl *dev = malloc(sizeof(*dev));
545
546         memset(dev, 0, sizeof(*dev));
547
548         dev->device.common.tag       = HARDWARE_DEVICE_TAG;
549         dev->device.common.version   = 0;
550         dev->device.common.module    = (struct hw_module_t*) module;
551         dev->device.common.close     = control__close;
552         dev->device.open_data_source = control__open_data_source;
553         dev->device.activate         = control__activate;
554         dev->device.set_delay        = control__set_delay;
555         dev->device.wake             = control__wake;
556         dev->fd                      = -1;
557
558         *device = &dev->device.common;
559         status  = 0;
560     }
561     else if (!strcmp(name, SENSORS_HARDWARE_DATA)) {
562         SensorData *dev = malloc(sizeof(*dev));
563
564         memset(dev, 0, sizeof(*dev));
565
566         dev->device.common.tag     = HARDWARE_DEVICE_TAG;
567         dev->device.common.version = 0;
568         dev->device.common.module  = (struct hw_module_t*) module;
569         dev->device.common.close   = data__close;
570         dev->device.data_open      = data__data_open;
571         dev->device.data_close     = data__data_close;
572         dev->device.poll           = data__poll;
573         dev->events_fd             = -1;
574
575         *device = &dev->device.common;
576         status  = 0;
577     }
578     return status;
579 }
580
581
582 static struct hw_module_methods_t sensors_module_methods = {
583     .open = open_sensors
584 };
585
586 const struct sensors_module_t HAL_MODULE_INFO_SYM = {
587     .common = {
588         .tag = HARDWARE_MODULE_TAG,
589         .version_major = 1,
590         .version_minor = 0,
591         .id = SENSORS_HARDWARE_MODULE_ID,
592         .name = "Goldfish SENSORS Module",
593         .author = "The Android Open Source Project",
594         .methods = &sensors_module_methods,
595     },
596     .get_sensors_list = sensors__get_sensors_list
597 };