package no.nordicsemi.android.dfu;

import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Intent;
import android.os.SystemClock;
import com.cvte.vman.instance.InvokeCmd;
import g.a.a.a.a;
import io.netty.handler.codec.dns.DnsRecord;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.UUID;
import java.util.zip.CRC32;
import kotlin.reflect.w.internal.y0.n.c2.c;
import no.nordicsemi.android.dfu.BaseCustomDfuImpl;
import no.nordicsemi.android.dfu.BaseDfuImpl;
import no.nordicsemi.android.dfu.internal.ArchiveInputStream;
import no.nordicsemi.android.dfu.internal.exception.DeviceDisconnectedException;
import no.nordicsemi.android.dfu.internal.exception.DfuException;
import no.nordicsemi.android.dfu.internal.exception.RemoteDfuException;
import no.nordicsemi.android.dfu.internal.exception.RemoteDfuExtendedErrorException;
import no.nordicsemi.android.dfu.internal.exception.UnknownResponseException;
import no.nordicsemi.android.dfu.internal.exception.UploadAbortedException;

/* JADX INFO: loaded from: classes2.dex */
public class SecureDfuImpl extends BaseCustomDfuImpl {
    public static final UUID DEFAULT_DFU_CONTROL_POINT_UUID;
    public static final UUID DEFAULT_DFU_PACKET_UUID;
    public static final UUID DEFAULT_DFU_SERVICE_UUID;
    public static UUID DFU_CONTROL_POINT_UUID = null;
    public static UUID DFU_PACKET_UUID = null;
    public static UUID DFU_SERVICE_UUID = null;
    private static final int DFU_STATUS_SUCCESS = 1;
    private static final int MAX_ATTEMPTS = 3;
    private static final int OBJECT_COMMAND = 1;
    private static final int OBJECT_DATA = 2;
    private static final byte[] OP_CODE_CALCULATE_CHECKSUM;
    private static final int OP_CODE_CALCULATE_CHECKSUM_KEY = 3;
    private static final byte[] OP_CODE_CREATE_COMMAND;
    private static final byte[] OP_CODE_CREATE_DATA;
    private static final int OP_CODE_CREATE_KEY = 1;
    private static final byte[] OP_CODE_EXECUTE;
    private static final int OP_CODE_EXECUTE_KEY = 4;
    private static final byte[] OP_CODE_PACKET_RECEIPT_NOTIF_REQ;
    private static final int OP_CODE_PACKET_RECEIPT_NOTIF_REQ_KEY = 2;
    private static final int OP_CODE_RESPONSE_CODE_KEY = 96;
    private static final byte[] OP_CODE_SELECT_OBJECT;
    private static final int OP_CODE_SELECT_OBJECT_KEY = 6;
    private final SecureBluetoothCallback mBluetoothCallback;
    private BluetoothGattCharacteristic mControlPointCharacteristic;
    private BluetoothGattCharacteristic mPacketCharacteristic;
    private long prepareObjectDelay;

    public static class ObjectChecksum {
        public int CRC32;
        public int offset;

        private ObjectChecksum() {
        }
    }

    public static class ObjectInfo extends ObjectChecksum {
        public int maxSize;

        private ObjectInfo() {
            super();
        }
    }

    public class SecureBluetoothCallback extends BaseCustomDfuImpl.BaseCustomBluetoothCallback {
        public SecureBluetoothCallback() {
            super();
        }

        @Override // android.bluetooth.BluetoothGattCallback
        public void onCharacteristicChanged(BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic bluetoothGattCharacteristic) {
            if (bluetoothGattCharacteristic.getValue() == null || bluetoothGattCharacteristic.getValue().length < 3) {
                SecureDfuImpl secureDfuImpl = SecureDfuImpl.this;
                StringBuilder sbF = a.F("Empty response: ");
                sbF.append(parse(bluetoothGattCharacteristic));
                secureDfuImpl.loge(sbF.toString());
                SecureDfuImpl secureDfuImpl2 = SecureDfuImpl.this;
                secureDfuImpl2.mError = 4104;
                secureDfuImpl2.notifyLock();
                return;
            }
            if (bluetoothGattCharacteristic.getIntValue(17, 0).intValue() != 96) {
                SecureDfuImpl secureDfuImpl3 = SecureDfuImpl.this;
                StringBuilder sbF2 = a.F("Invalid response: ");
                sbF2.append(parse(bluetoothGattCharacteristic));
                secureDfuImpl3.loge(sbF2.toString());
                SecureDfuImpl.this.mError = 4104;
            } else if (bluetoothGattCharacteristic.getIntValue(17, 1).intValue() == 3) {
                int iIntValue = bluetoothGattCharacteristic.getIntValue(20, 3).intValue();
                if (((int) (((ArchiveInputStream) SecureDfuImpl.this.mFirmwareStream).getCrc32() & 4294967295L)) == bluetoothGattCharacteristic.getIntValue(20, 7).intValue()) {
                    SecureDfuImpl.this.mProgressInfo.setBytesReceived(iIntValue);
                } else {
                    SecureDfuImpl secureDfuImpl4 = SecureDfuImpl.this;
                    if (secureDfuImpl4.mFirmwareUploadInProgress) {
                        secureDfuImpl4.mFirmwareUploadInProgress = false;
                        secureDfuImpl4.notifyLock();
                        return;
                    }
                }
                handlePacketReceiptNotification(bluetoothGatt, bluetoothGattCharacteristic);
            } else if (!SecureDfuImpl.this.mRemoteErrorOccurred) {
                if (bluetoothGattCharacteristic.getIntValue(17, 2).intValue() != 1) {
                    SecureDfuImpl.this.mRemoteErrorOccurred = true;
                }
                handleNotification(bluetoothGatt, bluetoothGattCharacteristic);
            }
            SecureDfuImpl.this.notifyLock();
        }
    }

