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 #define INVALID_DEV_NUM ((uint32_t) -1)
36 static int enable_buffer(int dev_num, int enabled)
38 char sysfs_path[PATH_MAX];
40 sprintf(sysfs_path, ENABLE_PATH, dev_num);
42 /* Low level, non-multiplexed, enable/disable routine */
43 return sysfs_write_int(sysfs_path, enabled);
47 static int setup_trigger(int dev_num, const char* trigger_val)
49 char sysfs_path[PATH_MAX];
51 sprintf(sysfs_path, TRIGGER_PATH, dev_num);
53 return sysfs_write_str(sysfs_path, trigger_val);
57 void build_sensor_report_maps(int dev_num)
60 * Read sysfs files from a iio device's scan_element directory, and
61 * build a couple of tables from that data. These tables will tell, for
62 * each sensor, where to gather relevant data in a device report, i.e.
63 * the structure that we read from the /dev/iio:deviceX file in order to
64 * sensor report, itself being the data that we return to Android when a
65 * sensor poll completes. The mapping should be straightforward in the
66 * case where we have a single sensor active per iio device but, this is
67 * not the general case. In general several sensors can be handled
68 * through a single iio device, and the _en, _index and _type syfs
69 * entries all concur to paint a picture of what the structure of the
79 char spec_buf[MAX_TYPE_SPEC_LEN];
80 struct datum_info_t* ch_info;
82 char sysfs_path[PATH_MAX];
85 int channel_size_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
86 int sensor_handle_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
87 int channel_number_from_index[MAX_SENSORS * MAX_CHANNELS] = { 0 };
91 /* For each sensor that is linked to this device */
92 for (s=0; s<sensor_count; s++) {
93 if (sensor_info[s].dev_num != dev_num)
96 i = sensor_info[s].catalog_index;
98 /* Read channel details through sysfs attributes */
99 for (c=0; c<sensor_info[s].num_channels; c++) {
101 /* Read _type file */
102 sprintf(sysfs_path, CHANNEL_PATH "%s",
103 sensor_info[s].dev_num,
104 sensor_catalog[i].channel[c].type_path);
106 n = sysfs_read_str(sysfs_path, spec_buf,
110 ALOGW( "Failed to read type: %s\n",
115 ch_spec = sensor_info[s].channel[c].type_spec;
117 memcpy(ch_spec, spec_buf, sizeof(spec_buf));
119 ch_info = &sensor_info[s].channel[c].type_info;
121 size = decode_type_spec(ch_spec, ch_info);
123 /* Read _index file */
124 sprintf(sysfs_path, CHANNEL_PATH "%s",
125 sensor_info[s].dev_num,
126 sensor_catalog[i].channel[c].index_path);
128 n = sysfs_read_int(sysfs_path, &ch_index);
131 ALOGW( "Failed to read index: %s\n",
136 if (ch_index >= MAX_SENSORS) {
137 ALOGE("Index out of bounds!: %s\n", sysfs_path);
141 /* Record what this index is about */
143 sensor_handle_from_index [ch_index] = s;
144 channel_number_from_index[ch_index] = c;
145 channel_size_from_index [ch_index] = size;
150 /* Turn on channels we're aware of */
151 for (c=0;c<sensor_info[s].num_channels; c++) {
152 sprintf(sysfs_path, CHANNEL_PATH "%s",
153 sensor_info[s].dev_num,
154 sensor_catalog[i].channel[c].en_path);
156 sysfs_write_int(sysfs_path, 1);
160 ALOGI("Found %d channels on iio device %d\n", known_channels, dev_num);
163 * Now that we know which channels are defined, their sizes and their
164 * ordering, update channels offsets within device report. Note: there
165 * is a possibility that several sensors share the same index, with
166 * their data fields being isolated by masking and shifting as specified
167 * through the real bits and shift values in type attributes. This case
168 * is not currently supported. Also, the code below assumes no hole in
169 * the sequence of indices, so it is dependent on discovery of all
173 for (i=0; i<MAX_SENSORS * MAX_CHANNELS; i++) {
174 s = sensor_handle_from_index[i];
175 c = channel_number_from_index[i];
176 size = channel_size_from_index[i];
181 ALOGI("S%d C%d : offset %d, size %d, type %s\n",
182 s, c, offset, size, sensor_info[s].channel[c].type_spec);
184 sensor_info[s].channel[c].offset = offset;
185 sensor_info[s].channel[c].size = size;
192 int adjust_counters (int s, int enabled)
195 * Adjust counters based on sensor enable action. Return values are:
196 * -1 if there's an inconsistency: abort action in this case
197 * 0 if the operation was completed and we're all set
198 * 1 if we toggled the state of the sensor and there's work left
201 int dev_num = sensor_info[s].dev_num;
202 int catalog_index = sensor_info[s].catalog_index;
203 int sensor_type = sensor_catalog[catalog_index].type;
205 /* Refcount per sensor, in terms of enable count */
207 ALOGI("Enabling sensor %d (iio device %d: %s)\n",
208 s, dev_num, sensor_info[s].friendly_name);
210 sensor_info[s].enable_count++;
212 if (sensor_info[s].enable_count != 1) {
213 return 0; /* The sensor was, and remains, in use */
215 if (sensor_type == SENSOR_TYPE_MAGNETIC_FIELD)
216 compass_read_data(COMPASS_CALIBRATION_PATH);
218 if (sensor_type == SENSOR_TYPE_GYROSCOPE)
219 gyro_cal_init(&sensor_info[s]);
222 if (sensor_info[s].enable_count == 0)
223 return -1; /* Spurious disable call */
225 ALOGI("Disabling sensor %d (iio device %d: %s)\n", s, dev_num,
226 sensor_info[s].friendly_name);
228 if (sensor_type == SENSOR_TYPE_MAGNETIC_FIELD)
229 compass_store_data(COMPASS_CALIBRATION_PATH);
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 device_name[PATH_MAX];
268 char trigger_name[MAX_NAME_SIZE + 16];
270 struct epoll_event ev = {0};
273 int dev_num = sensor_info[s].dev_num;
274 int i = sensor_info[s].catalog_index;
275 int is_poll_sensor = !sensor_info[s].num_channels;
277 ret = adjust_counters(s, enabled);
279 /* If the operation was neutral in terms of state, we're done */
283 if (!is_poll_sensor) {
286 enable_buffer(dev_num, 0);
287 setup_trigger(dev_num, "\n");
289 /* If there's at least one sensor enabled on this iio device */
290 if (trig_sensors_per_dev[dev_num]) {
291 sprintf(trigger_name, "%s-dev%d",
292 sensor_info[s].internal_name, dev_num);
295 setup_trigger(dev_num, trigger_name);
296 enable_buffer(dev_num, 1);
301 * Make sure we have a fd on the character device ; conversely, close
302 * the fd if no one is using associated sensor anymore. The assumption
303 * here is that the underlying driver will power on the relevant
304 * hardware block while someone hold a fd on the device.
306 dev_fd = device_fd[dev_num];
309 if (dev_fd != -1 && !poll_sensors_per_dev[dev_num] &&
310 !trig_sensors_per_dev[dev_num]) {
312 * Stop watching this fd. This should be a no-op
313 * in case this fd was not in the poll set.
315 epoll_ctl(poll_fd, EPOLL_CTL_DEL, dev_fd, NULL);
318 device_fd[dev_num] = -1;
324 /* First enabled sensor on this iio device */
325 sprintf(device_name, DEV_FILE_PATH, dev_num);
326 dev_fd = open(device_name, O_RDONLY | O_NONBLOCK);
328 device_fd[dev_num] = dev_fd;
331 ALOGE("Could not open fd on %s (%s)\n",
332 device_name, strerror(errno));
333 adjust_counters(s, 0);
337 ALOGV("Opened %s: fd=%d\n", device_name, dev_fd);
339 if (!is_poll_sensor) {
341 /* Add this iio device fd to the set of watched fds */
343 ev.data.u32 = dev_num;
345 ret = epoll_ctl(poll_fd, EPOLL_CTL_ADD, dev_fd, &ev);
348 ALOGE( "Failed adding %d to poll set (%s)\n",
349 dev_fd, strerror(errno));
353 /* Note: poll-mode fds are not readable */
357 /* Release the polling loop so an updated timeout gets used */
358 write(poll_socket_pair[1], "", 1);
364 static int integrate_device_report(int dev_num)
368 unsigned char buf[MAX_SENSOR_REPORT_SIZE] = { 0 };
370 unsigned char *target;
371 unsigned char *source;
375 /* There's an incoming report on the specified fd */
377 if (dev_num < 0 || dev_num >= MAX_DEVICES) {
378 ALOGE("Event reported on unexpected iio device %d\n", dev_num);
382 if (device_fd[dev_num] == -1) {
383 ALOGE("Ignoring stale report on iio device %d\n", dev_num);
387 ts = get_timestamp();
389 len = read(device_fd[dev_num], buf, MAX_SENSOR_REPORT_SIZE);
392 ALOGE("Could not read report from iio device %d (%s)\n",
393 dev_num, strerror(errno));
397 ALOGV("Read %d bytes from iio device %d\n", len, dev_num);
399 for (s=0; s<MAX_SENSORS; s++)
400 if (sensor_info[s].dev_num == dev_num &&
401 sensor_info[s].enable_count) {
405 /* Copy data from device to sensor report buffer */
406 for (c=0; c<sensor_info[s].num_channels; c++) {
408 target = sensor_info[s].report_buffer +
411 source = buf + sensor_info[s].channel[c].offset;
413 size = sensor_info[s].channel[c].size;
415 memcpy(target, source, size);
420 ALOGV("Sensor %d report available (%d bytes)\n", s,
423 sensor_info[s].report_ts = ts;
424 sensor_info[s].report_pending = 1;
431 static void propagate_sensor_report(int s, struct sensors_event_t* data)
433 /* There's a sensor report pending for this sensor ; transmit it */
435 int catalog_index = sensor_info[s].catalog_index;
436 int sensor_type = sensor_catalog[catalog_index].type;
439 unsigned char* current_sample;
440 int64_t current_ts = get_timestamp();
442 memset(data, 0, sizeof(sensors_event_t));
444 data->version = sizeof(sensors_event_t);
446 data->type = sensor_type;
448 if (sensor_info[s].report_ts)
449 data->timestamp = sensor_info[s].report_ts;
451 data->timestamp = current_ts;
453 switch (sensor_type) {
454 case SENSOR_TYPE_ACCELEROMETER: /* m/s^2 */
455 case SENSOR_TYPE_MAGNETIC_FIELD: /* micro-tesla */
456 case SENSOR_TYPE_ORIENTATION: /* degrees */
457 case SENSOR_TYPE_GYROSCOPE: /* radians/s */
461 case SENSOR_TYPE_LIGHT: /* SI lux units */
462 case SENSOR_TYPE_AMBIENT_TEMPERATURE: /* °C */
463 case SENSOR_TYPE_TEMPERATURE: /* °C */
464 case SENSOR_TYPE_PROXIMITY: /* centimeters */
465 case SENSOR_TYPE_PRESSURE: /* hecto-pascal */
466 case SENSOR_TYPE_RELATIVE_HUMIDITY: /* percent */
470 case SENSOR_TYPE_ROTATION_VECTOR:
474 case SENSOR_TYPE_DEVICE_PRIVATE_BASE: /* hidden for now */
479 ALOGE("Unknown sensor type!\n");
484 ALOGV("Sample on sensor %d (type %d):\n", s, sensor_type);
486 /* Take note of current time counter value for rate control purposes */
487 sensor_info[s].last_integration_ts = current_ts;
489 /* If we're dealing with a poll-mode sensor */
490 if (!sensor_info[s].num_channels) {
492 /* Read values through sysfs rather than from a report buffer */
493 for (c=0; c<num_fields; c++) {
495 data->data[c] = acquire_immediate_value(s, c);
497 ALOGV("\tfield %d: %f\n", c, data->data[c]);
500 sensor_info[s].ops.finalize(s, data);
504 /* Convert the data into the expected Android-level format */
506 current_sample = sensor_info[s].report_buffer;
508 for (c=0; c<num_fields; c++) {
510 data->data[c] = sensor_info[s].ops.transform
511 (s, c, current_sample);
513 ALOGV("\tfield %d: %f\n", c, data->data[c]);
514 current_sample += sensor_info[s].channel[c].size;
517 sensor_info[s].ops.finalize(s, data);
521 static int get_poll_time (void)
524 int64_t lowest_target_ts;
528 if (!active_poll_sensors)
529 return -1; /* Infinite wait */
531 /* Check if we should schedule a poll-mode sensor event delivery */
533 lowest_target_ts = INT64_MAX;
535 for (s=0; s<sensor_count; s++)
536 if (sensor_info[s].enable_count &&
537 sensor_info[s].sampling_rate &&
538 !sensor_info[s].num_channels) {
539 target_ts = sensor_info[s].last_integration_ts +
540 1000000000LL/sensor_info[s].sampling_rate;
542 if (target_ts < lowest_target_ts)
543 lowest_target_ts = target_ts;
546 if (lowest_target_ts == INT64_MAX)
549 current_ts = get_timestamp();
551 if (lowest_target_ts <= current_ts)
554 return (lowest_target_ts - current_ts)/1000000; /* ms */
558 static void acknowledge_release (void)
560 /* A write to our socket circuit was performed to release epoll */
562 read(poll_socket_pair[0], &buf, 1);
566 int sensor_poll(struct sensors_event_t* data, int count)
572 struct epoll_event ev[MAX_DEVICES];
575 /* Get one or more events from our collection of sensors */
577 return_first_available_sensor_report:
579 /* If there's at least one available report */
580 for (s=0; s<sensor_count; s++)
581 if (sensor_info[s].report_pending) {
584 propagate_sensor_report(s, data);
585 sensor_info[s].report_pending = 0;
586 ALOGV("Report on sensor %d\n", s);
591 ALOGV("Awaiting sensor data\n");
593 nfds = epoll_wait(poll_fd, ev, MAX_DEVICES, get_poll_time());
595 last_poll_exit_ts = get_timestamp();
598 ALOGI("epoll_wait returned -1 (%s)\n", strerror(errno));
602 ALOGV("%d fds signalled\n", nfds);
604 /* For each of the devices for which a report is available */
605 for (i=0; i<nfds; i++)
606 if (ev[i].events == EPOLLIN) {
607 if (ev[i].data.u32 == INVALID_DEV_NUM) {
608 acknowledge_release();
612 integrate_device_report(ev[i].data.u32);
615 /* Check poll-mode sensors and fire up an event if it's time to do so */
616 if (active_poll_sensors)
617 for (s=0; s<sensor_count; s++)
618 if (sensor_info[s].enable_count &&
619 !sensor_info[s].num_channels &&
620 sensor_info[s].sampling_rate) {
621 target_ts = sensor_info[s].last_integration_ts +
622 1000000000LL/sensor_info[s].sampling_rate;
624 if (last_poll_exit_ts >= target_ts)
625 sensor_info[s].report_pending = 1;
628 goto return_first_available_sensor_report;
632 int sensor_set_delay(int s, int64_t ns)
634 /* Set the rate at which a specific sensor should report events */
636 /* See Android sensors.h for indication on sensor trigger modes */
638 char sysfs_path[PATH_MAX];
639 char avail_sysfs_path[PATH_MAX];
640 int dev_num = sensor_info[s].dev_num;
641 int i = sensor_info[s].catalog_index;
642 const char *prefix = sensor_catalog[i].tag;
643 int new_sampling_rate; /* Granted sampling rate after arbitration */
644 int cur_sampling_rate; /* Currently used sampling rate */
645 int req_sampling_rate; /* Requested ; may be different from granted */
646 int per_sensor_sampling_rate;
647 int per_device_sampling_rate;
648 int max_supported_rate = 0;
655 ALOGE("Rejecting zero delay request on sensor %d\n", s);
659 new_sampling_rate = req_sampling_rate = (int) (1000000000L/ns);
661 if (!new_sampling_rate) {
662 ALOGI("Sub-HZ sampling rate requested on on sensor %d\n", s);
663 new_sampling_rate = 1;
666 sensor_info[s].sampling_rate = new_sampling_rate;
668 /* If we're dealing with a poll-mode sensor, release poll and return */
669 if (!sensor_info[s].num_channels)
672 sprintf(sysfs_path, SENSOR_SAMPLING_PATH, dev_num, prefix);
674 if (sysfs_read_int(sysfs_path, &cur_sampling_rate) != -1) {
675 per_sensor_sampling_rate = 1;
676 per_device_sampling_rate = 0;
678 per_sensor_sampling_rate = 0;
680 sprintf(sysfs_path, DEVICE_SAMPLING_PATH, dev_num);
682 if (sysfs_read_int(sysfs_path, &cur_sampling_rate) != -1)
683 per_device_sampling_rate = 1;
685 per_device_sampling_rate = 0;
688 if (!per_sensor_sampling_rate && !per_device_sampling_rate) {
689 ALOGE("No way to adjust sampling rate on sensor %d\n", s);
693 /* Coordinate with others active sensors on the same device, if any */
694 if (per_device_sampling_rate)
695 for (n=0; n<sensor_count; n++)
696 if (n != s && sensor_info[n].dev_num == dev_num &&
697 sensor_info[n].num_channels &&
698 sensor_info[n].enable_count &&
699 sensor_info[n].sampling_rate > new_sampling_rate)
700 new_sampling_rate= sensor_info[n].sampling_rate;
702 /* Check if we have contraints on allowed sampling rates */
704 sprintf(avail_sysfs_path, DEVICE_AVAIL_FREQ_PATH, dev_num);
706 if (sysfs_read_str(avail_sysfs_path, freqs_buf, sizeof(freqs_buf)) > 0){
709 /* Decode allowed sampling rates string, ex: "10 20 50 100" */
711 /* While we're not at the end of the string */
712 while (*cursor && cursor[0]) {
714 /* Decode a single integer value */
717 if (n > max_supported_rate)
718 max_supported_rate = n;
720 /* If this matches the selected rate, we're happy */
721 if (new_sampling_rate == n)
725 * If we reached a higher value than the desired rate,
726 * adjust selected rate so it matches the first higher
727 * available one and stop parsing - this makes the
728 * assumption that rates are sorted by increasing value
729 * in the allowed frequencies string.
731 if (n > new_sampling_rate) {
733 "Increasing sampling rate on sensor %d from %d to %d\n",
734 s, req_sampling_rate, n);
736 new_sampling_rate = n;
741 while (cursor[0] && !isspace(cursor[0]))
745 while (cursor[0] && isspace(cursor[0]))
750 /* Cap sampling rate at 1000 events per second for now*/
754 if (max_supported_rate && new_sampling_rate > max_supported_rate)
755 limit = max_supported_rate;
757 if (new_sampling_rate > limit) {
759 new_sampling_rate = limit;
761 ALOGI( "Can't support %d sampling rate, lowering to %d\n",
762 req_sampling_rate, new_sampling_rate);
765 /* If the desired rate is already active we're all set */
766 if (new_sampling_rate == cur_sampling_rate)
769 ALOGI("Sensor %d sampling rate switched to %d\n", s, new_sampling_rate);
771 if (trig_sensors_per_dev[dev_num])
772 enable_buffer(dev_num, 0);
774 sysfs_write_int(sysfs_path, new_sampling_rate);
776 if (trig_sensors_per_dev[dev_num])
777 enable_buffer(dev_num, 1);
780 /* Release the polling loop so an updated timeout value gets used */
781 write(poll_socket_pair[1], "", 1);
788 int allocate_control_data (void)
791 struct epoll_event ev = {0};
793 for (i=0; i<MAX_DEVICES; i++)
796 poll_fd = epoll_create(MAX_DEVICES);
799 ALOGE("Can't create epoll instance for iio sensors!\n");
803 /* Create and add "unblocking" fd to the set of watched fds */
805 if (socketpair(AF_UNIX, SOCK_STREAM, 0, poll_socket_pair) == -1) {
806 ALOGE("Can't create socket pair for iio sensors!\n");
812 ev.data.u32 = INVALID_DEV_NUM;
814 epoll_ctl(poll_fd, EPOLL_CTL_ADD, poll_socket_pair[0], &ev);
820 void delete_control_data (void)