# Ambient Light Sensor

## Editor’s Draft, 1 January 1970

This version:
  https://w3c.github.io/ambient-light/
Latest published version:
  http://www.w3.org/TR/ambient-light/
Previous Versions:
  https://www.w3.org/TR/2018/CR-ambient-light-20180320/
Version History:
  https://github.com/w3c/ambient-light/commits/gh-pages/index.bs
Feedback:
  public-device-apis@w3.org with subject line “`[ambient-light] … message topic …`” (archives)
Editor:
  Anssi Kostiainen (Intel Corporation)
Former Editors:
  Tobie Langel (Codespeaks, formerly on behalf of Intel Corporation) tobie@codespeaks.com
  Doug Turner (Mozilla Corporation)
Bug Reports:
  via the w3c/ambient-light repository on GitHub
Issue Tracking:
  Level 2 Issues
Test Suite:
  web-platform-tests on GitHub

Copyright © 1970 W3C® (MIT, ERCIM, Keio, Beihang). W3C liability, trademark and permissive document license rules apply.

## 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 is a public copy of the editors’ draft. It is provided for discussion only and may change at any moment. Its publication here does not imply endorsement of its contents by W3C. Don’t cite this document other than as work in progress.

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.

This document was produced by the Devices and Sensors Working Group.

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 1 March 2019 W3C Process Document.

## 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 ambient light levels are best served by the the `light-level` CSS media feature [MEDIAQUERIES-5] and its accompanying `matchMedia` API [CSSOM] and are out of scope of this API.

Note: it might be worthwhile to provide a high-level Light Level Sensor which would mirror the `light-level` media feature, but in JavaScript. This sensor would not require additional user permission to be activated in user agents that exposed the `light-level` media feature.

## 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:

- Profiling. Ambient Light Sensor can leak information about user’s use patterns and surrounding. This information can be used to enhance user profiling and behavioral analysis.

- Cross-device linking. Two devices can access web sites that include the same third-party script that correlates lighting levels over time.

- Cross-device communication. A simple broadcast communication method can use device screen or camera LED flashes to broadcast messages read out with an Ambient Light Sensor in a close by device.

- Cross-origin leaks. Light emitted from the screen can be reflected back to the sensor from nearby reflective surfaces. Malicious sites can embed resources from different origins and scale the content to display particular pixels to allow distinguishing the contents, pixel by pixel.

- Hijacking browsing history. Styling visited links to allow distinguishing the light levels associated with visited and unvisited links i.e. visited links styled as a block of black screen; white for unvisited.

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

- limit maximum sampling frequency

- reduce accuracy of sensor readings

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 has an associated sensor permission name which is "ambient-light-sensor".

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

- A Web application provides input for a smart home system to control lighting.

- A Web aplication checks whether light level at work space is sufficient.

- A Web application calculates settings for a camera with manual controls (apperture, shutter speed, ISO).

- A Web application monitors light level changes produced by hovering hand user gesture and interprets them to control a game character.

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.

## 10. Conformance

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]

A conformant user agent must implement all the requirements listed in this specification that are applicable to user agents.

The IDL fragments in this specification must be interpreted as required for conforming IDL fragments, as described in the Web IDL specification. [WEBIDL]

## Index

### Terms defined by this specification

- AmbientLightReadingValues, in §7.1
- Ambient Light Sensor, in §4
- AmbientLightSensor, in §5.1
- AmbientLightSensor(), in §5.1
- AmbientLightSensor(sensorOptions), in §5.1
- conformant user agent, in §10
- Construct an ambient light sensor object, in §6
- constructor(), in §5.1
- constructor(sensorOptions), in §5.1
- current light level, in §4
- illuminance
  - attribute for AmbientLightSensor, in §5.1
  - definition of, in §4
  - dict-member for AmbientLightReadingValues, in §7.1

https://w3c.github.io/sensors/#dom-mocksensortype-ambient-light Referenced in:

- 7.1. Mock Sensor Type

https://w3c.github.io/sensors/#sensor Referenced in:

- 4. Model
- 5.1. The AmbientLightSensor Interface

https://w3c.github.io/sensors/#dictdef-sensoroptions Referenced in:

- 5.1. The AmbientLightSensor Interface
- 6.1. Construct an ambient light sensor object

https://w3c.github.io/sensors/#automation Referenced in:

- 7. Automation

https://w3c.github.io/sensors/#check-sensor-policy-controlled-features Referenced in:

- 6.1. Construct an ambient light sensor object