    static {
        UUID uuid = new UUID(279658205548544L, -9223371485494954757L);
        DEFAULT_DFU_SERVICE_UUID = uuid;
        UUID uuid2 = new UUID(-8157989241631715488L, -6937650605005804976L);
        DEFAULT_DFU_CONTROL_POINT_UUID = uuid2;
        UUID uuid3 = new UUID(-8157989237336748192L, -6937650605005804976L);
        DEFAULT_DFU_PACKET_UUID = uuid3;
        DFU_SERVICE_UUID = uuid;
        DFU_CONTROL_POINT_UUID = uuid2;
        DFU_PACKET_UUID = uuid3;
        OP_CODE_CREATE_COMMAND = new byte[]{1, 1, 0, 0, 0, 0};
        OP_CODE_CREATE_DATA = new byte[]{1, 2, 0, 0, 0, 0};
        OP_CODE_PACKET_RECEIPT_NOTIF_REQ = new byte[]{2, 0, 0};
        OP_CODE_CALCULATE_CHECKSUM = new byte[]{3};
        OP_CODE_EXECUTE = new byte[]{4};
        OP_CODE_SELECT_OBJECT = new byte[]{6, 0};
    }

    public SecureDfuImpl(Intent intent, DfuBaseService dfuBaseService) {
        super(intent, dfuBaseService);
        this.mBluetoothCallback = new SecureBluetoothCallback();
    }

    private int getStatusCode(byte[] bArr, int i2) throws UnknownResponseException {
        if (bArr != null && bArr.length >= 3 && bArr[0] == 96 && bArr[1] == i2 && (bArr[2] == 1 || bArr[2] == 2 || bArr[2] == 3 || bArr[2] == 4 || bArr[2] == 5 || bArr[2] == 7 || bArr[2] == 8 || bArr[2] == 10 || bArr[2] == 11)) {
            return bArr[2];
        }
        throw new UnknownResponseException("Invalid response received", bArr, 96, i2);
    }

    private ObjectChecksum readChecksum() throws UploadAbortedException, RemoteDfuException, UnknownResponseException, DfuException, DeviceDisconnectedException {
        if (!this.mConnected) {
            throw new DeviceDisconnectedException("Unable to read Checksum: device disconnected");
        }
        writeOpCode(this.mControlPointCharacteristic, OP_CODE_CALCULATE_CHECKSUM);
        byte[] notificationResponse = readNotificationResponse();
        int statusCode = getStatusCode(notificationResponse, 3);
        if (statusCode == 11) {
            throw new RemoteDfuExtendedErrorException("Receiving Checksum failed", notificationResponse[3]);
        }
        if (statusCode != 1) {
            throw new RemoteDfuException("Receiving Checksum failed", statusCode);
        }
        ObjectChecksum objectChecksum = new ObjectChecksum();
        objectChecksum.offset = unsignedBytesToInt(notificationResponse, 3);
        objectChecksum.CRC32 = unsignedBytesToInt(notificationResponse, 7);
        return objectChecksum;
    }

    private ObjectInfo selectObject(int i2) throws UploadAbortedException, RemoteDfuException, UnknownResponseException, DfuException, DeviceDisconnectedException {
        if (!this.mConnected) {
            throw new DeviceDisconnectedException("Unable to read object info: device disconnected");
        }
        byte[] bArr = OP_CODE_SELECT_OBJECT;
        bArr[1] = (byte) i2;
        writeOpCode(this.mControlPointCharacteristic, bArr);
        byte[] notificationResponse = readNotificationResponse();
        int statusCode = getStatusCode(notificationResponse, 6);
        if (statusCode == 11) {
            throw new RemoteDfuExtendedErrorException("Selecting object failed", notificationResponse[3]);
        }
        if (statusCode != 1) {
            throw new RemoteDfuException("Selecting object failed", statusCode);
        }
        ObjectInfo objectInfo = new ObjectInfo();
        objectInfo.maxSize = unsignedBytesToInt(notificationResponse, 3);
        objectInfo.offset = unsignedBytesToInt(notificationResponse, 7);
        objectInfo.CRC32 = unsignedBytesToInt(notificationResponse, 11);
        return objectInfo;
    }

