package com.brytonsport.active.bleplugin;

import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import com.brytonsport.active.base.App;
import com.garmin.fit.Fit;
import com.github.mjdev.libaums.fs.UsbFile;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.mapbox.android.accounts.v1.MapboxAccounts;
import com.quickblox.core.ConstsInternal;
import com.welie.blessed.BluetoothPeripheral;
import com.welie.blessed.WriteType;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.json.JSONException;
import org.json.JSONObject;
import org.oscim.layers.tile.MapTile;

/* loaded from: classes.dex */
public class BbcpUtil {
  private static long CMD_CHECK_DEVICE_BUSY_TIMEOUT = 5000;
  private static final String TAG = "BbcpUtil";
  int cmdSeqNo;
  private CommandBbcpQueueUtil commandQueueUtil;
  byte[][] fileArr;
  BluetoothGatt mBluetoothGatt;
  Context mContext;
  Handler mMainHandler1;
  Handler mMainHandler2;
  BluetoothPeripheral mPeripheral;
  byte[] onChangeDataByteArray;
  List onChangeDataByteList;
  Map<Integer, byte[]> onChangeDataMap;
  byte[] phase2GetFileRangeTotalArray;
  private ConcurrentLinkedQueue<BLECommandBbcp> commandQueue = new ConcurrentLinkedQueue<>();
  private boolean bleProcessing = false;
  int dataChannelWriteType = 1;
  int payload = 20;
  int flowCtrl = 10;
  int chunkSizeRx = 990;
  int chunkSizeTx = 6930;
  int OLD_DEVICE_PAYLOAD_SIZE = 18;
  int NEW_DEVICE_PAYLOAD_SIZE = 148;
  int CMD_17_CHUNK_SIZE = 39600;
  int DOWNLOAD_SIZE = SampleGattAttributes.DOWNLOAD_SIZE;
  int PAYLOAD_SIZE = 148;
  int dataPayload = 18;
  int onChangeDataTotalSize = 0;
  int onChangeDataLastFragSize = 0;
  int onChangeDataFragNum = 0;
  int onChangeDataCrcCount = 0;
  int nowOnChangeDataCommandId = 0;
  int receiveDataSizeCount = 0;
  int cmd17FileId = 0;
  String cmd17FileName = "";
  byte cmd17FileType = 0;
  boolean cmd17FirstGetFileSize = true;
  int getFileRangeIndex = 0;
  int getFileRangeOffset = 0;
  int getFileRangeChunkSize = 0;
  int fileRangeDataSize = 0;
  int fileRangeReceiveDataSizeCount = 0;
  int fileRangeCount = 0;
  int fileRangeLastChunkSize = 0;
  int cmd16ContentType = 0;
  byte[] cmd16ContentArray = null;
  boolean openSysIniFlag = false;
  int decideSystemIniIndex = 0;
  int decideSystemIniOffset = 0;
  int systemIniFragSize = 0;
  int systemIniLastDataSize = 0;
  int sendFileCrcCount = 0;
  int sendFileOriginDataSize = 0;
  int sendPlanTripIndex = 0;
  boolean isCmdResponse = false;

  public BbcpUtil(Context mContext) {
    this.cmdSeqNo = 0;
    this.mContext = mContext;
    this.cmdSeqNo = 0;
    queueCleanup();
  }

  public BbcpUtil(Context mContext, BluetoothGatt gatt) {
    this.cmdSeqNo = 0;
    this.mContext = mContext;
    this.mBluetoothGatt = gatt;
    this.cmdSeqNo = 0;
    queueCleanup();
  }

  public BbcpUtil(Context mContext, BluetoothPeripheral peripheral, CommandBbcpQueueUtil mCommandQueueUtil) {
    this.cmdSeqNo = 0;
    this.mContext = mContext;
    this.mPeripheral = peripheral;
    this.cmdSeqNo = 0;
    this.commandQueueUtil = mCommandQueueUtil;
    mCommandQueueUtil.queueCleanup();
  }

  public void disconnect() {
    if (this.mBluetoothGatt != null) {
      refreshGatt();
      this.mBluetoothGatt.disconnect();
      this.mBluetoothGatt.close();
      this.mBluetoothGatt = null;
    }
  }

  public float getRxProgress() {
    float f;
    int i;
    int i2 = this.receiveDataSizeCount;
    if (DeviceInfo.ftp) {
      int i3 = this.fileRangeDataSize;
      if (i3 != 0 && (i = this.fileRangeReceiveDataSizeCount) != 0) {
        f = (i * 100.0f) / i3;
        String str = TAG;
        Log.d(str, "注意看! getRxProgress(getFileRange): " + this.fileRangeReceiveDataSizeCount + UsbFile.separator + this.fileRangeDataSize + ", percent: " + f);
      }
      f = 0.0f;
    } else {
      int i4 = this.onChangeDataTotalSize;
      if (i4 != 0) {
        f = (i2 * 100.0f) / i4;
        String str2 = TAG;
        Log.d(str2, "注意看! getRxProgress(getFile): " + i2 + UsbFile.separator + this.onChangeDataTotalSize + ", percent: " + f);
      }
      f = 0.0f;
    }
    if (f > 100.0f) {
      return 100.0f;
    }
    return f;
  }

  public void setDataChannelWriteType(int writeType) {
    this.dataChannelWriteType = writeType;
    String str = TAG;
    StringBuilder sb = new StringBuilder();
    sb.append("setDataChannelWriteType() -> writeType = ");
    sb.append(this.dataChannelWriteType == 2 ? "WRITE_TYPE_DEFAULT" : "WRITE_TYPE_NO_RESPONSE");
    Log.d(str, sb.toString());
  }

  public void setConfig(int payload, int flowCtrl, int chunkSizeRx, int chunkSizeTx) {
    this.payload = payload;
    this.flowCtrl = flowCtrl;
    this.chunkSizeRx = chunkSizeRx;
    this.chunkSizeTx = chunkSizeTx;
    String str = TAG;
    Log.d(str, "setConfig() -> payload = " + payload + ", flowCtrl = " + flowCtrl + ", chunkSizeRx = " + chunkSizeRx + ", chunkSizeTx = " + chunkSizeTx);
    int i = payload + (-2);
    this.OLD_DEVICE_PAYLOAD_SIZE = i;
    this.NEW_DEVICE_PAYLOAD_SIZE = i;
    this.CMD_17_CHUNK_SIZE = chunkSizeRx;
    this.DOWNLOAD_SIZE = chunkSizeTx + (-8);
    this.PAYLOAD_SIZE = i;
  }

  private void progressCmdSeq() {
    int i = this.cmdSeqNo + 1;
    this.cmdSeqNo = i;
    if (i % 8 == 0) {
      i = 0;
    }
    this.cmdSeqNo = i;
  }

