/
Ob1G5CollectionService.java
2039 lines (1771 loc) · 87.3 KB
/
Ob1G5CollectionService.java
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
package com.eveningoutpost.dexdrip.Services;
import android.annotation.TargetApi;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import com.eveningoutpost.dexdrip.AddCalibration;
import com.eveningoutpost.dexdrip.DoubleCalibrationActivity;
import com.eveningoutpost.dexdrip.G5Model.BatteryInfoRxMessage;
import com.eveningoutpost.dexdrip.G5Model.BluetoothServices;
import com.eveningoutpost.dexdrip.G5Model.CalibrationState;
import com.eveningoutpost.dexdrip.G5Model.DexSyncKeeper;
import com.eveningoutpost.dexdrip.G5Model.DexTimeKeeper;
import com.eveningoutpost.dexdrip.G5Model.FirmwareCapability;
import com.eveningoutpost.dexdrip.G5Model.Ob1G5StateMachine;
import com.eveningoutpost.dexdrip.G5Model.TransmitterStatus;
import com.eveningoutpost.dexdrip.G5Model.VersionRequest1RxMessage;
import com.eveningoutpost.dexdrip.G5Model.VersionRequest2RxMessage;
import com.eveningoutpost.dexdrip.G5Model.VersionRequestRxMessage;
import com.eveningoutpost.dexdrip.Home;
import com.eveningoutpost.dexdrip.Models.BgReading;
import com.eveningoutpost.dexdrip.Models.JoH;
import com.eveningoutpost.dexdrip.Models.Sensor;
import com.eveningoutpost.dexdrip.Models.UserError;
import com.eveningoutpost.dexdrip.R;
import com.eveningoutpost.dexdrip.UtilityModels.BroadcastGlucose;
import com.eveningoutpost.dexdrip.UtilityModels.CollectionServiceStarter;
import com.eveningoutpost.dexdrip.UtilityModels.Constants;
import com.eveningoutpost.dexdrip.UtilityModels.Inevitable;
import com.eveningoutpost.dexdrip.UtilityModels.PersistentStore;
import com.eveningoutpost.dexdrip.UtilityModels.Pref;
import com.eveningoutpost.dexdrip.UtilityModels.RxBleProvider;
import com.eveningoutpost.dexdrip.UtilityModels.StatusItem;
import com.eveningoutpost.dexdrip.UtilityModels.StatusItem.Highlight;
import com.eveningoutpost.dexdrip.UtilityModels.WholeHouse;
import com.eveningoutpost.dexdrip.ui.helpers.Span;
import com.eveningoutpost.dexdrip.utils.DexCollectionType;
import com.eveningoutpost.dexdrip.utils.bt.Subscription;
import com.eveningoutpost.dexdrip.utils.framework.WakeLockTrampoline;
import com.eveningoutpost.dexdrip.watch.thinjam.BlueJayEntry;
import com.eveningoutpost.dexdrip.xdrip;
import com.google.common.collect.Sets;
import com.polidea.rxandroidble2.RxBleClient;
import com.polidea.rxandroidble2.RxBleConnection;
import com.polidea.rxandroidble2.RxBleCustomOperation;
import com.polidea.rxandroidble2.RxBleDevice;
import com.polidea.rxandroidble2.RxBleDeviceServices;
import com.polidea.rxandroidble2.exceptions.BleGattCallbackTimeoutException;
import com.polidea.rxandroidble2.exceptions.BleScanException;
import com.polidea.rxandroidble2.internal.RxBleLog;
import com.polidea.rxandroidble2.internal.connection.RxBleGattCallback;
import com.polidea.rxandroidble2.scan.ScanFilter;
import com.polidea.rxandroidble2.scan.ScanResult;
import com.polidea.rxandroidble2.scan.ScanSettings;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.Scheduler;
import io.reactivex.schedulers.Schedulers;
import lombok.Setter;
import static com.eveningoutpost.dexdrip.G5Model.BluetoothServices.getUUIDName;
import static com.eveningoutpost.dexdrip.G5Model.CalibrationState.Ok;
import static com.eveningoutpost.dexdrip.G5Model.CalibrationState.Unknown;
import static com.eveningoutpost.dexdrip.G5Model.G6CalibrationParameters.getCurrentSensorCode;
import static com.eveningoutpost.dexdrip.G5Model.Ob1G5StateMachine.CLOSED_OK_TEXT;
import static com.eveningoutpost.dexdrip.G5Model.Ob1G5StateMachine.evaluateG6Settings;
import static com.eveningoutpost.dexdrip.G5Model.Ob1G5StateMachine.pendingCalibration;
import static com.eveningoutpost.dexdrip.G5Model.Ob1G5StateMachine.pendingStart;
import static com.eveningoutpost.dexdrip.G5Model.Ob1G5StateMachine.pendingStop;
import static com.eveningoutpost.dexdrip.G5Model.Ob1G5StateMachine.usingAlt;
import static com.eveningoutpost.dexdrip.Models.JoH.niceTimeScalar;
import static com.eveningoutpost.dexdrip.Models.JoH.tsl;
import static com.eveningoutpost.dexdrip.Services.Ob1G5CollectionService.STATE.BOND;
import static com.eveningoutpost.dexdrip.Services.Ob1G5CollectionService.STATE.CLOSE;
import static com.eveningoutpost.dexdrip.Services.Ob1G5CollectionService.STATE.CLOSED;
import static com.eveningoutpost.dexdrip.Services.Ob1G5CollectionService.STATE.CONNECT;
import static com.eveningoutpost.dexdrip.Services.Ob1G5CollectionService.STATE.CONNECT_NOW;
import static com.eveningoutpost.dexdrip.Services.Ob1G5CollectionService.STATE.DISCOVER;
import static com.eveningoutpost.dexdrip.Services.Ob1G5CollectionService.STATE.GET_DATA;
import static com.eveningoutpost.dexdrip.Services.Ob1G5CollectionService.STATE.INIT;
import static com.eveningoutpost.dexdrip.Services.Ob1G5CollectionService.STATE.PREBOND;
import static com.eveningoutpost.dexdrip.Services.Ob1G5CollectionService.STATE.SCAN;
import static com.eveningoutpost.dexdrip.UtilityModels.Constants.G5_CALIBRATION_REQUEST;
import static com.eveningoutpost.dexdrip.UtilityModels.Constants.G5_SENSOR_FAILED;
import static com.eveningoutpost.dexdrip.UtilityModels.Constants.G5_SENSOR_RESTARTED;
import static com.eveningoutpost.dexdrip.UtilityModels.Constants.G5_SENSOR_STARTED;
import static com.eveningoutpost.dexdrip.UtilityModels.Constants.HOUR_IN_MS;
import static com.eveningoutpost.dexdrip.UtilityModels.Constants.SECOND_IN_MS;
import static com.eveningoutpost.dexdrip.UtilityModels.StatusItem.Highlight.BAD;
import static com.eveningoutpost.dexdrip.UtilityModels.StatusItem.Highlight.CRITICAL;
import static com.eveningoutpost.dexdrip.UtilityModels.StatusItem.Highlight.NORMAL;
import static com.eveningoutpost.dexdrip.UtilityModels.StatusItem.Highlight.NOTICE;
import static com.eveningoutpost.dexdrip.utils.DexCollectionType.DexcomG5;
import static com.eveningoutpost.dexdrip.utils.bt.Subscription.addErrorHandler;
import static com.eveningoutpost.dexdrip.xdrip.gs;
/*import com.polidea.rxandroidble.RxBleClient;
import com.polidea.rxandroidble.RxBleConnection;
import com.polidea.rxandroidble.RxBleCustomOperation;
import com.polidea.rxandroidble.RxBleDevice;
import com.polidea.rxandroidble.RxBleDeviceServices;
import com.polidea.rxandroidble.exceptions.BleGattCallbackTimeoutException;
import com.polidea.rxandroidble.exceptions.BleScanException;
import com.polidea.rxandroidble.internal.RxBleLog;
import com.polidea.rxandroidble.internal.connection.RxBleGattCallback;
import com.polidea.rxandroidble.scan.ScanFilter;
import com.polidea.rxandroidble.scan.ScanResult;
import com.polidea.rxandroidble.scan.ScanSettings;
*/
//import rx.Observable;
//import rx.Scheduler;
//import rx.Subscription;
//import rx.schedulers.Schedulers;
/**
* OB1 G5/G6 collector
* Created by jamorham on 16/09/2017.
*
* App version is master, best to avoid editing wear version directly
*
*/
public class Ob1G5CollectionService extends G5BaseService {
public static final String TAG = Ob1G5CollectionService.class.getSimpleName();
public static final String OB1G5_PREFS = "use_ob1_g5_collector_service";
private static final String OB1G5_MACSTORE = "G5-mac-for-txid-";
private static final String OB1G5_STATESTORE = "ob1-state-store-";
private static final String OB1G5_STATESTORE_TIME = "ob1-state-store-time";
private static final int DEFAULT_AUTOMATA_DELAY = 100;
private static final String BUGGY_SAMSUNG_ENABLED = "buggy-samsung-enabled";
private static final String STOP_SCAN_TASK_ID = "ob1-g5-scan-timeout_scan";
private static volatile STATE state = INIT;
private static volatile STATE last_automata_state = CLOSED;
private static RxBleClient rxBleClient;
private static volatile PendingIntent pendingIntent;
private static String transmitterID;
private static volatile String transmitterMAC;
private static volatile String historicalTransmitterMAC;
private static String transmitterIDmatchingMAC;
private static String lastScanError = null;
public static volatile String lastSensorStatus = null;
public static volatile CalibrationState lastSensorState = null;
public static volatile long lastUsableGlucosePacketTime = 0;
private static volatile String static_connection_state = null;
private static volatile long static_last_connected = 0;
@Setter
private static long last_transmitter_timestamp = 0;
private static long lastStateUpdated = 0;
private static long wakeup_time = 0;
private static long wakeup_jitter = 0;
private static long max_wakeup_jitter = 0;
private static volatile long connecting_time = 0;
public static boolean keep_running = true;
public static boolean android_wear = false;
public static boolean wear_broadcast = false;
private static volatile Subscription scanSubscription;
private static volatile Subscription connectionSubscription;
private static volatile Subscription stateSubscription;
private Subscription discoverSubscription;
private RxBleDevice bleDevice;
private RxBleConnection connection;
private PowerManager.WakeLock connection_linger;
private volatile PowerManager.WakeLock scanWakeLock;
private volatile PowerManager.WakeLock floatingWakeLock;
private PowerManager.WakeLock fullWakeLock;
private volatile boolean background_launch_waiting = false;
private static long last_scan_started = -1;
private static volatile long last_connect_started = -1;
private static int error_count = 0;
private static int connectNowFailures = 0;
private static int connectFailures = 0;
private static volatile int scanTimeouts = 0;
private static boolean lastConnectFailed = false;
private static boolean preScanFailureMarker = false;
private static boolean auth_succeeded = false;
private int error_backoff_ms = 1000;
private static final int max_error_backoff_ms = 10000;
private static final long TOLERABLE_JITTER = 10000;
private static final boolean d = false;
private static boolean use_auto_connect = false;
private static volatile boolean minimize_scanning = false; // set by preference
private static volatile boolean always_scan = false;
private static volatile boolean scan_next_run = true;
private static boolean always_discover = false;
private static boolean always_connect = false;
private static boolean do_discovery = true;
private static final boolean do_auth = true;
//private static boolean initiate_bonding = false;
private static final Set<String> alwaysScanModels = Sets.newHashSet("SM-N910V", "G Watch");
private static final List<String> alwaysScanModelFamilies = Arrays.asList("SM-N910");
private static final Set<String> alwaysConnectModels = Sets.newHashSet("G Watch");
private static final Set<String> alwaysBuggyWakeupModels = Sets.newHashSet("Jelly-Pro", "SmartWatch 3");
// Internal process state tracking
public enum STATE {
INIT("Initializing"),
SCAN("Scanning"),
CONNECT("Waiting connect"),
CONNECT_NOW("Power connect"),
DISCOVER("Examining"),
CHECK_AUTH("Checking Auth"),
PREBOND("Bond Prepare"),
BOND("Bonding"),
RESET("Reseting"),
GET_DATA("Getting Data"),
CLOSE("Sleeping"),
CLOSED("Deep Sleeping");
private String str;
STATE(String custom) {
this.str = custom;
}
STATE() {
this.str = toString();
}
public String getString() {
return str;
}
}
public void authResult(boolean good) {
auth_succeeded = good;
}
private synchronized void backoff_automata() {
background_automata(error_backoff_ms);
if (error_backoff_ms < max_error_backoff_ms) error_backoff_ms += 100;
}
public void background_automata() {
background_automata(DEFAULT_AUTOMATA_DELAY);
}
public synchronized void background_automata(final int timeout) {
if (background_launch_waiting) {
UserError.Log.d(TAG, "Blocked by existing background automata pending");
return;
}
final PowerManager.WakeLock wl = JoH.getWakeLock("jam-g5-background", timeout + 5000);
background_launch_waiting = true;
new Thread(() -> {
JoH.threadSleep(timeout);
background_launch_waiting = false;
automata();
JoH.releaseWakeLock(wl);
}).start();
}
private synchronized void automata() {
if ((last_automata_state != state) || state == INIT || (JoH.ratelimit("jam-g5-dupe-auto", 2))) {
last_automata_state = state;
final PowerManager.WakeLock wl = JoH.getWakeLock("jam-g5-automata", 60000);
try {
switch (state) {
case INIT:
initialize();
break;
case SCAN:
// no connection? lets try a restart
if (JoH.msSince(static_last_connected) > 30 * 60 * 1000) {
if (JoH.pratelimit("ob1-collector-restart", 1200)) {
CollectionServiceStarter.restartCollectionServiceBackground();
break;
}
}
// TODO check if we know mac!!! Sync as part of wear sync?? - TODO preload transmitter mac??
if (useMinimizeScanningStrategy()) {
UserError.Log.d(TAG, "Skipping Scanning! : Changing state due to minimize_scanning flags");
changeState(CONNECT_NOW);
} else {
if (Build.VERSION.SDK_INT >= 29) { // TODO add preference option for this
UserError.Log.d(TAG, "Attempting Android 10+ workaround unbonding");
unBond();
}
scan_for_device();
}
break;
case CONNECT_NOW:
connect_to_device(false);
break;
case CONNECT:
connect_to_device(true);
break;
case DISCOVER:
if (wear_broadcast && usingAlt()) {
msg("Pausing");
UserError.Log.d(TAG, "Pausing for alt: ");
JoH.threadSleep(1000);
}
if (do_discovery) {
discover_services();
} else {
UserError.Log.d(TAG, "Skipping discovery");
changeState(STATE.CHECK_AUTH);
}
break;
case CHECK_AUTH:
if (do_auth) {
final PowerManager.WakeLock linger_wl_connect = JoH.getWakeLock("jam-g5-check-linger", 6000);
if (!Ob1G5StateMachine.doCheckAuth(this, connection)) resetState();
} else {
UserError.Log.d(TAG, "Skipping authentication");
changeState(GET_DATA);
}
break;
case PREBOND:
if (!getInitiateBondingFlag()) {
final PowerManager.WakeLock linger_wl_prebond = JoH.getWakeLock("jam-g5-prebond-linger", 16000);
if (!Ob1G5StateMachine.doKeepAliveAndBondRequest(this, connection))
resetState();
} else {
UserError.Log.d(TAG, "Going directly to initiate bond");
changeState(BOND);
}
break;
case BOND:
if (getInitiateBondingFlag()) {
UserError.Log.d(TAG, "State bond attempting to create bond");
} else {
UserError.Log.d(TAG, "State bond currently does nothing as setting disabled");
}
create_bond();
break;
case RESET:
UserError.Log.d(TAG, "Entering hard reset state");
Ob1G5StateMachine.doReset(this, connection);
break;
case GET_DATA:
if (hardResetTransmitterNow) {
send_reset_command();
} else {
final PowerManager.WakeLock linger_wl_get_data = JoH.getWakeLock("jam-g5-get-linger", 6000);
if (!Ob1G5StateMachine.doGetData(this, connection)) resetState();
}
break;
case CLOSE:
prepareToWakeup();
break;
case CLOSED:
handleWakeup();
break;
}
} finally {
JoH.releaseWakeLock(wl);
}
} else {
UserError.Log.d(TAG, "Ignoring duplicate automata state within 2 seconds: " + state);
}
}
private boolean useMinimizeScanningStrategy() {
tryLoadingSavedMAC();
final int modulo = (connectNowFailures + scanTimeouts) % 2;
UserError.Log.d(TAG, "minimize: " + minimize_scanning + " mac: " + transmitterMAC + " lastfailed:" + lastConnectFailed + " nowfail:" + connectNowFailures + " stimeout:" + scanTimeouts + " modulo:" + modulo);
final boolean wholeHouse = WholeHouse.isLive();
boolean alwaysMinimize = false;
if (wholeHouse) {
estimateAnticipateFromLinkedData();
alwaysMinimize = !preScanFailureMarker;
}
return minimize_scanning && transmitterMAC != null && (!lastConnectFailed || (modulo == 1) || alwaysMinimize) && (DexSyncKeeper.isReady(transmitterID));
}
private void estimateAnticipateFromLinkedData() {
final BgReading bg = BgReading.last();
if (bg != null && bg.timestamp > static_last_connected && JoH.msSince(bg.timestamp) < HOUR_IN_MS * 3) {
final long ts = bg.timestamp - Constants.SECOND_IN_MS;
UserError.Log.d(TAG, "Updating Sync Keeper with network learned timestamp: " + JoH.dateTimeText(ts));
DexSyncKeeper.store(transmitterID, ts);
}
}
private void resetState() {
UserError.Log.e(TAG, "Resetting sequence state to INIT");
changeState(INIT);
}
public STATE getState() {
return state;
}
public void changeState(STATE new_state) {
changeState(new_state, DEFAULT_AUTOMATA_DELAY);
}
public void changeState(STATE new_state, int timeout) {
if ((state == CLOSED || state == CLOSE) && new_state == CLOSE) {
UserError.Log.d(TAG, "Not closing as already closed");
} else {
UserError.Log.d(TAG, "Changing state from: " + state + " to " + new_state);
state = new_state;
if (android_wear && wear_broadcast) {
msg(new_state.toString());
}
background_automata(timeout);
}
}
private synchronized void initialize() {
if (state == INIT) {
msg("Initializing");
static_connection_state = null;
if (rxBleClient == null) {
//rxBleClient = RxBleClient.create(xdrip.getAppContext());
rxBleClient = RxBleProvider.getSingleton();
}
init_tx_id();
// load prefs etc
changeState(SCAN);
} else {
UserError.Log.wtf(TAG, "Attempt to initialize when not in INIT state");
}
}
private static void init_tx_id() {
transmitterID = Pref.getString("dex_txid", "NULL");
}
private synchronized void scan_for_device() {
if (state == SCAN) {
msg(gs(R.string.scanning));
stopScan();
tryLoadingSavedMAC(); // did we already find it?
if (always_scan || scan_next_run || (transmitterMAC == null) || (!transmitterID.equals(transmitterIDmatchingMAC)) || (static_last_timestamp < 1)) {
scan_next_run = false; // reset if set
transmitterMAC = null; // reset if set
last_scan_started = tsl();
scanWakeLock = JoH.getWakeLock("xdrip-jam-g5-scan", (int) Constants.MINUTE_IN_MS * 7);
historicalTransmitterMAC = PersistentStore.getString(OB1G5_MACSTORE + transmitterID); // "" if unset
ScanFilter filter;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && historicalTransmitterMAC.length() > 5) {
filter = new ScanFilter.Builder()
.setDeviceAddress(historicalTransmitterMAC)
.build();
} else {
final String localTransmitterID = transmitterID;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && localTransmitterID != null && localTransmitterID.length() > 4) {
filter = new ScanFilter.Builder().setDeviceName(getTransmitterBluetoothName()).build();
} else {
filter = new ScanFilter.Builder().build();
}
}
scanSubscription = new Subscription(rxBleClient.scanBleDevices(
new ScanSettings.Builder()
//.setScanMode(static_last_timestamp < 1 ? ScanSettings.SCAN_MODE_LOW_LATENCY : ScanSettings.SCAN_MODE_BALANCED)
//.setCallbackType(ScanSettings.CALLBACK_TYPE_FIRST_MATCH)
.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
// TODO revisit scan mode
.setScanMode(android_wear ? ScanSettings.SCAN_MODE_BALANCED :
minimize_scanning ? ScanSettings.SCAN_MODE_BALANCED : ScanSettings.SCAN_MODE_LOW_LATENCY)
// .setScanMode(ScanSettings.SCAN_MODE_BALANCED)
.build(),
// scan filter doesn't work reliable on android sdk 23+
filter
)
// observe on?
// do unsubscribe?
//.doOnUnsubscribe(this::clearSubscription)
.subscribeOn(Schedulers.io())
.subscribe(this::onScanResult, this::onScanFailure));
if (minimize_scanning) {
// Must be less than fail over timeout
Inevitable.task(STOP_SCAN_TASK_ID, 320 * Constants.SECOND_IN_MS, this::stopScanWithTimeoutAndReschedule);
}
UserError.Log.d(TAG, "Scanning for: " + getTransmitterBluetoothName());
} else {
UserError.Log.d(TAG, "Transmitter mac already known: " + transmitterMAC);
changeState(CONNECT);
}
} else {
UserError.Log.wtf(TAG, "Attempt to scan when not in SCAN state");
}
}
private void stopScanWithTimeoutAndReschedule() {
stopScan();
UserError.Log.d(TAG, "Stopped scan due to timeout at: " + JoH.dateTimeText(tsl()));
//noinspection NonAtomicOperationOnVolatileField
scanTimeouts++;
tryLoadingSavedMAC();
prepareToWakeup();
}
private synchronized void connect_to_device(boolean auto) {
if ((state == CONNECT) || (state == CONNECT_NOW)) {
// TODO check mac
if (transmitterMAC == null) {
tryLoadingSavedMAC();
}
final String localTransmitterMAC = transmitterMAC;
if (localTransmitterMAC != null) {
if (inPurdah()) {
msg("Purdah " + niceTimeScalar(purdahMs()));
changeState(CLOSE);
return;
}
msg("Connect request");
if (state == CONNECT_NOW) {
if (connection_linger != null) JoH.releaseWakeLock(connection_linger);
connection_linger = JoH.getWakeLock("jam-g5-pconnect", 60000);
}
if (d)
UserError.Log.d(TAG, "Local bonding state: " + (isDeviceLocallyBonded() ? "BONDED" : "NOT Bonded"));
stopConnect();
try {
bleDevice = rxBleClient.getBleDevice(localTransmitterMAC);
/// / Listen for connection state changes
stateSubscription = new Subscription(bleDevice.observeConnectionStateChanges()
// .observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(this::onConnectionStateChange, throwable -> {
UserError.Log.wtf(TAG, "Got Error from state subscription: " + throwable);
}));
last_connect_started = tsl();
// Attempt to establish a connection // TODO does this need different connection timeout for auto vs normal?
connectionSubscription = new Subscription(bleDevice.establishConnection(auto)
.timeout(7, TimeUnit.MINUTES)
// .flatMap(RxBleConnection::discoverServices)
// .observeOn(AndroidSchedulers.mainThread())
// .doOnUnsubscribe(this::clearSubscription)
.subscribeOn(Schedulers.io())
.subscribe(this::onConnectionReceived, this::onConnectionFailure));
} catch (IllegalArgumentException e) {
UserError.Log.e(TAG, "Caught IllegalArgument Exception: " + e + " retry on next run");
// TODO if this is due to concurrent access then changing state again may be a bad idea
state = SCAN;
backoff_automata(); // note backoff
}
} else {
UserError.Log.wtf(TAG, "No transmitter mac address!");
state = SCAN;
backoff_automata(); // note backoff
}
} else {
UserError.Log.wtf(TAG, "Attempt to connect when not in CONNECT state");
}
}
private synchronized void discover_services() {
if (state == DISCOVER) {
if (connection != null) {
if (d)
UserError.Log.d(TAG, "Local bonding state: " + (isDeviceLocallyBonded() ? "BONDED" : "NOT Bonded"));
stopDiscover();
discoverSubscription = new Subscription(connection.discoverServices(10, TimeUnit.SECONDS).subscribe(this::onServicesDiscovered, this::onDiscoverFailed));
} else {
UserError.Log.e(TAG, "No connection when in DISCOVER state - reset");
state = INIT;
background_automata();
}
} else {
UserError.Log.wtf(TAG, "Attempt to discover when not in DISCOVER state");
}
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private synchronized void create_bond() {
if (state == BOND) {
try {
msg("Bonding");
do_create_bond();
//state = STATE.CONNECT_NOW;
//background_automata(15000);
} catch (Exception e) {
UserError.Log.wtf(TAG, "Exception creating bond: " + e);
}
} else {
UserError.Log.wtf(TAG, "Attempt to bond when not in BOND state");
}
}
public synchronized void reset_bond(boolean allow) {
if (allow || (JoH.pratelimit("ob1-bond-cycle", 7200))) {
UserError.Log.e(TAG, "Attempting to refresh bond state");
msg("Resetting Bond");
unBond();
do_create_bond();
}
}
private synchronized void do_create_bond() {
final boolean isDeviceLocallyBonded = isDeviceLocallyBonded();
UserError.Log.d(TAG, "Attempting to create bond, device is : " + (isDeviceLocallyBonded ? "BONDED" : "NOT Bonded"));
if (isDeviceLocallyBonded && getInitiateBondingFlag()) {
UserError.Log.d(TAG, "Device is marked as bonded but we are being asked to bond so attempting to unbond first");
unbondIfAllowed();
changeState(CLOSE);
} else {
try {
Ob1G5StateMachine.doKeepAlive(this, connection, () -> {
weInitiatedBondConfirmation = 1;
instantCreateBondIfAllowed();
});
//background_automata(10000);
} catch (Exception e) {
UserError.Log.wtf(TAG, "Got exception in do_create_bond() " + e);
}
}
}
private synchronized void send_reset_command() {
hardResetTransmitterNow = false;
getBatteryStatusNow = true;
if (JoH.ratelimit("reset-command", 1200)) {
UserError.Log.e(TAG, "Issuing reset command!");
changeState(STATE.RESET);
} else {
UserError.Log.e(TAG, "Reset command blocked by 20 minute timer");
}
}
private String getTransmitterBluetoothName() {
final String transmitterIdLastTwo = getLastTwoCharacters(transmitterID);
// todo check for bad config
return "Dexcom" + transmitterIdLastTwo;
}
public static String getMac() {
return transmitterMAC;
}
private void tryLoadingSavedMAC() {
if ((transmitterMAC == null) || (!transmitterIDmatchingMAC.equals(transmitterID))) {
if (transmitterID != null) {
final String this_mac = PersistentStore.getString(OB1G5_MACSTORE + transmitterID);
if (this_mac.length() == 17) {
UserError.Log.d(TAG, "Loaded stored MAC for: " + transmitterID + " " + this_mac);
transmitterMAC = this_mac;
transmitterIDmatchingMAC = transmitterID;
} else {
UserError.Log.d(TAG, "Did not find any saved MAC for: " + transmitterID);
}
} else {
UserError.Log.e(TAG, "Could not load saved mac as transmitter id isn't set!");
}
} else {
UserError.Log.d(TAG, "MAC for transmitter id already populated: " + transmitterID + " " + transmitterMAC);
}
}
// should this service be running? Used to decide when to shut down
private static boolean shouldServiceRun() {
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return false;
if (!Pref.getBooleanDefaultFalse(OB1G5_PREFS)) return false;
if (!(DexCollectionType.getDexCollectionType() == DexcomG5)) return false;
if (!android_wear) {
if (Home.get_forced_wear()) {
if (JoH.quietratelimit("forced-wear-notice", 3))
UserError.Log.d(TAG, "Not running due to forced wear");
return false;
}
if (BlueJayEntry.isPhoneCollectorDisabled()) {
UserError.Log.d(TAG,"Not running as BlueJay is collector");
return false;
}
} else {
// android wear code
if (!PersistentStore.getBoolean(CollectionServiceStarter.pref_run_wear_collector))
return false;
}
return true;
}
// check required permissions and warn the user if they are wrong
private static void checkPermissions() {
}
private static synchronized boolean isDeviceLocallyBonded() {
if (transmitterMAC == null) return false;
final Set<RxBleDevice> pairedDevices = rxBleClient.getBondedDevices();
if ((pairedDevices != null) && (pairedDevices.size() > 0)) {
for (RxBleDevice device : pairedDevices) {
if ((device.getMacAddress() != null) && (device.getMacAddress().equals(transmitterMAC))) {
return true;
}
}
}
return false;
}
private synchronized void checkAndEnableBT() {
try {
if (Pref.getBoolean("automatically_turn_bluetooth_on", true)) {
final BluetoothAdapter mBluetoothAdapter = ((BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();
if (!mBluetoothAdapter.isEnabled()) {
if (JoH.ratelimit("g5-enabling-bluetooth", 30)) {
JoH.setBluetoothEnabled(this, true);
UserError.Log.e(TAG, "Enabling bluetooth");
}
}
}
} catch (Exception e) {
UserError.Log.e(TAG, "Got exception checking BT: " + e);
}
}
public synchronized void unBond() {
UserError.Log.d(TAG, "unBond() start");
if (transmitterMAC == null) return;
final BluetoothAdapter mBluetoothAdapter = ((BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();
final Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (final BluetoothDevice device : pairedDevices) {
if (device.getAddress() != null) {
if (device.getAddress().equals(transmitterMAC)) {
try {
UserError.Log.e(TAG, "removingBond: " + transmitterMAC);
final Method m = device.getClass().getMethod("removeBond", (Class[]) null);
m.invoke(device, (Object[]) null);
// TODO interpret boolean response
break;
} catch (Exception e) {
UserError.Log.e(TAG, e.getMessage(), e);
}
}
}
}
}
UserError.Log.d(TAG, "unBond() finished");
}
public static String getTransmitterID() {
if (transmitterID == null) {
init_tx_id();
}
return transmitterID;
}
private void handleWakeup() {
if (always_scan) {
UserError.Log.d(TAG, "Always scan mode");
changeState(SCAN);
} else {
if (connectFailures > 0 || (!use_auto_connect && connectNowFailures > 0)) {
always_scan = true;
UserError.Log.e(TAG, "Switching to scan always mode due to connect failures metric: " + connectFailures);
changeState(SCAN);
} else if (use_auto_connect && (connectNowFailures > 1) && (connectFailures < 0)) {
UserError.Log.d(TAG, "Avoiding power connect due to failure metric: " + connectNowFailures + " " + connectFailures);
changeState(CONNECT);
} else {
changeState(CONNECT_NOW);
}
}
}
private synchronized void prepareToWakeup() {
if (JoH.ratelimit("g5-wakeup-timer", 5)) {
final long when = DexSyncKeeper.anticipate(transmitterID);
if (when > 0) {
final long when_offset = when - tsl();
UserError.Log.d(TAG, "(" + JoH.dateTimeText(tsl()) + ") Wake up time anticipated at: " + JoH.dateTimeText(when));
scheduleWakeUp(when_offset - Constants.SECOND_IN_MS * 15, "anticipate");
} else {
scheduleWakeUp(Constants.SECOND_IN_MS * 285, "anticipate");
}
}
if ((android_wear && wakeup_jitter > TOLERABLE_JITTER) || always_connect) {
// TODO should be max_wakeup_jitter perhaps or set always_connect flag
UserError.Log.d(TAG, "Not stopping connect due to " + (always_connect ? "always_connect flag" : "unreliable wake up"));
state = CONNECT;
background_automata(6000);
} else {
state = CLOSED; // Don't poll automata as we want to do this on waking
stopConnect();
}
}
private void scheduleWakeUp(long future, final String info) {
if (future <= 0) future = 5000;
UserError.Log.d(TAG, "Scheduling wakeup @ " + JoH.dateTimeText(tsl() + future) + " (" + info + ")");
if (pendingIntent == null)
//pendingIntent = PendingIntent.getService(this, 0, new Intent(this, this.getClass()), 0);
pendingIntent = WakeLockTrampoline.getPendingIntent(this.getClass());
wakeup_time = tsl() + future;
JoH.wakeUpIntent(this, future, pendingIntent);
}
public void incrementErrors() {
error_count++;
if (error_count > 1) {
UserError.Log.e(TAG, "Error count reached: " + error_count);
}
}
public void clearErrors() {
error_count = 0;
}
private void checkAlwaysScanModels() {
final String this_model = Build.MODEL;
UserError.Log.d(TAG, "Checking model: " + this_model);
if ((JoH.isSamsung() && PersistentStore.getLong(BUGGY_SAMSUNG_ENABLED) > 4)) {
UserError.Log.d(TAG, "Enabling buggy samsung due to persistent metric");
JoH.buggy_samsung = true;
}
always_connect = alwaysConnectModels.contains(this_model);
if (alwaysBuggyWakeupModels.contains(this_model)) {
UserError.Log.e(TAG, "Always buggy wakeup exact match for " + this_model);
JoH.buggy_samsung = true;
}
if (alwaysScanModels.contains(this_model)) {
UserError.Log.e(TAG, "Always scan model exact match for: " + this_model);
always_scan = true;
return;
}
for (String check : alwaysScanModelFamilies) {
if (this_model.startsWith(check)) {
UserError.Log.e(TAG, "Always scan model fuzzy match for: " + this_model);
always_scan = true;
return;
}
}
}
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
UserError.Log.wtf(TAG, "Not high enough Android version to run: " + Build.VERSION.SDK_INT);
} else {
try {
registerReceiver(mBondStateReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
} catch (Exception e) {
UserError.Log.e(TAG, "Could not register bond state receiver: " + e);
}
final IntentFilter pairingRequestFilter = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
pairingRequestFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY - 1);
try {
registerReceiver(mPairingRequestRecevier, pairingRequestFilter);
} catch (Exception e) {
UserError.Log.e(TAG, "Could not register pairing request receiver:" + e);
}
checkAlwaysScanModels();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
android_wear = (getResources().getConfiguration().uiMode & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_WATCH;
if (android_wear) {
UserError.Log.d(TAG, "We are running on Android Wear");
wear_broadcast = Pref.getBooleanDefaultFalse("ob1_wear_broadcast");
}
}
}
if (d) RxBleClient.setLogLevel(RxBleLog.DEBUG);
addErrorHandler(TAG);
listenForChangeInSettings(true);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
xdrip.checkAppContext(getApplicationContext());
final PowerManager.WakeLock wl = JoH.getWakeLock("g5-start-service", 310000);
try {
UserError.Log.d(TAG, "WAKE UP WAKE UP WAKE UP WAKE UP @ " + JoH.dateTimeText(tsl()));
msg("Wake up");
if (wakeup_time > 0) {
wakeup_jitter = JoH.msSince(wakeup_time);
if (wakeup_jitter < 0) {
UserError.Log.d(TAG, "Woke up Early..");
} else {
if (wakeup_jitter > 1000) {
UserError.Log.d(TAG, "Wake up, time jitter: " + niceTimeScalar(wakeup_jitter));
if ((wakeup_jitter > TOLERABLE_JITTER) && (!JoH.buggy_samsung) && JoH.isSamsung()) {
UserError.Log.wtf(TAG, "Enabled Buggy Samsung workaround due to jitter of: " + niceTimeScalar(wakeup_jitter));
JoH.buggy_samsung = true;
PersistentStore.incrementLong(BUGGY_SAMSUNG_ENABLED);
max_wakeup_jitter = 0;
} else {
max_wakeup_jitter = Math.max(max_wakeup_jitter, wakeup_jitter);
}
}
}
}
if (!shouldServiceRun()) {
UserError.Log.d(TAG, "Stopping service due to shouldServiceRun() result");
msg("Stopping");
stopSelf();
return START_NOT_STICKY;
}
scheduleWakeUp(Constants.MINUTE_IN_MS * 6, "fail-over");
if ((state == BOND) || (state == PREBOND) || (state == DISCOVER) || (state == CONNECT))
state = SCAN;
checkAndEnableBT();
Ob1G5StateMachine.restoreQueue();
if (JoH.quietratelimit("evaluateG6Settings", 600)) {
evaluateG6Settings();
}
minimize_scanning = Pref.getBooleanDefaultFalse("ob1_minimize_scanning");
automata(); // sequence logic
UserError.Log.d(TAG, "Releasing service start");
return START_STICKY;
} finally {
JoH.releaseWakeLock(wl);
}
}