This specification defines a generic API for getting access to information provided by sensors available from a hosting device.

Introduction

This section is non-normative

This specification defines an API that allows application code to obtain information given by the various sensors available on a hosting device. The information provided through this API is raw sensor data. The specification is aimed at covering well-known sensors that are commonly found in devices. Nonetheless, the API is extensible, allowing to integrate vendor or external specific sensors if necessary .

The following code snippet illustrates how to monitor sensor data, for instance the ambient temperature:

			var sensorCnx = new SensorConnection('Temperature');
			sensorCnx.addEventListener('sensordata', function(e) {
				if(e.data > 20.0) {
					window.console.log('Temperature is too high!!!!');
				}
			} );
			
			var watchOptions = { interval: (15 * 60 * 1000) };
			sensorCnx.startWatch(watchOptions);
		

The following code snippet illustrates how to list all sensors hosted on the device:

			var sensorReq = navigator.sensors.list();
			
			sensorReq.onsuccess = function() {
			  for(var count = 0; count < this.result.length; count++) {
			    window.console.log("Sensor Found: " + this.result[count].type);
			  }
			}
			
			sensorReq.onerror = function() {
			  window.console.error(this.error.code);
			}
		

The following example shows how to connect to a default accelerometer sensor hosted on the device

		    var accel = navigator.sensors.Accelerometer;
		    accel.onsensordata = function(e) {
		      window.console.log("Accelerometer data: " + e.data.x + ", " + e.data.y)
		    }
		    accel.startWatch(1000);
		

This specification defines conformance criteria that apply to a single product: the user agent that implements the interfaces that it contains.

Implementations that use ECMAScript to implement the APIs defined in this specification MUST implement them in a manner consistent with the ECMAScript Bindings defined in the Web IDL specification [[!WEBIDL]], as this specification uses that specification and terminology.

A conforming implementation is required to implement all fields defined in this specification.

Security and Privacy Considerations

A conforming implementation of this specification must provide a mechanism that protects the user's privacy and this mechanism should ensure that no sensitive information is made available through this API without the user's express permission. User agents must acquire permission through a user interface, unless they have prearranged trust relationships with users.

Navigator Extensions

readonly attribute SensorManager sensors
Attribute to get access to the sensors functionality

Sensor Management

SensorManager

This interface allows applications to know what sensors are available from the device. The sensor information is acquired by calling platform native sensor interfaces, creating a list of Sensor objects, and populating that object with appropriate data accordingly.

SensorRequest list()

This is an asynchronous API that returns without blocking the calling thread.

When invoked the user agent MUST immediately return a SensorRequest instance (with done flag set to false), which does not initially contain any information about the result of the operation. If the user permissions are ok then the UA MUST queue a new listSensors process that will call platform native sensor interfaces to fill a list of SensorInfo with the type of sensors hosted by the device.

If user permissions are not ok the process must finish and an error event on the request with error code PERMISSION_DENIED MUST be fired.

Once the listSensors process finishes without error, an event is fired on the request, the done flag is set to true and the information becomes available through the properties of the SensorRequest instance. If an error occurs while performing the operation, the readyState is changed to done, the error is set to the code of the error, and a event with type error is fired at the request.

SensorConnection getter(DOMString sensorType)
It must provide a SensorConnection to the default sensor of the specified type hosted on the device

SensorRequest

This interface provides means to access results of asynchronous sensor discovery requests.
readonly attribute SensorInfo result
When the done flag is true, getting this property MUST return a list with information about sensors. This is undefined when the request resulted in an error. When the done flag is false, getting this property must throw a InvalidStateError.
readonly attribute SensorError error
When the done flag is true, getting this property MUST return the error of the request. This is null when no error occurred. When the done flag is false, getting this property MUST throw a DOMException of type InvalidStateError.
readonly attribute DOMString readyState
Represents the status of the request. It MUST be set to one of the following:
  • processing. If the done flag is false.
  • done. If the done flag is true.
attribute Function onsuccess
The event handler for the success event
attribute Function onerror
The event handler for the error event

SensorInfo

This interface defines the minimum information about a sensor hosted on a device.

readonly attribute DOMString type
It must return the type of sensor
readonly attribute DOMString id
It must return a unique identifier for the sensor

Sensor Metadata

Sensor