  public void readDeviceInfo() {
    progressCmdSeq();
    queueWrite(SampleGattAttributes.COMMAND_AND_DATA_SERVICE_UUID, SampleGattAttributes.COMMAND_CHANNEL_UUID, DataUtil.getInstance().requestDataCmd(6, this.cmdSeqNo), 2);
  }

  public void getFileList() {
    progressCmdSeq();
    queueWrite(SampleGattAttributes.COMMAND_AND_DATA_SERVICE_UUID, SampleGattAttributes.COMMAND_CHANNEL_UUID, DataUtil.getInstance().requestDataCmd(11, this.cmdSeqNo), 2);
  }

  public void getFile(int fileId, byte fileType) {
    progressCmdSeq();
    String str = TAG;
    Log.d(str, "enter getFile() -> fileId = " + fileId + ", fileType = " + ((int) fileType));
    queueWrite(SampleGattAttributes.COMMAND_AND_DATA_SERVICE_UUID, SampleGattAttributes.COMMAND_CHANNEL_UUID, DataUtil.getInstance().requestDataCmd(12, this.cmdSeqNo, fileType, fileId, ""), 2);
  }

  public void getFileRange(int fileId, byte fileType, int offset, int chunkSize) {
    if (offset == 0 && chunkSize == 4) {
      this.cmd17FirstGetFileSize = true;
      this.getFileRangeIndex = 0;
      this.getFileRangeOffset = 0;
    }
    this.cmd17FileId = fileId;
    progressCmdSeq();
    String str = TAG;
    Log.d(str, "enter getFileRange() -> fileId = " + fileId + ", fileType = " + ((int) fileType) + ", offset = " + offset + ", chunkSize = " + chunkSize);
    queueWrite(SampleGattAttributes.COMMAND_AND_DATA_SERVICE_UUID, SampleGattAttributes.COMMAND_CHANNEL_UUID, DataUtil.getInstance().requestDataCmd(17, this.cmdSeqNo, fileType, fileId, offset, chunkSize, ""), 2);
  }

  public void requestData() {
    requestData(0);
  }

  public void requestData(int requestType) {
    progressCmdSeq();
    queueWrite(SampleGattAttributes.COMMAND_AND_DATA_SERVICE_UUID, SampleGattAttributes.COMMAND_CHANNEL_UUID, DataUtil.getInstance().requestDataCmd(15, this.cmdSeqNo, requestType), 2);
  }

  public void postData(int contentType, byte[] content) {
    this.cmd16ContentType = contentType;
    this.cmd16ContentArray = content;
    progressCmdSeq();
    queueWrite(SampleGattAttributes.COMMAND_AND_DATA_SERVICE_UUID, SampleGattAttributes.COMMAND_CHANNEL_UUID, DataUtil.getInstance().requestDataCmd(16, this.cmdSeqNo, contentType), 2);
  }

  public void notifyIncomingText() {
    progressCmdSeq();
    queueWrite(SampleGattAttributes.NOTIFY_SERVICE_UUID, SampleGattAttributes.NOTIFY_CHANNEL_UUID, DataUtil.getInstance().smartNotifyText(this.cmdSeqNo), 2);
  }

  public void notifyIncomingEmail() {
    progressCmdSeq();
    queueWrite(SampleGattAttributes.NOTIFY_SERVICE_UUID, SampleGattAttributes.NOTIFY_CHANNEL_UUID, DataUtil.getInstance().smartNotifyMail(this.cmdSeqNo), 2);
  }

  public void notifyIncomingCall(String name, String number) {
    progressCmdSeq();
    queueWrite(SampleGattAttributes.NOTIFY_SERVICE_UUID, SampleGattAttributes.NOTIFY_CHANNEL_UUID, DataUtil.getInstance().smartNotifyPhone(this.cmdSeqNo, 0, name), 2);
    progressCmdSeq();
    queueWrite(SampleGattAttributes.NOTIFY_SERVICE_UUID, SampleGattAttributes.NOTIFY_CHANNEL_UUID, DataUtil.getInstance().smartNotifyPhone(this.cmdSeqNo, 1, number), 2);
  }

  public void notifyIncomingCallCancel() {
    progressCmdSeq();
    queueWrite(SampleGattAttributes.NOTIFY_SERVICE_UUID, SampleGattAttributes.NOTIFY_CHANNEL_UUID, DataUtil.getInstance().smartNotifyPhone(this.cmdSeqNo, 2, ""), 2);
  }

  public void notifyApplication(String name, String title, String content) {
    progressCmdSeq();
    queueWrite(SampleGattAttributes.NOTIFY_SERVICE_UUID, SampleGattAttributes.NOTIFY_CHANNEL_UUID, DataUtil.getInstance().smartNotifyApp(this.cmdSeqNo, 0, name), 2);
    progressCmdSeq();
    queueWrite(SampleGattAttributes.NOTIFY_SERVICE_UUID, SampleGattAttributes.NOTIFY_CHANNEL_UUID, DataUtil.getInstance().smartNotifyApp(this.cmdSeqNo, 1, title), 2);
    progressCmdSeq();
    queueWrite(SampleGattAttributes.NOTIFY_SERVICE_UUID, SampleGattAttributes.NOTIFY_CHANNEL_UUID, DataUtil.getInstance().smartNotifyApp(this.cmdSeqNo, 2, content), 2);
  }

  public void checkResponse() {
    String str = TAG;
    Log.d(str, "enter checkResponse()");
    synchronized (this) {
      Log.d(str, "enter checkResponse() -> synchronized");
      Handler handler = new Handler(Looper.getMainLooper());
      this.mMainHandler2 = handler;
      handler.postDelayed(new Runnable() { // from class: com.brytonsport.active.bleplugin.BbcpUtil.1
        @Override // java.lang.Runnable
        public void run() {
          BbcpUtil.this.waitForCmdResponse();
        }
      }, 6000L);
    }
  }

  public void waitForCmdResponse() {
    String str = TAG;
    Log.d(str, "enter waitForCmdResponse()");
    synchronized (this) {
      Log.d(str, "enter waitForCmdResponse() -> synchronized");
      this.isCmdResponse = true;
    }
  }

  public void setCommandTimeout(final int cmdId) {
    String str = TAG;
    Log.d(str, "Command " + cmdId + " enter setCommandTimeout");
    synchronized (this) {
      this.isCmdResponse = false;
      Log.d(str, "Command " + cmdId + " enter setCommandTimeout");
      Handler handler = new Handler(Looper.getMainLooper());
      this.mMainHandler1 = handler;
      handler.postDelayed(new Runnable() { // from class: com.brytonsport.active.bleplugin.BbcpUtil.2
        @Override // java.lang.Runnable
        public void run() {
          if (!BbcpUtil.this.isCmdResponse) {
            String str2 = BbcpUtil.TAG;
            Log.d(str2, "Command " + cmdId + " 還沒 Response");
            BbcpUtil.this.broadcastUpdate(SampleGattAttributes.ACTION_TIMEOUT_ERROR, cmdId, "timeout");
            return;
          }
          String str3 = BbcpUtil.TAG;
          Log.d(str3, "Command " + cmdId + " 已經 Response");
        }
      }, 5000L);
    }
  }

