forked from xdrip-js/Lookout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloopIO.js
79 lines (73 loc) · 2.18 KB
/
loopIO.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const Debug = require('debug');
/* eslint-disable-next-line no-unused-vars */
const log = Debug('loopIO:log');
const error = Debug('loopIO:error');
const debug = Debug('loopIO:debug');
const chokidar = require('chokidar');
const fs = require('fs');
const moment = require('moment');
module.exports = (io, options) => {
const openapsDir = options.openaps;
let iob;
let enacted;
const readIOB = (path) => {
debug(`Reading file ${path}`);
setTimeout(() => {
fs.readFile(path, 'utf8', (err, data) => {
if (err) {
error(`Error reading file: ${path}`);
return; // we'll not consider error handling for now
}
try {
const obj = JSON.parse(data);
[{ iob }] = obj;
io.emit('iob', iob);
} catch (e) {
error(`Error parsing JSON file: ${path}`);
}
});
}, 1000);
};
chokidar.watch(`${openapsDir}/monitor/iob.json`)
.on('change', readIOB)
.on('add', readIOB);
const readEnacted = (path) => {
debug(`Reading file ${path}`);
// use timeout of 1 s to make sure the write operation is finished
// as per https://github.com/paulmillr/chokidar/issues/365#issuecomment-146896170
setTimeout(() => {
fs.readFile(path, 'utf8', (err, data) => {
if (err) return; // we'll not consider error handling for now
try {
const obj = JSON.parse(data);
enacted = (({
timestamp,
rate,
duration,
units,
COB,
}) => ({
date: moment(timestamp).toDate().getTime(),
rate,
duration,
units,
COB,
}))(obj);
debug('Enacted:\n%O', enacted);
io.emit('enacted', enacted);
} catch (e) {
error(`Error parsing JSON file: ${path}`);
}
});
}, 1000);
};
chokidar.watch(`${openapsDir}/enact/enacted.json`)
.on('change', readEnacted)
.on('add', readEnacted);
io.on('connection', (socket) => {
socket.emit('iob', iob);
socket.emit('enacted', enacted);
// iob = require('/root/myopenaps/monitor/iob.json');
// socket.emit('iob', iob[0]['iob']);
});
};