package com.xixun.communicate;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.RemoteException;
import android.content.Context;

import com.xixun.contract.model.PlayerInfo;
import com.xixun.display.MyLog;
import com.xixun.joey.aidlset.CardService;
import com.xixun.joey.aidlset.CommunicationJoey;
import com.xixun.lededitor.FrameBuffer;
import com.xixun.lededitor.Multi;

import org.json.JSONException;
import org.json.JSONObject;


import java.io.File;

import static android.os.SystemClock.sleep;

/**
 * Created by Administrator on 16/12/17.
 */

/**
 * Created by Administrator on 16/11/9.
 */

public class LedCardCommunication {
    public static final boolean bTestInNewFpga=false;//true;

    static final int STRING_SIZE=16;
    static final int GROUP_ID_SIZE=4;

    static final int NET_COMMU_TYPE_MULTI_SET_LIGHT=0x12;
    static final int NET_COMMU_TYPE_SYSTEM_STATE_REQUEST=0x82;
    static final int NET_COMMU_TYPE_SCREEN_OPERATOR=0x84;


    static final int NET_SUB_COMMU_TYPE_SET_LIGHT=0x02;
    static final int NET_SUB_COMMU_TYPE_GET_FPGA_REG=0x1F;

    static final int SERIAL_COMMU_TYPE_GET_FPGA_REG=0x7F;


    private static final int FBR_LIGHT=19;

    private static final int BUFFER_SIZE = 1024*2;

    public ClientsManage clientsManage=null;

    //public Socket socket=null;
    //private DataInputStream receStream=null;
    //private DataOutputStream sendStream=null;
    
    //private String displayIpAddress=null;;
    private int iHhostPort=0;

    // Y10:
    /* */
    public  static final String serialDeviceName_Sensor="/dev/s3c2410_serial1";
    public  static final String serialDeviceName_Fpga="/dev/s3c2410_serial2";
    public  static final String serialDeviceName_Extention="/dev/s3c2410_serial3";

    // E10:
    /*
    public  static final String serialDeviceName_Sensor="/dev/ttyMT0";
    public  static final String serialDeviceName_Fpga="/dev/ttyMT1";
    public  static final String serialDeviceName_Extention="/dev/ttyMT1";
    */

    // M50:
    /*
    //public  static final String serialDeviceName_TTL="/dev/ttyS3";
    //public  static final String serialDeviceName_232="/dev/ttyS4;
    //public  static final String serialDeviceName_485="/dev/ttyS5";
    */

    public  Uart        uart_Sensor=null;
    public  Uart        uart_Fpga=null;
    public  Uart        uart_Extension=null;

    public AidlSerialPort aidlSerialPort_Sensor=null;

    public AidlSerialPort aidlSerialPort_Extention=null;

    public MooncellFpga mooncellFpga=null;
    public SerialExtension serialExtension=null;
    public FrameBuffer frameBuffer=null;
    public Multi multi=null;
    public CardService cardService=null;
    JSONObject gpioInput_JasonBoject=null;
    JSONObject gpioOutput_JasonBoject=null;
    JSONObject gpioConfig_JasonBoject=null;

    int iSleepLength=3000;

    public NetDevicesManage netDevicesManage=null;

    Report  report=null;


    LedCardCommunication(ClientsManage clientsManage, String displayIpAddress, int iHhostPort)
    {   this.clientsManage=clientsManage;
        //this.displayIpAddress=displayIpAddress;
        //this.iHhostPort=iHhostPort;
        //netDevicesManage=new NetDevicesManage(this);



        new Thread() {
            public void run() {
                Process();
            }
        }.start();
    }

