package com.tcl.factory.serial;

 
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.tcl.factory.bsp.TCL;
import com.tcl.factory.bsp.TV;
import com.tcl.factory.bsp.TVDefine;
import com.tcl.factory.def.DEFS;
import com.tcl.factory.def.FactoryCmdStatus;


import com.tcl.factory.thirdparty.ThirdParty;
import com.tcl.factory.utils.Debug;
import com.tcl.factory.utils.Utils;
import com.tcl.factory.view.MainMenu;
//import com.tcl.factory.view.USBCloneDialog;
import com.tcl.factory.view.PModeMenu;

public class SerialManager{
	public final static char FACTORY_DEBUG_HEADING_CODE=0xAA ;
	public final static char FACTORY_DEBUG_RETURN_CODE=0xAB ;
	public final static char FACTORY_HDCP_HEAD_CODE=0xFE;

	static final short BluetoothSync_STATUS=0x97;
	static final short KEY_3D=0xd0;
	static final short USB_QUERRY=0x18;
	static final short RE_WARMUP_TIME=0x7B;
	static final short PROJECT_ID_QUERY=0x85;
	static final short HDCP_KEY_QUDERY=0x88;
	static final short IP_TV_PLATFORM_QUERY=0x8D;
	static final short PC_LINK_STATUS=0xB1;
	static final short USB_CLONE_STATUS=0xC3;
	static final short PCI_STATUS=0xC6;
	static final short CI_PLUS_STATUS=0xC9;
	static final short KEY_QUERY=0x5C;
	static final short KEY_BOARD_QUERY=0x77;
	static final short NVM_DATA_READ=0x5a;
	static final short SW_DATA=0x58;
	static final short FAC_TEST_DATA=0x1D;
	static final short POLL_MAC_DEVICEID_STATUS=0xb5;
	static final short RE_PORTAL_STATUS=0xB7;
	static final short RETURN_NET_PARA=0xBF;
	static final short NATURL_LIGHT_PARA=0x95;
	static final short COMM_PARAM=0x98;
	static final short SCREEN_PIXEL_DATA=0xE3;
	static final short HDCP_KEY_2_0_QUDERY=0xE6;
	static int  ValidCmdStartindex=0;   //标识引导码的位置 

	static short buffer[]=null;
	static short bufferCrc[]=null;

