<!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 Max with Gravity</title>
</head>
<body>

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

<h4>Accelerometer Max 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);
    }    
}

// Initialize the max values
let xmax=0;
let ymax=0;
let zmax=0;

// Event listener for motion.  Triggered when the device accelerates.
function handleMotion(event) {
    // Save the accelerations
    let x = event.accelerationIncludingGravity.x;
    let y = event.accelerationIncludingGravity.y;
    let z = event.accelerationIncludingGravity.z;

    // Set the max for x,y,z
    if (x > xmax) {
        xmax = x;
    }
    if (y > ymax) {
        ymax = y;
    }
    if (z > zmax) {
        zmax = z;
    }
    
    // Update the page
    updateFieldIfNotNull('Accelerometer_gx', xmax);
    updateFieldIfNotNull('Accelerometer_gy', ymax);
    updateFieldIfNotNull('Accelerometer_gz', zmax);
}

// Stop and Start data collection
let is_running = false;

// Function to handle clicking the start/stop link
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();
    }
    // If running stop it
    if (is_running){
        // Stop event listener
        window.removeEventListener("devicemotion", handleMotion);
        // Set Link to "Start demo"
        demo_button.innerHTML = "Start demo";
        is_running = false;

    } else {
        // If stopped start it.
        window.addEventListener("devicemotion", handleMotion);
        document.getElementById("start_demo").innerHTML = "Stop demo";
        is_running = true;
        xmax = ymax = zmax = 0;
    }
};

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