Webinos Logo

The Generic Sensor API

Webinos API Specifications

29 Aug 2012

Authors


Abstract

The Webinos Generic Sensor API provides web applications with an API to access data from sensors in the device or in another device.

Table of Contents

  1. Introduction
  2. Interfaces and Dictionaries
    1. Sensor
    2. ConfigureSensorOptions
    3. GeoPosition
    4. PendingSensorConfigOp
    5. SensorEvent
  3. Callbacks
    1. SensorErrorCB
  4. Enums
    1. EventFireMode
    2. Accuracy
  5. Features
  6. Full WebIDL

Summary of Methods

Interface Method
Sensor PendingSensorConfigOp configureSensor(ConfigureSensorOptions options, VoidFunction successCB, SensorErrorCB errorCB)
PendingSensorConfigOp void cancel()
SensorEvent void initSensorEvent(DOMString type, boolean bubbles, boolean cancelable, DOMString sensorType, DOMString sensorId, Accuracy accuracy, unsigned long rate, EventFireMode eventFireMode, float[] sensorValues, GeoPosition position)

Introduction

The API is agnostic to underlying low level methods for sensor discovery and communication with sensors. However, the sensor API should be used in combination with the general Webinos service discovery methods findServices() and bind(). The sensors services can be located in the user's personal zone or be shared on the current network.

The API consists of two interfaces:
- A sensor interface that provides attributes for the sensors and a method to configure a selected sensor.
- A DOM level 3 event that provides sensor data.

This list of sensor types supported in the API could easily be extended with additional sensor types.

Implementation notes:
- From the security point of view an extensible set of features identifying the various sensor types is reported; this allows a granular control on the type os sensor that can be accessed. Another feature (sensor.read) that does not allow access to configuration capabilities has been added. This model may be modified due to further studies that will follow during implementation.
- Consider a visual warning on the device when the sensor is accessed, to avoid eavesdropping / privacy invasion by a remote or local application.
- Consider roaming costs for accessing remote sensors through the mobile network. An implementation might provide 'roaming' and 'non-roaming' profiles.
- Avoid unnecessary high rates of sensor events. Consider battery drain.

Interfaces and Dictionaries

Interface Sensor

This interface defines sensor properties. It is a sensor specific extension to the interface Service in the ServiceDiscovery module. The added attributes correspond to Android sensor API attributes.

WebIDL
    interface Sensor : Service {
 

        readonly attribute float?          maximumRange;


        readonly attribute unsigned long?   minDelay;


        readonly attribute float?         power;


        readonly attribute float?         resolution;


        readonly attribute DOMString?      vendor;  


        readonly attribute unsigned long?  version; 


        PendingSensorConfigOp configureSensor (ConfigureSensorOptions options, VoidFunction successCB, optional SensorErrorCB errorCB);
     };
Code example
        // Handle that can be used to cancel the ongoing asynchronous discovery process.
        var findHandle = 0;

        // Handle from service.bind.
        var sensorHandle = 0;

        // Array of found temperature sensors object.
        var availableTempSensors = {};
                 
        // Callback method that display a list of found sensors in a selection list
        // The selection list is dynamically extended every time a new sensor is discovered.
        function sensorFoundCB(sensor) {

                var selectlist = document.getElementById('sensorlist');
                var option = document.createElement('option');
                option.value = sensor.id;
                option.appendChild(document.createTextNode(sensor.displayName));
                availableTempSensors [sensor.id] = sensor;
                selectlist.appendChild(option);

        }
                      
 
       // Callback when bind has been successfully executed on the service object. The Sensor is authorized and ready to use
        function bindCB(mySensor) {

                alert('Sensor ' + mySensor.displayName + ' with ID: ' + mySensor.id + ' selected');
               

                // Configure the sensor.
                mySensor.configureSensor ( {timeout: 120, rate: 5000, eventFireMode: "valuechange"}, 
                                           successHandler () {alert('Sensor ' + mySensor.displayName + ' with ID: ' + mySensor.id +
                                                                    ' is configured') },
                                           errorHandler (error) {alert('Sensor ' + mySensor.displayName + ' with ID: ' + mySensor.id +
                                                                       ' configuration failed' + ' with error: ' + error.name)} );

               
                // Start listening to sensor events and log values. 
                mySensor.addEventListener('sensor', function (event) {
                          console.log(event.sensorValues[0]);

                          var temp = document.getElementById('temp');
                          temp.innerHTML = "Current temperature is: " + event.sensorValues[0];


                }, true); 

        }


       // Callback method that is invoked when user selects an option in the sensor selection list 
        function sensorSelected(sensor) {

                // Stops the findServices operation
                findHandle.cancel();

                // Binds to the sensor API to initiate an authorized objects used to
                // invoke services.  
                sensorHandle = sensor.bind({onBind:bindCB});                               
                
        }
        
        // Get list of temperature sensors registered in the device through the Service Discovery findServices() method
        findHandle  = window.webinos.discovery.findServices({api:'http://webinos.org/api/sensors.temperature'}, {onFound:sensorFoundCB});
 
       // Handle user selection of sensor
        var sensorlist = document.getElementById('sensorlist');
        sensorlist.addEventListener("change", function (e) {
                                var sensor = availableTempSensors[e.target.value];
                                if (sensor) {
                                    sensorSelected(sensor);
                                }
        }, false);


 

