DEV Community

Cover image for Native sensors that can be used within the web by default
veerreshr
veerreshr

Posted on • Updated on • Originally published at blog.veereshr.me

Native sensors that can be used within the web by default

Final result preview:

accelerometer reading
github link for the code given at end

Introduction :

Now a days every smart device comes with few integrated sensors within them, which we can use them by writing specific native code. Isn't it hard when you want to write different native code for different devices, as Apple sensor integration could be different from Android and Android could be different from laptops. Here comes the use of Generic sensor API for web, which abstracts the internal work and gives us an API to work with sensors present in devices. Using this you can use sensors of all devices that has browser support( check the caniuse site for which browsers support this API. ).It is most useful when you want to use specific sensors and don't want to complicate the implementation by writing different native codes for different platforms.

In this section I will discuss about few sensors that are supported by Generic Sensor API and there implementation.
Before directly going into knowing how to use certain sensor, I will go through high level overview or workflow of using a sensor.

Workflow :

Sensors in Web by Veeresh.jpg

Sensors :

The term device sensor refers to a device’s underlying physical sensor instance. Each sensor reading is composed of the values of the physical quantity measured by the device sensor at time tn which is called the reading timestamp.
Here is the interface of a sensor ( these denotes the available methods to deal with sensor and its data. ).

[SecureContext, Exposed=(DedicatedWorker, Window)]
interface Sensor : EventTarget {
  readonly attribute boolean activated;
  readonly attribute boolean hasReading;
  readonly attribute DOMHighResTimeStamp? timestamp;
  void start();
  void stop();
  attribute EventHandler onreading;
  attribute EventHandler onactivate;
  attribute EventHandler onerror;
};

dictionary SensorOptions {
  double frequency;
};
Enter fullscreen mode Exit fullscreen mode

So there is a frequency option which needs to be set by user before initializing a sensor. Few other methods like onreading, onacivate, onerror are used to access data and handle errors. Go through sensor-interface if you want to know more about it.

Few of the available generic sensors include :

  • ambient-light
  • accelerometer
  • linear-acceleration
  • gravity
  • gyroscope
  • magnetometer
  • uncalibrated-magnetometer
  • absolute-orientation
  • relative-orientation
  • geolocation
  • proximity

Usage

Let us consider using accelerometer sensor for this demonstration (any sensor can be used in place of accelerometer).

Check if your browser supports Generic API :

if('Accelerometer' in window){
//code to be written if Accelerometer interface is supported by the browser.
}else{
//Your browser doesn't support sensors.
}
Enter fullscreen mode Exit fullscreen mode

Here we will not worry if 'Accelerometer' interface is not supported by browser. However we can use pollyfill in this case. Using pollyfill you can import only relevant sensors and work with it . To know more about working with polyfill read sensor-polyfill.

Permissions

navigator.permissions.query({ name: "accelerometer" }).then(result => {
    if (result.state != 'granted') {
        setGameText("Sorry, we're not allowed to access sensors on your device. ");
        return;
    }
}).catch(err => {
    console.log("Integration with Permissions API is not enabled");
});
Enter fullscreen mode Exit fullscreen mode

Currently there isnt any api to request for permission for generic sensors like accelerometer. If you wish to ask for other sensors like geoloaction there is method to request permission :

const permissionsToRequest = {
  permissions: ["geolocation", "storage"]
}
browser.permissions.request(permissionsToRequest)
    .then(onResponse)
    .then((currentPermissions) => {
    console.log(`Current permissions:`, currentPermissions);
});
Enter fullscreen mode Exit fullscreen mode

List of all keywords that can be used with permission api are present here at API Permissions .

Reading data

let acl = new Accelerometer({frequency: 30});
acl.addEventListener('activate', () => console.log('Ready to measure.'));
acl.addEventListener('error', error => console.log(`Error: ${error.name}`));
acl.addEventListener('reading', () => {
    console.log("Sensor values are : ");
    console.log("X: "+acl.x+" Y: "+acl.y+" Z: "+acl.z);
});
acl.start();
Enter fullscreen mode Exit fullscreen mode

You can change the frequency as you wish, but you are not guaranteed with same frequency as all the device sensors doesn't support given frequency.

So here's the end , Now you are able to read the data from the generic sensor on the web. Below is the complete code combining all three methods above and you can refer to the generic sensor to learn more about it.

if ("Accelerometer" in window) {
  navigator.permissions
    .query({ name: "accelerometer" })
    .then((result) => {
      if (result.state != "granted") {
        console.log(
          "Sorry, we're not allowed to access sensors on your device. "
        );
        return;
      }

      let acl = new Accelerometer({ frequency: 60 });
      acl.addEventListener("activate", () => console.log("Ready to measure."));
      acl.addEventListener("error", (error) =>
        console.log(`Error: ${error.name}`)
      );
      acl.addEventListener("reading", () => {
        console.log("Sensor values are : ");
        console.log("X: " + acl.x + " Y: " + acl.y + " Z: " + acl.z);
      });
      acl.start();
    })
    .catch((err) => {
      console.log("Integration with Permissions API is not enabled");
    });
} else {
  console.log("Your browser doesn't support sensors.");
}


Enter fullscreen mode Exit fullscreen mode

For Live Implementation you can visit this site : https://accelerometer-demo.netlify.app


Code of this implementation is at : https://github.com/veerreshr/accelerometer-demo/




If you enjoyed the post, consider responding to the article with your feedback. ❤

Discussion (0)