package com.brytonsport.active.utils;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.ParcelUuid;
import android.util.Log;
import com.brytonsport.active.base.App;
import com.brytonsport.active.base.EasyBaseFragmentActivity;
import com.brytonsport.active.bleplugin.BbcpUtil;
import com.brytonsport.active.bleplugin.CommandBbcpQueueUtil;
import com.brytonsport.active.bleplugin.CommandQueueUtil;
import com.brytonsport.active.bleplugin.ConstSettingChannel;
import com.brytonsport.active.bleplugin.NewSettingUtil;
import com.brytonsport.active.bleplugin.SampleGattAttributes;
import com.brytonsport.active.db.setting.entity.DeviceManagerEntity;
import com.brytonsport.active.ui.DeviceVo;
import com.mapbox.mapboxsdk.Mapbox;
import com.welie.blessed.BluetoothCentralManager;
import com.welie.blessed.BluetoothCentralManagerCallback;
import com.welie.blessed.BluetoothPeripheral;
import com.welie.blessed.BluetoothPeripheralCallback;
import com.welie.blessed.BondState;
import com.welie.blessed.GattStatus;
import com.welie.blessed.HciStatus;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import pub.devrel.easypermissions.EasyPermissions;

/* loaded from: classes.dex */
public class BleUtil {
    public static final String ACTION_BLUETOOTH_STATE_CHANGE = "com.brytonsport.active.ACTION_BLUETOOTH_STATE_CHANGE";
    public static final String ACTION_BLUETOOTH_STATE_CHANGE_EXTRA_DATA = "com.brytonsport.active.ACTION_BLUETOOTH_STATE_CHANGE_EXTRA_DATA";
    public static final String ACTION_BONDING_FAILED = "com.brytonsport.active.ACTION_BONDING_FAILED";
    public static final String ACTION_BONDING_LOST = "com.brytonsport.active.ACTION_BONDING_LOST";
    public static final String ACTION_BONDING_STARTED = "com.brytonsport.active.ACTION_BONDING_STARTED";
    public static final String ACTION_BONDING_SUCCEEDED = "com.brytonsport.active.ACTION_BONDING_SUCCEEDED";
    public static final String ACTION_CONNECTED_PERIPHERAL = "com.brytonsport.active.ACTION_CONNECTED_PERIPHERAL";
    public static final String ACTION_CONNECTION_FAILED = "com.brytonsport.active.ACTION_CONNECTION_FAILED";
    public static final String ACTION_DISCONNECTED_PERIPHERAL = "com.brytonsport.active.ACTION_DISCONNECTED_PERIPHERAL";
    public static final String ACTION_DISCONNECTED_PERIPHERAL_EXTRA_DATA = "com.brytonsport.active.ACTION_DISCONNECTED_PERIPHERAL_EXTRA_DATA";
    public static final String ACTION_NOTIFICATION_STATE_SETTING_CHANNEL = "com.brytonsport.active.ACTION_NOTIFICATION_STATE_SETTING_CHANNEL";
    public static final String ACTION_SCAN_RECORD = "com.brytonsport.active.ACTION_SCAN_RECORD";
    public static final String ACTION_SCAN_RECORD_EXTRA_DATA = "com.brytonsport.active.ACTION_SCAN_RECORD_EXTRA_DATA";
    public static final String ACTION_SERVICES_DISCOVERED = "com.brytonsport.active.ACTION_SERVICES_DISCOVERED";
    public static final String FILTER_SERVICE_UUID = "00002014-0000-1000-8000-00805f9b34fb";
    private static final String TAG = "BleUtil";
    private static BleUtil sInstance;
    BbcpUtil bbcpUtil;
    private final BluetoothCentralManagerCallback bluetoothCentralManagerCallback;
    BluetoothPeripheralCallback bluetoothPeripheralCallback;
    public BluetoothCentralManager central;
    CommandBbcpQueueUtil commandBbcpQueueUtil;
    CommandQueueUtil commandQueueUtil;
    NewSettingUtil newSettingUtil;
    private Map<String, BluetoothPeripheral> peripheralsMap;
    public boolean hasBlePermission = false;
    private List<DeviceManagerEntity> devicesInDb = new ArrayList();
    int needMtuVal = 153;
    int defaultScanTimeout = 10000;