Attributes

readonly float? maximumRange

Max range of sensor in the sensors unit.

This attribute is readonly.
readonly unsigned long? minDelay

Min delay of sensor allowed between two events in microsecond or zero if this sensor only returns a value when the data it's measuring changes.

This attribute is readonly.
readonly float? power

Power consumption of sensor in mA used by this sensor while in use.

This attribute is readonly.
readonly float? resolution

Resolution of the sensor in the sensors unit.

This attribute is readonly.
readonly DOMString? vendor

Vendor string of this sensor.

This attribute is readonly.
readonly unsigned long? version

Version of the sensors module.

This attribute is readonly.

Methods

configureSensor

Configures a sensor.

Signature
PendingSensorConfigOp configureSensor(ConfigureSensorOptions options, VoidFunction successCB, optional SensorErrorCB errorCB);
Parameters
  • options
  • successCB
    • Optional: No.
    • Nullable: No
    • Type: VoidFunction
    • Description: Callback issued when sensor configuration succeeded.
  • errorCB
    • Optional: Yes.
    • Nullable: No
    • Type: SensorErrorCB
    • Description: Callback issued if sensor configuration fails.
Return value
A pending operation object making it possible to cancel the configureSensor operation

Dictionary ConfigureSensorOptions

ConfigureSensorOptions interface definition

WebIDL
    dictionary ConfigureSensorOptions {



       unsigned short timeout;


       unsigned long? rate;
       

       EventFireMode? eventFireMode;


       GeoPosition? position;


       DOMString? config;
        };

Dictionary Members

unsigned short timeout

A timeout value for when configureSensor() is canceled in seconds between 0-65535. Default value is 120 seconds. 0 means infinite.

unsigned long? rate

The requested rate of the sensor data. It is the time interval before a new event is generated. The value is expressed in ms. If the interval is too small for the sensor (that is it is unable to generate data at the selected rate) it shall use the maximum rate it can support.

EventFireMode? eventFireMode

The requested sensor event fire mode.

GeoPosition? position

The position of the sensor. This value may be ignored by the sensor if it retrieves position in a different way (for example has a gps module onboard)

DOMString? config

Generic configurations string. This string is in JSON format and can be used for additional sensors that need extra configuration parameters. The format of the string must be specified by the sensor developer.

Dictionary GeoPosition

GeoPosition interface definition

WebIDL
    dictionary GeoPosition {


       unsigned long latitude;


       unsigned long longitude;
     };

Dictionary Members

unsigned long latitude

Latitude.

unsigned long longitude

Longitude.

Interface PendingSensorConfigOp

The PendingSensorConfigOp interface

WebIDL
     interface PendingSensorConfigOp {


        void cancel ();
     };

The PendingSensorConfigOp interface describes the object that is returned by the asynchronous configure sensor method. It makes it possible to abort this operation to a stop if it hasn't produced a result within a desired time or before a given event, thereby possibly reclaiming resources.

Methods

cancel

Method Cancel

Signature
void cancel();

Cancel the pending configure sensor asynchronous operation. When this method is called, the user agent must immediately bring the operation to a stop and return. Allocated resources should be released and any ongoing related network operations should be terminated. An error callback is issued with the DOMError name "AbortError". If the configuration is no longer under control of the calling process, the cancel function will be ignored and all neccessary 'housekeeping functions' required after starting the configuration process will be performed as if the cancel had never been issued.

Interface SensorEvent

This interface defines the "genericsensor" event type.