  public void onCharacteristicWriteCommandChannel(BluetoothGattCharacteristic characteristic) {
    byte[] value = characteristic.getValue();
    if (value != null && value.length > 0) {
      int unsignedByte = ParserUtil.getUnsignedByte(value[0]);
      int intValue = ParserUtil.getBitByByte(value[1], 0, 2).intValue();
      int intValue2 = ParserUtil.getBitByByte(value[1], 3, 5).intValue();
      int intValue3 = ParserUtil.getBitByByte(value[1], 6, 7).intValue();
      String str = "";
      for (byte b : value) {
        str = str + ParserUtil.getUnsignedByte(b) + ", ";
      }
      Log.d(TAG, "onCharacteristicWriteCommandChannel data.length = " + value.length + ", " + ("cmdId = " + unsignedByte + ", [type = " + intValue + ", seqNo = " + intValue2 + ", rsv = " + intValue3 + "], (原始) -> " + str));
      if (intValue == 0) {
        if (unsignedByte == 17) {
          if (!ParserUtil.fitNameToFormatName(value).equals(this.cmd17FileName)) {
            broadcastUpdate(SampleGattAttributes.ACTION_GET_FILE_RANGE_START_TIME, new Date().getTime());
          }
          if (SampleGattAttributes.isGetFileRangePhase2) {
            this.cmd17FileName = ParserUtil.fitNameToFormatName(value);
            this.cmd17FileType = value[6];
          }
        }
      } else if (intValue == 2 && unsignedByte == 16) {
        this.decideSystemIniIndex = 0;
        prepareIniOrAltitude(intValue2);
      }
    }
    this.commandQueueUtil.commandCompleted();
  }

  public void onCharacteristicWriteDataChannel(BluetoothGattCharacteristic characteristic) {
    this.commandQueueUtil.commandCompleted();
  }

  public void onCharacteristicWriteNotifyChannel(BluetoothGattCharacteristic characteristic) {
    broadcastUpdate(SampleGattAttributes.ACTION_ANDROID_NOTIFY, "OK");
    this.commandQueueUtil.commandCompleted();
  }

  public void onCharacteristicChangedCommandChannel(BluetoothGattCharacteristic characteristic) {
    byte[] value = characteristic.getValue();
    if (value == null || value.length <= 0) {
      return;
    }
    int unsignedByte = ParserUtil.getUnsignedByte(value[0]);
    int intValue = ParserUtil.getBitByByte(value[1], 0, 2).intValue();
    int intValue2 = ParserUtil.getBitByByte(value[1], 3, 5).intValue();
    int intValue3 = ParserUtil.getBitByByte(value[1], 6, 7).intValue();
    if (intValue != 1) {
      if (intValue == 2) {
        int byte2Int = ParserUtil.byte2Int(value[2]);
        if (unsignedByte == 16) {
          if (byte2Int == 6) {
            Log.d(TAG, "CMD_SEND_FILE_TO_DEVICE ACTION_CODE_CONTINUE ------////-----");
            this.openSysIniFlag = true;
            prepareIniOrAltitude(intValue2);
            return;
          } else if (byte2Int == 3) {
            broadcastUpdate(SampleGattAttributes.ACTION_POST_DATA, this.cmd16ContentType, "OK");
            return;
          } else if (byte2Int == 1) {
            broadcastUpdate(SampleGattAttributes.ACTION_CRC_ERROR, unsignedByte);
            return;
          } else {
            broadcastUpdate(SampleGattAttributes.ACTION_ACTION_CODE_ERROR, unsignedByte, "action code = " + byte2Int + " error");
            return;
          }
        }
        return;
      }
      return;
    }
    int unsignedByte2 = ParserUtil.getUnsignedByte(value[2]);
    if (unsignedByte2 != 2) {
      if (unsignedByte2 == 6) {
        if (unsignedByte == 11) {
          broadcastUpdate(SampleGattAttributes.ACTION_GET_FILE_LIST, new byte[0]);
          return;
        }
        return;
      } else if (unsignedByte == 17) {
        JSONObject jSONObject = new JSONObject();
        try {
          jSONObject.put(NotificationCompat.CATEGORY_MESSAGE, SampleGattAttributes.statusCodeMsg.get(Integer.valueOf(unsignedByte2)));
          jSONObject.put(FirebaseAnalytics.Param.METHOD, "getFileRange");
          jSONObject.put(ConstsInternal.ERROR_CODE_MSG, unsignedByte2);
        } catch (JSONException e) {
          e.printStackTrace();
        }
        broadcastUpdate(SampleGattAttributes.ACTION_STATUS_CODE_ERROR, unsignedByte, jSONObject.toString());
        return;
      } else {
        broadcastUpdate(SampleGattAttributes.ACTION_STATUS_CODE_ERROR, unsignedByte, "status code = " + unsignedByte2 + " -> " + SampleGattAttributes.statusCodeMsg.get(Integer.valueOf(unsignedByte2)));
        return;
      }
    }
    byte[] bArr = null;
    if (unsignedByte != 6) {
      if (unsignedByte == 8) {
        broadcastUpdate(SampleGattAttributes.ACTION_SEND_USER_ADDRESS, "OK");
      } else if (unsignedByte != 11) {
        if (unsignedByte != 12) {
          switch (unsignedByte) {
            case 15:
              break;
            case 16:
            case 17:
              break;
            default:
              String str = "";
              for (byte b : value) {
                str = str + ParserUtil.getUnsignedByte(b) + ", ";
              }
              broadcastUpdate(SampleGattAttributes.ACTION_RUN_RESULT, "cmdId = " + unsignedByte + ", [type = " + intValue + ", seqNo = " + intValue2 + ", rsv = " + intValue3 + "], statusCode = " + unsignedByte2 + ", (原始) -> " + str);
              break;
          }
        }
        bArr = generateActionData(unsignedByte, intValue2, 5);
      }
      if (bArr != null || bArr.length <= 0) {
      }
      Log.d(TAG, "onCharacteristicChangedCommandChannel 準備 write actionData = " + bArr.length);
      queueWrite(SampleGattAttributes.COMMAND_AND_DATA_SERVICE_UUID, SampleGattAttributes.COMMAND_CHANNEL_UUID, bArr, 2);
      return;
    }
    bArr = generateActionData(unsignedByte, intValue2, 3);
    if (bArr != null) {
    }
  }

