Guest User

CORRECTED Fitbit Websocket Client code (app/index.js)

a guest
Aug 27th, 2019
305
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. let websocket;
  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 websocket object here
  38. var connection = new WebSocket('ws://192.168.1.2:8888')
  39.  
  40. connection.onopen = function(){
  41.   //Send a small message to the console to signify connection is made.
  42.   console.log('Connection open!');
  43. }
  44.  
  45. connection.onclose = function() {
  46.   console.log('Connection closed!');
  47. }
  48.  
  49. connection.onerror = function(error) {
  50.   console.log("Error detected: " + error);
  51. }
  52.  
  53. // Create a new instance of the HeartRateSensor object
  54. var hrm = new HeartRateSensor();
  55.  
  56. // Declare an event handler that will be called every time a new HR value is received.
  57. hrm.onreading = function() {
  58.   // Peek the current sensor values
  59.   console.log("Current heart rate: " + hrm.heartRate);
  60.   connection.send(hrm.heartRate);
  61.   hrLabel.text = hrm.heartRate;
  62.   lastValueTimestamp = Date.now();
  63. }
  64.  
  65. // Begin monitoring the sensor
  66. hrm.start();
  67.  
  68. // And update the display every second
  69. setInterval(updateDisplay, 1000);
Add Comment
Please, Sign In to add comment