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