X-Git-Url: http://git.osdn.net/view?a=blobdiff_plain;f=control.c;h=c36085eab7c92db937b23e6e6a2e3e8279883693;hb=d3fcd6151aa98afa8ac7649dbe692d358bf3a6f2;hp=5468aeeb47546cb7d0669df8075a5a54f3f139bb;hpb=de50236e1d77082493eeef498c576796fe1baeaa;p=android-x86%2Fhardware-intel-libsensors.git diff --git a/control.c b/control.c index 5468aee..c36085e 100644 --- a/control.c +++ b/control.c @@ -1,6 +1,18 @@ /* - * Copyright (C) 2014 Intel Corporation. - */ +// Copyright (c) 2015 Intel Corporation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +*/ #include #include @@ -9,9 +21,11 @@ #include #include #include +#include #include #include #include +#include #include "control.h" #include "enumeration.h" #include "utils.h" @@ -19,34 +33,42 @@ #include "calibration.h" #include "description.h" #include "filtering.h" +#ifndef __NO_EVENTS__ +#include +#include +#endif +#include /* Currently active sensors count, per device */ -static int poll_sensors_per_dev[MAX_DEVICES]; /* poll-mode sensors */ -static int trig_sensors_per_dev[MAX_DEVICES]; /* trigger, event based */ +static int poll_sensors_per_dev[MAX_DEVICES]; /* poll-mode sensors */ +static int trig_sensors_per_dev[MAX_DEVICES]; /* trigger, event based */ + +static int device_fd[MAX_DEVICES]; /* fd on the /dev/iio:deviceX file */ +static int events_fd[MAX_DEVICES]; /* fd on the /sys/bus/iio/devices/iio:deviceX/events/ file */ +static int has_iio_ts[MAX_DEVICES]; /* ts channel available on this iio dev */ +static int expected_dev_report_size[MAX_DEVICES]; /* expected iio scan len */ +static int poll_fd; /* epoll instance covering all enabled sensors */ -static int device_fd[MAX_DEVICES]; /* fd on the /dev/iio:deviceX file */ -static int has_iio_ts[MAX_DEVICES]; /* ts channel available on this iio dev */ -static int expected_dev_report_size[MAX_DEVICES]; /* expected iio scan len */ -static int poll_fd; /* epoll instance covering all enabled sensors */ +static int active_poll_sensors; /* Number of enabled poll-mode sensors */ -static int active_poll_sensors; /* Number of enabled poll-mode sensors */ +static int flush_event_fd[2]; /* Pipe used for flush signaling */ /* We use pthread condition variables to get worker threads out of sleep */ static pthread_condattr_t thread_cond_attr [MAX_SENSORS]; static pthread_cond_t thread_release_cond [MAX_SENSORS]; static pthread_mutex_t thread_release_mutex [MAX_SENSORS]; +#define FLUSH_REPORT_TAG 900 /* - * We associate tags to each of our poll set entries. These tags have the - * following values: + * We associate tags to each of our poll set entries. These tags have the following values: * - a iio device number if the fd is a iio character device fd - * - THREAD_REPORT_TAG_BASE + sensor handle if the fd is the receiving end of a - * pipe used by a sysfs data acquisition thread + * - THREAD_REPORT_TAG_BASE + sensor handle if the fd is the receiving end of a pipe used by a sysfs data acquisition thread */ -#define THREAD_REPORT_TAG_BASE 0x00010000 +#define THREAD_REPORT_TAG_BASE 1000 -#define ENABLE_BUFFER_RETRIES 10 -#define ENABLE_BUFFER_RETRY_DELAY_MS 10 +/* If buffer enable fails, we may want to retry a few times before giving up */ +#define ENABLE_BUFFER_RETRIES 3 +#define ENABLE_BUFFER_RETRY_DELAY_MS 10 inline int is_enabled (int s) @@ -59,70 +81,51 @@ static int check_state_change (int s, int enabled, int from_virtual) { if (enabled) { if (sensor[s].directly_enabled) - /* - * We're being enabled but already were - * directly activated: no change. - */ - return 0; + return 0; /* We're being enabled but already were directly activated: no change. */ if (!from_virtual) - /* We're being directly enabled */ - sensor[s].directly_enabled = 1; + sensor[s].directly_enabled = 1; /* We're being directly enabled */ if (sensor[s].ref_count) - /* We were already indirectly enabled */ - return 0; + return 0; /* We were already indirectly enabled */ - return 1; /* Do continue enabling this sensor */ + return 1; /* Do continue enabling this sensor */ } if (!is_enabled(s)) - /* We are being disabled but already were: no change */ - return 0; + return 0; /* We are being disabled but already were: no change */ if (from_virtual && sensor[s].directly_enabled) - /* We're indirectly disabled but the base is still active */ - return 0; + return 0; /* We're indirectly disabled but the base is still active */ - /* We're now directly disabled */ - sensor[s].directly_enabled = 0; + sensor[s].directly_enabled = 0; /* We're now directly disabled */ if (!from_virtual && sensor[s].ref_count) - return 0; /* We still have ref counts */ + return 0; /* We still have ref counts */ - return 1; /* Do continue disabling this sensor */ + return 1; /* Do continue disabling this sensor */ } -static int enable_buffer(int dev_num, int enabled) +static int enable_buffer (int dev_num, int enabled) { char sysfs_path[PATH_MAX]; - int ret, retries, millisec; - struct timespec req = {0}; - - retries = ENABLE_BUFFER_RETRIES; - millisec = ENABLE_BUFFER_RETRY_DELAY_MS; - req.tv_sec = 0; - req.tv_nsec = millisec * 1000000L; + int retries = ENABLE_BUFFER_RETRIES; sprintf(sysfs_path, ENABLE_PATH, dev_num); - while (retries--) { + while (retries) { /* Low level, non-multiplexed, enable/disable routine */ - ret = sysfs_write_int(sysfs_path, enabled); - if (ret > 0) - break; - - ALOGE("Failed enabling buffer, retrying"); - nanosleep(&req, (struct timespec *)NULL); - } + if (sysfs_write_int(sysfs_path, enabled) > 0) + return 0; - if (ret < 0) { - ALOGE("Could not enable buffer\n"); - return -EIO; + ALOGE("Failed enabling buffer on dev%d, retrying", dev_num); + usleep(ENABLE_BUFFER_RETRY_DELAY_MS*1000); + retries--; } - return 0; + ALOGE("Could not enable buffer\n"); + return -EIO; } @@ -134,8 +137,7 @@ static int setup_trigger (int s, const char* trigger_val) sprintf(sysfs_path, TRIGGER_PATH, sensor[s].dev_num); if (trigger_val[0] != '\n') - ALOGI("Setting S%d (%s) trigger to %s\n", s, - sensor[s].friendly_name, trigger_val); + ALOGI("Setting S%d (%s) trigger to %s\n", s, sensor[s].friendly_name, trigger_val); while (ret == -1 && attempts) { ret = sysfs_write_str(sysfs_path, trigger_val); @@ -145,11 +147,25 @@ static int setup_trigger (int s, const char* trigger_val) if (ret != -1) sensor[s].selected_trigger = trigger_val; else - ALOGE("Setting S%d (%s) trigger to %s FAILED.\n", s, - sensor[s].friendly_name, trigger_val); + ALOGE("Setting S%d (%s) trigger to %s FAILED.\n", s, sensor[s].friendly_name, trigger_val); return ret; } +static int enable_event(int dev_num, const char *name, int enabled) +{ + char sysfs_path[PATH_MAX]; + + sprintf(sysfs_path, EVENTS_PATH "%s", dev_num, name); + return sysfs_write_int(sysfs_path, enabled); +} + +static int enable_sensor(int dev_num, const char *tag, int enabled) +{ + char sysfs_path[PATH_MAX]; + + sprintf(sysfs_path, SENSOR_ENABLE_PATH, dev_num, tag); + return sysfs_write_int(sysfs_path, enabled); +} static void enable_iio_timestamp (int dev_num, int known_channels) { @@ -195,8 +211,7 @@ static void enable_iio_timestamp (int dev_num, int known_channels) } -static int decode_type_spec (const char type_buf[MAX_TYPE_SPEC_LEN], - struct datum_info_t *type_info) +static int decode_type_spec (const char type_buf[MAX_TYPE_SPEC_LEN], datum_info_t *type_info) { /* Return size in bytes for this type specification, or -1 in error */ char sign; @@ -206,17 +221,13 @@ static int decode_type_spec (const char type_buf[MAX_TYPE_SPEC_LEN], /* Valid specs: "le:u10/16>>0", "le:s16/32>>0" or "le:s32/32>>0" */ - tokens = sscanf(type_buf, "%ce:%c%u/%u>>%u", - &endianness, &sign, &realbits, &storagebits, &shift); + tokens = sscanf(type_buf, "%ce:%c%u/%u>>%u", &endianness, &sign, &realbits, &storagebits, &shift); - if (tokens != 5 || - (endianness != 'b' && endianness != 'l') || - (sign != 'u' && sign != 's') || - realbits > storagebits || - (storagebits != 16 && storagebits != 32 && storagebits != 64)) { + if (tokens != 5 || (endianness != 'b' && endianness != 'l') || (sign != 'u' && sign != 's') || + realbits > storagebits || (storagebits != 16 && storagebits != 32 && storagebits != 64)) { ALOGE("Invalid iio channel type spec: %s\n", type_buf); return -1; - } + } type_info->endianness = endianness; type_info->sign = sign; @@ -231,16 +242,11 @@ static int decode_type_spec (const char type_buf[MAX_TYPE_SPEC_LEN], void build_sensor_report_maps (int dev_num) { /* - * Read sysfs files from a iio device's scan_element directory, and - * build a couple of tables from that data. These tables will tell, for - * each sensor, where to gather relevant data in a device report, i.e. - * the structure that we read from the /dev/iio:deviceX file in order to - * sensor report, itself being the data that we return to Android when a - * sensor poll completes. The mapping should be straightforward in the - * case where we have a single sensor active per iio device but, this is - * not the general case. In general several sensors can be handled - * through a single iio device, and the _en, _index and _type syfs - * entries all concur to paint a picture of what the structure of the + * Read sysfs files from a iio device's scan_element directory, and build a couple of tables from that data. These tables will tell, for + * each sensor, where to gather relevant data in a device report, i.e. the structure that we read from the /dev/iio:deviceX file in order to + * sensor report, itself being the data that we return to Android when a sensor poll completes. The mapping should be straightforward in the + * case where we have a single sensor active per iio device but, this is not the general case. In general several sensors can be handled + * through a single iio device, and the _en, _index and _type syfs entries all concur to paint a picture of what the structure of the * device report is. */ @@ -251,7 +257,7 @@ void build_sensor_report_maps (int dev_num) int ch_index; char* ch_spec; char spec_buf[MAX_TYPE_SPEC_LEN]; - struct datum_info_t* ch_info; + datum_info_t* ch_info; int size; char sysfs_path[PATH_MAX]; int known_channels; @@ -273,18 +279,14 @@ void build_sensor_report_maps (int dev_num) for (c=0; c= MAX_SENSORS) { ALOGE("Index out of bounds!: %s\n", sysfs_path); @@ -321,15 +320,15 @@ void build_sensor_report_maps (int dev_num) known_channels++; } + sensor_update_max_range(s); + /* Stop sampling - if we are recovering from hal restart */ enable_buffer(dev_num, 0); setup_trigger(s, "\n"); /* Turn on channels we're aware of */ for (c=0;c MAX_DEVICE_REPORT_SIZE) { - ALOGE("Unexpectedly large scan buffer on iio dev%d: %d bytes\n", - dev_num, expected_dev_report_size[dev_num]); + ALOGE("Unexpectedly large scan buffer on iio dev%d: %d bytes\n", dev_num, expected_dev_report_size[dev_num]); expected_dev_report_size[dev_num] = MAX_DEVICE_REPORT_SIZE; } @@ -389,67 +383,85 @@ int adjust_counters (int s, int enabled, int from_virtual) * Adjust counters based on sensor enable action. Return values are: * 0 if the operation was completed and we're all set * 1 if we toggled the state of the sensor and there's work left + * -1 in case of an error */ int dev_num = sensor[s].dev_num; if (!check_state_change(s, enabled, from_virtual)) - /* The state of the sensor remains the same: we're done */ - return 0; + return 0; /* The state of the sensor remains the same: we're done */ if (enabled) { - ALOGI("Enabling sensor %d (iio device %d: %s)\n", - s, dev_num, sensor[s].friendly_name); + ALOGI("Enabling sensor %d (iio device %d: %s)\n", s, dev_num, sensor[s].friendly_name); switch (sensor[s].type) { + case SENSOR_TYPE_ACCELEROMETER: + accel_cal_init(s); + break; + case SENSOR_TYPE_MAGNETIC_FIELD: - compass_read_data(&sensor[s]); + compass_read_data(s); break; case SENSOR_TYPE_GYROSCOPE: - gyro_cal_init(&sensor[s]); + gyro_cal_init(s); break; } } else { - ALOGI("Disabling sensor %d (iio device %d: %s)\n", s, dev_num, - sensor[s].friendly_name); + ALOGI("Disabling sensor %d (iio device %d: %s)\n", s, dev_num, sensor[s].friendly_name); /* Sensor disabled, lower report available flag */ sensor[s].report_pending = 0; - if (sensor[s].type == SENSOR_TYPE_MAGNETIC_FIELD) - compass_store_data(&sensor[s]); + /* Save calibration data to persistent storage */ + switch (sensor[s].type) { + case SENSOR_TYPE_ACCELEROMETER: + accel_cal_store(s); + break; - if (sensor[s].type == SENSOR_TYPE_GYROSCOPE) - gyro_store_data(&sensor[s]); + case SENSOR_TYPE_MAGNETIC_FIELD: + compass_store_data(s); + break; + + case SENSOR_TYPE_GYROSCOPE: + gyro_store_data(s); + break; + } } /* We changed the state of a sensor: adjust device ref counts */ - if (sensor[s].num_channels) { - - if (enabled) - trig_sensors_per_dev[dev_num]++; - else - trig_sensors_per_dev[dev_num]--; + switch(sensor[s].mode) { + case MODE_TRIGGER: + if (enabled) + trig_sensors_per_dev[dev_num]++; + else + trig_sensors_per_dev[dev_num]--; + return 1; + case MODE_POLL: + if (enabled) { + active_poll_sensors++; + poll_sensors_per_dev[dev_num]++; return 1; - } - - if (enabled) { - active_poll_sensors++; - poll_sensors_per_dev[dev_num]++; + } else { + active_poll_sensors--; + poll_sensors_per_dev[dev_num]--; + return 1; + } + case MODE_EVENT: return 1; + default: + /* Invalid sensor mode */ + return -1; } - - active_poll_sensors--; - poll_sensors_per_dev[dev_num]--; - return 1; } -static int get_field_count (int s) +static int get_field_count (int s, size_t *field_size) { + *field_size = sizeof(float); + switch (sensor[s].type) { case SENSOR_TYPE_ACCELEROMETER: /* m/s^2 */ case SENSOR_TYPE_MAGNETIC_FIELD: /* micro-tesla */ @@ -458,65 +470,101 @@ static int get_field_count (int s) case SENSOR_TYPE_GYROSCOPE: /* radians/s */ return 3; + case SENSOR_TYPE_INTERNAL_INTENSITY: + case SENSOR_TYPE_INTERNAL_ILLUMINANCE: case SENSOR_TYPE_LIGHT: /* SI lux units */ case SENSOR_TYPE_AMBIENT_TEMPERATURE: /* °C */ case SENSOR_TYPE_TEMPERATURE: /* °C */ case SENSOR_TYPE_PROXIMITY: /* centimeters */ case SENSOR_TYPE_PRESSURE: /* hecto-pascal */ case SENSOR_TYPE_RELATIVE_HUMIDITY: /* percent */ + case SENSOR_TYPE_STEP_DETECTOR: /* event: always 1 */ return 1; case SENSOR_TYPE_ROTATION_VECTOR: return 4; + case SENSOR_TYPE_STEP_COUNTER: /* number of steps */ + *field_size = sizeof(uint64_t); + return 1; default: ALOGE("Unknown sensor type!\n"); return 0; /* Drop sample */ } } +/* + * CTS acceptable thresholds: + * EventGapVerification.java: (th <= 1.8) + * FrequencyVerification.java: (0.9)*(expected freq) => (th <= 1.1111) + */ +#define THRESHOLD 1.10 +#define MAX_DELAY 500000000 /* 500 ms */ + +void set_report_ts(int s, int64_t ts) +{ + int64_t maxTs, period; + + /* + * A bit of a hack to please a bunch of cts tests. They + * expect the timestamp to be exacly according to the set-up + * frequency but if we're simply getting the timestamp at hal level + * this may not be the case. Perhaps we'll get rid of this when + * we'll be reading the timestamp from the iio channel for all sensors + */ + if (sensor[s].report_ts && sensor[s].sampling_rate && + REPORTING_MODE(sensor_desc[s].flags) == SENSOR_FLAG_CONTINUOUS_MODE) + { + period = (int64_t) (1000000000.0 / sensor[s].sampling_rate); + maxTs = sensor[s].report_ts + THRESHOLD * period; + /* If we're too far behind get back on track */ + if (ts - maxTs >= MAX_DELAY) + maxTs = ts; + sensor[s].report_ts = (ts < maxTs ? ts : maxTs); + } else { + sensor[s].report_ts = ts; + } +} static void* acquisition_routine (void* param) { /* - * Data acquisition routine run in a dedicated thread, covering a single - * sensor. This loop will periodically retrieve sampling data through - * sysfs, then package it as a sample and transfer it to our master poll - * loop through a report fd. Checks for a cancellation signal quite - * frequently, as the thread may be disposed of at any time. Note that - * Bionic does not provide pthread_cancel / pthread_testcancel... + * Data acquisition routine run in a dedicated thread, covering a single sensor. This loop will periodically retrieve sampling data through + * sysfs, then package it as a sample and transfer it to our master poll loop through a report fd. Checks for a cancellation signal quite + * frequently, as the thread may be disposed of at any time. Note that Bionic does not provide pthread_cancel / pthread_testcancel... */ int s = (int) (size_t) param; - int num_fields, sample_size; - struct sensors_event_t data = {0}; + int num_fields; + sensors_event_t data = {0}; int c; int ret; struct timespec target_time; int64_t timestamp, period, start, stop; + size_t field_size; if (s < 0 || s >= sensor_count) { ALOGE("Invalid sensor handle!\n"); return NULL; } - ALOGI("Entering data acquisition thread S%d (%s), rate:%g\n", - s, sensor[s].friendly_name, sensor[s].sampling_rate); + ALOGI("Entering S%d (%s) data acquisition thread: rate:%g\n", s, sensor[s].friendly_name, sensor[s].sampling_rate); if (sensor[s].sampling_rate <= 0) { - ALOGE("Invalid rate in acquisition routine for sensor %d: %g\n", - s, sensor[s].sampling_rate); + ALOGE("Invalid rate in acquisition routine for sensor %d: %g\n", s, sensor[s].sampling_rate); return NULL; } - num_fields = get_field_count(s); - sample_size = sizeof(int64_t) + num_fields * sizeof(float); + /* Initialize data fields that will be shared by all sensor reports */ + data.version = sizeof(sensors_event_t); + data.sensor = s; + data.type = sensor_desc[s].type; + + num_fields = get_field_count(s, &field_size); /* - * Each condition variable is associated to a mutex that has to be - * locked by the thread that's waiting on it. We use these condition - * variables to get the acquisition threads out of sleep quickly after - * the sampling rate is adjusted, or the sensor is disabled. + * Each condition variable is associated to a mutex that has to be locked by the thread that's waiting on it. We use these condition + * variables to get the acquisition threads out of sleep quickly after the sampling rate is adjusted, or the sensor is disabled. */ pthread_mutex_lock(&thread_release_mutex[s]); @@ -526,51 +574,47 @@ static void* acquisition_routine (void* param) /* Check and honor termination requests */ while (sensor[s].thread_data_fd[1] != -1) { start = get_timestamp_boot(); + /* Read values through sysfs */ for (c=0; c arbitrated_rate) /* If sensor i depends on sensor s */ + arbitrated_rate = sensor[i].requested_rate; + + /* If any of the currently active sensors we rely on is using a higher sampling rate, switch to this rate */ + for (vi = 0; vi < sensor[s].base_count; vi++) { + i = sensor[s].base[vi]; + if (is_enabled(i) && sensor[i].requested_rate > arbitrated_rate) + arbitrated_rate = sensor[i].requested_rate; + } + + return arbitrated_rate; +} + +extern float sensor_get_max_freq (int s); + +static float select_closest_available_rate(int s, float requested_rate) +{ + float sr; + int j; + float selected_rate = 0; + float max_rate_from_prop = sensor_get_max_freq(s); + int dev_num = sensor[s].dev_num; + + if (!sensor[s].avail_freqs_count) + return requested_rate; + + for (j = 0; j < sensor[s].avail_freqs_count; j++) { + + sr = sensor[s].avail_freqs[j]; + + /* If this matches the selected rate, we're happy. Have some tolerance for rounding errors and avoid needless jumps to higher rates */ + if ((fabs(requested_rate - sr) <= 0.01) && (sr <= max_rate_from_prop)) { + return sr; + } + + /* Select rate if it's less than max freq */ + if ((sr > selected_rate) && (sr <= max_rate_from_prop)) { + selected_rate = sr; + } + + /* + * If we reached a higher value than the desired rate, adjust selected rate so it matches the first higher available one and + * stop parsing - this makes the assumption that rates are sorted by increasing value in the allowed frequencies string. + */ + if (sr > requested_rate) { + return selected_rate; + } + } + + /* Check for wrong values */ + if (selected_rate < 0.1) { + return requested_rate; + } else { + return selected_rate; + } +} + static int sensor_set_rate (int s, float requested_rate) { - /* Set the rate at which a specific sensor should report events */ - /* See Android sensors.h for indication on sensor trigger modes */ + /* Set the rate at which a specific sensor should report events. See Android sensors.h for indication on sensor trigger modes */ char sysfs_path[PATH_MAX]; - char avail_sysfs_path[PATH_MAX]; int dev_num = sensor[s].dev_num; int i = sensor[s].catalog_index; const char *prefix = sensor_catalog[i].tag; int per_sensor_sampling_rate; int per_device_sampling_rate; - int32_t min_delay_us = sensor_desc[s].minDelay; - max_delay_t max_delay_us = sensor_desc[s].maxDelay; - float min_supported_rate = max_delay_us ? 1000000.0/max_delay_us : 1; - float max_supported_rate = - min_delay_us && min_delay_us != -1 ? 1000000.0/min_delay_us : 0; - char freqs_buf[100]; - char* cursor; int n; float sr; + float group_max_sampling_rate; float cur_sampling_rate; /* Currently used sampling rate */ float arb_sampling_rate; /* Granted sampling rate after arbitration */ + char hrtimer_sampling_path[PATH_MAX]; + char trigger_path[PATH_MAX]; - ALOGV("Sampling rate %g requested on sensor %d (%s)\n", requested_rate, - s, sensor[s].friendly_name); + ALOGV("Sampling rate %g requested on sensor %d (%s)\n", requested_rate, s, sensor[s].friendly_name); sensor[s].requested_rate = requested_rate; arb_sampling_rate = requested_rate; - if (arb_sampling_rate < min_supported_rate) { - ALOGV("Sampling rate %g too low for %s, using %g instead\n", - arb_sampling_rate, sensor[s].friendly_name, - min_supported_rate); + if (arb_sampling_rate < sensor[s].min_supported_rate) { + ALOGV("Sampling rate %g too low for %s, using %g instead\n", arb_sampling_rate, sensor[s].friendly_name, sensor[s].min_supported_rate); + arb_sampling_rate = sensor[s].min_supported_rate; + } + + /* If one of the linked sensors uses a higher rate, adopt it */ + group_max_sampling_rate = get_group_max_sampling_rate(s); - arb_sampling_rate = min_supported_rate; + if (arb_sampling_rate < group_max_sampling_rate) { + ALOGV("Using %s sampling rate to %g too due to dependency\n", sensor[s].friendly_name, arb_sampling_rate); + arb_sampling_rate = group_max_sampling_rate; } - if (max_supported_rate && arb_sampling_rate > max_supported_rate) { - ALOGV("Sampling rate %g too high for %s, using %g instead\n", - arb_sampling_rate, sensor[s].friendly_name, max_supported_rate); - arb_sampling_rate = max_supported_rate; + if (sensor[s].max_supported_rate && arb_sampling_rate > sensor[s].max_supported_rate) { + ALOGV("Sampling rate %g too high for %s, using %g instead\n", arb_sampling_rate, sensor[s].friendly_name, sensor[s].max_supported_rate); + arb_sampling_rate = sensor[s].max_supported_rate; } sensor[s].sampling_rate = arb_sampling_rate; + /* If the sensor is virtual, we're done */ + if (sensor[s].is_virtual) + return 0; + /* If we're dealing with a poll-mode sensor */ - if (!sensor[s].num_channels) { + if (sensor[s].mode == MODE_POLL) { if (is_enabled(s)) - /* Wake up thread so the new sampling rate gets used */ - pthread_cond_signal(&thread_release_cond[s]); + pthread_cond_signal(&thread_release_cond[s]); /* Wake up thread so the new sampling rate gets used */ return 0; } @@ -760,94 +869,55 @@ static int sensor_set_rate (int s, float requested_rate) return -ENOSYS; } - /* Check if we have contraints on allowed sampling rates */ - - sprintf(avail_sysfs_path, DEVICE_AVAIL_FREQ_PATH, dev_num); - - if (sysfs_read_str(avail_sysfs_path, freqs_buf, sizeof(freqs_buf)) > 0){ - cursor = freqs_buf; - - /* Decode allowed sampling rates string, ex: "10 20 50 100" */ - - /* While we're not at the end of the string */ - while (*cursor && cursor[0]) { - - /* Decode a single value */ - sr = strtod(cursor, NULL); - - /* - * If this matches the selected rate, we're happy. - * Have some tolerance to counter rounding errors and - * avoid needless jumps to higher rates. - */ - if (fabs(arb_sampling_rate - sr) <= 0.001) { - arb_sampling_rate = sr; - break; - } - - /* - * If we reached a higher value than the desired rate, - * adjust selected rate so it matches the first higher - * available one and stop parsing - this makes the - * assumption that rates are sorted by increasing value - * in the allowed frequencies string. - */ - if (sr > arb_sampling_rate) { - arb_sampling_rate = sr; - break; - } - - /* Skip digits */ - while (cursor[0] && !isspace(cursor[0])) - cursor++; - - /* Skip spaces */ - while (cursor[0] && isspace(cursor[0])) - cursor++; - } - } - - if (max_supported_rate && - arb_sampling_rate > max_supported_rate) { - arb_sampling_rate = max_supported_rate; + if (sensor[s].hrtimer_trigger_name[0] != '\0') { + snprintf(trigger_path, PATH_MAX, "%s%s%d/", IIO_DEVICES, "trigger", sensor[s].trigger_nr); + snprintf(hrtimer_sampling_path, PATH_MAX, "%s%s", trigger_path, "sampling_frequency"); + /* Enforce frequency update when software trigger + * frequency and current sampling rate are different */ + if (sysfs_read_float(hrtimer_sampling_path, &sr) != -1 && sr != cur_sampling_rate) + cur_sampling_rate = -1; + } else { + arb_sampling_rate = select_closest_available_rate(s, arb_sampling_rate); } + /* Record the rate that was agreed upon with the sensor taken in isolation ; this avoid uncontrolled ripple effects between colocated sensor rates */ + sensor[s].semi_arbitrated_rate = arb_sampling_rate; /* Coordinate with others active sensors on the same device, if any */ if (per_device_sampling_rate) for (n=0; n arb_sampling_rate) { - ALOGV("Sampling rate shared between %s and %s, using %g instead of %g\n" - , sensor[s].friendly_name, sensor[n].friendly_name, - sensor[n].sampling_rate, arb_sampling_rate); - arb_sampling_rate = sensor[n].sampling_rate; + if (n != s && sensor[n].dev_num == dev_num && sensor[n].num_channels && is_enabled(n) && + sensor[n].semi_arbitrated_rate > arb_sampling_rate) { + ALOGV("Sampling rate shared between %s and %s, using %g instead of %g\n", sensor[s].friendly_name, sensor[n].friendly_name, + sensor[n].semi_arbitrated_rate, arb_sampling_rate); + arb_sampling_rate = sensor[n].semi_arbitrated_rate; } sensor[s].sampling_rate = arb_sampling_rate; - /* - * Update actual sampling rate field for this sensor and others which - * may be sharing the same sampling rate. - */ + /* Update actual sampling rate field for this sensor and others which may be sharing the same sampling rate */ if (per_device_sampling_rate) for (n=0; n arbitrated_rate) - arbitrated_rate = sensor[i].requested_rate; + if (sensor[s].is_virtual) { + /* Take care of downwards dependencies */ + for (i=0; i (th <= 1.1111) - */ -#define THRESHOLD 1.10 -#define MAX_DELAY 500000000 /* 500 ms */ - -void set_report_ts(int s, int64_t ts) -{ - int64_t maxTs, period; - - /* - * A bit of a hack to please a bunch of cts tests. They - * expect the timestamp to be exacly according to the set-up - * frequency but if we're simply getting the timestamp at hal level - * this may not be the case. Perhaps we'll get rid of this when - * we'll be reading the timestamp from the iio channel for all sensors - */ - if (sensor[s].report_ts && sensor[s].sampling_rate && - REPORTING_MODE(sensor_desc[s].flags) == SENSOR_FLAG_CONTINUOUS_MODE) - { - period = (int64_t) (1000000000LL / sensor[s].sampling_rate); - maxTs = sensor[s].report_ts + THRESHOLD * period; - /* If we're too far behind get back on track */ - if (ts - maxTs >= MAX_DELAY) - maxTs = ts; - sensor[s].report_ts = (ts < maxTs ? ts : maxTs); - } else { - sensor[s].report_ts = ts; - } -} - - static void stamp_reports (int dev_num, int64_t ts) { int s; for (s=0; s= MAX_DEVICES) { - ALOGE("Event reported on unexpected iio device %d\n", dev_num); - return -1; - } - - if (device_fd[dev_num] == -1) { + if (fd == -1) { ALOGE("Ignoring stale report on iio device %d\n", dev_num); return -1; } - len = read(device_fd[dev_num], buf, expected_dev_report_size[dev_num]); + len = read(fd, buf, expected_dev_report_size[dev_num]); if (len == -1) { - ALOGE("Could not read report from iio device %d (%s)\n", - dev_num, strerror(errno)); + ALOGE("Could not read report from iio device %d (%s)\n", dev_num, strerror(errno)); return -1; } @@ -1206,16 +1259,14 @@ static int integrate_device_report (int dev_num) /* Map device report to sensor reports */ for (s=0; s= MAX_DEVICES) { + ALOGE("Event reported on unexpected iio device %d\n", dev_num); + return -1; + } + +#ifndef __NO_EVENTS__ + if (events_fd[dev_num] != -1) { + ret = integrate_device_report_from_event(dev_num, events_fd[dev_num]); + if (ret < 0) + return ret; + } +#endif + + if (device_fd[dev_num] != -1) + ret = integrate_device_report_from_dev(dev_num, device_fd[dev_num]); + + return ret; +} -static int propagate_vsensor_report (int s, struct sensors_event_t *data) +static int propagate_vsensor_report (int s, sensors_event_t *data) { /* There's a new report stored in sensor.sample for this sensor; transmit it */ - memcpy(data, &sensor[s].sample, sizeof(struct sensors_event_t)); + memcpy(data, &sensor[s].sample, sizeof(sensors_event_t)); data->sensor = s; - data->type = sensor[s].type; + data->type = sensor_desc[s].type; /* sensor_desc[s].type can differ from sensor[s].type ; internal types are remapped */ return 1; } -static int propagate_sensor_report (int s, struct sensors_event_t *data) +static int propagate_sensor_report (int s, sensors_event_t *data) { /* There's a sensor report pending for this sensor ; transmit it */ - int num_fields = get_field_count(s); + size_t field_size; + int num_fields = get_field_count(s, &field_size); int c; unsigned char* current_sample; + int ret; /* If there's nothing to return... we're done */ if (!num_fields) return 0; + ALOGV("Sample on sensor %d (type %d):\n", s, sensor[s].type); + + if (sensor[s].mode == MODE_POLL) { + /* We received a good sample but we're not directly enabled so we'll drop */ + if (!sensor[s].directly_enabled) + return 0; + /* Use the data provided by the acquisition thread */ + ALOGV("Reporting data from worker thread for S%d\n", s); + memcpy(data, &sensor[s].sample, sizeof(sensors_event_t)); + data->timestamp = sensor[s].report_ts; + return 1; + } + memset(data, 0, sizeof(sensors_event_t)); data->version = sizeof(sensors_event_t); data->sensor = s; - data->type = sensor[s].type; + data->type = sensor_desc[s].type; /* sensor_desc[s].type can differ from sensor[s].type ; internal types are remapped */ data->timestamp = sensor[s].report_ts; - ALOGV("Sample on sensor %d (type %d):\n", s, sensor[s].type); - - current_sample = sensor[s].report_buffer; +#ifndef __NO_EVENTS__ + if (sensor[s].mode == MODE_EVENT) { + ALOGV("Reporting event\n"); + /* Android requires events to return 1.0 */ + int dir = IIO_EVENT_CODE_EXTRACT_DIR(sensor[s].event_id); + switch (sensor[s].type) { + case SENSOR_TYPE_PROXIMITY: + if (dir == IIO_EV_DIR_FALLING) + data->data[0] = 0.0; + else + data->data[0] = 1.0; + break; + default: + data->data[0] = 1.0; + break; - /* If this is a poll sensor */ - if (!sensor[s].num_channels) { - /* Use the data provided by the acquisition thread */ - ALOGV("Reporting data from worker thread for S%d\n", s); - memcpy(data->data, current_sample, num_fields * sizeof(float)); + } + data->data[1] = 0.0; + data->data[2] = 0.0; return 1; } +#endif /* Convert the data into the expected Android-level format */ + + current_sample = sensor[s].report_buffer; + for (c=0; cdata[c] = sensor[s].ops.transform - (s, c, current_sample); + data->data[c] = sensor[s].ops.transform (s, c, current_sample); - ALOGV("\tfield %d: %f\n", c, data->data[c]); + ALOGV("\tfield %d: %g\n", c, data->data[c]); current_sample += sensor[s].channel[c].size; } - /* - * The finalize routine, in addition to its late sample processing duty, - * has the final say on whether or not the sample gets sent to Android. - */ - return sensor[s].ops.finalize(s, data); + ret = sensor[s].ops.finalize(s, data); + + /* We will drop samples if the sensor is not directly enabled */ + if (!sensor[s].directly_enabled) + return 0; + + /* The finalize routine, in addition to its late sample processing duty, has the final say on whether or not the sample gets sent to Android */ + return ret; } static void synthetize_duplicate_samples (void) { /* - * Some sensor types (ex: gyroscope) are defined as continuously firing - * by Android, despite the fact that we can be dealing with iio drivers - * that only report events for new samples. For these we generate - * reports periodically, duplicating the last data we got from the - * driver. This is not necessary for polling sensors. + * Some sensor types (ex: gyroscope) are defined as continuously firing by Android, despite the fact that + * we can be dealing with iio drivers that only report events for new samples. For these we generate reports + * periodically, duplicating the last data we got from the driver. This is not necessary for polling sensors. */ int s; @@ -1360,8 +1498,7 @@ static void synthetize_duplicate_samples (void) continue; /* If the sensor is continuously firing, leave it alone */ - if (sensor[s].selected_trigger != - sensor[s].motion_trigger_name) + if (sensor[s].selected_trigger != sensor[s].motion_trigger_name) continue; /* If we haven't seen a sample, there's nothing to duplicate */ @@ -1376,7 +1513,7 @@ static void synthetize_duplicate_samples (void) if (!sensor[s].sampling_rate) continue; - period = (int64_t) (1000000000.0/ sensor[s].sampling_rate); + period = (int64_t) (1000000000.0 / sensor[s].sampling_rate); current_ts = get_timestamp_boot(); target_ts = sensor[s].report_ts + period; @@ -1394,33 +1531,19 @@ static void integrate_thread_report (uint32_t tag) { int s = tag - THREAD_REPORT_TAG_BASE; int len; - int expected_len; - int64_t timestamp; - unsigned char current_sample[MAX_SENSOR_REPORT_SIZE]; - - expected_len = sizeof(int64_t) + get_field_count(s) * sizeof(float); - - len = read(sensor[s].thread_data_fd[0], - current_sample, - expected_len); - memcpy(×tamp, current_sample, sizeof(int64_t)); - memcpy(sensor[s].report_buffer, sizeof(int64_t) + current_sample, - expected_len - sizeof(int64_t)); + len = read(sensor[s].thread_data_fd[0], &sensor[s].sample, sizeof(sensors_event_t)); - if (len == expected_len) { - set_report_ts(s, timestamp); + if (len == sizeof(sensors_event_t)) sensor[s].report_pending = DATA_SYSFS; - } } static int get_poll_wait_timeout (void) { /* - * Compute an appropriate timeout value, in ms, for the epoll_wait - * call that's going to await for iio device reports and incoming - * reports from our sensor sysfs data reader threads. + * Compute an appropriate timeout value, in ms, for the epoll_wait call that's going to await + * for iio device reports and incoming reports from our sensor sysfs data reader threads. */ int s; @@ -1429,18 +1552,12 @@ static int get_poll_wait_timeout (void) int64_t period; /* - * Check if we're dealing with a driver that only send events when - * there is motion, despite the fact that the associated Android sensor - * type is continuous rather than on-change. In that case we have to - * duplicate events. Check deadline for the nearest upcoming event. + * Check if we're dealing with a driver that only send events when there is motion, despite the fact that the associated Android sensor + * type is continuous rather than on-change. In that case we have to duplicate events. Check deadline for the nearest upcoming event. */ for (s=0; s