<!doctype html>
<html lang="en">
<!-- 
From:  https://sensor-js.xyz/demo.html
Modified by: Deid Reimer
Date: 2022-02-18
-->
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Acceleration with Gravity</title>
</head>
<body>

<h1 align="left">Acceleration</h1>
<img src="axis.png">
<a id="start_demo" href="#" role="button" >Start the demo</a>

<h4>Accelerometer including gravity</h4>
<ul>
    <li>X-axis: <span id="Accelerometer_gx">0</span><span> m/s<sup>2</sup></span></li>
    <li>Y-axis: <span id="Accelerometer_gy">0</span><span> m/s<sup>2</sup></span></li>
    <li>Z-axis: <span id="Accelerometer_gz">0</span><span> m/s<sup>2</sup></span></li>
</ul>

<script>

function updateFieldIfNotNull(fieldName, value, precision=1){
    if (value != null)
        document.getElementById(fieldName).innerHTML = value.toFixed(precision);
}

function handleMotion(event) {
    updateFieldIfNotNull('Accelerometer_gx', event.accelerationIncludingGravity.x);
    updateFieldIfNotNull('Accelerometer_gy', event.accelerationIncludingGravity.y);
    updateFieldIfNotNull('Accelerometer_gz', event.accelerationIncludingGravity.z); 
}

//  Stop and start data gathering
let is_running = false;
let demo_button = document.getElementById("start_demo");
demo_button.onclick = function(e) {
    e.preventDefault();
  
    // Request permission for iOS 13+ devices
    if ( DeviceMotionEvent && typeof DeviceMotionEvent.requestPermission === "function") {
        DeviceMotionEvent.requestPermission();
    }
    // Stop data gathering 
    if (is_running){
        window.removeEventListener("devicemotion", handleMotion);
        demo_button.innerHTML = "Start demo";
        demo_button.classList.add('btn-success');
        demo_button.classList.remove('btn-danger');
        is_running = false;
    }else{
        // Start data gathering
        window.addEventListener("devicemotion", handleMotion);
        document.getElementById("start_demo").innerHTML = "Stop demo";
        demo_button.classList.remove('btn-success');
        demo_button.classList.add('btn-danger');
        is_running = true;
    }
};

</script>
</body>
</html>