2 * Copyright (C) 2014 Intel Corporation.
10 #include <sys/socket.h>
11 #include <utils/Log.h>
12 #include <hardware/sensors.h>
14 #include "enumeration.h"
16 #include "transform.h"
17 #include "calibration.h"
19 /* Currently active sensors count, per device */
20 static int poll_sensors_per_dev[MAX_DEVICES]; /* poll-mode sensors */
21 static int trig_sensors_per_dev[MAX_DEVICES]; /* trigger, event based */
23 static int device_fd[MAX_DEVICES]; /* fd on the /dev/iio:deviceX file */
25 static int poll_fd; /* epoll instance covering all enabled sensors */
27 static int active_poll_sensors; /* Number of enabled poll-mode sensors */
30 * We associate tags to each of our poll set entries. These tags have the
32 * - a iio device number if the fd is a iio character device fd
33 * - THREAD_REPORT_TAG_BASE + sensor handle if the fd is the receiving end of a
34 * pipe used by a sysfs data acquisition thread
36 #define THREAD_REPORT_TAG_BASE 0x00010000
39 static int enable_buffer(int dev_num, int enabled)
41 char sysfs_path[PATH_MAX];
43 sprintf(sysfs_path, ENABLE_PATH, dev_num);
45 /* Low level, non-multiplexed, enable/disable routine */
46 return sysfs_write_int(sysfs_path, enabled);
50 static int setup_trigger(int dev_num, const char* trigger_val)
52 char sysfs_path[PATH_MAX];
54 sprintf(sysfs_path, TRIGGER_PATH, dev_num);
56 return sysfs_write_str(sysfs_path, trigger_val);
60 void build_sensor_report_maps(int dev_num)
63 * Read sysfs files from a iio device's scan_element directory, and
64 * build a couple of tables from that data. These tables will tell, for
65 * each sensor, where to gather relevant data in a device report, i.e.
66 * the structure that we read from the /dev/iio:deviceX file in order to
67 * sensor report, itself being the data that we return to Android when a
68 * sensor poll completes. The mapping should be straightforward in the
69 * case where we have a single sensor active per iio device but, this is
70 * not the general case. In general several sensors can be handled
71 * through a single iio device, and the _en, _index and _type syfs
72 * entries all concur to paint a picture of what the structure of the
82 char spec_buf[MAX_TYPE_SPEC_LEN];
83 struct datum_info_t* ch_info;
85 char sysfs_path[PATH_MAX];
88 int channel_size_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
89 int sensor_handle_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
90 int channel_number_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
94 /* For each sensor that is linked to this device */
95 for (s=0; s<sensor_count; s++) {
96 if (sensor_info[s].dev_num != dev_num)
99 i = sensor_info[s].catalog_index;
101 /* Read channel details through sysfs attributes */
102 for (c=0; c<sensor_info[s].num_channels; c++) {
104 /* Read _type file */
105 sprintf(sysfs_path, CHANNEL_PATH "%s",
106 sensor_info[s].dev_num,
107 sensor_catalog[i].channel[c].type_path);
109 n = sysfs_read_str(sysfs_path, spec_buf,
113 ALOGW( "Failed to read type: %s\n",
118 ch_spec = sensor_info[s].channel[c].type_spec;
120 memcpy(ch_spec, spec_buf, sizeof(spec_buf));
122 ch_info = &sensor_info[s].channel[c].type_info;
124 size = decode_type_spec(ch_spec, ch_info);
126 /* Read _index file */
127 sprintf(sysfs_path, CHANNEL_PATH "%s",
128 sensor_info[s].dev_num,
129 sensor_catalog[i].channel[c].index_path);
131 n = sysfs_read_int(sysfs_path, &ch_index);
134 ALOGW( "Failed to read index: %s\n",
139 if (ch_index >= MAX_SENSORS) {
140 ALOGE("Index out of bounds!: %s\n", sysfs_path);
144 /* Record what this index is about */
146 sensor_handle_from_index [ch_index] = s;
147 channel_number_from_index[ch_index] = c;
148 channel_size_from_index [ch_index] = size;
153 /* Stop sampling - if we are recovering from hal restart */
154 enable_buffer(dev_num, 0);
155 setup_trigger(dev_num, "\n");
157 /* Turn on channels we're aware of */
158 for (c=0;c<sensor_info[s].num_channels; c++) {
159 sprintf(sysfs_path, CHANNEL_PATH "%s",
160 sensor_info[s].dev_num,
161 sensor_catalog[i].channel[c].en_path);
162 sysfs_write_int(sysfs_path, 1);
166 ALOGI("Found %d channels on iio device %d\n", known_channels, dev_num);
169 * Now that we know which channels are defined, their sizes and their
170 * ordering, update channels offsets within device report. Note: there
171 * is a possibility that several sensors share the same index, with
172 * their data fields being isolated by masking and shifting as specified
173 * through the real bits and shift values in type attributes. This case
174 * is not currently supported. Also, the code below assumes no hole in
175 * the sequence of indices, so it is dependent on discovery of all
179 for (i=0; i<MAX_SENSORS * MAX_CHANNELS; i++) {
180 s = sensor_handle_from_index[i];
181 c = channel_number_from_index[i];
182 size = channel_size_from_index[i];
187 ALOGI("S%d C%d : offset %d, size %d, type %s\n",
188 s, c, offset, size, sensor_info[s].channel[c].type_spec);
190 sensor_info[s].channel[c].offset = offset;
191 sensor_info[s].channel[c].size = size;
198 int adjust_counters (int s, int enabled)
201 * Adjust counters based on sensor enable action. Return values are:
202 * -1 if there's an inconsistency: abort action in this case
203 * 0 if the operation was completed and we're all set
204 * 1 if we toggled the state of the sensor and there's work left
207 int dev_num = sensor_info[s].dev_num;
208 int catalog_index = sensor_info[s].catalog_index;
209 int sensor_type = sensor_catalog[catalog_index].type;
211 /* Refcount per sensor, in terms of enable count */
213 ALOGI("Enabling sensor %d (iio device %d: %s)\n",
214 s, dev_num, sensor_info[s].friendly_name);
216 sensor_info[s].enable_count++;
218 if (sensor_info[s].enable_count > 1)
219 return 0; /* The sensor was, and remains, in use */
221 switch (sensor_type) {
222 case SENSOR_TYPE_MAGNETIC_FIELD:
223 compass_read_data(&sensor_info[s]);
226 case SENSOR_TYPE_GYROSCOPE:
227 gyro_cal_init(&sensor_info[s]);
231 if (sensor_info[s].enable_count == 0)
232 return -1; /* Spurious disable call */
234 ALOGI("Disabling sensor %d (iio device %d: %s)\n", s, dev_num,
235 sensor_info[s].friendly_name);
237 sensor_info[s].enable_count--;
239 if (sensor_info[s].enable_count > 0)
240 return 0; /* The sensor was, and remains, in use */
242 /* Sensor disabled, lower report available flag */
243 sensor_info[s].report_pending = 0;
245 if (sensor_type == SENSOR_TYPE_MAGNETIC_FIELD)
246 compass_store_data(&sensor_info[s]);
249 /* We changed the state of a sensor - adjust per iio device counters */
251 /* If this is a regular event-driven sensor */
252 if (sensor_info[s].num_channels) {
255 trig_sensors_per_dev[dev_num]++;
257 trig_sensors_per_dev[dev_num]--;
263 active_poll_sensors++;
264 poll_sensors_per_dev[dev_num]++;
268 active_poll_sensors--;
269 poll_sensors_per_dev[dev_num]--;
274 static int get_field_count (int s)
276 int catalog_index = sensor_info[s].catalog_index;
277 int sensor_type = sensor_catalog[catalog_index].type;
279 switch (sensor_type) {
280 case SENSOR_TYPE_ACCELEROMETER: /* m/s^2 */
281 case SENSOR_TYPE_MAGNETIC_FIELD: /* micro-tesla */
282 case SENSOR_TYPE_ORIENTATION: /* degrees */
283 case SENSOR_TYPE_GYROSCOPE: /* radians/s */
286 case SENSOR_TYPE_LIGHT: /* SI lux units */
287 case SENSOR_TYPE_AMBIENT_TEMPERATURE: /* °C */
288 case SENSOR_TYPE_TEMPERATURE: /* °C */
289 case SENSOR_TYPE_PROXIMITY: /* centimeters */
290 case SENSOR_TYPE_PRESSURE: /* hecto-pascal */
291 case SENSOR_TYPE_RELATIVE_HUMIDITY: /* percent */
294 case SENSOR_TYPE_ROTATION_VECTOR:
298 ALOGE("Unknown sensor type!\n");
299 return 0; /* Drop sample */
304 /* Check and honor termination requests */
305 #define CHECK_CANCEL(s) \
306 if (sensor_info[s].thread_data_fd[1] == -1) { \
307 ALOGV("Acquisition thread for S%d exiting\n", s); \
312 static void* acquisition_routine (void* param)
315 * Data acquisition routine run in a dedicated thread, covering a single
316 * sensor. This loop will periodically retrieve sampling data through
317 * sysfs, then package it as a sample and transfer it to our master poll
318 * loop through a report fd. Checks for a cancellation signal quite
319 * frequently, as the thread may be disposed of at any time. Note that
320 * Bionic does not provide pthread_cancel / pthread_testcancel...
328 struct sensors_event_t data = {0};
334 ALOGV("Entering data acquisition thread for sensor %d\n", s);
336 if (s < 0 || s >= sensor_count) {
337 ALOGE("Invalid sensor handle!\n");
341 if (!sensor_info[s].sampling_rate) {
342 ALOGE("Zero rate in acquisition routine for sensor %d\n", s);
346 num_fields = get_field_count(s);
351 /* Pinpoint the moment we start sampling */
352 entry_ts = get_timestamp();
354 ALOGV("Acquiring sample data for sensor %d through sysfs\n", s);
356 /* Read values through sysfs */
357 for (c=0; c<num_fields; c++) {
358 data.data[c] = acquire_immediate_value(s, c);
360 ALOGV("\tfield %d: %f\n", c, data.data[c]);
364 /* If the sample looks good */
365 if (sensor_info[s].ops.finalize(s, &data)) {
367 /* Pipe it for transmission to poll loop */
368 ret = write( sensor_info[s].thread_data_fd[1],
370 num_fields * sizeof(float));
375 /* Sleep a little, deducting read & write times */
376 elapsed = (get_timestamp() - entry_ts) / 1000;
379 (1000000000LL / sensor_info[s].sampling_rate / 1000);
381 if (period > elapsed)
382 usleep(period - elapsed);
389 static void start_acquisition_thread (int s)
391 int incoming_data_fd;
394 struct epoll_event ev = {0};
396 ALOGV("Initializing acquisition context for sensor %d\n", s);
398 /* Create a pipe for inter thread communication */
399 ret = pipe(sensor_info[s].thread_data_fd);
401 incoming_data_fd = sensor_info[s].thread_data_fd[0];
404 ev.data.u32 = THREAD_REPORT_TAG_BASE + s;
406 /* Add incoming side of pipe to our poll set, with a suitable tag */
407 ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, incoming_data_fd , &ev);
409 /* Create and start worker thread */
410 ret = pthread_create( &sensor_info[s].acquisition_thread,
417 static void stop_acquisition_thread (int s)
419 int incoming_data_fd = sensor_info[s].thread_data_fd[0];
420 int outgoing_data_fd = sensor_info[s].thread_data_fd[1];
422 ALOGV("Tearing down acquisition context for sensor %d\n", s);
424 /* Delete the incoming side of the pipe from our poll set */
425 epoll_ctl(poll_fd, EPOLL_CTL_DEL, incoming_data_fd, NULL);
427 /* Mark the pipe ends as invalid ; that's a cheap exit signal */
428 sensor_info[s].thread_data_fd[0] = -1;
429 sensor_info[s].thread_data_fd[1] = -1;
431 /* Close both sides of our pipe */
432 close(incoming_data_fd);
433 close(outgoing_data_fd);
435 /* Wait end of thread, and clean up thread handle */
436 pthread_join(sensor_info[s].acquisition_thread, NULL);
438 /* Clean up our sensor descriptor */
439 sensor_info[s].acquisition_thread = -1;
443 int sensor_activate(int s, int enabled)
445 char device_name[PATH_MAX];
446 char trigger_name[MAX_NAME_SIZE + 16];
448 struct epoll_event ev = {0};
451 int dev_num = sensor_info[s].dev_num;
452 int i = sensor_info[s].catalog_index;
453 int is_poll_sensor = !sensor_info[s].num_channels;
455 ret = adjust_counters(s, enabled);
457 /* If the operation was neutral in terms of state, we're done */
461 if (!is_poll_sensor) {
464 enable_buffer(dev_num, 0);
465 setup_trigger(dev_num, "\n");
467 /* If there's at least one sensor enabled on this iio device */
468 if (trig_sensors_per_dev[dev_num]) {
469 sprintf(trigger_name, "%s-dev%d",
470 sensor_info[s].internal_name, dev_num);
473 setup_trigger(dev_num, trigger_name);
474 enable_buffer(dev_num, 1);
479 * Make sure we have a fd on the character device ; conversely, close
480 * the fd if no one is using associated sensors anymore. The assumption
481 * here is that the underlying driver will power on the relevant
482 * hardware block while someone holds a fd on the device.
484 dev_fd = device_fd[dev_num];
488 stop_acquisition_thread(s);
490 if (dev_fd != -1 && !poll_sensors_per_dev[dev_num] &&
491 !trig_sensors_per_dev[dev_num]) {
493 * Stop watching this fd. This should be a no-op
494 * in case this fd was not in the poll set.
496 epoll_ctl(poll_fd, EPOLL_CTL_DEL, dev_fd, NULL);
499 device_fd[dev_num] = -1;
505 /* First enabled sensor on this iio device */
506 sprintf(device_name, DEV_FILE_PATH, dev_num);
507 dev_fd = open(device_name, O_RDONLY | O_NONBLOCK);
509 device_fd[dev_num] = dev_fd;
512 ALOGE("Could not open fd on %s (%s)\n",
513 device_name, strerror(errno));
514 adjust_counters(s, 0);
518 ALOGV("Opened %s: fd=%d\n", device_name, dev_fd);
521 start_acquisition_thread(s);
524 /* Add this iio device fd to the set of watched fds */
526 ev.data.u32 = dev_num;
528 ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, dev_fd, &ev);
531 ALOGE( "Failed adding %d to poll set (%s)\n",
532 dev_fd, strerror(errno));
536 /* Note: poll-mode fds are not readable */
544 static int integrate_device_report(int dev_num)
548 unsigned char buf[MAX_SENSOR_REPORT_SIZE] = { 0 };
550 unsigned char *target;
551 unsigned char *source;
555 /* There's an incoming report on the specified iio device char dev fd */
557 if (dev_num < 0 || dev_num >= MAX_DEVICES) {
558 ALOGE("Event reported on unexpected iio device %d\n", dev_num);
562 if (device_fd[dev_num] == -1) {
563 ALOGE("Ignoring stale report on iio device %d\n", dev_num);
567 ts = get_timestamp();
569 len = read(device_fd[dev_num], buf, MAX_SENSOR_REPORT_SIZE);
572 ALOGE("Could not read report from iio device %d (%s)\n",
573 dev_num, strerror(errno));
577 ALOGV("Read %d bytes from iio device %d\n", len, dev_num);
579 for (s=0; s<MAX_SENSORS; s++)
580 if (sensor_info[s].dev_num == dev_num &&
581 sensor_info[s].enable_count) {
585 /* Copy data from device to sensor report buffer */
586 for (c=0; c<sensor_info[s].num_channels; c++) {
588 target = sensor_info[s].report_buffer +
591 source = buf + sensor_info[s].channel[c].offset;
593 size = sensor_info[s].channel[c].size;
595 memcpy(target, source, size);
600 ALOGV("Sensor %d report available (%d bytes)\n", s,
603 sensor_info[s].report_ts = ts;
604 sensor_info[s].report_pending = 1;
611 static int propagate_sensor_report(int s, struct sensors_event_t *data)
613 /* There's a sensor report pending for this sensor ; transmit it */
615 int catalog_index = sensor_info[s].catalog_index;
616 int sensor_type = sensor_catalog[catalog_index].type;
617 int num_fields = get_field_count(s);
619 unsigned char* current_sample;
621 /* If there's nothing to return... we're done */
625 memset(data, 0, sizeof(sensors_event_t));
627 data->version = sizeof(sensors_event_t);
629 data->type = sensor_type;
630 data->timestamp = sensor_info[s].report_ts;
632 ALOGV("Sample on sensor %d (type %d):\n", s, sensor_type);
634 current_sample = sensor_info[s].report_buffer;
636 /* If this is a poll sensor */
637 if (!sensor_info[s].num_channels) {
638 /* Use the data provided by the acquisition thread */
639 ALOGV("Reporting data from worker thread for S%d\n", s);
640 memcpy(data->data, current_sample, num_fields * sizeof(float));
644 /* Convert the data into the expected Android-level format */
645 for (c=0; c<num_fields; c++) {
647 data->data[c] = sensor_info[s].ops.transform
648 (s, c, current_sample);
650 ALOGV("\tfield %d: %f\n", c, data->data[c]);
651 current_sample += sensor_info[s].channel[c].size;
655 * The finalize routine, in addition to its late sample processing duty,
656 * has the final say on whether or not the sample gets sent to Android.
658 return sensor_info[s].ops.finalize(s, data);
662 static void integrate_thread_report (uint32_t tag)
664 int s = tag - THREAD_REPORT_TAG_BASE;
668 expected_len = get_field_count(s) * sizeof(float);
670 len = read(sensor_info[s].thread_data_fd[0],
671 sensor_info[s].report_buffer,
674 if (len == expected_len) {
675 sensor_info[s].report_ts = get_timestamp();
676 sensor_info[s].report_pending = 1;
681 int sensor_poll(struct sensors_event_t* data, int count)
686 struct epoll_event ev[MAX_DEVICES];
690 /* Get one or more events from our collection of sensors */
692 return_available_sensor_reports:
696 /* Check our sensor collection for available reports */
697 for (s=0; s<sensor_count && returned_events<count; s++)
698 if (sensor_info[s].report_pending) {
701 sensor_info[s].report_pending = 0;
703 /* Report this event if it looks OK */
705 propagate_sensor_report(s, &data[returned_events]);
708 * If the sample was deemed invalid or unreportable,
709 * e.g. had the same value as the previously reported
710 * value for a 'on change' sensor, silently drop it.
715 return returned_events;
719 ALOGV("Awaiting sensor data\n");
721 nfds = epoll_wait(poll_fd, ev, MAX_DEVICES, -1);
724 ALOGI("epoll_wait returned -1 (%s)\n", strerror(errno));
728 ALOGV("%d fds signalled\n", nfds);
730 /* For each of the signalled sources */
731 for (i=0; i<nfds; i++)
732 if (ev[i].events == EPOLLIN)
733 switch (ev[i].data.u32) {
734 case 0 ... MAX_DEVICES-1:
735 /* Read report from iio char dev fd */
736 integrate_device_report(ev[i].data.u32);
739 case THREAD_REPORT_TAG_BASE ...
740 THREAD_REPORT_TAG_BASE + MAX_SENSORS-1:
741 /* Get report from acquisition thread */
742 integrate_thread_report(ev[i].data.u32);
746 ALOGW("Unexpected event source!\n");
750 goto return_available_sensor_reports;
754 int sensor_set_delay(int s, int64_t ns)
756 /* Set the rate at which a specific sensor should report events */
758 /* See Android sensors.h for indication on sensor trigger modes */
760 char sysfs_path[PATH_MAX];
761 char avail_sysfs_path[PATH_MAX];
762 int dev_num = sensor_info[s].dev_num;
763 int i = sensor_info[s].catalog_index;
764 const char *prefix = sensor_catalog[i].tag;
765 float new_sampling_rate; /* Granted sampling rate after arbitration */
766 float cur_sampling_rate; /* Currently used sampling rate */
767 float req_sampling_rate; /* Requested ; may be different from granted */
768 int per_sensor_sampling_rate;
769 int per_device_sampling_rate;
770 int max_supported_rate = 0;
777 ALOGE("Rejecting zero delay request on sensor %d\n", s);
781 new_sampling_rate = req_sampling_rate = 1000000000L/ns;
783 if (new_sampling_rate < 1) {
784 ALOGI("Sub-HZ sampling rate requested on on sensor %d\n", s);
785 new_sampling_rate = 1;
788 sensor_info[s].sampling_rate = new_sampling_rate;
790 /* If we're dealing with a poll-mode sensor */
791 if (!sensor_info[s].num_channels) {
792 /* The new sampling rate will be used on next iteration */
796 sprintf(sysfs_path, SENSOR_SAMPLING_PATH, dev_num, prefix);
798 if (sysfs_read_float(sysfs_path, &cur_sampling_rate) != -1) {
799 per_sensor_sampling_rate = 1;
800 per_device_sampling_rate = 0;
802 per_sensor_sampling_rate = 0;
804 sprintf(sysfs_path, DEVICE_SAMPLING_PATH, dev_num);
806 if (sysfs_read_float(sysfs_path, &cur_sampling_rate) != -1)
807 per_device_sampling_rate = 1;
809 per_device_sampling_rate = 0;
812 if (!per_sensor_sampling_rate && !per_device_sampling_rate) {
813 ALOGE("No way to adjust sampling rate on sensor %d\n", s);
817 /* Coordinate with others active sensors on the same device, if any */
818 if (per_device_sampling_rate)
819 for (n=0; n<sensor_count; n++)
820 if (n != s && sensor_info[n].dev_num == dev_num &&
821 sensor_info[n].num_channels &&
822 sensor_info[n].enable_count &&
823 sensor_info[n].sampling_rate > new_sampling_rate)
824 new_sampling_rate= sensor_info[n].sampling_rate;
826 /* Check if we have contraints on allowed sampling rates */
828 sprintf(avail_sysfs_path, DEVICE_AVAIL_FREQ_PATH, dev_num);
830 if (sysfs_read_str(avail_sysfs_path, freqs_buf, sizeof(freqs_buf)) > 0){
833 /* Decode allowed sampling rates string, ex: "10 20 50 100" */
835 /* While we're not at the end of the string */
836 while (*cursor && cursor[0]) {
838 /* Decode a single value */
839 sr = strtod(cursor, NULL);
841 if (sr > max_supported_rate)
842 max_supported_rate = sr;
844 /* If this matches the selected rate, we're happy */
845 if (new_sampling_rate == sr)
849 * If we reached a higher value than the desired rate,
850 * adjust selected rate so it matches the first higher
851 * available one and stop parsing - this makes the
852 * assumption that rates are sorted by increasing value
853 * in the allowed frequencies string.
855 if (sr > new_sampling_rate) {
857 "Increasing sampling rate on sensor %d from %g to %g\n",
858 s, (double) req_sampling_rate, (double) sr);
860 new_sampling_rate = sr;
865 while (cursor[0] && !isspace(cursor[0]))
869 while (cursor[0] && isspace(cursor[0]))
875 if (max_supported_rate &&
876 new_sampling_rate > max_supported_rate) {
877 new_sampling_rate = max_supported_rate;
878 ALOGI( "Can't support %g sampling rate, lowering to %g\n",
879 (double) req_sampling_rate, (double) new_sampling_rate);
883 /* If the desired rate is already active we're all set */
884 if (new_sampling_rate == cur_sampling_rate)
887 ALOGI("Sensor %d sampling rate switched to %g\n", s, new_sampling_rate);
889 if (trig_sensors_per_dev[dev_num])
890 enable_buffer(dev_num, 0);
892 sysfs_write_float(sysfs_path, new_sampling_rate);
894 if (trig_sensors_per_dev[dev_num])
895 enable_buffer(dev_num, 1);
901 int allocate_control_data (void)
904 struct epoll_event ev = {0};
906 for (i=0; i<MAX_DEVICES; i++)
909 poll_fd = epoll_create(MAX_DEVICES);
912 ALOGE("Can't create epoll instance for iio sensors!\n");
920 void delete_control_data (void)