The Sensor object contains different attributes that provide sensor metadata.
readonly attribute float? resolution
It must return the sensor's resolution of the sensor in the sensor's unit or null if this parameter is not known to the implementation.
readonly attribute short? minDelay
It must return the minimum delay allowed between two sensor data events in microseconds or zero if only sensor data events are dispatched when there is a change in the measured magnitude. null must be returned if this parameter is not known to the implementation.
readonly attribute short? range
It must return the maximum range of the sensor in the sensor's unit or null if it is not known.
readonly attribute DOMString id
It must return an identifier for the sensor.
readonly attribute DOMString type
It must return the sensor type. See table below for a list sensor types defined by this specification
readonly attribute float? power
It must return the power in mA used by this sensor while in use. null if this parameter is not available
readonly attribute DOMString? vendor
It must return a string that identifies the vendor of the sensor. null if this data is not available.

Sensor Data

SensorConnection Interface

The SensorConnection object is an event target that MUST be used to request a connection to a sensor of a specified type on the hosting device. The sensor connection is acquired by calling platform native sensor interfaces.
readonly attribute Sensor meta
It must return the metadata of the sensor that is currently connected to this event target. If the connection is on the "new" state an InvalidStateError must be thrown.
readonly attribute DOMString status
Represents the current status of the event target. The status MUST be set to one of the following:
  • new. The object has been instantiated but a connection to the sensor has not been established yet.
  • open. All the infrastructure to get sensor data is ready.
  • watching. The sensor is under monitoring.
  • disconnected. The connection with the sensor has been lost.
  • error. An error has occured
readonly attribute SensorError? error
The code attribute of a SensorError object must return the code for the error. This is null when no error occurred.
attribute Function? onerror
Allows to set an event handler that will be invoked when the sensor connection is in error
attribute Function? onsensordata
Allows to set an event handler that will be invoked when new sensor data is available
attribute Function? onstatuschange
Allows to set an event handler that will be invoked when connection status change
attribute Function? oncalibneed
Allows to set an event handler that will be invoked when the sensor needs calibration
void read()
When invoked the user agent MUST run the following steps:
  1. If the status is other than open or watching an ILLEGAL_STATE exception MUST be thrown.
  2. Otherwise the user agent MUST queue a task TRead to perform a reading from the sensor and then return immediately.
  3. Once TRead has finished successfully, the implementation MUST queue a task to fire a SensorDataEvent with:
    • data field equal to the values read from the sensor.
    • reason field equal to 'read'
  4. If TRead fails Queue a task to fire a simple event named error at the SensorConnection.
void startWatch(SensorWatchOptions watchOptions)

When called the user agent MUST run the following steps:

  1. If status is other than open an ILLEGAL_STATE exception MUST be thrown
  2. If status is open then run the following sub-steps:
    1. Queue a task TWatch in charge of invoking the platform native interfaces to start monitoring sensor values in accordance with the parameters specified as part of SensorWatchOptions argument. Then, return immediately to the caller.
    2. If TWatch succeeds, the status attribute MUST be set to the watching value. Queue a task to fire a simple event named statuschange at the SensorConnection
    3. If TWatch fails then Queue a task to fire a simple event named error at the SensorConnection.

Everytime the platform monitoring mechanism notifies of a new sensor value the user agent MUST queue a task to fire a SensorDataEvent with:

  • data field equal to the values read from the sensor
  • reason field equal to 'watch'
void endWatch()
When this method is called the user agent MUST run the following steps:
  1. If status is other than watching an ILLEGAL_STATE exception MUST be thrown.
  2. If status is watching then the following substeps MUST be done:
    1. Invoke platform native interfaces to notify the end of the monitoring.
    2. If the invocation succeeds, the status attribute MUST be set to the open value and the control MUST be returned to the caller. Finally, Queue a task to fire a simple event named statuschange at the SensorConnection.
    3. If the invocation fails Queue a task to fire a simple event named error at the SensorConnection.
[Constructor(SensorOptions options)]
Constructs a new SensorConnection. when invoked the user agent MUST run the following steps:
  1. Let _sensor be the target sensor to be connected to. If none of the dictionary members are defined then raise an instantiation exception.
  2. If the dictionary member id is not defined then _sensor MUST correspond to the default sensor type specified by the type member. Otherwise _sensor MUST be assigned to a sensor of the specified type and whose identifier is equal to the id member.
  3. Check if the sensor identified by _sensor is available and ready to be connected
  4. If the sensor exists, is available and user permissions are ok, then instantiate a SensorConnection object and set its status to 'open'.
  5. If user permissions are needed then instantiate the SensorConnection object, set its status to 'new' and prompt the user in a user-agent-specific manner for permission.

    Once the user gives permission set status to 'open'. If the user does not give permission set status to 'error' with error code to PERMISSION_DENIED.

  6. If the sensor is not available or does not exist raise an instantiation exception (tbd).