    public BleUtil() {
        BluetoothCentralManagerCallback bluetoothCentralManagerCallback = new BluetoothCentralManagerCallback() { // from class: com.brytonsport.active.utils.BleUtil.2
            @Override // com.welie.blessed.BluetoothCentralManagerCallback
            public void onDiscoveredPeripheral(BluetoothPeripheral peripheral, ScanResult scanResult) {
                BluetoothDevice device = scanResult.getDevice();
                if (device != null) {
                    boolean z = false;
                    final String address = device.getAddress();
                    for (DeviceManagerEntity deviceManagerEntity : BleUtil.this.devicesInDb) {
                        if (deviceManagerEntity.getMacAddress().equals(address)) {
                            z = true;
                        }
                    }
                    if (z) {
                        return;
                    }
                    if (device.getBondState() == 12) {
                        new Thread(new Runnable() { // from class: com.brytonsport.active.utils.BleUtil.2.1
                            @Override // java.lang.Runnable
                            public void run() {
                                BleUtil.this.unBondDevice(address);
                            }
                        }).start();
                        return;
                    }
                    DeviceVo deviceVo = new DeviceVo();
                    deviceVo.setAddress(address);
                    deviceVo.setName(device.getName());
                    BleUtil.this.broadcastUpdate(BleUtil.ACTION_SCAN_RECORD, deviceVo);
                }
            }

            @Override // com.welie.blessed.BluetoothCentralManagerCallback
            public void onBluetoothAdapterStateChanged(int state) {
                super.onBluetoothAdapterStateChanged(state);
                BleUtil.this.broadcastUpdate(BleUtil.ACTION_BLUETOOTH_STATE_CHANGE, state);
            }

            @Override // com.welie.blessed.BluetoothCentralManagerCallback
            public void onConnectedPeripheral(BluetoothPeripheral peripheral) {
                super.onConnectedPeripheral(peripheral);
                BleUtil.this.broadcastUpdate(BleUtil.ACTION_CONNECTED_PERIPHERAL, peripheral.getAddress());
            }

            @Override // com.welie.blessed.BluetoothCentralManagerCallback
            public void onConnectionFailed(BluetoothPeripheral peripheral, HciStatus status) {
                super.onConnectionFailed(peripheral, status);
                BleUtil.this.broadcastUpdate(BleUtil.ACTION_CONNECTION_FAILED);
            }

            @Override // com.welie.blessed.BluetoothCentralManagerCallback
            public void onDisconnectedPeripheral(BluetoothPeripheral peripheral, HciStatus status) {
                super.onDisconnectedPeripheral(peripheral, status);
                BleUtil.this.broadcastUpdate(BleUtil.ACTION_DISCONNECTED_PERIPHERAL, peripheral.getAddress());
            }
        };
        this.bluetoothCentralManagerCallback = bluetoothCentralManagerCallback;
        this.bluetoothPeripheralCallback = new BluetoothPeripheralCallback() { // from class: com.brytonsport.active.utils.BleUtil.3
            @Override // com.welie.blessed.BluetoothPeripheralCallback
            public void onServicesDiscovered(BluetoothPeripheral peripheral) {
                super.onServicesDiscovered(peripheral);
                String str = BleUtil.TAG;
                Log.d(str, "onServicesDiscovered: CurrentMtu -> " + peripheral.getCurrentMtu());
                BleUtil.this.broadcastUpdate(BleUtil.ACTION_SERVICES_DISCOVERED);
                BleUtil.this.commandBbcpQueueUtil = new CommandBbcpQueueUtil(App.getInstance(), peripheral);
                BleUtil.this.bbcpUtil = new BbcpUtil(App.getInstance(), peripheral, BleUtil.this.commandBbcpQueueUtil);
                BleUtil.this.commandQueueUtil = new CommandQueueUtil(App.getInstance(), peripheral);
                BleUtil.this.newSettingUtil = new NewSettingUtil(App.getInstance(), peripheral, BleUtil.this.commandQueueUtil);
                BleUtil.this.checkDataChannelWriteType(peripheral);
                BleUtil.this.setNotifyOldChannel(peripheral);
                peripheral.requestMtu(BleUtil.this.needMtuVal);
            }

            @Override // com.welie.blessed.BluetoothPeripheralCallback
            public void onCharacteristicUpdate(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, GattStatus status) {
                super.onCharacteristicUpdate(peripheral, value, characteristic, status);
                if (value == null || value.length <= 0) {
                    return;
                }
                String upperCase = characteristic.getUuid().toString().toUpperCase();
                if (upperCase.equals(SampleGattAttributes.CHAR_COMMAND_CHANNEL)) {
                    Log.d(BleUtil.TAG, "onCharacteristicUpdate: Command channel");
                    if (BleUtil.this.bbcpUtil != null) {
                        BleUtil.this.bbcpUtil.onCharacteristicChangedCommandChannel(characteristic);
                    }
                } else if (upperCase.equals(SampleGattAttributes.CHAR_DATA_CHANNEL)) {
                    Log.d(BleUtil.TAG, "onCharacteristicUpdate: Data channel");
                    if (BleUtil.this.bbcpUtil != null) {
                        BleUtil.this.bbcpUtil.onCharacteristicChangedDataChannel(peripheral, characteristic);
                    }
                } else if (!upperCase.equals(SampleGattAttributes.CHAR_SETTING_CHANNEL) || BleUtil.this.newSettingUtil == null) {
                } else {
                    BleUtil.this.newSettingUtil.onCharacteristicChangedSettingChannel(characteristic);
                }
            }

            @Override // com.welie.blessed.BluetoothPeripheralCallback
            public void onCharacteristicWrite(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, GattStatus status) {
                super.onCharacteristicWrite(peripheral, value, characteristic, status);
                if (value == null || value.length <= 0) {
                    return;
                }
                String upperCase = characteristic.getUuid().toString().toUpperCase();
                if (upperCase.equals(SampleGattAttributes.CHAR_COMMAND_CHANNEL)) {
                    BleUtil.this.bbcpUtil.onCharacteristicWriteCommandChannel(characteristic);
                } else if (upperCase.equals(SampleGattAttributes.CHAR_DATA_CHANNEL)) {
                    BleUtil.this.bbcpUtil.onCharacteristicWriteDataChannel(characteristic);
                } else if (upperCase.equals(SampleGattAttributes.CHAR_NOTIFY_CHANNEL)) {
                    BleUtil.this.bbcpUtil.onCharacteristicWriteNotifyChannel(characteristic);
                } else if (upperCase.equals(SampleGattAttributes.CHAR_SETTING_CHANNEL)) {
                    BleUtil.this.newSettingUtil.onCharacteristicWriteSettingChannel(characteristic);
                }
            }

            @Override // com.welie.blessed.BluetoothPeripheralCallback
            public void onNotificationStateUpdate(BluetoothPeripheral peripheral, BluetoothGattCharacteristic characteristic, GattStatus status) {
                super.onNotificationStateUpdate(peripheral, characteristic, status);
                String upperCase = characteristic.getUuid().toString().toUpperCase();
                String str = BleUtil.TAG;
                Log.d(str, "onNotificationStateUpdate: " + upperCase + ", status: " + status);
                if (upperCase.equals(SampleGattAttributes.CHAR_SETTING_CHANNEL) && status.equals(GattStatus.SUCCESS)) {
                    BleUtil.this.broadcastUpdate(BleUtil.ACTION_NOTIFICATION_STATE_SETTING_CHANNEL);
                }
            }

            @Override // com.welie.blessed.BluetoothPeripheralCallback
            public void onBondingStarted(BluetoothPeripheral peripheral) {
                super.onBondingStarted(peripheral);
                Log.d(BleUtil.TAG, "00-onBondingStarted: ");
                BleUtil.this.broadcastUpdate(BleUtil.ACTION_BONDING_STARTED);
            }

            @Override // com.welie.blessed.BluetoothPeripheralCallback
            public void onBondingSucceeded(BluetoothPeripheral peripheral) {
                super.onBondingSucceeded(peripheral);
                Log.d(BleUtil.TAG, "onBondingSucceeded: ");
                BleUtil.this.broadcastUpdate(BleUtil.ACTION_BONDING_SUCCEEDED);
            }

            @Override // com.welie.blessed.BluetoothPeripheralCallback
            public void onBondingFailed(BluetoothPeripheral peripheral) {
                super.onBondingFailed(peripheral);
                Log.d(BleUtil.TAG, "onBondingFailed: ");
                BleUtil.this.broadcastUpdate(BleUtil.ACTION_BONDING_FAILED, peripheral.getAddress(), peripheral.getName());
            }

            @Override // com.welie.blessed.BluetoothPeripheralCallback
            public void onBondLost(BluetoothPeripheral peripheral) {
                super.onBondLost(peripheral);
                Log.d(BleUtil.TAG, "onBondLost: ");
                BleUtil.this.broadcastUpdate(BleUtil.ACTION_BONDING_LOST);
            }

            @Override // com.welie.blessed.BluetoothPeripheralCallback
            public void onMtuChanged(BluetoothPeripheral peripheral, int mtu, GattStatus status) {
                super.onMtuChanged(peripheral, mtu, status);
                String str = BleUtil.TAG;
                Log.d(str, "onMtuChanged: mtu -> " + mtu + ", status -> " + status);
                BleUtil.this.readDeviceInfo();
            }
        };
        Log.d(TAG, "BleUtil: 重新 new BleUtil()");
        if (this.central == null) {
            this.central = new BluetoothCentralManager(App.getInstance(), bluetoothCentralManagerCallback, new Handler(Looper.getMainLooper()));
        }
        if (this.peripheralsMap == null) {
            this.peripheralsMap = new HashMap();
        }
    }

