package com.cvte.dss.ups.sp20e;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanRecord;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.util.Log;
import com.cvte.dss.ups.plugin.IUpsPlugin;
import com.cvte.dss.ups.sp20e.Sp20ePlugin;
import com.cvte.vman.instance.InvokeCmd;
import g.a.a.a.a;
import g.h.a.i;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import kotlin.Metadata;
import kotlin.jvm.internal.d0;
import kotlin.jvm.internal.o;
import kotlin.text.Charsets;
import kotlin.text.j;
import kotlinx.serialization.json.internal.AbstractJsonLexerKt;
import no.nordicsemi.android.dfu.DfuProgressListener;

/* JADX INFO: loaded from: classes.dex */
@Metadata(d1 = {"\u0000Z\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0010\u000b\n\u0000\n\u0002\u0010\u000e\n\u0002\b\u0004\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0010 \n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0002\b\u0004\n\u0002\u0010\u0007\n\u0002\b\u0006\n\u0002\u0010\u0002\n\u0000\n\u0002\u0018\u0002\n\u0002\b\u0004\n\u0002\u0018\u0002\n\u0000\n\u0002\u0018\u0002\n\u0002\b\u0006\u0018\u0000 ,2\u00020\u0001:\u0001,B\u0005¢\u0006\u0002\u0010\u0002J\u0016\u0010\u0003\u001a\u00020\u00042\u0006\u0010\u0005\u001a\u00020\u00062\u0006\u0010\u0007\u001a\u00020\u0006J\u0016\u0010\b\u001a\u00020\u00042\u0006\u0010\u0007\u001a\u00020\u00062\u0006\u0010\t\u001a\u00020\u0006J\u0012\u0010\n\u001a\u0004\u0018\u00010\u000b2\u0006\u0010\f\u001a\u00020\rH\u0016J\u0016\u0010\u000e\u001a\b\u0012\u0004\u0012\u00020\u000b0\u000f2\u0006\u0010\f\u001a\u00020\rH\u0016J\u0010\u0010\u0010\u001a\u0004\u0018\u00010\u00062\u0006\u0010\u0007\u001a\u00020\u0006J\u0014\u0010\u0011\u001a\b\u0012\u0004\u0012\u00020\u00120\u000f2\u0006\u0010\f\u001a\u00020\rJ\u0010\u0010\u0013\u001a\u0004\u0018\u00010\u00062\u0006\u0010\u0007\u001a\u00020\u0006J\u0010\u0010\u0014\u001a\u00020\u00042\u0006\u0010\u0015\u001a\u00020\u0012H\u0002J0\u0010\u0016\u001a\u00020\u00172\u0006\u0010\u0018\u001a\u00020\u00172\u0006\u0010\u0019\u001a\u00020\u00172\u0006\u0010\u001a\u001a\u00020\u00172\u0006\u0010\u001b\u001a\u00020\u00172\u0006\u0010\u001c\u001a\u00020\u0017H\u0002J\u0016\u0010\u001d\u001a\u00020\u001e2\u0006\u0010\f\u001a\u00020\r2\u0006\u0010\u001f\u001a\u00020 J\u0016\u0010!\u001a\u00020\u001e2\u0006\u0010\f\u001a\u00020\r2\u0006\u0010\u001f\u001a\u00020 J(\u0010\"\u001a\u00020\u001e2\u0006\u0010#\u001a\u00020\u00062\u0006\u0010\f\u001a\u00020\r2\u0006\u0010$\u001a\u00020%2\b\u0010&\u001a\u0004\u0018\u00010'J(\u0010(\u001a\u00020\u00042\u0006\u0010\f\u001a\u00020\r2\u0006\u0010)\u001a\u00020\u00062\u0006\u0010*\u001a\u00020\u00042\u0006\u0010$\u001a\u00020%H\u0016J0\u0010(\u001a\u00020\u00042\u0006\u0010\f\u001a\u00020\r2\u0006\u0010+\u001a\u00020\u00062\u0006\u0010)\u001a\u00020\u00062\u0006\u0010*\u001a\u00020\u00042\u0006\u0010$\u001a\u00020%H\u0016¨\u0006-"}, d2 = {"Lcom/cvte/dss/ups/sp20e/Sp20ePlugin;", "Lcom/cvte/dss/ups/plugin/IUpsPlugin;", "()V", "changBootloaderName", "", "name", "", "addr", "enterBootloader", "bootloaderName", "getFirmwareInfo", "Lcom/cvte/dss/ups/plugin/IUpsPlugin$FirmwareInfo;", "context", "Landroid/content/Context;", "getFirmwareInfos", "", "getOtakey", "getSp20eDevice", "Landroid/bluetooth/BluetoothDevice;", "getVersion", "isSp20eDeviceName", "device", "normalizeProgress", "", "progress", "inMin", "inMax", "outMin", "outMax", "startScan", "", "scanCallback", "Landroid/bluetooth/le/ScanCallback;", "stopScan", "upgradeDfuFail", "msg", "listener", "Lcom/cvte/dss/ups/plugin/IUpsPlugin$IUpgradeStatusListener;", "dfuProgressListener", "Lno/nordicsemi/android/dfu/DfuProgressListener;", "upgradeFirmware", "path", "force", "id", "Companion", "lib_release"}, k = 1, mv = {1, 6, 0}, xi = 48)
public final class Sp20ePlugin implements IUpsPlugin {
    public static final String TAG = "Sp20ePlugin";
    public static final long dfuShortId = 2395537411L;