    private void sendFirmware(BluetoothGatt bluetoothGatt) throws UploadAbortedException, RemoteDfuException, UnknownResponseException, DfuException, DeviceDisconnectedException {
        int i2;
        int i3;
        String str;
        boolean z2;
        String str2;
        boolean z3;
        int i4 = this.mPacketsBeforeNotification;
        if (i4 > 0) {
            setPacketReceiptNotifications(i4);
            this.mService.sendLogBroadcast(10, "Packet Receipt Notif Req (Op Code = 2) sent (Value = " + i4 + ")");
        }
        logi("Setting object to Data (Op Code = 6, Type = 2)");
        ObjectInfo objectInfoSelectObject = selectObject(2);
        Locale locale = Locale.US;
        logi(String.format(locale, "Data object info received (Max size = %d, Offset = %d, CRC = %08X)", Integer.valueOf(objectInfoSelectObject.maxSize), Integer.valueOf(objectInfoSelectObject.offset), Integer.valueOf(objectInfoSelectObject.CRC32)));
        this.mService.sendLogBroadcast(10, String.format(locale, "Data object info received (Max size = %d, Offset = %d, CRC = %08X)", Integer.valueOf(objectInfoSelectObject.maxSize), Integer.valueOf(objectInfoSelectObject.offset), Integer.valueOf(objectInfoSelectObject.CRC32)));
        this.mProgressInfo.setMaxObjectSizeInBytes(objectInfoSelectObject.maxSize);
        int i5 = this.mImageSizeInBytes;
        int i6 = objectInfoSelectObject.maxSize;
        int i7 = ((i5 + i6) - 1) / i6;
        int i8 = objectInfoSelectObject.offset;
        if (i8 > 0) {
            try {
                int i9 = i8 / i6;
                int i10 = i6 * i9;
                int i11 = i8 - i10;
                if (i11 == 0) {
                    i10 -= i6;
                } else {
                    i6 = i11;
                }
                if (i10 > 0) {
                    i2 = i9;
                    this.mFirmwareStream.read(new byte[i10]);
                    this.mFirmwareStream.mark(objectInfoSelectObject.maxSize);
                } else {
                    i2 = i9;
                }
                this.mFirmwareStream.read(new byte[i6]);
                i3 = i7;
                str = ")";
                if (((int) (((ArchiveInputStream) this.mFirmwareStream).getCrc32() & 4294967295L)) == objectInfoSelectObject.CRC32) {
                    logi(objectInfoSelectObject.offset + " bytes of data sent before, CRC match");
                    this.mService.sendLogBroadcast(10, objectInfoSelectObject.offset + " bytes of data sent before, CRC match");
                    this.mProgressInfo.setBytesSent(objectInfoSelectObject.offset);
                    this.mProgressInfo.setBytesReceived(objectInfoSelectObject.offset);
                    if (i6 != objectInfoSelectObject.maxSize || objectInfoSelectObject.offset >= this.mImageSizeInBytes) {
                        z2 = true;
                    } else {
                        logi("Executing data object (Op Code = 4)");
                        try {
                            writeExecute();
                            this.mService.sendLogBroadcast(10, "Data object executed");
                        } catch (RemoteDfuException e2) {
                            if (e2.getErrorNumber() != 8) {
                                throw e2;
                            }
                            this.mService.sendLogBroadcast(10, "Data object already executed");
                            this.mRemoteErrorOccurred = false;
                        }
                    }
                } else {
                    logi(objectInfoSelectObject.offset + " bytes sent before, CRC does not match");
                    this.mService.sendLogBroadcast(15, objectInfoSelectObject.offset + " bytes sent before, CRC does not match");
                    this.mProgressInfo.setBytesSent(i10);
                    this.mProgressInfo.setBytesReceived(i10);
                    objectInfoSelectObject.offset = objectInfoSelectObject.offset - i6;
                    objectInfoSelectObject.CRC32 = 0;
                    this.mFirmwareStream.reset();
                    logi("Resuming from byte " + objectInfoSelectObject.offset + "...");
                    this.mService.sendLogBroadcast(10, "Resuming from byte " + objectInfoSelectObject.offset + "...");
                }
                z2 = false;
            } catch (IOException e3) {
                loge("Error while reading firmware stream", e3);
                this.mService.terminateConnection(bluetoothGatt, 4100);
                return;
            }
        } else {
            i3 = i7;
            str = ")";
            this.mProgressInfo.setBytesSent(0);
            z2 = false;
            i2 = 0;
        }
        long jElapsedRealtime = SystemClock.elapsedRealtime();
        if (objectInfoSelectObject.offset < this.mImageSizeInBytes) {
            int i12 = 1;
            while (this.mProgressInfo.getAvailableObjectSizeIsBytes() > 0) {
                if (z2) {
                    str2 = str;
                    this.mService.sendLogBroadcast(10, "Resuming uploading firmware...");
                    z3 = false;
                } else {
                    int availableObjectSizeIsBytes = this.mProgressInfo.getAvailableObjectSizeIsBytes();
                    StringBuilder sbG = a.G("Creating Data object (Op Code = 1, Type = 2, Size = ", availableObjectSizeIsBytes, ") (");
                    int i13 = i2 + 1;
                    sbG.append(i13);
                    boolean z4 = z2;
                    sbG.append("/");
                    sbG.append(i3);
                    sbG.append(str);
                    logi(sbG.toString());
                    writeCreateRequest(2, availableObjectSizeIsBytes);
                    str2 = str;
                    this.mService.sendLogBroadcast(10, a.p("Data object (", i13, "/", i3, ") created"));
                    long j2 = this.prepareObjectDelay;
                    if (j2 > 0 || i3 == 0) {
                        DfuBaseService dfuBaseService = this.mService;
                        if (j2 <= 0) {
                            j2 = 400;
                        }
                        dfuBaseService.waitFor(j2);
                    }
                    this.mService.sendLogBroadcast(10, "Uploading firmware...");
                    z3 = z4;
                }
                try {
                    logi("Uploading firmware...");
                    uploadFirmwareImage(this.mPacketCharacteristic);
                    logi("Sending Calculate Checksum command (Op Code = 3)");
                    ObjectChecksum checksum = readChecksum();
                    Locale locale2 = Locale.US;
                    logi(String.format(locale2, "Checksum received (Offset = %d, CRC = %08X)", Integer.valueOf(checksum.offset), Integer.valueOf(checksum.CRC32)));
                    boolean z5 = z3;
                    this.mService.sendLogBroadcast(10, String.format(locale2, "Checksum received (Offset = %d, CRC = %08X)", Integer.valueOf(checksum.offset), Integer.valueOf(checksum.CRC32)));
                    int bytesSent = this.mProgressInfo.getBytesSent() - checksum.offset;
                    if (bytesSent > 0) {
                        logw(bytesSent + " bytes were lost!");
                        this.mService.sendLogBroadcast(15, bytesSent + " bytes were lost");
                        try {
                            this.mFirmwareStream.reset();
                            this.mFirmwareStream.read(new byte[objectInfoSelectObject.maxSize - bytesSent]);
                            this.mProgressInfo.setBytesSent(checksum.offset);
                            int i14 = this.mPacketsBeforeNotification;
                            if (i14 == 0 || i14 > 1) {
                                this.mPacketsBeforeNotification = 1;
                                setPacketReceiptNotifications(1);
                                this.mService.sendLogBroadcast(10, "Packet Receipt Notif Req (Op Code = 2) sent (Value = 1)");
                            }
                        } catch (IOException e4) {
                            loge("Error while reading firmware stream", e4);
                            this.mService.terminateConnection(bluetoothGatt, 4100);
                            return;
                        } catch (Throwable th) {
                            StringBuilder sbF = a.F("Progress lost. Bytes sent: ");
                            sbF.append(this.mProgressInfo.getBytesSent());
                            loge(sbF.toString(), th);
                            this.mService.terminateConnection(bluetoothGatt, 4111);
                            return;
                        }
                    }
                    int crc32 = (int) (((ArchiveInputStream) this.mFirmwareStream).getCrc32() & 4294967295L);
                    if (crc32 != checksum.CRC32) {
                        String str3 = String.format(locale2, "CRC does not match! Expected %08X but found %08X.", Integer.valueOf(crc32), Integer.valueOf(checksum.CRC32));
                        if (i12 >= 3) {
                            loge(str3);
                            this.mService.sendLogBroadcast(20, str3);
                            this.mService.terminateConnection(bluetoothGatt, 4109);
                            return;
                        }
                        i12++;
                        StringBuilder sbF2 = a.F(str3);
                        sbF2.append(String.format(locale2, " Retrying...(%d/%d)", Integer.valueOf(i12), 3));
                        String string = sbF2.toString();
                        logi(string);
                        this.mService.sendLogBroadcast(15, string);
                        try {
                            this.mFirmwareStream.reset();
                            this.mProgressInfo.setBytesSent(((ArchiveInputStream) this.mFirmwareStream).getBytesRead());
                        } catch (IOException e5) {
                            loge("Error while resetting the firmware stream", e5);
                            this.mService.terminateConnection(bluetoothGatt, 4100);
                            return;
                        }
                    } else if (bytesSent > 0) {
                        z2 = true;
                        str = str2;
                    } else {
                        logi("Executing data object (Op Code = 4)");
                        writeExecute(this.mProgressInfo.isComplete());
                        this.mService.sendLogBroadcast(10, "Data object executed");
                        i2++;
                        this.mFirmwareStream.mark(0);
                        i12 = 1;
                    }
                    str = str2;
                    z2 = z5;
                } catch (DeviceDisconnectedException e6) {
                    loge("Disconnected while sending data");
                    throw e6;
                }
            }
        } else {
            logi("Executing data object (Op Code = 4)");
            writeExecute(true);
            this.mService.sendLogBroadcast(10, "Data object executed");
        }
        long jElapsedRealtime2 = SystemClock.elapsedRealtime();
        StringBuilder sbF3 = a.F("Transfer of ");
        sbF3.append(this.mProgressInfo.getBytesSent() - objectInfoSelectObject.offset);
        sbF3.append(" bytes has taken ");
        long j3 = jElapsedRealtime2 - jElapsedRealtime;
        sbF3.append(j3);
        sbF3.append(" ms");
        logi(sbF3.toString());
        this.mService.sendLogBroadcast(10, a.r("Upload completed in ", j3, " ms"));
    }

