OSDN Git Service

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