  public void onCharacteristicChangedDataChannel(BluetoothPeripheral peripheral, BluetoothGattCharacteristic characteristic) {
    byte[] value = characteristic.getValue();
    if (value == null || value.length <= 0) {
      return;
    }
    int intValue = new BigInteger(new byte[]{value[0], value[1]}).intValue();
    String str = "";
    for (byte b : value) {
      str = str + ParserUtil.getUnsignedByte(b) + ", ";
    }
    if (intValue == 0) {
      String str2 = TAG;
      Log.d(str2, "onCharacteristicChanged (data channel) flowCtrl = " + this.flowCtrl);
      this.onChangeDataCrcCount = 0;
      this.onChangeDataFragNum = ByteBuffer.wrap(new byte[]{value[2], value[3]}).getShort();
      this.onChangeDataLastFragSize = ParserUtil.getUnsignedByte(value[4]);
      Log.d(str2, "onCharacteristicChanged (data channel) 呼叫 onChangeDataFragNum = " + this.onChangeDataFragNum + ", onChangeDataLastFragSize = " + this.onChangeDataLastFragSize);
      int unsignedByte = ParserUtil.getUnsignedByte(value[5]);
      this.nowOnChangeDataCommandId = unsignedByte;
      this.onChangeDataByteList = new ArrayList();
      this.onChangeDataMap = new TreeMap();
      this.receiveDataSizeCount = 0;
      if (this.onChangeDataFragNum <= 0) {
        if (unsignedByte == 15) {
          broadcastUpdate(SampleGattAttributes.ACTION_REQUEST_DATA, new byte[0]);
        } else {
          broadcastUpdate(SampleGattAttributes.ACTION_EMPTY_DATA, unsignedByte);
        }
      } else if (unsignedByte == 6) {
        ParserUtil.byte2Int(value[6]);
        int i = ((this.onChangeDataFragNum - 1) * this.dataPayload) + this.onChangeDataLastFragSize;
        this.onChangeDataByteArray = new byte[i];
        this.onChangeDataTotalSize = i;
      } else if (unsignedByte == 11) {
        byte[] bArr = {value[7], value[8]};
        ParserUtil.byte2Int(value[6]);
        int intValue2 = new BigInteger(bArr).intValue();
        int i2 = this.dataPayload;
        this.onChangeDataByteArray = new byte[i2 * 2 * intValue2];
        this.onChangeDataTotalSize = intValue2 * i2 * 2;
      } else if (unsignedByte == 15) {
        byte[] bArr2 = {value[7], value[8]};
        ParserUtil.byte2Int(value[6]);
        new BigInteger(bArr2).intValue();
        int i3 = ((this.onChangeDataFragNum - 1) * this.dataPayload) + this.onChangeDataLastFragSize;
        this.onChangeDataByteArray = new byte[i3];
        this.onChangeDataTotalSize = i3;
      } else if (unsignedByte == 12) {
        ParserUtil.byte2Int(value[6]);
        ParserUtil.byte2Int(value[7]);
        int i4 = ((this.onChangeDataFragNum - 1) * this.dataPayload) + this.onChangeDataLastFragSize;
        this.onChangeDataByteArray = new byte[i4];
        this.onChangeDataTotalSize = i4;
        Log.d(str2, "注意看 Start fragment(CMD_GET_LOG_FILE): receiveDataSizeCount -> " + this.receiveDataSizeCount + ", onChangeDataTotalSize -> " + this.onChangeDataTotalSize);
      } else if (unsignedByte == 17) {
        ParserUtil.byte2Int(value[6]);
        ParserUtil.byte2Int(value[7]);
        int i5 = ((this.onChangeDataFragNum - 1) * this.NEW_DEVICE_PAYLOAD_SIZE) + this.onChangeDataLastFragSize;
        this.onChangeDataByteArray = new byte[i5];
        this.onChangeDataTotalSize = i5;
        if (SampleGattAttributes.isGetFileRangePhase2 && this.cmd17FirstGetFileSize) {
          int i6 = ((this.onChangeDataFragNum - 1) * this.NEW_DEVICE_PAYLOAD_SIZE) + this.onChangeDataLastFragSize;
          this.onChangeDataByteArray = new byte[i6];
          this.onChangeDataTotalSize = i6;
          Log.d(str2, "注意看 Start fragment(CMD_GET_FILE_RANGE): receiveDataSizeCount -> " + this.receiveDataSizeCount + ", onChangeDataTotalSize -> " + this.onChangeDataTotalSize);
        }
      }
    } else if (intValue > this.onChangeDataFragNum) {
      if (value.length != 7) {
        broadcastUpdate(SampleGattAttributes.ACTION_EMPTY_DATA, this.nowOnChangeDataCommandId);
        return;
      }
      ParserUtil.byte2Int(value[2]);
      byte[] bArr3 = new byte[4];
      for (int i7 = 3; i7 < value.length; i7++) {
        bArr3[i7 - 3] = value[i7];
      }
      if (new BigInteger(bArr3).intValue() != this.onChangeDataCrcCount) {
        int i8 = this.nowOnChangeDataCommandId;
        if (i8 == 17) {
          int i9 = this.getFileRangeIndex;
          if (i9 > 0) {
            this.getFileRangeIndex = i9 - 1;
          }
          this.fileRangeReceiveDataSizeCount = this.getFileRangeOffset;
          Log.d("Jeff1111", "*********************CRC ERROR retry idx->" + this.getFileRangeIndex);
          decideGetFileRange();
          return;
        }
        broadcastUpdate(SampleGattAttributes.ACTION_CRC_ERROR, i8);
        return;
      }
      this.onChangeDataByteList = new ArrayList();
      for (Integer num : this.onChangeDataMap.keySet()) {
        for (int i10 = 0; i10 < this.onChangeDataMap.get(num).length; i10++) {
          this.onChangeDataByteList.add(Byte.valueOf(this.onChangeDataMap.get(num)[i10]));
        }
      }
      Log.d(TAG, "onChangeDataMap -> onChangeDataByteList size:" + this.onChangeDataByteList.size());
      List list = this.onChangeDataByteList;
      if (list == null || list.size() <= 0) {
        return;
      }
      this.onChangeDataByteArray = new byte[this.onChangeDataByteList.size()];
      for (int i11 = 0; i11 < this.onChangeDataByteList.size(); i11++) {
        this.onChangeDataByteArray[i11] = ((Byte) this.onChangeDataByteList.get(i11)).byteValue();
      }
      this.onChangeDataTotalSize = 0;
      this.onChangeDataByteList.clear();
      int i12 = this.nowOnChangeDataCommandId;
      if (i12 == 6) {
        if (SampleGattAttributes.isNewBroadcastFormat) {
          broadcastUpdate(SampleGattAttributes.ACTION_READ_DEVICE_INFO, this.onChangeDataByteArray, peripheral.getAddress());
        } else {
          broadcastUpdate(SampleGattAttributes.ACTION_READ_DEVICE_INFO, DataUtil.readDeviceInfoFormat(this.onChangeDataByteArray).toString());
        }
      } else if (i12 == 15) {
        if (SampleGattAttributes.isNewBroadcastFormat) {
          broadcastUpdate(SampleGattAttributes.ACTION_REQUEST_DATA, this.onChangeDataByteArray);
        } else {
          broadcastUpdate(SampleGattAttributes.ACTION_REQUEST_DATA, DataUtil.requestDataResult(this.onChangeDataByteArray).toString());
        }
      } else if (i12 != 17) {
        if (i12 == 11) {
          if (SampleGattAttributes.isNewBroadcastFormat) {
            broadcastUpdate(SampleGattAttributes.ACTION_GET_FILE_LIST, this.onChangeDataByteArray);
          } else {
            broadcastUpdate(SampleGattAttributes.ACTION_GET_FILE_LIST, DataUtil.getFileListResult(this.onChangeDataByteArray));
          }
        } else if (i12 == 12) {
          if (SampleGattAttributes.isNewBroadcastFormat) {
            broadcastUpdate(SampleGattAttributes.ACTION_GET_FILE, this.onChangeDataByteArray);
          } else {
            broadcastUpdate(SampleGattAttributes.ACTION_GET_FILE, DataUtil.requestDataResult(this.onChangeDataByteArray).toString());
          }
        }
      } else if (SampleGattAttributes.isGetFileRangePhase2) {
        if (this.cmd17FirstGetFileSize) {
          byte[] bArr4 = this.onChangeDataByteArray;
          byte[] bArr5 = {bArr4[0], bArr4[1], bArr4[2], bArr4[3]};
          int i13 = ByteBuffer.wrap(new byte[]{bArr5[0], bArr5[1], bArr5[2], bArr5[3]}).getInt();
          broadcastUpdateDataSize(SampleGattAttributes.ACTION_GET_FILE_RANGE_DATA_SIZE, i13);
          String str3 = TAG;
          Log.d(str3, "onCharacteristicChanged (data channel) CommandId == 17 Total dataSize = " + i13 + "[" + (((int) bArr5[0]) + ", " + ((int) bArr5[1]) + ", " + ((int) bArr5[2]) + ", " + ((int) bArr5[3])) + "]");
          this.fileRangeDataSize = i13;
          int i14 = this.CMD_17_CHUNK_SIZE;
          this.fileRangeCount = i13 % i14 == 0 ? i13 / i14 : 1 + (i13 / i14);
          if (i13 % i14 != 0) {
            i14 = i13 % i14;
          }
          this.fileRangeLastChunkSize = i14;
          Log.d(str3, "注意看 End fragment[GetFileSize](CMD_GET_FILE_RANGE): getFileRangeIndex -> " + this.getFileRangeIndex + ", fileRangeCount -> " + this.fileRangeCount);
          this.fileRangeReceiveDataSizeCount = 0;
          this.phase2GetFileRangeTotalArray = new byte[0];
          this.onChangeDataByteArray = new byte[i13];
          this.cmd17FirstGetFileSize = false;
          decideGetFileRange();
          return;
        }
        String str4 = TAG;
        Log.d(str4, "注意看 End fragment(CMD_GET_FILE_RANGE): getFileRangeIndex -> " + this.getFileRangeIndex + ", fileRangeCount -> " + this.fileRangeCount);
        this.getFileRangeOffset = this.getFileRangeOffset + this.getFileRangeChunkSize;
        this.phase2GetFileRangeTotalArray = ParserUtil.joinByteArray(this.phase2GetFileRangeTotalArray, this.onChangeDataByteArray);
        Log.d(str4, "GetFileRangePhase2: total = " + this.phase2GetFileRangeTotalArray.length + ", changData = " + this.onChangeDataByteArray.length);
        decideGetFileRange();
      } else if (SampleGattAttributes.isNewBroadcastFormat) {
        App.fitUploadByteArray = this.onChangeDataByteArray;
        broadcastUpdate(SampleGattAttributes.ACTION_GET_FILE_RANGE, new byte[0]);
      } else {
        broadcastUpdate(SampleGattAttributes.ACTION_GET_FILE_RANGE, DataUtil.requestDataResult(this.onChangeDataByteArray).toString());
      }
    } else {
      for (int i15 = 2; i15 < value.length; i15++) {
        this.onChangeDataCrcCount += ParserUtil.getUnsignedByte(value[i15]);
        int i16 = this.nowOnChangeDataCommandId;
        if (i16 == 6 || i16 == 11 || i16 == 12 || i16 == 15) {
          this.onChangeDataByteList.add(Byte.valueOf(value[i15]));
        } else if (i16 == 17) {
          try {
            this.onChangeDataByteList.add(Byte.valueOf(value[i15]));
          } catch (Exception unused) {
          }
        }
      }
      byte[] copyOfRange = Arrays.copyOfRange(value, 2, value.length);
      Log.d(TAG, "onChangeDataMap 呼叫 -> slice size = " + copyOfRange.length + ", seqNo = " + intValue);
      this.onChangeDataMap.put(Integer.valueOf(intValue), copyOfRange);
      this.receiveDataSizeCount = this.receiveDataSizeCount + copyOfRange.length;
      this.fileRangeReceiveDataSizeCount = this.fileRangeReceiveDataSizeCount + copyOfRange.length;
      int i17 = this.nowOnChangeDataCommandId;
      if (i17 == 12) {
        int i18 = this.flowCtrl;
        if (intValue % i18 == i18 - 1) {
          checkGetLogFileContinue();
          return;
        }
      }
      if (i17 == 17) {
        int i19 = this.flowCtrl;
        if (intValue % i19 == i19 - 1) {
          checkGetFileRangeContinue();
        }
      }
    }
  }