    private void Process()
    {
        if (clientsManage==null) return;
        if (clientsManage.ms==null) return;

        try { // Wait Class Constructure Function Return And Value for ledCardCommunication.
            Thread.sleep(3000); // 等待控制卡配套程序可靠运行起来。
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
         } catch (Exception e) {
            e.printStackTrace();
        }
        // uart_Sensor=new Uart(this,serialDeviceName_Sensor,4000000);
        // uart_Fpga=new Uart(this,serialDeviceName_Fpga,115200);
        // uart_Extension=new Uart(this,serialDeviceName_Extention,4000000);

        /*
        while (socket==null) {
            try {
                if (NeedExit()) return;

                socket = new Socket(displayIpAddress, iHhostPort);

                if (socket == null) {
                    MyLog.i( "Wait controller socket connect："+displayIpAddress  );
                    sleep(100);
                    continue;
                }
                receStream = new DataInputStream(socket.getInputStream());
                sendStream = new DataOutputStream(socket.getOutputStream());
            } catch (Exception e) {
                MyLog.i(" "+ Thread.currentThread().getStackTrace()[2].getFileName() + "-->"
                            +   "Function: " +Thread.currentThread().getStackTrace()[2].getMethodName() + "-->"
                            +   "Line" +Thread.currentThread().getStackTrace()[2].getLineNumber() + ":\r\n"
                            +   " Error:" + e.getMessage() + "\r\n\r\n"
                    );
                Request_Exit();
                break;
            }
        }
        */

        //Test
        if ((bTestInNewFpga==false))//&&(Define.bRunOnDebug418==false))
        while (cardService==null) {
            try {
                if (NeedExit()) return;
                cardService = CommunicationJoey.getCardService(clientsManage.ms);
                if (cardService == null) {
                    MyLog.i( "Wait controller cardService connect."  );
                    sleep(100);
                    continue;
                }

                {
                    gpioConfig_JasonBoject= new JSONObject();
                    gpioConfig_JasonBoject.put("id", "None");
                    gpioConfig_JasonBoject.put("_type", "OperationGPIO");
                    gpioConfig_JasonBoject.put("method", 0);
                }

                {
                    gpioInput_JasonBoject= new JSONObject();
                    gpioInput_JasonBoject.put("id", "None");
                    gpioInput_JasonBoject.put("_type", "OperationGPIO");
                    gpioInput_JasonBoject.put("method", 1);
                }

                {
                    gpioOutput_JasonBoject= new JSONObject();
                    gpioOutput_JasonBoject.put("id", "None");
                    gpioOutput_JasonBoject.put("_type", "OperationGPIO");
                    gpioOutput_JasonBoject.put("method", 2);
                }

                GetSerialNumber();             //  获得卡型号

            } catch (Exception e) {
                MyLog.i(" "+ Thread.currentThread().getStackTrace()[2].getFileName() + "-->"
                            +   "Function: " +Thread.currentThread().getStackTrace()[2].getMethodName() + "-->"
                            +   "Line" +Thread.currentThread().getStackTrace()[2].getLineNumber() + ":\r\n"
                            + "    Error:" + e.getMessage() + "\r\n\r\n"
                    );
                Request_Exit();
                break;
            }

        }
      //      MyLog.i("------------SerialExtension");              // uart
        if (clientsManage.ms.bDisplay_RailWay)   //false
            serialExtension=new SerialExtension(this);

        //元亨徐荣生去掉下列if else mooncellFpga语句
        if (Define.bRunOn_GpsReport) {     //true
            report = new Report(this,"interads.co.id", ClientsManage.UDP_GPS_REPORT);// "163.53.193.72".
        }/*else*/
        {
           mooncellFpga = new MooncellFpga(this);
        }
        registerFpgaUpgrade(clientsManage.ms);
        bReady = true;

        boolean bSet=false;
        int iCounter=0;
        int [] Databuffer=new int[1920*256];
        while(NeedExit()==false || GetReady()) {
            //if (bHaveGetState==false) GetState();
            try {
                if (bSet==false) {
                    if (Get_DisplayID() != null) {    //  return StringID
                        if (CardType("M")) {
                            // nConfig.
                            MyLog.i("PhyIntial...............................");
                            GpioConfig('B',6,true);
                            GpioOutput('B',6,true);
                            // NCE.
                            GpioConfig('B',7,false);
                            // nConfigDone.
                            GpioConfig('I',8,false);

                            PhyIntial();
                        }
                        bSet = true;
                    }
                }

                if (CardType("E10")==false) {
                   // LightPro();
//                    MyLog.i("LightPro............................");
//                    LightPro();
                    sleep(iSleepLength);
                     UdiscPro(); // u盘导参数，备份参数，有问题：导入后文件后，apk重新给fpga加载参数会黑屏

                   /* if (frameBuffer!=null)
                    {   int i=0;
                        //for (int i=0;i<Databuffer.length;i++) Databuffer[i]=i*8;
                        //frameBuffer.DeveiceWrite(Databuffer,0,Databuffer.length);
                        for (;i<1920*10;i++) Databuffer[i]=0xFF;
                        for (;i<1920*20;i++) Databuffer[i]=0xFF00;
                        for (;i<1920*30;i++) Databuffer[i]=0xFF0000;
                        frameBuffer.DeveiceWrite(Databuffer,0,1920*256);

                        //MyLog.i("frameBuffer.lenth:"+ Databuffer.length);
                    }*/


                    if (false)
                    {   mooncellFpga.FpgaUpgrade(clientsManage.ms.strStoragePath + Define.RECE_FILES_PATH + "c003.rpd");
                        ReloadWorkParams();
                        Thread.sleep(3000);
                        mooncellFpga.FpgaUpgrade(clientsManage.ms.strStoragePath + Define.RECE_FILES_PATH + "c004.rpd");
                        ReloadWorkParams();
                        Thread.sleep(3000);
                    }
                    iCounter++;
                }

            } catch (Exception e) {
                MyLog.i(" "+ Thread.currentThread().getStackTrace()[2].getFileName() + "-->"
                        +   "Function: " +Thread.currentThread().getStackTrace()[2].getMethodName() + "-->"
                        +   "Line" +Thread.currentThread().getStackTrace()[2].getLineNumber() + ":\r\n"
                        + "    Error:" + e.getMessage() + "\r\n\r\n"
                );
                Request_Exit();
                break;
            }


        }
    }

    static final String ACTION_PLAYER ="com.xixun.action.PlayerInfo";
    public static final String PACKAGE_PLAYER="com.xixun.xixunplayer";
    public static Intent newPlayerIntent(){
        Intent intent = new Intent(ACTION_PLAYER);
        intent.setPackage(PACKAGE_PLAYER);
        return intent;
    }
    void A()
    {   Intent intent=newPlayerIntent();
        PlayerInfo playerInfo=new PlayerInfo();
        //MyLog.i("Fpga upgade path ==> " + playerInfo.getProgramName());
    }

    public static BroadcastReceiver receiver = null;


    private void registerFpgaUpgrade(Context context) {
        MyLog.i("--------- FpgaUpgrade ");
       IntentFilter filter = new IntentFilter();
        filter.addAction("xixun.intent.action.UPGRADE_FPGA");
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
             //   String path = intent.getStringExtra("path");
                String   path = "/data/joey/kernel";
                MyLog.i("Fpga upgade path ==> " + path);
                for (String pathname : new File(path).list()) {

                    if (pathname.endsWith(".rpd"))
                    {
                        String strFileNameAndPath =path+"/"+pathname;
                        MyLog.i("Fpga update file: "+strFileNameAndPath);
                        try {
//                            for (int i = 0;i<10000000;i++) {
//                                MyLog.sleepForSecond(2);
                                mooncellFpga.FpgaUpgrade(strFileNameAndPath);
//                            }
                        } catch (Exception e) {
                            MyLog.i(" "+ Thread.currentThread().getStackTrace()[2].getFileName() + "-->"
                                    +   "Function: " +Thread.currentThread().getStackTrace()[2].getMethodName() + "-->"
                                    +   "Line" +Thread.currentThread().getStackTrace()[2].getLineNumber() + ":\r\n"
                                    + "    Error:" + e.getMessage() + "\r\n\r\n"
                            );
                        }
                        ReloadWorkParams();
                    }

                }
            }
        };

        context.registerReceiver(receiver, filter);

    }


//Log.i(TAG, "---------------------------------------Brightness is: " + cardService.getBrightness());
    //                        TaskToSetBrightness tts = new TaskToSetBrightness();
