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"
17 /* Currently active sensors count, per device */
18 static int poll_sensors_per_dev[MAX_DEVICES]; /* poll-mode sensors */
19 static int trig_sensors_per_dev[MAX_DEVICES]; /* trigger, event based */
21 static int device_fd[MAX_DEVICES]; /* fd on the /dev/iio:deviceX file */
23 static int poll_fd; /* epoll instance covering all enabled sensors */
25 static int poll_socket_pair[2]; /* used to unblock the poll loop */
27 /* Timestamp for the moment when we last exited a poll operation */
28 static int64_t last_poll_exit_ts;
30 static int active_poll_sensors; /* Number of enabled poll-mode sensors */
32 /* Cap the time between poll operations to this, to counter runaway polls */
33 #define POLL_MIN_INTERVAL 1000 /* uS */
35 #define INVALID_DEV_NUM ((uint32_t) -1)
38 static int enable_buffer(int dev_num, int enabled)
40 char sysfs_path[PATH_MAX];
42 sprintf(sysfs_path, ENABLE_PATH, dev_num);
44 /* Low level, non-multiplexed, enable/disable routine */
45 return sysfs_write_int(sysfs_path, enabled);
49 static int setup_trigger(int dev_num, const char* trigger_val)
51 char sysfs_path[PATH_MAX];
53 sprintf(sysfs_path, TRIGGER_PATH, dev_num);
55 return sysfs_write_str(sysfs_path, trigger_val);
59 static void refresh_sensor_report_maps(int dev_num)
62 * Read sysfs files from a iio device's scan_element directory, and
63 * build a couple of tables from that data. These tables will tell, for
64 * each sensor, where to gather relevant data in a device report, i.e.
65 * the structure that we read from the /dev/iio:deviceX file in order to
66 * sensor report, itself being the data that we return to Android when a
67 * sensor poll completes. The mapping should be straightforward in the
68 * case where we have a single sensor active per iio device but, this is
69 * not the general case. In general several sensors can be handled
70 * through a single iio device, and the _en, _index and _type syfs
71 * 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 status through syfs attributes */
102 for (c=0; c<sensor_info[s].num_channels; c++) {
105 sprintf(sysfs_path, CHANNEL_PATH "%s",
106 sensor_info[s].dev_num,
107 sensor_catalog[i].channel[c].en_path);
109 n = sysfs_read_int(sysfs_path, &ch_enabled);
112 ALOGW( "Failed to read _en flag: %s\n",
117 if (!ch_enabled != 1) {
118 sensor_info[s].channel[c].size = 0;
121 /* Read _type file */
122 sprintf(sysfs_path, CHANNEL_PATH "%s",
123 sensor_info[s].dev_num,
124 sensor_catalog[i].channel[c].type_path);
126 n = sysfs_read_str(sysfs_path, spec_buf,
130 ALOGW( "Failed to read type: %s\n",
135 ch_spec = sensor_info[s].channel[c].type_spec;
137 memcpy(ch_spec, spec_buf, sizeof(spec_buf));
139 ch_info = &sensor_info[s].channel[c].type_info;
141 size = decode_type_spec(ch_spec, ch_info);
143 /* Read _index file */
144 sprintf(sysfs_path, CHANNEL_PATH "%s",
145 sensor_info[s].dev_num,
146 sensor_catalog[i].channel[c].index_path);
148 n = sysfs_read_int(sysfs_path, &ch_index);
151 ALOGW( "Failed to read index: %s\n",
156 if (ch_index >= MAX_SENSORS) {
157 ALOGE("Index out of bounds!: %s\n", sysfs_path);
161 /* Record what this index is about */
163 sensor_handle_from_index [ch_index] = s;
164 channel_number_from_index[ch_index] = c;
165 channel_size_from_index [ch_index] = size;
171 ALOGI("Found %d enabled channels for iio device %d\n", active_channels,
175 * Now that we know which channels are enabled, their sizes and their
176 * ordering, update channels offsets within device report. Note: there
177 * is a possibility that several sensors share the same index, with
178 * their data fields being isolated by masking and shifting as specified
179 * through the real bits and shift values in type attributes. This case
180 * is not currently supported. Also, the code below assumes no hole in
181 * the sequence of indices, so it is dependent on discovery of all
185 for (i=0; i<MAX_SENSORS * MAX_CHANNELS; i++) {
186 s = sensor_handle_from_index[i];
187 c = channel_number_from_index[i];
188 size = channel_size_from_index[i];
193 ALOGI("S%d C%d : offset %d, size %d, type %s\n",
194 s, c, offset, size, sensor_info[s].channel[c].type_spec);
196 sensor_info[s].channel[c].offset = offset;
197 sensor_info[s].channel[c].size = size;
204 int adjust_counters (int s, int enabled)
207 * Adjust counters based on sensor enable action. Return values are:
208 * -1 if there's an inconsistency: abort action in this case
209 * 0 if the operation was completed and we're all set
210 * 1 if we toggled the state of the sensor and there's work left
213 int dev_num = sensor_info[s].dev_num;
215 /* Refcount per sensor, in terms of enable count */
217 ALOGI("Enabling sensor %d (iio device %d: %s)\n",
218 s, dev_num, sensor_info[s].friendly_name);
220 sensor_info[s].enable_count++;
222 if (sensor_info[s].enable_count != 1)
223 return 0; /* The sensor was, and remains, in use */
225 if (sensor_info[s].enable_count == 0)
226 return -1; /* Spurious disable call */
228 ALOGI("Disabling sensor %d (iio device %d: %s)\n", s, dev_num,
229 sensor_info[s].friendly_name);
231 sensor_info[s].enable_count--;
233 if (sensor_info[s].enable_count > 0)
234 return 0; /* The sensor was, and remains, in use */
236 /* Sensor disabled, lower report available flag */
237 sensor_info[s].report_pending = 0;
240 /* We changed the state of a sensor - adjust per iio device counters */
242 /* If this is a regular event-driven sensor */
243 if (sensor_info[s].num_channels) {
246 trig_sensors_per_dev[dev_num]++;
248 trig_sensors_per_dev[dev_num]--;
254 active_poll_sensors++;
255 poll_sensors_per_dev[dev_num]++;
259 active_poll_sensors--;
260 poll_sensors_per_dev[dev_num]--;
265 int sensor_activate(int s, int enabled)
267 char sysfs_path[PATH_MAX];
268 char device_name[PATH_MAX];
269 char trigger_name[MAX_NAME_SIZE + 16];
271 struct epoll_event ev = {0};
274 int dev_num = sensor_info[s].dev_num;
275 int i = sensor_info[s].catalog_index;
276 int is_poll_sensor = !sensor_info[s].num_channels;
278 ret = adjust_counters(s, enabled);
280 /* If the operation was neutral in terms of state, we're done */
284 if (!is_poll_sensor) {
285 /* Changes have to be made while the buffer is turned off */
286 enable_buffer(dev_num, 0);
288 /* Configure trigger */
289 switch (trig_sensors_per_dev[dev_num]) {
291 setup_trigger(dev_num, "none");
295 sprintf(trigger_name, "%s-dev%d",
296 sensor_info[s].internal_name, dev_num);
298 setup_trigger(dev_num, trigger_name);
302 /* The trigger is already set */
307 * Turn channels associated to this sensor on or off, and update
308 * the channels maps for all sensors associated to this device.
310 for (c=0;c<sensor_info[s].num_channels; c++) {
311 sprintf(sysfs_path, CHANNEL_PATH "%s",
312 sensor_info[s].dev_num,
313 sensor_catalog[i].channel[c].en_path);
315 sysfs_write_int(sysfs_path, enabled);
318 /* If there's at least one sensor left */
319 if (trig_sensors_per_dev[dev_num]) {
320 refresh_sensor_report_maps(dev_num);
321 enable_buffer(dev_num, 1);
326 * Make sure we have a fd on the character device ; conversely, close
327 * the fd if no one is using associated sensor anymore. The assumption
328 * here is that the underlying driver will power on the relevant
329 * hardware block while someone hold a fd on the device.
331 dev_fd = device_fd[dev_num];
334 if (dev_fd != -1 && !poll_sensors_per_dev[dev_num] &&
335 !trig_sensors_per_dev[dev_num]) {
337 * Stop watching this fd. This should be a no-op
338 * in case this fd was not in the poll set.
340 epoll_ctl(poll_fd, EPOLL_CTL_DEL, dev_fd, NULL);
343 device_fd[dev_num] = -1;
349 /* First enabled sensor on this iio device */
350 sprintf(device_name, DEV_FILE_PATH, dev_num);
351 dev_fd = open(device_name, O_RDONLY | O_NONBLOCK);
353 device_fd[dev_num] = dev_fd;
356 ALOGE("Could not open fd on %s (%s)\n",
357 device_name, strerror(errno));
358 adjust_counters(s, 0);
362 ALOGV("Opened %s: fd=%d\n", device_name, dev_fd);
364 if (!is_poll_sensor) {
366 /* Add this iio device fd to the set of watched fds */
368 ev.data.u32 = dev_num;
370 ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, dev_fd, &ev);
373 ALOGE( "Failed adding %d to poll set (%s)\n",
374 dev_fd, strerror(errno));
378 /* Note: poll-mode fds are not readable */
382 /* Release the polling loop so an updated timeout gets used */
383 write(poll_socket_pair[1], "", 1);
389 static int integrate_device_report(int dev_num)
393 unsigned char buf[MAX_SENSOR_REPORT_SIZE * MAX_SENSORS] = { 0 };
395 unsigned char *target;
396 unsigned char *source;
398 int expected_size = 0;
400 /* There's an incoming report on the specified fd */
402 if (dev_num < 0 || dev_num >= MAX_DEVICES) {
403 ALOGE("Event reported on unexpected iio device %d\n", dev_num);
407 if (device_fd[dev_num] == -1) {
408 ALOGE("Ignoring stale report on iio device %d\n", dev_num);
412 for (s=0; s<MAX_SENSORS; s++)
413 if (sensor_info[s].dev_num == dev_num)
414 for (c=0; c<sensor_info[s].num_channels; c++)
415 expected_size += sensor_info[s].channel[c].size;
417 len = read(device_fd[dev_num], buf, expected_size);
420 ALOGE("Could not read report from iio device %d (%s)\n",
421 dev_num, strerror(errno));
425 ALOGV("Read %d bytes from iio device %d\n", len, dev_num);
427 for (s=0; s<MAX_SENSORS; s++)
428 if (sensor_info[s].dev_num == dev_num &&
429 sensor_info[s].enable_count) {
433 /* Copy data from device to sensor report buffer */
434 for (c=0; c<sensor_info[s].num_channels; c++) {
436 target = sensor_info[s].report_buffer +
439 source = buf + sensor_info[s].channel[c].offset;
441 size = sensor_info[s].channel[c].size;
443 memcpy(target, source, size);
448 ALOGV("Sensor %d report available (%d bytes)\n", s,
451 sensor_info[s].report_pending = 1;
458 static void propagate_sensor_report(int s, struct sensors_event_t* data)
460 /* There's a sensor report pending for this sensor ; transmit it */
462 int catalog_index = sensor_info[s].catalog_index;
463 int sensor_type = sensor_catalog[catalog_index].type;
466 unsigned char* current_sample;
468 memset(data, 0, sizeof(sensors_event_t));
470 data->version = sizeof(sensors_event_t);
472 data->type = sensor_type;
473 data->timestamp = get_timestamp();
475 switch (sensor_type) {
476 case SENSOR_TYPE_ACCELEROMETER: /* m/s^2 */
477 case SENSOR_TYPE_MAGNETIC_FIELD: /* micro-tesla */
478 case SENSOR_TYPE_ORIENTATION: /* degrees */
479 case SENSOR_TYPE_GYROSCOPE: /* radians/s */
483 case SENSOR_TYPE_LIGHT: /* SI lux units */
484 case SENSOR_TYPE_AMBIENT_TEMPERATURE: /* °C */
485 case SENSOR_TYPE_TEMPERATURE: /* °C */
486 case SENSOR_TYPE_PROXIMITY: /* centimeters */
487 case SENSOR_TYPE_PRESSURE: /* hecto-pascal */
488 case SENSOR_TYPE_RELATIVE_HUMIDITY: /* percent */
492 case SENSOR_TYPE_ROTATION_VECTOR:
496 case SENSOR_TYPE_DEVICE_PRIVATE_BASE: /* hidden for now */
501 ALOGE("Unknown sensor type!\n");
506 ALOGV("Sample on sensor %d (type %d):\n", s, sensor_type);
508 /* Take note of current time counter value for rate control purposes */
509 sensor_info[s].last_integration_ts = get_timestamp();
511 /* If we're dealing with a poll-mode sensor */
512 if (!sensor_info[s].num_channels) {
514 /* Read values through sysfs rather than from a report buffer */
515 for (c=0; c<num_fields; c++) {
517 data->data[c] = acquire_immediate_value(s, c);
519 ALOGV("\tfield %d: %f\n", c, data->data[c]);
522 sensor_info[s].ops.finalize(s, data);
526 /* Convert the data into the expected Android-level format */
528 current_sample = sensor_info[s].report_buffer;
530 for (c=0; c<num_fields; c++) {
532 data->data[c] = sensor_info[s].ops.transform
533 (s, c, current_sample);
535 ALOGV("\tfield %d: %f\n", c, data->data[c]);
536 current_sample += sensor_info[s].channel[c].size;
539 sensor_info[s].ops.finalize(s, data);
543 static int get_poll_time (void)
546 int64_t lowest_target_ts;
550 if (!active_poll_sensors)
551 return -1; /* Infinite wait */
553 /* Check if we should schedule a poll-mode sensor event delivery */
555 lowest_target_ts = INT64_MAX;
557 for (s=0; s<sensor_count; s++)
558 if (sensor_info[s].enable_count &&
559 sensor_info[s].sampling_rate &&
560 !sensor_info[s].num_channels) {
561 target_ts = sensor_info[s].last_integration_ts +
562 1000000000LL/sensor_info[s].sampling_rate;
564 if (target_ts < lowest_target_ts)
565 lowest_target_ts = target_ts;
568 if (lowest_target_ts == INT64_MAX)
571 current_ts = get_timestamp();
573 if (lowest_target_ts <= current_ts)
576 return (lowest_target_ts - current_ts)/1000000; /* ms */
580 static void acknowledge_release (void)
582 /* A write to our socket circuit was performed to release epoll */
584 read(poll_socket_pair[0], &buf, 1);
588 int sensor_poll(struct sensors_event_t* data, int count)
594 struct epoll_event ev[MAX_DEVICES];
596 /* Get one or more events from our collection of sensors */
598 return_first_available_sensor_report:
600 /* If there's at least one available report */
601 for (s=0; s<sensor_count; s++)
602 if (sensor_info[s].report_pending) {
605 propagate_sensor_report(s, data);
606 sensor_info[s].report_pending = 0;
607 ALOGV("Report on sensor %d\n", s);
612 /* Keep a minimum time interval between poll operations */
613 delta = (get_timestamp() - last_poll_exit_ts)/1000;
615 if (delta > 0 && delta < POLL_MIN_INTERVAL)
616 usleep(POLL_MIN_INTERVAL - delta);
618 ALOGV("Awaiting sensor data\n");
620 nfds = epoll_wait(poll_fd, ev, MAX_DEVICES, get_poll_time());
622 last_poll_exit_ts = get_timestamp();
625 ALOGI("epoll_wait returned -1 (%s)\n", strerror(errno));
629 ALOGV("%d fds signalled\n", nfds);
631 /* For each of the devices for which a report is available */
632 for (i=0; i<nfds; i++)
633 if (ev[i].events == EPOLLIN) {
634 if (ev[i].data.u32 == INVALID_DEV_NUM) {
635 acknowledge_release();
639 integrate_device_report(ev[i].data.u32);
642 /* It's a good time to invalidate poll-mode sensor values */
643 if (active_poll_sensors)
644 for (s=0; s<sensor_count; s++)
645 if (sensor_info[s].enable_count &&
646 !sensor_info[s].num_channels)
647 sensor_info[s].report_pending = 1;
649 goto return_first_available_sensor_report;
653 int sensor_set_delay(int s, int64_t ns)
655 /* Set the rate at which a specific sensor should report events */
657 /* See Android sensors.h for indication on sensor trigger modes */
659 char sysfs_path[PATH_MAX];
660 char avail_sysfs_path[PATH_MAX];
661 int dev_num = sensor_info[s].dev_num;
662 int i = sensor_info[s].catalog_index;
663 const char *prefix = sensor_catalog[i].tag;
664 int new_sampling_rate; /* Granted sampling rate after arbitration */
665 int cur_sampling_rate; /* Currently used sampling rate */
666 int req_sampling_rate; /* Requested ; may be different from granted */
667 int per_sensor_sampling_rate;
668 int per_device_sampling_rate;
669 int max_supported_rate = 0;
676 ALOGE("Rejecting zero delay request on sensor %d\n", s);
680 new_sampling_rate = req_sampling_rate = (int) (1000000000L/ns);
682 if (!new_sampling_rate) {
683 ALOGI("Sub-HZ sampling rate requested on on sensor %d\n", s);
684 new_sampling_rate = 1;
687 sensor_info[s].sampling_rate = new_sampling_rate;
689 /* If we're dealing with a poll-mode sensor, release poll and return */
690 if (!sensor_info[s].num_channels)
693 sprintf(sysfs_path, SENSOR_SAMPLING_PATH, dev_num, prefix);
695 if (sysfs_read_int(sysfs_path, &cur_sampling_rate) != -1) {
696 per_sensor_sampling_rate = 1;
697 per_device_sampling_rate = 0;
699 per_sensor_sampling_rate = 0;
701 sprintf(sysfs_path, DEVICE_SAMPLING_PATH, dev_num);
703 if (sysfs_read_int(sysfs_path, &cur_sampling_rate) != -1)
704 per_device_sampling_rate = 1;
706 per_device_sampling_rate = 0;
709 if (!per_sensor_sampling_rate && !per_device_sampling_rate) {
710 ALOGE("No way to adjust sampling rate on sensor %d\n", s);
714 /* Coordinate with others active sensors on the same device, if any */
715 if (per_device_sampling_rate)
716 for (n=0; n<sensor_count; n++)
717 if (n != s && sensor_info[n].dev_num == dev_num &&
718 sensor_info[n].num_channels &&
719 sensor_info[n].enable_count &&
720 sensor_info[n].sampling_rate > new_sampling_rate)
721 new_sampling_rate= sensor_info[n].sampling_rate;
723 /* Check if we have contraints on allowed sampling rates */
725 sprintf(avail_sysfs_path, DEVICE_AVAIL_FREQ_PATH, dev_num);
727 if (sysfs_read_str(avail_sysfs_path, freqs_buf, sizeof(freqs_buf)) > 0){
730 /* Decode allowed sampling rates string, ex: "10 20 50 100" */
732 /* While we're not at the end of the string */
733 while (*cursor && cursor[0]) {
735 /* Decode a single integer value */
738 if (n > max_supported_rate)
739 max_supported_rate = n;
741 /* If this matches the selected rate, we're happy */
742 if (new_sampling_rate == n)
746 * If we reached a higher value than the desired rate,
747 * adjust selected rate so it matches the first higher
748 * available one and stop parsing - this makes the
749 * assumption that rates are sorted by increasing value
750 * in the allowed frequencies string.
752 if (n > new_sampling_rate) {
754 "Increasing sampling rate on sensor %d from %d to %d\n",
755 s, req_sampling_rate, n);
757 new_sampling_rate = n;
762 while (cursor[0] && !isspace(cursor[0]))
766 while (cursor[0] && isspace(cursor[0]))
771 /* Cap sampling rate */
773 limit = 1000000/POLL_MIN_INTERVAL;
775 if (max_supported_rate && new_sampling_rate > max_supported_rate)
776 limit = max_supported_rate;
778 if (new_sampling_rate > limit) {
780 new_sampling_rate = limit;
782 ALOGI( "Can't support %d sampling rate, lowering to %d\n",
783 req_sampling_rate, new_sampling_rate);
786 /* If the desired rate is already active we're all set */
787 if (new_sampling_rate == cur_sampling_rate)
790 ALOGI("Sensor %d sampling rate switched to %d\n", s, new_sampling_rate);
792 if (trig_sensors_per_dev[dev_num])
793 enable_buffer(dev_num, 0);
795 sysfs_write_int(sysfs_path, new_sampling_rate);
797 if (trig_sensors_per_dev[dev_num])
798 enable_buffer(dev_num, 1);
801 /* Release the polling loop so an updated timeout value gets used */
802 write(poll_socket_pair[1], "", 1);
809 int allocate_control_data (void)
812 struct epoll_event ev = {0};
814 for (i=0; i<MAX_DEVICES; i++)
817 poll_fd = epoll_create(MAX_DEVICES);
820 ALOGE("Can't create epoll instance for iio sensors!\n");
824 /* Create and add "unblocking" fd to the set of watched fds */
826 if (socketpair(AF_UNIX, SOCK_STREAM, 0, poll_socket_pair) == -1) {
827 ALOGE("Can't create socket pair for iio sensors!\n");
833 ev.data.u32 = INVALID_DEV_NUM;
835 epoll_ctl(poll_fd, EPOLL_CTL_ADD, poll_socket_pair[0], &ev);
841 void delete_control_data (void)