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 <hardware/qemud.h> 49 50 /** SENSOR IDS AND NAMES 51 **/ 52 53 #define MAX_NUM_SENSORS 5 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 64 #define SENSORS_ACCELERATION (1 << ID_ACCELERATION) 65 #define SENSORS_MAGNETIC_FIELD (1 << ID_MAGNETIC_FIELD) 66 #define SENSORS_ORIENTATION (1 << ID_ORIENTATION) 67 #define SENSORS_TEMPERATURE (1 << ID_TEMPERATURE) 68 #define SENSORS_PROXIMITY (1 << ID_PROXIMITY) 69 70 #define ID_CHECK(x) ((unsigned)((x) - ID_BASE) < MAX_NUM_SENSORS) 71 72 #define SENSORS_LIST \ 73 SENSOR_(ACCELERATION,"acceleration") \ 74 SENSOR_(MAGNETIC_FIELD,"magnetic-field") \ 75 SENSOR_(ORIENTATION,"orientation") \ 76 SENSOR_(TEMPERATURE,"temperature") \ 77 SENSOR_(PROXIMITY,"proximity") \ 78 79 static const struct { 80 const char* name; 81 int id; } _sensorIds[MAX_NUM_SENSORS] = 82 { 83 #define SENSOR_(x,y) { y, ID_##x }, 84 SENSORS_LIST 85 #undef SENSOR_ 86 }; 87 88 static const char* 89 _sensorIdToName( int id ) 90 { 91 int nn; 92 for (nn = 0; nn < MAX_NUM_SENSORS; nn++) 93 if (id == _sensorIds[nn].id) 94 return _sensorIds[nn].name; 95 return "<UNKNOWN>"; 96 } 97 98 static int 99 _sensorIdFromName( const char* name ) 100 { 101 int nn; 102 103 if (name == NULL) 104 return -1; 105 106 for (nn = 0; nn < MAX_NUM_SENSORS; nn++) 107 if (!strcmp(name, _sensorIds[nn].name)) 108 return _sensorIds[nn].id; 109 110 return -1; 111 } 112 113 /* return the current time in nanoseconds */ 114 static int64_t now_ns(void) { 115 struct timespec ts; 116 clock_gettime(CLOCK_MONOTONIC, &ts); 117 return (int64_t)ts.tv_sec * 1000000000 + ts.tv_nsec; 118 } 119 120 /** SENSORS POLL DEVICE 121 ** 122 ** This one is used to read sensor data from the hardware. 123 ** We implement this by simply reading the data from the 124 ** emulator through the QEMUD channel. 125 **/ 126 127 typedef struct SensorDevice { 128 struct sensors_poll_device_1 device; 129 sensors_event_t sensors[MAX_NUM_SENSORS]; 130 uint32_t pendingSensors; 131 int64_t timeStart; 132 int64_t timeOffset; 133 uint32_t active_sensors; 134 int fd; 135 pthread_mutex_t lock; 136 } SensorDevice; 137 138 /* Grab the file descriptor to the emulator's sensors service pipe. 139 * This function returns a file descriptor on success, or -errno on 140 * failure, and assumes the SensorDevice instance's lock is held. 141 * 142 * This is needed because set_delay(), poll() and activate() can be called 143 * from different threads, and poll() is blocking. 144 * 145 * Note that the emulator's sensors service creates a new client for each 146 * connection through qemud_channel_open(), where each client has its own 147 * delay and set of activated sensors. This precludes calling 148 * qemud_channel_open() on each request, because a typical emulated system 149 * will do something like: 150 * 151 * 1) On a first thread, de-activate() all sensors first, then call poll(), 152 * which results in the thread blocking. 153 * 154 * 2) On a second thread, slightly later, call set_delay() then activate() 155 * to enable the acceleration sensor. 156 * 157 * The system expects this to unblock the first thread which will receive 158 * new sensor events after the activate() call in 2). 159 * 160 * This cannot work if both threads don't use the same connection. 161 * 162 * TODO(digit): This protocol is brittle, implement another control channel 163 * for set_delay()/activate()/batch() when supporting HAL 1.3 164 */ 165 static int sensor_device_get_fd_locked(SensorDevice* dev) { 166 /* Create connection to service on first call */ 167 if (dev->fd < 0) { 168 dev->fd = qemud_channel_open(SENSORS_SERVICE_NAME); 169 if (dev->fd < 0) { 170 int ret = -errno; 171 E("%s: Could not open connection to service: %s", __FUNCTION__, 172 strerror(-ret)); 173 return ret; 174 } 175 } 176 return dev->fd; 177 } 178 179 /* Send a command to the sensors virtual device. |dev| is a device instance and 180 * |cmd| is a zero-terminated command string. Return 0 on success, or -errno 181 * on failure. */ 182 static int sensor_device_send_command_locked(SensorDevice* dev, 183 const char* cmd) { 184 int fd = sensor_device_get_fd_locked(dev); 185 if (fd < 0) { 186 return fd; 187 } 188 189 int ret = 0; 190 if (qemud_channel_send(fd, cmd, strlen(cmd)) < 0) { 191 ret = -errno; 192 E("%s(fd=%d): ERROR: %s", __FUNCTION__, fd, strerror(errno)); 193 } 194 return ret; 195 } 196 197 /* Pick up one pending sensor event. On success, this returns the sensor 198 * id, and sets |*event| accordingly. On failure, i.e. if there are no 199 * pending events, return -EINVAL. 200 * 201 * Note: The device's lock must be acquired. 202 */ 203 static int sensor_device_pick_pending_event_locked(SensorDevice* d, 204 sensors_event_t* event) 205 { 206 uint32_t mask = SUPPORTED_SENSORS & d->pendingSensors; 207 if (mask) { 208 uint32_t i = 31 - __builtin_clz(mask); 209 d->pendingSensors &= ~(1U << i); 210 *event = d->sensors[i]; 211 event->sensor = i; 212 event->version = sizeof(*event); 213 214 D("%s: %d [%f, %f, %f]", __FUNCTION__, 215 i, 216 event->data[0], 217 event->data[1], 218 event->data[2]); 219 return i; 220 } 221 E("No sensor to return!!! pendingSensors=0x%08x", d->pendingSensors); 222 // we may end-up in a busy loop, slow things down, just in case. 223 usleep(100000); 224 return -EINVAL; 225 } 226 227 /* Block until new sensor events are reported by the emulator, or if a 228 * 'wake' command is received through the service. On succes, return 0 229 * and updates the |pendingEvents| and |sensors| fields of |dev|. 230 * On failure, return -errno. 231 * 232 * Note: The device lock must be acquired when calling this function, and 233 * will still be held on return. However, the function releases the 234 * lock temporarily during the blocking wait. 235 */ 236 static int sensor_device_poll_event_locked(SensorDevice* dev) 237 { 238 D("%s: dev=%p", __FUNCTION__, dev); 239 240 int fd = sensor_device_get_fd_locked(dev); 241 if (fd < 0) { 242 E("%s: Could not get pipe channel: %s", __FUNCTION__, strerror(-fd)); 243 return fd; 244 } 245 246 // Accumulate pending events into |events| and |new_sensors| mask 247 // until a 'sync' or 'wake' command is received. This also simplifies the 248 // code a bit. 249 uint32_t new_sensors = 0U; 250 sensors_event_t* events = dev->sensors; 251 252 int64_t event_time = -1; 253 int ret = 0; 254 255 for (;;) { 256 /* Release the lock since we're going to block on recv() */ 257 pthread_mutex_unlock(&dev->lock); 258 259 /* read the next event */ 260 char buff[256]; 261 int len = qemud_channel_recv(fd, buff, sizeof(buff) - 1U); 262 /* re-acquire the lock to modify the device state. */ 263 pthread_mutex_lock(&dev->lock); 264 265 if (len < 0) { 266 ret = -errno; 267 E("%s(fd=%d): Could not receive event data len=%d, errno=%d: %s", 268 __FUNCTION__, fd, len, errno, strerror(errno)); 269 break; 270 } 271 buff[len] = 0; 272 D("%s(fd=%d): received [%s]", __FUNCTION__, fd, buff); 273 274 275 /* "wake" is sent from the emulator to exit this loop. */ 276 /* TODO(digit): Is it still needed? */ 277 if (!strcmp((const char*)buff, "wake")) { 278 ret = 0x7FFFFFFF; 279 break; 280 } 281 282 float params[3]; 283 284 /* "acceleration:<x>:<y>:<z>" corresponds to an acceleration event */ 285 if (sscanf(buff, "acceleration:%g:%g:%g", params+0, params+1, params+2) 286 == 3) { 287 new_sensors |= SENSORS_ACCELERATION; 288 events[ID_ACCELERATION].acceleration.x = params[0]; 289 events[ID_ACCELERATION].acceleration.y = params[1]; 290 events[ID_ACCELERATION].acceleration.z = params[2]; 291 events[ID_ACCELERATION].type = SENSOR_TYPE_ACCELEROMETER; 292 continue; 293 } 294 295 /* "orientation:<azimuth>:<pitch>:<roll>" is sent when orientation 296 * changes */ 297 if (sscanf(buff, "orientation:%g:%g:%g", params+0, params+1, params+2) 298 == 3) { 299 new_sensors |= SENSORS_ORIENTATION; 300 events[ID_ORIENTATION].orientation.azimuth = params[0]; 301 events[ID_ORIENTATION].orientation.pitch = params[1]; 302 events[ID_ORIENTATION].orientation.roll = params[2]; 303 events[ID_ORIENTATION].orientation.status = 304 SENSOR_STATUS_ACCURACY_HIGH; 305 events[ID_ACCELERATION].type = SENSOR_TYPE_ORIENTATION; 306 continue; 307 } 308 309 /* "magnetic:<x>:<y>:<z>" is sent for the params of the magnetic 310 * field */ 311 if (sscanf(buff, "magnetic:%g:%g:%g", params+0, params+1, params+2) 312 == 3) { 313 new_sensors |= SENSORS_MAGNETIC_FIELD; 314 events[ID_MAGNETIC_FIELD].magnetic.x = params[0]; 315 events[ID_MAGNETIC_FIELD].magnetic.y = params[1]; 316 events[ID_MAGNETIC_FIELD].magnetic.z = params[2]; 317 events[ID_MAGNETIC_FIELD].magnetic.status = 318 SENSOR_STATUS_ACCURACY_HIGH; 319 events[ID_ACCELERATION].type = SENSOR_TYPE_MAGNETIC_FIELD; 320 continue; 321 } 322 323 /* "temperature:<celsius>" */ 324 if (sscanf(buff, "temperature:%g", params+0) == 1) { 325 new_sensors |= SENSORS_TEMPERATURE; 326 events[ID_TEMPERATURE].temperature = params[0]; 327 events[ID_ACCELERATION].type = SENSOR_TYPE_TEMPERATURE; 328 continue; 329 } 330 331 /* "proximity:<value>" */ 332 if (sscanf(buff, "proximity:%g", params+0) == 1) { 333 new_sensors |= SENSORS_PROXIMITY; 334 events[ID_PROXIMITY].distance = params[0]; 335 events[ID_ACCELERATION].type = SENSOR_TYPE_PROXIMITY; 336 continue; 337 } 338 339 /* "sync:<time>" is sent after a series of sensor events. 340 * where 'time' is expressed in micro-seconds and corresponds 341 * to the VM time when the real poll occured. 342 */ 343 if (sscanf(buff, "sync:%lld", &event_time) == 1) { 344 if (new_sensors) { 345 goto out; 346 } 347 D("huh ? sync without any sensor data ?"); 348 continue; 349 } 350 D("huh ? unsupported command"); 351 } 352 out: 353 if (new_sensors) { 354 /* update the time of each new sensor event. */ 355 dev->pendingSensors |= new_sensors; 356 int64_t t = (event_time < 0) ? 0 : event_time * 1000LL; 357 358 /* use the time at the first sync: as the base for later 359 * time values */ 360 if (dev->timeStart == 0) { 361 dev->timeStart = now_ns(); 362 dev->timeOffset = dev->timeStart - t; 363 } 364 t += dev->timeOffset; 365 366 while (new_sensors) { 367 uint32_t i = 31 - __builtin_clz(new_sensors); 368 new_sensors &= ~(1U << i); 369 dev->sensors[i].timestamp = t; 370 } 371 } 372 return ret; 373 } 374 375 /** SENSORS POLL DEVICE FUNCTIONS **/ 376 377 static int sensor_device_close(struct hw_device_t* dev0) 378 { 379 SensorDevice* dev = (void*)dev0; 380 // Assume that there are no other threads blocked on poll() 381 if (dev->fd >= 0) { 382 close(dev->fd); 383 dev->fd = -1; 384 } 385 pthread_mutex_destroy(&dev->lock); 386 free(dev); 387 return 0; 388 } 389 390 /* Return an array of sensor data. This function blocks until there is sensor 391 * related events to report. On success, it will write the events into the 392 * |data| array, which contains |count| items. The function returns the number 393 * of events written into the array, which shall never be greater than |count|. 394 * On error, return -errno code. 395 * 396 * Note that according to the sensor HAL [1], it shall never return 0! 397 * 398 * [1] http://source.android.com/devices/sensors/hal-interface.html 399 */ 400 static int sensor_device_poll(struct sensors_poll_device_t *dev0, 401 sensors_event_t* data, int count) 402 { 403 SensorDevice* dev = (void*)dev0; 404 D("%s: dev=%p data=%p count=%d ", __FUNCTION__, dev, data, count); 405 406 if (count <= 0) { 407 return -EINVAL; 408 } 409 410 int result = 0; 411 pthread_mutex_lock(&dev->lock); 412 if (!dev->pendingSensors) { 413 /* Block until there are pending events. Note that this releases 414 * the lock during the blocking call, then re-acquires it before 415 * returning. */ 416 int ret = sensor_device_poll_event_locked(dev); 417 if (ret < 0) { 418 result = ret; 419 goto out; 420 } 421 if (!dev->pendingSensors) { 422 /* 'wake' event received before any sensor data. */ 423 result = -EIO; 424 goto out; 425 } 426 } 427 /* Now read as many pending events as needed. */ 428 int i; 429 for (i = 0; i < count; i++) { 430 if (!dev->pendingSensors) { 431 break; 432 } 433 int ret = sensor_device_pick_pending_event_locked(dev, data); 434 if (ret < 0) { 435 if (!result) { 436 result = ret; 437 } 438 break; 439 } 440 data++; 441 result++; 442 } 443 out: 444 pthread_mutex_unlock(&dev->lock); 445 D("%s: result=%d", __FUNCTION__, result); 446 return result; 447 } 448 449 static int sensor_device_activate(struct sensors_poll_device_t *dev0, 450 int handle, 451 int enabled) 452 { 453 SensorDevice* dev = (void*)dev0; 454 455 D("%s: handle=%s (%d) enabled=%d", __FUNCTION__, 456 _sensorIdToName(handle), handle, enabled); 457 458 /* Sanity check */ 459 if (!ID_CHECK(handle)) { 460 E("%s: bad handle ID", __FUNCTION__); 461 return -EINVAL; 462 } 463 464 /* Exit early if sensor is already enabled/disabled. */ 465 uint32_t mask = (1U << handle); 466 uint32_t sensors = enabled ? mask : 0; 467 468 pthread_mutex_lock(&dev->lock); 469 470 uint32_t active = dev->active_sensors; 471 uint32_t new_sensors = (active & ~mask) | (sensors & mask); 472 uint32_t changed = active ^ new_sensors; 473 474 int ret = 0; 475 if (changed) { 476 /* Send command to the emulator. */ 477 char command[64]; 478 snprintf(command, 479 sizeof command, 480 "set:%s:%d", 481 _sensorIdToName(handle), 482 enabled != 0); 483 484 ret = sensor_device_send_command_locked(dev, command); 485 if (ret < 0) { 486 E("%s: when sending command errno=%d: %s", __FUNCTION__, -ret, 487 strerror(-ret)); 488 } else { 489 dev->active_sensors = new_sensors; 490 } 491 } 492 pthread_mutex_unlock(&dev->lock); 493 return ret; 494 } 495 496 static int sensor_device_set_delay(struct sensors_poll_device_t *dev0, 497 int handle __unused, 498 int64_t ns) 499 { 500 SensorDevice* dev = (void*)dev0; 501 502 int ms = (int)(ns / 1000000); 503 D("%s: dev=%p delay-ms=%d", __FUNCTION__, dev, ms); 504 505 char command[64]; 506 snprintf(command, sizeof command, "set-delay:%d", ms); 507 508 pthread_mutex_lock(&dev->lock); 509 int ret = sensor_device_send_command_locked(dev, command); 510 pthread_mutex_unlock(&dev->lock); 511 if (ret < 0) { 512 E("%s: Could not send command: %s", __FUNCTION__, strerror(-ret)); 513 } 514 return ret; 515 } 516 517 /** MODULE REGISTRATION SUPPORT 518 ** 519 ** This is required so that hardware/libhardware/hardware.c 520 ** will dlopen() this library appropriately. 521 **/ 522 523 /* 524 * the following is the list of all supported sensors. 525 * this table is used to build sSensorList declared below 526 * according to which hardware sensors are reported as 527 * available from the emulator (see get_sensors_list below) 528 * 529 * note: numerical values for maxRange/resolution/power were 530 * taken from the reference AK8976A implementation 531 */ 532 static const struct sensor_t sSensorListInit[] = { 533 { .name = "Goldfish 3-axis Accelerometer", 534 .vendor = "The Android Open Source Project", 535 .version = 1, 536 .handle = ID_ACCELERATION, 537 .type = SENSOR_TYPE_ACCELEROMETER, 538 .maxRange = 2.8f, 539 .resolution = 1.0f/4032.0f, 540 .power = 3.0f, 541 .reserved = {} 542 }, 543 544 { .name = "Goldfish 3-axis Magnetic field sensor", 545 .vendor = "The Android Open Source Project", 546 .version = 1, 547 .handle = ID_MAGNETIC_FIELD, 548 .type = SENSOR_TYPE_MAGNETIC_FIELD, 549 .maxRange = 2000.0f, 550 .resolution = 1.0f, 551 .power = 6.7f, 552 .reserved = {} 553 }, 554 555 { .name = "Goldfish Orientation sensor", 556 .vendor = "The Android Open Source Project", 557 .version = 1, 558 .handle = ID_ORIENTATION, 559 .type = SENSOR_TYPE_ORIENTATION, 560 .maxRange = 360.0f, 561 .resolution = 1.0f, 562 .power = 9.7f, 563 .reserved = {} 564 }, 565 566 { .name = "Goldfish Temperature sensor", 567 .vendor = "The Android Open Source Project", 568 .version = 1, 569 .handle = ID_TEMPERATURE, 570 .type = SENSOR_TYPE_TEMPERATURE, 571 .maxRange = 80.0f, 572 .resolution = 1.0f, 573 .power = 0.0f, 574 .reserved = {} 575 }, 576 577 { .name = "Goldfish Proximity sensor", 578 .vendor = "The Android Open Source Project", 579 .version = 1, 580 .handle = ID_PROXIMITY, 581 .type = SENSOR_TYPE_PROXIMITY, 582 .maxRange = 1.0f, 583 .resolution = 1.0f, 584 .power = 20.0f, 585 .reserved = {} 586 }, 587 }; 588 589 static struct sensor_t sSensorList[MAX_NUM_SENSORS]; 590 591 static int sensors__get_sensors_list(struct sensors_module_t* module __unused, 592 struct sensor_t const** list) 593 { 594 int fd = qemud_channel_open(SENSORS_SERVICE_NAME); 595 char buffer[12]; 596 int mask, nn, count; 597 int ret = 0; 598 599 if (fd < 0) { 600 E("%s: no qemud connection", __FUNCTION__); 601 goto out; 602 } 603 ret = qemud_channel_send(fd, "list-sensors", -1); 604 if (ret < 0) { 605 E("%s: could not query sensor list: %s", __FUNCTION__, 606 strerror(errno)); 607 goto out; 608 } 609 ret = qemud_channel_recv(fd, buffer, sizeof buffer-1); 610 if (ret < 0) { 611 E("%s: could not receive sensor list: %s", __FUNCTION__, 612 strerror(errno)); 613 goto out; 614 } 615 buffer[ret] = 0; 616 617 /* the result is a integer used as a mask for available sensors */ 618 mask = atoi(buffer); 619 count = 0; 620 for (nn = 0; nn < MAX_NUM_SENSORS; nn++) { 621 if (((1 << nn) & mask) == 0) 622 continue; 623 624 sSensorList[count++] = sSensorListInit[nn]; 625 } 626 D("%s: returned %d sensors (mask=%d)", __FUNCTION__, count, mask); 627 *list = sSensorList; 628 629 ret = count; 630 out: 631 if (fd >= 0) { 632 close(fd); 633 } 634 return ret; 635 } 636 637 638 static int 639 open_sensors(const struct hw_module_t* module, 640 const char* name, 641 struct hw_device_t* *device) 642 { 643 int status = -EINVAL; 644 645 D("%s: name=%s", __FUNCTION__, name); 646 647 if (!strcmp(name, SENSORS_HARDWARE_POLL)) { 648 SensorDevice *dev = malloc(sizeof(*dev)); 649 650 memset(dev, 0, sizeof(*dev)); 651 652 dev->device.common.tag = HARDWARE_DEVICE_TAG; 653 dev->device.common.version = SENSORS_DEVICE_API_VERSION_1_0; 654 dev->device.common.module = (struct hw_module_t*) module; 655 dev->device.common.close = sensor_device_close; 656 dev->device.poll = sensor_device_poll; 657 dev->device.activate = sensor_device_activate; 658 dev->device.setDelay = sensor_device_set_delay; 659 660 dev->fd = -1; 661 pthread_mutex_init(&dev->lock, NULL); 662 663 *device = &dev->device.common; 664 status = 0; 665 } 666 return status; 667 } 668 669 670 static struct hw_module_methods_t sensors_module_methods = { 671 .open = open_sensors 672 }; 673 674 struct sensors_module_t HAL_MODULE_INFO_SYM = { 675 .common = { 676 .tag = HARDWARE_MODULE_TAG, 677 .version_major = 1, 678 .version_minor = 0, 679 .id = SENSORS_HARDWARE_MODULE_ID, 680 .name = "Goldfish SENSORS Module", 681 .author = "The Android Open Source Project", 682 .methods = &sensors_module_methods, 683 }, 684 .get_sensors_list = sensors__get_sensors_list 685 }; 686