//                        card.setTimingTaskBrightness(tts);


   public String GetSerialNumber()
    {
        // 通过设置错误的管脚号返回Jason数据里面的CardId谢谢来得到控制卡序列号。
        //MyLog.i("=====================GPIO Get SerialNumber Test===========================");
        //MyLog.i("-------------------executeJsonCommand: " + gpioConfig_JasonBoject.toString());
        //{"value":1,"id":"None","_type":"OperationGPIO","num":31,"method":0,"group":90}
        //MyLog.i("-------------------strPinState: " + strPinState);
        //{"_type":"Error","cardId":"y10-116-01366","commandId":"None","errorMessage":"Can not set gpio mode"}
        while (StringID==null) {    // StringID = null
            try {
                JSONObject obj = new JSONObject(GpioConfig('Z', 31, true));
                if (obj==null)  {
                    sleep(300);
                    continue;
                }

                String strSerialNumber = (String) obj.get("cardId");
                if (strSerialNumber==null) {
                    sleep(300);
                    continue;
                }
                if (strSerialNumber.length()<="Y1-AB-1234".length()) break;

                StringID = strSerialNumber.toUpperCase();
               // StringID = "E30-999-0001";

                // modifide byfw  2019-4-17 ----start       y10 e10 误装display后，不给启动app
                int ch1 = (int) StringID.charAt(1);  // byfw  stop y10 ,e10...
                if( (ch1 >= 48 ) && (ch1 < 51)  ) {
                    StringID = "xxx-xxx-xxxx";
                    MyLog.i("display will stop! no need display apk!!");
                    System.exit(0);
                }
                MyLog.i("------------SerialNumber:" + StringID);
                // modifide byfw  2019-4-17 ----end

                /*CardService cardsystemService = null;
                JSONObject object = new JSONObject();
                try {
                    object.put("id", "display_brightness_success");
                    object.put("_type", "IsHardwareMooncell");
                    object.put("mooncell", true);
                    cardsystemService.executeJsonCommand(object.toString());
                }catch (JSONException e) {
                        MyLog.i( "aidl disconnect!"  );
                    e.printStackTrace();
                    }*/


                break;
            } catch (Exception e) {
                MyLog.i(" " + Thread.currentThread().getStackTrace()[2].getFileName() + "-->"
                        + "Function: " + Thread.currentThread().getStackTrace()[2].getMethodName() + "-->"
                        + "Line" + Thread.currentThread().getStackTrace()[2].getLineNumber() + ":\r\n"
                );
            }
        }
        return StringID;
    }

    public String GpioConfig(int ucPortId,int iPinId,boolean bOutput)
    {   if (cardService==null) return null;
        if (gpioConfig_JasonBoject==null) return null;

        String strPinState = null;
        try {
            gpioConfig_JasonBoject.put("group", ucPortId);
            gpioConfig_JasonBoject.put("num", iPinId);
            gpioConfig_JasonBoject.put("value", bOutput? 1: 0);
            strPinState = cardService.executeJsonCommand(gpioConfig_JasonBoject.toString());
            //MyLog.i(" " + Thread.currentThread().getStackTrace()[2].getFileName() + "-->"
            //        + "Function: " + Thread.currentThread().getStackTrace()[2].getMethodName() + "-->"
             //       + "Line" + Thread.currentThread().getStackTrace()[2].getLineNumber() + ":\r\n"
            //);
            //MyLog.i("-------------------executeJsonCommand: " + gpioConfig_JasonBoject.toString());
            //MyLog.i("-------------------strPinState: " + strPinState);
        }
        catch (Exception e) {
            MyLog.i(" "+ Thread.currentThread().getStackTrace()[2].getFileName() + "-->"
                    +   "Function: " +Thread.currentThread().getStackTrace()[2].getMethodName() + "-->"
                    +   "Line" +Thread.currentThread().getStackTrace()[2].getLineNumber() + ":\r\n"
            );
            Request_Exit();
        }
        return strPinState;
    }

    public void GpioOutput(int ucPortId,int iPinId,boolean bHighLevel)
    {
        if (cardService==null) return;
        if (gpioConfig_JasonBoject==null) return;

        try {
            gpioOutput_JasonBoject.put("group", ucPortId);
            gpioOutput_JasonBoject.put("num", iPinId);
            gpioOutput_JasonBoject.put("value", bHighLevel? 1:0);
            String strPinState = cardService.executeJsonCommand(gpioOutput_JasonBoject.toString());
            //MyLog.i("-------------------executeJsonCommand: " + gpioOutput_JasonBoject.toString());
            //MyLog.i("-------------------strPinState: " + strPinState);
        }
        catch (Exception e) {
            MyLog.i(" "+ Thread.currentThread().getStackTrace()[2].getFileName() + "-->"
                    +   "Function: " +Thread.currentThread().getStackTrace()[2].getMethodName() + "-->"
                    +   "Line" +Thread.currentThread().getStackTrace()[2].getLineNumber() + ":\r\n"
            );
            Request_Exit();
        }
    }

    public boolean GpioInput(int ucPortId,int iPinId)
    {
        if (cardService==null) return false;
        if (gpioConfig_JasonBoject==null) return false;

        try {
            gpioInput_JasonBoject.put("group", ucPortId);
            gpioInput_JasonBoject.put("num", iPinId);
            gpioInput_JasonBoject.put("value", 0);
            String strPinState = cardService.executeJsonCommand(gpioInput_JasonBoject.toString());
            //MyLog.i("-------------------executeJsonCommand: " + gpioInput_JasonBoject.toString());
            //MyLog.i("-------------------strPinState: " + strPinState);
        }
        catch (Exception e) {
            MyLog.i(" "+ Thread.currentThread().getStackTrace()[2].getFileName() + "-->"
                    +   "Function: " +Thread.currentThread().getStackTrace()[2].getMethodName() + "-->"
                    +   "Line" +Thread.currentThread().getStackTrace()[2].getLineNumber() + ":\r\n"
            );
            Request_Exit();
        }
        return false;
    }

    public boolean GetSecreenOn()
    {   try {
            return cardService.isScreenOpen();
        } catch (Exception e) {
            MyLog.i(" "+ Thread.currentThread().getStackTrace()[2].getFileName() + "-->"
                    +   "Function: " +Thread.currentThread().getStackTrace()[2].getMethodName() + "-->"
                    +   "Line" +Thread.currentThread().getStackTrace()[2].getLineNumber() + ":\r\n"
                    + "    Error:" + e.getMessage() + "\r\n\r\n"
            );
        }
        return false;

    }


    public String GetAlias()
    {
       HttpLan httpLan=new HttpLan();
       return httpLan.getAlias();
    }

    public String GetPlayProgram()
    {   try {
                return clientsManage.ms.playerInfo.getProgramName();
            } catch (Exception e) {
            MyLog.i(" "+ Thread.currentThread().getStackTrace()[2].getFileName() + "-->"
                    +   "Function: " +Thread.currentThread().getStackTrace()[2].getMethodName() + "-->"
                    +   "Line" +Thread.currentThread().getStackTrace()[2].getLineNumber() + ":\r\n"
                    + "    Error:" + e.getMessage() + "\r\n\r\n"
            );
        }
        return null;
    }

    void Reboot(int iDelaySeconds)
    {


        JSONObject jasonObject=null;
        try {
            cardService.reboot(iDelaySeconds);
            /*
            jasonObject= new JSONObject();
            jasonObject.put("_type", "callCardService");
            jasonObject.put("fn", "reboot");
            jasonObject.put("arg1", iDelaySe

            String strState = cardService.executeJsonCommand(jasonObject.toString());conds);
            MyLog.i("-------------------strState: " + strState);
            */

        } catch (Exception e) {
            MyLog.i(" "+ Thread.currentThread().getStackTrace()[2].getFileName() + "-->"
                    +   "Function: " +Thread.currentThread().getStackTrace()[2].getMethodName() + "-->"
                    +   "Line" +Thread.currentThread().getStackTrace()[2].getLineNumber() + ":\r\n"
                    + "    Error:" + e.getMessage() + "\r\n\r\n"
            );
        }
    }

    /**/
    static final int I2C_PORT='I';
    static final int I2C_SDA=4;
    static final int I2C_CLK=5;
    static final int GIG_RESET=6;
    static final int FPGA_nConfigDone=8;

    static final int PHY_RST_PORT='I';
    static final int PHY_RST=6;

    // new board Y30 v8.11
  /*  static final int I2C_PORT='D';
    static final int I2C_SDA=28;
    static final int I2C_CLK=30;
    static final int GIG_RESET=6;
    static final int FPGA_nConfigDone=8;

    static final int PHY_RST_PORT='E';
    static final int PHY_RST=0;*/

