1
0
Fork 0

[sleeplog] Change .onChange from array to object

master
storm64 2022-11-10 17:04:54 +01:00
parent 81aece08ee
commit 58330df11c
3 changed files with 71 additions and 70 deletions

View File

@ -7,4 +7,4 @@
0.10: Complete rework off this app! 0.10: Complete rework off this app!
0.10beta: Add interface.html to view saved log data, add "View log" function for debugging log, send data for gadgetbridge, change caching for global getStats 0.10beta: Add interface.html to view saved log data, add "View log" function for debugging log, send data for gadgetbridge, change caching for global getStats
0.11: Prevent module not found error 0.11: Prevent module not found error
0.12: Execute functions in `sleeplog.onChange[fn({timestamp, status, consecutive})]` on a status change 0.12: Execute functions in `sleeplog.onChange` object on a status change

View File

@ -1,6 +1,6 @@
# Sleep Log # Sleep Log
This app logs and displays the following states: This app logs and displays the following states:
- sleepling status: _unknown, not worn, awake, light sleep, deep sleep_ - sleepling status: _unknown, not worn, awake, light sleep, deep sleep_
- consecutive sleep status: _unknown, not consecutive, consecutive_ - consecutive sleep status: _unknown, not consecutive, consecutive_
@ -20,55 +20,55 @@ Logfiles are not removed on un-/reinstall to prevent data loss.
--- ---
#### On the main app screen: #### On the main app screen:
- __swipe left & right__ - __swipe left & right__
to change the displayed day to change the displayed day
- __touch the "title"__ (e.g. `Night to Fri 20/05/2022`) - __touch the "title"__ (e.g. `Night to Fri 20/05/2022`)
to enter day selection prompt to enter day selection prompt
- __touch the info area__ - __touch the info area__
to change the displayed information to change the displayed information
(by default: consecutive & true sleeping) (by default: consecutive & true sleeping)
- __touch the wrench__ (upper right corner) - __touch the wrench__ (upper right corner)
to enter the settings to enter the settings
- __use back button widget__ (upper left corner) - __use back button widget__ (upper left corner)
exit the app exit the app
#### Inside the settings: #### Inside the settings:
- __Thresholds__ submenu - __Thresholds__ submenu
Changes take effect from now on, not retrospective! Changes take effect from now on, not retrospective!
- __Max Awake__ | maximal awake duration - __Max Awake__ | maximal awake duration
_10min_ / _20min_ / ... / __60min__ / ... / _120min_ _10min_ / _20min_ / ... / __60min__ / ... / _120min_
- __Min Consecutive__ | minimal consecutive sleep duration - __Min Consecutive__ | minimal consecutive sleep duration
_10min_ / _20min_ / ... / __30min__ / ... / _120min_ _10min_ / _20min_ / ... / __30min__ / ... / _120min_
- __Deep Sleep__ | deep sleep threshold - __Deep Sleep__ | deep sleep threshold
_30_ / _31_ / ... / __100__ / ... / _200_ _30_ / _31_ / ... / __100__ / ... / _200_
- __Light Sleep__ | light sleep threshold - __Light Sleep__ | light sleep threshold
_100_ / _110_ / ... / __200__ / ... / _400_ _100_ / _110_ / ... / __200__ / ... / _400_
- __Reset to Default__ | reset to bold values above - __Reset to Default__ | reset to bold values above
- __BreakToD__ | time of day to break view - __BreakToD__ | time of day to break view
_0:00_ / _1:00_ / ... / __12:00__ / ... / _23:00_ _0:00_ / _1:00_ / ... / __12:00__ / ... / _23:00_
- __App Timeout__ | app specific lock timeout - __App Timeout__ | app specific lock timeout
__0s__ / _10s_ / ... / _120s_ __0s__ / _10s_ / ... / _120s_
- __Enabled__ | completely en-/disables the background service - __Enabled__ | completely en-/disables the background service
__on__ / _off_ __on__ / _off_
- __Debugging__ submenu - __Debugging__ submenu
- __View log__ | display logfile data - __View log__ | display logfile data
Select the logfile by its starting time. Select the logfile by its starting time.
Thresholds are shown as line with its value. Thresholds are shown as line with its value.
- __swipe left & right__ - __swipe left & right__
to change displayed duration to change displayed duration
- __swipe up & down__ - __swipe up & down__
to change displayed value range to change displayed value range
- __touch the graph__ - __touch the graph__
to change between light & dark colors to change between light & dark colors
- __use back button widget__ (upper left corner) - __use back button widget__ (upper left corner)
to go back to the logfile selection to go back to the logfile selection
- __Enabled__ | en-/disables debugging - __Enabled__ | en-/disables debugging
_on_ / __off__ _on_ / __off__
- __write File__ | toggles if a logfile is written - __write File__ | toggles if a logfile is written
_on_ / __off__ _on_ / __off__
- __Duration__ | duration for writing into logfile - __Duration__ | duration for writing into logfile
_1h_ / _2h_ / ... / __12h__ / _96_ _1h_ / _2h_ / ... / __12h__ / _96_
- The following data is logged to a csv-file: - The following data is logged to a csv-file:
_timestamp_ (in days since 1900-01-01 00:00 UTC used by office software) _, movement, status, consecutive, asleepSince, awakeSince, bpm, bpmConfidence_ _timestamp_ (in days since 1900-01-01 00:00 UTC used by office software) _, movement, status, consecutive, asleepSince, awakeSince, bpm, bpmConfidence_
@ -78,34 +78,34 @@ Logfiles are not removed on un-/reinstall to prevent data loss.
Available through the App Loader when your watch is connected. Available through the App Loader when your watch is connected.
- __view data__ - __view data__
Display the data to each timestamp in a table. Display the data to each timestamp in a table.
- __save csv-file__ - __save csv-file__
Download a csv-file with the data to each timestamp. Download a csv-file with the data to each timestamp.
The time format is chooseable beneath the file list. The time format is chooseable beneath the file list.
- __delete file__ - __delete file__
Deletes the logfile from the watch. __Please backup your data first!__ Deletes the logfile from the watch. __Please backup your data first!__
--- ---
### Timestamps and Files ### Timestamps and Files
--- ---
1. externally visible/usable timestamps (in `global.sleeplog`) are formatted as Bangle timestamps: 1. externally visible/usable timestamps (in `global.sleeplog`) are formatted as Bangle timestamps:
seconds since 1970-01-01 00:00 UTC seconds since 1970-01-01 00:00 UTC
2. internally used and logged (to `sleeplog.log (StorageFile)`) is within the highest available resolution: 2. internally used and logged (to `sleeplog.log (StorageFile)`) is within the highest available resolution:
10 minutes since 1970-01-01 00:00 UTC (`Bangle / (10 * 60 * 1000)`) 10 minutes since 1970-01-01 00:00 UTC (`Bangle / (10 * 60 * 1000)`)
3. debug .csv file ID (`sleeplog_123456.csv`) has a hourly resolution: 3. debug .csv file ID (`sleeplog_123456.csv`) has a hourly resolution:
hours since 1970-01-01 00:00 UTC (`Bangle / (60 * 60 * 1000)`) hours since 1970-01-01 00:00 UTC (`Bangle / (60 * 60 * 1000)`)
4. logged timestamps inside the debug .csv file are formatted for office calculation software: 4. logged timestamps inside the debug .csv file are formatted for office calculation software:
days since 1900-01-01 00:00 UTC (`Bangle / (24 * 60 * 60 * 1000) + 25569`) days since 1900-01-01 00:00 UTC (`Bangle / (24 * 60 * 60 * 1000) + 25569`)
5. every 14 days the `sleeplog.log (StorageFile)` is reduced and old entries are moved into separat files for each fortnight (`sleeplog_1234.log`) but still accessible though the app: 5. every 14 days the `sleeplog.log (StorageFile)` is reduced and old entries are moved into separat files for each fortnight (`sleeplog_1234.log`) but still accessible though the app:
fortnights since 1970-01-04 12:00 UTC (converted with `require("sleeplog").msToFn(Bangle)` and `require("sleeplog").fnToMs(fortnight)`) fortnights since 1970-01-04 12:00 UTC (converted with `require("sleeplog").msToFn(Bangle)` and `require("sleeplog").fnToMs(fortnight)`)
- __Logfiles from before 0.10:__ - __Logfiles from before 0.10:__
timestamps and sleeping status of old logfiles are automatically converted on your first consecutive sleep or manually by `require("sleeplog").convertOldLog()` timestamps and sleeping status of old logfiles are automatically converted on your first consecutive sleep or manually by `require("sleeplog").convertOldLog()`
- __View logged data:__ - __View logged data:__
if you'd like to view your logged data in the IDE, you can access it with `require("sleeplog").printLog(since, until)` or `require("sleeplog").readLog(since, until)` to view the raw data if you'd like to view your logged data in the IDE, you can access it with `require("sleeplog").printLog(since, until)` or `require("sleeplog").readLog(since, until)` to view the raw data
since & until in Bangle timestamp, e.g. `require("sleeplog").printLog(Date()-24*60*60*1000, Date())` for the last 24h since & until in Bangle timestamp, e.g. `require("sleeplog").printLog(Date()-24*60*60*1000, Date())` for the last 24h
@ -114,14 +114,14 @@ Available through the App Loader when your watch is connected.
--- ---
#### Access statistics #### Access statistics
- Last Asleep Time [Date]: - Last Asleep Time [Date]:
`Date(sleeplog.awakeSince)` `Date(sleeplog.awakeSince)`
- Last Awake Duration [ms]: - Last Awake Duration [ms]:
`Date() - sleeplog.awakeSince` `Date() - sleeplog.awakeSince`
- Last Statistics [object]: - Last Statistics [object]:
``` ```
// get stats of the last night (period as displayed inside the app) // get stats of the last night (period as displayed inside the app)
// as this might be the mostly used function the data is cached inside the global object // as this might be the mostly used function the data is cached inside the global object
sleeplog.getStats(); sleeplog.getStats();
// get stats of the last 24h // get stats of the last 24h
@ -132,20 +132,20 @@ Available through the App Loader when your watch is connected.
={ calculatedAt: 1653123553810, deepSleep: 250, lightSleep: 150, awakeSleep: 10, ={ calculatedAt: 1653123553810, deepSleep: 250, lightSleep: 150, awakeSleep: 10,
consecSleep: 320, awakeTime: 1030, notWornTime: 0, unknownTime: 0, logDuration: 1440, consecSleep: 320, awakeTime: 1030, notWornTime: 0, unknownTime: 0, logDuration: 1440,
firstDate: 1653036600000, lastDate: 1653111600000 } firstDate: 1653036600000, lastDate: 1653111600000 }
// to get the start of a period defined by "Break TOD" of any date // to get the start of a period defined by "Break TOD" of any date
var startOfBreak = require("sleeplog").getLastBreak(); var startOfBreak = require("sleeplog").getLastBreak();
// same as // same as
var startOfBreak = require("sleeplog").getLastBreak(Date.now()); var startOfBreak = require("sleeplog").getLastBreak(Date.now());
// output as date // output as date
=Date: Sat May 21 2022 12:00:00 GMT+0200 =Date: Sat May 21 2022 12:00:00 GMT+0200
// get stats of this period as displayed inside the app // get stats of this period as displayed inside the app
require("sleeplog").getStats(require("sleeplog").getLastBreak(), 24*60*60*1000); require("sleeplog").getStats(require("sleeplog").getLastBreak(), 24*60*60*1000);
// or any other day // or any other day
require("sleeplog").getStats(require("sleeplog").getLastBreak(Date(2022,4,10)), 24*60*60*1000); require("sleeplog").getStats(require("sleeplog").getLastBreak(Date(2022,4,10)), 24*60*60*1000);
``` ```
- Total Statistics [object]: - Total Statistics [object]:
``` ```
// use with caution, may take a long time ! // use with caution, may take a long time !
require("sleeplog").getStats(0, 0, require("sleeplog").readLog()); require("sleeplog").getStats(0, 0, require("sleeplog").readLog());
@ -154,18 +154,18 @@ Available through the App Loader when your watch is connected.
#### Add functions triggered by status changes #### Add functions triggered by status changes
With the following code it is possible to add functions that will be called on status changes. With the following code it is possible to add functions that will be called on status changes.
``` ```
// first ensure that the sleeplog object is available // first ensure that the sleeplog onChange object is available
if (typeof (global.sleeplog || {}).onChange === "object") { if (typeof (global.sleeplog || {}).onChange === "object") {
// then add your function to the onChange-array // then add your function to the onChange object
sleeplog.onChange.push( function(data) { print(data); } ); sleeplog.onChange["my app name"] = function(data) { print(data); };
} }
``` ```
The passed data object has the following properties: The passed data object has the following properties:
- timestamp: of the status change as date object, - timestamp: of the status change as date object,
(should be around 10min. before "now", the actual call of the function) (should be around 10min. before "now", the actual call of the function)
- status: if changed the value of the new status (0-4) else undefined, - status: if changed the value of the new status (0-4) else undefined,
(0 = unknown, 1 = not worn, 2 = awake, 3 = light sleep, 4 = deep sleep) (0 = unknown, 1 = not worn, 2 = awake, 3 = light sleep, 4 = deep sleep)
- consecutive: if changed the value of the new status (0-2) else undefined, - consecutive: if changed the value of the new status (0-2) else undefined,
(0 = unknown, 1 = no consecutive sleep, 2 = consecutive sleep) (0 = unknown, 1 = no consecutive sleep, 2 = consecutive sleep)
- prevStatus: value of the previous status (0-4), - prevStatus: value of the previous status (0-4),
- prevConsecutive: value of the previous status (0-2) - prevConsecutive: value of the previous status (0-2)
@ -177,7 +177,7 @@ The passed data object has the following properties:
#### To do list #### To do list
- Check translations. - Check translations.
- Add more functionallities to interface.html. - Add more functionallities to interface.html.
- Enable recieving data on the Gadgetbridge side + testing. - Enable recieving data on the Gadgetbridge side + testing.
__Help appreciated!__ __Help appreciated!__
#### Requests, Bugs and Feedback #### Requests, Bugs and Feedback

