10-06-2022 14:17
10-06-2022 14:17
I have an app and it basically runs through the night.
Before, I would only access the the accelerometer data but I added a feature so that I can have a continuous reading of the HR.
Here is the main piece of code. I am hoping that maybe a pair of eyes more can help me figure why my app crashes after adding the HR reader (it gets the HR values every 30 seconds).
import { Accelerometer } from "accelerometer";
import { HeartRateSensor } from "heart-rate";
import { vibration } from "haptics";
import sleep from "sleep";
import * as scientific from "scientific";
import { today } from "user-activity";
import { me as appbit } from "appbit";
import * as document from "document";
import * as fs from "fs";
appbit.appTimeoutEnabled = false;
const bEndSession = document.getElementById("bEndSession");
const bAActive = document.getElementById("bAActive");
const bASleepy = document.getElementById("bASleepy");
const displayText = document.getElementById("textBox");
const timeBox = document.getElementById("timeBox");
var _today = new Date();
var _time = _today.getHours() + ":" + _today.getMinutes() + ":" + _today.getSeconds();
export class Kobe {
constructor(kobeId) {
console.log("Constructor");
this.accelerometer = new Accelerometer({ frequency: 10, batch: 10 });
this.hrm = new HeartRateSensor();
this.ss = 0;
this.kk = 0;
this.tid = 0;
this.noResCount = 0;
this.maxNoResponse = 9;
this.movementFound = false;
this.noMovementStDev = 0;
this.movementStDev = 0
this.startTime = new Date().getTime();
this.maxTime = 30; //30minutes
this.fallingAsleep = 0;
this.fitbitData = {};
this.userInfo = {};
//
this.currentSteps = today.adjusted.steps;
this.bedActive = true;
this.probeOn = true;
this.awake = false;
this.exiting = false;
this.stepsArr = []
//bedSleepy = false;
this.startAccel();
displayText.text = `Probe ON: ${this.maxTime} mins.`
_today = new Date();
_time = _today.getHours() + ":" + _today.getMinutes();
timeBox.text = _time;
}
//data
setFitbitData = (kobeId) => {
//console.log("I am setFitbitData")
var _date = new Date();
this.fitbitData = {
uid: `${kobeId.deviceId}_${kobeId.userType}${kobeId.userId}`,
sessionDate: Date.now(), //ts in UTC
awakeTime: 0,
sleepData: [],
hrData: [],
userMeta: {
withPpets: false,
withPartner: false,
withFans: false,
tzOffset: _date.getTimezoneOffset(),
deviceId: kobeId.deviceId,
esId: `${kobeId.userType}${kobeId.userId}`
},
userSteps: [],
sleepStarts: [],
kobeRecall: [],
badSession: false
}
}
//startAccel();
//}
startAccel() {
//console.log("I am startAccel")
this.accelerometer.addEventListener("reading", () => {
this.ss = scientific.std(this.accelerometer.readings.x) + scientific.std(this.accelerometer.readings.y) + scientific.std(this.accelerometer.readings.z);
console.log(`ss: ${this.ss}`);
});
this.accelerometer.start();
if (HeartRateSensor) {
console.log("This device has a HeartRateSensor!");
//const hrm = new HeartRateSensor();
this.hrm.addEventListener("reading", () => {
console.log(`Current heart rate: ${this.hrm.heartRate}`);
});
this.hrm.start();
} else {
console.log("This device does NOT have a HeartRateSensor!");
}
}
checkForMovement = () => {
var ss1 = scientific.std(this.accelerometer.readings.x) + scientific.std(this.accelerometer.readings.y) + scientific.std(this.accelerometer.readings.z);
console.log(`checkForMovement ${this.kk} ${this.ss} ${this.ss1}`);
// disc1.crossCountT();
if (this.ss > 5.0) {
this.noResCount = 0;
this.fallingAsleep = 0;
this.movementStDev = ss;
console.log(`movement detected ${kk} ${ss}`);
} else {
this.noResCount++;
if (this.noResCount > 0 && this.noResCount <= 3) {
this.fallingAsleep = Date.now();
}
console.log(`movement nope ${this.kk} ${this.ss}`);
this.noMovementStDev = this.ss;
}
console.log(`noResCount: ${this.noResCount}`);
//console.log(inWakeWindow);
this.movementFound = (this.noResCount < 3) ? true : false;
this.userInfo = {
//action: inWakeWindow ? 'Awake Nudge' : 'Buzzed',
action: 'Buzzed',
timeStamp: Date.now(),
movement: this.movementFound,
stDev: this.movementFound ? this.movementStDev : this.noMovementStDev,
userState: sleep.state,
awakeActive: this.bedActive,
awakeSleepy: !this.bedActive
}
}
sendUserInfo = () => {
// userData.push(userInfo)
this.fitbitData.sleepData.push(this.userInfo);
console.log(`User info: ${JSON.stringify(this.fitbitData, null, 4)}`);
//console.log(util.inspect(myObject, false, null, true /* enable colors */))
var fileName = `${this.fitbitData.sessionDate}`;
fs.writeFileSync(`${fileName}.json`, this.fitBitData, "json");
//transferFile(fileName);
}
pingUser = () => {
console.log('Vibrating');
vibration.start("nudge");
//vibration.start("nudge-max");
this.kk++;
setTimeout(this.checkForMovement, 2 * 1000);
setTimeout(this.checkForMovement, 3 * 1000);
setTimeout(this.checkForMovement, 4 * 1000);
setTimeout(this.sendUserInfo, 4 * 1000)
// console.log("hi! im here dear!");
}
clear = () => {
if (this.noResCount >= this.maxNoResponse) {
clearInterval(this.tid);
console.log("Probe should be off!!")
//accel.stop();
// exit from
this.probeOn = false;
//bEndSession.text = `End Session`
displayText.text = 'Probe OFF'
displayText.style.fill = "fb-red"
bAActive.text = 'Awake in bed';
bAActive.style.fill = "#FFA07A";
bASleepy.text = 'Going to sleep'
bASleepy.style.fill = "#FFA07A";
const exitMessage = {
action: 'Normal Exit',
timeStamp: Date.now(),
movement: this.movementFound,
stDev: this.movementFound ? this.movementStDev : this.noMovementStDev,
userState: sleep.state,
awakeActive: this.bedActive,
awakeSleepy: !this.bedActive
}
this.fitbitData.sleepStarts.push(this.fallingAsleep);
this.fitbitData.sleepData.push(exitMessage);
this.noResCount = 0;
}
if (this.awake) {
//accel.start();
this.awake = false;
this.fitbitData.kobeRecall.push(Date.now());
clearInterval(this.tid);
this.tid = setInterval(this.pingUser, 5 * 60 * 1000);
//bEndSession.text = `End Session`
displayText.text = 'Probe ON'
}
if (this.exiting) {
//console.log('Clear - exiting');
clearInterval(this.tid);
this.fitbitData.awakeTime = Date.now();
// var _date = new Date();
this.fitbitData.userSteps.push(this.stepsArr);
}
//console.log(`kk ${this.kk} ${this.tid}`);
}
stepCounter = () => {
var prevSteps = this.currentSteps;
var stepsTs = Date.now();
this.currentSteps = today.adjusted.steps;
var stepsDiff = this.currentSteps - prevSteps;
if (stepsDiff > 0 && stepsDiff != null) {
console.log(stepsDiff);
// this.stepsArr.push({
// time: stepsTs,
// values: stepsDiff,
// });
this.fitbitData.userSteps.push({
time: stepsTs,
values: stepsDiff,
})
} else if (stepsDiff < 0 && stepsDiff != null) {
// this.stepsArr.push({
// time: stepsTs,
// values: this.currentSteps,
// })
this.fitbitData.userSteps.push({
time: stepsTs,
values: this.currentSteps
})
prevSteps = this.currentSteps;
} else {
console.log("No movement");
}
// TIMER
if (this.maxTime <= 0 && this.probeOn) {
displayText.text = `Probe ON: Ok to sleep`;
}
else if (this.maxTime <= 0 && !this.probeOn) {
displayText.text = `Probe OFF`;
} else if (this.maxTime > 0 && !this.probeOn) {
displayText.text = `Probe OFF`;
}else {
this.maxTime--;
displayText.text = `Probe ON: ${this.maxTime} mins.`
}
// if (new Date().getTime() - this.startTime >= 30 * 60 * 1000) {
// displayText.text = `Probe ON: Go sleep`;
// } else {
// displayText.text = `Probe ON: ${this.maxTime} mins.`
// }
// this.maxTime--;
_today = new Date();
_time = _today.getHours() + ":" + _today.getMinutes();
timeBox.text = _time;
}
writeHr = () => {
console.log(`HR iss ${this.hrm.heartRate}`);
this.fitbitData.hrData.push({
value: this.hrm.heartRate,
timeStamp: Date.now()
})
}
firstPing = () => {
console.log('Vibrating');
vibration.start("ping");
const mex = {
action: 'First push',
timeStamp: Date.now(),
movement: true,
stDev: this.movementFound ? this.movementStDev : this.noMovementStDev,
userState: sleep.state,
awakeActive: this.bedActive,
awakeSleepy: !this.bedActive
}
// userData.push(mex)
this.fitbitData.sleepData.push(mex)
// console.log(`User info: ${JSON.stringify(fitBitData)}`)
}
activeProbe = () => {
console.log("This is active Probe");
this.probeOn = true;
bEndSession.text = `End Session`
this.firstPing()
this.tid = setInterval(this.pingUser, 5 * 60 * 1000)
setInterval(this.clear, 2 * 1000)
setInterval(this.writeHr, 30 * 1000);
setInterval(this.stepCounter, 1 * 60 * 1000);
}
}