/*
    static final int I2C_PORT='B';
    static final int I2C_SDA=10;
    static final int I2C_CLK=13;
    static final int PHY_RST_PORT='H';
    static final int PHY_RST=20;
*/


    void MDIO_OUTPUT(){   GpioConfig(I2C_PORT,I2C_SDA,true);    }
    void MDIO_INPUT(){   GpioConfig(I2C_PORT,I2C_SDA,false);    }
    void MDIO_HIGH(){   GpioOutput(I2C_PORT,I2C_SDA,true);    }
    void MDIO_LOW(){   GpioOutput(I2C_PORT,I2C_SDA,false);    }
    boolean MDIO_GET(){   return GpioInput(I2C_PORT,4);    }

    void MDC_OUTPUT(){   GpioConfig(I2C_PORT,I2C_CLK,true);    }
    void MDC_HIGH(){   GpioOutput(I2C_PORT,I2C_CLK,true);    }
    void MDC_LOW(){   GpioOutput(I2C_PORT,I2C_CLK,false);    }

    void RST_OUTPUT(){   GpioConfig(PHY_RST_PORT,PHY_RST,true);    }
    void RST_HIGH(){   GpioOutput(PHY_RST_PORT,PHY_RST,true);    }
    void RST_LOW(){   GpioOutput(PHY_RST_PORT,PHY_RST,false);    }

    void PhyReset()
    {
        RST_OUTPUT();
        RST_HIGH();
        sleep(100);
        RST_LOW();
        sleep(100);
        RST_HIGH();
        sleep(100);
    }


    void PhyIntial()
    {
        PhyReset();

        WritePhyData(0x00,0x09,0x1A00);
        WritePhyData(0x01,0x09,0x1A00);


    }

    void WritePhyData(int uiPhyAddress,int uiRegAddress,int iData)
    {
        int i;
        MDC_OUTPUT();
        MDIO_OUTPUT();
        sleep(10);


        for(i=0;i<32;i++)
        {
            MDC_LOW();
            MDIO_HIGH();    //1
            MDC_HIGH();
        }

        MDC_LOW();
        MDIO_LOW();	    //0
        MDC_HIGH();

        MDC_LOW();
        MDIO_HIGH();    //1
        MDC_HIGH();

        MDC_LOW();
        MDIO_LOW();     //0
        MDC_HIGH();

        MDC_LOW();
        MDIO_HIGH();	//1
        MDC_HIGH();


        for(i=5;i>=1;i--)
        {
            if((uiPhyAddress & (1<<(i-1)))!=0)
            {
                MDC_LOW();
                MDIO_HIGH();	//1
                MDC_HIGH();
            }
            else
            {
                MDC_LOW();
                MDIO_LOW();	    //0
                MDC_HIGH();

            }
        }

        for(i=5;i>=1;i--)
        {
            if((uiRegAddress & (1<<(i-1)))!=0)
            {
                MDC_LOW();
                MDIO_HIGH();	//1
                MDC_HIGH();

            }
            else
            {
                MDC_LOW();
                MDIO_LOW();	    //0
                MDC_HIGH();

            }
        }
        MDC_LOW();
        MDIO_HIGH();	//1
        MDC_HIGH();

        MDC_LOW();
        MDIO_LOW();	    //0
        MDC_HIGH();

        for(i=16;i>=1;i--)
        {
            if((iData & (1<<(i-1)))!=0)
            {
                MDC_LOW();
                MDIO_HIGH();	//1
                MDC_HIGH();

            }
            else
            {
                MDC_LOW();
                MDIO_LOW();	    //0
                MDC_HIGH();

            }
        }
        MDIO_HIGH();

    }


    int ReadPhyData(int uiPhyAddress,int uiRegAddress)
    {
        int temp=0,i=0;

        MDC_OUTPUT();
        MDIO_OUTPUT();
        sleep(10);

        for(i=0;i<32;i++)
        {
            MDC_LOW();
            MDIO_HIGH();    //1
            MDC_HIGH();
        }
        MDC_LOW();
        MDIO_LOW();	    //0
        MDC_HIGH();

        MDC_LOW();
        MDIO_HIGH();    //1
        MDC_HIGH();

        MDC_LOW();
        MDIO_HIGH();     //1
        MDC_HIGH();

        MDC_LOW();
        MDIO_LOW();		//0
        MDC_HIGH();


        for(i=5;i>=1;i--)
        {
            if((uiPhyAddress & (1<<(i-1)))!=0)
            {
                MDC_LOW();
                MDIO_HIGH();	//1
                MDC_HIGH();

            }
            else
            {
                MDC_LOW();
                MDIO_LOW();	    //0
                MDC_HIGH();
            }
        }

        for(i=5;i>=1;i--)
        {
            if((uiRegAddress & (1<<(i-1)))!=0)
            {
                MDC_LOW();
                MDIO_HIGH();	//1
                MDC_HIGH();
            }
            else
            {
                MDC_LOW();
                MDIO_LOW();	    //0
                MDC_HIGH();
            }
        }

        MDIO_INPUT();
        sleep(10);

        MDC_LOW();
        MDC_HIGH();

        MDC_LOW();
        MDC_HIGH();

        temp=0;
        for(i=16;i>=1;i--)
        {
            MDC_LOW();

            if(MDIO_GET())
            {
                temp |= 1<<(i-1);
            }

            MDC_HIGH();
        }
        return temp;
    }

    int iErroorCounter=0;
    public static boolean reboot_cmd = false;

 public boolean OldY30_Reboot_LightSet()
 {

     if( reboot_cmd )
     {
         MyLog.i( "---------OldY30_Reboot_LightSet ");
         if (mooncellFpga == null) {
             MyLog.i( "mooncellFpga == null");
             mooncellFpga = new MooncellFpga(this);
         }
         if (mooncellFpga.Reboot_LightSet()){
             MyLog.i( " Old Y30 Reboot_LightSet iLightValue = 0");
             sleep(5000);
         }
         else {
             MyLog.i("----------Set false iLightValue and again");
         }

         return true;
     }
     return false;
 }

   // CardService cardsystem_cardService = null;
   // int test_iLightValue=0;

