sensors

October 22, 2022

sensors

Stability: 2-Stable

The sensors module provides support for obtaining the information of the sensors on the mobile phone. These sensors include distance sensors, light sensors, gravity sensors, and direction sensors. It should be pointed out that the script can only obtain sensor data, cannot simulate or forge sensor data and events, so functions such as simulating a shake cannot be realized.

When you want to monitor a sensor, you need to use sensors.register() to register the listener before you can start listening; when you don't need to listen, call sensors.unregister() to unregister the listener. All listeners will be automatically logged out at the end of the script. At the same time, this kind of monitoring keeps the script running. If you don't log off the listener, the script will keep running.

For example, the code for monitoring the light sensor is:

//Light sensor monitor
sensors.register("light").on("change", (event, light)=>{
    log("The current light intensity is", light);
});

It should be noted that the data of each sensor is not the same, so the callback function parameters when calling on() to listen to the event are not the same. For example, the light sensor parameter is (event, light), the acceleration sensor parameter It is (event, ax, ay, az). Even the sensor parameters on some devices have increased. For example, the distance sensor of Huawei mobile phones has three parameters, and the general mobile phone has only one parameter.

The commonly used sensors and their event parameters are as follows:

  • accelerometer acceleration sensor, parameters (event, ax, ay, az):

    • event SensorEvent sensor event, used to get all the information when the sensor data changes
    • ax {number} The acceleration on the x axis, in m/s^2
    • ay {number} The acceleration on the y axis, in m/s^2
    • az {number} The acceleration on the z axis, in m/s^2 The coordinate system of the x-axis, y-axis, and z-axis here are as follows (where the z-axis is perpendicular to the device screen surface):

    !axis_device

  • orientation direction sensor, parameter (event, azimuth, pitch, roll):

    • event SensorEvent sensor event, used to get all the information when the sensor data changes
    • azimuth {number} Azimuth, the horizontal angle between clockwise direction and y-axis from the north direction line of geomagnetic field, unit angle, range 0~359
    • pitch {number} The angle of rotation around the x axis, when the device is placed horizontally, the value is 0, when the top of the device is tilted, the value is positive, when the tail of the device is tilted, the value is negative, the unit is angle, Range -180~180
    • roll {number} The angle of clockwise rotation around the y-axis, unit angle, range -90~90
  • gyroscope gyroscope sensor, parameters (event, wx, wy, wz):

    • event SensorEvent sensor event, used to get all the information when the sensor data changes
    • wx {number} Angular velocity around the x-axis, in radians/s
    • wy {number} Angular velocity around the y axis, in radians/s
    • wz {number} Angular velocity around the z axis, in radians/s
  • magnetic_field magnetic field sensor, parameter (event, bx, by, bz):

    • event SensorEvent sensor event, used to get all the information when the sensor data changes
    • bx {number} The magnetic field strength on the x-axis, in uT
    • by {number} The magnetic field strength on the y-axis, in uT
    • bz {number} The magnetic field strength on the z-axis, in uT
  • gravity gravity sensor, parameters(event, gx, gy, gz):

    • event SensorEvent sensor event, used to get all the information when the sensor data changes
    • gx {number} The acceleration of gravity on the x-axis, in m/s^2
    • gy {number} The acceleration of gravity on the y-axis, in m/s^2
    • gz {number} The acceleration of gravity on the z axis, in m/s^2
  • linear_acceleration linear acceleration sensor, parameters (event, ax, ay, az):

    • event SensorEvent sensor event, used to get all the information when the sensor data changes
    • ax {number} Linear acceleration on the x-axis, in m/s^2
    • ay {number} Linear acceleration on the y axis, in m/s^2
    • az {number} Linear acceleration on the z axis, in m/s^2
  • ambient_temperature ambient temperature sensor, most devices do not support, the parameter (event, t):

    • event SensorEvent sensor event, used to get all the information when the sensor data changes
    • t {number} Ambient temperature in degrees Celsius.
  • light light sensor, parameter (event, light):

    • event SensorEvent sensor event, used to get all the information when the sensor data changes
    • light {number} Ambient light intensity, unit lux
  • pressure pressure sensor, parameter (event, p):

    • event SensorEvent sensor event, used to get all the information when the sensor data changes
    • p {number} Atmospheric pressure in hPa
  • proximity distance sensor, parameter (event, distance):

    • event SensorEvent sensor event, used to get all the information when the sensor data changes
    • distance {number} generally refers to the distance from the distance sensor next to the front camera of the device to the obstacle in front, and there are only two cases for this value on many devices: when the obstacle is close, the value is 0, when the obstacle is relatively close, the value is 0. The value is 5 when there is no obstacle in the distance or within the range
  • relative_humidity humidity sensor, most devices do not support, the parameter (event, rh):

    • event SensorEvent sensor event, used to get all the information when the sensor data changes
    • rh {number} relative humidity, the range is 0~100 (percentage)