  public void decideGetFileRange() {
    int i = this.getFileRangeIndex;
    int i2 = this.fileRangeCount;
    if (i < i2) {
      this.getFileRangeChunkSize = i == i2 + (-1) ? this.fileRangeLastChunkSize : this.CMD_17_CHUNK_SIZE;
      String str = TAG;
      Log.d(str, "decideGetFileRange: 第" + this.getFileRangeIndex + "段，共" + this.fileRangeCount + "段getFileRangeOffset = " + this.getFileRangeOffset + ", getFileRangeChunkSize = " + this.getFileRangeChunkSize + ", cmd17FileId: " + this.cmd17FileId);
      getFileRangePartTwo(this.getFileRangeOffset, this.getFileRangeChunkSize);
      this.getFileRangeIndex = this.getFileRangeIndex + 1;
      return;
    }
    String str2 = TAG;
    Log.d(str2, "decideGetFileRange 全部收完: onChangeDataByteArray size = " + this.phase2GetFileRangeTotalArray.length + ", cmd17FileId: " + this.cmd17FileId);
    App.fitUploadByteArray = this.phase2GetFileRangeTotalArray;
    broadcastUpdate(SampleGattAttributes.ACTION_GET_FILE_RANGE, new byte[0]);
  }

  public void getFileRangePartTwo(int offset, int chunkSize) {
    broadcastUpdate(SampleGattAttributes.ACTION_GET_FILE_RANGE_PART_TWO, this.cmd17FileId, this.cmd17FileType, offset, chunkSize);
  }