    private void sendInitPacket(BluetoothGatt bluetoothGatt, boolean z2) throws UploadAbortedException, RemoteDfuException, UnknownResponseException, DfuException, DeviceDisconnectedException {
        boolean z3;
        boolean z4;
        int i2;
        CRC32 crc32 = new CRC32();
        logi("Setting object to Command (Op Code = 6, Type = 1)");
        ObjectInfo objectInfoSelectObject = selectObject(1);
        Locale locale = Locale.US;
        int i3 = 3;
        logi(String.format(locale, "Command object info received (Max size = %d, Offset = %d, CRC = %08X)", Integer.valueOf(objectInfoSelectObject.maxSize), Integer.valueOf(objectInfoSelectObject.offset), Integer.valueOf(objectInfoSelectObject.CRC32)));
        this.mService.sendLogBroadcast(10, String.format(locale, "Command object info received (Max size = %d, Offset = %d, CRC = %08X)", Integer.valueOf(objectInfoSelectObject.maxSize), Integer.valueOf(objectInfoSelectObject.offset), Integer.valueOf(objectInfoSelectObject.CRC32)));
        int i4 = this.mInitPacketSizeInBytes;
        if (!z2 || (i2 = objectInfoSelectObject.offset) <= 0 || i2 > i4) {
            z3 = false;
            z4 = false;
        } else {
            try {
                byte[] bArr = new byte[i2];
                this.mInitPacketStream.read(bArr);
                crc32.update(bArr);
                if (objectInfoSelectObject.CRC32 == ((int) (4294967295L & crc32.getValue()))) {
                    logi("Init packet CRC is the same");
                    if (objectInfoSelectObject.offset == this.mInitPacketSizeInBytes) {
                        logi("-> Whole Init packet was sent before");
                        try {
                            this.mService.sendLogBroadcast(10, "Received CRC match Init packet");
                            z3 = true;
                            z4 = false;
                        } catch (IOException e2) {
                            e = e2;
                            z3 = true;
                            z4 = false;
                            StringBuilder sbF = a.F("Error while reading ");
                            sbF.append(objectInfoSelectObject.offset);
                            sbF.append(" bytes from the init packet stream");
                            loge(sbF.toString(), e);
                            try {
                                this.mInitPacketStream.reset();
                                crc32.reset();
                                objectInfoSelectObject.offset = 0;
                            } catch (IOException e3) {
                                loge("Error while resetting the init packet stream", e3);
                                this.mService.terminateConnection(bluetoothGatt, 4100);
                                return;
                            }
                        }
                    } else {
                        logi("-> " + objectInfoSelectObject.offset + " bytes of Init packet were sent before");
                        try {
                            this.mService.sendLogBroadcast(10, "Resuming sending Init packet...");
                            z4 = true;
                            z3 = false;
                        } catch (IOException e4) {
                            e = e4;
                            z4 = true;
                            z3 = false;
                            StringBuilder sbF2 = a.F("Error while reading ");
                            sbF2.append(objectInfoSelectObject.offset);
                            sbF2.append(" bytes from the init packet stream");
                            loge(sbF2.toString(), e);
                            this.mInitPacketStream.reset();
                            crc32.reset();
                            objectInfoSelectObject.offset = 0;
                        }
                    }
                } else {
                    this.mInitPacketStream.reset();
                    crc32.reset();
                    objectInfoSelectObject.offset = 0;
                    z3 = false;
                    z4 = false;
                }
            } catch (IOException e5) {
                e = e5;
                z3 = false;
                z4 = false;
            }
        }
        if (!z3) {
            setPacketReceiptNotifications(0);
            this.mService.sendLogBroadcast(10, "Packet Receipt Notif disabled (Op Code = 2, Value = 0)");
            int i5 = 1;
            while (i5 <= i3) {
                if (!z4) {
                    StringBuilder sbF3 = a.F("Creating Init packet object (Op Code = 1, Type = 1, Size = ");
                    sbF3.append(this.mInitPacketSizeInBytes);
                    sbF3.append(")");
                    logi(sbF3.toString());
                    writeCreateRequest(1, this.mInitPacketSizeInBytes);
                    this.mService.sendLogBroadcast(10, "Command object created");
                }
                try {
                    logi("Sending " + (this.mInitPacketSizeInBytes - objectInfoSelectObject.offset) + " bytes of init packet...");
                    writeInitData(this.mPacketCharacteristic, crc32);
                    int value = (int) (crc32.getValue() & 4294967295L);
                    DfuBaseService dfuBaseService = this.mService;
                    Locale locale2 = Locale.US;
                    dfuBaseService.sendLogBroadcast(10, String.format(locale2, "Command object sent (CRC = %08X)", Integer.valueOf(value)));
                    logi("Sending Calculate Checksum command (Op Code = 3)");
                    ObjectChecksum checksum = readChecksum();
                    this.mService.sendLogBroadcast(10, String.format(locale2, "Checksum received (Offset = %d, CRC = %08X)", Integer.valueOf(checksum.offset), Integer.valueOf(checksum.CRC32)));
                    logi(String.format(locale2, "Checksum received (Offset = %d, CRC = %08X)", Integer.valueOf(checksum.offset), Integer.valueOf(checksum.CRC32)));
                    if (value == checksum.CRC32) {
                        break;
                    }
                    i3 = 3;
                    if (i5 >= 3) {
                        loge("CRC does not match!");
                        this.mService.sendLogBroadcast(20, "CRC does not match!");
                        this.mService.terminateConnection(bluetoothGatt, 4109);
                        return;
                    }
                    i5++;
                    logi(a.p("CRC does not match! Retrying...(", i5, "/", 3, ")"));
                    this.mService.sendLogBroadcast(15, a.p("CRC does not match! Retrying...(", i5, "/", 3, ")"));
                    try {
                        objectInfoSelectObject.offset = 0;
                        objectInfoSelectObject.CRC32 = 0;
                        this.mInitPacketStream.reset();
                        crc32.reset();
                        z4 = false;
                    } catch (IOException e6) {
                        loge("Error while resetting the init packet stream", e6);
                        this.mService.terminateConnection(bluetoothGatt, 4100);
                        return;
                    }
                } catch (DeviceDisconnectedException e7) {
                    loge("Disconnected while sending init packet");
                    throw e7;
                }
            }
        }
        logi("Executing init packet (Op Code = 4)");
        writeExecute();
        this.mService.sendLogBroadcast(10, "Command object executed");
    }