//  public CardService cardsystem_cardService = null;
 public boolean LightPro(boolean manual,int iLightValue) {
     boolean result = false;
     if (iLightValue<=0 || OldY30_Reboot_LightSet()){
         return result;
     }
//        if (clientsManage.ms.workParams.iLightValue != iLightValue) {
     MyLog.i(" -----------iLightValue "+iLightValue);
        /* if( cardService == null ) {
             cardService = CommunicationJoey.getCardService(clientsManage.ms);
             MyLog.i("------- AIDL"+cardService);
         }
         if( cardService == null ){
             // 绑定不成功
             return false;
         }*/
        if (iLightValue>1024) {
            iErroorCounter++; // 统计3次均为错误数据，做出错处理.
            if (iErroorCounter>3) {
                Request_Exit(); // 亮度异常，会为155376，CardSystem已经重启过了，需要重启。
            }
            MyLog.i(" error -----------iLightValue");
            return false;
        }

        iErroorCounter=0;
        if (mooncellFpga!=null){
            result = mooncellFpga.LightSet(iLightValue);
        }
            /*if (result){ // 设置成功。
                JSONObject object = new JSONObject();
                try {
                    object.put("id", "display_brightness_success");
                    object.put("_type", "SetBrightnessFromDisplay");
                    object.put("manual", manual);
                    object.put("brightness", iLightValue);                         //byfw
                    object.put("result", result);
                    cardService.executeJsonCommand(object.toString());
                } catch (JSONException e) {
                    MyLog.i( "Wait controller cardService connect."  );
                    sleep(100);
                    e.printStackTrace();
                } catch (RemoteException e) {
                    cardService = null;
                    e.printStackTrace();
                }

                //====================================================
                //      MyLog.i("========================== iLightValue = "+iLightValue);
                iSleepLength = 500; // 亮度发生改变，加快反应时间。
                //MyLog.i( "iSleepLength="+ iSleepLength);

                clientsManage.ms.workParams.iLightValue=iLightValue;
                clientsManage.ms.workParams.pushBaseParams();
            }*/
//        }
     MyLog.i("result=============="+result);
    return result;
 }

    /**
     * 查询亮度
     * @return
     */
    public int getBrightness() {
        int result = mooncellFpga.getBrightness();
        return result;
    }

    public boolean CardType(String styCardType)
    {
        if (styCardType==null) return false;
        if (Get_DisplayID()==null) return false;

        return  Get_DisplayID().startsWith(styCardType);
    }

    boolean bHaveBackupOrRecover=false;
    void UdiscPro()
    {   boolean bHaveUdisc=false;
        if (mooncellFpga==null) return;
        if (mooncellFpga.GetReady()==false) return; // FPGA初始化时不能读取参数文件。
            // 检测优盘状态，自动备份、还原参数。
        if (CardType("M")) {
            for (int i = 0; i < 4; i++) {
                String strUdiscPath = "/mnt/usbhost" + i +"/";
                bHaveUdisc = UdiscProcess(strUdiscPath);
                if (bHaveUdisc) break;
            }
        }
        else
        if (CardType("Y")){
            bHaveUdisc = UdiscProcess("/udisk/");
           // bHaveUdisc = UdiscProcess("/mnt/media_rw");
        }
        else
        if (CardType("E"))
        {   // ????
        }
        else
        {
            bHaveUdisc = UdiscProcess("/storage/usbdisk3/");
        }

        if (bHaveUdisc==false) // 优盘拔出，清除状态。
        {
            if (bHaveBackupOrRecover)
            {   bHaveBackupOrRecover=false;
                MyLog.i("Udisc DragOut.");
                MyLog.i(" "+ Thread.currentThread().getStackTrace()[2].getFileName() + "-->"
                        +   "Function: " +Thread.currentThread().getStackTrace()[2].getMethodName() + "-->"
                        +   "Line" +Thread.currentThread().getStackTrace()[2].getLineNumber() + ":\r\n"
                );



                if (CardType("Y"))
                {   mooncellFpga.DispalyOff();
                    MyLog.i("System restart...");
                    Reboot(1);

                    //Request_Exit(); // 重启会导致网络连接不可靠，反复bind不成功。

                    // 防止重启不成功，重新加载FPGA参数。
                    MyLog.i("Wait 20s to reload params.");
                    sleep(20*1000);// 优盘拔出后控制卡会掉电一会，造成显示屏黑屏。
                    ReloadWorkParams();
                }
            }
        }

    }

    boolean UdiscProcess(String strUdiscPath)
    {
       // MyLog.i("aaa");
        File file=new File(strUdiscPath);
        if (file.exists()) // 检测优盘插入.
        {
       //    MyLog.i("bb");
            if (file.getTotalSpace() > (1 * 1024 * 1024 * 1024)) // 1GB.
            {
                MyLog.i("UDisc Path: " + strUdiscPath);
                iSleepLength = 200; // 优盘插入，加快反应时间。

                if ((bHaveBackupOrRecover == false)) {
                    MyLog.i(strUdiscPath + " Size:" + file.getTotalSpace() / 1024 / 1024 + " MBytes");

                    file = new File(strUdiscPath + "program.zip");
                    if (file.exists()) // 优盘升级节目用，则不备份参数。
                    {
                        MyLog.i("Disc use as program updating.");
                    } else // 优盘不作为升级节目用，则备份参数。
                    {   // // 因为接收卡参数不能备份出来，暂时不用备份发送卡参数。
                        String strPath = strUdiscPath + Define.WORK_FILES_PATH;

                        file = new File(strPath);
                        if (file.exists()) // 优盘-->控制卡。
                        {
                            MyLog.i("Recover params from UDisc.");
                            Define.FileCopy(strPath, clientsManage.ms.strStoragePath + Define.WORK_FILES_PATH);
                            //Toast.makeText(this, "这是一个Toast提示", Toast.LENGTH_LONG).show();
                            //MyLog.i("Udisc to Card : "+strUdiscPath + Define.WORK_FILES_PATH  + " to "+ clientsManage.strStoragePath+Define.WORK_FILES_PATH);
                            clientsManage.ms.workParams.Recover(strPath);
                            ReloadWorkParams();
                        } else // 控制卡-->优盘。
                        {
                            MyLog.i("Backup params to UDisc.");

                            Define.CreateFolder(strUdiscPath + Define.STORAGE_PATH);
                            Define.CreateFolder(strPath);
                            Define.FileCopy(clientsManage.ms.strStoragePath + Define.WORK_FILES_PATH, strPath);
                            clientsManage.ms.workParams.Backup(strPath);
                        }
                    }

                    /*

                     */

                    bHaveBackupOrRecover = true;
                }
                return true;
            }
        }
        return false;
    }

    void ReloadWorkParams()
    {
        if (mooncellFpga != null) mooncellFpga.Exit(false);
        mooncellFpga=new MooncellFpga(this); // 重新加载显示参数。
        while (mooncellFpga.GetReady()==false) sleep(100);

        mooncellFpga.LightSet(Get_Light());
    }

    //Boolean bHaveGetState=false;