View File

@ -124,7 +124,7 @@ if (sleeplog.conf.enabled) {
if (!sleeplog.info.saveUpToDate || force) { if (!sleeplog.info.saveUpToDate || force) {
// save status, consecutive status and info timestamps to restore on reload // save status, consecutive status and info timestamps to restore on reload
var save = [sleeplog.info.lastCheck, sleeplog.info.awakeSince, sleeplog.info.asleepSince]; var save = [sleeplog.info.lastCheck, sleeplog.info.awakeSince, sleeplog.info.asleepSince];
// add debuging status if active // add debuging status if active
if (sleeplog.debug) save.push(sleeplog.debug.writeUntil, sleeplog.debug.fileid); if (sleeplog.debug) save.push(sleeplog.debug.writeUntil, sleeplog.debug.fileid);
// stringify entries // stringify entries
@ -258,19 +258,20 @@ if (sleeplog.conf.enabled) {
// check if the status has changed // check if the status has changed
if (data.status !== this.status || data.consecutive !== this.consecutive) { if (data.status !== this.status || data.consecutive !== this.consecutive) {
// check for onChange functions // read and check for onChange functions
if ((this.onChange || []).length) { var onChange = Object.keys(this.onChange) || [];
this.onChange.forEach(fn => { if (onChange.length) onChange.forEach(key => {
// setup timeouts to start onChange functions if fn is a function // read function to key
if (typeof fn === "function") setTimeout(fn, 100, { var fn = this.onChange[key];
timestamp: new Date(data.timestamp), // setup timeouts to start onChange functions if fn is a function
status: data.status === this.status ? undefined : data.status, if (typeof fn === "function") setTimeout(fn, 100, {
consecutive: data.consecutive === this.consecutive ? undefined : data.consecutive, timestamp: new Date(data.timestamp),
prevStatus: this.status, status: data.status === this.status ? undefined : data.status,
prevConsecutive: this.consecutive consecutive: data.consecutive === this.consecutive ? undefined : data.consecutive,
}); prevStatus: this.status,
prevConsecutive: this.consecutive
}); });
} });
// append status // append status
this.appendStatus(data.timestamp, data.status, data.consecutive); this.appendStatus(data.timestamp, data.status, data.consecutive);
@ -335,7 +336,7 @@ if (sleeplog.conf.enabled) {
return this.statsCache; return this.statsCache;
}, },
// define array for functions to execute after a status change (changes had hapened 10min earlier) // define object for functions to execute after a status change (changes had hapened 10min earlier)
// changed values will be passed as object with the following properties: // changed values will be passed as object with the following properties:
// timestamp: as date object, // timestamp: as date object,
// status: if changed 0-4 else undefined, // status: if changed 0-4 else undefined,