Home | History | Annotate | Download | only in sensors
      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(...)  ALOGD(__VA_ARGS__)
     43 #else
     44 #define  D(...)  ((void)0)
     45 #endif
     46 
     47 #define  E(...)  ALOGE(__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*
     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
    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_1  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*
    136 control__open_data_source(struct sensors_poll_device_1 *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
    151 control__activate(struct sensors_poll_device_1 *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
    196 control__set_delay(struct sensors_poll_device_1 *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
    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
    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
    229 data__data_open(struct sensors_poll_device_1 *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     data->pendingSensors = 0;
    237     data->timeStart      = 0;
    238     data->timeOffset     = 0;
    239 
    240     data->events_fd = dup(handle->data[0]);
    241     D("%s: dev=%p fd=%d (was %d)", __FUNCTION__, dev, data->events_fd, handle->data[0]);
    242     native_handle_close(handle);
    243     native_handle_delete(handle);
    244     return 0;
    245 }
    246 
    247 static int
    248 data__data_close(struct sensors_poll_device_1 *dev)
    249 {
    250     SensorPoll*  data = (void*)dev;
    251     D("%s: dev=%p", __FUNCTION__, dev);
    252     if (data->events_fd >= 0) {
    253         close(data->events_fd);
    254         data->events_fd = -1;
    255     }
    256     return 0;
    257 }
    258 
    259 static int
    260 pick_sensor(SensorPoll*       data,
    261             sensors_event_t*  values)
    262 {
    263     uint32_t mask = SUPPORTED_SENSORS;
    264     while (mask) {
    265         uint32_t i = 31 - __builtin_clz(mask);
    266         mask &= ~(1<<i);
    267         if (data->pendingSensors & (1<<i)) {
    268             data->pendingSensors &= ~(1<<i);
    269             *values = data->sensors[i];
    270             values->sensor = i;
    271             values->version = sizeof(*values);
    272 
    273             D("%s: %d [%f, %f, %f]", __FUNCTION__,
    274                     i,
    275                     values->data[0],
    276                     values->data[1],
    277                     values->data[2]);
    278             return i;
    279         }
    280     }
    281     ALOGE("No sensor to return!!! pendingSensors=%08x", data->pendingSensors);
    282     // we may end-up in a busy loop, slow things down, just in case.
    283     usleep(100000);
    284     return -EINVAL;
    285 }
    286 
    287 static int
    288 data__poll(struct sensors_poll_device_1 *dev, sensors_event_t* values)
    289 {
    290     SensorPoll*  data = (void*)dev;
    291     int fd = data->events_fd;
    292 
    293     D("%s: data=%p", __FUNCTION__, dev);
    294 
    295     // there are pending sensors, returns them now...
    296     if (data->pendingSensors) {
    297         return pick_sensor(data, values);
    298     }
    299 
    300     // wait until we get a complete event for an enabled sensor
    301     uint32_t new_sensors = 0;
    302 
    303     while (1) {
    304         /* read the next event */
    305         char     buff[256];
    306         int      len = qemud_channel_recv(data->events_fd, buff, sizeof buff-1);
    307         float    params[3];
    308         int64_t  event_time;
    309 
    310         if (len < 0) {
    311             E("%s: len=%d, errno=%d: %s", __FUNCTION__, len, errno, strerror(errno));
    312             return -errno;
    313         }
    314 
    315         buff[len] = 0;
    316 
    317         /* "wake" is sent from the emulator to exit this loop. */
    318         if (!strcmp((const char*)data, "wake")) {
    319             return 0x7FFFFFFF;
    320         }
    321 
    322         /* "acceleration:<x>:<y>:<z>" corresponds to an acceleration event */
    323         if (sscanf(buff, "acceleration:%g:%g:%g", params+0, params+1, params+2) == 3) {
    324             new_sensors |= SENSORS_ACCELERATION;
    325             data->sensors[ID_ACCELERATION].acceleration.x = params[0];
    326             data->sensors[ID_ACCELERATION].acceleration.y = params[1];
    327             data->sensors[ID_ACCELERATION].acceleration.z = params[2];
    328             data->sensors[ID_ACCELERATION].type = SENSOR_TYPE_ACCELEROMETER;
    329             continue;
    330         }
    331 
    332         /* "orientation:<azimuth>:<pitch>:<roll>" is sent when orientation changes */
    333         if (sscanf(buff, "orientation:%g:%g:%g", params+0, params+1, params+2) == 3) {
    334             new_sensors |= SENSORS_ORIENTATION;
    335             data->sensors[ID_ORIENTATION].orientation.azimuth = params[0];
    336             data->sensors[ID_ORIENTATION].orientation.pitch   = params[1];
    337             data->sensors[ID_ORIENTATION].orientation.roll    = params[2];
    338             data->sensors[ID_ORIENTATION].orientation.status  = SENSOR_STATUS_ACCURACY_HIGH;
    339             data->sensors[ID_ACCELERATION].type = SENSOR_TYPE_ORIENTATION;
    340             continue;
    341         }
    342 
    343         /* "magnetic:<x>:<y>:<z>" is sent for the params of the magnetic field */
    344         if (sscanf(buff, "magnetic:%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             data->sensors[ID_MAGNETIC_FIELD].magnetic.status = SENSOR_STATUS_ACCURACY_HIGH;
    350             data->sensors[ID_ACCELERATION].type = SENSOR_TYPE_MAGNETIC_FIELD;
    351             continue;
    352         }
    353 
    354         /* "temperature:<celsius>" */
    355         if (sscanf(buff, "temperature:%g", params+0) == 1) {
    356             new_sensors |= SENSORS_TEMPERATURE;
    357             data->sensors[ID_TEMPERATURE].temperature = params[0];
    358             data->sensors[ID_ACCELERATION].type = SENSOR_TYPE_TEMPERATURE;
    359             continue;
    360         }
    361 
    362         /* "proximity:<value>" */
    363         if (sscanf(buff, "proximity:%g", params+0) == 1) {
    364             new_sensors |= SENSORS_PROXIMITY;
    365             data->sensors[ID_PROXIMITY].distance = params[0];
    366             data->sensors[ID_ACCELERATION].type = SENSOR_TYPE_PROXIMITY;
    367             continue;
    368         }
    369 
    370         /* "sync:<time>" is sent after a series of sensor events.
    371          * where 'time' is expressed in micro-seconds and corresponds
    372          * to the VM time when the real poll occured.
    373          */
    374         if (sscanf(buff, "sync:%lld", &event_time) == 1) {
    375             if (new_sensors) {
    376                 data->pendingSensors = new_sensors;
    377                 int64_t t = event_time * 1000LL;  /* convert to nano-seconds */
    378 
    379                 /* use the time at the first sync: as the base for later
    380                  * time values */
    381                 if (data->timeStart == 0) {
    382                     data->timeStart  = data__now_ns();
    383                     data->timeOffset = data->timeStart - t;
    384                 }
    385                 t += data->timeOffset;
    386 
    387                 while (new_sensors) {
    388                     uint32_t i = 31 - __builtin_clz(new_sensors);
    389                     new_sensors &= ~(1<<i);
    390                     data->sensors[i].timestamp = t;
    391                 }
    392                 return pick_sensor(data, values);
    393             } else {
    394                 D("huh ? sync without any sensor data ?");
    395             }
    396             continue;
    397         }
    398         D("huh ? unsupported command");
    399     }
    400     return -1;
    401 }
    402 
    403 static int
    404 data__close(struct hw_device_t *dev)
    405 {
    406     SensorPoll* data = (SensorPoll*)dev;
    407     if (data) {
    408         if (data->events_fd >= 0) {
    409             //ALOGD("(device close) about to close fd=%d", data->events_fd);
    410             close(data->events_fd);
    411         }
    412         free(data);
    413     }
    414     return 0;
    415 }
    416 
    417 /** SENSORS POLL DEVICE FUNCTIONS **/
    418 
    419 static int poll__close(struct hw_device_t* dev)
    420 {
    421     SensorPoll*  ctl = (void*)dev;
    422     close(ctl->fd);
    423     if (ctl->fd >= 0) {
    424         close(ctl->fd);
    425     }
    426     if (ctl->events_fd >= 0) {
    427         close(ctl->events_fd);
    428     }
    429     free(ctl);
    430     return 0;
    431 }
    432 
    433 static int poll__poll(struct sensors_poll_device_1 *dev,
    434             sensors_event_t* data, int count)
    435 {
    436     SensorPoll*  datadev = (void*)dev;
    437     int ret;
    438     int i;
    439     D("%s: dev=%p data=%p count=%d ", __FUNCTION__, dev, data, count);
    440 
    441     for (i = 0; i < count; i++)  {
    442         ret = data__poll(dev, data);
    443         data++;
    444         if (ret > MAX_NUM_SENSORS || ret < 0) {
    445            return i;
    446         }
    447         if (!datadev->pendingSensors) {
    448            return i + 1;
    449         }
    450     }
    451     return count;
    452 }
    453 
    454 static int poll__activate(struct sensors_poll_device_1 *dev,
    455             int handle, int enabled)
    456 {
    457     int ret;
    458     native_handle_t* hdl;
    459     SensorPoll*  ctl = (void*)dev;
    460     D("%s: dev=%p handle=%x enable=%d ", __FUNCTION__, dev, handle, enabled);
    461     if (ctl->fd < 0) {
    462         D("%s: OPEN CTRL and DATA ", __FUNCTION__);
    463         hdl = control__open_data_source(dev);
    464         ret = data__data_open(dev,hdl);
    465     }
    466     ret = control__activate(dev, handle, enabled);
    467     return ret;
    468 }
    469 
    470 static int poll__setDelay(struct sensors_poll_device_1 *dev,
    471             int handle, int64_t ns)
    472 {
    473     // TODO
    474     return 0;
    475 }
    476 
    477 /** MODULE REGISTRATION SUPPORT
    478  **
    479  ** This is required so that hardware/libhardware/hardware.c
    480  ** will dlopen() this library appropriately.
    481  **/
    482 
    483 /*
    484  * the following is the list of all supported sensors.
    485  * this table is used to build sSensorList declared below
    486  * according to which hardware sensors are reported as
    487  * available from the emulator (see get_sensors_list below)
    488  *
    489  * note: numerical values for maxRange/resolution/power were
    490  *       taken from the reference AK8976A implementation
    491  */
    492 static const struct sensor_t sSensorListInit[] = {
    493         { .name       = "Goldfish 3-axis Accelerometer",
    494           .vendor     = "The Android Open Source Project",
    495           .version    = 1,
    496           .handle     = ID_ACCELERATION,
    497           .type       = SENSOR_TYPE_ACCELEROMETER,
    498           .maxRange   = 2.8f,
    499           .resolution = 1.0f/4032.0f,
    500           .power      = 3.0f,
    501           .reserved   = {}
    502         },
    503 
    504         { .name       = "Goldfish 3-axis Magnetic field sensor",
    505           .vendor     = "The Android Open Source Project",
    506           .version    = 1,
    507           .handle     = ID_MAGNETIC_FIELD,
    508           .type       = SENSOR_TYPE_MAGNETIC_FIELD,
    509           .maxRange   = 2000.0f,
    510           .resolution = 1.0f,
    511           .power      = 6.7f,
    512           .reserved   = {}
    513         },
    514 
    515         { .name       = "Goldfish Orientation sensor",
    516           .vendor     = "The Android Open Source Project",
    517           .version    = 1,
    518           .handle     = ID_ORIENTATION,
    519           .type       = SENSOR_TYPE_ORIENTATION,
    520           .maxRange   = 360.0f,
    521           .resolution = 1.0f,
    522           .power      = 9.7f,
    523           .reserved   = {}
    524         },
    525 
    526         { .name       = "Goldfish Temperature sensor",
    527           .vendor     = "The Android Open Source Project",
    528           .version    = 1,
    529           .handle     = ID_TEMPERATURE,
    530           .type       = SENSOR_TYPE_TEMPERATURE,
    531           .maxRange   = 80.0f,
    532           .resolution = 1.0f,
    533           .power      = 0.0f,
    534           .reserved   = {}
    535         },
    536 
    537         { .name       = "Goldfish Proximity sensor",
    538           .vendor     = "The Android Open Source Project",
    539           .version    = 1,
    540           .handle     = ID_PROXIMITY,
    541           .type       = SENSOR_TYPE_PROXIMITY,
    542           .maxRange   = 1.0f,
    543           .resolution = 1.0f,
    544           .power      = 20.0f,
    545           .reserved   = {}
    546         },
    547 };
    548 
    549 static struct sensor_t  sSensorList[MAX_NUM_SENSORS];
    550 
    551 static int sensors__get_sensors_list(struct sensors_module_t* module,
    552         struct sensor_t const** list)
    553 {
    554     int  fd = qemud_channel_open(SENSORS_SERVICE_NAME);
    555     char buffer[12];
    556     int  mask, nn, count;
    557 
    558     int  ret;
    559     if (fd < 0) {
    560         E("%s: no qemud connection", __FUNCTION__);
    561         return 0;
    562     }
    563     ret = qemud_channel_send(fd, "list-sensors", -1);
    564     if (ret < 0) {
    565         E("%s: could not query sensor list: %s", __FUNCTION__,
    566           strerror(errno));
    567         close(fd);
    568         return 0;
    569     }
    570     ret = qemud_channel_recv(fd, buffer, sizeof buffer-1);
    571     if (ret < 0) {
    572         E("%s: could not receive sensor list: %s", __FUNCTION__,
    573           strerror(errno));
    574         close(fd);
    575         return 0;
    576     }
    577     buffer[ret] = 0;
    578     close(fd);
    579 
    580     /* the result is a integer used as a mask for available sensors */
    581     mask  = atoi(buffer);
    582     count = 0;
    583     for (nn = 0; nn < MAX_NUM_SENSORS; nn++) {
    584         if (((1 << nn) & mask) == 0)
    585             continue;
    586 
    587         sSensorList[count++] = sSensorListInit[nn];
    588     }
    589     D("%s: returned %d sensors (mask=%d)", __FUNCTION__, count, mask);
    590     *list = sSensorList;
    591     return count;
    592 }
    593 
    594 
    595 static int
    596 open_sensors(const struct hw_module_t* module,
    597              const char*               name,
    598              struct hw_device_t*      *device)
    599 {
    600     int  status = -EINVAL;
    601 
    602     D("%s: name=%s", __FUNCTION__, name);
    603 
    604     if (!strcmp(name, SENSORS_HARDWARE_POLL)) {
    605         SensorPoll *dev = malloc(sizeof(*dev));
    606 
    607         memset(dev, 0, sizeof(*dev));
    608 
    609         dev->device.common.tag     = HARDWARE_DEVICE_TAG;
    610         dev->device.common.version = SENSORS_DEVICE_API_VERSION_1_0;
    611         dev->device.common.module  = (struct hw_module_t*) module;
    612         dev->device.common.close   = poll__close;
    613         dev->device.poll           = poll__poll;
    614         dev->device.activate       = poll__activate;
    615         dev->device.setDelay       = poll__setDelay;
    616         dev->events_fd             = -1;
    617         dev->fd                    = -1;
    618 
    619         *device = &dev->device.common;
    620         status  = 0;
    621     }
    622     return status;
    623 }
    624 
    625 
    626 static struct hw_module_methods_t sensors_module_methods = {
    627     .open = open_sensors
    628 };
    629 
    630 struct sensors_module_t HAL_MODULE_INFO_SYM = {
    631     .common = {
    632         .tag = HARDWARE_MODULE_TAG,
    633         .version_major = 1,
    634         .version_minor = 0,
    635         .id = SENSORS_HARDWARE_MODULE_ID,
    636         .name = "Goldfish SENSORS Module",
    637         .author = "The Android Open Source Project",
    638         .methods = &sensors_module_methods,
    639     },
    640     .get_sensors_list = sensors__get_sensors_list
    641 };
    642