导航菜单

页面标题

页面副标题

xDrip+ v04633772025.07.16 - Ob1G5CollectionService.java 源代码

正在查看: xDrip+ v04633772025.07.16 应用的 Ob1G5CollectionService.java JAVA 源代码文件

本页面展示 JAVA 反编译生成的源代码文件,支持语法高亮显示。 仅供安全研究与技术分析使用,严禁用于任何非法用途。请遵守相关法律法规。


package com.eveningoutpost.dexdrip.services;

import android.annotation.TargetApi;
import android.app.PendingIntent;
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.media.AudioManager;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import androidx.appcompat.R$styleable;
import com.eveningoutpost.dexdrip.AddCalibration;
import com.eveningoutpost.dexdrip.DoubleCalibrationActivity;
import com.eveningoutpost.dexdrip.Home;
import com.eveningoutpost.dexdrip.g5model.BluetoothServices;
import com.eveningoutpost.dexdrip.g5model.CalibrationState;
import com.eveningoutpost.dexdrip.g5model.DexSyncKeeper;
import com.eveningoutpost.dexdrip.g5model.Ob1G5StateMachine;
import com.eveningoutpost.dexdrip.g5model.VersionRequest1RxMessage;
import com.eveningoutpost.dexdrip.importedlibraries.usbserial.driver.UsbId;
import com.eveningoutpost.dexdrip.models.BgReading;
import com.eveningoutpost.dexdrip.models.JoH;
import com.eveningoutpost.dexdrip.models.Sensor;
import com.eveningoutpost.dexdrip.models.Treatments;
import com.eveningoutpost.dexdrip.models.UserError;
import com.eveningoutpost.dexdrip.plugin.Dialog;
import com.eveningoutpost.dexdrip.plugin.IPluginDA;
import com.eveningoutpost.dexdrip.plugin.Loader;
import com.eveningoutpost.dexdrip.plugin.Registry;
import com.eveningoutpost.dexdrip.services.Ob1G5CollectionService;
import com.eveningoutpost.dexdrip.ui.helpers.Span;
import com.eveningoutpost.dexdrip.utilitymodels.BroadcastGlucose;
import com.eveningoutpost.dexdrip.utilitymodels.CollectionServiceStarter;
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.SendFeedBack;
import com.eveningoutpost.dexdrip.utilitymodels.StatusItem;
import com.eveningoutpost.dexdrip.utilitymodels.UpdateActivity;
import com.eveningoutpost.dexdrip.utilitymodels.WholeHouse;
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.connection.RxBleGattCallback;
import com.polidea.rxandroidble2.scan.ScanResult;
import io.reactivex.Observable;
import io.reactivex.Scheduler;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