    private void setNumberOfPackets(byte[] bArr, int i2) {
        bArr[1] = (byte) (i2 & DnsRecord.CLASS_ANY);
        bArr[2] = (byte) ((i2 >> 8) & DnsRecord.CLASS_ANY);
    }

    private void setObjectSize(byte[] bArr, int i2) {
        bArr[2] = (byte) (i2 & DnsRecord.CLASS_ANY);
        bArr[3] = (byte) ((i2 >> 8) & DnsRecord.CLASS_ANY);
        bArr[4] = (byte) ((i2 >> 16) & DnsRecord.CLASS_ANY);
        bArr[5] = (byte) ((i2 >> 24) & DnsRecord.CLASS_ANY);
    }

    private void setPacketReceiptNotifications(int i2) throws UploadAbortedException, RemoteDfuException, UnknownResponseException, DfuException, DeviceDisconnectedException {
        if (!this.mConnected) {
            throw new DeviceDisconnectedException("Unable to read Checksum: device disconnected");
        }
        logi("Sending the number of packets before notifications (Op Code = 2, Value = " + i2 + ")");
        byte[] bArr = OP_CODE_PACKET_RECEIPT_NOTIF_REQ;
        setNumberOfPackets(bArr, i2);
        writeOpCode(this.mControlPointCharacteristic, bArr);
        byte[] notificationResponse = readNotificationResponse();
        int statusCode = getStatusCode(notificationResponse, 2);
        if (statusCode == 11) {
            throw new RemoteDfuExtendedErrorException("Sending the number of packets failed", notificationResponse[3]);
        }
        if (statusCode != 1) {
            throw new RemoteDfuException("Sending the number of packets failed", statusCode);
        }
    }

