forked from xdrip-js/Logger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxdrip-get-entries.sh
executable file
·2055 lines (1764 loc) · 67.5 KB
/
xdrip-get-entries.sh
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
#!/bin/bash
common_funcs="/root/src/Logger/bin/logger-common-funcs.sh"
if [ ! -e $common_funcs ]; then
echo "ERROR: Failed to run logger-common-funcs.sh. Is Logger correctly installed?"
exit 1
fi
source $common_funcs
SECONDS_IN_10_DAYS=864000
SECONDS_IN_1_DAY=86400
SECONDS_IN_7_DAYS=604800
SECONDS_IN_30_MINUTES=1800
CONF_DIR="${HOME}/myopenaps"
OLD_LDIR="${HOME}/myopenaps/monitor/logger"
treatmentsFile="${LDIR}/treatments-backfill.json"
lastEntryFile="${LDIR}/last-entry.json"
calibrationFile="${LDIR}/calibration-linear.json"
calCacheFile="${LDIR}/calibrations.csv"
xdripMessageFile="${LDIR}/xdrip-js-messages.json"
calibrationMessageFile="${LDIR}/calibration-xdrip-js-messages.json"
sentLoggerCalibrationToTx=false
CALFILE="${LDIR}/calibration.json"
main()
{
log "Starting Logger"
check_dirs
# Cmd line args - transmitter $1 is 6 character tx serial number
transmitter=$1
if [ -z "$transmitter" ]; then
# check config file
transmitter=$(cat ${CONF_DIR}/xdripjs.json | jq -M -r '.transmitter_id')
fi
if [ -z "$transmitter" ] || [ "$transmitter" == "null" ]; then
log "ERROR: No transmitter id set!; exiting"
exit
fi
txType="g5"
if [[ $transmitter == 8* ]]; then
txType="g6"
fi
cmd_line_mode=$2
if [ -z "$cmd_line_mode" ]; then
# check config file
cmd_line_mode=$(cat ${CONF_DIR}/xdripjs.json | jq -M -r '.mode')
if [ -z "$cmd_line_mode" ] || [ "$cmd_line_mode" == "null" ]; then
cmd_line_mode=""
fi
fi
pumpUnits=$3
if [ -z "$pumpUnits" ]; then
# check config file
pumpUnits=$(cat ${CONF_DIR}/xdripjs.json | jq -M -r '.pump_units')
if [ -z "$pumpUnits" ] || [ "$pumpUnits" == "null" ]; then
pumpUnits="mg/dl"
fi
fi
meterid=$4
if [ -z "$meterid" ]; then
# check config file
meterid=$(cat ${CONF_DIR}/xdripjs.json | jq -M -r '.fake_meter_id')
if [ -z "$meterid" ] || [ "$meterid" == "null" ]; then
meterid="000000"
fi
fi
# check config file
sensorCode=$(cat ${CONF_DIR}/xdripjs.json | jq -M -r '.sensor_code')
if [ -z "$sensorCode" ] || [ "$sensorCode" == "null" ]; then
sensorCode=""
fi
watchdog=$(cat ${CONF_DIR}/xdripjs.json | jq -M -r '.watchdog')
if [ -z "$watchdog" ] || [ "$watchdog" == "null" ]; then
watchdog=true
fi
log "Parameter (watchdog): $watchdog"
utc=$(cat ${CONF_DIR}/xdripjs.json | jq -M -r '.utc')
if [ -z "$utc" ] || [ "$utc" == "null" ]; then
utc=true
fi
log "Parameter (utc): $utc"
auto_sensor_restart=$(cat ${CONF_DIR}/xdripjs.json | jq -M -r '.auto_sensor_restart')
if [ -z "$auto_sensor_restart" ] || [ "$auto_sensor_restart" == "null" ]; then
auto_sensor_restart=false
fi
log "Parameter (auto_sensor_restart): $auto_sensor_restart"
fakemeter_only_offline=$(cat ${CONF_DIR}/xdripjs.json | jq -M -r '.fakemeter_only_offline')
if [ -z "$fakemeter_only_offline" ] || [ "$fakemeter_only_offline" == "null" ]; then
fakemeter_only_offline=false
fi
log "Parameter (fakemeter_only_offline): $fakemeter_only_offline"
alternateBluetoothChannel=$(cat ${CONF_DIR}/xdripjs.json | jq -M -r '.alternate_bluetooth_channel')
if [ -z "$alternateBluetoothChannel" ] || [ "$alternateBluetoothChannel" == "null" ]; then
alternateBluetoothChannel=false
fi
log "Parameter (alternateBluetoothChannel): $alternateBluetoothChannel"
log "Parameter (transmitter): $transmitter"
id2=$(echo "${transmitter: -2}")
id="Dexcom${id2}"
rig="openaps://$(hostname)"
glucoseType="unfiltered"
noiseSend=4 # default heavy
UTCString=" -u "
lastGlucose=0
lastGlucoseDate=0
lastSensorInsertDate=0
variation=0
messages=""
ns_url="${NIGHTSCOUT_HOST}"
METERBG_NS_RAW="${LDIR}/meterbg_ns_raw.json"
battery_check="No" # default - however it will be changed to Yes every 12 hours
sensitivty=0
epochdate=$(date +'%s')
epochdatems=$(date +'%s%3N')
dateString=$(date -u +"%Y-%m-%dT%H:%M:%S.%3NZ")
getTxVersion # reads the json file that stores the latest known tx firmware version
initialize_mode # call now and after getting status from tx
initialize_messages
check_environment
check_utc
check_last_entry_values
check_last_glucose_time_smart_sleep
# clear out prior curl or tx responses
rm -f $METERBG_NS_RAW
rm -f ${LDIR}/entry.json
check_sensor_change
check_sensitivity
check_send_battery_status
check_sensor_start
check_sensor_stop
# begin calibration logic - look for calibration from NS, use existing calibration or none
maxDelta=30
found_meterbg=false
check_cmd_line_calibration
check_pump_history_calibration
check_ns_calibration
check_messages
remove_dexcom_bt_pair
compile_messages
call_logger
epochdate=$(date +'%s')
epochdatems=$(date +'%s%3N')
dateString=$(date -u +"%Y-%m-%dT%H:%M:%S.%3NZ")
capture_entry_values
checkif_fallback_mode
log "Mode = $mode"
if [[ "$mode" != "expired" ]]; then
initialize_calibrate_bg
else
check_last_calibration
fi
set_entry_fields
check_variation
check_native_calibrates_lsr
check_tx_calibration
#call after posting to NS OpenAPS for not-expired mode
if [ "$mode" == "expired" ]; then
calculate_calibrations
fi
check_recent_sensor_insert
readLastState
if [ "$mode" == "expired" ]; then
apply_lsr_calibration
fi
# necessary for not-expired mode - ok for both modes
cp -p ${LDIR}/entry.json ${LDIR}/entry-xdrip.json
process_delta # call for all modes
calculate_noise # necessary for all modes
process_if_lsr_calibrates_native
fake_meter
if [ "$state" != "Stopped" ] || [ "$mode" == "expired" ]; then
log "Posting glucose record to xdripAPS / OpenAPS"
if [ -e "${LDIR}/entry-backfill2.json" ] ; then
local numBackfills=$(jq '. | length' ${LDIR}/entry-backfill2.json)
if [ $(bc <<< "$numBackfills > 6") -eq 1 ]; then
# more than 30 minutes of missed/backfilled glucose values
postAnnouncementToNSAdder="Backfilled $numBackfills glucose values"
fi
/usr/local/bin/cgm-post-xdrip ${LDIR}/entry-backfill2.json
fi
/usr/local/bin/cgm-post-xdrip ${LDIR}/entry-xdrip.json
fi
post-nightscout-with-backfill
cp -p ${LDIR}/entry-xdrip.json $lastEntryFile
if [ "$mode" != "expired" ]; then
log "Calling expired tx lsr calcs (after posting) -allows mode switches / comparisons"
calculate_calibrations
apply_lsr_calibration
fi
check_battery_status
log_cgm_csv
process_announcements
post_cgm_ns_pill
saveLastState
remove_dexcom_bt_pair
log "Completed Logger"
echo
}
function validNumber()
{
local num=$1
case ${num#[-+]} in
*[!0-9.]* | '') echo false ;;
* ) echo true ;;
esac
}
function validBG()
{
local bg=$1
local valid="false"
if [ "$(validNumber $bg)" == "true" ]; then
if [ $(bc -l <<< "$bg >= 20") -eq 1 -a $(bc -l <<< "$bg < 500") -eq 1 ]; then
valid="true"
fi
fi
echo $valid
}
function check_dirs() {
if [ ! -d ${LDIR} ]; then
if [ -d ${OLD_LDIR} ]; then
mv ${OLD_LDIR} ${LDIR}
fi
fi
mkdir -p ${LDIR}
mkdir -p ${LDIR}/old-calibrations
}
# This func takes an arg list of value name pairs creating a simple json string
# What's different about this vs jq is that this function will ignore
# any value/name pair where the variable value name is null or blank
# it also automatically handles quotes around variable values with strings
# and doesn't include quotes for those without strings
function build_json() {
local __result="{"
args=("$@")
for (( i=0; i < ${#}; i+=2 ))
do
local __key=${args[$i]}
local __value=${args[$i+1]}
#echo "key=$__key, value=$__value"
local __len=${#__value}
if [ $__len -gt 0 ]; then
if [ $(echo "$__value" | grep -cE "^\-?([0-9]+)(\.[0-9]+)?$") -gt 0 ]; then
# must be a number
__result="$__result\"$__key\":$__value,"
else
# must be a string
__result="$__result\"$__key\":\"$__value\","
fi
fi
done
# remove comma on last value/name pair
__result="${__result::-1}}"
echo $__result
}
function readLastState
{
lastState=$(cat ${LDIR}/Logger-last-state.json | jq -M '.[0].state')
lastState="${lastState%\"}"
lastState="${lastState#\"}"
log "readLastState: lastState=$lastState"
}
function saveLastState
{
log "saveLastState, state=$state"
echo "[{\"state\":\"${state}\",\"txId\":\"${transmitter}\"}]" > ${LDIR}/Logger-last-state.json
}
function log
{
echo -e "$(date +'%m/%d %H:%M:%S') $*"
}
function fake_meter()
{
if [[ "$fakemeter_only_offline" == true && !$(~/src/Logger/bin/logger-online.sh) ]]; then
log "Not running fakemeter because fakemeter_only_offline=true and not offline"
return
fi
if [ -e "/usr/local/bin/fakemeter" ]; then
if [ -d ~/myopenaps/plugins/once ]; then
scriptf=~/myopenaps/plugins/once/run_fakemeter.sh
log "Scheduling fakemeter run once at end of next OpenAPS loop to send BG of $calibratedBG to pump via meterid $meterid"
echo "#!/bin/bash" > $scriptf
echo "fakemeter -m $meterid $calibratedBG" >> $scriptf
chmod +x $scriptf
else
if ! listen -t 4s >& /dev/null ; then
log "Sending BG of $calibratedBG to pump via meterid $meterid"
fakemeter -m $meterid $calibratedBG
else
log "Timed out trying to send BG of $calibratedBG to pump via meterid $meterid"
fi
fi
fi
}
# Check required environment variables
function check_environment
{
source ~/.bash_profile
cd ~/src/Logger
export API_SECRET
export NIGHTSCOUT_HOST
if [ "$API_SECRET" = "" ]; then
log "API_SECRET environment variable is not set"
log "Make sure the two lines below are in your ~/.bash_profile as follows:\n"
log "API_SECRET=xxxxxxxxxxxxxxxxxxxxxxxxxx # where xxxx is your hashed NS API_SECRET"
log "export API_SECRET\n\nexiting\n"
state_id=0x21
state="API_SECRET Not Set" ; stateString=$state ; stateStringShort=$state
post_cgm_ns_pill
exit
fi
if [ "$NIGHTSCOUT_HOST" = "" ]; then
log "NIGHTSCOUT_HOST environment variable is not set"
log "Make sure the two lines below are in your ~/.bash_profile as follows:\n"
log "NIGHTSCOUT_HOST=https://xxxx # where xxxx is your hashed Nightscout url"
log "export NIGHTSCOUT_HOST\n\nexiting\n"
state_id=0x22
state="NIGHTSCOUT_HOST Not Set" ; stateString=$state ; stateStringShort=$state
post_cgm_ns_pill
exit
fi
type bt-device 2> /dev/null || log "Error: bt-device is not found. Use sudo apt-get install bluez-tools"
}
function ClearCalibrationInput()
{
if [ -e $calCacheFile ]; then
cp $calCacheFile "${LDIR}/old-calibrations/calibrations.csv.$(date +%Y%m%d-%H%M%S)"
rm $calCacheFile
fi
}
# we need to save the last calibration for meterbgid checks, throw out the rest
function ClearCalibrationInputOne()
{
if [ -e $calCacheFile ]; then
howManyLines=$(wc -l $calCacheFile | awk '{print $1}')
if [ $(bc <<< "$howManyLines > 1") -eq 1 ]; then
cp $calCacheFile "${LDIR}/old-calibrations/calibrations.csv.$(date +%Y%m%d-%H%M%S)"
tail -1 $calCacheFile > ${LDIR}/calibrations.csv.new
rm $calCacheFile
mv ${LDIR}/calibrations.csv.new $calCacheFile
fi
fi
}
function ClearCalibrationCache()
{
if [ -e $calibrationFile ]; then
cp $calibrationFile "${LDIR}/old-calibrations/calibration-linear.$(date +%Y%m%d-%H%M%S)"
rm $calibrationFile
fi
}
# check utc command line to begin with and use UTC flag for any curls
function check_utc()
{
if [[ "$utc" == true ]]; then
UTCString=" -u "
log "Using UTCString $UTCString"
else
UTC=""
log "Not Using UTCString"
fi
}
function log_status_csv()
{
file="/var/log/openaps/cgm-status.csv"
if [ ! -f $file ]; then
echo "epochdate,datetime,status,voltagea,voltageb,resist,runtime,temperature" > $file
fi
echo "${epochdate},${datetime},${tx_status},${voltagea},${voltageb},${resist},${runtime} days,${temperature} celcuis" >> $file
}
#called after a battery status update was sent and logger got a response
function check_battery_status()
{
file="${LDIR}/cgm-battery.json"
voltagea=$(jq ".voltagea" $file)
voltageb=$(jq ".voltageb" $file)
resist=$(jq ".resist" $file)
runtime=$(jq ".runtime" $file)
temperature=$(jq ".temperature" $file)
batteryTimestamp=$(date +%s%3N -r $file)
if [ "$battery_check" == "Yes" ]; then
tx_status=$(jq ".status" $file)
battery_msg="tx_status=$tx_status, voltagea=$voltagea, voltageb=$voltageb, resist=$resist, runtime=$runtime days, temp=$temperature celcius"
echo "[{\"enteredBy\":\"Logger\",\"eventType\":\"Note\",\"notes\":\"Battery $battery_msg\"}]" > ${LDIR}/cgm-battery-status.json
/usr/local/bin/cgm-post-ns ${LDIR}/cgm-battery-status.json treatments && (echo; log "Upload to NightScout of battery status change worked") || (echo; log "Upload to NS of battery status change did not work")
log_status_csv
fi
}
function check_send_battery_status()
{
file="${LDIR}/cgm-battery.json"
if [ -e $file ]; then
if test `find $file -mmin +720`
then
battery_check="Yes"
fi
else
touch $file
battery_check="Yes"
fi
if [ "$battery_check" == "Yes" ]; then
touch $file
battery_date=$(date +'%s%3N')
batteryJSON="[{\"date\": ${battery_date}, \"type\": \"BatteryStatus\"}]"
versionJSON="[{\"date\": ${battery_date}, \"type\": \"VersionRequest\"}]"
log "Sending Message to Transmitter to request battery and version status"
fi
}
function check_sensor_stop()
{
if [ "$mode" == "read-only" ]; then
return
fi
file="${LDIR}/nightscout_sensor_stop_treatment.json"
rm -f $file
curl --compressed -m 30 -H "API-SECRET: ${API_SECRET}" "${NIGHTSCOUT_HOST}/api/v1/treatments.json?find\[created_at\]\[\$gte\]=$(date -d "3 hours ago" --iso-8601=seconds $UTCString )&find\[eventType\]\[\$regex\]=Sensor.Stop&count=1" 2>/dev/null > $file
if [ $? == 0 ]; then
len=$(jq '. | length' $file)
index=$(bc <<< "$len - 1")
if [ $(bc <<< "$index >= 0") -eq 1 ]; then
createdAt=$(jq ".[$index].created_at" $file)
createdAt="${createdAt%\"}"
createdAt="${createdAt#\"}"
if [ ${#createdAt} -ge 8 ]; then
touch ${LDIR}/nightscout-treatments.log
if ! cat ${LDIR}/nightscout-treatments.log | egrep "$createdAt"; then
stop_date=$(date "+%s%3N" -d "$createdAt")
log "Processing sensor stop retrieved from Nightscout - stopdate = $createdAt"
# comment out below line for testing sensor stop without actually sending tx message
stopJSON="[{\"date\":\"${stop_date}\",\"type\":\"StopSensor\"}]"
log "stopJSON = $stopJSON"
# below done so that next time the egrep returns positive for this specific message and the log reads right
echo "Already Processed Sensor Stop Message from Nightscout at $createdAt" >> ${LDIR}/nightscout-treatments.log
# Always clear LSR cache for any new firmware g6 start / stop
if [ "$(newFirmware $tx_version)" == "true" ]; then
ClearCalibrationInput
ClearCalibrationCache
fi
fi
fi
fi
fi
}
function check_sensor_start()
{
if [ "$mode" == "read-only" ]; then
return
fi
file="${LDIR}/nightscout_sensor_start_treatment.json"
rm -f $file
curl --compressed -m 30 -H "API-SECRET: ${API_SECRET}" "${NIGHTSCOUT_HOST}/api/v1/treatments.json?find\[created_at\]\[\$gte\]=$(date -d "3 hours ago" --iso-8601=seconds $UTCString )&find\[eventType\]\[\$regex\]=Sensor.Start&count=1" 2>/dev/null > $file
if [ $? == 0 ]; then
len=$(jq '. | length' $file)
index=$(bc <<< "$len - 1")
if [ $(bc <<< "$index >= 0") -eq 1 ]; then
createdAt=$(jq ".[$index].created_at" $file)
createdAt="${createdAt%\"}"
createdAt="${createdAt#\"}"
if [ ${#createdAt} -ge 8 ]; then
touch ${LDIR}/nightscout-treatments.log
if ! cat ${LDIR}/nightscout-treatments.log | egrep "$createdAt"; then
sensorSerialCode=$(jq ".[$index].notes" $file)
sensorSerialCode="${sensorSerialCode%\"}"
sensorSerialCode="${sensorSerialCode#\"}"
start_date=$(date "+%s%3N" -d "$createdAt")
log "Processing sensor start retrieved from Nightscout - startdate = $createdAt, sensorCode = $sensorSerialCode"
# comment out below line for testing sensor start without actually sending tx message
# always send sensorSerialCode even if it is blank - doesn't matter for g5, but needed
# for g6
startJSON="[{\"date\":\"${start_date}\",\"type\":\"StartSensor\",\"sensorSerialCode\":\"${sensorSerialCode}\"}]"
log "startJSON = $startJSON"
# below done so that next time the egrep returns positive for this specific message and the log reads right
echo "Already Processed Sensor Start Message from Nightscout at $createdAt" >> ${LDIR}/nightscout-treatments.log
# Always clear LSR cache for any new firmware g6 start / stop
if [ "$(newFirmware $tx_version)" == "true" ]; then
log "clearing calibration due to Sensor Start and tx version $tx_version"
ClearCalibrationInput
ClearCalibrationCache
else
log "Not clearing calibration due to Sensor Start, tx version $tx_version"
fi
#update xdripjs.json with new sensor code
if [ "$sensorSerialCode" != "null" -a "$sensorSerialCode" != "" ]; then
config="/root/myopenaps/xdripjs.json"
if [ -e "$config" ]; then
tmp=$(mktemp)
jq --arg sensorSerialCode "$sensorSerialCode" '.sensor_code = $sensorSerialCode' "$config" > "$tmp" && mv "$tmp" "$config"
fi
fi
fi
fi
fi
fi
}
# remove old calibration storage when sensor change occurs
# calibrate after 15 minutes of sensor change time entered in NS
function check_sensor_change()
{
if [ "$mode" == "read-only" ]; then
return
fi
curl --compressed -m 30 -H "API-SECRET: ${API_SECRET}" "${NIGHTSCOUT_HOST}/api/v1/treatments.json?find\[created_at\]\[\$gte\]=$(date -d "15 minutes ago" --iso-8601=seconds $UTCString )&find\[eventType\]\[\$regex\]=Sensor.Change" 2>/dev/null | grep "Sensor Change"
if [ $? == 0 ]; then
log "sensor change within last 15 minutes - clearing calibration files"
ClearCalibrationInput
ClearCalibrationCache
touch ${LDIR}/last_sensor_change
state_id=0x02
state="Paused" ; stateString=$state ; stateStringShort=$state
post_cgm_ns_pill
log "exiting"
exit
fi
curl --compressed -m 30 -H "API-SECRET: ${API_SECRET}" "${NIGHTSCOUT_HOST}/api/v1/treatments.json?find\[created_at\]\[\$gte\]=$(date -d "15 minutes ago" --iso-8601=seconds $UTCString)&find\[eventType\]\[\$regex\]=Sensor.Stop" 2>/dev/null | grep "Sensor Stop"
if [ $? == 0 ]; then
log "sensor stopped within last 15 minutes - clearing calibration files"
ClearCalibrationInput
ClearCalibrationCache
touch ${LDIR}/last_sensor_change
state_id=0x02
state="Paused" ; stateString=$state ; stateStringShort=$state
post_cgm_ns_pill
log "exiting"
exit
fi
curl --compressed -m 30 -H "API-SECRET: ${API_SECRET}" "${NIGHTSCOUT_HOST}/api/v1/treatments.json?find\[created_at\]\[\$gte\]=$(date -d "15 minutes ago" --iso-8601=seconds $UTCString)&find\[eventType\]\[\$regex\]=Sensor.Start" 2>/dev/null | grep "Sensor Start"
if [ $? == 0 ]; then
log "sensor start within last 15 minutes - clearing calibration files"
ClearCalibrationInput
ClearCalibrationCache
touch ${LDIR}/last_sensor_change
state_id=0x02
state="Starting" ; stateString=$state ; stateStringShort=$state
post_cgm_ns_pill
log "exiting"
exit
fi
}
function check_last_entry_values()
{
# RESOLVED: check file stamp for > x for last-entry.json and ignore lastGlucose if older than x minutes
# if within last 11 minutes
if test `find $lastEntryFile -mmin -11`
then
if [ -e "$lastEntryFile" ] ; then
lastGlucose=$(cat $lastEntryFile | jq -M '.[0].sgv')
lastGlucoseDate=$(cat $lastEntryFile | jq -M '.[0].date')
lastStatus=$(cat $lastEntryFile | jq -M '.[0].status')
lastStatus="${lastStatus%\"}"
lastStatus="${lastStatus#\"}"
lastFiltered=$(cat $lastEntryFile | jq -M '.[0].filtered')
lastUnfiltered=$(cat $lastEntryFile | jq -M '.[0].unfiltered')
if [ "$mode" != "expired" ]; then
lastState=$(cat $lastEntryFile | jq -M '.[0].state')
lastState="${lastState%\"}"
lastState="${lastState#\"}"
fi
log "check_last_entry_values: lastGlucose=$lastGlucose, lastStatus=$lastStatus, lastState=$lastState"
fi
fi
}
function updateCalibrationCache()
{
local filtered=$1
local unfiltered=$2
local meterbg=$3
local meterbgid=$4
local datetime=$5 # string form of date/time
local epochdate=$6 # epoch date in seconds
local enteredBy=$7
log "updateCalibrationCache, filtered=$filtered, unfiltered=$unfiltered, meterbg=$meterbg"
log " meterbgid=$meterbgid, datetime=$datetime"
log " epochdate=$epochdate, enteredBy=$enteredBy"
local variation=0
local after=$epochdate
local before=$epochdate
local f=$calCacheFile
if [ $(bc <<< "$after > 1") -eq 1 ]; then
after=$(($epochdate+1))
fi
if [ $(bc <<< "$before > 1") -eq 1 ]; then
before=$(($epochdate-1))
fi
# grep txepochdate in to see if this tx calibration is known yet or not
# The tx reports a time in ms that shifts each and every time, so to be sure
# to not have duplicates, grep for the second before and second after
if cat $f | egrep "$epochdate" || cat $f | egrep "$after" || cat $f | egrep "$before"; then
log "Already processed calibration of $meterbg with id = $epochdate"
return
fi
if cat $f | egrep "$meterbgid"; then
log "Already processed calibration of $meterbg with id = $meterbgid"
return
fi
if [ "$(validBG $unfiltered)" == "false" ]; then
log "Calibration of $meterbg not being used due to unfiltered of $unfiltered"
return
fi
# safety check to make sure we don't have wide variance between the meterbg and the unfiltered value
# Use 1 as slope for safety in this check
meterbg_delta=$(bc -l <<< "$meterbg - $unfiltered/1")
# calculate absolute value
if [ $(bc -l <<< "$meterbg_delta < 0") -eq 1 ]; then
meterbg_delta=$(bc -l <<< "0 - $meterbg_delta")
fi
if [ $(bc -l <<< "$meterbg_delta > 150") -eq 1 ]; then
log "Raw/unfiltered compared to meterbg is $meterbg_delta > 150, ignoring calibration"
return
fi
variation=$(calc_variation $filtered $unfiltered)
if [ $(bc <<< "$variation > 10") -eq 1 ]; then
log "would not allow calibration - filtered/unfiltered variation of $variation exceeds 10%"
return
fi
log "Calibration is new and within bounds - adding to calibrations.csv"
log "meterbg=$meterbg,datetime=$datetime,epochdate=$epochdate,meterbgid=$meterbgid,filtered=$filtered,unfiltered=$unfiltered"
echo "$unfiltered,$meterbg,$datetime,$epochdate,$meterbgid,$filtered,$unfiltered,$enteredBy" >> $calCacheFile
/usr/local/bin/cgm-calc-calibration $calCacheFile $calibrationFile
}
function seen_before()
{
# pass unique id as arg1 and it will return "No" if not seen before
# Optional arg2 that is the application usage for unique id check
# or "Yes" if it is the first and only time this id has been seen
# Remembers up to 200 last unique id
bg=${1:-"null"} # arg 1 is meter bg value
local uid=$1
local app=${2:-"Logger"}
local processed_before="No"
local f="${LDIR}/already_processed.txt"
local t=$(mktemp)
if [ -e $f ]; then
if cat $f | egrep "$uid"; then
processed_before="Yes"
fi
else
touch $f
fi
if [[ "$processed_before" == "No" ]]; then
echo "$datetime, seen at least once, $uid, $app" >> $f
fi
echo $processed_before
# keep only last 200 seen unique ids
cp $f $t
tail -200 $t > $f
}
function check_tx_calibration()
{
if [ "$mode" == "read-only" ]; then
return
fi
# TODO: remove - it is likely not necessary anymore
if [[ "$sentLoggerCalibrationToTx" == true ]]; then
# This is the reflection of the cmd line based calibration.
# Do not process it twice
return
fi
TXCALFILE="${LDIR}/tx-calibration-data.json"
if [ -e $TXCALFILE ]; then
txdatetime=$(jq ".date" $TXCALFILE)
txdatetime="${txdatetime%\"}"
txdatetime="${txdatetime#\"}"
txmeterbg=$(jq ".glucose" $TXCALFILE)
txepochdate=`date --date="$txdatetime" +"%s"`
txmeterbgid=$txepochdate
# calibrations.csv "unfiltered,meterbg,datetime,epochdate,meterbgid,filtered,unfiltered"
seen=$(seen_before $txepochdate "Calibration from Tx")
if [[ "$seen_before" == "No" ]]; then
log "Tx last calibration of $txmeterbg being considered - id = $txmeterbgid, txdatetime= $txdatetime"
else
log "Tx last calibration of $txmeterbg seen before, already processed - id = $txmeterbgid, txdatetime= $txdatetime"
return
fi
epochdateNow=$(date +'%s')
if [ $(bc <<< "($epochdateNow - $txepochdate) < 420") -eq 1 ]; then
log "tx meterbg is within 7 minutes so use current filtered/unfiltered values "
txfiltered=$filtered
txunfiltered=$unfiltered
else
log "tx meterbg is older than 7 minutes so queryfiltered/unfiltered values"
# after=$(date -d "15 minutes ago" -Iminutes)
# glucosejqstr="'[ .[] | select(.dateString > \"$after\") ]'"
before=$(bc -l <<< "$txepochdate *1000 + 240*1000")
after=$(bc -l <<< "$txepochdate *1000 - 240*1000")
glucosejqstr="'[ .[] | select(.date > $after) | select(.date < $before) ]'"
bash -c "jq -c $glucosejqstr ~/myopenaps/monitor/glucose.json" > ${LDIR}/test.json
txunfiltered=( $(jq -r ".[0].unfiltered" ${LDIR}/test.json) )
txfiltered=( $(jq -r ".[0].filtered" ${LDIR}/test.json) )
fi
updateCalibrationCache $txfiltered $txunfiltered $txmeterbg $txmeterbgid "$txdatetime" $txepochdate "Logger-tx"
# use enteredBy Logger so that
# it can be filtered and not reprocessed by Logger again
readyCalibrationToNS $txdatetime $txmeterbg "Logger-tx"
postTreatmentsToNS
rm -f $TXCALFILE
fi
}
function addToMessages()
{
local jsonToAdd=$1
local resultJSON=""
local msgFile=$2
log "addToMessages jsonToAdd=$jsonToAdd"
jqType=$(jq type <<< "$jsonToAdd")
if [[ "$jqType" != *"array"* ]]; then
log "jsonToAdd is not valid = $jsonToAdd"
return
fi
local lengthJSON=${#jsonToAdd}
if [ $(bc <<< "$lengthJSON < 2") -eq 1 ]; then
log "jsonToAdd is not valid too short = $jsonToAdd"
return
fi
if [ -e $msgFile ]; then
local stagingFile1=$(mktemp)
local stagingFile2=$(mktemp)
echo "$jsonToAdd" > $stagingFile1
cp $msgFile $stagingFile2
log "stagingFile2 is below"
cat $stagingFile2
log "stagingFile1 is below"
cat $stagingFile1
resultJSON=$(jq -c -s add $stagingFile2 $stagingFile1)
else
resultJSON=$jsonToAdd
fi
jqType=$(jq type <<< "$resultJSON")
if [[ "$jqType" != *"array"* ]]; then
log "resultJSON is not valid = $resultJSON"
return
fi
log "resultJSON=$resultJSON"
echo "$resultJSON" > $msgFile
}
# TODO: make one of these for start/stop treatments
function readyCalibrationToNS()
{
# takes a calibration record and puts it in json file for later sending it to NS
local createDate="$1"
local meterbg=$2
local enteredBy="$3"
# arg1 = createDate in string format T ... Z
# arg2 = meterbg
# arg3 = enteredBy
calibrationNSFile=$(mktemp)
stagingFile=$(mktemp)
log "Setting up to send calibration to NS now if online (or later with backfill)"
echo "[{\"created_at\":\"$createDate\",\"enteredBy\":\"$enteredBy\",\"reason\":\"sensor calibration\",\"eventType\":\"BG Check\",\"glucose\":$meterbg,\"glucoseType\":\"Finger\",\"units\":\"mg/dl\"}]" > $calibrationNSFile
cat $calibrationNSFile
if [ -e $treatmentsFile ]; then
cp $treatmentsFile $stagingFile
jq -s add $calibrationNSFile $stagingFile > $treatmentsFile
else
cp $calibrationNSFile $treatmentsFile
fi
}
function generate_uuid()
{
cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1
}
function check_cmd_line_calibration()
{
if [ "$mode" == "read-only" ]; then
return
fi
## look for a bg check from ${LDIR}/calibration.json
if [ -e $CALFILE ]; then
epochdatems=$(date +'%s%3N')
if test `find $CALFILE -mmin -7`
then
log "calibration file $CALFILE contents below"
cat $CALFILE
echo
cJSON=$(cat $CALFILE)
addToMessages "$cJSON" $calibrationMessageFile
calDateA=( $(jq -r ".[].date" ${CALFILE}) )
meterbgA=( $(jq -r ".[].glucose" ${CALFILE}) )
calRecords=${#meterbgA[@]}
log "Calibration records from command line=$calRecords"
# Leverage tx reflection here. The first calibration is the latest one
# based on how the command line utility does it
# so process the records in reverse order
# Consider in the future: use lastFiltered and lastUnfiltered
# values if they exist, otherwise
# do LSR here and set variable so that
# reflective Tx calibration doesn't duplicate
for (( i=$calRecords-1; i>=0; i-- ))
do
calDate=${calDateA[$i]}
# check the date inside to make sure we don't calibrate using old record
if [ $(bc <<< "($epochdatems - $calDate)/1000 < 820") -eq 1 ]; then
calDateSeconds=$(bc <<< "($calDate / 1000)") # truncate
meterbg=${meterbgA[$i]}
meterbgid=$(generate_uuid)
log "Calibration of $meterbg from $CALFILE being processed - id = $meterbgid"
found_meterbg=true
# put in backfill so that the command line calibration will be sent up to NS
# now (or later if offline)
createdAt=$(date $UTCString -d @$calDateSeconds +'%Y-%m-%dT%H:%M:%S.%3NZ')
if [ $(bc <<< "$lastUnfiltered > 0") -eq 1 ]; then
updateCalibrationCache $lastFiltered $lastUnfiltered $meterbg $meterbgid "$createdAt" $calDateSeconds "Logger-cmd-line"
sentLoggerCalibrationToTx=true
fi
readyCalibrationToNS $createdAt $meterbg "Logger-cmd-line"
postTreatmentsToNS
else
log "Calibration is too old - not used"
fi
done
fi
rm -f $CALFILE
log "meterbg from ${LDIR}/calibration.json: $meterbg"
fi
}
function remove_dexcom_bt_pair()
{
log "Removing existing Dexcom bluetooth connection = ${id}"
bt-device -r $id 2> /dev/null
# Also remove the mac address tx pairing if exists
sfile="${LDIR}/saw-transmitter.json"
if [ -e $sfile ]; then
mac=$(cat $sfile | jq -M '.address')
mac="${mac%\"}"
mac="${mac#\"}"
if [ ${#mac} -ge 8 ]; then
smac=${mac//:/-}
smac=${smac^^}
#echo $smac
log "Removing existing Dexcom bluetooth mac connection also = ${smac}"
bt-device -r $smac 2> /dev/null
fi
fi
}
function initialize_messages()
{
stopJSON=""
startJSON=""
batteryJSON=""
resetJSON=""
versionJSON=""
}
function compile_messages()
{
if [ "${resetJSON}" != "" ]; then
addToMessages "$resetJSON" $xdripMessageFile
fi