/*
    public String GetState()
    {   if (NeedExit()) return null;
        if (GetReady()==false) return null;

        int iOffset=0,iCounter=0;
        byte []	    pBuffer=new byte[100];
        // 获取宽高等参数。
        TransData(NET_COMMU_TYPE_SYSTEM_STATE_REQUEST,null,0);
        return null;
    }
*/



    public String Get_DisplayID() { return StringID; }
   // public String Get_DisplayName() { return pCardName; }
    //public String Get_MacAddress() { return MacAddress; }
    //public String Get_IpAddress() { return IpAddress; }
    //public String Get_IpMask() { return IpMask; }
    public int Get_ScreenWidth() { return uiScreenWidth; }
	public int Get_ScreenHeight() { return uiScreenHeight; }

	public int Get_Light() {
        int iLightValue=-1;

        if (cardService!=null) {
            try {
                iLightValue = cardService.getBrightness();
            } catch (Exception e) {
                return -1;
            }
        }

        if (iLightValue<0) return -1;

        if (CardType("M")) // M:1~255.
        {
            if (iLightValue>0x100) return -1;
            return iLightValue;
        }

        if (iLightValue>64) return -1;
        return iLightValue*4; // Y10、E10：1~64.
    }

    private static final int IP_MAC_ADDRESS_SEG_NUM =6;
    private static final int IP_SEG_MIN_SIZE          =1;
    private static final int IP_SEG_MAX_SIZE	        =3;
    private static final int IP_SEG_SIZE		        =(IP_SEG_MAX_SIZE+1);
    private static final int IP_SEG_NUM 	            =4;

    private static final int CARD_NAME_SIZE=20;
    private static final int IP_MAC_ADDRESS_SIZE=(IP_MAC_ADDRESS_SEG_NUM*3+2);
    private static final int IP_ADDRESS_SIZE =(IP_SEG_SIZE*IP_SEG_NUM*2);

    public static final int LIGHT_START_VALUE =50;

    String  StringID    = null;      // 控制卡ID。
  /*  String      pCardName=null;     // 控制卡名称。

    String      MacAddress=null;    // MAC地址。
    String      IpAddress=null;     // IP 地址。
    String      IpMask=null;        // 掩码。
    int         uiIpPortBase=0;	 // 端口映射开始值。

    int		    uiColorNum=0;		 // 控制卡颜色数，Computer Use.*/
    int		    uiScreenWidth=0;	// 屏幕宽度。
    int		    uiScreenHeight=0;	// 屏幕高度。

  /*  int		    uiLanguage=0;		// 语言类型。见“_LAGNUAGE_TYPE”定义。

    int		    uiScreenMaxWidth=0;	// 屏幕最大支持宽度。
    int		    uiScreenMaxHeight=0;	// 屏幕最大支持高度。

    int		    bUseRetrace=0;			// 屏体是否有折返。
    int		    bStaticOrScan=0;		// 屏体是否静态或扫描。
    int		    uiGroupID=0;			// 控制卡组号。
    String	    IpGateWay=null;		// 网关地址。
    int			bNetRate100Mbps=0;		// 0x55AA55AA：100mbps双工，其他10M. HelecXu 11.10.20.

    int			uiCrossDisplayRemoveSize=0; // 十字屏，缺角像素点。
    int			bUseDhcp=0; 			// 0:不自动获取。UINT_SPECTIAL_FLAG：自动获取。

    int         uiLightValue=-1;*/

