package com.example.administrator.wingcool_gt9_apk;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
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.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.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
//import android.widget.RadioButton;
//import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.DatagramPacket;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Timer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FirmwareUpdate extends AppCompatActivity
        implements  OpenDevicesReceiver.OpenDevicesListener, View.OnClickListener{//,CompoundButton.OnCheckedChangeListener{

    private static final int CONNECTED_SUCCESS = 0;
    private static final int RECEIVER_MESSAGE_SUCCESS = 1;
    private static final int SEND_MESSAGE_SUCCESS = 2;
    private static final int DEBUG_MESSAGE_SUCCESS = 3;
    private static final int DEBUG_MESSAGE_ERROR = 4;
    private static final int UPDATE_FW= 5;

    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 fwOpenDevicesReceiver;
    private EditText mError;
    private UsbDeviceConnection mUsbDeviceConnection;

    private UsbEndpoint mUsbEndpointOut;
    private UsbEndpoint mUsbEndpointIn;
    private byte[] mBytes = new byte[1024];
    private byte[] mSendData = new byte[1024];
    private byte[] mConfigData = new byte[1024];
    private String[] mVersionShow = new String[7];
   // byte mSendData[] = null;

    private boolean isReceiverMessage = true;
    private boolean isSendMessage = true;

    private boolean isNeedFindDevice  = true;

    private int bottonMode = 0;

    private UsbInterface mUsbInterface;
    private StringBuffer mStringBuffer = new StringBuffer();
    private Context mContext;
    private Button btnReadVersion;
    private TextView mShow;
    private TextView tvUpDataResult;
    
    int FW_HEAD_LENGTH	=		0x80;
    int FW_SECTION_LENGTH	=	0x1000; 	/** 4K */
    int FW_DSP_ISP_LENGTH	=	0x800;	/**  2K */
    int FW_DSP_LENGTH	=		0x1000;	/** 4K */
    //int FW_BOOT_LENGTH	=		0x800;	/**  2K */
    int FW_SS51_LENGTH	=		(8 * FW_SECTION_LENGTH);	/**  32K */
    //int FW_BOOT_ISP_LENGTH	=	0x800;	/**  2k */
    //int FW_GLINK_LENGTH	=		0x3000;	/**  12k */
    //int FW_GWAKE_LENGTH		=	(4 * FW_SECTION_LENGTH) ; /**  32k */

    int FW_HEAD_OFFSET   =       0;
    int FW_DSP_ISP_OFFSET	=	(FW_HEAD_OFFSET + FW_HEAD_LENGTH);
    int FW_DSP_OFFSET	=		(FW_DSP_ISP_OFFSET + FW_DSP_ISP_LENGTH);
    int FW_SS51_OFFSET	 =		(FW_DSP_OFFSET + FW_DSP_LENGTH);

    //int FW_BOOT_OFFSET	=		(FW_DSP_OFFSET + FW_DSP_LENGTH);
    //int FW_BOOT_ISP_OFFSET	=	(FW_BOOT_OFFSET + FW_BOOT_LENGTH);
    //int FW_GLINK_OFFSET		=	(FW_BOOT_ISP_OFFSET + FW_BOOT_ISP_LENGTH);
    //int FW_GWAKE_OFFSET		=	(FW_GLINK_OFFSET + FW_GLINK_LENGTH);


    private byte mSendGetGt9VersionData[]={
            0x03,0x00,0x0f,(byte)0x81,0x40,0x00,0x06,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 Button btn_update;
    private Button btn_AutoUpdate;
    //private RadioGroup rad_group;

    private Button search_button;
    private TextView edit_search;
    private EditText edit_text;

    private Context mAlertContext;

    private AlertDialog alert = null;
    private AlertDialog.Builder builder = null;
	
	public String Update_log;
    public String Update_log1;
    public String Update_log2;
    String updateLogShow= "";

    //==============头部信息是大端在前======================//
    //typedef struct _ST_SUBSYS_FW_INFO {
    byte type;    //32
    int ilength;  //33,34
    int address;  //35,36
    private byte[] RES = new byte[3];  //37-39
    //}ST_SUBSYS_FW_INFO, *PST_SUBSYS_FW_INFO;

    //typedef struct _ST_FW_INFO {
    long llength;    //0-3
    int checksum;    //4,5
    private byte[] target_mask = new byte[6];  //6-11
    private byte[] target_mask_version = new byte[3];  //12-14
    private byte[] pid = new byte[6];  //15-20
    private byte[] version = new byte[3];  //21-23
    byte subsystem_count; //24
    byte chip_type;  //25
    private byte[] reserved = new byte[6];  //26-31
    //ST_SUBSYS_FW_INFO subsystem[12];
    //}ST_FW_INFO, *PST_FW_INFO;
    //====================================================//

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            StringBuilder stringBuilder = new StringBuilder("");
            StringBuffer resultSb = new StringBuffer();
            // for (int i = 1; i < mBytes.length; i++) {
            int checksum = 0 ;
            switch (msg.what) {
                case CONNECTED_SUCCESS://车机和手机连接成功
                    btnReadVersion.setEnabled(true);
                    //loopReceiverMessage();
                    break;

                case RECEIVER_MESSAGE_SUCCESS://成功接受到数据

                    //String hv = null;

                    for (int i = 0; i < 189; i++) {

                        if (i == 0 || i == 64 || i == 128)
                        {
                            continue;
                        }
                        int v = mBytes[i] & 0xFF;
                        checksum =checksum+ v;
                        String hv = Integer.toHexString(v);
                        stringBuilder.append(hv);
                        stringBuilder.append(",");
                    }

                    //String d_value =Arrays.toString(mBytes[);
                    //String d_value =Arrays.hv.toString();
                    //mShow.setText( stringBuilder.toString() );//输出显示
                    //edit_search.setText(uri.getPath().toString());
                    // mLog.setText(mStringBuffer.toString());

                    break;

                case SEND_MESSAGE_SUCCESS://成功发送数据
                    mShow.setText("");
                    break;

                case DEBUG_MESSAGE_SUCCESS://成功发送数据
                    //StringBuilder stringBuilder = new StringBuilder("");
                    // StringBuffer resultSb = new StringBuffer();

                    checksum = 0 ;
                    for (int i = 0; i < 216; i++) {

                        int v = mSendData[i] & 0xFF;
                        checksum =checksum+ v;
                        //byte v = mSendData[i];
                        String hv = Integer.toHexString(v);
                        //String hv = Byte.toString(v);
                        stringBuilder.append(hv);
                        stringBuilder.append(",");
                    }
                    mShow.setText(stringBuilder.toString());
                    //mShow.setText(value);
                    break;
                case DEBUG_MESSAGE_ERROR://成功发送数据
                    //mShow.setText("ERROR");

                    updateLogShow = updateLogShow.concat(Update_log);
                    updateLogShow = updateLogShow.concat("\n");
                    updateLogShow = updateLogShow.concat(Update_log2);
                    mError.setText(updateLogShow);
                    mError.setSelection(mError.getText().length());
                    Update_log2 = "";
                    Update_log = "";
                    break;

                case UPDATE_FW:
                    tvUpDataResult.setText(Update_log1);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_firmware_update);
        mAlertContext = FirmwareUpdate.this;
        ConstantsActivity.activityList.add(this);
        //switchLanguage(ConstantsActivity.langae);
        bindView();
        initData();
        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;
        }
    }

    private void updateProcHandle() {

        mThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                 SystemClock.sleep(100);
                 Update_log1 =  "UPDATE START...";  //升级成功
                 updateLogShow =  "";
                 Update_log2 =  "";
                 mHandler.sendEmptyMessage(UPDATE_FW);
                 if(updateProc() == true) {
                    // mHandler.sendEmptyMessage(UPDATE_FW);
                     Update_log1 =  "UPDATE SUCCESS!!!";  //升级成功
                     mHandler.sendEmptyMessage(UPDATE_FW);
                 }
                 else {
                     Update_log1 = "UPDATE FAILED!";   //升级失败
                     mHandler.sendEmptyMessage(UPDATE_FW);
                 }
            }   //ThreadPool
        });   //ThreadPool
    }

    private void bindView() {
        //mLog = (TextView) findViewById(R.id.log);
        btnReadVersion = (Button) findViewById(R.id.version);
        mError = (EditText) findViewById(R.id.error);
        mShow = (TextView) findViewById(R.id.show);
        //mSendMessage = (Button) findViewById(R.id.sendmessage);
        //mlog1 = (Button) findViewById(R.id.log1);
        //mSendCfg = (Button) findViewById(R.id.btn1);
        btn_update = (Button) findViewById(R.id.btnUpdate);
        btn_AutoUpdate = (Button) findViewById(R.id.btnAutoUpdate);
        // mShow = (EditText) findViewById(R.id.show);

        search_button = (Button) findViewById(R.id.searchbutton);
        edit_search = (TextView) findViewById(R.id.editsearch);
        edit_text = (EditText) findViewById(R.id.editsearch);

        tvUpDataResult = (TextView) findViewById(R.id.updataresult);

        mError.setKeyListener(null);

        btnReadVersion.setOnClickListener(this);
        btn_update.setOnClickListener(this);
        btn_AutoUpdate.setOnClickListener(this);

        search_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");//设置类型，我这里是任意类型，任意、后缀的可以这样写。
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, 1);
            }
        });
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //创建文件夹
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                        //Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                        //intent.setType("*/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
                        //intent.addCategory(Intent.CATEGORY_OPENABLE);
                        //startActivityForResult(intent, 1);
                    }
                }
                break;
        }
    }

    private void initData() {
        mContext = getApplicationContext();
        btnReadVersion.setEnabled(false);    //
        btn_update.setEnabled(false);
        btn_AutoUpdate.setEnabled(false);

        mThreadPool = Executors.newFixedThreadPool(5);

        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);

    }

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

        //列举设备(手机)
        fwOpenDevicesReceiver = 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(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 (productId == 0xC52F && vendorId == 0x046D) {
                            //if (productId == 0x55e0 && vendorId == 0x4348) {
                            if ((productId == 0x0616 && vendorId == 0x27C0)
                                    ||(productId == 0x0818 && vendorId == 0x27C0)
                                    ||(productId == 0x222A && vendorId == 0x0001)) {
                                //这里说明下,这里的377 , 7205是我这台机子上独有,因为我这上面有多台设备,所以我在这里
                                //判断了下.只有一台设备的无需这一步.
                                //mUsbManager.requestPermission(usbDevice, pendingIntent);
                                //SystemClock.sleep(100);
                                if (mUsbManager.hasPermission(usbDevice)) {
                                    initDevice();

                                } else {

                                    //String avalue = "S818 IS NOT PERMISSION";
                                    //mShow.setText(avalue);//输出显示
                                    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();
                if (productId == 0x0818 || productId == 0x222A || productId == 0x0616) {

                    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)) {
                                    //if ((null == mUsbEndpointIn) && (null == mUsbEndpointOut)) {
                                    // tvInfo.append("endpoint is null\n");
                                    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){
                                        mHandler.sendEmptyMessage(CONNECTED_SUCCESS);
                                    }
                                }
                            }
                        }
                    } else {
                        mUsbManager.requestPermission(usbDevice, PendingIntent.getBroadcast(mContext, 0, new Intent(""), 0));
                    }
                }
            }
        } else {
            // finish();
        }
    }

    @Override
    public void onClick(final View view) {
        int j = 0;
        int sendLoop = 1;
        byte addressH,addressL;
        switch(view.getId()) {
            case R.id.version:     //read version
                bottonMode = 0;
                mSendData = mSendGetGt9VersionData;
                isSendMessage = false;

                iicWriteCommand((byte)0x12,(byte)0,(byte)0,0,0);

                while(true) {
                    SystemClock.sleep(100);

                    iicRead((byte) 0x81, (byte) 0x4e, mBytes, 1);
                    if (mBytes[0] == (byte)0)
                    {
                        break;
                    }

                    iicWriteCommand((byte) 0x0f, (byte) 0x81, (byte) 0x4e, 0, 1);
                }

                addressH = (byte)0x81;
                addressL = (byte)0x40;
                iicRead(addressH,addressL,mBytes,32);

                int v = mBytes[4] & 0xFF;
                String hv = Integer.toHexString(v);
                if (hv.length() < 2){
                    hv = "0" + hv;
                }
                mVersionShow[0] = hv;

                v = mBytes[5] & 0xFF;
                hv = Integer.toHexString(v);
                if (hv.length() < 2){
                    hv = "0" + hv;
                }
                mVersionShow[1] = hv;

                v = mBytes[6] & 0xFF;
                hv = Integer.toHexString(v);
                if (hv.length() < 2){
                    hv = "0" + hv;
                }
                mVersionShow[2] = hv;

                v = mBytes[7] & 0xFF;
                hv = Integer.toHexString(v);
                if (hv.length() < 2){
                    hv = "0" + hv;
                }
                mVersionShow[3] = hv;

                if (mBytes[0] == 0x39 && mBytes[1] == 0x31 && mBytes[2] == 0x31 && mBytes[3] == 0x32){
                    mShow.setText( "GT9110H_" + mVersionShow[1].toString() + mVersionShow[0].toString() );//输出显示
                }
                else if (mBytes[0] == 0x36 && mBytes[1] == 0x31 && mBytes[2] == 0x30 && mBytes[3] == 0x39){
                    mShow.setText( "GT6108H_" + mVersionShow[1].toString() + mVersionShow[0].toString() );//输出显示
                }
                else if (mBytes[0] == 0x37 && mBytes[1] == 0x32 && mBytes[2] == 0x38 && mBytes[3] == 0x38){
                    mShow.setText( "GT7288_" + mVersionShow[0] + "." + mVersionShow[1] + "." + mVersionShow[2] + "." + mVersionShow[3]);//输出显示
                }
                else{
                    mShow.setText( "Null" );//输出显示
                }

                btn_update.setEnabled(true);
                btn_AutoUpdate.setEnabled(true);

                break;

            case R.id.btnAutoUpdate:
              //  mThreadPool.shutdownNow();
                bottonMode = 3;
                isReceiverMessage = false;  //升级关闭循环接收信息
                //mSendData = mSendGetGt9VersionData;
                isSendMessage = false;
                updateProcHandle();
                //mHandler.sendEmptyMessage(UPDATE_FW);
                break;
            case R.id.btnUpdate:
                //  mThreadPool.shutdownNow();
                bottonMode = 4;
                isReceiverMessage = false;  //升级关闭循环接收信息
                //mSendData = mSendGetGt9VersionData;
                isSendMessage = false;
                //mHandler.sendEmptyMessage(UPDATE_FW);
                updateProcHandle();

                break;

            default:
                break;
        }


       while (isSendMessage) {
            /**
             * 发送数据的地方 , 只接受byte数据类型的数据
             */
            SystemClock.sleep(1);
            // int i = mUsbDeviceConnection.bulkTransfer(mUsbEndpointOut, messageContent.getBytes(), messageContent.getBytes().length, 3000);
            //String c_value = "SENDING";
            // mShow.setText(c_value);//输出显示


            j = j +1;
            if(1000 == j) {
                j = 0;
                isSendMessage = false;
            }
            //int i = mUsbDeviceConnection.bulkTransfer(mUsbEndpointOut, mSendData, mSendData.length, 3000);
            // UsbPipe
            // UsbEndpoint
            //int i = mUsbDeviceConnection.controlTransfer(0x21, 0x09, 0x301, 0, mSendGetGt9VersionData, mSendGetGt9VersionData.length, 100);
            //
           if (null != mUsbEndpointOut) {
              //  if ((null != mUsbEndpointOut) && (bottonMode != 1)) {
                //mSendGetGt9ConfigData  mSendGetGt9VersionData
                int i = -1;
                int count = 0;
                for (int k = 0; k < sendLoop; k++) {
                    int offset1 = k*64;
                    if(k==3)
                    i = mUsbDeviceConnection.bulkTransfer(mUsbEndpointOut, mSendData, offset1, 0x40, 100);
                    else
                        i = mUsbDeviceConnection.bulkTransfer(mUsbEndpointOut, mSendData, offset1, 0x40, 100);
                    SystemClock.sleep(10);

                    if (i == 0x0f || i == 0x40) {

                        //   String b_value = "SEND MESSAGE SUCCESS";
                        //  mShow.setText(b_
                        // value);//输出显示
                        count++;
                        //mHandler.sendEmptyMessage(SEND_MESSAGE_SUCCESS);
                        // mlog1.setEnabled(true);
                       // isSendMessage = false;

                    } else {
                        //  mlog1.setEnabled(true);
                        if(sendLoop == 4)
                        mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
                    }

                    if(count == 4)
                        mHandler.sendEmptyMessage(DEBUG_MESSAGE_SUCCESS);
                }
                if (i == 0x0f ||i == 0x40 )
                isSendMessage = false;
                //int i = mUsbDeviceConnection.bulkTransfer(mUsbEndpointIn, mBytes, mBytes.length, 3000);
                //int i =0;


            } else {

                //mlog1.setEnabled(true);

            }

        }

          //  }
       // });
        // }
    }

    protected void onActivityResult ( int requestCode, int resultCode, Intent data){
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 1) {
                Uri uri = data.getData();
                //Toast.makeText(this, "文件路径：" + uri.getPath().toString(), Toast.LENGTH_SHORT).show();
                edit_search.setText(uri.getPath().toString());
            }
        }

    }

    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 iicWriteCommand(byte command,byte addressHigh,byte addressLow,int offset,int length) {
        int i;

        iicWriteData[1] = 0x01; //write GT9PT command
        iicWriteData[2] = command; //command
        iicWriteData[3] = addressHigh;
        iicWriteData[4] = addressLow;
        iicWriteData[5] = 0x00;
        iicWriteData[6] = 0x39;  //length 57

        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] = 0;//wBuffer[finalOffset + j -7];
            }
            i = mUsbDeviceConnection.bulkTransfer(mUsbEndpointOut, iicWriteData, 0, 0x40, 100);

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

            }

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

        return true;
    }

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

        iicByteData[5] = (byte)(length>>8);
        iicByteData[6] = (byte)length;  //length 一次接收63个数据

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

        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;
          //  }


           // SystemClock.sleep(1);

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

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

            //if (i != 0x40) {
            if (i != 0x40) {
               // mError.setText("iicWrite Failed");
                Update_log = "iicRead Failed";
                mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
                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");
                Update_log = "iicWrite Failed";
                mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
                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;
            //mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
           // initDevice();
            i = mUsbDeviceConnection.bulkTransfer(mUsbEndpointOut, iicByteData, 0, 0x40, 100);
        }
        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;  //先关闭循环接收信息


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

    private boolean enterUpdateMode() {
        // if ( == false)
        {
            //FwUpdateMessage(L"[FW update]Touch IC reset failed", MSG_ERR);
            byte maddressHigh = (byte)0x80;
            byte maddressLow = (byte)0x40;
            byte msubcommand =0x04 ;  //rst IC
            byte mdata = (byte)0x00;

            if(!iicByteWrite(maddressHigh,maddressLow,msubcommand,mdata)) {
               // mError.setText("[FW update]Touch IC reset failed");
                Update_log = "[FW update]Touch IC reset failed";
                mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
                return false;
            }
        }

        for (int k = 0; k < 5; k++)
        {
            //nTryTimes--;
            byte maddressHigh = (byte)0x41;
            byte maddressLow = (byte)0x80;  //_rRW_MISCTL__SWRST_B0_
            byte msubcommand =0x0f ;  //no command
            byte mdata = (byte)0x0C;

            if(!iicByteWrite(maddressHigh,maddressLow,msubcommand,mdata))
                return false;

            maddressHigh = (byte)0x40;
            maddressLow = (byte)0xB0;  //_bRW_MISCTL__TMR0_EN
            mdata = (byte)0x00;

            if(!iicByteWrite(maddressHigh,maddressLow,msubcommand,mdata))
                return false;
        }

        byte maddressHigh = (byte)0x41;
        byte maddressLow = (byte)0x80;  //_rRW_MISCTL__SWRST_B0_

        if (0x0C ==iicByteRead(maddressHigh,maddressLow))
        {
           // FwUpdateMessage(L"[FW update]Hold IC successfully", MSG_NOR);
           // mError.setText("[FW update]Hold IC successfully");
            Update_log = "[FW update]Hold IC successfully";
            mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);

        }
        else
        {
           // FwUpdateMessage(L"[FW update]Hold IC failed", MSG_ERR);
           // mError.setText("[FW update]Hold IC failed");
            Update_log = "[FW update]Hold IC failed";
            mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
            return false;
        }

        maddressHigh = (byte)0x40;
        maddressLow = (byte)0xB0;  //_bRW_MISCTL__TMR0_EN
        if (0x00 == iicByteRead(maddressHigh,maddressLow))
        {
            //FwUpdateMessage(L"[FW update]Disable watch dog", MSG_NOR);
          //  mError.setText("[FW update]Disable watch dog");
            Update_log = "[FW update]Disable watch dog";
            mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
        }
        else
        {
          //  FwUpdateMessage(L"[FW update]Disable watch dog failed", MSG_ERR);
           // mError.setText("[FW update]Disable watch dog failed");
            Update_log = "[FW update]Disable watch dog failed";
            mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
            return false;
        }

        maddressHigh = (byte)0x40;
        maddressLow = (byte)0x10;  //_bRW_MISCTL__CACHE_EN
        byte mdata = (byte)0x00;
        byte msubcommand =0x0f ;  //no command
        if (!iicByteWrite(maddressHigh,maddressLow,msubcommand,mdata))
        {
            //  FwUpdateMessage(L"[FW update]Clear cache enable failed", MSG_ERR);
            //  mError.setText("[FW update]Clear cache enable failed");
            Update_log = "[FW update]Clear 0x4010 enable failed";
            mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
            return false;
        }

        maddressHigh = (byte)0x40;
        maddressLow = (byte)0x4B;  //_bRW_MISCTL__CACHE_EN
        mdata = (byte)0x00;
        //msubcommand =0x0f ;  //no command
        if (!iicByteWrite(maddressHigh,maddressLow,msubcommand,mdata))
        {
          //  FwUpdateMessage(L"[FW update]Clear cache enable failed", MSG_ERR);
          //  mError.setText("[FW update]Clear cache enable failed");
            Update_log = "[FW update]Clear cache enable failed";
            mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
            return false;
        }
        // FwUpdateMessage(L"[FW update]Clear cache enable", MSG_NOR);

        maddressHigh = (byte)0x41;
        maddressLow = (byte)0x84;   //_bWO_MISCTL__CPU_SWRST_PULSE
        mdata = (byte)0x01;
        if (!iicByteWrite(maddressHigh,maddressLow,msubcommand,mdata))
        {
            //FwUpdateMessage(L"[FW update]Clear update ctrlflag failed", MSG_ERR);
            // mError.setText("[FW update]Clear update ctrlflag failed");
            Update_log = "[FW update]set _bWO_MISCTL__CPU_SWRST_PULSE failed";
            mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
            return false;
        }

        maddressHigh = (byte)0x42;
        maddressLow = (byte)0x18;  //_rRW_MISCTL__BOOT_OPT_B0_
        mdata = (byte)0x00;
        if (!iicByteWrite(maddressHigh,maddressLow,msubcommand,mdata))
        {
            //FwUpdateMessage(L"[FW update]Clear update ctrlflag failed", MSG_ERR);
            // mError.setText("[FW update]Clear update ctrlflag failed");
            Update_log = "[FW update]Clear _rRW_MISCTL__BOOT_OPT_B0_ failed";
            mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
            return false;
        }

        maddressHigh = (byte)0x40;
        maddressLow = (byte)0x48;  //_bRW_MISCTL__SRAM_BANK
        mdata = (byte)0x04;
        if (!iicByteWrite(maddressHigh,maddressLow,msubcommand,mdata))
        {
            //FwUpdateMessage(L"[FW update]Clear update ctrlflag failed", MSG_ERR);
            // mError.setText("[FW update]Clear update ctrlflag failed");
            Update_log = "[FW update]set _bRW_MISCTL__SRAM_BANK failed";
            mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
            return false;
        }

        maddressHigh = (byte)0x40;
        maddressLow = (byte)0x4D;  //_rRW_MISCTL__BOOT_CTL_
        mdata = (byte)0x01;
        if (!iicByteWrite(maddressHigh,maddressLow,msubcommand,mdata))
        {
            //FwUpdateMessage(L"[FW update]Clear update ctrlflag failed", MSG_ERR);
           // mError.setText("[FW update]Clear update ctrlflag failed");
            Update_log = "[FW update]set 0x404D failed";
            mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
            return false;
        }
       // FwUpdateMessage(L"[FW update]Clear update ctrlflag", MSG_NOR);
       // mError.setText("[FW update]Clear update ctrlflag");
        Update_log = "[FW update]Enter Update Mode";
        mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);

        return true;
    }

    boolean memCmp(byte[] sBuffer,byte[] deBuffer,int offset,int length) {

         {
            try {

                for (int i = 0; i < length; i++) {
                    if (sBuffer[i] != deBuffer[offset + i]) {
                        // FwUpdateMessage(L"Recall frame data fail,not equal.", MSG_ERR);
                        // mError.setText("Recall frame data fail,not equal.");
                        StringBuilder stringBuilder = new StringBuilder("sBuffer[i]=");
                        int v = sBuffer[i] & 0xFF;
                        String hv = Integer.toHexString(v);
                        stringBuilder.append(hv);
                        stringBuilder.append(",dBuffer[offset + i]=");

                        v = deBuffer[offset + i]& 0xFF;
                        hv = Integer.toHexString(v);
                        stringBuilder.append(hv);
                        stringBuilder.append(",i=");

                        stringBuilder.append(i);
                        stringBuilder.append(",offset=");
                        stringBuilder.append(offset);
                        stringBuilder.append(".\n");


                        for (int j = 0; j < 129; i++) {

                             v = sBuffer[i+j] & 0xFF;
                            hv = Integer.toHexString(v);
                            stringBuilder.append(hv);
                            stringBuilder.append(",");
                        }

                        Update_log2 = Update_log2.concat(stringBuilder.toString()) ;
                        Update_log2 = Update_log2.concat("\n");
                       // mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
                        return false;
                    }
                }
            } catch (ArithmeticException e) {
               // mShow.setText("ArithmeticException!");
                Update_log2 = Update_log2.concat("ArithmeticException");
                Update_log2 = Update_log2.concat("\n");
              //  mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
                e.printStackTrace();
            } catch (ArrayIndexOutOfBoundsException e) {
               // mShow.setText("ArrayIndexOutOfBoundsException!");

                Update_log2 = Update_log2.concat("ArrayIndexOutOfBoundsException");
                Update_log2 = Update_log2.concat("\n");
                //  mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
                e.printStackTrace();
            }
        }
        return true;
    }


    boolean recallCheck(byte addressHigh,byte addressLow,byte[] dBuffer,int offset,int length)
    {
        //BYTE* pbBuf = new BYTE[wLen];
        byte[] recallBuf =new byte[length+0x3000];

        //if(false)
        {
            if (!iicRead(addressHigh, addressLow, recallBuf, length)) {
                //FwUpdateMessage(L"recall i2c error failed", MSG_ERR);
               // mShow.setText("recall i2c error failed");
                Update_log2 =Update_log2.concat("recall i2c error failed!") ;
                Update_log2 = Update_log2.concat("\n");
               // mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
                return false;
            }
            if (!memCmp(recallBuf, dBuffer, offset, length)) {  //recallBuf为回读的数据,dBuffer为源数据

                // FwUpdateMessage(L"Recall frame data fail,not equal.", MSG_ERR);
               // mMessage.setText("Recall frame data fail,not equal.");
               // Update_log = "recall frame data fail,not equal";
                Update_log2 =Update_log2.concat("recall frame data fail,not equal") ;
                Update_log2 = Update_log2.concat("\n");
               // mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
                return false;
            }
        }
        return true;

    }

    byte[] mGt9FirmwareData = new byte[88*1024+512];
    byte[] m_nComparBuf = new byte[88*1024+512];
    /**
    public void readFile() throws IOException {
        //打开文件输入流
        String filename = "///storage/emulated/0/Download/GT9110H_2002(A2E3).BIN";
        FileInputStream input = mContext.openFileInput(filename);
        //读取文件内容:
        input.read(mGt9FirmwareData);
        //关闭输入流
        input.close();
    }*/
    private boolean burnDspIsp() {

        // FwUpdateMessage(L"Set boot from sram", MSG_NOR);
        byte maddressHigh = (byte)0x41;
        byte maddressLow = (byte)0x90;   //_rRW_MISCTL__BOOTCTL_B0_  1
        byte msubcommand =0x0f ;  //no command
        byte mdata = (byte)0x02;

        /*
        if(!iicByteWrite(maddressHigh,maddressLow,msubcommand,mdata)) {

           // FwUpdateMessage(L"Set boot from sram failed", MSG_ERR);
            //mError.setText("Set boot from sram failed");
            Update_log = "Set boot from sram failed";
            mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
            return false;
        }

        maddressHigh = (byte)0x41;
        maddressLow = (byte)0x84;   //_bWO_MISCTL__CPU_SWRST_PULSE  2
        msubcommand =0x0f ;  //no command
        mdata = (byte)0x01;

        if(!iicByteWrite(maddressHigh,maddressLow,msubcommand,mdata)) {
                    // FwUpdateMessage(L"Set boot from sram failed", MSG_ERR);
            //mError.setText("Software reboot failed");
            Update_log = "Software reboot failed";
            mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
            return false;
        }

        maddressHigh = (byte)0x40;
        maddressLow = (byte)0x48;   //_bRW_MISCTL__SRAM_BANK   3
        msubcommand =0x0f ;  //no command
        mdata = (byte)0x02;

        if(!iicByteWrite(maddressHigh,maddressLow,msubcommand,mdata)) {
                        // FwUpdateMessage(L"Set boot from sram failed", MSG_ERR);
          //  mError.setText("select bank2 failed");
            Update_log = "select bank2 failed";
            mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
            return false;
        }


        maddressHigh = (byte)0x40;
        maddressLow = (byte)0x49;   //_bRW_MISCTL__MEM_CD_EN   4
        msubcommand =0x0f ;  //no command
        mdata = (byte)0x01;

        if(!iicByteWrite(maddressHigh,maddressLow,msubcommand,mdata))
        {
                            // FwUpdateMessage(L"Set boot from sram failed", MSG_ERR);
           // mError.setText("enable accessing failed");
            Update_log = "enable accessing failed";
            mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
            return false;
        }
        */

        maddressHigh = (byte)0xC0;
        maddressLow = (byte)0x00;   //_bRW_MISCTL__SRAM_BANK   3
        //int mDspIsplength = 0x1000;

        //FileInputStream input = mContext.openFileInput("Gt9Firmware");
        // byte[] mGt9FirmwareData = new byte[88*1024+512];
        // StringBuilder sb = new StringBuilder("");
        // byte[] temp ;


        //读取文件内容:
        /**
         try {
         readFile();
         } catch (IOException e) {
         mMessage.setText("文件不存在!");
         // e.printStackTrace();
         }
         */

        ActivityCompat.requestPermissions(  FirmwareUpdate.this, new String[]{android
                .Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);   //申请权限，android6.0以上系统首次使用必须添加

        StringBuffer buffer = new StringBuffer();
        StringBuilder stringBuilder = new StringBuilder("");
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

            try {

                //String filename = Environment.getExternalStorageDirectory() + "/Download/GT9110H_2002(A2E3).BIN";
                String filename = "GT9110H_2002(A2E3).BIN";
                //mError.setText(filename);
                //FileInputStream fis = new FileInputStream(filename);
                if(bottonMode == 4)
                {
                    filename = edit_search.getText().toString();
                    FileInputStream fw = new FileInputStream(filename);
                    fw.read(mGt9FirmwareData);
                    fw.close();
                }
                else {

                    if(bottonMode == 3) {
                        //InputStream config = getResources().openRawResource(R.raw.gt9110h_config_2018110802);
                        //InputStream config = getResources().openRawResource(R.raw.xinjian);\
                        //config.read(mConfigData);

                        InputStream fis = getResources().openRawResource(R.raw.gt7288_06_00_21_00);
                        //gt9110h_config_20181108
                        fis.read(mGt9FirmwareData);

                        //config.close();
                        fis.close();
                    }

                }
                /**
                for (int i = 0; i < 64; i++) {

                    int k = mGt9FirmwareData[i+FW_DSP_ISP_OFFSET+FW_DSP_ISP_LENGTH-2] & 0xFF;
                    if(i>1)
                    {
                        k= mConfigData[i-2]&0xFF;
                    }
                    String hv = Integer.toHexString(k);
                    stringBuilder.append(hv);
                    stringBuilder.append(",");
                }
               mShow.setText(stringBuilder.toString());*/




            } catch (FileNotFoundException e) {
                e.printStackTrace();
               // mMessage.setText("文件没被发现");
                Update_log = "文件没被发现";
                mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);

                return false;
            }
            catch (IOException e) {
                e.printStackTrace();
               // mMessage.setText("IOException");
                Update_log = "IOException";
                mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
            }

        }
        else{
           // mMessage.setText("SD卡不可读写!");
            Update_log = "SD卡不可读写!";
            mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
        }
        //return false;
        //int mOffset = mGt9FirmwareData.length - mDspIsplength;

        //mGt9FirmwareData
        if(true) {
            //if (mGt9FirmwareData[1] == 0x01 && mGt9FirmwareData[2] == 0x60) {
                if (!iicWrite(maddressHigh, maddressLow, mGt9FirmwareData, FW_DSP_ISP_OFFSET, FW_DSP_ISP_LENGTH)) {
                    // FwUpdateMessage(L"Set boot from sram failed", MSG_ERR);
                   // mError.setText("burn 4k dsp_isp failed");
                    Update_log = "burn 2k dsp_isp failed";
                    mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);

                    return false;

                } else {
                    //mError.setText("burn 4k dsp_isp successed");
                    Update_log = "burn 2k dsp_isp successed";
                    mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
                }
            /*
            } else {
               // mError.setText("get FW data error, burn 4k dsp_isp failed");
                Update_log = "get FW data error, burn 4k dsp_isp failed";
                mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);



                return false;
            }
            */

                // if (!recallCheck(maddressHigh, maddressLow, mGt9FirmwareData, FW_DSP_ISP_OFFSET, FW_DSP_ISP_LENGTH)) {
                maddressHigh = (byte) 0xC0;
                maddressLow = (byte) 0x00;
                //if (!recallCheck(maddressHigh, maddressLow, mGt9FirmwareData, FW_DSP_ISP_OFFSET, 2500))
                //    {
                //    mError.setText("recall check error,burn 4k dsp_isp failed");
                //    return false;
                //}
                //else
                {
                    //if (!recallCheck(maddressHigh, maddressLow, mGt9FirmwareData, FW_DSP_ISP_OFFSET+2500, 100))
                    if (!recallCheck(maddressHigh, maddressLow, mGt9FirmwareData, FW_DSP_ISP_OFFSET, FW_DSP_ISP_LENGTH)) {
                        //mError.setText("recall check error,burn 4k dsp_isp failed");
                        Update_log = "recall check error,burn 2k dsp_isp failed";
                        mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
                        return false;
                    } else {
                        //mError.setText("recall check success,burn 4k dsp_isp failed");
                        Update_log = "recall check success,burn 2k dsp_isp success";
                        mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
                        //return false;

                    }
                }


            maddressHigh = (byte) 0x40;
            maddressLow = (byte) 0x4D;   //_rRW_MISCTL__BOOT_OPT_B0_   4
            msubcommand = 0x0f;  //no command
            mdata = (byte) 0x00;

            if (!iicByteWrite(maddressHigh, maddressLow, msubcommand, mdata)) {
                //mError.setText("set scramble failed");
                Update_log = "set scramble failed";
                mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
                return false;
            }
