package com.example.administrator.wingcool_gt9_apk;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
//import android.hardware.usb.UsbPipe;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbRequest;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.MarkerView;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NoiseAnalysis extends AppCompatActivity implements OpenDevicesReceiver.OpenDevicesListener {

    private Context mAlertContext;
    //MainActivity mMainAct = new MainActivity();
    private byte[] mRawdataBytes = new byte[256];

    private static final int RAWDATA_MESSAGE = 0;
    private static final int LOG1_MESSAG = 1;
    private static final int CLEAR_MESSAGE= 2;
    private static final int LOG2_MESSAGE = 3;
    private static final int DEBUG_MESSAGE_ERROR = 4;
    private static final int UPDATE_FW= 5;
    private static final int DIFF_MESSAGE = 6;
    private static final int MANUALDIFF_MESSAGE = 7;

    public static String USB_ACTION = "com.host2device";
    public static  String ACTION_USB_PERMISSION = "com.host2device.USB_PERMISSION";
    private TextView mLog;
    private EditText mMessage;
    // private UsbDetachedReceiver mUsbDetachedReceiver;
    private ExecutorService mThreadPool;
    private UsbManager mUsbManager;
    private OpenDevicesReceiver fwOpenDevicesReceiver;
    private TextView mError;
    private UsbDeviceConnection mUsbDeviceConnection;
    private UsbRequest mUsbRequest = new UsbRequest();

    private UsbEndpoint mUsbEndpointOut;
    private UsbEndpoint mUsbEndpointIn;
    private boolean bIsconnected = false;

    private boolean isDetached = false;
    private byte[] mBytes = new byte[1024];
    private byte[] mSendData = new byte[1024];
    private byte[] mConfigData = new byte[1024];

    String value;
    private boolean isReceiverMessage = true;

    private boolean isSendMessage = true;

    private boolean isNeedFindDevice  = true;

    private int dataLength;

    private UsbInterface mUsbInterface;
    private StringBuffer mStringBuffer = new StringBuffer();
    private Context mDataContext;
    private int iProductId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_noise_analysis);
        mAlertContext = NoiseAnalysis.this;
        //ConstantsActivity.activityList.add(this);
        //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        //switchLanguage(ConstantsActivity.langae);

        openDevices();
       // initTextView();
       // showNoiseView();
        showNoiseView();

    }

    //核心设置的代码
    protected void switchLanguage(String language) {
        Resources resources = getResources();
        Configuration config = resources.getConfiguration();
        DisplayMetrics dm = resources.getDisplayMetrics();
        switch (language) {
            case "zh":
                config.locale = Locale.CHINESE;
                resources.updateConfiguration(config, dm);
                break;
            case "en":
                config.locale = Locale.ENGLISH;
                resources.updateConfiguration(config, dm);
                break;
            default:
                config.locale = Locale.US;
                resources.updateConfiguration(config, dm);
                break;
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    private void showNoiseView() {

        mThreadPool.execute(new Runnable() {
            @Override

            public void run() {
                dataLength = 157;
                byte startFreq;
                byte endFreq ;
                int bitFreq ;
                byte currentFreqIndex ;
                int currentFreq;
                int freqNum;
                byte addressH;
                byte addressL;

                while(true) {
                    StringBuilder stringBuilder1 = new StringBuilder("");
                    StringBuilder stringBuilder2 = new StringBuilder("");
                    //获取噪声数据
                    //if((mUsbEndpointIn != null) || (mUsbEndpointOut != null)) {
                    if (bIsconnected == true){
                        if ((iProductId == 0x0819) || (iProductId == 0x8191) || (iProductId == 0x0528))
                        {
                            addressH = (byte) 0xF3;
                            addressL = (byte) 0xB4;
                            if (!iicRead(addressH, addressL, mRawdataBytes, 156)) {  //读取ADC噪声
                                startFreq = 0;
                                continue;
                            } else {

                                iicRead((byte)0x81, (byte)0xBD, mConfigData,1);

                                startFreq = mRawdataBytes[0];
                                endFreq = mRawdataBytes[1];
                                freqNum = endFreq - startFreq + 1;
                                bitFreq = 1000000 / (mConfigData[0] & 0xFF);
                                currentFreqIndex = mRawdataBytes[5];
                                currentFreq = currentFreqIndex * bitFreq;
                            }
                        }
                        else
                        {
                            addressH = (byte) 0xc6;
                            addressL = (byte) 0xe6;
                            if (!iicRead(addressH, addressL, mRawdataBytes, 156)) {  //读取ADC噪声

                                startFreq = 0;
                                continue;
                            } else {

                                startFreq = mRawdataBytes[0];
                                endFreq = mRawdataBytes[1];
                                freqNum = endFreq - startFreq + 1;
                                bitFreq = ((mRawdataBytes[2] & 0xFF) << 8) + (mRawdataBytes[3] & 0xFF);
                                currentFreqIndex = mRawdataBytes[5];
                                currentFreq = currentFreqIndex * bitFreq;
                            }
                        }
                    }
                    else{
                        startFreq = 0;
                        endFreq = 0;
                        bitFreq = 0;
                        currentFreqIndex = 0;
                        freqNum =0;
                        currentFreq= 137;
                    }

                    //设置数据

                    LineChart mLineChart = (LineChart) findViewById(R.id.lineChart);

                    //设置x轴
                    XAxis xAxis = mLineChart.getXAxis();
                    xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//值：BOTTOM,BOTH_SIDED,BOTTOM_INSIDE,TOP,TOP_INSIDE
                    //xAxis.setGranularity(1f); //比例间隔
                    if(startFreq != 0){
                        xAxis.setLabelCount(freqNum, true);//刻度数量 此函数只能显示26个标签
                        xAxis.setAxisMinimum(startFreq * bitFreq);// x刻度最小值
                        xAxis.setAxisMaximum(endFreq * bitFreq); //x刻度最大值
                    }
                    else {
                        xAxis.setLabelCount(21, true);//刻度数量
                        xAxis.setAxisMinimum(120f);// x刻度最小值
                        xAxis.setAxisMaximum(280f); //x刻度最大值
                    }
                    xAxis.setTextSize(12f);
                    xAxis.setGridColor(Color.GRAY);
                    mLineChart.setScaleXEnabled(false);  //关闭缩放


                    //设置y轴
                    //YAxis leftYAxis = mLineChart.GET();
                    YAxis rightYAxis = mLineChart.getAxisRight();

                    rightYAxis.setAxisMinimum(0f);
                    rightYAxis.setAxisMaximum(255f);
                    //rightYAxis.setGranularity(1f);
                    rightYAxis.setLabelCount(16,true);
                    rightYAxis.setTextColor(Color.BLACK); //文字颜色
                    rightYAxis.setTextSize(13f);
                    //rightYAxis.setGridColor(Color.GRAY); //网格线颜色
                    rightYAxis.setDrawGridLines(false);  //屏蔽网格线

                    YAxis leftYAxis = mLineChart.getAxisLeft();

                    leftYAxis.setAxisMinimum(0f);
                    leftYAxis.setAxisMaximum(255f);
                    //leftYAxis.setGranularity(1f);
                    leftYAxis.setLabelCount(16,true);
                    leftYAxis.setTextColor(Color.BLACK); //文字颜色
                    leftYAxis.setTextSize(13f);
                    // rightYAxis.setGridColor(Color.GRAY); //网格线颜色
                    leftYAxis.setDrawGridLines(false);  //屏蔽网格线

                    mLineChart.setScaleYEnabled(false);  //关闭缩放

                    List<Entry> entries = new ArrayList<>();
                    float fl_max = 0;
                    int k = 6;

                    try {
                        if (startFreq != 0) {
                            for (int i = startFreq * bitFreq; i < endFreq * bitFreq; ) {
                                // k = 6;
                                int fl_temp = mRawdataBytes[k];
                                if (fl_temp > fl_max) {
                                    fl_max = fl_temp;
                                }
                                entries.add(new Entry(i, fl_temp));
                                i = i + bitFreq;
                                k++;
                            }
                        } else {
                            for (int i = 120; i <= 280; ) {
                                float fl_temp = (float) (Math.random()) * 80;
                                if (fl_temp > fl_max) {
                                    fl_max = fl_temp;
                                }
                                entries.add(new Entry(i, fl_temp));
                                i = i + (280 - 120) / 20;
                            }
                        }
                    }  catch (ArithmeticException e) {
                        // mShow.setText("ArithmeticException!");
                        //  mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
                        e.printStackTrace();
                    } catch (ArrayIndexOutOfBoundsException e) {
                        // mShow.setText("ArrayIndexOutOfBoundsException!");
                        //  mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
                        e.printStackTrace();
                    }

                    //最高点线
                    StringBuilder maxnoise = new StringBuilder("");
                    maxnoise.append((String)getResources().getString(R.string.maximumnoise));
                    LimitLine limitLine = new LimitLine(fl_max,maxnoise.toString()); //得到限制线
                    limitLine.setLineWidth(1f); //宽度
                    limitLine.setTextSize(12f);
                    limitLine.setTextColor(Color.parseColor("#F15A4A"));  //颜色
                    limitLine.setLineColor(Color.parseColor("#5C5C5C"));
                    rightYAxis.addLimitLine(limitLine); //



                    // 当前频点线

                    int v =  currentFreq;
                    String dv = Integer.toString(v);
                    stringBuilder1.append((String)getResources().getString(R.string.currentfrequency));
                    stringBuilder1.append(dv);
                    stringBuilder1.append("Hz");

                    LimitLine currentFreqLine = new LimitLine(currentFreq,stringBuilder1.toString()); //得到限制线
                    //LimitLine currentFreqLine = new LimitLine(137,"当前频点"); //得到限制线
                    currentFreqLine.setLineWidth(4f); //宽度
                    currentFreqLine.setTextSize(40f);
                    currentFreqLine.setTextColor(Color.parseColor("#e75049"));  //颜色
                    currentFreqLine.setLineColor(Color.parseColor("#e75049"));
                    xAxis.addLimitLine(currentFreqLine); //X轴添加限制线


                    //设置描述内容
                    v =  bitFreq;
                    dv = Integer.toString(v);
                    stringBuilder2.append("[" + (String)getResources().getString(R.string.bitfrequency) + " = ");
                    stringBuilder2.append(dv);
                    stringBuilder2.append("Hz, ");
                    v =  freqNum;
                    dv = Integer.toString(v);
                    stringBuilder2.append((String)getResources().getString(R.string.frequencyfactor) + " = ");
                    stringBuilder2.append(dv);
                    stringBuilder2.append("]");

                    Description description = new Description();
                    description.setText(stringBuilder2.toString());
                    description.setTextColor(Color.parseColor("#FFC800"));
                    description.setTextSize(18f);
                    // description.setTextAlign(Paint.Align.LEFT);
                    //description.setTextAlign(Paint.Align.CENTER);
                    //description.setPosition(1000,300);
                    mLineChart.setDescription(description);


                    //一个LineDataSet就是一条线
                    LineDataSet lineDataSet;
                    lineDataSet = new LineDataSet(entries, "频点噪声(X轴单位：hz，Y轴单位：0-255)");
                    LineData data = new LineData(lineDataSet);
                    //线颜色
                    lineDataSet.setColor(Color.parseColor("#F15A4A"));
                    //线宽度
                    lineDataSet.setLineWidth(2f);
                    //不显示圆点
                    // lineDataSet.setDrawCircles(false);
                    lineDataSet.setDrawCircleHole(true);
                    lineDataSet.setCircleColorHole(Color.parseColor("#F15A4A"));
                    lineDataSet.setCircleColor(Color.parseColor("#F15A4A"));  //淡红色
                    lineDataSet.setCircleRadius(3f);
                    //线条平滑
                    //lineDataSet.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
                    //设置折线图填充
                   ////        lineDataSet.setDrawFilled(true);
                   // LineData ldata = new LineData(lineDataSet);
                    //无数据时显示的文字
                   // mLineChart.setNoDataText("暂无数据");
                    //折线图不显示数值
                   // ldata.setDrawValues(false);
                   // mLineChart.setVisibleXRangeMaximum(24);//需要在设置数据源后生效
                    //mLineChart.setDragEnabled(true);//打开或关闭对图表的拖动。
                    //显示边界
                    mLineChart.setDrawBorders(true);

                   // lineDataSet.setHighlightEnabled(false); //如果设置为true，在图表中选中触屏高亮。
                    //mLineChart.setHighlightPerDragEnabled(false);// 设置为true时允许高亮显示拖动结束的对象在缩放到最下时。默认：true
                   // mLineChart.setTouchEnabled(false);// 允许你打开或者关闭与图表的所有触摸交互的情况
                    //lineDataSet.setHighlightIndicatorEnabled(false); // 如果设置为true， 指标线（或杆）将展示被选择的线的绘制的值。
                 //   mLineChart.setActivated(true);
                   // MyMarkerView mv = new MyMarkerView(this);

                    //
                    Legend legend = mLineChart.getLegend();
                    legend.setEnabled(false);   //先把左下方的标签设为false，否则多点击几次会报空指针异常，挂死


                   // MyMarkerView mv = new  MyMarkerView(this);
                   // mLineChart.setMarkerView(mv);

                    mLineChart.setData(data);
                    SystemClock.sleep(100);
                    rightYAxis.removeLimitLine(limitLine);
                    xAxis.removeLimitLine(currentFreqLine);
                   // mLineChart.setData(data);
                    SystemClock.sleep(10);
                } //while

        }   //ThreadPool
    });   //ThreadPool

    }

    /**
     * 打开设备 , 让车机和手机端连起来
     */

    public void openDevices() {

        mThreadPool = Executors.newFixedThreadPool(5);
        mDataContext = getApplicationContext();
        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        //列举设备(手机)
        fwOpenDevicesReceiver = new OpenDevicesReceiver(this);
        mThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                SystemClock.sleep(1000);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(mDataContext, 0, new Intent(ACTION_USB_PERMISSION), 0);
                IntentFilter intentFilter = new IntentFilter(USB_ACTION);

                registerReceiver(fwOpenDevicesReceiver, intentFilter);
                while(isNeedFindDevice) {
                    SystemClock.sleep(100);
                    HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
                    if (deviceList != null) {
                        for (UsbDevice usbDevice : deviceList.values()) {
                            //int productId = usbDevice.getProductId();
                            int vendorId = usbDevice.getVendorId();
                            if ((vendorId == 0x27C0)          //之前VID错误了，做兼容
                                    ||(vendorId == 0x27C6)    //汇顶的VID
                                    ||(vendorId == 0x222A)    //奕力的VID
                                    ||(vendorId == 0x056A))   //8191主动笔和Wacom主动笔
                            {
                                if (mUsbManager.hasPermission(usbDevice)) {
                                    //initAccessory(usbDevice);
                                    // String avalue = "S818 IS PERMISSION";
                                    // mShow.setText(avalue);//输出显示
                                    initDevice();

                                } else {
                                    mUsbManager.requestPermission(usbDevice, pendingIntent);
                                    break;
                                }
                                break;
                            }
                        }
                    } else {
                        // mError.setText("请连接USB");
                    }
                    // }
                }

            }   //ThreadPool
        });   //ThreadPool

    }

    /**
     * 初始化设备(手机) , 当手机进入Accessory模式后 , 手机的PID会变为Google定义的2个常量值其中的一个 ,
     */
    private void initDevice() {
        HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
        Collection<UsbDevice> values = deviceList.values();
        if (!values.isEmpty()) {
            for (UsbDevice usbDevice : values) {
                //int productId = usbDevice.getProductId();
                int vendorId = usbDevice.getVendorId();
                //if (productId == 0x0818 || productId == 0x0001 )
                if ((vendorId == 0x27C0)          //之前VID错误了，做兼容
                        ||(vendorId == 0x27C6)    //汇顶的VID
                        ||(vendorId == 0x222A)    //奕力的VID
                        ||(vendorId == 0x056A))   //8191主动笔和Wacom主动笔
                {
                    if (mUsbManager.hasPermission(usbDevice)) {

                        UsbInterface usbInterface = usbDevice.getInterface(1);

                        for (int i = 0; i < usbInterface.getEndpointCount(); i++) {
                            UsbEndpoint ep = usbInterface.getEndpoint(i);

                            if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
                                //mUsbEndpointIn = ep;
                                mUsbEndpointOut = ep;
                            } else {
                                //mUsbEndpointOut = ep;
                                mUsbEndpointIn = ep;
                            }
                        }

                        if ((null == mUsbEndpointIn) || (null == mUsbEndpointOut)) {
                            mUsbDeviceConnection = mUsbManager.openDevice(usbDevice);
                            if (mUsbDeviceConnection!=null) {
                                int i = mUsbDeviceConnection.controlTransfer(0x00, 0x09,
                                        0x002, 0, null, 0, 100);
                                SystemClock.sleep(1000);
                                if (i >= 0) {
                                    //mHandler.sendEmptyMessage(DEBUG_MESSAGE_SUCCESS);
                                } else {
                                    //mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
                                }
                            }
                        } else {
                            bIsconnected = false;
                            isNeedFindDevice = false;
                            mUsbInterface = usbInterface;
                            mUsbDeviceConnection = mUsbManager.openDevice(usbDevice);
                            mUsbDeviceConnection.claimInterface(mUsbInterface, true);
                            if(null != mUsbEndpointIn){
                                iProductId = usbDevice.getProductId();
                                bIsconnected = true;
                            }
                        }
                    } else {
                        mUsbManager.requestPermission(usbDevice, PendingIntent.getBroadcast(mDataContext, 0, new Intent(""), 0));
                    }
                }
            }
        } else {
            // finish();
        }

        //  }
        // }
        // });

    }
   //  boolean iicByteWrite(byte addressHigh, byte addressLow, byte subCommand, byte data);

    private byte iicByteData[]={
            //0    1   2     3    4    5    6
            0x03,0x00,0x0f,0x00,0x00,0x00,0x01,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,

    };
    private byte iicWriteData[]={
            //0    1   2     3    4    5    6
            0x03,0x00,0x0f,0x00,0x00,0x00,0x39,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,

    };


