Skip to content

Latest commit

 

History

History
295 lines (208 loc) · 11.2 KB

README.md

File metadata and controls

295 lines (208 loc) · 11.2 KB


Capacitor Lightsensor Plugin

capacitor-plugin-lightsensor

This plugin get the illuminance level on the device


Maintainers

Maintainer GitHub Social
Elvin Chu Elvincth @elvincth

Installation

Step 1

npm install capacitor-plugin-lightsensor --save
npx cap sync

Step 2

IOS Platform: No further action required.

Android Platform: Register the plugin in your main activity (MainActivity.java):

import com.gren.plugin.lightsensor.LightSensor; //ADD this line

public class MainActivity extends BridgeActivity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.init(
        savedInstanceState,
        new ArrayList<Class<? extends Plugin>>() {

          {
             add(LightSensor.class); //ADD this line
          }
        }
      );
  }
}

Supported methods

Name Android iOS Web
init
registerListener
unregisterListener
getInfo
isAvailable

Usage

Getting illuminance level

import { SensorManager } from "capacitor-plugin-lightsensor";
import { Plugins } from "@capacitor/core"; 
const { LightSensor } = Plugins;

async function getLux() {
  try {
    //Initialize the sensor with some settings
    await LightSensor.init({
      SensorDelay: SensorManager.SENSOR_DELAY_UI, //Optional, for android only Default is SENSOR_DELAY_NORMAL
    });

    //Register onLightSensorChanged listener
    await LightSensor.registerListener();

    //Listen for the sensor change
    window.addEventListener("onLightSensorChanged", (evt) => {
      console.log("value", evt.value); //The illuminance (lux) level 
      console.log("accuracy", evt.accuracy); //Android only the accuracy of this event, for web return -1
      console.log("timestamp", evt.timestamp); //For android in nanoseconds, For web in millisecond
      
      console.log("onLightSensorChanged", JSON.stringify(evt));  
      //{"isTrusted":false,"accuracy":3,"timestamp":58769305913765,"value":281.9115905761719}
    });

  } catch (error) {
    console.log("Error occur:", error);
  }
}

Pause the sensor after registered

import { SensorManager } from "capacitor-plugin-lightsensor";
import { Plugins } from "@capacitor/core"; 
const { LightSensor } = Plugins;

async function pause() {
  try {
   
    //Pause the sesnor
    await LightSensor.unregisterListener();
    
    //To resume, run register again
    //await LightSensor.registerListener();

  } catch (error) {
    console.log("Error occur:", error);
  }
}

Check the availability of light sensor

import { SensorManager } from "capacitor-plugin-lightsensor";
import { Plugins } from "@capacitor/core"; 
const { LightSensor } = Plugins;

async function checkSensor() {
  const isSensorAvailable = await LightSensor.isAvailable();

  if (isSensorAvailable.status) {
    console.log("There is light sensor on this device");
  } else {
    console.log("No light sensor on this device");
  }
  
  console.log("isSensorAvailable", JSON.stringify(isSensorAvailable)); // {"status":true} or {"status":false}
}

Getting the light sensor information (Android ONLY)

import { SensorManager } from "capacitor-plugin-lightsensor";
import { Plugins } from "@capacitor/core"; 
const { LightSensor } = Plugins;

async function getInfo() {
  try {
    const sensorInfo = await LightSensor.getInfo();

    //For android only, if web all number will return -1
    
    console.log("vendor", sensorInfo.vendor); //vendor string of this sensor
    console.log("version", sensorInfo.version); //version of the sensor's module
    console.log("type", sensorInfo.type); //generic type of this sensor
    console.log("maxRange", sensorInfo.maxRange); //maximum range of the sensor in the sensor's unit.
    console.log("resolution", sensorInfo.resolution); //resolution of the sensor in the sensor's unit.
    console.log("power", sensorInfo.power); //the power in mA used by this sensor while in use
    console.log("minDelay", sensorInfo.minDelay); //the minimum delay allowed between two events in microsecond or zero if this sensor only returns a value when the data it's measuring changes.
    console.log("minDelay", sensorInfo.maxDelay); //The max delay for this sensor in microseconds.

    console.log("sensorInfo", JSON.stringify(sensorInfo));
    //{"vendor":"OnePlus","version":1,"type":5,"maxRange":4096,"resolution":1,"power":1.7049999237060547,"minDelay":0,"maxDelay":0}
  } catch (error) {
    console.log("Light sensor not available");
  }
}

API

Methods

init(...)

Initialize the light sensor with settings (See example here )

Param Type Description
option object See option table

Option

Key Type Description
SensorDelay Enum (SensorManager) Optional, for android only Default is SensorManager.SENSOR_DELAY_NORMAL

Returns: Promise


registerListener()

Register onLightSensorChanged listener (To start or resume the sensor, see example here )

Returns: Promise


unregisterListener()

Unregister onLightSensorChanged listener (To stop or pause the sensor, see example here )

Returns: Promise


isAvailable()

Check if the device have a light sensor or not (See example here )

Returns: Promise of following object structure:

Key Type Description
status Boolean Have light sensor?

getInfo()

Get light sensor information (See example here )

More information in https://developer.android.com/reference/android/hardware/Sensor#getVendor()

NOTE: Web didn't support this method it will return -1 for all numbers and Unknown for string

Returns: Promise of following object structure:

Key Type Description
vendor object Vendor string of this sensor
version Number Version of the sensor's module
type Number Generic type of this sensor
maxRange Number Maximum range of the sensor in the sensor's unit
resolution Number Resolution of the sensor in the sensor's unit
power Number The power in mA used by this sensor while in use
minDelay Number The minimum delay allowed between two events in microsecond or zero if this sensor only returns a value when the data it's measuring changes
maxDelay Number The max delay for this sensor in microseconds

Events

onLightSensorChanged

More information in https://developer.android.com/reference/android/hardware/SensorEvent#timestamp

See example here

Returns: object of following object structure:

Key Type Description
isTrusted Boolean Returns true if event was dispatched by the user agent, and false otherwise. (Capacitor thing you can ignore this)
accuracy Boolean Android only the accuracy of this event, for web return -1
timestamp Number For android in nanoseconds, For web in millisecond
value Number The illuminance (lux) level

Enums

SensorManager

(For android only, see more in: https://developer.android.com/reference/android/hardware/SensorManager#SENSOR_DELAY_FASTEST )

Members Value Description
SENSOR_DELAY_FASTEST 0 Get sensor data as fast as possible
SENSOR_DELAY_GAME 1 Rate suitable for games
SENSOR_DELAY_UI 2 Rate suitable for the user interface
SENSOR_DELAY_NORMAL 3 Normal rate (Default)