https://w3c.github.io/sensors/#default-sensor Referenced in:

- 4. Model

https://w3c.github.io/sensors/#get-value-from-latest-reading Referenced in:

- 5.1.1. The illuminance attribute

https://w3c.github.io/sensors/#high-level Referenced in:

- 1.1. Scope

https://w3c.github.io/sensors/#initialize-a-sensor-object Referenced in:

- 6.1. Construct an ambient light sensor object

https://w3c.github.io/sensors/#limit-max-frequency Referenced in:

- 3. Security and Privacy Considerations

https://w3c.github.io/sensors/#mitigation-strategies Referenced in:

- 3. Security and Privacy Considerations

https://w3c.github.io/sensors/#mock-sensor-reading-values Referenced in:

- 7.1. Mock Sensor Type

https://w3c.github.io/sensors/#mock-sensor-type Referenced in:

- 7.1. Mock Sensor Type

https://w3c.github.io/sensors/#reduce-accuracy Referenced in:

- 3. Security and Privacy Considerations

https://w3c.github.io/sensors/#sampling-frequency Referenced in:

- 8. Use Cases and Requirements

https://w3c.github.io/sensors/#sensor-permission-names Referenced in:

- 4. Model

https://w3c.github.io/sensors/#sensor-reading Referenced in:

- 2. Examples (2) (3) (4)

https://w3c.github.io/sensors/#sensor-type Referenced in:

- 4. Model

https://w3c.github.io/permissions/#dom-permissionname-ambient-light-sensor Referenced in:

- 4. Model

https://heycam.github.io/webidl/#idl-DOMException Referenced in:

- 6.1. Construct an ambient light sensor object

https://heycam.github.io/webidl/#Exposed Referenced in:

- 5.1. The AmbientLightSensor Interface

https://heycam.github.io/webidl/#SecureContext Referenced in:

- 5.1. The AmbientLightSensor Interface

https://heycam.github.io/webidl/#securityerror Referenced in:

- 6.1. Construct an ambient light sensor object

https://heycam.github.io/webidl/#idl-double Referenced in:

- 5.1. The AmbientLightSensor Interface
- 7.1. Mock Sensor Type

https://heycam.github.io/webidl/#dfn-throw Referenced in:

- 6.1. Construct an ambient light sensor object

### Terms defined by reference

- [GENERIC-SENSOR] defines the following terms:
  - "ambient-light"
  - Sensor
  - SensorOptions
  - automation
  - check sensor policy-controlled features
  - default sensor
  - get value from latest reading
  - high-level
  - initialize a sensor object
  - limit maximum sampling frequency
  - mitigation strategies
  - mock sensor reading values
  - mock sensor type
  - reduce accuracy
  - sampling frequency
  - sensor permission name
  - sensor reading
  - sensor type
- [permissions] defines the following terms:
  - "ambient-light-sensor"
- [WEBIDL] defines the following terms:
  - DOMException
  - Exposed
  - SecureContext
  - SecurityError
  - double
  - throw

## References

### Normative References

[GENERIC-SENSOR]
  Mikhail Pozdnyakov; Alexander Shalamov; Tobie Langel. Generic Sensor API. URL: https://w3c.github.io/sensors/
[PERMISSIONS]
  Mounir Lamouri; Marcos Caceres; Jeffrey Yasskin. Permissions. URL: https://w3c.github.io/permissions/
[RFC2119]
  S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119
[WEBIDL]
  Boris Zbarsky. Web IDL. URL: https://heycam.github.io/webidl/

### Informative References

[CSSOM]
  Simon Pieters; Glenn Adams. CSS Object Model (CSSOM). URL: https://drafts.csswg.org/cssom/
[MEDIAQUERIES-5]
  Dean Jackson; Florian Rivoal; Tab Atkins. Media Queries Level 5. ED. 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;
    };

#ambient-light-sensor Referenced in:

- 4. Model (2)
- 7. Automation

#current-light-level Referenced in:

- 5.1.1. The illuminance attribute

#ambientlightsensor Referenced in:

- 4. Model
- 5.1. The AmbientLightSensor Interface
- 5.1.1. The illuminance attribute
- 6.1. Construct an ambient light sensor object (2) (3)
- 7.1. Mock Sensor Type

#dom-ambientlightsensor-illuminance Referenced in:

- 2. Examples
- 5.1.1. The illuminance attribute

#construct-an-ambient-light-sensor-object Referenced in:

- 5.1. The AmbientLightSensor Interface