/*
    int ReceCommand_GetSystemState(byte [] pBuffer,int iOffset,int iLength)
    {    int iWorkResault=0;

        {
            StringID = new String(pBuffer, iOffset, 13).toUpperCase();
            StringID = StringID.toUpperCase();
        }

        iOffset+=STRING_SIZE;
        //MyLog.i(iOffset+"====================================================StringID:"+StringID);

        iOffset+=4;

        pCardName=new String(pBuffer,iOffset,13);
        iOffset+=CARD_NAME_SIZE;
        //MyLog.i(iOffset+"====================================================pCardName:"+pCardName);

        MacAddress=new String(pBuffer,iOffset,IP_MAC_ADDRESS_SIZE);
        iOffset+=IP_MAC_ADDRESS_SIZE;
        //MyLog.i(iOffset+"====================================================MacAddress:"+MacAddress);

        IpAddress=new String(pBuffer,iOffset,IP_ADDRESS_SIZE);
        iOffset+=IP_ADDRESS_SIZE;
        //MyLog.i(iOffset+"====================================================IpAddress:"+IpAddress);

        IpMask=new String(pBuffer,iOffset,IP_ADDRESS_SIZE);
        iOffset+=IP_ADDRESS_SIZE;
        //MyLog.i(iOffset+"====================================================IpMask:"+IpMask);

        uiIpPortBase=Define.GetBtyeToInt(pBuffer,iOffset);
        iOffset+=4;
        //MyLog.i(iOffset+"====================================================uiIpPortBase:"+uiIpPortBase);

        uiColorNum=Define.GetBtyeToInt(pBuffer,iOffset);
        iOffset+=4;
        //MyLog.i(iOffset+"====================================================uiColorNum:"+uiColorNum);

        uiScreenWidth=Define.GetBtyeToInt(pBuffer,iOffset);
        iOffset+=4;
        //MyLog.i(iOffset+"====================================================uiScreenWidth:"+uiScreenWidth);

        uiScreenHeight=Define.GetBtyeToInt(pBuffer,iOffset);
        iOffset+=4;
        //MyLog.i(iOffset+"====================================================uiScreenHeight:"+uiScreenHeight);

        uiLanguage=Define.GetBtyeToInt(pBuffer,iOffset);
        iOffset+=4;
        //MyLog.i(iOffset+"====================================================uiLanguage:"+uiLanguage);

        uiScreenMaxWidth=Define.GetBtyeToInt(pBuffer,iOffset);
        iOffset+=4;
        //MyLog.i(iOffset+"====================================================uiScreenMaxWidth:"+uiScreenMaxWidth);

        uiScreenMaxHeight=Define.GetBtyeToInt(pBuffer,iOffset);
        iOffset+=4;
        //MyLog.i(iOffset+"====================================================uiScreenMaxHeight:"+uiScreenMaxHeight);

        iOffset+=(4*3);

        IpGateWay=new String(pBuffer,iOffset,IP_ADDRESS_SIZE);
        iOffset+=IP_ADDRESS_SIZE;
        //MyLog.i(iOffset+"====================================================IpGateWay:"+IpGateWay);

        bNetRate100Mbps=Define.GetBtyeToInt(pBuffer,iOffset);
        iOffset+=4;
        //MyLog.i(iOffset+"====================================================bNetRate100Mbps:"+bNetRate100Mbps);

        iOffset+=(4*84);

        uiCrossDisplayRemoveSize=Define.GetBtyeToInt(pBuffer,iOffset);
        iOffset+=4;
        //MyLog.i(iOffset+"====================================================uiCrossDisplayRemoveSize:"+uiCrossDisplayRemoveSize);

        bUseDhcp=Define.GetBtyeToInt(pBuffer,iOffset);
        iOffset+=4;
        //MyLog.i(iOffset+"====================================================bUseDhcp:"+bUseDhcp);

        iOffset+=(4*6);

        uiLightValue=Define.GetBtyeToInt(pBuffer,iOffset);
        iOffset+=4;
        //MyLog.i(iOffset+"====================================================uiLightValue:"+uiLightValue);


        //bHaveGetState=true;
        return iWorkResault;
    }

    public int ReceCommand()
    {   int i=0,iWorkResault=0,iReceLenth=0;
        byte[]  receDataBuffer=new byte[1024*3];
        //MyLog.i("====================================================ReceCommand:");
        while (socket!=null) {
            if (socket.isConnected()==false) break;
            if (receStream==null) break;
            if (GetReady()==false) break;
            if (NeedExit()) return -1;

            try {

                iReceLenth=receStream.read(receDataBuffer);
                //MyLog.i("====================================================ReceCommand:iReceLenth=" + iReceLenth);
                //7e 7e 55 c2 0 0 0 0 40 4 0 0 65 31 30 2d 61 31 36 2d 30 30 32 33 32 0 0 0 0 0 0 0 65 31 30 2d 61 31 36 2d 30 30 32 33 32 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 c0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 aa 55 aa 55 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 40 0 0 0 0 0 0 0 33 33 13 40 33 33 13 40 33 33 13 40 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 19 12 16 20 14 a2 0 65 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 85====================================================ReceCommand:iReceLenth=25
               //7e 7e 55 c4 0 0 0 0 c 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 2
                if (iReceLenth<=0) continue;

                {   int iOffset=3;  // 命令类型偏移量。
                    int iCommandType=receDataBuffer[iOffset]&0xFF;
                    byte iCheckCode=Define.GetCheckCodeIn8(receDataBuffer,iOffset,iReceLenth-1);
                    iOffset=8;      // 协议包长度位置偏移量。
                    int iDataBufferLength=Define.GetBtyeToInt(receDataBuffer,iOffset);
                    iOffset=12;     // 协议包正文位置偏移量。
                    //System.out.printf(" iCommandType=0x%x\r\n",iCommandType);
                    //System.out.printf(" iCheckCode=0x%x\n",iCheckCode);
                    //System.out.printf(" iDataBufferLength=0x%x\n",iDataBufferLength);

                    if (iCheckCode==receDataBuffer[iReceLenth-1])
                    {   switch (iCommandType-0x40)
                        {   case NET_COMMU_TYPE_SYSTEM_STATE_REQUEST:
                                iWorkResault=ReceCommand_GetSystemState(receDataBuffer,iOffset,iReceLenth-1);
                                break;
                            default:
                                System.out.printf(" Unknow iCommandType=0x%x\n",iCommandType);
                                break;
                        }
                    } else System.out.printf("iCheckCode="+iCheckCode+" Real:"+receDataBuffer[iReceLenth-1]);

                    if (false) {
                        for (i = 0; i < iReceLenth; i++) {
                            System.out.printf(" %x", receDataBuffer[i]);
                            // if (i%16==0) System.out.printf("  0x=%d\n",i);
                        }
                        System.out.printf("\n\n");
                    }
                }

                //if (bHaveGetState) break;


            } catch (Exception e) {
                if (NeedExit()==false || GetReady())
                    MyLog.i(" "+ Thread.currentThread().getStackTrace()[2].getFileName() + "-->"
                        + "Function: " + Thread.currentThread().getStackTrace()[2].getMethodName() + "-->"
                        + "Line" + Thread.currentThread().getStackTrace()[2].getLineNumber() + ":\r\n"
                        + "    Error:" + e.getMessage() + "\r\n\r\n"
                );
                Request_Exit();
                break;
            }
        }
        //MyLog.i("====================================================ReceCommand:Out.");
        return iWorkResault;
    }

    int TransData(int ucCommand,byte pDataBuffer[],int iLength)
    {	int         i=0,iWorkResault=0,iTransLen=0,uiCheckOffset=0;
        byte []	    pBuffer=new byte[20+iLength];

        if (NeedExit()) return -1;
        if (GetReady()==false) return -1;
        if (sendStream==null) return -1;

        pBuffer[iTransLen++]=StreamPort.STREAM_SYNC_HEAD;   // 同步头。
        pBuffer[iTransLen++]=StreamPort.STREAM_SYNC_HEAD;
        pBuffer[iTransLen++]=StreamPort.STREAM_SYNC_HEAD2;
        pBuffer[iTransLen++]=(byte)ucCommand;      // 命令类型。

        //iTransLen+=STRING_SIZE;                   // 序列号。
        iTransLen+=GROUP_ID_SIZE;                 // 组号。

        Define.SetIntToBye(iLength,pBuffer,iTransLen);    // 正文长度。
        iTransLen+=4;

        if (pDataBuffer!=null && iLength>0) {
            System.arraycopy(pDataBuffer, 0, pBuffer, iTransLen, iLength);    // 正文内容。
            iTransLen += iLength;
        }

        //for (i=0;i<iLength;i++)  pBuffer[iTransLen++]=pDataBuffer[i];// 正文。

        pBuffer[iTransLen]=Define.GetCheckCodeIn8(pBuffer,3,iTransLen);
        iTransLen++;

        if (false)
        {	MyLog.i("---------------------------------------------------------------iLength="+iLength);
            MyLog.i("---------------------------------------------------------------iTransLen="+iTransLen);
            MyLog.i("---------------------------------------------------------------Last Data="+pBuffer[iTransLen]);
            MyLog.i("---------------------------------------------------------------Check="+pBuffer[iTransLen-1]);
        }

        if (false)
        {   System.out.printf("Trans Data:\n");
            for (i = 0; i < iTransLen; i++) {
                System.out.printf(" %x", pBuffer[i]);
                // if (i%16==0) System.out.printf("  0x=%d\n",i);
            }
            System.out.printf("\n\n");
        }

        try {
            synchronized (this) {
                sendStream.write(pBuffer, 0, iTransLen);
                sendStream.flush();
            }
        }catch (Exception e) {
            if (NeedExit()==false || GetReady())
                MyLog.i(displayIpAddress+ " "+ Thread.currentThread().getStackTrace()[2].getFileName() + "-->"
                        +   "Function: " +Thread.currentThread().getStackTrace()[2].getMethodName() + "-->"
                        +   "Line" +Thread.currentThread().getStackTrace()[2].getLineNumber() + ":\r\n"
                        +   "    Error:" + e.getMessage() + "\r\n\r\n"
                );
            Request_Exit();
            iWorkResault=-1;
        }
        return iWorkResault;
    }
*/
    Boolean bHaveRequest = false;
    public void Request_Exit()
    {
        if (bHaveRequest) return;
        bHaveRequest = true;

        if (NeedExit()) return;

        MyLog.i("LedCardCommunication Request_Exit.");

        if (clientsManage!=null)
            clientsManage.Request_Exit(null);
    }



    boolean bReady=false;
	public boolean GetReady() { return bReady; }

    boolean bNeedExit=false;
	public boolean NeedExit() { return bNeedExit; }
	
	public void Exit()
    {   if (NeedExit()) return;
        bNeedExit=true;
        bReady=false;
        /*
        try {
            if (receStream != null) receStream.close();
            receStream=null;
            if (sendStream != null) sendStream.close();
            sendStream=null;
            if (socket != null) socket.close();
            //socket=null;

        } catch (Exception e1) {}
        */


        if (aidlSerialPort_Sensor != null) aidlSerialPort_Sensor.Exit();
        aidlSerialPort_Sensor=null;

        if (serialExtension != null) serialExtension.Exit();
        serialExtension=null;

        if (mooncellFpga != null) mooncellFpga.Exit(true);
        mooncellFpga=null;

        if (netDevicesManage!=null) netDevicesManage.Exit();
        netDevicesManage=null;

        if (frameBuffer!=null)
        {
            // JNI ERROR (app bug): accessed stale local reference 0x1d50000d (index 3 in a table of size 1)
            // JNI WARNING: 0x1d50000d is not a valid JNI reference
            //frameBuffer.Close();
            frameBuffer=null;
        }

        if (report!=null)
        {
            report.Exit();
            report=null;
        }

        MyLog.i(" "+ Thread.currentThread().getStackTrace()[2].getFileName() + "-->"
                +   "Function: " +Thread.currentThread().getStackTrace()[2].getMethodName() + "-->"
                +   "Line" +Thread.currentThread().getStackTrace()[2].getLineNumber() + ":\r\n"
        );
    }

    private int count = 0;
  public void Send_Version_to_CardSystem(boolean flag)
    {
        int i;
      //  String p=null;
        CardService cardsystemService_Version = null;
        for(i=0; i<15; i++) {

            if (cardsystemService_Version != null)
                break;


            cardsystemService_Version = CommunicationJoey.getCardService(clientsManage.ms);
            try{
                sleep(200);

            }catch (Exception e)
            { }
        }

        if (cardsystemService_Version == null)
            return;

        JSONObject object = new JSONObject();
        try {
            object.put("id", "display_brightness_success");
            object.put("_type", "IsHardwareMooncell");
            object.put("mooncell", flag);
            object.put("count", count++);
       //    MyLog.i(" -------3    " + Thread.currentThread().getName());
           cardsystemService_Version.executeJsonCommand(object.toString());
       //     MyLog.i( "---p" +p  );
        }catch (Exception e) {
            MyLog.i( "aidl disconnect!"  );
            e.printStackTrace();
        }
        MyLog.i(" -------FPGA version = "+flag);
    }
}
