package com.cvte.dss.ups.camera.zyzh;

import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import c.n.a;
import com.cvte.dss.ups.camera.zyzh.listener.UpgradeProgressListener;
import com.cvte.dss.ups.camera.zyzh.support.ICameraUpgrade;
import com.cvte.dss.ups.camera.zyzh.support.ShellUpgrade;
import com.cvte.dss.ups.camera.zyzh.support.VmanUpgrade;
import com.cvte.vman.instance.InvokeCmd;
import d.d.c.a.b;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import jxl.SheetSettings;

/* JADX INFO: loaded from: classes.dex */
public class CameraDevice {
    private static final byte CAMERA_MAIN_CODE = 32;
    private static final byte CAMERA_SUB_REQUEST_CODE_ENTER_UPGRADE = 8;
    private static final byte CAMERA_SUB_REQUEST_CODE_GET_MODULE = 10;
    private static final byte CAMERA_SUB_REQUEST_CODE_GET_OTA = 14;
    private static final byte CAMERA_SUB_REQUEST_CODE_GET_VERSION = 6;
    private static final byte CAMERA_SUB_RESPONSE_CODE_ENTER_UPGRADE = 9;
    private static final byte CAMERA_SUB_RESPONSE_CODE_GET_MODULE = 11;
    private static final byte CAMERA_SUB_RESPONSE_CODE_GET_OTA = 15;
    private static final byte CAMERA_SUB_RESPONSE_CODE_GET_VERSION = 7;
    private static final String CHARSET = "ISO8859-1";
    private static final int CHECK_STATUS_TIME_MS = 500;
    private static final int COMMAND_DATA_BEGIN_INDEX = 7;
    private static final int COMMAND_DATA_LENGTH_INDEX = 5;
    private static final int COMMAND_DATA_MAIN_INDEX = 3;
    private static final int COMMAND_DATA_SUB_INDEX = 4;
    private static final int COUNT_CHECK_FAST_BOOT = 40;
    private static final int COUNT_CHECK_VERSION = 120;
    private static final int COUNT_SEND_FAST_BOOT_COMMAND = 5;
    private static final int HID_BUF_LEN = 64;
    private static final String TAG = "CameraDevice";
    private static final String UNZIP_DIR = "cameraUpgradeUnzipTmp";
    public static final String UPGRADE_FILE_BOOT_IMG = "boot.img";
    public static final String UPGRADE_FILE_LK_BIN = "lk.bin";
    public static final String UPGRADE_FILE_SYSTEM_IMG = "system.img";
    public static final String VERSION_IN_FAST_BOOT = "0.0.0.0";
    private static final String ZIP_SUFFIX = ".zip";
    private static final ArrayList<CameraInfo> ZYZH_CAMERA_DEVICES = new ArrayList() { // from class: com.cvte.dss.ups.camera.zyzh.CameraDevice.1
        {
            add(new CameraInfo(9546, InvokeCmd.CMD_NETWORK_SET_ETHERNET_NAT_ENABLE));
            add(new CameraInfo(9546, InvokeCmd.CMD_NETWORK_WOL_SET_ENABLE));
            add(new CameraInfo(9546, InvokeCmd.CMD_NETWORK_WOL_GET_ENABLE));
            add(new CameraInfo(9546, InvokeCmd.CMD_NETWORK_SET_MCU_DHCP_IP));
            add(new CameraInfo(2996, 3073));
        }
    };
    private final ICameraUpgrade mCameraSupport;
    private b mUsbDevice;

    public static class CameraInfo {
        public int pid;
        public int vid;

        public CameraInfo(int i2, int i3) {
            this.vid = i2;
            this.pid = i3;
        }
    }

    public CameraDevice(Context context) {
        if (SystemPropertyUtil.isUseVmanUpgrade()) {
            this.mCameraSupport = new VmanUpgrade();
        } else {
            this.mCameraSupport = new ShellUpgrade(context);
        }
    }

