package no.nordicsemi.android.dfu;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.SystemClock;
import android.util.Log;
import d.h.b.k;
import d.h.b.l;
import g.a.a.a.a;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import no.nordicsemi.android.dfu.DfuProgressInfo;
import no.nordicsemi.android.dfu.internal.ArchiveInputStream;
import no.nordicsemi.android.dfu.internal.HexInputStream;

/* JADX INFO: loaded from: classes2.dex */
@SuppressLint({"MissingPermission"})
public abstract class DfuBaseService extends IntentService implements DfuProgressInfo.ProgressListener {
    public static final /* synthetic */ boolean $assertionsDisabled = false;
    public static final int ACTION_ABORT = 2;
    public static final int ACTION_PAUSE = 0;
    public static final int ACTION_RESUME = 1;
    public static final String BROADCAST_ACTION = "no.nordicsemi.android.dfu.broadcast.BROADCAST_ACTION";
    public static final String BROADCAST_ERROR = "no.nordicsemi.android.dfu.broadcast.BROADCAST_ERROR";
    public static final String BROADCAST_LOG = "no.nordicsemi.android.dfu.broadcast.BROADCAST_LOG";
    public static final String BROADCAST_PROGRESS = "no.nordicsemi.android.dfu.broadcast.BROADCAST_PROGRESS";
    public static boolean DEBUG = false;
    public static final int ERROR_BLUETOOTH_DISABLED = 4106;
    public static final int ERROR_CONNECTION_MASK = 16384;
    public static final int ERROR_CONNECTION_STATE_MASK = 32768;
    public static final int ERROR_CRC_ERROR = 4109;
    public static final int ERROR_DEVICE_DISCONNECTED = 4096;
    public static final int ERROR_DEVICE_NOT_BONDED = 4110;
    public static final int ERROR_FILE_ERROR = 4098;
    public static final int ERROR_FILE_INVALID = 4099;
    public static final int ERROR_FILE_IO_EXCEPTION = 4100;
    public static final int ERROR_FILE_NOT_FOUND = 4097;
    public static final int ERROR_FILE_SIZE_INVALID = 4108;
    public static final int ERROR_FILE_TYPE_UNSUPPORTED = 4105;
    public static final int ERROR_INIT_PACKET_REQUIRED = 4107;
    public static final int ERROR_INVALID_RESPONSE = 4104;
    public static final int ERROR_MASK = 4096;
    public static final int ERROR_PROGRESS_LOST = 4111;
    public static final int ERROR_REMOTE_MASK = 8192;
    public static final int ERROR_REMOTE_TYPE_LEGACY = 256;
    public static final int ERROR_REMOTE_TYPE_SECURE = 512;
    public static final int ERROR_REMOTE_TYPE_SECURE_BUTTONLESS = 2048;
    public static final int ERROR_REMOTE_TYPE_SECURE_EXTENDED = 1024;
    public static final int ERROR_SERVICE_DISCOVERY_NOT_STARTED = 4101;
    public static final int ERROR_SERVICE_NOT_FOUND = 4102;
    public static final int ERROR_TYPE_COMMUNICATION = 2;
    public static final int ERROR_TYPE_COMMUNICATION_STATE = 1;
    public static final int ERROR_TYPE_DFU_REMOTE = 3;
    public static final int ERROR_TYPE_OTHER = 0;
    public static final String EXTRA_ACTION = "no.nordicsemi.android.dfu.extra.EXTRA_ACTION";
    public static final String EXTRA_AVG_SPEED_B_PER_MS = "no.nordicsemi.android.dfu.extra.EXTRA_AVG_SPEED_B_PER_MS";
    public static final String EXTRA_CURRENT_MTU = "no.nordicsemi.android.dfu.extra.EXTRA_CURRENT_MTU";
    public static final String EXTRA_CUSTOM_UUIDS_FOR_BUTTONLESS_DFU_WITHOUT_BOND_SHARING = "no.nordicsemi.android.dfu.extra.EXTRA_CUSTOM_UUIDS_FOR_BUTTONLESS_DFU_WITHOUT_BOND_SHARING";
    public static final String EXTRA_CUSTOM_UUIDS_FOR_BUTTONLESS_DFU_WITH_BOND_SHARING = "no.nordicsemi.android.dfu.extra.EXTRA_CUSTOM_UUIDS_FOR_BUTTONLESS_DFU_WITH_BOND_SHARING";
    public static final String EXTRA_CUSTOM_UUIDS_FOR_EXPERIMENTAL_BUTTONLESS_DFU = "no.nordicsemi.android.dfu.extra.EXTRA_CUSTOM_UUIDS_FOR_EXPERIMENTAL_BUTTONLESS_DFU";
    public static final String EXTRA_CUSTOM_UUIDS_FOR_LEGACY_DFU = "no.nordicsemi.android.dfu.extra.EXTRA_CUSTOM_UUIDS_FOR_LEGACY_DFU";
    public static final String EXTRA_CUSTOM_UUIDS_FOR_SECURE_DFU = "no.nordicsemi.android.dfu.extra.EXTRA_CUSTOM_UUIDS_FOR_SECURE_DFU";
    public static final String EXTRA_DATA = "no.nordicsemi.android.dfu.extra.EXTRA_DATA";
    public static final String EXTRA_DATA_OBJECT_DELAY = "no.nordicsemi.android.dfu.extra.EXTRA_DATA_OBJECT_DELAY";
    public static final String EXTRA_DEVICE_ADDRESS = "no.nordicsemi.android.dfu.extra.EXTRA_DEVICE_ADDRESS";
    public static final String EXTRA_DEVICE_NAME = "no.nordicsemi.android.dfu.extra.EXTRA_DEVICE_NAME";
    public static final String EXTRA_DFU_ATTEMPT = "no.nordicsemi.android.dfu.extra.EXTRA_DFU_ATTEMPT";
    public static final String EXTRA_DISABLE_NOTIFICATION = "no.nordicsemi.android.dfu.extra.EXTRA_DISABLE_NOTIFICATION";
    public static final String EXTRA_DISABLE_RESUME = "no.nordicsemi.android.dfu.extra.EXTRA_DISABLE_RESUME";
    public static final String EXTRA_ERROR_TYPE = "no.nordicsemi.android.dfu.extra.EXTRA_ERROR_TYPE";
    public static final String EXTRA_FILE_MIME_TYPE = "no.nordicsemi.android.dfu.extra.EXTRA_MIME_TYPE";
    public static final String EXTRA_FILE_PATH = "no.nordicsemi.android.dfu.extra.EXTRA_FILE_PATH";
    public static final String EXTRA_FILE_RES_ID = "no.nordicsemi.android.dfu.extra.EXTRA_FILE_RES_ID";
    public static final String EXTRA_FILE_TYPE = "no.nordicsemi.android.dfu.extra.EXTRA_FILE_TYPE";
    public static final String EXTRA_FILE_URI = "no.nordicsemi.android.dfu.extra.EXTRA_FILE_URI";
    public static final String EXTRA_FORCE_DFU = "no.nordicsemi.android.dfu.extra.EXTRA_FORCE_DFU";
    public static final String EXTRA_FORCE_SCANNING_FOR_BOOTLOADER_IN_LEGACY_DFU = "no.nordicsemi.android.dfu.extra.EXTRA_FORCE_SCANNING_FOR_BOOTLOADER_IN_LEGACY_DFU";
    public static final String EXTRA_FOREGROUND_SERVICE = "no.nordicsemi.android.dfu.extra.EXTRA_FOREGROUND_SERVICE";
    public static final String EXTRA_INIT_FILE_PATH = "no.nordicsemi.android.dfu.extra.EXTRA_INIT_FILE_PATH";
    public static final String EXTRA_INIT_FILE_RES_ID = "no.nordicsemi.android.dfu.extra.EXTRA_INIT_FILE_RES_ID";
    public static final String EXTRA_INIT_FILE_URI = "no.nordicsemi.android.dfu.extra.EXTRA_INIT_FILE_URI";
    public static final String EXTRA_KEEP_BOND = "no.nordicsemi.android.dfu.extra.EXTRA_KEEP_BOND";
    public static final String EXTRA_LOG_LEVEL = "no.nordicsemi.android.dfu.extra.EXTRA_LOG_LEVEL";
    public static final String EXTRA_LOG_MESSAGE = "no.nordicsemi.android.dfu.extra.EXTRA_LOG_INFO";
    public static final String EXTRA_MAX_DFU_ATTEMPTS = "no.nordicsemi.android.dfu.extra.EXTRA_MAX_DFU_ATTEMPTS";
    public static final String EXTRA_MBR_SIZE = "no.nordicsemi.android.dfu.extra.EXTRA_MBR_SIZE";
    public static final String EXTRA_MTU = "no.nordicsemi.android.dfu.extra.EXTRA_MTU";
    public static final String EXTRA_PACKET_RECEIPT_NOTIFICATIONS_ENABLED = "no.nordicsemi.android.dfu.extra.EXTRA_PRN_ENABLED";
    public static final String EXTRA_PACKET_RECEIPT_NOTIFICATIONS_VALUE = "no.nordicsemi.android.dfu.extra.EXTRA_PRN_VALUE";
    public static final String EXTRA_PARTS_TOTAL = "no.nordicsemi.android.dfu.extra.EXTRA_PARTS_TOTAL";
    public static final String EXTRA_PART_CURRENT = "no.nordicsemi.android.dfu.extra.EXTRA_PART_CURRENT";
    public static final String EXTRA_PROGRESS = "no.nordicsemi.android.dfu.extra.EXTRA_PROGRESS";
    private static final String EXTRA_RECONNECTION_ATTEMPT = "no.nordicsemi.android.dfu.extra.EXTRA_RECONNECTION_ATTEMPT";
    public static final String EXTRA_RESTORE_BOND = "no.nordicsemi.android.dfu.extra.EXTRA_RESTORE_BOND";
    public static final String EXTRA_SCAN_DELAY = "no.nordicsemi.android.dfu.extra.EXTRA_SCAN_DELAY";
    public static final String EXTRA_SCAN_TIMEOUT = "no.nordicsemi.android.dfu.extra.EXTRA_SCAN_TIMEOUT";
    public static final String EXTRA_SPEED_B_PER_MS = "no.nordicsemi.android.dfu.extra.EXTRA_SPEED_B_PER_MS";
    public static final String EXTRA_UNSAFE_EXPERIMENTAL_BUTTONLESS_DFU = "no.nordicsemi.android.dfu.extra.EXTRA_UNSAFE_EXPERIMENTAL_BUTTONLESS_DFU";
    public static final int LOG_LEVEL_APPLICATION = 10;
    public static final int LOG_LEVEL_DEBUG = 0;
    public static final int LOG_LEVEL_ERROR = 20;
    public static final int LOG_LEVEL_INFO = 5;
    public static final int LOG_LEVEL_VERBOSE = 1;
    public static final int LOG_LEVEL_WARNING = 15;
    public static final String MIME_TYPE_OCTET_STREAM = "application/octet-stream";
    public static final String MIME_TYPE_ZIP = "application/zip";
    public static final String NOTIFICATION_CHANNEL_DFU = "dfu";
    public static final int NOTIFICATION_ID = 283;
    public static final int PROGRESS_ABORTED = -7;
    public static final int PROGRESS_COMPLETED = -6;
    public static final int PROGRESS_CONNECTING = -1;
    public static final int PROGRESS_DISCONNECTING = -5;
    public static final int PROGRESS_ENABLING_DFU_MODE = -3;
    public static final int PROGRESS_STARTING = -2;
    public static final int PROGRESS_VALIDATING = -4;
    public static final int STATE_CLOSED = -5;
    public static final int STATE_CONNECTED = -2;
    public static final int STATE_CONNECTED_AND_READY = -3;
    public static final int STATE_CONNECTING = -1;
    public static final int STATE_DISCONNECTED = 0;
    public static final int STATE_DISCONNECTING = -4;
    private static final String TAG = "DfuBaseService";
    public static final int TYPE_APPLICATION = 4;
    public static final int TYPE_AUTO = 0;
    public static final int TYPE_BOOTLOADER = 2;
    public static final int TYPE_SOFT_DEVICE = 1;
    private boolean mAborted;
    private BluetoothAdapter mBluetoothAdapter;
    private final BroadcastReceiver mBluetoothStateBroadcastReceiver;
    private final BroadcastReceiver mBondStateBroadcastReceiver;
    public int mConnectionState;
    private final BroadcastReceiver mConnectionStateBroadcastReceiver;
    private String mDeviceAddress;
    private String mDeviceName;
    private final BroadcastReceiver mDfuActionReceiver;
    private DfuCallback mDfuServiceImpl;
    private boolean mDisableNotification;
    private int mError;
    private InputStream mFirmwareInputStream;
    private final BluetoothGattCallback mGattCallback;
    private InputStream mInitFileInputStream;
    private long mLastNotificationTime;
    private int mLastProgress;
    private final Object mLock;
    public DfuProgressInfo mProgressInfo;