/**
    private enum _EN_COMMAND_TYPE {
        I2C_READ,  //0x00
        I2C_WRITE, //0x01
        I2C_READ_BLOCK, //0x02
        I2C_WRITE_ACK, //0x03
        RESET_TOUCH_IC,  //0x04
        REBOOT_FROM_SRAM,  //0x05
        ENTRY_DEBUG_MODE,  //0x06
        QUIT_DEBUG_MODE,  //0x07
        HID_RECONNECT,  //0x08
        HID_DISCONNECT,  //0x09
        CHECK_HID_CONNECTION,  //0x0A
        CHECK_TOUCH_IC_CONNECTION, //0x0B
        WRITE_SYNC, //0x0C
        READ_SYNC, //0x0D
        S818X_ENTER_UPDATE_MODE,  //0x0E
        NULL_COMMAND, //0x0F
    }
*/
    //发送命令，使得S818可以通过IIC向GT9的固定地址读取任意bytes的数据
    private boolean iicRead(byte addressHigh,byte addressLow,byte[] wBuffer,int length) {

        int i;
        iicByteData[1] = 0x00; //read GT9 command
        iicByteData[2] = 0x0f; //no command
        iicByteData[3] = addressHigh;
        iicByteData[4] = addressLow;
        iicByteData[5] = 0x00;
        iicByteData[6] = 63;  //length 一次接收63个数据

        for (int j = 7; j < 64; j++) {
            iicWriteData[j] = 0x00;
        }

        int address1 = ((addressHigh&0xff)<<8);
        int address2 = addressLow&0xff;
        int address = address1|address2;

        int sendTimes = length/63 + 1;  //预计是向下取整，所以+1

        for (int k = 0; k < sendTimes; k++) {
            int finalOffset = k*63; //每次只能发57bytes数据
            int offset = k*64;

            if(length - (finalOffset ) < 63) {

                iicByteData[6] = (byte) (length - (finalOffset));  //length
            }
            else
            {
                iicByteData[6] = 63;
            }

            //发送读取命令
            i = mUsbDeviceConnection.bulkTransfer(mUsbEndpointOut, iicByteData, 0, 0x40, 100);
            if (i != 0x40)
                return false;  //传输失败
            // SystemClock.sleep(1);

            isReceiverMessage = false;  //先关闭循环接收信息

            //接收数据
            i = mUsbDeviceConnection.bulkTransfer(mUsbEndpointIn, wBuffer, offset, 0x40, 3000);

            if (i != 0x40) {
               // mError.setText("iicWrite Failed");
                return false;

            }

            address = address + 63;
            iicByteData[3] = (byte)(address>>8);
            iicByteData[4] = (byte)address;
        }

        //将report id从数组中去除
        //byte[] temperBuffer =new byte[length];
        if(true) {
            int count1 = 0;
            for (int k = 0; k < length; k++) {
                if (k % 63 == 0) {
                    count1++;
                }

                wBuffer[k] = wBuffer[k + count1];

            }
        }
        return true;
    }