public class Ob1G5CollectionService extends G5BaseService {
    public static final String TAG = "Ob1G5CollectionService";
    private static volatile Subscription connectionSubscription;
    private static volatile String historicalTransmitterMAC;
    private static volatile long lastProcessCalibrationState;
    private static volatile PendingIntent pendingIntent;
    private static RxBleClient rxBleClient;
    private static volatile Subscription scanSubscription;
    private static volatile Subscription stateSubscription;
    private static volatile String transmitterID;
    private static String transmitterIDmatchingMAC;
    private static volatile String transmitterMAC;
    private RxBleDevice bleDevice;
    private RxBleConnection connection;
    private PowerManager.WakeLock connection_linger;
    private Subscription discoverSubscription;
    private volatile PowerManager.WakeLock floatingWakeLock;
    private PowerManager.WakeLock fullWakeLock;
    public volatile IPluginDA plugin;
    private volatile PowerManager.WakeLock scanWakeLock;
    private static volatile STATE state = STATE.INIT;
    private static volatile STATE last_automata_state = STATE.CLOSED;
    private static volatile String lastScanError = null;
    private static volatile int lastScanException = -1;
    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;
    public static volatile long static_last_connected = 0;
    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 long last_scan_started = -1;
    private static volatile long last_connect_started = -1;
    private static volatile long last_mega_status_read = -1;
    private static volatile int error_count = 0;
    private static volatile int retry_count = 0;
    private static volatile int connectNowFailures = 0;
    private static volatile int connectFailures = 0;
    private static volatile int scanTimeouts = 0;
    private static volatile boolean lastConnectFailed = false;
    private static volatile boolean preScanFailureMarker = false;
    private static boolean auth_succeeded = false;
    private static volatile String wasBonded = "";
    private static volatile int skippedConnects = 0;
    private static volatile boolean allow_scan_by_mac = false;
    private static volatile boolean use_auto_connect = false;
    private static volatile boolean minimize_scanning = false;
    private static volatile boolean always_scan = false;
    private static volatile boolean scan_next_run = true;
    private static boolean always_connect = false;
    private static boolean do_discovery = true;
    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");
    private static final HashMap<String, Long> failureTally = new HashMap<>();
    private volatile boolean background_launch_waiting = false;
    private int error_backoff_ms = 1000;
    private volatile boolean lastWasScanByMac = false;
    private int currentBondState = 0;
    public volatile int waitingBondConfirmation = 0;
    public volatile int weInitiatedBondConfirmation = 0;
    final BroadcastReceiver mBondStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (!Ob1G5CollectionService.keep_running) {
                try {
                    UserError.Log.e(Ob1G5CollectionService.TAG, "Rogue bond state receiver still active - unregistering");
                    Ob1G5CollectionService ob1G5CollectionService = Ob1G5CollectionService.this;
                    ob1G5CollectionService.unregisterReceiver(ob1G5CollectionService.mBondStateReceiver);
                    return;
                } catch (Exception unused) {
                    return;
                }
            }
            String action = intent.getAction();
            String str = Ob1G5CollectionService.TAG;
            UserError.Log.d(str, "BondState: onReceive ACTION: " + action);
            if ("android.bluetooth.device.action.BOND_STATE_CHANGED".equals(action)) {
                BluetoothDevice bluetoothDevice = (BluetoothDevice) intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
                Ob1G5CollectionService.this.currentBondState = bluetoothDevice.getBondState();
                int intExtra = intent.getIntExtra("android.bluetooth.device.extra.BOND_STATE", -1);
                UserError.Log.e(str, "onReceive UPDATE Name " + bluetoothDevice.getName() + " Value " + bluetoothDevice.getAddress() + " Bond state " + bluetoothDevice.getBondState() + G5BaseService.bondState(bluetoothDevice.getBondState()) + " bs: " + G5BaseService.bondState(intExtra) + " was " + G5BaseService.bondState(intent.getIntExtra("android.bluetooth.device.extra.PREVIOUS_BOND_STATE", -1)));
                try {
                    if (bluetoothDevice.getAddress().equals(Ob1G5CollectionService.transmitterMAC)) {
                        Ob1G5CollectionService.msg(G5BaseService.bondState(intExtra).replace(" ", ""));
                        if (bluetoothDevice.getBondState() == 12) {
                            if (Ob1G5CollectionService.this.waitingBondConfirmation == 1) {
                                Ob1G5CollectionService.this.waitingBondConfirmation = 2;
                                UserError.Log.e(str, "Bond confirmation received!");
                                UserError.Log.d(str, "Sleeping before create bond");
                                try {
                                    Thread.sleep(1000L);
                                } catch (InterruptedException unused2) {
                                }
                                Ob1G5CollectionService.this.instantCreateBondIfAllowed();
                            }
                            if (Ob1G5CollectionService.this.weInitiatedBondConfirmation == 1) {
                                Ob1G5CollectionService.this.weInitiatedBondConfirmation = 2;
                                Ob1G5CollectionService.this.changeState(STATE.GET_DATA);
                                return;
                            }
                            return;
                        }
                        if (bluetoothDevice.getBondState() != 11 || Build.VERSION.SDK_INT < 26) {
                            return;
                        }
                        JoH.playResourceAudio(2131689473);
                        UserError.Log.uel(str, "Prompting user to notice pairing request with sound - On Android 8+ you have to manually pair when requested");
                    }
                } catch (Exception e) {
                    UserError.Log.e(Ob1G5CollectionService.TAG, "Got exception trying to process bonded confirmation: ", e);
                }
            }
        }
    };
    private final BroadcastReceiver mPairingRequestRecevier = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Ob1G5CollectionService.keep_running) {
                if (Ob1G5CollectionService.this.bleDevice != null && Ob1G5CollectionService.this.bleDevice.getBluetoothDevice().getAddress() != null) {
                    String str = Ob1G5CollectionService.TAG;
                    UserError.Log.e(str, "Processing mPairingRequestReceiver !!!");
                    JoH.releaseWakeLock(Ob1G5CollectionService.this.fullWakeLock);
                    Ob1G5CollectionService.this.fullWakeLock = JoH.fullWakeLock("pairing-screen-wake", 30000L);
                    if (!Ob1G5CollectionService.android_wear) {
                        Home.startHomeWithExtra(context, "HOME_FULL_WAKEUP", "1");
                    }
                    if (JoH.doPairingRequest(context, this, intent, Ob1G5CollectionService.this.bleDevice.getBluetoothDevice().getAddress()) || Ob1G5CollectionService.android_wear) {
                        return;
                    }
                    Ob1G5CollectionService.this.unregisterPairingReceiver();
                    UserError.Log.e(str, "Pairing failed so removing pairing automation");
                    return;
                }
                UserError.Log.e(Ob1G5CollectionService.TAG, "Received pairing request but device was null !!!");
                return;
            }
            try {
                UserError.Log.e(Ob1G5CollectionService.TAG, "Rogue pairing request receiver still active - unregistering");
                Ob1G5CollectionService ob1G5CollectionService = Ob1G5CollectionService.this;
                ob1G5CollectionService.unregisterReceiver(ob1G5CollectionService.mPairingRequestRecevier);
            } catch (Exception unused) {
            }
        }
    };
    public final SharedPreferences.OnSharedPreferenceChangeListener prefListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String str) {
            Ob1G5CollectionService.this.checkPreferenceKey(str, sharedPreferences);
        }
    };

    private boolean getInitiateBondingFlag() {
        return true;
    }

    public static void setLast_transmitter_timestamp(long j) {
        last_transmitter_timestamp = j;
    }

    public static long getLast_transmitter_timestamp() {
        return last_transmitter_timestamp;
    }

    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"),
        UNBOND("UnBonding"),
        RESET("Reseting"),
        GET_DATA("Getting Data"),
        CLOSE("Sleeping"),
        CLOSED("Deep Sleeping");

        private String str;

        STATE(String str) {
            this.str = str;
        }

        public String getString() {
            return this.str;
        }
    }

    public void authResult(boolean z) {
        auth_succeeded = z;
    }

    private synchronized void backoff_automata() {
        background_automata(this.error_backoff_ms);
        int i = this.error_backoff_ms;
        if (i < 10000) {
            this.error_backoff_ms = i + 100;
        }
    }

    public void background_automata() {
        background_automata(100);
    }

    public synchronized void background_automata(final int i) {
        if (this.background_launch_waiting) {
            UserError.Log.d(TAG, "Blocked by existing background automata pending");
            return;
        }
        final PowerManager.WakeLock wakeLock = JoH.getWakeLock("jam-g5-background", i + 5000);
        this.background_launch_waiting = true;
        new Thread(new Runnable() {
            @Override
            public final void run() {
                Ob1G5CollectionService.this.lambda$background_automata$0(i, wakeLock);
            }
        }).start();
    }

    public void lambda$background_automata$0(int i, PowerManager.WakeLock wakeLock) {
        JoH.threadSleep(i);
        this.background_launch_waiting = false;
        automata();
        JoH.releaseWakeLock(wakeLock);
    }

    private static boolean specialPairingWorkaround() {
        return Pref.getBooleanDefaultFalse("ob1_special_pairing_workaround");
    }

    private static boolean getTrustAutoConnect() {
        return Pref.getBoolean("bluetooth_trust_autoconnect", true);
    }

    private synchronized void automata() {
        PowerManager.WakeLock wakeLock;
        try {
            if (last_automata_state == state && state != STATE.INIT && !JoH.ratelimit("jam-g5-dupe-auto", 2)) {
                UserError.Log.d(TAG, "Ignoring duplicate automata state within 2 seconds: " + state);
            }
            boolean z = true;
            switch (AnonymousClass7.$SwitchMap$com$eveningoutpost$dexdrip$services$Ob1G5CollectionService$STATE[state.ordinal()]) {
                case 1:
                    initialize();
                    break;
                case 2:
                    if (JoH.msSince(static_last_connected) > 1800000 && JoH.pratelimit("ob1-collector-restart", 1200)) {
                        CollectionServiceStarter.restartCollectionServiceBackground();
                        break;
                    } else if (useMinimizeScanningStrategy()) {
                        UserError.Log.d(TAG, "Skipping Scanning! : Changing state due to minimize_scanning flags");
                        changeState(STATE.CONNECT_NOW);
                        break;
                    } else {
                        scan_for_device();
                        break;
                    }
                    break;
                case 3:
                    if (specialPairingWorkaround()) {
                        boolean isDeviceLocallyBonded = isDeviceLocallyBonded();
                        String str = TAG;
                        UserError.Log.d(str, "wasbonded = " + wasBonded + " local: " + isDeviceLocallyBonded);
                        if (wasBonded.equals(getTransmitterID()) && !isDeviceLocallyBonded && skippedConnects < 10) {
                            skippedConnects++;
                            UserError.Log.wtf(str, "Appears to have lost bonding, skipping this connect! @ " + skippedConnects);
                            changeState(STATE.CLOSE);
                            break;
                        } else {
                            wasBonded = isDeviceLocallyBonded ? getTransmitterID() : "";
                            skippedConnects = 0;
                            if (!specialPairingWorkaround() || !getTrustAutoConnect()) {
                                z = false;
                            }
                            connect_to_device(z);
                            break;
                        }
                    } else {
                        connect_to_device(false);
                        break;
                    }
                case 4:
                    connect_to_device(true);
                    break;
                case 5:
                    if ((wear_broadcast && Ob1G5StateMachine.usingAlt()) || specialPairingWorkaround()) {
                        msg("Pausing");
                        UserError.Log.d(TAG, "Pausing for alt: ");
                        JoH.threadSleep(1000L);
                    }
                    if (do_discovery) {
                        discover_services();
                        break;
                    } else {
                        UserError.Log.d(TAG, "Skipping discovery");
                        changeState(STATE.CHECK_AUTH);
                        break;
                    }
                    break;
                case 6:
                    JoH.getWakeLock("jam-g5-check-linger", 6000);
                    if (this.plugin != null) {
                        if (!Ob1G5StateMachine.doCheckAuth2(this, this.connection)) {
                            resetState();
                            break;
                        }
                    } else if (!Ob1G5StateMachine.doCheckAuth(this, this.connection)) {
                        resetState();
                        break;
                    }
                    break;
                case 7:
                    if (!getInitiateBondingFlag()) {
                        JoH.getWakeLock("jam-g5-prebond-linger", 16000);
                        if (!Ob1G5StateMachine.doKeepAliveAndBondRequest(this, this.connection)) {
                            resetState();
                            break;
                        }
                    } else {
                        UserError.Log.d(TAG, "Going directly to initiate bond");
                        changeState(STATE.BOND);
                        break;
                    }
                    break;
                case 8:
                    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 9:
                    UserError.Log.d(TAG, "Unbond state");
                    Ob1G5StateMachine.doUnBond(this, this.connection);
                    Inevitable.task("unbond close", 10000L, new Runnable() {
                        @Override
                        public final void run() {
                            Ob1G5CollectionService.this.lambda$automata$1();
                        }
                    });
                    break;
                case 10:
                    UserError.Log.d(TAG, "Entering hard reset state");
                    Ob1G5StateMachine.doReset(this, this.connection);
                    break;
                case 11:
                    if (G5BaseService.hardResetTransmitterNow) {
                        send_reset_command();
                        DexSyncKeeper.clear(transmitterID);
                        break;
                    } else {
                        JoH.getWakeLock("jam-g5-get-linger", 6000);
                        if (!Ob1G5StateMachine.doGetData(this, this.connection)) {
                            resetState();
                            break;
                        }
                    }
                    break;
                case 12:
                    prepareToWakeup();
                    break;
                case 13:
                    handleWakeup();
                    break;
            }
        } finally {
            JoH.releaseWakeLock(wakeLock);
        }
        last_automata_state = state;
        wakeLock = JoH.getWakeLock("jam-g5-automata", UsbId.SILABS_CP2102);
    }

    public void lambda$automata$1() {
        changeState(STATE.CLOSE);
    }

    private boolean useMinimizeScanningStrategy() {
        boolean z;
        tryLoadingSavedMAC();
        int i = (connectNowFailures + scanTimeouts) % 2;
        String str = TAG;
        UserError.Log.d(str, "minimize: " + minimize_scanning + " mac: " + transmitterMAC + " lastfailed:" + lastConnectFailed + " nowfail:" + connectNowFailures + " stimeout:" + scanTimeouts + " modulo:" + i);
        if (WholeHouse.isLive()) {
            estimateAnticipateFromLinkedData();
            z = !preScanFailureMarker;
        } else {
            z = false;
        }
        if (!z) {
            z = Pref.getBooleanDefaultFalse("ob1_avoid_scanning");
            if (z && !JoH.upForAtLeastMins(15)) {
                UserError.Log.d(str, "Not avoiding scanning as phone has recently rebooted and clock may be inaccurate");
                z = false;
            }
            if (z && connectNowFailures > 4 && connectNowFailures % 10 == 1) {
                UserError.Log.d(str, "Not avoiding scanning due to connect failure level: " + connectNowFailures);
                connectNowFailures = connectNowFailures + 1;
                z = false;
            }
        }
        if (transmitterMAC == null) {
            UserError.Log.d(str, "Do not know transmitter mac inside minimize scanning!!");
        }
        return minimize_scanning && transmitterMAC != null && (!lastConnectFailed || i == 1 || z) && DexSyncKeeper.isReady(transmitterID);
    }

    private void estimateAnticipateFromLinkedData() {
        BgReading last = BgReading.last();
        if (last == null || last.timestamp <= static_last_connected || JoH.msSince(last.timestamp) >= 10800000) {
            return;
        }
        long j = last.timestamp - 1000;
        UserError.Log.d(TAG, "Updating Sync Keeper with network learned timestamp: " + JoH.dateTimeText(j));
        DexSyncKeeper.store(transmitterID, j);
    }

    private void resetState() {
        UserError.Log.e(TAG, "Resetting sequence state to INIT");
        changeState(STATE.INIT);
    }

    public STATE getState() {
        return state;
    }

    public void changeState(STATE state2) {
        if (shouldServiceRun()) {
            changeState(state2, 100);
        } else {
            UserError.Log.d(TAG, "Stopping service due to having being disabled in preferences");
            stopSelf();
        }
    }

    public void changeState(STATE state2, int i) {
        if ((state == STATE.CLOSED || state == STATE.CLOSE) && state2 == STATE.CLOSE) {
            UserError.Log.d(TAG, "Not closing as already closed");
            return;
        }
        UserError.Log.d(TAG, "Changing state from: " + state + " to " + state2);
        state = state2;
        if (android_wear && wear_broadcast) {
            msg(state2.toString());
        }
        background_automata(i);
    }

    private synchronized void initialize() {
        if (state == STATE.INIT) {
            msg("Initializing");
            static_connection_state = null;
            if (rxBleClient == null) {
                rxBleClient = RxBleProvider.getSingleton();
            }
            init_tx_id();
            changeState(STATE.SCAN);
        } else {
            UserError.Log.wtf(TAG, "Attempt to initialize when not in INIT state");
        }
    }

    private static void init_tx_id() {
        String string = Pref.getString("dex_txid", "NULL");
        String trim = string.trim();
        transmitterID = trim;
        if (string.equals(trim)) {
            return;
        }
        Pref.setString("dex_txid", trim);
        UserError.Log.wtf(TAG, "Had to fix invalid txid: :" + string + ": -> :" + trim + ":");
    }

    private synchronized void scan_for_device() {
        throw new UnsupportedOperationException("Method not decompiled: com.eveningoutpost.dexdrip.services.Ob1G5CollectionService.scan_for_device():void");
    }

    public void stopScanWithTimeoutAndReschedule() {
        stopScan();
        UserError.Log.d(TAG, "Stopped scan due to timeout at: " + JoH.dateTimeText(JoH.tsl()));
        scanTimeouts = scanTimeouts + 1;
        tryLoadingSavedMAC();
        prepareToWakeup();
    }

    private synchronized void connect_to_device(boolean z) {
        if (state != STATE.CONNECT && state != STATE.CONNECT_NOW) {
            UserError.Log.wtf(TAG, "Attempt to connect when not in CONNECT state");
        }
        if (transmitterMAC == null) {
            tryLoadingSavedMAC();
        }
        String str = transmitterMAC;
        if (str != null) {
            if (inPurdah()) {
                msg("Purdah " + JoH.niceTimeScalar(purdahMs()));
                changeState(STATE.CLOSE);
                return;
            }
            msg("Connect request");
            if (state == STATE.CONNECT_NOW) {
                PowerManager.WakeLock wakeLock = this.connection_linger;
                if (wakeLock != null) {
                    JoH.releaseWakeLock(wakeLock);
                }
                this.connection_linger = JoH.getWakeLock("jam-g5-pconnect", UsbId.SILABS_CP2102);
            }
            stopConnect();
            try {
                RxBleDevice bleDevice = rxBleClient.getBleDevice(str);
                this.bleDevice = bleDevice;
                stateSubscription = new Subscription(bleDevice.observeConnectionStateChanges().subscribeOn(Schedulers.io()).doFinally(new Action() {
                    public final void run() {
                        Ob1G5CollectionService.this.releaseFloating();
                    }
                }).subscribe(new Consumer() {
                    public final void accept(Object obj) {
                        Ob1G5CollectionService.this.onConnectionStateChange((RxBleConnection.RxBleConnectionState) obj);
                    }
                }, new Consumer() {
                    public final void accept(Object obj) {
                        Ob1G5CollectionService.lambda$connect_to_device$2((Throwable) obj);
                    }
                }));
                last_connect_started = JoH.tsl();
                UserError.Log.d(TAG, "Connecting with auto: " + z);
                connectionSubscription = new Subscription(this.bleDevice.establishConnection(z).timeout(7L, TimeUnit.MINUTES).subscribeOn(Schedulers.io()).subscribe(new Consumer() {
                    public final void accept(Object obj) {
                        Ob1G5CollectionService.this.onConnectionReceived((RxBleConnection) obj);
                    }
                }, new Consumer() {
                    public final void accept(Object obj) {
                        Ob1G5CollectionService.this.onConnectionFailure((Throwable) obj);
                    }
                }));
            } catch (IllegalArgumentException e) {
                UserError.Log.e(TAG, "Caught IllegalArgument Exception: " + e + " retry on next run");
                state = STATE.SCAN;
                backoff_automata();
            }
        } else {
            UserError.Log.wtf(TAG, "No transmitter mac address!");
            state = STATE.SCAN;
            backoff_automata();
        }
    }

    public static void lambda$connect_to_device$2(Throwable th) throws Exception {
        UserError.Log.wtf(TAG, "Got Error from state subscription: " + th);
    }

    private synchronized void discover_services() {
        if (state == STATE.DISCOVER) {
            if (this.connection != null) {
                stopDiscover();
                this.discoverSubscription = new Subscription(this.connection.discoverServices(10L, TimeUnit.SECONDS).subscribe(new Consumer() {
                    public final void accept(Object obj) {
                        Ob1G5CollectionService.this.onServicesDiscovered((RxBleDeviceServices) obj);
                    }
                }, new Consumer() {
                    public final void accept(Object obj) {
                        Ob1G5CollectionService.this.onDiscoverFailed((Throwable) obj);
                    }
                }));
            } else {
                UserError.Log.e(TAG, "No connection when in DISCOVER state - reset");
                state = STATE.INIT;
                background_automata();
            }
        } else {
            UserError.Log.wtf(TAG, "Attempt to discover when not in DISCOVER state");
        }
    }

    @TargetApi(19)
    private synchronized void create_bond() {
        if (state == STATE.BOND) {
            try {
                msg("Bonding");
                do_create_bond();
                DexSyncKeeper.clear(getTransmitterID());
            } 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 r2) {
        throw new UnsupportedOperationException("Method not decompiled: com.eveningoutpost.dexdrip.services.Ob1G5CollectionService.reset_bond(boolean):void");
    }

    private synchronized void do_create_bond() {
        boolean isDeviceLocallyBonded = isDeviceLocallyBonded();
        String str = TAG;
        StringBuilder sb = new StringBuilder();
        sb.append("Attempting to create bond, device is : ");
        sb.append(isDeviceLocallyBonded ? "BONDED" : "NOT Bonded");
        UserError.Log.d(str, sb.toString());
        if (isDeviceLocallyBonded && getInitiateBondingFlag()) {
            UserError.Log.e(str, "Device is marked as bonded but we are being asked to bond so attempting to unbond first");
            unbondIfAllowed();
            changeState(STATE.CLOSE);
        } else {
            try {
                if (transmitterID.length() > 4) {
                    Ob1G5StateMachine.doKeepAlive(this, this.connection, new Runnable() {
                        @Override
                        public final void run() {
                            Ob1G5CollectionService.this.startInitiateBondReal();
                        }
                    });
                } else {
                    startInitiateBondReal();
                }
            } catch (Exception e) {
                UserError.Log.wtf(TAG, "Got exception in do_create_bond() " + e);
            }
        }
    }

    public void startInitiateBondReal() {
        try {
            this.weInitiatedBondConfirmation = 1;
            instantCreateBondIfAllowed();
        } catch (Exception e) {
            UserError.Log.wtf(TAG, "Got exception in startInitiateBondReal() " + e);
        }
    }

    private synchronized void send_reset_command() {
        G5BaseService.hardResetTransmitterNow = false;
        G5BaseService.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() {
        if (transmitterID == null || transmitterID.length() <= 4) {
            return null;
        }
        return "Dexcom" + G5BaseService.getLastTwoCharacters(transmitterID);
    }

    public static String getMac() {
        return transmitterMAC;
    }

    private void tryLoadingSavedMAC() {
        if (transmitterMAC == null || !transmitterIDmatchingMAC.equals(transmitterID)) {
            if (transmitterID != null) {
                String string = PersistentStore.getString("G5-mac-for-txid-" + transmitterID);
                if (string.length() == 17) {
                    UserError.Log.d(TAG, "Loaded stored MAC for: " + transmitterID + " " + string);
                    transmitterMAC = string;
                    transmitterIDmatchingMAC = transmitterID;
                    return;
                }
                UserError.Log.d(TAG, "Did not find any saved MAC for: " + transmitterID);
                return;
            }
            UserError.Log.e(TAG, "Could not load saved mac as transmitter id isn't set!");
            return;
        }
        UserError.Log.d(TAG, "MAC for transmitter id already populated: " + transmitterID + " " + transmitterMAC);
    }

    private static boolean shouldServiceRun() {
        if (!Pref.getBooleanDefaultFalse("use_ob1_g5_collector_service") || DexCollectionType.getDexCollectionType() != DexCollectionType.DexcomG5) {
            return false;
        }
        if (android_wear) {
            return PersistentStore.getBoolean("run_wear_collector");
        }
        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()) {
            return true;
        }
        UserError.Log.d(TAG, "Not running as BlueJay is collector");
        return false;
    }

    public static synchronized boolean isDeviceLocallyBonded() {
        synchronized (Ob1G5CollectionService.class) {
            if (transmitterMAC == null) {
                return false;
            }
            Set<RxBleDevice> bondedDevices = rxBleClient.getBondedDevices();
            if (bondedDevices != null && bondedDevices.size() > 0) {
                for (RxBleDevice rxBleDevice : bondedDevices) {
                    if (rxBleDevice.getMacAddress() != null && rxBleDevice.getMacAddress().equals(transmitterMAC)) {
                        return true;
                    }
                }
            }
            return false;
        }
    }

    public static boolean immediateBonding() {
        return Pref.getBooleanDefaultFalse("engineering_ob1_bonding_test") || BlueJayEntry.isNative();
    }

    public static boolean ignoreBonding() {
        return Pref.getBooleanDefaultFalse("engineering_ob1_ignore_bonding");
    }

    private byte[] fwChalCache(boolean z) {
        StringBuilder sb = new StringBuilder();
        sb.append("engineering_ob1_chal_cache");
        sb.append(z ? "_1" : "");
        long j = Pref.getLong(sb.toString(), 0L);
        if (j == 0 || !Ob1G5StateMachine.shortTxId()) {
            return new byte[0];
        }
        byte[] bArr = new byte[8];
        for (int i = 0; i < 8; i++) {
            bArr[i] = (byte) (j >> (((8 - i) - 1) * 8));
        }
        return bArr;
    }

    private synchronized void checkAndEnableBT() {
        try {
            if (Pref.getBoolean("automatically_turn_bluetooth_on", true) && !((BluetoothManager) getSystemService("bluetooth")).getAdapter().isEnabled() && 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;
        }
        Set<BluetoothDevice> bondedDevices = ((BluetoothManager) getSystemService("bluetooth")).getAdapter().getBondedDevices();
        if (bondedDevices.size() > 0) {
            for (BluetoothDevice bluetoothDevice : bondedDevices) {
                if (bluetoothDevice.getAddress() != null && bluetoothDevice.getAddress().equals(transmitterMAC)) {
                    try {
                        UserError.Log.e(TAG, "removingBond: " + transmitterMAC);
                        bluetoothDevice.getClass().getMethod("removeBond", null).invoke(bluetoothDevice, null);
                        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(STATE.SCAN);
            return;
        }
        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(STATE.SCAN);
            return;
        }
        if (use_auto_connect && connectNowFailures > 1 && connectFailures < 0) {
            UserError.Log.d(TAG, "Avoiding power connect due to failure metric: " + connectNowFailures + " " + connectFailures);
            changeState(STATE.CONNECT);
            return;
        }
        changeState(STATE.CONNECT_NOW);
    }

    private synchronized void prepareToWakeup() {
        if (JoH.ratelimit("g5-wakeup-timer", 5)) {
            long anticipate = DexSyncKeeper.anticipate(transmitterID);
            if (anticipate > 0) {
                long tsl = anticipate - JoH.tsl();
                UserError.Log.d(TAG, "(" + JoH.dateTimeText(JoH.tsl()) + ")  Wake up time anticipated at: " + JoH.dateTimeText(anticipate));
                scheduleWakeUp(tsl - 15000, "anticipate");
            } else {
                scheduleWakeUp(285000L, "anticipate");
            }
        }
        if ((android_wear && wakeup_jitter > 10000) || always_connect) {
            String str = TAG;
            StringBuilder sb = new StringBuilder();
            sb.append("Not stopping connect due to ");
            sb.append(always_connect ? "always_connect flag" : "unreliable wake up");
            UserError.Log.d(str, sb.toString());
            state = STATE.CONNECT;
            background_automata(6000);
        } else {
            state = STATE.CLOSED;
            stopConnect();
        }
        if (this.plugin != null) {
            UserError.Log.d(TAG, "Saving persistent data for keks");
            savePersist();
        }
    }

    public synchronized void savePersist() {
        if (this.plugin != null) {
            PersistentStore.cleanupOld("keks1_");
            PersistentStore.setBytes("keks1_" + transmitterMAC, this.plugin.getPersistence(1));
        }
    }

    public static void clearPersistStore() {
        PersistentStore.cleanupOld("keks1_");
        PersistentStore.cleanupOld("G5-mac-for-txid-");
    }

    public static void clearPersist() {
        clearPersistStore();
        expireFailures(true);
        transmitterID = null;
        transmitterMAC = null;
    }

    private void scheduleWakeUp(long j, String str) {
        if (j <= 0) {
            j = 5000;
        }
        UserError.Log.d(TAG, "Scheduling wakeup @ " + JoH.dateTimeText(JoH.tsl() + j) + " (" + str + ")");
        if (pendingIntent == null) {
            pendingIntent = WakeLockTrampoline.getPendingIntent(getClass());
        }
        wakeup_time = JoH.tsl() + j;
        JoH.wakeUpIntent(this, j, pendingIntent);
    }

    public void incrementErrors() {
        error_count++;
        if (error_count > 1) {
            UserError.Log.e(TAG, "Error count reached: " + error_count);
        }
    }

    public int incrementRetry() {
        retry_count++;
        return retry_count;
    }

    public void clearErrors() {
        error_count = 0;
    }

    public void clearRetries() {
        retry_count = 0;
    }

    private void checkAlwaysScanModels() {
        String str = Build.MODEL;
        String str2 = TAG;
        UserError.Log.d(str2, "Checking model: " + str);
        if (JoH.isSamsung() && PersistentStore.getLong("buggy-samsung-enabled") > 4) {
            UserError.Log.d(str2, "Enabling wake workaround due to persistent metric");
            JoH.buggy_samsung = true;
        }
        always_connect = alwaysConnectModels.contains(str);
        if (alwaysBuggyWakeupModels.contains(str)) {
            UserError.Log.e(str2, "Always buggy wakeup exact match for " + str);
            JoH.buggy_samsung = true;
        }
        if (alwaysScanModels.contains(str)) {
            UserError.Log.e(str2, "Always scan model exact match for: " + str);
            always_scan = true;
            return;
        }
        Iterator<String> it = alwaysScanModelFamilies.iterator();
        while (it.hasNext()) {
            if (str.startsWith(it.next())) {
                UserError.Log.e(TAG, "Always scan model fuzzy match for: " + str);
                always_scan = true;
                return;
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        try {
            registerReceiver(this.mBondStateReceiver, new IntentFilter("android.bluetooth.device.action.BOND_STATE_CHANGED"));
        } catch (Exception e) {
            UserError.Log.e(TAG, "Could not register bond state receiver: " + e);
        }
        IntentFilter intentFilter = new IntentFilter("android.bluetooth.device.action.PAIRING_REQUEST");
        intentFilter.setPriority(999);
        try {
            if (Build.VERSION.SDK_INT < 26) {
                registerReceiver(this.mPairingRequestRecevier, intentFilter);
            } else {
                UserError.Log.d(TAG, "Not registering pairing receiver on Android 8+");
            }
        } catch (Exception e2) {
            UserError.Log.e(TAG, "Could not register pairing request receiver:" + e2);
        }
        checkAlwaysScanModels();
        boolean areWeRunningOnAndroidWear = JoH.areWeRunningOnAndroidWear();
        android_wear = areWeRunningOnAndroidWear;
        if (areWeRunningOnAndroidWear) {
            UserError.Log.d(TAG, "We are running on Android Wear");
            wear_broadcast = Pref.getBooleanDefaultFalse("ob1_wear_broadcast");
        }
        Subscription.addErrorHandler(TAG);
        listenForChangeInSettings(true);
    }

    @Override
    public int onStartCommand(Intent intent, int i, int i2) {
        xdrip.checkAppContext(getApplicationContext());
        PowerManager.WakeLock wakeLock = JoH.getWakeLock("g5-start-service", 310000);
        try {
            String str = TAG;
            UserError.Log.d(str, "WAKE UP WAKE UP WAKE UP WAKE UP @ " + JoH.dateTimeText(JoH.tsl()));
            msg("Wake up");
            long j = wakeup_time;
            if (j > 0) {
                long msSince = JoH.msSince(j);
                wakeup_jitter = msSince;
                if (msSince < 0) {
                    UserError.Log.d(str, "Woke up Early..");
                } else if (msSince > 1000) {
                    UserError.Log.d(str, "Wake up, time jitter: " + JoH.niceTimeScalar(wakeup_jitter));
                    if (wakeup_jitter > 10000 && !JoH.buggy_samsung && JoH.isSamsung()) {
                        UserError.Log.wtf(str, "Enabled wake workaround due to jitter of: " + JoH.niceTimeScalar(wakeup_jitter));
                        JoH.buggy_samsung = true;
                        PersistentStore.incrementLong("buggy-samsung-enabled");
                        max_wakeup_jitter = 0L;
                    } else {
                        max_wakeup_jitter = Math.max(max_wakeup_jitter, wakeup_jitter);
                    }
                }
            }
            if (!shouldServiceRun()) {
                UserError.Log.d(str, "Stopping service due to shouldServiceRun() result");
                msg("Stopping");
                stopSelf();
                JoH.releaseWakeLock(wakeLock);
                return 2;
            }
            scheduleWakeUp(360000L, "fail-over");
            if (state == STATE.BOND || state == STATE.PREBOND || state == STATE.DISCOVER || state == STATE.CONNECT) {
                state = STATE.SCAN;
            }
            checkAndEnableBT();
            Ob1G5StateMachine.restoreQueue();
            if (JoH.quietratelimit("evaluateG6Settings", 600)) {
                Ob1G5StateMachine.evaluateG6Settings();
            }
            minimize_scanning = Pref.getBooleanDefaultFalse("ob1_minimize_scanning");
            automata();
            UserError.Log.d(str, "Releasing service start");
            return 1;
        } finally {
            JoH.releaseWakeLock(wakeLock);
        }
    }

    @Override
    public void onDestroy() {
        msg("Shutting down");
        if (pendingIntent != null) {
            JoH.cancelAlarm(this, pendingIntent);
            pendingIntent = null;
            wakeup_time = 0L;
        }
        stopScan();
        stopDiscover();
        stopConnect();
        scanSubscription = null;
        connectionSubscription = null;
        stateSubscription = null;
        this.discoverSubscription = null;
        listenForChangeInSettings(false);
        unregisterPairingReceiver();
        try {
            unregisterReceiver(this.mBondStateReceiver);
        } catch (Exception e) {
            UserError.Log.e(TAG, "Got exception unregistering pairing receiver: " + e);
        }
        state = STATE.INIT;
        last_automata_state = STATE.CLOSED;
        msg("Service Stopped");
        super.onDestroy();
    }

    public void unregisterPairingReceiver() {
        try {
            unregisterReceiver(this.mPairingRequestRecevier);
        } catch (Exception e) {
            UserError.Log.d(TAG, "Got exception unregistering pairing receiver: " + e);
        }
    }

    private synchronized void stopScan() {
        if (scanSubscription != null) {
            scanSubscription.unsubscribe();
        }
        UserError.Log.d(TAG, "DEBUG: killing stop scan task");
        Inevitable.kill("ob1-g5-scan-timeout_scan");
        if (this.scanWakeLock != null) {
            JoH.releaseWakeLock(this.scanWakeLock);
        }
        last_scan_started = 0L;
    }

    private synchronized void stopConnect() {
        if (connectionSubscription != null) {
            connectionSubscription.unsubscribe();
        }
        if (stateSubscription != null) {
            stateSubscription.unsubscribe();
        }
    }

    private synchronized void stopDiscover() {
        Subscription subscription = this.discoverSubscription;
        if (subscription != null) {
            subscription.unsubscribe();
        }
    }

    private boolean isScanMatch(String str, String str2, String str3, String str4) {
        boolean z = true;
        if (str4 == null && (str.equalsIgnoreCase(str2) || str3 == null || ((JoH.emptyString(str2) && str3.startsWith("DXCM")) || ((JoH.emptyString(str2) && str3.startsWith("DX02")) || (JoH.emptyString(str2) && str3.startsWith("DX01")))))) {
            return !inFailureTally(str);
        }
        if (!str.equalsIgnoreCase(str2) && (str3 == null || !str3.equalsIgnoreCase(str4))) {
            z = false;
        }
        if (!z || str2.length() != str.length() || str.equalsIgnoreCase(str2)) {
            return z;
        }
        if (!JoH.ratelimit("ob1-address-change-error", 30)) {
            return false;
        }
        UserError.Log.wtf(TAG, "Bluetooth device: " + str4 + " apparently changed from mac: " + str2 + " to: " + str + " :: There appears to be confusion between devices - ignoring this scan result");
        return false;
    }

    public static void clearScanError() {
        lastScanError = null;
    }

    public synchronized void onScanResult(ScanResult scanResult) {
        int rssi = scanResult.getRssi();
        String name = scanResult.getBleDevice().getName();
        String macAddress = scanResult.getBleDevice().getMacAddress();
        String transmitterBluetoothName = getTransmitterBluetoothName();
        scanResult.getScanRecord().getManufacturerSpecificData(208);
        if (isScanMatch(macAddress, historicalTransmitterMAC, name, transmitterBluetoothName)) {
            stopScan();
            last_scan_started = 0L;
            lastScanError = null;
            String str = TAG;
            UserError.Log.d(str, "Got scan result match: " + scanResult.getBleDevice().getName() + " " + macAddress + " rssi: " + rssi);
            transmitterMAC = scanResult.getBleDevice().getMacAddress();
            transmitterIDmatchingMAC = transmitterID;
            if (transmitterBluetoothName != null) {
                saveTransmitterMac();
            }
            if (state == STATE.SCAN) {
                changeState(STATE.CONNECT_NOW, 500);
            } else {
                UserError.Log.e(str, "Skipping apparent duplicate connect transition, current state = " + state);
            }
        } else {
            String macAddress2 = scanResult.getBleDevice().getMacAddress();
            if (macAddress2 == null) {
                macAddress2 = "NULL";
            }
            if (JoH.quietratelimit("bt-obi1-null-match" + macAddress2, 15)) {
                UserError.Log.d(TAG, "Bluetooth scanned device doesn't match (" + transmitterBluetoothName + ") found: " + name + " " + scanResult.getBleDevice().getMacAddress());
            }
        }
    }

    public void saveTransmitterMac() {
        UserError.Log.d(TAG, "Saving transmitter mac: " + transmitterID + " = " + transmitterMAC);
        PersistentStore.cleanupOld("G5-mac-for-txid-");
        StringBuilder sb = new StringBuilder();
        sb.append("G5-mac-for-txid-");
        sb.append(transmitterID);
        PersistentStore.setString(sb.toString(), transmitterMAC);
    }

    public synchronized void onScanFailure(Throwable th) {
        if (th instanceof BleScanException) {
            lastScanException = ((BleScanException) th).getReason();
            String handleBleScanException = handleBleScanException((BleScanException) th);
            lastScanError = handleBleScanException;
            String str = TAG;
            UserError.Log.d(str, handleBleScanException);
            int reason = ((BleScanException) th).getReason();
            if (reason == 7 && allow_scan_by_mac && this.lastWasScanByMac) {
                allow_scan_by_mac = false;
                UserError.Log.wtf(str, "Turning scan by by mac off");
                if (JoH.ratelimit("bluetooth-internal-error-register", R$styleable.AppCompatTheme_windowFixedWidthMajor)) {
                    if (Pref.getBooleanDefaultFalse("automatically_turn_bluetooth_on")) {
                        UserError.Log.wtf(str, "Android bluetooth appears broken with scan by mac - attempting to turn off and on");
                        JoH.niceRestartBluetooth(xdrip.getAppContext());
                    } else {
                        UserError.Log.e(str, "Cannot reset bluetooth due to preference being disabled");
                    }
                }
            }
            if (reason == 6 && JoH.ratelimit("bluetooth-cannot-register", R$styleable.AppCompatTheme_windowFixedWidthMajor)) {
                if (Pref.getBooleanDefaultFalse("automatically_turn_bluetooth_on")) {
                    UserError.Log.wtf(str, "Android bluetooth appears broken - attempting to turn off and on");
                    JoH.niceRestartBluetooth(xdrip.getAppContext());
                } else {
                    UserError.Log.e(str, "Cannot reset bluetooth due to preference being disabled");
                }
            }
            if (reason == 1 && JoH.ratelimit("bluetooth_toggle_on", 30)) {
                UserError.Log.d(str, "Pause before Turn Bluetooth on");
                try {
                    Thread.sleep(2000L);
                } catch (InterruptedException unused) {
                }
                if (WholeHouse.isRpi()) {
                    UserError.Log.e(TAG, "Trying to turn off/on bluetooth");
                    JoH.niceRestartBluetooth(xdrip.getAppContext());
                } else {
                    UserError.Log.e(TAG, "Trying to Turn Bluetooth on");
                    JoH.setBluetoothEnabled(xdrip.getAppContext(), true);
                }
            }
            stopScan();
            if (minimize_scanning) {
                UserError.Log.d(TAG, "Preparing to wake up at next expected time");
                prepareToWakeup();
            } else {
                backoff_automata();
            }
        }
    }

    private void unbondIfAllowed() {
        if (Pref.getBoolean("ob1_g5_allow_resetbond", true)) {
            unBond();
        } else {
            UserError.Log.e(TAG, "Would have tried to unpair but preference setting prevents it. (unbond)");
        }
    }

    private boolean resetBondIfAllowed(boolean z) {
        if (Pref.getBoolean("ob1_g5_allow_resetbond", false) && !specialPairingWorkaround()) {
            reset_bond(z);
            return true;
        }
        UserError.Log.w(TAG, "Would have tried to unpair but preference setting prevents it. (resetbond) Allow OB1 unbonding setting and disable pairing workaround");
        return false;
    }

    public void onConnectionFailure(Throwable th) {
        String str = TAG;
        UserError.Log.d(str, "Connection Disconnected/Failed: " + th);
        if (state == STATE.DISCOVER) {
            if (resetBondIfAllowed(false) || !android_wear) {
                return;
            }
            UserError.Log.d(str, "Trying alternate reconnection strategy");
            changeState(STATE.CONNECT_NOW);
            return;
        }
        if (state == STATE.CONNECT_NOW) {
            connectNowFailures++;
            lastConnectFailed = true;
            if (connectNowFailures % 12 == 7 && genericBluetoothWatchdog()) {
                UserError.Log.e(str, "Initiating bluetooth watchdog reset");
                JoH.niceRestartBluetooth(xdrip.getAppContext());
            }
            if (th instanceof BleGattCallbackTimeoutException) {
                if (th.getMessage().contains("BleGattOperation{description='CONNECTION_STATE'")) {
                    UserError.Log.d(str, "Setting pre-scan failure marker enabled due to exception type");
                    preScanFailureMarker = true;
                }
            } else if (JoH.msSince(last_connect_started) < 1000) {
                UserError.Log.d(str, "Setting pre-scan failure marker enabled due to exception timing");
                preScanFailureMarker = true;
            }
            UserError.Log.d(str, "Connect Now failures incremented to: " + connectNowFailures);
            if (minimize_scanning && DexSyncKeeper.anticipate(transmitterID) > 0) {
                changeState(STATE.CLOSE);
                return;
            } else {
                changeState(STATE.CONNECT);
                return;
            }
        }
        if (state == STATE.CONNECT) {
            connectFailures++;
            lastConnectFailed = true;
            if (JoH.ratelimit("ob1-restart-scan-on-connect-failure", 10)) {
                UserError.Log.d(str, "Restarting scan due to connect failure");
                tryGattRefresh();
                changeState(STATE.SCAN);
            }
        }
    }

    public void tryGattRefresh() {
        if (JoH.ratelimit("ob1-gatt-refresh", 60)) {
            if (Pref.getBoolean("use_gatt_refresh", true)) {
                try {
                    if (this.connection != null) {
                        UserError.Log.d(TAG, "Trying gatt refresh queue");
                    }
                    this.connection.queue(new GattRefreshOperation(0L)).timeout(2L, TimeUnit.SECONDS).subscribe(new Consumer() {
                        public final void accept(Object obj) {
                            Ob1G5CollectionService.lambda$tryGattRefresh$3((Void) obj);
                        }
                    }, new Consumer() {
                        public final void accept(Object obj) {
                            Ob1G5CollectionService.lambda$tryGattRefresh$4((Throwable) obj);
                        }
                    });
                    return;
                } catch (NullPointerException e) {
                    UserError.Log.d(TAG, "Probably harmless gatt refresh exception: " + e);
                    return;
                } catch (Exception e2) {
                    UserError.Log.d(TAG, "Got exception trying gatt refresh: " + e2);
                    return;
                }
            }
            UserError.Log.d(TAG, "Gatt refresh rate limited");
        }
    }

    public static void lambda$tryGattRefresh$3(Void r3) throws Exception {
        UserError.Log.d(TAG, "Refresh OK: " + r3);
    }

    public static void lambda$tryGattRefresh$4(Throwable th) throws Exception {
        UserError.Log.d(TAG, "Refresh exception: " + th);
    }

    public void onConnectionReceived(RxBleConnection rxBleConnection) {
        msg("Connected");
        if (shouldServiceRun()) {
            static_last_connected = JoH.tsl();
            lastConnectFailed = false;
            preScanFailureMarker = false;
            DexSyncKeeper.store(transmitterID, static_last_connected);
            PowerManager.WakeLock wakeLock = this.connection_linger;
            if (wakeLock != null) {
                JoH.releaseWakeLock(wakeLock);
            }
            this.connection = rxBleConnection;
            if (state == STATE.CONNECT_NOW) {
                connectNowFailures = -3;
            }
            if (state == STATE.CONNECT) {
                connectFailures = -1;
            }
            scanTimeouts = 0;
            clearRetries();
            if (JoH.ratelimit("g5-to-discover", 1)) {
                changeState(STATE.DISCOVER);
                return;
            }
            return;
        }
        msg("Shutdown");
        stopSelf();
    }

    public synchronized void onConnectionStateChange(RxBleConnection.RxBleConnectionState rxBleConnectionState) {
        String str = "Unknown";
        int i = AnonymousClass7.$SwitchMap$com$polidea$rxandroidble2$RxBleConnection$RxBleConnectionState[rxBleConnectionState.ordinal()];
        if (i == 1) {
            str = "Connecting";
            connecting_time = JoH.tsl();
        } else if (i == 2) {
            str = "Connected";
            JoH.releaseWakeLock(this.floatingWakeLock);
            this.floatingWakeLock = JoH.getWakeLock("floating-connected", 40000);
            long msSince = JoH.msSince(connecting_time);
            if (connecting_time > G5BaseService.static_last_timestamp && msSince > 310000 && msSince < 620000) {
                if (!always_scan) {
                    UserError.Log.e(TAG, "Connection time shows missed reading, switching to always scan, metric: " + JoH.niceTimeScalar(msSince));
                    always_scan = true;
                } else {
                    UserError.Log.e(TAG, "Connection time shows missed reading, despite always scan, metric: " + JoH.niceTimeScalar(msSince));
                }
            }
        } else if (i == 3) {
            str = "Disconnecting";
        } else if (i == 4) {
            str = "Disconnected";
            JoH.releaseWakeLock(this.floatingWakeLock);
        }
        static_connection_state = str;
        UserError.Log.d(TAG, "Bluetooth connection: " + static_connection_state);
        str.equals("Disconnecting");
    }

    public void releaseFloating() {
        PowerManager.WakeLock wakeLock = this.floatingWakeLock;
        if (wakeLock == null || !wakeLock.isHeld()) {
            return;
        }
        JoH.releaseWakeLock(wakeLock);
    }

    public void connectionStateChange(String str) {
        static_connection_state = str;
        if (str.equals("Closed OK")) {
            JoH.releaseWakeLock(this.floatingWakeLock);
        }
    }

    public void onServicesDiscovered(RxBleDeviceServices rxBleDeviceServices) {
        boolean z;
        for (BluetoothGattService bluetoothGattService : rxBleDeviceServices.getBluetoothGattServices()) {
            if (bluetoothGattService.getUuid().equals(BluetoothServices.CGMService)) {
                if (Dialog.txIdMatch(getTransmitterID()) && bluetoothGattService.getCharacteristic(BluetoothServices.ExtraData) != null) {
                    try {
                        this.plugin = Loader.getLocalInstance(Registry.get("keks"), getTransmitterID());
                        if (this.plugin == null) {
                            UserError.Log.wtf(TAG, "Unable to load keks plugin - please re-enter transmitter id");
                            JoH.static_toast_long("Unable to load keks plugin - please re-enter transmitter id");
                        } else {
                            this.plugin.setPersistence(2, PersistentStore.getBytes("keks1_" + transmitterMAC));
                            if (immediateBonding()) {
                                if (isDeviceLocallyBonded() && !ignoreBonding()) {
                                    z = false;
                                    needsBonding(z);
                                }
                                z = true;
                                needsBonding(z);
                            }
                            for (int i = 1; i < 4; i++) {
                                try {
                                    this.plugin.setPersistence(i + 7, JoH.tolerantHexStringToByteArray(Pref.getStringDefaultBlank("keks_p" + i)));
                                } catch (Exception unused) {
                                    UserError.Log.e(TAG, "Problem with persistence");
                                }
                            }
                        }
                    } catch (Exception e) {
                        UserError.Log.e(TAG, "Exception getting instance: " + e);
                        e.printStackTrace();
                    }
                } else {
                    this.plugin = null;
                }
                if (specialPairingWorkaround()) {
                    UserError.Log.d(TAG, "Samsung additional delay");
                    Inevitable.task("samsung delay", 1000L, new Runnable() {
                        @Override
                        public final void run() {
                            Ob1G5CollectionService.this.lambda$onServicesDiscovered$5();
                        }
                    });
                    return;
                } else {
                    changeState(STATE.CHECK_AUTH);
                    return;
                }
            }
        }
        UserError.Log.e(TAG, "Could not locate CGM service during discovery");
        incrementErrors();
    }

    public void lambda$onServicesDiscovered$5() {
        changeState(STATE.CHECK_AUTH);
    }

    public void onDiscoverFailed(Throwable th) {
        UserError.Log.e(TAG, "Discover failure: " + th.toString());
        incrementErrors();
        prepareToWakeup();
    }

    private boolean genericBluetoothWatchdog() {
        return Pref.getBoolean("bluetooth_watchdog", true);
    }

    public static void updateLast(long j) {
        if (G5BaseService.static_last_timestamp == 0 && transmitterID != null) {
            String str = "last-ob1-data-" + transmitterID;
            if (PersistentStore.getLong(str) == 0) {
                PersistentStore.setLong(str, j);
                if (!android_wear) {
                    JoH.playResourceAudio(2131689966);
                }
            }
        }
        G5BaseService.static_last_timestamp = j;
    }

    private String handleBleScanException(BleScanException bleScanException) {
        String format;
        int reason = bleScanException.getReason();
        if (reason != 2147483646) {
            switch (reason) {
                case 1:
                    format = "Enable bluetooth and try again";
                    break;
                case 2:
                    format = "Bluetooth is not available";
                    break;
                case 3:
                    format = "On Android 6.0+ location permission is required. Implement Runtime Permissions";
                    break;
                case 4:
                    format = "Location services needs to be enabled on Android 6.0+";
                    break;
                case 5:
                    format = "Scan with the same filters is already started";
                    break;
                case 6:
                    format = "Failed to register application for bluetooth scan";
                    break;
                case 7:
                    format = "Scan failed due to internal error";
                    break;
                case 8:
                    format = "Scan with specified parameters is not supported";
                    break;
                case 9:
                    format = "Scan cannot start due to limited hardware resources";
                    break;
                default:
                    format = "Unable to start scanning";
                    break;
            }
        } else {
            format = String.format(Locale.getDefault(), "Android 7+ does not allow more scans. Try in %d seconds", Long.valueOf(secondsTill(bleScanException.getRetryDateSuggestion())));
        }
        UserError.Log.w(TAG, format + " " + bleScanException);
        return format;
    }

    static class GattRefreshOperation implements RxBleCustomOperation<Void> {
        private long delay_ms;

        GattRefreshOperation(long j) {
            this.delay_ms = j;
        }

        public Observable<Void> asObservable(final BluetoothGatt bluetoothGatt, RxBleGattCallback rxBleGattCallback, Scheduler scheduler) throws Throwable {
            return Observable.fromCallable(new Callable() {
                @Override
                public final Object call() {
                    Void lambda$asObservable$0;
                    lambda$asObservable$0 = Ob1G5CollectionService.GattRefreshOperation.this.lambda$asObservable$0(bluetoothGatt);
                    return lambda$asObservable$0;
                }
            }).delay(this.delay_ms, TimeUnit.MILLISECONDS, Schedulers.computation()).subscribeOn(scheduler);
        }

        public Void lambda$asObservable$0(BluetoothGatt bluetoothGatt) {
            String str = Ob1G5CollectionService.TAG;
            StringBuilder sb = new StringBuilder();
            sb.append("Gatt Refresh ");
            sb.append(JoH.refreshDeviceCache(str, bluetoothGatt) ? "succeeded" : "failed");
            UserError.Log.d(str, sb.toString());
            return null;
        }
    }

    public void instantCreateBondIfAllowed() {
        if (getInitiateBondingFlag()) {
            try {
                UserError.Log.d(TAG, "instantCreateBond() called");
                this.bleDevice.getBluetoothDevice().createBond();
                return;
            } catch (Exception e) {
                UserError.Log.e(TAG, "Got exception in instantCreateBond() " + e);
                return;
            }
        }
        UserError.Log.e(TAG, "instantCreateBond blocked by lack of initiate_bonding flag");
    }

    private static long secondsTill(Date date) {
        return TimeUnit.MILLISECONDS.toSeconds(date.getTime() - System.currentTimeMillis());
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    public static void processCalibrationStateLite(CalibrationState calibrationState, long j) {
        if (j > lastProcessCalibrationState) {
            processCalibrationStateLite(calibrationState);
            return;
        }
        UserError.Log.d(TAG, "Ignoring calibration state as it is: " + JoH.dateTimeText(j) + " vs local: " + JoH.dateTimeText(lastProcessCalibrationState));
    }

    public static boolean processCalibrationStateLite(CalibrationState calibrationState) {
        if (calibrationState == CalibrationState.Unknown) {
            UserError.Log.d(TAG, "Not processing push of unknown state as this is the unset state");
            return false;
        }
        if (JoH.msSince(lastProcessCalibrationState) < 60000) {
            UserError.Log.d(TAG, "Ignoring duplicate processCalibration State");
            return false;
        }
        lastProcessCalibrationState = JoH.tsl();
        lastSensorStatus = calibrationState.getExtendedText();
        lastSensorState = calibrationState;
        return true;
    }

    public static void processCalibrationState(final CalibrationState calibrationState) {
        final Class cls;
        if (!processCalibrationStateLite(calibrationState)) {
            UserError.Log.d(TAG, "Not processing more calibration state as lite returned false");
            return;
        }
        storeCalibrationState(calibrationState);
        boolean needsCalibration = calibrationState.needsCalibration();
        boolean z = PersistentStore.getBoolean("G5_NEEDING_CALIBRATION");
        boolean sensorStarted = calibrationState.sensorStarted();
        boolean z2 = PersistentStore.getBoolean("G5_IS_STARTED");
        boolean sensorFailed = calibrationState.sensorFailed();
        boolean z3 = PersistentStore.getBoolean("G5_IS_FAILED");
        if (needsCalibration && !z) {
            if (AnonymousClass7.$SwitchMap$com$eveningoutpost$dexdrip$g5model$CalibrationState[calibrationState.ordinal()] == 1) {
                cls = DoubleCalibrationActivity.class;
            } else {
                cls = AddCalibration.class;
            }
            Inevitable.task("ask initial calibration", 30000L, new Runnable() {
                @Override
                public final void run() {
                    Ob1G5CollectionService.lambda$processCalibrationState$6(cls, calibrationState);
                }
            });
        } else if (!needsCalibration && z) {
            JoH.cancelNotification(1007);
        }
        if (!sensorStarted && z2) {
            if (Sensor.isActive()) {
                if (Pref.getBooleanDefaultFalse("ob1_g5_restart_sensor")) {
                    if (calibrationState.ended()) {
                        UserError.Log.uel(TAG, "Requesting time-travel restart");
                        Ob1G5StateMachine.restartSensorWithTimeTravel();
                    } else {
                        UserError.Log.uel(TAG, "Attempting to auto-start sensor");
                        Ob1G5StateMachine.startSensor(JoH.tsl());
                    }
                    JoH.showNotification("Auto Start", "Sensor Requesting Restart", PendingIntent.getActivity(xdrip.getAppContext(), 1013, JoH.getStartActivityIntent(Home.class), 134217728), 1013, true, true, false);
                    UserError.Log.uel(TAG, "Sensor Requesting Restart");
                } else {
                    UserError.Log.uel(TAG, "Marking sensor session as stopped");
                    Sensor.stopSensor();
                }
            }
            JoH.showNotification(calibrationState.getText(), "Sensor Stopped", PendingIntent.getActivity(xdrip.getAppContext(), 1012, JoH.getStartActivityIntent(Home.class), 134217728), 1012, true, true, false);
            UserError.Log.ueh(TAG, "Native Sensor is now Stopped: " + calibrationState.getExtendedText());
            Treatments.sensorStop(null, "Stopped by transmitter: " + calibrationState.getExtendedText());
        } else if (sensorStarted && !z2) {
            JoH.cancelNotification(1012);
            UserError.Log.ueh(TAG, "Native Sensor is now Started: " + calibrationState.getExtendedText());
            Treatments.sensorStartIfNeeded();
        }
        if (sensorFailed && !z3) {
            JoH.showNotification(calibrationState.getText(), "Sensor FAILED", PendingIntent.getActivity(xdrip.getAppContext(), 1011, JoH.getStartActivityIntent(Home.class), 134217728), 1011, true, true, false);
            UserError.Log.ueh(TAG, "Native Sensor is now marked FAILED: " + calibrationState.getExtendedText());
        }
        updateG5State(needsCalibration, z, "G5_NEEDING_CALIBRATION");
        updateG5State(sensorStarted, z2, "G5_IS_STARTED");
        updateG5State(sensorFailed, z3, "G5_IS_FAILED");
    }

    static class AnonymousClass7 {
        static final int[] $SwitchMap$com$eveningoutpost$dexdrip$g5model$CalibrationState;
        static final int[] $SwitchMap$com$eveningoutpost$dexdrip$services$Ob1G5CollectionService$STATE;
        static final int[] $SwitchMap$com$polidea$rxandroidble2$RxBleConnection$RxBleConnectionState;

        static {
            int[] iArr = new int[CalibrationState.values().length];
            $SwitchMap$com$eveningoutpost$dexdrip$g5model$CalibrationState = iArr;
            try {
                iArr[CalibrationState.NeedsFirstCalibration.ordinal()] = 1;
            } catch (NoSuchFieldError unused) {
            }
            int[] iArr2 = new int[RxBleConnection.RxBleConnectionState.values().length];
            $SwitchMap$com$polidea$rxandroidble2$RxBleConnection$RxBleConnectionState = iArr2;
            try {
                iArr2[RxBleConnection.RxBleConnectionState.CONNECTING.ordinal()] = 1;
            } catch (NoSuchFieldError unused2) {
            }
            try {
                $SwitchMap$com$polidea$rxandroidble2$RxBleConnection$RxBleConnectionState[RxBleConnection.RxBleConnectionState.CONNECTED.ordinal()] = 2;
            } catch (NoSuchFieldError unused3) {
            }
            try {
                $SwitchMap$com$polidea$rxandroidble2$RxBleConnection$RxBleConnectionState[RxBleConnection.RxBleConnectionState.DISCONNECTING.ordinal()] = 3;
            } catch (NoSuchFieldError unused4) {
            }
            try {
                $SwitchMap$com$polidea$rxandroidble2$RxBleConnection$RxBleConnectionState[RxBleConnection.RxBleConnectionState.DISCONNECTED.ordinal()] = 4;
            } catch (NoSuchFieldError unused5) {
            }
            int[] iArr3 = new int[STATE.values().length];
            $SwitchMap$com$eveningoutpost$dexdrip$services$Ob1G5CollectionService$STATE = iArr3;
            try {
                iArr3[STATE.INIT.ordinal()] = 1;
            } catch (NoSuchFieldError unused6) {
            }
            try {
                $SwitchMap$com$eveningoutpost$dexdrip$services$Ob1G5CollectionService$STATE[STATE.SCAN.ordinal()] = 2;
            } catch (NoSuchFieldError unused7) {
            }
            try {
                $SwitchMap$com$eveningoutpost$dexdrip$services$Ob1G5CollectionService$STATE[STATE.CONNECT_NOW.ordinal()] = 3;
            } catch (NoSuchFieldError unused8) {
            }
            try {
                $SwitchMap$com$eveningoutpost$dexdrip$services$Ob1G5CollectionService$STATE[STATE.CONNECT.ordinal()] = 4;
            } catch (NoSuchFieldError unused9) {
            }
            try {
                $SwitchMap$com$eveningoutpost$dexdrip$services$Ob1G5CollectionService$STATE[STATE.DISCOVER.ordinal()] = 5;
            } catch (NoSuchFieldError unused10) {
            }
            try {
                $SwitchMap$com$eveningoutpost$dexdrip$services$Ob1G5CollectionService$STATE[STATE.CHECK_AUTH.ordinal()] = 6;
            } catch (NoSuchFieldError unused11) {
            }
            try {
                $SwitchMap$com$eveningoutpost$dexdrip$services$Ob1G5CollectionService$STATE[STATE.PREBOND.ordinal()] = 7;
            } catch (NoSuchFieldError unused12) {
            }
            try {
                $SwitchMap$com$eveningoutpost$dexdrip$services$Ob1G5CollectionService$STATE[STATE.BOND.ordinal()] = 8;
            } catch (NoSuchFieldError unused13) {
            }
            try {
                $SwitchMap$com$eveningoutpost$dexdrip$services$Ob1G5CollectionService$STATE[STATE.UNBOND.ordinal()] = 9;
            } catch (NoSuchFieldError unused14) {
            }
            try {
                $SwitchMap$com$eveningoutpost$dexdrip$services$Ob1G5CollectionService$STATE[STATE.RESET.ordinal()] = 10;
            } catch (NoSuchFieldError unused15) {
            }
            try {
                $SwitchMap$com$eveningoutpost$dexdrip$services$Ob1G5CollectionService$STATE[STATE.GET_DATA.ordinal()] = 11;
            } catch (NoSuchFieldError unused16) {
            }
            try {
                $SwitchMap$com$eveningoutpost$dexdrip$services$Ob1G5CollectionService$STATE[STATE.CLOSE.ordinal()] = 12;
            } catch (NoSuchFieldError unused17) {
            }
            try {
                $SwitchMap$com$eveningoutpost$dexdrip$services$Ob1G5CollectionService$STATE[STATE.CLOSED.ordinal()] = 13;
            } catch (NoSuchFieldError unused18) {
            }
        }
    }

    public static void lambda$processCalibrationState$6(Class cls, CalibrationState calibrationState) {
        PendingIntent activity = PendingIntent.getActivity(xdrip.getAppContext(), 1007, JoH.getStartActivityIntent(cls), 134217728);
        String text = calibrationState.getText();
        if (android_wear) {
            activity = null;
        }
        JoH.showNotification(text, "Calibration Required", activity, 1007, calibrationState == CalibrationState.NeedsFirstCalibration, true, false);
        UserError.Log.uel(TAG, "Calibration Required");
    }

    private static void updateG5State(boolean z, boolean z2, String str) {
        if (z != z2) {
            PersistentStore.setBoolean(str, z);
        }
    }

    private static void storeCalibrationState(CalibrationState calibrationState) {
        PersistentStore.setByte("ob1-state-store-", calibrationState.getValue());
        PersistentStore.setLong("ob1-state-store-time", JoH.tsl());
    }

    private static CalibrationState getStoredCalibrationState() {
        if (JoH.msSince(PersistentStore.getLong("ob1-state-store-time")) < 7200000) {
            return CalibrationState.parse(PersistentStore.getByte("ob1-state-store-"));
        }
        return CalibrationState.Unknown;
    }

    private static void loadCalibrationStateAsRequired() {
        CalibrationState storedCalibrationState;
        if (lastSensorState == null && JoH.quietratelimit("ob1-load-sensor-state", 5) && (storedCalibrationState = getStoredCalibrationState()) != CalibrationState.Unknown) {
            lastSensorState = storedCalibrationState;
        }
    }

    public static boolean isG5ActiveButUnknownState() {
        loadCalibrationStateAsRequired();
        return (lastSensorState == null || lastSensorState == CalibrationState.Unknown) && usingNativeMode();
    }

    public static boolean isG5WarmingUp() {
        loadCalibrationStateAsRequired();
        return lastSensorState != null && lastSensorState == CalibrationState.WarmingUp && usingNativeMode();
    }

    public static boolean isG5SensorStarted() {
        loadCalibrationStateAsRequired();
        return (lastSensorState == null || !lastSensorState.sensorStarted() || !usingNativeMode() || Ob1G5StateMachine.pendingStop() || Ob1G5StateMachine.pendingStart()) ? false : true;
    }

    public static boolean isPendingStart() {
        return Ob1G5StateMachine.pendingStart() && usingNativeMode();
    }

    public static boolean isPendingStop() {
        return Ob1G5StateMachine.pendingStop() && usingNativeMode();
    }

    public static boolean isPendingCalibration() {
        return Ob1G5StateMachine.pendingCalibration() && usingNativeMode();
    }

    public static boolean isG5WantingInitialCalibration() {
        loadCalibrationStateAsRequired();
        return lastSensorStatus != null && lastSensorState == CalibrationState.NeedsFirstCalibration && usingNativeMode();
    }

    public static boolean isG5WantingCalibration() {
        loadCalibrationStateAsRequired();
        return lastSensorStatus != null && lastSensorState.needsCalibration() && usingNativeMode();
    }

    public static boolean usingNativeMode() {
        return usingCollector() && Pref.getBooleanDefaultFalse("ob1_g5_use_transmitter_alg") && Pref.getBooleanDefaultFalse("use_ob1_g5_collector_service");
    }

    public static boolean onlyUsingNativeMode() {
        return (usingNativeMode() && !fallbackToXdripAlgorithm()) || usingMockPreCalibrated();
    }

    public static boolean usingMockPreCalibrated() {
        return Pref.getBooleanDefaultFalse("fake_data_pre_calibrated") && DexCollectionType.getDexCollectionType() == DexCollectionType.Mock;
    }

    public static boolean isProvidingNativeGlucoseData() {
        loadCalibrationStateAsRequired();
        return usingNativeMode() && lastSensorState != null && lastSensorState.usableGlucose();
    }

    public static boolean fallbackToXdripAlgorithm() {
        return Pref.getBooleanDefaultFalse("ob1_g5_fallback_to_xdrip");
    }

    public static void msg(String str) {
        G5BaseService.lastState = str + " " + JoH.hourMinuteString();
        UserError.Log.d(TAG, "Status: " + G5BaseService.lastState);
        lastStateUpdated = JoH.tsl();
        if (android_wear && wear_broadcast) {
            BroadcastGlucose.sendLocalBroadcast(null);
        }
    }

    public static SpannableString nanoStatus() {
        String str = "";
        if (android_wear) {
            SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
            if (lastSensorStatus != null) {
                str = lastSensorStatus + "\n";
            }
            spannableStringBuilder.append((CharSequence) str);
            spannableStringBuilder.append((CharSequence) state.getString());
            return new SpannableString(spannableStringBuilder);
        }
        if (!usingNativeMode()) {
            return null;
        }
        if (lastSensorState != null && lastSensorState != CalibrationState.Ok) {
            if (!lastSensorState.sensorStarted() && isPendingStart()) {
                return Span.colorSpan("Starting Sensor", StatusItem.Highlight.NOTICE.color());
            }
            if (lastSensorState.sensorStarted() && isPendingStop()) {
                return Span.colorSpan("Stopping Sensor", StatusItem.Highlight.NOTICE.color());
            }
            if (lastSensorState.needsCalibration() && Ob1G5StateMachine.pendingCalibration()) {
                return Span.colorSpan("Sending calibration", StatusItem.Highlight.NOTICE.color());
            }
            return Span.colorSpan(lastSensorState.getExtendedText(), (lastSensorState.transitional() ? StatusItem.Highlight.NOTICE : lastSensorState.sensorFailed() ? StatusItem.Highlight.CRITICAL : StatusItem.Highlight.BAD).color());
        }
        return Span.colorSpan("", StatusItem.Highlight.NORMAL.color());
    }

    private boolean inPurdah() {
        return purdahMs() > 0;
    }

    private long purdahMs() {
        long msTill = JoH.msTill(PersistentStore.getLong("ob1g5-purdah-time"));
        if (msTill < 0 || msTill > 14400000) {
            return 0L;
        }
        return msTill;
    }

    void needsBonding(boolean z) {
        this.plugin.setPersistence(6, JoH.joinBytes(new byte[]{(byte) ((!z ? 1 : 0) << 1)}, fwChalCache(z)));
    }

    public static void handleUnknownFirmwareClick() {
        String str = TAG;
        UserError.Log.d(str, "handleUnknownFirmwareClick()");
        if (UpdateActivity.testAndSetNightly(true)) {
            VersionRequest1RxMessage versionRequest1RxMessage = (VersionRequest1RxMessage) Ob1G5StateMachine.getFirmwareXDetails(getTransmitterID(), 1);
            UserError.Log.d(str, "Starting feedback activity");
            xdrip.getAppContext().startActivity(new Intent(xdrip.getAppContext(), (Class<?>) SendFeedBack.class).putExtra("generic_text", "Automated Report of unknown firmware version\n" + versionRequest1RxMessage.toString()).setFlags(268435456));
        }
    }

    public static java.util.List<com.eveningoutpost.dexdrip.utilitymodels.StatusItem> megaStatus() {
        throw new UnsupportedOperationException("Method not decompiled: com.eveningoutpost.dexdrip.services.Ob1G5CollectionService.megaStatus():java.util.List");
    }

    public static void resetSomeInternalState() {
        UserError.Log.d(TAG, "Resetting internal state by request");
        transmitterMAC = null;
        state = STATE.INIT;
        scan_next_run = true;
    }

    public synchronized void logFailure() {
        String str = transmitterMAC;
        if (str == null) {
            UserError.Log.e(TAG, "Could not log failure as mac is null");
            return;
        }
        long tsl = JoH.tsl();
        failureTally.put(str, Long.valueOf(tsl));
        UserError.Log.d(TAG, "Adding " + str + " to failure tally " + JoH.dateTimeText(tsl));
        resetSomeInternalState();
    }

    private static void expireFailures(boolean z) {
        ArrayList arrayList = new ArrayList();
        for (Map.Entry<String, Long> entry : failureTally.entrySet()) {
            if (z || JoH.msSince(entry.getValue().longValue()) > 1800000) {
                arrayList.add(entry.getKey());
            }
        }
        Iterator it = arrayList.iterator();
        while (it.hasNext()) {
            String str = (String) it.next();
            UserError.Log.d(TAG, "Removing " + str + " from failure tally");
            failureTally.remove(str);
        }
    }

    private static boolean inFailureTally(String str) {
        if (str == null) {
            return false;
        }
        return failureTally.containsKey(str);
    }

    public void listenForChangeInSettings(boolean z) {
        try {
            SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            if (z) {
                defaultSharedPreferences.registerOnSharedPreferenceChangeListener(this.prefListener);
            } else {
                defaultSharedPreferences.unregisterOnSharedPreferenceChangeListener(this.prefListener);
            }
        } catch (Exception e) {
            UserError.Log.e(TAG, "Error with preference listener: " + e + " " + z);
        }
    }

    public static boolean isCollecting() {
        return (state == STATE.CONNECT_NOW && JoH.msSince(G5BaseService.static_last_timestamp) < 1800000) || JoH.msSince(G5BaseService.static_last_timestamp) < 360000;
    }

    public static boolean usingCollector() {
        return Pref.getBooleanDefaultFalse("use_ob1_g5_collector_service") && DexCollectionType.getDexCollectionType() == DexCollectionType.DexcomG5;
    }

    private static boolean isVolumeSilent() {
        return ((AudioManager) xdrip.getAppContext().getSystemService("audio")).getRingerMode() != 2;
    }

    public static void clearDataWhenTransmitterIdEntered(String str) {
        try {
            UserError.Log.e(TAG, "Clearing data when new transmitter is entered: " + str);
            Ob1G5StateMachine.emptyQueue();
            try {
                DexSyncKeeper.clear(str);
            } catch (Exception unused) {
            }
            clearPersist();
        } catch (Exception e) {
            UserError.Log.e(TAG, "Got error when clearing data: " + e);
        }
    }
}