package com.example.administrator.wingcool_gt9_apk;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbRequest;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

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

public class TestOperation extends AppCompatActivity
        implements   OpenDevicesReceiver.OpenDevicesListener, View.OnClickListener {
    private Context mAlertContext;
    //MainActivity mMainAct = new MainActivity();
    private byte[] mRawdataBytes = new byte[42*32*2+64*2];
    private byte[] mManualRef = new byte[42*32*2+64*2];
    private int[] mManualRefInt = new int[42*32+64];
    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;

    private static final String USB_ACTION = "com.host2device";
    private static final String ACTION_USB_PERMISSION = "com.host2device.USB_PERMISSION";
    private ExecutorService mThreadPool;
    private UsbManager mUsbManager;
    private OpenDevicesReceiver daOpenDevicesReceiver;
    private UsbDeviceConnection mUsbDeviceConnection;
    private UsbRequest mUsbRequest = new UsbRequest();
    private UsbEndpoint mUsbEndpointOut;
    private UsbEndpoint mUsbEndpointIn;

    private Button btn_StartTesting;
    private Button btn_DiffdataShow;
    private Button btn_ReffdataShow;
    private Button btn_ManualdiffdataShow;
    private Button btn_Manualreff;
    private Button btn_Stop;

    private byte[] mBytes = new byte[1024];

    private EditText edt_Maximum;
    private EditText edt_Minimum;
    private EditText edt_TestiInformation;  //显示测试过程信息

    private boolean isReceiverMessage = true;
    private boolean isNeedFindDevice  = true;

    private UsbInterface mUsbInterface;
    private Context mContext;

    private int colnum;
    private int rownum;
    private int iMaximum;  //存放外部输入的最大值测试阈值
    private int iMinimum;  //存放外部输入的最小值测试阈值
    private byte byMaximumOverCount;  //最大值超过阈值的次数
    private byte byMinimumOverCount;  //最小值超过阈值的次数
    private byte byTestCount;  //统计测试的帧数
    private byte byReTestCount;  //重新测试的测试，最多测试4次输出判定结果
    private boolean bTestResult;  //测试结果pass或者fail;
    private TextView tvMaximum;
    private TextView tvMinimum;
    //private TextView tvMaxSubMin;
    //private TextView tvMaxDivMin;
    //private TextView tvDataContent;
    //private TextView tvAverage;
    //private TextView tvSTD;
    //private TextView tvATR;
    //private TextView tvMAD;
    private TextView tvTestResult;  //显示测试结果

    public String stTestLog;  //测试信息存放字符串
    String stTestLogShow= "";  //测试信息合并起来存放字符串

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_testoperation);
        mAlertContext = TestOperation.this;
        //ConstantsActivity.activityList.add(this);
        //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        //switchLanguage(ConstantsActivity.langae);
        InitButton();
        InitEditText();
        InitListener();
        InitData();
        initTextView();
		openDevices();
    }

    //核心设置的代码
    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 InitButton(){
        btn_StartTesting = (Button) findViewById(R.id.starttesting);
        btn_Stop = (Button) findViewById(R.id.stop);
    }

    private void InitEditText(){
        edt_Maximum = (EditText) findViewById(R.id.inputmaximum);
        edt_Minimum = (EditText) findViewById(R.id.inputminimum);
        edt_TestiInformation = (EditText) findViewById(R.id.testinformation);  //显示测试过程信息
    }

    private void InitListener(){
        btn_StartTesting.setOnClickListener(this);
        btn_Stop.setOnClickListener(this);
    }

    private void InitData(){
        //btn_RawdataShow.setEnabled(false);
        //btn_Stop.setEnabled(false);
    }

    /**
     * 打开设备 , 让车机和手机端连起来
     */
    public void openDevices() {

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

                registerReceiver(daOpenDevicesReceiver, 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 ((productId == 0x0818 && vendorId == 0x27C0)
                                    ||(productId == 0x0001 && vendorId == 0x222A))   //奕力的PID和VID
                            {
                                if (mUsbManager.hasPermission(usbDevice)) {
                                    initDevice();
                                } else {
                                    mUsbManager.requestPermission(usbDevice, pendingIntent);
                                    break;
                                }
                                break;
                            }
                        }
                    }
                }
            }   //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();
                if (productId == 0x0818 || productId == 0x0001) {  //0x0001是奕力的PID

                    if (mUsbManager.hasPermission(usbDevice)) {

                        mUsbDeviceConnection = mUsbManager.openDevice(usbDevice);
                        if (mUsbDeviceConnection != null) {

                            int interfaceCount = usbDevice.getInterfaceCount();
                            // for (int interfaceIndex = 0; interfaceIndex < interfaceCount; interfaceIndex++)
                            {
                                // UsbInterface usbInterface = usbDevice.getInterface(interfaceIndex);
                                UsbInterface usbInterface = usbDevice.getInterface(1);

                                if(UsbConstants.USB_CLASS_HID != usbInterface.getInterfaceClass())
                                {
                                    // continue;
                                }

                                for (int i = 0; i < usbInterface.getEndpointCount(); i++) {
                                    UsbEndpoint ep = usbInterface.getEndpoint(i);
                                    if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
                                        if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
                                            //mUsbEndpointIn = ep;
                                            mUsbEndpointOut = ep;
                                        } else {
                                            //mUsbEndpointOut = ep;
                                            mUsbEndpointIn = ep;
                                        }
                                    }
                                    else{
                                        // mHandler.sendEmptyMessage(CONNECTED_SUCCESS);
                                    }
                                }

                                if ((null == mUsbEndpointIn) || (null == mUsbEndpointOut)) {
                                    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 {

                                    //if(0x80 == mUsbEndpointIn)
                                    //mlog1.setEnabled(true);
                                    //mToggle = false;
                                    //isDetached = true;
                                    isNeedFindDevice = false;
                                    // mSendMessage.setEnabled(true);

                                    mUsbInterface = usbInterface;
                                    mUsbDeviceConnection = mUsbManager.openDevice(usbDevice);
                                    if(null != mUsbEndpointIn){

                                    }
                                }
                            }

                        }
                    } else {
                        mUsbManager.requestPermission(usbDevice, PendingIntent.getBroadcast(mContext, 0, new Intent(""), 0));
                    }
                }
            }
        } else {
            // finish();
        }
    }

    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,

    };

    //发送命令，使得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;
    }

    private boolean iicTest() {

        if(isReceiverMessage)
            return false;

        return true;
    }

    //发送命令，使得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来表示传输失败
        // }

        // return 0x77;  //用0x77来表示传输失败
        // }
        // });

    }

    private boolean changeToDebugMode() {

        byte maddressHigh = (byte)0x80;
        byte maddressLow = (byte)0x46;
        byte msubcommand =0x0f ;  //
        byte mdata = (byte)0x01;

        //if(false) {
        maddressHigh = (byte) 0x80;
        maddressLow = (byte) 0x40;
        msubcommand = (byte) 0x06;   //ENTRY_DEBUG_MODE
        mdata = (byte) 0x01;

        if (!iicByteWrite(maddressHigh, maddressLow, msubcommand, mdata)) {
           // mrawlog.setText("[changeDebug]0x8040 write failed");
            return false;
        }
        //}

        return true;
    }

    private boolean changeToNormalMode() {

        byte maddressHigh = (byte)0x80;
        byte maddressLow = (byte)0x40;
        byte msubcommand =0x07 ;  //QUIT_DEBUG_MODE
        byte mdata = (byte)0x00;

        if(!iicByteWrite(maddressHigh,maddressLow,msubcommand,mdata)) {
            //   mrawlog.setText("[changeNormal]0x8040 write failed");
            return false;
        }
        else
        {
            //mrawlog.setText("[changeNormal]0x8040 write success");
        }

        return true;
    }


    byte showAddressHigh = (byte)0x8b;
    byte showAddressLow = (byte)0x98;  //需要显示的 address
    private int[] datatemp = new int[42*30];
    private boolean getRawdata() {

        byte maddressHigh = (byte)0x80;
        byte maddressLow = (byte)0x40;  //rawdata address
        byte msubcommand =0x0d ;  //  READ_SYNC
        byte mdata = (byte)0x01;
        if(!iicByteWrite(maddressHigh,maddressLow,msubcommand,mdata)) {
            // mrawlog.setText("READ_SYNC write failed");
            return false;
        }


        if(!iicRead(showAddressHigh,showAddressLow,mRawdataBytes,42*30*2)) {  //读取rawData
            // mrawlog.setText("iicRead rawdata failed");
            return false;
        }

        maddressHigh = (byte)0x81;
        maddressLow = (byte)0x4E;  // SYNC address
        msubcommand =0x0f ;  //  READ_SYNC
        mdata = (byte)0x00;

        // MainActivity mMainAct = new MainActivity();
        if(!iicByteWrite(maddressHigh,maddressLow,msubcommand,mdata)) {
            //  mrawlog.setText("0x814E_SYNC write failed");
            return false;
        }
        return true;
    }

    //private TextView mrawlog;

    public void initTextView() {
        //mrawlog = (TextView) findViewById(R.id.rawlog);
        tvMaximum = (TextView) findViewById(R.id.maximumshow);  //显示最大值
        tvMinimum = (TextView) findViewById(R.id.minimumshow);  //显示最小值
        //tvMaxSubMin = (TextView) findViewById(R.id.maxsubminshow);
        //tvMaxDivMin = (TextView) findViewById(R.id.maxdivminshow);
        //tvDataContent = (TextView) findViewById(R.id.datacontentshow);
        //tvSTD = (TextView) findViewById(R.id.stdshow);
        //tvATR = (TextView) findViewById(R.id.atrshow);
        //tvMAD = (TextView) findViewById(R.id.madshow);
        tvTestResult = (TextView) findViewById(R.id.testresult);  //显示测试结果
    }

    int count = 1000;
    private void showRawdata() {

        mThreadPool.execute(new Runnable() {
            @Override
            public void run() {

                byte syncFlag = 1;
                //if (!changeToDebugMode())
                //  return false;
                // if(false) {
                changeToDebugMode();

                while(showFlag!=4) {

                    if(count-- == 0)
                    {
                        count = 0;
                    }

                    if (getRawdata() == true) {

                        switch (showFlag) {
                            case 1:// rawdata
                                mHandler.sendEmptyMessage(RAWDATA_MESSAGE);
                                break;
                            case 2://manual diff
                                break;
                            case 3://
                                break;
                            default:
                                break;
                        }
                    }

                    // }

                    while(true) {
                        //轮询读取0x814E，如果非0，则读取rawdata
                        byte maddressHigh = (byte) 0x81;
                        byte maddressLow = (byte) 0x4E;  //_rRW_MISCTL__SWRST_B0_
                        syncFlag = iicByteRead(maddressHigh, maddressLow);
                        //while ((syncFlag == 0 )|| (syncFlag == 0x77)) {
                        if (((syncFlag == 0) || (syncFlag == 0x77)) ){
                            SystemClock.sleep(1);
                            mHandler.sendEmptyMessage(LOG1_MESSAG);
                        }
                        else
                        {
                            if(count == 0) {
                                mHandler.sendEmptyMessage(LOG2_MESSAGE);
                            }
                            else {
                                // mHandler.sendEmptyMessage(SEND_MESSAGE_SUCCESS); //清空文本框
                            }
                            for (int i = 0; i <mRawdataBytes.length; i++)
                            {
                                mRawdataBytes[i] = (byte)0x00;
                            }
                            break;
                        }
                    }

                    SystemClock.sleep(100);
                }

            }   //ThreadPool
        });   //ThreadPool
        //   return true;


    }



    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int idtemp;
            int i = 0;
            int maxdata;
            int mindata;
            switch (msg.what) {
                case RAWDATA_MESSAGE://
                    maxdata = 0;
                    mindata = 65535;
                    //控制行数
                    for (int row = 0; row < rownum; row++) {
                        //控制列数
                        for (int col = 0; col < colnum; col++) {

                            idtemp = row + col * rownum;
                            datatemp[i] = ((mRawdataBytes[idtemp * 2] & 0xFF) << 8) + (mRawdataBytes[idtemp * 2 + 1] & 0xFF);

                            //获取最大值
                            if (datatemp[i] > maxdata){
                                maxdata = datatemp[i];
                            }
                            //获取最小值
                            if (datatemp[i] < mindata){
                                mindata = datatemp[i];
                            }

                        }
                    }

                    tvMaximum.setText(Integer.toString(maxdata));
                    tvMinimum.setText(Integer.toString(mindata));

                    if (maxdata > iMaximum)  //统计最大值大于阈值的次数
                    {
                        byMaximumOverCount++;
                    }

                    if (mindata < iMinimum)  //统计最小值小于阈值的次数
                    {
                        byMinimumOverCount++;
                    }

                    byTestCount++;
                    stTestLog = "采样第" + Integer.toString(byTestCount) + "帧";
                    stTestLogShow = stTestLogShow.concat(stTestLog);
                    stTestLogShow = stTestLogShow.concat("\n");


                    if (byTestCount >= 16)
                    {
                        stTestLog = "测试完成！！";
                        stTestLogShow = stTestLogShow.concat(stTestLog);
                        stTestLogShow = stTestLogShow.concat("\n");
                        stTestLog = "最大值超过阈值的次数：" + Integer.toString(byMaximumOverCount);
                        stTestLogShow = stTestLogShow.concat(stTestLog);
                        stTestLogShow = stTestLogShow.concat("\n");
                        stTestLog = "最小值超过阈值的次数：" + Integer.toString(byMinimumOverCount);
                        stTestLogShow = stTestLogShow.concat(stTestLog);
                        stTestLogShow = stTestLogShow.concat("\n");
                        if (byMaximumOverCount >= 15)
                        {
                            bTestResult = false;
                            stTestLog = "最大值超限！！";
                            stTestLogShow = stTestLogShow.concat(stTestLog);
                            stTestLogShow = stTestLogShow.concat("\n");
                        }
                        else if(byMaximumOverCount < 2)
                        {
                            bTestResult = true;
                            stTestLog = "最大值测试pass";
                            stTestLogShow = stTestLogShow.concat(stTestLog);
                            stTestLogShow = stTestLogShow.concat("\n");
                        }
                        else
                        {
                            bTestResult = false;
                            byTestCount = 0;
                            //byReTestCount++;
                            stTestLog = "最大值在临界范围，重新进行测试";
                            stTestLogShow = stTestLogShow.concat(stTestLog);
                            stTestLogShow = stTestLogShow.concat("\n");
                        }


                        if (byMinimumOverCount >= 15)
                        {
                            bTestResult = false;
                            stTestLog = "最小值超限";
                            stTestLogShow = stTestLogShow.concat(stTestLog);
                            stTestLogShow = stTestLogShow.concat("\n");
                        }
                        else if (byMinimumOverCount < 2)
                        {
                            bTestResult = true;
                            stTestLog = "最小值测试pass";
                            stTestLogShow = stTestLogShow.concat(stTestLog);
                            stTestLogShow = stTestLogShow.concat("\n");
                        }
                        else
                        {
                            bTestResult = false;
                            byTestCount = 0;
                            stTestLog = "最小值在临界范围，重新进行测试";
                            stTestLogShow = stTestLogShow.concat(stTestLog);
                            stTestLogShow = stTestLogShow.concat("\n");
                        }

                        if (bTestResult == true)
                        {
                            tvTestResult.setText("测 试 Pass ！！");
                        }
                        else
                        {
                            tvTestResult.setText("测 试 NG ！！");
                        }

                        showFlag = 4;
                        count = 1000;
                        changeToNormalMode();

                    }
                    edt_TestiInformation.setText(stTestLogShow);
                    edt_TestiInformation.setSelection(edt_TestiInformation.getText().length());

                    break;

                case LOG1_MESSAG://
                    //mrawlog.setText("0x814E_SYNC read failed");
                    break;

                case CLEAR_MESSAGE://清除数据
                    //mtextView.setText("");
                    break;

                case LOG2_MESSAGE://成功发送数据

                    //mrawlog.setText("0x814E_SYNC read success,count == 0");
                    break;
                case DEBUG_MESSAGE_ERROR://成功发送数据
                    break;

                case UPDATE_FW:
                    break;

                case DIFF_MESSAGE://
                    break;
                case  MANUALDIFF_MESSAGE:
                    break;


            }
        }
    };

    byte showFlag = 0;

    @Override
    public void onClick(final View view) {

        byte addressH = (byte)0x80;
        byte addressL = (byte)0x47;
        iicRead(addressH,addressL,mBytes,186);

        int checksum = 0;
        for (int i = 0; i < 186; i++) {
            int k = mBytes[i] & 0xFF;
            checksum = checksum + k;
        }
        if(checksum % 256 == 0)  //校验和正确
        {
            colnum = (mBytes[27] & 0x1F) + (mBytes[28] & 0x1F);
            rownum = (mBytes[29] & 0x0F) + ((mBytes[29] & 0xFF) >> 4);

        }
        else {
            Toast.makeText(this,"Cfg读取错误，请再次点击测试",Toast.LENGTH_SHORT).show();
            return;
        }


        if (edt_Maximum.getText().length()==0)
        {
            edt_Maximum.setText(Integer.toString(3000));
            iMaximum = 3000;
        }
        else
        {
            iMaximum = (byte) Integer.parseInt(edt_Maximum.getText().toString(),10);
        }

        if (edt_Minimum.getText().length()==0)
        {
            edt_Minimum.setText(Integer.toString(1000));
            iMinimum = 1000;
        }
        else
        {
            iMinimum = (byte) Integer.parseInt(edt_Minimum.getText().toString(),10);
        }

        switch (view.getId()) {
            case R.id.starttesting:   //Read RawData
                showFlag =1;
                byTestCount = 0;
                byMaximumOverCount = 0;
                byMinimumOverCount = 0;
                byReTestCount = 0;
                //count = 1000;
                showAddressHigh = (byte)0x8b;
                showAddressLow = (byte)0x98;
                if(count == 1000){
                    //tvDataContent.setText("["+getResources().getString(R.string.rawdata)+"]");
                    stTestLog = "开始测试！";
                    stTestLogShow = stTestLogShow.concat(stTestLog);
                    stTestLogShow = stTestLogShow.concat("\n");
                    showRawdata();
                }
                break;

            case R.id.stop:    //back
                showFlag =4;
                count = 1000;
                changeToNormalMode();
                break;
				
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();

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