Wholesale Application Community Device API Specifications 2.1

Accelerometer API

The Accelerometer API lets you access accelerometer data.

Contents

  1. 1 Introduction
  2. 2 Feature string
    1. 2.1 Processing the feature declaration
  3. 3 DeviceapisAccelerometer interface
    1. 3.1 The accelerometer attribute
  4. 4 Accelerometer interface
    1. 4.1 Constants
    2. 4.2 The getCurrentAcceleration() method
    3. 4.3 The watchAcceleration() method
    4. 4.4 The clearWatch() method
  5. 5 Acceleration interface
    1. 5.1 The xAxis, yAxis, zAxis attributes
  6. Change Log

1 Introduction

An accelerometer is a sensor that gives a measurement of the rate of change of magnitude and direction of velocity of a device (i.e., the acceleration). This API allows a developer to asynchronously query the device's accelerometer and/or to "watch" the accelerometer and, through callbacks, be notified of changes over time. A device's accelerometer provides a measurement of acceleration relative to a resting state and along 3 different axes (illustrated below). These axes are defined with respect to the default orientation of the screen.

x-axis
Holding the device flat, the x-axis runs left to right along the top of the device's screen. Positive acceleration indicates the device is accelerating along the increasing x-axis (i.e. acceleration of the device to the right of the user). Negative acceleration occurs along the decreasing x-axis (i.e. acceleration of the device to the left of the user).
y-axis
Holding the device flat, the y-axis runs from bottom of the device to the bottom of the device's screen (outwards away from the user). Hence, positive acceleration indicates the device is accelerating along the increasing y-axis. If the device is placed on a flat surface, screen up, and the user stands at the "bottom" of the screen - the lowest point on the y-axis - the acceleration of the device is away from the user. Negative acceleration occurs along the decreasing y-axis (i.e. when the user pulls the device towards themselves).
z-axis
The z-axis is perpendicular to the screen plane and increases out of the screen plane. Positive acceleration indicates the device is accelerating along the increasing z-axis. If the device is placed on a flat surface, screen up, the device is accelerating by moving above the surface. Negative acceleration occurs along the decreasing z-axis as it moves towards the ground.
The x-axis, y-axis, and z-axis relative to the user holding a device.

The value of acceleration for each axis is therefore determined by the proportion of acceleration in that axis and is measured in meters over seconds squared (m/s2). In a normal resting state, the accelerometer will read 0 (zero) meters per second2 in all axes.

