2 // Copyright (c) 2015 Intel Corporation
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
8 // http://www.apache.org/licenses/LICENSE-2.0
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.
23 #include <sys/epoll.h>
24 #include <sys/ioctl.h>
25 #include <sys/socket.h>
26 #include <utils/Log.h>
27 #include <hardware/sensors.h>
28 #include <linux/ioctl.h>
30 #include "enumeration.h"
32 #include "transform.h"
33 #include "calibration.h"
34 #include "description.h"
35 #include "filtering.h"
36 #include <linux/iio/events.h>
39 /* Currently active sensors count, per device */
40 static int poll_sensors_per_dev[MAX_DEVICES]; /* poll-mode sensors */
41 static int trig_sensors_per_dev[MAX_DEVICES]; /* trigger, event based */
43 static int device_fd[MAX_DEVICES]; /* fd on the /dev/iio:deviceX file */
44 static int events_fd[MAX_DEVICES]; /* fd on the /sys/bus/iio/devices/iio:deviceX/events/<event_name> file */
45 static int has_iio_ts[MAX_DEVICES]; /* ts channel available on this iio dev */
46 static int expected_dev_report_size[MAX_DEVICES]; /* expected iio scan len */
47 static int poll_fd; /* epoll instance covering all enabled sensors */
49 static int active_poll_sensors; /* Number of enabled poll-mode sensors */
51 static int flush_event_fd[2]; /* Pipe used for flush signaling */
53 /* We use pthread condition variables to get worker threads out of sleep */
54 static pthread_condattr_t thread_cond_attr [MAX_SENSORS];
55 static pthread_cond_t thread_release_cond [MAX_SENSORS];
56 static pthread_mutex_t thread_release_mutex [MAX_SENSORS];
58 #define FLUSH_REPORT_TAG 900
60 * We associate tags to each of our poll set entries. These tags have the following values:
61 * - a iio device number if the fd is a iio character device fd
62 * - THREAD_REPORT_TAG_BASE + sensor handle if the fd is the receiving end of a pipe used by a sysfs data acquisition thread
64 #define THREAD_REPORT_TAG_BASE 1000
66 /* If buffer enable fails, we may want to retry a few times before giving up */
67 #define ENABLE_BUFFER_RETRIES 3
68 #define ENABLE_BUFFER_RETRY_DELAY_MS 10
71 inline int is_enabled (int s)
73 return sensor[s].directly_enabled || sensor[s].ref_count;
77 static int check_state_change (int s, int enabled, int from_virtual)
80 if (sensor[s].directly_enabled)
81 return 0; /* We're being enabled but already were directly activated: no change. */
84 sensor[s].directly_enabled = 1; /* We're being directly enabled */
86 if (sensor[s].ref_count)
87 return 0; /* We were already indirectly enabled */
89 return 1; /* Do continue enabling this sensor */
93 return 0; /* We are being disabled but already were: no change */
95 if (from_virtual && sensor[s].directly_enabled)
96 return 0; /* We're indirectly disabled but the base is still active */
98 sensor[s].directly_enabled = 0; /* We're now directly disabled */
100 if (!from_virtual && sensor[s].ref_count)
101 return 0; /* We still have ref counts */
103 return 1; /* Do continue disabling this sensor */
107 static int enable_buffer (int dev_num, int enabled)
109 char sysfs_path[PATH_MAX];
110 int retries = ENABLE_BUFFER_RETRIES;
112 sprintf(sysfs_path, ENABLE_PATH, dev_num);
115 /* Low level, non-multiplexed, enable/disable routine */
116 if (sysfs_write_int(sysfs_path, enabled) > 0)
119 ALOGE("Failed enabling buffer on dev%d, retrying", dev_num);
120 usleep(ENABLE_BUFFER_RETRY_DELAY_MS*1000);
124 ALOGE("Could not enable buffer\n");
129 static int setup_trigger (int s, const char* trigger_val)
131 char sysfs_path[PATH_MAX];
132 int ret = -1, attempts = 5;
134 sprintf(sysfs_path, TRIGGER_PATH, sensor[s].dev_num);
136 if (trigger_val[0] != '\n')
137 ALOGI("Setting S%d (%s) trigger to %s\n", s, sensor[s].friendly_name, trigger_val);
139 while (ret == -1 && attempts) {
140 ret = sysfs_write_str(sysfs_path, trigger_val);
145 sensor[s].selected_trigger = trigger_val;
147 ALOGE("Setting S%d (%s) trigger to %s FAILED.\n", s, sensor[s].friendly_name, trigger_val);
151 static int enable_event(int dev_num, const char *name, int enabled)
153 char sysfs_path[PATH_MAX];
155 sprintf(sysfs_path, EVENTS_PATH "%s", dev_num, name);
156 return sysfs_write_int(sysfs_path, enabled);
159 static int enable_sensor(int dev_num, const char *tag, int enabled)
161 char sysfs_path[PATH_MAX];
163 sprintf(sysfs_path, SENSOR_ENABLE_PATH, dev_num, tag);
164 return sysfs_write_int(sysfs_path, enabled);
167 static void enable_iio_timestamp (int dev_num, int known_channels)
169 /* Check if we have a dedicated iio timestamp channel */
171 char spec_buf[MAX_TYPE_SPEC_LEN];
172 char sysfs_path[PATH_MAX];
175 sprintf(sysfs_path, CHANNEL_PATH "%s", dev_num, "in_timestamp_type");
177 n = sysfs_read_str(sysfs_path, spec_buf, sizeof(spec_buf));
182 if (strcmp(spec_buf, "le:s64/64>>0"))
185 /* OK, type is int64_t as expected, in little endian representation */
187 sprintf(sysfs_path, CHANNEL_PATH"%s", dev_num, "in_timestamp_index");
189 if (sysfs_read_int(sysfs_path, &n))
192 /* Check that the timestamp comes after the other fields we read */
193 if (n != known_channels)
196 /* Try enabling that channel */
197 sprintf(sysfs_path, CHANNEL_PATH "%s", dev_num, "in_timestamp_en");
199 sysfs_write_int(sysfs_path, 1);
201 if (sysfs_read_int(sysfs_path, &n))
205 ALOGI("Detected timestamp channel on iio device %d\n", dev_num);
206 has_iio_ts[dev_num] = 1;
211 static int decode_type_spec (const char type_buf[MAX_TYPE_SPEC_LEN], datum_info_t *type_info)
213 /* Return size in bytes for this type specification, or -1 in error */
216 unsigned int realbits, storagebits, shift;
219 /* Valid specs: "le:u10/16>>0", "le:s16/32>>0" or "le:s32/32>>0" */
221 tokens = sscanf(type_buf, "%ce:%c%u/%u>>%u", &endianness, &sign, &realbits, &storagebits, &shift);
223 if (tokens != 5 || (endianness != 'b' && endianness != 'l') || (sign != 'u' && sign != 's') ||
224 realbits > storagebits || (storagebits != 16 && storagebits != 32 && storagebits != 64)) {
225 ALOGE("Invalid iio channel type spec: %s\n", type_buf);
229 type_info->endianness = endianness;
230 type_info->sign = sign;
231 type_info->realbits = (short) realbits;
232 type_info->storagebits = (short) storagebits;
233 type_info->shift = (short) shift;
235 return storagebits / 8;
239 void build_sensor_report_maps (int dev_num)
242 * 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
243 * 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
244 * sensor report, itself being the data that we return to Android when a sensor poll completes. The mapping should be straightforward in the
245 * 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
246 * 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
256 char spec_buf[MAX_TYPE_SPEC_LEN];
257 datum_info_t* ch_info;
259 char sysfs_path[PATH_MAX];
262 int channel_size_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
263 int sensor_handle_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
264 int channel_number_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
268 /* For each sensor that is linked to this device */
269 for (s=0; s<sensor_count; s++) {
270 if (sensor[s].dev_num != dev_num)
273 i = sensor[s].catalog_index;
275 /* Read channel details through sysfs attributes */
276 for (c=0; c<sensor[s].num_channels; c++) {
278 /* Read _type file */
279 sprintf(sysfs_path, CHANNEL_PATH "%s", sensor[s].dev_num, sensor_catalog[i].channel[c].type_path);
281 n = sysfs_read_str(sysfs_path, spec_buf, sizeof(spec_buf));
284 ALOGW( "Failed to read type: %s\n", sysfs_path);
288 ch_spec = sensor[s].channel[c].type_spec;
290 memcpy(ch_spec, spec_buf, sizeof(spec_buf));
292 ch_info = &sensor[s].channel[c].type_info;
294 size = decode_type_spec(ch_spec, ch_info);
296 /* Read _index file */
297 sprintf(sysfs_path, CHANNEL_PATH "%s", sensor[s].dev_num, sensor_catalog[i].channel[c].index_path);
299 n = sysfs_read_int(sysfs_path, &ch_index);
302 ALOGW( "Failed to read index: %s\n", sysfs_path);
306 if (ch_index >= MAX_SENSORS) {
307 ALOGE("Index out of bounds!: %s\n", sysfs_path);
311 /* Record what this index is about */
313 sensor_handle_from_index [ch_index] = s;
314 channel_number_from_index[ch_index] = c;
315 channel_size_from_index [ch_index] = size;
320 sensor_update_max_range(s);
322 /* Stop sampling - if we are recovering from hal restart */
323 enable_buffer(dev_num, 0);
324 setup_trigger(s, "\n");
326 /* Turn on channels we're aware of */
327 for (c=0;c<sensor[s].num_channels; c++) {
328 sprintf(sysfs_path, CHANNEL_PATH "%s", sensor[s].dev_num, sensor_catalog[i].channel[c].en_path);
329 sysfs_write_int(sysfs_path, 1);
333 ALOGI("Found %d channels on iio device %d\n", known_channels, dev_num);
336 * Now that we know which channels are defined, their sizes and their ordering, update channels offsets within device report. Note: there
337 * is a possibility that several sensors share the same index, with their data fields being isolated by masking and shifting as specified
338 * through the real bits and shift values in type attributes. This case is not currently supported. Also, the code below assumes no hole in
339 * the sequence of indices, so it is dependent on discovery of all sensors.
343 for (i=0; i<MAX_SENSORS * MAX_CHANNELS; i++) {
344 s = sensor_handle_from_index[i];
345 c = channel_number_from_index[i];
346 size = channel_size_from_index[i];
351 ALOGI("S%d C%d : offset %d, size %d, type %s\n", s, c, offset, size, sensor[s].channel[c].type_spec);
353 sensor[s].channel[c].offset = offset;
354 sensor[s].channel[c].size = size;
359 /* Enable the timestamp channel if there is one available */
360 enable_iio_timestamp(dev_num, known_channels);
362 /* Add padding and timestamp size if it's enabled on this iio device */
363 if (has_iio_ts[dev_num])
364 offset = (offset+7)/8*8 + sizeof(int64_t);
366 expected_dev_report_size[dev_num] = offset;
367 ALOGI("Expecting %d scan length on iio dev %d\n", offset, dev_num);
369 if (expected_dev_report_size[dev_num] > MAX_DEVICE_REPORT_SIZE) {
370 ALOGE("Unexpectedly large scan buffer on iio dev%d: %d bytes\n", dev_num, expected_dev_report_size[dev_num]);
372 expected_dev_report_size[dev_num] = MAX_DEVICE_REPORT_SIZE;
377 int adjust_counters (int s, int enabled, int from_virtual)
380 * Adjust counters based on sensor enable action. Return values are:
381 * 0 if the operation was completed and we're all set
382 * 1 if we toggled the state of the sensor and there's work left
383 * -1 in case of an error
386 int dev_num = sensor[s].dev_num;
388 if (!check_state_change(s, enabled, from_virtual))
389 return 0; /* The state of the sensor remains the same: we're done */
392 ALOGI("Enabling sensor %d (iio device %d: %s)\n", s, dev_num, sensor[s].friendly_name);
394 switch (sensor[s].type) {
395 case SENSOR_TYPE_ACCELEROMETER:
399 case SENSOR_TYPE_MAGNETIC_FIELD:
400 compass_read_data(s);
403 case SENSOR_TYPE_GYROSCOPE:
408 ALOGI("Disabling sensor %d (iio device %d: %s)\n", s, dev_num, sensor[s].friendly_name);
410 /* Sensor disabled, lower report available flag */
411 sensor[s].report_pending = 0;
413 /* Save calibration data to persistent storage */
414 switch (sensor[s].type) {
415 case SENSOR_TYPE_ACCELEROMETER:
419 case SENSOR_TYPE_MAGNETIC_FIELD:
420 compass_store_data(s);
423 case SENSOR_TYPE_GYROSCOPE:
429 /* We changed the state of a sensor: adjust device ref counts */
431 switch(sensor[s].mode) {
434 trig_sensors_per_dev[dev_num]++;
436 trig_sensors_per_dev[dev_num]--;
441 active_poll_sensors++;
442 poll_sensors_per_dev[dev_num]++;
445 active_poll_sensors--;
446 poll_sensors_per_dev[dev_num]--;
452 /* Invalid sensor mode */
458 static int get_field_count (int s, size_t *field_size)
460 *field_size = sizeof(float);
462 switch (sensor[s].type) {
463 case SENSOR_TYPE_ACCELEROMETER: /* m/s^2 */
464 case SENSOR_TYPE_MAGNETIC_FIELD: /* micro-tesla */
465 case SENSOR_TYPE_ORIENTATION: /* degrees */
466 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
467 case SENSOR_TYPE_GYROSCOPE: /* radians/s */
470 case SENSOR_TYPE_INTERNAL_INTENSITY:
471 case SENSOR_TYPE_INTERNAL_ILLUMINANCE:
472 case SENSOR_TYPE_LIGHT: /* SI lux units */
473 case SENSOR_TYPE_AMBIENT_TEMPERATURE: /* °C */
474 case SENSOR_TYPE_TEMPERATURE: /* °C */
475 case SENSOR_TYPE_PROXIMITY: /* centimeters */
476 case SENSOR_TYPE_PRESSURE: /* hecto-pascal */
477 case SENSOR_TYPE_RELATIVE_HUMIDITY: /* percent */
478 case SENSOR_TYPE_STEP_DETECTOR: /* event: always 1 */
481 case SENSOR_TYPE_ROTATION_VECTOR:
484 case SENSOR_TYPE_STEP_COUNTER: /* number of steps */
485 *field_size = sizeof(uint64_t);
488 ALOGE("Unknown sensor type!\n");
489 return 0; /* Drop sample */
494 * CTS acceptable thresholds:
495 * EventGapVerification.java: (th <= 1.8)
496 * FrequencyVerification.java: (0.9)*(expected freq) => (th <= 1.1111)
498 #define THRESHOLD 1.10
499 #define MAX_DELAY 500000000 /* 500 ms */
501 void set_report_ts(int s, int64_t ts)
503 int64_t maxTs, period;
506 * A bit of a hack to please a bunch of cts tests. They
507 * expect the timestamp to be exacly according to the set-up
508 * frequency but if we're simply getting the timestamp at hal level
509 * this may not be the case. Perhaps we'll get rid of this when
510 * we'll be reading the timestamp from the iio channel for all sensors
512 if (sensor[s].report_ts && sensor[s].sampling_rate &&
513 REPORTING_MODE(sensor_desc[s].flags) == SENSOR_FLAG_CONTINUOUS_MODE)
515 period = (int64_t) (1000000000.0 / sensor[s].sampling_rate);
516 maxTs = sensor[s].report_ts + THRESHOLD * period;
517 /* If we're too far behind get back on track */
518 if (ts - maxTs >= MAX_DELAY)
520 sensor[s].report_ts = (ts < maxTs ? ts : maxTs);
522 sensor[s].report_ts = ts;
526 static void* acquisition_routine (void* param)
529 * Data acquisition routine run in a dedicated thread, covering a single sensor. This loop will periodically retrieve sampling data through
530 * 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
531 * frequently, as the thread may be disposed of at any time. Note that Bionic does not provide pthread_cancel / pthread_testcancel...
534 int s = (int) (size_t) param;
536 sensors_event_t data = {0};
539 struct timespec target_time;
540 int64_t timestamp, period, start, stop;
543 if (s < 0 || s >= sensor_count) {
544 ALOGE("Invalid sensor handle!\n");
548 ALOGI("Entering S%d (%s) data acquisition thread: rate:%g\n", s, sensor[s].friendly_name, sensor[s].sampling_rate);
550 if (sensor[s].sampling_rate <= 0) {
551 ALOGE("Invalid rate in acquisition routine for sensor %d: %g\n", s, sensor[s].sampling_rate);
555 /* Initialize data fields that will be shared by all sensor reports */
556 data.version = sizeof(sensors_event_t);
558 data.type = sensor_desc[s].type;
560 num_fields = get_field_count(s, &field_size);
563 * 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
564 * variables to get the acquisition threads out of sleep quickly after the sampling rate is adjusted, or the sensor is disabled.
566 pthread_mutex_lock(&thread_release_mutex[s]);
568 /* Pinpoint the moment we start sampling */
569 timestamp = get_timestamp_monotonic();
571 /* Check and honor termination requests */
572 while (sensor[s].thread_data_fd[1] != -1) {
573 start = get_timestamp_boot();
575 /* Read values through sysfs */
576 for (c=0; c<num_fields; c++) {
577 if (field_size == sizeof(uint64_t))
578 data.u64.data[c] = acquire_immediate_uint64_value(s, c);
580 data.data[c] = acquire_immediate_float_value(s, c);
582 /* Check and honor termination requests */
583 if (sensor[s].thread_data_fd[1] == -1)
586 stop = get_timestamp_boot();
587 set_report_ts(s, start/2 + stop/2);
588 data.timestamp = sensor[s].report_ts;
589 /* If the sample looks good */
590 if (sensor[s].ops.finalize(s, &data)) {
592 /* Pipe it for transmission to poll loop */
593 ret = write(sensor[s].thread_data_fd[1], &data, sizeof(sensors_event_t));
595 if (ret != sizeof(sensors_event_t))
596 ALOGE("S%d write failure: wrote %d, got %d\n", s, sizeof(sensors_event_t), ret);
599 /* Check and honor termination requests */
600 if (sensor[s].thread_data_fd[1] == -1)
603 /* Recalculate period assuming sensor[s].sampling_rate can be changed dynamically during the thread run */
604 if (sensor[s].sampling_rate <= 0) {
605 ALOGE("Unexpected sampling rate for sensor %d: %g\n", s, sensor[s].sampling_rate);
609 period = (int64_t) (1000000000.0 / sensor[s].sampling_rate);
611 set_timestamp(&target_time, timestamp);
613 /* Wait until the sampling time elapses, or a rate change is signaled, or a thread exit is requested */
614 ret = pthread_cond_timedwait(&thread_release_cond[s], &thread_release_mutex[s], &target_time);
618 ALOGV("Acquisition thread for S%d exiting\n", s);
619 pthread_mutex_unlock(&thread_release_mutex[s]);
625 static void start_acquisition_thread (int s)
627 int incoming_data_fd;
630 struct epoll_event ev = {0};
632 ALOGV("Initializing acquisition context for sensor %d\n", s);
634 /* Create condition variable and mutex for quick thread release */
635 ret = pthread_condattr_init(&thread_cond_attr[s]);
636 ret = pthread_condattr_setclock(&thread_cond_attr[s], CLOCK_MONOTONIC);
637 ret = pthread_cond_init(&thread_release_cond[s], &thread_cond_attr[s]);
638 ret = pthread_mutex_init(&thread_release_mutex[s], NULL);
640 /* Create a pipe for inter thread communication */
641 ret = pipe(sensor[s].thread_data_fd);
643 incoming_data_fd = sensor[s].thread_data_fd[0];
646 ev.data.u32 = THREAD_REPORT_TAG_BASE + s;
648 /* Add incoming side of pipe to our poll set, with a suitable tag */
649 ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, incoming_data_fd , &ev);
651 ALOGE("Failed adding %d to poll set (%s)\n",
652 incoming_data_fd, strerror(errno));
655 /* Create and start worker thread */
656 ret = pthread_create(&sensor[s].acquisition_thread, NULL, acquisition_routine, (void*) (size_t) s);
660 static void stop_acquisition_thread (int s)
662 int incoming_data_fd = sensor[s].thread_data_fd[0];
663 int outgoing_data_fd = sensor[s].thread_data_fd[1];
665 ALOGV("Tearing down acquisition context for sensor %d\n", s);
667 /* Delete the incoming side of the pipe from our poll set */
668 epoll_ctl(poll_fd, EPOLL_CTL_DEL, incoming_data_fd, NULL);
670 /* Mark the pipe ends as invalid ; that's a cheap exit flag */
671 sensor[s].thread_data_fd[0] = -1;
672 sensor[s].thread_data_fd[1] = -1;
674 /* Close both sides of our pipe */
675 close(incoming_data_fd);
676 close(outgoing_data_fd);
678 /* Stop acquisition thread and clean up thread handle */
679 pthread_cond_signal(&thread_release_cond[s]);
680 pthread_join(sensor[s].acquisition_thread, NULL);
682 /* Clean up our sensor descriptor */
683 sensor[s].acquisition_thread = -1;
685 /* Delete condition variable and mutex */
686 pthread_cond_destroy(&thread_release_cond[s]);
687 pthread_mutex_destroy(&thread_release_mutex[s]);
691 static int is_fast_accelerometer (int s)
694 * Some games don't react well to accelerometers using any-motion triggers. Even very low thresholds seem to trip them, and they tend to
695 * request fairly high event rates. Favor continuous triggers if the sensor is an accelerometer and uses a sampling rate of at least 25.
698 if (sensor[s].type != SENSOR_TYPE_ACCELEROMETER)
701 if (sensor[s].sampling_rate < 25)
708 static void tentative_switch_trigger (int s)
711 * Under certain situations it may be beneficial to use an alternate trigger:
713 * - for applications using the accelerometer with high sampling rates, prefer the continuous trigger over the any-motion one, to avoid
714 * jumps related to motion thresholds
717 if (is_fast_accelerometer(s) && !(sensor[s].quirks & QUIRK_TERSE_DRIVER) && sensor[s].selected_trigger == sensor[s].motion_trigger_name)
718 setup_trigger(s, sensor[s].init_trigger_name);
722 static float get_group_max_sampling_rate (int s)
724 /* Review the sampling rates of linked sensors and return the maximum */
728 float arbitrated_rate = 0;
731 arbitrated_rate = sensor[s].requested_rate;
733 /* If any of the currently active sensors built on top of this one need a higher sampling rate, switch to this rate */
734 for (i = 0; i < sensor_count; i++)
735 for (vi = 0; vi < sensor[i].base_count; vi++)
736 if (sensor[i].base[vi] == s && is_enabled(i) && sensor[i].requested_rate > arbitrated_rate) /* If sensor i depends on sensor s */
737 arbitrated_rate = sensor[i].requested_rate;
739 /* If any of the currently active sensors we rely on is using a higher sampling rate, switch to this rate */
740 for (vi = 0; vi < sensor[s].base_count; vi++) {
741 i = sensor[s].base[vi];
742 if (is_enabled(i) && sensor[i].requested_rate > arbitrated_rate)
743 arbitrated_rate = sensor[i].requested_rate;
746 return arbitrated_rate;
749 extern float sensor_get_max_freq (int s);
751 static float select_closest_available_rate(int s, float requested_rate)
755 float selected_rate = 0;
756 float max_rate_from_prop = sensor_get_max_freq(s);
757 int dev_num = sensor[s].dev_num;
759 if (!sensor[s].avail_freqs_count)
760 return requested_rate;
762 for (j = 0; j < sensor[s].avail_freqs_count; j++) {
764 sr = sensor[s].avail_freqs[j];
766 /* If this matches the selected rate, we're happy. Have some tolerance for rounding errors and avoid needless jumps to higher rates */
767 if ((fabs(requested_rate - sr) <= 0.01) && (sr <= max_rate_from_prop)) {
771 /* Select rate if it's less than max freq */
772 if ((sr > selected_rate) && (sr <= max_rate_from_prop)) {
777 * If we reached a higher value than the desired rate, adjust selected rate so it matches the first higher available one and
778 * stop parsing - this makes the assumption that rates are sorted by increasing value in the allowed frequencies string.
780 if (sr > requested_rate) {
781 return selected_rate;
785 /* Check for wrong values */
786 if (selected_rate < 0.1) {
787 return requested_rate;
789 return selected_rate;
793 static int sensor_set_rate (int s, float requested_rate)
795 /* Set the rate at which a specific sensor should report events. See Android sensors.h for indication on sensor trigger modes */
797 char sysfs_path[PATH_MAX];
798 int dev_num = sensor[s].dev_num;
799 int i = sensor[s].catalog_index;
800 const char *prefix = sensor_catalog[i].tag;
801 int per_sensor_sampling_rate;
802 int per_device_sampling_rate;
805 float group_max_sampling_rate;
806 float cur_sampling_rate; /* Currently used sampling rate */
807 float arb_sampling_rate; /* Granted sampling rate after arbitration */
808 char hrtimer_sampling_path[PATH_MAX];
809 char trigger_path[PATH_MAX];
811 ALOGV("Sampling rate %g requested on sensor %d (%s)\n", requested_rate, s, sensor[s].friendly_name);
813 sensor[s].requested_rate = requested_rate;
815 arb_sampling_rate = requested_rate;
817 if (arb_sampling_rate < sensor[s].min_supported_rate) {
818 ALOGV("Sampling rate %g too low for %s, using %g instead\n", arb_sampling_rate, sensor[s].friendly_name, sensor[s].min_supported_rate);
819 arb_sampling_rate = sensor[s].min_supported_rate;
822 /* If one of the linked sensors uses a higher rate, adopt it */
823 group_max_sampling_rate = get_group_max_sampling_rate(s);
825 if (arb_sampling_rate < group_max_sampling_rate) {
826 ALOGV("Using %s sampling rate to %g too due to dependency\n", sensor[s].friendly_name, arb_sampling_rate);
827 arb_sampling_rate = group_max_sampling_rate;
830 if (sensor[s].max_supported_rate && arb_sampling_rate > sensor[s].max_supported_rate) {
831 ALOGV("Sampling rate %g too high for %s, using %g instead\n", arb_sampling_rate, sensor[s].friendly_name, sensor[s].max_supported_rate);
832 arb_sampling_rate = sensor[s].max_supported_rate;
835 sensor[s].sampling_rate = arb_sampling_rate;
837 /* If the sensor is virtual, we're done */
838 if (sensor[s].is_virtual)
841 /* If we're dealing with a poll-mode sensor */
842 if (sensor[s].mode == MODE_POLL) {
844 pthread_cond_signal(&thread_release_cond[s]); /* Wake up thread so the new sampling rate gets used */
848 sprintf(sysfs_path, SENSOR_SAMPLING_PATH, dev_num, prefix);
850 if (sysfs_read_float(sysfs_path, &cur_sampling_rate) != -1) {
851 per_sensor_sampling_rate = 1;
852 per_device_sampling_rate = 0;
854 per_sensor_sampling_rate = 0;
856 sprintf(sysfs_path, DEVICE_SAMPLING_PATH, dev_num);
858 if (sysfs_read_float(sysfs_path, &cur_sampling_rate) != -1)
859 per_device_sampling_rate = 1;
861 per_device_sampling_rate = 0;
864 if (!per_sensor_sampling_rate && !per_device_sampling_rate) {
865 ALOGE("No way to adjust sampling rate on sensor %d\n", s);
869 if (sensor[s].hrtimer_trigger_name[0] != '\0') {
870 snprintf(trigger_path, PATH_MAX, "%s%s%d/", IIO_DEVICES, "trigger", sensor[s].trigger_nr);
871 snprintf(hrtimer_sampling_path, PATH_MAX, "%s%s", trigger_path, "sampling_frequency");
872 /* Enforce frequency update when software trigger
873 * frequency and current sampling rate are different */
874 if (sysfs_read_float(hrtimer_sampling_path, &sr) != -1 && sr != cur_sampling_rate)
875 cur_sampling_rate = -1;
877 arb_sampling_rate = select_closest_available_rate(s, arb_sampling_rate);
880 /* Record the rate that was agreed upon with the sensor taken in isolation ; this avoid uncontrolled ripple effects between colocated sensor rates */
881 sensor[s].semi_arbitrated_rate = arb_sampling_rate;
883 /* Coordinate with others active sensors on the same device, if any */
884 if (per_device_sampling_rate)
885 for (n=0; n<sensor_count; n++)
886 if (n != s && sensor[n].dev_num == dev_num && sensor[n].num_channels && is_enabled(n) &&
887 sensor[n].semi_arbitrated_rate > arb_sampling_rate) {
888 ALOGV("Sampling rate shared between %s and %s, using %g instead of %g\n", sensor[s].friendly_name, sensor[n].friendly_name,
889 sensor[n].semi_arbitrated_rate, arb_sampling_rate);
890 arb_sampling_rate = sensor[n].semi_arbitrated_rate;
893 sensor[s].sampling_rate = arb_sampling_rate;
895 /* Update actual sampling rate field for this sensor and others which may be sharing the same sampling rate */
896 if (per_device_sampling_rate)
897 for (n=0; n<sensor_count; n++)
898 if (sensor[n].dev_num == dev_num && n != s && sensor[n].num_channels)
899 sensor[n].sampling_rate = arb_sampling_rate;
901 /* If the desired rate is already active we're all set */
902 if (arb_sampling_rate == cur_sampling_rate)
905 ALOGI("Sensor %d (%s) sampling rate set to %g\n", s, sensor[s].friendly_name, arb_sampling_rate);
907 if (sensor[s].hrtimer_trigger_name[0] != '\0')
908 sysfs_write_float(hrtimer_sampling_path, ceilf(arb_sampling_rate));
910 if (trig_sensors_per_dev[dev_num])
911 enable_buffer(dev_num, 0);
913 if (sensor[s].hrtimer_trigger_name[0] != '\0') {
914 sysfs_write_float(sysfs_path, select_closest_available_rate(s, arb_sampling_rate));
916 sysfs_write_float(sysfs_path, arb_sampling_rate);
919 /* Check if it makes sense to use an alternate trigger */
920 tentative_switch_trigger(s);
922 if (trig_sensors_per_dev[dev_num])
923 enable_buffer(dev_num, 1);
929 static void reapply_sampling_rates (int s)
932 * The specified sensor was either enabled or disabled. Other sensors in the same group may have constraints related to this sensor
933 * sampling rate on their own sampling rate, so reevaluate them by retrying to use their requested sampling rate, rather than the one
934 * that ended up being used after arbitration.
939 if (sensor[s].is_virtual) {
940 /* Take care of downwards dependencies */
941 for (i=0; i<sensor[s].base_count; i++) {
942 base = sensor[s].base[i];
943 sensor_set_rate(base, sensor[base].requested_rate);
949 for (i=0; i<sensor_count; i++)
950 for (j=0; j<sensor[i].base_count; j++)
951 if (sensor[i].base[j] == s) /* If sensor i depends on sensor s */
952 sensor_set_rate(i, sensor[i].requested_rate);
956 static int sensor_activate_virtual (int s, int enabled, int from_virtual)
960 sensor[s].event_count = 0;
961 sensor[s].meta_data_pending = 0;
963 if (!check_state_change(s, enabled, from_virtual))
964 return 0; /* The state of the sensor remains the same ; we're done */
967 ALOGI("Enabling sensor %d (%s)\n", s, sensor[s].friendly_name);
969 ALOGI("Disabling sensor %d (%s)\n", s, sensor[s].friendly_name);
971 sensor[s].report_pending = 0;
973 for (i=0; i<sensor[s].base_count; i++) {
975 base = sensor[s].base[i];
976 sensor_activate(base, enabled, 1);
979 sensor[base].ref_count++;
981 sensor[base].ref_count--;
984 /* Reevaluate sampling rates of linked sensors */
985 reapply_sampling_rates(s);
990 int sensor_activate (int s, int enabled, int from_virtual)
992 char device_name[PATH_MAX];
993 struct epoll_event ev = {0};
994 int dev_fd, event_fd;
996 int dev_num = sensor[s].dev_num;
998 int catalog_index = sensor[s].catalog_index;
1000 if (sensor[s].is_virtual)
1001 return sensor_activate_virtual(s, enabled, from_virtual);
1003 /* Prepare the report timestamp field for the first event, see set_report_ts method */
1004 sensor[s].report_ts = 0;
1006 ret = adjust_counters(s, enabled, from_virtual);
1008 /* If the operation was neutral in terms of state, we're done */
1012 sensor[s].event_count = 0;
1013 sensor[s].meta_data_pending = 0;
1016 setup_noise_filtering(s); /* Initialize filtering data if required */
1018 if (sensor[s].mode == MODE_TRIGGER) {
1021 enable_buffer(dev_num, 0);
1022 setup_trigger(s, "\n");
1024 /* If there's at least one sensor enabled on this iio device */
1025 if (trig_sensors_per_dev[dev_num]) {
1027 /* Start sampling */
1028 if (sensor[s].hrtimer_trigger_name[0] != '\0')
1029 setup_trigger(s, sensor[s].hrtimer_trigger_name);
1031 setup_trigger(s, sensor[s].init_trigger_name);
1033 enable_buffer(dev_num, 1);
1035 } else if (sensor[s].mode == MODE_POLL) {
1036 if (sensor[s].needs_enable) {
1037 enable_sensor(dev_num, sensor_catalog[catalog_index].tag, enabled);
1042 * Make sure we have a fd on the character device ; conversely, close the fd if no one is using associated sensors anymore. The assumption
1043 * here is that the underlying driver will power on the relevant hardware block while someone holds a fd on the device.
1045 dev_fd = device_fd[dev_num];
1048 if (sensor[s].mode == MODE_POLL)
1049 stop_acquisition_thread(s);
1051 if (dev_fd != -1 && !poll_sensors_per_dev[dev_num] && !trig_sensors_per_dev[dev_num]) {
1052 /* Stop watching this fd. This should be a no-op in case this fd was not in the poll set. */
1053 epoll_ctl(poll_fd, EPOLL_CTL_DEL, dev_fd, NULL);
1056 device_fd[dev_num] = -1;
1059 if (sensor[s].mode == MODE_EVENT) {
1060 event_fd = events_fd[dev_num];
1062 for (c = 0; c < sensor_catalog[catalog_index].num_channels; c++) {
1063 for (d = 0; d < sensor_catalog[catalog_index].channel[c].num_events; d++)
1064 enable_event(dev_num, sensor_catalog[catalog_index].channel[c].event[d].ev_en_path, enabled);
1067 epoll_ctl(poll_fd, EPOLL_CTL_DEL, event_fd, NULL);
1069 events_fd[dev_num] = -1;
1073 /* Release any filtering data we may have accumulated */
1074 release_noise_filtering_data(s);
1076 /* Reevaluate sampling rates of linked sensors */
1077 reapply_sampling_rates(s);
1082 /* First enabled sensor on this iio device */
1083 sprintf(device_name, DEV_FILE_PATH, dev_num);
1084 dev_fd = open(device_name, O_RDONLY | O_NONBLOCK);
1086 device_fd[dev_num] = dev_fd;
1089 ALOGE("Could not open fd on %s (%s)\n", device_name, strerror(errno));
1090 adjust_counters(s, 0, from_virtual);
1094 ALOGV("Opened %s: fd=%d\n", device_name, dev_fd);
1096 if (sensor[s].mode == MODE_TRIGGER) {
1098 /* Add this iio device fd to the set of watched fds */
1099 ev.events = EPOLLIN;
1100 ev.data.u32 = dev_num;
1102 ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, dev_fd, &ev);
1105 ALOGE("Failed adding %d to poll set (%s)\n", dev_fd, strerror(errno));
1109 /* Note: poll-mode fds are not readable */
1110 } else if (sensor[s].mode == MODE_EVENT) {
1111 event_fd = events_fd[dev_num];
1113 ret = ioctl(dev_fd, IIO_GET_EVENT_FD_IOCTL, &event_fd);
1114 if (ret == -1 || event_fd == -1) {
1115 ALOGE("Failed to retrieve event_fd from %d (%s)\n", dev_fd, strerror(errno));
1118 events_fd[dev_num] = event_fd;
1119 ALOGV("Opened fd=%d to receive events\n", event_fd);
1121 /* Add this event fd to the set of watched fds */
1122 ev.events = EPOLLIN;
1123 ev.data.u32 = dev_num;
1125 ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, event_fd, &ev);
1127 ALOGE("Failed adding %d to poll set (%s)\n", event_fd, strerror(errno));
1130 for (c = 0; c < sensor_catalog[catalog_index].num_channels; c++) {
1132 for (d = 0; d < sensor_catalog[catalog_index].channel[c].num_events; d++)
1133 enable_event(dev_num, sensor_catalog[catalog_index].channel[c].event[d].ev_en_path, enabled);
1136 if (!poll_sensors_per_dev[dev_num] && !trig_sensors_per_dev[dev_num]) {
1138 device_fd[dev_num] = -1;
1143 /* Ensure that on-change sensors send at least one event after enable */
1144 get_field_count(s, &field_size);
1145 if (field_size == sizeof(uint64_t))
1146 sensor[s].prev_val.data64 = -1;
1148 sensor[s].prev_val.data = -1;
1150 if (sensor[s].mode == MODE_POLL)
1151 start_acquisition_thread(s);
1153 /* Reevaluate sampling rates of linked sensors */
1154 reapply_sampling_rates(s);
1160 static void enable_motion_trigger (int dev_num)
1163 * In the ideal case, we enumerate two triggers per iio device ; the default (periodically firing) trigger, and another one (the motion
1164 * trigger) that only fires up when motion is detected. This second one allows for lesser energy consumption, but requires periodic sample
1165 * duplication at the HAL level for sensors that Android defines as continuous. This "duplicate last sample" logic can only be engaged
1166 * 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
1167 * trigger when we got events for all active sensors. Unfortunately in the general case several sensors can be associated to a given iio
1168 * device, they can independently be controlled, and we have to adjust the trigger in use at the iio device level depending on whether or
1169 * not appropriate conditions are met at the sensor level.
1174 int active_sensors = trig_sensors_per_dev[dev_num];
1175 int candidate[MAX_SENSORS];
1176 int candidate_count = 0;
1178 if (!active_sensors)
1181 /* Check that all active sensors are ready to switch */
1183 for (s=0; s<MAX_SENSORS; s++)
1184 if (sensor[s].dev_num == dev_num && is_enabled(s) && sensor[s].num_channels &&
1185 (!sensor[s].motion_trigger_name[0] || !sensor[s].report_initialized || is_fast_accelerometer(s) ||
1186 (sensor[s].quirks & QUIRK_FORCE_CONTINUOUS)))
1189 /* Record which particular sensors need to switch */
1191 for (s=0; s<MAX_SENSORS; s++)
1192 if (sensor[s].dev_num == dev_num && is_enabled(s) && sensor[s].num_channels && sensor[s].selected_trigger != sensor[s].motion_trigger_name)
1193 candidate[candidate_count++] = s;
1195 if (!candidate_count)
1198 /* Now engage the motion trigger for sensors which aren't using it */
1200 enable_buffer(dev_num, 0);
1202 for (i=0; i<candidate_count; i++) {
1204 setup_trigger(s, sensor[s].motion_trigger_name);
1207 enable_buffer(dev_num, 1);
1210 static void stamp_reports (int dev_num, int64_t ts)
1214 for (s=0; s<MAX_SENSORS; s++)
1215 if (sensor[s].dev_num == dev_num && is_enabled(s) && sensor[s].mode != MODE_POLL) {
1216 if (sensor[s].quirks & QUIRK_SPOTTY)
1217 set_report_ts(s, ts);
1219 sensor[s].report_ts = ts;
1224 static int integrate_device_report_from_dev(int dev_num, int fd)
1228 unsigned char buf[MAX_DEVICE_REPORT_SIZE] = { 0 };
1230 unsigned char *target;
1231 unsigned char *source;
1234 int ts_offset = 0; /* Offset of iio timestamp, if provided */
1235 int64_t boot_to_rt_delta;
1237 /* There's an incoming report on the specified iio device char dev fd */
1239 ALOGE("Ignoring stale report on iio device %d\n", dev_num);
1243 len = read(fd, buf, expected_dev_report_size[dev_num]);
1246 ALOGE("Could not read report from iio device %d (%s)\n", dev_num, strerror(errno));
1250 ALOGV("Read %d bytes from iio device %d\n", len, dev_num);
1252 /* Map device report to sensor reports */
1254 for (s=0; s<MAX_SENSORS; s++)
1255 if (sensor[s].dev_num == dev_num && is_enabled(s)) {
1259 /* Copy data from device to sensor report buffer */
1260 for (c=0; c<sensor[s].num_channels; c++) {
1262 target = sensor[s].report_buffer + sr_offset;
1264 source = buf + sensor[s].channel[c].offset;
1266 size = sensor[s].channel[c].size;
1268 memcpy(target, source, size);
1273 ALOGV("Sensor %d report available (%d bytes)\n", s, sr_offset);
1275 sensor[s].report_pending = DATA_TRIGGER;
1276 sensor[s].report_initialized = 1;
1280 /* Tentatively switch to an any-motion trigger if conditions are met */
1281 enable_motion_trigger(dev_num);
1283 /* If no iio timestamp channel was detected for this device, bail out */
1284 if (!has_iio_ts[dev_num]) {
1285 stamp_reports(dev_num, get_timestamp_boot());
1289 /* Don't trust the timestamp channel in any-motion mode */
1290 for (s=0; s<MAX_SENSORS; s++)
1291 if (sensor[s].dev_num == dev_num && is_enabled(s) && sensor[s].selected_trigger == sensor[s].motion_trigger_name) {
1292 stamp_reports(dev_num, get_timestamp_boot());
1296 /* Align on a 64 bits boundary */
1297 ts_offset = expected_dev_report_size[dev_num] - sizeof(int64_t);
1299 /* If we read an amount of data consistent with timestamp presence */
1300 if (len == expected_dev_report_size[dev_num])
1301 ts = *(int64_t*) (buf + ts_offset);
1304 ALOGV("Unreliable timestamp channel on iio dev %d\n", dev_num);
1305 stamp_reports(dev_num, get_timestamp_boot());
1309 ALOGV("Driver timestamp on iio device %d: ts=%lld\n", dev_num, ts);
1311 boot_to_rt_delta = get_timestamp_boot() - get_timestamp_realtime();
1313 stamp_reports(dev_num, ts + boot_to_rt_delta);
1318 static int integrate_device_report_from_event(int dev_num, int fd)
1322 struct iio_event_data event;
1323 int64_t boot_to_rt_delta = get_timestamp_boot() - get_timestamp_realtime();
1325 /* There's an incoming report on the specified iio device char dev fd */
1327 ALOGE("Ignoring stale report on event fd %d of device %d\n",
1332 len = read(fd, &event, sizeof(event));
1335 ALOGE("Could not read event from fd %d of device %d (%s)\n",
1336 fd, dev_num, strerror(errno));
1340 ts = event.timestamp + boot_to_rt_delta;
1342 ALOGV("Read event %lld from fd %d of iio device %d - ts %lld\n", event.id, fd, dev_num, ts);
1344 /* Map device report to sensor reports */
1345 for (s = 0; s < MAX_SENSORS; s++)
1346 if (sensor[s].dev_num == dev_num &&
1348 sensor[s].event_id = event.id;
1349 sensor[s].report_ts = ts;
1350 sensor[s].report_pending = 1;
1351 sensor[s].report_initialized = 1;
1352 ALOGV("Sensor %d report available (1 byte)\n", s);
1357 static int integrate_device_report(int dev_num)
1361 if (dev_num < 0 || dev_num >= MAX_DEVICES) {
1362 ALOGE("Event reported on unexpected iio device %d\n", dev_num);
1366 if (events_fd[dev_num] != -1) {
1367 ret = integrate_device_report_from_event(dev_num, events_fd[dev_num]);
1372 if (device_fd[dev_num] != -1)
1373 ret = integrate_device_report_from_dev(dev_num, device_fd[dev_num]);
1378 static int propagate_vsensor_report (int s, sensors_event_t *data)
1380 /* There's a new report stored in sensor.sample for this sensor; transmit it */
1382 memcpy(data, &sensor[s].sample, sizeof(sensors_event_t));
1385 data->type = sensor_desc[s].type; /* sensor_desc[s].type can differ from sensor[s].type ; internal types are remapped */
1390 static int propagate_sensor_report (int s, sensors_event_t *data)
1392 /* There's a sensor report pending for this sensor ; transmit it */
1395 int num_fields = get_field_count(s, &field_size);
1397 unsigned char* current_sample;
1400 /* If there's nothing to return... we're done */
1404 ALOGV("Sample on sensor %d (type %d):\n", s, sensor[s].type);
1406 if (sensor[s].mode == MODE_POLL) {
1407 /* We received a good sample but we're not directly enabled so we'll drop */
1408 if (!sensor[s].directly_enabled)
1410 /* Use the data provided by the acquisition thread */
1411 ALOGV("Reporting data from worker thread for S%d\n", s);
1412 memcpy(data, &sensor[s].sample, sizeof(sensors_event_t));
1413 data->timestamp = sensor[s].report_ts;
1417 memset(data, 0, sizeof(sensors_event_t));
1419 data->version = sizeof(sensors_event_t);
1421 data->type = sensor_desc[s].type; /* sensor_desc[s].type can differ from sensor[s].type ; internal types are remapped */
1422 data->timestamp = sensor[s].report_ts;
1424 if (sensor[s].mode == MODE_EVENT) {
1425 ALOGV("Reporting event\n");
1426 /* Android requires events to return 1.0 */
1427 int dir = IIO_EVENT_CODE_EXTRACT_DIR(sensor[s].event_id);
1428 switch (sensor[s].type) {
1429 case SENSOR_TYPE_PROXIMITY:
1430 if (dir == IIO_EV_DIR_FALLING)
1431 data->data[0] = 0.0;
1433 data->data[0] = 1.0;
1436 data->data[0] = 1.0;
1440 data->data[1] = 0.0;
1441 data->data[2] = 0.0;
1445 /* Convert the data into the expected Android-level format */
1447 current_sample = sensor[s].report_buffer;
1449 for (c=0; c<num_fields; c++) {
1451 data->data[c] = sensor[s].ops.transform (s, c, current_sample);
1453 ALOGV("\tfield %d: %g\n", c, data->data[c]);
1454 current_sample += sensor[s].channel[c].size;
1457 ret = sensor[s].ops.finalize(s, data);
1459 /* We will drop samples if the sensor is not directly enabled */
1460 if (!sensor[s].directly_enabled)
1463 /* 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 */
1468 static void synthetize_duplicate_samples (void)
1471 * Some sensor types (ex: gyroscope) are defined as continuously firing by Android, despite the fact that
1472 * we can be dealing with iio drivers that only report events for new samples. For these we generate reports
1473 * periodically, duplicating the last data we got from the driver. This is not necessary for polling sensors.
1481 for (s=0; s<sensor_count; s++) {
1483 /* Ignore disabled sensors */
1487 /* If the sensor is continuously firing, leave it alone */
1488 if (sensor[s].selected_trigger != sensor[s].motion_trigger_name)
1491 /* If we haven't seen a sample, there's nothing to duplicate */
1492 if (!sensor[s].report_initialized)
1495 /* If a sample was recently buffered, leave it alone too */
1496 if (sensor[s].report_pending)
1499 /* We also need a valid sampling rate to be configured */
1500 if (!sensor[s].sampling_rate)
1503 period = (int64_t) (1000000000.0 / sensor[s].sampling_rate);
1505 current_ts = get_timestamp_boot();
1506 target_ts = sensor[s].report_ts + period;
1508 if (target_ts <= current_ts) {
1509 /* Mark the sensor for event generation */
1510 set_report_ts(s, current_ts);
1511 sensor[s].report_pending = DATA_DUPLICATE;
1517 static void integrate_thread_report (uint32_t tag)
1519 int s = tag - THREAD_REPORT_TAG_BASE;
1522 len = read(sensor[s].thread_data_fd[0], &sensor[s].sample, sizeof(sensors_event_t));
1524 if (len == sizeof(sensors_event_t))
1525 sensor[s].report_pending = DATA_SYSFS;
1529 static int get_poll_wait_timeout (void)
1532 * Compute an appropriate timeout value, in ms, for the epoll_wait call that's going to await
1533 * for iio device reports and incoming reports from our sensor sysfs data reader threads.
1537 int64_t target_ts = INT64_MAX;
1542 * Check if we're dealing with a driver that only send events when there is motion, despite the fact that the associated Android sensor
1543 * type is continuous rather than on-change. In that case we have to duplicate events. Check deadline for the nearest upcoming event.
1545 for (s=0; s<sensor_count; s++)
1546 if (is_enabled(s) && sensor[s].selected_trigger == sensor[s].motion_trigger_name && sensor[s].sampling_rate) {
1547 period = (int64_t) (1000000000.0 / sensor[s].sampling_rate);
1549 if (sensor[s].report_ts + period < target_ts)
1550 target_ts = sensor[s].report_ts + period;
1553 /* If we don't have such a driver to deal with */
1554 if (target_ts == INT64_MAX)
1555 return -1; /* Infinite wait */
1557 ms_to_wait = (target_ts - get_timestamp_boot()) / 1000000;
1559 /* If the target timestamp is already behind us, don't wait */
1567 int sensor_poll (sensors_event_t* data, int count)
1572 struct epoll_event ev[MAX_DEVICES];
1573 int returned_events;
1576 /* Get one or more events from our collection of sensors */
1577 return_available_sensor_reports:
1579 /* Synthetize duplicate samples if needed */
1580 synthetize_duplicate_samples();
1582 returned_events = 0;
1584 /* Check our sensor collection for available reports */
1585 for (s=0; s<sensor_count && returned_events < count; s++) {
1587 if (sensor[s].report_pending) {
1590 if (sensor[s].is_virtual)
1591 event_count = propagate_vsensor_report(s, &data[returned_events]);
1593 /* Report this event if it looks OK */
1594 event_count = propagate_sensor_report(s, &data[returned_events]);
1597 sensor[s].report_pending = 0;
1598 returned_events += event_count;
1601 * If the sample was deemed invalid or unreportable, e.g. had the same value as the previously reported
1602 * value for a 'on change' sensor, silently drop it.
1606 while (sensor[s].meta_data_pending) {
1607 /* See sensors.h on these */
1608 data[returned_events].version = META_DATA_VERSION;
1609 data[returned_events].sensor = 0;
1610 data[returned_events].type = SENSOR_TYPE_META_DATA;
1611 data[returned_events].reserved0 = 0;
1612 data[returned_events].timestamp = 0;
1613 data[returned_events].meta_data.sensor = s;
1614 data[returned_events].meta_data.what = META_DATA_FLUSH_COMPLETE;
1616 sensor[s].meta_data_pending--;
1620 if (returned_events)
1621 return returned_events;
1625 ALOGV("Awaiting sensor data\n");
1627 nfds = epoll_wait(poll_fd, ev, MAX_DEVICES, get_poll_wait_timeout());
1630 ALOGE("epoll_wait returned -1 (%s)\n", strerror(errno));
1634 ALOGV("%d fds signalled\n", nfds);
1636 /* For each of the signalled sources */
1637 for (i=0; i<nfds; i++)
1638 if (ev[i].events == EPOLLIN)
1639 switch (ev[i].data.u32) {
1640 case 0 ... MAX_DEVICES-1:
1641 /* Read report from iio char dev fd */
1642 integrate_device_report(ev[i].data.u32);
1645 case THREAD_REPORT_TAG_BASE ...
1646 THREAD_REPORT_TAG_BASE + MAX_SENSORS-1:
1647 /* Get report from acquisition thread */
1648 integrate_thread_report(ev[i].data.u32);
1650 case FLUSH_REPORT_TAG:
1652 char flush_event_content;
1653 read(flush_event_fd[0], &flush_event_content, sizeof(flush_event_content));
1658 ALOGW("Unexpected event source!\n");
1662 goto return_available_sensor_reports;
1666 int sensor_set_delay (int s, int64_t ns)
1668 float requested_sampling_rate;
1671 ALOGE("Invalid delay requested on sensor %d: %lld\n", s, ns);
1675 requested_sampling_rate = 1000000000.0 / ns;
1677 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);
1680 * 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
1681 * reads and writes as well as buffer enable/disable operations, since at the iio level most drivers require the buffer to be turned off
1682 * 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
1683 * is changing the sampling rate.
1686 if (requested_sampling_rate != sensor[s].sampling_rate)
1687 return sensor_set_rate(s, requested_sampling_rate);
1693 int sensor_flush (int s)
1695 char flush_event_content = 0;
1696 /* If one shot or not enabled return -EINVAL */
1697 if (sensor_desc[s].flags & SENSOR_FLAG_ONE_SHOT_MODE || !is_enabled(s))
1700 sensor[s].meta_data_pending++;
1701 write(flush_event_fd[1], &flush_event_content, sizeof(flush_event_content));
1706 int allocate_control_data (void)
1709 struct epoll_event ev = {0};
1711 for (i=0; i<MAX_DEVICES; i++) {
1716 poll_fd = epoll_create(MAX_DEVICES);
1718 if (poll_fd == -1) {
1719 ALOGE("Can't create epoll instance for iio sensors!\n");
1723 ret = pipe(flush_event_fd);
1725 ALOGE("Cannot create flush_event_fd");
1729 ev.events = EPOLLIN;
1730 ev.data.u32 = FLUSH_REPORT_TAG;
1731 ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, flush_event_fd[0] , &ev);
1733 ALOGE("Failed adding %d to poll set (%s)\n",
1734 flush_event_fd[0], strerror(errno));
1742 void delete_control_data (void)