WebIDL
   interface SensorEvent : Event {


    readonly attribute DOMString sensorType;


    readonly attribute DOMString sensorId;



    readonly attribute Accuracy accuracy;

 

    readonly attribute unsigned long rate;


    readonly attribute EventFireMode eventFireMode;


    readonly attribute float[] sensorValues;


     readonly attribute GeoPosition?  position;



    void initSensorEvent(DOMString type,
                         boolean bubbles,
                         boolean cancelable,
                         DOMString sensorType,
                         DOMString sensorId,
                         Accuracy accuracy,
                         unsigned long rate,
                         EventFireMode eventFireMode, 
                         float[] sensorValues,
                         GeoPosition position);
    };

Registration for generic sensor events is achieved by calling addEventListener instantiated on the selected sensor object with event type set to "sensor" (see code example in the beginning of this specification).
To stop listening to a sensor removeEventListener is called.

Attributes

readonly DOMString sensorType

The type of sensor. This is a URI defining the sensor type according to the defined sensor "feature" URI strings. See section "Features".

For the defined sensor types the sensorValues array contains the following data:

http://webinos.org/api/sensors.light:
sensorValue[0] = the measured ambient light level around the device in SI lux units.

http://webinos.org/api/sensors.noise:
sensorValue[0] = the measured ambient noise around the device, DB(SPL).

http://webinos.org/api/sensors.temperature:
sensorValue[0] = the measured ambient temperature around the device, degrees Celsius.

http://webinos.org/api/sensors.pressure:
sensorValue[0] = the measured atmospheric pressure around the device in hPa (millibar)

http://webinos.org/api/sensors.proximity:
sensorValue[0] = proximity sensor distance measured in centimeters. Some sensor can only state "near" (0) and "far" (1)

http://webinos.org/api/sensors.humidity:
sensorValue[0] = the measured relative humidity around the device in percent.

http://webinos.org/api/sensors.heartratemonitor:
sensorValue[0] = the measured heart rate as beats per minute (bpm).

This attribute is readonly.
readonly DOMString sensorId

The unique identity of the of the specific sensor

This attribute is readonly.
readonly Accuracy accuracy

The accuracy of the sensor

This attribute is readonly.
readonly unsigned long rate

The rate of the sensor data. This value will be 0 if the rate is undefined or eventFireMode is set to valuechange.

This attribute is readonly.
readonly EventFireMode eventFireMode

The event fire mode the sensor.

This attribute is readonly.
readonly float[] sensorValues

Array of sensor values

This attribute is readonly.
readonly GeoPosition? position

Position of the sensor.

This attribute is readonly.

Methods

initSensorEvent

Method to set initial values of sensor event.

Signature
void initSensorEvent(DOMString type, boolean bubbles, boolean cancelable, DOMString sensorType, DOMString sensorId, Accuracy accuracy, unsigned long rate, EventFireMode eventFireMode, float[] sensorValues, GeoPosition position);

The initSensorEvent() method must initialize the event in a manner analogous to the initEvent() method in http://www.w3.org/TR/2010/WD-DOM-Level-3-Events-20100907/. The method can for example be used with document.createEvent() and EventTarget.dispatchEvent() to simulate a specific event. The sensorType, sensorId, accuracy, rate, eventFireMode and sensorvalues arguments must initialize the attributes with the same names.

Parameters
  • type
    • Optional: No.
    • Nullable: No
    • Type: DOMString
    • Description: Event type i.e. 'sensor'
  • bubbles
    • Optional: No.
    • Nullable: No
    • Type: boolean
    • Description: True if event bubbles
  • cancelable
    • Optional: No.
    • Nullable: No
    • Type: boolean
    • Description: True if event cancelable
  • sensorType
    • Optional: No.
    • Nullable: No
    • Type: DOMString
    • Description: Sensor type as a URI
  • sensorId
    • Optional: No.
    • Nullable: No
    • Type: DOMString
    • Description: The unique identity of the specific sensor
  • accuracy
    • Optional: No.
    • Nullable: No
    • Type: Accuracy
    • Description: Accuracy of sensor data
  • rate
    • Optional: No.
    • Nullable: No
    • Type: unsigned long
    • Description: Rate of sensor data event
  • eventFireMode
    • Optional: No.
    • Nullable: No
    • Type: EventFireMode
    • Description: Mode of firing events
  • sensorValues
    • Optional: No.
    • Nullable: No
    • Type: array
    • Description: Array of sensor values
  • position
    • Optional: No.
    • Nullable: No
    • Type: GeoPosition
    • Description: Position of the sensor

