导航菜单

页面标题

页面副标题

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

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

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


package com.eveningoutpost.dexdrip.services;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.PendingIntent;
import android.app.Service;
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.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.IBinder;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.util.Log;
import com.eveningoutpost.dexdrip.GcmActivity;
import com.eveningoutpost.dexdrip.Home;
import com.eveningoutpost.dexdrip.importedlibraries.usbserial.driver.UsbId;
import com.eveningoutpost.dexdrip.importedlibraries.usbserial.util.HexDump;
import com.eveningoutpost.dexdrip.models.ActiveBluetoothDevice;
import com.eveningoutpost.dexdrip.models.Atom;
import com.eveningoutpost.dexdrip.models.BgReading;
import com.eveningoutpost.dexdrip.models.Bubble;
import com.eveningoutpost.dexdrip.models.JoH;
import com.eveningoutpost.dexdrip.models.LibreBluetooth;
import com.eveningoutpost.dexdrip.models.Sensor;
import com.eveningoutpost.dexdrip.models.Tomato;
import com.eveningoutpost.dexdrip.models.TransmitterData;
import com.eveningoutpost.dexdrip.models.UserError;
import com.eveningoutpost.dexdrip.models.blueReader;
import com.eveningoutpost.dexdrip.services.DexCollectionService;
import com.eveningoutpost.dexdrip.utilitymodels.Blukon;
import com.eveningoutpost.dexdrip.utilitymodels.BridgeResponse;
import com.eveningoutpost.dexdrip.utilitymodels.CollectionServiceStarter;
import com.eveningoutpost.dexdrip.utilitymodels.ForegroundServiceStarter;
import com.eveningoutpost.dexdrip.utilitymodels.Inevitable;
import com.eveningoutpost.dexdrip.utilitymodels.PersistentStore;
import com.eveningoutpost.dexdrip.utilitymodels.Pref;
import com.eveningoutpost.dexdrip.utilitymodels.StatusItem;
import com.eveningoutpost.dexdrip.utilitymodels.XbridgePlus;
import com.eveningoutpost.dexdrip.utils.BtCallBack;
import com.eveningoutpost.dexdrip.utils.CheckBridgeBattery;
import com.eveningoutpost.dexdrip.utils.DexCollectionType;
import com.eveningoutpost.dexdrip.utils.DisconnectReceiver;
import com.eveningoutpost.dexdrip.utils.bt.Helper;
import com.eveningoutpost.dexdrip.utils.bt.ScanMeister;
import com.eveningoutpost.dexdrip.utils.framework.WakeLockTrampoline;
import com.eveningoutpost.dexdrip.xdrip;
import com.google.android.gms.wearable.DataMap;
import com.rits.cloning.Cloner;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.UUID;

@TargetApi(19)
public class DexCollectionService extends Service implements BtCallBack {
    private static final String TAG = "DexCollectionService";
    private static String bondedState = null;
    private static int bondingTries = 0;
    private static volatile int descriptor_callback_failures = 0;
    private static volatile long descriptor_time = 0;
    private static volatile BluetoothDevice device = null;
    private static long failover_time = 0;
    private static byte[] immediateSend = null;
    public static String lastError = null;
    public static String lastState = "Not running";
    public static String lastStateWatch = "Not running";
    private static int last_battery_level = -1;
    private static long last_connect_request = 0;
    private static long last_time_seen = 0;
    public static TransmitterData last_transmitter_Data = null;
    private static TransmitterData last_transmitter_DataWatch = null;
    private static volatile BluetoothGatt mBluetoothGatt = null;
    private static volatile BluetoothGattCharacteristic mCharacteristic = null;
    private static volatile BluetoothGattCharacteristic mCharacteristicSend = null;
    private static volatile int mStaticState = 3;
    private static int mStaticStateWatch;
    private static long max_wakeup_jitter;
    private static long poll_backoff;
    private static long retry_backoff;
    private static long retry_time;
    private static volatile ScanMeister scanMeister;
    private static PendingIntent serviceFailoverIntent;
    private static PendingIntent serviceIntent;
    private static String static_last_hexdump;
    private static String static_last_hexdump_watch;
    private static String static_last_sent_hexdump;
    private static String static_last_sent_hexdump_watch;
    private static int watchdog_count;
    private final String DEFAULT_BT_PIN;
    private final UUID Libre2ServiceUUID;
    private final UUID blukonDataService;
    private final Cloner cloner;
    private volatile long delay_offset;
    public DexCollectionService dexCollectionService;
    private ForegroundServiceStarter foregroundServiceStarter;
    long lastPacketTime;
    private byte[] lastdata;
    private BluetoothAdapter mBluetoothAdapter;
    private volatile int mConnectionState;
    private String mDeviceAddress;
    private final BluetoothGattCallback mGattCallback;
    private final BroadcastReceiver mPairingRequestRecevier;
    public SharedPreferences.OnSharedPreferenceChangeListener prefListener;
    private SharedPreferences prefs;
    private final boolean use_polling;
    private final boolean use_rfduino_bluetooth;
    private final boolean use_transmiter_pl_bluetooth;
    private final UUID xDripDataCharacteristic;
    private final UUID xDripDataCharacteristicSend;
    private final UUID xDripDataService;
    private static volatile DISCOVERED servicesDiscovered = DISCOVERED.NULL;
    private static boolean static_use_transmiter_pl_bluetooth = false;
    private static boolean static_use_rfduino_bluetooth = false;
    private static boolean static_use_polling = false;
    private static boolean static_use_blukon = false;
    private static boolean static_use_nrf = false;
    private static int last_battery_level_watch = -1;
    private static int error133 = 0;
    private static long last_poll_sent = 0;
    private static long retry_time_watch = 0;
    private static long failover_time_watch = 0;
    private static final UUID CCCD = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
    private static int mStatus = -1;
    public final UUID nrfDataService = UUID.fromString("6E400001-B5A3-F393-E0A9-E50E24DCCA9E");
    public final UUID nrfDataRXCharacteristic = UUID.fromString("6E400003-B5A3-F393-E0A9-E50E24DCCA9E");
    public final UUID nrfDataTXCharacteristic = UUID.fromString("6E400002-B5A3-F393-E0A9-E50E24DCCA9E");
    private final Object mLock = new Object();

    private enum DISCOVERED {
        NULL,
        PENDING,
        COMPLETE
    }