/**
    //发送命令，使得S818可以通过IIC向GT9的固定地址写任意bytes的数据
    private  boolean iicWrite(byte addressHigh,byte addressLow,byte[] wBuffer,int offset,int length) {
        int i;
        iicWriteData[1] = 0x01; //write GT9 command
        iicWriteData[2] = 0x0f; //no command
        iicWriteData[3] = addressHigh;
        iicWriteData[4] = addressLow;
        iicWriteData[5] = 0x00;
        iicWriteData[6] = 0x39;  //length

        int address1 = ((addressHigh&0xff)<<8);
        int address2 = addressLow&0xff;
        int address = address1|address2;

        int sendTimes = length/57 + 1;  //预计是向下取整，所以+1

        for (int k = 0; k < sendTimes; k++) {
            int finalOffset = offset + k*57; //每次只能发57bytes数据

            if(length - (finalOffset -offset) < 57) {

                iicWriteData[6] = (byte) (length - (finalOffset -offset));  //length
            }
            else
            {
                iicWriteData[6] = 0x39;
            }

            for (int j = 7; j < 64; j++) {
                iicWriteData[j] = wBuffer[finalOffset + j -7];
            }
            i = mUsbDeviceConnection.bulkTransfer(mUsbEndpointOut, iicWriteData, 0, 0x40, 100);

            if (i != 0x40) {
              //  mError.setText("iicWrite Failed");
                return false;

            }

            address = address + 57;
            iicWriteData[3] = (byte)(address>>8);
            iicWriteData[4] = (byte)address;
        }

        return true;
    }


    //发送命令，使得S818可以通过IIC向GT9的固定地址写1byte数据
    private  boolean iicByteWrite(byte addressHigh,byte addressLow,byte subCommand,byte data) {
        int i;

        iicByteData[1] = 0x01; //write GT9 command
        iicByteData[2] = subCommand;
        iicByteData[3] = addressHigh;
        iicByteData[4] = addressLow;
        iicByteData[5] = 0x00;
        iicByteData[6] = 0x01;  //length

        iicByteData[7] = data;
        if ((null == mUsbEndpointIn) || (null == mUsbEndpointOut)){
            i=0;
           // mrawlog.setText("mUsbEndpointIn is null");
        }
        else {
            i = mUsbDeviceConnection.bulkTransfer(mUsbEndpointOut, iicByteData, 0, 0x40, 100);
        }
        // i = 0;
        if(i == 0x40)
            return true;
        else
            return false;
    }

    //发送命令，使得S818可以通过IIC向GT9的固定地址读取1byte数据
    private byte iicByteRead(byte addressHigh,byte addressLow) {

        iicByteData[1] = 0x00; //read GT9 command
        iicByteData[2] = 0x0f;  //no command
        iicByteData[3] = addressHigh;
        iicByteData[4] = addressLow;
        iicByteData[5] = 0x00;   //length
        iicByteData[6] = 0x01;   //lengthlow

        iicByteData[7] = 0x00;
        //  mThreadPool.execute(new Runnable() {
        //     @Override
        //     public void run() {
        int i;
        boolean byteReceiverLoop = true;
        i = mUsbDeviceConnection.bulkTransfer(mUsbEndpointOut, iicByteData, 0, 0x40, 100);
        if (i != 0x40)
            return 0x77;  //用0x77来表示传输失败
        SystemClock.sleep(5);

        isReceiverMessage = false;  //先关闭循环接收信息

        // while(byteReceiverLoop) {

        i = mUsbDeviceConnection.bulkTransfer(mUsbEndpointIn, mBytes, 0, 0x40, 3000);
        SystemClock.sleep(5);
        if (i == 0x40)
            return mBytes[1];
        else
            return 0x77;  //用0x77来表示传输失败
        // }

    }
*/

    @Override
    protected void onDestroy() {

        super.onDestroy();

        if (mUsbDeviceConnection != null) {
            mUsbDeviceConnection.releaseInterface(mUsbInterface);
            mUsbDeviceConnection.close();
            mUsbDeviceConnection = null;
        }
        mUsbEndpointIn = null;
        mUsbEndpointOut = null;
        bIsconnected = false;
        isReceiverMessage = false;
        isNeedFindDevice = false;
        mThreadPool.shutdownNow();
        // unregisterReceiver(mUsbDetachedReceiver);
        unregisterReceiver(fwOpenDevicesReceiver);
    }
}