  public byte[] generateActionData(int cmdId, int seqNo, int actionCode) {
    byte[] bArr = actionCode == 5 ? new byte[5] : new byte[3];
    bArr[0] = (byte) cmdId;
    String intToBinaryString = ParserUtil.intToBinaryString(seqNo, 3);
    bArr[1] = Byte.parseByte("010" + intToBinaryString + MapboxAccounts.SKU_ID_MAPS_MAUS, 2);
    bArr[2] = (byte) actionCode;
    if (actionCode == 5) {
      byte[] array = ByteBuffer.allocate(2).putShort((short) this.flowCtrl).array();
      bArr[3] = array[0];
      bArr[4] = array[1];
    }
    return bArr;
  }

  public void checkGetLogFileContinue() {
    CommandBbcpQueueUtil commandBbcpQueueUtil;
    byte[] generateActionData = generateActionData(12, this.cmdSeqNo, 6);
    if (generateActionData == null || generateActionData.length <= 0 || (commandBbcpQueueUtil = this.commandQueueUtil) == null) {
      return;
    }
    commandBbcpQueueUtil.queueWriteForBbcp(SampleGattAttributes.COMMAND_AND_DATA_SERVICE_UUID, SampleGattAttributes.COMMAND_CHANNEL_UUID, generateActionData, 2);
  }

  public void checkGetFileRangeContinue() {
    CommandBbcpQueueUtil commandBbcpQueueUtil;
    byte[] generateActionData = generateActionData(17, this.cmdSeqNo, 6);
    if (generateActionData == null || generateActionData.length <= 0 || (commandBbcpQueueUtil = this.commandQueueUtil) == null) {
      return;
    }
    commandBbcpQueueUtil.queueWriteForBbcp(SampleGattAttributes.COMMAND_AND_DATA_SERVICE_UUID, SampleGattAttributes.COMMAND_CHANNEL_UUID, generateActionData, 2);
  }

  public void prepareIniOrAltitude(int seqNo) {
    if (this.decideSystemIniIndex == 0) {
      byte[] bArr = this.cmd16ContentArray;
      this.sendFileOriginDataSize = bArr.length;
      this.sendFileCrcCount = 0;
      int i = this.payload - 2;
      this.systemIniFragSize = bArr.length % i == 0 ? bArr.length / i : (bArr.length / i) + 1;
      if (bArr.length % i != 0) {
        i = bArr.length % i;
      }
      this.systemIniLastDataSize = i;
      iniOrAltitudeStartFragment(seqNo);
    }
    IniOrAltitudeDataPackage(this.systemIniFragSize, this.systemIniLastDataSize);
  }

  public void iniOrAltitudeStartFragment(int seqNo) {
    byte[] array = ByteBuffer.allocate(2).putShort((short) this.systemIniFragSize).array();
    String intToBinaryString = ParserUtil.intToBinaryString(seqNo, 3);
    queueWrite(SampleGattAttributes.COMMAND_AND_DATA_SERVICE_UUID, SampleGattAttributes.DATA_CHANNEL_UUID, new byte[]{0, 0, array[0], array[1], (byte) this.systemIniLastDataSize, MapTile.State.CANCEL, Byte.parseByte("000" + intToBinaryString + MapboxAccounts.SKU_ID_MAPS_MAUS, 2)}, this.dataChannelWriteType);
    this.decideSystemIniOffset = 0;
    this.decideSystemIniIndex = this.decideSystemIniIndex + 1;
  }

