package com.device.comm.mylibrary.NativeDevice;

import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;

import android.util.Log;

import com.device.comm.mylibrary.BleDevice;
import com.device.comm.mylibrary.BleDeviceConnect;
import com.device.comm.mylibrary.BleDeviceManager;
import com.device.comm.mylibrary.NativeDevice.cgmadi.Bt4ThCallback;
import com.device.comm.mylibrary.NativeDevice.cgmadi.bean.RequestBean;
import com.device.comm.mylibrary.NativeDevice.cgmadi.bean.ResponseBean;
import com.device.comm.mylibrary.NativeDevice.cgmadi.bean.THStatus;
import com.device.comm.mylibrary.NativeDevice.cgmadi.constants.Command;
import com.device.comm.mylibrary.NativeDevice.cgmadi.enums.OBJCode;
import com.device.comm.mylibrary.NativeDevice.cgmadi.enums.OPCode;
import com.device.comm.mylibrary.NativeDevice.cgmadi.impl.IBtConnectionImpl;
import com.device.comm.mylibrary.NativeDevice.cgmadi.util.DataFormatUtil;
import com.device.comm.mylibrary.NativeDevice.cgmadi.util.ResponseAnalysis;
import com.device.comm.mylibrary.RNLog;
import com.device.comm.mylibrary.UpdateLoop;

import org.json.JSONArray;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by lvwang2002 on 2017/2/16.
 */

public class BleDynamicGlucose extends BleNativeDevice{
    private String TAG ="BLE_DY_GLU";

    private static final String UUID_BTLE_SERVICE = "0000ffe0-0000-1000-8000-00805f9b34fb";
    private static final String UUID_BTLE_SEND = "0000ffe1-0000-1000-8000-00805f9b34fb";
    private static final String UUID_BTLE_RECEIVE = "0000ffe1-0000-1000-8000-00805f9b34fb";
    private String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb";


    private BleDevice mDevice = null;
    private BleDeviceManager mDeviceManager = null;

    private static int requestInt = 0;
    private static int requestCode = 0;
    private String emitterCode = "00000";


    byte[] mDataList = {};

    int mProgressIndex = 0;

    BleDynamicGlucose(BleDevice device, BleDeviceManager deviceManager){
        mDevice = device;
        mDeviceManager = deviceManager;
    }

    public interface BleNativeDYDeviceCallback extends BleNativeDeviceCallback{
        public void onCreatedChannel(BleDevice device);
        public void onAuthenticated(BleDevice device,Boolean isSuc);
        public void onGetMonitorStatus(BleDevice device,Boolean isStartMonitor);
        public void onGetBattery(BleDevice device,Double value);
        public void onGetName(BleDevice device,String name);
        public void onGetAllDataCount(BleDevice device,int count);
        public void onGetProgressData(BleDevice device,Double[] dataList,int index);
        public void onStartMonitor(BleDevice device,Boolean isSuc);
        public void onStopMonitor(BleDevice device,Boolean isSuc);
        public void onUpdateNewData(BleDevice device,int index,Double value);
    }

    private BleNativeDYDeviceCallback mDeviceCallback = null;

    @Override
    public String getNotifyCharacteristicUUID() {
        return UUID_BTLE_RECEIVE;
    }

    @Override
    public String getDeviceServiceUUID(){
        return  UUID_BTLE_SERVICE;
    }

    private boolean postNeeded() {
        return mDeviceManager.getUpdateLoop().postNeeded();
    }

    private void post(final Runnable runnable) {
        final UpdateLoop updateLoop = mDeviceManager.getUpdateLoop();

        updateLoop.postIfNeeded(runnable);
    }

    private boolean postMainThreadNeeded() {
        return mDeviceManager.getMainUpdateLoop().postNeeded();
    }

    private void postMainThread(final Runnable runnable) {
        final UpdateLoop updateLoop = mDeviceManager.getMainUpdateLoop();

        updateLoop.postIfNeeded(runnable);
    }




    @Override
    public void  setNativeDeviceCallback(BleNativeDevice.BleNativeDeviceCallback deviceCallback){
        mDeviceCallback = (BleNativeDYDeviceCallback) deviceCallback;
    }

    @Override
    public String getConnectedStatus(){
        return connectedStatus;
    }