Acceleration due to gravity can be measured by allowing the device to free-fall, and assuming the device is allowed to free fall with the rear of the device facing the ground and without any other motion, the x and y axes will measure 0 m/s2 and the z-axis will measure somewhere around -9.8 meters per second (because of earth's gravity, which varies slightly from place-to-place and sensors can be "noisy").

2 Feature string

An accelerometer feature declaration in a widget's configuration document represent a developer's intention to use the functionality provided by this API.

The accelerometer feature string is: http://wacapps.net/api/accelerometer

The accelerometer feature string needs to be present in a widget's configuration document in order for the API to be made available at runtime.

2.1 Processing the feature declaration

A user agent needs to process feature elements in accordance with the W3C's Widgets Packaging and Configuration specification.

If the feature-list contains any features whose feature-name exactly matches the accelerometer feature string, then the user agent MUST apply the steps for processing an accelerometer feature declaration.

Steps for processing an accelerometer feature declaration

The steps for processing an accelerometer feature declaration is given by the following algorithm:

  1. Implement the DeviceapisAccelerometer interface when the widget's start file is instantiated.

  2. Expose Accelerometer and Acceleration in the global scope.

XML Example

<widget xmlns="http://www.w3.org/ns/widgets">
  <feature name="http://wacapps.net/api/accelerometer"
           required="false"/>
</widget>

The above example shows how a developer uses the accelerometer feature declaration to declare their intention to use the Accelerometer API.

3 DeviceapisAccelerometer interface

[NoInterfaceObject]
interface DeviceapisAccelerometer {
  readonly attribute Accelerometer accelerometer;
};
Deviceapis implements DeviceapisAccelerometer;

When an accelerometer feature declaration appears in the widget's configuration document, the user agent implements the DeviceapisAccelerometer interface; thus providing access to Accelerometer API through the deviceapis.accelerometer attribute (see Accelerometer interface).

3.1 The accelerometer attribute

The accelerometer attribute is the point of access to the Accelerometer API (see Accelerometer interface).

Javascript example

//check that the API is available
if(deviceapis.accelerometer){
	//Alias it, so it's more usable
	var accel = deviceapis.accelerometer; 
	
	// Scroll around the page by using the acceleration
	accel.watchAcceleration(function(obj) {
		window.scrollBy(
		Math.round(obj.xAxis * 10 * - 1), Math.round(obj.yAxis * 10 * - 1));
	});
}

4 Accelerometer interface

interface Accelerometer {
  const float EARTH_GRAVITY = -9.8;

  void getCurrentAcceleration(
                  AccelerationCB successCallback,
                  optional ErrorCB? errorCallback);

  long watchAcceleration( AccelerationCB successCallback,
                 optional ErrorCB?       errorCallback,
                 optional WatchOptions?  options);

  void clearWatch(long watchId);
};
callback AccelerationCB = void(Acceleration axes);  

The Accelerometer interface provides a way to interface with the accelerometer of the device. To allow for asynchronous notification to changes in acceleration, the user agent keeps a list of active accelerometer watch operations. Each entry in this list is identified by a number, which is unique within its list for the lifetime of the application.

4.1 Constants

EARTH_GRAVITY
Represents the standard gravity on earth (-9.8m/s2).

4.2 The getCurrentAcceleration() method

The getCurrentAcceleration() method is used to request the device's acceleration.

When the getCurrentAcceleration() method is invoked, the user agent MUST run the steps to get the current acceleration.

Steps to get the current acceleration

The steps to get the current acceleration are given by the following algorithm:

  1. Run the general invocation checks algorithm. If no exceptions were generated, continue.
  2. When the accelerometer is available to be queried, let x, y, and z, be the values corresponding to the accelerometer's x-axis, y-axis, z-axis respectively.
  3. If it was not possible to retrieve any axes and if errorCallback is callable:
    1. Let exception be a new DOMException of type "InvalidStateError" with message "Accelerometer data is unavailable." (or similar).
    2. Queue a task to invoke the errorCallback with exception as the argument.
    3. Terminate this algorithm, skipping all steps below.
  4. Let axes be a new object that implements the Acceleration interface.
  5. Set axes' xAxis, yAxis, zAxis attributes to x, y, z respectively.
  6. Let task be a task invoke the successCallback with axes as the argument.
  7. Queue a task task.

Javascript example

//check that the API is available
if(deviceapis.accelerometer){
	var handler = function(acceleration) {
		//check if there is significant movement
		if (Math.round(acceleration.xAxis * 100) === 0.0) {
			console.log("The device is not moving in the xAxis");
			return;
		}
		console.log("The device is moving in the xAxis");
	};
	deviceapis.accelerometer.getCurrentAcceleration(handler);
}

4.3 The watchAcceleration() method

The watchAcceleration() method allows the developer to receive notifications about changes in acceleration.

When the watchAcceleration() method is invoked, the user agent MUST run the steps for watching the acceleration.

Steps for watching the acceleration

The steps for watching the acceleration are given by the following algorithm:

  1. Run the general invocation checks algorithm. If no exceptions were generated, continue.
  2. Let interval be the value 0.
  3. If the third argument (options) is present and has a minNotificationInterval member:
    1. Let minInterval be the result of performing WebIDL's unsigned long type mapping to the value of minNotificationInterval. If no exceptions were generated, continue.
    2. If the value of minInterval is a unsigned long, then let interval be the value of minNotificationInterval. (Ignore other dictionary members of options).
  4. Let subscription id be a user-agent-defined (random or sequential) WebIDL-long that will represent the looping action to be created by invoking this method.
  5. Add subscription id to the list of active accelerometer watch operations.
  6. Return subscription id, and then continue running this algorithm asynchronously.
  7. If interval is less than a user-agent-defined value for a minimal check interval (i.e., to stop the sensor being flooded or because it would drain too much battery), set interval to that user-agent-defined value.
  8. Wait, at minimum (optionally more time if needed), the amount of time indicated by interval:
    1. If the entry for subscription id has been cleared from the list of active accelerometer watch operations, terminate this algorithm.
    2. Run the getCurrentAcceleration() method using successCallback as the first argument, and, if used, errorCallback as the second argument.
  9. Return to step 8.

4.4 The clearWatch() method

The clearWatch() method, given an identifier, stops monitoring acceleration changes. If watchid does not identify an entry in the list of active accelerometer watch operations, the method does nothing.

When the clearWatch() method is invoked, the user agent MUST run the steps to stop watching the accelerometer.

The steps to stop watching the accelerometer are given by the following algorithm:

  1. Run the general invocation checks algorithm. If no exceptions were generated, continue.
  2. If the first argument (watchId) identifies an item in the list of active accelerometer watch operations, then clear the corresponding item from the list of active accelerometer watch operations.

Javascript example

var outLimit = 0;

function error(e) {
	alert(e);
}

// Receives changes in acceleration
function changeWatcher(axes) {
	console.log(outLimit + " The acceleration in x-axis changed " + axes.xAxis);
	outLimit++;
	if (outLimit > 10) { // limit output to 10
		cancelWatch(watchid);
	}
}

// Cancel the watch operation if someting goes wrong
function cancelWatch(watchid) {
	deviceapis.accelerometer.clearWatch(watchid);
}

var intervals = {
	minNotificationInterval: 50
};

var watchid = deviceapis.accelerometer.watchAcceleration(
  changeWatcher, //success callback
  error,         //failure callback
  intervals      //how often to watch
);

5 Acceleration interface

interface Acceleration {
  readonly attribute float xAxis;
  readonly attribute float yAxis;
  readonly attribute float zAxis;
};

The Acceleration interface represents the three axes of acceleration.

5.1 The xAxis, yAxis, zAxis attributes

The xAxis, yAxis, and zAxis attributes represents the acceleration along the x-axis, y-axis, and z-axis measured in m/s2 at some moment in time.

Javascript example

//feature detect 
if (deviceapis.accelerometer) {

  deviceapis.accelerometer.getCurrentAcceleration(
        //callback 
        function show(axis) {
            console.log("Acceleration in the x,y,z axes are: " + 
                    axis.xAxis + "," + 
                    axis.yAxis + "," + 
                    axis.zAxis);
        }
    );
}

Change Log

This specification was last updated on 30 April 2012.

A complete list of changes are kept on our GIT repository.

March 13, 2012
  • Removed all mention of PendingOperation; the getCurrentAcceleration() method now returns void. PendingOperation was unreliable and no one was using it.
March 9, 2012
  • Marked getCurrentAcceleration()'s use of PendingOperation at risk.
March 8, 2012
  • Removed [NoInterfaceObject] from Accelerometer and Acceleration
January 9, 2012
  • Spec was rewritten to reflect the changes to WebIDL.
  • Added algorithmic descriptions for how to get acceleration and how to actually do the asynchronous callbacks.