2 * Copyright (C) 2014-2015 Intel Corporation.
11 #include <sys/epoll.h>
12 #include <sys/ioctl.h>
13 #include <sys/socket.h>
14 #include <utils/Log.h>
15 #include <hardware/sensors.h>
16 #include <linux/ioctl.h>
18 #include "enumeration.h"
20 #include "transform.h"
21 #include "calibration.h"
22 #include "description.h"
23 #include "filtering.h"
24 #include <linux/iio/events.h>
25 /* Currently active sensors count, per device */
26 static int poll_sensors_per_dev[MAX_DEVICES]; /* poll-mode sensors */
27 static int trig_sensors_per_dev[MAX_DEVICES]; /* trigger, event based */
29 static int device_fd[MAX_DEVICES]; /* fd on the /dev/iio:deviceX file */
30 static int events_fd[MAX_DEVICES]; /* fd on the /sys/bus/iio/devices/iio:deviceX/events/<event_name> file */
31 static int has_iio_ts[MAX_DEVICES]; /* ts channel available on this iio dev */
32 static int expected_dev_report_size[MAX_DEVICES]; /* expected iio scan len */
33 static int poll_fd; /* epoll instance covering all enabled sensors */
35 static int active_poll_sensors; /* Number of enabled poll-mode sensors */
37 /* We use pthread condition variables to get worker threads out of sleep */
38 static pthread_condattr_t thread_cond_attr [MAX_SENSORS];
39 static pthread_cond_t thread_release_cond [MAX_SENSORS];
40 static pthread_mutex_t thread_release_mutex [MAX_SENSORS];
43 * We associate tags to each of our poll set entries. These tags have the following values:
44 * - a iio device number if the fd is a iio character device fd
45 * - THREAD_REPORT_TAG_BASE + sensor handle if the fd is the receiving end of a pipe used by a sysfs data acquisition thread
47 #define THREAD_REPORT_TAG_BASE 1000
49 /* If buffer enable fails, we may want to retry a few times before giving up */
50 #define ENABLE_BUFFER_RETRIES 3
51 #define ENABLE_BUFFER_RETRY_DELAY_MS 10
54 inline int is_enabled (int s)
56 return sensor[s].directly_enabled || sensor[s].ref_count;
60 static int check_state_change (int s, int enabled, int from_virtual)
63 if (sensor[s].directly_enabled)
64 return 0; /* We're being enabled but already were directly activated: no change. */
67 sensor[s].directly_enabled = 1; /* We're being directly enabled */
69 if (sensor[s].ref_count)
70 return 0; /* We were already indirectly enabled */
72 return 1; /* Do continue enabling this sensor */
76 return 0; /* We are being disabled but already were: no change */
78 if (from_virtual && sensor[s].directly_enabled)
79 return 0; /* We're indirectly disabled but the base is still active */
81 sensor[s].directly_enabled = 0; /* We're now directly disabled */
83 if (!from_virtual && sensor[s].ref_count)
84 return 0; /* We still have ref counts */
86 return 1; /* Do continue disabling this sensor */
90 static int enable_buffer (int dev_num, int enabled)
92 char sysfs_path[PATH_MAX];
93 int retries = ENABLE_BUFFER_RETRIES;
95 sprintf(sysfs_path, ENABLE_PATH, dev_num);
98 /* Low level, non-multiplexed, enable/disable routine */
99 if (sysfs_write_int(sysfs_path, enabled) > 0)
102 ALOGE("Failed enabling buffer on dev%d, retrying", dev_num);
103 usleep(ENABLE_BUFFER_RETRY_DELAY_MS*1000);
107 ALOGE("Could not enable buffer\n");
112 static int setup_trigger (int s, const char* trigger_val)
114 char sysfs_path[PATH_MAX];
115 int ret = -1, attempts = 5;
117 sprintf(sysfs_path, TRIGGER_PATH, sensor[s].dev_num);
119 if (trigger_val[0] != '\n')
120 ALOGI("Setting S%d (%s) trigger to %s\n", s, sensor[s].friendly_name, trigger_val);
122 while (ret == -1 && attempts) {
123 ret = sysfs_write_str(sysfs_path, trigger_val);
128 sensor[s].selected_trigger = trigger_val;
130 ALOGE("Setting S%d (%s) trigger to %s FAILED.\n", s, sensor[s].friendly_name, trigger_val);
134 static int enable_event(int dev_num, const char *name, int enabled)
136 char sysfs_path[PATH_MAX];
138 sprintf(sysfs_path, EVENTS_PATH "%s", dev_num, name);
139 return sysfs_write_int(sysfs_path, enabled);
142 static int enable_sensor(int dev_num, const char *tag, int enabled)
144 char sysfs_path[PATH_MAX];
146 sprintf(sysfs_path, SENSOR_ENABLE_PATH, dev_num, tag);
147 return sysfs_write_int(sysfs_path, enabled);
150 static void enable_iio_timestamp (int dev_num, int known_channels)
152 /* Check if we have a dedicated iio timestamp channel */
154 char spec_buf[MAX_TYPE_SPEC_LEN];
155 char sysfs_path[PATH_MAX];
158 sprintf(sysfs_path, CHANNEL_PATH "%s", dev_num, "in_timestamp_type");
160 n = sysfs_read_str(sysfs_path, spec_buf, sizeof(spec_buf));
165 if (strcmp(spec_buf, "le:s64/64>>0"))
168 /* OK, type is int64_t as expected, in little endian representation */
170 sprintf(sysfs_path, CHANNEL_PATH"%s", dev_num, "in_timestamp_index");
172 if (sysfs_read_int(sysfs_path, &n))
175 /* Check that the timestamp comes after the other fields we read */
176 if (n != known_channels)
179 /* Try enabling that channel */
180 sprintf(sysfs_path, CHANNEL_PATH "%s", dev_num, "in_timestamp_en");
182 sysfs_write_int(sysfs_path, 1);
184 if (sysfs_read_int(sysfs_path, &n))
188 ALOGI("Detected timestamp channel on iio device %d\n", dev_num);
189 has_iio_ts[dev_num] = 1;
194 static int decode_type_spec (const char type_buf[MAX_TYPE_SPEC_LEN], datum_info_t *type_info)
196 /* Return size in bytes for this type specification, or -1 in error */
199 unsigned int realbits, storagebits, shift;
202 /* Valid specs: "le:u10/16>>0", "le:s16/32>>0" or "le:s32/32>>0" */
204 tokens = sscanf(type_buf, "%ce:%c%u/%u>>%u", &endianness, &sign, &realbits, &storagebits, &shift);
206 if (tokens != 5 || (endianness != 'b' && endianness != 'l') || (sign != 'u' && sign != 's') ||
207 realbits > storagebits || (storagebits != 16 && storagebits != 32 && storagebits != 64)) {
208 ALOGE("Invalid iio channel type spec: %s\n", type_buf);
212 type_info->endianness = endianness;
213 type_info->sign = sign;
214 type_info->realbits = (short) realbits;
215 type_info->storagebits = (short) storagebits;
216 type_info->shift = (short) shift;
218 return storagebits / 8;
222 void build_sensor_report_maps (int dev_num)
225 * 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
226 * 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
227 * sensor report, itself being the data that we return to Android when a sensor poll completes. The mapping should be straightforward in the
228 * 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
229 * 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
239 char spec_buf[MAX_TYPE_SPEC_LEN];
240 datum_info_t* ch_info;
242 char sysfs_path[PATH_MAX];
245 int channel_size_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
246 int sensor_handle_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
247 int channel_number_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
251 /* For each sensor that is linked to this device */
252 for (s=0; s<sensor_count; s++) {
253 if (sensor[s].dev_num != dev_num)
256 i = sensor[s].catalog_index;
258 /* Read channel details through sysfs attributes */
259 for (c=0; c<sensor[s].num_channels; c++) {
261 /* Read _type file */
262 sprintf(sysfs_path, CHANNEL_PATH "%s", sensor[s].dev_num, sensor_catalog[i].channel[c].type_path);
264 n = sysfs_read_str(sysfs_path, spec_buf, sizeof(spec_buf));
267 ALOGW( "Failed to read type: %s\n", sysfs_path);
271 ch_spec = sensor[s].channel[c].type_spec;
273 memcpy(ch_spec, spec_buf, sizeof(spec_buf));
275 ch_info = &sensor[s].channel[c].type_info;
277 size = decode_type_spec(ch_spec, ch_info);
279 /* Read _index file */
280 sprintf(sysfs_path, CHANNEL_PATH "%s", sensor[s].dev_num, sensor_catalog[i].channel[c].index_path);
282 n = sysfs_read_int(sysfs_path, &ch_index);
285 ALOGW( "Failed to read index: %s\n", sysfs_path);
289 if (ch_index >= MAX_SENSORS) {
290 ALOGE("Index out of bounds!: %s\n", sysfs_path);
294 /* Record what this index is about */
296 sensor_handle_from_index [ch_index] = s;
297 channel_number_from_index[ch_index] = c;
298 channel_size_from_index [ch_index] = size;
303 sensor_update_max_range(s);
305 /* Stop sampling - if we are recovering from hal restart */
306 enable_buffer(dev_num, 0);
307 setup_trigger(s, "\n");
309 /* Turn on channels we're aware of */
310 for (c=0;c<sensor[s].num_channels; c++) {
311 sprintf(sysfs_path, CHANNEL_PATH "%s", sensor[s].dev_num, sensor_catalog[i].channel[c].en_path);
312 sysfs_write_int(sysfs_path, 1);
316 ALOGI("Found %d channels on iio device %d\n", known_channels, dev_num);
319 * Now that we know which channels are defined, their sizes and their ordering, update channels offsets within device report. Note: there
320 * is a possibility that several sensors share the same index, with their data fields being isolated by masking and shifting as specified
321 * through the real bits and shift values in type attributes. This case is not currently supported. Also, the code below assumes no hole in
322 * the sequence of indices, so it is dependent on discovery of all sensors.
326 for (i=0; i<MAX_SENSORS * MAX_CHANNELS; i++) {
327 s = sensor_handle_from_index[i];
328 c = channel_number_from_index[i];
329 size = channel_size_from_index[i];
334 ALOGI("S%d C%d : offset %d, size %d, type %s\n", s, c, offset, size, sensor[s].channel[c].type_spec);
336 sensor[s].channel[c].offset = offset;
337 sensor[s].channel[c].size = size;
342 /* Enable the timestamp channel if there is one available */
343 enable_iio_timestamp(dev_num, known_channels);
345 /* Add padding and timestamp size if it's enabled on this iio device */
346 if (has_iio_ts[dev_num])
347 offset = (offset+7)/8*8 + sizeof(int64_t);
349 expected_dev_report_size[dev_num] = offset;
350 ALOGI("Expecting %d scan length on iio dev %d\n", offset, dev_num);
352 if (expected_dev_report_size[dev_num] > MAX_DEVICE_REPORT_SIZE) {
353 ALOGE("Unexpectedly large scan buffer on iio dev%d: %d bytes\n", dev_num, expected_dev_report_size[dev_num]);
355 expected_dev_report_size[dev_num] = MAX_DEVICE_REPORT_SIZE;
360 int adjust_counters (int s, int enabled, int from_virtual)
363 * Adjust counters based on sensor enable action. Return values are:
364 * 0 if the operation was completed and we're all set
365 * 1 if we toggled the state of the sensor and there's work left
366 * -1 in case of an error
369 int dev_num = sensor[s].dev_num;
371 if (!check_state_change(s, enabled, from_virtual))
372 return 0; /* The state of the sensor remains the same: we're done */
375 ALOGI("Enabling sensor %d (iio device %d: %s)\n", s, dev_num, sensor[s].friendly_name);
377 switch (sensor[s].type) {
378 case SENSOR_TYPE_ACCELEROMETER:
382 case SENSOR_TYPE_MAGNETIC_FIELD:
383 compass_read_data(s);
386 case SENSOR_TYPE_GYROSCOPE:
391 ALOGI("Disabling sensor %d (iio device %d: %s)\n", s, dev_num, sensor[s].friendly_name);
393 /* Sensor disabled, lower report available flag */
394 sensor[s].report_pending = 0;
396 /* Save calibration data to persistent storage */
397 switch (sensor[s].type) {
398 case SENSOR_TYPE_ACCELEROMETER:
402 case SENSOR_TYPE_MAGNETIC_FIELD:
403 compass_store_data(s);
406 case SENSOR_TYPE_GYROSCOPE:
412 /* We changed the state of a sensor: adjust device ref counts */
414 switch(sensor[s].mode) {
417 trig_sensors_per_dev[dev_num]++;
419 trig_sensors_per_dev[dev_num]--;
424 active_poll_sensors++;
425 poll_sensors_per_dev[dev_num]++;
428 active_poll_sensors--;
429 poll_sensors_per_dev[dev_num]--;
435 /* Invalid sensor mode */
441 static int get_field_count (int s, size_t *field_size)
443 *field_size = sizeof(float);
445 switch (sensor[s].type) {
446 case SENSOR_TYPE_ACCELEROMETER: /* m/s^2 */
447 case SENSOR_TYPE_MAGNETIC_FIELD: /* micro-tesla */
448 case SENSOR_TYPE_ORIENTATION: /* degrees */
449 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
450 case SENSOR_TYPE_GYROSCOPE: /* radians/s */
453 case SENSOR_TYPE_INTERNAL_INTENSITY:
454 case SENSOR_TYPE_INTERNAL_ILLUMINANCE:
455 case SENSOR_TYPE_LIGHT: /* SI lux units */
456 case SENSOR_TYPE_AMBIENT_TEMPERATURE: /* °C */
457 case SENSOR_TYPE_TEMPERATURE: /* °C */
458 case SENSOR_TYPE_PROXIMITY: /* centimeters */
459 case SENSOR_TYPE_PRESSURE: /* hecto-pascal */
460 case SENSOR_TYPE_RELATIVE_HUMIDITY: /* percent */
461 case SENSOR_TYPE_STEP_DETECTOR: /* event: always 1 */
464 case SENSOR_TYPE_ROTATION_VECTOR:
467 case SENSOR_TYPE_STEP_COUNTER: /* number of steps */
468 *field_size = sizeof(uint64_t);
471 ALOGE("Unknown sensor type!\n");
472 return 0; /* Drop sample */
477 * CTS acceptable thresholds:
478 * EventGapVerification.java: (th <= 1.8)
479 * FrequencyVerification.java: (0.9)*(expected freq) => (th <= 1.1111)
481 #define THRESHOLD 1.10
482 #define MAX_DELAY 500000000 /* 500 ms */
484 void set_report_ts(int s, int64_t ts)
486 int64_t maxTs, period;
489 * A bit of a hack to please a bunch of cts tests. They
490 * expect the timestamp to be exacly according to the set-up
491 * frequency but if we're simply getting the timestamp at hal level
492 * this may not be the case. Perhaps we'll get rid of this when
493 * we'll be reading the timestamp from the iio channel for all sensors
495 if (sensor[s].report_ts && sensor[s].sampling_rate &&
496 REPORTING_MODE(sensor_desc[s].flags) == SENSOR_FLAG_CONTINUOUS_MODE)
498 period = (int64_t) (1000000000.0 / sensor[s].sampling_rate);
499 maxTs = sensor[s].report_ts + THRESHOLD * period;
500 /* If we're too far behind get back on track */
501 if (ts - maxTs >= MAX_DELAY)
503 sensor[s].report_ts = (ts < maxTs ? ts : maxTs);
505 sensor[s].report_ts = ts;
509 static void* acquisition_routine (void* param)
512 * Data acquisition routine run in a dedicated thread, covering a single sensor. This loop will periodically retrieve sampling data through
513 * 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
514 * frequently, as the thread may be disposed of at any time. Note that Bionic does not provide pthread_cancel / pthread_testcancel...
517 int s = (int) (size_t) param;
519 sensors_event_t data = {0};
522 struct timespec target_time;
523 int64_t timestamp, period, start, stop;
526 if (s < 0 || s >= sensor_count) {
527 ALOGE("Invalid sensor handle!\n");
531 ALOGI("Entering S%d (%s) data acquisition thread: rate:%g\n", s, sensor[s].friendly_name, sensor[s].sampling_rate);
533 if (sensor[s].sampling_rate <= 0) {
534 ALOGE("Invalid rate in acquisition routine for sensor %d: %g\n", s, sensor[s].sampling_rate);
538 /* Initialize data fields that will be shared by all sensor reports */
539 data.version = sizeof(sensors_event_t);
541 data.type = sensor_desc[s].type;
543 num_fields = get_field_count(s, &field_size);
546 * 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
547 * variables to get the acquisition threads out of sleep quickly after the sampling rate is adjusted, or the sensor is disabled.
549 pthread_mutex_lock(&thread_release_mutex[s]);
551 /* Pinpoint the moment we start sampling */
552 timestamp = get_timestamp_monotonic();
554 /* Check and honor termination requests */
555 while (sensor[s].thread_data_fd[1] != -1) {
556 start = get_timestamp_boot();
558 /* Read values through sysfs */
559 for (c=0; c<num_fields; c++) {
560 if (field_size == sizeof(uint64_t))
561 data.u64.data[c] = acquire_immediate_uint64_value(s, c);
563 data.data[c] = acquire_immediate_float_value(s, c);
565 /* Check and honor termination requests */
566 if (sensor[s].thread_data_fd[1] == -1)
569 stop = get_timestamp_boot();
570 set_report_ts(s, start/2 + stop/2);
571 data.timestamp = sensor[s].report_ts;
572 /* If the sample looks good */
573 if (sensor[s].ops.finalize(s, &data)) {
575 /* Pipe it for transmission to poll loop */
576 ret = write(sensor[s].thread_data_fd[1], &data, sizeof(sensors_event_t));
578 if (ret != sizeof(sensors_event_t))
579 ALOGE("S%d write failure: wrote %d, got %d\n", s, sizeof(sensors_event_t), ret);
582 /* Check and honor termination requests */
583 if (sensor[s].thread_data_fd[1] == -1)
586 /* Recalculate period assuming sensor[s].sampling_rate can be changed dynamically during the thread run */
587 if (sensor[s].sampling_rate <= 0) {
588 ALOGE("Unexpected sampling rate for sensor %d: %g\n", s, sensor[s].sampling_rate);
592 period = (int64_t) (1000000000.0 / sensor[s].sampling_rate);
594 set_timestamp(&target_time, timestamp);
596 /* Wait until the sampling time elapses, or a rate change is signaled, or a thread exit is requested */
597 ret = pthread_cond_timedwait(&thread_release_cond[s], &thread_release_mutex[s], &target_time);
601 ALOGV("Acquisition thread for S%d exiting\n", s);
602 pthread_mutex_unlock(&thread_release_mutex[s]);
608 static void start_acquisition_thread (int s)
610 int incoming_data_fd;
613 struct epoll_event ev = {0};
615 ALOGV("Initializing acquisition context for sensor %d\n", s);
617 /* Create condition variable and mutex for quick thread release */
618 ret = pthread_condattr_init(&thread_cond_attr[s]);
619 ret = pthread_condattr_setclock(&thread_cond_attr[s], CLOCK_MONOTONIC);
620 ret = pthread_cond_init(&thread_release_cond[s], &thread_cond_attr[s]);
621 ret = pthread_mutex_init(&thread_release_mutex[s], NULL);
623 /* Create a pipe for inter thread communication */
624 ret = pipe(sensor[s].thread_data_fd);
626 incoming_data_fd = sensor[s].thread_data_fd[0];
629 ev.data.u32 = THREAD_REPORT_TAG_BASE + s;
631 /* Add incoming side of pipe to our poll set, with a suitable tag */
632 ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, incoming_data_fd , &ev);
634 ALOGE("Failed adding %d to poll set (%s)\n",
635 incoming_data_fd, strerror(errno));
638 /* Create and start worker thread */
639 ret = pthread_create(&sensor[s].acquisition_thread, NULL, acquisition_routine, (void*) (size_t) s);
643 static void stop_acquisition_thread (int s)
645 int incoming_data_fd = sensor[s].thread_data_fd[0];
646 int outgoing_data_fd = sensor[s].thread_data_fd[1];
648 ALOGV("Tearing down acquisition context for sensor %d\n", s);
650 /* Delete the incoming side of the pipe from our poll set */
651 epoll_ctl(poll_fd, EPOLL_CTL_DEL, incoming_data_fd, NULL);
653 /* Mark the pipe ends as invalid ; that's a cheap exit flag */
654 sensor[s].thread_data_fd[0] = -1;
655 sensor[s].thread_data_fd[1] = -1;
657 /* Close both sides of our pipe */
658 close(incoming_data_fd);
659 close(outgoing_data_fd);
661 /* Stop acquisition thread and clean up thread handle */
662 pthread_cond_signal(&thread_release_cond[s]);
663 pthread_join(sensor[s].acquisition_thread, NULL);
665 /* Clean up our sensor descriptor */
666 sensor[s].acquisition_thread = -1;
668 /* Delete condition variable and mutex */
669 pthread_cond_destroy(&thread_release_cond[s]);
670 pthread_mutex_destroy(&thread_release_mutex[s]);
674 static int is_fast_accelerometer (int s)
677 * Some games don't react well to accelerometers using any-motion triggers. Even very low thresholds seem to trip them, and they tend to
678 * request fairly high event rates. Favor continuous triggers if the sensor is an accelerometer and uses a sampling rate of at least 25.
681 if (sensor[s].type != SENSOR_TYPE_ACCELEROMETER)
684 if (sensor[s].sampling_rate < 25)
691 static void tentative_switch_trigger (int s)
694 * Under certain situations it may be beneficial to use an alternate trigger:
696 * - for applications using the accelerometer with high sampling rates, prefer the continuous trigger over the any-motion one, to avoid
697 * jumps related to motion thresholds
700 if (is_fast_accelerometer(s) && !(sensor[s].quirks & QUIRK_TERSE_DRIVER) && sensor[s].selected_trigger == sensor[s].motion_trigger_name)
701 setup_trigger(s, sensor[s].init_trigger_name);
705 static float get_group_max_sampling_rate (int s)
707 /* Review the sampling rates of linked sensors and return the maximum */
711 float arbitrated_rate = 0;
714 arbitrated_rate = sensor[s].requested_rate;
716 /* If any of the currently active sensors built on top of this one need a higher sampling rate, switch to this rate */
717 for (i = 0; i < sensor_count; i++)
718 for (vi = 0; vi < sensor[i].base_count; vi++)
719 if (sensor[i].base[vi] == s && is_enabled(i) && sensor[i].requested_rate > arbitrated_rate) /* If sensor i depends on sensor s */
720 arbitrated_rate = sensor[i].requested_rate;
722 /* If any of the currently active sensors we rely on is using a higher sampling rate, switch to this rate */
723 for (vi = 0; vi < sensor[s].base_count; vi++) {
724 i = sensor[s].base[vi];
725 if (is_enabled(i) && sensor[i].requested_rate > arbitrated_rate)
726 arbitrated_rate = sensor[i].requested_rate;
729 return arbitrated_rate;
732 extern float sensor_get_max_freq (int s);
734 static float select_closest_available_rate(int s, float requested_rate)
738 float selected_rate = 0;
739 float max_rate_from_prop = sensor_get_max_freq(s);
740 int dev_num = sensor[s].dev_num;
742 if (!sensor[s].avail_freqs_count)
743 return requested_rate;
745 for (j = 0; j < sensor[s].avail_freqs_count; j++) {
747 sr = sensor[s].avail_freqs[j];
749 /* If this matches the selected rate, we're happy. Have some tolerance for rounding errors and avoid needless jumps to higher rates */
750 if ((fabs(requested_rate - sr) <= 0.01) && (sr <= max_rate_from_prop)) {
754 /* Select rate if it's less than max freq */
755 if ((sr > selected_rate) && (sr <= max_rate_from_prop)) {
760 * If we reached a higher value than the desired rate, adjust selected rate so it matches the first higher available one and
761 * stop parsing - this makes the assumption that rates are sorted by increasing value in the allowed frequencies string.
763 if (sr > requested_rate) {
764 return selected_rate;
768 /* Check for wrong values */
769 if (selected_rate < 0.1) {
770 return requested_rate;
772 return selected_rate;
776 static int sensor_set_rate (int s, float requested_rate)
778 /* Set the rate at which a specific sensor should report events. See Android sensors.h for indication on sensor trigger modes */
780 char sysfs_path[PATH_MAX];
781 int dev_num = sensor[s].dev_num;
782 int i = sensor[s].catalog_index;
783 const char *prefix = sensor_catalog[i].tag;
784 int per_sensor_sampling_rate;
785 int per_device_sampling_rate;
788 float group_max_sampling_rate;
789 float cur_sampling_rate; /* Currently used sampling rate */
790 float arb_sampling_rate; /* Granted sampling rate after arbitration */
791 char hrtimer_sampling_path[PATH_MAX];
792 char trigger_path[PATH_MAX];
794 ALOGV("Sampling rate %g requested on sensor %d (%s)\n", requested_rate, s, sensor[s].friendly_name);
796 sensor[s].requested_rate = requested_rate;
798 arb_sampling_rate = requested_rate;
800 if (arb_sampling_rate < sensor[s].min_supported_rate) {
801 ALOGV("Sampling rate %g too low for %s, using %g instead\n", arb_sampling_rate, sensor[s].friendly_name, sensor[s].min_supported_rate);
802 arb_sampling_rate = sensor[s].min_supported_rate;
805 /* If one of the linked sensors uses a higher rate, adopt it */
806 group_max_sampling_rate = get_group_max_sampling_rate(s);
808 if (arb_sampling_rate < group_max_sampling_rate) {
809 ALOGV("Using %s sampling rate to %g too due to dependency\n", sensor[s].friendly_name, arb_sampling_rate);
810 arb_sampling_rate = group_max_sampling_rate;
813 if (sensor[s].max_supported_rate && arb_sampling_rate > sensor[s].max_supported_rate) {
814 ALOGV("Sampling rate %g too high for %s, using %g instead\n", arb_sampling_rate, sensor[s].friendly_name, sensor[s].max_supported_rate);
815 arb_sampling_rate = sensor[s].max_supported_rate;
818 sensor[s].sampling_rate = arb_sampling_rate;
820 /* If the sensor is virtual, we're done */
821 if (sensor[s].is_virtual)
824 /* If we're dealing with a poll-mode sensor */
825 if (sensor[s].mode == MODE_POLL) {
827 pthread_cond_signal(&thread_release_cond[s]); /* Wake up thread so the new sampling rate gets used */
831 sprintf(sysfs_path, SENSOR_SAMPLING_PATH, dev_num, prefix);
833 if (sysfs_read_float(sysfs_path, &cur_sampling_rate) != -1) {
834 per_sensor_sampling_rate = 1;
835 per_device_sampling_rate = 0;
837 per_sensor_sampling_rate = 0;
839 sprintf(sysfs_path, DEVICE_SAMPLING_PATH, dev_num);
841 if (sysfs_read_float(sysfs_path, &cur_sampling_rate) != -1)
842 per_device_sampling_rate = 1;
844 per_device_sampling_rate = 0;
847 if (!per_sensor_sampling_rate && !per_device_sampling_rate) {
848 ALOGE("No way to adjust sampling rate on sensor %d\n", s);
852 if (sensor[s].hrtimer_trigger_name[0] != '\0') {
853 snprintf(trigger_path, PATH_MAX, "%s%s%d/", IIO_DEVICES, "trigger", sensor[s].trigger_nr);
854 snprintf(hrtimer_sampling_path, PATH_MAX, "%s%s", trigger_path, "sampling_frequency");
855 /* Enforce frequency update when software trigger
856 * frequency and current sampling rate are different */
857 if (sysfs_read_float(hrtimer_sampling_path, &sr) != -1 && sr != cur_sampling_rate)
858 cur_sampling_rate = -1;
861 /* Check if we have contraints on allowed sampling rates */
863 if (!(sensor_get_quirks(s) & QUIRK_HRTIMER)) {
864 arb_sampling_rate = select_closest_available_rate(s, arb_sampling_rate);
868 /* Record the rate that was agreed upon with the sensor taken in isolation ; this avoid uncontrolled ripple effects between colocated sensor rates */
869 sensor[s].semi_arbitrated_rate = arb_sampling_rate;
871 /* Coordinate with others active sensors on the same device, if any */
872 if (per_device_sampling_rate)
873 for (n=0; n<sensor_count; n++)
874 if (n != s && sensor[n].dev_num == dev_num && sensor[n].num_channels && is_enabled(n) &&
875 sensor[n].semi_arbitrated_rate > arb_sampling_rate) {
876 ALOGV("Sampling rate shared between %s and %s, using %g instead of %g\n", sensor[s].friendly_name, sensor[n].friendly_name,
877 sensor[n].semi_arbitrated_rate, arb_sampling_rate);
878 arb_sampling_rate = sensor[n].semi_arbitrated_rate;
881 sensor[s].sampling_rate = arb_sampling_rate;
883 /* Update actual sampling rate field for this sensor and others which may be sharing the same sampling rate */
884 if (per_device_sampling_rate)
885 for (n=0; n<sensor_count; n++)
886 if (sensor[n].dev_num == dev_num && n != s && sensor[n].num_channels)
887 sensor[n].sampling_rate = arb_sampling_rate;
889 /* If the desired rate is already active we're all set */
890 if (arb_sampling_rate == cur_sampling_rate)
893 ALOGI("Sensor %d (%s) sampling rate set to %g\n", s, sensor[s].friendly_name, arb_sampling_rate);
895 if (sensor[s].hrtimer_trigger_name[0] != '\0')
896 sysfs_write_float(hrtimer_sampling_path, ceilf(arb_sampling_rate));
898 if (trig_sensors_per_dev[dev_num])
899 enable_buffer(dev_num, 0);
901 if (sensor_get_quirks(s) & QUIRK_HRTIMER) {
902 sysfs_write_float(sysfs_path, select_closest_available_rate(s, arb_sampling_rate));
904 sysfs_write_float(sysfs_path, arb_sampling_rate);
907 /* Check if it makes sense to use an alternate trigger */
908 tentative_switch_trigger(s);
910 if (trig_sensors_per_dev[dev_num])
911 enable_buffer(dev_num, 1);
917 static void reapply_sampling_rates (int s)
920 * The specified sensor was either enabled or disabled. Other sensors in the same group may have constraints related to this sensor
921 * sampling rate on their own sampling rate, so reevaluate them by retrying to use their requested sampling rate, rather than the one
922 * that ended up being used after arbitration.
927 if (sensor[s].is_virtual) {
928 /* Take care of downwards dependencies */
929 for (i=0; i<sensor[s].base_count; i++) {
930 base = sensor[s].base[i];
931 sensor_set_rate(base, sensor[base].requested_rate);
937 for (i=0; i<sensor_count; i++)
938 for (j=0; j<sensor[i].base_count; j++)
939 if (sensor[i].base[j] == s) /* If sensor i depends on sensor s */
940 sensor_set_rate(i, sensor[i].requested_rate);
944 static int sensor_activate_virtual (int s, int enabled, int from_virtual)
948 sensor[s].event_count = 0;
949 sensor[s].meta_data_pending = 0;
951 if (!check_state_change(s, enabled, from_virtual))
952 return 0; /* The state of the sensor remains the same ; we're done */
955 ALOGI("Enabling sensor %d (%s)\n", s, sensor[s].friendly_name);
957 ALOGI("Disabling sensor %d (%s)\n", s, sensor[s].friendly_name);
959 sensor[s].report_pending = 0;
961 for (i=0; i<sensor[s].base_count; i++) {
963 base = sensor[s].base[i];
964 sensor_activate(base, enabled, 1);
967 sensor[base].ref_count++;
969 sensor[base].ref_count--;
972 /* Reevaluate sampling rates of linked sensors */
973 reapply_sampling_rates(s);
978 int sensor_activate (int s, int enabled, int from_virtual)
980 char device_name[PATH_MAX];
981 struct epoll_event ev = {0};
982 int dev_fd, event_fd;
984 int dev_num = sensor[s].dev_num;
986 int catalog_index = sensor[s].catalog_index;
988 if (sensor[s].is_virtual)
989 return sensor_activate_virtual(s, enabled, from_virtual);
991 /* Prepare the report timestamp field for the first event, see set_report_ts method */
992 sensor[s].report_ts = 0;
994 ret = adjust_counters(s, enabled, from_virtual);
996 /* If the operation was neutral in terms of state, we're done */
1000 sensor[s].event_count = 0;
1001 sensor[s].meta_data_pending = 0;
1004 setup_noise_filtering(s); /* Initialize filtering data if required */
1006 if (sensor[s].mode == MODE_TRIGGER) {
1009 enable_buffer(dev_num, 0);
1010 setup_trigger(s, "\n");
1012 /* If there's at least one sensor enabled on this iio device */
1013 if (trig_sensors_per_dev[dev_num]) {
1015 /* Start sampling */
1016 if (sensor[s].hrtimer_trigger_name[0] != '\0')
1017 setup_trigger(s, sensor[s].hrtimer_trigger_name);
1019 setup_trigger(s, sensor[s].init_trigger_name);
1021 enable_buffer(dev_num, 1);
1023 } else if (sensor[s].mode == MODE_POLL) {
1024 if (sensor[s].needs_enable) {
1025 enable_sensor(dev_num, sensor_catalog[catalog_index].tag, enabled);
1030 * Make sure we have a fd on the character device ; conversely, close the fd if no one is using associated sensors anymore. The assumption
1031 * here is that the underlying driver will power on the relevant hardware block while someone holds a fd on the device.
1033 dev_fd = device_fd[dev_num];
1036 if (sensor[s].mode == MODE_POLL)
1037 stop_acquisition_thread(s);
1039 if (dev_fd != -1 && !poll_sensors_per_dev[dev_num] && !trig_sensors_per_dev[dev_num]) {
1040 /* Stop watching this fd. This should be a no-op in case this fd was not in the poll set. */
1041 epoll_ctl(poll_fd, EPOLL_CTL_DEL, dev_fd, NULL);
1044 device_fd[dev_num] = -1;
1047 if (sensor[s].mode == MODE_EVENT) {
1048 event_fd = events_fd[dev_num];
1050 for (c = 0; c < sensor_catalog[catalog_index].num_channels; c++) {
1051 for (d = 0; d < sensor_catalog[catalog_index].channel[c].num_events; d++)
1052 enable_event(dev_num, sensor_catalog[catalog_index].channel[c].event[d].ev_en_path, enabled);
1055 epoll_ctl(poll_fd, EPOLL_CTL_DEL, event_fd, NULL);
1057 events_fd[dev_num] = -1;
1061 /* Release any filtering data we may have accumulated */
1062 release_noise_filtering_data(s);
1064 /* Reevaluate sampling rates of linked sensors */
1065 reapply_sampling_rates(s);
1070 /* First enabled sensor on this iio device */
1071 sprintf(device_name, DEV_FILE_PATH, dev_num);
1072 dev_fd = open(device_name, O_RDONLY | O_NONBLOCK);
1074 device_fd[dev_num] = dev_fd;
1077 ALOGE("Could not open fd on %s (%s)\n", device_name, strerror(errno));
1078 adjust_counters(s, 0, from_virtual);
1082 ALOGV("Opened %s: fd=%d\n", device_name, dev_fd);
1084 if (sensor[s].mode == MODE_TRIGGER) {
1086 /* Add this iio device fd to the set of watched fds */
1087 ev.events = EPOLLIN;
1088 ev.data.u32 = dev_num;
1090 ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, dev_fd, &ev);
1093 ALOGE("Failed adding %d to poll set (%s)\n", dev_fd, strerror(errno));
1097 /* Note: poll-mode fds are not readable */
1098 } else if (sensor[s].mode == MODE_EVENT) {
1099 event_fd = events_fd[dev_num];
1101 ret = ioctl(dev_fd, IIO_GET_EVENT_FD_IOCTL, &event_fd);
1102 if (ret == -1 || event_fd == -1) {
1103 ALOGE("Failed to retrieve event_fd from %d (%s)\n", dev_fd, strerror(errno));
1106 events_fd[dev_num] = event_fd;
1107 ALOGV("Opened fd=%d to receive events\n", event_fd);
1109 /* Add this event fd to the set of watched fds */
1110 ev.events = EPOLLIN;
1111 ev.data.u32 = dev_num;
1113 ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, event_fd, &ev);
1115 ALOGE("Failed adding %d to poll set (%s)\n", event_fd, strerror(errno));
1118 for (c = 0; c < sensor_catalog[catalog_index].num_channels; c++) {
1120 for (d = 0; d < sensor_catalog[catalog_index].channel[c].num_events; d++)
1121 enable_event(dev_num, sensor_catalog[catalog_index].channel[c].event[d].ev_en_path, enabled);
1124 if (!poll_sensors_per_dev[dev_num] && !trig_sensors_per_dev[dev_num]) {
1126 device_fd[dev_num] = -1;
1131 /* Ensure that on-change sensors send at least one event after enable */
1132 get_field_count(s, &field_size);
1133 if (field_size == sizeof(uint64_t))
1134 sensor[s].prev_val.data64 = -1;
1136 sensor[s].prev_val.data = -1;
1138 if (sensor[s].mode == MODE_POLL)
1139 start_acquisition_thread(s);
1141 /* Reevaluate sampling rates of linked sensors */
1142 reapply_sampling_rates(s);
1148 static void enable_motion_trigger (int dev_num)
1151 * In the ideal case, we enumerate two triggers per iio device ; the default (periodically firing) trigger, and another one (the motion
1152 * trigger) that only fires up when motion is detected. This second one allows for lesser energy consumption, but requires periodic sample
1153 * duplication at the HAL level for sensors that Android defines as continuous. This "duplicate last sample" logic can only be engaged
1154 * once we got a first sample for the driver, so we start with the default trigger when an iio device is first opened, then adjust the
1155 * trigger when we got events for all active sensors. Unfortunately in the general case several sensors can be associated to a given iio
1156 * device, they can independently be controlled, and we have to adjust the trigger in use at the iio device level depending on whether or
1157 * not appropriate conditions are met at the sensor level.
1162 int active_sensors = trig_sensors_per_dev[dev_num];
1163 int candidate[MAX_SENSORS];
1164 int candidate_count = 0;
1166 if (!active_sensors)
1169 /* Check that all active sensors are ready to switch */
1171 for (s=0; s<MAX_SENSORS; s++)
1172 if (sensor[s].dev_num == dev_num && is_enabled(s) && sensor[s].num_channels &&
1173 (!sensor[s].motion_trigger_name[0] || !sensor[s].report_initialized || is_fast_accelerometer(s) ||
1174 (sensor[s].quirks & QUIRK_FORCE_CONTINUOUS)))
1177 /* Record which particular sensors need to switch */
1179 for (s=0; s<MAX_SENSORS; s++)
1180 if (sensor[s].dev_num == dev_num && is_enabled(s) && sensor[s].num_channels && sensor[s].selected_trigger != sensor[s].motion_trigger_name)
1181 candidate[candidate_count++] = s;
1183 if (!candidate_count)
1186 /* Now engage the motion trigger for sensors which aren't using it */
1188 enable_buffer(dev_num, 0);
1190 for (i=0; i<candidate_count; i++) {
1192 setup_trigger(s, sensor[s].motion_trigger_name);
1195 enable_buffer(dev_num, 1);
1198 static void stamp_reports (int dev_num, int64_t ts)
1202 for (s=0; s<MAX_SENSORS; s++)
1203 if (sensor[s].dev_num == dev_num && is_enabled(s) && sensor[s].mode != MODE_POLL) {
1204 if (sensor[s].quirks & QUIRK_SPOTTY)
1205 set_report_ts(s, ts);
1207 sensor[s].report_ts = ts;
1212 static int integrate_device_report_from_dev(int dev_num, int fd)
1216 unsigned char buf[MAX_DEVICE_REPORT_SIZE] = { 0 };
1218 unsigned char *target;
1219 unsigned char *source;
1222 int ts_offset = 0; /* Offset of iio timestamp, if provided */
1223 int64_t boot_to_rt_delta;
1225 /* There's an incoming report on the specified iio device char dev fd */
1227 ALOGE("Ignoring stale report on iio device %d\n", dev_num);
1231 len = read(fd, buf, expected_dev_report_size[dev_num]);
1234 ALOGE("Could not read report from iio device %d (%s)\n", dev_num, strerror(errno));
1238 ALOGV("Read %d bytes from iio device %d\n", len, dev_num);
1240 /* Map device report to sensor reports */
1242 for (s=0; s<MAX_SENSORS; s++)
1243 if (sensor[s].dev_num == dev_num && is_enabled(s)) {
1247 /* Copy data from device to sensor report buffer */
1248 for (c=0; c<sensor[s].num_channels; c++) {
1250 target = sensor[s].report_buffer + sr_offset;
1252 source = buf + sensor[s].channel[c].offset;
1254 size = sensor[s].channel[c].size;
1256 memcpy(target, source, size);
1261 ALOGV("Sensor %d report available (%d bytes)\n", s, sr_offset);
1263 sensor[s].report_pending = DATA_TRIGGER;
1264 sensor[s].report_initialized = 1;
1268 /* Tentatively switch to an any-motion trigger if conditions are met */
1269 enable_motion_trigger(dev_num);
1271 /* If no iio timestamp channel was detected for this device, bail out */
1272 if (!has_iio_ts[dev_num]) {
1273 stamp_reports(dev_num, get_timestamp_boot());
1277 /* Don't trust the timestamp channel in any-motion mode */
1278 for (s=0; s<MAX_SENSORS; s++)
1279 if (sensor[s].dev_num == dev_num && is_enabled(s) && sensor[s].selected_trigger == sensor[s].motion_trigger_name) {
1280 stamp_reports(dev_num, get_timestamp_boot());
1284 /* Align on a 64 bits boundary */
1285 ts_offset = expected_dev_report_size[dev_num] - sizeof(int64_t);
1287 /* If we read an amount of data consistent with timestamp presence */
1288 if (len == expected_dev_report_size[dev_num])
1289 ts = *(int64_t*) (buf + ts_offset);
1292 ALOGV("Unreliable timestamp channel on iio dev %d\n", dev_num);
1293 stamp_reports(dev_num, get_timestamp_boot());
1297 ALOGV("Driver timestamp on iio device %d: ts=%lld\n", dev_num, ts);
1299 boot_to_rt_delta = get_timestamp_boot() - get_timestamp_realtime();
1301 stamp_reports(dev_num, ts + boot_to_rt_delta);
1306 static int integrate_device_report_from_event(int dev_num, int fd)
1310 struct iio_event_data event;
1311 int64_t boot_to_rt_delta = get_timestamp_boot() - get_timestamp_realtime();
1313 /* There's an incoming report on the specified iio device char dev fd */
1315 ALOGE("Ignoring stale report on event fd %d of device %d\n",
1320 len = read(fd, &event, sizeof(event));
1323 ALOGE("Could not read event from fd %d of device %d (%s)\n",
1324 fd, dev_num, strerror(errno));
1328 ts = event.timestamp + boot_to_rt_delta;
1330 ALOGV("Read event %lld from fd %d of iio device %d - ts %lld\n", event.id, fd, dev_num, ts);
1332 /* Map device report to sensor reports */
1333 for (s = 0; s < MAX_SENSORS; s++)
1334 if (sensor[s].dev_num == dev_num &&
1336 sensor[s].event_id = event.id;
1337 sensor[s].report_ts = ts;
1338 sensor[s].report_pending = 1;
1339 sensor[s].report_initialized = 1;
1340 ALOGV("Sensor %d report available (1 byte)\n", s);
1345 static int integrate_device_report(int dev_num)
1349 if (dev_num < 0 || dev_num >= MAX_DEVICES) {
1350 ALOGE("Event reported on unexpected iio device %d\n", dev_num);
1354 if (events_fd[dev_num] != -1) {
1355 ret = integrate_device_report_from_event(dev_num, events_fd[dev_num]);
1360 if (device_fd[dev_num] != -1)
1361 ret = integrate_device_report_from_dev(dev_num, device_fd[dev_num]);
1366 static int propagate_vsensor_report (int s, sensors_event_t *data)
1368 /* There's a new report stored in sensor.sample for this sensor; transmit it */
1370 memcpy(data, &sensor[s].sample, sizeof(sensors_event_t));
1373 data->type = sensor_desc[s].type; /* sensor_desc[s].type can differ from sensor[s].type ; internal types are remapped */
1378 static int propagate_sensor_report (int s, sensors_event_t *data)
1380 /* There's a sensor report pending for this sensor ; transmit it */
1383 int num_fields = get_field_count(s, &field_size);
1385 unsigned char* current_sample;
1388 /* If there's nothing to return... we're done */
1392 ALOGV("Sample on sensor %d (type %d):\n", s, sensor[s].type);
1394 if (sensor[s].mode == MODE_POLL) {
1395 /* We received a good sample but we're not directly enabled so we'll drop */
1396 if (!sensor[s].directly_enabled)
1398 /* Use the data provided by the acquisition thread */
1399 ALOGV("Reporting data from worker thread for S%d\n", s);
1400 memcpy(data, &sensor[s].sample, sizeof(sensors_event_t));
1401 data->timestamp = sensor[s].report_ts;
1405 memset(data, 0, sizeof(sensors_event_t));
1407 data->version = sizeof(sensors_event_t);
1409 data->type = sensor_desc[s].type; /* sensor_desc[s].type can differ from sensor[s].type ; internal types are remapped */
1410 data->timestamp = sensor[s].report_ts;
1412 if (sensor[s].mode == MODE_EVENT) {
1413 ALOGV("Reporting event\n");
1414 /* Android requires events to return 1.0 */
1415 int dir = IIO_EVENT_CODE_EXTRACT_DIR(sensor[s].event_id);
1416 switch (sensor[s].type) {
1417 case SENSOR_TYPE_PROXIMITY:
1418 if (dir == IIO_EV_DIR_FALLING)
1419 data->data[0] = 0.0;
1421 data->data[0] = 1.0;
1424 data->data[0] = 1.0;
1428 data->data[1] = 0.0;
1429 data->data[2] = 0.0;
1433 /* Convert the data into the expected Android-level format */
1435 current_sample = sensor[s].report_buffer;
1437 for (c=0; c<num_fields; c++) {
1439 data->data[c] = sensor[s].ops.transform (s, c, current_sample);
1441 ALOGV("\tfield %d: %g\n", c, data->data[c]);
1442 current_sample += sensor[s].channel[c].size;
1445 ret = sensor[s].ops.finalize(s, data);
1447 /* We will drop samples if the sensor is not directly enabled */
1448 if (!sensor[s].directly_enabled)
1451 /* 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 */
1456 static void synthetize_duplicate_samples (void)
1459 * Some sensor types (ex: gyroscope) are defined as continuously firing by Android, despite the fact that
1460 * we can be dealing with iio drivers that only report events for new samples. For these we generate reports
1461 * periodically, duplicating the last data we got from the driver. This is not necessary for polling sensors.
1469 for (s=0; s<sensor_count; s++) {
1471 /* Ignore disabled sensors */
1475 /* If the sensor is continuously firing, leave it alone */
1476 if (sensor[s].selected_trigger != sensor[s].motion_trigger_name)
1479 /* If we haven't seen a sample, there's nothing to duplicate */
1480 if (!sensor[s].report_initialized)
1483 /* If a sample was recently buffered, leave it alone too */
1484 if (sensor[s].report_pending)
1487 /* We also need a valid sampling rate to be configured */
1488 if (!sensor[s].sampling_rate)
1491 period = (int64_t) (1000000000.0 / sensor[s].sampling_rate);
1493 current_ts = get_timestamp_boot();
1494 target_ts = sensor[s].report_ts + period;
1496 if (target_ts <= current_ts) {
1497 /* Mark the sensor for event generation */
1498 set_report_ts(s, current_ts);
1499 sensor[s].report_pending = DATA_DUPLICATE;
1505 static void integrate_thread_report (uint32_t tag)
1507 int s = tag - THREAD_REPORT_TAG_BASE;
1510 len = read(sensor[s].thread_data_fd[0], &sensor[s].sample, sizeof(sensors_event_t));
1512 if (len == sizeof(sensors_event_t))
1513 sensor[s].report_pending = DATA_SYSFS;
1517 static int get_poll_wait_timeout (void)
1520 * Compute an appropriate timeout value, in ms, for the epoll_wait call that's going to await
1521 * for iio device reports and incoming reports from our sensor sysfs data reader threads.
1525 int64_t target_ts = INT64_MAX;
1530 * Check if we're dealing with a driver that only send events when there is motion, despite the fact that the associated Android sensor
1531 * type is continuous rather than on-change. In that case we have to duplicate events. Check deadline for the nearest upcoming event.
1533 for (s=0; s<sensor_count; s++)
1534 if (is_enabled(s) && sensor[s].selected_trigger == sensor[s].motion_trigger_name && sensor[s].sampling_rate) {
1535 period = (int64_t) (1000000000.0 / sensor[s].sampling_rate);
1537 if (sensor[s].report_ts + period < target_ts)
1538 target_ts = sensor[s].report_ts + period;
1541 /* If we don't have such a driver to deal with */
1542 if (target_ts == INT64_MAX)
1543 return -1; /* Infinite wait */
1545 ms_to_wait = (target_ts - get_timestamp_boot()) / 1000000;
1547 /* If the target timestamp is already behind us, don't wait */
1555 int sensor_poll (sensors_event_t* data, int count)
1560 struct epoll_event ev[MAX_DEVICES];
1561 int returned_events;
1564 /* Get one or more events from our collection of sensors */
1565 return_available_sensor_reports:
1567 /* Synthetize duplicate samples if needed */
1568 synthetize_duplicate_samples();
1570 returned_events = 0;
1572 /* Check our sensor collection for available reports */
1573 for (s=0; s<sensor_count && returned_events < count; s++) {
1575 if (sensor[s].report_pending) {
1578 if (sensor[s].is_virtual)
1579 event_count = propagate_vsensor_report(s, &data[returned_events]);
1581 /* Report this event if it looks OK */
1582 event_count = propagate_sensor_report(s, &data[returned_events]);
1585 sensor[s].report_pending = 0;
1586 returned_events += event_count;
1589 * If the sample was deemed invalid or unreportable, e.g. had the same value as the previously reported
1590 * value for a 'on change' sensor, silently drop it.
1594 while (sensor[s].meta_data_pending) {
1595 /* See sensors.h on these */
1596 data[returned_events].version = META_DATA_VERSION;
1597 data[returned_events].sensor = 0;
1598 data[returned_events].type = SENSOR_TYPE_META_DATA;
1599 data[returned_events].reserved0 = 0;
1600 data[returned_events].timestamp = 0;
1601 data[returned_events].meta_data.sensor = s;
1602 data[returned_events].meta_data.what = META_DATA_FLUSH_COMPLETE;
1604 sensor[s].meta_data_pending--;
1608 if (returned_events)
1609 return returned_events;
1613 ALOGV("Awaiting sensor data\n");
1615 nfds = epoll_wait(poll_fd, ev, MAX_DEVICES, get_poll_wait_timeout());
1618 ALOGE("epoll_wait returned -1 (%s)\n", strerror(errno));
1622 ALOGV("%d fds signalled\n", nfds);
1624 /* For each of the signalled sources */
1625 for (i=0; i<nfds; i++)
1626 if (ev[i].events == EPOLLIN)
1627 switch (ev[i].data.u32) {
1628 case 0 ... MAX_DEVICES-1:
1629 /* Read report from iio char dev fd */
1630 integrate_device_report(ev[i].data.u32);
1633 case THREAD_REPORT_TAG_BASE ...
1634 THREAD_REPORT_TAG_BASE + MAX_SENSORS-1:
1635 /* Get report from acquisition thread */
1636 integrate_thread_report(ev[i].data.u32);
1640 ALOGW("Unexpected event source!\n");
1644 goto return_available_sensor_reports;
1648 int sensor_set_delay (int s, int64_t ns)
1650 float requested_sampling_rate;
1653 ALOGE("Invalid delay requested on sensor %d: %lld\n", s, ns);
1657 requested_sampling_rate = 1000000000.0 / ns;
1659 ALOGV("Entering set delay S%d (%s): current rate: %g, requested: %g\n", s, sensor[s].friendly_name, sensor[s].sampling_rate, requested_sampling_rate);
1662 * Only try to adjust the low level sampling rate if it's different from the current one, as set by the HAL. This saves a few sysfs
1663 * reads and writes as well as buffer enable/disable operations, since at the iio level most drivers require the buffer to be turned off
1664 * in order to accept a sampling rate change. Of course that implies that this field has to be kept up to date and that only this library
1665 * is changing the sampling rate.
1668 if (requested_sampling_rate != sensor[s].sampling_rate)
1669 return sensor_set_rate(s, requested_sampling_rate);
1675 int sensor_flush (int s)
1677 /* If one shot or not enabled return -EINVAL */
1678 if (sensor_desc[s].flags & SENSOR_FLAG_ONE_SHOT_MODE || !is_enabled(s))
1681 sensor[s].meta_data_pending++;
1686 int allocate_control_data (void)
1690 for (i=0; i<MAX_DEVICES; i++) {
1695 poll_fd = epoll_create(MAX_DEVICES);
1697 if (poll_fd == -1) {
1698 ALOGE("Can't create epoll instance for iio sensors!\n");
1706 void delete_control_data (void)