    private int unsignedBytesToInt(byte[] bArr, int i2) {
        return (bArr[i2] & 255) + ((bArr[i2 + 1] & 255) << 8) + ((bArr[i2 + 2] & 255) << 16) + ((bArr[i2 + 3] & 255) << 24);
    }

    private void writeCreateRequest(int i2, int i3) throws UploadAbortedException, RemoteDfuException, UnknownResponseException, DfuException, DeviceDisconnectedException {
        if (!this.mConnected) {
            throw new DeviceDisconnectedException("Unable to create object: device disconnected");
        }
        byte[] bArr = i2 == 1 ? OP_CODE_CREATE_COMMAND : OP_CODE_CREATE_DATA;
        setObjectSize(bArr, i3);
        writeOpCode(this.mControlPointCharacteristic, bArr);
        byte[] notificationResponse = readNotificationResponse();
        int statusCode = getStatusCode(notificationResponse, 1);
        if (statusCode == 11) {
            throw new RemoteDfuExtendedErrorException("Creating Command object failed", notificationResponse[3]);
        }
        if (statusCode != 1) {
            throw new RemoteDfuException("Creating Command object failed", statusCode);
        }
    }

    private void writeExecute() throws UploadAbortedException, RemoteDfuException, UnknownResponseException, DfuException, DeviceDisconnectedException {
        if (!this.mConnected) {
            throw new DeviceDisconnectedException("Unable to read Checksum: device disconnected");
        }
        writeOpCode(this.mControlPointCharacteristic, OP_CODE_EXECUTE);
        byte[] notificationResponse = readNotificationResponse();
        int statusCode = getStatusCode(notificationResponse, 4);
        if (statusCode == 11) {
            throw new RemoteDfuExtendedErrorException("Executing object failed", notificationResponse[3]);
        }
        if (statusCode != 1) {
            throw new RemoteDfuException("Executing object failed", statusCode);
        }
    }

