OSDN Git Service

config.ini: change the default settings for OPENTHOS
[android-x86/device-generic-goldfish.git] / 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/sockets.h>
38 #include <hardware/sensors.h>
39
40 #if 0
41 #define  D(...)  ALOGD(__VA_ARGS__)
42 #else
43 #define  D(...)  ((void)0)
44 #endif
45
46 #define  E(...)  ALOGE(__VA_ARGS__)
47
48 #include "qemud.h"
49
50 /** SENSOR IDS AND NAMES
51  **/
52
53 #define MAX_NUM_SENSORS 10
54
55 #define SUPPORTED_SENSORS  ((1<<MAX_NUM_SENSORS)-1)
56
57 #define  ID_BASE                        SENSORS_HANDLE_BASE
58 #define  ID_ACCELERATION                (ID_BASE+0)
59 #define  ID_GYROSCOPE                   (ID_BASE+1)
60 #define  ID_MAGNETIC_FIELD              (ID_BASE+2)
61 #define  ID_ORIENTATION                 (ID_BASE+3)
62 #define  ID_TEMPERATURE                 (ID_BASE+4)
63 #define  ID_PROXIMITY                   (ID_BASE+5)
64 #define  ID_LIGHT                       (ID_BASE+6)
65 #define  ID_PRESSURE                    (ID_BASE+7)
66 #define  ID_HUMIDITY                    (ID_BASE+8)
67 #define  ID_MAGNETIC_FIELD_UNCALIBRATED (ID_BASE+9)
68
69 #define  SENSORS_ACCELERATION                 (1 << ID_ACCELERATION)
70 #define  SENSORS_GYROSCOPE                    (1 << ID_GYROSCOPE)
71 #define  SENSORS_MAGNETIC_FIELD               (1 << ID_MAGNETIC_FIELD)
72 #define  SENSORS_ORIENTATION                  (1 << ID_ORIENTATION)
73 #define  SENSORS_TEMPERATURE                  (1 << ID_TEMPERATURE)
74 #define  SENSORS_PROXIMITY                    (1 << ID_PROXIMITY)
75 #define  SENSORS_LIGHT                        (1 << ID_LIGHT)
76 #define  SENSORS_PRESSURE                     (1 << ID_PRESSURE)
77 #define  SENSORS_HUMIDITY                     (1 << ID_HUMIDITY)
78 #define  SENSORS_MAGNETIC_FIELD_UNCALIBRATED  (1 << ID_MAGNETIC_FIELD)
79
80 #define  ID_CHECK(x)  ((unsigned)((x) - ID_BASE) < MAX_NUM_SENSORS)
81
82 #define  SENSORS_LIST  \
83     SENSOR_(ACCELERATION,"acceleration") \
84     SENSOR_(GYROSCOPE,"gyroscope") \
85     SENSOR_(MAGNETIC_FIELD,"magnetic-field") \
86     SENSOR_(ORIENTATION,"orientation") \
87     SENSOR_(TEMPERATURE,"temperature") \
88     SENSOR_(PROXIMITY,"proximity") \
89     SENSOR_(LIGHT, "light") \
90     SENSOR_(PRESSURE, "pressure") \
91     SENSOR_(HUMIDITY, "humidity") \
92     SENSOR_(MAGNETIC_FIELD_UNCALIBRATED,"magnetic-field-uncalibrated") \
93
94 static const struct {
95     const char*  name;
96     int          id; } _sensorIds[MAX_NUM_SENSORS] =
97 {
98 #define SENSOR_(x,y)  { y, ID_##x },
99     SENSORS_LIST
100 #undef  SENSOR_
101 };
102
103 static const char*
104 _sensorIdToName( int  id )
105 {
106     int  nn;
107     for (nn = 0; nn < MAX_NUM_SENSORS; nn++)
108         if (id == _sensorIds[nn].id)
109             return _sensorIds[nn].name;
110     return "<UNKNOWN>";
111 }
112
113 static int
114 _sensorIdFromName( const char*  name )
115 {
116     int  nn;
117
118     if (name == NULL)
119         return -1;
120
121     for (nn = 0; nn < MAX_NUM_SENSORS; nn++)
122         if (!strcmp(name, _sensorIds[nn].name))
123             return _sensorIds[nn].id;
124
125     return -1;
126 }
127
128 /* return the current time in nanoseconds */
129 static int64_t now_ns(void) {
130     struct timespec  ts;
131     clock_gettime(CLOCK_MONOTONIC, &ts);
132     return (int64_t)ts.tv_sec * 1000000000 + ts.tv_nsec;
133 }
134
135 /** SENSORS POLL DEVICE
136  **
137  ** This one is used to read sensor data from the hardware.
138  ** We implement this by simply reading the data from the
139  ** emulator through the QEMUD channel.
140  **/
141
142 typedef struct SensorDevice {
143     struct sensors_poll_device_1  device;
144     sensors_event_t               sensors[MAX_NUM_SENSORS];
145     uint32_t                      pendingSensors;
146     int64_t                       timeStart;
147     int64_t                       timeOffset;
148     uint32_t                      active_sensors;
149     int                           fd;
150     pthread_mutex_t               lock;
151 } SensorDevice;
152
153 /* Grab the file descriptor to the emulator's sensors service pipe.
154  * This function returns a file descriptor on success, or -errno on
155  * failure, and assumes the SensorDevice instance's lock is held.
156  *
157  * This is needed because set_delay(), poll() and activate() can be called
158  * from different threads, and poll() is blocking.
159  *
160  * Note that the emulator's sensors service creates a new client for each
161  * connection through qemud_channel_open(), where each client has its own
162  * delay and set of activated sensors. This precludes calling
163  * qemud_channel_open() on each request, because a typical emulated system
164  * will do something like:
165  *
166  * 1) On a first thread, de-activate() all sensors first, then call poll(),
167  *    which results in the thread blocking.
168  *
169  * 2) On a second thread, slightly later, call set_delay() then activate()
170  *    to enable the acceleration sensor.
171  *
172  * The system expects this to unblock the first thread which will receive
173  * new sensor events after the activate() call in 2).
174  *
175  * This cannot work if both threads don't use the same connection.
176  *
177  * TODO(digit): This protocol is brittle, implement another control channel
178  *              for set_delay()/activate()/batch() when supporting HAL 1.3
179  */
180 static int sensor_device_get_fd_locked(SensorDevice* dev) {
181     /* Create connection to service on first call */
182     if (dev->fd < 0) {
183         dev->fd = qemud_channel_open(SENSORS_SERVICE_NAME);
184         if (dev->fd < 0) {
185             int ret = -errno;
186             E("%s: Could not open connection to service: %s", __FUNCTION__,
187                 strerror(-ret));
188             return ret;
189         }
190     }
191     return dev->fd;
192 }
193
194 /* Send a command to the sensors virtual device. |dev| is a device instance and
195  * |cmd| is a zero-terminated command string. Return 0 on success, or -errno
196  * on failure. */
197 static int sensor_device_send_command_locked(SensorDevice* dev,
198                                              const char* cmd) {
199     int fd = sensor_device_get_fd_locked(dev);
200     if (fd < 0) {
201         return fd;
202     }
203
204     int ret = 0;
205     if (qemud_channel_send(fd, cmd, strlen(cmd)) < 0) {
206         ret = -errno;
207         E("%s(fd=%d): ERROR: %s", __FUNCTION__, fd, strerror(errno));
208     }
209     return ret;
210 }
211
212 /* Pick up one pending sensor event. On success, this returns the sensor
213  * id, and sets |*event| accordingly. On failure, i.e. if there are no
214  * pending events, return -EINVAL.
215  *
216  * Note: The device's lock must be acquired.
217  */
218 static int sensor_device_pick_pending_event_locked(SensorDevice* d,
219                                                    sensors_event_t*  event)
220 {
221     uint32_t mask = SUPPORTED_SENSORS & d->pendingSensors;
222     if (mask) {
223         uint32_t i = 31 - __builtin_clz(mask);
224         d->pendingSensors &= ~(1U << i);
225         // Copy the structure
226         *event = d->sensors[i];
227
228         if (d->sensors[i].type == SENSOR_TYPE_META_DATA) {
229             // sensor_device_poll_event_locked() will leave
230             // the meta-data in place until we have it.
231             // Set |type| to something other than META_DATA
232             // so sensor_device_poll_event_locked() can
233             // continue.
234             d->sensors[i].type = SENSOR_TYPE_META_DATA + 1;
235         } else {
236             event->sensor = i;
237             event->version = sizeof(*event);
238         }
239
240         D("%s: %d [%f, %f, %f]", __FUNCTION__,
241                 i,
242                 event->data[0],
243                 event->data[1],
244                 event->data[2]);
245         return i;
246     }
247     E("No sensor to return!!! pendingSensors=0x%08x", d->pendingSensors);
248     // we may end-up in a busy loop, slow things down, just in case.
249     usleep(1000);
250     return -EINVAL;
251 }
252
253 /* Block until new sensor events are reported by the emulator, or if a
254  * 'wake' command is received through the service. On succes, return 0
255  * and updates the |pendingEvents| and |sensors| fields of |dev|.
256  * On failure, return -errno.
257  *
258  * Note: The device lock must be acquired when calling this function, and
259  *       will still be held on return. However, the function releases the
260  *       lock temporarily during the blocking wait.
261  */
262 static int sensor_device_poll_event_locked(SensorDevice* dev)
263 {
264     D("%s: dev=%p", __FUNCTION__, dev);
265
266     int fd = sensor_device_get_fd_locked(dev);
267     if (fd < 0) {
268         E("%s: Could not get pipe channel: %s", __FUNCTION__, strerror(-fd));
269         return fd;
270     }
271
272     // Accumulate pending events into |events| and |new_sensors| mask
273     // until a 'sync' or 'wake' command is received. This also simplifies the
274     // code a bit.
275     uint32_t new_sensors = 0U;
276     sensors_event_t* events = dev->sensors;
277
278     int64_t event_time = -1;
279     int ret = 0;
280
281     for (;;) {
282         /* Release the lock since we're going to block on recv() */
283         pthread_mutex_unlock(&dev->lock);
284
285         /* read the next event */
286         char buff[256];
287         int len = qemud_channel_recv(fd, buff, sizeof(buff) - 1U);
288         /* re-acquire the lock to modify the device state. */
289         pthread_mutex_lock(&dev->lock);
290
291         if (len < 0) {
292             ret = -errno;
293             E("%s(fd=%d): Could not receive event data len=%d, errno=%d: %s",
294               __FUNCTION__, fd, len, errno, strerror(errno));
295             break;
296         }
297         buff[len] = 0;
298         D("%s(fd=%d): received [%s]", __FUNCTION__, fd, buff);
299
300
301         /* "wake" is sent from the emulator to exit this loop. */
302         /* TODO(digit): Is it still needed? */
303         if (!strcmp((const char*)buff, "wake")) {
304             ret = 0x7FFFFFFF;
305             break;
306         }
307
308         float params[3];
309
310         // If the existing entry for this sensor is META_DATA,
311         // do not overwrite it. We can resume saving sensor
312         // values after that meta data has been received.
313
314         /* "acceleration:<x>:<y>:<z>" corresponds to an acceleration event */
315         if (sscanf(buff, "acceleration:%g:%g:%g", params+0, params+1, params+2)
316                 == 3) {
317             new_sensors |= SENSORS_ACCELERATION;
318             if (events[ID_ACCELERATION].type == SENSOR_TYPE_META_DATA) continue;
319             events[ID_ACCELERATION].acceleration.x = params[0];
320             events[ID_ACCELERATION].acceleration.y = params[1];
321             events[ID_ACCELERATION].acceleration.z = params[2];
322             events[ID_ACCELERATION].type = SENSOR_TYPE_ACCELEROMETER;
323             continue;
324         }
325
326         /* "gyroscope:<x>:<y>:<z>" corresponds to a gyroscope event */
327         if (sscanf(buff, "gyroscope:%g:%g:%g", params+0, params+1, params+2)
328                 == 3) {
329             new_sensors |= SENSORS_GYROSCOPE;
330             if (events[ID_GYROSCOPE].type == SENSOR_TYPE_META_DATA) continue;
331             events[ID_GYROSCOPE].gyro.x = params[0];
332             events[ID_GYROSCOPE].gyro.y = params[1];
333             events[ID_GYROSCOPE].gyro.z = params[2];
334             events[ID_GYROSCOPE].type = SENSOR_TYPE_GYROSCOPE;
335             continue;
336         }
337
338         /* "orientation:<azimuth>:<pitch>:<roll>" is sent when orientation
339          * changes */
340         if (sscanf(buff, "orientation:%g:%g:%g", params+0, params+1, params+2)
341                 == 3) {
342             new_sensors |= SENSORS_ORIENTATION;
343             if (events[ID_ORIENTATION].type == SENSOR_TYPE_META_DATA) continue;
344             events[ID_ORIENTATION].orientation.azimuth = params[0];
345             events[ID_ORIENTATION].orientation.pitch   = params[1];
346             events[ID_ORIENTATION].orientation.roll    = params[2];
347             events[ID_ORIENTATION].orientation.status  =
348                     SENSOR_STATUS_ACCURACY_HIGH;
349             events[ID_ORIENTATION].type = SENSOR_TYPE_ORIENTATION;
350             continue;
351         }
352
353         /* "magnetic:<x>:<y>:<z>" is sent for the params of the magnetic
354          * field */
355         if (sscanf(buff, "magnetic:%g:%g:%g", params+0, params+1, params+2)
356                 == 3) {
357             new_sensors |= SENSORS_MAGNETIC_FIELD;
358             if (events[ID_MAGNETIC_FIELD].type == SENSOR_TYPE_META_DATA) continue;
359             events[ID_MAGNETIC_FIELD].magnetic.x = params[0];
360             events[ID_MAGNETIC_FIELD].magnetic.y = params[1];
361             events[ID_MAGNETIC_FIELD].magnetic.z = params[2];
362             events[ID_MAGNETIC_FIELD].magnetic.status =
363                     SENSOR_STATUS_ACCURACY_HIGH;
364             events[ID_MAGNETIC_FIELD].type = SENSOR_TYPE_MAGNETIC_FIELD;
365             continue;
366         }
367
368         if (sscanf(buff, "magnetic-uncalibrated:%g:%g:%g", params+0, params+1, params+2)
369                 == 3) {
370             new_sensors |= SENSORS_MAGNETIC_FIELD_UNCALIBRATED;
371             if (events[ID_MAGNETIC_FIELD_UNCALIBRATED].type == SENSOR_TYPE_META_DATA) continue;
372             events[ID_MAGNETIC_FIELD_UNCALIBRATED].magnetic.x = params[0];
373             events[ID_MAGNETIC_FIELD_UNCALIBRATED].magnetic.y = params[1];
374             events[ID_MAGNETIC_FIELD_UNCALIBRATED].magnetic.z = params[2];
375             events[ID_MAGNETIC_FIELD_UNCALIBRATED].magnetic.status =
376                     SENSOR_STATUS_ACCURACY_HIGH;
377             events[ID_MAGNETIC_FIELD_UNCALIBRATED].type = SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED;
378             continue;
379         }
380
381         /* "temperature:<celsius>" */
382         if (sscanf(buff, "temperature:%g", params+0) == 1) {
383             new_sensors |= SENSORS_TEMPERATURE;
384             if (events[ID_TEMPERATURE].type == SENSOR_TYPE_META_DATA) continue;
385             events[ID_TEMPERATURE].temperature = params[0];
386             events[ID_TEMPERATURE].type = SENSOR_TYPE_AMBIENT_TEMPERATURE;
387             continue;
388         }
389
390         /* "proximity:<value>" */
391         if (sscanf(buff, "proximity:%g", params+0) == 1) {
392             new_sensors |= SENSORS_PROXIMITY;
393             if (events[ID_PROXIMITY].type == SENSOR_TYPE_META_DATA) continue;
394             events[ID_PROXIMITY].distance = params[0];
395             events[ID_PROXIMITY].type = SENSOR_TYPE_PROXIMITY;
396             continue;
397         }
398         /* "light:<lux>" */
399         if (sscanf(buff, "light:%g", params+0) == 1) {
400             new_sensors |= SENSORS_LIGHT;
401             if (events[ID_LIGHT].type == SENSOR_TYPE_META_DATA) continue;
402             events[ID_LIGHT].light = params[0];
403             events[ID_LIGHT].type = SENSOR_TYPE_LIGHT;
404             continue;
405         }
406
407         /* "pressure:<hpa>" */
408         if (sscanf(buff, "pressure:%g", params+0) == 1) {
409             new_sensors |= SENSORS_PRESSURE;
410             if (events[ID_PRESSURE].type == SENSOR_TYPE_META_DATA) continue;
411             events[ID_PRESSURE].pressure = params[0];
412             events[ID_PRESSURE].type = SENSOR_TYPE_PRESSURE;
413             continue;
414         }
415
416         /* "humidity:<percent>" */
417         if (sscanf(buff, "humidity:%g", params+0) == 1) {
418             new_sensors |= SENSORS_HUMIDITY;
419             if (events[ID_HUMIDITY].type == SENSOR_TYPE_META_DATA) continue;
420             events[ID_HUMIDITY].relative_humidity = params[0];
421             events[ID_HUMIDITY].type = SENSOR_TYPE_RELATIVE_HUMIDITY;
422             continue;
423         }
424
425         /* "sync:<time>" is sent after a series of sensor events.
426          * where 'time' is expressed in micro-seconds and corresponds
427          * to the VM time when the real poll occured.
428          */
429         if (sscanf(buff, "sync:%lld", &event_time) == 1) {
430             if (new_sensors) {
431                 goto out;
432             }
433             D("huh ? sync without any sensor data ?");
434             continue;
435         }
436         D("huh ? unsupported command");
437     }
438 out:
439     if (new_sensors) {
440         /* update the time of each new sensor event. */
441         dev->pendingSensors |= new_sensors;
442         int64_t t = (event_time < 0) ? 0 : event_time * 1000LL;
443
444         /* Use the time at the first "sync:" as the base for later
445          * time values.
446          * CTS tests require sensors to return an event timestamp (sync) that is
447          * strictly before the time of the event arrival. We don't actually have
448          * a time syncronization protocol here, and the only data point is the
449          * "sync:" timestamp - which is an emulator's timestamp of a clock that
450          * is synced with the guest clock, and it only the timestamp after all
451          * events were sent.
452          * To make it work, let's compare the calculated timestamp with current
453          * time and take the lower value - we don't believe in events from the
454          * future anyway.
455          */
456         const int64_t now = now_ns();
457
458         if (dev->timeStart == 0) {
459             dev->timeStart  = now;
460             dev->timeOffset = dev->timeStart - t;
461         }
462         t += dev->timeOffset;
463         if (t > now) {
464             t = now;
465         }
466
467         while (new_sensors) {
468             uint32_t i = 31 - __builtin_clz(new_sensors);
469             new_sensors &= ~(1U << i);
470             dev->sensors[i].timestamp = t;
471         }
472     }
473     return ret;
474 }
475
476 /** SENSORS POLL DEVICE FUNCTIONS **/
477
478 static int sensor_device_close(struct hw_device_t* dev0)
479 {
480     SensorDevice* dev = (void*)dev0;
481     // Assume that there are no other threads blocked on poll()
482     if (dev->fd >= 0) {
483         close(dev->fd);
484         dev->fd = -1;
485     }
486     pthread_mutex_destroy(&dev->lock);
487     free(dev);
488     return 0;
489 }
490
491 /* Return an array of sensor data. This function blocks until there is sensor
492  * related events to report. On success, it will write the events into the
493  * |data| array, which contains |count| items. The function returns the number
494  * of events written into the array, which shall never be greater than |count|.
495  * On error, return -errno code.
496  *
497  * Note that according to the sensor HAL [1], it shall never return 0!
498  *
499  * [1] http://source.android.com/devices/sensors/hal-interface.html
500  */
501 static int sensor_device_poll(struct sensors_poll_device_t *dev0,
502                               sensors_event_t* data, int count)
503 {
504     SensorDevice* dev = (void*)dev0;
505     D("%s: dev=%p data=%p count=%d ", __FUNCTION__, dev, data, count);
506
507     if (count <= 0) {
508         return -EINVAL;
509     }
510
511     int result = 0;
512     pthread_mutex_lock(&dev->lock);
513     if (!dev->pendingSensors) {
514         /* Block until there are pending events. Note that this releases
515          * the lock during the blocking call, then re-acquires it before
516          * returning. */
517         int ret = sensor_device_poll_event_locked(dev);
518         if (ret < 0) {
519             result = ret;
520             goto out;
521         }
522         if (!dev->pendingSensors) {
523             /* 'wake' event received before any sensor data. */
524             result = -EIO;
525             goto out;
526         }
527     }
528     /* Now read as many pending events as needed. */
529     int i;
530     for (i = 0; i < count; i++)  {
531         if (!dev->pendingSensors) {
532             break;
533         }
534         int ret = sensor_device_pick_pending_event_locked(dev, data);
535         if (ret < 0) {
536             if (!result) {
537                 result = ret;
538             }
539             break;
540         }
541         data++;
542         result++;
543     }
544 out:
545     pthread_mutex_unlock(&dev->lock);
546     D("%s: result=%d", __FUNCTION__, result);
547     return result;
548 }
549
550 static int sensor_device_activate(struct sensors_poll_device_t *dev0,
551                                   int handle,
552                                   int enabled)
553 {
554     SensorDevice* dev = (void*)dev0;
555
556     D("%s: handle=%s (%d) enabled=%d", __FUNCTION__,
557         _sensorIdToName(handle), handle, enabled);
558
559     /* Sanity check */
560     if (!ID_CHECK(handle)) {
561         E("%s: bad handle ID", __FUNCTION__);
562         return -EINVAL;
563     }
564
565     /* Exit early if sensor is already enabled/disabled. */
566     uint32_t mask = (1U << handle);
567     uint32_t sensors = enabled ? mask : 0;
568
569     pthread_mutex_lock(&dev->lock);
570
571     uint32_t active = dev->active_sensors;
572     uint32_t new_sensors = (active & ~mask) | (sensors & mask);
573     uint32_t changed = active ^ new_sensors;
574
575     int ret = 0;
576     if (changed) {
577         /* Send command to the emulator. */
578         char command[64];
579         snprintf(command,
580                  sizeof command,
581                  "set:%s:%d",
582                  _sensorIdToName(handle),
583                  enabled != 0);
584
585         ret = sensor_device_send_command_locked(dev, command);
586         if (ret < 0) {
587             E("%s: when sending command errno=%d: %s", __FUNCTION__, -ret,
588               strerror(-ret));
589         } else {
590             dev->active_sensors = new_sensors;
591         }
592     }
593     pthread_mutex_unlock(&dev->lock);
594     return ret;
595 }
596
597 static int sensor_device_default_flush(
598         struct sensors_poll_device_1* dev0,
599         int handle) {
600
601     SensorDevice* dev = (void*)dev0;
602
603     D("%s: handle=%s (%d)", __FUNCTION__,
604         _sensorIdToName(handle), handle);
605
606     /* Sanity check */
607     if (!ID_CHECK(handle)) {
608         E("%s: bad handle ID", __FUNCTION__);
609         return -EINVAL;
610     }
611
612     pthread_mutex_lock(&dev->lock);
613     dev->sensors[handle].version = META_DATA_VERSION;
614     dev->sensors[handle].type = SENSOR_TYPE_META_DATA;
615     dev->sensors[handle].sensor = 0;
616     dev->sensors[handle].timestamp = 0;
617     dev->sensors[handle].meta_data.sensor = handle;
618     dev->sensors[handle].meta_data.what = META_DATA_FLUSH_COMPLETE;
619     dev->pendingSensors |= (1U << handle);
620     pthread_mutex_unlock(&dev->lock);
621
622     return 0;
623 }
624
625 static int sensor_device_set_delay(struct sensors_poll_device_t *dev0,
626                                    int handle __unused,
627                                    int64_t ns)
628 {
629     SensorDevice* dev = (void*)dev0;
630
631     int ms = (int)(ns / 1000000);
632     D("%s: dev=%p delay-ms=%d", __FUNCTION__, dev, ms);
633
634     char command[64];
635     snprintf(command, sizeof command, "set-delay:%d", ms);
636
637     pthread_mutex_lock(&dev->lock);
638     int ret = sensor_device_send_command_locked(dev, command);
639     pthread_mutex_unlock(&dev->lock);
640     if (ret < 0) {
641         E("%s: Could not send command: %s", __FUNCTION__, strerror(-ret));
642     }
643     return ret;
644 }
645
646 static int sensor_device_default_batch(
647      struct sensors_poll_device_1* dev,
648      int sensor_handle,
649      int flags,
650      int64_t sampling_period_ns,
651      int64_t max_report_latency_ns) {
652     return sensor_device_set_delay(dev, sensor_handle, sampling_period_ns);
653 }
654
655 /** MODULE REGISTRATION SUPPORT
656  **
657  ** This is required so that hardware/libhardware/hardware.c
658  ** will dlopen() this library appropriately.
659  **/
660
661 /*
662  * the following is the list of all supported sensors.
663  * this table is used to build sSensorList declared below
664  * according to which hardware sensors are reported as
665  * available from the emulator (see get_sensors_list below)
666  *
667  * note: numerical values for maxRange/resolution/power for
668  *       all sensors but light, pressure and humidity were
669  *       taken from the reference AK8976A implementation
670  */
671 static const struct sensor_t sSensorListInit[] = {
672         { .name       = "Goldfish 3-axis Accelerometer",
673           .vendor     = "The Android Open Source Project",
674           .version    = 1,
675           .handle     = ID_ACCELERATION,
676           .type       = SENSOR_TYPE_ACCELEROMETER,
677           .maxRange   = 2.8f,
678           .resolution = 1.0f/4032.0f,
679           .power      = 3.0f,
680           .minDelay   = 10000,
681           .maxDelay   = 60 * 1000 * 1000,
682           .fifoReservedEventCount = 0,
683           .fifoMaxEventCount =   0,
684           .stringType =         0,
685           .requiredPermission = 0,
686           .flags = SENSOR_FLAG_CONTINUOUS_MODE,
687           .reserved   = {}
688         },
689
690         { .name       = "Goldfish 3-axis Gyroscope",
691           .vendor     = "The Android Open Source Project",
692           .version    = 1,
693           .handle     = ID_GYROSCOPE,
694           .type       = SENSOR_TYPE_GYROSCOPE,
695           .maxRange   = 11.1111111,
696           .resolution = 1.0f/1000.0f,
697           .power      = 3.0f,
698           .minDelay   = 10000,
699           .maxDelay   = 60 * 1000 * 1000,
700           .reserved   = {}
701         },
702
703         { .name       = "Goldfish 3-axis Magnetic field sensor",
704           .vendor     = "The Android Open Source Project",
705           .version    = 1,
706           .handle     = ID_MAGNETIC_FIELD,
707           .type       = SENSOR_TYPE_MAGNETIC_FIELD,
708           .maxRange   = 2000.0f,
709           .resolution = 1.0f,
710           .power      = 6.7f,
711           .minDelay   = 10000,
712           .maxDelay   = 60 * 1000 * 1000,
713           .fifoReservedEventCount = 0,
714           .fifoMaxEventCount =   0,
715           .stringType =         0,
716           .requiredPermission = 0,
717           .flags = SENSOR_FLAG_CONTINUOUS_MODE,
718           .reserved   = {}
719         },
720
721         { .name       = "Goldfish Orientation sensor",
722           .vendor     = "The Android Open Source Project",
723           .version    = 1,
724           .handle     = ID_ORIENTATION,
725           .type       = SENSOR_TYPE_ORIENTATION,
726           .maxRange   = 360.0f,
727           .resolution = 1.0f,
728           .power      = 9.7f,
729           .minDelay   = 10000,
730           .maxDelay   = 60 * 1000 * 1000,
731           .fifoReservedEventCount = 0,
732           .fifoMaxEventCount =   0,
733           .stringType =         0,
734           .requiredPermission = 0,
735           .flags = SENSOR_FLAG_CONTINUOUS_MODE,
736           .reserved   = {}
737         },
738
739         { .name       = "Goldfish Temperature sensor",
740           .vendor     = "The Android Open Source Project",
741           .version    = 1,
742           .handle     = ID_TEMPERATURE,
743           .type       = SENSOR_TYPE_AMBIENT_TEMPERATURE,
744           .maxRange   = 80.0f,
745           .resolution = 1.0f,
746           .power      = 0.0f,
747           .minDelay   = 10000,
748           .maxDelay   = 60 * 1000 * 1000,
749           .fifoReservedEventCount = 0,
750           .fifoMaxEventCount =   0,
751           .stringType =         0,
752           .requiredPermission = 0,
753           .flags = SENSOR_FLAG_CONTINUOUS_MODE,
754           .reserved   = {}
755         },
756
757         { .name       = "Goldfish Proximity sensor",
758           .vendor     = "The Android Open Source Project",
759           .version    = 1,
760           .handle     = ID_PROXIMITY,
761           .type       = SENSOR_TYPE_PROXIMITY,
762           .maxRange   = 1.0f,
763           .resolution = 1.0f,
764           .power      = 20.0f,
765           .minDelay   = 10000,
766           .maxDelay   = 60 * 1000 * 1000,
767           .fifoReservedEventCount = 0,
768           .fifoMaxEventCount =   0,
769           .stringType =         0,
770           .requiredPermission = 0,
771           .flags = SENSOR_FLAG_WAKE_UP | SENSOR_FLAG_ON_CHANGE_MODE,
772           .reserved   = {}
773         },
774
775         { .name       = "Goldfish Light sensor",
776           .vendor     = "The Android Open Source Project",
777           .version    = 1,
778           .handle     = ID_LIGHT,
779           .type       = SENSOR_TYPE_LIGHT,
780           .maxRange   = 40000.0f,
781           .resolution = 1.0f,
782           .power      = 20.0f,
783           .minDelay   = 10000,
784           .maxDelay   = 60 * 1000 * 1000,
785           .fifoReservedEventCount = 0,
786           .fifoMaxEventCount =   0,
787           .stringType =         0,
788           .requiredPermission = 0,
789           .flags = SENSOR_FLAG_ON_CHANGE_MODE,
790           .reserved   = {}
791         },
792
793         { .name       = "Goldfish Pressure sensor",
794           .vendor     = "The Android Open Source Project",
795           .version    = 1,
796           .handle     = ID_PRESSURE,
797           .type       = SENSOR_TYPE_PRESSURE,
798           .maxRange   = 800.0f,
799           .resolution = 1.0f,
800           .power      = 20.0f,
801           .minDelay   = 10000,
802           .maxDelay   = 60 * 1000 * 1000,
803           .fifoReservedEventCount = 0,
804           .fifoMaxEventCount =   0,
805           .stringType =         0,
806           .requiredPermission = 0,
807           .flags = SENSOR_FLAG_CONTINUOUS_MODE,
808           .reserved   = {}
809         },
810
811         { .name       = "Goldfish Humidity sensor",
812           .vendor     = "The Android Open Source Project",
813           .version    = 1,
814           .handle     = ID_HUMIDITY,
815           .type       = SENSOR_TYPE_RELATIVE_HUMIDITY,
816           .maxRange   = 100.0f,
817           .resolution = 1.0f,
818           .power      = 20.0f,
819           .minDelay   = 10000,
820           .maxDelay   = 60 * 1000 * 1000,
821           .fifoReservedEventCount = 0,
822           .fifoMaxEventCount =   0,
823           .stringType =         0,
824           .requiredPermission = 0,
825           .flags = SENSOR_FLAG_CONTINUOUS_MODE,
826           .reserved   = {}
827         },
828
829         { .name       = "Goldfish 3-axis Magnetic field sensor (uncalibrated)",
830           .vendor     = "The Android Open Source Project",
831           .version    = 1,
832           .handle     = ID_MAGNETIC_FIELD_UNCALIBRATED,
833           .type       = SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED,
834           .maxRange   = 2000.0f,
835           .resolution = 1.0f,
836           .power      = 6.7f,
837           .minDelay   = 10000,
838           .maxDelay   = 60 * 1000 * 1000,
839           .reserved   = {}
840         },
841 };
842
843 static struct sensor_t  sSensorList[MAX_NUM_SENSORS];
844
845 static int sensors__get_sensors_list(struct sensors_module_t* module __unused,
846         struct sensor_t const** list)
847 {
848     int  fd = qemud_channel_open(SENSORS_SERVICE_NAME);
849     char buffer[12];
850     int  mask, nn, count;
851     int  ret = 0;
852
853     if (fd < 0) {
854         E("%s: no qemud connection", __FUNCTION__);
855         goto out;
856     }
857     ret = qemud_channel_send(fd, "list-sensors", -1);
858     if (ret < 0) {
859         E("%s: could not query sensor list: %s", __FUNCTION__,
860           strerror(errno));
861         goto out;
862     }
863     ret = qemud_channel_recv(fd, buffer, sizeof buffer-1);
864     if (ret < 0) {
865         E("%s: could not receive sensor list: %s", __FUNCTION__,
866           strerror(errno));
867         goto out;
868     }
869     buffer[ret] = 0;
870
871     /* the result is a integer used as a mask for available sensors */
872     mask  = atoi(buffer);
873     count = 0;
874     for (nn = 0; nn < MAX_NUM_SENSORS; nn++) {
875         if (((1 << nn) & mask) == 0)
876             continue;
877         sSensorList[count++] = sSensorListInit[nn];
878     }
879     D("%s: returned %d sensors (mask=%d)", __FUNCTION__, count, mask);
880     *list = sSensorList;
881
882     ret = count;
883 out:
884     if (fd >= 0) {
885         close(fd);
886     }
887     return ret;
888 }
889
890
891 static int
892 open_sensors(const struct hw_module_t* module,
893              const char*               name,
894              struct hw_device_t*      *device)
895 {
896     int  status = -EINVAL;
897
898     D("%s: name=%s", __FUNCTION__, name);
899
900     if (!strcmp(name, SENSORS_HARDWARE_POLL)) {
901         SensorDevice *dev = malloc(sizeof(*dev));
902
903         memset(dev, 0, sizeof(*dev));
904
905         dev->device.common.tag     = HARDWARE_DEVICE_TAG;
906         dev->device.common.version = SENSORS_DEVICE_API_VERSION_1_3;
907         dev->device.common.module  = (struct hw_module_t*) module;
908         dev->device.common.close   = sensor_device_close;
909         dev->device.poll           = sensor_device_poll;
910         dev->device.activate       = sensor_device_activate;
911         dev->device.setDelay       = sensor_device_set_delay;
912
913         // (dev->sensors[i].type == SENSOR_TYPE_META_DATA) is
914         // sticky. Don't start off with that setting.
915         for (int idx = 0; idx < MAX_NUM_SENSORS; idx++) {
916             dev->sensors[idx].type = SENSOR_TYPE_META_DATA + 1;
917         }
918
919         // Version 1.3-specific functions
920         dev->device.batch       = sensor_device_default_batch;
921         dev->device.flush       = sensor_device_default_flush;
922
923         dev->fd = -1;
924         pthread_mutex_init(&dev->lock, NULL);
925
926         *device = &dev->device.common;
927         status  = 0;
928     }
929     return status;
930 }
931
932
933 static struct hw_module_methods_t sensors_module_methods = {
934     .open = open_sensors
935 };
936
937 struct sensors_module_t HAL_MODULE_INFO_SYM = {
938     .common = {
939         .tag = HARDWARE_MODULE_TAG,
940         .version_major = 1,
941         .version_minor = 3,
942         .id = SENSORS_HARDWARE_MODULE_ID,
943         .name = "Goldfish SENSORS Module",
944         .author = "The Android Open Source Project",
945         .methods = &sensors_module_methods,
946     },
947     .get_sensors_list = sensors__get_sensors_list
948 };