-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathtransmitterIO.js
1515 lines (1237 loc) · 43.2 KB
/
transmitterIO.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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const cp = require('child_process');
const moment = require('moment');
const Debug = require('debug');
const log = Debug('transmitterIO:log');
const error = Debug('transmitterIO:error');
const debug = Debug('transmitterIO:debug');
const _ = require('lodash');
const calibration = require('./calibration');
const xDripAPS = require('./xDripAPS')();
module.exports = async (options, storage, client, fakeMeter) => {
let txId;
let txAddress = null;
let txFailedReads = 0;
let txStatus = null;
let txFirmware = null;
let pending = [];
let worker = null;
let timerObj = null;
let lastSuccessfulTxmitterCalTime = null;
let lastSuccessfulRead = null;
const transmitterInSession = (sgv) => {
if (sgv && ('inSession' in sgv) && sgv.inSession) {
return true;
}
return false;
};
const sessionLength = () => {
// G6s are 10 days
if (txId.substr(0, 1) === '8') {
return 10 * 24 * 60;
}
// default to G5's 7 days
return 7 * 24 * 60;
};
const autoStopSession = (glucoseHist) => {
if (!options.auto_stop || (glucoseHist.length === 0)) {
return false;
}
const lastSGV = glucoseHist[glucoseHist.length - 1];
if (!lastSGV.sessionStartDate) {
return false;
}
const sessionEndTime = moment(lastSGV.sessionStartDate);
sessionEndTime.add(sessionLength(), 'minutes');
const minutesRemaining = sessionEndTime.diff(moment(), 'minutes');
if (minutesRemaining > 15) {
return false;
}
return true;
};
const filterPending = (oldPending) => {
let haveBatteryStatus = false;
let haveFirmwareRequest = false;
const newPending = oldPending.filter((msg) => {
// Don't send stop or start sensors older than 2 hours and 12 minutes
if (((msg.type === 'StopSensor') || (msg.type === 'StartSensor')) && ((Date.now() - msg.date) > 132 * 60000)) {
return false;
}
// Don't send other messages older than 12 minutes
if (((msg.type !== 'StopSensor') && (msg.type !== 'StartSensor')) && (Date.now() - msg.date) > 12 * 60000) {
return false;
}
// Don't send any commands if in read only mode
if (options.read_only && (msg.type !== 'BatteryStatus')) {
return false;
}
if (msg.type === 'BatteryStatus') {
if (haveBatteryStatus) {
return false;
}
haveBatteryStatus = true;
}
if (msg.type === 'VersionRequest') {
if (haveFirmwareRequest) {
return false;
}
haveFirmwareRequest = true;
}
return true;
});
return newPending;
};
const sgvGaps = (rigSGVs) => {
const now = moment().valueOf();
const minDate = moment().subtract(24, 'hours').valueOf();
const rigGaps = [];
if (rigSGVs && (rigSGVs.length > 0)) {
let prevTime = rigSGVs[0].readDateMills;
for (let i = 1; i < rigSGVs.length; i += 1) {
// Add 1 minute to gapStart and subtract 1 minute from gapEnd to prevent duplicats
const gap = {
gapStart: moment(prevTime + 60000),
gapEnd: moment(rigSGVs[i].readDateMills - 60000),
};
if ((rigSGVs[i].readDateMills - prevTime) > 6 * 60000) {
rigGaps.push(gap);
}
prevTime = rigSGVs[i].readDateMills;
}
if ((now - prevTime) > 6 * 60000) {
// Add 1 minute to gapStart to prevent duplicats
rigGaps.push({ gapStart: moment(prevTime + 60000), gapEnd: moment(now) });
}
} else {
// Add 1 minute to gapStart to prevent duplicats
rigGaps.push({ gapStart: moment(minDate + 60000), gapEnd: moment(now) });
}
return rigGaps;
};
const getGlucose = async () => {
const glucoseHist = await storage.getArray('glucoseHist');
if (glucoseHist.length > 0) {
return glucoseHist[glucoseHist.length - 1];
}
return null;
};
const removeBTDevice = (btName) => {
cp.exec(`bt-device -a hci${options.hci} -r ${btName}`, (err, stdout, stderr) => {
if (err) {
debug(`Unable to remove BT Device: ${btName} - ${err}`);
return;
}
log(`Removed BT Device: ${btName}`);
debug(`stdout: ${stdout}`);
debug(`stderr: ${stderr}`);
});
};
const removeBTDevices = () => {
const btName = `Dexcom${txId.slice(-2)}`;
removeBTDevice(btName);
if (txAddress) {
const btAddressName = txAddress.split(':').join('-').toUpperCase();
removeBTDevice(btAddressName);
}
};
// Return true if there is no SGV or the most recent SGV was received from transmitter
// Also return true if the latest SGV we have is more than 15 minutes old
// Return false if most recent SGV was received from NS
const isControlling = async (sgv) => {
let latestSgv = sgv;
if (!latestSgv) {
latestSgv = await getGlucose();
}
// inSession is only in the SGV record if it came from transmitter
if (!latestSgv || (typeof latestSgv.inSession !== 'undefined')) {
return true;
}
if ((moment().valueOf() - latestSgv.readDateMills) > 15 * 60000) {
return true;
}
return false;
};
const rebootRig = async () => {
if (await isControlling()) {
error(
'\n====================================\n'
+ `Too many read failures: ${txFailedReads} failures, rebooting rig`
+ '\n====================================',
);
cp.exec('bash -c "wall Rebooting Due to Transmitter Read Errors; sleep 5; shutdown -r now"', (err, stdout, stderr) => {
if (err) {
error(`Unable to reboot rig: - ${err}`);
return;
}
debug(`stdout: ${stdout}`);
debug(`stderr: ${stderr}`);
});
} else {
error(
'\n====================================\n'
+ `Too many read failures: ${txFailedReads} failures, but not rebooting because not controlling rig\n`
+ '\n====================================',
);
}
};
const stopSensorSession = async (stopTime, reason) => {
const now = moment();
let stopWhen = stopTime || now;
// if the commanded stop time is older than 2 hours, use current time - 120 minutes
if (stopTime.diff(now, 'minutes') > 132) {
stopWhen = moment(now.valueOf() - 120 * 60000);
}
const sensorStop = {
date: stopWhen,
notes: reason,
};
await storage.setEvent('sensorStop', sensorStop)
.catch((err) => {
error(`Unable to store sensorStop: ${err}`);
});
await calibration.clearCalibration(storage);
};
const stopTransmitterSession = (stopTime) => {
const twoAgo = moment().subtract(2, 'hours');
const stopWhen = stopTime || twoAgo;
// Stop sensor 2 hours prior to now to enable a rapid restart
// if one is desired.
pending.push({ date: stopWhen.valueOf(), type: 'StopSensor' });
pending = filterPending(pending);
client.newPending(pending);
};
// Checks whether the current sensor session should end based on
// the latest sensor stop and sensor insert records.
const checkSensorSession = async (sensorInsert, sensorStop, bgChecks, sgv) => {
let sessionStart = 0;
let sensorStartDelta = 0;
let sensorStopDelta = 0;
let reason = null;
const txmitterInSession = transmitterInSession(sgv);
if (txmitterInSession) {
// this is only true if we are the controlling rig AND the transmitter has an active session
sessionStart = moment(sgv.sessionStartDate);
// Give 6 minutes extra time
sensorStartDelta = sensorInsert
? (sensorInsert.valueOf() - sessionStart.valueOf() - 6 * 60000) : 0;
sensorStopDelta = sensorStop ? (sensorStop.valueOf() - sessionStart.valueOf()) : 0;
}
if (txmitterInSession && (sensorStartDelta > 0 || sensorStopDelta > 0)) {
// give a 2 hour play between the sensor insert record
// and the session start date from the transmitter
if (sensorStartDelta > 0) {
reason = '\n===================================='
+ `\nSensor Insert, ${sensorInsert.format()}, is after Sensor Start, ${sessionStart.format()}`
+ '\nStopping Sensor Session'
+ '\n====================================';
} else {
reason = '\n===================================='
+ `\nSensor Stop, ${sensorStop.format()}, is after Sensor Start, ${sessionStart.format()}`
+ '\nStopping Sensor Session'
+ '\n====================================';
}
log(reason);
debug(`Session Start: ${sessionStart} sensorStart: ${sensorInsert} sensorStop: ${sensorStop}`);
stopTransmitterSession(sensorStop);
await stopSensorSession(sensorStop, reason);
} else if (isControlling(sgv)) {
const haveCal = await calibration.haveCalibration(storage);
let latestBgCheckTime = null;
if (bgChecks && (bgChecks.length > 0)) {
latestBgCheckTime = moment(bgChecks[bgChecks.length - 1].dateMills);
}
const haveValidCal = await calibration.validateCalibration(
options, storage, sensorInsert, sensorStop, latestBgCheckTime,
);
if (haveCal && !haveValidCal) {
reason = '\n===================================='
+ '\nTransmitter not in session and found sensor change, start, or stop after latest calibration and transmitter not in session. Stopping Sensor Session.'
+ '\nSee calibration log messages above for details'
+ '\n====================================';
log(reason);
await stopSensorSession(sensorStop, reason);
}
}
};
const inSensorSession = (sgv) => {
if (transmitterInSession(sgv)) {
return true;
}
// If the transmitter is not in a session, return whether
// we have a valid set of calibration values
return calibration.haveCalibration(storage);
};
const startSession = async (startTime, sensorSerialCode, reason) => {
const sgv = await getGlucose();
log(
'\n===================================='
+ `\nAttempting to start sensor session at time: ${moment(startTime).format()}`
+ '\n====================================',
);
if (!inSensorSession(sgv)) {
// Only enter a sensorStart if we aren't
// in either a transmitter session, extend session, or expired session
await storage.setEvent('sensorStart',
{
date: moment(),
notes: reason,
})
.catch((err) => {
error(`Error setting rig sensorStart: ${err}`);
});
}
if (!transmitterInSession(sgv)) {
let startPending = false;
_.each(pending, (cmd) => {
if (cmd.type === 'StartSensor') {
startPending = true;
}
});
if (!startPending) {
pending.push({ date: startTime, type: 'StartSensor', sensorSerialCode });
pending = filterPending(pending);
client.newPending(pending);
}
}
};
const sendNewGlucose = async (sgv, sendToXdrip) => {
client.newSGV(sgv);
if (sgv.glucose) {
// wait for fakeMeter to finish so it doesn't interfere with
// pump-loop
await fakeMeter.glucose(sgv.glucose);
}
xDripAPS.post(sgv, sendToXdrip, options.nightscout && !options.read_only);
};
const sendCGMStatus = async (sgv, bgChecks) => {
let latestBGCheckTime = null;
if (bgChecks.length > 0) {
latestBGCheckTime = bgChecks[bgChecks.length - 1].dateMills;
}
const activeCal = await calibration.getActiveCal(options, storage);
if (options.nightscout) {
xDripAPS.postStatus(txId, sgv, txStatus, activeCal, latestBGCheckTime);
}
};
// Store the last 24 hours of glucose readings
const storeNewGlucose = async (glucoseHist, sgv) => {
glucoseHist.push(sgv);
let newGlucoseHist = _.sortBy(glucoseHist, ['readDateMills']);
const minDate = moment().subtract(24, 'hours').valueOf();
let sliceStart = 0;
// store the last 24 hours of glucose
// history is used to determine trend and noise values
// and back fill nightscout.
for (let i = 0; i < newGlucoseHist.length; i += 1) {
if (newGlucoseHist[i].readDateMills < minDate) {
sliceStart = i + 1;
}
}
newGlucoseHist = newGlucoseHist.slice(sliceStart);
await storage.setItem('glucoseHist', newGlucoseHist)
.catch((err) => {
error(`Unable to store glucoseHist: ${err}`);
});
};
const txStatusString = (state) => {
switch (state) {
case null:
return 'None';
case 0x00:
return 'OK';
case 0x81:
return 'Low battery';
case 0x83:
return 'Expired';
default:
return state ? `Unknown: 0x${state.toString(16)}` : '--';
}
};
const txStatusStringShort = (state) => {
switch (state) {
case null:
return '--';
case 0x00:
return 'OK';
case 0x81:
return 'Low bat';
case 0x83:
return 'Expired';
default:
return state ? `Unknown: 0x${state.toString(16)}` : '--';
}
};
const stateString = (sgv) => {
let state = null;
switch (sgv.state) {
case 0x00:
state = 'None';
break;
case 0x01:
state = 'Stopped';
break;
case 0x02:
state = 'Warmup';
break;
case 0x03:
state = 'Unused';
break;
case 0x04:
state = 'First calibration';
break;
case 0x05:
state = 'Second calibration';
break;
case 0x06:
state = 'OK';
break;
case 0x07:
state = 'Need calibration';
break;
case 0x08:
state = 'Calibration Error 1';
break;
case 0x09:
state = 'Calibration Error 0';
break;
case 0x0a:
state = 'Calibration Linearity Fit Failure';
break;
case 0x0b:
state = 'Sensor Failed Due to Counts Aberration';
break;
case 0x0c:
state = 'Sensor Failed Due to Residual Aberration';
break;
case 0x0d:
state = 'Out of Calibration Due To Outlier';
break;
case 0x0e:
state = 'Outlier Calibration Request - Need a Calibration';
break;
case 0x0f:
state = 'Session Expired';
break;
case 0x10:
state = 'Session Failed Due To Unrecoverable Error';
break;
case 0x11:
state = 'Session Failed Due To Transmitter Error';
break;
case 0x12:
state = 'Temporary Session Failure - ???';
break;
case 0x13:
state = 'Reserved';
break;
case 0x15:
state = 'Sensor Failed';
break;
case 0x16:
state = 'Sensor Failed Start';
break;
case 0x80:
state = 'Calibration State - Start';
break;
case 0x81:
state = 'Calibration State - Start Up';
break;
case 0x82:
state = 'Calibration State - First of Two Calibrations Needed';
break;
case 0x83:
state = 'Calibration State - High Wedge Display With First BG';
break;
case 0x84:
state = 'Unused Calibration State - Low Wedge Display With First BG';
break;
case 0x85:
state = 'Calibration State - Second of Two Calibrations Needed';
break;
case 0x86:
state = 'Calibration State - In Calibration Transmitter';
break;
case 0x87:
state = 'Calibration State - In Calibration Display';
break;
case 0x88:
state = 'Calibration State - High Wedge Transmitter';
break;
case 0x89:
state = 'Calibration State - Low Wedge Transmitter';
break;
case 0x8a:
state = 'Calibration State - Linearity Fit Transmitter';
break;
case 0x8b:
state = 'Calibration State - Out of Cal Due to Outlier Transmitter';
break;
case 0x8c:
state = 'Calibration State - High Wedge Display';
break;
case 0x8d:
state = 'Calibration State - Low Wedge Display';
break;
case 0x8e:
state = 'Calibration State - Linearity Fit Display';
break;
case 0x8f:
state = 'Calibration State - Session Not in Progress';
break;
default:
state = sgv.state ? `Unknown: 0x${sgv.state.toString(16)}` : '--';
}
return state;
};
const stateStringShort = (sgv) => {
let state = null;
switch (sgv.state) {
case 0x00:
state = 'None';
break;
case 0x01:
state = 'Stopped';
break;
case 0x02:
state = 'Warmup';
break;
case 0x03:
state = 'Unused';
break;
case 0x04:
state = '1st Cal';
break;
case 0x05:
state = '2nd Cal';
break;
case 0x06:
state = 'OK';
break;
case 0x07:
state = 'Need Cal';
break;
case 0x08:
state = 'Cal Err 1';
break;
case 0x09:
state = 'Cal Err 0';
break;
case 0x0a:
state = 'Cal Lin Fit';
break;
case 0x0b:
state = 'Fail Counts';
break;
case 0x0c:
state = 'Fail Resid';
break;
case 0x0d:
state = 'Outlier';
break;
case 0x0e:
state = 'Cal NOW';
break;
case 0x0f:
state = 'Expired';
break;
case 0x10:
state = 'Unrecoverable';
break;
case 0x11:
state = 'Failed Tx';
break;
case 0x12:
state = 'Temp Fail';
break;
case 0x13:
state = 'Reserved';
break;
case 0x15:
state = 'Sensor Failed';
break;
case 0x16:
state = 'Failed Start';
break;
case 0x80:
state = 'Cal - Start';
break;
case 0x81:
state = 'Cal - Start Up';
break;
case 0x82:
state = '1 of 2 Cal';
break;
case 0x83:
state = 'Hi Wedge Display';
break;
case 0x84:
state = 'Unused Cal';
break;
case 0x85:
state = '2 of 2 Cal';
break;
case 0x86:
state = 'In Cal Tx';
break;
case 0x87:
state = 'In Cal Display';
break;
case 0x88:
state = 'Hi Wedge Tx';
break;
case 0x89:
state = 'Lo Wedge Tx';
break;
case 0x8a:
state = 'Lin Fit Tx';
break;
case 0x8b:
state = 'Outlier Cal Tx';
break;
case 0x8c:
state = 'Hi Wedge Display';
break;
case 0x8d:
state = 'Lo Wedge Display';
break;
case 0x8e:
state = 'Lin Fit Display';
break;
case 0x8f:
state = 'No Session';
break;
default:
state = sgv.state ? `Unknown: 0x${sgv.state.toString(16)}` : '--';
}
if (options.include_mode && sgv.inExtendedSession) {
state += '-ext';
} else if (options.include_mode && sgv.inExpiredSession) {
state += '-exp';
}
return state;
};
const processNewGlucose = async (newSgv, startingSession) => {
let glucoseHist = null;
let sendSGV = true;
let sgv = _.cloneDeep(newSgv);
let sensorInsert = await storage.getEvent('sensorInsert')
.catch((err) => {
error(`Error getting rig sensorInsert: ${err}`);
});
let sensorStart = await storage.getEvent('sensorStart')
.catch((err) => {
error(`Error getting rig sensorStart: ${err}`);
});
if (transmitterInSession(sgv)) {
const txmitterSessionStart = moment(sgv.sessionStartDate);
let updatedStart = false;
// If we don't have a sensor start, use the transmitter's session start
// Else, check if the sensor session start time reported by the transmitter is
// after the stored sensor start.
if (!sensorStart) {
sensorStart = {
date: txmitterSessionStart,
notes: 'Transmitter Reported Start Time',
};
updatedStart = true;
} else if (txmitterSessionStart.diff(sensorStart.date, 'hours') > 2) {
log(
'\n===================================='
+ '\nTransmitter session start date more than 2 hours after stored sensorStart'
+ `\nSetting stored sensorStart to ${txmitterSessionStart.format()}`
+ '\n====================================',
);
sensorStart = {
date: txmitterSessionStart,
notes: 'Transmitter Reported Start Time',
};
updatedStart = true;
}
if (updatedStart) {
storage.setEvent('sensorStart', sensorStart)
.catch((err) => {
error(`Error saving rig sensorStart: ${err}`);
});
}
}
if (sensorStart) {
debug(`SyncNS Rig sensor start - date: ${sensorStart.date.format()}`);
if (!sensorInsert || (sensorStart.date.valueOf() > sensorInsert.date.valueOf())) {
// allow the user to enter either to reset the session.
sensorInsert = sensorStart;
}
}
const sensorStop = await storage.getEvent('sensorStop')
.catch((err) => {
error(`Error getting rig sensorStop: ${err}`);
});
if (sensorStop) {
debug(`SyncNS Rig sensor stop - date: ${sensorStop.date.format()}`);
}
await storage.lock();
sgv.readDateMills = moment(sgv.readDate).valueOf();
const bgChecks = await storage.getArray('bgChecks')
.catch((err) => {
error(`Error getting bgChecks: ${err}`);
});
await checkSensorSession(sensorInsert.date, sensorStop.date, bgChecks, sgv);
glucoseHist = await storage.getArray('glucoseHist')
.catch((err) => {
error(`Error getting glucoseHist: ${err}`);
});
sgv = await calibration.calibrateGlucose(
storage, options, sensorInsert.date, sensorStop.date, glucoseHist, sgv,
);
if (sgv.inExtendedSession) {
sgv.mode = 'extended cal';
// set the sessionStartDate from the known start since transmitter
// no longer reports it
sgv.sessionStartDate = sensorStart.date.format();
} else if (sgv.inExpiredSession) {
sgv.mode = 'expired cal';
// set the sessionStartDate from the known start since transmitter
// no longer reports it
sgv.sessionStartDate = sensorStart.date.format();
} else {
sgv.mode = 'txmitter cal';
}
// Only override the state if expired calibration enabled
// Otherwise, the session would be immediately stopped if a BG Check is entered
if (sgv.state === 0x1 && options.expired_cal
&& (sgv.inExtendedSession || sgv.inExpiredSession)) {
if (moment().diff(sensorStart.date, 'days') <= 4 && bgChecks.length > 0 && moment().diff(moment(bgChecks[bgChecks.length - 1].dateMills), 'hours') > 12) {
// set session state to Need Calibration - cal every 12 hours for first 4 days
sgv.state = 0x7;
} else if (moment().diff(sensorStart.date, 'days') > 4 && bgChecks.length > 0 && moment().diff(moment(bgChecks[bgChecks.length - 1].dateMills), 'hours') > 24) {
// set session state to Need Calibration - cal every 24 hours after first 4 days
sgv.state = 0x7;
} else {
// set session state to OK
sgv.state = 0x6;
}
}
sgv.stateString = stateString(sgv);
sgv.stateStringShort = stateStringShort(sgv);
sgv.txStatusString = txStatusString(sgv.status);
sgv.txStatusStringShort = txStatusStringShort(sgv.status);
log(`sensor state: ${sgv.stateString}`);
if (glucoseHist.length > 0) {
const prevSgv = await getGlucose();
if ((!prevSgv || (sgv.state !== prevSgv.state)) && options.nightscout) {
xDripAPS.postAnnouncement(`Sensor: ${sgv.stateString}`);
} else if (startingSession && sgv.state !== 0x02) {
xDripAPS.postAnnouncement(`Unable to Start Session: ${sgv.stateString} should have been 'Warmup'`);
log('============================================='
+ '\nLookout sent start session command to transmitter; however,'
+ '\ntransmitter did not start the session. Possible causes:'
+ '\n * Attempting to back start session at a time prior to the transmitter start time'
+ '\n * Attempting to back start session at a time prior to the prior session stop time'
+ '\n * Attempting to back start session (sometimes it just does not work)'
+ '\n * Previous session not stopped'
+ '\n=============================================');
}
}
if (!sgv.glucose || sgv.glucose < 20) {
sgv.glucose = null;
log('No valid glucose to send.');
sendSGV = false;
}
await storeNewGlucose(glucoseHist, sgv)
.catch(() => {
error('Unable to store new glucose');
});
storage.unlock();
sendCGMStatus(sgv, bgChecks);
sendNewGlucose(sgv, sendSGV);
};
const processTxmitterCalData = async (calData) => {
let bgChecks = null;
let bgCheckIdx = -1;
const newCal = {
date: calData.date,
dateMills: moment(calData.date).valueOf(),
glucose: calData.glucose,
};
log(`Last calibration: ${Math.round((Date.now() - newCal.dateMills) / 1000 / 60 / 60 * 10) / 10} hours ago, ${newCal.glucose} mg/dL`);
if (newCal.glucose > 400 || newCal.glucose < 20) {
log('Txmitter Last Calibration Data glucose out of range - ignoring');
return;
}
const rigSGVs = await storage.getArray('glucoseHist')
.catch((err) => {
error(`Error getting rig SGVs: ${err}`);
});
if (rigSGVs.length < 1) {
// we really shouldn't have gotten to this
// state, but bail since we don't have any
// glucose history to work with
return;
}
const latestSGV = rigSGVs[rigSGVs.length - 1];
// check the sensor state
// don't use this cal message data
// if sensor state isn't OK or Need Calibration
// In stopped state and maybe other states,
// the last calibration data is not valid
if ((latestSGV.state !== 0x06) && (latestSGV.state !== 0x07)) {
return;
}
newCal.type = 'Txmitter';
await storage.lock();
bgChecks = await storage.getArray('bgChecks')
.catch((err) => {
error(`Error getting bgChecks: ${err}`);
});
// Look through the BG Checks we have to see if we already
// have this BG Check
for (let i = (bgChecks.length - 1); i >= 0; i -= 1) {
if (Math.abs(bgChecks[i].dateMills - newCal.dateMills) < 2 * 60 * 1000) {
// The CGM transmitter report varies the time around
// the real time a little between read events.
// If they are within two minutes, assume it's the same
// check and bail out.
if (bgChecks[i].unfiltered) {
// If it already has a unfiltered value
// we have already completed processing
// it.
storage.unlock();
return;
}
// break out of the loop, but try to find
// the unfiltered value
bgCheckIdx = i;
}
}
const sensorStart = await storage.getEvent('sensorStart')
.catch((err) => {
error(`Error getting rig sensorStart: ${err}`);
});
let sensorInsert = await storage.getEvent('sensorInsert')
.catch((err) => {
error(`Error getting rig sensorInsert: ${err}`);
});
if (sensorStart) {
if (!sensorInsert || (sensorStart.date.valueOf() > sensorInsert.date.valueOf())) {
// allow the user to enter either to reset the session.
sensorInsert = sensorStart;
}
}
const valueTime = moment(newCal.date);
if (sensorInsert && (sensorInsert.date.diff(valueTime) > 0)) {
// The calibration value pre-dates the NS sensorInsert record
// Bail out.
storage.unlock();
return;
}
const raw = await calibration.getUnfiltered(valueTime, rigSGVs);
if (raw) {
newCal.unfiltered = raw.unfiltered;
newCal.filtered = raw.filtered;
}
if (bgCheckIdx >= 0) {
// We already had this bgCheck but didn't have the unfiltered value
bgChecks[bgCheckIdx].unfiltered = newCal.unfiltered;
bgChecks[bgCheckIdx].filtered = newCal.filtered;
bgChecks[bgCheckIdx].type = newCal.type;
} else {
// This is a new bgCheck we didn't already have
bgChecks.push(newCal);
bgChecks = _.sortBy(bgChecks, ['dateMills']);
client.newCal(newCal);