    private void writeExecute(boolean z2) throws UploadAbortedException, RemoteDfuException, UnknownResponseException, DfuException, DeviceDisconnectedException {
        try {
            writeExecute();
        } catch (RemoteDfuException e2) {
            if (!z2 || e2.getErrorNumber() != 5) {
                throw e2;
            }
            logw(e2.getMessage() + ": " + c.o0(InvokeCmd.CMD_XBUG_VMAN_FUNTION_CHECK_TIMEOUT_BASE_GET));
            if (this.mFileType == 1) {
                logw("Are you sure your new SoftDevice is API compatible with the updated one? If not, update the bootloader as well");
            }
            this.mService.sendLogBroadcast(15, String.format(Locale.US, "Remote DFU error: %s. SD busy? Retrying...", c.o0(InvokeCmd.CMD_XBUG_VMAN_FUNTION_CHECK_TIMEOUT_BASE_GET)));
            logi("SD busy? Retrying...");
            logi("Executing data object (Op Code = 4)");
            writeExecute();
        }
    }

    private void writeOpCode(BluetoothGattCharacteristic bluetoothGattCharacteristic, byte[] bArr) throws UploadAbortedException, DfuException, DeviceDisconnectedException {
        writeOpCode(bluetoothGattCharacteristic, bArr, false);
    }

    @Override // no.nordicsemi.android.dfu.BaseCustomDfuImpl
    public UUID getControlPointCharacteristicUUID() {
        return DFU_CONTROL_POINT_UUID;
    }

    @Override // no.nordicsemi.android.dfu.BaseCustomDfuImpl
    public UUID getDfuServiceUUID() {
        return DFU_SERVICE_UUID;
    }

    @Override // no.nordicsemi.android.dfu.DfuCallback
    public BaseDfuImpl.BaseBluetoothGattCallback getGattCallback() {
        return this.mBluetoothCallback;
    }

    @Override // no.nordicsemi.android.dfu.BaseCustomDfuImpl
    public UUID getPacketCharacteristicUUID() {
        return DFU_PACKET_UUID;
    }

    @Override // no.nordicsemi.android.dfu.BaseDfuImpl, no.nordicsemi.android.dfu.DfuService
    public boolean initialize(Intent intent, BluetoothGatt bluetoothGatt, int i2, InputStream inputStream, InputStream inputStream2) {
        if (inputStream2 != null) {
            return super.initialize(intent, bluetoothGatt, i2, inputStream, inputStream2);
        }
        this.mService.sendLogBroadcast(20, "The Init packet is required by this version DFU Bootloader");
        this.mService.terminateConnection(bluetoothGatt, 4107);
        return false;
    }

    @Override // no.nordicsemi.android.dfu.DfuService
    public boolean isClientCompatible(Intent intent, BluetoothGatt bluetoothGatt) {
        BluetoothGattCharacteristic characteristic;
        BluetoothGattService service = bluetoothGatt.getService(DFU_SERVICE_UUID);
        if (service == null || (characteristic = service.getCharacteristic(DFU_CONTROL_POINT_UUID)) == null || characteristic.getDescriptor(BaseDfuImpl.CLIENT_CHARACTERISTIC_CONFIG) == null) {
            return false;
        }
        this.mControlPointCharacteristic = characteristic;
        BluetoothGattCharacteristic characteristic2 = service.getCharacteristic(DFU_PACKET_UUID);
        this.mPacketCharacteristic = characteristic2;
        return characteristic2 != null;
    }

