OSDN Git Service

GMINL-7944: Ignore ALS intensity if illuminance is available
[android-x86/hardware-intel-libsensors.git] / enumeration.c
1 /*
2  * Copyright (C) 2014-2015 Intel Corporation.
3  */
4
5 #include <ctype.h>
6 #include <dirent.h>
7 #include <stdlib.h>
8 #include <fcntl.h>
9 #include <utils/Log.h>
10 #include <hardware/sensors.h>
11 #include "enumeration.h"
12 #include "description.h"
13 #include "utils.h"
14 #include "transform.h"
15 #include "description.h"
16 #include "control.h"
17 #include "calibration.h"
18
19 /*
20  * This table maps syfs entries in scan_elements directories to sensor types,
21  * and will also be used to determine other sysfs names as well as the iio
22  * device number associated to a specific sensor.
23  */
24
25  /*
26   * We duplicate entries for the uncalibrated types after their respective base
27   * sensor. This is because all sensor entries must have an associated catalog entry
28   * and also because when only the uncal sensor is active it needs to take it's data
29   * from the same iio device as the base one.
30   */
31
32 sensor_catalog_entry_t sensor_catalog[] = {
33         {
34                 .tag            = "accel",
35                 .type           = SENSOR_TYPE_ACCELEROMETER,
36                 .num_channels   = 3,
37                 .is_virtual     = 0,
38                 .channel = {
39                         { DECLARE_NAMED_CHANNEL("accel", "x") },
40                         { DECLARE_NAMED_CHANNEL("accel", "y") },
41                         { DECLARE_NAMED_CHANNEL("accel", "z") },
42                 },
43         },
44         {
45                 .tag            = "anglvel",
46                 .type           = SENSOR_TYPE_GYROSCOPE,
47                 .num_channels   = 3,
48                 .is_virtual     = 0,
49                 .channel = {
50                         { DECLARE_NAMED_CHANNEL("anglvel", "x") },
51                         { DECLARE_NAMED_CHANNEL("anglvel", "y") },
52                         { DECLARE_NAMED_CHANNEL("anglvel", "z") },
53                 },
54         },
55         {
56                 .tag            = "magn",
57                 .type           = SENSOR_TYPE_MAGNETIC_FIELD,
58                 .num_channels   = 3,
59                 .is_virtual     = 0,
60                 .channel = {
61                         { DECLARE_NAMED_CHANNEL("magn", "x") },
62                         { DECLARE_NAMED_CHANNEL("magn", "y") },
63                         { DECLARE_NAMED_CHANNEL("magn", "z") },
64                 },
65         },
66         {
67                 .tag            = "intensity",
68                 .type           = SENSOR_TYPE_INTERNAL_INTENSITY,
69                 .num_channels   = 1,
70                 .is_virtual     = 0,
71                 .channel = {
72                         { DECLARE_NAMED_CHANNEL("intensity", "both") },
73                 },
74         },
75         {
76                 .tag            = "illuminance",
77                 .type           = SENSOR_TYPE_INTERNAL_ILLUMINANCE,
78                 .num_channels   = 1,
79                 .is_virtual     = 0,
80                 .channel = {
81                         { DECLARE_GENERIC_CHANNEL("illuminance") },
82                 },
83         },
84         {
85                 .tag            = "incli",
86                 .type           = SENSOR_TYPE_ORIENTATION,
87                 .num_channels   = 3,
88                 .is_virtual     = 0,
89                 .channel = {
90                         { DECLARE_NAMED_CHANNEL("incli", "x") },
91                         { DECLARE_NAMED_CHANNEL("incli", "y") },
92                         { DECLARE_NAMED_CHANNEL("incli", "z") },
93                 },
94         },
95         {
96                 .tag            = "rot",
97                 .type           = SENSOR_TYPE_ROTATION_VECTOR,
98                 .num_channels   = 4,
99                 .is_virtual     = 0,
100                 .channel = {
101                         { DECLARE_NAMED_CHANNEL("rot", "quat_x") },
102                         { DECLARE_NAMED_CHANNEL("rot", "quat_y") },
103                         { DECLARE_NAMED_CHANNEL("rot", "quat_z") },
104                         { DECLARE_NAMED_CHANNEL("rot", "quat_w") },
105                 },
106         },
107         {
108                 .tag            = "temp",
109                 .type           = SENSOR_TYPE_AMBIENT_TEMPERATURE,
110                 .num_channels   = 1,
111                 .is_virtual     = 0,
112                 .channel = {
113                         { DECLARE_GENERIC_CHANNEL("temp") },
114                 },
115         },
116         {
117                 .tag            = "proximity",
118                 .type           = SENSOR_TYPE_PROXIMITY,
119                 .num_channels   = 1,
120                 .is_virtual     = 0,
121                 .channel = {
122                         { DECLARE_GENERIC_CHANNEL("proximity") },
123                 },
124         },
125         {
126                 .tag            = "",
127                 .type           = SENSOR_TYPE_GYROSCOPE_UNCALIBRATED,
128                 .num_channels   = 0,
129                 .is_virtual     = 1,
130                 .channel = {
131                         { DECLARE_GENERIC_CHANNEL("") },
132                 },
133
134         },
135         {
136                 .tag            = "",
137                 .type           = SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED,
138                 .num_channels   = 0,
139                 .is_virtual     = 1,
140                 .channel = {
141                         { DECLARE_GENERIC_CHANNEL("") },
142                 },
143         },
144         {
145                 .tag            = "steps",
146                 .type           = SENSOR_TYPE_STEP_COUNTER,
147                 .num_channels   = 1,
148                 .is_virtual     = 0,
149                 .channel = {
150                         { DECLARE_GENERIC_CHANNEL("steps") },
151                 },
152         },
153         {
154                 .tag            = "steps",
155                 .type           = SENSOR_TYPE_STEP_DETECTOR,
156                 .num_channels   = 1,
157                 .is_virtual     = 0,
158                 .channel = {
159                         {
160                                 DECLARE_VOID_CHANNEL("steps")
161                                 .num_events = 1,
162                                 .event = {
163                                         { DECLARE_NAMED_EVENT("steps", "change") },
164                                 },
165                         },
166                 },
167         },
168         {
169                 .tag            = "proximity",
170                 .type           = SENSOR_TYPE_PROXIMITY,
171                 .num_channels   = 4,
172                 .is_virtual     = 0,
173                 .channel = {
174                         {
175                                 DECLARE_VOID_CHANNEL("proximity0")
176                                 .num_events = 1,
177                                 .event = {
178                                         { DECLARE_EVENT("proximity0", "_", "", "", "thresh", "_", "either") },
179                                 },
180                         },
181                         {
182                                 DECLARE_VOID_CHANNEL("proximity1")
183                                 .num_events = 1,
184                                 .event = {
185                                         { DECLARE_EVENT("proximity1", "_", "", "", "thresh", "_", "either") },
186                                 },
187                         },
188                         {
189                                 DECLARE_VOID_CHANNEL("proximity2")
190                                 .num_events = 1,
191                                 .event = {
192                                         { DECLARE_EVENT("proximity2", "_", "", "", "thresh", "_", "either") },
193                                 },
194                         },
195                         {
196                                 DECLARE_VOID_CHANNEL("proximity3")
197                                 .num_events = 1,
198                                 .event = {
199                                         { DECLARE_EVENT("proximity3", "_", "", "", "thresh", "_", "either") },
200                                 },
201                         },
202                 },
203         },
204 };
205
206 unsigned int catalog_size = ARRAY_SIZE(sensor_catalog);
207
208 /* ACPI PLD (physical location of device) definitions, as used with sensors */
209
210 #define PANEL_FRONT     4
211 #define PANEL_BACK      5
212
213 /* We equate sensor handles to indices in these tables */
214
215 struct sensor_t sensor_desc[MAX_SENSORS];       /* Android-level descriptors */
216 sensor_info_t   sensor[MAX_SENSORS];            /* Internal descriptors      */
217 int             sensor_count;                   /* Detected sensors          */
218
219
220 /* if the sensor has an _en attribute, we need to enable it */
221 int get_needs_enable(int dev_num, const char *tag)
222 {
223         char sysfs_path[PATH_MAX];
224         int fd;
225
226         sprintf(sysfs_path, SENSOR_ENABLE_PATH, dev_num, tag);
227
228         fd = open(sysfs_path, O_RDWR);
229         if (fd == -1)
230                 return 0;
231
232         close(fd);
233         return 1;
234 }
235
236 static void setup_properties_from_pld (int s, int panel, int rotation,
237                                        int num_channels)
238 {
239         /*
240          * Generate suitable order and opt_scale directives from the PLD panel
241          * and rotation codes we got. This can later be superseded by the usual
242          * properties if necessary. Eventually we'll need to replace these
243          * mechanisms by a less convoluted one, such as a 3x3 placement matrix.
244          */
245
246         int x = 1;
247         int y = 1;
248         int z = 1;
249         int xy_swap = 0;
250         int angle = rotation * 45;
251
252         /* Only deal with 3 axis chips for now */
253         if (num_channels < 3)
254                 return;
255
256         if (panel == PANEL_BACK) {
257                 /* Chip placed on the back panel ; negate x and z */
258                 x = -x;
259                 z = -z;
260         }
261
262         switch (angle) {
263                 case 90: /* 90° clockwise: negate y then swap x,y */
264                         xy_swap = 1;
265                         y = -y;
266                         break;
267
268                 case 180: /* Upside down: negate x and y */
269                         x = -x;
270                         y = -y;
271                         break;
272
273                 case 270: /* 90° counter clockwise: negate x then swap x,y */
274                         x = -x;
275                         xy_swap = 1;
276                         break;
277         }
278
279         if (xy_swap) {
280                 sensor[s].order[0] = 1;
281                 sensor[s].order[1] = 0;
282                 sensor[s].order[2] = 2;
283                 sensor[s].quirks |= QUIRK_FIELD_ORDERING;
284         }
285
286         sensor[s].channel[0].opt_scale = x;
287         sensor[s].channel[1].opt_scale = y;
288         sensor[s].channel[2].opt_scale = z;
289 }
290
291
292 static int is_valid_pld (int panel, int rotation)
293 {
294         if (panel != PANEL_FRONT && panel != PANEL_BACK) {
295                 ALOGW("Unhandled PLD panel spec: %d\n", panel);
296                 return 0;
297         }
298
299         /* Only deal with 90° rotations for now */
300         if (rotation < 0 || rotation > 7 || (rotation & 1)) {
301                 ALOGW("Unhandled PLD rotation spec: %d\n", rotation);
302                 return 0;
303         }
304
305         return 1;
306 }
307
308
309 static int read_pld_from_properties (int s, int* panel, int* rotation)
310 {
311         int p, r;
312
313         if (sensor_get_prop(s, "panel", &p))
314                 return -1;
315
316         if (sensor_get_prop(s, "rotation", &r))
317                 return -1;
318
319         if (!is_valid_pld(p, r))
320                 return -1;
321
322         *panel = p;
323         *rotation = r;
324
325         ALOGI("S%d PLD from properties: panel=%d, rotation=%d\n", s, p, r);
326
327         return 0;
328 }
329
330
331 static int read_pld_from_sysfs (int s, int dev_num, int* panel, int* rotation)
332 {
333         char sysfs_path[PATH_MAX];
334         int p,r;
335
336         sprintf(sysfs_path, BASE_PATH "../firmware_node/pld/panel", dev_num);
337
338         if (sysfs_read_int(sysfs_path, &p))
339                 return -1;
340
341         sprintf(sysfs_path, BASE_PATH "../firmware_node/pld/rotation", dev_num);
342
343         if (sysfs_read_int(sysfs_path, &r))
344                 return -1;
345
346         if (!is_valid_pld(p, r))
347                 return -1;
348
349         *panel = p;
350         *rotation = r;
351
352         ALOGI("S%d PLD from sysfs: panel=%d, rotation=%d\n", s, p, r);
353
354         return 0;
355 }
356
357
358 static void decode_placement_information (int dev_num, int num_channels, int s)
359 {
360         /*
361          * See if we have optional "physical location of device" ACPI tags.
362          * We're only interested in panel and rotation specifiers. Use the
363          * .panel and .rotation properties in priority, and the actual ACPI
364          * values as a second source.
365          */
366
367         int panel;
368         int rotation;
369
370         if (read_pld_from_properties(s, &panel, &rotation) &&
371                 read_pld_from_sysfs(s, dev_num, &panel, &rotation))
372                         return; /* No PLD data available */
373
374         /* Map that to field ordering and scaling mechanisms */
375         setup_properties_from_pld(s, panel, rotation, num_channels);
376 }
377
378
379 static int map_internal_to_external_type (int sensor_type)
380 {
381         /* Most sensors are internally identified using the Android type, but for some we use a different type specification internally */
382
383         switch (sensor_type) {
384                 case SENSOR_TYPE_INTERNAL_ILLUMINANCE:
385                 case SENSOR_TYPE_INTERNAL_INTENSITY:
386                         return SENSOR_TYPE_LIGHT;
387
388                 default:
389                         return sensor_type;
390         }
391 }
392
393 static void populate_descriptors (int s, int sensor_type)
394 {
395         int32_t         min_delay_us;
396         max_delay_t     max_delay_us;
397
398         /* Initialize Android-visible descriptor */
399         sensor_desc[s].name             = sensor_get_name(s);
400         sensor_desc[s].vendor           = sensor_get_vendor(s);
401         sensor_desc[s].version          = sensor_get_version(s);
402         sensor_desc[s].handle           = s;
403         sensor_desc[s].type             = map_internal_to_external_type(sensor_type);
404
405         sensor_desc[s].maxRange         = sensor_get_max_range(s);
406         sensor_desc[s].resolution       = sensor_get_resolution(s);
407         sensor_desc[s].power            = sensor_get_power(s);
408         sensor_desc[s].stringType       = sensor_get_string_type(s);
409
410         /* None of our supported sensors requires a special permission */
411         sensor_desc[s].requiredPermission = "";
412
413         sensor_desc[s].flags = sensor_get_flags(s);
414         sensor_desc[s].minDelay = sensor_get_min_delay(s);
415         sensor_desc[s].maxDelay = sensor_get_max_delay(s);
416
417         ALOGV("Sensor %d (%s) type(%d) minD(%d) maxD(%d) flags(%2.2x)\n",
418                 s, sensor[s].friendly_name, sensor_desc[s].type,
419                 sensor_desc[s].minDelay, sensor_desc[s].maxDelay,
420                 sensor_desc[s].flags);
421
422         /* We currently do not implement batching */
423         sensor_desc[s].fifoReservedEventCount = 0;
424         sensor_desc[s].fifoMaxEventCount = 0;
425
426         min_delay_us = sensor_desc[s].minDelay;
427         max_delay_us = sensor_desc[s].maxDelay;
428
429         sensor[s].min_supported_rate = max_delay_us ? 1000000.0 / max_delay_us : 1;
430         sensor[s].max_supported_rate = min_delay_us && min_delay_us != -1 ? 1000000.0 / min_delay_us : 0;
431 }
432
433
434 static void add_virtual_sensor (int catalog_index)
435 {
436         int s;
437         int sensor_type;
438
439         if (sensor_count == MAX_SENSORS) {
440                 ALOGE("Too many sensors!\n");
441                 return;
442         }
443
444         sensor_type = sensor_catalog[catalog_index].type;
445
446         s = sensor_count;
447
448         sensor[s].is_virtual = 1;
449         sensor[s].catalog_index = catalog_index;
450         sensor[s].type          = sensor_type;
451
452         populate_descriptors(s, sensor_type);
453
454         /* Initialize fields related to sysfs reads offloading */
455         sensor[s].thread_data_fd[0]  = -1;
456         sensor[s].thread_data_fd[1]  = -1;
457         sensor[s].acquisition_thread = -1;
458
459         sensor_count++;
460 }
461
462
463 static int add_sensor (int dev_num, int catalog_index, int mode)
464 {
465         int s;
466         int sensor_type;
467         int retval;
468         char sysfs_path[PATH_MAX];
469         const char* prefix;
470         float scale;
471         int c;
472         float opt_scale;
473         const char* ch_name;
474         int num_channels;
475         char suffix[MAX_NAME_SIZE + 8];
476         int calib_bias;
477
478         if (sensor_count == MAX_SENSORS) {
479                 ALOGE("Too many sensors!\n");
480                 return -1;
481         }
482
483         sensor_type = sensor_catalog[catalog_index].type;
484
485         /*
486          * At this point we could check that the expected sysfs attributes are
487          * present ; that would enable having multiple catalog entries with the
488          * same sensor type, accomodating different sets of sysfs attributes.
489          */
490
491         s = sensor_count;
492
493         sensor[s].dev_num       = dev_num;
494         sensor[s].catalog_index = catalog_index;
495         sensor[s].type          = sensor_type;
496         sensor[s].mode          = mode;
497
498         num_channels = sensor_catalog[catalog_index].num_channels;
499
500         if (mode == MODE_POLL)
501                 sensor[s].num_channels = 0;
502         else
503                 sensor[s].num_channels = num_channels;
504
505         /* Populate the quirks array */
506         sensor_get_quirks(s);
507
508         /* Reject interfaces that may have been disabled through a quirk for this driver */
509         if ((mode == MODE_EVENT   && (sensor[s].quirks & QUIRK_NO_EVENT_MODE)) ||
510             (mode == MODE_TRIGGER && (sensor[s].quirks & QUIRK_NO_TRIG_MODE )) ||
511             (mode == MODE_POLL    && (sensor[s].quirks & QUIRK_NO_POLL_MODE ))) {
512                 memset(&sensor[s], 0, sizeof(sensor[0]));
513                 return -1;
514         }
515
516         prefix = sensor_catalog[catalog_index].tag;
517
518         /*
519          * receiving the illumination sensor calibration inputs from
520          * the Android properties and setting it within sysfs
521          */
522         if (sensor_type == SENSOR_TYPE_INTERNAL_ILLUMINANCE) {
523                 retval = sensor_get_illumincalib(s);
524                 if (retval > 0) {
525                         sprintf(sysfs_path, ILLUMINATION_CALIBPATH, dev_num);
526                         sysfs_write_int(sysfs_path, retval);
527                 }
528         }
529
530         /*
531          * See if we have optional calibration biases for each of the channels of this sensor. These would be expressed using properties like
532          * iio.accel.y.calib_bias = -1, or possibly something like iio.temp.calib_bias if the sensor has a single channel. This value gets stored in the
533          * relevant calibbias sysfs file if that file can be located and then used internally by the iio sensor driver.
534          */
535
536         if (num_channels) {
537                 for (c = 0; c < num_channels; c++) {
538                         ch_name = sensor_catalog[catalog_index].channel[c].name;
539                         sprintf(suffix, "%s.calib_bias", ch_name);
540                         if (!sensor_get_prop(s, suffix, &calib_bias) && calib_bias) {
541                                 sprintf(suffix, "%s_%s", prefix, sensor_catalog[catalog_index].channel[c].name);
542                                 sprintf(sysfs_path, SENSOR_CALIB_BIAS_PATH, dev_num, suffix);
543                                 sysfs_write_int(sysfs_path, calib_bias);
544                         }
545                 }
546         } else
547                 if (!sensor_get_prop(s, "calib_bias", &calib_bias) && calib_bias) {
548                                 sprintf(sysfs_path, SENSOR_CALIB_BIAS_PATH, dev_num, prefix);
549                                 sysfs_write_int(sysfs_path, calib_bias);
550                         }
551
552         /* Read name attribute, if available */
553         sprintf(sysfs_path, NAME_PATH, dev_num);
554         sysfs_read_str(sysfs_path, sensor[s].internal_name, MAX_NAME_SIZE);
555
556         /* See if we have general offsets and scale values for this sensor */
557
558         sprintf(sysfs_path, SENSOR_OFFSET_PATH, dev_num, prefix);
559         sysfs_read_float(sysfs_path, &sensor[s].offset);
560
561         sprintf(sysfs_path, SENSOR_SCALE_PATH, dev_num, prefix);
562         if (!sensor_get_fl_prop(s, "scale", &scale)) {
563                 /*
564                  * There is a chip preferred scale specified,
565                  * so try to store it in sensor's scale file
566                  */
567                 if (sysfs_write_float(sysfs_path, scale) == -1 && errno == ENOENT) {
568                         ALOGE("Failed to store scale[%g] into %s - file is missing", scale, sysfs_path);
569                         /* Store failed, try to store the scale into channel specific file */
570                         for (c = 0; c < num_channels; c++)
571                         {
572                                 sprintf(sysfs_path, BASE_PATH "%s", dev_num,
573                                         sensor_catalog[catalog_index].channel[c].scale_path);
574                                 if (sysfs_write_float(sysfs_path, scale) == -1)
575                                         ALOGE("Failed to store scale[%g] into %s", scale, sysfs_path);
576                         }
577                 }
578         }
579
580         sprintf(sysfs_path, SENSOR_SCALE_PATH, dev_num, prefix);
581         if (!sysfs_read_float(sysfs_path, &scale)) {
582                 sensor[s].scale = scale;
583                 ALOGV("Scale path:%s scale:%g dev_num:%d\n",
584                                         sysfs_path, scale, dev_num);
585         } else {
586                 sensor[s].scale = 1;
587
588                 /* Read channel specific scale if any*/
589                 for (c = 0; c < num_channels; c++)
590                 {
591                         sprintf(sysfs_path, BASE_PATH "%s", dev_num,
592                            sensor_catalog[catalog_index].channel[c].scale_path);
593
594                         if (!sysfs_read_float(sysfs_path, &scale)) {
595                                 sensor[s].channel[c].scale = scale;
596                                 sensor[s].scale = 0;
597
598                                 ALOGV(  "Scale path:%s "
599                                         "channel scale:%g dev_num:%d\n",
600                                         sysfs_path, scale, dev_num);
601                         }
602                 }
603         }
604
605         /* Set default scaling - if num_channels is zero, we have one channel */
606
607         sensor[s].channel[0].opt_scale = 1;
608
609         for (c = 1; c < num_channels; c++)
610                 sensor[s].channel[c].opt_scale = 1;
611
612         for (c = 0; c < num_channels; c++) {
613                 /* Check the presence of the channel's input_path */
614                 sprintf(sysfs_path, BASE_PATH "%s", dev_num,
615                         sensor_catalog[catalog_index].channel[c].input_path);
616                 sensor[s].channel[c].input_path_present = (access(sysfs_path, R_OK) != -1);
617                 /* Check the presence of the channel's raw_path */
618                 sprintf(sysfs_path, BASE_PATH "%s", dev_num,
619                         sensor_catalog[catalog_index].channel[c].raw_path);
620                 sensor[s].channel[c].raw_path_present = (access(sysfs_path, R_OK) != -1);
621         }
622
623         /* Read ACPI _PLD attributes for this sensor, if there are any */
624         decode_placement_information(dev_num, num_channels, s);
625
626         /*
627          * See if we have optional correction scaling factors for each of the
628          * channels of this sensor. These would be expressed using properties
629          * like iio.accel.y.opt_scale = -1. In case of a single channel we also
630          * support things such as iio.temp.opt_scale = -1. Note that this works
631          * for all types of sensors, and whatever transform is selected, on top
632          * of any previous conversions.
633          */
634
635         if (num_channels) {
636                 for (c = 0; c < num_channels; c++) {
637                         ch_name = sensor_catalog[catalog_index].channel[c].name;
638                         sprintf(suffix, "%s.opt_scale", ch_name);
639                         if (!sensor_get_fl_prop(s, suffix, &opt_scale))
640                                 sensor[s].channel[c].opt_scale = opt_scale;
641                 }
642         } else {
643                 if (!sensor_get_fl_prop(s, "opt_scale", &opt_scale))
644                         sensor[s].channel[0].opt_scale = opt_scale;
645         }
646
647         populate_descriptors(s, sensor_type);
648
649         if (sensor[s].internal_name[0] == '\0') {
650                 /*
651                  * In case the kernel-mode driver doesn't expose a name for
652                  * the iio device, use (null)-dev%d as the trigger name...
653                  * This can be considered a kernel-mode iio driver bug.
654                  */
655                 ALOGW("Using null trigger on sensor %d (dev %d)\n", s, dev_num);
656                 strcpy(sensor[s].internal_name, "(null)");
657         }
658
659         switch (sensor_type) {
660                 case SENSOR_TYPE_ACCELEROMETER:
661                         /* Only engage accelerometer bias compensation if really needed */
662                         if (sensor_get_quirks(s) & QUIRK_BIASED)
663                                 sensor[s].cal_data = calloc(1, sizeof(accel_cal_t));
664                         break;
665
666                         case SENSOR_TYPE_GYROSCOPE:
667                         sensor[s].cal_data = malloc(sizeof(gyro_cal_t));
668                         break;
669
670                 case SENSOR_TYPE_MAGNETIC_FIELD:
671                         sensor[s].cal_data = malloc(sizeof(compass_cal_t));
672                         break;
673         }
674
675         sensor[s].max_cal_level = sensor_get_cal_steps(s);
676
677         /* Select one of the available sensor sample processing styles */
678         select_transform(s);
679
680         /* Initialize fields related to sysfs reads offloading */
681         sensor[s].thread_data_fd[0]  = -1;
682         sensor[s].thread_data_fd[1]  = -1;
683         sensor[s].acquisition_thread = -1;
684
685         /* Check if we have a special ordering property on this sensor */
686         if (sensor_get_order(s, sensor[s].order))
687                 sensor[s].quirks |= QUIRK_FIELD_ORDERING;
688
689         sensor[s].needs_enable = get_needs_enable(dev_num, sensor_catalog[catalog_index].tag);
690
691         sensor_count++;
692         return 0;
693 }
694
695 static void virtual_sensors_check (void)
696 {
697         int i;
698         int has_acc = 0;
699         int has_gyr = 0;
700         int has_mag = 0;
701         int has_rot = 0;
702         int has_ori = 0;
703         int gyro_cal_idx = 0;
704         int magn_cal_idx = 0;
705         unsigned int j;
706
707         for (i=0; i<sensor_count; i++)
708                 switch (sensor[i].type) {
709                         case SENSOR_TYPE_ACCELEROMETER:
710                                 has_acc = 1;
711                                 break;
712                         case SENSOR_TYPE_GYROSCOPE:
713                                 has_gyr = 1;
714                                 gyro_cal_idx = i;
715                                 break;
716                         case SENSOR_TYPE_MAGNETIC_FIELD:
717                                 has_mag = 1;
718                                 magn_cal_idx = i;
719                                 break;
720                         case SENSOR_TYPE_ORIENTATION:
721                                 has_ori = 1;
722                                 break;
723                         case SENSOR_TYPE_ROTATION_VECTOR:
724                                 has_rot = 1;
725                                 break;
726                 }
727
728         for (j=0; j<catalog_size; j++)
729                 switch (sensor_catalog[j].type) {
730                         /*
731                          * If we have accel + gyro + magn but no rotation vector sensor,
732                          * SensorService replaces the HAL provided orientation sensor by the
733                          * AOSP version... provided we report one. So initialize a virtual
734                          * orientation sensor with zero values, which will get replaced. See:
735                          * frameworks/native/services/sensorservice/SensorService.cpp, looking
736                          * for SENSOR_TYPE_ROTATION_VECTOR; that code should presumably fall
737                          * back to mUserSensorList.add instead of replaceAt, but accommodate it.
738                          */
739
740                         case SENSOR_TYPE_ORIENTATION:
741                                 if (has_acc && has_gyr && has_mag && !has_rot && !has_ori)
742                                         add_sensor(0, j, MODE_POLL);
743                                 break;
744                         case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
745                                 if (has_gyr) {
746                                         sensor[sensor_count].base_count = 1;
747                                         sensor[sensor_count].base[0] = gyro_cal_idx;
748                                         add_virtual_sensor(j);
749                                 }
750                                 break;
751                         case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
752                                 if (has_mag) {
753                                         sensor[sensor_count].base_count = 1;
754                                         sensor[sensor_count].base[0] = magn_cal_idx;
755                                         add_virtual_sensor(j);
756                                 }
757                                 break;
758                         default:
759                                 break;
760                 }
761 }
762
763
764 static void propose_new_trigger (int s, char trigger_name[MAX_NAME_SIZE],
765                                  int sensor_name_len)
766 {
767         /*
768          * A new trigger has been enumerated for this sensor. Check if it makes sense to use it over the currently selected one,
769          *  and select it if it is so. The format is something like sensor_name-dev0.
770          */
771
772         const char *suffix = trigger_name + sensor_name_len + 1;
773
774         /* dev is the default, and lowest priority; no need to update */
775         if (!memcmp(suffix, "dev", 3))
776                 return;
777
778         /* If we found any-motion trigger, record it */
779
780         if (!memcmp(suffix, "any-motion-", 11)) {
781                 strcpy(sensor[s].motion_trigger_name, trigger_name);
782                 return;
783         }
784
785         /*
786          * It's neither the default "dev" nor an "any-motion" one. Make sure we use this though, as we may not have any other indication of the name
787          * of the trigger to use with this sensor.
788          */
789         strcpy(sensor[s].init_trigger_name, trigger_name);
790 }
791
792
793 static void update_sensor_matching_trigger_name (char name[MAX_NAME_SIZE])
794 {
795         /*
796          * Check if we have a sensor matching the specified trigger name, which should then begin with the sensor name, and end with a number
797          * equal to the iio device number the sensor is associated to. If so, update the string we're going to write to trigger/current_trigger
798          * when enabling this sensor.
799          */
800
801         int s;
802         int dev_num;
803         int len;
804         char* cursor;
805         int sensor_name_len;
806
807         /*
808          * First determine the iio device number this trigger refers to. We expect the last few characters (typically one) of the trigger name
809          * to be this number, so perform a few checks.
810          */
811         len = strnlen(name, MAX_NAME_SIZE);
812
813         if (len < 2)
814                 return;
815
816         cursor = name + len - 1;
817
818         if (!isdigit(*cursor))
819                 return;
820
821         while (len && isdigit(*cursor)) {
822                 len--;
823                 cursor--;
824         }
825
826         dev_num = atoi(cursor+1);
827
828         /* See if that matches a sensor */
829         for (s=0; s<sensor_count; s++)
830                 if (sensor[s].dev_num == dev_num) {
831
832                         sensor_name_len = strlen(sensor[s].internal_name);
833
834                         if (!strncmp(name, sensor[s].internal_name, sensor_name_len))
835                                 /* Switch to new trigger if appropriate */
836                                 propose_new_trigger(s, name, sensor_name_len);
837                 }
838 }
839
840
841 static void setup_trigger_names (void)
842 {
843         char filename[PATH_MAX];
844         char buf[MAX_NAME_SIZE];
845         int s;
846         int trigger;
847         int ret;
848
849         /* By default, use the name-dev convention that most drivers use */
850         for (s=0; s<sensor_count; s++)
851                 snprintf(sensor[s].init_trigger_name, MAX_NAME_SIZE, "%s-dev%d", sensor[s].internal_name, sensor[s].dev_num);
852
853         /* Now have a look to /sys/bus/iio/devices/triggerX entries */
854
855         for (trigger=0; trigger<MAX_TRIGGERS; trigger++) {
856
857                 snprintf(filename, sizeof(filename), TRIGGER_FILE_PATH,trigger);
858
859                 ret = sysfs_read_str(filename, buf, sizeof(buf));
860
861                 if (ret < 0)
862                         break;
863
864                 /* Record initial and any-motion triggers names */
865                 update_sensor_matching_trigger_name(buf);
866         }
867
868         /*
869          * Certain drivers expose only motion triggers even though they should be continous. For these, use the default trigger name as the motion
870          * trigger. The code generating intermediate events is dependent on motion_trigger_name being set to a non empty string.
871          */
872
873         for (s=0; s<sensor_count; s++)
874                 if ((sensor[s].quirks & QUIRK_TERSE_DRIVER) && sensor[s].motion_trigger_name[0] == '\0')
875                         strcpy(sensor[s].motion_trigger_name, sensor[s].init_trigger_name);
876
877         for (s=0; s<sensor_count; s++)
878                 if (sensor[s].mode == MODE_TRIGGER) {
879                         ALOGI("Sensor %d (%s) default trigger: %s\n", s, sensor[s].friendly_name, sensor[s].init_trigger_name);
880                         if (sensor[s].motion_trigger_name[0])
881                                 ALOGI("Sensor %d (%s) motion trigger: %s\n", s, sensor[s].friendly_name, sensor[s].motion_trigger_name);
882                 }
883 }
884
885
886 static int catalog_index_from_sensor_type (int type)
887 {
888         /* Return first matching catalog entry index for selected type */
889         unsigned int i;
890
891         for (i=0; i<catalog_size; i++)
892                 if (sensor_catalog[i].type == type)
893                         return i;
894
895         return -1;
896 }
897
898
899 static void post_process_sensor_list (char poll_map[catalog_size], char trig_map[catalog_size], char event_map[catalog_size])
900 {
901         int illuminance_cat_index = catalog_index_from_sensor_type(SENSOR_TYPE_INTERNAL_ILLUMINANCE);
902         int intensity_cat_index   = catalog_index_from_sensor_type(SENSOR_TYPE_INTERNAL_INTENSITY);
903         int illuminance_found     = poll_map[illuminance_cat_index] || trig_map[illuminance_cat_index] || event_map[illuminance_cat_index];
904
905         /* If an illumimance sensor has been reported */
906         if (illuminance_found) {
907                 /* Hide any intensity sensors we can have for the same iio device */
908                 poll_map [intensity_cat_index     ] = 0;
909                 trig_map [intensity_cat_index     ] = 0;
910                 event_map[intensity_cat_index     ] = 0;
911                 return;
912         }
913 }
914
915
916 void enumerate_sensors (void)
917 {
918         /*
919          * Discover supported sensors and allocate control structures for them. Multiple sensors can potentially rely on a single iio device (each
920          * using their own channels). We can't have multiple sensors of the same type on the same device. In case of detection as both a poll-mode
921          * and trigger-based sensor, use the trigger usage mode.
922          */
923         char poll_sensors[catalog_size];
924         char trig_sensors[catalog_size];
925         char event_sensors[catalog_size];
926         int dev_num;
927         unsigned int i;
928         int trig_found;
929
930         for (dev_num=0; dev_num<MAX_DEVICES; dev_num++) {
931                 trig_found = 0;
932
933                 discover_sensors(dev_num, BASE_PATH, poll_sensors, check_poll_sensors);
934                 discover_sensors(dev_num, CHANNEL_PATH, trig_sensors, check_trig_sensors);
935                 discover_sensors(dev_num, EVENTS_PATH, event_sensors, check_event_sensors);
936
937                 /* Hide specific sensor types if appropriate */
938                 post_process_sensor_list(poll_sensors, trig_sensors, event_sensors);
939
940                 for (i=0; i<catalog_size; i++) {
941                         /* Try using events interface */
942                         if (event_sensors[i] && !add_sensor(dev_num, i, MODE_EVENT))
943                                 continue;
944
945                         /* Then trigger */
946                         if (trig_sensors[i] && !add_sensor(dev_num, i, MODE_TRIGGER)) {
947                                 trig_found = 1;
948                                 continue;
949                         }
950
951                         /* Try polling otherwise */
952                         if (poll_sensors[i])
953                                 add_sensor(dev_num, i, MODE_POLL);
954                 }
955
956                 if (trig_found)
957                         build_sensor_report_maps(dev_num);
958         }
959
960         ALOGI("Discovered %d sensors\n", sensor_count);
961
962         /* Set up default - as well as custom - trigger names */
963         setup_trigger_names();
964
965         virtual_sensors_check();
966 }
967
968
969 void delete_enumeration_data (void)
970 {
971         int i;
972         for (i = 0; i < sensor_count; i++)
973                 if (sensor[i].cal_data) {
974                         free(sensor[i].cal_data);
975                         sensor[i].cal_data = NULL;
976                         sensor[i].cal_level = 0;
977                 }
978
979         /* Reset sensor count */
980         sensor_count = 0;
981 }
982
983
984 int get_sensors_list (__attribute__((unused)) struct sensors_module_t* module,
985                       struct sensor_t const** list)
986 {
987         *list = sensor_desc;
988         return sensor_count;
989 }
990