    public DexCollectionService() {
        boolean booleanDefaultFalse = Pref.getBooleanDefaultFalse("use_transmiter_pl_bluetooth");
        this.use_transmiter_pl_bluetooth = booleanDefaultFalse;
        boolean booleanDefaultFalse2 = Pref.getBooleanDefaultFalse("use_rfduino_bluetooth");
        this.use_rfduino_bluetooth = booleanDefaultFalse2;
        this.use_polling = Pref.getBooleanDefaultFalse("pref_dex_collection_polling");
        this.xDripDataService = UUID.fromString(booleanDefaultFalse ? "c97433f0-be8f-4dc8-b6f0-5343e6100eb4" : "0000ffe0-0000-1000-8000-00805f9b34fb");
        this.xDripDataCharacteristic = booleanDefaultFalse ? UUID.fromString("c97433f1-be8f-4dc8-b6f0-5343e6100eb4") : UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb");
        this.xDripDataCharacteristicSend = booleanDefaultFalse2 ? UUID.fromString("0000ffe2-0000-1000-8000-00805f9b34fb") : UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb");
        this.DEFAULT_BT_PIN = getDefaultPin();
        this.blukonDataService = UUID.fromString("436a62c0-082e-4ce8-a08b-01d81f195b24");
        this.Libre2ServiceUUID = UUID.fromString("0000fde3-0000-1000-8000-00805f9b34fb");
        this.delay_offset = 0L;
        this.cloner = new Cloner();
        this.mPairingRequestRecevier = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                UserError.Log.d(DexCollectionService.TAG, "Received pairing request");
                if (JoH.doPairingRequest(context, this, intent, DexCollectionService.this.mDeviceAddress, DexCollectionService.this.DEFAULT_BT_PIN)) {
                    return;
                }
                UserError.Log.d(DexCollectionService.TAG, "Pairing request marked as failed, reducing settings to avoid auto-pairing");
                Pref.setBoolean("blukon_unbonding", false);
                DexCollectionService.this.unRegisterPairingReceiver();
            }
        };
        this.mConnectionState = 3;
        this.lastdata = null;
        this.prefListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
            @Override
            public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String str) {
                if (str.compareTo("run_service_in_foreground") == 0) {
                    UserError.Log.d("FOREGROUND", "run_service_in_foreground changed!");
                    if (sharedPreferences.getBoolean("run_service_in_foreground", false)) {
                        DexCollectionService dexCollectionService = DexCollectionService.this;
                        dexCollectionService.foregroundServiceStarter = new ForegroundServiceStarter(dexCollectionService.getApplicationContext(), DexCollectionService.this.dexCollectionService);
                        DexCollectionService.this.foregroundServiceStarter.start();
                        UserError.Log.d(DexCollectionService.TAG, "Moving to foreground");
                    } else {
                        DexCollectionService.this.dexCollectionService.stopForeground(true);
                        UserError.Log.d(DexCollectionService.TAG, "Removing from foreground");
                    }
                }
                if (str.equals("dex_collection_method") || str.equals("dex_txid")) {
                    UserError.Log.d(DexCollectionService.TAG, "collection method or txID changed - setting lastdata to null");
                    DexCollectionService.this.lastdata = null;
                }
            }
        };
        this.mGattCallback = new AnonymousClass3();
    }

    static int access$1508() {
        int i = bondingTries;
        bondingTries = i + 1;
        return i;
    }

    static int access$3508() {
        int i = descriptor_callback_failures;
        descriptor_callback_failures = i + 1;
        return i;
    }

    static int access$708() {
        int i = error133;
        error133 = i + 1;
        return i;
    }

    public synchronized void handleConnectedStateChange() {
        this.mConnectionState = 2;
        scanMeister.stop();
        if (servicesDiscovered == DISCOVERED.NULL || Pref.getBoolean("always_discover_services", true)) {
            UserError.Log.d(TAG, "Requesting to discover services: previous: " + servicesDiscovered);
            servicesDiscovered = DISCOVERED.PENDING;
        }
        ActiveBluetoothDevice.connected();
        if (JoH.ratelimit("attempt-connection", 30)) {
            checkConnection();
        }
        if (servicesDiscovered != DISCOVERED.COMPLETE) {
            if (mBluetoothGatt != null) {
                if (JoH.ratelimit("dexcollect-discover-services", 1)) {
                    UserError.Log.d(TAG, "Calling discoverServices");
                    mBluetoothGatt.discoverServices();
                } else {
                    UserError.Log.d(TAG, "Discover services duplicate blocked by rate limit");
                }
            } else {
                UserError.Log.d(TAG, "Wanted to discover services but gatt was null!");
            }
        } else {
            UserError.Log.d(TAG, "Services already discovered");
            checkImmediateSend();
        }
        if (mBluetoothGatt == null) {
            UserError.Log.e(TAG, "gregorybel: force disconnect!");
            handleDisconnectedStateChange();
        }
    }

    @Override
    public void btCallback(String str, String str2) {
        String str3 = TAG;
        UserError.Log.d(str3, "Processing callback: " + str + " :: " + str2);
        if (str.equals(this.mDeviceAddress)) {
            str2.hashCode();
            switch (str2) {
                case "SCAN_FAILED":
                    status("Scan Failed!");
                    break;
                case "SCAN_TIMEOUT":
                    status("Scan timed out");
                    setRetryTimer();
                    break;
                case "SCAN_FOUND":
                    connectIfNotConnected(str);
                    break;
                case "DISCONNECTED":
                    handleDisconnectedStateChange();
                    break;
                default:
                    UserError.Log.e(str3, "Unknown status callback for: " + str + " with " + str2);
                    break;
            }
        }
        UserError.Log.d(str3, "Ignoring: " + str2 + " for " + str + " as we are using: " + this.mDeviceAddress);
    }

    public synchronized void handleDisconnectedStateChange() {
        if (JoH.ratelimit("handle-disconnected-state-change", 2)) {
            this.mConnectionState = 0;
            ActiveBluetoothDevice.disconnected();
            if (!getTrustAutoConnect() && mBluetoothGatt != null) {
                UserError.Log.d(TAG, "Sending disconnection");
                try {
                    mBluetoothGatt.disconnect();
                } catch (Exception unused) {
                }
            }
            if (this.prefs.getBoolean("close_gatt_on_ble_disconnect", true)) {
                if (mBluetoothGatt != null) {
                    String str = TAG;
                    UserError.Log.i(str, "onConnectionStateChange: mBluetoothGatt is not null, closing.");
                    if (JoH.ratelimit("refresh-gatt", 60)) {
                        UserError.Log.d(str, "Refresh result state close: " + JoH.refreshDeviceCache(str, mBluetoothGatt));
                    }
                    mBluetoothGatt.close();
                    mBluetoothGatt = null;
                    mCharacteristic = null;
                    servicesDiscovered = DISCOVERED.NULL;
                } else {
                    UserError.Log.d(TAG, "mBluetoothGatt is null so not closing");
                }
                this.lastdata = null;
            } else {
                UserError.Log.d(TAG, "Not closing gatt on bluetooth disconnect");
            }
            UserError.Log.i(TAG, "onConnectionStateChange: Disconnected from GATT server.");
            setRetryTimer();
        } else {
            UserError.Log.d(TAG, "Ignoring duplicate disconnected state change");
        }
    }

    class AnonymousClass3 extends BluetoothGattCallback {
        AnonymousClass3() {
        }

        @Override
        public synchronized void onConnectionStateChange(BluetoothGatt bluetoothGatt, int i, int i2) {
            PowerManager.WakeLock wakeLock = JoH.getWakeLock("bluetooth-gatt", UsbId.SILABS_CP2102);
            int unused = DexCollectionService.mStatus = i;
            if (i != 133) {
                int unused2 = DexCollectionService.error133 = 0;
            } else {
                DexCollectionService.access$708();
            }
            try {
                try {
                    if (Pref.getBoolean("bluetooth_excessive_wakelocks", true)) {
                        JoH.getWakeLock("DexCollectionExcessive", 45000);
                    }
                    UserError.Log.d(DexCollectionService.TAG, "onState change status = " + i);
                    if (i2 == 0) {
                        UserError.Log.i(DexCollectionService.TAG, "onConnectionStateChange: State disconnected.");
                        DexCollectionService.this.handleDisconnectedStateChange();
                    } else if (i2 == 2) {
                        if (i == 0) {
                            UserError.Log.i(DexCollectionService.TAG, "onConnectionStateChange: Connected to GATT server. ");
                            DexCollectionService.this.handleConnectedStateChange();
                        } else {
                            UserError.Log.i(DexCollectionService.TAG, "Not accepting CONNECTED change as status code is: " + i);
                            if (i == 133) {
                                UserError.Log.i(DexCollectionService.TAG, "Treating as disconnected due to error 133 count: " + DexCollectionService.error133);
                                if (DexCollectionService.error133 > 3) {
                                    Blukon.unBondIfBlukonAtInit();
                                }
                                DexCollectionService.this.handleDisconnectedStateChange();
                            }
                        }
                    }
                    int unused3 = DexCollectionService.mStaticState = DexCollectionService.this.mConnectionState;
                } catch (Exception e) {
                    UserError.Log.wtf(DexCollectionService.TAG, "Caught exception in Gatt callback " + e);
                    UserError.Log.wtf(DexCollectionService.TAG, e);
                    int unused4 = DexCollectionService.mStaticState = DexCollectionService.this.mConnectionState;
                }
                JoH.releaseWakeLock(wakeLock);
            } catch (Throwable th) {
                int unused5 = DexCollectionService.mStaticState = DexCollectionService.this.mConnectionState;
                JoH.releaseWakeLock(wakeLock);
                throw th;
            }
        }

        @Override
        public synchronized void onServicesDiscovered(BluetoothGatt bluetoothGatt, int i) {
            UserError.Log.d(DexCollectionService.TAG, "Services discovered start");
            if (i != 0) {
                UserError.Log.d(DexCollectionService.TAG, "onServicesDiscovered received: " + i);
                return;
            }
            PowerManager.WakeLock wakeLock = JoH.getWakeLock("bluetooth-onservices", UsbId.SILABS_CP2102);
            UserError.Log.d(DexCollectionService.TAG, "onServicesDiscovered received status: " + i);
            if (DexCollectionService.this.prefs.getBoolean("pref_dex_collection_bonding", false) && DexCollectionService.this.mDeviceAddress != null && DexCollectionService.device != null) {
                DexCollectionService dexCollectionService = DexCollectionService.this;
                if (!dexCollectionService.areWeBonded(dexCollectionService.mDeviceAddress) && JoH.ratelimit("dexcollect-create-bond", 20)) {
                    UserError.Log.d(DexCollectionService.TAG, "Attempting to create bond to: " + DexCollectionService.this.mDeviceAddress + " try " + DexCollectionService.bondingTries);
                    DexCollectionService.access$1508();
                    if (DexCollectionService.bondingTries > 5) {
                        UserError.Log.w(DexCollectionService.TAG, "Bonding failing so disabling bonding feature");
                        Home.toaststaticnext("Bonding failing so disabling bonding feature");
                        Pref.setBoolean("pref_dex_collection_bonding", false);
                    } else {
                        DexCollectionService.device.setPin(JoH.convertPinToBytes(DexCollectionService.this.DEFAULT_BT_PIN));
                        DexCollectionService.device.createBond();
                    }
                }
            }
            BluetoothGattService service = DexCollectionService.mBluetoothGatt.getService(DexCollectionService.this.xDripDataService);
            if (service == null) {
                if (!DexCollectionService.static_use_blukon && !blueReader.isblueReader() && !Tomato.isTomato() && !Bubble.isBubble() && !Atom.isAtom() && !LibreBluetooth.isLibreBluettoh()) {
                    UserError.Log.w(DexCollectionService.TAG, "onServicesDiscovered: xdrip service " + DexCollectionService.this.xDripDataService + " not found");
                    DexCollectionService.this.listAvailableServices(DexCollectionService.mBluetoothGatt);
                }
            } else {
                BluetoothGattCharacteristic characteristic = service.getCharacteristic(DexCollectionService.this.xDripDataCharacteristic);
                if (characteristic == null) {
                    UserError.Log.w(DexCollectionService.TAG, "onServicesDiscovered: characteristic " + DexCollectionService.this.xDripDataCharacteristic + " not found");
                    JoH.releaseWakeLock(wakeLock);
                    UserError.Log.d(DexCollectionService.TAG, "onServicesDiscovered: returning due to null xDrip characteristic");
                    return;
                }
                BluetoothGattCharacteristic unused = DexCollectionService.mCharacteristic = characteristic;
                if ((characteristic.getProperties() & 16) > 0) {
                    DexCollectionService.mBluetoothGatt.setCharacteristicNotification(characteristic, true);
                    if (!DexCollectionService.static_use_blukon) {
                        try {
                            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
                            UserError.Log.i(DexCollectionService.TAG, "Bluetooth Notification Descriptor found: " + descriptor.getUuid());
                            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                            long unused2 = DexCollectionService.descriptor_time = JoH.tsl();
                            DexCollectionService.mBluetoothGatt.writeDescriptor(descriptor);
                        } catch (Exception e) {
                            UserError.Log.e(DexCollectionService.TAG, "Error setting notification value descriptor: " + e);
                        }
                    }
                    if (DexCollectionService.this.use_rfduino_bluetooth) {
                        UserError.Log.w(DexCollectionService.TAG, "onServicesDiscovered: use_rfduino_bluetooth send characteristic " + DexCollectionService.this.xDripDataCharacteristicSend + " found");
                        BluetoothGattCharacteristic unused3 = DexCollectionService.mCharacteristicSend = service.getCharacteristic(DexCollectionService.this.xDripDataCharacteristicSend);
                    } else {
                        BluetoothGattCharacteristic unused4 = DexCollectionService.mCharacteristicSend = DexCollectionService.mCharacteristic;
                    }
                } else {
                    UserError.Log.w(DexCollectionService.TAG, "onServicesDiscovered: characteristic " + DexCollectionService.this.xDripDataCharacteristic + " not found");
                }
            }
            BluetoothGattService service2 = DexCollectionService.mBluetoothGatt.getService(DexCollectionService.this.nrfDataService);
            if (service2 != null) {
                BluetoothGattCharacteristic characteristic2 = service2.getCharacteristic(DexCollectionService.this.nrfDataRXCharacteristic);
                if (characteristic2 == null) {
                    UserError.Log.w(DexCollectionService.TAG, "onServicesDiscovered: characteristic " + characteristic2 + " not found");
                    JoH.releaseWakeLock(wakeLock);
                    UserError.Log.d(DexCollectionService.TAG, "onServicesDiscovered: returning due to null nrf characteristic");
                    return;
                }
                boolean unused5 = DexCollectionService.static_use_nrf = true;
                BluetoothGattCharacteristic unused6 = DexCollectionService.mCharacteristic = characteristic2;
                if ((characteristic2.getProperties() | 16) > 0) {
                    DexCollectionService.mBluetoothGatt.setCharacteristicNotification(characteristic2, true);
                    try {
                        BluetoothGattDescriptor descriptor2 = characteristic2.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
                        UserError.Log.i(DexCollectionService.TAG, "NRF Bluetooth Notification Descriptor found: " + descriptor2.getUuid());
                        long unused7 = DexCollectionService.descriptor_time = JoH.tsl();
                        descriptor2.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                        DexCollectionService.mBluetoothGatt.writeDescriptor(descriptor2);
                    } catch (Exception e2) {
                        UserError.Log.e(DexCollectionService.TAG, "Error setting notification value descriptor: " + e2);
                    }
                }
                BluetoothGattCharacteristic unused8 = DexCollectionService.mCharacteristic = characteristic2;
                BluetoothGattCharacteristic unused9 = DexCollectionService.mCharacteristicSend = service2.getCharacteristic(DexCollectionService.this.nrfDataTXCharacteristic);
                if (DexCollectionService.mCharacteristicSend == null) {
                    UserError.Log.w(DexCollectionService.TAG, "onServicesDiscovered: nrf characteristic " + DexCollectionService.mCharacteristicSend + " not found");
                    JoH.releaseWakeLock(wakeLock);
                    return;
                }
                if (blueReader.isblueReader()) {
                    DexCollectionService.status("Enabled blueReader");
                    UserError.Log.d(DexCollectionService.TAG, "blueReader initialized and Version requested");
                    DexCollectionService.this.sendBtMessage(blueReader.initialize());
                } else if (Tomato.isTomato()) {
                    DexCollectionService.status("Enabled tomato");
                    UserError.Log.d(DexCollectionService.TAG, "Queueing Tomato initialization..");
                    Inevitable.task("initialize-tomato", 4000L, new Runnable() {
                        @Override
                        public void run() {
                            Iterator<ByteBuffer> it = Tomato.initialize().iterator();
                            while (it.hasNext()) {
                                DexCollectionService.this.sendBtMessage(it.next());
                                JoH.threadSleep(150L);
                            }
                            UserError.Log.d(DexCollectionService.TAG, "tomato initialized and data requested");
                        }
                    });
                    DISCOVERED unused10 = DexCollectionService.servicesDiscovered = DISCOVERED.NULL;
                } else if (Bubble.isBubble()) {
                    DexCollectionService.status("Enabled bubble");
                    UserError.Log.d(DexCollectionService.TAG, "Queueing bubble initialization..");
                    Inevitable.task("initialize-bubble", 4000L, new Runnable() {
                        @Override
                        public void run() {
                            Iterator<ByteBuffer> it = Bubble.initialize().iterator();
                            while (it.hasNext()) {
                                DexCollectionService.this.sendBtMessage(it.next());
                                JoH.threadSleep(150L);
                            }
                            UserError.Log.d(DexCollectionService.TAG, "bubble initialized and data requested");
                        }
                    });
                    DISCOVERED unused11 = DexCollectionService.servicesDiscovered = DISCOVERED.NULL;
                } else if (Atom.isAtom()) {
                    DexCollectionService.status("Enabled atom");
                    UserError.Log.d(DexCollectionService.TAG, "Queueing atom initialization..");
                    Inevitable.task("initialize-atom", 4000L, new Runnable() {
                        @Override
                        public void run() {
                            Iterator<ByteBuffer> it = Atom.initialize().iterator();
                            while (it.hasNext()) {
                                DexCollectionService.this.sendBtMessage(it.next());
                                JoH.threadSleep(150L);
                            }
                            UserError.Log.d(DexCollectionService.TAG, "atom initialized and data requested");
                        }
                    });
                    DISCOVERED unused12 = DexCollectionService.servicesDiscovered = DISCOVERED.NULL;
                }
            }
            BluetoothGattService service3 = DexCollectionService.mBluetoothGatt.getService(DexCollectionService.this.blukonDataService);
            if (service3 != null) {
                UserError.Log.i(DexCollectionService.TAG, "Found " + DexCollectionService.this.getString(2131755241) + " device");
                BluetoothGattCharacteristic unused13 = DexCollectionService.mCharacteristic = service3.getCharacteristic(UUID.fromString("436a0c82-082e-4ce8-a08b-01d81f195b24"));
                if (DexCollectionService.mCharacteristic == null) {
                    UserError.Log.w(DexCollectionService.TAG, "onServicesDiscovered: blukon characteristic " + DexCollectionService.mCharacteristic + " not found");
                    JoH.releaseWakeLock(wakeLock);
                    return;
                }
                try {
                    int properties = DexCollectionService.mCharacteristic.getProperties();
                    if ((properties & 16) > 0) {
                        UserError.Log.d(DexCollectionService.TAG, "Setting notification on characteristic: " + DexCollectionService.mCharacteristic.getUuid() + " charaprop: " + properties);
                        if (!DexCollectionService.mBluetoothGatt.setCharacteristicNotification(DexCollectionService.mCharacteristic, true)) {
                            UserError.Log.d(DexCollectionService.TAG, "Failed setting notification on blukon characteristic! " + DexCollectionService.mCharacteristic.getUuid());
                        }
                    } else {
                        UserError.Log.e(DexCollectionService.TAG, "Blukon characteristic doesn't seem to allow notify - this is very unusual");
                    }
                } catch (Exception e3) {
                    UserError.Log.e(DexCollectionService.TAG, " Exception during notification preparation " + e3);
                }
                BluetoothGattCharacteristic unused14 = DexCollectionService.mCharacteristicSend = service3.getCharacteristic(UUID.fromString("436aa6e9-082e-4ce8-a08b-01d81f195b24"));
                if (DexCollectionService.mCharacteristicSend == null) {
                    UserError.Log.w(DexCollectionService.TAG, "onServicesDiscovered: blukon send characteristic " + DexCollectionService.mCharacteristicSend + " not found");
                    JoH.releaseWakeLock(wakeLock);
                    return;
                }
                DexCollectionService.status("Enabled " + DexCollectionService.this.getString(2131755241));
                boolean unused15 = DexCollectionService.static_use_blukon = true;
                Blukon.initialize();
            }
            UserError.Log.i(DexCollectionService.TAG, "Looking for  libre2 device");
            BluetoothGattService service4 = DexCollectionService.mBluetoothGatt.getService(DexCollectionService.this.Libre2ServiceUUID);
            if (service4 != null) {
                UserError.Log.i(DexCollectionService.TAG, "Found libre2 device");
                BluetoothGattCharacteristic unused16 = DexCollectionService.mCharacteristic = service4.getCharacteristic(UUID.fromString("0000f002-0000-1000-8000-00805f9b34fb"));
                if (DexCollectionService.mCharacteristic == null) {
                    UserError.Log.w(DexCollectionService.TAG, "onServicesDiscovered: libre2 characteristic  not found");
                    JoH.releaseWakeLock(wakeLock);
                    return;
                }
                try {
                    int properties2 = DexCollectionService.mCharacteristic.getProperties();
                    if ((properties2 & 16) > 0) {
                        UserError.Log.d(DexCollectionService.TAG, "Setting notification on characteristic: " + DexCollectionService.mCharacteristic.getUuid() + " charaprop: " + properties2);
                        if (!DexCollectionService.mBluetoothGatt.setCharacteristicNotification(DexCollectionService.mCharacteristic, true)) {
                            UserError.Log.d(DexCollectionService.TAG, "Failed setting notification on libre2 characteristic! " + DexCollectionService.mCharacteristic.getUuid());
                        }
                    } else {
                        UserError.Log.e(DexCollectionService.TAG, "Libre2 characteristic doesn't seem to allow notify - this is very unusual");
                    }
                } catch (Exception e4) {
                    UserError.Log.e(DexCollectionService.TAG, "Libre2 Exception during notification preparation " + e4);
                }
                BluetoothGattCharacteristic unused17 = DexCollectionService.mCharacteristicSend = service4.getCharacteristic(UUID.fromString("0000f001-0000-1000-8000-00805f9b34fb"));
                if (DexCollectionService.mCharacteristicSend == null) {
                    UserError.Log.w(DexCollectionService.TAG, "onServicesDiscovered: Libre2 login characteristic not found");
                    JoH.releaseWakeLock(wakeLock);
                    return;
                }
                DexCollectionService.status("Enabled " + DexCollectionService.this.getString(2131755241));
                byte[] initialize = LibreBluetooth.initialize();
                if (initialize != null) {
                    DexCollectionService.this.sendBtMessage(initialize);
                } else {
                    UserError.Log.e(DexCollectionService.TAG, "Not sending, No bluetooth enable buffer.");
                }
            }
            Inevitable.task("dex-descrpiptor-retry", 2000L, new Runnable() {
                @Override
                public final void run() {
                    DexCollectionService.AnonymousClass3.this.lambda$onServicesDiscovered$0();
                }
            });
            try {
                int properties3 = DexCollectionService.mCharacteristic.getProperties();
                if (!DexCollectionService.static_use_blukon && (properties3 & 2) > 0) {
                    JoH.runOnUiThreadDelayed(new Runnable() {
                        @Override
                        public final void run() {
                            DexCollectionService.AnonymousClass3.lambda$onServicesDiscovered$1();
                        }
                    }, 300L);
                }
            } catch (NullPointerException unused18) {
                UserError.Log.d(DexCollectionService.TAG, "mCharacteristic was null when attempting to get properties!");
            }
            UserError.Log.d(DexCollectionService.TAG, "Services discovered end");
            DISCOVERED unused19 = DexCollectionService.servicesDiscovered = DISCOVERED.COMPLETE;
            UserError.Log.d(DexCollectionService.TAG, "Services discovered release");
            DexCollectionService.this.checkImmediateSend();
            JoH.releaseWakeLock(wakeLock);
        }

        public void lambda$onServicesDiscovered$0() {
            try {
                UserError.Log.d(DexCollectionService.TAG, "Writing descriptor inside delayed discover services");
                final BluetoothGattDescriptor descriptor = DexCollectionService.mCharacteristic.getDescriptor(DexCollectionService.CCCD);
                if (descriptor != null) {
                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                    long unused = DexCollectionService.descriptor_time = JoH.tsl();
                    if (!DexCollectionService.mBluetoothGatt.writeDescriptor(descriptor)) {
                        UserError.Log.d(DexCollectionService.TAG, "Failed to write descriptor!");
                        DexCollectionService.this.unBondBlucon();
                    } else {
                        Inevitable.task("dex_check_descriptor_write", 2000L, new Runnable() {
                            @Override
                            public void run() {
                                if (DexCollectionService.descriptor_time != 0) {
                                    UserError.Log.e(DexCollectionService.TAG, "Descriptor write did not callback! since: " + JoH.dateTimeText(DexCollectionService.descriptor_time));
                                    long unused2 = DexCollectionService.descriptor_time = 0L;
                                    if (DexCollectionService.descriptor_callback_failures == 0 || !DexCollectionService.static_use_blukon) {
                                        try {
                                            if (DexCollectionService.mBluetoothGatt.writeDescriptor(descriptor)) {
                                                return;
                                            }
                                            UserError.Log.d(DexCollectionService.TAG, "Failed to write descriptor in check callback!");
                                            DexCollectionService.this.unBondBlucon();
                                            return;
                                        } catch (Exception e) {
                                            UserError.Log.e(DexCollectionService.TAG, "Exception during callback check retry: " + e);
                                            return;
                                        }
                                    }
                                    if (DexCollectionService.this.unBondBlucon()) {
                                        int unused3 = DexCollectionService.descriptor_callback_failures = 0;
                                    }
                                }
                            }
                        });
                    }
                }
            } catch (NullPointerException unused2) {
                UserError.Log.e(DexCollectionService.TAG, "Got null pointer trying to set CCCD descriptor");
                if ((DexCollectionService.static_use_blukon || Blukon.expectingBlukonDevice()) && JoH.ratelimit("null-ccd-retry", 300)) {
                    UserError.Log.d(DexCollectionService.TAG, "Refresh result state close: " + JoH.refreshDeviceCache(DexCollectionService.TAG, DexCollectionService.mBluetoothGatt));
                    DexCollectionService.this.setRetryTimer();
                }
            }
        }

        public static void lambda$onServicesDiscovered$1() {
            try {
                UserError.Log.d(DexCollectionService.TAG, "Reading characteristic: " + DexCollectionService.mCharacteristic.getUuid().toString());
                DexCollectionService.mBluetoothGatt.readCharacteristic(DexCollectionService.mCharacteristic);
            } catch (NullPointerException unused) {
                UserError.Log.e(DexCollectionService.TAG, "Got null pointer trying to readCharacteristic");
            }
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic, int i) {
            try {
                String str = "OnCharacteristic WRITE:  status: " + Helper.getStatusName(i) + " data: " + JoH.bytesToHex(bluetoothGattCharacteristic.getValue()) + " uuid: " + bluetoothGattCharacteristic.getUuid();
                if (i == 0) {
                    UserError.Log.d(DexCollectionService.TAG, str);
                } else {
                    UserError.Log.e(DexCollectionService.TAG, str);
                }
            } catch (Exception e) {
                UserError.Log.wtf(DexCollectionService.TAG, "Got exception trying to display data: " + e);
            }
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic, int i) {
            onCharacteristicChanged(bluetoothGatt, bluetoothGattCharacteristic);
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic) {
            PowerManager.WakeLock wakeLock = JoH.getWakeLock(DexCollectionService.TAG, UsbId.SILABS_CP2102);
            try {
                byte[] value = bluetoothGattCharacteristic.getValue();
                if (value != null && value.length > 0) {
                    DexCollectionService.this.setSerialDataToTransmitterRawData(value, value.length);
                    String dumpHexString = HexDump.dumpHexString(value);
                    if (value.length > 1 || value[0] != 0) {
                        String unused = DexCollectionService.static_last_hexdump = dumpHexString;
                    }
                    UserError.Log.i(DexCollectionService.TAG, "onCharacteristicChanged entered " + dumpHexString);
                }
                DexCollectionService.this.lastdata = value;
                Inevitable.task("dex-set-failover", 1000L, new Runnable() {
                    @Override
                    public final void run() {
                        DexCollectionService.AnonymousClass3.this.lambda$onCharacteristicChanged$2();
                    }
                });
            } finally {
                JoH.releaseWakeLock(wakeLock);
            }
        }

        public void lambda$onCharacteristicChanged$2() {
            DexCollectionService.this.setFailoverTimer();
            JoH.getWakeLock("DexCollectionLinger", 5000);
        }

        @Override
        public synchronized void onDescriptorWrite(BluetoothGatt bluetoothGatt, BluetoothGattDescriptor bluetoothGattDescriptor, int i) {
            if (i == 0) {
                UserError.Log.d(DexCollectionService.TAG, "onDescriptorWrite: Wrote GATT Descriptor successfully.");
                int unused = DexCollectionService.descriptor_callback_failures = 0;
            } else {
                UserError.Log.d(DexCollectionService.TAG, "onDescriptorWrite: Error writing GATT Descriptor: " + i);
                if (DexCollectionService.descriptor_callback_failures != 0) {
                    DexCollectionService.this.unBondBlucon();
                } else {
                    DexCollectionService.access$3508();
                    try {
                        if (!DexCollectionService.mBluetoothGatt.writeDescriptor(bluetoothGattDescriptor)) {
                            UserError.Log.d(DexCollectionService.TAG, "Failed to write descriptor in on descriptor write retry");
                            DexCollectionService.this.unBondBlucon();
                        } else {
                            UserError.Log.d(DexCollectionService.TAG, "Tried to write descriptor again inside onDescriptorWrite");
                        }
                    } catch (Exception e) {
                        UserError.Log.e(DexCollectionService.TAG, "Exception during callback retry: " + e);
                    }
                }
            }
            long unused2 = DexCollectionService.descriptor_time = 0L;
        }
    }

    private static String getDefaultPin() {
        String pin = Blukon.getPin();
        return pin != null ? pin : "000000";
    }

    @SuppressLint({"ObsoleteSdkInt"})
    private boolean shouldServiceRun() {
        boolean z = (DexCollectionType.hasXbridgeWixel() || DexCollectionType.hasBtWixel()) && (!(Home.get_forced_wear() || JoH.areWeRunningOnAndroidWear()) || PersistentStore.getBoolean("run_wear_collector"));
        UserError.Log.d(TAG, "shouldServiceRun() returning: " + z);
        return z;
    }

    public static boolean isCollecting() {
        if (static_use_blukon) {
            return Blukon.isCollecting();
        }
        return false;
    }

    public static void status(String str) {
        lastState = str + " " + JoH.hourMinuteString();
    }

    private static void error(String str) {
        lastError = str + " " + JoH.hourMinuteString();
    }

    private static String getStateStr(int i) {
        mStaticState = i;
        return i != 0 ? i != 1 ? i != 2 ? i != 3 ? "UNKNOWN STATE!" : "DISCONNECTING" : "CONNECTED" : "CONNECTING" : "DISCONNECTED";
    }

    private static Integer convertSrc(String str) {
        Integer num = 0;
        String upperCase = str.toUpperCase();
        return Integer.valueOf(getSrcValue(upperCase.charAt(4)) | Integer.valueOf(Integer.valueOf(Integer.valueOf(Integer.valueOf((getSrcValue(upperCase.charAt(0)) << 20) | num.intValue()).intValue() | (getSrcValue(upperCase.charAt(1)) << 15)).intValue() | (getSrcValue(upperCase.charAt(2)) << 10)).intValue() | (getSrcValue(upperCase.charAt(3)) << 5)).intValue());
    }

    private static int getSrcValue(char c) {
        char[] cArr = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'W', 'X', 'Y'};
        int i = 0;
        while (i < 32 && cArr[i] != c) {
            i++;
        }
        return i;
    }

    public static boolean isRunning() {
        return (lastState.equals("Not Running") || lastState.startsWith("Stopping", 0)) ? false : true;
    }

    public static void setWatchStatus(DataMap dataMap) {
        lastStateWatch = dataMap.getString("lastState", "");
        TransmitterData transmitterData = new TransmitterData();
        last_transmitter_DataWatch = transmitterData;
        transmitterData.timestamp = dataMap.getLong("timestamp", 0L);
        mStaticStateWatch = dataMap.getInt("mStaticState", 0);
        last_battery_level_watch = dataMap.getInt("last_battery_level", -1);
        retry_time_watch = dataMap.getLong("retry_time", 0L);
        failover_time_watch = dataMap.getLong("failover_time", 0L);
        static_last_hexdump_watch = dataMap.getString("static_last_hexdump", "");
        static_last_sent_hexdump_watch = dataMap.getString("static_last_sent_hexdump", "");
    }

    public static String getBestLimitterHardwareName() {
        if (static_use_nrf && blueReader.isblueReader()) {
            return "BlueReader";
        }
        if (static_use_nrf && Tomato.isTomato()) {
            return xdrip.getAppContext().getString(2131756892);
        }
        if (static_use_nrf && Bubble.isBubble()) {
            return xdrip.getAppContext().getString(2131755246);
        }
        if (static_use_nrf && Atom.isAtom()) {
            return xdrip.getAppContext().getString(2131755159);
        }
        if (static_use_blukon) {
            return xdrip.getAppContext().getString(2131755241);
        }
        return static_use_transmiter_pl_bluetooth ? "Transmiter PL" : static_use_rfduino_bluetooth ? "Rfduino" : "LimiTTer";
    }

    public static List<StatusItem> megaStatus() {
        String str;
        String str2;
        String str3;
        String str4;
        String sb;
        String str5;
        ArrayList arrayList = new ArrayList();
        boolean z = Home.get_forced_wear();
        StringBuilder sb2 = new StringBuilder();
        sb2.append(lastState);
        String str6 = "";
        sb2.append(z ? " (Watch Forced)" : "");
        arrayList.add(new StatusItem("Phone Service State", sb2.toString()));
        String str7 = lastError;
        if (str7 != null) {
            arrayList.add(new StatusItem("Last Error", str7, StatusItem.Highlight.NOTICE, "long-press", new Runnable() {
                @Override
                public final void run() {
                    DexCollectionService.lastError = null;
                }
            }));
        }
        arrayList.add(new StatusItem("Bluetooth Device", JoH.ucFirst(getStateStr(mStaticState))));
        if (device != null) {
            arrayList.add(new StatusItem("Device Mac Address", device.getAddress()));
        }
        if (Home.get_engineering_mode()) {
            arrayList.add(new StatusItem("Active device connected", String.valueOf(ActiveBluetoothDevice.is_connected())));
            arrayList.add(new StatusItem("Bluetooth GATT", String.valueOf(mBluetoothGatt)));
            arrayList.add(new StatusItem("Last status", String.valueOf(mStatus) + (mStatus == 133 ? " (restart device?)" : "")));
            BluetoothManager bluetoothManager = (BluetoothManager) xdrip.getAppContext().getSystemService("bluetooth");
            if (bluetoothManager != null) {
                Iterator<BluetoothDevice> it = bluetoothManager.getConnectedDevices(7).iterator();
                while (it.hasNext()) {
                    arrayList.add(new StatusItem("GATT device connected", it.next().getAddress()));
                }
            }
        }
        if (mStaticState == 1) {
            arrayList.add(new StatusItem("Connecting for", JoH.niceTimeScalar(JoH.msSince(last_connect_request))));
        }
        if (static_use_polling) {
            if (last_poll_sent > 0) {
                str5 = "Last poll: " + JoH.niceTimeSince(last_poll_sent) + " ago";
            } else {
                str5 = "Enabled";
            }
            arrayList.add(new StatusItem("Polling mode", str5));
        }
        if (static_use_transmiter_pl_bluetooth) {
            arrayList.add(new StatusItem("Hardware", "Transmiter PL"));
        }
        if (static_use_rfduino_bluetooth) {
            arrayList.add(new StatusItem("Hardware", "Rfduino"));
        }
        if (static_use_blukon) {
            arrayList.add(new StatusItem("Hardware", xdrip.getAppContext().getString(2131755241)));
        }
        if (static_use_nrf && blueReader.isblueReader()) {
            arrayList.add(new StatusItem("Hardware", "BlueReader"));
        }
        if (static_use_nrf && Tomato.isTomato()) {
            arrayList.add(new StatusItem("Hardware", xdrip.getAppContext().getString(2131756892)));
        }
        if (last_transmitter_Data != null) {
            arrayList.add(new StatusItem("Glucose data from", JoH.niceTimeSince(last_transmitter_Data.timestamp) + " ago"));
        }
        int i = last_battery_level;
        if (i > -1) {
            arrayList.add(new StatusItem("Battery level", Integer.valueOf(i)));
        }
        if (Pref.getBooleanDefaultFalse("pref_dex_collection_bonding")) {
            String str8 = bondedState;
            if (str8 != null) {
                if (str8.length() > 0) {
                    sb = "Bonded";
                } else {
                    StringBuilder sb3 = new StringBuilder();
                    sb3.append("Not bonded");
                    if (bondingTries > 1) {
                        str6 = " (" + bondingTries + ")";
                    }
                    sb3.append(str6);
                    sb = sb3.toString();
                }
                arrayList.add(new StatusItem("Bluetooth Pairing", sb, bondedState.length() > 0 ? StatusItem.Highlight.GOOD : StatusItem.Highlight.NOTICE, "long-press", new Runnable() {
                    @Override
                    public void run() {
                        Pref.setBoolean("pref_dex_collection_bonding", false);
                        if (DexCollectionService.bondedState.length() > 0) {
                            JoH.static_toast_long("If you want to unbond use Android bluetooth system settings to Forget device");
                            String unused = DexCollectionService.bondedState = null;
                        }
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                CollectionServiceStarter.restartCollectionService(xdrip.getAppContext());
                            }
                        }).start();
                    }
                }));
            }
        } else {
            arrayList.add(new StatusItem("Bluetooth Pairing", "Disabled, tap to enable", StatusItem.Highlight.NORMAL, "long-press", new Runnable() {
                @Override
                public void run() {
                    Pref.setBoolean("pref_dex_collection_bonding", true);
                    JoH.static_toast_long("This probably only works on HM10/HM11 and blucon devices at the moment and takes a minute");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            CollectionServiceStarter.restartCollectionService(xdrip.getAppContext());
                        }
                    }).start();
                }
            }));
        }
        if (max_wakeup_jitter > 2000) {
            arrayList.add(new StatusItem("Slowest wake up", JoH.niceTimeScalar(max_wakeup_jitter) + " late", max_wakeup_jitter > 61000 ? StatusItem.Highlight.CRITICAL : StatusItem.Highlight.NORMAL));
        }
        if (JoH.buggy_samsung) {
            arrayList.add(new StatusItem("Buggy handset", "Using workaround", max_wakeup_jitter < 10000 ? StatusItem.Highlight.GOOD : StatusItem.Highlight.BAD));
        }
        long j = retry_time;
        if (j > 0) {
            arrayList.add(new StatusItem("Next Retry", JoH.niceTimeTill(j), JoH.msTill(retry_time) < -2 ? StatusItem.Highlight.CRITICAL : StatusItem.Highlight.NORMAL));
        }
        long j2 = failover_time;
        if (j2 > 0) {
            arrayList.add(new StatusItem("Next Wake up", JoH.niceTimeTill(j2), JoH.msTill(failover_time) < -2 ? StatusItem.Highlight.CRITICAL : StatusItem.Highlight.NORMAL));
        }
        if (Home.get_engineering_mode() && DexCollectionType.hasLibre()) {
            arrayList.add(new StatusItem("Request Data", "Test for xBridgePlus protocol", immediateSend == null ? StatusItem.Highlight.NORMAL : StatusItem.Highlight.NOTICE, "long-press", new Runnable() {
                @Override
                public void run() {
                    byte[] unused = DexCollectionService.immediateSend = XbridgePlus.sendDataRequestPacket();
                    CollectionServiceStarter.restartCollectionService(xdrip.getAppContext());
                }
            }));
        }
        if (Home.get_engineering_mode() && (str4 = static_last_hexdump) != null) {
            arrayList.add(new StatusItem("Received Data", filterHexdump(str4)));
        }
        if (Home.get_engineering_mode() && (str3 = static_last_sent_hexdump) != null) {
            arrayList.add(new StatusItem("Sent Data", filterHexdump(str3)));
        }
        if (z) {
            arrayList.add(new StatusItem());
            arrayList.add(new StatusItem("Watch Service State", lastStateWatch));
            arrayList.add(new StatusItem("Bridge Device", JoH.ucFirst(getStateStr(mStaticStateWatch))));
            TransmitterData transmitterData = last_transmitter_DataWatch;
            if (transmitterData != null && transmitterData.timestamp > 0) {
                arrayList.add(new StatusItem("Watch Glucose data", JoH.niceTimeSince(last_transmitter_DataWatch.timestamp) + " ago"));
            }
            int i2 = last_battery_level_watch;
            if (i2 > -1) {
                arrayList.add(new StatusItem("Bridge Battery level", Integer.valueOf(i2)));
            }
            long j3 = retry_time_watch;
            if (j3 > 0) {
                arrayList.add(new StatusItem("Watch Next Retry", JoH.niceTimeTill(j3)));
            }
            long j4 = failover_time_watch;
            if (j4 > 0) {
                arrayList.add(new StatusItem("Watch Wake up", JoH.niceTimeTill(j4)));
            }
            if (Home.get_engineering_mode() && (str2 = static_last_hexdump_watch) != null && str2.length() > 0) {
                arrayList.add(new StatusItem("Watch Received Data", filterHexdump(static_last_hexdump_watch)));
            }
            if (Home.get_engineering_mode() && (str = static_last_sent_hexdump_watch) != null && str.length() > 0) {
                arrayList.add(new StatusItem("Watch Sent Data", filterHexdump(static_last_sent_hexdump_watch)));
            }
        }
        if (blueReader.isblueReader()) {
            arrayList.add(new StatusItem("blueReader Battery", Pref.getInt("bridge_battery", 0) + "%"));
            arrayList.add(new StatusItem("blueReader rest days", PersistentStore.getString("bridge_battery_days")));
            arrayList.add(new StatusItem("blueReader Firmware", PersistentStore.getString("blueReaderFirmware")));
        }
        if (Tomato.isTomato()) {
            arrayList.add(new StatusItem("Tomato Battery", PersistentStore.getString("Tomatobattery")));
            arrayList.add(new StatusItem("Tomato Hardware", PersistentStore.getString("TomatoHArdware")));
            arrayList.add(new StatusItem("Tomato Firmware", PersistentStore.getString("TomatoFirmware")));
            arrayList.add(new StatusItem("Libre SN", PersistentStore.getString("LibreSN")));
        }
        if (Bubble.isBubble()) {
            arrayList.add(new StatusItem("Bubble Battery", PersistentStore.getString("Bubblebattery")));
            arrayList.add(new StatusItem("Bubble Hardware", PersistentStore.getString("BubbleHArdware")));
            arrayList.add(new StatusItem("Bubble Firmware", PersistentStore.getString("BubbleFirmware")));
            arrayList.add(new StatusItem("Libre SN", PersistentStore.getString("LibreSN")));
        }
        if (Atom.isAtom()) {
            arrayList.add(new StatusItem("Atom Battery", PersistentStore.getString("Atombattery")));
            arrayList.add(new StatusItem("Atom Hardware", PersistentStore.getString("AtomHArdware")));
            arrayList.add(new StatusItem("Atom Firmware", PersistentStore.getString("AtomFirmware")));
            arrayList.add(new StatusItem("Libre SN", PersistentStore.getString("LibreSN")));
        }
        if (static_use_blukon) {
            arrayList.add(new StatusItem("Battery", Pref.getInt("bridge_battery", 0) + "%"));
            arrayList.add(new StatusItem("Sensor age", JoH.qs(((double) Pref.getInt("nfc_sensor_age", 0)) / 1440.0d, 1) + "d"));
            arrayList.add(new StatusItem("Libre SN", PersistentStore.getString("LibreSN")));
        }
        return arrayList;
    }

    private static String filterHexdump(String str) {
        return str.replaceAll("[ ]+", " ").replaceAll("\n0x0000[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f] ", "\n").replaceFirst("^\n", "");
    }

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

    @Override
    public void onCreate() {
        if (scanMeister == null) {
            scanMeister = new ScanMeister().applyKnownWorkarounds().addCallBack(this, TAG);
        }
        ForegroundServiceStarter foregroundServiceStarter = new ForegroundServiceStarter(getApplicationContext(), this);
        this.foregroundServiceStarter = foregroundServiceStarter;
        foregroundServiceStarter.start();
        this.dexCollectionService = this;
        this.prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        listenForChangeInSettings();
        if (CollectionServiceStarter.isDexBridgeOrWifiandDexBridge()) {
            UserError.Log.i(TAG, "onCreate: resetting bridge_battery preference to 0");
            this.prefs.edit().putInt("bridge_battery", 0).apply();
        }
        this.cloner.dontClone(new Class[]{BluetoothDevice.class, BluetoothGattService.class});
        IntentFilter intentFilter = new IntentFilter("android.bluetooth.device.action.PAIRING_REQUEST");
        intentFilter.setPriority(999);
        if (Build.VERSION.SDK_INT < 26) {
            registerReceiver(this.mPairingRequestRecevier, intentFilter);
        } else {
            UserError.Log.d(TAG, "Not starting pairing request receiver on android 8+");
        }
        UserError.Log.i(TAG, "onCreate: STARTING SERVICE: pin code: " + this.DEFAULT_BT_PIN);
        Blukon.unBondIfBlukonAtInit();
    }

    @Override
    public int onStartCommand(Intent intent, int i, int i2) {
        PowerManager.WakeLock wakeLock = JoH.getWakeLock("dexcollect-service", 120000);
        long j = retry_time;
        if (j > 0) {
            long j2 = failover_time;
            if (j2 > 0) {
                long msSince = JoH.msSince(Math.min(j, j2));
                String niceTimeScalar = JoH.niceTimeScalar(msSince);
                if (!niceTimeScalar.startsWith("0 ")) {
                    UserError.Log.d(TAG, "Wake up jitter: " + niceTimeScalar);
                }
                JoH.persistentBuggySamsungCheck();
                if (msSince > 10000 && !JoH.buggy_samsung && JoH.isSamsung()) {
                    UserError.Log.wtf(TAG, "Enabled wake workaround due to jitter of: " + JoH.niceTimeScalar(msSince));
                    JoH.setBuggySamsungEnabled();
                    max_wakeup_jitter = 0L;
                } else {
                    max_wakeup_jitter = Math.max(max_wakeup_jitter, msSince);
                }
            }
        }
        retry_time = 0L;
        failover_time = 0L;
        static_use_rfduino_bluetooth = this.use_rfduino_bluetooth;
        static_use_transmiter_pl_bluetooth = this.use_transmiter_pl_bluetooth;
        static_use_polling = this.use_polling;
        status("Started");
        if (shouldServiceRun()) {
            setFailoverTimer();
            this.lastdata = null;
            DisconnectReceiver.addCallBack(this, TAG);
            checkConnection();
            watchdog();
            JoH.releaseWakeLock(wakeLock);
            return 1;
        }
        status("Stopping");
        stopSelf();
        JoH.releaseWakeLock(wakeLock);
        return 2;
    }

    public void unRegisterPairingReceiver() {
        try {
            unregisterReceiver(this.mPairingRequestRecevier);
        } catch (Exception e) {
            Log.e(TAG, "Error unregistering pairing receiver: " + e);
        }
    }

    @Override
    public void onDestroy() {
        status("Shutdown");
        super.onDestroy();
        String str = TAG;
        UserError.Log.d(str, "onDestroy entered");
        close();
        this.foregroundServiceStarter.stop();
        unRegisterPairingReceiver();
        DisconnectReceiver.removeCallBack(str);
        if (scanMeister != null) {
            scanMeister.removeCallBack(str);
            scanMeister.stop();
        }
        if (shouldServiceRun()) {
            setRetryTimer();
            status("Stopped, attempting restart");
        } else {
            UserError.Log.d(str, "onDestroy stop Alarm serviceIntent");
            JoH.cancelAlarm(this, serviceIntent);
            UserError.Log.d(str, "onDestroy stop Alarm serviceFailoverIntent");
            JoH.cancelAlarm(this, serviceFailoverIntent);
            status("Service full stop");
            retry_time = 0L;
            failover_time = 0L;
        }
        retry_backoff = 0L;
        poll_backoff = 0L;
        servicesDiscovered = DISCOVERED.NULL;
        bondingTries = 0;
        UserError.Log.i(str, "SERVICE STOPPED");
    }

    public void listenForChangeInSettings() {
        this.prefs.registerOnSharedPreferenceChangeListener(this.prefListener);
    }

    public void setRetryTimer() {
        mStaticState = this.mConnectionState;
        if (shouldServiceRun()) {
            long whenToRetryNext = whenToRetryNext();
            UserError.Log.d(TAG, "setRetryTimer: Restarting in: " + (whenToRetryNext / 1000) + " seconds");
            PendingIntent pendingIntent = WakeLockTrampoline.getPendingIntent(getClass(), 1002);
            serviceIntent = pendingIntent;
            retry_time = JoH.wakeUpIntent(this, whenToRetryNext, pendingIntent);
            return;
        }
        UserError.Log.d(TAG, "Not setting retry timer as service should not be running");
    }

    public synchronized void setFailoverTimer() {
        if (shouldServiceRun()) {
            long whenToPollNext = this.use_polling ? whenToPollNext() : 360000L;
            UserError.Log.d(TAG, "setFailoverTimer: Fallover Restarting in: " + (whenToPollNext / 60000) + " minutes");
            PendingIntent pendingIntent = WakeLockTrampoline.getPendingIntent(getClass(), UsbId.VENDOR_ATMEL);
            serviceFailoverIntent = pendingIntent;
            failover_time = JoH.wakeUpIntent(this, whenToPollNext, pendingIntent);
            retry_time = 0L;
        } else {
            stopSelf();
        }
    }

    private long whenToRetryNext() {
        long max = Math.max(retry_backoff + 10000, 205000 - JoH.msSince(this.lastPacketTime));
        long j = retry_backoff;
        if (j < 60000) {
            retry_backoff = j + 1000;
        }
        UserError.Log.d(TAG, "Scheduling next retry in: " + JoH.niceTimeScalar(max) + " @ " + JoH.dateTimeText(JoH.tsl() + max) + " period diff: " + (205000 - JoH.msSince(this.lastPacketTime)));
        return max;
    }

    private long whenToPollNext() {
        long max = Math.max(poll_backoff + 5000, 299000 - JoH.msSince(this.lastPacketTime));
        long j = poll_backoff;
        if (j < 360000) {
            poll_backoff = j + 1000;
        }
        UserError.Log.d(TAG, "Scheduling next poll in: " + JoH.niceTimeScalar(max) + " @ " + JoH.dateTimeText(JoH.tsl() + max) + " period diff: " + (299000 - JoH.msSince(this.lastPacketTime)));
        return max;
    }

    synchronized void checkConnection() {
        String str;
        String str2;
        boolean z;
        status("Attempting connection");
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService("bluetooth");
        if (bluetoothManager == null) {
            status("No bluetooth manager");
            setRetryTimer();
            return;
        }
        BluetoothAdapter adapter = bluetoothManager.getAdapter();
        this.mBluetoothAdapter = adapter;
        if (adapter == null) {
            status("No bluetooth adapter");
            setRetryTimer();
            return;
        }
        if (!adapter.isEnabled()) {
            this.mConnectionState = 0;
            if (Pref.getBoolean("automatically_turn_bluetooth_on", true)) {
                UserError.Log.i(TAG, "Turning bluetooth on as appears disabled");
                status("Turning bluetooth on");
                JoH.setBluetoothEnabled(getApplicationContext(), true);
            } else {
                UserError.Log.d(TAG, "Not automatically turning on bluetooth due to preferences");
            }
        }
        if (device != null) {
            Iterator<BluetoothDevice> it = bluetoothManager.getConnectedDevices(7).iterator();
            while (true) {
                if (!it.hasNext()) {
                    z = false;
                    break;
                } else if (it.next().getAddress().equals(device.getAddress())) {
                    if (this.mConnectionState != 2) {
                        UserError.Log.d(TAG, "Detected state change by checking connected devices");
                        handleConnectedStateChange();
                    }
                    z = true;
                }
            }
            if (!z && this.mConnectionState == 2) {
                UserError.Log.d(TAG, "Marking disconnected as not in list of connected devices");
                this.mConnectionState = 0;
            }
        } else {
            UserError.Log.d(TAG, "Device is null in checkConnection");
            this.mConnectionState = 0;
        }
        String str3 = TAG;
        UserError.Log.i(str3, "checkConnection: Connection state: " + getStateStr(this.mConnectionState));
        if (this.mConnectionState != 0 && this.mConnectionState != 3) {
            if (this.mConnectionState == 1) {
                mStaticState = this.mConnectionState;
                if (JoH.msSince(last_connect_request) > (getTrustAutoConnect() ? 3600000L : 30000L)) {
                    UserError.Log.i(str3, "Connecting for too long, shutting down");
                    retry_backoff = 0L;
                    close();
                }
            } else if (this.mConnectionState == 2) {
                status("Last Connected");
                UserError.Log.i(str3, "checkConnection: Looks like we are already connected, ready to receive");
                retry_backoff = 0L;
                mStaticState = this.mConnectionState;
                if (this.use_polling && JoH.msSince(this.lastPacketTime) >= 299000) {
                    pollForData();
                }
                return;
            }
            setRetryTimer();
        }
        ActiveBluetoothDevice first = ActiveBluetoothDevice.first();
        if (first != null) {
            String str4 = first.address;
            this.mDeviceAddress = str4;
            try {
                if (this.mBluetoothAdapter.isEnabled() && this.mBluetoothAdapter.getRemoteDevice(str4) != null) {
                    if (useScanning()) {
                        StringBuilder sb = new StringBuilder();
                        sb.append(xdrip.gs(2131756235));
                        if (Home.get_engineering_mode()) {
                            str2 = ": " + str4;
                        } else {
                            str2 = "";
                        }
                        sb.append(str2);
                        status(sb.toString());
                        UserError.Log.i(str3, "scanning for addresses " + str4);
                        scanMeister.setAddress(str4).addCallBack(this, str3).scan();
                    } else {
                        StringBuilder sb2 = new StringBuilder();
                        sb2.append("Connecting");
                        if (Home.get_engineering_mode()) {
                            str = ": " + str4;
                        } else {
                            str = "";
                        }
                        sb2.append(str);
                        status(sb2.toString());
                        UserError.Log.i(str3, "Connecting to addresses " + str4);
                        connect(str4);
                    }
                    mStaticState = this.mConnectionState;
                    return;
                }
            } catch (IllegalArgumentException e) {
                UserError.Log.e(TAG, "IllegalArgumentException: " + e);
            }
        }
        setRetryTimer();
    }

    public synchronized void checkImmediateSend() {
        if (immediateSend != null) {
            UserError.Log.d(TAG, "Sending immediate data: " + JoH.bytesToHex(immediateSend));
            sendBtMessage(immediateSend);
            immediateSend = null;
        }
    }

    private synchronized void pollForData() {
        if (JoH.ratelimit("poll-for-data", 5)) {
            new Thread() {
                @Override
                public void run() {
                    UserError.Log.d(DexCollectionService.TAG, "Polling for data");
                    for (int i = 0; DexCollectionService.servicesDiscovered != DISCOVERED.COMPLETE && i < 10; i++) {
                        UserError.Log.d(DexCollectionService.TAG, "Waiting for service discovery: " + DexCollectionService.servicesDiscovered + " count: " + i);
                        try {
                            Thread.sleep(200L);
                        } catch (InterruptedException unused) {
                        }
                    }
                    if (DexCollectionService.servicesDiscovered == DISCOVERED.NULL) {
                        UserError.Log.e(DexCollectionService.TAG, "Failed to discover services!");
                        try {
                            if (JoH.ratelimit("rediscover-services", 30)) {
                                UserError.Log.d(DexCollectionService.TAG, "Refresh result: " + JoH.refreshDeviceCache(DexCollectionService.TAG, DexCollectionService.mBluetoothGatt));
                                DexCollectionService.mBluetoothGatt.discoverServices();
                            }
                        } catch (Exception e) {
                            UserError.Log.d(DexCollectionService.TAG, "Exception discovering services: " + e);
                        }
                    }
                    long unused2 = DexCollectionService.last_poll_sent = JoH.tsl();
                    if (JoH.msSince(DexCollectionService.this.lastPacketTime) <= Home.stale_data_millis() || !JoH.ratelimit("poll-request-part-b", 15)) {
                        DexCollectionService.this.sendBtMessage(XbridgePlus.sendDataRequestPacket());
                    } else {
                        UserError.Log.e(DexCollectionService.TAG, "Stale data so requesting backfill");
                        DexCollectionService.this.sendBtMessage(XbridgePlus.sendLast15BRequestPacket());
                    }
                }
            }.start();
        }
    }

    public void listAvailableServices(BluetoothGatt bluetoothGatt) {
        UserError.Log.d(TAG, "Listing available services:");
        for (BluetoothGattService bluetoothGattService : bluetoothGatt.getServices()) {
            UserError.Log.d(TAG, "Service: " + bluetoothGattService.getUuid().toString());
            for (BluetoothGattCharacteristic bluetoothGattCharacteristic : bluetoothGattService.getCharacteristics()) {
                UserError.Log.d(TAG, "|-- Characteristic: " + bluetoothGattCharacteristic.getUuid().toString());
            }
        }
    }

    public boolean sendBtMessage(byte[] bArr) {
        return sendBtMessage(JoH.bArrayAsBuffer(bArr));
    }

    public synchronized boolean sendBtMessage(ByteBuffer byteBuffer) {
        String str = TAG;
        UserError.Log.i(str, "sendBtMessage: entered");
        if (mBluetoothGatt == null) {
            UserError.Log.w(str, "sendBtMessage: lost connection");
            if (JoH.ratelimit("sendbtmessagelost", 60)) {
                this.mConnectionState = 0;
                setRetryTimer();
            }
            return false;
        }
        byte[] array = byteBuffer.array();
        static_last_sent_hexdump = HexDump.dumpHexString(array);
        UserError.Log.i(str, "sendBtMessage: sending message: " + static_last_sent_hexdump);
        if (this.use_rfduino_bluetooth) {
            UserError.Log.w(str, "sendBtMessage: use_rfduino_bluetooth");
            if (mCharacteristicSend == null) {
                status("Error: mCharacteristicSend was null in sendBtMessage");
                UserError.Log.e(str, lastState);
                servicesDiscovered = DISCOVERED.NULL;
                return false;
            }
            return writeChar(mCharacteristicSend, array);
        }
        if (mCharacteristic == null) {
            status("Error: mCharacteristic was null in sendBtMessage");
            UserError.Log.e(str, lastState);
            servicesDiscovered = DISCOVERED.NULL;
            return false;
        }
        if (mCharacteristicSend != null && mCharacteristicSend != mCharacteristic) {
            return writeChar(mCharacteristicSend, array);
        }
        return writeChar(mCharacteristic, array);
    }

    private synchronized boolean writeChar(BluetoothGattCharacteristic bluetoothGattCharacteristic, final byte[] bArr) {
        boolean z = false;
        if (bArr == null) {
            UserError.Log.e(TAG, "Value null in write char");
            return false;
        }
        if (bluetoothGattCharacteristic == null) {
            UserError.Log.e(TAG, "localmCharacteristic null in write char");
            return false;
        }
        bluetoothGattCharacteristic.setValue(bArr);
        if (mBluetoothGatt != null && mBluetoothGatt.writeCharacteristic(bluetoothGattCharacteristic)) {
            z = true;
        }
        if (!z) {
            String str = TAG;
            UserError.Log.d(str, "Error writing characteristic: " + bluetoothGattCharacteristic.getUuid() + " " + JoH.bytesToHex(bArr));
            final BluetoothGattCharacteristic bluetoothGattCharacteristic2 = (BluetoothGattCharacteristic) this.cloner.shallowClone(bluetoothGattCharacteristic);
            if (JoH.quietratelimit("dexcol-resend-offset", 2)) {
                this.delay_offset = 0L;
            } else {
                this.delay_offset += 100;
                UserError.Log.e(str, "Delay offset now: " + this.delay_offset);
            }
            JoH.getWakeLock("dexcol-resend-linger", 1000);
            JoH.runOnUiThreadDelayed(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (!(DexCollectionService.mBluetoothGatt != null && DexCollectionService.mBluetoothGatt.writeCharacteristic(bluetoothGattCharacteristic2))) {
                            UserError.Log.e(DexCollectionService.TAG, "Error writing characteristic: (2nd try) " + bluetoothGattCharacteristic2.getUuid() + " " + JoH.bytesToHex(bArr));
                            return;
                        }
                        UserError.Log.d(DexCollectionService.TAG, "Succeeded writing characteristic: (2nd try) " + bluetoothGattCharacteristic2.getUuid() + " " + JoH.bytesToHex(bArr));
                    } catch (Exception e) {
                        UserError.Log.wtf(DexCollectionService.TAG, "Exception during 2nd try write: " + e + " " + bluetoothGattCharacteristic2.getUuid() + " " + JoH.bytesToHex(bArr));
                    }
                }
            }, this.delay_offset + 500);
        }
        return z;
    }

    public synchronized boolean connectIfNotConnected(String str) {
        String str2 = TAG;
        UserError.Log.d(str2, "connectIfNotConnected!!! " + str);
        if (this.mConnectionState != 2) {
            return connect(str);
        }
        UserError.Log.d(str2, "Already connected");
        return false;
    }

    public synchronized boolean connect(java.lang.String r9) {
        throw new UnsupportedOperationException("Method not decompiled: com.eveningoutpost.dexdrip.services.DexCollectionService.connect(java.lang.String):boolean");
    }

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

    private void closeCycle(boolean z) {
        if (mBluetoothGatt != null) {
            try {
                try {
                    if (JoH.ratelimit("refresh-gatt", 60)) {
                        String str = TAG;
                        UserError.Log.d(str, "Refresh result close: " + JoH.refreshDeviceCache(str, mBluetoothGatt));
                    }
                    if (z) {
                        UserError.Log.i(TAG, "connect: mBluetoothGatt isn't null, Closing.");
                        mBluetoothGatt.close();
                    } else {
                        UserError.Log.i(TAG, "preserving existing connection");
                    }
                    if (!z) {
                        return;
                    }
                } catch (NullPointerException unused) {
                    UserError.Log.wtf(TAG, "Concurrency related null pointer in connect");
                    if (!z) {
                        return;
                    }
                }
                mBluetoothGatt = null;
            } catch (Throwable th) {
                if (z) {
                    mBluetoothGatt = null;
                }
                throw th;
            }
        }
    }

    public synchronized void close() {
        String str = TAG;
        UserError.Log.i(str, "close: Closing Connection - setting state DISCONNECTED");
        if (mBluetoothGatt == null) {
            UserError.Log.i(str, "not closing as bluetooth gatt is null");
        } else {
            if (JoH.ratelimit("refresh-gatt", 180)) {
                UserError.Log.d(str, "Refresh result state close: " + JoH.refreshDeviceCache(str, mBluetoothGatt));
            }
            try {
                mBluetoothGatt.close();
            } catch (NullPointerException unused) {
                UserError.Log.wtf(TAG, "Concurrency related null pointer in close");
            }
        }
        setRetryTimer();
        mBluetoothGatt = null;
        mCharacteristic = null;
        this.mConnectionState = 0;
        servicesDiscovered = DISCOVERED.NULL;
        last_connect_request = 0L;
    }

    public void lambda$setSerialDataToTransmitterRawData$5(BridgeResponse bridgeResponse) {
        sendReply(bridgeResponse.getSend());
    }

    private void sendReply(AbstractList<ByteBuffer> abstractList) {
        Iterator<ByteBuffer> it = abstractList.iterator();
        while (it.hasNext()) {
            ByteBuffer next = it.next();
            UserError.Log.d(TAG, "Sending reply message");
            sendBtMessage(next);
        }
    }

    public synchronized void setSerialDataToTransmitterRawData(byte[] bArr, int i) {
        byte b;
        last_time_seen = JoH.tsl();
        watchdog_count = 0;
        if (static_use_blukon && Blukon.checkBlukonPacket(bArr)) {
            byte[] decodeBlukonPacket = Blukon.decodeBlukonPacket(bArr);
            if (decodeBlukonPacket != null) {
                UserError.Log.d(TAG, "Sending reply message from Blukon decoder");
                sendBtMessage(decodeBlukonPacket);
                gotValidPacket();
            }
        } else if (blueReader.isblueReader()) {
            byte[] decodeblueReaderPacket = blueReader.decodeblueReaderPacket(bArr, i);
            if (decodeblueReaderPacket != null) {
                UserError.Log.d(TAG, "Sending reply message from blueReader decoder");
                sendBtMessage(decodeblueReaderPacket);
                gotValidPacket();
            }
        } else if (Tomato.isTomato()) {
            final BridgeResponse decodeTomatoPacket = Tomato.decodeTomatoPacket(bArr, i);
            if (decodeTomatoPacket.shouldDelay()) {
                Inevitable.task("send-tomato-reply", decodeTomatoPacket.getDelay(), new Runnable() {
                    @Override
                    public final void run() {
                        DexCollectionService.this.lambda$setSerialDataToTransmitterRawData$1(decodeTomatoPacket);
                    }
                });
            } else {
                lambda$setSerialDataToTransmitterRawData$5(decodeTomatoPacket);
            }
            if (decodeTomatoPacket.hasError()) {
                JoH.static_toast_long(decodeTomatoPacket.getError_message());
                error(decodeTomatoPacket.getError_message());
            }
            if (decodeTomatoPacket.StillWaitingForData()) {
                UserError.Log.d(TAG, "Arming the timer, asking to send again...");
                Inevitable.task("send-tomato-init", 5000L, new Runnable() {
                    @Override
                    public final void run() {
                        DexCollectionService.this.lambda$setSerialDataToTransmitterRawData$2();
                    }
                });
            } else if (decodeTomatoPacket.GotAllData()) {
                Inevitable.kill("send-tomato-init");
            }
            gotValidPacket();
        } else if (Bubble.isBubble()) {
            final BridgeResponse decodeBubblePacket = Bubble.decodeBubblePacket(bArr, i);
            if (decodeBubblePacket.shouldDelay()) {
                Inevitable.task("send-bubble-reply", decodeBubblePacket.getDelay(), new Runnable() {
                    @Override
                    public final void run() {
                        DexCollectionService.this.lambda$setSerialDataToTransmitterRawData$3(decodeBubblePacket);
                    }
                });
            } else {
                lambda$setSerialDataToTransmitterRawData$5(decodeBubblePacket);
            }
            if (decodeBubblePacket.hasError()) {
                JoH.static_toast_long(decodeBubblePacket.getError_message());
                error(decodeBubblePacket.getError_message());
            }
            gotValidPacket();
        } else if (Atom.isAtom()) {
            final BridgeResponse decodeAtomPacket = Atom.decodeAtomPacket(bArr, i);
            if (decodeAtomPacket.shouldDelay()) {
                Inevitable.task("send-atom-reply", decodeAtomPacket.getDelay(), new Runnable() {
                    @Override
                    public final void run() {
                        DexCollectionService.this.lambda$setSerialDataToTransmitterRawData$4(decodeAtomPacket);
                    }
                });
            } else {
                lambda$setSerialDataToTransmitterRawData$5(decodeAtomPacket);
            }
            if (decodeAtomPacket.hasError()) {
                JoH.static_toast_long(decodeAtomPacket.getError_message());
                error(decodeAtomPacket.getError_message());
            }
            gotValidPacket();
        } else if (LibreBluetooth.isLibreBluettoh()) {
            final BridgeResponse decodeLibrePacket = LibreBluetooth.decodeLibrePacket(bArr, i);
            if (decodeLibrePacket.shouldDelay()) {
                Inevitable.task("send-tomato-reply", decodeLibrePacket.getDelay(), new Runnable() {
                    @Override
                    public final void run() {
                        DexCollectionService.this.lambda$setSerialDataToTransmitterRawData$5(decodeLibrePacket);
                    }
                });
            } else {
                lambda$setSerialDataToTransmitterRawData$5(decodeLibrePacket);
            }
            if (decodeLibrePacket.hasError()) {
                JoH.static_toast_long(decodeLibrePacket.getError_message());
                error(decodeLibrePacket.getError_message());
            }
            gotValidPacket();
        } else if (XbridgePlus.isXbridgeExtensionPacket(bArr)) {
            byte[] decodeXbridgeExtensionPacket = XbridgePlus.decodeXbridgeExtensionPacket(bArr);
            if (decodeXbridgeExtensionPacket != null) {
                UserError.Log.d(TAG, "Sending reply message from xBridge decoder");
                sendBtMessage(decodeXbridgeExtensionPacket);
                gotValidPacket();
            }
        } else {
            long time = new Date().getTime();
            if ((bArr.length > 0 && ((b = bArr[0]) == 7 || b == 17 || b == 21)) || CollectionServiceStarter.isDexBridgeOrWifiandDexBridge()) {
                if (bArr.length == 1 && bArr[0] == 0) {
                    return;
                }
                String str = TAG;
                UserError.Log.i(str, "setSerialDataToTransmitterRawData: Dealing with Dexbridge packet!");
                ByteBuffer allocate = ByteBuffer.allocate(i);
                ByteOrder byteOrder = ByteOrder.LITTLE_ENDIAN;
                allocate.order(byteOrder);
                allocate.put(bArr, 0, i);
                ByteBuffer allocate2 = ByteBuffer.allocate(6);
                allocate2.order(byteOrder);
                byte b2 = bArr[0];
                if (b2 == 7 && bArr[1] == -15) {
                    UserError.Log.i(str, "setSerialDataToTransmitterRawData: Received Beacon packet.");
                    int i2 = allocate.getInt(2);
                    String string = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("dex_txid", "00000");
                    int intValue = convertSrc(string).intValue();
                    if (string.compareTo("00000") != 0 && Integer.compare(i2, intValue) != 0) {
                        UserError.Log.w(str, "setSerialDataToTransmitterRawData: TXID wrong.  Expected " + intValue + " but got " + i2);
                        allocate2.put(0, (byte) 6);
                        allocate2.put(1, (byte) 1);
                        allocate2.putInt(2, intValue);
                        sendBtMessage(allocate2);
                    }
                    return;
                }
                if ((b2 == 17 || b2 == 21) && bArr[1] == 0) {
                    UserError.Log.i(str, "setSerialDataToTransmitterRawData: Received Data packet");
                    if (i >= 17) {
                        int i3 = allocate.getInt(12);
                        int intValue2 = convertSrc(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("dex_txid", "00000")).intValue();
                        if (Integer.compare(i3, intValue2) != 0) {
                            UserError.Log.w(str, "TXID wrong.  Expected " + intValue2 + " but got " + i3);
                            allocate2.put(0, (byte) 6);
                            allocate2.put(1, (byte) 1);
                            allocate2.putInt(2, intValue2);
                            sendBtMessage(allocate2);
                        }
                        Pref.setInt("bridge_battery", ByteBuffer.wrap(bArr).get(11));
                        last_battery_level = Pref.getInt("bridge_battery", -1);
                        UserError.Log.d(str, "setSerialDataToTransmitterRawData: Sending Data packet Ack, to put wixel to sleep");
                        ByteBuffer allocate3 = ByteBuffer.allocate(2);
                        allocate3.put(0, (byte) 2);
                        allocate3.put(1, (byte) -16);
                        sendBtMessage(allocate3);
                        poll_backoff = 0L;
                        gotValidPacket();
                        UserError.Log.v(str, "setSerialDataToTransmitterRawData: Creating TransmitterData at " + time);
                        processNewTransmitterData(TransmitterData.create(bArr, i, Long.valueOf(time)), time);
                        if (Home.get_master()) {
                            GcmActivity.sendBridgeBattery(Pref.getInt("bridge_battery", -1));
                        }
                        CheckBridgeBattery.checkBridgeBattery();
                    }
                }
            } else {
                processNewTransmitterData(TransmitterData.create(bArr, i, Long.valueOf(time)), time);
            }
        }
    }

    public void lambda$setSerialDataToTransmitterRawData$2() {
        UserError.Log.d(TAG, "Asking for sending data again");
        sendReply(Tomato.resetTomatoState());
    }

    private void gotValidPacket() {
        retry_backoff = 0L;
        this.lastPacketTime = JoH.tsl();
    }

    public boolean unBondBlucon() {
        if (!static_use_blukon || !Pref.getBooleanDefaultFalse("blukon_unbonding")) {
            return false;
        }
        UserError.Log.d(TAG, "Attempting to unbond blukon");
        JoH.unBond(this.mDeviceAddress);
        return true;
    }

    private synchronized void processNewTransmitterData(TransmitterData transmitterData, long j) {
        if (transmitterData == null) {
            return;
        }
        Sensor currentSensor = Sensor.currentSensor();
        if (currentSensor == null) {
            UserError.Log.i(TAG, "setSerialDataToTransmitterRawData: No Active Sensor, Data only stored in Transmitter Data");
            return;
        }
        if (this.use_transmiter_pl_bluetooth && transmitterData.raw_data == 100000.0d) {
            UserError.Log.wtf(TAG, "Ignoring probably erroneous Transmiter_PL data: " + transmitterData.raw_data);
            return;
        }
        currentSensor.latest_battery_level = transmitterData.sensor_battery_level;
        currentSensor.save();
        last_transmitter_Data = transmitterData;
        UserError.Log.d(TAG, "BgReading.create: new BG reading at " + j + " with a timestamp of " + transmitterData.timestamp);
        BgReading.create(transmitterData.raw_data, transmitterData.filtered_data, this, Long.valueOf(transmitterData.timestamp));
    }

    public synchronized boolean areWeBonded(String str) {
        BluetoothAdapter bluetoothAdapter = this.mBluetoothAdapter;
        if (bluetoothAdapter == null) {
            UserError.Log.e(TAG, "mBluetoothAdapter is null");
            return true;
        }
        Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
        if (bondedDevices != null && bondedDevices.size() > 0) {
            Iterator<BluetoothDevice> it = bondedDevices.iterator();
            while (it.hasNext()) {
                String address = it.next().getAddress();
                if (address != null && str.equals(address)) {
                    UserError.Log.d(TAG, str + " is bonded");
                    bondedState = str;
                    return true;
                }
            }
        }
        UserError.Log.d(TAG, str + " is not bonded");
        bondedState = "";
        return false;
    }

    private void watchdog() {
        if (last_time_seen != 0 && this.prefs.getBoolean("bluetooth_watchdog", false)) {
            int i = 20;
            int parseIntWithDefault = JoH.parseIntWithDefault(Pref.getString("bluetooth_watchdog_timer", Integer.toString(20)), 10, 20);
            if (parseIntWithDefault > 5 && parseIntWithDefault <= 20) {
                i = parseIntWithDefault;
            }
            if (JoH.msSince(last_time_seen) > i * 60000) {
                String str = TAG;
                UserError.Log.d(str, "Use BT Watchdog timer=" + i);
                if (!JoH.isOngoingCall()) {
                    UserError.Log.e(str, "Watchdog triggered, attempting to reset bluetooth");
                    status("Watchdog triggered");
                    JoH.restartBluetooth(getApplicationContext());
                    last_time_seen = JoH.tsl();
                    int i2 = watchdog_count + 1;
                    watchdog_count = i2;
                    if (i2 > 5) {
                        last_time_seen = 0L;
                        return;
                    }
                    return;
                }
                UserError.Log.e(str, "Delaying watchdog reset as phone call is ongoing.");
            }
        }
    }

    private static boolean useScanning() {
        return Pref.getBooleanDefaultFalse("bluetooth_use_scan");
    }
}