package com.example.administrator.wingcool_gt9_apk;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
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.graphics.drawable.ColorDrawable;
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.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
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.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


import android.util.Log;
import android.widget.EditText;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.concurrent.atomic.AtomicInteger;

//===============================================================//
//=================================================================//

public class GT9MainActivity extends AppCompatActivity
        implements OpenDevicesReceiver.OpenDevicesListener, View.OnClickListener {

    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 CONNECTED_FAILED = 3;
    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 mOpenDevicesReceiver;
    private UsbDeviceConnection mUsbDeviceConnection;
    private UsbEndpoint mUsbEndpointOut;
    private UsbEndpoint mUsbEndpointIn;
    //private byte[] mBytes = new byte[1024 * 8 + 32];
    private boolean isNeedFindDevice  = true;

    public boolean isS818Device  = false;

    private UsbInterface mUsbInterface;
    private TextView mShow;
    private TextView tvIPAddress;
    private Context mShowID;
    private Button btnExit;

    //private Button btnConfigSetting;
    //private Button btnFWUpdate;
    //private Button btnDataAnalysis;
    //private Button btnNoiseAnalysis;
    //private Button btnDemoTools;
    //private Button btnIICOperation;
    //private Button btnContactUs;

    public static List<Activity> activityList = new LinkedList();

    private int iProductId;
    //private int iVendorId;
    private String strVersion;
    private int iDeviceId;

/*
    private Button bt_tcpstart;
    private final static String TAG = "Main2Activity-------->";
    private Socket socket = null;
    private ServerSocket server = new ServerSocket(5168);

    // 获取输出流与输入流
    private OutputStream outputStream = null;
    private InputStream inputStream = null;

    private byte[] SyncCmd = new byte[] {0x03, 0x00, 0x0d, (byte)0x81, 0x4E, 0x00, 0x01};
*/

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CONNECTED_SUCCESS://??????????????????
                    //mError.setText("");
                    //mSendMessage.setEnabled(true);
                    //String avalue = "S818 is connected";
                    //mShow.setText(getResources().getString(R.string.connected));
                    mShow.setText("S"+Integer.toHexString(iProductId)+" "+getResources().getString(R.string.connected));//????????
                    //bt_tcpstart.setEnabled(true);
                    break;
                case CONNECTED_FAILED://??????????????????
                    //String bvalue = "S818 is disconnected";
                    //mError.setText("");
                    //mSendMessage.setEnabled(true);

                    mShow.setText(getResources().getString(R.string.disconnected));//????????
                    break;

                case RECEIVER_MESSAGE_SUCCESS://??????????????

                    break;

                case SEND_MESSAGE_SUCCESS://????????????
                    //mMessage.setText("");
                    break;
            }
        }
    };