sensors.register(sensorName[, delay])

  • sensorName {string} Sensor name, commonly used sensor names are as described above
  • delay {number} Sensor data update frequency, optional, default is sensors.delay.normal. The available values ​​are as follows:
    • sensors.delay.normal normal frequency
    • sensors.delay.ui is suitable for the update frequency of the user interface
    • sensors.delay.game is suitable for the update frequency of the game
    • sensors.delay.fastest fastest update frequency]
  • Return SensorEventEmitter

Register a sensor to monitor and return SensorEventEmitter.

E.g:

console.show();
//Register the sensor to listen
var sensor = sensors.register("gravity");
if(sensor == null){
    toast("Gravity sensor is not supported");
    exit();
}
//Monitor data
sensor.on("change", (gx, gy, gz)=>{
    log("gravitational acceleration: %d, %d, %d", gx, gy, gz);
});

The update frequency of sensor data can be specified by the delay parameter, for example:

var sensor = sensors.register("gravity", sensors.delay.game);

In addition, if the sensor specified by sensorName is not supported, the function will return null; but if the value of sensors.ignoresUnsupportedSensor is set to true, the function will return a sensor event that will not be distributed SensorEventEmitter.

E.g:

sensors.ignoresUnsupportedSensor = true;
//No need to judge by null
sensors.register("gravity").on("change", (gx, gy, gz)=>{
    log("gravitational acceleration: %d, %d, %d", gx, gy, gz);
});

For more information, see SensorEventEmitter and sensors.ignoresUnsupportedSensor.

sensors.unregister(emitter)

Log out of the sensor listener. The logged-out listener will no longer be able to listen to sensor data.

//Register a sensor listener
var sensor = sensors.register("gravity");
if(sensor == null){
    exit();
}
//Log out the listener after 2 seconds
setTimeout(()=> {
    sensors.unregister(sensor);
}, 2000);

sensors.unregisterAll()

Log out of all sensor listeners.

sensors.ignoresUnsupportedSensor

  • {boolean}

Indicates whether to ignore unsupported sensors. If the value is set to true, the function sensors.register() will return a virtual sensor monitor without any data even for unsupported sensors, that is, sensors.register() will not returnnull to avoid non-null judgment, and at this time, the "unsupported_sensor" event of sensors will be triggered.

//Ignore unsupported sensors
sensors.ignoresUnsupportedSensor = true;
//Monitor events when there are unsupported sensors
sensors.on("unsupported_sensor", function(sensorName){
    toastLog("Unsupported sensor: "+ sensorName);
});
//Register a sensor that does not exist at will.
log(sensors.register("aaabbb"));

Event:'unsupported_sensor'

  • sensorName {string} Unsupported sensor name

This event is triggered when sensors.ignoresUnsupportedSensor is set to true and an unsupported sensor is registered. The sensor name of the event parameter.

SensorEventEmitter

The object returned by the registered sensor is itself an EventEmitter, which is used to monitor sensor events.

Event:'change'

  • ..args {Any} sensor parameters

This event is triggered when the sensor data changes; the maximum frequency of this event is determined by the delay parameter specified by sensors.register().

The event parameters vary according to the sensor type. For details, see the list at the top of this chapter.

An example of monitoring the light sensor and acceleration sensor and acquiring data every 0.5 seconds and finally writing it to a csv table file is as follows:

//csv file path
const csvPath = "/sdcard/sensors_data.csv";
//Record the data of the light sensor
var light = 0;
//Record the data of the accelerometer
var ax = 0;
var ay = 0;
var az = 0;
//Monitor light sensor
sensors.register("light", sensors.delay.fastest)
    .on("change", l => {
        light = l;
    });
//Monitor accelerometer
sensors.register("accelerometer", sensors.delay.fastest)
    .on("change", (ax0, ay0, az0) => {
        ax = ax0;
        ay = ay0;
        az = az0;
    });

var file = open(csvPath, "w");
//Write the csv table header
file.writeline("light,ax,ay,az")
//Get data and write to file every 0.5 seconds
setInterval(()=>{
    file.writeline(util.format("%d,%d,%d,%d", light, ax, ay, az));
}, 500);
//Exit and open the file after 10 seconds
setTimeout(()=>{
    file.close();
    sensors.unregisterAll();
    app.viewFile(csvPath);
}, 10 * 1000);

Event:'accuracy_change'

  • accuracy {number} indicates the accuracy of the sensor. Is one of the following values:
    • -1 The sensor is not connected
    • 0 The sensor is not readable
    • 1 Low accuracy
    • 2 Medium precision
    • 3 High precision

An event that is triggered when the accuracy of the sensor changes. Less used.

Last update:
Contributors: Bruce