  public void IniOrAltitudeDataPackage(int fragSize, int lastDataSize) {
    int i = this.payload - 2;
    for (int i2 = this.decideSystemIniIndex; i2 <= fragSize; i2++) {
      if (!this.openSysIniFlag && this.decideSystemIniIndex % this.flowCtrl == 0) {
        return;
      }
      this.openSysIniFlag = false;
      if (i2 == fragSize) {
        int i3 = lastDataSize + 2;
        byte[] bArr = new byte[i3];
        byte[] array = ByteBuffer.allocate(2).putShort((short) i2).array();
        bArr[0] = array[0];
        bArr[1] = array[1];
        for (int i4 = 2; i4 < i3; i4++) {
          bArr[i4] = this.cmd16ContentArray[(this.decideSystemIniOffset + i4) - 2];
          this.sendFileCrcCount += ParserUtil.getUnsignedByte(bArr[i4]);
        }
        this.decideSystemIniIndex++;
        try {
          Thread.sleep(5L);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        queueWrite(SampleGattAttributes.COMMAND_AND_DATA_SERVICE_UUID, SampleGattAttributes.DATA_CHANNEL_UUID, bArr, this.dataChannelWriteType);
        IniOrAltitudeEndFragment();
      } else {
        int i5 = this.payload;
        byte[] bArr2 = new byte[i5];
        byte[] array2 = ByteBuffer.allocate(2).putShort((short) i2).array();
        bArr2[0] = array2[0];
        bArr2[1] = array2[1];
        for (int i6 = 2; i6 < i5; i6++) {
          bArr2[i6] = this.cmd16ContentArray[(this.decideSystemIniOffset + i6) - 2];
          this.sendFileCrcCount += ParserUtil.getUnsignedByte(bArr2[i6]);
        }
        this.decideSystemIniIndex++;
        this.decideSystemIniOffset += i;
        try {
          Thread.sleep(5L);
        } catch (InterruptedException e2) {
          e2.printStackTrace();
        }
        queueWrite(SampleGattAttributes.COMMAND_AND_DATA_SERVICE_UUID, SampleGattAttributes.DATA_CHANNEL_UUID, bArr2, this.dataChannelWriteType);
      }
    }
  }

  public void IniOrAltitudeEndFragment() {
    byte[] bArr = new byte[7];
    byte[] array = ByteBuffer.allocate(2).putShort((short) (this.systemIniFragSize + 1)).array();
    bArr[0] = array[0];
    bArr[1] = array[1];
    bArr[2] = 0;
    byte[] array2 = ByteBuffer.allocate(4).putInt(this.sendFileCrcCount).array();
    for (int i = 0; i < array2.length; i++) {
      bArr[i + 3] = array2[i];
    }
    try {
      Thread.sleep(5L);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    queueWrite(SampleGattAttributes.COMMAND_AND_DATA_SERVICE_UUID, SampleGattAttributes.DATA_CHANNEL_UUID, bArr, this.dataChannelWriteType);
  }

  public void decidePlanTripOrWorkout(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int seqNo) {
    int i;
    byte[][] bArr = this.fileArr;
    if (bArr != null && (i = this.sendPlanTripIndex) < bArr.length - 1) {
      this.sendPlanTripIndex = i + 1;
      writeCommand(gatt, characteristic, DataUtil.getInstance().requestDataCmd(16, seqNo, this.cmd16ContentType), 2);
      return;
    }
    broadcastUpdate(SampleGattAttributes.ACTION_POST_DATA, "OK");
    if (this.cmd16ContentType == 11) {
      queueWrite(SampleGattAttributes.SETTING_SERVICE_UUID, SampleGattAttributes.SETTING_CHANNEL_UUID, new byte[]{49, 1, 49, 49, 48, 53, 95, -25, -103, Fit.UTF8_BOM_BYTE_2, -27, -79, -79, -24, -73, -81, -25, -73, -102, 96}, 2);
    }
    this.sendPlanTripIndex = 0;
  }

  private void preparePlanTripOrWorkout(int seqNo) {
    int i;
    if (this.sendPlanTripIndex == 0) {
      int length = this.cmd16ContentArray.length;
      this.sendFileOriginDataSize = length;
      int i2 = this.DOWNLOAD_SIZE;
      int i3 = length % i2 > 0 ? length % i2 : i2;
      int i4 = (length / i2) + 1;
      this.fileArr = new byte[i4];
      int i5 = 0;
      int i6 = 0;
      while (true) {
        i = i4 - 1;
        if (i5 >= i) {
          break;
        }
        this.fileArr[i5] = ParserUtil.bufToDataPkg(this.cmd16ContentArray, i6, i2);
        i6 += i2;
        i5++;
      }
      this.fileArr[i] = ParserUtil.bufToDataPkg(this.cmd16ContentArray, i6, i3);
    }
    checkPlanTripOrWorkoutToSend(seqNo);
  }

  private void checkPlanTripOrWorkoutToSend(int seqNo) {
    byte[][] bArr = this.fileArr;
    if (bArr == null || bArr.length <= this.sendPlanTripIndex) {
      return;
    }
    String str = TAG;
    Log.d(str, "Plan Trip 傳檔 fileArr[sendPlanTripIndex] sendPlanTripIndex -> " + this.sendPlanTripIndex);
    processingPlanTripOrWorkout(this.fileArr[this.sendPlanTripIndex], seqNo);
  }

  private void processingPlanTripOrWorkout(byte[] dataPackageArray, int seqNo) {
    int i = this.PAYLOAD_SIZE;
    int i2 = 7;
    byte[] bArr = new byte[7];
    bArr[0] = 0;
    bArr[1] = 0;
    int length = dataPackageArray.length % i == 0 ? dataPackageArray.length / i : (dataPackageArray.length / i) + 1;
    int length2 = dataPackageArray.length % i == 0 ? i : dataPackageArray.length % i;
    byte[] array = ByteBuffer.allocate(2).putShort((short) length).array();
    bArr[2] = array[0];
    bArr[3] = array[1];
    bArr[4] = (byte) length2;
    bArr[5] = MapTile.State.CANCEL;
    String intToBinaryString = ParserUtil.intToBinaryString(seqNo, 3);
    bArr[6] = Byte.parseByte("000" + intToBinaryString + MapboxAccounts.SKU_ID_MAPS_MAUS, 2);
    queueWrite(SampleGattAttributes.COMMAND_AND_DATA_SERVICE_UUID, SampleGattAttributes.DATA_CHANNEL_UUID, bArr, this.dataChannelWriteType);
    int i3 = 1;
    int i4 = 0;
    int i5 = 0;
    while (i3 <= length) {
      if (i3 == length) {
        int i6 = length2 + 2;
        byte[] bArr2 = new byte[i6];
        bArr2[0] = array[0];
        bArr2[1] = array[1];
        for (int i7 = 2; i7 < i6; i7++) {
          bArr2[i7] = dataPackageArray[(i5 + i7) - 2];
          i4 += ParserUtil.getUnsignedByte(bArr2[i7]);
        }
        i5 += i;
        queueWrite(SampleGattAttributes.COMMAND_AND_DATA_SERVICE_UUID, SampleGattAttributes.DATA_CHANNEL_UUID, bArr2, this.dataChannelWriteType);
      } else {
        int i8 = i + 2;
        byte[] bArr3 = new byte[i8];
        byte[] array2 = ByteBuffer.allocate(2).putShort((short) i3).array();
        bArr3[0] = array2[0];
        bArr3[1] = array2[1];
        for (int i9 = 2; i9 < i8; i9++) {
          bArr3[i9] = dataPackageArray[(i5 + i9) - 2];
          i4 += ParserUtil.getUnsignedByte(bArr3[i9]);
        }
        i5 += i;
        queueWrite(SampleGattAttributes.COMMAND_AND_DATA_SERVICE_UUID, SampleGattAttributes.DATA_CHANNEL_UUID, bArr3, this.dataChannelWriteType);
      }
      i3++;
      i2 = 7;
    }
    byte[] bArr4 = new byte[i2];
    byte[] array3 = ByteBuffer.allocate(2).putShort((short) (length + 1)).array();
    bArr4[0] = array3[0];
    bArr4[1] = array3[1];
    bArr4[2] = 0;
    byte[] array4 = ByteBuffer.allocate(4).putInt(i4).array();
    for (int i10 = 0; i10 < array4.length; i10++) {
      bArr4[i10 + 3] = array4[i10];
    }
    queueWrite(SampleGattAttributes.COMMAND_AND_DATA_SERVICE_UUID, SampleGattAttributes.DATA_CHANNEL_UUID, bArr4, this.dataChannelWriteType);
  }

  private BluetoothGattCharacteristic findWritableCharacteristic(BluetoothGattService service, UUID characteristicUUID, int writeType) {
    BluetoothGattCharacteristic bluetoothGattCharacteristic;
    int i = writeType == 1 ? 4 : 8;
    Iterator<BluetoothGattCharacteristic> it = service.getCharacteristics().iterator();
    while (true) {
      if (!it.hasNext()) {
        bluetoothGattCharacteristic = null;
        break;
      }
      bluetoothGattCharacteristic = it.next();
      if ((bluetoothGattCharacteristic.getProperties() & i) != 0 && characteristicUUID.equals(bluetoothGattCharacteristic.getUuid())) {
        break;
      }
    }
    return bluetoothGattCharacteristic == null ? service.getCharacteristic(characteristicUUID) : bluetoothGattCharacteristic;
  }

  private void writeCommand(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, byte[] data, int writeType) {
    if (characteristic != null) {
      characteristic.setValue(data);
      characteristic.setWriteType(writeType);
      gatt.writeCharacteristic(characteristic);
    }
  }

  private void broadcastUpdate(String action, byte[] data, String macAddress) {
    Intent intent = new Intent(action);
    intent.putExtra("com.example.bluetooth.le.EXTRA_DATA", data);
    intent.putExtra(SampleGattAttributes.EXTRA_DATA_MAC_ADDRESS, macAddress);
    this.mContext.sendBroadcast(intent);
  }

  private void broadcastUpdate(String action, int fileId, byte cmd17FileType, int offset, int chunkSize) {
    Intent intent = new Intent(action);
    intent.putExtra(SampleGattAttributes.GET_FILE_RANGE_PARA_FILE_ID, fileId);
    intent.putExtra(SampleGattAttributes.GET_FILE_RANGE_PARA_FILE_TYPE, cmd17FileType);
    intent.putExtra(SampleGattAttributes.GET_FILE_RANGE_PARA_OFFSET, offset);
    intent.putExtra(SampleGattAttributes.GET_FILE_RANGE_PARA_CHUNK_SIZE, chunkSize);
    this.mContext.sendBroadcast(intent);
  }

  private void broadcastUpdate(String action, byte[] data) {
    Intent intent = new Intent(action);
    intent.putExtra("com.example.bluetooth.le.EXTRA_DATA", data);
    this.mContext.sendBroadcast(intent);
  }

  private void broadcastUpdate(String action, String result) {
    Intent intent = new Intent(action);
    intent.putExtra("com.example.bluetooth.le.EXTRA_DATA", result);
    this.mContext.sendBroadcast(intent);
  }

  private void broadcastUpdate(String action, int cmdId) {
    Intent intent = new Intent(action);
    intent.putExtra(SampleGattAttributes.EXTRA_DATA_CMD_ID, cmdId);
    this.mContext.sendBroadcast(intent);
  }

  /* JADX INFO: Access modifiers changed from: private */
  public void broadcastUpdate(String action, int cmdId, String result) {
    Intent intent = new Intent(action);
    intent.putExtra(SampleGattAttributes.EXTRA_DATA_CMD_ID, cmdId);
    intent.putExtra("com.example.bluetooth.le.EXTRA_DATA", result);
    this.mContext.sendBroadcast(intent);
  }

  private void broadcastUpdate(String action, long startTimeStamp) {
    Intent intent = new Intent(action);
    intent.putExtra(SampleGattAttributes.ACTION_GET_FILE_RANGE_START_TIME_EXTRA, startTimeStamp);
    this.mContext.sendBroadcast(intent);
  }

  private void broadcastUpdateDataSize(String action, int dataSize) {
    Intent intent = new Intent(action);
    intent.putExtra(SampleGattAttributes.ACTION_GET_FILE_RANGE_DATA_SIZE_EXTRA, dataSize);
    this.mContext.sendBroadcast(intent);
  }

  public void queueWrite(UUID serviceUUID, UUID characteristicUUID, byte[] data, int writeType) {
    CommandBbcpQueueUtil commandBbcpQueueUtil = this.commandQueueUtil;
    if (commandBbcpQueueUtil != null) {
      commandBbcpQueueUtil.queueWriteForBbcp(serviceUUID, characteristicUUID, data, writeType);
    }
  }

  private void queueCleanup() {
    this.bleProcessing = false;
    do {
    } while (this.commandQueue.poll() != null);
  }

  private void queueCommand(BLECommandBbcp command) {
    this.commandQueue.add(command);
    if (this.bleProcessing) {
      return;
    }
    processCommands();
  }

  private void commandCompleted() {
    Log.d(TAG, "Processing Complete");
    this.bleProcessing = false;
    processCommands();
  }

  private void processCommands() {
    String str = TAG;
    Log.d(str, "Processing Commands");
    if (this.bleProcessing) {
      return;
    }
    BLECommandBbcp poll = this.commandQueue.poll();
    if (poll != null) {
      if (poll.getType() == 2) {
        Log.d(str, "Write " + poll.getCharacteristicUUID());
        this.bleProcessing = true;
        writeCharacteristic(poll.getServiceUUID(), poll.getCharacteristicUUID(), poll.getData(), poll.getType());
        return;
      } else if (poll.getType() == 1) {
        Log.d(str, "Write No Response " + poll.getCharacteristicUUID());
        this.bleProcessing = true;
        writeCharacteristic(poll.getServiceUUID(), poll.getCharacteristicUUID(), poll.getData(), poll.getType());
        return;
      } else {
        throw new RuntimeException("Unexpected BLE Command type " + poll.getType());
      }
    }
    Log.d(str, "Command Queue is empty.");
  }

  private void writeCharacteristic(UUID serviceUUID, UUID characteristicUUID, byte[] data, int writeType) {
    boolean writeCharacteristic;
    if (writeType == 2) {
      writeCharacteristic = this.mPeripheral.writeCharacteristic(serviceUUID, characteristicUUID, data, WriteType.WITH_RESPONSE);
    } else {
      writeCharacteristic = this.mPeripheral.writeCharacteristic(serviceUUID, characteristicUUID, data, WriteType.WITHOUT_RESPONSE);
    }
    String str = TAG;
    Log.d(str, "writeCharacteristic 要呼叫 -> commandCompleted(), success = " + writeCharacteristic);
    if (writeCharacteristic) {
      return;
    }
    commandCompleted();
  }

  private boolean isDeviceBusy() {
    boolean z = false;
    try {
      z = ((Boolean) readField(this.mBluetoothGatt, "mDeviceBusy")).booleanValue();
      Log.e("potter123", "isDeviceBusy:" + z + ", mBluetoothGatt = " + this.mBluetoothGatt);
      return z;
    } catch (IllegalAccessException e) {
      e.printStackTrace();
      return z;
    } catch (NoSuchFieldException e2) {
      e2.printStackTrace();
      return z;
    }
  }

  private Object readField(Object object, String name) throws IllegalAccessException, NoSuchFieldException {
    Field declaredField = object.getClass().getDeclaredField(name);
    declaredField.setAccessible(true);
    return declaredField.get(object);
  }

  private void refreshGatt() {
    try {
      Log.e("potter123", "refreshGatt()");
      Method method = this.mBluetoothGatt.getClass().getMethod("refresh", new Class[0]);
      if (method != null) {
        method.invoke(this.mBluetoothGatt, new Object[0]);
      }
    } catch (Exception e) {
      Log.e("potter123", "refreshGatt error:" + e);
    }
  }
}