- 
                Notifications
    
You must be signed in to change notification settings  - Fork 8.2k
 
Description
API meeting (@carlescufi):
- Currently (for the next month, until 8th March) under discussion in this Google doc: https://docs.google.com/document/d/1UsElJJHRudeWXb-tYwXA6qt9gF6PH8wwS7PjhqO1MLI/edit#bookmark=id.jkiwnksvdslt
 
Updated Sensor API
This issue is an attempt to start identifying improvements that can be made to the current sensor API in Zephyr, with the goal of defining a new API that will eventually replace the existing one.
A more formal proposal will be made in due time, but any weaknesses in the current API can be listed here, or requirements for a new API.
The current proposals are based on existing issues and discussion during the weekly API call, and are subject to revision. They do no reflect definitive positions, rather a starting point to define a more flexible sensor architecture.
Project Management
The overall sensor API project is tracked here.
Components (Issues, PRs)
The following issues or PRs are part of the overall sensor API project, and are used for tracking purposes:
- TODO
 
Two-tier sensor data API (raw + SI)
- Raw data at the lowest level (mandatory: channel 0, attribute 0):
- Memory efficient (Two mandatory 32-bit values today)
 - Low latency
 - Higher processing burden in user land
 
 - Standardised SI-based data at the higher-level (mandatory: channel 0: attribute 1):
- Higher per-sample memory use
 - Higher latency
 - Low user processing burden (standard SI units and scale, filtering, etc.)
 - Smarter event callbacks based on richer data filtering, etc.
 
 
Both tiers must be implemented in a valid sensor driver.
General Requirements
Timestamp API
- Timestamping API for individual samples, required for DSP filters, logs, etc.
 - An option should be provided to enable or disable this feature (memory constraint).
 
Flexible Execution Context
- Allow execution context to be specified by user, with a goal of enabling
a single thread or limited thread count for all sensor activity. 
Internal FIFO Management
- Sensor data is cached via a FIFO buffer associated with channel attributes
 - Allows more efficient resource usage, lower user-burden.
 - FIFO should have watermark/threshold alert(s).
 - An appropriate set of helper functions should be provided to filter and manipulate buffers.
 - It should be possible to use one buffer across multiple attributes efficiently.
 
Sensor Data
- Enable raw data for smallest footprint with higher user burden.
 - Driver MUST implement raw->stdtype conversion function(s) or provide necessary converstion coefficients (via attributes, etc.)
 - Determine sensible SI unit/scale per channel or sensor type
- Should scale be adjustable at the KConfig level? Auto-scaling?
 
 - Where possible, flag missed sample(s) event between reads.
 - Optionally associate variable meta-data (die temp, etc.) with sample.
- Memory an issue here
 - Seems like this should possible via attributes
 
 
Current thinking is that all sensor data will be based on attribute records, with each channel in the sensor driver having appropriate attributes like
CHAN_ATTR_RAW_DATAandCHAN_ATTR_SI_DATA. Each attribute is associated with an appropriate data type and payload.
Channels
- Channels indicate a specific type of sensor data or information (ex. 
CHAN_ACCEL_VECT, and may have generic catch-all versions likeCHAN_LIGHTas well as more narrowly defined subtypes likeCHAN_LIGHT_IR). - Allow multiple instances of a channel.
 - Meta-data can be assigned to channels via channel attributes, for example you can associate a wavelength value or range to an instance of the 
CHAN_LIGHTchannel via theCHAN_ATTR_FREQUENCYattribute. 
Attributes (Device + Channel)
A flexible, generic system is required here, though further discussion is
needed to define the initial attribute list.
Attributes will allow a high degree of flexibility, with only a minimal set of mandatory attribute required for basic drivers.
- Current thinking (subject to debate!) is that two types of attributes makes sense: device attributes, and channel attributes. Needs testing to validate of course.
 
Triggers
Triggers are associate with channel attributes, and provide a mechanism to indicate how or when a channel attribute should be updated.
- Review and revise current overly-narrow list of trigger events.
 - Use a singly-linked list of callbacks that can be traversed asynchronously,
starting in the IRQ handler but with the blocking SPI/I2C/ADC calls
elsewhere. An slist allows this to be dynamically adjusted at runtime. 
Events
- A callback based 'event' system might make debugging and characterisation easier by making it easy to defer error handling, and state tracking to the app level. For example, by having events fire and optionally subscribing to them via a generic callback, you can track conversion start and end events and see if there is a disparity (indicating conversion errors), etc.)
 
Additional APIs or Requirements
Calibration API?
- Common API to calculate, load/store and apply calibration coefficients?
 
Logging/Storage API?
- Centralised logging API for sensor data to make storing and off-loading
sensor data at a later date easier? Persist data in a standard format to
NVM, etc.? 
Device Simulation?
While perhaps not restricted to the sensor API, a design goal should be
enabling simulation of specific sensors when HW isn't available, or specific
edge cases are difficult to reproduce on real HW (to properly test algorithms
or application code that relies on sensor data).
- Allow a sensor driver to 'register' itself at a specific I2C address, and
in a simulated environment when a generic I2C read/write request is made, the
I2C handler can redirect the request to the simulated function in the driver. - The following functions would be required for I2C sensors, for example:
- Read request handler
 - Write request handler
 - Init function to register the simulated device with the generic I2C layer.
 
 
For an example of this using I2C, see mcu_sim_i2c.h from Apache
Mynewt, and tsl2591_sim.c for a partial implementation of
this concept.
Permissions API?
Is a permissions API required/useful/relevant? Should some level of control be put in place over, for example, being able to access raw or sensitive data?
- Perhaps an 8-bit value can be associated with a device or channel attribute with flags like 
Read
,Write,Public,Private, etc.? 
Firmware Management?
Certain classes of sensors today have user updatable firmware. It's worth at least considering some of the implications around this, and how to update sensors on deployed devices, even if it's a very manufacturer-specific requirement.
Security Considerations
There are a number of critical security consideration to keep in mind when working with sensor data, and how it is exposed. For example, on devices with touch screens where a password may be entered, and where sensor data like accel/mag/gyro readings is publicly being streamed out, you can detect passwords based on the sensor data.
There should perhaps be some security mechanisms in situations like entering a password, where certain classes of sensors can be disabled to reduce the overall risk (disable the accel and gyro while the password screen is shown or while a keypad is being used for password or ID entry).
This fits into the permissions API idea to an extent, but is sufficiently different to merit individual consideration.
The W3 Generic Sensor API highlights a number of security risks associated with sensors, and some suggestions on mitigating these risks. It's worth reading through for the numerous practical implications the document details.
Discussion of accelerometer abuse in mobile devices: https://www.mysk.blog/2021/10/24/accelerometer-ios/
Sensor rate limiting on Android as a security mitigation: https://developer.android.com/guide/topics/sensors/sensors_overview#sensors-rate-limiting
Related Issues
#14008 : WIP: Sensor API Playground
#13455 : Improvements to drivers/sensors for light sensors
#1387 : Lack of a performant sensor API
#14245 : Sensor API channel definitions
Existing APIs to consider
- Linux IIO
 - W3 Generic Sensor API
 - Android Sensor API and ContextHub
- Related Android Sensor API components:
- ISensors
 - ISensorManager
 - ContextHub
 - Channels, event, etc.: sensors-base.h
 - Core structs like 
sensors_event_tsensors.h 
 
 - Related Android Sensor API components:
 
Context hub is intended to enable the use of additional co-processors for sensor data, and the interaction between context hub and the main kernel or sensor API might have some useful insights to consider.
Metadata
Metadata
Assignees
Labels
Type
Projects
Status
Status