/*
    public GT9MainActivity() throws IOException
    {
    }
*/
    //==========================================================================================//

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gt9_main);
        ConstantsActivity.activityList.add(this);

        RadioGroup radio = (RadioGroup) findViewById(R.id.radio);
        final RadioButton radioButtonen = (RadioButton) findViewById(R.id.radio_en);
        final RadioButton radioButtonzh = (RadioButton) findViewById(R.id.radio_zh);
        //Locale curLocale = getResources().getConfiguration().locale;
        //String language = locale.getLanguage();

        //通过Locale的equals方法，判断出当前语言环境
        //if (curLocale.equals(Locale.CHINESE)) {
        if (ConstantsActivity.bHaveChange == false) {
            if (isZh()) {
                ConstantsActivity.langae = "zh";
            } else {//if(curLocale.equals(Locale.ENGLISH)){
                ConstantsActivity.langae = "en";
            }
        }

        if (ConstantsActivity.langae.equals("zh")) {
            radioButtonzh.setChecked(true);
            radioButtonen.setChecked(false);
        } else {
            radioButtonen.setChecked(true);
            radioButtonzh.setChecked(false);
        }

        if (ConstantsActivity.bHaveChange == false) {
            switchLanguage(ConstantsActivity.langae);
        }

        radio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.radio_zh) {
                    ConstantsActivity.langae = "zh";
                    radioButtonen.setChecked(false);
                } else {
                    radioButtonzh.setChecked(false);
                    ConstantsActivity.langae = "en";
                }
                ConstantsActivity.bHaveChange = true;
                changelanguage();
            }
        });

        RadioGroup screenradio = (RadioGroup) findViewById(R.id.screenradio);
        final RadioButton radioButtonLandscape = (RadioButton) findViewById(R.id.radio_landscape);
        final RadioButton radioButtonPortrait = (RadioButton) findViewById(R.id.radio_portrait);

        if (ConstantsActivity.screenview.equals("landscape")) {
            radioButtonLandscape.setChecked(true);
            radioButtonPortrait.setChecked(false);
        } else {
            radioButtonPortrait.setChecked(true);
            radioButtonLandscape.setChecked(false);
        }

        if (ConstantsActivity.bScreenHaveChange == false) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }

        screenradio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.radio_landscape) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    ConstantsActivity.screenview = "landscape";
                } else {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    ConstantsActivity.screenview = "portrait";
                }
                ConstantsActivity.bScreenHaveChange = true;
            }
        });

        init();//
    }

    private boolean isZh() {
        Locale locale = getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        if (language.endsWith("zh"))
            return true;
        else
            return false;
    }

    private void changelanguage() {
        Locale locale = new Locale(ConstantsActivity.langae);
        Locale.setDefault(locale);
        Configuration config = new Configuration();
        config.locale = locale;
        Resources resources = getResources();
        resources.updateConfiguration(config, resources.getDisplayMetrics());

        //让之前打开的所有界面全部彻底关闭
        for (Activity activity : ConstantsActivity.activityList) {
            activity.finish();
        }
        //回到应用的首页
        startActivity(new Intent(this, GT9MainActivity.class));
    }
    //核心设置的代码
    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);
    }

    /** Called when the user taps the Config Setting button */
    public void ConfigSetting(View view) {
        Intent intent = new Intent(this, Config.class);
        //EditText editText = (EditText) findViewById(R.id.editText);
        //String message = editText.getText().toString();
        //intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    }

    /** Called when the user taps the Firmware Update button */
    public void FirmwareUpdate(View view) {
        Intent intent = new Intent(this, FirmwareUpdate.class);
        //EditText editText = (EditText) findViewById(R.id.editText);
        //String message = editText.getText().toString();
        //intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    }

    /** Called when the user taps the Data Analysis button */
    public void DataAnalysis(View view) {
        Intent intent = new Intent(this, DataAnalysis.class);
        //EditText editText = (EditText) findViewById(R.id.editText);
        //String message = editText.getText().toString();
        //intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    }

    /** Called when the user taps the Noise Analysis button */
    public void NoiseAnalysis(View view) {
        Intent intent = new Intent(this, NoiseAnalysis.class);
        //EditText editText = (EditText) findViewById(R.id.editText);
        //String message = editText.getText().toString();
        //intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    }

    /** Called when the user taps the Demo Tools button */
    public void DemoTools(View view) {
        Intent intent = new Intent(this, DemoTools.class);
        //EditText editText = (EditText) findViewById(R.id.editText);
        //String message = editText.getText().toString();
        //intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    }

    /** Called when the user taps the IIC Operation button */
    public void IICOperation(View view) {
        Intent intent = new Intent(this, IICOperation.class);
        //EditText editText = (EditText) findViewById(R.id.editText);
        //String message = editText.getText().toString();
        //intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    }

    /** Called when the user taps the Contact Us button */
    public void ContactUs(View view) {
        Intent intent = new Intent(this, ContactUs.class);
        //EditText editText = (EditText) findViewById(R.id.editText);
        //String message = editText.getText().toString();
        //intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    }

    //===============================================================//
    private void init() {
        initView();
        initData();
        openDevices();
        //GetIPAddress();
    }

    private void initView() {
        mShow = (TextView) findViewById(R.id.show);
        tvIPAddress = (TextView) findViewById(R.id.ipaddressshow);

        tvIPAddress.setText("IP Address : " + GetIPAddress());
    }

    private void initData() {
        mShowID = getApplicationContext();

        mThreadPool = Executors.newFixedThreadPool(5);

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

        //bt_tcpstart = findViewById(R.id.bt_tcpstart);
        //bt_tcpstart.setOnClickListener(this);
        //bt_tcpstart.setEnabled(false);

        //btnConfigSetting = findViewById(R.id.ConfigSetting);
        //btnFWUpdate = findViewById(R.id.FWUpdate);
        //btnDataAnalysis = findViewById(R.id.DataAnalysis);
        //btnNoiseAnalysis = findViewById(R.id.NoiseAnalysis);
        //btnDemoTools = findViewById(R.id.DemoTools);
        //btnIICOperation = findViewById(R.id.IICOperation);
        //btnContactUs = findViewById(R.id.ContactUs);

        btnExit = findViewById(R.id.Exit);
        btnExit.setOnClickListener(this);
    }



    @Override
    public void onClick(final View v) {
        switch (v.getId()) {
            case R.id.Exit:   //Exit
                exit();
                break;
        /*
            case R.id.bt_tcpstart:

                String btContent = bt_tcpstart.getText().toString();

                if (btContent.equals("TCP启动")) {

                    bt_tcpstart.setText("TCP停止");

                    btnConfigSetting.setEnabled(false);
                    btnFWUpdate.setEnabled(false);
                    btnDataAnalysis.setEnabled(false);
                    btnNoiseAnalysis.setEnabled(false);
                    //btnDemoTools.setEnabled(false);
                    btnIICOperation.setEnabled(false);
                    btnContactUs.setEnabled(false);

                    //bt_tcpstart.setBackgroundColor(getResources().getColor(R.color.colorAccent1));

                    new Thread(new Runnable() {

                        @Override

                        public void run() {
                            while(true) {
                                try {
                                    // server将一直等待连接的到来

                                    System.out.println("等待客户端连接");
                                    socket = server.accept();
                                    System.out.println("客户端已连接");
                                    // 建立好连接后，从socket中获取输入流，并建立缓冲区进行读取
                                    inputStream = socket.getInputStream();
                                    outputStream = socket.getOutputStream();
                                    byte[] headbytes = new byte[8];
                                    byte[] databytes = new byte[1024 * 8];
                                    int len;
                                    int datalen = 0;
                                    int framelen = 0;
                                    int frameid = 0;
                                    StringBuilder sb = new StringBuilder();

                                    //只有当客户端关闭它的输出流的时候，服务端才能取得结尾的-1
                                    while ((len = inputStream.read(headbytes, 0, 8)) != -1) {

                                        //先判断头部字节是否正确
                                        if (headbytes[0] == (byte) 0x8d
                                                && headbytes[1] == 0x7c
                                                && headbytes[2] == 0x6b
                                                && headbytes[3] == 0x5a) {

                                            framelen = (headbytes[4] & 0xff) + (int) ((headbytes[5] & 0xff) * 256);  //低位在前
                                            frameid = (headbytes[6] & 0xff) + (int) ((headbytes[7] & 0xff) * 256);

                                            int offset = 0;

                                            do {
                                                // byte[] bytes = new byte[framelen];
                                                len = inputStream.read(mBytes, offset, framelen - offset);
                                                if (len == -1) {
                                                    break;
                                                }
                                                offset += len;
                                            } while (offset < framelen);

                                            if (offset != framelen) {
                                                continue;
                                            }

                                            datalen = (mBytes[5] & 0xFF) + (int) (mBytes[4] * 256);  //高位在前

                                            if (mBytes[0] == 1) {
                                                SetUSBData(mBytes, datalen);
                                            } else {
                                                if (GetUSBData(mBytes, databytes, datalen)) {//根据命令去获取USB数据
                                                    databytes[0] = (byte) 0x8d;
                                                    databytes[1] = 0x7c;
                                                    databytes[2] = 0x6b;
                                                    databytes[3] = 0x5a;
                                                    databytes[4] = (byte) datalen;
                                                    databytes[5] = (byte) (datalen >> 8);
                                                    databytes[6] = (byte) frameid;
                                                    databytes[7] = (byte) (frameid >> 8);
                                                    outputStream.write(databytes, 0, datalen + 8);
                                                }
                                            }
                                        }
                                    }

                                    inputStream.close();
                                    outputStream.close();
                                    socket.close();
                                    System.out.println("客户端已断开");

                                    //server.close();

                                } catch (IOException e) {
                                    e.printStackTrace();
                                    Log.i(TAG, "连接失败！！!" + e.toString());

                                }
                            }
                        }

                    }).start();

                } else {

                    bt_tcpstart.setText("TCP启动");
                    //bt_tcpstart.setBackgroundColor(getResources().getColor(R.color.colorAccent2));

                    try {
                        inputStream.close();
                        outputStream.close();
                        socket.close();
                        //server.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    btnConfigSetting.setEnabled(true);
                    btnFWUpdate.setEnabled(true);
                    btnDataAnalysis.setEnabled(true);
                    btnNoiseAnalysis.setEnabled(true);
                    //btnDemoTools.setEnabled(true);
                    btnIICOperation.setEnabled(true);
                    btnContactUs.setEnabled(true);

                }

                break;
        */
            default:
                break;
        }
    }

    /**
     * ???? , ??????????
     */
    private void openDevices() {
        //????(??)
        mOpenDevicesReceiver = new OpenDevicesReceiver(this);
        mThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                SystemClock.sleep(1000);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(mShowID, 0, new Intent(ACTION_USB_PERMISSION), 0);
                IntentFilter intentFilter = new IntentFilter(USB_ACTION);

                registerReceiver(mOpenDevicesReceiver, intentFilter);

               // while(true)
                {
                    isNeedFindDevice = true;

                    while (isNeedFindDevice) {
                        SystemClock.sleep(100);
                        isS818Device = false;
                        HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
                        if (deviceList != null) {

                            for (UsbDevice usbDevice : deviceList.values()) {
                                //int productId = usbDevice.getProductId();
                                int iVendorId = usbDevice.getVendorId();
                                if ((iVendorId == 0x27C0)          //之前VID错误了，做兼容
                                        ||(iVendorId == 0x27C6)    //汇顶的VID
                                        ||(iVendorId == 0x222A)    //奕力的VID
                                        ||(iVendorId == 0x056A))   //8191主动笔和Wacom主动笔
                                {
                                    isS818Device = true;
                                    if (mUsbManager.hasPermission(usbDevice)) {
                                        initDevice();
                                    }
                                    else {
                                        // mUsbManager.requestPermission(usbDevice, PendingIntent.getBroadcast(mContext, 0, new Intent(""), 0));//pendingIntent
                                        mUsbManager.requestPermission(usbDevice,pendingIntent);

                                        SystemClock.sleep(1500);
                                        break;
                                    }//if (mUsbManager.hasPermission(usbDevice))

                                    break;

                                }  // if (productId == 0x0818 && vendorId == 0x27C0)

                            }  // for (UsbDevice usbDevice : deviceList.values())

                            if(isS818Device==false){
                                mUsbEndpointOut = null;

                                mUsbEndpointIn = null;

                                mHandler.sendEmptyMessage(CONNECTED_FAILED);
                            }
                            //break;
                        } //if (deviceList != null)
                        else {
                            // mError.setText("请连接USB");
                        }
                        // }
                    }  //while (isNeedFindDevice)
                }  //while(1)

            }   //ThreadPool
        });   //ThreadPool
    }

    /**
     * ??????????(????) , ??????????Accessory?????? , ??????PID??????Google??????2?????????????????? ,
     */
    @SuppressLint("NewApi")
    private void initDevice() {
        HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
        Collection<UsbDevice> values = deviceList.values();
        if (!values.isEmpty()) {
            for (UsbDevice usbDevice : values) {
                //int productId = usbDevice.getProductId();
                int iVendorId = usbDevice.getVendorId();
                //if (productId == 0x0818 || productId == 0x0001 )
                if ((iVendorId == 0x27C0)          //之前VID错误了，做兼容
                        ||(iVendorId == 0x27C6)    //汇顶的VID
                        ||(iVendorId == 0x222A)    //奕力的VID
                        ||(iVendorId == 0x056A))   //8191主动笔和Wacom主动笔
                {

                    if (mUsbManager.hasPermission(usbDevice)) {
                        UsbInterface usbInterface = usbDevice.getInterface(1);

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

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

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

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
/*
        try {

            server.close();

        } catch (IOException e) {

            e.printStackTrace();

        }
*/
        if (mUsbDeviceConnection != null) {
            mUsbDeviceConnection.releaseInterface(mUsbInterface);
            mUsbDeviceConnection.close();
            mUsbDeviceConnection = null;
        }
        mUsbEndpointIn = null;
        mUsbEndpointOut = null;
        isNeedFindDevice = false;
        mThreadPool.shutdownNow();
        unregisterReceiver(mOpenDevicesReceiver);
    }

    public void exit()
    {
/*
        try {

            server.close();

        } catch (IOException e) {

            e.printStackTrace();

        }
*/
        for(Activity act:activityList)
        {
            act.finish();
        }

        System.exit(0);
    }

    public static String GetIPAddress()
    {
       try {

            for (Enumeration<NetworkInterface> enNetI = NetworkInterface.getNetworkInterfaces(); enNetI.hasMoreElements(); ) {

                NetworkInterface netI = enNetI.nextElement();

                for (Enumeration<InetAddress> enumIpAddr = netI.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {

                    InetAddress inetAddress = enumIpAddr.nextElement();

                    if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {

                        return inetAddress.getHostAddress();

                    }

                }

            }

        } catch (SocketException e) {

            e.printStackTrace();

        }

        return "0.0.0.0";
    }
/*
    private byte iicByteData[]={
            //0    1   2     3    4    5    6
            0x03,0x00,0x0f,0x00,0x00,0x00,0x01,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,

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

    };

    private boolean SetUSBData(byte[]wBuffer, int length) {
        int address = (wBuffer[3] & 0xff) + (int)((wBuffer[2] & 0xff) * 256);//(wBuffer[3]<<8) + (wBuffer[4]&0xff);

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

        int offset = 0;

        for(int j=1; j <= 4; j++)   //命令和首地址
        {
            iicWriteData[j] = wBuffer[j-1];
        }
        iicWriteData[0] = 0x03;
        iicWriteData[5] = 0;

        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 - 1];  //copy 数据
            }
            int  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的固定地址读取任意bytes的数据
    private boolean GetUSBData(byte[]cmd, byte[] wBuffer,int length) {

        int i;

        do
        {
            i = mUsbDeviceConnection.bulkTransfer(mUsbEndpointIn, wBuffer, 0, 512, 3);//清空接收缓冲区
        }while(i!=-1);

        if(cmd[1] == 13)//同步读取数据
        {
            int nTryTimes = 40;

            do{
                i = mUsbDeviceConnection.bulkTransfer(mUsbEndpointOut, SyncCmd, 0, 7, 100);
                if (i != 7)
                    return false;  //传输失败

                i = mUsbDeviceConnection.bulkTransfer(mUsbEndpointIn, iicByteData, 0, 0x40, 100);

                if (i != 0x40) {
                    return false;
                }
                if(((iicByteData[1]) &0x080)!=0)
                {
                    break;
                }

            }while(--nTryTimes > 0);
        }


        for(int j=1; j <= 6; j++)
        {
            iicByteData[j] = cmd[j-1];
        }
        iicByteData[0] = 0x03;

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

        int offset = 0;

        do{
            //接收数据
            i = mUsbDeviceConnection.bulkTransfer(mUsbEndpointIn, iicByteData, 0, 0x40, 100);

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

            for(int j = 1; j < i; j++)
            {
                wBuffer[offset + 7 + j] = iicByteData[j];
            }

            offset += i-1;

        }while(offset < length);

        return true;
    }

*/
}

class OpenDevicesReceiver extends BroadcastReceiver {

    private OpenDevicesListener mOpenDevicesListener;

    public OpenDevicesReceiver(OpenDevicesListener openDevicesListener) {
        mOpenDevicesListener = openDevicesListener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
        if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
            if (usbDevice != null) {
                // mOpenDevicesListener.openAccessoryModel(usbDevice);
            } else {
                //mOpenDevicesListener.openDevicesError();
            }
        } else {
            //mOpenDevicesListener.openDevicesError();
        }
    }

    public interface OpenDevicesListener {

        /**
         * 打开设备(手机)失败
         */
        //void openDevicesError();
    }

}