1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 /**
18  * @addtogroup Sensor
19  * @{
20  */
21 
22 /**
23  * @file sensor.h
24  */
25 
26 #ifndef ANDROID_SENSOR_H
27 #define ANDROID_SENSOR_H
28 
29 /******************************************************************
30  *
31  * IMPORTANT NOTICE:
32  *
33  *   This file is part of Android's set of stable system headers
34  *   exposed by the Android NDK (Native Development Kit).
35  *
36  *   Third-party source AND binary code relies on the definitions
37  *   here to be FROZEN ON ALL UPCOMING PLATFORM RELEASES.
38  *
39  *   - DO NOT MODIFY ENUMS (EXCEPT IF YOU ADD NEW 32-BIT VALUES)
40  *   - DO NOT MODIFY CONSTANTS OR FUNCTIONAL MACROS
41  *   - DO NOT CHANGE THE SIGNATURE OF FUNCTIONS IN ANY WAY
42  *   - DO NOT CHANGE THE LAYOUT OR SIZE OF STRUCTURES
43  */
44 
45 /**
46  * Structures and functions to receive and process sensor events in
47  * native code.
48  *
49  */
50 
51 #include <android/looper.h>
52 
53 #include <sys/types.h>
54 #include <math.h>
55 #include <stdint.h>
56 
57 #ifdef __cplusplus
58 extern "C" {
59 #endif
60 
61 typedef struct AHardwareBuffer AHardwareBuffer;
62 
63 #define ASENSOR_RESOLUTION_INVALID     (nanf(""))
64 #define ASENSOR_FIFO_COUNT_INVALID     (-1)
65 #define ASENSOR_DELAY_INVALID          INT32_MIN
66 
67 /**
68  * Sensor types.
69  * (keep in sync with hardware/sensors.h)
70  */
71 enum {
72     /**
73      * Invalid sensor type. Returned by {@link ASensor_getType} as error value.
74      */
75     ASENSOR_TYPE_INVALID = -1,
76     /**
77      * {@link ASENSOR_TYPE_ACCELEROMETER}
78      * reporting-mode: continuous
79      *
80      *  All values are in SI units (m/s^2) and measure the acceleration of the
81      *  device minus the force of gravity.
82      */
83     ASENSOR_TYPE_ACCELEROMETER       = 1,
84     /**
85      * {@link ASENSOR_TYPE_MAGNETIC_FIELD}
86      * reporting-mode: continuous
87      *
88      *  All values are in micro-Tesla (uT) and measure the geomagnetic
89      *  field in the X, Y and Z axis.
90      */
91     ASENSOR_TYPE_MAGNETIC_FIELD      = 2,
92     /**
93      * {@link ASENSOR_TYPE_GYROSCOPE}
94      * reporting-mode: continuous
95      *
96      *  All values are in radians/second and measure the rate of rotation
97      *  around the X, Y and Z axis.
98      */
99     ASENSOR_TYPE_GYROSCOPE           = 4,
100     /**
101      * {@link ASENSOR_TYPE_LIGHT}
102      * reporting-mode: on-change
103      *
104      * The light sensor value is returned in SI lux units.
105      */
106     ASENSOR_TYPE_LIGHT               = 5,
107     /**
108      * {@link ASENSOR_TYPE_PROXIMITY}
109      * reporting-mode: on-change
110      *
111      * The proximity sensor which turns the screen off and back on during calls is the
112      * wake-up proximity sensor. Implement wake-up proximity sensor before implementing
113      * a non wake-up proximity sensor. For the wake-up proximity sensor set the flag
114      * SENSOR_FLAG_WAKE_UP.
115      * The value corresponds to the distance to the nearest object in centimeters.
116      */
117     ASENSOR_TYPE_PROXIMITY           = 8,
118     /**
119      * {@link ASENSOR_TYPE_LINEAR_ACCELERATION}
120      * reporting-mode: continuous
121      *
122      *  All values are in SI units (m/s^2) and measure the acceleration of the
123      *  device not including the force of gravity.
124      */
125     ASENSOR_TYPE_LINEAR_ACCELERATION = 10
126 };
127 
128 /**
129  * Sensor accuracy measure.
130  */
131 enum {
132     /** no contact */
133     ASENSOR_STATUS_NO_CONTACT       = -1,
134     /** unreliable */
135     ASENSOR_STATUS_UNRELIABLE       = 0,
136     /** low accuracy */
137     ASENSOR_STATUS_ACCURACY_LOW     = 1,
138     /** medium accuracy */
139     ASENSOR_STATUS_ACCURACY_MEDIUM  = 2,
140     /** high accuracy */
141     ASENSOR_STATUS_ACCURACY_HIGH    = 3
142 };
143 
144 /**
145  * Sensor Reporting Modes.
146  */
147 enum {
148     /** invalid reporting mode */
149     AREPORTING_MODE_INVALID = -1,
150     /** continuous reporting */
151     AREPORTING_MODE_CONTINUOUS = 0,
152     /** reporting on change */
153     AREPORTING_MODE_ON_CHANGE = 1,
154     /** on shot reporting */
155     AREPORTING_MODE_ONE_SHOT = 2,
156     /** special trigger reporting */
157     AREPORTING_MODE_SPECIAL_TRIGGER = 3
158 };
159 
160 /**
161  * Sensor Direct Report Rates.
162  */
163 enum {
164     /** stopped */
165     ASENSOR_DIRECT_RATE_STOP = 0,
166     /** nominal 50Hz */
167     ASENSOR_DIRECT_RATE_NORMAL = 1,
168     /** nominal 200Hz */
169     ASENSOR_DIRECT_RATE_FAST = 2,
170     /** nominal 800Hz */
171     ASENSOR_DIRECT_RATE_VERY_FAST = 3
172 };
173 
174 /**
175  * Sensor Direct Channel Type.
176  */
177 enum {
178     /** shared memory created by ASharedMemory_create */
179     ASENSOR_DIRECT_CHANNEL_TYPE_SHARED_MEMORY = 1,
180     /** AHardwareBuffer */
181     ASENSOR_DIRECT_CHANNEL_TYPE_HARDWARE_BUFFER = 2
182 };
183 
184 /*
185  * A few useful constants
186  */
187 
188 /** Earth's gravity in m/s^2 */
189 #define ASENSOR_STANDARD_GRAVITY            (9.80665f)
190 /** Maximum magnetic field on Earth's surface in uT */
191 #define ASENSOR_MAGNETIC_FIELD_EARTH_MAX    (60.0f)
192 /** Minimum magnetic field on Earth's surface in uT*/
193 #define ASENSOR_MAGNETIC_FIELD_EARTH_MIN    (30.0f)
194 
195 /**
196  * A sensor event.
197  */
198 
199 /* NOTE: Must match hardware/sensors.h */
200 typedef struct ASensorVector {
201     union {
202         float v[3];
203         struct {
204             float x;
205             float y;
206             float z;
207         };
208         struct {
209             float azimuth;
210             float pitch;
211             float roll;
212         };
213     };
214     int8_t status;
215     uint8_t reserved[3];
216 } ASensorVector;
217 
218 typedef struct AMetaDataEvent {
219     int32_t what;
220     int32_t sensor;
221 } AMetaDataEvent;
222 
223 typedef struct AUncalibratedEvent {
224     union {
225         float uncalib[3];
226         struct {
227             float x_uncalib;
228             float y_uncalib;
229             float z_uncalib;
230         };
231     };
232     union {
233         float bias[3];
234         struct {
235             float x_bias;
236             float y_bias;
237             float z_bias;
238         };
239     };
240 } AUncalibratedEvent;
241 
242 typedef struct AHeartRateEvent {
243     float bpm;
244     int8_t status;
245 } AHeartRateEvent;
246 
247 typedef struct ADynamicSensorEvent {
248     int32_t  connected;
249     int32_t  handle;
250 } ADynamicSensorEvent;
251 
252 typedef struct {
253     int32_t type;
254     int32_t serial;
255     union {
256         int32_t data_int32[14];
257         float   data_float[14];
258     };
259 } AAdditionalInfoEvent;
260 
261 /* NOTE: Must match hardware/sensors.h */
262 typedef struct ASensorEvent {
263     int32_t version; /* sizeof(struct ASensorEvent) */
264     int32_t sensor;
265     int32_t type;
266     int32_t reserved0;
267     int64_t timestamp;
268     union {
269         union {
270             float           data[16];
271             ASensorVector   vector;
272             ASensorVector   acceleration;
273             ASensorVector   magnetic;
274             float           temperature;
275             float           distance;
276             float           light;
277             float           pressure;
278             float           relative_humidity;
279             AUncalibratedEvent uncalibrated_gyro;
280             AUncalibratedEvent uncalibrated_magnetic;
281             AMetaDataEvent meta_data;
282             AHeartRateEvent heart_rate;
283             ADynamicSensorEvent dynamic_sensor_meta;
284             AAdditionalInfoEvent additional_info;
285         };
286         union {
287             uint64_t        data[8];
288             uint64_t        step_counter;
289         } u64;
290     };
291 
292     uint32_t flags;
293     int32_t reserved1[3];
294 } ASensorEvent;
295 
296 struct ASensorManager;
297 /**
298  * {@link ASensorManager} is an opaque type to manage sensors and
299  * events queues.
300  *
301  * {@link ASensorManager} is a singleton that can be obtained using
302  * ASensorManager_getInstance().
303  *
304  * This file provides a set of functions that uses {@link
305  * ASensorManager} to access and list hardware sensors, and
306  * create and destroy event queues:
307  * - ASensorManager_getSensorList()
308  * - ASensorManager_getDefaultSensor()
309  * - ASensorManager_getDefaultSensorEx()
310  * - ASensorManager_createEventQueue()
311  * - ASensorManager_destroyEventQueue()
312  */
313 typedef struct ASensorManager ASensorManager;
314 
315 
316 struct ASensorEventQueue;
317 /**
318  * {@link ASensorEventQueue} is an opaque type that provides access to
319  * {@link ASensorEvent} from hardware sensors.
320  *
321  * A new {@link ASensorEventQueue} can be obtained using ASensorManager_createEventQueue().
322  *
323  * This file provides a set of functions to enable and disable
324  * sensors, check and get events, and set event rates on a {@link
325  * ASensorEventQueue}.
326  * - ASensorEventQueue_enableSensor()
327  * - ASensorEventQueue_disableSensor()
328  * - ASensorEventQueue_hasEvents()
329  * - ASensorEventQueue_getEvents()
330  * - ASensorEventQueue_setEventRate()
331  */
332 typedef struct ASensorEventQueue ASensorEventQueue;
333 
334 struct ASensor;
335 /**
336  * {@link ASensor} is an opaque type that provides information about
337  * an hardware sensors.
338  *
339  * A {@link ASensor} pointer can be obtained using
340  * ASensorManager_getDefaultSensor(),
341  * ASensorManager_getDefaultSensorEx() or from a {@link ASensorList}.
342  *
343  * This file provides a set of functions to access properties of a
344  * {@link ASensor}:
345  * - ASensor_getName()
346  * - ASensor_getVendor()
347  * - ASensor_getType()
348  * - ASensor_getResolution()
349  * - ASensor_getMinDelay()
350  * - ASensor_getFifoMaxEventCount()
351  * - ASensor_getFifoReservedEventCount()
352  * - ASensor_getStringType()
353  * - ASensor_getReportingMode()
354  * - ASensor_isWakeUpSensor()
355  */
356 typedef struct ASensor ASensor;
357 /**
358  * {@link ASensorRef} is a type for constant pointers to {@link ASensor}.
359  *
360  * This is used to define entry in {@link ASensorList} arrays.
361  */
362 typedef ASensor const* ASensorRef;
363 /**
364  * {@link ASensorList} is an array of reference to {@link ASensor}.
365  *
366  * A {@link ASensorList} can be initialized using ASensorManager_getSensorList().
367  */
368 typedef ASensorRef const* ASensorList;
369 
370 /*****************************************************************************/
371 
372 /**
373  * Get a reference to the sensor manager. ASensorManager is a singleton
374  * per package as different packages may have access to different sensors.
375  *
376  * Deprecated: Use ASensorManager_getInstanceForPackage(const char*) instead.
377  *
378  * Example:
379  *
380  *     ASensorManager* sensorManager = ASensorManager_getInstance();
381  *
382  */
383 __attribute__ ((deprecated)) ASensorManager* ASensorManager_getInstance();
384 
385 /*
386  * Get a reference to the sensor manager. ASensorManager is a singleton
387  * per package as different packages may have access to different sensors.
388  *
389  * Example:
390  *
391  *    ASensorManager* sensorManager = ASensorManager_getInstanceForPackage("foo.bar.baz");
392  *
393  */
394 ASensorManager* ASensorManager_getInstanceForPackage(const char* packageName);
395 
396 /**
397  * Returns the list of available sensors.
398  */
399 int ASensorManager_getSensorList(ASensorManager* manager, ASensorList* list);
400 
401 /**
402  * Returns the default sensor for the given type, or NULL if no sensor
403  * of that type exists.
404  */
405 ASensor const* ASensorManager_getDefaultSensor(ASensorManager* manager, int type);
406 
407 #if __ANDROID_API__ >= 21
408 /**
409  * Returns the default sensor with the given type and wakeUp properties or NULL if no sensor
410  * of this type and wakeUp properties exists.
411  */
412 ASensor const* ASensorManager_getDefaultSensorEx(ASensorManager* manager, int type, bool wakeUp);
413 #endif
414 
415 /**
416  * Creates a new sensor event queue and associate it with a looper.
417  *
418  * "ident" is a identifier for the events that will be returned when
419  * calling ALooper_pollOnce(). The identifier must be >= 0, or
420  * ALOOPER_POLL_CALLBACK if providing a non-NULL callback.
421  */
422 ASensorEventQueue* ASensorManager_createEventQueue(ASensorManager* manager,
423         ALooper* looper, int ident, ALooper_callbackFunc callback, void* data);
424 
425 /**
426  * Destroys the event queue and free all resources associated to it.
427  */
428 int ASensorManager_destroyEventQueue(ASensorManager* manager, ASensorEventQueue* queue);
429 
430 #if __ANDROID_API__ >= __ANDROID_API_O__
431 /**
432  * Create direct channel based on shared memory
433  *
434  * Create a direct channel of {@link ASENSOR_DIRECT_CHANNEL_TYPE_SHARED_MEMORY} to be used
435  * for configuring sensor direct report.
436  *
437  * \param manager the {@link ASensorManager} instance obtained from
438  *                {@link ASensorManager_getInstanceForPackage}.
439  * \param fd      file descriptor representing a shared memory created by
440  *                {@link ASharedMemory_create}
441  * \param size    size to be used, must be less or equal to size of shared memory.
442  *
443  * \return a positive integer as a channel id to be used in
444  *         {@link ASensorManager_destroyDirectChannel} and
445  *         {@link ASensorManager_configureDirectReport}, or value less or equal to 0 for failures.
446  */
447 int ASensorManager_createSharedMemoryDirectChannel(ASensorManager* manager, int fd, size_t size);
448 
449 /**
450  * Create direct channel based on AHardwareBuffer
451  *
452  * Create a direct channel of {@link ASENSOR_DIRECT_CHANNEL_TYPE_HARDWARE_BUFFER} type to be used
453  * for configuring sensor direct report.
454  *
455  * \param manager the {@link ASensorManager} instance obtained from
456  *                {@link ASensorManager_getInstanceForPackage}.
457  * \param buffer  {@link AHardwareBuffer} instance created by {@link AHardwareBuffer_allocate}.
458  * \param size    the intended size to be used, must be less or equal to size of buffer.
459  *
460  * \return a positive integer as a channel id to be used in
461  *         {@link ASensorManager_destroyDirectChannel} and
462  *         {@link ASensorManager_configureDirectReport}, or value less or equal to 0 for failures.
463  */
464 int ASensorManager_createHardwareBufferDirectChannel(
465         ASensorManager* manager, AHardwareBuffer const * buffer, size_t size);
466 
467 /**
468  * Destroy a direct channel
469  *
470  * Destroy a direct channel previously created using {@link ASensorManager_createDirectChannel}.
471  * The buffer used for creating direct channel does not get destroyed with
472  * {@link ASensorManager_destroy} and has to be close or released separately.
473  *
474  * \param manager the {@link ASensorManager} instance obtained from
475  *                {@link ASensorManager_getInstanceForPackage}.
476  * \param channelId channel id (a positive integer) returned from
477  *                  {@link ASensorManager_createSharedMemoryDirectChannel} or
478  *                  {@link ASensorManager_createHardwareBufferDirectChannel}.
479  */
480 void ASensorManager_destroyDirectChannel(ASensorManager* manager, int channelId);
481 
482 /**
483  * Configure direct report on channel
484  *
485  * Configure sensor direct report on a direct channel: set rate to value other than
486  * {@link ASENSOR_DIRECT_RATE_STOP} so that sensor event can be directly
487  * written into the shared memory region used for creating the buffer. It returns a positive token
488  * which can be used for identify sensor events from different sensors on success. Calling with rate
489  * {@link ASENSOR_DIRECT_RATE_STOP} will stop direct report of the sensor specified in the channel.
490  *
491  * To stop all active sensor direct report configured to a channel, set sensor to NULL and rate to
492  * {@link ASENSOR_DIRECT_RATE_STOP}.
493  *
494  * In order to successfully configure a direct report, the sensor has to support the specified rate
495  * and the channel type, which can be checked by {@link ASensor_getHighestDirectReportRateLevel} and
496  * {@link ASensor_isDirectChannelTypeSupported}, respectively.
497  *
498  * Example:
499  * \code{.cpp}
500  *      ASensorManager *manager = ...;
501  *      ASensor *sensor = ...;
502  *      int channelId = ...;
503  *
504  *      ASensorManager_configureDirectReport(
505  *              manager, sensor, channel_id, ASENSOR_DIRECT_RATE_FAST);
506  * \endcode
507  *
508  * \param manager   the {@link ASensorManager} instance obtained from
509  *                  {@link ASensorManager_getInstanceForPackage}.
510  * \param sensor    a {@link ASensor} to denote which sensor to be operate. It can be NULL if rate
511  *                  is {@link ASENSOR_DIRECT_RATE_STOP}, denoting stopping of all active sensor
512  *                  direct report.
513  * \param channelId channel id (a positive integer) returned from
514  *                  {@link ASensorManager_createSharedMemoryDirectChannel} or
515  *                  {@link ASensorManager_createHardwareBufferDirectChannel}.
516  *
517  * \return positive token for success or negative error code.
518  */
519 int ASensorManager_configureDirectReport(
520         ASensorManager* manager, ASensor const* sensor, int channelId, int rate);
521 #endif
522 
523 /*****************************************************************************/
524 
525 /**
526  * Enable the selected sensor with a specified sampling period and max batch report latency.
527  * Returns a negative error code on failure.
528  * Note: To disable the selected sensor, use ASensorEventQueue_disableSensor() same as before.
529  */
530 int ASensorEventQueue_registerSensor(ASensorEventQueue* queue, ASensor const* sensor,
531         int32_t samplingPeriodUs, int64_t maxBatchReportLatencyUs);
532 
533 /**
534  * Enable the selected sensor. Returns a negative error code on failure.
535  */
536 int ASensorEventQueue_enableSensor(ASensorEventQueue* queue, ASensor const* sensor);
537 
538 /**
539  * Disable the selected sensor. Returns a negative error code on failure.
540  */
541 int ASensorEventQueue_disableSensor(ASensorEventQueue* queue, ASensor const* sensor);
542 
543 /**
544  * Sets the delivery rate of events in microseconds for the given sensor.
545  * Note that this is a hint only, generally event will arrive at a higher
546  * rate. It is an error to set a rate inferior to the value returned by
547  * ASensor_getMinDelay().
548  * Returns a negative error code on failure.
549  */
550 int ASensorEventQueue_setEventRate(ASensorEventQueue* queue, ASensor const* sensor, int32_t usec);
551 
552 /**
553  * Returns true if there are one or more events available in the
554  * sensor queue.  Returns 1 if the queue has events; 0 if
555  * it does not have events; and a negative value if there is an error.
556  */
557 int ASensorEventQueue_hasEvents(ASensorEventQueue* queue);
558 
559 /**
560  * Returns the next available events from the queue.  Returns a negative
561  * value if no events are available or an error has occurred, otherwise
562  * the number of events returned.
563  *
564  * Examples:
565  *   ASensorEvent event;
566  *   ssize_t numEvent = ASensorEventQueue_getEvents(queue, &event, 1);
567  *
568  *   ASensorEvent eventBuffer[8];
569  *   ssize_t numEvent = ASensorEventQueue_getEvents(queue, eventBuffer, 8);
570  *
571  */
572 ssize_t ASensorEventQueue_getEvents(ASensorEventQueue* queue, ASensorEvent* events, size_t count);
573 
574 
575 /*****************************************************************************/
576 
577 /**
578  * Returns this sensor's name (non localized)
579  */
580 const char* ASensor_getName(ASensor const* sensor);
581 
582 /**
583  * Returns this sensor's vendor's name (non localized)
584  */
585 const char* ASensor_getVendor(ASensor const* sensor);
586 
587 /**
588  * Return this sensor's type
589  */
590 int ASensor_getType(ASensor const* sensor);
591 
592 /**
593  * Returns this sensors's resolution
594  */
595 float ASensor_getResolution(ASensor const* sensor);
596 
597 /**
598  * Returns the minimum delay allowed between events in microseconds.
599  * A value of zero means that this sensor doesn't report events at a
600  * constant rate, but rather only when a new data is available.
601  */
602 int ASensor_getMinDelay(ASensor const* sensor);
603 
604 #if __ANDROID_API__ >= 21
605 /**
606  * Returns the maximum size of batches for this sensor. Batches will often be
607  * smaller, as the hardware fifo might be used for other sensors.
608  */
609 int ASensor_getFifoMaxEventCount(ASensor const* sensor);
610 
611 /**
612  * Returns the hardware batch fifo size reserved to this sensor.
613  */
614 int ASensor_getFifoReservedEventCount(ASensor const* sensor);
615 
616 /**
617  * Returns this sensor's string type.
618  */
619 const char* ASensor_getStringType(ASensor const* sensor);
620 
621 /**
622  * Returns the reporting mode for this sensor. One of AREPORTING_MODE_* constants.
623  */
624 int ASensor_getReportingMode(ASensor const* sensor);
625 
626 /**
627  * Returns true if this is a wake up sensor, false otherwise.
628  */
629 bool ASensor_isWakeUpSensor(ASensor const* sensor);
630 #endif /* __ANDROID_API__ >= 21 */
631 
632 #if __ANDROID_API__ >= __ANDROID_API_O__
633 /**
634  * Test if sensor supports a certain type of direct channel.
635  *
636  * \param sensor  a {@link ASensor} to denote the sensor to be checked.
637  * \param channelType  Channel type constant, either
638  *                     {@ASENSOR_DIRECT_CHANNEL_TYPE_SHARED_MEMORY}
639  *                     or {@link ASENSOR_DIRECT_CHANNEL_TYPE_HARDWARE_BUFFER}.
640  * \returns true if sensor supports the specified direct channel type.
641  */
642 bool ASensor_isDirectChannelTypeSupported(ASensor const* sensor, int channelType);
643 /**
644  * Get the highest direct rate level that a sensor support.
645  *
646  * \param sensor  a {@link ASensor} to denote the sensor to be checked.
647  *
648  * \return a ASENSOR_DIRECT_RATE_... enum denoting the highest rate level supported by the sensor.
649  *         If return value is {@link ASENSOR_DIRECT_RATE_STOP}, it means the sensor
650  *         does not support direct report.
651  */
652 int ASensor_getHighestDirectReportRateLevel(ASensor const* sensor);
653 #endif
654 
655 #ifdef __cplusplus
656 };
657 #endif
658 
659 #endif // ANDROID_SENSOR_H
660 
661 /** @} */
662