kabyru

app/index.js

Aug 28th, 2019
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let document = require("document");
  2. import { HeartRateSensor } from "heart-rate";
  3. import * as messaging from "messaging";
  4.  
  5. // Fetch UI elements we will need to change
  6. let hrLabel = document.getElementById("hrm");
  7. let updatedLabel = document.getElementById("updated");
  8.  
  9. // Keep a timestamp of the last reading received. Start when the app is started.
  10. let lastValueTimestamp = Date.now();
  11.  
  12. // Initialize the UI with some values
  13. hrLabel.text = "--";
  14. updatedLabel.text = "...";
  15.  
  16. // This function takes a number of milliseconds and returns a string
  17. // such as "5min ago".
  18. function convertMsAgoToString(millisecondsAgo) {
  19.   if (millisecondsAgo < 120*1000) {
  20.     return Math.round(millisecondsAgo / 1000) + "s ago";
  21.   }
  22.   else if (millisecondsAgo < 60*60*1000) {
  23.     return Math.round(millisecondsAgo / (60*1000)) + "min ago";
  24.   }
  25.   else {
  26.     return Math.round(millisecondsAgo / (60*60*1000)) + "h ago"
  27.   }
  28. }
  29.  
  30. // This function updates the label on the display that shows when data was last updated.
  31. function updateDisplay() {
  32.   if (lastValueTimestamp !== undefined) {
  33.     updatedLabel.text = convertMsAgoToString(Date.now() - lastValueTimestamp);
  34.   }
  35. }
  36.  
  37. // Create messaging socket object here
  38. messaging.peerSocket.onopen = function(){
  39.   messaging.peerSocket.send("I'm alive!")
  40. }
  41.  
  42. messaging.peerSocket.onmessage = function() {
  43.   console.log("Sent!")
  44. }
  45.  
  46. function heartSend(rate) {
  47.   messaging.peerSocket.send(rate.toString());
  48.   console.log("Sent!");
  49. }
  50.  
  51. messaging.peerSocket.onerror = function(err) {
  52.   console.log("Connection error: " + err.code + "-" + err.message);
  53. }
  54.  
  55. // Create a new instance of the HeartRateSensor object
  56. var hrm = new HeartRateSensor();
  57.  
  58. // Declare an event handler that will be called every time a new HR value is received.
  59. hrm.onreading = function() {
  60.   // Peek the current sensor values
  61.   console.log("Current heart rate: " + hrm.heartRate);
  62.   //var heartString = hrm.heartRate.toString();
  63.   messaging.peerSocket.send(hrm.heartRate);
  64.   // heartSend(hrm.heartRate);
  65.   hrLabel.text = hrm.heartRate;
  66.   lastValueTimestamp = Date.now();
  67. }
  68.  
  69. // Begin monitoring the sensor
  70. hrm.start();
  71.  
  72. // And update the display every second
  73. setInterval(updateDisplay, 1000);
Advertisement
Add Comment
Please, Sign In to add comment