Callbacks

SensorErrorCB

The SensorErrorCB method is called if an error occurs during the configureSensor() process.

WebIDL
    callback SensorErrorCB = void (DOMError error);
Signature
void SensorErrorCB(DOMError error);
Parameters
  • error
    • Optional: No.
    • Nullable: No
    • Type: DOMError
    • Description: DOMError object detailing what went wrong in an unsuccessful configureSensor() asynchronous operation. The following error names cold be issued:
      - "SyntaxError": Input parameters did not match the expected pattern.
      - "NotSupportedError": Sensor configuration not supported.
      - "InvalidModificationError": Sensor can not be configured in this way.
      - "AbortError": Operation was aborted by the user.
      - "TimeoutError": The operation timed out.

Enums

EventFireMode

Sensor event fire mode.
- fixedinterval = Events fired with a fixed time interval.
- valuechange = Events fired when value changes. This is the default value.

WebIDL
    enum EventFireMode { "fixedinterval", "valuechange"};

Values

fixedinterval
valuechange

Accuracy

Sensor event accuracy.
high = The sensor is reporting data with maximum accuracy
medium = The sensor is reporting data with an average level of accuracy, calibrating with the environment may improve the reading.
low = The sensor is reporting with low accuracy, calibrating with the environment is needed.
unreliable = The sensor data cannot be trusted, calibrating is needed or the environment does not allow reading.
unavailable = The sensor is not available and no sensor data can be provided. This accuracy attribute will for example take this value when contact is lost with a sensor using Bluetooth communication.

WebIDL
   enum Accuracy { "high", "medium", "low", "unreliable", "unavailable"};

Values

high
medium
low
unreliable
unavailable

Features

This is the list of URIs used to declare this API's features, for use in the widget config.xml and as identifier for service type in service discovery functionality. For each URI, the list of functions covered is provided.

http://webinos.org/api/sensors

Identifies all the sensor types.

http://webinos.org/api/sensors.read

Enables access only to read methods of the api - access to configureSensor is forbidden

http://webinos.org/api/sensors.light

Identifies the light sensor type.

http://webinos.org/api/sensors.noise

Identifies the noise sensor type.

http://webinos.org/api/sensors.temperature

Identifies the temperature sensor type.

http://webinos.org/api/sensors.pressure

Identifies the pressure sensor type.

http://webinos.org/api/sensors.proximity

Identifies the proximity sensor type.

http://webinos.org/api/sensors.humidity

Identifies the relative humidity sensor type.

http://webinos.org/api/sensors.heartratemonitor

Identifies a heart rate monitor sensor type.

Full WebIDL

WebIDL
    interface Sensor : Service {
 

        readonly attribute float?          maximumRange;


        readonly attribute unsigned long?   minDelay;


        readonly attribute float?         power;


        readonly attribute float?         resolution;


        readonly attribute DOMString?      vendor;  


        readonly attribute unsigned long?  version; 


        PendingSensorConfigOp configureSensor (ConfigureSensorOptions options, VoidFunction successCB, optional SensorErrorCB errorCB);
     };



    callback SensorErrorCB = void (DOMError error);


    enum EventFireMode { "fixedinterval", "valuechange"};


    dictionary ConfigureSensorOptions {



       unsigned short timeout;


       unsigned long? rate;
       

       EventFireMode? eventFireMode;


       GeoPosition? position;


       DOMString? config;
        };


    dictionary GeoPosition {


       unsigned long latitude;


       unsigned long longitude;
     };


     interface PendingSensorConfigOp {


        void cancel ();
     };



   enum Accuracy { "high", "medium", "low", "unreliable", "unavailable"};




   interface SensorEvent : Event {


    readonly attribute DOMString sensorType;


    readonly attribute DOMString sensorId;



    readonly attribute Accuracy accuracy;

 

    readonly attribute unsigned long rate;


    readonly attribute EventFireMode eventFireMode;


    readonly attribute float[] sensorValues;


     readonly attribute GeoPosition?  position;



    void initSensorEvent(DOMString type,
                         boolean bubbles,
                         boolean cancelable,
                         DOMString sensorType,
                         DOMString sensorId,
                         Accuracy accuracy,
                         unsigned long rate,
                         EventFireMode eventFireMode, 
                         float[] sensorValues,
                         GeoPosition position);
    };