package com.tencent.usb;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
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.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import kotlinx.serialization.json.internal.AbstractJsonLexerKt;

/* JADX INFO: loaded from: classes.dex */
public class UsbHidDevice {
    private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
    private static final String ACTION_USB_STATE = "android.hardware.usb.action.USB_STATE";
    private static final int INTERFACE_CLASS_HID = 3;
    private static final String TAG = "USB_DEV";
    private static final String USB_CONFIGURED = "configured";
    private static final String USB_CONNECTED = "connected";
    private static final String USB_DATA_UNLOCKED = "unlocked";
    private static final String USB_FUNCTION_ADB = "adb";
    private static final String USB_FUNCTION_AUDIO_SOURCE = "audio_source";
    private static final String USB_FUNCTION_MIDI = "midi";
    private static final String USB_FUNCTION_MTP = "mtp";
    private static final String USB_FUNCTION_NONE = "none";
    private static final String USB_FUNCTION_PTP = "ptp";
    private static final String USB_FUNCTION_RNDIS = "rndis";
    private static List<UsbHidDevice> mHidDeviceList = new ArrayList();
    public int mBusNum;
    private UsbDeviceConnection mConnection;
    public int mDevNum;
    private int mDeviceId;
    private String mDeviceName;
    public int mFd;
    private Handler mHandler;
    public int mInEpAddr;
    private UsbEndpoint mInUsbEndpoint;
    private com.tencent.usb.b mListener;
    public int mOutEpAddr;
    private UsbEndpoint mOutUsbEndpoint;
    private PendingIntent mPermissionIntent;
    public int mPid;
    private String mProductName;
    private UsbDevice mUsbDevice;
    private UsbInterface mUsbInterface;
    private UsbManager mUsbManager;
    public int mVid;
    private final BroadcastReceiver mUsbPermissionReceiver = new a();
    private String mDeviceSn = AbstractJsonLexerKt.NULL;

    public class a extends BroadcastReceiver {
        public a() {
        }

