导航菜单

页面标题

页面副标题

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

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

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


package com.eveningoutpost.dexdrip.services;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import androidx.health.platform.client.error.ErrorCode;
import com.eveningoutpost.dexdrip.Home;
import com.eveningoutpost.dexdrip.g5model.AuthChallengeRxMessage;
import com.eveningoutpost.dexdrip.g5model.AuthChallengeTxMessage;
import com.eveningoutpost.dexdrip.g5model.AuthRequestTxMessage;
import com.eveningoutpost.dexdrip.g5model.AuthStatusRxMessage;
import com.eveningoutpost.dexdrip.g5model.BatteryInfoRxMessage;
import com.eveningoutpost.dexdrip.g5model.BatteryInfoTxMessage;
import com.eveningoutpost.dexdrip.g5model.BluetoothServices;
import com.eveningoutpost.dexdrip.g5model.BondRequestTxMessage;
import com.eveningoutpost.dexdrip.g5model.DisconnectTxMessage;
import com.eveningoutpost.dexdrip.g5model.Extensions;
import com.eveningoutpost.dexdrip.g5model.FirmwareCapability;
import com.eveningoutpost.dexdrip.g5model.GlucoseRxMessage;
import com.eveningoutpost.dexdrip.g5model.GlucoseTxMessage;
import com.eveningoutpost.dexdrip.g5model.KeepAliveTxMessage;
import com.eveningoutpost.dexdrip.g5model.SensorRxMessage;
import com.eveningoutpost.dexdrip.g5model.SensorTxMessage;
import com.eveningoutpost.dexdrip.g5model.Transmitter;
import com.eveningoutpost.dexdrip.g5model.TransmitterStatus;
import com.eveningoutpost.dexdrip.g5model.VersionRequestRxMessage;
import com.eveningoutpost.dexdrip.g5model.VersionRequestTxMessage;
import com.eveningoutpost.dexdrip.models.BgReading;
import com.eveningoutpost.dexdrip.models.JoH;
import com.eveningoutpost.dexdrip.models.Sensor;
import com.eveningoutpost.dexdrip.models.TransmitterData;
import com.eveningoutpost.dexdrip.models.UserError;
import com.eveningoutpost.dexdrip.utilitymodels.CollectionServiceStarter;
import com.eveningoutpost.dexdrip.utilitymodels.PersistentStore;
import com.eveningoutpost.dexdrip.utilitymodels.Pref;
import com.eveningoutpost.dexdrip.utilitymodels.StatusItem;
import com.eveningoutpost.dexdrip.utils.PowerStateReceiver;
import com.eveningoutpost.dexdrip.utils.bt.Helper;
import com.eveningoutpost.dexdrip.xdrip;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

@TargetApi(21)
public class G5CollectionService extends G5BaseService {
    public static final String TAG = "G5CollectionService";
    private static boolean cycling_bt = false;
    private static int disconnected133 = 0;
    private static int disconnected59 = 0;
    private static int failures = 0;
    private static boolean isScanning = false;
    public static boolean keep_running = true;
    private static byte lastOnReadCode = -1;
    private static PendingIntent pendingIntent = null;
    private static boolean scan_scheduled = false;
    private static boolean service_running = false;
    private static String static_device_address = null;
    private static boolean static_is_bonded = false;
    private static int successes;
    public ArrayList<Long> advertiseTimeMS;
    private BluetoothGattCharacteristic authCharacteristic;
    private BluetoothGattService cgmService;
    private BluetoothGattCharacteristic controlCharacteristic;
    private int currentBondState;
    private Transmitter defaultTransmitter;
    private BluetoothDevice device;
    private boolean encountered133;
    private List<ScanFilter> filters;
    private final BluetoothGattCallback gattCallback;
    private Boolean isBonded;
    private Boolean isBondedOrBonding;
    private boolean isConnected;
    public boolean isIntialScan;
    StringBuilder log;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothManager mBluetoothManager;
    private BluetoothGatt mGatt;
    private BluetoothLeScanner mLEScanner;
    private BluetoothAdapter.LeScanCallback mLeScanCallback;
    final BroadcastReceiver mPairReceiver;
    private final BroadcastReceiver mPairingRequestRecevier;
    private ScanCallback mScanCallback;
    private final int max133Retries;
    public int max133RetryCounter;
    private int maxScanCycles;
    private int maxScanIntervalInMilliseconds;
    public final SharedPreferences.OnSharedPreferenceChangeListener prefListener;
    private SharedPreferences prefs;
    private int scanCycleCount;
    private ScanSettings settings;
    public long timeInMillisecondsOfLastSuccessfulSensorRead;
    private int waitingBondConfirmation;
    private static final Object short_lock = new Object();
    public static Timer scan_interval_timer = new Timer();
    private static long last_transmitter_timestamp = 0;
    private final Object mLock = new Object();
    private boolean force_always_authenticate = false;
    public AuthStatusRxMessage authStatus = null;
    public AuthRequestTxMessage authRequest = null;

    public int getTokenSize() {
        return 8;
    }

    private boolean useG5NewMethod() {
        return false;
    }