    private BluetoothGattCharacteristic mNotifyCharacteristic = null;
    BluetoothGattService mDeviceService = null;
    private BluetoothGattCharacteristic mGattCharacteristicTrans = null;
    @Override
    public void onServicesDiscovered_mainThread(final BluetoothGatt gatt, final int gattStatus) {
        RNLog.d(TAG,"找到服务,开始处理");
        connectedStatus = CREATING_CHANNEL;
        if( gattStatus == BluetoothGatt.GATT_SUCCESS ) {
            List<BluetoothGattService> services =  gatt.getServices();

            for(BluetoothGattService service:services){
                mNotifyCharacteristic = service.getCharacteristic(UUID.fromString("0000ffb2-0000-1000-8000-00805f9b34fb"));
                if(mNotifyCharacteristic == null){
                    continue;
                }


                mNotifyCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
                mGattCharacteristicTrans = mNotifyCharacteristic;

                if( postNeeded() ) {
                    post(new Runnable() {
                        @Override
                        public void run() {
                            enableNotification(gatt,true,mNotifyCharacteristic);
                            if(mDeviceCallback == null){
                                return;
                            }
                            connectedStatus = CREATED_CHANNEL;

                            mDeviceCallback.onCreatedChannel(mDevice);

                        }
                    });
                } else {
                    enableNotification(gatt,true,mNotifyCharacteristic);
                    if(mDeviceCallback == null){
                        return;
                    }
                    connectedStatus = CREATED_CHANNEL;

                    mDeviceCallback.onCreatedChannel(mDevice);
                }
                break;

            }

        } else {
            mDeviceManager.uhOh(mDevice,"service status error:"+gattStatus);
        }

    }

    private void enableNotification(final BluetoothGatt gatt,final boolean enable,final BluetoothGattCharacteristic characteristic) {
        if (gatt == null){
            Log.e(TAG,"gatt 为空");
            return;
        }

        if (!(gatt.setCharacteristicNotification(characteristic, enable))){
            Log.e(TAG,"设置Gatt失败");
            mDeviceManager.uhOh(mDevice,"set gatt notify error");
            return;
        }

        BluetoothGattDescriptor clientConfig = characteristic.getDescriptor(UUID
                .fromString(CLIENT_CHARACTERISTIC_CONFIG));
        if (clientConfig == null){
            Log.e(TAG,"clientConfig为空,但好像也不是特别影响");
            return;
        }
        byte[] b = {
                (byte) 0x00, (byte) 0x01
        };
        try{
            clientConfig.setValue(b);
        }catch (Exception e) {
            mDeviceManager.uhOh(mDevice,"null exception");
            return;
        }

        if (enable) {
            Log.i(TAG, "enable notification");
            clientConfig.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        } else {
            Log.i(TAG, "disable notification");
            clientConfig.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
        }

        if(!gatt.writeDescriptor(clientConfig)){
            Log.i(TAG,"write descriptor error");

            mDeviceManager.uhOh(mDevice,"write descriptor error");
            return;
        }

    }

    private void sendData(byte[] data) {

        if (data != null && data.length > 0 && data.length < 21) {
            if (mGattCharacteristicTrans.setValue(data)
                    && mDevice.getDeviceConnect().getGatt().writeCharacteristic(mGattCharacteristicTrans)) {
                Log.d(TAG, "send data OK");
            }else{
                Log.d(TAG,"数据长度不在指定范围内");
            }
        }
    }

