forked from timoschlueter/nightscout-librelink-up
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
349 lines (298 loc) · 10.1 KB
/
index.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
const cron = require("node-cron");
const axios = require("axios");
const {createLogger, format, transports} = require("winston");
const {combine, timestamp, printf} = format;
const NIGHTSCOUT_TREND_ARROWS = require("./utils/nightscout-trend-arrows");
const LLU_API_ENDPOINTS = require("./utils/llu-api-endpoints");
const logFormat = printf(({level, message}) => {
return `[${level}]: ${message}`;
});
const logger = createLogger({
format: combine(
timestamp(),
logFormat
),
transports: [
new transports.Console({level: process.env.LOG_LEVEL || "info"}),
]
});
axios.interceptors.response.use(response => {
return response;
}, error => {
if (error.response)
{
logger.error(JSON.stringify(error.response.data));
}
else
{
logger.error(error.message);
}
return error;
});
const USER_AGENT = "FreeStyle LibreLink Up NightScout Uploader";
/**
* LibreLink Up Credentials
*/
const LINK_UP_USERNAME = process.env.LINK_UP_USERNAME;
const LINK_UP_PASSWORD = process.env.LINK_UP_PASSWORD;
const LINK_UP_CONNECTION = process.env.LINK_UP_CONNECTION;
/**
* LibreLink Up API Settings (Don't change this unless you know what you are doing)
*/
const LIBRE_LINK_UP_VERSION = "4.2.2";
const LIBRE_LINK_UP_PRODUCT = "llu.ios";
const LINK_UP_REGION = process.env.LINK_UP_REGION || "EU";
const LIBRE_LINK_UP_URL = getLibreLinkUpUrl(LINK_UP_REGION);
function getLibreLinkUpUrl(region) {
if (LLU_API_ENDPOINTS.hasOwnProperty(region)) {
return LLU_API_ENDPOINTS[region];
}
return LLU_API_ENDPOINTS.EU;
}
/**
* NightScout API
*/
const NIGHTSCOUT_URL = process.env.NIGHTSCOUT_URL;
const NIGHTSCOUT_API_TOKEN = process.env.NIGHTSCOUT_API_TOKEN;
const NIGHTSCOUT_DISABLE_HTTPS = process.env.NIGHTSCOUT_DISABLE_HTTPS || false;
function getNightscoutUrl() {
if (NIGHTSCOUT_DISABLE_HTTPS === "true") {
return "http://" + NIGHTSCOUT_URL;
}
return "https://" + NIGHTSCOUT_URL;
}
/**
* last known authTicket
*/
let authTicket = {};
const libreLinkUpHttpHeaders = {
"User-Agent": USER_AGENT,
"Content-Type": "application/json",
"version": LIBRE_LINK_UP_VERSION,
"product": LIBRE_LINK_UP_PRODUCT,
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
}
const nightScoutHttpHeaders = {
"api-secret": NIGHTSCOUT_API_TOKEN,
"User-Agent": USER_AGENT,
"Content-Type": "application/json",
}
if (process.env.SINGLE_SHOT === "true") {
main().then();
} else {
const schedule = "*/" + (process.env.LINK_UP_TIME_INTERVAL || 5) + " * * * *";
logger.info("Starting cron schedule: " + schedule)
cron.schedule(schedule, () => { main().then() }, {});
}
async function main() {
if (hasValidAuthentication() === false) {
logger.info("renew token");
deleteAuthTicket();
await login();
}
await getGlucoseMeasurements();
}
async function login() {
try {
const url = "https://" + LIBRE_LINK_UP_URL + "/llu/auth/login"
const response = await axios.post(
url,
{
email: LINK_UP_USERNAME,
password: LINK_UP_PASSWORD,
},
{
headers: libreLinkUpHttpHeaders
});
try {
logger.info("Logged in to LibreLink Up");
updateAuthTicket(response.data.data.authTicket);
} catch (err) {
logger.error("Invalid authentication token. Please check your LibreLink Up credentials", err);
}
} catch (error) {
logger.error("Invalid credentials", error);
deleteAuthTicket();
}
}
async function getGlucoseMeasurements() {
try {
let connectionId = await getLibreLinkUpConnection();
if (!connectionId) {
return;
}
const url = "https://" + LIBRE_LINK_UP_URL + "/llu/connections/" + connectionId + "/graph"
const response = await axios.get(
url,
{
headers: getLluAuthHeaders()
});
await uploadToNightScout(response.data.data);
} catch (error) {
logger.error("Error getting glucose measurements", error);
deleteAuthTicket();
}
}
async function getLibreLinkUpConnection() {
try {
const url = "https://" + LIBRE_LINK_UP_URL + "/llu/connections"
const response = await axios.get(
url,
{
headers: getLluAuthHeaders()
});
let connectionData = response.data.data;
if (connectionData.length === 0) {
logger.error("No LibreLink Up connection found");
return null;
}
if (connectionData.length === 1) {
logger.info("Found 1 LibreLink Up connection.");
logPickedUpConnection(connectionData[0]);
return connectionData[0].patientId;
}
dumpConnectionData(connectionData);
if (!LINK_UP_CONNECTION) {
logger.warn("You did not specify a Patient-ID in the LINK_UP_CONNECTION environment variable.");
logPickedUpConnection(connectionData[0]);
return connectionData[0].patientId;
}
let connection = connectionData.filter(connectionEntry => connectionEntry.patientId === LINK_UP_CONNECTION)[0];
if (!connection) {
logger.error("The specified Patient-ID was not found.");
return null;
}
logPickedUpConnection(connection)
return connection.patientId;
} catch (error) {
logger.error("getting libreLinkUpConnection: ", error);
deleteAuthTicket();
return null;
}
}
async function lastEntryDate() {
const url = getNightscoutUrl() + "/api/v1/entries?count=1"
const response = await axios.get(
url,
{
headers: nightScoutHttpHeaders
});
if (!response.data || response.data.length === 0)
{
return null;
}
return new Date(response.data.pop().dateString);
}
async function uploadToNightScout(measurementData) {
const glucoseMeasurement = measurementData.connection.glucoseMeasurement;
const measurementDate = getUtcDateFromString(glucoseMeasurement.FactoryTimestamp);
let lastEntry = await lastEntryDate();
let formattedMeasurements = [];
// Add the most recent measurement first
if (measurementDate > lastEntry) {
formattedMeasurements.push({
"type": "sgv",
"dateString": measurementDate.toISOString(),
"date": measurementDate.getTime(),
"direction": mapTrendArrow(glucoseMeasurement.TrendArrow),
"sgv": glucoseMeasurement.ValueInMgPerDl
});
}
measurementData.graphData.forEach((glucoseMeasurementHistoryEntry) => {
let entryDate = getUtcDateFromString(glucoseMeasurementHistoryEntry.FactoryTimestamp);
if (entryDate > lastEntry) {
formattedMeasurements.push({
"type": "sgv",
"dateString": entryDate.toISOString(),
"date": entryDate.getTime(),
"sgv": glucoseMeasurementHistoryEntry.ValueInMgPerDl
});
}
});
if (formattedMeasurements.length > 0)
{
logger.info("Trying to upload " + formattedMeasurements.length + " glucose measurement items to Nightscout");
try
{
const url = getNightscoutUrl() + "/api/v1/entries"
const response = await axios.post(
url,
formattedMeasurements,
{
headers: nightScoutHttpHeaders
});
if (response.status !== 200)
{
logger.error("Upload to NightScout failed ", response.statusText);
} else
{
logger.info("Upload of " + formattedMeasurements.length + " measurements to Nightscout succeeded");
}
} catch (error)
{
logger.error("Upload to NightScout failed ", error);
}
} else {
logger.info("No new measurements to upload");
}
}
function dumpConnectionData(connectionData) {
logger.debug("Found " + connectionData.length + " LibreLink Up connections:");
connectionData.map((connectionEntry, index) => {
logger.debug("[" + (index + 1) + "] " + connectionEntry.firstName + " " + connectionEntry.lastName + " (Patient-ID: " + connectionEntry.patientId + ")");
});
}
function logPickedUpConnection(connection) {
logger.info("-> The following connection will be used: " + connection.firstName + " " + connection.lastName + " (Patient-ID: " + connection.patientId + ")");
}
function mapTrendArrow(libreTrendArrowRaw) {
switch (libreTrendArrowRaw) {
case 1:
return NIGHTSCOUT_TREND_ARROWS.singleDown
case 2:
return NIGHTSCOUT_TREND_ARROWS.fortyFiveDown
case 3:
return NIGHTSCOUT_TREND_ARROWS.flat
case 4:
return NIGHTSCOUT_TREND_ARROWS.fortyFiveUp
case 5:
return NIGHTSCOUT_TREND_ARROWS.singleUp
default:
return NIGHTSCOUT_TREND_ARROWS.notComputable
}
}
function getLluAuthHeaders() {
let authenticatedHttpHeaders = libreLinkUpHttpHeaders;
authenticatedHttpHeaders.authorization = "Bearer " + getAuthenticationToken();
logger.debug("authenticatedHttpHeaders: " + JSON.stringify(authenticatedHttpHeaders));
return authenticatedHttpHeaders;
}
function deleteAuthTicket() {
authTicket = {};
}
function updateAuthTicket(newAuthTicket) {
authTicket = newAuthTicket;
}
function getAuthenticationToken() {
if (authTicket.token) {
return authTicket.token;
}
logger.warn("no authTicket.token");
return null;
}
function hasValidAuthentication() {
if (authTicket.expires !== undefined) {
let currentDate = Math.round(new Date().getTime() / 1000);
return currentDate < authTicket.expires;
}
logger.info("no authTicket.expires");
return false;
}
function getUtcDateFromString(timeStamp) {
let utcDate = new Date(timeStamp);
utcDate.setTime(utcDate.getTime() - utcDate.getTimezoneOffset() * 60 * 1000);
return utcDate;
}