    public DfuBaseService() {
        super(TAG);
        this.mLock = new Object();
        this.mLastProgress = -1;
        this.mDfuActionReceiver = new BroadcastReceiver() { // from class: no.nordicsemi.android.dfu.DfuBaseService.1
            @Override // android.content.BroadcastReceiver
            public void onReceive(Context context, Intent intent) {
                int intExtra = intent.getIntExtra(DfuBaseService.EXTRA_ACTION, 0);
                DfuBaseService.this.logi("User action received: " + intExtra);
                if (intExtra == 0) {
                    DfuBaseService.this.sendLogBroadcast(15, "[Broadcast] Pause action received");
                    if (DfuBaseService.this.mDfuServiceImpl != null) {
                        DfuBaseService.this.mDfuServiceImpl.pause();
                        return;
                    }
                    return;
                }
                if (intExtra == 1) {
                    DfuBaseService.this.sendLogBroadcast(15, "[Broadcast] Resume action received");
                    if (DfuBaseService.this.mDfuServiceImpl != null) {
                        DfuBaseService.this.mDfuServiceImpl.resume();
                        return;
                    }
                    return;
                }
                if (intExtra != 2) {
                    return;
                }
                DfuBaseService.this.sendLogBroadcast(15, "[Broadcast] Abort action received");
                DfuBaseService.this.mAborted = true;
                if (DfuBaseService.this.mDfuServiceImpl != null) {
                    DfuBaseService.this.mDfuServiceImpl.abort();
                }
            }
        };
        this.mBluetoothStateBroadcastReceiver = new BroadcastReceiver() { // from class: no.nordicsemi.android.dfu.DfuBaseService.2
            @Override // android.content.BroadcastReceiver
            public void onReceive(Context context, Intent intent) {
                int intExtra = intent.getIntExtra("android.bluetooth.adapter.extra.STATE", 10);
                int intExtra2 = intent.getIntExtra("android.bluetooth.adapter.extra.PREVIOUS_STATE", 12);
                DfuBaseService.this.logw(a.p("Action received: android.bluetooth.adapter.action.STATE_CHANGED [state: ", intExtra, ", previous state: ", intExtra2, "]"));
                if (intExtra2 == 12) {
                    if (intExtra == 13 || intExtra == 10) {
                        DfuBaseService.this.sendLogBroadcast(15, "Bluetooth adapter disabled");
                        DfuBaseService dfuBaseService = DfuBaseService.this;
                        dfuBaseService.mConnectionState = 0;
                        if (dfuBaseService.mDfuServiceImpl != null) {
                            DfuBaseService.this.mDfuServiceImpl.getGattCallback().onDisconnected();
                        }
                        synchronized (DfuBaseService.this.mLock) {
                            DfuBaseService.this.mLock.notifyAll();
                        }
                    }
                }
            }
        };
        this.mBondStateBroadcastReceiver = new BroadcastReceiver() { // from class: no.nordicsemi.android.dfu.DfuBaseService.3
            @Override // android.content.BroadcastReceiver
            public void onReceive(Context context, Intent intent) {
                int intExtra;
                BluetoothDevice bluetoothDevice = (BluetoothDevice) intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
                if (bluetoothDevice == null || !bluetoothDevice.getAddress().equals(DfuBaseService.this.mDeviceAddress) || (intExtra = intent.getIntExtra("android.bluetooth.device.extra.BOND_STATE", -1)) == 11 || DfuBaseService.this.mDfuServiceImpl == null) {
                    return;
                }
                DfuBaseService.this.mDfuServiceImpl.onBondStateChanged(intExtra);
            }
        };
        this.mConnectionStateBroadcastReceiver = new BroadcastReceiver() { // from class: no.nordicsemi.android.dfu.DfuBaseService.4
            @Override // android.content.BroadcastReceiver
            public void onReceive(Context context, Intent intent) {
                BluetoothDevice bluetoothDevice = (BluetoothDevice) intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
                if (bluetoothDevice == null || !bluetoothDevice.getAddress().equals(DfuBaseService.this.mDeviceAddress)) {
                    return;
                }
                String action = intent.getAction();
                DfuBaseService.this.logi("Action received: " + action);
                DfuBaseService.this.sendLogBroadcast(0, "[Broadcast] Action received: " + action);
            }
        };
        this.mGattCallback = new BluetoothGattCallback() { // from class: no.nordicsemi.android.dfu.DfuBaseService.5
            @Override // android.bluetooth.BluetoothGattCallback
            public void onCharacteristicChanged(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic) {
                if (DfuBaseService.this.mDfuServiceImpl != null) {
                    DfuBaseService.this.mDfuServiceImpl.getGattCallback().onCharacteristicChanged(bluetoothGatt, bluetoothGattCharacteristic);
                }
            }

            @Override // android.bluetooth.BluetoothGattCallback
            public void onCharacteristicRead(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic, int i2) {
                if (DfuBaseService.this.mDfuServiceImpl != null) {
                    DfuBaseService.this.mDfuServiceImpl.getGattCallback().onCharacteristicRead(bluetoothGatt, bluetoothGattCharacteristic, i2);
                }
            }

            @Override // android.bluetooth.BluetoothGattCallback
            public void onCharacteristicWrite(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic, int i2) {
                if (DfuBaseService.this.mDfuServiceImpl != null) {
                    DfuBaseService.this.mDfuServiceImpl.getGattCallback().onCharacteristicWrite(bluetoothGatt, bluetoothGattCharacteristic, i2);
                }
            }

            /* JADX WARN: Removed duplicated region for block: B:32:0x00e4  */
            @Override // android.bluetooth.BluetoothGattCallback
            /*
                Code decompiled incorrectly, please refer to instructions dump.
                To view partially-correct add '--show-bad-code' argument
            */
            public void onConnectionStateChange(android.bluetooth.BluetoothGatt r4, int r5, int r6) {
                /*
                    Method dump skipped, instruction units count: 262
                    To view this dump add '--comments-level debug' option
                */
                throw new UnsupportedOperationException("Method not decompiled: no.nordicsemi.android.dfu.DfuBaseService.AnonymousClass5.onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int):void");
            }

            @Override // android.bluetooth.BluetoothGattCallback
            public void onDescriptorRead(BluetoothGatt bluetoothGatt, BluetoothGattDescriptor bluetoothGattDescriptor, int i2) {
                if (DfuBaseService.this.mDfuServiceImpl != null) {
                    DfuBaseService.this.mDfuServiceImpl.getGattCallback().onDescriptorRead(bluetoothGatt, bluetoothGattDescriptor, i2);
                }
            }

            @Override // android.bluetooth.BluetoothGattCallback
            public void onDescriptorWrite(BluetoothGatt bluetoothGatt, BluetoothGattDescriptor bluetoothGattDescriptor, int i2) {
                if (DfuBaseService.this.mDfuServiceImpl != null) {
                    DfuBaseService.this.mDfuServiceImpl.getGattCallback().onDescriptorWrite(bluetoothGatt, bluetoothGattDescriptor, i2);
                }
            }

            @Override // android.bluetooth.BluetoothGattCallback
            @SuppressLint({"NewApi"})
            public void onMtuChanged(BluetoothGatt bluetoothGatt, int i2, int i3) {
                if (DfuBaseService.this.mDfuServiceImpl != null) {
                    DfuBaseService.this.mDfuServiceImpl.getGattCallback().onMtuChanged(bluetoothGatt, i2, i3);
                }
            }

            @Override // android.bluetooth.BluetoothGattCallback
            @SuppressLint({"NewApi"})
            public void onPhyUpdate(BluetoothGatt bluetoothGatt, int i2, int i3, int i4) {
                if (DfuBaseService.this.mDfuServiceImpl != null) {
                    DfuBaseService.this.mDfuServiceImpl.getGattCallback().onPhyUpdate(bluetoothGatt, i2, i3, i4);
                }
            }

            @Override // android.bluetooth.BluetoothGattCallback
            public void onServicesDiscovered(BluetoothGatt bluetoothGatt, int i2) {
                DfuBaseService dfuBaseService = DfuBaseService.this;
                if (i2 == 0) {
                    dfuBaseService.logi("Services discovered");
                    DfuBaseService.this.mConnectionState = -3;
                } else {
                    dfuBaseService.loge("Service discovery error: " + i2);
                    DfuBaseService.this.mError = i2 | 16384;
                }
                synchronized (DfuBaseService.this.mLock) {
                    DfuBaseService.this.mLock.notifyAll();
                }
            }
        };
    }

