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