Ambient Light Sensor

W3C Working Draft,

More details about this document
This version:
https://www.w3.org/TR/2021/WD-ambient-light-20211214/
Latest published version:
https://www.w3.org/TR/ambient-light/
Editor's Draft:
https://w3c.github.io/ambient-light/
Previous Versions:
History:
https://www.w3.org/standards/history/ambient-light
Feedback:
public-device-apis@w3.org with subject line “[ambient-light] … message topic …” (archives)
GitHub
Test Suite:
https://github.com/web-platform-tests/wpt/tree/master/ambient-light
Editors:
Anssi Kostiainen (Intel Corporation)
Rijubrata Bhaumik (Intel Corporation)
Former Editors:
Tobie Langel (Codespeaks, formerly on behalf of Intel Corporation)
Doug Turner (Mozilla Corporation)
Issue Tracking:
Level 2 Issues

Abstract

This specification defines a concrete sensor interface to monitor the ambient light level or illuminance of the device’s environment.

Status of this document

This section describes the status of this document at the time of its publication. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at https://www.w3.org/TR/.

This document was published by the Devices and Sensors Working Group as a Working Draft using the Recommendation track. This document is intended to become a W3C Recommendation.

If you wish to make comments regarding this document, please send them to public-device-apis@w3.org (subscribe, archives). When sending e-mail, please put the text “ambient-light” in the subject, preferably like this: “[ambient-light] …summary of comment…”. All comments are welcome.

Publication as a Working Draft does not imply endorsement by W3C and its Members. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under the W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This document is governed by the 2 November 2021 W3C Process Document.

The Devices and Sensors Working Group is pursuing modern security and privacy reviews for this specification in consideration of the amount of change in both this specification and in privacy and security review practices since the horizontal reviews took place on 3 October 2017. Similarly, the group is pursuing an update to the Technical Architecture Group review for this specification to account for the latest architectural review practices.

1. Introduction

The Ambient Light Sensor extends the Generic Sensor API [GENERIC-SENSOR] to provide information about ambient light levels, as detected by the device’s main light detector, in terms of lux units.

1.1. Scope

This document specifies an API designed for use cases which require fine grained illuminance data, with low latency, and possibly sampled at high frequencies.

Common use cases relying on a small set of illuminance values, such as styling webpages according to contrast level or preferred color scheme that may be influenced by a device’s measured ambient light level are best served by the the prefers-contrast and prefers-color-scheme CSS media features [MEDIAQUERIES-5] as well as the accompanying matchMedia API [CSSOM-VIEW-1] and are out of scope of this API.

Note: The [MEDIAQUERIES-5] specification used to contain a light-level media feature that was more directly tied to ambient light readings. It has since been dropped from the specification in favor of the higher-level prefers-color-scheme and prefers-contrast media features.

2. Examples

In this simple example, ambient light sensor is created with default configuration. Whenever a new reading is available, it is printed to the console.
const sensor = new AmbientLightSensor();
sensor.onreading = () => console.log(sensor.illuminance);
sensor.onerror = event => console.log(event.error.name, event.error.message);
sensor.start();
In this example, the exposure value (EV) at ISO 100 is calculated from the ambient light sensor readings. Initially, we check that the user agent has permissions to access ambient light sensor readings. Then, the illuminance value is converted to the closest exposure value.
navigator.permissions.query({ name: 'ambient-light-sensor' }).then(result => {
    if (result.state === 'denied') {
        console.log('Permission to use ambient light sensor is denied.');
        return;
    }

    const als = new AmbientLightSensor({frequency: 20});
    als.addEventListener('activate', () => console.log('Ready to measure EV.'));
    als.addEventListener('error', event => console.log(`Error: ${event.error.name}`));
    als.addEventListener('reading', () => {
        // Defaut ISO value.
        const ISO = 100;
        // Incident-light calibration constant.
        const C = 250;

        let EV = Math.round(Math.log2((als.illuminance * ISO) / C));
        console.log(`Exposure Value (EV) is: ${EV}`);
    });

    als.start();
});
This example demonstrates how ambient light sensor readings can be mapped to recommended workplace light levels.
const als = new AmbientLightSensor();

als.onreading = () => {
    let str = luxToWorkplaceLevel(als.illuminance);
    if (str) {
        console.log(`Light level is suitable for: ${str}.`);
    }
};

als.start();

function luxToWorkplaceLevel(lux) {
    if (lux > 20 && lux < 100) {
        return 'public areas, short visits';
    } else if (lux > 100 && lux < 150) {
        return 'occasionally performed visual tasks';
    } else if (lux > 150 && lux < 250) {
        return 'easy office work, classes, homes, theaters';
    } else if (lux > 250 && lux < 500) {
        return 'normal office work, groceries, laboratories';
    } else if (lux > 500 && lux < 1000) {
        return 'mechanical workshops, drawing, supermarkets';
    } else if (lux > 1000 && lux < 5000) {
        return 'detailed drawing work, visual tasks of low contrast';
    }

    return;
}

3. Security and Privacy Considerations

Ambient Light Sensor provides information about lighting conditions near the device environment. Potential privacy risks include:

To mitigate these Ambient Light Sensor specific threats, user agents should use one or both of the following mitigation strategies:

These mitigation strategies complement the generic mitigations defined in the Generic Sensor API [GENERIC-SENSOR].

4. Model

The Ambient Light Sensor sensor type’s associated Sensor subclass is the AmbientLightSensor class.

The Ambient Light Sensor has a default sensor, which is the device’s main light detector.

The Ambient Light Sensor is a powerful feature that is identified by the name "ambient-light-sensor", which is also its associated sensor permission name. Its permission revocation algorithm is the result of calling the generic sensor permission revocation algorithm with "ambient-light-sensor".

The Ambient Light Sensor is a policy-controlled feature identified by the string "ambient-light-sensor". Its default allowlist is 'self'.

The current light level or illuminance is a value that represents the ambient light level around the hosting device. Its unit is the lux (lx) [SI].

Note: The precise lux value reported by different devices in the same light can be different, due to differences in detection method, sensor construction, etc.

5. API

5.1. The AmbientLightSensor Interface

[SecureContext, Exposed=Window]
interface AmbientLightSensor : Sensor {
  constructor(optional SensorOptions sensorOptions = {});
  readonly attribute double? illuminance;
};

To construct an AmbientLightSensor object the user agent must invoke the construct an ambient light sensor object abstract operation.

5.1.1. The illuminance attribute

The illuminance attribute of the AmbientLightSensor interface represents the current light level and returns the result of invoking get value from latest reading with this and "illuminance" as arguments.

6. Abstract Operations

6.1. Construct an ambient light sensor object

input

options, a SensorOptions object.

output

An AmbientLightSensor object.

  1. Let allowed be the result of invoking check sensor policy-controlled features with AmbientLightSensor.

  2. If allowed is false, then:

    1. Throw a SecurityError DOMException.

  3. Let ambient_light_sensor be the new AmbientLightSensor object.

  4. Invoke initialize a sensor object with ambient_light_sensor and options.

  5. Return ambient_light_sensor.

7. Automation

This section extends the automation section defined in the Generic Sensor API [GENERIC-SENSOR] to provide mocking information about the ambient light levels for the purposes of testing a user agent’s implementation of Ambient Light Sensor.

7.1. Mock Sensor Type

The AmbientLightSensor class has an associated mock sensor type which is "ambient-light", its mock sensor reading values dictionary is defined as follows:

dictionary AmbientLightReadingValues {
  required double? illuminance;
};

8. Use Cases and Requirements

While some of the use cases may benefit from obtaining precise ambient light measurements, the use cases that convert ambient light level fluctuations to user input events would benefit from higher sampling frequencies.

9. Acknowledgements

Doug Turner for the initial prototype and Marcos Caceres for the test suite.

Paul Bakaus for the LightLevelSensor idea.

Mikhail Pozdnyakov and Alexander Shalamov for the use cases and requirements.

Lukasz Olejnik for the privacy risk assessment.

Conformance

Document conventions

Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.

All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]

Examples in this specification are introduced with the words “for example” or are set apart from the normative text with class="example", like this:

This is an example of an informative example.

Informative notes begin with the word “Note” and are set apart from the normative text with class="note", like this:

Note, this is an informative note.

Conformant Algorithms

Requirements phrased in the imperative as part of algorithms (such as "strip any leading space characters" or "return false and abort these steps") are to be interpreted with the meaning of the key word ("must", "should", "may", etc) used in introducing the algorithm.

Conformance requirements phrased as algorithms or specific steps can be implemented in any manner, so long as the end result is equivalent. In particular, the algorithms defined in this specification are intended to be easy to understand and are not intended to be performant. Implementers are encouraged to optimize.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[GENERIC-SENSOR]
Rick Waldron. Generic Sensor API. URL: https://w3c.github.io/sensors/
[PERMISSIONS]
Marcos Caceres; Mike Taylor. Permissions. URL: https://w3c.github.io/permissions/
[PERMISSIONS-POLICY-1]
Ian Clelland. Permissions Policy. URL: https://w3c.github.io/webappsec-permissions-policy/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://datatracker.ietf.org/doc/html/rfc2119
[WEBIDL]
Edgar Chen; Timothy Gu. Web IDL Standard. Living Standard. URL: https://webidl.spec.whatwg.org/

Informative References

[CSSOM-VIEW-1]
Simon Pieters. CSSOM View Module. URL: https://drafts.csswg.org/cssom-view/
[MEDIAQUERIES-5]
Dean Jackson; Florian Rivoal; Tab Atkins Jr.. Media Queries Level 5. URL: https://drafts.csswg.org/mediaqueries-5/
[SI]
SI Brochure: The International System of Units (SI), 8th edition. 2014. URL: http://www.bipm.org/en/publications/si-brochure/

IDL Index

[SecureContext, Exposed=Window]
interface AmbientLightSensor : Sensor {
  constructor(optional SensorOptions sensorOptions = {});
  readonly attribute double? illuminance;
};

dictionary AmbientLightReadingValues {
  required double? illuminance;
};