    private boolean initialize() {
        String str;
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService("bluetooth");
        if (bluetoothManager == null) {
            str = "Unable to initialize BluetoothManager.";
        } else {
            BluetoothAdapter adapter = bluetoothManager.getAdapter();
            this.mBluetoothAdapter = adapter;
            if (adapter != null) {
                return true;
            }
            str = "Unable to obtain a BluetoothAdapter.";
        }
        loge(str);
        return false;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void loge(String str) {
        Log.e(TAG, str);
    }

    private void loge(String str, Throwable th) {
        Log.e(TAG, str, th);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void logi(String str) {
        if (DEBUG) {
            Log.i(TAG, str);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void logw(String str) {
        if (DEBUG) {
            Log.w(TAG, str);
        }
    }

    private static IntentFilter makeDfuActionIntentFilter() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BROADCAST_ACTION);
        return intentFilter;
    }

    private InputStream openInputStream(int i2, String str, int i3, int i4) throws IOException {
        InputStream inputStreamOpenRawResource = getResources().openRawResource(i2);
        if (MIME_TYPE_ZIP.equals(str)) {
            return new ArchiveInputStream(inputStreamOpenRawResource, i3, i4);
        }
        inputStreamOpenRawResource.mark(2);
        int i5 = inputStreamOpenRawResource.read();
        inputStreamOpenRawResource.reset();
        return i5 == 58 ? new HexInputStream(inputStreamOpenRawResource, i3) : inputStreamOpenRawResource;
    }

    private InputStream openInputStream(Uri uri, String str, int i2, int i3) {
        InputStream inputStreamOpen = uri.toString().startsWith("file:///android_asset/") ? getAssets().open(uri.getPath().substring(15)) : getContentResolver().openInputStream(uri);
        if (MIME_TYPE_ZIP.equals(str)) {
            return new ArchiveInputStream(inputStreamOpen, i2, i3);
        }
        Cursor cursorQuery = getContentResolver().query(uri, new String[]{"_display_name"}, null, null, null);
        if (cursorQuery != null) {
            try {
                if (cursorQuery.moveToNext() && cursorQuery.getString(0).toLowerCase(Locale.US).endsWith("hex")) {
                    HexInputStream hexInputStream = new HexInputStream(inputStreamOpen, i2);
                    cursorQuery.close();
                    return hexInputStream;
                }
            } catch (Throwable th) {
                try {
                    cursorQuery.close();
                } catch (Throwable th2) {
                    th.addSuppressed(th2);
                }
                throw th;
            }
        }
        if (cursorQuery != null) {
            cursorQuery.close();
        }
        return inputStreamOpen;
    }

    private InputStream openInputStream(String str, String str2, int i2, int i3) {
        FileInputStream fileInputStream = new FileInputStream(str);
        return MIME_TYPE_ZIP.equals(str2) ? new ArchiveInputStream(fileInputStream, i2, i3) : str.toLowerCase(Locale.US).endsWith("hex") ? new HexInputStream(fileInputStream, i2) : fileInputStream;
    }

    private void report(int i2) {
        sendErrorBroadcast(i2);
        if (this.mDisableNotification) {
            return;
        }
        String str = this.mDeviceAddress;
        String string = this.mDeviceName;
        if (string == null) {
            string = getString(R.string.dfu_unknown_name);
        }
        l lVar = new l(this, NOTIFICATION_CHANNEL_DFU);
        lVar.f2614q.icon = android.R.drawable.stat_sys_upload;
        lVar.e(8, true);
        lVar.f2611n = -65536;
        lVar.e(2, false);
        lVar.d(getString(R.string.dfu_status_error));
        lVar.f2614q.icon = android.R.drawable.stat_sys_upload_done;
        lVar.c(getString(R.string.dfu_status_error_msg));
        lVar.e(16, true);
        Intent intent = new Intent(this, getNotificationTarget());
        intent.addFlags(268435456);
        intent.putExtra(EXTRA_DEVICE_ADDRESS, str);
        intent.putExtra(EXTRA_DEVICE_NAME, string);
        intent.putExtra(EXTRA_PROGRESS, i2);
        lVar.f2604g = PendingIntent.getActivity(this, 0, intent, 201326592);
        updateErrorNotification(lVar);
        NotificationManager notificationManager = (NotificationManager) getSystemService("notification");
        if (notificationManager != null) {
            notificationManager.notify(NOTIFICATION_ID, lVar.a());
        }
    }

    private void sendErrorBroadcast(int i2) {
        int i3;
        Intent intent = new Intent(BROADCAST_ERROR);
        if ((i2 & 16384) > 0) {
            intent.putExtra(EXTRA_DATA, i2 & (-16385));
            i3 = 2;
        } else if ((32768 & i2) > 0) {
            intent.putExtra(EXTRA_DATA, i2 & (-32769));
            i3 = 1;
        } else if ((i2 & 8192) > 0) {
            intent.putExtra(EXTRA_DATA, i2 & (-8193));
            i3 = 3;
        } else {
            intent.putExtra(EXTRA_DATA, i2);
            i3 = 0;
        }
        intent.putExtra(EXTRA_ERROR_TYPE, i3);
        intent.putExtra(EXTRA_DEVICE_ADDRESS, this.mDeviceAddress);
        d.o.a.a.a(this).c(intent);
    }

    private void sendProgressBroadcast(DfuProgressInfo dfuProgressInfo) {
        Intent intent = new Intent(BROADCAST_PROGRESS);
        intent.putExtra(EXTRA_DATA, dfuProgressInfo.getProgress());
        intent.putExtra(EXTRA_DEVICE_ADDRESS, this.mDeviceAddress);
        intent.putExtra(EXTRA_PART_CURRENT, dfuProgressInfo.getCurrentPart());
        intent.putExtra(EXTRA_PARTS_TOTAL, dfuProgressInfo.getTotalParts());
        intent.putExtra(EXTRA_SPEED_B_PER_MS, dfuProgressInfo.getSpeed());
        intent.putExtra(EXTRA_AVG_SPEED_B_PER_MS, dfuProgressInfo.getAverageSpeed());
        d.o.a.a.a(this).c(intent);
    }

    private void startForeground() {
        l lVar = new l(this, NOTIFICATION_CHANNEL_DFU);
        lVar.f2614q.icon = android.R.drawable.stat_sys_upload;
        lVar.d(getString(R.string.dfu_status_foreground_title));
        lVar.c(getString(R.string.dfu_status_foreground_content));
        lVar.f2611n = -7829368;
        lVar.f2605h = -1;
        lVar.e(2, true);
        Class<? extends Activity> notificationTarget = getNotificationTarget();
        if (notificationTarget != null) {
            Intent intent = new Intent(this, notificationTarget);
            intent.addFlags(268435456);
            intent.putExtra(EXTRA_DEVICE_ADDRESS, this.mDeviceAddress);
            intent.putExtra(EXTRA_DEVICE_NAME, this.mDeviceName);
            lVar.f2604g = PendingIntent.getActivity(this, 0, intent, 201326592);
        } else {
            logw("getNotificationTarget() should not return null if the service is to be started as a foreground service");
        }
        updateForegroundNotification(lVar);
        startForeground(NOTIFICATION_ID, lVar.a());
    }

    public void close(BluetoothGatt bluetoothGatt) {
        logi("Cleaning up...");
        sendLogBroadcast(0, "gatt.disconnect()");
        bluetoothGatt.disconnect();
        sendLogBroadcast(0, "gatt.close()");
        bluetoothGatt.close();
        this.mConnectionState = -5;
    }

    public BluetoothGatt connect(String str) {
        if (!this.mBluetoothAdapter.isEnabled()) {
            return null;
        }
        this.mConnectionState = -1;
        logi("Connecting to the device...");
        BluetoothDevice remoteDevice = this.mBluetoothAdapter.getRemoteDevice(str);
        sendLogBroadcast(0, "gatt = device.connectGatt(autoConnect = false, TRANSPORT_LE, preferredPhy = LE_1M | LE_2M)");
        BluetoothGatt bluetoothGattConnectGatt = remoteDevice.connectGatt(this, false, this.mGattCallback, 2, 3);
        try {
            synchronized (this.mLock) {
                while (true) {
                    int i2 = this.mConnectionState;
                    if ((i2 != -1 && i2 != -2) || this.mError != 0 || this.mAborted) {
                        break;
                    }
                    this.mLock.wait();
                }
            }
        } catch (InterruptedException e2) {
            loge("Sleeping interrupted", e2);
        }
        return bluetoothGattConnectGatt;
    }

    public void disconnect(BluetoothGatt bluetoothGatt) {
        if (this.mConnectionState == 0) {
            return;
        }
        sendLogBroadcast(1, "Disconnecting...");
        this.mProgressInfo.setProgress(-5);
        this.mConnectionState = -4;
        logi("Disconnecting from the device...");
        sendLogBroadcast(0, "gatt.disconnect()");
        bluetoothGatt.disconnect();
        waitUntilDisconnected();
        sendLogBroadcast(5, "Disconnected");
    }

    public DfuDeviceSelector getDeviceSelector() {
        return new DfuDefaultDeviceSelector();
    }

    public abstract Class<? extends Activity> getNotificationTarget();

    public boolean isDebug() {
        return false;
    }

    @Override // android.app.IntentService, android.app.Service
    public void onCreate() {
        super.onCreate();
        DEBUG = isDebug();
        logi("DFU service created. Version: 2.2.2");
        initialize();
        d.o.a.a aVarA = d.o.a.a.a(this);
        IntentFilter intentFilterMakeDfuActionIntentFilter = makeDfuActionIntentFilter();
        aVarA.b(this.mDfuActionReceiver, intentFilterMakeDfuActionIntentFilter);
        registerReceiver(this.mDfuActionReceiver, intentFilterMakeDfuActionIntentFilter);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.bluetooth.device.action.ACL_CONNECTED");
        intentFilter.addAction("android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED");
        intentFilter.addAction("android.bluetooth.device.action.ACL_DISCONNECTED");
        registerReceiver(this.mConnectionStateBroadcastReceiver, intentFilter);
        registerReceiver(this.mBondStateBroadcastReceiver, new IntentFilter("android.bluetooth.device.action.BOND_STATE_CHANGED"));
        registerReceiver(this.mBluetoothStateBroadcastReceiver, new IntentFilter("android.bluetooth.adapter.action.STATE_CHANGED"));
    }

    @Override // android.app.IntentService, android.app.Service
    public void onDestroy() {
        super.onDestroy();
        DfuCallback dfuCallback = this.mDfuServiceImpl;
        if (dfuCallback != null) {
            dfuCallback.abort();
        }
        d.o.a.a.a(this).d(this.mDfuActionReceiver);
        unregisterReceiver(this.mDfuActionReceiver);
        unregisterReceiver(this.mConnectionStateBroadcastReceiver);
        unregisterReceiver(this.mBondStateBroadcastReceiver);
        unregisterReceiver(this.mBluetoothStateBroadcastReceiver);
        try {
            InputStream inputStream = this.mFirmwareInputStream;
            if (inputStream != null) {
                inputStream.close();
            }
            InputStream inputStream2 = this.mInitFileInputStream;
            if (inputStream2 != null) {
                inputStream2.close();
            }
        } catch (IOException unused) {
        } catch (Throwable th) {
            this.mFirmwareInputStream = null;
            this.mInitFileInputStream = null;
            throw th;
        }
        this.mFirmwareInputStream = null;
        this.mInitFileInputStream = null;
        logi("DFU service destroyed");
    }

    /* JADX WARN: Removed duplicated region for block: B:135:0x0213 A[Catch: all -> 0x0179, Exception -> 0x017d, IOException -> 0x0181, SizeValidationException -> 0x0185, FileNotFoundException -> 0x0189, SecurityException -> 0x018d, TryCatch #17 {SecurityException -> 0x018d, blocks: (B:62:0x0124, B:64:0x012e, B:71:0x0145, B:77:0x0167, B:95:0x0195, B:97:0x019b, B:99:0x01a0, B:101:0x01a9, B:103:0x01ad, B:106:0x01b6, B:107:0x01bd, B:108:0x01be, B:110:0x01c2, B:113:0x01cb, B:114:0x01d2, B:115:0x01d3, B:117:0x01d7, B:120:0x01e0, B:121:0x01e7, B:124:0x01eb, B:126:0x01f1, B:135:0x0213, B:137:0x021c, B:138:0x0223, B:127:0x01fb, B:129:0x0201, B:100:0x01a5, B:80:0x0171, B:81:0x0178, B:73:0x0150, B:75:0x015a, B:66:0x0135, B:68:0x013c), top: B:312:0x0124, outer: #16 }] */
    /* JADX WARN: Removed duplicated region for block: B:142:0x023b A[Catch: all -> 0x0179, TRY_ENTER, TRY_LEAVE, TryCatch #16 {all -> 0x0179, blocks: (B:62:0x0124, B:64:0x012e, B:71:0x0145, B:77:0x0167, B:95:0x0195, B:97:0x019b, B:99:0x01a0, B:101:0x01a9, B:103:0x01ad, B:106:0x01b6, B:107:0x01bd, B:108:0x01be, B:110:0x01c2, B:113:0x01cb, B:114:0x01d2, B:115:0x01d3, B:117:0x01d7, B:120:0x01e0, B:121:0x01e7, B:124:0x01eb, B:126:0x01f1, B:135:0x0213, B:137:0x021c, B:138:0x0223, B:139:0x022d, B:142:0x023b, B:146:0x024e, B:148:0x026a, B:152:0x027f, B:158:0x0290, B:186:0x039c, B:192:0x03ac, B:194:0x03b0, B:199:0x03c4, B:201:0x03c8, B:205:0x03df, B:212:0x040e, B:222:0x042a, B:254:0x0501, B:245:0x04a2, B:268:0x052d, B:269:0x0530, B:127:0x01fb, B:129:0x0201, B:100:0x01a5, B:80:0x0171, B:81:0x0178, B:73:0x0150, B:75:0x015a, B:66:0x0135, B:68:0x013c, B:270:0x0531, B:274:0x0559, B:278:0x0581, B:282:0x0598, B:286:0x05af), top: B:311:0x0122, inners: #17, #17, #15 }] */
    /* JADX WARN: Removed duplicated region for block: B:146:0x024e A[Catch: all -> 0x0179, TRY_ENTER, TryCatch #16 {all -> 0x0179, blocks: (B:62:0x0124, B:64:0x012e, B:71:0x0145, B:77:0x0167, B:95:0x0195, B:97:0x019b, B:99:0x01a0, B:101:0x01a9, B:103:0x01ad, B:106:0x01b6, B:107:0x01bd, B:108:0x01be, B:110:0x01c2, B:113:0x01cb, B:114:0x01d2, B:115:0x01d3, B:117:0x01d7, B:120:0x01e0, B:121:0x01e7, B:124:0x01eb, B:126:0x01f1, B:135:0x0213, B:137:0x021c, B:138:0x0223, B:139:0x022d, B:142:0x023b, B:146:0x024e, B:148:0x026a, B:152:0x027f, B:158:0x0290, B:186:0x039c, B:192:0x03ac, B:194:0x03b0, B:199:0x03c4, B:201:0x03c8, B:205:0x03df, B:212:0x040e, B:222:0x042a, B:254:0x0501, B:245:0x04a2, B:268:0x052d, B:269:0x0530, B:127:0x01fb, B:129:0x0201, B:100:0x01a5, B:80:0x0171, B:81:0x0178, B:73:0x0150, B:75:0x015a, B:66:0x0135, B:68:0x013c, B:270:0x0531, B:274:0x0559, B:278:0x0581, B:282:0x0598, B:286:0x05af), top: B:311:0x0122, inners: #17, #17, #15 }] */
    /* JADX WARN: Removed duplicated region for block: B:245:0x04a2 A[Catch: all -> 0x0179, PHI: r2
      0x04a2: PHI (r2v41 no.nordicsemi.android.dfu.DfuService) = 
      (r2v38 no.nordicsemi.android.dfu.DfuService)
      (r2v39 no.nordicsemi.android.dfu.DfuService)
      (r2v42 no.nordicsemi.android.dfu.DfuService)
     binds: [B:262:0x0521, B:244:0x04a0, B:260:0x050f] A[DONT_GENERATE, DONT_INLINE], TRY_ENTER, TRY_LEAVE, TryCatch #16 {all -> 0x0179, blocks: (B:62:0x0124, B:64:0x012e, B:71:0x0145, B:77:0x0167, B:95:0x0195, B:97:0x019b, B:99:0x01a0, B:101:0x01a9, B:103:0x01ad, B:106:0x01b6, B:107:0x01bd, B:108:0x01be, B:110:0x01c2, B:113:0x01cb, B:114:0x01d2, B:115:0x01d3, B:117:0x01d7, B:120:0x01e0, B:121:0x01e7, B:124:0x01eb, B:126:0x01f1, B:135:0x0213, B:137:0x021c, B:138:0x0223, B:139:0x022d, B:142:0x023b, B:146:0x024e, B:148:0x026a, B:152:0x027f, B:158:0x0290, B:186:0x039c, B:192:0x03ac, B:194:0x03b0, B:199:0x03c4, B:201:0x03c8, B:205:0x03df, B:212:0x040e, B:222:0x042a, B:254:0x0501, B:245:0x04a2, B:268:0x052d, B:269:0x0530, B:127:0x01fb, B:129:0x0201, B:100:0x01a5, B:80:0x0171, B:81:0x0178, B:73:0x0150, B:75:0x015a, B:66:0x0135, B:68:0x013c, B:270:0x0531, B:274:0x0559, B:278:0x0581, B:282:0x0598, B:286:0x05af), top: B:311:0x0122, inners: #17, #17, #15 }] */
    /* JADX WARN: Removed duplicated region for block: B:252:0x04ca A[Catch: all -> 0x0443, TRY_LEAVE, TryCatch #1 {all -> 0x0443, blocks: (B:207:0x03ea, B:250:0x04aa, B:252:0x04ca, B:258:0x050a, B:238:0x0449, B:240:0x0451, B:241:0x0470, B:243:0x0492, B:242:0x0474, B:261:0x0510), top: B:300:0x03ea }] */
    /* JADX WARN: Removed duplicated region for block: B:258:0x050a A[Catch: all -> 0x0443, TRY_ENTER, TryCatch #1 {all -> 0x0443, blocks: (B:207:0x03ea, B:250:0x04aa, B:252:0x04ca, B:258:0x050a, B:238:0x0449, B:240:0x0451, B:241:0x0470, B:243:0x0492, B:242:0x0474, B:261:0x0510), top: B:300:0x03ea }] */
    /* JADX WARN: Removed duplicated region for block: B:265:0x0527  */
    /* JADX WARN: Removed duplicated region for block: B:291:0x05c8  */
    /* JADX WARN: Removed duplicated region for block: B:322:? A[RETURN, SYNTHETIC] */
    /* JADX WARN: Removed duplicated region for block: B:329:? A[SYNTHETIC] */
    /* JADX WARN: Removed duplicated region for block: B:55:0x010c  */
    @Override // android.app.IntentService
    /*
        Code decompiled incorrectly, please refer to instructions dump.
        To view partially-correct add '--show-bad-code' argument
    */
    public void onHandleIntent(android.content.Intent r26) throws java.lang.Throwable {
        /*
            Method dump skipped, instruction units count: 1506
            To view this dump add '--comments-level debug' option
        */
        throw new UnsupportedOperationException("Method not decompiled: no.nordicsemi.android.dfu.DfuBaseService.onHandleIntent(android.content.Intent):void");
    }

    @Override // android.app.Service
    public void onTaskRemoved(Intent intent) {
        super.onTaskRemoved(intent);
        NotificationManager notificationManager = (NotificationManager) getSystemService("notification");
        if (notificationManager != null) {
            notificationManager.cancel(NOTIFICATION_ID);
        }
        stopSelf();
    }

    public void refreshDeviceCache(BluetoothGatt bluetoothGatt, boolean z2) {
        if (z2 || bluetoothGatt.getDevice().getBondState() == 10) {
            sendLogBroadcast(0, "gatt.refresh() (hidden)");
            try {
                logi("Refreshing result: " + ((Boolean) bluetoothGatt.getClass().getMethod("refresh", new Class[0]).invoke(bluetoothGatt, new Object[0])).booleanValue());
            } catch (Exception e2) {
                loge("An exception occurred while refreshing device", e2);
                sendLogBroadcast(15, "Refreshing failed");
            }
        }
    }

    public void sendLogBroadcast(int i2, String str) {
        String strT = a.t("[DFU] ", str);
        Intent intent = new Intent(BROADCAST_LOG);
        intent.putExtra(EXTRA_LOG_MESSAGE, strT);
        intent.putExtra(EXTRA_LOG_LEVEL, i2);
        intent.putExtra(EXTRA_DEVICE_ADDRESS, this.mDeviceAddress);
        d.o.a.a.a(this).c(intent);
    }

    public void terminateConnection(BluetoothGatt bluetoothGatt, int i2) {
        if (this.mConnectionState != 0) {
            disconnect(bluetoothGatt);
        }
        refreshDeviceCache(bluetoothGatt, false);
        close(bluetoothGatt);
        waitFor(600L);
        if (i2 != 0) {
            report(i2);
        }
    }

    public void updateErrorNotification(l lVar) {
    }

    public void updateForegroundNotification(l lVar) {
    }

    @Override // no.nordicsemi.android.dfu.DfuProgressInfo.ProgressListener
    public void updateProgressNotification() {
        String string;
        int i2;
        DfuProgressInfo dfuProgressInfo = this.mProgressInfo;
        int progress = dfuProgressInfo.getProgress();
        if (this.mLastProgress == progress) {
            return;
        }
        this.mLastProgress = progress;
        sendProgressBroadcast(dfuProgressInfo);
        if (this.mDisableNotification) {
            return;
        }
        long jElapsedRealtime = SystemClock.elapsedRealtime();
        if (jElapsedRealtime - this.mLastNotificationTime >= 250 || -6 == progress || -7 == progress) {
            this.mLastNotificationTime = jElapsedRealtime;
            String str = this.mDeviceAddress;
            String string2 = this.mDeviceName;
            if (string2 == null) {
                string2 = getString(R.string.dfu_unknown_name);
            }
            l lVar = new l(this, NOTIFICATION_CHANNEL_DFU);
            lVar.f2614q.icon = android.R.drawable.stat_sys_upload;
            lVar.e(8, true);
            lVar.f2611n = -7829368;
            switch (progress) {
                case PROGRESS_ABORTED /* -7 */:
                    lVar.e(2, false);
                    lVar.d(getString(R.string.dfu_status_aborted));
                    lVar.f2614q.icon = android.R.drawable.stat_sys_upload_done;
                    lVar.c(getString(R.string.dfu_status_aborted_msg));
                    lVar.e(16, true);
                    break;
                case PROGRESS_COMPLETED /* -6 */:
                    lVar.e(2, false);
                    lVar.d(getString(R.string.dfu_status_completed));
                    lVar.f2614q.icon = android.R.drawable.stat_sys_upload_done;
                    lVar.c(getString(R.string.dfu_status_completed_msg));
                    lVar.e(16, true);
                    lVar.f2611n = -16730086;
                    break;
                case -5:
                    lVar.e(2, true);
                    lVar.d(getString(R.string.dfu_status_disconnecting));
                    string = getString(R.string.dfu_status_disconnecting_msg, new Object[]{string2});
                    lVar.c(string);
                    lVar.f(100, 0, true);
                    break;
                case -4:
                    lVar.e(2, true);
                    lVar.d(getString(R.string.dfu_status_validating));
                    i2 = R.string.dfu_status_validating_msg;
                    string = getString(i2);
                    lVar.c(string);
                    lVar.f(100, 0, true);
                    break;
                case -3:
                    lVar.e(2, true);
                    lVar.d(getString(R.string.dfu_status_switching_to_dfu));
                    i2 = R.string.dfu_status_switching_to_dfu_msg;
                    string = getString(i2);
                    lVar.c(string);
                    lVar.f(100, 0, true);
                    break;
                case -2:
                    lVar.e(2, true);
                    lVar.d(getString(R.string.dfu_status_starting));
                    i2 = R.string.dfu_status_starting_msg;
                    string = getString(i2);
                    lVar.c(string);
                    lVar.f(100, 0, true);
                    break;
                case -1:
                    lVar.e(2, true);
                    lVar.d(getString(R.string.dfu_status_connecting));
                    string = getString(R.string.dfu_status_connecting_msg, new Object[]{string2});
                    lVar.c(string);
                    lVar.f(100, 0, true);
                    break;
                default:
                    CharSequence string3 = dfuProgressInfo.getTotalParts() == 1 ? getString(R.string.dfu_status_uploading) : getString(R.string.dfu_status_uploading_part, new Object[]{Integer.valueOf(dfuProgressInfo.getCurrentPart()), Integer.valueOf(dfuProgressInfo.getTotalParts())});
                    CharSequence string4 = getString(R.string.dfu_status_uploading_msg, new Object[]{string2});
                    lVar.e(2, true);
                    lVar.d(string3);
                    lVar.c(string4);
                    lVar.f(100, progress, false);
                    break;
            }
            Intent intent = new Intent(this, getNotificationTarget());
            intent.addFlags(268435456);
            intent.putExtra(EXTRA_DEVICE_ADDRESS, str);
            intent.putExtra(EXTRA_DEVICE_NAME, string2);
            intent.putExtra(EXTRA_PROGRESS, progress);
            lVar.f2604g = PendingIntent.getActivity(this, 0, intent, 201326592);
            updateProgressNotification(lVar, progress);
            NotificationManager notificationManager = (NotificationManager) getSystemService("notification");
            if (notificationManager != null) {
                notificationManager.notify(NOTIFICATION_ID, lVar.a());
            }
        }
    }

    public void waitFor(long j2) {
        synchronized (this.mLock) {
            try {
                sendLogBroadcast(0, "wait(" + j2 + ")");
                this.mLock.wait(j2);
            } catch (InterruptedException e2) {
                loge("Sleeping interrupted", e2);
            }
        }
    }

    public void waitUntilDisconnected() {
        try {
            synchronized (this.mLock) {
                while (this.mConnectionState != 0 && this.mError == 0) {
                    this.mLock.wait();
                }
            }
        } catch (InterruptedException e2) {
            loge("Sleeping interrupted", e2);
        }
    }

    public void updateProgressNotification(l lVar, int i2) {
        if (i2 == -7 || i2 == -6) {
            return;
        }
        Intent intent = new Intent(BROADCAST_ACTION);
        intent.putExtra(EXTRA_ACTION, 2);
        PendingIntent broadcast = PendingIntent.getBroadcast(this, 1, intent, 201326592);
        lVar.f2599b.add(new k(R.drawable.ic_action_notify_cancel, getString(R.string.dfu_action_abort), broadcast));
    }
}
