xref: /nrf52832-nimble/rt-thread/components/drivers/sensors/sensor.h (revision 104654410c56c573564690304ae786df310c91fc)
1 /*
2  * Copyright (c) 2006-2018, RT-Thread Development Team
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  *
6  * Change Logs:
7  * Date           Author       Notes
8  * 2014-08-03     Bernard      the first version
9  */
10 
11 /* Modified from: https://github.com/android/platform_hardware_libhardware/blob/master/include/hardware/sensors.h */
12 
13 /*
14  * Copyright (C) 2012 The Android Open Source Project
15  *
16  * Licensed under the Apache License, Version 2.0 (the "License");
17  * you may not use this file except in compliance with the License.
18  * You may obtain a copy of the License at
19  *
20  *      http://www.apache.org/licenses/LICENSE-2.0
21  *
22  * Unless required by applicable law or agreed to in writing, software
23  * distributed under the License is distributed on an "AS IS" BASIS,
24  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
25  * See the License for the specific language governing permissions and
26  * limitations under the License.
27  */
28 
29 #ifndef SENSORS_H__
30 #define SENSORS_H__
31 
32 #include <rtdevice.h>
33 #include <stdint.h>
34 
35 #ifdef __CC_ARM /* skip warning in armcc */
36 #pragma anon_unions
37 #endif
38 
39 /**
40  * Handles must be higher than SENSORS_HANDLE_BASE and must be unique.
41  * A Handle identifies a given sensors. The handle is used to activate
42  * and/or deactivate sensors.
43  * In this version of the API there can only be 256 handles.
44  */
45 #define SENSORS_HANDLE_BASE             0
46 #define SENSORS_HANDLE_BITS             8
47 #define SENSORS_HANDLE_COUNT            (1<<SENSORS_HANDLE_BITS)
48 
49 
50 /*
51  * flags for (*batch)()
52  * Availability: SENSORS_DEVICE_API_VERSION_1_0
53  * see (*batch)() documentation for details
54  */
55 enum
56 {
57     SENSORS_BATCH_DRY_RUN               = 0x00000001,
58     SENSORS_BATCH_WAKE_UPON_FIFO_FULL   = 0x00000002
59 };
60 
61 /*
62  * what field for meta_data_event_t
63  */
64 enum
65 {
66     /* a previous flush operation has completed */
67     META_DATA_FLUSH_COMPLETE = 1,
68     META_DATA_VERSION   /* always last, leave auto-assigned */
69 };
70 
71 /**
72  * Definition of the axis used by the sensor HAL API
73  *
74  * This API is relative to the screen of the device in its default orientation,
75  * that is, if the device can be used in portrait or landscape, this API
76  * is only relative to the NATURAL orientation of the screen. In other words,
77  * the axis are not swapped when the device's screen orientation changes.
78  * Higher level services /may/ perform this transformation.
79  *
80  *   x<0         x>0
81  *                ^
82  *                |
83  *    +-----------+-->  y>0
84  *    |           |
85  *    |           |
86  *    |           |
87  *    |           |   / z<0
88  *    |           |  /
89  *    |           | /
90  *    O-----------+/
91  *    |[]  [ ]  []/
92  *    +----------/+     y<0
93  *              /
94  *             /
95  *           |/ z>0 (toward the sky)
96  *
97  *    O: Origin (x=0,y=0,z=0)
98  *
99  */
100 
101 /*
102  * Interaction with suspend mode
103  *
104  * Unless otherwise noted, an enabled sensor shall not prevent the
105  * SoC to go into suspend mode. It is the responsibility of applications
106  * to keep a partial wake-lock should they wish to receive sensor
107  * events while the screen is off. While in suspend mode, and unless
108  * otherwise noted (batch mode, sensor particularities, ...), enabled sensors'
109  * events are lost.
110  *
111  * Note that conceptually, the sensor itself is not de-activated while in
112  * suspend mode -- it's just that the data it returns are lost. As soon as
113  * the SoC gets out of suspend mode, operations resume as usual. Of course,
114  * in practice sensors shall be disabled while in suspend mode to
115  * save power, unless batch mode is active, in which case they must
116  * continue fill their internal FIFO (see the documentation of batch() to
117  * learn how suspend interacts with batch mode).
118  *
119  * In batch mode, and only when the flag SENSORS_BATCH_WAKE_UPON_FIFO_FULL is
120  * set and supported, the specified sensor must be able to wake-up the SoC and
121  * be able to buffer at least 10 seconds worth of the requested sensor events.
122  *
123  * There are notable exceptions to this behavior, which are sensor-dependent
124  * (see sensor types definitions below)
125  *
126  *
127  * The sensor type documentation below specifies the wake-up behavior of
128  * each sensor:
129  *   wake-up: yes     this sensor must wake-up the SoC to deliver events
130  *   wake-up: no      this sensor shall not wake-up the SoC, events are dropped
131  *
132  */
133 
134 /*
135  * Sensor type
136  *
137  * Each sensor has a type which defines what this sensor measures and how
138  * measures are reported. All types are defined below.
139  *
140  * Device manufacturers (OEMs) can define their own sensor types, for
141  * their private use by applications or services provided by them. Such
142  * sensor types are specific to an OEM and can't be exposed in the SDK.
143  * These types must start at SENSOR_TYPE_DEVICE_PRIVATE_BASE.
144  */
145 
146 /*
147  * Base for device manufacturers private sensor types.
148  * These sensor types can't be exposed in the SDK.
149  */
150 #define SENSOR_TYPE_DEVICE_PRIVATE_BASE     0x10000
151 
152 /*
153  * Sensor fusion and virtual sensors
154  *
155  * Many sensor types are or can be implemented as virtual sensors from
156  * physical sensors on the device. For instance the rotation vector sensor,
157  * orientation sensor, step-detector, step-counter, etc...
158  *
159  * From the point of view of this API these virtual sensors MUST appear as
160  * real, individual sensors. It is the responsibility of the driver and HAL
161  * to make sure this is the case.
162  *
163  * In particular, all sensors must be able to function concurrently.
164  * For example, if defining both an accelerometer and a step counter,
165  * then both must be able to work concurrently.
166  */
167 
168 /*
169  * Trigger modes
170  *
171  * Sensors can report events in different ways called trigger modes,
172  * each sensor type has one and only one trigger mode associated to it.
173  * Currently there are four trigger modes defined:
174  *
175  * continuous: events are reported at a constant rate defined by setDelay().
176  *             eg: accelerometers, gyroscopes.
177  * on-change:  events are reported only if the sensor's value has changed.
178  *             setDelay() is used to set a lower limit to the reporting
179  *             period (minimum time between two events).
180  *             The HAL must return an event immediately when an on-change
181  *             sensor is activated.
182  *             eg: proximity, light sensors
183  * one-shot:   upon detection of an event, the sensor deactivates itself and
184  *             then sends a single event. Order matters to avoid race
185  *             conditions. No other event is sent until the sensor get
186  *             reactivated. setDelay() is ignored.
187  *             eg: significant motion sensor
188  * special:    see details in the sensor type specification below
189  *
190  */
191 
192 /*
193  * SENSOR_TYPE_META_DATA
194  * trigger-mode: n/a
195  * wake-up sensor: n/a
196  *
197  * NO SENSOR OF THAT TYPE MUST BE RETURNED (*get_sensors_list)()
198  *
199  * SENSOR_TYPE_META_DATA is a special token used to populate the
200  * sensors_meta_data_event structure. It doesn't correspond to a physical
201  * sensor. sensors_meta_data_event are special, they exist only inside
202  * the HAL and are generated spontaneously, as opposed to be related to
203  * a physical sensor.
204  *
205  *   sensors_meta_data_event_t.version must be META_DATA_VERSION
206  *   sensors_meta_data_event_t.sensor must be 0
207  *   sensors_meta_data_event_t.type must be SENSOR_TYPE_META_DATA
208  *   sensors_meta_data_event_t.reserved must be 0
209  *   sensors_meta_data_event_t.timestamp must be 0
210  *
211  * The payload is a meta_data_event_t, where:
212  * meta_data_event_t.what can take the following values:
213  *
214  * META_DATA_FLUSH_COMPLETE
215  *   This event indicates that a previous (*flush)() call has completed for the sensor
216  *   handle specified in meta_data_event_t.sensor.
217  *   see (*flush)() for more details
218  *
219  * All other values for meta_data_event_t.what are reserved and
220  * must not be used.
221  *
222  */
223 #define SENSOR_TYPE_META_DATA                           (0)
224 
225 /*
226  * SENSOR_TYPE_ACCELEROMETER
227  * trigger-mode: continuous
228  * wake-up sensor: no
229  *
230  *  All values are in SI units (m/s^2) and measure the acceleration of the
231  *  device minus the force of gravity.
232  *
233  *  Acceleration sensors return sensor events for all 3 axes at a constant
234  *  rate defined by setDelay().
235  *
236  *  x: Acceleration on the x-axis
237  *  y: Acceleration on the y-axis
238  *  z: Acceleration on the z-axis
239  *
240  * Note that the readings from the accelerometer include the acceleration
241  * due to gravity (which is opposite to the direction of the gravity vector).
242  *
243  *  Examples:
244  *    The norm of <x, y, z>  should be close to 0 when in free fall.
245  *
246  *    When the device lies flat on a table and is pushed on its left side
247  *    toward the right, the x acceleration value is positive.
248  *
249  *    When the device lies flat on a table, the acceleration value is +9.81,
250  *    which correspond to the acceleration of the device (0 m/s^2) minus the
251  *    force of gravity (-9.81 m/s^2).
252  *
253  *    When the device lies flat on a table and is pushed toward the sky, the
254  *    acceleration value is greater than +9.81, which correspond to the
255  *    acceleration of the device (+A m/s^2) minus the force of
256  *    gravity (-9.81 m/s^2).
257  */
258 #define SENSOR_TYPE_ACCELEROMETER                    (1)
259 
260 /*
261  * SENSOR_TYPE_GEOMAGNETIC_FIELD
262  * trigger-mode: continuous
263  * wake-up sensor: no
264  *
265  *  All values are in micro-Tesla (uT) and measure the geomagnetic
266  *  field in the X, Y and Z axis.
267  *
268  *  Returned values include calibration mechanisms such that the vector is
269  *  aligned with the magnetic declination and heading of the earth's
270  *  geomagnetic field.
271  *
272  *  Magnetic Field sensors return sensor events for all 3 axes at a constant
273  *  rate defined by setDelay().
274  */
275 #define SENSOR_TYPE_GEOMAGNETIC_FIELD                (2)
276 #define SENSOR_TYPE_MAGNETIC_FIELD  SENSOR_TYPE_GEOMAGNETIC_FIELD
277 
278 /*
279  * SENSOR_TYPE_ORIENTATION
280  * trigger-mode: continuous
281  * wake-up sensor: no
282  *
283  * All values are angles in degrees.
284  *
285  * Orientation sensors return sensor events for all 3 axes at a constant
286  * rate defined by setDelay().
287  *
288  * azimuth: angle between the magnetic north direction and the Y axis, around
289  *  the Z axis (0<=azimuth<360).
290  *      0=North, 90=East, 180=South, 270=West
291  *
292  * pitch: Rotation around X axis (-180<=pitch<=180), with positive values when
293  *  the z-axis moves toward the y-axis.
294  *
295  * roll: Rotation around Y axis (-90<=roll<=90), with positive values when
296  *  the x-axis moves towards the z-axis.
297  *
298  * Note: For historical reasons the roll angle is positive in the clockwise
299  *  direction (mathematically speaking, it should be positive in the
300  *  counter-clockwise direction):
301  *
302  *                Z
303  *                ^
304  *  (+roll)  .--> |
305  *          /     |
306  *         |      |  roll: rotation around Y axis
307  *     X <-------(.)
308  *                 Y
309  *       note that +Y == -roll
310  *
311  *
312  *
313  * Note: This definition is different from yaw, pitch and roll used in aviation
314  *  where the X axis is along the long side of the plane (tail to nose).
315  */
316 #define SENSOR_TYPE_ORIENTATION                      (3)
317 
318 /*
319  * SENSOR_TYPE_GYROSCOPE
320  * trigger-mode: continuous
321  * wake-up sensor: no
322  *
323  *  All values are in radians/second and measure the rate of rotation
324  *  around the X, Y and Z axis.  The coordinate system is the same as is
325  *  used for the acceleration sensor. Rotation is positive in the
326  *  counter-clockwise direction (right-hand rule). That is, an observer
327  *  looking from some positive location on the x, y or z axis at a device
328  *  positioned on the origin would report positive rotation if the device
329  *  appeared to be rotating counter clockwise. Note that this is the
330  *  standard mathematical definition of positive rotation and does not agree
331  *  with the definition of roll given earlier.
332  *  The range should at least be 17.45 rad/s (ie: ~1000 deg/s).
333  *
334  *  automatic gyro-drift compensation is allowed but not required.
335  */
336 #define SENSOR_TYPE_GYROSCOPE                        (4)
337 
338 /*
339  * SENSOR_TYPE_LIGHT
340  * trigger-mode: on-change
341  * wake-up sensor: no
342  *
343  * The light sensor value is returned in SI lux units.
344  */
345 #define SENSOR_TYPE_LIGHT                            (5)
346 
347 /*
348  * SENSOR_TYPE_PRESSURE
349  * trigger-mode: continuous
350  * wake-up sensor: no
351  *
352  * The pressure sensor return the athmospheric pressure in hectopascal (hPa)
353  */
354 #define SENSOR_TYPE_PRESSURE                         (6)
355 
356 /* SENSOR_TYPE_TEMPERATURE is deprecated in the HAL */
357 #define SENSOR_TYPE_TEMPERATURE                      (7)
358 
359 /*
360  * SENSOR_TYPE_PROXIMITY
361  * trigger-mode: on-change
362  * wake-up sensor: yes
363  *
364  * The distance value is measured in centimeters.  Note that some proximity
365  * sensors only support a binary "close" or "far" measurement.  In this case,
366  * the sensor should report its maxRange value in the "far" state and a value
367  * less than maxRange in the "near" state.
368  */
369 #define SENSOR_TYPE_PROXIMITY                        (8)
370 
371 /*
372  * SENSOR_TYPE_GRAVITY
373  * trigger-mode: continuous
374  * wake-up sensor: no
375  *
376  * A gravity output indicates the direction of and magnitude of gravity in
377  * the devices's coordinates.  On Earth, the magnitude is 9.8 m/s^2.
378  * Units are m/s^2.  The coordinate system is the same as is used for the
379  * acceleration sensor. When the device is at rest, the output of the
380  * gravity sensor should be identical to that of the accelerometer.
381  */
382 #define SENSOR_TYPE_GRAVITY                          (9)
383 
384 /*
385  * SENSOR_TYPE_LINEAR_ACCELERATION
386  * trigger-mode: continuous
387  * wake-up sensor: no
388  *
389  * Indicates the linear acceleration of the device in device coordinates,
390  * not including gravity.
391  *
392  * The output is conceptually:
393  *    output of TYPE_ACCELERATION - output of TYPE_GRAVITY
394  *
395  * Readings on all axes should be close to 0 when device lies on a table.
396  * Units are m/s^2.
397  * The coordinate system is the same as is used for the acceleration sensor.
398  */
399 #define SENSOR_TYPE_LINEAR_ACCELERATION             (10)
400 
401 /*
402  * SENSOR_TYPE_ROTATION_VECTOR
403  * trigger-mode: continuous
404  * wake-up sensor: no
405  *
406  * The rotation vector symbolizes the orientation of the device relative to the
407  * East-North-Up coordinates frame. It is usually obtained by integration of
408  * accelerometer, gyroscope and magnetometer readings.
409  *
410  * The East-North-Up coordinate system is defined as a direct orthonormal basis
411  * where:
412  * - X points east and is tangential to the ground.
413  * - Y points north and is tangential to the ground.
414  * - Z points towards the sky and is perpendicular to the ground.
415  *
416  * The orientation of the phone is represented by the rotation necessary to
417  * align the East-North-Up coordinates with the phone's coordinates. That is,
418  * applying the rotation to the world frame (X,Y,Z) would align them with the
419  * phone coordinates (x,y,z).
420  *
421  * The rotation can be seen as rotating the phone by an angle theta around
422  * an axis rot_axis to go from the reference (East-North-Up aligned) device
423  * orientation to the current device orientation.
424  *
425  * The rotation is encoded as the 4 (reordered) components of a unit quaternion:
426  *   sensors_event_t.data[0] = rot_axis.x*sin(theta/2)
427  *   sensors_event_t.data[1] = rot_axis.y*sin(theta/2)
428  *   sensors_event_t.data[2] = rot_axis.z*sin(theta/2)
429  *   sensors_event_t.data[3] = cos(theta/2)
430  * where
431  *   - rot_axis.x,y,z are the North-East-Up coordinates of a unit length vector
432  *     representing the rotation axis
433  *   - theta is the rotation angle
434  *
435  * The quaternion must be of norm 1 (it is a unit quaternion). Failure to ensure
436  * this will cause erratic client behaviour.
437  *
438  * In addition, this sensor reports an estimated heading accuracy.
439  *   sensors_event_t.data[4] = estimated_accuracy (in radians)
440  * The heading error must be less than estimated_accuracy 95% of the time
441  *
442  * This sensor must use a gyroscope and an accelerometer as main orientation
443  * change input.
444  *
445  * This sensor can also include magnetometer input to make up for gyro drift,
446  * but it cannot be implemented using only a magnetometer.
447  */
448 #define SENSOR_TYPE_ROTATION_VECTOR                 (11)
449 
450 /*
451  * SENSOR_TYPE_RELATIVE_HUMIDITY
452  * trigger-mode: on-change
453  * wake-up sensor: no
454  *
455  * A relative humidity sensor measures relative ambient air humidity and
456  * returns a value in percent.
457  */
458 #define SENSOR_TYPE_RELATIVE_HUMIDITY               (12)
459 
460 /*
461  * SENSOR_TYPE_AMBIENT_TEMPERATURE
462  * trigger-mode: on-change
463  * wake-up sensor: no
464  *
465  * The ambient (room) temperature in degree Celsius.
466  */
467 #define SENSOR_TYPE_AMBIENT_TEMPERATURE             (13)
468 
469 /*
470  * SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED
471  * trigger-mode: continuous
472  * wake-up sensor: no
473  *
474  *  Similar to SENSOR_TYPE_MAGNETIC_FIELD, but the hard iron calibration is
475  *  reported separately instead of being included in the measurement.
476  *  Factory calibration and temperature compensation should still be applied to
477  *  the "uncalibrated" measurement.
478  *  Separating away the hard iron calibration estimation allows the system to
479  *  better recover from bad hard iron estimation.
480  *
481  *  All values are in micro-Tesla (uT) and measure the ambient magnetic
482  *  field in the X, Y and Z axis. Assumptions that the the magnetic field
483  *  is due to the Earth's poles should be avoided.
484  *
485  *  The uncalibrated_magnetic event contains
486  *  - 3 fields for uncalibrated measurement: x_uncalib, y_uncalib, z_uncalib.
487  *    Each is a component of the measured magnetic field, with soft iron
488  *    and temperature compensation applied, but not hard iron calibration.
489  *    These values should be continuous (no re-calibration should cause a jump).
490  *  - 3 fields for hard iron bias estimates: x_bias, y_bias, z_bias.
491  *    Each field is a component of the estimated hard iron calibration.
492  *    They represent the offsets to apply to the calibrated readings to obtain
493  *    uncalibrated readings (x_uncalib ~= x_calibrated + x_bias)
494  *    These values are expected to jump as soon as the estimate of the hard iron
495  *    changes, and they should be stable the rest of the time.
496  *
497  *  If this sensor is present, then the corresponding
498  *  SENSOR_TYPE_MAGNETIC_FIELD must be present and both must return the
499  *  same sensor_t::name and sensor_t::vendor.
500  *
501  *  Minimum filtering should be applied to this sensor. In particular, low pass
502  *  filters should be avoided.
503  *
504  * See SENSOR_TYPE_MAGNETIC_FIELD for more information
505  */
506 #define SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED     (14)
507 
508 /*
509  * SENSOR_TYPE_GAME_ROTATION_VECTOR
510  * trigger-mode: continuous
511  * wake-up sensor: no
512  *
513  *  Similar to SENSOR_TYPE_ROTATION_VECTOR, but not using the geomagnetic
514  *  field. Therefore the Y axis doesn't point north, but instead to some other
515  *  reference. That reference is allowed to drift by the same order of
516  *  magnitude than the gyroscope drift around the Z axis.
517  *
518  *  This sensor does not report an estimated heading accuracy:
519  *    sensors_event_t.data[4] is reserved and should be set to 0
520  *
521  *  In the ideal case, a phone rotated and returning to the same real-world
522  *  orientation should report the same game rotation vector
523  *  (without using the earth's geomagnetic field).
524  *
525  *  This sensor must be based on a gyroscope. It cannot be implemented using
526  *  a magnetometer.
527  *
528  * see SENSOR_TYPE_ROTATION_VECTOR for more details
529  */
530 #define SENSOR_TYPE_GAME_ROTATION_VECTOR            (15)
531 
532 /*
533  * SENSOR_TYPE_GYROSCOPE_UNCALIBRATED
534  * trigger-mode: continuous
535  * wake-up sensor: no
536  *
537  *  All values are in radians/second and measure the rate of rotation
538  *  around the X, Y and Z axis. An estimation of the drift on each axis is
539  *  reported as well.
540  *
541  *  No gyro-drift compensation shall be performed.
542  *  Factory calibration and temperature compensation should still be applied
543  *  to the rate of rotation (angular speeds).
544  *
545  *  The coordinate system is the same as is
546  *  used for the acceleration sensor. Rotation is positive in the
547  *  counter-clockwise direction (right-hand rule). That is, an observer
548  *  looking from some positive location on the x, y or z axis at a device
549  *  positioned on the origin would report positive rotation if the device
550  *  appeared to be rotating counter clockwise. Note that this is the
551  *  standard mathematical definition of positive rotation and does not agree
552  *  with the definition of roll given earlier.
553  *  The range should at least be 17.45 rad/s (ie: ~1000 deg/s).
554  *
555  *  Content of an uncalibrated_gyro event: (units are rad/sec)
556  *   x_uncalib : angular speed (w/o drift compensation) around the X axis
557  *   y_uncalib : angular speed (w/o drift compensation) around the Y axis
558  *   z_uncalib : angular speed (w/o drift compensation) around the Z axis
559  *   x_bias : estimated drift around X axis in rad/s
560  *   y_bias : estimated drift around Y axis in rad/s
561  *   z_bias : estimated drift around Z axis in rad/s
562  *
563  *  IMPLEMENTATION NOTES:
564  *
565  *  If the implementation is not able to estimate the drift, then this
566  *  sensor MUST NOT be reported by this HAL. Instead, the regular
567  *  SENSOR_TYPE_GYROSCOPE is used without drift compensation.
568  *
569  *  If this sensor is present, then the corresponding
570  *  SENSOR_TYPE_GYROSCOPE must be present and both must return the
571  *  same sensor_t::name and sensor_t::vendor.
572  */
573 #define SENSOR_TYPE_GYROSCOPE_UNCALIBRATED          (16)
574 
575 /*
576  * SENSOR_TYPE_SIGNIFICANT_MOTION
577  * trigger-mode: one-shot
578  * wake-up sensor: yes
579  *
580  * A sensor of this type triggers an event each time significant motion
581  * is detected and automatically disables itself.
582  * The only allowed value to return is 1.0.
583  *
584  * A significant motion is a motion that might lead to a change in the user
585  * location.
586  * Examples of such motions are:
587  *   walking, biking, sitting in a moving car, coach or train.
588  * Examples of situations that should not trigger significant motion:
589  * - phone in pocket and person is not moving
590  * - phone is on a table, even if the table shakes a bit due to nearby traffic
591  *   or washing machine
592  *
593  * A note on false positive / false negative / power consumption tradeoff
594  *  - The goal of this sensor is to save power.
595  *  - Triggering an event when the user is not moving (false positive) is costly
596  *    in terms of power, so it should be avoided.
597  *  - Not triggering an event when the user is moving (false negative) is
598  *    acceptable as long as it is not done repeatedly. If the user has been
599  *    walking for 10 seconds, not triggering an event within those 10 seconds
600  *    is not acceptable.
601  *
602  *  IMPORTANT NOTE: this sensor type is very different from other types
603  *  in that it must work when the screen is off without the need of
604  *  holding a partial wake-lock and MUST allow the SoC to go into suspend.
605  *  When significant motion is detected, the sensor must awaken the SoC and
606  *  the event be reported.
607  *
608  *  If a particular hardware cannot support this mode of operation then this
609  *  sensor type MUST NOT be reported by the HAL. ie: it is not acceptable
610  *  to "emulate" this sensor in the HAL.
611  *
612  *  The whole point of this sensor type is to save power by keeping the
613  *  SoC in suspend mode when the device is at rest.
614  *
615  *  When the sensor is not activated, it must also be deactivated in the
616  *  hardware: it must not wake up the SoC anymore, even in case of
617  *  significant motion.
618  *
619  *  setDelay() has no effect and is ignored.
620  *  Once a "significant motion" event is returned, a sensor of this type
621  *  must disables itself automatically, as if activate(..., 0) had been called.
622  */
623 
624 #define SENSOR_TYPE_SIGNIFICANT_MOTION              (17)
625 
626 /*
627  * SENSOR_TYPE_STEP_DETECTOR
628  * trigger-mode: special
629  * wake-up sensor: no
630  *
631  * A sensor of this type triggers an event each time a step is taken
632  * by the user. The only allowed value to return is 1.0 and an event is
633  * generated for each step. Like with any other event, the timestamp
634  * indicates when the event (here the step) occurred, this corresponds to when
635  * the foot hit the ground, generating a high variation in acceleration.
636  *
637  * While this sensor operates, it shall not disrupt any other sensors, in
638  * particular, but not limited to, the accelerometer; which might very well
639  * be in use as well.
640  *
641  * This sensor must be low power. That is, if the step detection cannot be
642  * done in hardware, this sensor should not be defined. Also, when the
643  * step detector is activated and the accelerometer is not, only steps should
644  * trigger interrupts (not accelerometer data).
645  *
646  * setDelay() has no impact on this sensor type
647  */
648 
649 #define SENSOR_TYPE_STEP_DETECTOR                   (18)
650 
651 /*
652  * SENSOR_TYPE_STEP_COUNTER
653  * trigger-mode: on-change
654  * wake-up sensor: no
655  *
656  * A sensor of this type returns the number of steps taken by the user since
657  * the last reboot while activated. The value is returned as a uint64_t and is
658  * reset to zero only on a system / android reboot.
659  *
660  * The timestamp of the event is set to the time when the first step
661  * for that event was taken.
662  * See SENSOR_TYPE_STEP_DETECTOR for the signification of the time of a step.
663  *
664  *  The minimum size of the hardware's internal counter shall be 16 bits
665  *  (this restriction is here to avoid too frequent wake-ups when the
666  *  delay is very large).
667  *
668  *  IMPORTANT NOTE: this sensor type is different from other types
669  *  in that it must work when the screen is off without the need of
670  *  holding a partial wake-lock and MUST allow the SoC to go into suspend.
671  *  Unlike other sensors, while in suspend mode this sensor must stay active,
672  *  no events are reported during that time but, steps continue to be
673  *  accounted for; an event will be reported as soon as the SoC resumes if
674  *  the timeout has expired.
675  *
676  *    In other words, when the screen is off and the device allowed to
677  *    go into suspend mode, we don't want to be woken up, regardless of the
678  *    setDelay() value, but the steps shall continue to be counted.
679  *
680  *    The driver must however ensure that the internal step count never
681  *    overflows. It is allowed in this situation to wake the SoC up so the
682  *    driver can do the counter maintenance.
683  *
684  *  While this sensor operates, it shall not disrupt any other sensors, in
685  *  particular, but not limited to, the accelerometer; which might very well
686  *  be in use as well.
687  *
688  *  If a particular hardware cannot support these modes of operation then this
689  *  sensor type MUST NOT be reported by the HAL. ie: it is not acceptable
690  *  to "emulate" this sensor in the HAL.
691  *
692  * This sensor must be low power. That is, if the step detection cannot be
693  * done in hardware, this sensor should not be defined. Also, when the
694  * step counter is activated and the accelerometer is not, only steps should
695  * trigger interrupts (not accelerometer data).
696  *
697  *  The whole point of this sensor type is to save power by keeping the
698  *  SoC in suspend mode when the device is at rest.
699  */
700 
701 #define SENSOR_TYPE_STEP_COUNTER                    (19)
702 
703 /*
704  * SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR
705  * trigger-mode: continuous
706  * wake-up sensor: no
707  *
708  *  Similar to SENSOR_TYPE_ROTATION_VECTOR, but using a magnetometer instead
709  *  of using a gyroscope.
710  *
711  *  This sensor must be based on a magnetometer. It cannot be implemented using
712  *  a gyroscope, and gyroscope input cannot be used by this sensor, as the
713  *  goal of this sensor is to be low power.
714  *  The accelerometer can be (and usually is) used.
715  *
716  *  Just like SENSOR_TYPE_ROTATION_VECTOR, this sensor reports an estimated
717  *  heading accuracy:
718  *    sensors_event_t.data[4] = estimated_accuracy (in radians)
719  *  The heading error must be less than estimated_accuracy 95% of the time
720  *
721  * see SENSOR_TYPE_ROTATION_VECTOR for more details
722  */
723 #define SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR            (20)
724 
725 /**
726  * Values returned by the accelerometer in various locations in the universe.
727  * all values are in SI units (m/s^2)
728  */
729 #define SENSORS_GRAVITY_SUN                 (275.0f)
730 #define SENSORS_GRAVITY_MOON                (1.6f)
731 #define SENSORS_GRAVITY_EARTH               (9.80665f)
732 #define SENSORS_GRAVITY_STANDARD            (SENSORS_GRAVITY_EARTH)
733 
734 /** Maximum magnetic field on Earth's surface */
735 #define MAGNETIC_FIELD_EARTH_MAX            (60.0f)
736 
737 /** Minimum magnetic field on Earth's surface */
738 #define MAGNETIC_FIELD_EARTH_MIN            (30.0f)
739 
740 /** Average sea level pressure is 1013.25 hPa */
741 #define SENSORS_PRESSURE_SEALEVELHPA        (1013.25F)
742 
743 /** Degrees/s to rad/s multiplier */
744 #define SENSORS_DPS_TO_RADS                 (0.017453293F)
745 /** Gauss to micro-Tesla multiplier */
746 #define SENSORS_GAUSS_TO_MICROTESLA         (100)
747 
748 /**
749  * status of orientation sensor
750  */
751 #define SENSOR_STATUS_UNRELIABLE        0
752 #define SENSOR_STATUS_ACCURACY_LOW      1
753 #define SENSOR_STATUS_ACCURACY_MEDIUM   2
754 #define SENSOR_STATUS_ACCURACY_HIGH     3
755 
756 /**
757  * sensor event data
758  */
759 typedef struct
760 {
761     union
762     {
763         float v[3];
764         struct
765         {
766             float x;
767             float y;
768             float z;
769         };
770         struct
771         {
772             float azimuth;
773             float pitch;
774             float roll;
775         };
776     };
777     int8_t status;
778     uint8_t reserved[3];
779 } sensors_vec_t;
780 
781 /**
782  * sensor raw vector data
783  */
784 typedef struct
785 {
786     struct
787     {
788         int16_t x;
789         int16_t y;
790         int16_t z;
791     };
792 
793     int8_t status;
794     uint8_t reserved[1];
795 } sensors_raw_vec_t;
796 
797 /**
798  * uncalibrated gyroscope and magnetometer event data
799  */
800 typedef struct
801 {
802     union
803     {
804         float uncalib[3];
805         struct
806         {
807             float x_uncalib;
808             float y_uncalib;
809             float z_uncalib;
810         };
811     };
812     union
813     {
814         float bias[3];
815         struct
816         {
817             float x_bias;
818             float y_bias;
819             float z_bias;
820         };
821     };
822 } uncalibrated_event_t;
823 
824 typedef struct meta_data_event
825 {
826     int32_t what;
827     int32_t sensor;
828 } meta_data_event_t;
829 
830 /**
831  * Union of the various types of sensor data
832  * that can be returned.
833  */
834 typedef struct sensors_event_t
835 {
836     /* must be sizeof(struct sensors_event_t) */
837     int32_t version;
838 
839     /* sensor identifier */
840     int32_t sensor;
841 
842     /* sensor type */
843     int32_t type;
844 
845     /* reserved */
846     int32_t reserved0;
847 
848     /* time is in nanosecond */
849     int64_t timestamp;
850 
851     union
852     {
853         union
854         {
855             float           data[16];
856 
857             /* acceleration values are in meter per second per second (m/s^2) */
858             sensors_vec_t   acceleration;
859             /* raw acceleration data */
860             sensors_raw_vec_t raw_acceleration;
861 
862             /* magnetic vector values are in micro-Tesla (uT) */
863             sensors_vec_t   magnetic;
864             /* raw magnetic data */
865             sensors_raw_vec_t raw_magnetic;
866 
867             /* orientation values are in degrees */
868             sensors_vec_t   orientation;
869 
870             /* gyroscope values are in rad/s */
871             sensors_vec_t   gyro;
872             /* raw gyroscope data */
873             sensors_raw_vec_t raw_gyro;
874 
875             /* temperature is in degrees centigrade (Celsius) */
876             float           temperature;
877 
878             /* distance in centimeters */
879             float           distance;
880 
881             /* light in SI lux units */
882             float           light;
883 
884             /* pressure in hectopascal (hPa) */
885             float           pressure;
886 
887             /* relative humidity in percent */
888             float           relative_humidity;
889 
890             /* uncalibrated gyroscope values are in rad/s */
891             uncalibrated_event_t uncalibrated_gyro;
892 
893             /* uncalibrated magnetometer values are in micro-Teslas */
894             uncalibrated_event_t uncalibrated_magnetic;
895 
896             /* this is a special event. see SENSOR_TYPE_META_DATA above.
897              * sensors_meta_data_event_t events are all reported with a type of
898              * SENSOR_TYPE_META_DATA. The handle is ignored and must be zero.
899              */
900             meta_data_event_t meta_data;
901         };
902 
903         union
904         {
905             uint64_t        data[8];
906 
907             /* step-counter */
908             uint64_t        step_counter;
909         } u64;
910     };
911     uint32_t reserved1[4];
912 } sensors_event_t;
913 
914 /* see SENSOR_TYPE_META_DATA */
915 typedef sensors_event_t sensors_meta_data_event_t;
916 
917 typedef struct sensor_t
918 {
919     /* Name of this sensor.
920      * All sensors of the same "type" must have a different "name".
921      */
922     const char     *name;
923 
924     /* vendor of the hardware part */
925     const char     *vendor;
926 
927     /* version of the hardware part + driver. The value of this field
928      * must increase when the driver is updated in a way that changes the
929      * output of this sensor. This is important for fused sensors when the
930      * fusion algorithm is updated.
931      */
932     int             version;
933 
934     /* handle that identifies this sensors. This handle is used to reference
935      * this sensor throughout the HAL API.
936      */
937     int             handle;
938 
939     /* this sensor's type. */
940     int             type;
941 
942     /* maximum range of this sensor's value in SI units */
943     float           maxRange;
944 
945     /* smallest difference between two values reported by this sensor */
946     float           resolution;
947 
948     /* rough estimate of this sensor's power consumption in mA */
949     float           power;
950 
951     /* this value depends on the trigger mode:
952      *
953      *   continuous: minimum sample period allowed in microseconds
954      *   on-change : 0
955      *   one-shot  :-1
956      *   special   : 0, unless otherwise noted
957      */
958     int32_t         minDelay;
959 
960     /* number of events reserved for this sensor in the batch mode FIFO.
961      * If there is a dedicated FIFO for this sensor, then this is the
962      * size of this FIFO. If the FIFO is shared with other sensors,
963      * this is the size reserved for that sensor and it can be zero.
964      */
965     uint32_t        fifoReservedEventCount;
966 
967     /* maximum number of events of this sensor that could be batched.
968      * This is especially relevant when the FIFO is shared between
969      * several sensors; this value is then set to the size of that FIFO.
970      */
971     uint32_t        fifoMaxEventCount;
972 
973     /* reserved fields, must be zero */
974     void           *reserved[6];
975 } sensor_t;
976 
977 enum SensorMode
978 {
979     SENSOR_MODE_RAW,
980     SENSOR_MODE_CALIBRATED,
981     SENSOR_MODE_NORMAL,
982 };
983 
984 enum SensorAccelRange
985 {
986     SENSOR_ACCEL_RANGE_2G,
987     SENSOR_ACCEL_RANGE_4G,
988     SENSOR_ACCEL_RANGE_8G,
989     SENSOR_ACCEL_RANGE_16G,
990 };
991 #define SENSOR_ACCEL_SENSITIVITY_2G  ((float)2/32768)
992 #define SENSOR_ACCEL_SENSITIVITY_4G  ((float)4/32768)
993 #define SENSOR_ACCEL_SENSITIVITY_8G  ((float)8/32768)
994 #define SENSOR_ACCEL_SENSITIVITY_16G ((float)16/32768)
995 
996 enum SensorGyroRange
997 {
998     SENSOR_GYRO_RANGE_250DPS,
999     SENSOR_GYRO_RANGE_500DPS,
1000     SENSOR_GYRO_RANGE_1000DPS,
1001     SENSOR_GYRO_RANGE_2000DPS,
1002 };
1003 #define SENSOR_GYRO_SENSITIVITY_250DPS  (0.00875F)
1004 #define SENSOR_GYRO_SENSITIVITY_500DPS  (0.0175F)
1005 #define SENSOR_GYRO_SENSITIVITY_1000DPS (0.035F)
1006 #define SENSOR_GYRO_SENSITIVITY_2000DPS (0.070F)
1007 
1008 enum SensorDataRate
1009 {
1010     SENSOR_DATARATE_3200HZ,
1011     SENSOR_DATARATE_1600HZ,
1012     SENSOR_DATARATE_800HZ,
1013     SENSOR_DATARATE_400HZ,
1014     SENSOR_DATARATE_200HZ,
1015     SENSOR_DATARATE_100HZ,
1016     SENSOR_DATARATE_50HZ,
1017     SENSOR_DATARATE_25HZ,
1018     SENSOR_DATARATE_12_5HZ,
1019     SENSOR_DATARATE_6_25HZ,
1020     SENSOR_DATARATE_3_13HZ,
1021     SENSOR_DATARATE_1_56HZ,
1022     SENSOR_DATARATE_0_78HZ,
1023     SENSOR_DATARATE_0_39HZ,
1024     SENSOR_DATARATE_0_20HZ,
1025     SENSOR_DATARATE_0_10HZ,
1026 };
1027 
1028 /**
1029  * Sensor Configuration
1030  */
1031 typedef struct SensorConfig
1032 {
1033     int mode;
1034 
1035     enum SensorDataRate data_rate;
1036 
1037     union range
1038     {
1039         int range;
1040         enum SensorAccelRange accel_range;
1041         enum SensorGyroRange  gyro_range;
1042     } range;
1043 }SensorConfig;
1044 
1045 typedef void (*SensorEventHandler_t)(void *user_data);
1046 
1047 #ifdef __cplusplus
1048 class SensorBase;
1049 class SensorManager;
1050 
1051 /**
1052  * Sensor Base Class
1053  */
1054 class SensorBase
1055 {
1056 private:
1057     int type;
1058 
1059 public:
1060     SensorBase(int type);
1061     ~SensorBase();
1062 
1063     virtual int configure(SensorConfig *config) = 0;
1064     virtual int activate(int enable) = 0;
1065 
1066     virtual int poll(sensors_event_t *events) = 0;
1067     virtual void getSensor(struct sensor_t *sensor) = 0;
1068 
1069     int getType(void);
1070 
1071     int setConfig(SensorConfig *config);
1072     int getConfig(SensorConfig *config);
1073 
1074     int subscribe(SensorEventHandler_t handler, void *user_data);
1075     int publish(void);
1076 
1077 protected:
1078     SensorBase *next;
1079     SensorBase *prev;
1080 
1081     /* sensor configuration */
1082     SensorConfig config;
1083 
1084     SensorEventHandler_t evtHandler;
1085     void *userData;
1086 
1087     friend class SensorManager;
1088 };
1089 
1090 /**
1091  * Sensor Manager
1092  */
1093 class SensorManager
1094 {
1095 public:
1096     SensorManager();
1097     ~SensorManager();
1098 
1099     static int registerSensor(SensorBase *sensor);
1100     static int unregisterSensor(SensorBase *sensor);
1101 
1102     static SensorBase *getDefaultSensor(int type);
1103     static int subscribe(int type, SensorEventHandler_t handler, void *user_data);
1104 
1105     static int sensorEventReady(SensorBase *sensor);
1106     static int pollSensor(SensorBase *sensor, sensors_event_t *events, int number, int duration);
1107 };
1108 #endif
1109 
1110 /* C programming language APIs */
1111 /* rt_sensor_t is a C typedef for SensorBase */
1112 typedef void* rt_sensor_t;
1113 
1114 #ifdef __cplusplus
1115 extern "C" {
1116 #endif
1117 
1118 rt_sensor_t rt_sensor_get_default(int type);
1119 
1120 int rt_sensor_subscribe(rt_sensor_t sensor, SensorEventHandler_t handler, void *user_data);
1121 int rt_sensor_activate (rt_sensor_t sensor, int enable);
1122 int rt_sensor_configure(rt_sensor_t sensor, SensorConfig *config);
1123 int rt_sensor_poll(rt_sensor_t sensor, sensors_event_t *event);
1124 
1125 #ifdef __cplusplus
1126 }
1127 #endif
1128 
1129 #endif
1130