	static final short COMMAND_OK[]=
	{                
		0xAB,0x05,0x0A,0xDF,0x4E
	};
	static final short COM_OR_DATA_WRONG[]=
	{                
		0xAB,0x05,0x0E,0x9F,0xCA
	};
	static final short CRC_WRONG[]=
	{                
		0xAB,0x05,0x0F,0x8F,0xEB
	};
	private final static String TAG = "SerialManager";

	

	
public static void serialCmdVerify(short cmd[])
{
	Debug.v("TAG", "[serialCmdVerify]IN");
	if(cmd.length<5)
		return;
	if(cmd[2]==0x10)
	{
		switch(cmd[3])
		{
		case 0x00:
			TV.writeS(TVDefine.SerialDebug, DEFS.Disable);
			TV.writeS(TVDefine.WarmUP, DEFS.Disable);
			TV.writeD(TVDefine.Serial, COMMAND_OK);
			return;
			//break;
		case 0x01:
			TV.writeS(TVDefine.SerialDebug, DEFS.Enable);
 			break;
		}
	}
 
	if(TV.readS(TVDefine.SerialDebug) == DEFS.Disable)
	{
		Debug.v(TAG, "[COM_OR_DATA_WRONG]SerialDebug = "+TV.readS(TVDefine.SerialDebug));
		TV.writeD(TVDefine.Serial, COM_OR_DATA_WRONG);
 		return;
	}
 	if(TV.readS(TVDefine.PMode) == DEFS.Disable)
 	{
 		Debug.v(TAG, "[COM_OR_DATA_WRONG]PMode = "+TV.readS(TVDefine.PMode));
		TV.writeD(TVDefine.Serial, COM_OR_DATA_WRONG);
 		return;
	}
	buffer=new short[cmd.length];
	boolean firstIndexFlag = false;//标记是否找到 第一个引导码 
	int crcValue=0;
	int index=0;
	FactoryCmdStatus cmdDataStatus = FactoryCmdStatus.DATA_OK;
	while(index < cmd.length-1)	
	{
		Debug.v(TAG, ",cmd["+index+"] = "+cmd[index]);
		// 寻找是不�?0xAA开�?
		if((!firstIndexFlag)&&(cmd[index]==SerialManager.FACTORY_DEBUG_HEADING_CODE))
		{
			ValidCmdStartindex=index;//引导码在 字符串的位置
			firstIndexFlag = true;
			Debug.v("find..... oxAA", "great ....... ");
			   
			if(cmd[index+1]==SerialManager.FACTORY_HDCP_HEAD_CODE)
			{
				int factory_hdcp_key_length = ((cmd[index+2]<<8)&0xff00)+cmd[index+3]-7;
				
				Debug.v("HDCP Code", "index/buffer.length/factory_hdcp_key_length/hdcpLength = "+index+"/"+buffer.length+"/" + factory_hdcp_key_length  + "/" + (int)(((cmd[index+2]<<8)&0xff00)|cmd[index+3]));
				if(buffer.length-index>=factory_hdcp_key_length+7)// (AA AE LENGTH1 + LENGTH2+0x86+ crc1+crc2)=7
				{ 
					int hdcpCmdLength=((cmd[index+2]<<8)&0xff00)+cmd[index+3];
					//这个判断�?链路层？
 					if(hdcpCmdLength!=factory_hdcp_key_length+7){//327 byte
						Log.i(TAG, "[COM_OR_DATA_WRONG][HDCP]hdcpLength Wrong = "+hdcpCmdLength);
 						TV.writeD(TVDefine.Serial, COM_OR_DATA_WRONG);
  						break;
					}
 					int cmdType=cmd[index+4];// 0x86
					if((cmdType!=0x86) && (cmdType!=0xe4))  //hdcp2_0:0xe4
					{
						Log.i(TAG, "[COM_OR_DATA_WRONG][HDCP]cmdType Wrong = "+cmdType);
 						TV.writeD(TVDefine.HdcpKey, COM_OR_DATA_WRONG);
 						break;
					}
 					for(int j=0;j<factory_hdcp_key_length+7;j++)// 327 byte
					{
						buffer[j]=cmd[j];// AA AE len1 len2 4 byte deleted
					}
 					
					crcValue=(int)Utils.CRCCalculate(buffer,(hdcpCmdLength-2));// crc -2
					if((((crcValue&0xff00)>>8)!=buffer[factory_hdcp_key_length+5])
							||((crcValue&0x00ff)!=buffer[factory_hdcp_key_length+6]))
					{
						Log.i(TAG, "[CRC_WRONG][HDCP]");
						TV.writeD(TVDefine.Serial, CRC_WRONG);
  						break;
					}
					
					//命令执行时间长，服务器需做延�?
					Log.i(TAG, "[COMMAND_OK][HDCP]");
					TV.writeD(TVDefine.Serial, COMMAND_OK);
					
					if(cmdType==0x86) {
						TV.writeD(TVDefine.HdcpKey, getHdcpKey(buffer,factory_hdcp_key_length));
					}
					else if(cmdType==0xe4) {
						TV.writeD(TVDefine.HdcpKey20, getHdcpKey(buffer,factory_hdcp_key_length));
					}
					break;
 				}
				else
				{
					Log.i(TAG, "[COM_OR_DATA_WRONG][HDCP]buffer.length/index Wrong ! = "+buffer.length+"/"+index);
					TV.writeD(TVDefine.Serial, COM_OR_DATA_WRONG);
 					break;
				}
			}
		}
		else
		{
			index++;
			firstIndexFlag=false;
			cmdDataStatus =FactoryCmdStatus.DATA_OK;
			continue; 
		} 
		if((buffer.length-index)>4)
			if(firstIndexFlag) 
			{
				if(ValidCmdStartindex==cmd.length)//data length is wrong
				{
					cmdDataStatus= FactoryCmdStatus.DATA_ERROR_DATA_LOST;
					Log.i(TAG, "[COM_OR_DATA_WRONG]ValidCmdStartindex/cmd.length = "+ValidCmdStartindex+"/"+cmd.length);
					TV.writeD(TVDefine.Serial, COM_OR_DATA_WRONG);
					break;
				}
				else if(cmd[ValidCmdStartindex+1]>cmd.length)//data length
				{
					cmdDataStatus= FactoryCmdStatus.DATA_ERROR_INVALID_LEN;
					Log.i(TAG, "[COM_OR_DATA_WRONG]cmd[ValidCmdStartindex+1]/cmd.length = "+cmd[ValidCmdStartindex+1]+"/"+cmd.length);
					TV.writeD(TVDefine.Serial, COM_OR_DATA_WRONG);
 					break;
				}                    
				else if(!Utils.verifyCommandDataLength(cmd[ValidCmdStartindex+2],cmd[ValidCmdStartindex+1]-5)) 
				{     
					index++; 
					cmdDataStatus= FactoryCmdStatus.DATA_ERROR_DATA_UNSUITABLE_FOR_CMD;
					Log.i(TAG, "[COM_OR_DATA_WRONG]cmd[ValidCmdStartindex+2]/cmd[ValidCmdStartindex+1] = "+cmd[ValidCmdStartindex+2]+"/"+cmd[ValidCmdStartindex+1]);
					TV.writeD(TVDefine.Serial, COM_OR_DATA_WRONG);
 					continue;
				}                  
				for(int j=0;j<cmd[ValidCmdStartindex+1];j++)
				{
					buffer[j]=cmd[ValidCmdStartindex+j];
				}
				crcValue=(int)Utils.CRCCalculate(buffer,buffer[1]-2);//crc 计算�? buffer[1]-2 除开 CRC 的长�?

				if((((crcValue&0xff00)>>8)!=buffer[buffer[1]-2])
						||((crcValue&0x00ff)!=buffer[buffer[1]-1]))
				{
					cmdDataStatus= FactoryCmdStatus.DATA_ERROR_CRC_ERROR;
					Log.i(TAG, "[CRC_WRONG]");
					TV.writeD(TVDefine.Serial, CRC_WRONG);
 					index++;
					firstIndexFlag=false;
					continue;
				}
				//如果都没有错 则命令送出�?
				if(cmdDataStatus ==FactoryCmdStatus.DATA_OK)
				{  	 
					if((buffer[2]==0x4a)|(buffer[2]==0x4d))
					{
						if(buffer[3]!=4){
							Log.i(TAG, "[COM_OR_DATA_WRONG]buffer[2/3] = "+buffer[2]+"/"+buffer[3]);
							TV.writeD(TVDefine.Serial, COM_OR_DATA_WRONG);
							break;
						}
					}
					Log.i(TAG, "[COMMAND_OK]");
					TV.writeD(TVDefine.Serial, COMMAND_OK);
					factoryCommondParser(buffer);
					firstIndexFlag=false;
					break;
				}
			}
	}
	if( cmdDataStatus !=FactoryCmdStatus.DATA_OK) 
	{   
		cmdDataStatus= FactoryCmdStatus.DATA_OK;
	}
}
 
 
	
 
		public static void factoryCommondParser(short[] tclCommondBuffer)
		{
			Debug.v("TAG", "[factoryCommondParser]IN");

			short buffer[];
			Debug.v(TAG, "factoryCommondParser start["+tclCommondBuffer[0]+"]"+"["+tclCommondBuffer[1]+"]"+"["+tclCommondBuffer[2]+"]");
			if(tclCommondBuffer[0]!=SerialManager.FACTORY_DEBUG_HEADING_CODE)
			{
				Log.i(TAG, "DEFS.FACTORY_DEBUG_HEADING_CODE Error ");
			return;
			}
			if(TV.readS(TVDefine.SerialDebug) == DEFS.Enable){
 			switch(tclCommondBuffer[2])
			{
			case 0x11://00--Factory OSD Off   01--Factory OSD On   0x02--Pro Info  Display ON   0x03--Pro Info  Display Off
				switch(tclCommondBuffer[3])
				{
				case 0x00:
					TCL.setFacInfoShowEnable(DEFS.Disable);
 					break;
				case 0x01:
					TCL.setFacInfoShowEnable(DEFS.Enable);
 					break;
				case 0x02: 
					TCL.setSerInfoShowEnable(DEFS.Enable);
 					break;
				case 0x03: 
					TCL.setSerInfoShowEnable(DEFS.Disable);
 					break;
				}
				break;
			case 0x13: 
				if(tclCommondBuffer[3] == 0)
				{  
					TV.writeS(TVDefine.WarmUP, DEFS.Disable);
 				}
				else if(tclCommondBuffer[3] == 0x01)
				{   
					TV.writeS(TVDefine.WarmUP, DEFS.Enable);
				}
				break;
			case 0x14: 
				if(tclCommondBuffer[3] == 0)
				{
					TV.writeS(TVDefine.KeyCodeTest, DEFS.Disable);
				}
				else if(tclCommondBuffer[3] == 0x01)
				{
					TV.writeS(TVDefine.KeyCodeTest, DEFS.Enable);
 				}
				break;
			case 0x15://Factory Channel Preset  00--Factory Channel Empty
				switch(tclCommondBuffer[3])
				{
				case 0x00:/* Reset factory frequency */
					TV.writeV(TVDefine.ChannelPreSet,0);
 					break;
				case 0x01:/* Set HUIZHOU factory frequency */
					TV.writeV(TVDefine.ChannelPreSet,  0);
 					break;
				case 0x02:/* Set POLAND factory frequency */
					TV.writeV(TVDefine.ChannelPreSet,  1);
 					break;
				case 0x03:/* Set TTET factory frequency */
					TV.writeV(TVDefine.ChannelPreSet, 2);
 					break;
				case 0x04:/* Set WX factory frequency */
					TV.writeV(TVDefine.ChannelPreSet, 3);
 					break;
				}
				break;
			case 0x16://00--White Blance alignment condition preset  01--White Blance alignment condition cancel
				switch (tclCommondBuffer[3])
				{
				case 0x00:/* Set Picture Enhance ON */
//					TV.writeS(TVDefine.FleshTone, DEFS.Enable);
//					TV.writeS(TVDefine.Luma, DEFS.Enable);
 					break;
				case 0x01:/* Set Picture Enhance OFF */
					TCL.setFacInfoShowEnable(DEFS.Disable);
//					TV.setSource(DEFS.SOURCE_HDMI, 1);
					TV.writeV(TVDefine.WhiteBalance);
 					break;
				}
				break;
			case 0x17: {//usb check	
				short[] status = new short[1];
				if(tclCommondBuffer[3]==2) {//cheak sd card
					if(TV.readS(TVDefine.SDCard))status[0] = 0;
					else status[0] = 1;
					factoryCommondRespondsData(USB_QUERRY,status);	
				}
				else {
					if(TV.readS(TVDefine.USB))status[0] = 0;
					else status[0] = 1;
					factoryCommondRespondsData(USB_QUERRY,status);
				}
			}
				break;
			case 0x19://00--Reset all(NVM)  01--Shop init ..
				switch (tclCommondBuffer[3])
				{
				case 0x00: 
					TV.writeV(TVDefine.NVMReSet);
 					break;
				case 0x01: 
					TV.writeV(TVDefine.ShopInit);
 					break;
				}
				break;
			case 0x1a: 
				break;
			case 0x1b: 
					TV.writeD(TVDefine.FactoryTest, Utils.getData(tclCommondBuffer));
				break;
			case 0x1c : 
					factoryCommondRespondsData(FAC_TEST_DATA, TV.readD(TVDefine.FactoryTest));
				break;
			case 0x20: 
				TCL.AsyncsetATVChannel(tclCommondBuffer[4]);
				break;
			case 0x21: 
				int channelNum=tclCommondBuffer[4]*255+tclCommondBuffer[5];	

				switch(tclCommondBuffer[3])
				{
				case 0x00:
					TCL.AsyncsetDTVChannel(DEFS.TYPE_DTMB,channelNum);
					break;
				case 0x01:
					TCL.AsyncsetDTVChannel(DEFS.TYPE_DVBC,channelNum);
					break;
				}
				
				break;
			case 0x22:// AV or scart Source Selection
				if(tclCommondBuffer[3]==0)
					TV.setSource(DEFS.SOURCE_ATV,1);
				else if(tclCommondBuffer[3]>0)
				{  if(tclCommondBuffer[3]<=DEFS.AV_NUM)
					TV.setSource(DEFS.SOURCE_AV,tclCommondBuffer[3]);
				}
				break;
			case 0x23://COMP Source Selection Y PB PR

				if(tclCommondBuffer[3]==DEFS.YPBPR_NUM)
					TV.setSource(DEFS.SOURCE_YPBPR,tclCommondBuffer[3]);
				break;
			case 0x24://select source VGA
				if(tclCommondBuffer[3]==DEFS.VGA_NUM)
					TV.setSource(DEFS.SOURCE_VGA,tclCommondBuffer[3]);
				break;
			case 0x25://select source HDMI	
					if(tclCommondBuffer[3]<=DEFS.HDMI_NUM)
						if(tclCommondBuffer[3]>0)
							TV.setSource(DEFS.SOURCE_HDMI,tclCommondBuffer[3]);
				break;
			case 0x26://Media Source Selection
				if(tclCommondBuffer[3]>3)
				{
					Log.i(TAG, "[COM_OR_DATA_WRONG]tclCommondBuffer[3] = "+tclCommondBuffer[3]);
					TV.writeD(TVDefine.Serial, COM_OR_DATA_WRONG);
 					return;
				}
				Utils.intentHandler(DEFS.Package_TCL_FileExplorer, DEFS.Activity_TCL_FileExplorer); 			
					break;
				//	Commond_Execute.set_Fact_Pattern_Rgb_Gradiant_Value(tclCommondBuffer[3],tclCommondBuffer[4],tclCommondBuffer[5]);
			case 0x29:
			{
				if(tclCommondBuffer[3] == DEFS.COMMON_OFF)
				{
					TCL.setTestPatternStatus(false);
				}
				else
				{
					TCL.setTestPatternStatus(true);
				}
			}break;
			case 0x2a:
			{
				int index = 0;
				index = tclCommondBuffer[3];
		 
				if( (TCL.getTestPatternStatus() == true) && (index >= 0) && (index <= 8))
				{
					TCL.setTestPatternColor(index);
				}
				
			}break;
			case 0x30://Preset Picture  mode
				TV.writeV(TVDefine.PictureMode, tclCommondBuffer[3]);
 				break;
			case 0x31:  
				TV.writeV(TVDefine.ColorTemperature, tclCommondBuffer[3]);
 				break;
			case 0x32: 
				TV.writeV(TVDefine.Brightness, tclCommondBuffer[3]);
 				break;
			case 0x33: 
				TV.writeV(TVDefine.Contrast, tclCommondBuffer[3]);
				break;
			case 0x34: 
				TV.writeV(TVDefine.Color, tclCommondBuffer[3]);
 				break;
			case 0x35: 
				TV.writeV(TVDefine.Sharpness, tclCommondBuffer[3]);
 				break;
			case 0x36:
				TV.writeV(TVDefine.BackLight, tclCommondBuffer[3]);
 				break;
			case 0x37: 
//				TV.writeS(TVDefine.FleshTone, DEFS.Enable);
 				break;
			case 0x38: 
				if(tclCommondBuffer[3]==0)	
				{
					TV.writeV(TVDefine.PowerMode, DEFS.POWER_MODE_ON);
				}
				else if(tclCommondBuffer[3]==1)
				{
					TV.writeV(TVDefine.PowerMode, DEFS.POWER_MODE_STANDY);
				}
				else if(tclCommondBuffer[3]==2)
				{
					TV.writeV(TVDefine.PowerMode, DEFS.POWER_MODE_LAST);
				}
 				break;
 			case 0x39:
				if(tclCommondBuffer[3]==DEFS.COMMON_ON)	
				{
					TV.writeS(TVDefine.DBC, DEFS.Enable);
				}
				else
				{
					TV.writeS(TVDefine.DBC, DEFS.Disable);
				}
 				break;
			case 0x40: 
				if( TV.readV(TVDefine.ColorTemperature) == DEFS.TMP_STANDARD)
					TV.writeV(TVDefine.RGain, tclCommondBuffer[3]);
				else {
					byte gain = (byte)(tclCommondBuffer[3]);
					TV.writeV(TVDefine.RGain, gain);
				}
 				break;
			case 0x41://Green Gain 		
				if( TV.readV(TVDefine.ColorTemperature) == DEFS.TMP_STANDARD)
					TV.writeV(TVDefine.GGain, tclCommondBuffer[3]);
 				else{
 					byte gain = (byte)(tclCommondBuffer[3]);
 					TV.writeV(TVDefine.GGain, gain);
 				}
				break;
			case 0x42:
				if(TV.readV(TVDefine.ColorTemperature) == DEFS.TMP_STANDARD) 
					TV.writeV(TVDefine.BGain, tclCommondBuffer[3]);
				else {
					byte gain = (byte)(tclCommondBuffer[3]);
					TV.writeV(TVDefine.BGain, gain);
				}
				break;
			case 0x43: 			
				if(TV.readV(TVDefine.ColorTemperature) == DEFS.TMP_STANDARD) 
//					TV.writeV(TVDefine.RGainOffset, tclCommondBuffer[3]-128);
					TV.writeV(TVDefine.RGainOffset, 128);
				else
//					TV.writeV(TVDefine.RGainOffset, tclCommondBuffer[3]);
					TV.writeV(TVDefine.RGainOffset, 0);
				break;
			case 0x44://Green Offset
				if(TV.readV(TVDefine.ColorTemperature) == DEFS.TMP_STANDARD) 
//					TV.writeV(TVDefine.GGainOffset, tclCommondBuffer[3] - 128);
					TV.writeV(TVDefine.GGainOffset, 128);
				else
//					TV.writeV(TVDefine.GGainOffset, tclCommondBuffer[3]);
					TV.writeV(TVDefine.GGainOffset, 0);
				break;
			case 0x45://Blue Offset 
				if(TV.readV(TVDefine.ColorTemperature) == DEFS.TMP_STANDARD) 
//					TV.writeV(TVDefine.BGainOffset, tclCommondBuffer[3]-128);
					TV.writeV(TVDefine.GGainOffset, 128);
 				else
// 					TV.writeV(TVDefine.BGainOffset, tclCommondBuffer[3]);
 					TV.writeV(TVDefine.BGainOffset, 0);
				break;
			case 0x4a: {
				int sourcetype=tclCommondBuffer[3+0];
				int colorTmpType=tclCommondBuffer[3+1];
//				switch(sourcetype) {
//				case 1:TV.setSource(DEFS.SOURCE_AV, 1);break;
//				case 2:TV.setSource(DEFS.SOURCE_YPBPR, 1);break;
//				case 3:TV.setSource(DEFS.SOURCE_VGA, 1);break;
//				case 4:TV.setSource(DEFS.SOURCE_HDMI, 1);break;
//				default:
//					TV.setSource(DEFS.SOURCE_YPBPR, 1);
//				}
 
 				TV.writeV(TVDefine.ColorTemperature, colorTmpType);
				if(colorTmpType==DEFS.TMP_STANDARD) 
				{
					TV.writeV(TVDefine.RGain, tclCommondBuffer[3+2]);
					TV.writeV(TVDefine.GGain, tclCommondBuffer[3+3]);
					TV.writeV(TVDefine.BGain, tclCommondBuffer[3+4]);
					TV.writeV(TVDefine.RGainOffset, 128);
					TV.writeV(TVDefine.GGainOffset, 128);
					TV.writeV(TVDefine.BGainOffset, 128);
				}
				else
				{
					byte gain = 0;
					gain = (byte)tclCommondBuffer[3+2];
					TV.writeV(TVDefine.RGain, gain);
					gain = (byte)tclCommondBuffer[3+3];
					TV.writeV(TVDefine.GGain, gain);
					gain = (byte)tclCommondBuffer[3+4];
					TV.writeV(TVDefine.BGain, gain);
					TV.writeV(TVDefine.RGainOffset, 0);
					TV.writeV(TVDefine.GGainOffset, 0);
					TV.writeV(TVDefine.BGainOffset, 0);
				}
			}
 				break;
				/*
				 * 0x4b 0x4c 
				 * */
			case 0x4d: {
				int sourcetype=tclCommondBuffer[3+0];
				int colorTmpType=tclCommondBuffer[3+1];

//				switch(sourcetype) {
//				case 1:TV.setSource(DEFS.SOURCE_AV, 1);break;
//				case 2:TV.setSource(DEFS.SOURCE_YPBPR, 1);break;
//				case 3:TV.setSource(DEFS.SOURCE_VGA, 1);break;
//				case 4:TV.setSource(DEFS.SOURCE_HDMI, 1);break;
//				default:
//					TV.setSource(DEFS.SOURCE_YPBPR, 1);
//				}
 				TV.writeV(TVDefine.ColorTemperature, colorTmpType);
				if(TV.readV(TVDefine.ColorTemperature) == DEFS.TMP_STANDARD)
				{
					if(tclCommondBuffer[3+2]==0x01)
					{
						TV.writeV(TVDefine.RGain, tclCommondBuffer[3+3]);
						TV.writeV(TVDefine.GGain, tclCommondBuffer[3+4]);
						TV.writeV(TVDefine.BGain, tclCommondBuffer[3+5]);
					}
					else if(tclCommondBuffer[3+2]==0x02)
					{
						TV.writeV(TVDefine.RGainOffset, 128);
						TV.writeV(TVDefine.GGainOffset, 128);
						TV.writeV(TVDefine.BGainOffset, 128);
					}
				}
				else
				{//all hdmi  warm cold
					//Rreen Gain 
					if(tclCommondBuffer[3+2]==0x01)
					{
						byte gain = 0;
						gain = (byte)tclCommondBuffer[3+3];
						TV.writeV(TVDefine.RGain, gain);
						gain = (byte)tclCommondBuffer[3+4];
						TV.writeV(TVDefine.GGain, gain);
						gain = (byte)tclCommondBuffer[3+5];
						TV.writeV(TVDefine.BGain, gain);
					}
					else if(tclCommondBuffer[3+2]==0x02)
					{
						TV.writeV(TVDefine.RGainOffset, 0);
						TV.writeV(TVDefine.GGainOffset, 0);
						TV.writeV(TVDefine.BGainOffset, 0);
					}
				}
			}
				break;
			case 0x56:// Save the ADC data into NVM
				buffer=null;
				buffer=new short[7];
				for(int i=0;i<7;i++)
				{
					buffer[i]=tclCommondBuffer[3+i];
				}
			
				break;
			case 0x57:// Read related TV version software device 
		         if(tclCommondBuffer[3]==0x0)
		         {
		        	 factoryCommondRespondsData(SW_DATA,TV.readD(TVDefine.SoftwareVersion));
		         }else if(tclCommondBuffer[3]==0x03)
		         {
		        	 factoryCommondRespondsData(SW_DATA,TV.readD(TVDefine.BootloaderVersion));
		         }		        
				break;
			case 0x59:// Send Read NVM address
				int addr=((tclCommondBuffer[3]<<8)&0xff00)+tclCommondBuffer[4];
				buffer = new short[1];
				buffer[0]=(short) TV.readV(TVDefine.NVM, addr);
  					factoryCommondRespondsData(NVM_DATA_READ,buffer);	
				break;
			case 0x5b:// Send Read NVM address
				addr=((tclCommondBuffer[3]<<8)&0xff00)+tclCommondBuffer[4];
				TV.writeV(TVDefine.NVM, addr, tclCommondBuffer[5]);
 				break;
			case 0x5c:// key query  test 
				factoryCommondRespondsData(KEY_QUERY,TCL.getIrKeyCode());
				break;
			case 0x60: 
				TV.writeV(TVDefine.AudioVolume, tclCommondBuffer[3]);
 				break;
			case 0x61:// Balance
				TV.writeV(TVDefine.AudioBalance, tclCommondBuffer[3]);
 				break;
			case 0x62://Sound Preset
				TV.writeV(TVDefine.AudioMode, tclCommondBuffer[3]);
 				break;
			case 0x67://Mute Control
				if(tclCommondBuffer[3]==DEFS.COMMON_ON)	
				{
					TV.writeS(TVDefine.AudioMute, DEFS.Enable);
//					MainMenu.AudioMuteLabel.setVisibility(View.VISIBLE);
				}
				else
				{
					TV.writeS(TVDefine.AudioMute, DEFS.Disable);
//					MainMenu.AudioMuteLabel.setVisibility(View.INVISIBLE);
				}
				break;
			case 0x70://Set Panel ID
				if(tclCommondBuffer[3]>=0)
					TV.writeV(TVDefine.ProjectID, tclCommondBuffer[3]);
 				break;
			case 0x71://S/N write
				TV.writeD(TVDefine.SN, Utils.getData(tclCommondBuffer));
 				break;
			case 0x72://register code write	
				buffer=Utils.getData(tclCommondBuffer);
				TV.writeD(TVDefine.RegiterCode, buffer);
 				break;
			case 0x76://   keyboard query

				factoryCommondRespondsData(KEY_BOARD_QUERY,TCL.getFrontPanelKeyCode());

				break;
			case 0x7a://read warm up time
				if(tclCommondBuffer[3] == 0x00)
				{					
						factoryCommondRespondsData(RE_WARMUP_TIME, TV.readD(TVDefine.WarmUPTime));
				}
				break;
			case 0x7e:
			{
				if(tclCommondBuffer[3] == 0x00)
					TCL.AsyncEnableKaraoke(DEFS.COMMON_ON);
				else if(tclCommondBuffer[3] == 0x01)
					TCL.AsyncEnableKaraoke(DEFS.COMMON_OFF);
			}
			break;
			case 0x84://project id querry 
				buffer=new short[1];
				
					buffer[0]=(short) (TV.readV(TVDefine.ProjectID));
					factoryCommondRespondsData(PROJECT_ID_QUERY,buffer);
				break;
			case 0x86://write hdcp	
				//remove it 
				short[] hdcpkey=Utils.getData(tclCommondBuffer,6);
				TV.writeD(TVDefine.HdcpKey,hdcpkey);
				break;
			case 0x87:// hdcp	status querry
				short[] hdcpstatus = ThirdParty.pollingHdcpStatus();
				if(hdcpstatus[0]==DEFS.STATUS_OK) {
					hdcpstatus[0]= 0x01;					
				}else {
					hdcpstatus[0]= 0x00;
				}
				factoryCommondRespondsData(HDCP_KEY_QUDERY,hdcpstatus);
				break;
			case 0x8c:// platform	 querry
					factoryCommondRespondsData(IP_TV_PLATFORM_QUERY,TV.readD(TVDefine.PlatformType));
				break;
			case 0x93://set natural light param	
			{
				TV.writeV(TVDefine.NatureLightBP, tclCommondBuffer[3]);
				TV.writeV(TVDefine.NatureLightAPL2, tclCommondBuffer[4]);
				TV.writeV(TVDefine.NatureLightBKE, tclCommondBuffer[5]);
//				TV.writeV(TVDefine.NatureLightBD, tclCommondBuffer[5]);                                        //BD value
			}
			case 0x94://read natural light param
			{
	         if(tclCommondBuffer[3]==0)
	         {	         
	        	 factoryCommondRespondsData(NATURL_LIGHT_PARA, TV.readD(TVDefine.NatureLight)); 		
	         }
	      
			}
			break;
			case 0x97:
			{
				 /*
		         if(tclCommondBuffer[3]==2){
		        	 factoryCommondRespondsData(COMM_PARAM,convert(tclCommondBuffer[3],TCL.getWifiLeve()));
		         }
		         */
		         
		         /*date:2014.01.16 
		          * add by:yangms
		          * Blutooth*/
		         
				 switch(tclCommondBuffer[3])
				 {
				      case 2:
				    	    factoryCommondRespondsData(COMM_PARAM,convert(tclCommondBuffer[3],TCL.getWifiLeve()));
				    	    break;
				      case 16:
				    	    factoryCommondRespondsData(COMM_PARAM,convert(tclCommondBuffer[3],TCL.getBluetoothsync()));
				    	    break;
				      case 17:
				    	    factoryCommondRespondsData(COMM_PARAM,convert(tclCommondBuffer[3],TCL.getBluetoothvsync()));
				    	    break;
				 }
			}
			break;
			case 0xb0://PC Link check	 
 				factoryCommondRespondsData(PC_LINK_STATUS,Utils.boolean2Short(TV.readS(TVDefine.NetworkConnectivity)));	
				break;
			case 0xb2://Device ID write	 //store crc value
				short[] deviced=Utils.getData(tclCommondBuffer);
				TV.writeD(TVDefine.DeviceID, deviced);
 				break;
			case 0xb3://MAC Address write
				buffer=Utils.getData(tclCommondBuffer);

				short[] macBuffer=new short[6];
				for(int i=0;i<6;i++)
				{
					macBuffer[i]=buffer[i];
				}
				TV.writeD(TVDefine.MAC, macBuffer);
 				break;
			case 0xb4://MAC Address and Device ID status polling
					factoryCommondRespondsData(POLL_MAC_DEVICEID_STATUS, TV.readD(TVDefine.DeviceIDMACStatus));
				break;
			case 0xb6://Portal net check
				if(tclCommondBuffer[3] == 0x00)
				{
					
						factoryCommondRespondsData(RE_PORTAL_STATUS,Utils.boolean2Short(TV.readS(TVDefine.DeviceID)));
				}
				break;
				case 0xbd://set product SN	
					TV.writeD(TVDefine.SN, Utils.getData(tclCommondBuffer));
 					break;
			case 0xbe://query net para
				if(tclCommondBuffer[3] == 0x00){
					
						factoryCommondRespondsData(RETURN_NET_PARA,convert(tclCommondBuffer[3],TV.readD(TVDefine.MAC)));//return mac
				}
				else if(tclCommondBuffer[3] == 0x01)
				{
						factoryCommondRespondsData(RETURN_NET_PARA,convert(tclCommondBuffer[3],TV.readD(TVDefine.DeviceID)));//rerun device id 
				}
				else if(tclCommondBuffer[3] == 0x02){
					
						factoryCommondRespondsData(RETURN_NET_PARA,convert(tclCommondBuffer[3],TV.readD(TVDefine.RegiterCode)));//return register code
				}
				else if(tclCommondBuffer[3] == 0x03){
					
					factoryCommondRespondsData(RETURN_NET_PARA,convert(tclCommondBuffer[3],TV.readD(TVDefine.SN)));//return bar code
			    }
				else if(tclCommondBuffer[3] == 0x04)
				{
			    }
				break;
			case 0xc0://Backup NVM data to U dis 
				TV.writeV(TVDefine.NVM2USB,tclCommondBuffer[3]);
				break;
			case 0xc1://Restore U disk to NVM 
				TV.writeV(TVDefine.USB2NVM,tclCommondBuffer[3]);
				break;
			case 0xc2://usb querry  status
					factoryCommondRespondsData(USB_CLONE_STATUS, TV.readD(TVDefine.USBCloneStatus));
				break;
			case 0xc5://CI querry  status
					factoryCommondRespondsData(PCI_STATUS,Utils.boolean2Short(TV.readS(TVDefine.CICard)));
				break;
			case 0xc8://3 D model working  
				short[] status = {1};//default is ok
					factoryCommondRespondsData(CI_PLUS_STATUS,status);//ci plus querry
				break;
			case 0xd0://3 D model working  
					if(tclCommondBuffer[3]==DEFS.COMMON_OFF)
					{
						TVDefine.period=-1;						
						TV.writeS(TVDefine.ThreeDMode, DEFS.Disable);
						TVDefine.status_3d=false;
						
					}
 					else if (tclCommondBuffer[3]==DEFS.COMMON_ON)
 					{
 						if(!TVDefine.status_3d)
 						TVDefine.period=-1;
						TV.writeS(TVDefine.ThreeDMode, DEFS.Enable);
						TVDefine.status_3d=true;
						
 					}
				break;
			case 0xda://wifi on/off  
				if(tclCommondBuffer[3]==DEFS.COMMON_ON)
					TCL.setWiFiPower(DEFS.COMMON_ON);
				else if(tclCommondBuffer[3]==DEFS.COMMON_OFF)
					TCL.setWiFiPower(DEFS.COMMON_OFF);
				break;
			case 0xE2:
				factoryCommondRespondsData(SCREEN_PIXEL_DATA,ThirdParty.getPanelPixelShort(tclCommondBuffer[3], tclCommondBuffer[4], tclCommondBuffer[5]));
				break;
 			case 0xe5:
				short[] hdcp20status = ThirdParty.pollingHdcp20Status();
				if(hdcp20status[0]==DEFS.STATUS_OK) {
					hdcp20status[0]= 0x01;
				}else {
					hdcp20status[0]= 0x00;
				}
				factoryCommondRespondsData(HDCP_KEY_2_0_QUDERY,hdcp20status);
				break;

 			case 0xe7: {
 				short [] hdcpKey20Short = ThirdParty.getHdcpKey20Short();
 				int factory_hdcp_key_length = hdcpKey20Short.length;
 				short [] returnData= new short[factory_hdcp_key_length+7];
 				returnData[0]=SerialManager.FACTORY_DEBUG_RETURN_CODE;
 				returnData[1]=SerialManager.FACTORY_HDCP_HEAD_CODE;
 				returnData[2]=(short)(((factory_hdcp_key_length+7)>>8)&0xff);
 				returnData[3]=(short)((factory_hdcp_key_length+7)&0xff);
 				returnData[4]=0xe8;
 				for(int i=0;i<hdcpKey20Short.length;i++)
 					returnData[i+5]=hdcpKey20Short[i];
 				int crcData=(int)Utils.CRCCalculate(returnData,factory_hdcp_key_length+7-2);
 				returnData[factory_hdcp_key_length+7-2]=(short) ((crcData&0xff00)>>8);
 				returnData[factory_hdcp_key_length+7-1]= (short) (crcData&0x00ff);
 				TV.writeD(TVDefine.Serial, returnData);
 			}
 			
			}
		}
 
	}
	 
		
public static void factoryCommondRespondsData(short cmd,short[]bufferData){
	short [] returnData= new short[bufferData.length+5];
	returnData[0]=SerialManager.FACTORY_DEBUG_RETURN_CODE;
	returnData[1]=(short) returnData.length;
	returnData[2]=cmd;
	for(int i=0;i<bufferData.length;i++)
		returnData[i+3]=bufferData[i];
	int crcData=(int)Utils.CRCCalculate(returnData,returnData[1]-2);
	returnData[returnData[1]-2]=(short) ((crcData&0xff00)>>8);
	returnData[returnData[1]-1]= (short) (crcData&0x00ff);
	TV.writeD(TVDefine.Serial, returnData);
}

public static short[] convert(short data,short[] tmp) {
	short[] convertData=new short[tmp.length+1];
	convertData[0]=data;
	for(int i=0;i<tmp.length;i++)
	{convertData[i+1]=tmp[i];}
	return convertData;
}
public static short[] getHdcpKey(short[] data,int dataLength) {
	
	short[] buffer=null;
	//debug  if the data length buffer is null; danger!!!!
	if(dataLength==0){
		buffer=new short[1];
		buffer[0]=0;
		return	buffer;  //------------
	}
	buffer=new short[dataLength];
	for(int i=0;i<dataLength;i++)
	{
		buffer[i]= data[5+i];
	}	
	return buffer;  //-------------
}

//public  interface UiSerialListener{
////	void  onChange();
//
//	void onChange(int valueStatus);
//}
//public static UiSerialListener  mUiSLsner;
//
//public static void  addListener(UiSerialListener mLsner){
//	mUiSLsner=mLsner;
//}
//
//public interface GetInsListener
//{
//	void onChange();
//}
//
//public static GetInsListener mGetInsListener;


}