    private boolean enterFastBoot() {
        if (isFastBoot()) {
            return true;
        }
        for (int i2 = 0; i2 < 5; i2++) {
            if (hasEnterFastBoot(sendUpgradeMessage())) {
                for (int i3 = 0; i3 < 40; i3++) {
                    if (checkFastBoot()) {
                        return true;
                    }
                    a.P(500L);
                }
            } else {
                a.P(500L);
            }
        }
        return false;
    }

    private UsbDevice findUsbDevice(Context context) {
        UsbManager usbManager = (UsbManager) context.getSystemService("usb");
        for (UsbDevice usbDevice : usbManager == null ? new ArrayList() : new ArrayList(usbManager.getDeviceList().values())) {
            for (CameraInfo cameraInfo : ZYZH_CAMERA_DEVICES) {
                if (usbDevice != null && usbDevice.getVendorId() == cameraInfo.vid && usbDevice.getProductId() == cameraInfo.pid) {
                    return usbDevice;
                }
            }
        }
        return null;
    }

    private byte[] getCameraCommand(byte b2) {
        byte[] bArr = new byte[64];
        bArr[0] = -86;
        bArr[1] = -69;
        bArr[2] = -52;
        bArr[3] = 32;
        bArr[4] = b2;
        bArr[63] = getCheckSum(bArr, 63);
        try {
            b bVar = this.mUsbDevice;
            UsbDeviceConnection usbDeviceConnection = bVar.f2495e;
            UsbEndpoint usbEndpoint = bVar.f2493c;
            if (usbEndpoint != null && usbEndpoint.getDirection() == 0 && usbDeviceConnection.bulkTransfer(usbEndpoint, bArr, 64, 2000) <= 0) {
                Log.e("UsbUtils", "send data error");
            }
            UsbDeviceConnection usbDeviceConnection2 = bVar.f2495e;
            UsbEndpoint usbEndpoint2 = bVar.f2494d;
            if (usbEndpoint2.getDirection() != 128) {
                return null;
            }
            byte[] bArr2 = new byte[64];
            if (usbDeviceConnection2.bulkTransfer(usbEndpoint2, bArr2, 64, 2000) > 0) {
                return bArr2;
            }
            return null;
        } catch (Exception e2) {
            Log.e(TAG, "getCameraCommand", e2);
            return null;
        }
    }

    private String getCameraMessage(byte b2, byte b3) {
        byte[] cameraCommand;
        b bVar = this.mUsbDevice;
        if (bVar == null || !bVar.b() || (cameraCommand = getCameraCommand(b2)) == 0 || cameraCommand.length < 6 || cameraCommand[3] != ' ' || cameraCommand[4] != b3) {
            return null;
        }
        int i2 = cameraCommand[5];
        byte[] bArr = new byte[i2];
        System.arraycopy(cameraCommand, 7, bArr, 0, i2);
        if (i2 == 0 || i2 <= 0 || i2 <= 0 || i2 + 0 < i2) {
            return null;
        }
        byte[] bArr2 = new byte[i2];
        System.arraycopy(bArr, 0, bArr2, 0, i2);
        try {
            return new String(bArr2, CHARSET);
        } catch (Exception unused) {
            Log.e("ByteUtils", "An exception has occurred in ByteUtils.bytesToAscii");
            return null;
        }
    }

    private byte getCheckSum(byte[] bArr, int i2) {
        int i3 = 0;
        for (int i4 = 0; i4 < i2; i4++) {
            i3 += bArr[i4] & 255;
        }
        return (byte) ((i3 % 256) & SheetSettings.DEFAULT_DEFAULT_ROW_HEIGHT);
    }

    private boolean hasEnterFastBoot(byte[] bArr) {
        return bArr != null && bArr.length >= 5 && bArr[3] == 32 && bArr[4] == 9;
    }

    private boolean isFastBoot() {
        for (int i2 = 0; i2 < 10; i2++) {
            if (checkFastBoot()) {
                return true;
            }
            a.P(500L);
        }
        return false;
    }

    private byte[] sendUpgradeMessage() {
        if (this.mUsbDevice.b()) {
            return getCameraCommand((byte) 8);
        }
        return null;
    }

