This repository has been archived by the owner on Apr 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.js
665 lines (616 loc) · 28.5 KB
/
main.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
'use strict';
const request = require('request');
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
const adapterName = require('./package.json').name.split('.').pop();
const BASE_URL = 'https://api.fitbit.com/1/user/';
const clientID = '22BD68';
const clientSecret = 'c4612114c93436901b6affb03a1e5ec8';
let adapter;
function startAdapter(options) {
options = options || {};
options = Object.assign({}, options, {name: adapterName});
adapter = new utils.Adapter(options);
adapter.on('ready', () => main(adapter));
return adapter;
}
function getDate() {
const today = new Date();
let dd = today.getDate();
let mm = today.getMonth() + 1;
const year = today.getFullYear();
if (mm < 10) {
mm = '0' + mm;
}
if (dd < 10) {
dd = '0' + dd;
}
return `${year}-${mm}-${dd}`;
}
function requestProfile(token, adapter) {
if (adapter._profilePromise) {
return adapter._profilePromise;
}
const url = `${BASE_URL}-/profile.json`;
const headers = {Authorization: 'Bearer ' + token};
adapter._profilePromise = new Promise((resolve, reject) => {
// read more here: https://dev.fitbit.com/build/reference/web-api/body/
// const response = {
// "user": {
// "aboutMe":<value>,
// "avatar":<value>,
// "avatar150":<value>,
// "avatar640":<value>,
// "city":<value>,
// "clockTimeDisplayFormat":<12hour|24hour>,
// "country":<value>,
// "dateOfBirth":<value>,
// "displayName":<value>,
// "distanceUnit":<value>,
// "encodedId":<value>,
// "foodsLocale":<value>,
// "fullName":<value>,
// "gender":<FEMALE|MALE|NA>,
// "glucoseUnit":<value>,
// "height":<value>,
// "heightUnit":<value>,
// "locale":<value>,
// "memberSince":<value>,
// "offsetFromUTCMillis":<value>,
// "startDayOfWeek":<value>,
// "state":<value>,
// "strideLengthRunning":<value>,
// "strideLengthWalking":<value>,
// "timezone":<value>,
// "waterUnit":<value>,
// "weight":<value>,
// "weightUnit":<value>
// }
// };
request({url, headers}, (error, response, body) => {
if (!error && response.statusCode === 200) {
const data = JSON.parse(body);
adapter.log.debug('Profile: ' + JSON.stringify(data));
if (data && data.user) {
resolve(data.user);
} else {
reject('User not found');
}
} else {
adapter.log.error('Cannot read profile: ' + (body || error || response.statusCode));
reject('Cannot read profile: ' + (body || error || response.statusCode));
}
});
});
return adapter._profilePromise;
}
function requestWeight(token, adapter) {
const url = `${BASE_URL}-/body/log/weight/date/${getDate()}.json`;
const headers = {Authorization: 'Bearer ' + token};
return new Promise((resolve, reject) => {
// read more here: https://dev.fitbit.com/build/reference/web-api/body/
// const response = {
// "weight":[
// {
// "bmi":23.57,
// "date":"2015-03-05",
// "logId":1330991999000,
// "time":"23:59:59",
// "weight":73,
// "source": "API"
// },
// {
// "bmi":22.57,
// "date":"2015-03-05",
// "logId":1330991999000,
// "time":"21:10:59",
// "weight":72.5,
// "source": "Aria"
// }
// ]
// };
request({url, headers}, (error, response, body) => {
if (!error && response.statusCode === 200) {
const data = JSON.parse(body);
adapter.log.debug('weight: ' + JSON.stringify(data));
createObject(token, adapter, 'weight', {role: 'value.health.weight', unit: '%%WEIGHT%%'})
.then(() => createObject(token, adapter, 'bmi', {role: 'value.health.bmi'}))
.then(() => {
if (data && data.weight && data.weight.length) {
const value = data.weight.pop();
const date = new Date(`${value.date}T${value.time}`);
adapter.getState('weight', (err, state) => {
if (!state ||
!state.val ||
Math.abs(state.ts - date.getTime()) > 1000 || // one second difference
Math.abs(state.val - value.weight) > 0.1) { // 0.1 difference
adapter.setState('weight', {val: value.weight, ack: true, ts: date.getTime()}, () =>
adapter.setState('bmi', {val: value.bmi, ack: true, ts: date.getTime()}, () =>
resolve()));
} else {
resolve();
}
});
} else {
reject('Weight is not found');
}
});
} else {
adapter.log.error('Cannot read weight: ' + (body || error || response.statusCode));
reject('Cannot read weight: ' + (body || error || response.statusCode));
}
});
});
}
function createObject(token, adapter, name, common) {
return new Promise(resolve => {
adapter.getObject(name, (err, obj) => {
if (!obj) {
requestProfile(token, adapter)
.then(user => {
obj = {};
obj.type = 'state';
obj.common = common;
obj.common.name = user.displayName + ' ' + name;
obj.common.type = obj.common.type || 'number';
if (common.unit === '%%WEIGHT%%') {
common.unit = user.weightUnit === 'METRIC' ? 'kg' : (user.weightUnit === 'US' ? 'pounds' : 'stone');
}
obj.common.read = true;
obj.common.write = false;
obj.native = {};
adapter.extendObject(name, obj, () => resolve(user));
});
} else {
resolve();
}
});
});
}
function requestBodyFat(token, adapter) {
const url = `${BASE_URL}-/body/log/fat/date/${getDate()}.json`;
const headers = {Authorization: 'Bearer ' + token};
return new Promise((resolve, reject) => {
// read more here: https://dev.fitbit.com/build/reference/web-api/body/
// const response = {
// "fat":[
// {
// "date":"2012-03-05",
// "fat":14,
// "logId":1330991999000,
// "time":"23:59:59",
// "source": "API"
// },
// {
// "date":"2012-03-05",
// "fat":13.5,
// "logId":1330991999000,
// "time":"21:20:59",
// "source":"Aria"
// }
// ]
// };
request({url, headers}, (error, response, body) => {
if (!error && response.statusCode === 200) {
const data = JSON.parse(body);
adapter.log.debug('Fat: ' + JSON.stringify(data));
createObject(token, adapter, 'fat', {role: 'value.health.fat', unit: '%',})
.then(() => {
if (data && data.fat && data.fat.length) {
const value = data.fat.pop();
const date = new Date(`${value.date}T${value.time}`);
adapter.getState('fat', (err, state) => {
if (!state ||
!state.val ||
Math.abs(state.ts - date.getTime()) > 1000 || // one second difference
Math.abs(state.val - value.fat) > 0.1) { // 0.1 difference
adapter.setState('fat', {val: value.fat, ack: true, ts: date.getTime()}, () =>
resolve());
} else {
resolve();
}
});
} else {
reject('fat is not found');
}
});
} else {
adapter.log.error('Cannot read fat: ' + (body || error || response.statusCode));
reject('Cannot read fat: ' + (body || error || response.statusCode));
}
});
});
}
function requestSleep(token, adapter) {
const url = `${BASE_URL}-/sleep/date/${getDate()}.json`;
const headers = {Authorization: 'Bearer ' + token};
return new Promise((resolve, reject) => {
// read more here: https://dev.fitbit.com/build/reference/web-api/body/
// const response =
//
// {
// "sleep": [
// {
// "dateOfSleep": "2017-04-02",
// "duration": <value in milliseconds>,
// "efficiency": <value>,
// "isMainSleep": true,
// "levels": {
// "summary": {
// "deep": {
// "count": <value>,
// "minutes": <value>,
// "thirtyDayAvgMinutes": <value>
// },
// "light": {
// "count": <value>,
// "minutes": <value>,
// "thirtyDayAvgMinutes": <value>
// },
// "rem": {
// "count": <value>,
// "minutes": <value>,
// "thirtyDayAvgMinutes": <value>
// },
// "wake": {
// "count": <value>,
// "minutes": <value>,
// "thirtyDayAvgMinutes": <value>
// }
// },
// "data": [
// {
// "datetime": "2017-04-01T23:58:30.000",
// "level": "wake",
// "seconds": <value>
// },
// {
// "datetime": "2017-04-02T00:16:30.000",
// "level": "rem",
// "seconds": <value>
// },
// <...>
// ],
// "shortData": [
// {
// "datetime": "2017-04-02T05:58:30.000",
// "level": "wake",
// "seconds": <value>
// },
// <...>
// ]
// },
// "logId": <value>,
// "minutesAfterWakeup": <value>,
// "minutesAsleep": <value>,
// "minutesAwake": <value>,
// "minutesToFallAsleep": <value>, // this is generally 0 for autosleep created sleep logs
// "startTime": "2017-04-01T23:58:30.000",
// "timeInBed": <value in minutes>,
// "type": "stages"
// },
// {
// "dateOfSleep": "2017-04-02",
// "duration": <value in milliseconds>,
// "efficiency": <value>,
// "isMainSleep": false,
// "levels": {
// "data": [
// {
// "dateTime": "2017-04-02T12:06:00.000",
// "level": "asleep",
// "seconds": <value>
// },
// {
// "dateTime": "2017-04-02T12:13:00.000",
// "level": "restless",
// "seconds": <value>
// },
// {
// "dateTime": "2017-04-02T12:14:00.000",
// "level": "awake",
// "seconds": <value>
// },
// <...>
// ],
// "summary": {
// "asleep": {
// "count": 0, // this field should not be used for "asleep" summary info
// "minutes": <value>
// },
// "awake": {
// "count": <value>,
// "minutes": <value>
// },
// "restless": {
// "count": <value>,
// "minutes": <value>
// }
// }
// },
// "logId": <value>,
// "minutesAfterWakeup": <value>,
// "minutesAsleep": <value>,
// "minutesAwake": <value>,
// "minutesToFallAsleep": <value>, // this is generally 0 for autosleep created sleep logs
// "startTime": "2017-04-02T12:06:00.000",
// "timeInBed": <value in minutes>,
// "type": "classic"
// }
// ],
// "summary": {
// "totalMinutesAsleep": <value>,
// "totalSleepRecords": 2,
// "totalTimeInBed": <value in minutes>
// }
// };
request({url, headers}, (error, response, body) => {
if (!error && response.statusCode === 200) {
const data = JSON.parse(body);
adapter.log.debug('Sleep: ' + JSON.stringify(data ? data.summary : data));
createObject(token, adapter, 'sleep', {role: 'value.health.sleep', unit: 'min'})
.then(() => {
if (data && data.summary && data.summary.totalMinutesAsleep !== undefined) {
const value = data.summary.totalMinutesAsleep;
adapter.getState('sleep', (err, state) => {
if (!state ||
!state.val ||
Math.abs(state.val - value) > 0.1) { // 0.1 difference
adapter.setState('sleep', {val: value, ack: true}, () =>
resolve());
} else {
resolve();
}
});
} else {
reject('sleep is not found');
}
});
} else {
adapter.log.error('Cannot read sleep: ' + (body || error || response.statusCode));
reject('Cannot read sleep: ' + (body || error || response.statusCode));
}
});
});
}
function requestActivities(token, adapter) {
const url = `${BASE_URL}-/activities/date/${getDate()}.json`;
const headers = {Authorization: 'Bearer ' + token};
return new Promise((resolve, reject) => {
// read more here: https://dev.fitbit.com/build/reference/web-api/user/
// const response = {
// "activities":[
// {
// "activityId":51007,
// "activityParentId":90019,
// "calories":230,
// "description":"7mph",
// "distance":2.04,
// "duration":1097053,
// "hasStartTime":true,
// "isFavorite":true,
// "logId":1154701,
// "name":"Treadmill, 0% Incline",
// "startTime":"00:25",
// "steps":3783
// }
// ],
// "goals":{
// "caloriesOut":2826,
// "distance":8.05,
// "floors":150,
// "steps":10000
// },
// "summary":{
// "activityCalories":230,
// "caloriesBMR":1913,
// "caloriesOut":2143,
// "distances":[
// {"activity":"tracker", "distance":1.32},
// {"activity":"loggedActivities", "distance":0},
// {"activity":"total","distance":1.32},
// {"activity":"veryActive", "distance":0.51},
// {"activity":"moderatelyActive", "distance":0.51},
// {"activity":"lightlyActive", "distance":0.51},
// {"activity":"sedentaryActive", "distance":0.51},
// {"activity":"Treadmill, 0% Incline", "distance":3.28}
// ],
// "elevation":48.77,
// "fairlyActiveMinutes":0,
// "floors":16,
// "lightlyActiveMinutes":0,
// "marginalCalories":200,
// "sedentaryMinutes":1166,
// "steps":0,
// "veryActiveMinutes":0
// }
// };
request({url, headers}, (error, response, body) => {
if (!error && response.statusCode === 200) {
const data = JSON.parse(body);
adapter.log.debug('Profile: ' + JSON.stringify(data));
createObject(token, adapter, 'steps', {unit: 'steps', role: 'value.health.steps'})
.then(() => createObject(token, adapter, 'restingHeartRate', {
desc: {
"en": "The number of heart beats per minute while you are at rest",
"de": "Die Anzahl der Herzschläge pro Minute im Ruhezustand",
"ru": "Количество сердечных сокращений в минуту, пока вы находитесь в состоянии покоя",
"pt": "O número de batimentos cardíacos por minuto enquanto você está em repouso",
"nl": "Het aantal hartslagen per minuut terwijl u in rust bent",
"fr": "Le nombre de battements de coeur par minute lorsque vous êtes au repos",
"it": "Il numero di battiti cardiaci al minuto mentre sei a riposo",
"es": "La cantidad de latidos del corazón por minuto mientras estás en reposo",
"pl": "Liczba uderzeń serca na minutę podczas odpoczynku",
"zh-cn": "休息时每分钟的心跳次数"
},
role: 'value.health.bpm',
unit: 'bpm'
}))
.then(() => createObject(token, adapter, 'calories', {unit: 'kcal', role: 'value.health.calories'}))
.then(() => {
if (data && data.summary) {
const summary = data.summary;
adapter.setState('steps', summary.steps, true);
summary.restingHeartRate && adapter.setState('restingHeartRate', summary.restingHeartRate, true);
adapter.setState('calories', summary.caloriesOut, true);
resolve();
} else {
reject('Activities not found');
}
});
} else {
adapter.log.error('Cannot read activities: ' + (body || error || response.statusCode));
reject('Cannot read activities: ' + (body || error || response.statusCode));
}
});
});
}
function requestDevices(token, adapter) {
const url = `${BASE_URL}-/devices.json`;
const headers = {Authorization: 'Bearer ' + token};
return new Promise((resolve, reject) => {
// read more here: https://dev.fitbit.com/build/reference/web-api/devices/
// const response = [
// {
// "battery": "High",
// "deviceVersion": "Charge HR",
// "id": "27072629",
// "lastSyncTime": "2015-07-27T17:01:39.313",
// "type": "TRACKER"
// },
// {
// "battery": "Empty",
// "deviceVersion": "MobileTrack",
// "id": "29559794",
// "lastSyncTime": "2015-07-19T16:57:59.000",
// "type": "TRACKER"
// },
// {
// "battery": "High",
// "deviceVersion": "Aria",
// "id": "Y1PFEJZGGX8QFYTV",
// "lastSyncTime": "2015-07-27T07:14:34.000",
// "type": "SCALE"
// }
// ];
request({url, headers}, (error, response, body) => {
if (!error && response.statusCode === 200) {
const data = JSON.parse(body);
adapter.log.debug('Devices: ' + JSON.stringify(data));
const promises = [];
if (data && data.length) {
data.forEach(device => {
promises.push(new Promise(resolve => {
const id = 'batteryAlarm.' + device.deviceVersion + '_' + device.id;
const value = device.battery.toLowerCase() === 'empty';
const date = new Date(device.lastSyncTime);
adapter.setObjectNotExists(id, {
type: 'state',
common: {
name: 'Battery status',
type: 'boolean',
role: 'indicator.lowbat',
read: true,
write: false
},
native: {}
}, () =>
adapter.getState(id, (err, state) => {
if (!state ||
!state.val ||
Math.abs(state.ts - date.getTime()) > 1000 || // one second difference
value !== state.val) {
adapter.setState(id, {val: value, ack: true, ts: date.getTime()}, () =>
resolve());
} else {
resolve();
}
}));
}));
});
} else {
reject('devices not found');
}
Promise.all(promises)
.then(() => resolve())
.catch(e => reject(e));
} else {
adapter.log.error('Cannot read devices: ' + (body || error || response.statusCode));
reject('Cannot read devices: ' + (body || error || response.statusCode));
}
});
});
}
function checkToken(adapter) {
return new Promise((resolve, reject) => {
if (adapter.config.token) {
adapter.log.debug('Used user token: ' + adapter.config.token);
return resolve(adapter.config.token);
}
adapter.getState('tokens.expire', (err, state) => {
if (!state || !state.val) {
reject('No tokens. Please authenticate in configuration');
} else {
const time = new Date(state.val);
// if less then 5 hours
if (time.getTime() - Date.now() < 4 * 3600000) {
adapter.getState('tokens.refresh', (err, state) => {
if (!state || !state.val) {
reject('No tokens. Please authenticate in configuration');
} else {
request({
url: 'https://api.fitbit.com/oauth2/token',
headers: {
Authorization: 'Basic ' + Buffer.from(clientID + ':' + clientSecret).toString('base64'),
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'POST',
body: 'grant_type=refresh_token&refresh_token=' + state.val
}, (error, state, body) => {
if (error || state.statusCode !== 200 || !body) {
adapter.log.error('Cannot get new token: ' + (body || error || response.statusCode));
return reject('Cannot get new token: ' + (error || body || state.statusCode || 'NO body'));
}
if (typeof body !== 'object') {
body = JSON.parse(body);
}
const time = new Date();
time.setSeconds(time.getSeconds() + body.expires_in);
adapter.setState('tokens.access', body.access_token, true, () =>
adapter.setState('tokens.refresh', body.refresh_token, true, () =>
adapter.setState('tokens.expire', time.toISOString(), true, () =>
resolve(body.access_token))));
});
}
});
} else {
adapter.getState('tokens.access', (err, state) => resolve(state.val));
}
}
});
});
}
function main(adapter) {
checkToken(adapter)
.then(token => {
const promises = [];
adapter.config.weight && promises.push(requestWeight(token, adapter));
adapter.config.fat && promises.push(requestBodyFat(token, adapter));
adapter.config.activities && promises.push(requestActivities(token, adapter));
adapter.config.devices && promises.push(requestDevices(token, adapter));
adapter.config.sleep && promises.push(requestSleep(token, adapter));
!promises.length && adapter.log.error('No one option is enabled. Please enable what kind of data do you want to have in adapter configuration!');
Promise.all(promises)
.catch(e => adapter.log.error('Cannot read: ' + e))
.then(() => setTimeout(() => adapter.stop(), 1000));
}).catch(e => {
adapter.log.error(e);
setTimeout(() => adapter.stop(), 1000);
});
}
// If started as allInOne mode => return function to create instance
if (module.parent) {
module.exports = startAdapter;
} else {
// or start the instance directly
startAdapter();
}