    @Override // no.nordicsemi.android.dfu.DfuService
    public void performDfu(Intent intent) throws UploadAbortedException, DfuException, DeviceDisconnectedException {
        DfuBaseService dfuBaseService;
        int i2;
        logw("Secure DFU bootloader found");
        this.mProgressInfo.setProgress(-2);
        BluetoothGatt bluetoothGatt = this.mGatt;
        if (intent.hasExtra(DfuBaseService.EXTRA_MTU)) {
            int intExtra = intent.getIntExtra(DfuBaseService.EXTRA_MTU, InvokeCmd.CMD_XBUG_VMAN_FUNTION_CHECK_TIMEOUT_BASE_GET);
            logi("Requesting MTU = " + intExtra);
            requestMtu(intExtra);
        }
        this.prepareObjectDelay = intent.getLongExtra(DfuBaseService.EXTRA_DATA_OBJECT_DELAY, 0L);
        try {
            try {
                enableCCCD(this.mControlPointCharacteristic, 1);
                this.mService.sendLogBroadcast(10, "Notifications enabled");
                boolean z2 = (intent.hasExtra(DfuBaseService.EXTRA_DISABLE_RESUME) && intent.getBooleanExtra(DfuBaseService.EXTRA_DISABLE_RESUME, false)) ? false : true;
                if (!z2) {
                    logi("Resume feature disabled. Performing fresh DFU");
                }
                try {
                    sendInitPacket(bluetoothGatt, z2);
                } catch (RemoteDfuException e2) {
                    if (this.mProgressInfo.isLastPart()) {
                        throw e2;
                    }
                    this.mRemoteErrorOccurred = false;
                    logw("Sending SD+BL failed. Trying to send App only");
                    this.mService.sendLogBroadcast(15, "Invalid system components. Trying to send application");
                    this.mFileType = 4;
                    ArchiveInputStream archiveInputStream = (ArchiveInputStream) this.mFirmwareStream;
                    archiveInputStream.setContentType(4);
                    byte[] applicationInit = archiveInputStream.getApplicationInit();
                    this.mInitPacketStream = new ByteArrayInputStream(applicationInit);
                    this.mInitPacketSizeInBytes = applicationInit.length;
                    int iApplicationImageSize = archiveInputStream.applicationImageSize();
                    this.mImageSizeInBytes = iApplicationImageSize;
                    this.mProgressInfo.init(iApplicationImageSize, 2, 2);
                    sendInitPacket(bluetoothGatt, false);
                }
                sendFirmware(bluetoothGatt);
                this.mProgressInfo.setProgress(-5);
                this.mService.waitUntilDisconnected();
                this.mService.sendLogBroadcast(5, "Disconnected by the remote device");
                finalize(intent, false);
            } catch (RemoteDfuException e3) {
                int errorNumber = e3.getErrorNumber() | 512;
                loge(e3.getMessage() + ": " + c.o0(errorNumber));
                this.mService.sendLogBroadcast(20, String.format(Locale.US, "Remote DFU error: %s", c.o0(errorNumber)));
                if (e3 instanceof RemoteDfuExtendedErrorException) {
                    RemoteDfuExtendedErrorException remoteDfuExtendedErrorException = (RemoteDfuExtendedErrorException) e3;
                    errorNumber = remoteDfuExtendedErrorException.getExtendedErrorNumber() | 1024;
                    StringBuilder sbF = a.F("Extended Error details: ");
                    sbF.append(c.s0(errorNumber));
                    loge(sbF.toString());
                    DfuBaseService dfuBaseService2 = this.mService;
                    StringBuilder sbF2 = a.F("Details: ");
                    sbF2.append(c.s0(errorNumber));
                    sbF2.append(" (Code = ");
                    sbF2.append(remoteDfuExtendedErrorException.getExtendedErrorNumber());
                    sbF2.append(")");
                    dfuBaseService2.sendLogBroadcast(20, sbF2.toString());
                }
                dfuBaseService = this.mService;
                i2 = errorNumber | 8192;
                dfuBaseService.terminateConnection(bluetoothGatt, i2);
            }
        } catch (UnknownResponseException e4) {
            loge(e4.getMessage());
            this.mService.sendLogBroadcast(20, e4.getMessage());
            dfuBaseService = this.mService;
            i2 = 4104;
            dfuBaseService.terminateConnection(bluetoothGatt, i2);
        } catch (UploadAbortedException e5) {
            throw e5;
        }
    }
}
