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 #define  SENSORS_SERVICE_NAME "sensors"
26 
27 #define LOG_TAG "Dummy_Sensors"
28 
29 #include <unistd.h>
30 #include <fcntl.h>
31 #include <errno.h>
32 #include <string.h>
33 #include <log/log.h>
34 #include <cutils/sockets.h>
35 #include <hardware/sensors.h>
36 #include <pthread.h>
37 
38 #if 0
39 #define  D(...)  ALOGD(__VA_ARGS__)
40 #else
41 #define  D(...)  ((void)0)
42 #endif
43 
44 #define  E(...)  ALOGE(__VA_ARGS__)
45 
46 /** SENSOR IDS AND NAMES
47  **/
48 
49 #define MAX_NUM_SENSORS 8
50 
51 #define SUPPORTED_SENSORS  ((1<<MAX_NUM_SENSORS)-1)
52 
53 #define  ID_BASE           SENSORS_HANDLE_BASE
54 #define  ID_ACCELERATION   (ID_BASE+0)
55 #define  ID_MAGNETIC_FIELD (ID_BASE+1)
56 #define  ID_ORIENTATION    (ID_BASE+2)
57 #define  ID_TEMPERATURE    (ID_BASE+3)
58 #define  ID_PROXIMITY      (ID_BASE+4)
59 #define  ID_LIGHT          (ID_BASE+5)
60 #define  ID_PRESSURE       (ID_BASE+6)
61 #define  ID_HUMIDITY       (ID_BASE+7)
62 
63 #define  SENSORS_ACCELERATION    (1 << ID_ACCELERATION)
64 #define  SENSORS_MAGNETIC_FIELD  (1 << ID_MAGNETIC_FIELD)
65 #define  SENSORS_ORIENTATION     (1 << ID_ORIENTATION)
66 #define  SENSORS_TEMPERATURE     (1 << ID_TEMPERATURE)
67 #define  SENSORS_PROXIMITY       (1 << ID_PROXIMITY)
68 #define  SENSORS_LIGHT           (1 << ID_LIGHT)
69 #define  SENSORS_PRESSURE        (1 << ID_PRESSURE)
70 #define  SENSORS_HUMIDITY        (1 << ID_HUMIDITY)
71 
72 #define  ID_CHECK(x)  ((unsigned)((x) - ID_BASE) < MAX_NUM_SENSORS)
73 
74 #define  SENSORS_LIST  \
75     SENSOR_(ACCELERATION,"acceleration") \
76     SENSOR_(MAGNETIC_FIELD,"magnetic-field") \
77     SENSOR_(ORIENTATION,"orientation") \
78     SENSOR_(TEMPERATURE,"temperature") \
79     SENSOR_(PROXIMITY,"proximity") \
80     SENSOR_(LIGHT, "light") \
81     SENSOR_(PRESSURE, "pressure") \
82     SENSOR_(HUMIDITY, "humidity")
83 
84 static const struct {
85     const char*  name;
86     int          id; } _sensorIds[MAX_NUM_SENSORS] =
87 {
88 #define SENSOR_(x,y)  { y, ID_##x },
89     SENSORS_LIST
90 #undef  SENSOR_
91 };
92 
93 static const char*
_sensorIdToName(int id)94 _sensorIdToName( int  id )
95 {
96     int  nn;
97     for (nn = 0; nn < MAX_NUM_SENSORS; nn++)
98         if (id == _sensorIds[nn].id)
99             return _sensorIds[nn].name;
100     return "<UNKNOWN>";
101 }
102 
103 static int
_sensorIdFromName(const char * name)104 _sensorIdFromName( const char*  name )
105 {
106     int  nn;
107 
108     if (name == NULL)
109         return -1;
110 
111     for (nn = 0; nn < MAX_NUM_SENSORS; nn++)
112         if (!strcmp(name, _sensorIds[nn].name))
113             return _sensorIds[nn].id;
114 
115     return -1;
116 }
117 
118 /* return the current time in nanoseconds */
now_ns(void)119 static int64_t now_ns(void) {
120     struct timespec  ts;
121     clock_gettime(CLOCK_MONOTONIC, &ts);
122     return (int64_t)ts.tv_sec * 1000000000 + ts.tv_nsec;
123 }
124 
125 /** SENSORS POLL DEVICE
126  **
127  ** This one is used to read sensor data from the hardware.
128  ** We implement this by simply reading the data from the
129  ** emulator through the QEMUD channel.
130  **/
131 
132 typedef struct SensorDevice {
133     struct sensors_poll_device_1  device;
134     sensors_event_t               sensors[MAX_NUM_SENSORS];
135     uint32_t                      pendingSensors;
136     int64_t                       timeStart;
137     int64_t                       timeOffset;
138     uint32_t                      active_sensors;
139     int                           fd;
140     pthread_mutex_t               lock;
141 } SensorDevice;
142 
143 /* Grab the file descriptor to the emulator's sensors service pipe.
144  * This function returns a file descriptor on success, or -errno on
145  * failure, and assumes the SensorDevice instance's lock is held.
146  *
147  * This is needed because set_delay(), poll() and activate() can be called
148  * from different threads, and poll() is blocking.
149  *
150  * 1) On a first thread, de-activate() all sensors first, then call poll(),
151  *    which results in the thread blocking.
152  *
153  * 2) On a second thread, slightly later, call set_delay() then activate()
154  *    to enable the acceleration sensor.
155  *
156  * The system expects this to unblock the first thread which will receive
157  * new sensor events after the activate() call in 2).
158  *
159  * This cannot work if both threads don't use the same connection.
160  *
161  * TODO(digit): This protocol is brittle, implement another control channel
162  *              for set_delay()/activate()/batch() when supporting HAL 1.3
163  */
sensor_device_get_fd_locked(SensorDevice * dev)164 static int sensor_device_get_fd_locked(SensorDevice* dev) {
165     /* Create connection to service on first call */
166     if (dev->fd < 0) {
167 	    int ret = -errno;
168 	    E("%s: Could not open connection to service: %s", __FUNCTION__,
169 	    		    strerror(-ret));
170 	    return ret;
171     }
172     return dev->fd;
173 }
174 
175 /* Pick up one pending sensor event. On success, this returns the sensor
176  * id, and sets |*event| accordingly. On failure, i.e. if there are no
177  * pending events, return -EINVAL.
178  *
179  * Note: The device's lock must be acquired.
180  */
sensor_device_pick_pending_event_locked(SensorDevice * d,sensors_event_t * event)181 static int sensor_device_pick_pending_event_locked(SensorDevice* d,
182                                                    sensors_event_t*  event)
183 {
184     uint32_t mask = SUPPORTED_SENSORS & d->pendingSensors;
185 
186     if (mask) {
187         uint32_t i = 31 - __builtin_clz(mask);
188 
189 	pthread_mutex_lock(&d->lock);
190         d->pendingSensors &= ~(1U << i);
191         *event = d->sensors[i];
192         event->sensor = i;
193         event->version = sizeof(*event);
194 	pthread_mutex_unlock(&d->lock);
195         D("%s: %d [%f, %f, %f]", __FUNCTION__,
196                 i,
197                 event->data[0],
198                 event->data[1],
199                 event->data[2]);
200         return i;
201     }
202     E("No sensor to return!!! pendingSensors=0x%08x", d->pendingSensors);
203     // we may end-up in a busy loop, slow things down, just in case.
204     usleep(1000);
205     return -EINVAL;
206 }
207 
sensor_device_close(struct hw_device_t * dev0)208 static int sensor_device_close(struct hw_device_t* dev0)
209 {
210     SensorDevice* dev = (void*)dev0;
211     // Assume that there are no other threads blocked on poll()
212     if (dev->fd >= 0) {
213         close(dev->fd);
214         dev->fd = -1;
215     }
216     pthread_mutex_destroy(&dev->lock);
217     free(dev);
218     return 0;
219 }
220 
221 /* Return an array of sensor data. This function blocks until there is sensor
222  * related events to report. On success, it will write the events into the
223  * |data| array, which contains |count| items. The function returns the number
224  * of events written into the array, which shall never be greater than |count|.
225  * On error, return -errno code.
226  *
227  * Note that according to the sensor HAL [1], it shall never return 0!
228  *
229  * [1] http://source.android.com/devices/sensors/hal-interface.html
230  */
sensor_device_poll(struct sensors_poll_device_t * dev0,sensors_event_t * data,int count)231 static int sensor_device_poll(struct sensors_poll_device_t *dev0,
232                               sensors_event_t* data, int count)
233 {
234     return -EIO;
235 }
236 
sensor_device_activate(struct sensors_poll_device_t * dev0,int handle,int enabled)237 static int sensor_device_activate(struct sensors_poll_device_t *dev0,
238                                   int handle,
239                                   int enabled)
240 {
241     SensorDevice* dev = (void*)dev0;
242 
243     D("%s: handle=%s (%d) enabled=%d", __FUNCTION__,
244         _sensorIdToName(handle), handle, enabled);
245 
246     /* Sanity check */
247     if (!ID_CHECK(handle)) {
248         E("%s: bad handle ID", __FUNCTION__);
249         return -EINVAL;
250     }
251 
252     /* Exit early if sensor is already enabled/disabled. */
253     uint32_t mask = (1U << handle);
254     uint32_t sensors = enabled ? mask : 0;
255 
256     pthread_mutex_lock(&dev->lock);
257 
258     uint32_t active = dev->active_sensors;
259     uint32_t new_sensors = (active & ~mask) | (sensors & mask);
260     uint32_t changed = active ^ new_sensors;
261 
262     if (changed)
263 	    dev->active_sensors = new_sensors;
264 
265     pthread_mutex_unlock(&dev->lock);
266     return 0;
267 }
268 
sensor_device_default_flush(struct sensors_poll_device_1 * dev0,int handle)269 static int sensor_device_default_flush(
270         struct sensors_poll_device_1* dev0,
271         int handle) {
272 
273     SensorDevice* dev = (void*)dev0;
274 
275     D("%s: handle=%s (%d)", __FUNCTION__,
276         _sensorIdToName(handle), handle);
277 
278     /* Sanity check */
279     if (!ID_CHECK(handle)) {
280         E("%s: bad handle ID", __FUNCTION__);
281         return -EINVAL;
282     }
283 
284     pthread_mutex_lock(&dev->lock);
285     dev->sensors[handle].version = META_DATA_VERSION;
286     dev->sensors[handle].type = SENSOR_TYPE_META_DATA;
287     dev->sensors[handle].sensor = 0;
288     dev->sensors[handle].timestamp = 0;
289     dev->sensors[handle].meta_data.what = META_DATA_FLUSH_COMPLETE;
290     dev->pendingSensors |= (1U << handle);
291     pthread_mutex_unlock(&dev->lock);
292 
293     return 0;
294 }
295 
sensor_device_set_delay(struct sensors_poll_device_t * dev0,int handle __unused,int64_t ns)296 static int sensor_device_set_delay(struct sensors_poll_device_t *dev0,
297                                    int handle __unused,
298                                    int64_t ns)
299 {
300     return 0;
301 }
302 
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)303 static int sensor_device_default_batch(
304      struct sensors_poll_device_1* dev,
305      int sensor_handle,
306      int flags,
307      int64_t sampling_period_ns,
308      int64_t max_report_latency_ns) {
309     return sensor_device_set_delay(dev, sensor_handle, sampling_period_ns);
310 }
311 
312 /** MODULE REGISTRATION SUPPORT
313  **
314  ** This is required so that hardware/libhardware/hardware.c
315  ** will dlopen() this library appropriately.
316  **/
317 
318 /*
319  * the following is the list of all supported sensors.
320  * this table is used to build sSensorList declared below
321  * according to which hardware sensors are reported as
322  * available from the emulator (see get_sensors_list below)
323  *
324  * note: numerical values for maxRange/resolution/power for
325  *       all sensors but light, pressure and humidity were
326  *       taken from the reference AK8976A implementation
327  */
328 static const struct sensor_t sSensorListInit[] = {
329         { .name       = "Accelerometer",
330           .vendor     = "The Android Open Source Project",
331           .version    = 1,
332           .handle     = ID_ACCELERATION,
333           .type       = SENSOR_TYPE_ACCELEROMETER,
334           .maxRange   = 2.8f,
335           .resolution = 1.0f/4032.0f,
336           .power      = 3.0f,
337           .minDelay   = 10000,
338           .maxDelay   = 60 * 1000 * 1000,
339           .fifoReservedEventCount = 0,
340           .fifoMaxEventCount =   0,
341           .stringType =         0,
342           .requiredPermission = 0,
343           .flags = SENSOR_FLAG_CONTINUOUS_MODE,
344           .reserved   = {}
345         },
346 };
347 
348 static struct sensor_t  sSensorList[1];
349 
sensors__get_sensors_list(struct sensors_module_t * module __unused,struct sensor_t const ** list)350 static int sensors__get_sensors_list(struct sensors_module_t* module __unused,
351         struct sensor_t const** list)
352 {
353     *list = sSensorList;
354 
355     return 0;
356 }
357 
358 static int
open_sensors(const struct hw_module_t * module,const char * name,struct hw_device_t ** device)359 open_sensors(const struct hw_module_t* module,
360              const char*               name,
361              struct hw_device_t*      *device)
362 {
363     int  status = -EINVAL;
364 
365     D("%s: name=%s", __FUNCTION__, name);
366 
367     if (!strcmp(name, SENSORS_HARDWARE_POLL)) {
368         SensorDevice *dev = malloc(sizeof(*dev));
369 
370         memset(dev, 0, sizeof(*dev));
371 
372         dev->device.common.tag     = HARDWARE_DEVICE_TAG;
373         dev->device.common.version = SENSORS_DEVICE_API_VERSION_1_3;
374         dev->device.common.module  = (struct hw_module_t*) module;
375         dev->device.common.close   = sensor_device_close;
376         dev->device.poll           = sensor_device_poll;
377         dev->device.activate       = sensor_device_activate;
378         dev->device.setDelay       = sensor_device_set_delay;
379 
380         // Version 1.3-specific functions
381         dev->device.batch       = sensor_device_default_batch;
382         dev->device.flush       = sensor_device_default_flush;
383 
384         dev->fd = -1;
385         pthread_mutex_init(&dev->lock, NULL);
386 
387         *device = &dev->device.common;
388         status  = 0;
389     }
390     return status;
391 }
392 
393 
394 static struct hw_module_methods_t sensors_module_methods = {
395     .open = open_sensors
396 };
397 
398 struct sensors_module_t HAL_MODULE_INFO_SYM = {
399     .common = {
400         .tag = HARDWARE_MODULE_TAG,
401         .version_major = 1,
402         .version_minor = 0,
403         .id = SENSORS_HARDWARE_MODULE_ID,
404         .name = "Dummy SENSORS Module",
405         .author = "The Android Open Source Project",
406         .methods = &sensors_module_methods,
407     },
408     .get_sensors_list = sensors__get_sensors_list
409 };
410