2 * Copyright (C) 2014 Intel Corporation.
10 #include <sys/epoll.h>
11 #include <sys/socket.h>
12 #include <utils/Log.h>
13 #include <hardware/sensors.h>
15 #include "enumeration.h"
17 #include "transform.h"
18 #include "calibration.h"
19 #include "description.h"
20 #include "filtering.h"
22 /* Currently active sensors count, per device */
23 static int poll_sensors_per_dev[MAX_DEVICES]; /* poll-mode sensors */
24 static int trig_sensors_per_dev[MAX_DEVICES]; /* trigger, event based */
26 static int device_fd[MAX_DEVICES]; /* fd on the /dev/iio:deviceX file */
28 static int poll_fd; /* epoll instance covering all enabled sensors */
30 static int active_poll_sensors; /* Number of enabled poll-mode sensors */
32 int64_t ts_delta; /* delta between SystemClock.getNanos and our timestamp */
34 /* We use pthread condition variables to get worker threads out of sleep */
35 static pthread_condattr_t thread_cond_attr [MAX_SENSORS];
36 static pthread_cond_t thread_release_cond [MAX_SENSORS];
37 static pthread_mutex_t thread_release_mutex [MAX_SENSORS];
40 * We associate tags to each of our poll set entries. These tags have the
42 * - a iio device number if the fd is a iio character device fd
43 * - THREAD_REPORT_TAG_BASE + sensor handle if the fd is the receiving end of a
44 * pipe used by a sysfs data acquisition thread
46 #define THREAD_REPORT_TAG_BASE 0x00010000
48 #define ENABLE_BUFFER_RETRIES 10
49 #define ENABLE_BUFFER_RETRY_DELAY_MS 10
51 static int enable_buffer(int dev_num, int enabled)
53 char sysfs_path[PATH_MAX];
54 int ret, retries, millisec;
55 struct timespec req = {0};
57 retries = ENABLE_BUFFER_RETRIES;
58 millisec = ENABLE_BUFFER_RETRY_DELAY_MS;
60 req.tv_nsec = millisec * 1000000L;
62 sprintf(sysfs_path, ENABLE_PATH, dev_num);
65 /* Low level, non-multiplexed, enable/disable routine */
66 ret = sysfs_write_int(sysfs_path, enabled);
70 ALOGE("Failed enabling buffer, retrying");
71 nanosleep(&req, (struct timespec *)NULL);
75 ALOGE("Could not enable buffer\n");
83 static int setup_trigger (int s, const char* trigger_val)
85 char sysfs_path[PATH_MAX];
86 int ret = -1, attempts = 5;
88 sprintf(sysfs_path, TRIGGER_PATH, sensor_info[s].dev_num);
90 if (trigger_val[0] != '\n')
91 ALOGI("Setting S%d (%s) trigger to %s\n", s,
92 sensor_info[s].friendly_name, trigger_val);
94 while (ret == -1 && attempts) {
95 ret = sysfs_write_str(sysfs_path, trigger_val);
100 sensor_info[s].selected_trigger = trigger_val;
102 ALOGE("Setting S%d (%s) trigger to %s FAILED.\n", s,
103 sensor_info[s].friendly_name, trigger_val);
108 void build_sensor_report_maps(int dev_num)
111 * Read sysfs files from a iio device's scan_element directory, and
112 * build a couple of tables from that data. These tables will tell, for
113 * each sensor, where to gather relevant data in a device report, i.e.
114 * the structure that we read from the /dev/iio:deviceX file in order to
115 * sensor report, itself being the data that we return to Android when a
116 * sensor poll completes. The mapping should be straightforward in the
117 * case where we have a single sensor active per iio device but, this is
118 * not the general case. In general several sensors can be handled
119 * through a single iio device, and the _en, _index and _type syfs
120 * entries all concur to paint a picture of what the structure of the
130 char spec_buf[MAX_TYPE_SPEC_LEN];
131 struct datum_info_t* ch_info;
133 char sysfs_path[PATH_MAX];
136 int channel_size_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
137 int sensor_handle_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
138 int channel_number_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
142 /* For each sensor that is linked to this device */
143 for (s=0; s<sensor_count; s++) {
144 if (sensor_info[s].dev_num != dev_num)
147 i = sensor_info[s].catalog_index;
149 /* Read channel details through sysfs attributes */
150 for (c=0; c<sensor_info[s].num_channels; c++) {
152 /* Read _type file */
153 sprintf(sysfs_path, CHANNEL_PATH "%s",
154 sensor_info[s].dev_num,
155 sensor_catalog[i].channel[c].type_path);
157 n = sysfs_read_str(sysfs_path, spec_buf,
161 ALOGW( "Failed to read type: %s\n",
166 ch_spec = sensor_info[s].channel[c].type_spec;
168 memcpy(ch_spec, spec_buf, sizeof(spec_buf));
170 ch_info = &sensor_info[s].channel[c].type_info;
172 size = decode_type_spec(ch_spec, ch_info);
174 /* Read _index file */
175 sprintf(sysfs_path, CHANNEL_PATH "%s",
176 sensor_info[s].dev_num,
177 sensor_catalog[i].channel[c].index_path);
179 n = sysfs_read_int(sysfs_path, &ch_index);
182 ALOGW( "Failed to read index: %s\n",
187 if (ch_index >= MAX_SENSORS) {
188 ALOGE("Index out of bounds!: %s\n", sysfs_path);
192 /* Record what this index is about */
194 sensor_handle_from_index [ch_index] = s;
195 channel_number_from_index[ch_index] = c;
196 channel_size_from_index [ch_index] = size;
201 /* Stop sampling - if we are recovering from hal restart */
202 enable_buffer(dev_num, 0);
203 setup_trigger(s, "\n");
205 /* Turn on channels we're aware of */
206 for (c=0;c<sensor_info[s].num_channels; c++) {
207 sprintf(sysfs_path, CHANNEL_PATH "%s",
208 sensor_info[s].dev_num,
209 sensor_catalog[i].channel[c].en_path);
210 sysfs_write_int(sysfs_path, 1);
214 ALOGI("Found %d channels on iio device %d\n", known_channels, dev_num);
217 * Now that we know which channels are defined, their sizes and their
218 * ordering, update channels offsets within device report. Note: there
219 * is a possibility that several sensors share the same index, with
220 * their data fields being isolated by masking and shifting as specified
221 * through the real bits and shift values in type attributes. This case
222 * is not currently supported. Also, the code below assumes no hole in
223 * the sequence of indices, so it is dependent on discovery of all
227 for (i=0; i<MAX_SENSORS * MAX_CHANNELS; i++) {
228 s = sensor_handle_from_index[i];
229 c = channel_number_from_index[i];
230 size = channel_size_from_index[i];
235 ALOGI("S%d C%d : offset %d, size %d, type %s\n",
236 s, c, offset, size, sensor_info[s].channel[c].type_spec);
238 sensor_info[s].channel[c].offset = offset;
239 sensor_info[s].channel[c].size = size;
246 int adjust_counters (int s, int enabled)
249 * Adjust counters based on sensor enable action. Return values are:
250 * -1 if there's an inconsistency: abort action in this case
251 * 0 if the operation was completed and we're all set
252 * 1 if we toggled the state of the sensor and there's work left
255 int dev_num = sensor_info[s].dev_num;
257 /* Refcount per sensor, in terms of enable count */
259 ALOGI("Enabling sensor %d (iio device %d: %s)\n",
260 s, dev_num, sensor_info[s].friendly_name);
262 if (sensor_info[s].enabled)
263 return 0; /* The sensor was, and remains, in use */
265 sensor_info[s].enabled = 1;
267 switch (sensor_info[s].type) {
268 case SENSOR_TYPE_MAGNETIC_FIELD:
269 compass_read_data(&sensor_info[s]);
272 case SENSOR_TYPE_GYROSCOPE:
273 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
274 gyro_cal_init(&sensor_info[s]);
278 if (sensor_info[s].enabled == 0)
279 return 0; /* Spurious disable call */
281 ALOGI("Disabling sensor %d (iio device %d: %s)\n", s, dev_num,
282 sensor_info[s].friendly_name);
284 sensor_info[s].enabled = 0;
286 /* Sensor disabled, lower report available flag */
287 sensor_info[s].report_pending = 0;
289 if (sensor_info[s].type == SENSOR_TYPE_MAGNETIC_FIELD)
290 compass_store_data(&sensor_info[s]);
292 if(sensor_info[s].type == SENSOR_TYPE_GYROSCOPE ||
293 sensor_info[s].type == SENSOR_TYPE_GYROSCOPE_UNCALIBRATED)
294 gyro_store_data(&sensor_info[s]);
298 /* If uncalibrated type and pair is already active don't adjust counters */
299 if (sensor_info[s].type == SENSOR_TYPE_GYROSCOPE_UNCALIBRATED &&
300 sensor_info[sensor_info[s].pair_idx].enabled != 0)
303 /* We changed the state of a sensor - adjust per iio device counters */
305 /* If this is a regular event-driven sensor */
306 if (sensor_info[s].num_channels) {
309 trig_sensors_per_dev[dev_num]++;
311 trig_sensors_per_dev[dev_num]--;
317 active_poll_sensors++;
318 poll_sensors_per_dev[dev_num]++;
322 active_poll_sensors--;
323 poll_sensors_per_dev[dev_num]--;
328 static int get_field_count (int s)
330 switch (sensor_info[s].type) {
331 case SENSOR_TYPE_ACCELEROMETER: /* m/s^2 */
332 case SENSOR_TYPE_MAGNETIC_FIELD: /* micro-tesla */
333 case SENSOR_TYPE_ORIENTATION: /* degrees */
334 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
335 case SENSOR_TYPE_GYROSCOPE: /* radians/s */
338 case SENSOR_TYPE_LIGHT: /* SI lux units */
339 case SENSOR_TYPE_AMBIENT_TEMPERATURE: /* °C */
340 case SENSOR_TYPE_TEMPERATURE: /* °C */
341 case SENSOR_TYPE_PROXIMITY: /* centimeters */
342 case SENSOR_TYPE_PRESSURE: /* hecto-pascal */
343 case SENSOR_TYPE_RELATIVE_HUMIDITY: /* percent */
346 case SENSOR_TYPE_ROTATION_VECTOR:
350 ALOGE("Unknown sensor type!\n");
351 return 0; /* Drop sample */
356 static void* acquisition_routine (void* param)
359 * Data acquisition routine run in a dedicated thread, covering a single
360 * sensor. This loop will periodically retrieve sampling data through
361 * sysfs, then package it as a sample and transfer it to our master poll
362 * loop through a report fd. Checks for a cancellation signal quite
363 * frequently, as the thread may be disposed of at any time. Note that
364 * Bionic does not provide pthread_cancel / pthread_testcancel...
367 int s = (int) (size_t) param;
368 int num_fields, sample_size;
369 struct sensors_event_t data = {0};
372 struct timespec target_time;
373 int64_t timestamp, period;
375 if (s < 0 || s >= sensor_count) {
376 ALOGE("Invalid sensor handle!\n");
380 ALOGI("Entering data acquisition thread S%d (%s): rate(%f), ts(%lld)\n", s,
381 sensor_info[s].friendly_name, sensor_info[s].sampling_rate, sensor_info[s].report_ts);
383 if (sensor_info[s].sampling_rate <= 0) {
384 ALOGE("Non-positive rate in acquisition routine for sensor %d: %f\n",
385 s, sensor_info[s].sampling_rate);
389 num_fields = get_field_count(s);
390 sample_size = num_fields * sizeof(float);
393 * Each condition variable is associated to a mutex that has to be
394 * locked by the thread that's waiting on it. We use these condition
395 * variables to get the acquisition threads out of sleep quickly after
396 * the sampling rate is adjusted, or the sensor is disabled.
398 pthread_mutex_lock(&thread_release_mutex[s]);
400 /* Pinpoint the moment we start sampling */
401 timestamp = get_timestamp_monotonic();
403 /* Check and honor termination requests */
404 while (sensor_info[s].thread_data_fd[1] != -1) {
406 /* Read values through sysfs */
407 for (c=0; c<num_fields; c++) {
408 data.data[c] = acquire_immediate_value(s, c);
409 /* Check and honor termination requests */
410 if (sensor_info[s].thread_data_fd[1] == -1)
414 /* If the sample looks good */
415 if (sensor_info[s].ops.finalize(s, &data)) {
417 /* Pipe it for transmission to poll loop */
418 ret = write( sensor_info[s].thread_data_fd[1],
419 data.data, sample_size);
420 if (ret != sample_size)
421 ALOGE("S%d acquisition thread: tried to write %d, ret: %d\n",
422 s, sample_size, ret);
425 /* Check and honor termination requests */
426 if (sensor_info[s].thread_data_fd[1] == -1)
429 /* Recalculate period asumming sensor_info[s].sampling_rate
430 * can be changed dynamically during the thread run */
431 if (sensor_info[s].sampling_rate <= 0) {
432 ALOGE("Non-positive rate in acquisition routine for sensor %d: %f\n",
433 s, sensor_info[s].sampling_rate);
437 period = (int64_t) (1000000000LL / sensor_info[s].sampling_rate);
439 set_timestamp(&target_time, timestamp);
442 * Wait until the sampling time elapses, or a rate change is
443 * signaled, or a thread exit is requested.
445 ret = pthread_cond_timedwait( &thread_release_cond[s],
446 &thread_release_mutex[s],
451 ALOGV("Acquisition thread for S%d exiting\n", s);
452 pthread_mutex_unlock(&thread_release_mutex[s]);
458 static void start_acquisition_thread (int s)
460 int incoming_data_fd;
463 struct epoll_event ev = {0};
465 ALOGV("Initializing acquisition context for sensor %d\n", s);
467 /* Create condition variable and mutex for quick thread release */
468 ret = pthread_condattr_init(&thread_cond_attr[s]);
469 ret = pthread_condattr_setclock(&thread_cond_attr[s], CLOCK_MONOTONIC);
470 ret = pthread_cond_init(&thread_release_cond[s], &thread_cond_attr[s]);
471 ret = pthread_mutex_init(&thread_release_mutex[s], NULL);
473 /* Create a pipe for inter thread communication */
474 ret = pipe(sensor_info[s].thread_data_fd);
476 incoming_data_fd = sensor_info[s].thread_data_fd[0];
479 ev.data.u32 = THREAD_REPORT_TAG_BASE + s;
481 /* Add incoming side of pipe to our poll set, with a suitable tag */
482 ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, incoming_data_fd , &ev);
484 /* Create and start worker thread */
485 ret = pthread_create( &sensor_info[s].acquisition_thread,
492 static void stop_acquisition_thread (int s)
494 int incoming_data_fd = sensor_info[s].thread_data_fd[0];
495 int outgoing_data_fd = sensor_info[s].thread_data_fd[1];
497 ALOGV("Tearing down acquisition context for sensor %d\n", s);
499 /* Delete the incoming side of the pipe from our poll set */
500 epoll_ctl(poll_fd, EPOLL_CTL_DEL, incoming_data_fd, NULL);
502 /* Mark the pipe ends as invalid ; that's a cheap exit flag */
503 sensor_info[s].thread_data_fd[0] = -1;
504 sensor_info[s].thread_data_fd[1] = -1;
506 /* Close both sides of our pipe */
507 close(incoming_data_fd);
508 close(outgoing_data_fd);
510 /* Stop acquisition thread and clean up thread handle */
511 pthread_cond_signal(&thread_release_cond[s]);
512 pthread_join(sensor_info[s].acquisition_thread, NULL);
514 /* Clean up our sensor descriptor */
515 sensor_info[s].acquisition_thread = -1;
517 /* Delete condition variable and mutex */
518 pthread_cond_destroy(&thread_release_cond[s]);
519 pthread_mutex_destroy(&thread_release_mutex[s]);
523 int sensor_activate(int s, int enabled)
525 char device_name[PATH_MAX];
526 struct epoll_event ev = {0};
529 int dev_num = sensor_info[s].dev_num;
530 int is_poll_sensor = !sensor_info[s].num_channels;
532 /* Prepare the report timestamp field for the first event, see set_report_ts method */
533 sensor_info[s].report_ts = 0;
534 ts_delta = load_timestamp_sys_clock() - get_timestamp_monotonic();
537 /* If we want to activate gyro calibrated and gyro uncalibrated is activated
538 * Deactivate gyro uncalibrated - Uncalibrated releases handler
539 * Activate gyro calibrated - Calibrated has handler
540 * Reactivate gyro uncalibrated - Uncalibrated gets data from calibrated */
542 /* If we want to deactivate gyro calibrated and gyro uncalibrated is active
543 * Deactivate gyro uncalibrated - Uncalibrated no longer gets data from handler
544 * Deactivate gyro calibrated - Calibrated releases handler
545 * Reactivate gyro uncalibrated - Uncalibrated has handler */
547 if (sensor_info[s].type == SENSOR_TYPE_GYROSCOPE &&
548 sensor_info[s].pair_idx && sensor_info[sensor_info[s].pair_idx].enabled != 0) {
550 sensor_activate(sensor_info[s].pair_idx, 0);
551 ret = sensor_activate(s, enabled);
552 sensor_activate(sensor_info[s].pair_idx, 1);
556 ret = adjust_counters(s, enabled);
558 /* If the operation was neutral in terms of state, we're done */
562 sensor_info[s].event_count = 0;
563 sensor_info[s].meta_data_pending = 0;
565 if (enabled && (sensor_info[s].quirks & QUIRK_NOISY))
566 /* Initialize filtering data if required */
567 setup_noise_filtering(s);
569 if (!is_poll_sensor) {
572 enable_buffer(dev_num, 0);
573 setup_trigger(s, "\n");
575 /* If there's at least one sensor enabled on this iio device */
576 if (trig_sensors_per_dev[dev_num]) {
579 setup_trigger(s, sensor_info[s].init_trigger_name);
580 enable_buffer(dev_num, 1);
585 * Make sure we have a fd on the character device ; conversely, close
586 * the fd if no one is using associated sensors anymore. The assumption
587 * here is that the underlying driver will power on the relevant
588 * hardware block while someone holds a fd on the device.
590 dev_fd = device_fd[dev_num];
594 stop_acquisition_thread(s);
596 if (dev_fd != -1 && !poll_sensors_per_dev[dev_num] &&
597 !trig_sensors_per_dev[dev_num]) {
599 * Stop watching this fd. This should be a no-op
600 * in case this fd was not in the poll set.
602 epoll_ctl(poll_fd, EPOLL_CTL_DEL, dev_fd, NULL);
605 device_fd[dev_num] = -1;
608 /* Release any filtering data we may have accumulated */
609 release_noise_filtering_data(s);
615 /* First enabled sensor on this iio device */
616 sprintf(device_name, DEV_FILE_PATH, dev_num);
617 dev_fd = open(device_name, O_RDONLY | O_NONBLOCK);
619 device_fd[dev_num] = dev_fd;
622 ALOGE("Could not open fd on %s (%s)\n",
623 device_name, strerror(errno));
624 adjust_counters(s, 0);
628 ALOGV("Opened %s: fd=%d\n", device_name, dev_fd);
630 if (!is_poll_sensor) {
632 /* Add this iio device fd to the set of watched fds */
634 ev.data.u32 = dev_num;
636 ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, dev_fd, &ev);
639 ALOGE( "Failed adding %d to poll set (%s)\n",
640 dev_fd, strerror(errno));
644 /* Note: poll-mode fds are not readable */
648 /* Ensure that on-change sensors send at least one event after enable */
649 sensor_info[s].prev_val = -1;
652 start_acquisition_thread(s);
658 static int is_fast_accelerometer (int s)
661 * Some games don't react well to accelerometers using any-motion
662 * triggers. Even very low thresholds seem to trip them, and they tend
663 * to request fairly high event rates. Favor continuous triggers if the
664 * sensor is an accelerometer and uses a sampling rate of at least 25.
667 if (sensor_info[s].type != SENSOR_TYPE_ACCELEROMETER)
670 if (sensor_info[s].sampling_rate < 25)
677 static void enable_motion_trigger (int dev_num)
680 * In the ideal case, we enumerate two triggers per iio device ; the
681 * default (periodically firing) trigger, and another one (the motion
682 * trigger) that only fires up when motion is detected. This second one
683 * allows for lesser energy consumption, but requires periodic sample
684 * duplication at the HAL level for sensors that Android defines as
685 * continuous. This "duplicate last sample" logic can only be engaged
686 * once we got a first sample for the driver, so we start with the
687 * default trigger when an iio device is first opened, then adjust the
688 * trigger when we got events for all active sensors. Unfortunately in
689 * the general case several sensors can be associated to a given iio
690 * device, they can independently be controlled, and we have to adjust
691 * the trigger in use at the iio device level depending on whether or
692 * not appropriate conditions are met at the sensor level.
697 int active_sensors = trig_sensors_per_dev[dev_num];
698 int candidate[MAX_SENSORS];
699 int candidate_count = 0;
704 /* Check that all active sensors are ready to switch */
706 for (s=0; s<MAX_SENSORS; s++)
707 if (sensor_info[s].dev_num == dev_num &&
708 sensor_info[s].enabled &&
709 sensor_info[s].num_channels &&
710 (!sensor_info[s].motion_trigger_name[0] ||
711 !sensor_info[s].report_initialized ||
712 is_fast_accelerometer(s) ||
713 (sensor_info[s].quirks & QUIRK_FORCE_CONTINUOUS))
717 /* Record which particular sensors need to switch */
719 for (s=0; s<MAX_SENSORS; s++)
720 if (sensor_info[s].dev_num == dev_num &&
721 sensor_info[s].enabled &&
722 sensor_info[s].num_channels &&
723 sensor_info[s].selected_trigger !=
724 sensor_info[s].motion_trigger_name)
725 candidate[candidate_count++] = s;
727 if (!candidate_count)
730 /* Now engage the motion trigger for sensors which aren't using it */
732 enable_buffer(dev_num, 0);
734 for (i=0; i<candidate_count; i++) {
736 setup_trigger(s, sensor_info[s].motion_trigger_name);
739 enable_buffer(dev_num, 1);
742 /* CTS acceptable thresholds:
743 * EventGapVerification.java: (th <= 1.8)
744 * FrequencyVerification.java: (0.9)*(expected freq) => (th <= 1.1111)
746 #define THRESHOLD 1.10
747 #define MAX_DELAY 500000000 /* 500 ms */
748 void set_report_ts(int s, int64_t ts)
750 int64_t maxTs, period;
751 int catalog_index = sensor_info[s].catalog_index;
752 int is_accel = (sensor_catalog[catalog_index].type == SENSOR_TYPE_ACCELEROMETER);
755 * A bit of a hack to please a bunch of cts tests. They
756 * expect the timestamp to be exacly according to the set-up
757 * frequency but if we're simply getting the timestamp at hal level
758 * this may not be the case. Perhaps we'll get rid of this when
759 * we'll be reading the timestamp from the iio channel for all sensors
761 if (sensor_info[s].report_ts && sensor_info[s].sampling_rate &&
762 REPORTING_MODE(sensor_desc[s].flags) == SENSOR_FLAG_CONTINUOUS_MODE)
764 period = (int64_t) (1000000000LL / sensor_info[s].sampling_rate);
765 maxTs = sensor_info[s].report_ts + (is_accel ? 1 : THRESHOLD) * period;
766 /* If we're too far behind get back on track */
767 if (ts - maxTs >= MAX_DELAY)
769 sensor_info[s].report_ts = (ts < maxTs ? ts : maxTs);
771 sensor_info[s].report_ts = ts;
775 static int integrate_device_report (int dev_num)
779 unsigned char buf[MAX_SENSOR_REPORT_SIZE] = { 0 };
781 unsigned char *target;
782 unsigned char *source;
785 /* There's an incoming report on the specified iio device char dev fd */
787 if (dev_num < 0 || dev_num >= MAX_DEVICES) {
788 ALOGE("Event reported on unexpected iio device %d\n", dev_num);
792 if (device_fd[dev_num] == -1) {
793 ALOGE("Ignoring stale report on iio device %d\n", dev_num);
799 len = read(device_fd[dev_num], buf, MAX_SENSOR_REPORT_SIZE);
802 ALOGE("Could not read report from iio device %d (%s)\n",
803 dev_num, strerror(errno));
807 ALOGV("Read %d bytes from iio device %d\n", len, dev_num);
809 /* Map device report to sensor reports */
811 for (s=0; s<MAX_SENSORS; s++)
812 if (sensor_info[s].dev_num == dev_num &&
813 sensor_info[s].enabled) {
817 /* Copy data from device to sensor report buffer */
818 for (c=0; c<sensor_info[s].num_channels; c++) {
820 target = sensor_info[s].report_buffer +
823 source = buf + sensor_info[s].channel[c].offset;
825 size = sensor_info[s].channel[c].size;
827 memcpy(target, source, size);
832 ALOGV("Sensor %d report available (%d bytes)\n", s,
835 set_report_ts(s, get_timestamp());
836 sensor_info[s].report_pending = DATA_TRIGGER;
837 sensor_info[s].report_initialized = 1;
840 /* Tentatively switch to an any-motion trigger if conditions are met */
841 enable_motion_trigger(dev_num);
847 static int propagate_sensor_report (int s, struct sensors_event_t *data)
849 /* There's a sensor report pending for this sensor ; transmit it */
851 int num_fields = get_field_count(s);
853 unsigned char* current_sample;
855 /* If there's nothing to return... we're done */
860 /* Only return uncalibrated event if also gyro active */
861 if (sensor_info[s].type == SENSOR_TYPE_GYROSCOPE_UNCALIBRATED &&
862 sensor_info[sensor_info[s].pair_idx].enabled != 0)
865 memset(data, 0, sizeof(sensors_event_t));
867 data->version = sizeof(sensors_event_t);
869 data->type = sensor_info[s].type;
870 data->timestamp = sensor_info[s].report_ts;
872 ALOGV("Sample on sensor %d (type %d):\n", s, sensor_info[s].type);
874 current_sample = sensor_info[s].report_buffer;
876 /* If this is a poll sensor */
877 if (!sensor_info[s].num_channels) {
878 /* Use the data provided by the acquisition thread */
879 ALOGV("Reporting data from worker thread for S%d\n", s);
880 memcpy(data->data, current_sample, num_fields * sizeof(float));
884 /* Convert the data into the expected Android-level format */
885 for (c=0; c<num_fields; c++) {
887 data->data[c] = sensor_info[s].ops.transform
888 (s, c, current_sample);
890 ALOGV("\tfield %d: %f\n", c, data->data[c]);
891 current_sample += sensor_info[s].channel[c].size;
895 * The finalize routine, in addition to its late sample processing duty,
896 * has the final say on whether or not the sample gets sent to Android.
898 return sensor_info[s].ops.finalize(s, data);
902 static void synthetize_duplicate_samples (void)
905 * Some sensor types (ex: gyroscope) are defined as continuously firing
906 * by Android, despite the fact that we can be dealing with iio drivers
907 * that only report events for new samples. For these we generate
908 * reports periodically, duplicating the last data we got from the
909 * driver. This is not necessary for polling sensors.
917 for (s=0; s<sensor_count; s++) {
919 /* Ignore disabled sensors */
920 if (!sensor_info[s].enabled)
923 /* If the sensor is continuously firing, leave it alone */
924 if (sensor_info[s].selected_trigger !=
925 sensor_info[s].motion_trigger_name)
928 /* If we haven't seen a sample, there's nothing to duplicate */
929 if (!sensor_info[s].report_initialized)
932 /* If a sample was recently buffered, leave it alone too */
933 if (sensor_info[s].report_pending)
936 /* We also need a valid sampling rate to be configured */
937 if (!sensor_info[s].sampling_rate)
940 period = (int64_t) (1000000000.0/ sensor_info[s].sampling_rate);
942 current_ts = get_timestamp();
943 target_ts = sensor_info[s].report_ts + period;
945 if (target_ts <= current_ts) {
946 /* Mark the sensor for event generation */
947 set_report_ts(s, current_ts);
948 sensor_info[s].report_pending = DATA_DUPLICATE;
954 static void integrate_thread_report (uint32_t tag)
956 int s = tag - THREAD_REPORT_TAG_BASE;
960 expected_len = get_field_count(s) * sizeof(float);
962 len = read(sensor_info[s].thread_data_fd[0],
963 sensor_info[s].report_buffer,
966 if (len == expected_len) {
967 set_report_ts(s, get_timestamp());
968 sensor_info[s].report_pending = DATA_SYSFS;
973 static int get_poll_wait_timeout (void)
976 * Compute an appropriate timeout value, in ms, for the epoll_wait
977 * call that's going to await for iio device reports and incoming
978 * reports from our sensor sysfs data reader threads.
982 int64_t target_ts = INT64_MAX;
987 * Check if we're dealing with a driver that only send events when
988 * there is motion, despite the fact that the associated Android sensor
989 * type is continuous rather than on-change. In that case we have to
990 * duplicate events. Check deadline for the nearest upcoming event.
992 for (s=0; s<sensor_count; s++)
993 if (sensor_info[s].enabled &&
994 sensor_info[s].selected_trigger ==
995 sensor_info[s].motion_trigger_name &&
996 sensor_info[s].sampling_rate) {
997 period = (int64_t) (1000000000.0 /
998 sensor_info[s].sampling_rate);
1000 if (sensor_info[s].report_ts + period < target_ts)
1001 target_ts = sensor_info[s].report_ts + period;
1004 /* If we don't have such a driver to deal with */
1005 if (target_ts == INT64_MAX)
1006 return -1; /* Infinite wait */
1008 ms_to_wait = (target_ts - get_timestamp()) / 1000000;
1010 /* If the target timestamp is already behind us, don't wait */
1018 int sensor_poll(struct sensors_event_t* data, int count)
1023 struct epoll_event ev[MAX_DEVICES];
1024 int returned_events;
1028 /* Get one or more events from our collection of sensors */
1030 return_available_sensor_reports:
1032 /* Synthetize duplicate samples if needed */
1033 synthetize_duplicate_samples();
1035 returned_events = 0;
1037 /* Check our sensor collection for available reports */
1038 for (s=0; s<sensor_count && returned_events < count; s++) {
1039 if (sensor_info[s].report_pending) {
1042 /* Report this event if it looks OK */
1043 event_count = propagate_sensor_report(s, &data[returned_events]);
1046 sensor_info[s].report_pending = 0;
1048 /* Duplicate only if both cal & uncal are active */
1049 if (sensor_info[s].type == SENSOR_TYPE_GYROSCOPE &&
1050 sensor_info[s].pair_idx && sensor_info[sensor_info[s].pair_idx].enabled != 0) {
1051 struct gyro_cal* gyro_data = (struct gyro_cal*) sensor_info[s].cal_data;
1053 memcpy(&data[returned_events + event_count], &data[returned_events],
1054 sizeof(struct sensors_event_t) * event_count);
1056 uncal_start = returned_events + event_count;
1057 for (i = 0; i < event_count; i++) {
1058 data[uncal_start + i].type = SENSOR_TYPE_GYROSCOPE_UNCALIBRATED;
1059 data[uncal_start + i].sensor = sensor_info[s].pair_idx;
1061 data[uncal_start + i].data[0] = data[returned_events + i].data[0] + gyro_data->bias_x;
1062 data[uncal_start + i].data[1] = data[returned_events + i].data[1] + gyro_data->bias_y;
1063 data[uncal_start + i].data[2] = data[returned_events + i].data[2] + gyro_data->bias_z;
1065 data[uncal_start + i].uncalibrated_gyro.bias[0] = gyro_data->bias_x;
1066 data[uncal_start + i].uncalibrated_gyro.bias[1] = gyro_data->bias_y;
1067 data[uncal_start + i].uncalibrated_gyro.bias[2] = gyro_data->bias_z;
1071 sensor_info[sensor_info[s].pair_idx].report_pending = 0;
1072 returned_events += event_count;
1074 * If the sample was deemed invalid or unreportable,
1075 * e.g. had the same value as the previously reported
1076 * value for a 'on change' sensor, silently drop it.
1079 while (sensor_info[s].meta_data_pending) {
1080 /* See sensors.h on these */
1081 data[returned_events].version = META_DATA_VERSION;
1082 data[returned_events].sensor = 0;
1083 data[returned_events].type = SENSOR_TYPE_META_DATA;
1084 data[returned_events].reserved0 = 0;
1085 data[returned_events].timestamp = 0;
1086 data[returned_events].meta_data.sensor = s;
1087 data[returned_events].meta_data.what = META_DATA_FLUSH_COMPLETE;
1089 sensor_info[s].meta_data_pending--;
1092 if (returned_events)
1093 return returned_events;
1097 ALOGV("Awaiting sensor data\n");
1099 nfds = epoll_wait(poll_fd, ev, MAX_DEVICES, get_poll_wait_timeout());
1102 ALOGE("epoll_wait returned -1 (%s)\n", strerror(errno));
1106 ALOGV("%d fds signalled\n", nfds);
1108 /* For each of the signalled sources */
1109 for (i=0; i<nfds; i++)
1110 if (ev[i].events == EPOLLIN)
1111 switch (ev[i].data.u32) {
1112 case 0 ... MAX_DEVICES-1:
1113 /* Read report from iio char dev fd */
1114 integrate_device_report(ev[i].data.u32);
1117 case THREAD_REPORT_TAG_BASE ...
1118 THREAD_REPORT_TAG_BASE + MAX_SENSORS-1:
1119 /* Get report from acquisition thread */
1120 integrate_thread_report(ev[i].data.u32);
1124 ALOGW("Unexpected event source!\n");
1128 goto return_available_sensor_reports;
1132 static void tentative_switch_trigger (int s)
1135 * Under certain situations it may be beneficial to use an alternate
1138 * - for applications using the accelerometer with high sampling rates,
1139 * prefer the continuous trigger over the any-motion one, to avoid
1140 * jumps related to motion thresholds
1143 if (is_fast_accelerometer(s) &&
1144 !(sensor_info[s].quirks & QUIRK_TERSE_DRIVER) &&
1145 sensor_info[s].selected_trigger ==
1146 sensor_info[s].motion_trigger_name)
1147 setup_trigger(s, sensor_info[s].init_trigger_name);
1151 int sensor_set_delay(int s, int64_t ns)
1153 /* Set the rate at which a specific sensor should report events */
1155 /* See Android sensors.h for indication on sensor trigger modes */
1157 char sysfs_path[PATH_MAX];
1158 char avail_sysfs_path[PATH_MAX];
1159 int dev_num = sensor_info[s].dev_num;
1160 int i = sensor_info[s].catalog_index;
1161 const char *prefix = sensor_catalog[i].tag;
1162 float new_sampling_rate; /* Granted sampling rate after arbitration */
1163 float cur_sampling_rate; /* Currently used sampling rate */
1164 int per_sensor_sampling_rate;
1165 int per_device_sampling_rate;
1166 int32_t min_delay_us = sensor_desc[s].minDelay;
1167 max_delay_t max_delay_us = sensor_desc[s].maxDelay;
1168 float min_supported_rate = max_delay_us ? (1000000.0f / max_delay_us) : 1;
1169 float max_supported_rate =
1170 (min_delay_us && min_delay_us != -1) ? (1000000.0f / min_delay_us) : 0;
1171 char freqs_buf[100];
1177 ALOGE("Rejecting non-positive delay request on sensor %d, required delay: %lld\n", s, ns);
1181 new_sampling_rate = 1000000000LL/ns;
1183 ALOGV("Entering set delay S%d (%s): old rate(%f), new rate(%f)\n",
1184 s, sensor_info[s].friendly_name, sensor_info[s].sampling_rate,
1188 * Artificially limit ourselves to 1 Hz or higher. This is mostly to
1189 * avoid setting up the stage for divisions by zero.
1191 if (new_sampling_rate < min_supported_rate)
1192 new_sampling_rate = min_supported_rate;
1194 if (max_supported_rate &&
1195 new_sampling_rate > max_supported_rate) {
1196 new_sampling_rate = max_supported_rate;
1199 sensor_info[s].sampling_rate = new_sampling_rate;
1201 /* If we're dealing with a poll-mode sensor */
1202 if (!sensor_info[s].num_channels) {
1203 /* Interrupt current sleep so the new sampling gets used */
1204 pthread_cond_signal(&thread_release_cond[s]);
1208 sprintf(sysfs_path, SENSOR_SAMPLING_PATH, dev_num, prefix);
1210 if (sysfs_read_float(sysfs_path, &cur_sampling_rate) != -1) {
1211 per_sensor_sampling_rate = 1;
1212 per_device_sampling_rate = 0;
1214 per_sensor_sampling_rate = 0;
1216 sprintf(sysfs_path, DEVICE_SAMPLING_PATH, dev_num);
1218 if (sysfs_read_float(sysfs_path, &cur_sampling_rate) != -1)
1219 per_device_sampling_rate = 1;
1221 per_device_sampling_rate = 0;
1224 if (!per_sensor_sampling_rate && !per_device_sampling_rate) {
1225 ALOGE("No way to adjust sampling rate on sensor %d\n", s);
1229 /* Coordinate with others active sensors on the same device, if any */
1230 if (per_device_sampling_rate)
1231 for (n=0; n<sensor_count; n++)
1232 if (n != s && sensor_info[n].dev_num == dev_num &&
1233 sensor_info[n].num_channels &&
1234 sensor_info[n].enabled &&
1235 sensor_info[n].sampling_rate > new_sampling_rate)
1236 new_sampling_rate= sensor_info[n].sampling_rate;
1238 /* Check if we have contraints on allowed sampling rates */
1240 sprintf(avail_sysfs_path, DEVICE_AVAIL_FREQ_PATH, dev_num);
1242 if (sysfs_read_str(avail_sysfs_path, freqs_buf, sizeof(freqs_buf)) > 0){
1245 /* Decode allowed sampling rates string, ex: "10 20 50 100" */
1247 /* While we're not at the end of the string */
1248 while (*cursor && cursor[0]) {
1250 /* Decode a single value */
1251 sr = strtod(cursor, NULL);
1253 /* If this matches the selected rate, we're happy */
1254 if (new_sampling_rate == sr)
1258 * If we reached a higher value than the desired rate,
1259 * adjust selected rate so it matches the first higher
1260 * available one and stop parsing - this makes the
1261 * assumption that rates are sorted by increasing value
1262 * in the allowed frequencies string.
1264 if (sr > new_sampling_rate) {
1265 new_sampling_rate = sr;
1270 while (cursor[0] && !isspace(cursor[0]))
1274 while (cursor[0] && isspace(cursor[0]))
1279 if (max_supported_rate &&
1280 new_sampling_rate > max_supported_rate) {
1281 new_sampling_rate = max_supported_rate;
1284 /* If the desired rate is already active we're all set */
1285 if (new_sampling_rate == cur_sampling_rate)
1288 ALOGI("Sensor %d sampling rate set to %g\n", s, new_sampling_rate);
1290 if (trig_sensors_per_dev[dev_num])
1291 enable_buffer(dev_num, 0);
1293 sysfs_write_float(sysfs_path, new_sampling_rate);
1295 /* Check if it makes sense to use an alternate trigger */
1296 tentative_switch_trigger(s);
1298 if (trig_sensors_per_dev[dev_num])
1299 enable_buffer(dev_num, 1);
1304 int sensor_flush (int s)
1306 /* If one shot or not enabled return -EINVAL */
1307 if (sensor_desc[s].flags & SENSOR_FLAG_ONE_SHOT_MODE ||
1308 sensor_info[s].enabled == 0)
1311 sensor_info[s].meta_data_pending++;
1315 int allocate_control_data (void)
1319 for (i=0; i<MAX_DEVICES; i++)
1322 poll_fd = epoll_create(MAX_DEVICES);
1324 if (poll_fd == -1) {
1325 ALOGE("Can't create epoll instance for iio sensors!\n");
1333 void delete_control_data (void)