    public static synchronized BleUtil getInstance() {
        BleUtil bleUtil;
        synchronized (BleUtil.class) {
            if (sInstance == null) {
                Log.d(TAG, "getInstance: BleUtil null 重新 new");
                sInstance = new BleUtil();
            }
            bleUtil = sInstance;
        }
        return bleUtil;
    }

    public void startScan() {
        new Handler().postDelayed(new Runnable() { // from class: com.brytonsport.active.utils.BleUtil.1
            @Override // java.lang.Runnable
            public void run() {
                if (BleUtil.this.central != null) {
                    BleUtil.this.central.stopScan();
                }
                Log.d(BleUtil.TAG, "mHandler stopScan");
            }
        }, this.defaultScanTimeout);
        ArrayList arrayList = new ArrayList();
        arrayList.add(new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(FILTER_SERVICE_UUID)).build());
        this.central.scanForPeripheralsUsingFilters(arrayList);
    }

    public boolean isDeviceAlreadyConnected(String macAddress) {
        BluetoothCentralManager bluetoothCentralManager = this.central;
        if (bluetoothCentralManager != null) {
            for (BluetoothPeripheral bluetoothPeripheral : bluetoothCentralManager.getConnectedPeripherals()) {
                if (bluetoothPeripheral.getAddress().equals(macAddress)) {
                    return true;
                }
            }
            return false;
        }
        return false;
    }

    public void createBondOrConnect(String macAddress, boolean isSptBinding) {
        String[] strArr;
        Log.d("susan", "createBondOrConnect");
        Log.d("susan", "central = " + this.central);
        if (this.central == null) {
            Log.e(TAG, "createBondOrConnect got a null central");
            return;
        }
        if (!this.peripheralsMap.containsKey(macAddress) && this.central.getPeripheral(macAddress) != null) {
            this.peripheralsMap.put(macAddress, this.central.getPeripheral(macAddress));
        }
        BluetoothPeripheral bluetoothPeripheral = this.peripheralsMap.get(macAddress);
        if (bluetoothPeripheral == null) {
            Log.e(TAG, "createBondOrConnect got a null peripheral");
            return;
        }
        BondState bondState = BondState.NONE;
        Log.d("susan", "LocationUtils.isSorAbove()");
        if (LocationUtils.isSorAbove()) {
            strArr = new String[]{"android.permission.BLUETOOTH_SCAN", "android.permission.BLUETOOTH_CONNECT"};
        } else {
            strArr = new String[]{"android.permission.ACCESS_COARSE_LOCATION", EasyBaseFragmentActivity.PERMISSION_ACCESS_FINE_LOCATION};
        }
        if (EasyPermissions.hasPermissions(Mapbox.getApplicationContext(), strArr)) {
            BondState bondState2 = bluetoothPeripheral.getBondState();
            this.hasBlePermission = true;
            BluetoothCentralManager bluetoothCentralManager = this.central;
            if (bluetoothCentralManager != null) {
                bluetoothCentralManager.stopScan();
            }
            if (isSptBinding && !bondState2.equals(BondState.BONDED)) {
                this.central.createBond(bluetoothPeripheral, this.bluetoothPeripheralCallback);
            } else {
                this.central.autoConnectPeripheral(bluetoothPeripheral, this.bluetoothPeripheralCallback);
            }
            Log.d("susan", "createBondOrConnect()結束");
            Log.d("susan", "Build.VERSION.SDK_INT = " + Build.VERSION.SDK_INT);
            return;
        }
        this.hasBlePermission = false;
    }

    public void unBondDevice(String macAddress) {
        BluetoothPeripheral bluetoothPeripheral;
        BluetoothCentralManager bluetoothCentralManager = this.central;
        if (bluetoothCentralManager != null) {
            boolean removeBond = bluetoothCentralManager.removeBond(macAddress);
            String str = TAG;
            Log.d(str, "unBondDevice ->" + macAddress + " result:" + removeBond);
        }
        Map<String, BluetoothPeripheral> map = this.peripheralsMap;
        if (map == null || (bluetoothPeripheral = map.get(macAddress)) == null || !bluetoothPeripheral.getBondState().equals(BondState.BONDED)) {
            return;
        }
        this.central.cancelConnection(bluetoothPeripheral);
    }

    public void disConnect(String macAddress) {
        if (this.peripheralsMap.containsKey(macAddress)) {
            this.central.cancelConnection(this.peripheralsMap.get(macAddress));
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void setNotifyOldChannel(BluetoothPeripheral peripheral) {
        peripheral.setNotify(SampleGattAttributes.COMMAND_AND_DATA_SERVICE_UUID, SampleGattAttributes.COMMAND_CHANNEL_UUID, true);
        peripheral.setNotify(SampleGattAttributes.COMMAND_AND_DATA_SERVICE_UUID, SampleGattAttributes.DATA_CHANNEL_UUID, true);
        peripheral.setNotify(SampleGattAttributes.NOTIFY_SERVICE_UUID, SampleGattAttributes.NOTIFY_CHANNEL_UUID, true);
    }

    public void setNotifyNewChannel(BluetoothPeripheral peripheral) {
        peripheral.setNotify(SampleGattAttributes.SETTING_SERVICE_UUID, SampleGattAttributes.SETTING_CHANNEL_UUID, true);
    }

    public void readDeviceInfo() {
        BbcpUtil bbcpUtil = this.bbcpUtil;
        if (bbcpUtil != null) {
            bbcpUtil.readDeviceInfo();
        }
    }

    public void getFileList() {
        BbcpUtil bbcpUtil = this.bbcpUtil;
        if (bbcpUtil != null) {
            bbcpUtil.getFileList();
        }
    }

    public void getFile(int fileId, byte fileType) {
        BbcpUtil bbcpUtil = this.bbcpUtil;
        if (bbcpUtil != null) {
            bbcpUtil.getFile(fileId, fileType);
        }
    }

    public void getFileRange(int fileId, byte fileType, int offset, int chunkSize) {
        BbcpUtil bbcpUtil = this.bbcpUtil;
        if (bbcpUtil != null) {
            bbcpUtil.getFileRange(fileId, fileType, offset, chunkSize);
        }
    }

    public void requestData(int requestType) {
        BbcpUtil bbcpUtil = this.bbcpUtil;
        if (bbcpUtil != null) {
            bbcpUtil.requestData(requestType);
        }
    }

    public void postData(int contentType, byte[] content) {
        BbcpUtil bbcpUtil = this.bbcpUtil;
        if (bbcpUtil != null) {
            bbcpUtil.postData(contentType, content);
        }
    }

    public float getRxProgress() {
        BbcpUtil bbcpUtil = this.bbcpUtil;
        if (bbcpUtil != null) {
            try {
                return bbcpUtil.getRxProgress();
            } catch (Exception e) {
                String str = TAG;
                Log.d(str, "getRxProgress error: " + e.getMessage());
            }
        }
        return 0.0f;
    }

    public void notifyIncomingText() {
        BbcpUtil bbcpUtil = this.bbcpUtil;
        if (bbcpUtil != null) {
            bbcpUtil.notifyIncomingText();
        }
    }

    public void notifyIncomingEmail() {
        BbcpUtil bbcpUtil = this.bbcpUtil;
        if (bbcpUtil != null) {
            bbcpUtil.notifyIncomingEmail();
        }
    }

    public void notifyIncomingCall(String name, String number) {
        BbcpUtil bbcpUtil = this.bbcpUtil;
        if (bbcpUtil != null) {
            bbcpUtil.notifyIncomingCall(name, number);
        }
    }

    public void notifyIncomingCallCancel() {
        BbcpUtil bbcpUtil = this.bbcpUtil;
        if (bbcpUtil != null) {
            bbcpUtil.notifyIncomingCallCancel();
        }
    }

    public void notifyApplication(String name, String title, String content) {
        BbcpUtil bbcpUtil = this.bbcpUtil;
        if (bbcpUtil != null) {
            bbcpUtil.notifyApplication(name, title, content);
        }
    }

    public void postAltitudeValue(int altitudeVal) {
        byte[] array = ByteBuffer.allocate(4).putInt(altitudeVal).array();
        BbcpUtil bbcpUtil = this.bbcpUtil;
        if (bbcpUtil != null) {
            bbcpUtil.postData(1, array);
        }
    }

    public void setNewApp() {
        JSONArray jSONArray = new JSONArray();
        try {
            jSONArray.put(0, ConstSettingChannel.DEVICE_CMD_SET_NEW_APP);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        passSettingCommand(jSONArray);
    }

    public void setUnit(int value) {
        JSONArray jSONArray = new JSONArray();
        jSONArray.put(ConstSettingChannel.DEVICE_CMD_SET_UNIT);
        jSONArray.put(value);
        passSettingCommand(jSONArray);
    }

    public void getLogState() {
        JSONArray jSONArray = new JSONArray();
        jSONArray.put(ConstSettingChannel.DEVICE_CMD_GET_LOG_STATE);
        passSettingCommand(jSONArray);
    }

    public void setPhoneName(String phoneName) {
        JSONArray jSONArray = new JSONArray();
        jSONArray.put(ConstSettingChannel.DEVICE_CMD_SET_PHONE_NAME);
        jSONArray.put(phoneName);
        passSettingCommand(jSONArray);
    }

    public void setDevVoiceLang(String langName) {
        JSONArray jSONArray = new JSONArray();
        jSONArray.put(ConstSettingChannel.DEVICE_CMD_SET_DEV_VOICE_LANG);
        jSONArray.put(langName);
        passSettingCommand(jSONArray);
    }

    public void getServerEE() {
        JSONArray jSONArray = new JSONArray();
        jSONArray.put(ConstSettingChannel.DEVICE_CMD_GET_SERVER_EE);
        passSettingCommand(jSONArray);
    }

    public void setDevNotify(int seconds) {
        JSONArray jSONArray = new JSONArray();
        jSONArray.put(ConstSettingChannel.DEVICE_CMD_SET_DEV_NOTIFY);
        jSONArray.put(seconds);
        passSettingCommand(jSONArray);
    }

    public void setBtNotifyDev(int fileId) {
        JSONArray jSONArray = new JSONArray();
        jSONArray.put(ConstSettingChannel.DEVICE_CMD_SET_BT_NOTIFY_DEV);
        jSONArray.put(fileId);
        passSettingCommand(jSONArray);
    }

    public void setLatLon(int value, double lat, double lng) {
        JSONArray jSONArray = new JSONArray();
        jSONArray.put(ConstSettingChannel.DEVICE_CMD_SET_LAT_LON);
        jSONArray.put(value);
        JSONObject jSONObject = new JSONObject();
        try {
            jSONObject.put("latitude", lat);
            jSONObject.put("longitude", lng);
            jSONArray.put(jSONObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        passSettingCommand(jSONArray);
    }

    public void setVoiceResult(String voiceResult) {
        JSONArray jSONArray = new JSONArray();
        jSONArray.put(ConstSettingChannel.DEVICE_CMD_SET_VOICE_RESULT);
        jSONArray.put(voiceResult);
        passSettingCommand(jSONArray);
    }

    public void setSpeechToText(int value) {
        JSONArray jSONArray = new JSONArray();
        jSONArray.put(ConstSettingChannel.DEVICE_CMD_SET_SPEECH_TO_TEXT);
        jSONArray.put(value);
        passSettingCommand(jSONArray);
    }

    public void setPlantrip(int state) {
        JSONArray jSONArray = new JSONArray();
        jSONArray.put(ConstSettingChannel.DEVICE_CMD_SET_PLAN_TRIP);
        jSONArray.put(state);
        passSettingCommand(jSONArray);
    }

    public void setPlantripName(String planTripName) {
        JSONArray jSONArray = new JSONArray();
        jSONArray.put(ConstSettingChannel.DEVICE_CMD_SET_PLAN_TRIP_NAME);
        jSONArray.put(planTripName);
        passSettingCommand(jSONArray);
    }

    public void setSurpriseMeDistance(int state) {
        JSONArray jSONArray = new JSONArray();
        jSONArray.put(ConstSettingChannel.DEVICE_CMD_SET_SURPRISE_ME_DISTANCE);
        jSONArray.put(state);
        passSettingCommand(jSONArray);
    }

    public void setLiveTrackingSwitch(int interval) {
        JSONArray jSONArray = new JSONArray();
        jSONArray.put(ConstSettingChannel.DEVICE_CMD_SET_LIVE_TRACKING_SWITCH_INTERVAL);
        jSONArray.put(1);
        jSONArray.put(interval);
        passSettingCommand(jSONArray);
    }

    public void setLiveTrackingSwitchStop(int enable) {
        JSONArray jSONArray = new JSONArray();
        jSONArray.put(ConstSettingChannel.DEVICE_CMD_SET_LIVE_TRACKING_SWITCH_INTERVAL);
        jSONArray.put(enable);
        jSONArray.put(0);
        passSettingCommand(jSONArray);
    }

    public void passSettingCommand(JSONArray paramArray) {
        NewSettingUtil newSettingUtil = this.newSettingUtil;
        if (newSettingUtil != null) {
            newSettingUtil.settingCommand(paramArray);
        }
    }

    public JSONObject getNewAppSupportForService(String supportKey) {
        NewSettingUtil newSettingUtil = this.newSettingUtil;
        if (newSettingUtil != null) {
            return newSettingUtil.getNewAppSupportForService(supportKey);
        }
        return null;
    }

    public JSONObject getAppSupportFeature() {
        JSONObject jSONObject = new JSONObject();
        try {
            jSONObject.put("surprise_me", true);
            jSONObject.put("log_compress", true);
            jSONObject.put("group_ride", true);
            jSONObject.put("live_tracking", true);
            jSONObject.put("android_notification", true);
            jSONObject.put("native_app", true);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jSONObject;
    }

    public void setAppSupportFun(JSONObject appSupFeatureObj) {
        if (appSupFeatureObj != null) {
            Iterator<String> keys = appSupFeatureObj.keys();
            String str = "";
            while (true) {
                if (!keys.hasNext()) {
                    break;
                }
                try {
                    boolean z = appSupFeatureObj.getBoolean(keys.next());
                    StringBuilder sb = new StringBuilder();
                    sb.append(str);
                    sb.append(String.valueOf(z ? 1 : 0));
                    str = sb.toString();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            int ceil = (int) Math.ceil(str.length() / 4.0d);
            for (int i = 0; i < ceil; i++) {
                str = str + 0;
            }
            String str2 = TAG;
            Log.d(str2, "setAppSupportFun: appSupFeature = " + str);
            StringBuilder sb2 = new StringBuilder(str);
            sb2.reverse();
            String sb3 = sb2.toString();
            Log.d(str2, "setAppSupportFun: reverseStr = " + sb3);
            int parseInt = Integer.parseInt(sb3, 2);
            Log.d(str2, "setAppSupportFun: appSupFeatureNum = " + parseInt);
            setAppFunSupportCmd(parseInt);
        }
    }

    private void setAppFunSupportCmd(int support) {
        JSONArray jSONArray = new JSONArray();
        jSONArray.put(ConstSettingChannel.DEVICE_CMD_SET_APP_FUN_SUPPORT);
        jSONArray.put(support);
        passSettingCommand(jSONArray);
    }

    public void setBbcpRxTx(JSONObject jsonObject) {
        if (jsonObject != null) {
            try {
                config(jsonObject.getInt("payloadSize"), jsonObject.getInt("handShakeSize"), 39600, 6930);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    public void setDevicesInDb(List<DeviceManagerEntity> devices) {
        this.devicesInDb = devices;
    }

    public void config(int payload, int flowCtrl, int chunkSizeRx, int chunkSizeTx) {
        BbcpUtil bbcpUtil = this.bbcpUtil;
        if (bbcpUtil != null) {
            bbcpUtil.setConfig(payload, flowCtrl, chunkSizeRx, chunkSizeTx);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void broadcastUpdate(final String action, int state) {
        Intent intent = new Intent(action);
        intent.putExtra(ACTION_BLUETOOTH_STATE_CHANGE_EXTRA_DATA, state);
        App.getInstance().sendBroadcast(intent);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void broadcastUpdate(final String action) {
        App.getInstance().sendBroadcast(new Intent(action));
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void broadcastUpdate(final String action, DeviceVo deviceVo) {
        Intent intent = new Intent(action);
        intent.putExtra(ACTION_SCAN_RECORD_EXTRA_DATA, deviceVo);
        App.getInstance().sendBroadcast(intent);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void broadcastUpdate(final String action, String macAddress) {
        Intent intent = new Intent(action);
        intent.putExtra(ACTION_DISCONNECTED_PERIPHERAL_EXTRA_DATA, macAddress);
        App.getInstance().sendBroadcast(intent);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void broadcastUpdate(final String action, String macAddress, String deviceName) {
        Intent intent = new Intent(action);
        intent.putExtra("macAddress", macAddress);
        intent.putExtra("deviceName", deviceName);
        App.getInstance().sendBroadcast(intent);
    }

    public void checkDataChannelWriteType(BluetoothPeripheral peripheral) {
        BluetoothGattCharacteristic characteristic = peripheral.getCharacteristic(SampleGattAttributes.COMMAND_AND_DATA_SERVICE_UUID, SampleGattAttributes.DATA_CHANNEL_UUID);
        if (characteristic != null) {
            int isCharacteristicWriteNoResponse = isCharacteristicWriteNoResponse(characteristic);
            BbcpUtil bbcpUtil = this.bbcpUtil;
            if (bbcpUtil != null) {
                bbcpUtil.setDataChannelWriteType(isCharacteristicWriteNoResponse);
            }
        }
    }

    public int isCharacteristicWriteNoResponse(BluetoothGattCharacteristic c) {
        return (c.getProperties() & 4) != 0 ? 1 : 2;
    }

    public void resetBleUtil() {
        Log.d(TAG, "resetBleUtil: 斷線清除 BleUtil 相關資料");
        BluetoothCentralManager bluetoothCentralManager = this.central;
        if (bluetoothCentralManager != null) {
            bluetoothCentralManager.close();
        }
        this.central = null;
        this.peripheralsMap = null;
        sInstance = null;
        this.bbcpUtil = null;
        this.commandBbcpQueueUtil = null;
        this.newSettingUtil = null;
        this.commandQueueUtil = null;
        SampleGattAttributes.isGetFileRangePhase2 = true;
    }
}