        @Override // android.content.BroadcastReceiver
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            context.unregisterReceiver(this);
            if (action.equals(UsbHidDevice.ACTION_USB_PERMISSION)) {
                Log.i(UsbHidDevice.TAG, "device ask permission");
                synchronized (this) {
                    UsbDevice usbDevice = (UsbDevice) intent.getParcelableExtra("device");
                    boolean booleanExtra = intent.getBooleanExtra("permission", false);
                    boolean zHasPermission = UsbHidDevice.this.mUsbManager.hasPermission(usbDevice);
                    if ((booleanExtra || zHasPermission) && usbDevice != null) {
                        UsbHidDevice.this.openDevice();
                    } else {
                        Log.e(UsbHidDevice.TAG, "device ask permission failed");
                        UsbHidDevice.this.onConnectFailed();
                    }
                }
            }
        }
    }

    public class b implements Runnable {
        public b() {
        }

        @Override // java.lang.Runnable
        public void run() {
            if (UsbHidDevice.this.mListener != null) {
                UsbHidDevice.this.mListener.onUsbHidDeviceConnectFailed(UsbHidDevice.this);
            }
        }
    }

    public class c implements Runnable {
        public c() {
        }

        @Override // java.lang.Runnable
        public void run() {
            if (UsbHidDevice.this.mListener != null) {
                UsbHidDevice.this.mListener.onUsbHidDeviceConnected(UsbHidDevice.this);
            }
        }
    }

    private UsbHidDevice(UsbDevice usbDevice, UsbInterface usbInterface, UsbManager usbManager) {
        this.mUsbDevice = usbDevice;
        this.mUsbInterface = usbInterface;
        this.mUsbManager = usbManager;
        this.mDeviceName = usbDevice.getDeviceName();
        this.mProductName = usbDevice.getProductName();
        this.mDeviceId = usbDevice.getDeviceId();
        String[] strArrSplit = !TextUtils.isEmpty(this.mDeviceName) ? this.mDeviceName.split("/") : null;
        if (strArrSplit != null) {
            this.mBusNum = Integer.parseInt(strArrSplit[strArrSplit.length - 2]);
            this.mDevNum = Integer.parseInt(strArrSplit[strArrSplit.length - 1]);
        }
        this.mVid = usbDevice.getVendorId();
        this.mPid = usbDevice.getProductId();
        StringBuilder sbF = g.a.a.a.a.F("UsbHidDevice vid:0x");
        sbF.append(Integer.toHexString(this.mVid));
        sbF.append(",pid:0x");
        sbF.append(Integer.toHexString(this.mPid));
        sbF.append(",devname:");
        sbF.append(this.mDeviceName);
        sbF.append(",busnum:");
        sbF.append(this.mBusNum);
        sbF.append(",devnum:");
        g.a.a.a.a.q0(sbF, this.mDevNum, TAG);
        for (int i2 = 0; i2 < this.mUsbInterface.getEndpointCount(); i2++) {
            UsbEndpoint endpoint = this.mUsbInterface.getEndpoint(i2);
            int direction = endpoint.getDirection();
            int type = endpoint.getType();
            if (this.mInUsbEndpoint == null && direction == 128 && type == 3) {
                this.mInUsbEndpoint = endpoint;
                this.mInEpAddr = endpoint.getAddress();
                g.a.a.a.a.q0(g.a.a.a.a.F("Input endpoint address:"), this.mInEpAddr, TAG);
            }
            if (this.mOutUsbEndpoint == null && direction == 0 && type == 3) {
                this.mOutUsbEndpoint = endpoint;
                this.mOutEpAddr = endpoint.getAddress();
                g.a.a.a.a.q0(g.a.a.a.a.F("Output endpoint address:"), this.mOutEpAddr, TAG);
            }
        }
    }

    public static UsbHidDevice InsertDevice(Context context) {
        int i2;
        boolean z2;
        UsbManager usbManager = (UsbManager) context.getApplicationContext().getSystemService("usb");
        UsbHidDevice usbHidDevice = null;
        if (usbManager == null) {
            Log.i(TAG, "InsertDevice device usbManager is null.");
            return null;
        }
        for (UsbDevice usbDevice : usbManager.getDeviceList().values()) {
            if ((usbDevice.getVendorId() == 10071 && usbDevice.getProductId() == 16388) || ((usbDevice.getVendorId() == 10847 && (usbDevice.getProductId() & 61440) == 8192) || ((usbDevice.getVendorId() == 8183 && usbDevice.getProductId() == 1105) || ((usbDevice.getVendorId() == 6127 && usbDevice.getProductId() == 41088) || ((usbDevice.getVendorId() == 8711 && usbDevice.getProductId() == 8197) || (usbDevice.getVendorId() == 12372 && usbDevice.getProductId() == 34952)))))) {
                Iterator<UsbHidDevice> it = mHidDeviceList.iterator();
                while (true) {
                    if (!it.hasNext()) {
                        z2 = false;
                        break;
                    }
                    if (usbDevice.getDeviceName().equals(it.next().getDeviceName())) {
                        StringBuilder sbF = g.a.a.a.a.F("InsertDevice device already_exsit ");
                        sbF.append(usbDevice.getDeviceName());
                        Log.i(TAG, sbF.toString());
                        z2 = true;
                        break;
                    }
                }
                if (!z2) {
                    for (i2 = 0; i2 < usbDevice.getInterfaceCount(); i2++) {
                        UsbInterface usbInterface = usbDevice.getInterface(i2);
                        if (usbInterface.getInterfaceClass() == 3) {
                            StringBuilder sbF2 = g.a.a.a.a.F("InsertDevice device interface ");
                            sbF2.append(usbInterface.getName());
                            Log.i(TAG, sbF2.toString());
                            usbHidDevice = new UsbHidDevice(usbDevice, usbInterface, usbManager);
                            mHidDeviceList.add(usbHidDevice);
                        }
                    }
                }
            }
        }
        return usbHidDevice;
    }

    public static void RemoveDevice(String str) {
        Iterator<UsbHidDevice> it = mHidDeviceList.iterator();
        while (it.hasNext()) {
            UsbHidDevice next = it.next();
            if (next.getDeviceName().equals(str)) {
                next.close();
                it.remove();
            }
        }
    }

    public static List<UsbHidDevice> enumerate(Context context) throws Exception {
        UsbManager usbManager = (UsbManager) context.getApplicationContext().getSystemService("usb");
        if (usbManager == null) {
            throw new Exception("no usb service");
        }
        HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
        ArrayList arrayList = new ArrayList();
        for (UsbDevice usbDevice : deviceList.values()) {
            if ((usbDevice.getVendorId() == 10071 && usbDevice.getProductId() == 16388) || ((usbDevice.getVendorId() == 10847 && (usbDevice.getProductId() & 61440) == 8192) || ((usbDevice.getVendorId() == 8183 && usbDevice.getProductId() == 1105) || ((usbDevice.getVendorId() == 6127 && usbDevice.getProductId() == 41088) || ((usbDevice.getVendorId() == 8711 && usbDevice.getProductId() == 8197) || (usbDevice.getVendorId() == 12372 && usbDevice.getProductId() == 34952)))))) {
                Log.i(TAG, "enumerate found device");
                for (int i2 = 0; i2 < usbDevice.getInterfaceCount(); i2++) {
                    UsbInterface usbInterface = usbDevice.getInterface(i2);
                    if (usbInterface.getInterfaceClass() == 3) {
                        StringBuilder sbF = g.a.a.a.a.F("enumerate open device interface ");
                        sbF.append(usbInterface.getName());
                        Log.i(TAG, sbF.toString());
                        arrayList.add(new UsbHidDevice(usbDevice, usbInterface, usbManager));
                        Log.i(TAG, "enumerate open device end");
                    }
                }
            }
        }
        return arrayList;
    }

    public static void factory(Context context) {
        try {
            mHidDeviceList = enumerate(context);
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }

    public static UsbHidDevice[] getHidDeviceList() {
        List<UsbHidDevice> list = mHidDeviceList;
        return (UsbHidDevice[]) list.toArray(new UsbHidDevice[list.size()]);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void onConnectFailed() {
        this.mHandler.post(new b());
    }

    private void onConnectSuccess() {
        this.mHandler.post(new c());
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void openDevice() {
        try {
            this.mConnection = this.mUsbManager.openDevice(this.mUsbDevice);
        } catch (IllegalArgumentException e2) {
            e2.printStackTrace();
        }
        UsbDeviceConnection usbDeviceConnection = this.mConnection;
        if (usbDeviceConnection == null) {
            Log.e(TAG, "openDevice failed, connection is null");
            onConnectFailed();
            return;
        }
        usbDeviceConnection.releaseInterface(this.mUsbInterface);
        if (!this.mConnection.claimInterface(this.mUsbInterface, true)) {
            Log.e(TAG, "openDevice failed, retrying...");
            for (int i2 = 0; i2 < this.mUsbDevice.getInterfaceCount(); i2++) {
                UsbInterface usbInterface = this.mUsbDevice.getInterface(i2);
                if (usbInterface.getInterfaceClass() == 3) {
                    this.mUsbInterface = usbInterface;
                }
            }
            this.mConnection.releaseInterface(this.mUsbInterface);
            if (!this.mConnection.claimInterface(this.mUsbInterface, true)) {
                Log.e(TAG, "openDevice failed, connection claim interface failed");
                this.mConnection.releaseInterface(this.mUsbInterface);
                this.mConnection.close();
                onConnectFailed();
                return;
            }
        }
        this.mFd = this.mConnection.getFileDescriptor();
        this.mConnection.setInterface(this.mUsbInterface);
        this.mDeviceSn = this.mUsbDevice.getSerialNumber();
        onConnectSuccess();
    }

    public void close() {
        UsbDeviceConnection usbDeviceConnection = this.mConnection;
        if (usbDeviceConnection != null) {
            usbDeviceConnection.releaseInterface(this.mUsbInterface);
            this.mConnection.close();
        }
    }

    public int getDeviceId() {
        return this.mUsbDevice.getDeviceId();
    }

    public String getDeviceInfo() {
        return getProductName() + ";" + (this.mDeviceSn + ";" + Integer.toHexString(getDeviceVid()) + ";" + Integer.toHexString(getDevicePid()));
    }

    public String getDeviceName() {
        return this.mUsbDevice.getDeviceName();
    }

    public int getDevicePid() {
        return this.mUsbDevice.getProductId();
    }

    public int getDeviceVid() {
        return this.mUsbDevice.getVendorId();
    }

    public String getProductName() {
        return this.mUsbDevice.getProductName();
    }

    public String getSerialNumber() {
        return this.mDeviceSn;
    }

    public UsbDevice getUsbDevice() {
        return this.mUsbDevice;
    }

    public void open(Context context, com.tencent.usb.b bVar) {
        int deviceId;
        int i2;
        this.mListener = bVar;
        this.mHandler = new Handler(context.getMainLooper());
        Intent intent = new Intent(ACTION_USB_PERMISSION);
        intent.putExtra("device", this.mUsbDevice);
        if (Build.VERSION.SDK_INT >= 31) {
            deviceId = this.mUsbDevice.getDeviceId();
            i2 = 201326592;
        } else {
            deviceId = this.mUsbDevice.getDeviceId();
            i2 = 134217728;
        }
        this.mPermissionIntent = PendingIntent.getBroadcast(context, deviceId, intent, i2);
        if (this.mUsbManager.hasPermission(this.mUsbDevice)) {
            Log.i(TAG, "UsbManager has permission, open device directly");
            openDevice();
            return;
        }
        StringBuilder sbF = g.a.a.a.a.F("UsbManager not has permission, request for device: ");
        sbF.append(this.mUsbDevice.getDeviceName());
        Log.i(TAG, sbF.toString());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_USB_PERMISSION);
        context.registerReceiver(this.mUsbPermissionReceiver, intentFilter);
        this.mUsbManager.requestPermission(this.mUsbDevice, this.mPermissionIntent);
    }

    public byte[] read(int i2) {
        return read(i2, -1);
    }

    public byte[] read(int i2, int i3) {
        byte[] bArr = new byte[i2];
        int iBulkTransfer = this.mConnection.bulkTransfer(this.mInUsbEndpoint, bArr, i2, i3);
        return iBulkTransfer < i2 ? Arrays.copyOfRange(bArr, 0, iBulkTransfer) : bArr;
    }

    public void write(byte[] bArr) {
        write(bArr, 0, bArr.length);
    }

    public void write(byte[] bArr, int i2) {
        write(bArr, 0, i2);
    }

    public void write(byte[] bArr, int i2, int i3) {
        if (i2 != 0) {
            bArr = Arrays.copyOfRange(bArr, i2, i3);
        }
        UsbEndpoint usbEndpoint = this.mOutUsbEndpoint;
        if (usbEndpoint == null) {
            return;
        }
        this.mConnection.bulkTransfer(usbEndpoint, bArr, i3, 1000);
    }
}