/*
            byte RegData[] = { 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55 };

            maddressHigh = (byte) 0x80;
            maddressLow = (byte) 0x06;   //_bRW_MISCTL__SRAM_BANK   5

            if (!iicWrite(maddressHigh,maddressLow,RegData,0,8))
            {
                Update_log = "write 0x8006 failed";
                mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
                return false;

            }
*/
            maddressHigh = (byte) 0x80;
            maddressLow = (byte) 0x06;   //_bRW_MISCTL__SRAM_BANK   5
            msubcommand = 0x0f;  //no command
            mdata = (byte) 0x55;

            iicByteWrite(maddressHigh, maddressLow, msubcommand, mdata);
            maddressLow++;
            iicByteWrite(maddressHigh, maddressLow, msubcommand, mdata);
            maddressLow++;
            iicByteWrite(maddressHigh, maddressLow, msubcommand, mdata);
            maddressLow++;
            iicByteWrite(maddressHigh, maddressLow, msubcommand, mdata);
            maddressLow++;
            iicByteWrite(maddressHigh, maddressLow, msubcommand, mdata);
            maddressLow++;
            iicByteWrite(maddressHigh, maddressLow, msubcommand, mdata);
            maddressLow++;
            iicByteWrite(maddressHigh, maddressLow, msubcommand, mdata);
            maddressLow++;
            iicByteWrite(maddressHigh, maddressLow, msubcommand, mdata);


            maddressHigh = (byte) 0x41;
            maddressLow = (byte) 0x80;   //_rRW_MISCTL__SWRST_B0_
            msubcommand = 0x0f;  //no command
            mdata = (byte) 0x08;

            if (!iicByteWrite(maddressHigh, maddressLow, msubcommand, mdata)) {
                //mError.setText("select bank3 failed");
                Update_log = "select _rRW_MISCTL__SWRST_B0_ failed";
                mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
                return false;
            }

            SystemClock.sleep(15);

            iicRead((byte) 0x80, (byte) 0x06, mBytes, 2);
            if ((mBytes[0] != (byte)0xAA) && (mBytes[1] != (byte)0xBB))
            {
                Update_log = "0x8006 flag is wrong";
                mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
                return false;

            }
        }
        return true;
        //return false;
    }

    int GetCheckSum(byte[] pBuf, int offser, int nLength)
    {
        int CheckSum = 0;

        for (int i = 0; i < nLength; i += 2) {
            CheckSum += (((int)pBuf[i + offser]) << 8);
            CheckSum += pBuf[i + offser + 1];
        }
        return CheckSum;
    }

    private boolean updateProc() {

        if (!enterUpdateMode())  //NO1
        {
            //FwUpdateMessage(L"[FW update]Enter update mode failed", MSG_ERR);
            return false;
        }

        if (!burnDspIsp()) {   //NO2
                // FwUpdateMessage(L"[FW update]Burn DSP isp failed", MSG_ERR);
                return false;
        }

        int offset = FW_DSP_OFFSET;
        int ilength;
        int iaddress;
        byte btype;

        Update_log = "Update Section Start...";
        mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);

        for (int i = 1,j = 0; i < mGt9FirmwareData[24]; i++,j++)
        {
            int len;
            int checksum;
            int tempindex;

            tempindex = 40 + j * 8;

            ilength = (int)mGt9FirmwareData[tempindex + 1] * 256 + mGt9FirmwareData[tempindex + 2];  //m_pFwInfo->subsystem[i].length
            iaddress = (int)mGt9FirmwareData[tempindex + 3] * 256 + mGt9FirmwareData[tempindex + 4];  //subSys->address
            btype = mGt9FirmwareData[tempindex];

            for (int offsetindex = 0; offsetindex < ilength; offsetindex += FW_SECTION_LENGTH, iaddress += 0x10)
            {
                if (offsetindex + FW_SECTION_LENGTH > ilength)
                {
                    len = ilength - offsetindex;
                }
                else
                {
                    len = FW_SECTION_LENGTH;
                }


                checksum = GetCheckSum(mGt9FirmwareData, offset, len);

                checksum += len;

                checksum += iaddress;

                checksum = 0 - checksum;

                byte maddressHigh = (byte)0x81;
                byte maddressLow = (byte)0x00;   //0x8100
                byte msubcommand =0x0f ;  //no command
                byte mdata = (byte)(len >> 8);
                if(!iicByteWrite(maddressHigh,maddressLow,msubcommand,mdata))
                    return false;

                maddressLow++;  //8101
                mdata = (byte)len;
                if(!iicByteWrite(maddressHigh,maddressLow,msubcommand,mdata))
                    return false;

                maddressHigh = (byte)0x81;
                maddressLow = (byte)0x02;  //0x8102
                mdata = (byte)(iaddress >> 8);
                if(!iicByteWrite(maddressHigh,maddressLow,msubcommand,mdata))
                    return false;

                maddressLow++;  //0x8103
                mdata = (byte)iaddress;
                if(!iicByteWrite(maddressHigh,maddressLow,msubcommand,mdata))
                    return false;

                maddressHigh = (byte)0x81;
                maddressLow = (byte)0x04;
                if (!iicWrite(maddressHigh,maddressLow,mGt9FirmwareData,offset + offsetindex,len))
                    return false;

                maddressHigh = (byte)((0x8104 + len) >> 8);
                maddressLow = (byte)(0x8104 + len);
                mdata = (byte)(checksum >> 8);
                if(!iicByteWrite(maddressHigh,maddressLow,msubcommand,mdata))
                    return false;

                maddressLow++;  //地址加1
                mdata = (byte)checksum;
                if(!iicByteWrite(maddressHigh,maddressLow,msubcommand,mdata))
                    return false;

                maddressHigh = (byte)0x80;
                maddressLow = (byte)0x22;
                mdata = (byte)0;
                if(!iicByteWrite(maddressHigh,maddressLow,msubcommand,mdata))
                    return false;

                maddressHigh = (byte)0x80;
                maddressLow = (byte)0x20;
                mdata = btype;
                if(!iicByteWrite(maddressHigh,maddressLow,msubcommand,mdata))
                    return false;

                maddressHigh = (byte)0x80;
                maddressLow = (byte)0x22;
                byte readcount = 0;
                while(readcount < 50) {
                    iicRead(maddressHigh, maddressLow, mBytes, 1);

                    if (mBytes[0] == 0xBB)
                    {
                        break;
                    }

                    readcount++;
                }

                maddressHigh = (byte)0x81;
                maddressLow = (byte)0x04;
                if (!iicRead(maddressHigh, maddressLow, m_nComparBuf, len))
                    return false;

                while (--len >= 0)
                {
                    if (m_nComparBuf[len] != mGt9FirmwareData[offset + offsetindex + len])
                    {
                        return false;
                    }
                }
            }

            offset += ilength;
        }

        Update_log = "Update Section FW Success";
        mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);

        /*
        byte cmd[] = { 0x60, 0x00, (byte)0xA0 };

        if (!iicWrite((byte)0x80,(byte)0x40,cmd,0,3))
            return false;
        */

        if(!iicByteWrite((byte)0x80,(byte)0x40, (byte)0x0f, (byte)0x60))
            return false;
        if(!iicByteWrite((byte)0x80,(byte)0x41, (byte)0x0f, (byte)0x00))
            return false;
        if(!iicByteWrite((byte)0x80,(byte)0x42, (byte)0x0f, (byte)0xA0))
            return false;

        if(!iicByteWrite((byte)0x40,(byte)0xB0,(byte)0x0f,(byte)0x00))
            return false;

        if(!iicByteWrite((byte)0x41,(byte)0x80,(byte)0x0f,(byte)0x01))
            return false;

        SystemClock.sleep(30);

        Update_log = "upgrade is finished";
        mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);

        return true;
    }

    @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(fwOpenDevicesReceiver);
    }
}