    /** 接收并处理数据  */
    @Override
    synchronized public void receiveData(BluetoothGattCharacteristic characteristic){
        RNLog.d(TAG,"received data"+"request:"+requestCode);
        if (!checkReturn(characteristic)) {
            return;
        }
        ResponseBean response = getReturnData(characteristic);
//        RNLog.d(TAG,"data:"+ByteUtil.byteArrToHexString(response.getData()));

        if (response == null) {
            RNLog.d(TAG,"no respond");
//            ((Bt4ThCallback)IBtConnectionImpl.this.context).bt4ThFailure(IBtConnectionImpl.requestCode);
        }
        else
        {
            Object rtn = null;
            switch (requestCode)
            {
                case 1:{
                    RNLog.d(TAG,"Bt4Th-startMonitor:" + response);
                    rtn = Boolean.valueOf(ResponseAnalysis.booleanAnalysis(response,
                            OPCode.SET, OBJCode.MONITOR));
                    final Boolean iSuc = (Boolean)rtn;
                    RNLog.d(TAG,"Bt4Th-startMonitor:" + rtn);
                    post(new Runnable() {
                        @Override
                        public void run() {
                            if(mDeviceCallback==null){
                                return;
                            }

                            mDeviceCallback.onStartMonitor(mDevice,iSuc);
                        }
                    });
//                    ((Bt4ThCallback)IBtConnectionImpl.this.context).bt4ThSuccess(IBtConnectionImpl.requestInt, rtn);
                    break;}
                case 2:{
                    RNLog.d(TAG,"Bt4Th-stopMonitor:" + response);
                    rtn = Boolean.valueOf(ResponseAnalysis.booleanAnalysis(response,
                            OPCode.SET, OBJCode.MONITOR));
                    RNLog.d(TAG,"Bt4Th-stopMonitor:" + rtn);

                    final Boolean iSuc = (Boolean)rtn;
                    post(new Runnable() {
                        @Override
                        public void run() {
                            if(mDeviceCallback==null){
                                return;
                            }

                            mDeviceCallback.onStopMonitor(mDevice,iSuc);
                        }
                    });
//                    ((Bt4ThCallback)IBtConnectionImpl.this.context).bt4ThSuccess(IBtConnectionImpl.requestInt, rtn);
                    break;}
                case 12:
                    RNLog.d(TAG,"Bt4Th-getNumberDataFromIndex:" +
                            response);
                    rtn = ResponseAnalysis.electricAnalysis(response,
                            OPCode.GET, OBJCode.NDFI);
                    RNLog.d(TAG,"Bt4Th-getNumberDataFromIndex:" +
                            rtn.toString());
                    break;
                case 13:
                    RNLog.d(TAG,"Bt4Th-getAllDataFromIndex:" + response);
                    rtn = ResponseAnalysis.electricAnalysis(response,
                            OPCode.GET, OBJCode.ADFI);
                    RNLog.d(TAG,"Bt4Th-getAllDataFromIndex:" +
                            rtn.toString());
                    break;
                case 3:
                    RNLog.d(TAG,"Bt4Th-getAllDataCount:" + response);
                    Integer[] values = ResponseAnalysis.intAnalysis(response,
                            OPCode.GET, OBJCode.AC);
                    if (values != null) {
                        rtn = values[0];
                    }
                    RNLog.d(TAG,"Bt4Th-getAllDataCount:" + rtn);
                    final int count = (Integer)rtn;
                    post(new Runnable() {
                        @Override
                        public void run() {
                            if(mDeviceCallback == null){
                                return;
                            }

                            mDeviceCallback.onGetAllDataCount(mDevice,count);
                        }
                    });
//                    ((Bt4ThCallback)IBtConnectionImpl.this.context).bt4ThSuccess(IBtConnectionImpl.requestInt, rtn);
                    break;
                case 4:
                    RNLog.d(TAG,"Bt4Th-getAllData:" + response);
                    rtn = Boolean.valueOf(ResponseAnalysis.booleanAnalysis(response,
                            OPCode.GET, OBJCode.AD));
                    RNLog.d(TAG,"Bt4Th-getAllData:" + rtn.toString());
                    break;
                case 5:
                    RNLog.d(TAG,"Bt4Th-getName:" + response);
                    rtn = ResponseAnalysis.stringASCIIAnalysis(response,
                            OPCode.GET, OBJCode.NAME);
                    RNLog.d(TAG,"Bt4Th-getName:" + rtn);
//                    ((Bt4ThCallback)IBtConnectionImpl.this.context).bt4ThSuccess(IBtConnectionImpl.requestInt, rtn);
                    break;
                case 6:
                    RNLog.d(TAG,"Bt4Th-getMaxNumber:" + response);
                    Integer[] v = ResponseAnalysis.intAnalysis(response,
                            OPCode.GET, OBJCode.MAXNUM);
                    if (v != null) {
                        rtn = v[0];
                    }
                    RNLog.d(TAG,"Bt4Th-getMaxNumber:" + rtn);
//                    ((Bt4ThCallback)IBtConnectionImpl.this.context).bt4ThSuccess(IBtConnectionImpl.requestInt, rtn);
                    break;
                case 7:
                    RNLog.d(TAG,"Bt4Th-disConnection:" + response);
                    rtn = Boolean.valueOf(ResponseAnalysis.booleanAnalysis(response,
                            OPCode.SET, OBJCode.CON_DIS));
                    RNLog.d(TAG,"Bt4Th-disConnection:" + rtn);
//                    ((Bt4ThCallback)IBtConnectionImpl.this.context).bt4ThSuccess(IBtConnectionImpl.requestInt, rtn);

//                    IBtConnectionImpl.this.disconnect();
                    break;
                case 8:
                    RNLog.d(TAG,"Bt4Th-getSn:" + response);
                    rtn = ResponseAnalysis.stringASCIIAnalysis(response,
                            OPCode.GET, OBJCode.SN);
                    RNLog.d(TAG,"Bt4Th-getSn:" + rtn);
//                    ((Bt4ThCallback)IBtConnectionImpl.this.context).bt4ThSuccess(IBtConnectionImpl.requestInt, rtn);
                    break;
                case 9:
                    RNLog.d(TAG,"Bt4Th-getVersion:" + response);
                    rtn = ResponseAnalysis.stringASCIIAnalysis(response,
                            OPCode.GET, OBJCode.VERSION);
                    RNLog.d(TAG,"Bt4Th-getVersion:" + rtn);
                    break;
                case 10:
                    RNLog.d(TAG,"Bt4Th-doAuthorization:" + response);
                    rtn = Boolean.valueOf(ResponseAnalysis.booleanAnalysis(response,
                            OPCode.GET, OBJCode.AUTHO));
                    final Boolean isSuc = (Boolean)rtn;
                    RNLog.d(TAG,"Bt4Th-doAuthorization:" + rtn);

                    post(new Runnable() {
                        @Override
                        public void run() {
                            if(mDeviceCallback == null){
                                return;
                            }

                            if(isSuc){
                                connectedStatus=AUTHORIZATION_SUCCESSFUL;
                            }else{
                                connectedStatus=AUTHORIZATION_FAILED;
                            }

                            mDeviceCallback.onAuthenticated(mDevice,isSuc);
                        }
                    });
//                    ((Bt4ThCallback)IBtConnectionImpl.this.context).bt4ThSuccess(IBtConnectionImpl.requestInt, rtn);
                    break;
                case 11:
                    RNLog.d(TAG,"Bt4Th-getRecord:" + response);
                    rtn = ResponseAnalysis.statusAnalysis(response, OPCode.GET,
                            OBJCode.RECORD);
                    RNLog.d(TAG,"Bt4Th-getRecord:" + rtn);
                    break;
                case 14:
                    if(response.getObjCode().getValue() == null){
                        return;
                    }

                    RNLog.d(TAG,"Bt4Th-getMonitorStatus:" + response);
                    rtn = ResponseAnalysis.intToBooleanAnalysis(response,
                            OPCode.GET, OBJCode.MONITOR);
                    final Boolean isStartMonitor = (Boolean)rtn;
//                    ((Bt4ThCallback)IBtConnectionImpl.this.context).bt4ThSuccess(IBtConnectionImpl.requestInt, rtn);
                    RNLog.d(TAG,"Bt4Th-getMonitorStatus:" + rtn);
                    post(new Runnable() {
                        @Override
                        public void run() {
                            if(mDeviceCallback == null){
                                return;
                            }

                            mDeviceCallback.onGetMonitorStatus(mDevice,isStartMonitor);
                        }
                    });

                    break;
                case 15:
                    byte[] data = characteristic.getValue();
                    RNLog.d(TAG,"Bt4Th-getBattery:" + ByteUtil.byteArrToHexString(data));
                    final Double value = ((data[1]&0xff) + (data[2]&0xff)*256)/100.0d;
                    post(new Runnable() {
                        @Override
                        public void run() {
                            if(mDeviceCallback == null){
                                return;
                            }

                            mDeviceCallback.onGetBattery(mDevice,value);
                        }
                    });


            }
        }
    }