    private final boolean isSp20eDeviceName(BluetoothDevice device) {
        String name = device.getName();
        if (name == null || name.length() == 0) {
            return false;
        }
        String name2 = device.getName();
        o.e(name2, "device.name");
        return j.M(name2, "SP20E_", false, 2);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public final float normalizeProgress(float progress, float inMin, float inMax, float outMin, float outMax) {
        if (progress < inMin) {
            return outMin;
        }
        if (progress > inMax) {
            return outMax;
        }
        return (((progress - inMin) * (outMax - outMin)) / (inMax - inMin)) + outMin;
    }

    /* JADX INFO: Access modifiers changed from: private */
    /* JADX INFO: renamed from: upgradeFirmware$lambda-0, reason: not valid java name */
    public static final void m1upgradeFirmware$lambda0(Sp20ePlugin sp20ePlugin, Context context, Sp20ePlugin$upgradeFirmware$scanCallback$1 sp20ePlugin$upgradeFirmware$scanCallback$1, IUpsPlugin.IUpgradeStatusListener iUpgradeStatusListener) {
        o.f(sp20ePlugin, "this$0");
        o.f(context, "$context");
        o.f(sp20ePlugin$upgradeFirmware$scanCallback$1, "$scanCallback");
        o.f(iUpgradeStatusListener, "$listener");
        Log.d(TAG, "can't find bootloader device after 60s");
        sp20ePlugin.stopScan(context, sp20ePlugin$upgradeFirmware$scanCallback$1);
        iUpgradeStatusListener.onFailed("can't find bootloader device");
    }

    public final boolean changBootloaderName(String name, String addr) {
        o.f(name, "name");
        o.f(addr, "addr");
        Log.d(TAG, addr + " try change bootloader name to " + name);
        ArrayList arrayList = new ArrayList();
        arrayList.add((byte) 2);
        arrayList.add(Byte.valueOf((byte) name.length()));
        byte[] bytes = name.getBytes(Charsets.f9181b);
        o.e(bytes, "this as java.lang.String).getBytes(charset)");
        for (byte b2 : bytes) {
            arrayList.add(Byte.valueOf(b2));
        }
        return BleUtils.INSTANCE.writeCharacteristic(addr, dfuShortId, arrayList);
    }

    public final boolean enterBootloader(String addr, String bootloaderName) {
        o.f(addr, "addr");
        o.f(bootloaderName, "bootloaderName");
        Log.d(TAG, addr + " try enter bootloader");
        changBootloaderName(bootloaderName, addr);
        return BleUtils.INSTANCE.writeCharacteristic(addr, dfuShortId, i.H2((byte) 1));
    }

    @Override // com.cvte.dss.ups.plugin.IUpsPlugin
    public IUpsPlugin.FirmwareInfo getFirmwareInfo(Context context) {
        o.f(context, "context");
        Log.e(TAG, "not support getFirmwareInfo");
        return null;
    }

    @Override // com.cvte.dss.ups.plugin.IUpsPlugin
    public List<IUpsPlugin.FirmwareInfo> getFirmwareInfos(Context context) {
        o.f(context, "context");
        List<BluetoothDevice> sp20eDevice = getSp20eDevice(context);
        ArrayList arrayList = new ArrayList();
        for (BluetoothDevice bluetoothDevice : sp20eDevice) {
            BleUtils bleUtils = BleUtils.INSTANCE;
            String address = bluetoothDevice.getAddress();
            o.e(address, "device.address");
            if (bleUtils.connectBleDevice(address)) {
                String address2 = bluetoothDevice.getAddress();
                o.e(address2, "device.address");
                String otakey = getOtakey(address2);
                if (otakey != null) {
                    String address3 = bluetoothDevice.getAddress();
                    o.e(address3, "device.address");
                    String version = getVersion(address3);
                    if (version != null) {
                        String address4 = bluetoothDevice.getAddress();
                        o.e(address4, "device.address");
                        String strC = j.C(address4, ":", "-", false, 4);
                        String name = bluetoothDevice.getName();
                        o.e(name, "device.name");
                        arrayList.add(new IUpsPlugin.FirmwareInfo(name, "sp20e", "sp20e", version, otakey, false, true, strC));
                    }
                }
            }
        }
        return arrayList;
    }

    @Override // com.cvte.dss.ups.plugin.IUpsPlugin
    public List<IUpsPlugin.FirmwareInfo> getFirmwareInfosWithOptions(Context context, String str) {
        return IUpsPlugin.DefaultImpls.getFirmwareInfosWithOptions(this, context, str);
    }

    public final String getOtakey(String addr) {
        o.f(addr, "addr");
        CharacteristicApiGetResponse characteristic = BleUtils.INSTANCE.readCharacteristic(addr, 10788L);
        if (characteristic == null) {
            return null;
        }
        String str = new String(kotlin.collections.j.f0(characteristic.getData()), Charsets.f9181b);
        a.g0("otakey: ", str, TAG);
        return str;
    }

    public final List<BluetoothDevice> getSp20eDevice(Context context) {
        o.f(context, "context");
        ArrayList arrayList = new ArrayList();
        Object systemService = context.getSystemService("bluetooth");
        Objects.requireNonNull(systemService, "null cannot be cast to non-null type android.bluetooth.BluetoothManager");
        BluetoothAdapter adapter = ((BluetoothManager) systemService).getAdapter();
        try {
            Method declaredMethod = BluetoothAdapter.class.getDeclaredMethod("getConnectionState", new Class[0]);
            o.e(declaredMethod, "bluetoothAdapterClass.ge…hod(\"getConnectionState\")");
            declaredMethod.setAccessible(true);
            if (o.a(declaredMethod.invoke(adapter, new Object[0]), 2)) {
                Set<BluetoothDevice> bondedDevices = adapter.getBondedDevices();
                o.e(bondedDevices, "adapter.bondedDevices");
                for (BluetoothDevice bluetoothDevice : bondedDevices) {
                    Method declaredMethod2 = BluetoothDevice.class.getDeclaredMethod("isConnected", new Class[0]);
                    o.e(declaredMethod2, "BluetoothDevice::class.j…aredMethod(\"isConnected\")");
                    declaredMethod.setAccessible(true);
                    Object objInvoke = declaredMethod2.invoke(bluetoothDevice, new Object[0]);
                    if (objInvoke == null) {
                        throw new NullPointerException("null cannot be cast to non-null type kotlin.Boolean");
                    }
                    if (((Boolean) objInvoke).booleanValue() && isSp20eDeviceName(bluetoothDevice)) {
                        Log.d(TAG, "find connect sp20e : " + bluetoothDevice.getAddress() + ",name:" + bluetoothDevice.getName());
                        arrayList.add(bluetoothDevice);
                    }
                }
            }
        } catch (Exception e2) {
            Log.e(TAG, "getConnectClassicBluetooth failed", e2);
        }
        return arrayList;
    }

    public final String getVersion(String addr) {
        o.f(addr, "addr");
        CharacteristicApiGetResponse characteristic = BleUtils.INSTANCE.readCharacteristic(addr, 10792L);
        if (characteristic == null) {
            return null;
        }
        String str = new String(kotlin.collections.j.f0(characteristic.getData()), Charsets.f9181b);
        a.g0("version: ", str, TAG);
        return str;
    }

    public final void startScan(Context context, ScanCallback scanCallback) {
        o.f(context, "context");
        o.f(scanCallback, "scanCallback");
        Object systemService = context.getSystemService("bluetooth");
        Objects.requireNonNull(systemService, "null cannot be cast to non-null type android.bluetooth.BluetoothManager");
        BluetoothAdapter adapter = ((BluetoothManager) systemService).getAdapter();
        BluetoothLeScanner bluetoothLeScanner = adapter != null ? adapter.getBluetoothLeScanner() : null;
        Log.d(TAG, "startScan,use SCAN_MODE_LOW_LATENCY");
        ScanSettings scanSettingsBuild = new ScanSettings.Builder().setScanMode(2).build();
        if (bluetoothLeScanner != null) {
            bluetoothLeScanner.startScan((List<ScanFilter>) null, scanSettingsBuild, scanCallback);
        }
    }

    public final void stopScan(Context context, ScanCallback scanCallback) {
        o.f(context, "context");
        o.f(scanCallback, "scanCallback");
        Object systemService = context.getSystemService("bluetooth");
        Objects.requireNonNull(systemService, "null cannot be cast to non-null type android.bluetooth.BluetoothManager");
        BluetoothAdapter adapter = ((BluetoothManager) systemService).getAdapter();
        BluetoothLeScanner bluetoothLeScanner = adapter != null ? adapter.getBluetoothLeScanner() : null;
        Log.d(TAG, "stopScan");
        if (bluetoothLeScanner != null) {
            bluetoothLeScanner.stopScan(scanCallback);
        }
    }

    public final void upgradeDfuFail(String msg, Context context, IUpsPlugin.IUpgradeStatusListener listener, DfuProgressListener dfuProgressListener) {
        o.f(msg, "msg");
        o.f(context, "context");
        o.f(listener, "listener");
        if (dfuProgressListener != null) {
            DfuUtils.INSTANCE.dispose(context, dfuProgressListener);
        }
        listener.onFailed(msg);
    }

    /* JADX WARN: Multi-variable type inference failed */
    /* JADX WARN: Type inference failed for: r11v2, types: [T, java.util.concurrent.ScheduledFuture] */
    /* JADX WARN: Type inference failed for: r12v3, types: [android.bluetooth.le.ScanCallback, com.cvte.dss.ups.sp20e.Sp20ePlugin$upgradeFirmware$scanCallback$1] */
    /* JADX WARN: Type inference failed for: r7v0, types: [com.cvte.dss.ups.sp20e.Sp20ePlugin$upgradeFirmware$dfuProgressListener$1] */
    @Override // com.cvte.dss.ups.plugin.IUpsPlugin
    public boolean upgradeFirmware(final Context context, String id, final String path, boolean force, final IUpsPlugin.IUpgradeStatusListener listener) {
        o.f(context, "context");
        o.f(id, "id");
        o.f(path, "path");
        o.f(listener, "listener");
        if (path.length() == 0) {
            listener.onFailed("empty path");
        }
        ScheduledExecutorService scheduledExecutorServiceNewSingleThreadScheduledExecutor = Executors.newSingleThreadScheduledExecutor();
        final d0 d0Var = new d0();
        String strC = j.C(id, "-", ":", false, 4);
        StringBuilder sbF = a.F("UdiDfu");
        String str = String.format("%04d", Arrays.copyOf(new Object[]{Integer.valueOf(new Random().nextInt(InvokeCmd.CMD_PMSCTRL_SET_PMS_WAKEUP_SOURCES))}, 1));
        o.e(str, "format(format, *args)");
        sbF.append(str);
        final String string = sbF.toString();
        BleUtils bleUtils = BleUtils.INSTANCE;
        bleUtils.connectBleDevice(strC);
        bleUtils.setCharacteristicIndication(strC, dfuShortId, true);
        listener.onProcess(0.3f);
        enterBootloader(strC, string);
        listener.onProcess(0.5f);
        final ?? r7 = new DfuProgressListener() { // from class: com.cvte.dss.ups.sp20e.Sp20ePlugin$upgradeFirmware$dfuProgressListener$1
            @Override // no.nordicsemi.android.dfu.DfuProgressListener
            public void onDeviceConnected(String deviceAddress) {
                o.f(deviceAddress, "deviceAddress");
            }

            @Override // no.nordicsemi.android.dfu.DfuProgressListener
            public void onDeviceConnecting(String deviceAddress) {
                o.f(deviceAddress, "deviceAddress");
            }

            @Override // no.nordicsemi.android.dfu.DfuProgressListener
            public void onDeviceDisconnected(String deviceAddress) {
                o.f(deviceAddress, "deviceAddress");
            }

            @Override // no.nordicsemi.android.dfu.DfuProgressListener
            public void onDeviceDisconnecting(String deviceAddress) {
            }

            @Override // no.nordicsemi.android.dfu.DfuProgressListener
            public void onDfuAborted(String deviceAddress) {
                o.f(deviceAddress, "deviceAddress");
                Log.e(Sp20ePlugin.TAG, deviceAddress + "升级失败");
                listener.onFailed("onDfuAborted");
            }

            @Override // no.nordicsemi.android.dfu.DfuProgressListener
            public void onDfuCompleted(String deviceAddress) {
                o.f(deviceAddress, "deviceAddress");
                Log.d(Sp20ePlugin.TAG, deviceAddress + "升级成功");
                DfuUtils.INSTANCE.dispose(context, this);
                listener.onProcess(1.0f);
                listener.onComplete();
            }

            @Override // no.nordicsemi.android.dfu.DfuProgressListener
            public void onDfuProcessStarted(String deviceAddress) {
                o.f(deviceAddress, "deviceAddress");
            }

            @Override // no.nordicsemi.android.dfu.DfuProgressListener
            public void onDfuProcessStarting(String deviceAddress) {
                o.f(deviceAddress, "deviceAddress");
            }

            @Override // no.nordicsemi.android.dfu.DfuProgressListener
            public void onEnablingDfuMode(String deviceAddress) {
                o.f(deviceAddress, "deviceAddress");
            }

            @Override // no.nordicsemi.android.dfu.DfuProgressListener
            public void onError(String deviceAddress, int error, int errorType, String message) {
                o.f(deviceAddress, "deviceAddress");
                o.f(message, "message");
                Log.e(Sp20ePlugin.TAG, deviceAddress + "升级错误" + error + "====" + errorType + "====" + message);
                listener.onFailed(message);
            }

            @Override // no.nordicsemi.android.dfu.DfuProgressListener
            public void onFirmwareValidating(String deviceAddress) {
                o.f(deviceAddress, "deviceAddress");
            }

            @Override // no.nordicsemi.android.dfu.DfuProgressListener
            public void onProgressChanged(String deviceAddress, int percent, float speed, float avgSpeed, int currentPart, int partsTotal) {
                o.f(deviceAddress, "deviceAddress");
                Log.e(Sp20ePlugin.TAG, deviceAddress + "升级进度 " + percent);
                listener.onProcess(this.this$0.normalizeProgress(((float) percent) / 100.0f, 0.0f, 1.0f, 0.5f, 0.9f));
            }
        };
        final ?? r12 = new ScanCallback() { // from class: com.cvte.dss.ups.sp20e.Sp20ePlugin$upgradeFirmware$scanCallback$1
            @Override // android.bluetooth.le.ScanCallback
            public void onScanFailed(int errorCode) {
                super.onScanFailed(errorCode);
                Log.e(Sp20ePlugin.TAG, "onScanFailed : " + errorCode);
            }

            @Override // android.bluetooth.le.ScanCallback
            public void onScanResult(int callbackType, ScanResult result) {
                super.onScanResult(callbackType, result);
                if (result != null) {
                    String str2 = string;
                    Sp20ePlugin sp20ePlugin = this;
                    Context context2 = context;
                    d0<ScheduledFuture<?>> d0Var2 = d0Var;
                    Sp20ePlugin$upgradeFirmware$dfuProgressListener$1 sp20ePlugin$upgradeFirmware$dfuProgressListener$1 = r7;
                    String str3 = path;
                    ScanRecord scanRecord = result.getScanRecord();
                    String deviceName = scanRecord != null ? scanRecord.getDeviceName() : null;
                    if (deviceName == null || deviceName.length() == 0) {
                        StringBuilder sbE = a.E(AbstractJsonLexerKt.BEGIN_OBJ);
                        sbE.append(result.getDevice().getAddress());
                        sbE.append("} device name null,ignore");
                        Log.d(Sp20ePlugin.TAG, sbE.toString());
                        return;
                    }
                    Log.d(Sp20ePlugin.TAG, "onScanResult:  " + result);
                    Log.d(Sp20ePlugin.TAG, "device name:" + deviceName + ",target bootloaderName " + str2);
                    if (o.a(deviceName, str2)) {
                        Log.d(Sp20ePlugin.TAG, str2 + " device found");
                        sp20ePlugin.stopScan(context2, this);
                        ScheduledFuture<?> scheduledFuture = d0Var2.f6165f;
                        if (scheduledFuture != null) {
                            scheduledFuture.cancel(false);
                        }
                        DfuUtils dfuUtils = DfuUtils.INSTANCE;
                        dfuUtils.setDfuProgressListener(context2, sp20ePlugin$upgradeFirmware$dfuProgressListener$1);
                        dfuUtils.startUpdate(context2, result.getDevice().getAddress(), deviceName, str3);
                    }
                }
            }
        };
        startScan(context, r12);
        d0Var.f6165f = scheduledExecutorServiceNewSingleThreadScheduledExecutor.schedule(new Runnable() { // from class: g.b.a.a.c.a
            @Override // java.lang.Runnable
            public final void run() {
                Sp20ePlugin.m1upgradeFirmware$lambda0(this.f3460f, context, r12, listener);
            }
        }, 60L, TimeUnit.SECONDS);
        return true;
    }

    @Override // com.cvte.dss.ups.plugin.IUpsPlugin
    public boolean upgradeFirmware(Context context, String str, String str2, boolean z2, String str3, IUpsPlugin.IUpgradeStatusListener iUpgradeStatusListener) {
        return IUpsPlugin.DefaultImpls.upgradeFirmware(this, context, str, str2, z2, str3, iUpgradeStatusListener);
    }

    @Override // com.cvte.dss.ups.plugin.IUpsPlugin
    public boolean upgradeFirmware(Context context, String path, boolean force, IUpsPlugin.IUpgradeStatusListener listener) {
        o.f(context, "context");
        o.f(path, "path");
        o.f(listener, "listener");
        Log.e(TAG, "not support upgradeFirmware without id");
        listener.onFailed("not support upgradeFirmware without id");
        return false;
    }
}