    public G5CollectionService() {
        Boolean bool = Boolean.FALSE;
        this.isBondedOrBonding = bool;
        this.isBonded = bool;
        this.currentBondState = 0;
        this.waitingBondConfirmation = 0;
        this.isConnected = false;
        this.encountered133 = false;
        this.max133Retries = 5;
        this.max133RetryCounter = 0;
        this.isIntialScan = true;
        this.advertiseTimeMS = new ArrayList<>();
        this.timeInMillisecondsOfLastSuccessfulSensorRead = new Date().getTime();
        this.maxScanIntervalInMilliseconds = 5000;
        this.maxScanCycles = 24;
        this.scanCycleCount = 0;
        this.log = new StringBuilder();
        this.mPairReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                String str = G5CollectionService.TAG;
                UserError.Log.d(str, "onReceive ACTION: " + action);
                if ("android.bluetooth.device.action.FOUND".equals(action)) {
                    BluetoothDevice bluetoothDevice = (BluetoothDevice) intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
                    G5CollectionService.this.currentBondState = bluetoothDevice.getBondState();
                    UserError.Log.d(str, "onReceive FOUND: " + bluetoothDevice.getName() + " STATE: " + bluetoothDevice.getBondState());
                    return;
                }
                if ("android.bluetooth.device.action.BOND_STATE_CHANGED".equals(action)) {
                    BluetoothDevice bluetoothDevice2 = (BluetoothDevice) intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
                    G5CollectionService.this.currentBondState = bluetoothDevice2.getBondState();
                    UserError.Log.e(str, "onReceive UPDATE Name " + bluetoothDevice2.getName() + " Value " + bluetoothDevice2.getAddress() + " Bond state " + bluetoothDevice2.getBondState() + G5BaseService.bondState(bluetoothDevice2.getBondState()) + " bs: " + G5BaseService.bondState(intent.getIntExtra("android.bluetooth.device.extra.BOND_STATE", -1)) + " was " + G5BaseService.bondState(intent.getIntExtra("android.bluetooth.device.extra.PREVIOUS_BOND_STATE", -1)));
                    try {
                        if (bluetoothDevice2.getBondState() == 12 && bluetoothDevice2.getAddress().equals(G5CollectionService.this.device.getAddress()) && G5CollectionService.this.waitingBondConfirmation == 1) {
                            G5CollectionService.this.waitingBondConfirmation = 2;
                            UserError.Log.e(str, "Bond confirmation received!");
                        }
                    } catch (Exception e) {
                        UserError.Log.wtf(G5CollectionService.TAG, "Got exception trying to process bonded confirmation: ", e);
                    }
                }
            }
        };
        this.prefListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
            @Override
            public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String str) {
                G5CollectionService.this.checkPreferenceKey(str, sharedPreferences);
                if (str.compareTo("run_ble_scan_constantly") == 0 || str.compareTo("always_unbond_G5") == 0 || str.compareTo("always_get_new_keys") == 0 || str.compareTo("run_G5_ble_tasks_on_uithread") == 0) {
                    UserError.Log.i(G5CollectionService.TAG, "G5 Setting Change");
                    G5CollectionService.this.cycleScan(0);
                }
            }
        };
        this.mLeScanCallback = null;
        this.gattCallback = new BluetoothGattCallback() {
            @Override
            public void onConnectionStateChange(final BluetoothGatt bluetoothGatt, final int i, final int i2) {
                if (G5CollectionService.this.enforceMainThread()) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            processOnStateChange(bluetoothGatt, i, i2);
                        }
                    });
                } else {
                    processOnStateChange(bluetoothGatt, i, i2);
                }
            }

            public synchronized void processOnStateChange(BluetoothGatt bluetoothGatt, int i, int i2) {
                if (i2 == 0) {
                    G5CollectionService.this.isConnected = false;
                    if (G5CollectionService.isScanning) {
                        G5CollectionService.this.stopScan();
                    }
                    String str = G5CollectionService.TAG;
                    UserError.Log.e(str, "STATE_DISCONNECTED: " + Helper.getStatusName(i));
                    if (i == 19) {
                        G5CollectionService.access$2208();
                        if (!G5CollectionService.this.alwaysAuthenticate() && G5CollectionService.successes == 0 && G5CollectionService.failures > 1 && G5CollectionService.lastOnReadCode == 7) {
                            UserError.Log.wtf(str, "Force enabling AlwaysAuthenticate mode!");
                            G5CollectionService.this.force_always_authenticate = true;
                        }
                    }
                    if (G5CollectionService.this.mGatt != null) {
                        try {
                            G5CollectionService.this.mGatt.close();
                        } catch (NullPointerException unused) {
                        }
                    }
                    G5CollectionService.this.mGatt = null;
                    if (i == 0 && !G5CollectionService.this.encountered133) {
                        UserError.Log.i(G5CollectionService.TAG, "clean disconnect");
                        G5CollectionService g5CollectionService = G5CollectionService.this;
                        g5CollectionService.max133RetryCounter = 0;
                        if (g5CollectionService.scanConstantly()) {
                            G5CollectionService.this.cycleScan(15000);
                        }
                    } else {
                        if (i != 133) {
                            G5CollectionService g5CollectionService2 = G5CollectionService.this;
                            if (g5CollectionService2.max133RetryCounter < 5) {
                                if (g5CollectionService2.encountered133) {
                                    String str2 = G5CollectionService.TAG;
                                    UserError.Log.e(str2, "max133RetryCounter? " + G5CollectionService.this.max133RetryCounter);
                                    UserError.Log.e(str2, "Encountered 133: " + G5CollectionService.this.encountered133);
                                    if (G5CollectionService.this.scanConstantly()) {
                                        G5CollectionService.this.startScan();
                                    } else {
                                        G5CollectionService.this.cycleScan(0);
                                    }
                                    G5CollectionService.this.max133RetryCounter++;
                                } else if (i != 129) {
                                    if (i == 59) {
                                        G5CollectionService.access$3208();
                                    }
                                    if (G5CollectionService.disconnected59 > 2) {
                                        G5CollectionService.this.cycleBT(true);
                                    } else {
                                        if (G5CollectionService.this.scanConstantly()) {
                                            G5CollectionService.this.startScan();
                                        } else {
                                            G5CollectionService.this.cycleScan(0);
                                        }
                                        G5CollectionService.this.max133RetryCounter = 0;
                                    }
                                } else {
                                    UserError.Log.d(G5CollectionService.TAG, "Forgetting device due to status: " + i);
                                    G5CollectionService.this.forgetDevice();
                                }
                            }
                        }
                        String str3 = G5CollectionService.TAG;
                        UserError.Log.e(str3, "max133RetryCounter? " + G5CollectionService.this.max133RetryCounter);
                        UserError.Log.e(str3, "Encountered 133: " + G5CollectionService.this.encountered133);
                        G5CollectionService.this.max133RetryCounter = 0;
                        G5CollectionService.access$2908();
                        G5CollectionService.this.cycleBT(true);
                    }
                } else if (i2 == 2) {
                    String str4 = G5CollectionService.TAG;
                    UserError.Log.e(str4, "STATE_CONNECTED");
                    G5CollectionService.this.isConnected = true;
                    if (G5CollectionService.this.enforceMainThread()) {
                        if (!G5CollectionService.isOnMainThread()) {
                            UserError.Log.d(str4, "We are not on the main thread so this section is still needed!!");
                        }
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                G5CollectionService.this.discoverServices();
                            }
                        });
                    } else {
                        G5CollectionService.this.discoverServices();
                    }
                    G5CollectionService.this.stopScan();
                    G5CollectionService.scan_interval_timer.cancel();
                    G5CollectionService.this.keepAlive();
                } else {
                    UserError.Log.e(G5CollectionService.TAG, "STATE_OTHER: " + i2);
                }
            }

            @Override
            public synchronized void onServicesDiscovered(final BluetoothGatt bluetoothGatt, final int i) {
                if (G5CollectionService.this.enforceMainThread()) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            processOnServicesDiscovered(bluetoothGatt, i);
                        }
                    });
                } else {
                    processOnServicesDiscovered(bluetoothGatt, i);
                }
            }

            public synchronized void processOnServicesDiscovered(BluetoothGatt bluetoothGatt, int i) {
                String str = G5CollectionService.TAG;
                UserError.Log.i(str, "onServicesDiscovered On Main Thread? " + G5CollectionService.isOnMainThread());
                UserError.Log.e(str, "onServicesDiscovered: " + Helper.getStatusName(i));
                if (i == 0) {
                    if (G5CollectionService.this.mGatt != null) {
                        try {
                            G5CollectionService g5CollectionService = G5CollectionService.this;
                            g5CollectionService.cgmService = g5CollectionService.mGatt.getService(BluetoothServices.CGMService);
                            if (G5CollectionService.this.cgmService != null) {
                                G5CollectionService g5CollectionService2 = G5CollectionService.this;
                                g5CollectionService2.authCharacteristic = g5CollectionService2.cgmService.getCharacteristic(BluetoothServices.Authentication);
                                G5CollectionService g5CollectionService3 = G5CollectionService.this;
                                g5CollectionService3.controlCharacteristic = g5CollectionService3.cgmService.getCharacteristic(BluetoothServices.Control);
                            }
                        } catch (NullPointerException unused) {
                            UserError.Log.e(G5CollectionService.TAG, "Got Null pointer in OnServices discovered 2");
                        }
                        G5CollectionService.this.mBluetoothAdapter.cancelDiscovery();
                    }
                    if (!G5CollectionService.this.alwaysAuthenticate() && !G5CollectionService.this.alwaysUnbond()) {
                        G5CollectionService.this.authenticate();
                    }
                    G5CollectionService.this.fullAuthenticate();
                } else {
                    UserError.Log.w(str, "onServicesDiscovered received error status: " + Helper.getStatusName(i));
                }
                if (i == 133) {
                    G5CollectionService.this.encountered133 = true;
                }
            }

            @Override
            public void onDescriptorWrite(final BluetoothGatt bluetoothGatt, final BluetoothGattDescriptor bluetoothGattDescriptor, final int i) {
                UserError.Log.e(G5CollectionService.TAG, "OnDescriptor WRITE started: status: " + Helper.getStatusName(i));
                if (G5CollectionService.this.enforceMainThread()) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            processonDescrptorWrite(bluetoothGatt, bluetoothGattDescriptor, i);
                        }
                    });
                } else {
                    processonDescrptorWrite(bluetoothGatt, bluetoothGattDescriptor, i);
                }
            }

            public void processonDescrptorWrite(BluetoothGatt bluetoothGatt, BluetoothGattDescriptor bluetoothGattDescriptor, int i) {
                String str = G5CollectionService.TAG;
                UserError.Log.i(str, "onDescriptorWrite On Main Thread? " + G5CollectionService.isOnMainThread());
                if (i == 0) {
                    UserError.Log.e(str, "Writing to characteristic: " + BluetoothServices.getUUIDName(bluetoothGattDescriptor.getCharacteristic().getUuid()));
                    if (G5CollectionService.this.mGatt != null) {
                        G5CollectionService.this.mGatt.writeCharacteristic(bluetoothGattDescriptor.getCharacteristic());
                    } else {
                        UserError.Log.e(str, "mGatt was null when trying to write UUID descriptor");
                    }
                } else {
                    UserError.Log.e(str, "not writing characteristic due to Unknown error writing descriptor");
                }
                if (i == 133) {
                    G5CollectionService.this.encountered133 = true;
                }
                UserError.Log.e(str, "OnDescriptor WRITE finished: status: " + Helper.getStatusName(i));
            }

            @Override
            public void onCharacteristicWrite(final BluetoothGatt bluetoothGatt, final BluetoothGattCharacteristic bluetoothGattCharacteristic, final int i) {
                UserError.Log.e(G5CollectionService.TAG, "OnCharacteristic WRITE started: " + BluetoothServices.getUUIDName(bluetoothGattCharacteristic.getUuid()) + " status: " + Helper.getStatusName(i));
                if (G5CollectionService.this.enforceMainThread()) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            processOnCharacteristicWrite(bluetoothGatt, bluetoothGattCharacteristic, i);
                        }
                    });
                } else {
                    processOnCharacteristicWrite(bluetoothGatt, bluetoothGattCharacteristic, i);
                }
            }

            public synchronized void processOnCharacteristicWrite(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic, int i) {
                String str = G5CollectionService.TAG;
                UserError.Log.i(str, "processOnCharacteristicWrite On Main Thread? " + G5CollectionService.isOnMainThread());
                if (i == 0) {
                    if (String.valueOf(bluetoothGattCharacteristic.getUuid()).equalsIgnoreCase(String.valueOf(G5CollectionService.this.authCharacteristic.getUuid()))) {
                        UserError.Log.i(str, "Auth ow Char Value: " + Arrays.toString(bluetoothGattCharacteristic.getValue()));
                        UserError.Log.i(str, "Auth ow auth? name: " + BluetoothServices.getUUIDName(bluetoothGattCharacteristic.getUuid()));
                        if (bluetoothGattCharacteristic.getValue() != null) {
                            UserError.Log.e(str, "Auth ow: got opcode: " + ((int) bluetoothGattCharacteristic.getValue()[0]));
                            if (bluetoothGattCharacteristic.getValue()[0] != 6) {
                                if (G5CollectionService.this.max133RetryCounter > 1) {
                                    UserError.Log.e(str, "Adding a delay before reading characteristic with 133 count of: " + G5CollectionService.this.max133RetryCounter);
                                    G5CollectionService.this.waitFor(300);
                                }
                                if (G5CollectionService.this.mGatt != null) {
                                    G5CollectionService.this.mGatt.readCharacteristic(bluetoothGattCharacteristic);
                                } else {
                                    UserError.Log.e(str, "mGatt was null when trying to read KeepAliveTxMessage");
                                }
                            } else {
                                UserError.Log.e(str, "Auth ow: got keepalive");
                                UserError.Log.e(str, "Keepalive written, now trying bond");
                                performBondWrite(bluetoothGattCharacteristic);
                            }
                        } else {
                            UserError.Log.e(str, "Auth ow: got NULL opcode!");
                        }
                    } else {
                        UserError.Log.i(str, "ow unexpected? characteristic: " + BluetoothServices.getUUIDName(bluetoothGattCharacteristic.getUuid()));
                    }
                }
                if (i == 133) {
                    G5CollectionService.this.encountered133 = true;
                }
                UserError.Log.e(str, "OnCharacteristic WRITE finished: status: " + Helper.getStatusName(i));
            }

            @Override
            public void onCharacteristicRead(final BluetoothGatt bluetoothGatt, final BluetoothGattCharacteristic bluetoothGattCharacteristic, final int i) {
                UserError.Log.e(G5CollectionService.TAG, "OnCharacteristic READ started: " + BluetoothServices.getUUIDName(bluetoothGattCharacteristic.getUuid()) + " status: " + i);
                if (G5CollectionService.this.enforceMainThread()) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            processOnCharacteristicRead(bluetoothGatt, bluetoothGattCharacteristic, i);
                        }
                    });
                } else {
                    processOnCharacteristicRead(bluetoothGatt, bluetoothGattCharacteristic, i);
                }
            }

            private synchronized void performBondWrite(BluetoothGattCharacteristic bluetoothGattCharacteristic) {
                String str = G5CollectionService.TAG;
                UserError.Log.d(str, "performBondWrite() started");
                bluetoothGattCharacteristic.setValue(new BondRequestTxMessage().byteSequence);
                if (G5CollectionService.this.mGatt != null) {
                    G5CollectionService.this.mGatt.writeCharacteristic(bluetoothGattCharacteristic);
                } else {
                    UserError.Log.e(str, "mGatt was null when trying to write bondRequest");
                }
                G5CollectionService.this.isBondedOrBonding = Boolean.TRUE;
                G5CollectionService.this.device.createBond();
                UserError.Log.d(str, "performBondWrite() finished");
            }

            public synchronized void processOnCharacteristicRead(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic, int i) {
                String str = G5CollectionService.TAG;
                StringBuilder sb = new StringBuilder();
                sb.append("processOnCRead: Status value: ");
                sb.append(Helper.getStatusName(i));
                sb.append(G5CollectionService.isOnMainThread() ? " on main thread" : " not on main thread");
                UserError.Log.e(str, sb.toString());
                if (i == 0) {
                    UserError.Log.e(str, "CharBytes-or " + Arrays.toString(bluetoothGattCharacteristic.getValue()));
                    UserError.Log.i(str, "CharHex-or " + Extensions.bytesToHex(bluetoothGattCharacteristic.getValue()));
                    byte[] value = bluetoothGattCharacteristic.getValue();
                    if (value.length == 0) {
                        UserError.Log.e(str, "OnCharacteristic READ Got ZERO sized buffer: status: " + Helper.getStatusName(i));
                        return;
                    }
                    byte b = value[0];
                    UserError.Log.e(str, "processOncRead: code:" + ((int) b));
                    G5CollectionService g5CollectionService = G5CollectionService.this;
                    g5CollectionService.mBluetoothAdapter = g5CollectionService.mBluetoothManager.getAdapter();
                    byte unused = G5CollectionService.lastOnReadCode = b;
                    if (b == 3) {
                        AuthChallengeRxMessage authChallengeRxMessage = new AuthChallengeRxMessage(bluetoothGattCharacteristic.getValue());
                        G5CollectionService g5CollectionService2 = G5CollectionService.this;
                        if (g5CollectionService2.authRequest == null) {
                            g5CollectionService2.authRequest = new AuthRequestTxMessage(G5CollectionService.this.getTokenSize());
                        }
                        UserError.Log.i(str, "tokenHash " + Arrays.toString(authChallengeRxMessage.tokenHash));
                        StringBuilder sb2 = new StringBuilder();
                        sb2.append("singleUSe ");
                        G5CollectionService g5CollectionService3 = G5CollectionService.this;
                        sb2.append(Arrays.toString(g5CollectionService3.calculateHash(g5CollectionService3.authRequest.singleUseToken)));
                        UserError.Log.i(str, sb2.toString());
                        byte[] calculateHash = G5CollectionService.this.calculateHash(authChallengeRxMessage.challenge);
                        UserError.Log.d(str, "challenge hash" + Arrays.toString(calculateHash));
                        if (calculateHash != null) {
                            UserError.Log.d(str, "Transmitter try auth challenge");
                            AuthChallengeTxMessage authChallengeTxMessage = new AuthChallengeTxMessage(calculateHash);
                            UserError.Log.i(str, "Auth Challenge: " + Arrays.toString(authChallengeTxMessage.byteSequence));
                            bluetoothGattCharacteristic.setValue(authChallengeTxMessage.byteSequence);
                            if (G5CollectionService.this.mGatt != null) {
                                G5CollectionService.this.mGatt.writeCharacteristic(bluetoothGattCharacteristic);
                            } else {
                                UserError.Log.e(str, "mGatt was null when trying to write in opcode 3 reply");
                            }
                        }
                    } else if (b == 5) {
                        G5CollectionService.this.authStatus = new AuthStatusRxMessage(value);
                        G5CollectionService g5CollectionService4 = G5CollectionService.this;
                        AuthStatusRxMessage authStatusRxMessage = g5CollectionService4.authStatus;
                        if (authStatusRxMessage.authenticated == 1 && authStatusRxMessage.bonded == 1 && !g5CollectionService4.isBondedOrBonding.booleanValue()) {
                            UserError.Log.e(str, "Special bonding test case!");
                            G5CollectionService.this.getTransmitterDetails();
                        }
                        G5CollectionService g5CollectionService5 = G5CollectionService.this;
                        AuthStatusRxMessage authStatusRxMessage2 = g5CollectionService5.authStatus;
                        if (authStatusRxMessage2.authenticated == 1 && authStatusRxMessage2.bonded == 1 && g5CollectionService5.isBondedOrBonding.booleanValue()) {
                            G5CollectionService.this.isBondedOrBonding = Boolean.TRUE;
                            G5CollectionService.this.getSensorData();
                        }
                        G5CollectionService g5CollectionService6 = G5CollectionService.this;
                        AuthStatusRxMessage authStatusRxMessage3 = g5CollectionService6.authStatus;
                        int i2 = authStatusRxMessage3.authenticated;
                        if ((i2 == 1 && authStatusRxMessage3.bonded == 2) || (i2 == 1 && authStatusRxMessage3.bonded == 1 && !g5CollectionService6.isBondedOrBonding.booleanValue())) {
                            StringBuilder sb3 = new StringBuilder();
                            sb3.append("Let's Bond! ");
                            sb3.append(G5CollectionService.this.isBondedOrBonding.booleanValue() ? "locally bonded" : "not locally bonded");
                            UserError.Log.i(str, sb3.toString());
                            UserError.Log.e(str, "Trying keepalive..");
                            bluetoothGattCharacteristic.setValue(new KeepAliveTxMessage(25).byteSequence);
                            if (G5CollectionService.this.mGatt != null) {
                                G5CollectionService.this.mGatt.writeCharacteristic(bluetoothGattCharacteristic);
                            } else {
                                UserError.Log.e(str, "mGatt was null when trying to write keepAliveRequest");
                            }
                        } else {
                            UserError.Log.i(str, "Transmitter NOT already authenticated");
                            G5CollectionService.this.sendAuthRequestTxMessage(bluetoothGatt, bluetoothGattCharacteristic);
                        }
                    } else {
                        if (b == 7) {
                            UserError.Log.e(str, "Trying ondemand bond with delay!");
                            G5CollectionService.this.isBondedOrBonding = Boolean.TRUE;
                            G5CollectionService.this.waitingBondConfirmation = 1;
                            G5CollectionService.this.device.createBond();
                            UserError.Log.e(str, "Using simple wait for 15 secs");
                            G5CollectionService.this.waitFor(15000);
                            UserError.Log.e(str, "ondemandbond delay finished");
                        }
                        UserError.Log.i(str, "Read code: " + ((int) b) + " - Transmitter NOT already authenticated?");
                        G5CollectionService.this.sendAuthRequestTxMessage(bluetoothGatt, bluetoothGattCharacteristic);
                    }
                }
                if (i == 133) {
                    G5CollectionService.this.encountered133 = true;
                }
                UserError.Log.e(str, "OnCharacteristic READ finished: status: " + Helper.getStatusName(i));
            }

            @Override
            public void onCharacteristicChanged(final BluetoothGatt bluetoothGatt, final BluetoothGattCharacteristic bluetoothGattCharacteristic) {
                UserError.Log.e(G5CollectionService.TAG, "OnCharacteristic CHANGED started: " + BluetoothServices.getUUIDName(bluetoothGattCharacteristic.getUuid()));
                if (G5CollectionService.this.enforceMainThread()) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            processRxCharacteristic(bluetoothGatt, bluetoothGattCharacteristic);
                        }
                    });
                } else {
                    processRxCharacteristic(bluetoothGatt, bluetoothGattCharacteristic);
                }
            }

            public synchronized void processRxCharacteristic(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic) {
                int i;
                String str = G5CollectionService.TAG;
                UserError.Log.i(str, "onCharacteristicChanged On Main Thread? " + G5CollectionService.isOnMainThread());
                UserError.Log.e(str, "CharBytes-nfy" + Arrays.toString(bluetoothGattCharacteristic.getValue()));
                UserError.Log.i(str, "CharHex-nfy" + Extensions.bytesToHex(bluetoothGattCharacteristic.getValue()));
                byte[] value = bluetoothGattCharacteristic.getValue();
                byte b = value[0];
                if (bluetoothGatt != null) {
                    bluetoothGatt.requestConnectionPriority(1);
                }
                UserError.Log.d(str, "Received opcode reply: " + JoH.bytesToHex(new byte[]{b}));
                if (b == 47) {
                    SensorRxMessage sensorRxMessage = new SensorRxMessage(bluetoothGattCharacteristic.getValue());
                    ByteBuffer allocate = ByteBuffer.allocate(value.length);
                    allocate.order(ByteOrder.LITTLE_ENDIAN);
                    allocate.put(value, 0, value.length);
                    TransmitterStatus transmitterStatus = sensorRxMessage.status;
                    if (transmitterStatus == TransmitterStatus.BRICKED) {
                        i = 206;
                    } else {
                        i = transmitterStatus == TransmitterStatus.LOW ? 209 : 216;
                    }
                    int i2 = i;
                    int unused = G5CollectionService.disconnected133 = 0;
                    int unused2 = G5CollectionService.disconnected59 = 0;
                    G5BaseService.lastState = "Got data OK: " + JoH.hourMinuteString();
                    G5CollectionService.access$2408();
                    int unused3 = G5CollectionService.failures = 0;
                    UserError.Log.e(str, "SUCCESS!! unfiltered: " + sensorRxMessage.unfiltered + " timestamp: " + sensorRxMessage.timestamp + " " + JoH.qs(sensorRxMessage.timestamp / 86400.0d, 1) + " days");
                    if (sensorRxMessage.unfiltered == 0) {
                        G5BaseService.lastState = "Transmitter sent raw sensor value of 0 !! This isn't good. " + JoH.hourMinuteString();
                    }
                    long unused4 = G5CollectionService.last_transmitter_timestamp = sensorRxMessage.timestamp;
                    if (!G5CollectionService.this.haveFirmwareDetails()) {
                        G5CollectionService.this.doVersionRequestMessage(bluetoothGatt, bluetoothGattCharacteristic);
                    } else {
                        if (!G5BaseService.getBatteryStatusNow && G5CollectionService.this.haveCurrentBatteryStatus()) {
                            G5CollectionService.this.doDisconnectMessage(bluetoothGatt, bluetoothGattCharacteristic);
                        }
                        G5CollectionService.this.doBatteryInfoRequestMessage(bluetoothGatt, bluetoothGattCharacteristic);
                    }
                    boolean usingG6 = G5BaseService.usingG6();
                    G5CollectionService.this.processNewTransmitterData(usingG6 ? sensorRxMessage.unfiltered * 34 : sensorRxMessage.unfiltered, usingG6 ? sensorRxMessage.filtered * 34 : sensorRxMessage.filtered, i2, new Date().getTime());
                    if (G5CollectionService.this.force_always_authenticate && G5CollectionService.successes == 1) {
                        UserError.Log.wtf(str, "We apparently only got a reading after forcing the Always Authenticate option");
                        Home.toaststaticnext("Please Enable G5 Always Authenticate debug option!");
                    }
                } else if (b == 49) {
                    int unused5 = G5CollectionService.disconnected133 = 0;
                    int unused6 = G5CollectionService.disconnected59 = 0;
                    GlucoseRxMessage glucoseRxMessage = new GlucoseRxMessage(bluetoothGattCharacteristic.getValue());
                    UserError.Log.e(str, "SUCCESS!! glucose unfiltered: " + glucoseRxMessage.unfiltered);
                    G5CollectionService.access$2408();
                    int unused7 = G5CollectionService.failures = 0;
                    G5CollectionService.this.doDisconnectMessage(bluetoothGatt, bluetoothGattCharacteristic);
                    G5CollectionService.this.processNewTransmitterData(glucoseRxMessage.unfiltered, glucoseRxMessage.filtered, 216, new Date().getTime());
                } else if (b == 33) {
                    if (!G5CollectionService.setStoredFirmwareBytes(G5CollectionService.this.defaultTransmitter.transmitterId, bluetoothGattCharacteristic.getValue(), true)) {
                        UserError.Log.wtf(str, "Could not save out firmware version!");
                    }
                    G5CollectionService.this.doDisconnectMessage(bluetoothGatt, bluetoothGattCharacteristic);
                } else if (b == 35) {
                    if (!G5CollectionService.setStoredBatteryBytes(G5CollectionService.this.defaultTransmitter.transmitterId, bluetoothGattCharacteristic.getValue())) {
                        UserError.Log.wtf(str, "Could not save out battery data!");
                    }
                    G5BaseService.getBatteryStatusNow = false;
                    G5CollectionService.this.doDisconnectMessage(bluetoothGatt, bluetoothGattCharacteristic);
                } else {
                    UserError.Log.e(str, "onCharacteristic CHANGED unexpected opcode: " + ((int) b) + " (have not disconnected!)");
                }
                UserError.Log.e(str, "OnCharacteristic CHANGED finished: ");
            }
        };
        this.mPairingRequestRecevier = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (G5CollectionService.this.device != null && G5CollectionService.this.device.getAddress() != null) {
                    UserError.Log.e(G5CollectionService.TAG, "Processing mPairingRequestReceiver");
                    JoH.doPairingRequest(context, this, intent, G5CollectionService.this.device.getAddress());
                } else {
                    UserError.Log.e(G5CollectionService.TAG, "Received pairing request but device was null");
                }
            }
        };
    }

    static int access$2208() {
        int i = failures;
        failures = i + 1;
        return i;
    }

    static int access$2408() {
        int i = successes;
        successes = i + 1;
        return i;
    }

    static int access$2908() {
        int i = disconnected133;
        disconnected133 = i + 1;
        return i;
    }

    static int access$3208() {
        int i = disconnected59;
        disconnected59 = i + 1;
        return i;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        int i = Build.VERSION.SDK_INT;
        initScanCallback();
        this.advertiseTimeMS.add(0L);
        this.prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        listenForChangeInSettings(true);
        IntentFilter intentFilter = new IntentFilter("android.bluetooth.device.action.BOND_STATE_CHANGED");
        intentFilter.addAction("android.bluetooth.device.action.FOUND");
        registerReceiver(this.mPairReceiver, intentFilter);
        IntentFilter intentFilter2 = new IntentFilter("android.bluetooth.device.action.PAIRING_REQUEST");
        intentFilter2.setPriority(999);
        if (i < 26) {
            registerReceiver(this.mPairingRequestRecevier, intentFilter2);
        } else {
            UserError.Log.d(TAG, "Not registering pairing receiver on Android 8+");
        }
    }

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

    @Override
    public int onStartCommand(Intent intent, int i, int i2) {
        xdrip.checkAppContext(getApplicationContext());
        PowerManager.WakeLock wakeLock = JoH.getWakeLock("g5-start-service", 120000);
        try {
            if (!service_running && keep_running) {
                service_running = true;
                String str = TAG;
                UserError.Log.d(str, "onG5StartCommand wakeup: " + JoH.dateTimeText(JoH.tsl()));
                UserError.Log.e(str, "settingsToString: " + settingsToString());
                G5BaseService.lastState = "Started: " + JoH.hourMinuteString();
                if (!shouldServiceRun()) {
                    UserError.Log.e(str, "Shutting down as no longer using G5 data source");
                    service_running = false;
                    keep_running = false;
                    stopSelf();
                    return 2;
                }
                this.scanCycleCount = 0;
                BluetoothManager bluetoothManager = (BluetoothManager) getSystemService("bluetooth");
                this.mBluetoothManager = bluetoothManager;
                this.mBluetoothAdapter = bluetoothManager.getAdapter();
                if (this.mGatt != null) {
                    try {
                        UserError.Log.d(str, "onStartCommand mGatt != null; mGatt.close() and set to null.");
                        this.mGatt.close();
                        this.mGatt = null;
                    } catch (NullPointerException unused) {
                    }
                }
                if (Sensor.isActive()) {
                    setupBluetooth();
                    UserError.Log.d(TAG, "Active Sensor");
                } else {
                    stopScan();
                    UserError.Log.d(TAG, "No Active Sensor");
                }
                service_running = false;
                if (JoH.quietratelimit("evaluateG6Settingsc", 600)) {
                    evaluateG6Settings();
                }
                return 1;
            }
            UserError.Log.e(TAG, "G5 service already active!");
            keepAlive();
            return 2;
        } finally {
            JoH.releaseWakeLock(wakeLock);
        }
    }

    public void evaluateG6Settings() {
        if (this.defaultTransmitter == null) {
            getTransmitterDetails();
        }
        if (haveFirmwareDetails() && FirmwareCapability.isTransmitterG6(this.defaultTransmitter.transmitterId) && !G5BaseService.usingG6()) {
            G5BaseService.setG6bareBones();
            JoH.showNotification("Enabled G6", "G6 Features for old collector automatically enabled", null, 1014, false, true, false);
            UserError.Log.uel(TAG, "G6 Features for old collector automatically enabled");
        }
    }

    public synchronized void getTransmitterDetails() {
        this.prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        String str = TAG;
        UserError.Log.d(str, "Transmitter: " + this.prefs.getString("dex_txid", "ABCDEF"));
        this.defaultTransmitter = new Transmitter(this.prefs.getString("dex_txid", "ABCDEF"));
        boolean booleanValue = this.isBonded.booleanValue();
        Boolean bool = Boolean.FALSE;
        this.isBondedOrBonding = bool;
        this.isBonded = bool;
        static_is_bonded = false;
        BluetoothAdapter bluetoothAdapter = this.mBluetoothAdapter;
        if (bluetoothAdapter == null) {
            UserError.Log.wtf(str, "No bluetooth adapter");
            return;
        }
        Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
        if (bondedDevices != null && bondedDevices.size() > 0) {
            for (BluetoothDevice bluetoothDevice : bondedDevices) {
                if (bluetoothDevice.getName() != null) {
                    if (Extensions.lastTwoCharactersOfString(this.defaultTransmitter.transmitterId).equals(Extensions.lastTwoCharactersOfString(bluetoothDevice.getName()))) {
                        Boolean bool2 = Boolean.TRUE;
                        this.isBondedOrBonding = bool2;
                        this.isBonded = bool2;
                        static_is_bonded = true;
                        if (!booleanValue) {
                            UserError.Log.e(TAG, "Device is now detected as bonded!");
                        }
                    } else {
                        this.isIntialScan = true;
                    }
                }
            }
        }
        if (booleanValue && !this.isBonded.booleanValue()) {
            UserError.Log.e(TAG, "Device is no longer detected as bonded!");
        }
        String str2 = TAG;
        StringBuilder sb = new StringBuilder();
        sb.append("getTransmitterDetails() result: Bonded? ");
        sb.append(this.isBondedOrBonding.toString());
        sb.append(this.isBonded.booleanValue() ? " localed bonded" : " not locally bonded");
        UserError.Log.d(str2, sb.toString());
    }

    private static boolean shouldServiceRun() {
        boolean z = CollectionServiceStarter.isBTG5(xdrip.getAppContext()) && !Home.get_forced_wear();
        UserError.Log.d(TAG, "shouldServiceRun() returning: " + z);
        return z;
    }

    @Override
    public void onDestroy() {
        listenForChangeInSettings(false);
        isScanning = true;
        stopScan();
        isScanning = false;
        String str = TAG;
        UserError.Log.d(str, "onDestroy");
        scan_interval_timer.cancel();
        if (pendingIntent != null && !shouldServiceRun()) {
            UserError.Log.d(str, "onDestroy stop Alarm pendingIntent");
            AlarmManager alarmManager = (AlarmManager) getSystemService("alarm");
            if (alarmManager != null) {
                alarmManager.cancel(pendingIntent);
            }
        }
        try {
            unregisterReceiver(this.mPairReceiver);
        } catch (Exception e) {
            UserError.Log.e(TAG, "Got exception unregistering bonding receiver: ", e);
        }
        try {
            unregisterReceiver(this.mPairingRequestRecevier);
        } catch (Exception e2) {
            UserError.Log.e(TAG, "Got exception unregistering pairing receiver: ", e2);
        }
        UserError.Log.i(TAG, "SERVICE STOPPED");
        G5BaseService.lastState = "Stopped";
        super.onDestroy();
    }

    public synchronized void keepAlive() {
        keepAlive(0);
    }

    public synchronized void keepAlive(int i) {
        long timeInMillis;
        String str = TAG;
        UserError.Log.d(str, "keepAlive keep_running=" + keep_running);
        if (keep_running) {
            if (JoH.ratelimit("G5-keepalive", 5)) {
                if (i == 0) {
                    timeInMillis = getNextAdvertiseTime() - 60000;
                } else {
                    timeInMillis = Calendar.getInstance().getTimeInMillis() + i;
                }
                UserError.Log.e(str, "Scheduling Wake Time: in " + JoH.qs((timeInMillis - JoH.tsl()) / 1000, 0) + " secs " + JoH.dateTimeText(timeInMillis));
                AlarmManager alarmManager = (AlarmManager) getSystemService("alarm");
                PendingIntent pendingIntent2 = pendingIntent;
                if (pendingIntent2 != null) {
                    alarmManager.cancel(pendingIntent2);
                }
                pendingIntent = PendingIntent.getService(this, 0, new Intent(this, getClass()), 0);
                alarmManager.setExactAndAllowWhileIdle(0, timeInMillis, pendingIntent);
            } else {
                UserError.Log.e(str, "Ignoring keepalive call due to ratelimit");
            }
        }
    }

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

    public void setupBluetooth() {
        getTransmitterDetails();
        BluetoothAdapter bluetoothAdapter = this.mBluetoothAdapter;
        if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
            new Intent("android.bluetooth.adapter.action.REQUEST_ENABLE");
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    try {
                        if (G5CollectionService.this.mBluetoothAdapter != null) {
                            G5CollectionService.this.mBluetoothAdapter.enable();
                        }
                    } catch (SecurityException unused) {
                        JoH.static_toast_short("Please enable Bluetooth!");
                    }
                }
            }, 1000L);
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    G5CollectionService.this.setupBluetooth();
                }
            }, 10000L);
            return;
        }
        this.mLEScanner = this.mBluetoothAdapter.getBluetoothLeScanner();
        this.settings = new ScanSettings.Builder().setScanMode(2).build();
        this.filters = new ArrayList();
        String lastTwoCharactersOfString = Extensions.lastTwoCharactersOfString(this.defaultTransmitter.transmitterId);
        this.filters.add(new ScanFilter.Builder().setDeviceName("Dexcom" + lastTwoCharactersOfString).build());
        if (alwaysUnbond()) {
            forgetDevice();
        }
        JoH.ratelimit("G5-timeout", 0);
        cycleScan(0);
    }

    public synchronized void stopScan() {
        if (!isScanning) {
            UserError.Log.d(TAG, "alreadyStoppedScanning");
            return;
        }
        BluetoothAdapter bluetoothAdapter = this.mBluetoothAdapter;
        if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
            try {
                if (enforceMainThread()) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            G5CollectionService.this.stopLogic();
                        }
                    });
                } else {
                    stopLogic();
                }
            } catch (NullPointerException unused) {
                UserError.Log.e(TAG, "stopscan() Caught the NullPointerException");
            }
        }
    }

    public synchronized void stopLogic() {
        try {
            UserError.Log.e(TAG, "stopScan");
            try {
                this.mLEScanner.stopScan(this.mScanCallback);
            } catch (IllegalStateException | NullPointerException e) {
                UserError.Log.e(TAG, "Exception in stopLogic: " + e);
            }
            isScanning = false;
        } catch (IllegalStateException unused) {
        }
    }

    public synchronized void cycleScan(int i) {
        String str = TAG;
        UserError.Log.d(str, "cycleScan keep_running=" + keep_running);
        if (!keep_running) {
            UserError.Log.e(str, " OnDestroy failed to stop service. Shutting down now to prevent service from being initiated onScanResult().");
            stopSelf();
            return;
        }
        if (!JoH.ratelimit("G5-timeout", 60) && scan_scheduled) {
            UserError.Log.e(str, "jamorham blocked excessive scan schedule");
        }
        if (JoH.ratelimit("g5-scan-log", 60)) {
            UserError.Log.d(str, "cycleScan running");
        }
        scan_scheduled = true;
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                if (!G5CollectionService.this.scanConstantly()) {
                    if (G5CollectionService.this.mBluetoothAdapter != null) {
                        try {
                            if (G5CollectionService.this.mBluetoothAdapter.isEnabled()) {
                                try {
                                    if (!G5CollectionService.this.enforceMainThread()) {
                                        G5CollectionService.this.scanLogic();
                                    } else {
                                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                                            @Override
                                            public void run() {
                                                G5CollectionService.this.scanLogic();
                                            }
                                        });
                                    }
                                } catch (NullPointerException unused) {
                                    UserError.Log.e(G5CollectionService.TAG, "Caught the NullPointerException in cyclescan");
                                }
                                boolean unused2 = G5CollectionService.scan_scheduled = false;
                            }
                        } finally {
                            boolean unused3 = G5CollectionService.scan_scheduled = false;
                        }
                    }
                } else {
                    G5CollectionService.this.startScan();
                }
            }
        }, i);
    }

    public synchronized void scanLogic() {
        String str = TAG;
        UserError.Log.d(str, "scanLogic keep_running=" + keep_running);
        if (keep_running) {
            if (JoH.ratelimit("G5-scanlogic", 1)) {
                try {
                    this.mLEScanner.stopScan(this.mScanCallback);
                    isScanning = false;
                    if (!this.isConnected) {
                        this.mLEScanner.startScan(this.filters, this.settings, this.mScanCallback);
                        G5BaseService.lastState = "Scanning";
                        if (JoH.ratelimit("g5-scan-log", 60)) {
                            UserError.Log.w(str, "scan cycle start");
                        }
                    }
                    isScanning = true;
                } catch (IllegalStateException | NullPointerException unused) {
                    setupBluetooth();
                }
                int i = this.scanCycleCount + 1;
                this.scanCycleCount = i;
                boolean z = this.isIntialScan;
                if (!z && i > this.maxScanCycles) {
                    scan_interval_timer.cancel();
                    Timer timer = new Timer();
                    scan_interval_timer = timer;
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            if (G5CollectionService.isScanning) {
                                G5CollectionService.this.keepAlive();
                            }
                            G5CollectionService.this.stopScan();
                        }
                    }, this.maxScanIntervalInMilliseconds);
                } else if (!z && getMillisecondsSinceLastSuccesfulSensorRead() > 660000) {
                    UserError.Log.e(TAG, "MSSinceSensorRx: " + getMillisecondsSinceLastSuccesfulSensorRead());
                    this.isIntialScan = true;
                    cycleBT();
                } else {
                    scan_interval_timer.cancel();
                    Timer timer2 = new Timer();
                    scan_interval_timer = timer2;
                    timer2.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            G5CollectionService.this.cycleScan(0);
                        }
                    }, this.maxScanIntervalInMilliseconds);
                }
            }
        }
    }

    public synchronized void startScan() {
        String str = TAG;
        UserError.Log.e(str, "Initial scan?" + this.isIntialScan);
        if (isScanning) {
            UserError.Log.d(str, "alreadyScanning");
            scan_interval_timer.cancel();
            UserError.Log.d(str, "startScan keep_running=" + keep_running);
            if (keep_running) {
                return;
            } else {
                return;
            }
        }
        UserError.Log.d(str, "startScan keep_running=" + keep_running);
        if (keep_running) {
            getTransmitterDetails();
            BluetoothAdapter bluetoothAdapter = this.mBluetoothAdapter;
            if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
                if (enforceMainThread()) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            G5CollectionService.this.startLogic();
                        }
                    });
                } else {
                    startLogic();
                }
                UserError.Log.e(str, "startScan normal");
            }
            setupBluetooth();
        }
    }

    public synchronized void startLogic() {
        try {
            isScanning = true;
            this.mLEScanner.startScan(this.filters, this.settings, this.mScanCallback);
        } catch (Exception unused) {
            isScanning = false;
            setupBluetooth();
        }
    }

    public synchronized void cycleBT(boolean z) {
        String str = TAG;
        UserError.Log.e(str, "cycleBT special: count:" + disconnected133 + " / " + disconnected59);
        if (disconnected133 < 2 && disconnected59 < 2) {
            cycleBT();
        } else {
            UserError.Log.e(str, "jamorham special restart");
            keepAlive(ErrorCode.INVALID_OWNERSHIP);
            BluetoothGatt bluetoothGatt = this.mGatt;
            if (bluetoothGatt != null) {
                try {
                    bluetoothGatt.close();
                } catch (NullPointerException unused) {
                    UserError.Log.d(TAG, "concurrency related null pointer exception in close");
                }
            }
            disconnected133 = 0;
            disconnected59 = 0;
            stopSelf();
        }
    }

    public synchronized void cycleBT() {
        synchronized (short_lock) {
            if (JoH.ratelimit("cyclebt", 20)) {
                if (cycling_bt) {
                    UserError.Log.e(TAG, "jamorham Already concurrent BT cycle in progress!");
                    return;
                }
                this.encountered133 = false;
                stopScan();
                if (g5BluetoothWatchdog()) {
                    UserError.Log.e(TAG, "Cycling BT-gatt - disabling BT");
                    this.mBluetoothAdapter.disable();
                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            G5CollectionService.this.mBluetoothAdapter.enable();
                            UserError.Log.e(G5CollectionService.TAG, "Cycling BT-gatt - enableing BT");
                            boolean unused = G5CollectionService.cycling_bt = false;
                        }
                    }, 3000L);
                } else {
                    UserError.Log.e(TAG, "Wanted to cycle g5 bluetooth but is disabled in advanced bluetooth preferences!");
                    waitFor(3000);
                }
            }
            keepAlive();
        }
    }

    public synchronized void forgetDevice() {
        UserError.Log.d(TAG, "forgetDevice() start");
        Transmitter transmitter = new Transmitter(this.prefs.getString("dex_txid", "ABCDEF"));
        BluetoothAdapter adapter = this.mBluetoothManager.getAdapter();
        this.mBluetoothAdapter = adapter;
        Set<BluetoothDevice> bondedDevices = adapter.getBondedDevices();
        if (bondedDevices.size() > 0) {
            for (BluetoothDevice bluetoothDevice : bondedDevices) {
                if (bluetoothDevice.getName() != null) {
                    String lastTwoCharactersOfString = Extensions.lastTwoCharactersOfString(transmitter.transmitterId);
                    String lastTwoCharactersOfString2 = Extensions.lastTwoCharactersOfString(bluetoothDevice.getName());
                    if (lastTwoCharactersOfString.equals(lastTwoCharactersOfString2)) {
                        try {
                            UserError.Log.e(TAG, "removingBond: " + lastTwoCharactersOfString + " vs " + lastTwoCharactersOfString2);
                            bluetoothDevice.getClass().getMethod("removeBond", null).invoke(bluetoothDevice, null);
                            getTransmitterDetails();
                        } catch (Exception e) {
                            UserError.Log.e(TAG, e.getMessage(), e);
                        }
                    }
                }
            }
        }
        UserError.Log.d(TAG, "forgetDevice() finished");
    }

    private void initScanCallback() {
        this.mScanCallback = new ScanCallback() {
            @Override
            public void onScanResult(int i, ScanResult scanResult) {
                UserError.Log.i(G5CollectionService.TAG, "result: " + scanResult.toString());
                BluetoothDevice device = scanResult.getDevice();
                if (device.getName() == null || !Extensions.lastTwoCharactersOfString(G5CollectionService.this.defaultTransmitter.transmitterId).equals(Extensions.lastTwoCharactersOfString(device.getName()))) {
                    return;
                }
                if (G5CollectionService.this.advertiseTimeMS.size() > 0) {
                    long time = new Date().getTime();
                    ArrayList<Long> arrayList = G5CollectionService.this.advertiseTimeMS;
                    if (time - arrayList.get(arrayList.size() - 1).longValue() > 150000.0d) {
                        G5CollectionService.this.advertiseTimeMS.clear();
                    }
                }
                G5CollectionService.this.advertiseTimeMS.add(Long.valueOf(new Date().getTime()));
                G5CollectionService g5CollectionService = G5CollectionService.this;
                g5CollectionService.isIntialScan = false;
                g5CollectionService.device = g5CollectionService.mBluetoothAdapter.getRemoteDevice(device.getAddress());
                String unused = G5CollectionService.static_device_address = device.getAddress();
                G5CollectionService.this.stopScan();
                G5CollectionService.this.connectToDevice(device);
            }

            @Override
            public void onScanFailed(int i) {
                String str = G5CollectionService.TAG;
                UserError.Log.e(str, "Scan Failed Error Code: " + i);
                if (i != 1) {
                    if (i == 2) {
                        G5CollectionService.this.cycleBT();
                    }
                } else {
                    UserError.Log.e(str, "Already Scanning: " + G5CollectionService.isScanning);
                }
            }
        };
    }

    public synchronized void fullAuthenticate() {
        String str = TAG;
        UserError.Log.e(str, "fullAuthenticate() start");
        if (alwaysUnbond()) {
            forgetDevice();
        }
        try {
            UserError.Log.i(str, "Start Auth Process(fullAuthenticate)");
            BluetoothGattCharacteristic bluetoothGattCharacteristic = this.authCharacteristic;
            if (bluetoothGattCharacteristic != null) {
                sendAuthRequestTxMessage(this.mGatt, bluetoothGattCharacteristic);
            } else {
                UserError.Log.e(str, "fullAuthenticate: authCharacteristic is NULL!");
            }
        } catch (NullPointerException e) {
            UserError.Log.e(TAG, "Got null pointer in fullAuthenticate: " + e);
        }
    }

    public synchronized void authenticate() {
        String str = TAG;
        UserError.Log.e(str, "authenticate() start");
        try {
            this.mGatt.setCharacteristicNotification(this.authCharacteristic, true);
            if (!this.mGatt.readCharacteristic(this.authCharacteristic)) {
                UserError.Log.e(str, "onCharacteristicRead : ReadCharacteristicError");
            }
        } catch (NullPointerException e) {
            UserError.Log.e(TAG, "Got Nullpointer exception in authenticate(): " + e);
        }
    }

    public synchronized void getSensorData() {
        String str = TAG;
        UserError.Log.i(str, "Request Sensor Data");
        try {
            BluetoothGatt bluetoothGatt = this.mGatt;
            if (bluetoothGatt != null) {
                bluetoothGatt.setCharacteristicNotification(this.controlCharacteristic, true);
                BluetoothGattDescriptor descriptor = this.controlCharacteristic.getDescriptor(BluetoothServices.CharacteristicUpdateNotification);
                descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
                if (useG5NewMethod()) {
                    this.controlCharacteristic.setValue(new GlucoseTxMessage().byteSequence);
                } else {
                    this.controlCharacteristic.setValue(new SensorTxMessage().byteSequence);
                }
                UserError.Log.d(str, "getSensorData(): writing desccrptor");
                this.mGatt.writeDescriptor(descriptor);
            } else {
                UserError.Log.e(str, "getSensorData() mGatt was null");
            }
        } catch (NullPointerException e) {
            UserError.Log.e(TAG, "Got null pointer in getSensorData() " + e);
        }
    }

    public synchronized void connectToDevice(final BluetoothDevice bluetoothDevice) {
        if (JoH.ratelimit("G5connect-rate", 2)) {
            String str = TAG;
            UserError.Log.d(str, "connectToDevice() start");
            if (this.mGatt != null) {
                UserError.Log.i(str, "BGatt isnt null, Closing.");
                try {
                    this.mGatt.close();
                } catch (NullPointerException unused) {
                }
                this.mGatt = null;
            }
            UserError.Log.i(TAG, "Request Connect");
            if (enforceMainThread()) {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        G5CollectionService.this.connectGatt(bluetoothDevice);
                    }
                });
            } else {
                connectGatt(bluetoothDevice);
            }
        } else {
            UserError.Log.e(TAG, "connectToDevice baulking due to rate-limit");
        }
    }

    public synchronized void connectGatt(BluetoothDevice bluetoothDevice) {
        String str = TAG;
        UserError.Log.i(str, "mGatt Null, connecting...");
        UserError.Log.i(str, "connectToDevice On Main Thread? " + isOnMainThread());
        G5BaseService.lastState = "Found, Connecting";
        if (this.max133RetryCounter > 1) {
            UserError.Log.e(str, "Adding a delay before connecting to 133 count of: " + this.max133RetryCounter);
            waitFor(600);
            UserError.Log.e(str, "connectGatt() delay completed");
        }
        this.mGatt = bluetoothDevice.connectGatt(getApplicationContext(), false, this.gattCallback);
    }

    public synchronized void doDisconnectMessage(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic) {
        String str = TAG;
        UserError.Log.d(str, "doDisconnectMessage() start");
        bluetoothGatt.setCharacteristicNotification(this.controlCharacteristic, false);
        bluetoothGattCharacteristic.setValue(new DisconnectTxMessage().byteSequence);
        bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristic);
        bluetoothGatt.disconnect();
        UserError.Log.d(str, "doDisconnectMessage() finished");
    }

    public synchronized void doVersionRequestMessage(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic) {
        String str = TAG;
        UserError.Log.d(str, "doVersionRequestMessage() start");
        bluetoothGattCharacteristic.setValue(new VersionRequestTxMessage().byteSequence);
        bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristic);
        UserError.Log.d(str, "doVersionRequestMessage() finished");
    }

    public synchronized void doBatteryInfoRequestMessage(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic) {
        String str = TAG;
        UserError.Log.d(str, "doBatteryInfoMessage() start");
        bluetoothGattCharacteristic.setValue(new BatteryInfoTxMessage().byteSequence);
        bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristic);
        UserError.Log.d(str, "doBatteryInfoMessage() finished");
    }

    public synchronized void discoverServices() {
        if (JoH.ratelimit("G5-discservices", 2)) {
            String str = TAG;
            StringBuilder sb = new StringBuilder();
            sb.append("discoverServices() started ");
            sb.append(isOnMainThread() ? "on main thread" : "not on main thread");
            UserError.Log.i(str, sb.toString());
            if (this.mGatt != null) {
                if (this.max133RetryCounter > 1) {
                    UserError.Log.e(str, "Adding a delay before discovering services due to 133 count of: " + this.max133RetryCounter);
                    waitFor(1600);
                }
                this.mGatt.discoverServices();
            } else {
                UserError.Log.e(str, "discoverServices: mGatt is null");
            }
        } else {
            UserError.Log.e(TAG, "discoverServices rate limited!");
        }
    }

    public boolean haveFirmwareDetails() {
        return this.defaultTransmitter.transmitterId.length() == 6 && getStoredFirmwareBytes(this.defaultTransmitter.transmitterId).length >= 10;
    }

    public boolean haveCurrentBatteryStatus() {
        if (this.defaultTransmitter.transmitterId.length() == 6) {
            if (JoH.msSince(PersistentStore.getLong("g5-battery-from" + this.defaultTransmitter.transmitterId)) < 43200000) {
                return true;
            }
        }
        return false;
    }

    private static byte[] getStoredFirmwareBytes(String str) {
        if (str.length() != 6) {
            return new byte[0];
        }
        return PersistentStore.getBytes("g5-firmware-" + str);
    }

    public static boolean setStoredFirmwareBytes(String str, byte[] bArr) {
        return setStoredFirmwareBytes(str, bArr, false);
    }

    public static boolean setStoredFirmwareBytes(String str, byte[] bArr, boolean z) {
        if (z) {
            UserError.Log.e(TAG, "Store: VersionRX dbg: " + JoH.bytesToHex(bArr));
        }
        if (str.length() != 6 || bArr.length < 10) {
            return false;
        }
        if (!JoH.ratelimit("store-firmware-bytes", 60)) {
            return true;
        }
        PersistentStore.setBytes("g5-firmware-" + str, bArr);
        return true;
    }

    public static synchronized boolean setStoredBatteryBytes(String str, byte[] bArr) {
        synchronized (G5CollectionService.class) {
            String str2 = TAG;
            UserError.Log.e(str2, "Store: BatteryRX dbg: " + JoH.bytesToHex(bArr));
            if (str.length() != 6) {
                return false;
            }
            if (bArr.length < 10) {
                return false;
            }
            G5BaseService.updateBatteryWarningLevel();
            BatteryInfoRxMessage batteryInfoRxMessage = new BatteryInfoRxMessage(bArr);
            UserError.Log.wtf(str2, "Saving battery data: " + batteryInfoRxMessage.toString());
            PersistentStore.setBytes("g5-battery-" + str, bArr);
            PersistentStore.setLong("g5-battery-from" + str, JoH.tsl());
            long j = PersistentStore.getLong("g5-battery-level-" + str);
            int i = batteryInfoRxMessage.voltagea;
            if (i < j || j == 0) {
                if (i < G5BaseService.LOW_BATTERY_WARNING_LEVEL && JoH.pratelimit("g5-low-battery-warning", 40000)) {
                    boolean z = !PowerStateReceiver.is_power_connected();
                    JoH.showNotification("G5 Battery Low", "G5 Transmitter battery has dropped to: " + batteryInfoRxMessage.voltagea + " it may fail soon", null, 770, "lowTransmitterBattery", z, z, null, null, null);
                    StringBuilder sb = new StringBuilder();
                    sb.append("G5 Transmitter battery has dropped to: ");
                    sb.append(batteryInfoRxMessage.voltagea);
                    UserError.Log.uel(str2, sb.toString());
                }
                PersistentStore.setLong("g5-battery-level-" + str, batteryInfoRxMessage.voltagea);
            }
            return true;
        }
    }

    public static BatteryInfoRxMessage getBatteryDetails(String str) {
        try {
            byte[] bytes = PersistentStore.getBytes("g5-battery-" + str);
            if (bytes.length > 0) {
                return new BatteryInfoRxMessage(bytes);
            }
            return null;
        } catch (Exception e) {
            UserError.Log.wtf(TAG, "Exception in getFirmwareDetails: " + e);
            return null;
        }
    }

    public static VersionRequestRxMessage getFirmwareDetails(String str) {
        try {
            byte[] storedFirmwareBytes = getStoredFirmwareBytes(str);
            if (storedFirmwareBytes == null || storedFirmwareBytes.length <= 9) {
                return null;
            }
            return new VersionRequestRxMessage(storedFirmwareBytes);
        } catch (Exception e) {
            UserError.Log.wtf(TAG, "Exception in getFirmwareDetails: " + e);
            return null;
        }
    }

    public static String getFirmwareVersionString(String str) {
        VersionRequestRxMessage firmwareDetails = getFirmwareDetails(str);
        if (firmwareDetails == null) {
            return "";
        }
        return "FW: " + firmwareDetails.firmware_version_string;
    }

    public synchronized void sendAuthRequestTxMessage(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic) {
        String str = TAG;
        UserError.Log.e(str, "Sending new AuthRequestTxMessage to " + BluetoothServices.getUUIDName(bluetoothGattCharacteristic.getUuid()) + " ...");
        this.authRequest = new AuthRequestTxMessage(getTokenSize());
        UserError.Log.i(str, "AuthRequestTX: " + JoH.bytesToHex(this.authRequest.byteSequence));
        bluetoothGattCharacteristic.setValue(this.authRequest.byteSequence);
        if (bluetoothGatt != null) {
            bluetoothGatt.writeCharacteristic(bluetoothGattCharacteristic);
        } else {
            UserError.Log.e(str, "Cannot send AuthRequestTx as supplied gatt is null!");
        }
    }

    public synchronized void processNewTransmitterData(int i, int i2, int i3, long j) {
        TransmitterData create = TransmitterData.create(i, i2, i3, j);
        if (create == null) {
            UserError.Log.e(TAG, "TransmitterData.create failed: Duplicate packet");
            return;
        }
        this.timeInMillisecondsOfLastSuccessfulSensorRead = j;
        Sensor currentSensor = Sensor.currentSensor();
        if (currentSensor == null) {
            UserError.Log.e(TAG, "setSerialDataToTransmitterRawData: No Active Sensor, Data only stored in Transmitter Data");
            return;
        }
        Sensor.updateBatteryLevel(currentSensor, create.sensor_battery_level);
        String str = TAG;
        UserError.Log.i(str, "timestamp create: " + Long.toString(create.timestamp));
        BgReading.create(create.raw_data, create.filtered_data, this, Long.valueOf(create.timestamp));
        UserError.Log.d(str, "Dex raw_data " + Double.toString(create.raw_data));
        UserError.Log.d(str, "Dex filtered_data " + Double.toString(create.filtered_data));
        UserError.Log.d(str, "Dex sensor_battery_level " + Double.toString((double) create.sensor_battery_level));
        UserError.Log.d(str, "Dex timestamp " + JoH.dateTimeText(create.timestamp));
        G5BaseService.static_last_timestamp = create.timestamp;
    }

    @SuppressLint({"GetInstance"})
    public synchronized byte[] calculateHash(byte[] bArr) {
        if (bArr != null) {
            if (bArr.length == 8) {
                byte[] cryptKey = cryptKey();
                if (cryptKey == null) {
                    return null;
                }
                ByteBuffer allocate = ByteBuffer.allocate(16);
                allocate.put(bArr);
                allocate.put(bArr);
                byte[] array = allocate.array();
                try {
                    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
                    cipher.init(1, new SecretKeySpec(cryptKey, "AES"));
                    byte[] doFinal = cipher.doFinal(array, 0, array.length);
                    ByteBuffer allocate2 = ByteBuffer.allocate(8);
                    allocate2.put(doFinal, 0, 8);
                    return allocate2.array();
                } catch (InvalidKeyException | NoSuchAlgorithmException | BadPaddingException | IllegalBlockSizeException | NoSuchPaddingException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }
        UserError.Log.e(TAG, "Decrypt Data length should be exactly 8.");
        return null;
    }

    private byte[] cryptKey() {
        if (this.defaultTransmitter.transmitterId.length() != 6) {
            UserError.Log.e(TAG, "cryptKey: Wrong transmitter id length!: " + this.defaultTransmitter.transmitterId.length());
        }
        try {
            return ("00" + this.defaultTransmitter.transmitterId + "00" + this.defaultTransmitter.transmitterId).getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static boolean isOnMainThread() {
        return Looper.getMainLooper().getThread() == Thread.currentThread();
    }

    private long getNextAdvertiseTime() {
        long millisecondsSinceTxLastSeen = getMillisecondsSinceTxLastSeen();
        long time = (new Date().getTime() + (300000 - (millisecondsSinceTxLastSeen % 300000))) - 3000;
        String str = TAG;
        UserError.Log.e(str, "millisecondsSinceTxAd: " + millisecondsSinceTxLastSeen);
        UserError.Log.e(str, "advertiseTimeMS.get(0): " + this.advertiseTimeMS.get(0) + " " + JoH.dateTimeText(this.advertiseTimeMS.get(0).longValue()));
        StringBuilder sb = new StringBuilder();
        sb.append("timeInMillisecondsOfLastSuccessfulSensorRead:  ");
        sb.append(this.timeInMillisecondsOfLastSuccessfulSensorRead);
        sb.append(JoH.dateTimeText(this.timeInMillisecondsOfLastSuccessfulSensorRead));
        UserError.Log.e(str, sb.toString());
        return time;
    }

    protected void waitFor(int i) {
        synchronized (this.mLock) {
            try {
                UserError.Log.e(TAG, "waiting " + i + "ms");
                this.mLock.wait((long) i);
            } catch (InterruptedException e) {
                UserError.Log.e(TAG, "Sleeping interrupted", e);
            }
        }
    }

    private long getMillisecondsSinceTxLastSeen() {
        return new Date().getTime() - this.advertiseTimeMS.get(0).longValue();
    }

    private long getMillisecondsSinceLastSuccesfulSensorRead() {
        return new Date().getTime() - this.timeInMillisecondsOfLastSuccessfulSensorRead;
    }

    public boolean scanConstantly() {
        return PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean("run_ble_scan_constantly", false);
    }

    public boolean alwaysUnbond() {
        return PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean("always_unbond_G5", false);
    }

    public boolean alwaysAuthenticate() {
        return this.force_always_authenticate || PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean("always_get_new_keys", false);
    }

    public boolean enforceMainThread() {
        return PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean("run_G5_ble_tasks_on_uithread", false);
    }

    private boolean engineeringMode() {
        return Pref.getBooleanDefaultFalse("engineering_mode");
    }

    private boolean g5BluetoothWatchdog() {
        return Pref.getBoolean("g5_bluetooth_watchdog", true);
    }

    private String settingsToString() {
        StringBuilder sb = new StringBuilder();
        sb.append(scanConstantly() ? "scanConstantly " : "");
        sb.append(alwaysUnbond() ? "alwaysUnbond " : "");
        sb.append(alwaysAuthenticate() ? "alwaysAuthenticate " : "");
        sb.append(enforceMainThread() ? "enforceMainThread " : "");
        sb.append(useG5NewMethod() ? "useG5NewMethod " : "");
        sb.append("");
        sb.append("");
        sb.append("delayOn133Errors ");
        sb.append("tryOnDemandBondWithDelay ");
        sb.append(engineeringMode() ? "engineeringMode " : "");
        sb.append("");
        return sb.toString();
    }

    public static List<StatusItem> megaStatus() {
        String str;
        ArrayList arrayList = new ArrayList();
        arrayList.add(new StatusItem("Phone Service State", G5BaseService.lastState));
        if (G5BaseService.static_last_timestamp > 0) {
            arrayList.add(new StatusItem("Phone got Glucose", JoH.niceTimeSince(G5BaseService.static_last_timestamp) + " ago"));
        } else if (static_device_address != null) {
            if (Home.get_engineering_mode()) {
                arrayList.add(new StatusItem("Bluetooth Device", static_device_address));
            }
            arrayList.add(new StatusItem("Bonded", xdrip.gs(static_is_bonded ? 2131757071 : 2131755900), static_is_bonded ? StatusItem.Highlight.GOOD : StatusItem.Highlight.NOTICE));
        } else {
            arrayList.add(new StatusItem("Bluetooth Device", "Not yet found"));
        }
        if (Pref.getBooleanDefaultFalse("wear_sync") && Pref.getBooleanDefaultFalse("enable_wearG5")) {
            arrayList.add(new StatusItem("Watch Service State", G5BaseService.lastStateWatch));
            if (G5BaseService.static_last_timestamp_watch > 0) {
                arrayList.add(new StatusItem("Watch got Glucose", JoH.niceTimeSince(G5BaseService.static_last_timestamp_watch) + " ago"));
            }
        }
        String stringDefaultBlank = Pref.getStringDefaultBlank("dex_txid");
        arrayList.add(new StatusItem("Transmitter ID", stringDefaultBlank));
        VersionRequestRxMessage firmwareDetails = getFirmwareDetails(stringDefaultBlank);
        if (firmwareDetails != null) {
            try {
                if (firmwareDetails.firmware_version_string.length() > 0) {
                    arrayList.add(new StatusItem("Firmware Version", firmwareDetails.firmware_version_string));
                    if (Home.get_engineering_mode()) {
                        arrayList.add(new StatusItem("Bluetooth Version", firmwareDetails.bluetooth_firmware_version_string));
                        arrayList.add(new StatusItem("Other Version", firmwareDetails.other_firmware_version));
                        arrayList.add(new StatusItem("Hardware Version", Integer.valueOf(firmwareDetails.hardwarev)));
                        int i = firmwareDetails.asic;
                        if (i != 61440) {
                            arrayList.add(new StatusItem("ASIC", Integer.valueOf(i), StatusItem.Highlight.NOTICE));
                        }
                    }
                }
            } catch (NullPointerException unused) {
                arrayList.add(new StatusItem("Version", "Information corrupted", StatusItem.Highlight.BAD));
            }
        }
        BatteryInfoRxMessage batteryDetails = getBatteryDetails(stringDefaultBlank);
        long j = PersistentStore.getLong("g5-battery-from" + stringDefaultBlank);
        if (G5BaseService.getBatteryStatusNow) {
            arrayList.add(new StatusItem("Battery Status Request Queued", "Will attempt to read battery status on next sensor reading", StatusItem.Highlight.NOTICE, "long-press", new Runnable() {
                @Override
                public void run() {
                    G5BaseService.getBatteryStatusNow = false;
                }
            }));
        }
        if (batteryDetails != null && j > 0) {
            String str2 = JoH.niceTimeSince(j) + " ago";
            StatusItem.Highlight highlight = StatusItem.Highlight.NORMAL;
            arrayList.add(new StatusItem("Battery Last queried", str2, highlight, "long-press", new Runnable() {
                @Override
                public void run() {
                    G5BaseService.getBatteryStatusNow = true;
                }
            }));
            if (firmwareDetails != null) {
                arrayList.add(new StatusItem("Transmitter Status", TransmitterStatus.getBatteryLevel(firmwareDetails.status).toString()));
            }
            StringBuilder sb = new StringBuilder();
            sb.append(batteryDetails.runtime);
            if (last_transmitter_timestamp > 0) {
                str = " / " + JoH.qs(last_transmitter_timestamp / 86400.0d, 1);
            } else {
                str = "";
            }
            sb.append(str);
            arrayList.add(new StatusItem("Transmitter Days", sb.toString()));
            arrayList.add(new StatusItem("Voltage A", Integer.valueOf(batteryDetails.voltagea), batteryDetails.voltagea < G5BaseService.LOW_BATTERY_WARNING_LEVEL ? StatusItem.Highlight.BAD : highlight));
            arrayList.add(new StatusItem("Voltage B", Integer.valueOf(batteryDetails.voltageb), batteryDetails.voltageb < G5BaseService.LOW_BATTERY_WARNING_LEVEL + (-10) ? StatusItem.Highlight.BAD : highlight));
            int i2 = batteryDetails.resist;
            if (i2 != 0) {
                Integer valueOf = Integer.valueOf(i2);
                int i3 = batteryDetails.resist;
                if (i3 > 1400) {
                    highlight = StatusItem.Highlight.BAD;
                } else if (i3 > 1000) {
                    highlight = StatusItem.Highlight.NOTICE;
                } else if (i3 <= 750) {
                    highlight = StatusItem.Highlight.GOOD;
                }
                arrayList.add(new StatusItem("Resistance", valueOf, highlight));
            }
            arrayList.add(new StatusItem("Temperature", batteryDetails.temperature + " ℃"));
        }
        return arrayList;
    }
}