    public boolean checkFastBoot() {
        return this.mCameraSupport.checkFastBoot();
    }

    public boolean connect(Context context) {
        b bVar = this.mUsbDevice;
        if (bVar == null) {
            return false;
        }
        try {
            bVar.a(context);
            return true;
        } catch (Exception e2) {
            Log.e(TAG, "connect error", e2);
            return true;
        }
    }

    public boolean disconnect() {
        b bVar = this.mUsbDevice;
        if (bVar == null) {
            return false;
        }
        UsbDeviceConnection usbDeviceConnection = bVar.f2495e;
        UsbInterface usbInterface = bVar.f2492b;
        if (usbDeviceConnection != null && usbInterface != null) {
            usbDeviceConnection.releaseInterface(usbInterface);
        }
        UsbDeviceConnection usbDeviceConnection2 = bVar.f2495e;
        if (usbDeviceConnection2 != null) {
            usbDeviceConnection2.close();
        }
        bVar.f2495e = null;
        bVar.f2492b = null;
        bVar.f2494d = null;
        bVar.f2493c = null;
        return true;
    }

    public String getModule() {
        String cameraMessage = getCameraMessage((byte) 10, (byte) 11);
        return (TextUtils.isEmpty(cameraMessage) || checkFastBoot()) ? "zyzh" : cameraMessage;
    }

    public String getOTAKey() {
        String cameraMessage = getCameraMessage((byte) 14, (byte) 15);
        return (TextUtils.isEmpty(cameraMessage) && checkFastBoot()) ? this.mCameraSupport.getOtaKeyOnFastBoot() : cameraMessage;
    }

    public String getVersion() {
        String cameraMessage = getCameraMessage((byte) 6, (byte) 7);
        return (cameraMessage == null && checkFastBoot()) ? VERSION_IN_FAST_BOOT : cameraMessage;
    }

    public boolean refreshUsbDevice(Context context) {
        UsbDevice usbDeviceFindUsbDevice = findUsbDevice(context);
        if (usbDeviceFindUsbDevice == null) {
            return false;
        }
        this.mUsbDevice = new b(usbDeviceFindUsbDevice);
        return true;
    }