Implementations MAY support other connection options as part of the SensorOptions interface

[Constructor(DOMString type)]
Constructs a new SensorConnection by passing a sensor type. This is a convenient function for the more general function described above.

These constructors must be visible when the script's global object is either a Window object or an object implementing the WorkerUtils interface.

SensorOptions Dictionary

DOMString type
Sensor type for which a connection is requested
DOMString id
Sensor id for which a connection is requested

SensorWatchOptions Dictionary

attribute double threshold
This attribute only applies to sensors that provide single value readings. It indicates that a data event MUST only be raised when the sensor reaches a value below the specified threshold.

This attribute is likely to be revisited to support these use cases:
- Low and high thresholds
- Ranges [10,20] (10,20] ....
- Thresholds that apply to the different data components of a sensor, for instance x,y,z in the case of accelerometer.

attribute double interval
The interval attribute represents the monitorization interval at which data SHOULD be obtained from the underlying sensor hardware and must be expressed in milliseconds. The caller should be aware that setting a value too small can adversely affect the battery life. If the interval is set to zero, then the implementation MUST return sensor data only when there is a change since the last acquisition.

SensorDataEvent Interface

Once the spec progress this section will be changed to comply with the DOM4 Event interfaces

readonly attribute any data
This attribute represents the raw data provided by the sensor. The specific type depends on the type of the sensor. See for implementation requirements for this attribute depending on the type of sensor.
readonly attribute DOMString accuracy
This attribute MUST return an enumerated value that gives an indication of the accuracy of the sensor data. The allowed values are:
  • high - This sensor is reporting data with maximum accuracy
  • medium - This sensor is reporting data with average accuracy, calibration with the environment may improve readings
  • low This sensor is reporting data with low level of accuracy, calibration with the environment is needed
  • unreliable - This sensor is reporting data that can't be trusted, calibration is needed.
readonly attribute double timestamp
The time in nanosecond at which the sensor data was read.
readonly attribute DOMString reason
It is a string that denotes the reason for this data. The only admissible values for this attribute are:
  • read. The event was raised due to a read operation
  • watch. The event was raised due to a watch operation
void initSensorDataEvent(in DOMString type, in boolean bubbles, in boolean cancelable, in DOMString reason, in double timestamp, in DOMString accuracy, in any data)
Initializes a SensorDataEvent created through the DocumentEvent interface.

A section describing all the events defined by the API might be added for next draft.

Sensor Data Implementation Requirements

Summary

An implementation MUST set the specific data type of the SensorDataEvent.data attribute in accordance with the following table:

Sensor Type Data Type Units
Temperaturedoubledegree Celsius (ºC)
AmbientLightdoubleLux
AmbientNoisedoubledbA
MagneticFieldMagneticFieldDatamicro-Tesla (uTesla)
Proximitydoublecentimetres (cm)
AtmPressuredoublekiloPascal (kP)
RelHumiditydouble
AccelerometerAccelerationDatameters/second^2 (m/s2)
GyroscopeRotationDataradians/second
OrientationOrientationDataradians

The AccelerationData interface

readonly attribute double x
readonly attribute double y
readonly attribute double z

The MagneticFieldData interface

readonly attribute double x
ambient magnetic field in X
readonly attribute double y
ambient magnetic field in Y
readonly attribute double z
ambient magnetic field in Z

The RotationData interface

readonly attribute double x
Angular speed around the x-axis
readonly attribute double y
Angular speed around the y-axis
readonly attribute double z
Angular speed around the z-axis

The OrientationData interface

readonly attribute double alpha
readonly attribute double beta
readonly attribute double gamma

Errors

Sensor Error

readonly attribute DOMString message
Error message
readonly attribute unsigned short code
Error code
const unsigned short PERMISSION_DENIED = -100
The user has not given permission

Acknowledgements

WAC Ipanema Device APIs Lightweight Participation WG, in particular Bryan Sullivan, Balaji N.V., and Kaushik Das.

Free Web Hosting