    public static int byteToInt(byte a){
        return a&0xff;
    }



    public static boolean checkedCommandCRC(byte[] b){
        byte[] a = new byte[10];
        System.arraycopy(b, 4, a, 0, 10);
        int crcValue = BleDeviceCRC.calcCrc16(a,0,10,65535);
        long high = ((long) (b[15] & 0xFF))*256;
        long result = high + (long)(b[14] & 0xFF);
        return result == crcValue;
    }

    private static int queId = -1;
    /** 校验是否是重复指令 */


    @Override
    public String getDeviceDisplayName(){
        return "动态血糖仪";
    }


    public boolean disableNotifications() {
        BleDeviceConnect connect  = mDevice.getDeviceConnect();
        if(connect == null){
            return false;
        }

        BluetoothGatt gatt = connect.getGatt();
        if (gatt == null || mNotifyCharacteristic == null)
            return false;

        if (!(gatt.setCharacteristicNotification(mNotifyCharacteristic, false)))
            return false;

        BluetoothGattDescriptor clientConfig = mNotifyCharacteristic.getDescriptor(UUID.fromString(this.CLIENT_CHARACTERISTIC_CONFIG));
        if (clientConfig == null)
            return false;

        Log.i(TAG, "disable notification");
        clientConfig.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);

        return gatt.writeDescriptor(clientConfig);
    }

    public boolean sendRequest(RequestBean request) {
        RNLog.d(TAG,"IBtConnectionImpl 已经连接上蓝牙，环境就绪，发送命令开始........ ");
        requestCode = request.getRequestCode();
        requestInt = request.getRequest();
        byte[] sendData = request.toTrancation();
        RNLog.d(TAG,DataFormatUtil.bytes2HexString(sendData));
        try {
            if (sendTHData(sendData)) {
                RNLog.d(TAG,"IBtConnectionImpl 命令数据发送成功");
                return Boolean.TRUE.booleanValue();
            }
//            ((Bt4ThCallback)this.context).bt4ThFailure(requestInt);
            RNLog.d(TAG,"IBtConnectionImpl 发送数据失败");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return Boolean.FALSE.booleanValue();
    }

    private boolean sendTHData(byte[] sendData) {
            if (this.mGattCharacteristicTrans == null) {
                RNLog.d(TAG,"sendTHData 11111");
                mDeviceManager.uhOh(mDevice,"send error");
                return false;
            }
            this.mGattCharacteristicTrans.setValue(sendData);
            if (this.mDevice.getDeviceConnect().getGatt().writeCharacteristic(this.mGattCharacteristicTrans)) {
                return true;
            }

            return false;
    }


    synchronized public void startMonitor(int requestCode) {
        Command.MONITOR_START.setRequest(requestCode);
        sendRequest(Command.MONITOR_START);
    }

    synchronized public void stopMonitor(int requestCode) {
        Command.MONITOR_STOP.setRequest(requestCode);
        sendRequest(Command.MONITOR_STOP);
    }

    synchronized public  void getNumberDataFromIndex(int requestCode, int index, int number) {
        byte[] numberArray = DataFormatUtil.int2WordBytesAndLow(number);
        byte[] indexArray = DataFormatUtil.int2WordBytesAndLow(index);
        List<Byte> list = new ArrayList();
        byte[] arrayOfByte1;
        int j;
        int i;
        if (numberArray != null)
        {
            j = (arrayOfByte1 = numberArray).length;
            for (i = 0; i < j; i++)
            {
                byte nByte = arrayOfByte1[i];
                list.add(Byte.valueOf(nByte));
            }
        }
        if (indexArray != null)
        {
            j = (arrayOfByte1 = indexArray).length;
            for (i = 0; i < j; i++)
            {
                byte iByte = arrayOfByte1[i];
                list.add(Byte.valueOf(iByte));
            }
        }
        byte[] paramArray = new byte[list.size()];
        for (i = 0; i < paramArray.length; i++) {
            paramArray[i] = ((Byte)list.get(i)).byteValue();
        }

        mProgressIndex = 0;
        RequestBean NDFI = new RequestBean(OPCode.GET, OBJCode.NDFI, paramArray,
                12, requestCode);
        sendRequest(NDFI);
    }

    synchronized public  void getAllDataFromIndex(int requestCode, int index) {
        mProgressIndex = 0;
        RequestBean ADFI = new RequestBean(OPCode.GET, OBJCode.ADFI, DataFormatUtil.int2WordBytesAndLow(index), 13,
                requestCode);
        sendRequest(ADFI);
    }

    synchronized public void getAllDataCount(int requestCode) {
        Command.AC.setRequest(requestCode);
        sendRequest(Command.AC);
    }

    synchronized public void getAllData(int requestCode) {
        mProgressIndex = 0;
        Command.AD.setRequest(requestCode);
        sendRequest(Command.AD);
    }

    synchronized public void getBattery(int requestCode) {
        Command.GET_BATTERY.setRequest(requestCode);
        sendRequest(Command.GET_BATTERY);
    }



    public  void getName(int requestCode) {
        Command.GET_NAME.setRequest(requestCode);
        sendRequest(Command.GET_NAME);
    }

    public  void getMaxNumber(int requestCode) {
        Command.GET_MAXNUM.setRequest(requestCode);
        sendRequest(Command.GET_MAXNUM);
    }

    public  void disConnection(int requestCode) {
        Command.CON_DIS.setRequest(requestCode);
        sendRequest(Command.CON_DIS);
    }

    public  void getSn(int requestCode) {
        Command.GET_SN.setRequest(requestCode);
        sendRequest(Command.GET_SN);
    }

    public  void getVersion( int requestCode) {
        Command.GET_VERSION.setRequest(requestCode);
        sendRequest(Command.GET_VERSION);
    }

    public void doAuthorization(int requestCode) {
        connectedStatus = START_AUTHORIZATION;
        Command.AUTHO.setRequest(requestCode);
        sendRequest(Command.AUTHO);
    }

    public  void getRecord(int requestCode) {
        Command.GET_RECORD.setRequest(requestCode);
        sendRequest(Command.GET_RECORD);
    }

//    public <T extends Context> boolean connectTh(T context, String address)
//    {
//        this.btConnection.createConnect(address);
//        return false;
//    }
//
//    public  <T extends Context> boolean isConnected(T content)
//    {
//        return this.btConnection.isRequest();
//    }

    public void getMonitorStatus(int requestCode)  {
        Command.MONITOR_STATUS.setRequest(requestCode);
        sendRequest(Command.MONITOR_STATUS);
    }


    protected static LinkedList<Byte> elList = new LinkedList();

    protected boolean checkReturn(BluetoothGattCharacteristic characteristic)
    {
        RNLog.d(TAG,"$$$$$$$$$$$$校验返回结果");
        byte[] temp = characteristic.getValue();
        if (temp != null) {
            String str = DataFormatUtil.bytes2HexString(temp);
            Integer[] eleByteNum;
            Double[] elc;
            Double[] ecc;
            if (temp.length == 9) {
                RNLog.d(TAG,"*返回值*：" +
                        DataFormatUtil.bytes2HexString(temp));

                byte[] eleByteNumber = { temp[6], temp[5] };
                byte[] eleByte = { temp[8], temp[7] };
                byte[] eccByte = { temp[2], temp[1] };
                eleByteNum =
                        DataFormatUtil.byteArray2Int(eleByteNumber);
                elc = DataFormatUtil.byteArray2Elec(eleByte);
                ecc = DataFormatUtil.byteArray2Vcc(eccByte);
                if ((elc != null) && (elc.length > 0) && (eleByteNum != null) &&
                        (eleByteNum.length > 0)) {
                    RNLog.d(TAG,"checkReturn： 电流序号" + eleByteNum[0] +
                            " 电流值" + elc[0]);
                    final int eleIndex = eleByteNum[0];
                    final Double value = elc[0];
                    post(new Runnable() {
                        @Override
                        public void run() {
                            if(mDeviceCallback == null){
                                return;
                            }

                            mDeviceCallback.onUpdateNewData(mDevice,eleIndex,value);
                        }
                    });
//                    ((Bt4ThCallback)this.context).bt4ThElec(eleByteNum[0], elc[0], ecc[0]);

                    JSONArray datas = new JSONArray();
                    JSONArray data = new JSONArray();
                    datas.put(data.put(eleByteNum[0]).put(elc[0]));
                }
                return false;
            }
            RNLog.d(TAG,"checkReturn：返回命为：" + str);
            if (isCommandWord(temp)) {
                RNLog.d(TAG,"command true");
                return Boolean.TRUE.booleanValue();
            }

            if (requestCode == 9) {
                RNLog.d(TAG,"Bt4Th-getVersion:" + str);
                String rtn = ResponseAnalysis.stringASCIIAnalysis(temp);
                RNLog.d(TAG,"Bt4Th-getVersion rtn:" + rtn);
//                ((Bt4ThCallback)this.context).bt4ThSuccess(requestInt, rtn);
                return Boolean.FALSE.booleanValue();
            }

            if (requestCode == 11) {
                RNLog.d(TAG,"Bt4Th-getRecord:" + str);
                THStatus[] rtn = ResponseAnalysis.statusAnalysis(temp);
                RNLog.d(TAG,"Bt4Th-getRecord rtn:" +
                        Arrays.toString(rtn));
//                ((Bt4ThCallback)this.context).bt4ThSuccess(requestInt, rtn);
                return Boolean.FALSE.booleanValue();
            }

            if(requestCode == 16){
                final Double value = (temp[1]&0xff*256+temp[2]&0xff)/10.0;
                post(new Runnable() {
                    @Override
                    public void run() {
                        if(mDeviceCallback == null){
                            return;
                        }
                        mDeviceCallback.onGetBattery(mDevice,value);
                    }
                });


                return Boolean.TRUE.booleanValue();
            }

            if (str.startsWith("FF113355EE")) {
                if (requestCode == 10)
                {
//                    ((Bt4ThCallback)this.context).bt4ThSuccess(requestInt, Boolean.valueOf(true));
                    return Boolean.FALSE.booleanValue();
                }
                return Boolean.TRUE.booleanValue();
            }


            Double[] elValues = null;
            byte[] elArray = null;
            if (((requestCode == 4) ||
                    (requestCode == 13) ||
                    (requestCode == 12)) &&
                    (temp != null))
            {

                int myElc = temp.length;
                for (int m = 0; m < myElc; m++)
                {
                    byte b = temp[m];
                    elList.add(Byte.valueOf(b));
                }
                if (elList.size() >= 2)
                {
                    int length = elList.size() % 2 == 0 ? elList.size() :
                            elList.size() - 1;
                    elArray = new byte[length];
                    for (int i = 0; i < length; i++) {
                        elArray[i] = ((Byte)elList.removeFirst()).byteValue();
                    }
                }
            }


            if (elArray != null)
            {
                RNLog.d(TAG,"getData rtn:" +
                        DataFormatUtil.bytes2HexString(elArray));
                switch (requestCode)
                {
                    case 4:{
                        final Double[] values = DataFormatUtil.byteArray2Elec(
                                DataFormatUtil.changeHighAndLow(temp));
                        final int index = mProgressIndex;
                        mProgressIndex +=1;

                            post(new Runnable() {
                                @Override
                                public void run() {
                                    if(mDeviceCallback == null){
                                        return;
                                    }
                                    mDeviceCallback.onGetProgressData(mDevice,values,index);
                                }
                            });
//                        ((Bt4ThCallback)this.context).bt4ThSuccess(requestInt, elValues);
                        return Boolean.FALSE.booleanValue();}
                    case 13:{
                        final Double[] values = DataFormatUtil.byteArray2Elec(
                                DataFormatUtil.changeHighAndLow(temp));
                        final int index = mProgressIndex;
                        mProgressIndex +=1;

                        post(new Runnable() {
                            @Override
                            public void run() {
                                if(mDeviceCallback == null){
                                    return;
                                }
                                mDeviceCallback.onGetProgressData(mDevice,values,index);
                            }
                        });

//                        ((Bt4ThCallback)this.context).bt4ThSuccess(requestInt, elValues);
                        return Boolean.FALSE.booleanValue();}
                    case 12:
//                        elValues = DataFormatUtil.byteArray2Elec(
//                                DataFormatUtil.changeHighAndLow(temp));
//                        RNLog.d(TAG,"getNumberDataFromIndex rtn:" +
//                                Arrays.toString(elValues));
                        final Double[] values = DataFormatUtil.byteArray2Elec(
                                DataFormatUtil.changeHighAndLow(temp));
                        final int index = mProgressIndex;
                        mProgressIndex +=1;

                        post(new Runnable() {
                            @Override
                            public void run() {
                                if(mDeviceCallback == null){
                                    return;
                                }
                                mDeviceCallback.onGetProgressData(mDevice,values,index);
                            }
                        });
//                        ((Bt4ThCallback)this.context).bt4ThSuccess(requestInt, elValues);
                        return Boolean.FALSE.booleanValue();
                }
            }
            return false;
        }
        return Boolean.FALSE.booleanValue();
    }

    private boolean isCommandWord(byte[] commandByte)
    {
        if ((commandByte == null) || (commandByte.length < 5)) {
            return false;
        }
        if ((isGetOrSet(commandByte[3])) && (isCommand(commandByte[4]))) {
            return true;
        }
        return false;
    }

    private boolean isGetOrSet(byte command)
    {
        if (command == OPCode.GET.getValue().byteValue()) {
            return true;
        }
        if (command == OPCode.SET.getValue().byteValue()) {
            return true;
        }
        return false;
    }

    private boolean isCommand(byte command)
    {
        if (command == OBJCode.VOLTAGE.getValue().byteValue()) {
            return true;
        }
        if (command == OBJCode.RECORD.getValue().byteValue()) {
            return true;
        }
        if (command == OBJCode.NDFI.getValue().byteValue()) {
            return true;
        }
        if (command == OBJCode.ADFI.getValue().byteValue()) {
            return true;
        }
        if (command == OBJCode.AC.getValue().byteValue()) {
            return true;
        }
        if (command == OBJCode.AD.getValue().byteValue()) {
            return true;
        }
        if (command == OBJCode.MONITOR.getValue().byteValue()) {
            return true;
        }
        if (command == OBJCode.ADVINTV.getValue().byteValue()) {
            return true;
        }
        if (command == OBJCode.AUTHO.getValue().byteValue()) {
            return true;
        }
        if (command == OBJCode.PW.getValue().byteValue()) {
            return true;
        }
        if (command == OBJCode.CLEINTV.getValue().byteValue()) {
            return true;
        }
        if (command == OBJCode.CLENUM.getValue().byteValue()) {
            return true;
        }
        if (command == OBJCode.NAME.getValue().byteValue()) {
            return true;
        }
        if (command == OBJCode.MAXNUM.getValue().byteValue()) {
            return true;
        }
        if (command == OBJCode.BATTERY.getValue().byteValue()) {
            return true;
        }

        if (command == OBJCode.CON_DIS.getValue().byteValue()) {
            return true;
        }
        if (command == OBJCode.SN.getValue().byteValue()) {
            return true;
        }
        if (command == OBJCode.VERSION.getValue().byteValue()) {
            return true;
        }
        if (command == OBJCode.CLET_ID.getValue().byteValue()) {
            return true;
        }
        return false;
    }

    private ResponseBean getReturnData(BluetoothGattCharacteristic characteristic) {
        List<Byte> responseData = new ArrayList();
        byte[] temp = characteristic.getValue();
        if (temp != null) {
            String str = DataFormatUtil.bytes2HexString(temp);
            if ((requestCode != 7) &&
                    (str.startsWith("FF113355EE"))) {
//                ((Bt4ThCallback)this.context).bt4ThFailure(requestInt);
                Log.d(TAG,"requestInt命令被舍弃了：断开了连接" + requestInt);
            }
            switch (requestCode) {
                case 1:
                    Log.d(TAG,"Bt4Th-startMonitor:" + str);
                    break;
                case 2:
                    Log.d(TAG,"Bt4Th-stopMonitor:" + str);
                    break;
                case 12:
                    Log.d(TAG,"Bt4Th-getNumberDataFromIndex:" + str);
                    break;
                case 13:
                    Log.d(TAG,"Bt4Th-getAllDataFromIndex:" + str);
                case 3:
                    Log.d(TAG,"Bt4Th-getAllDataCount:" + str);
                    break;
                case 4:
                    Log.d(TAG,"Bt4Th-getAllData:" + str);
                    break;
                case 5:
                    Log.d(TAG,"Bt4Th-getName:" + str);
                    this.emitterCode = str;
                    break;
                case 6:
                    Log.d(TAG,"Bt4Th-getMaxNumber:" + str);
                    break;
                case 7:
                    Log.d(TAG,"Bt4Th-disConnection:" + str);
                    break;
                case 8:
                    Log.d(TAG,"Bt4Th-getSn:" + str);
                    break;
                case 9:
                    Log.d(TAG,"Bt4Th-getVersion:" + str);
                    break;
                case 10:
                    Log.d(TAG,"Bt4Th-doAuthorization:" + str);
                    break;
                case 11:
                    Log.d(TAG,"Bt4Th-getRecord:" + str);
                    break;
            }
            for (int i = 0; i < temp.length; i++) {
                responseData.add(Byte.valueOf(temp[i]));
            }
        }
        if (responseData.size() >= 5) {
            ResponseBean response = new ResponseBean();
            byte[] event = new byte[3];
            for (int i = 0; i < event.length; i++) {
                event[i] = ((Byte)responseData.remove(0)).byteValue();
            }
            response.setEvent(event);

            response.setOpCode(OPCode.valueOf((Byte)responseData.remove(0)));

            response.setObjCode(OBJCode.valueOf((Byte)responseData.remove(0)));

            Byte[] array = (Byte[])responseData.toArray(new Byte[0]);
            byte[] datas = new byte[array.length];
            for (int i = 0; i < array.length; i++) {
                datas[i] = array[i].byteValue();
            }
            response.setData(datas);

            return response;
        }
        return null;
    }
}