    public boolean upgrade(Context context, File file, UpgradeProgressListener upgradeProgressListener, String str) throws Throwable {
        boolean z;
        ZipFile zipFile;
        FileOutputStream fileOutputStream;
        FileOutputStream fileOutputStream2;
        InputStream inputStream;
        if (!file.exists()) {
            StringBuilder sbB = d.b.a.a.a.B("upgrade: ");
            sbB.append(file.getAbsolutePath());
            sbB.append(" not exists");
            Log.i(TAG, sbB.toString());
            return false;
        }
        if (file.isDirectory()) {
            return upgrade(context, file.getAbsolutePath(), str, upgradeProgressListener);
        }
        if (file.getName().endsWith(ZIP_SUFFIX)) {
            File file2 = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), UNZIP_DIR);
            if (!file2.exists() && !file2.mkdirs()) {
                StringBuilder sbB2 = d.b.a.a.a.B("upgrade unzipDir path = ");
                sbB2.append(file2.getAbsolutePath());
                sbB2.append(" not exists");
                Log.d(TAG, sbB2.toString());
                return false;
            }
            try {
                zipFile = new ZipFile(file);
            } catch (IOException unused) {
            }
            if (file2.exists()) {
                Enumeration<? extends ZipEntry> enumerationEntries = zipFile.entries();
                while (enumerationEntries.hasMoreElements()) {
                    ZipEntry zipEntryNextElement = enumerationEntries.nextElement();
                    File file3 = new File(file2, zipEntryNextElement.getName());
                    if (zipEntryNextElement.isDirectory()) {
                        file3.mkdirs();
                    } else {
                        File parentFile = file3.getParentFile();
                        if (parentFile != null && (parentFile.exists() || parentFile.mkdirs())) {
                            String absolutePath = file3.getAbsolutePath();
                            InputStream inputStream2 = null;
                            FileOutputStream fileOutputStream3 = null;
                            InputStream inputStream3 = null;
                            try {
                                inputStream = zipFile.getInputStream(zipEntryNextElement);
                            } catch (IOException unused2) {
                                fileOutputStream2 = null;
                            } catch (Throwable th) {
                                th = th;
                                fileOutputStream = null;
                                a.O(inputStream2);
                                a.O(fileOutputStream);
                                throw th;
                            }
                            try {
                                fileOutputStream2 = new FileOutputStream(new File(absolutePath));
                            } catch (IOException unused3) {
                                fileOutputStream2 = null;
                            } catch (Throwable th2) {
                                th = th2;
                                fileOutputStream = fileOutputStream3;
                                inputStream2 = inputStream;
                                a.O(inputStream2);
                                a.O(fileOutputStream);
                                throw th;
                            }
                            try {
                                a.k(inputStream, fileOutputStream2);
                                a.O(inputStream);
                            } catch (IOException unused4) {
                                inputStream3 = inputStream;
                                try {
                                    Log.e("ZipUtils", "unzip to " + absolutePath + " failed");
                                    a.O(inputStream3);
                                } catch (Throwable th3) {
                                    th = th3;
                                    inputStream = inputStream3;
                                    fileOutputStream3 = fileOutputStream2;
                                    fileOutputStream = fileOutputStream3;
                                    inputStream2 = inputStream;
                                    a.O(inputStream2);
                                    a.O(fileOutputStream);
                                    throw th;
                                }
                            } catch (Throwable th4) {
                                th = th4;
                                fileOutputStream3 = fileOutputStream2;
                                fileOutputStream = fileOutputStream3;
                                inputStream2 = inputStream;
                                a.O(inputStream2);
                                a.O(fileOutputStream);
                                throw th;
                            }
                            a.O(fileOutputStream2);
                        }
                    }
                }
                a.O(zipFile);
                z = true;
            } else {
                z = false;
            }
            if (z) {
                boolean zUpgrade = upgrade(context, file2, upgradeProgressListener, str);
                Log.d(TAG, "upgrade result：" + zUpgrade + " start delete zipDir" + file2.getAbsolutePath());
                String absolutePath2 = file2.getAbsolutePath();
                File file4 = new File(absolutePath2);
                d.b.a.a.a.P("delete zipDir result : ", file4.exists() ? file4.isFile() ? a.n(absolutePath2) : a.m(absolutePath2) : false, TAG);
                return zUpgrade;
            }
            Log.d(TAG, "upgrade unzip file fail");
        }
        return false;
    }

    private boolean upgrade(Context context, String str, String str2, UpgradeProgressListener upgradeProgressListener) {
        upgradeProgressListener.process(0.1f);
        File file = new File(str, UPGRADE_FILE_LK_BIN);
        File file2 = new File(str, UPGRADE_FILE_BOOT_IMG);
        File file3 = new File(str, UPGRADE_FILE_SYSTEM_IMG);
        if (file.exists() && file2.exists() && file3.exists()) {
            if (!enterFastBoot()) {
                Log.d(Plugin.TAG, "enterFastBoot failed");
                return false;
            }
            upgradeProgressListener.process(0.2f);
            if (!this.mCameraSupport.upgrade(context, str, str2, upgradeProgressListener)) {
                return false;
            }
            upgradeProgressListener.process(0.9f);
            for (int i2 = 0; i2 < 120; i2++) {
                refreshUsbDevice(context);
                if (!this.mUsbDevice.b()) {
                    this.mUsbDevice.a(context);
                }
                String cameraMessage = getCameraMessage((byte) 6, (byte) 7);
                if (cameraMessage != null && !TextUtils.isEmpty(cameraMessage)) {
                    Log.d(Plugin.TAG, "upgrade success");
                    upgradeProgressListener.process(1.0f);
                    return true;
                }
                a.P(500L);
            }
            return false;
        }
        Log.d(Plugin.TAG, "lkBin or bootImg or systemImg not exist");
        return false;
    }
}
