2 * Copyright (C) 2014 Intel Corporation.
9 #include <sys/socket.h>
10 #include <utils/Log.h>
11 #include <hardware/sensors.h>
13 #include "enumeration.h"
15 #include "transform.h"
16 #include "calibration.h"
18 /* Currently active sensors count, per device */
19 static int poll_sensors_per_dev[MAX_DEVICES]; /* poll-mode sensors */
20 static int trig_sensors_per_dev[MAX_DEVICES]; /* trigger, event based */
22 static int device_fd[MAX_DEVICES]; /* fd on the /dev/iio:deviceX file */
24 static int poll_fd; /* epoll instance covering all enabled sensors */
26 static int poll_socket_pair[2]; /* used to unblock the poll loop */
28 /* Timestamp for the moment when we last exited a poll operation */
29 static int64_t last_poll_exit_ts;
31 static int active_poll_sensors; /* Number of enabled poll-mode sensors */
33 /* Cap the time between poll operations to this, to counter runaway polls */
34 #define POLL_MIN_INTERVAL 1000 /* uS */
36 #define INVALID_DEV_NUM ((uint32_t) -1)
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 static void refresh_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
83 char spec_buf[MAX_TYPE_SPEC_LEN];
84 struct datum_info_t* ch_info;
86 char sysfs_path[PATH_MAX];
89 int channel_size_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
90 int sensor_handle_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
91 int channel_number_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
95 /* For each sensor that is linked to this device */
96 for (s=0; s<sensor_count; s++) {
97 if (sensor_info[s].dev_num != dev_num)
100 i = sensor_info[s].catalog_index;
102 /* Read channel status through syfs attributes */
103 for (c=0; c<sensor_info[s].num_channels; c++) {
106 sprintf(sysfs_path, CHANNEL_PATH "%s",
107 sensor_info[s].dev_num,
108 sensor_catalog[i].channel[c].en_path);
110 n = sysfs_read_int(sysfs_path, &ch_enabled);
113 ALOGW( "Failed to read _en flag: %s\n",
118 if (!ch_enabled != 1) {
119 sensor_info[s].channel[c].size = 0;
122 /* Read _type file */
123 sprintf(sysfs_path, CHANNEL_PATH "%s",
124 sensor_info[s].dev_num,
125 sensor_catalog[i].channel[c].type_path);
127 n = sysfs_read_str(sysfs_path, spec_buf,
131 ALOGW( "Failed to read type: %s\n",
136 ch_spec = sensor_info[s].channel[c].type_spec;
138 memcpy(ch_spec, spec_buf, sizeof(spec_buf));
140 ch_info = &sensor_info[s].channel[c].type_info;
142 size = decode_type_spec(ch_spec, ch_info);
144 /* Read _index file */
145 sprintf(sysfs_path, CHANNEL_PATH "%s",
146 sensor_info[s].dev_num,
147 sensor_catalog[i].channel[c].index_path);
149 n = sysfs_read_int(sysfs_path, &ch_index);
152 ALOGW( "Failed to read index: %s\n",
157 if (ch_index >= MAX_SENSORS) {
158 ALOGE("Index out of bounds!: %s\n", sysfs_path);
162 /* Record what this index is about */
164 sensor_handle_from_index [ch_index] = s;
165 channel_number_from_index[ch_index] = c;
166 channel_size_from_index [ch_index] = size;
172 ALOGI("Found %d enabled channels for iio device %d\n", active_channels,
176 * Now that we know which channels are enabled, their sizes and their
177 * ordering, update channels offsets within device report. Note: there
178 * is a possibility that several sensors share the same index, with
179 * their data fields being isolated by masking and shifting as specified
180 * through the real bits and shift values in type attributes. This case
181 * is not currently supported. Also, the code below assumes no hole in
182 * the sequence of indices, so it is dependent on discovery of all
186 for (i=0; i<MAX_SENSORS * MAX_CHANNELS; i++) {
187 s = sensor_handle_from_index[i];
188 c = channel_number_from_index[i];
189 size = channel_size_from_index[i];
194 ALOGI("S%d C%d : offset %d, size %d, type %s\n",
195 s, c, offset, size, sensor_info[s].channel[c].type_spec);
197 sensor_info[s].channel[c].offset = offset;
198 sensor_info[s].channel[c].size = size;
205 int adjust_counters (int s, int enabled)
208 * Adjust counters based on sensor enable action. Return values are:
209 * -1 if there's an inconsistency: abort action in this case
210 * 0 if the operation was completed and we're all set
211 * 1 if we toggled the state of the sensor and there's work left
214 int dev_num = sensor_info[s].dev_num;
215 int catalog_index = sensor_info[s].catalog_index;
216 int sensor_type = sensor_catalog[catalog_index].type;
218 /* Refcount per sensor, in terms of enable count */
220 ALOGI("Enabling sensor %d (iio device %d: %s)\n",
221 s, dev_num, sensor_info[s].friendly_name);
223 sensor_info[s].enable_count++;
225 if (sensor_info[s].enable_count != 1) {
226 return 0; /* The sensor was, and remains, in use */
228 if (sensor_type == SENSOR_TYPE_MAGNETIC_FIELD)
229 compass_read_data(COMPASS_CALIBRATION_PATH);
232 if (sensor_info[s].enable_count == 0)
233 return -1; /* Spurious disable call */
235 ALOGI("Disabling sensor %d (iio device %d: %s)\n", s, dev_num,
236 sensor_info[s].friendly_name);
238 if (sensor_type == SENSOR_TYPE_MAGNETIC_FIELD)
239 compass_store_data(COMPASS_CALIBRATION_PATH);
241 sensor_info[s].enable_count--;
243 if (sensor_info[s].enable_count > 0)
244 return 0; /* The sensor was, and remains, in use */
246 /* Sensor disabled, lower report available flag */
247 sensor_info[s].report_pending = 0;
250 /* We changed the state of a sensor - adjust per iio device counters */
252 /* If this is a regular event-driven sensor */
253 if (sensor_info[s].num_channels) {
256 trig_sensors_per_dev[dev_num]++;
258 trig_sensors_per_dev[dev_num]--;
264 active_poll_sensors++;
265 poll_sensors_per_dev[dev_num]++;
269 active_poll_sensors--;
270 poll_sensors_per_dev[dev_num]--;
275 int sensor_activate(int s, int enabled)
277 char sysfs_path[PATH_MAX];
278 char device_name[PATH_MAX];
279 char trigger_name[MAX_NAME_SIZE + 16];
281 struct epoll_event ev = {0};
284 int dev_num = sensor_info[s].dev_num;
285 int i = sensor_info[s].catalog_index;
286 int is_poll_sensor = !sensor_info[s].num_channels;
288 ret = adjust_counters(s, enabled);
290 /* If the operation was neutral in terms of state, we're done */
294 if (!is_poll_sensor) {
295 /* Changes have to be made while the buffer is turned off */
296 enable_buffer(dev_num, 0);
298 /* Configure trigger */
299 switch (trig_sensors_per_dev[dev_num]) {
301 setup_trigger(dev_num, "none");
305 sprintf(trigger_name, "%s-dev%d",
306 sensor_info[s].internal_name, dev_num);
308 setup_trigger(dev_num, trigger_name);
312 /* The trigger is already set */
317 * Turn channels associated to this sensor on or off, and update
318 * the channels maps for all sensors associated to this device.
320 for (c=0;c<sensor_info[s].num_channels; c++) {
321 sprintf(sysfs_path, CHANNEL_PATH "%s",
322 sensor_info[s].dev_num,
323 sensor_catalog[i].channel[c].en_path);
325 sysfs_write_int(sysfs_path, enabled);
328 /* If there's at least one sensor left */
329 if (trig_sensors_per_dev[dev_num]) {
330 refresh_sensor_report_maps(dev_num);
331 enable_buffer(dev_num, 1);
336 * Make sure we have a fd on the character device ; conversely, close
337 * the fd if no one is using associated sensor anymore. The assumption
338 * here is that the underlying driver will power on the relevant
339 * hardware block while someone hold a fd on the device.
341 dev_fd = device_fd[dev_num];
344 if (dev_fd != -1 && !poll_sensors_per_dev[dev_num] &&
345 !trig_sensors_per_dev[dev_num]) {
347 * Stop watching this fd. This should be a no-op
348 * in case this fd was not in the poll set.
350 epoll_ctl(poll_fd, EPOLL_CTL_DEL, dev_fd, NULL);
353 device_fd[dev_num] = -1;
359 /* First enabled sensor on this iio device */
360 sprintf(device_name, DEV_FILE_PATH, dev_num);
361 dev_fd = open(device_name, O_RDONLY | O_NONBLOCK);
363 device_fd[dev_num] = dev_fd;
366 ALOGE("Could not open fd on %s (%s)\n",
367 device_name, strerror(errno));
368 adjust_counters(s, 0);
372 ALOGV("Opened %s: fd=%d\n", device_name, dev_fd);
374 if (!is_poll_sensor) {
376 /* Add this iio device fd to the set of watched fds */
378 ev.data.u32 = dev_num;
380 ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, dev_fd, &ev);
383 ALOGE( "Failed adding %d to poll set (%s)\n",
384 dev_fd, strerror(errno));
388 /* Note: poll-mode fds are not readable */
392 /* Release the polling loop so an updated timeout gets used */
393 write(poll_socket_pair[1], "", 1);
399 static int integrate_device_report(int dev_num)
403 unsigned char buf[MAX_SENSOR_REPORT_SIZE * MAX_SENSORS] = { 0 };
405 unsigned char *target;
406 unsigned char *source;
408 int expected_size = 0;
410 /* There's an incoming report on the specified fd */
412 if (dev_num < 0 || dev_num >= MAX_DEVICES) {
413 ALOGE("Event reported on unexpected iio device %d\n", dev_num);
417 if (device_fd[dev_num] == -1) {
418 ALOGE("Ignoring stale report on iio device %d\n", dev_num);
422 for (s=0; s<MAX_SENSORS; s++)
423 if (sensor_info[s].dev_num == dev_num)
424 for (c=0; c<sensor_info[s].num_channels; c++)
425 expected_size += sensor_info[s].channel[c].size;
427 len = read(device_fd[dev_num], buf, expected_size);
430 ALOGE("Could not read report from iio device %d (%s)\n",
431 dev_num, strerror(errno));
435 ALOGV("Read %d bytes from iio device %d\n", len, dev_num);
437 for (s=0; s<MAX_SENSORS; s++)
438 if (sensor_info[s].dev_num == dev_num &&
439 sensor_info[s].enable_count) {
443 /* Copy data from device to sensor report buffer */
444 for (c=0; c<sensor_info[s].num_channels; c++) {
446 target = sensor_info[s].report_buffer +
449 source = buf + sensor_info[s].channel[c].offset;
451 size = sensor_info[s].channel[c].size;
453 memcpy(target, source, size);
458 ALOGV("Sensor %d report available (%d bytes)\n", s,
461 sensor_info[s].report_pending = 1;
468 static void propagate_sensor_report(int s, struct sensors_event_t* data)
470 /* There's a sensor report pending for this sensor ; transmit it */
472 int catalog_index = sensor_info[s].catalog_index;
473 int sensor_type = sensor_catalog[catalog_index].type;
476 unsigned char* current_sample;
477 int64_t current_ts = get_timestamp();
479 memset(data, 0, sizeof(sensors_event_t));
481 data->version = sizeof(sensors_event_t);
483 data->type = sensor_type;
484 data->timestamp = current_ts;
486 switch (sensor_type) {
487 case SENSOR_TYPE_ACCELEROMETER: /* m/s^2 */
488 case SENSOR_TYPE_MAGNETIC_FIELD: /* micro-tesla */
489 case SENSOR_TYPE_ORIENTATION: /* degrees */
490 case SENSOR_TYPE_GYROSCOPE: /* radians/s */
494 case SENSOR_TYPE_LIGHT: /* SI lux units */
495 case SENSOR_TYPE_AMBIENT_TEMPERATURE: /* °C */
496 case SENSOR_TYPE_TEMPERATURE: /* °C */
497 case SENSOR_TYPE_PROXIMITY: /* centimeters */
498 case SENSOR_TYPE_PRESSURE: /* hecto-pascal */
499 case SENSOR_TYPE_RELATIVE_HUMIDITY: /* percent */
503 case SENSOR_TYPE_ROTATION_VECTOR:
507 case SENSOR_TYPE_DEVICE_PRIVATE_BASE: /* hidden for now */
512 ALOGE("Unknown sensor type!\n");
517 ALOGV("Sample on sensor %d (type %d):\n", s, sensor_type);
519 /* Take note of current time counter value for rate control purposes */
520 sensor_info[s].last_integration_ts = current_ts;
522 /* If we're dealing with a poll-mode sensor */
523 if (!sensor_info[s].num_channels) {
525 /* Read values through sysfs rather than from a report buffer */
526 for (c=0; c<num_fields; c++) {
528 data->data[c] = acquire_immediate_value(s, c);
530 ALOGV("\tfield %d: %f\n", c, data->data[c]);
533 sensor_info[s].ops.finalize(s, data);
537 /* Convert the data into the expected Android-level format */
539 current_sample = sensor_info[s].report_buffer;
541 for (c=0; c<num_fields; c++) {
543 data->data[c] = sensor_info[s].ops.transform
544 (s, c, current_sample);
546 ALOGV("\tfield %d: %f\n", c, data->data[c]);
547 current_sample += sensor_info[s].channel[c].size;
550 sensor_info[s].ops.finalize(s, data);
554 static int get_poll_time (void)
557 int64_t lowest_target_ts;
561 if (!active_poll_sensors)
562 return -1; /* Infinite wait */
564 /* Check if we should schedule a poll-mode sensor event delivery */
566 lowest_target_ts = INT64_MAX;
568 for (s=0; s<sensor_count; s++)
569 if (sensor_info[s].enable_count &&
570 sensor_info[s].sampling_rate &&
571 !sensor_info[s].num_channels) {
572 target_ts = sensor_info[s].last_integration_ts +
573 1000000000LL/sensor_info[s].sampling_rate;
575 if (target_ts < lowest_target_ts)
576 lowest_target_ts = target_ts;
579 if (lowest_target_ts == INT64_MAX)
582 current_ts = get_timestamp();
584 if (lowest_target_ts <= current_ts)
587 return (lowest_target_ts - current_ts)/1000000; /* ms */
591 static void acknowledge_release (void)
593 /* A write to our socket circuit was performed to release epoll */
595 read(poll_socket_pair[0], &buf, 1);
599 int sensor_poll(struct sensors_event_t* data, int count)
605 struct epoll_event ev[MAX_DEVICES];
608 /* Get one or more events from our collection of sensors */
610 return_first_available_sensor_report:
612 /* If there's at least one available report */
613 for (s=0; s<sensor_count; s++)
614 if (sensor_info[s].report_pending) {
617 propagate_sensor_report(s, data);
618 sensor_info[s].report_pending = 0;
619 ALOGV("Report on sensor %d\n", s);
624 /* Keep a minimum time interval between poll operations */
625 delta = (get_timestamp() - last_poll_exit_ts)/1000;
627 if (delta > 0 && delta < POLL_MIN_INTERVAL)
628 usleep(POLL_MIN_INTERVAL - delta);
630 ALOGV("Awaiting sensor data\n");
632 nfds = epoll_wait(poll_fd, ev, MAX_DEVICES, get_poll_time());
634 last_poll_exit_ts = get_timestamp();
637 ALOGI("epoll_wait returned -1 (%s)\n", strerror(errno));
641 ALOGV("%d fds signalled\n", nfds);
643 /* For each of the devices for which a report is available */
644 for (i=0; i<nfds; i++)
645 if (ev[i].events == EPOLLIN) {
646 if (ev[i].data.u32 == INVALID_DEV_NUM) {
647 acknowledge_release();
651 integrate_device_report(ev[i].data.u32);
654 /* Check poll-mode sensors and fire up an event if it's time to do so */
655 if (active_poll_sensors)
656 for (s=0; s<sensor_count; s++)
657 if (sensor_info[s].enable_count &&
658 !sensor_info[s].num_channels &&
659 sensor_info[s].sampling_rate) {
660 target_ts = sensor_info[s].last_integration_ts +
661 1000000000LL/sensor_info[s].sampling_rate;
663 if (last_poll_exit_ts >= target_ts)
664 sensor_info[s].report_pending = 1;
667 goto return_first_available_sensor_report;
671 int sensor_set_delay(int s, int64_t ns)
673 /* Set the rate at which a specific sensor should report events */
675 /* See Android sensors.h for indication on sensor trigger modes */
677 char sysfs_path[PATH_MAX];
678 char avail_sysfs_path[PATH_MAX];
679 int dev_num = sensor_info[s].dev_num;
680 int i = sensor_info[s].catalog_index;
681 const char *prefix = sensor_catalog[i].tag;
682 int new_sampling_rate; /* Granted sampling rate after arbitration */
683 int cur_sampling_rate; /* Currently used sampling rate */
684 int req_sampling_rate; /* Requested ; may be different from granted */
685 int per_sensor_sampling_rate;
686 int per_device_sampling_rate;
687 int max_supported_rate = 0;
694 ALOGE("Rejecting zero delay request on sensor %d\n", s);
698 new_sampling_rate = req_sampling_rate = (int) (1000000000L/ns);
700 if (!new_sampling_rate) {
701 ALOGI("Sub-HZ sampling rate requested on on sensor %d\n", s);
702 new_sampling_rate = 1;
705 sensor_info[s].sampling_rate = new_sampling_rate;
707 /* If we're dealing with a poll-mode sensor, release poll and return */
708 if (!sensor_info[s].num_channels)
711 sprintf(sysfs_path, SENSOR_SAMPLING_PATH, dev_num, prefix);
713 if (sysfs_read_int(sysfs_path, &cur_sampling_rate) != -1) {
714 per_sensor_sampling_rate = 1;
715 per_device_sampling_rate = 0;
717 per_sensor_sampling_rate = 0;
719 sprintf(sysfs_path, DEVICE_SAMPLING_PATH, dev_num);
721 if (sysfs_read_int(sysfs_path, &cur_sampling_rate) != -1)
722 per_device_sampling_rate = 1;
724 per_device_sampling_rate = 0;
727 if (!per_sensor_sampling_rate && !per_device_sampling_rate) {
728 ALOGE("No way to adjust sampling rate on sensor %d\n", s);
732 /* Coordinate with others active sensors on the same device, if any */
733 if (per_device_sampling_rate)
734 for (n=0; n<sensor_count; n++)
735 if (n != s && sensor_info[n].dev_num == dev_num &&
736 sensor_info[n].num_channels &&
737 sensor_info[n].enable_count &&
738 sensor_info[n].sampling_rate > new_sampling_rate)
739 new_sampling_rate= sensor_info[n].sampling_rate;
741 /* Check if we have contraints on allowed sampling rates */
743 sprintf(avail_sysfs_path, DEVICE_AVAIL_FREQ_PATH, dev_num);
745 if (sysfs_read_str(avail_sysfs_path, freqs_buf, sizeof(freqs_buf)) > 0){
748 /* Decode allowed sampling rates string, ex: "10 20 50 100" */
750 /* While we're not at the end of the string */
751 while (*cursor && cursor[0]) {
753 /* Decode a single integer value */
756 if (n > max_supported_rate)
757 max_supported_rate = n;
759 /* If this matches the selected rate, we're happy */
760 if (new_sampling_rate == n)
764 * If we reached a higher value than the desired rate,
765 * adjust selected rate so it matches the first higher
766 * available one and stop parsing - this makes the
767 * assumption that rates are sorted by increasing value
768 * in the allowed frequencies string.
770 if (n > new_sampling_rate) {
772 "Increasing sampling rate on sensor %d from %d to %d\n",
773 s, req_sampling_rate, n);
775 new_sampling_rate = n;
780 while (cursor[0] && !isspace(cursor[0]))
784 while (cursor[0] && isspace(cursor[0]))
789 /* Cap sampling rate */
791 limit = 1000000/POLL_MIN_INTERVAL;
793 if (max_supported_rate && new_sampling_rate > max_supported_rate)
794 limit = max_supported_rate;
796 if (new_sampling_rate > limit) {
798 new_sampling_rate = limit;
800 ALOGI( "Can't support %d sampling rate, lowering to %d\n",
801 req_sampling_rate, new_sampling_rate);
804 /* If the desired rate is already active we're all set */
805 if (new_sampling_rate == cur_sampling_rate)
808 ALOGI("Sensor %d sampling rate switched to %d\n", s, new_sampling_rate);
810 if (trig_sensors_per_dev[dev_num])
811 enable_buffer(dev_num, 0);
813 sysfs_write_int(sysfs_path, new_sampling_rate);
815 if (trig_sensors_per_dev[dev_num])
816 enable_buffer(dev_num, 1);
819 /* Release the polling loop so an updated timeout value gets used */
820 write(poll_socket_pair[1], "", 1);
827 int allocate_control_data (void)
830 struct epoll_event ev = {0};
832 for (i=0; i<MAX_DEVICES; i++)
835 poll_fd = epoll_create(MAX_DEVICES);
838 ALOGE("Can't create epoll instance for iio sensors!\n");
842 /* Create and add "unblocking" fd to the set of watched fds */
844 if (socketpair(AF_UNIX, SOCK_STREAM, 0, poll_socket_pair) == -1) {
845 ALOGE("Can't create socket pair for iio sensors!\n");
851 ev.data.u32 = INVALID_DEV_NUM;
853 epoll_ctl(poll_fd, EPOLL_CTL_ADD, poll_socket_pair[0], &ev);
859 void delete_control_data (void)