//#include "stdafx.h"				// QT删掉stdafx头文件引用
#include "SecsEquip.h"

// 获取通讯状态文字
std::string GetCommunicationText(COMM_STATE e)	
{
	std::string text;
	switch (e)
	{
	case eCOMM_DISABLED:					text = "DISNABLE";					break;			
	case eCOMM_ENABLED_NOT_COMMUNICATING:	text = "ENABLE{NOT COMMUNICATION}"; break;		
	case eCOMM_COMMUNICATING:				text = "COMMUNICATION";				break;		
	default:								text = "ERROR";						break;	
	}
	return text;
}

// 获取控制状态文字
std::string GetControlText(CONTROL_STATE e)
{
	std::string text;
	switch (e)
	{
	case eCONTROL_OFFLINE_ATTEMPT_ONLINE:	text = "OFF-LINE Attempt Online"; break;
	case eCONTROL_OFFLINE_HOST:				text = "OFF-LINE Host"; break;
	case eCONTROL_OFFLINE_EQUIPMENT:		text = "OFF-LINE Equip"; break;
	case eCONTROL_ONLINE_LOCAL:				text = "ON-LINE Local"; break;
	case eCONTROL_ONLINE_REMOTE:			text = "ON-LINE Remote"; break;
	default:								text = "ERROR"; break;
	}
	return text;
}

// UNICODE字符串转换ANSI
std::string UnicodeToAscii(std::wstring pUnicode)
{	
	std::string pTextMulti;

	// 先取得转换后的ANSI字符串所需的长度
	int nLen = WideCharToMultiByte(CP_ACP, 0, pUnicode.c_str(), -1, NULL, 0, NULL, NULL); 

	// 缓冲区
	nLen += 20;
	char* pMultiByte = (char*)malloc(nLen * sizeof(char));                                             
	if(pMultiByte != NULL)
	{
		// 转换
		memset(pMultiByte, 0, nLen);		
		int nNewSize = WideCharToMultiByte(CP_ACP, 0, pUnicode.c_str(), -1, pMultiByte, nLen, NULL, NULL);   
		pTextMulti =  pMultiByte;                                            
		free(pMultiByte);  
	}
	return pTextMulti;
}

// ANSI字符串转换UNICODE
std::wstring AsciiToUnicode(std::string pAscii)
{	
	std::wstring pTextpWide;

	// 先取得转换后的ANSI字符串所需的长度
	int nLen = MultiByteToWideChar(CP_ACP, 0, pAscii.c_str(), -1, NULL, 0); 

	// 缓冲区
	nLen += 20;
	wchar_t* pWideChar = (wchar_t*)malloc(nLen * sizeof(wchar_t));                                             
	if(pWideChar != NULL)
	{
		// 转换
		memset(pWideChar, 0, nLen);		
		int nNewSize = MultiByteToWideChar(CP_ACP, 0, pAscii.c_str(), -1, pWideChar, nLen);   
		pTextpWide =  pWideChar;                                            
		free(pWideChar);  
	}
	return pTextpWide;
}

// 状态改变处理
static void OnStateChangeHandler (IMCHandle dmh, const char *DestinationMailbox, 
	const char* ReplyMailbox, const char* pData, void* pClientData) 
{ 
	if ( pClientData != NULL)
	{
		CSecsEquip *obj = (CSecsEquip *)pClientData;
		obj->OnStateChangeHandler(pData);
	}
}


// 终端 TERMINAL
static void OnTerminalHandler (IMCHandle dmh, const char *DestinationMailbox, 
	const char* ReplyMailbox, const char* pData, void* pClientData) 
{ 
	if ( pClientData != NULL)
	{
		CSecsEquip *obj = (CSecsEquip *)pClientData;
		obj->OnTerminalHandler(ReplyMailbox, pData);
	}
}



// 远程 
static void OnRemoteHandler (IMCHandle dmh, const char *DestinationMailbox, 
	const char* ReplyMailbox, const char* pData, void* pClientData) 
{ 
	if ( pClientData != NULL)
	{
		CSecsEquip *obj = (CSecsEquip *)pClientData;
		obj->OnRemoteHandler(ReplyMailbox, pData);
	}
}

// 常量 
static void OnConstantsChangeHandler (IMCHandle dmh, const char *DestinationMailbox, 
	const char* ReplyMailbox, const char* pData, void* pClientData) 
{ 
	if ( pClientData != NULL)
	{
		CSecsEquip *obj = (CSecsEquip *)pClientData;
		obj->OnConstantsChangeHandler(pData);
	}
}

// 处理程序 
static void OnPPChangeNotifyHandler (IMCHandle dmh, const char *DestinationMailbox, 
	const char* ReplyMailbox, const char* pData, void* pClientData) 
{ 
	if ( pClientData != NULL)
	{
		CSecsEquip *obj = (CSecsEquip *)pClientData;
		obj->OnPPChangeNotifyHandler(pData);
	}
}

// 时间处理 
static void OnClockHandler (IMCHandle dmh, const char *DestinationMailbox, 
	const char* ReplyMailbox, const char* pData, void* pClientData) 
{ 
	if ( pClientData != NULL)
	{
		CSecsEquip *obj = (CSecsEquip *)pClientData;
		obj->OnClockHandler(pData);
	}
}


// 变量
static void OnVarValueHandler (IMCHandle dmh, const char *DestinationMailbox, 
	const char* ReplyMailbox, const char* pData, void* pClientData) 
{ 
	if ( pClientData != NULL)
	{
		CSecsEquip *obj = (CSecsEquip *)pClientData;
		obj->OnVarValueHandler(ReplyMailbox, pData);
	}
}

// 常量
static void OnConstantValueHandler (IMCHandle dmh, const char *DestinationMailbox, 
	const char* ReplyMailbox, const char* pData, void* pClientData) 
{ 
	if ( pClientData != NULL)
	{
		CSecsEquip *obj = (CSecsEquip *)pClientData;
		obj->OnConstantValueHandler(ReplyMailbox, pData);
	}
}

// PP Format
static void OnPPFormatValueHandler (IMCHandle dmh, const char *DestinationMailbox, 
	const char* ReplyMailbox, const char* pData, void* pClientData) 
{ 
	if ( pClientData != NULL)
	{
		CSecsEquip *obj = (CSecsEquip *)pClientData;
		obj->OnPPFormatValueHandler(ReplyMailbox, pData);
	}
}

// PP Format 动态模式
static void OnPPFormatDynamicValueHandler (IMCHandle dmh, const char *DestinationMailbox, 
	const char* ReplyMailbox, const char* pData, void* pClientData) 
{ 
	if ( pClientData != NULL)
	{
		CSecsEquip *obj = (CSecsEquip *)pClientData;
		obj->OnPPFormatValueDynamicHandler(ReplyMailbox, pData);
	}
}

// PP Format发生改变
static void OnPPFormatChangeHandler (IMCHandle dmh, const char *DestinationMailbox, 
	const char* ReplyMailbox, const char* pData, void* pClientData) 
{ 
	if ( pClientData != NULL)
	{
		CSecsEquip *obj = (CSecsEquip *)pClientData;
		obj->OnPPFormatChangeHandler(ReplyMailbox, pData);
	}
}

// PP Format发生改变
static void OnPPFormatChangeDynamicHandler (IMCHandle dmh, const char *DestinationMailbox, 
	const char* ReplyMailbox, const char* pData, void* pClientData) 
{ 
	if ( pClientData != NULL)
	{
		CSecsEquip *obj = (CSecsEquip *)pClientData;
		obj->OnPPFormatChangeDynamicHandler(ReplyMailbox, pData);
	}
}

// PP Callback Handle
static void OnPPCallbackHandle (IMCHandle dmh, const char *DestinationMailbox, 
	const char* ReplyMailbox, const char* pData, void* pClientData) 
{ 
	if ( pClientData != NULL)
	{
		CSecsEquip *obj = (CSecsEquip *)pClientData;
		obj->OnPPFormatValueHandler(ReplyMailbox, pData);
	}
}

// PP自定义处理
static void OnPPChangeCostomizeHandler (IMCHandle dmh, const char *DestinationMailbox, 
	const char* ReplyMailbox, const char* pData, void* pClientData) 
{ 
	if ( pClientData != NULL)
	{
		CSecsEquip *obj = (CSecsEquip *)pClientData;
		obj->OnPPChangeCostomizeHandler(ReplyMailbox, pData);
	}
}

// 响应S9处理后通知
static void OnS9ErrorNotifyHandler (IMCHandle dmh, const char *DestinationMailbox, 
	const char* ReplyMailbox, const char* pData, void* pClientData) 
{ 
	if ( pClientData != NULL)
	{
		CSecsEquip *obj = (CSecsEquip *)pClientData;
		obj->OnS9ErrorNotifyHandler(ReplyMailbox, pData);
	}
}

// 响应Wafer信息处理
static void OnWaferMapSubstrateHandler (IMCHandle dmh, const char *DestinationMailbox, 
	const char* ReplyMailbox, const char* pData, void* pClientData) 
{ 
	if ( pClientData != NULL)
	{
		CSecsEquip *obj = (CSecsEquip *)pClientData;
		obj->OnWaferMapSubstrateHandler(ReplyMailbox, pData);
	}
}


CSecsEquip::CSecsEquip()
{
	m_nT1 = 500;
	m_nT2 = 10000;
	m_nT3 = 45000;
	m_nT4 = 45000;
	m_nT5 = 10000;
	m_nT6 = 5000;
	m_nT7 = 10000;


	m_bPassive = true;	
	m_nPort = 5555;	
	m_pIP = "127.0.0.1";

	m_pMDLN = "JNG_DMS";
	m_pSOFTREV = "4.2024.5.14";

	m_nControlState = ::eCONTROL_MODE_OFFLINE;

	m_bAutoResponseTimeSync = true;

	m_pClientData = NULL;
	m_pStateChangeCallback = NULL;
	m_pTerminalCallback = NULL;
	m_pRemoteCallback = NULL;
	m_pRemoteExCallback = NULL;
	m_pConstantsChangeCallback = NULL;
	m_pPPChangeNotifyProc = NULL;
	m_pClockProc = NULL;
	m_pVarValueProc = NULL;
	m_pConstantValueProc = NULL;
	m_pPPFormatValueProc = NULL;
	m_pPPFormatChangeProc = NULL;
	m_pPPNameListProc = NULL;
	m_pPPEventProc = NULL;
	m_pWaferMapSubstrateProc = NULL;
	m_pS9ErrorNotifyProc = NULL;
	m_pPPFormatValueDynamicProc = NULL;
	m_pPPFormatChangeDynamicProc = NULL;

}

/// 初始化SECS参数 
RcResult CSecsEquip::InitSecsParament()
{	       	
	int i = 0; 
	int n = 0;
	const char* argv[64] = {0};
	const char* argD[64] = {0};
	std::string pTimeout[8];
	std::string pPort;

	argv[i++] = "T1"; pTimeout[0] = IntToString(m_nT1); argD[n++] = pTimeout[0].c_str();
	argv[i++] = "T2"; pTimeout[1] = IntToString(m_nT2); argD[n++] = pTimeout[1].c_str();
	argv[i++] = "T3"; pTimeout[2] = IntToString(m_nT3); argD[n++] = pTimeout[2].c_str();
	argv[i++] = "T4"; pTimeout[3] = IntToString(m_nT4); argD[n++] = pTimeout[3].c_str();
	argv[i++] = "T5"; pTimeout[4] = IntToString(m_nT5); argD[n++] = pTimeout[4].c_str();
	argv[i++] = "T6"; pTimeout[5] = IntToString(m_nT6); argD[n++] = pTimeout[5].c_str();
	argv[i++] = "T7"; pTimeout[6] = IntToString(m_nT7); argD[n++] = pTimeout[6].c_str();
	argv[i++] = "MDLN"; argD[n++] = m_pMDLN.c_str();
	argv[i++] = "SOFTREV"; argD[n++] = m_pSOFTREV.c_str();


	// address
	argv[i++] = "IP"; argD[n++] = m_pIP.c_str();
	argv[i++] = "PASSIVE"; argD[n++] = m_bPassive?"1":"0";
	argv[i++] = "PORT"; pPort = IntToString(m_nPort); argD[n++] = pPort.c_str();

	// set to imc 
	return m_impl.SetParament(argv, argD, i);  
}



// 初始化回调
void CSecsEquip::InitCallback()
{
	m_impl.WheneverAdd("STATE", ::OnStateChangeHandler, this);
	m_impl.WheneverAdd("TERMINAL", ::OnTerminalHandler, this);
	m_impl.WheneverAdd("REMOTE", ::OnRemoteHandler, this);
	m_impl.WheneverAdd("CONSTANTS", ::OnConstantsChangeHandler, this);
	m_impl.WheneverAdd("PP_CHANGE", ::OnPPChangeNotifyHandler, this);
	m_impl.WheneverAdd("CLOCK", ::OnClockHandler, this);
	m_impl.WheneverAdd("VARIABLE", ::OnVarValueHandler, this);
	m_impl.WheneverAdd("CONSTANT", ::OnConstantValueHandler, this);
	m_impl.WheneverAdd("PP_FORMAT_VALUE", ::OnPPFormatValueHandler, this);
	m_impl.WheneverAdd("PP_FORMAT_DYNAMIC_VALUE", ::OnPPFormatDynamicValueHandler, this);	
	m_impl.WheneverAdd("PP_FORMAT_CHANGE", ::OnPPFormatChangeHandler, this);	
	m_impl.WheneverAdd("PP_FORMAT_DYNAMIC_CHANGE", ::OnPPFormatChangeDynamicHandler, this);		
	m_impl.WheneverAdd("PP_CUSTOMIZE_HANDLE", ::OnPPChangeCostomizeHandler, this);
	m_impl.WheneverAdd("S9_ERROR_NOTIFY", ::OnS9ErrorNotifyHandler, this);
	m_impl.WheneverAdd("WAFER_MAP_SUBSTRATE", ::OnWaferMapSubstrateHandler, this);

}




// 开始连接     
// 失败后或没连接，不能操作其他功能
RcResult CSecsEquip::Start(std::string pServerAddr, int nPort)
{	
	// 测试
//	pServerAddr = "127.0.0.1";
	
	// 连接
	RcResult rc = m_impl.Start(pServerAddr, nPort);	
	if(rc.rc == 0)
	{
		rc = InitSecsParament();		// 初始化自己的
		InitCallback();	// 初始化回调
	}
	return rc;
}

// 启用/禁用 SECS功能
void CSecsEquip::SecsEnable(bool bEnable)
{
	m_impl.SecsEnable(bEnable);
}

// 终止连接
void CSecsEquip::Abort()
{
	// 关闭SECS回调
	// 设为空，避免调用窗口消息函数导致死锁
	m_pTerminalCallback = NULL;
	m_pStateChangeCallback = NULL;
	m_pRemoteCallback = NULL;
	m_pRemoteExCallback = NULL;
	m_pConstantsChangeCallback = NULL;
	m_pClockProc = NULL;
	m_pVarValueProc = NULL;

	m_impl.Abort();
}

// 启用通信      
RcResult CSecsEquip::CommEnable()
{
	return m_impl.CommEnable();
}

// 关闭通信
RcResult CSecsEquip::CommDisable()
{
	return m_impl.CommDisable();
}

// 通讯是否开启
RcResult CSecsEquip::CommIsEnable(bool& bEnable)		
{
	return m_impl.CommIsEnable(bEnable);
}

// 获取通讯状态
/* 没有启用通讯 */	
/* 启用，没有通讯 */
/* 通讯着 */
RcResult CSecsEquip::GetCommState(COMM_STATE& nState)
{
	int tmp;
	RcResult rc = m_impl.GetCommState(tmp);	// 获取通信状态
	nState = (COMM_STATE)tmp;
	return rc;
}


// 设置控制状态,符合semi标准
RcResult CSecsEquip::SetControlMode(CONTROL_MODE nState)
{
	m_nControlState = nState;
	return m_impl.SetControlMode((int)m_nControlState);
}

// 强制设置控制状态，不经过Host允许
RcResult CSecsEquip::SetControlModeForce(CONTROL_MODE nState)
{
	m_nControlState = nState;
	return m_impl.SetControlModeForce((int)m_nControlState);
}

// 获取设置的状态
CONTROL_MODE CSecsEquip::GetControlMode()
{
	return m_nControlState;
}

// 获取控制状态
RcResult CSecsEquip::GetControlState(CONTROL_STATE& nState)	
{
	int nTmpState;
	RcResult rc = m_impl.GetControlState(nTmpState);
	nState = (CONTROL_STATE)nTmpState;
	return rc;
}

// 主动请求在线，在线状态通过SetControlState设置
RcResult CSecsEquip::ActiveRequestOnline()
{
	return m_impl.ActiveRequestOnline();
}

// 授权
// 获取许可授权级别
RcResult CSecsEquip::GetLicenseLevel(__int32& nLevel)			
{
	return m_impl.GetMaxRunDataPoint(nLevel);
}

// 获取允许运行个数
RcResult CSecsEquip::GetMaxRunCount(__int32& nCount)			
{
	return m_impl.GetMaxRunDataPoint(nCount);
}

// 获取允许运行数据点(变量、事件、警报分别计算)
RcResult CSecsEquip::GetMaxRunDataPoint(__int32& nCount)
{
	return m_impl.GetMaxRunDataPoint(nCount);
}




// 设置客户数据
void CSecsEquip::SetClientData(void* pClientData)
{
	m_pClientData = pClientData;
}


// 获取客户数据
void* CSecsEquip::GetClientData()
{
	return m_pClientData;
}

// 设置参数		
RcResult CSecsEquip::SetDeviceID(int nDeviceID)
{	
	if(nDeviceID < 0 ||
		nDeviceID > 32767)
	{
		return RcResult(1, "device ID超出范围");
	}

	m_nDeviceID = nDeviceID;
	std::string pDeviceID = IntToString(m_nDeviceID);
	return m_impl.SetParament("DEVICE_ID", pDeviceID);
}

RcResult CSecsEquip::GetDeviceID(int& nDeviceID)
{
	nDeviceID = m_nDeviceID;
	return RcResult(0);
}

// 设置连接IP, 被动不需要设置
RcResult CSecsEquip::SetIP(std::string ip)
{
	m_pIP = ip;
	return m_impl.SetParament("IP", m_pIP);
}				

std::string CSecsEquip::GetIP()
{
	return m_pIP;
}

// 通过加载Csv文件加载数据, 内置功能	
// 目录为空，则使用配置目录
// pDir为配置路径,空着为默认 ./Jng_Server/SecsCongfig/
RcResult CSecsEquip::LoadDataByCsvFile(std::string pDir)
{
	return m_impl.LoadDataByCsvFile(pDir);
}


// 加载SECS配置
RcResult CSecsEquip::LoadProtocolConfig(std::string pDir)
{
	return m_impl.LoadSecsConfig(pDir);
}


// 设置被动/主动模式
RcResult CSecsEquip::SetPassive(bool bPassive)
{
	m_bPassive = bPassive;
	std::string buff = m_bPassive?"1":"0";
	return m_impl.SetParament("PASSIVE", buff);
}	

bool CSecsEquip::GetPassive()
{
	return m_bPassive;
}

// 设置连接端口
RcResult CSecsEquip::SetPort(int port)
{	
	m_nPort = port;	 
	return m_impl.SetParament("PORT", IntToString(m_nPort));
}			

int CSecsEquip::GetPort()
{
	return m_nPort;
}


// 设置T1超时
RcResult CSecsEquip::SetT1(int nTimeout)
{
	return m_impl.SetTn("T1", nTimeout);        
}

// 设置T2超时
RcResult CSecsEquip::SetT2(int nTimeout)
{
	return m_impl.SetTn("T2", nTimeout);
}

// 设置T3超时
RcResult CSecsEquip::SetT3(int nTimeout)
{
	return m_impl.SetTn("T3", nTimeout);
}

// 设置T4超时
RcResult CSecsEquip::SetT4(int nTimeout)
{
	return m_impl.SetTn("T4", nTimeout);
}

// 设置T5超时
RcResult CSecsEquip::SetT5(int nTimeout)
{
	return m_impl.SetTn("T5", nTimeout);
}

// 设置T6超时
RcResult CSecsEquip::SetT6(int nTimeout)
{
	return m_impl.SetTn("T6", nTimeout);
}

// 设置T7超时
RcResult CSecsEquip::SetT7(int nTimeout)
{
	return m_impl.SetTn("T7", nTimeout);
}

// 设置T8超时
RcResult CSecsEquip::SetT8(int nTimeout)
{
	return m_impl.SetTn("T8", nTimeout);
}


// 设备型号
RcResult CSecsEquip::SetMDLN(std::string pMDLN)
{
	return m_impl.SetParament("MDLN", pMDLN);
}

// 软件版本
RcResult CSecsEquip::SetSOFTREV(std::string pSOFTREV)
{
	return m_impl.SetParament("SOFTREV", pSOFTREV);
}

// 启用Log记录
RcResult CSecsEquip::SetEnableLog(bool bEnable)
{
	return m_impl.SetParament("ENABLE_LOG", bEnable ? "1" : "0");
}

// 设置Log日志目录
RcResult CSecsEquip::SetLogDir(std::string pDir)
{
	return m_impl.SetParament("LOG_DIR", pDir);
}


 
// 设置自动删除Log日志目录，nDay小于等于0，代表不删除log
RcResult CSecsEquip::SetAutoDeleteLog(int nDay)
{
	return m_impl.SetParament("AUTO_DELETE_LOG_DAY", IntToString(nDay));
}


// 启用运行过程中的LogTrace,追查BUG等	
void CSecsEquip::EnableRuntimeTrace(bool bEnable)
{
	return m_impl.EnableRuntimeTrace(bEnable);
}

// 报警列表获取
RcResult CSecsEquip::AlarmListGet(std::vector<ALARM_DATA>& ved)		
{
	std::string pList;
	RcResult rc = m_impl.AlarmGetList(pList);

	if(rc.rc == 0)
	{
		std::vector<std::string> sv;
		rc = listSplit(pList, sv);
		if(rc == 0)
		{
			ALARM_DATA ad;
			std::vector<std::string> value;
			ved.reserve(sv.size());

			for (std::vector<std::string>::size_type i = 0; i < sv.size(); i++)
			{		
				rc = listSplit(sv[i], value);	
				if(rc != 0)
				{
					break;
				}

				if(value.size() != 5)
				{
					continue;
				}

				//提取
				ad.ALID = value[0];
				ad.ALTX = value[1];
				ad.bEnable = (value[2] == "1" ? true : false);
				ad.bSet = (value[3] == "1" ? true : false);
				ad.nCategory = ::atoi(value[4].c_str());
				ved.push_back(ad);
			}
		}
	}
	return rc;
}


// 增加报警
RcResult CSecsEquip::AlarmAdd(int nALID, std::string pALTX)		
{
	return m_impl.AlarmAdd(nALID, pALTX);	
}

// 添加报警
RcResult CSecsEquip::AlarmAdd(int nALID, std::string pALTX, int nAlarmSetCEID, int nAlarmClearCEID, int nCategory)
{
	return m_impl.AlarmAdd(nALID, pALTX, nAlarmSetCEID, nAlarmClearCEID, true, nCategory, true);	
}

// 添加报警
RcResult CSecsEquip::AlarmAdd(int nALID, std::string pALTX, int nAlarmSetCEID, int nAlarmClearCEID, 
	bool bEnable, int nCategory, bool bAddEvent)
{
	return m_impl.AlarmAdd(nALID, pALTX, nAlarmSetCEID, nAlarmClearCEID, bEnable, nCategory, bAddEvent);	
}

// 启用报警	
RcResult CSecsEquip::AlarmEnable(int nALID, bool bEnable)
{
	return m_impl.AlarmEnable(nALID, bEnable);	
}

// 设置报警
RcResult CSecsEquip::AlarmSet(int nALID, bool bSet)
{
	return m_impl.AlarmSet(nALID, bSet);
}

// 设置触发所有的报警
RcResult CSecsEquip::AlarmSetAll(bool bSet)
{
	return m_impl.AlarmSetAll(bSet);
}

// 报警发生后的通知模式，默认都通知
RcResult CSecsEquip::AlarmNotifyEventMode(ALARM_NOTIFY_EVENT_MODE nMode)	
{	
	return m_impl.AlarmNotifyEventMode(nMode);
}


// 事件列表获取
RcResult CSecsEquip::EventListGet(std::vector<EVENT_DATA>& ved)		
{
	std::string pList;
	RcResult rc = m_impl.EventGetList(pList);

	if(rc.rc == 0)
	{
		std::vector<std::string> sv;
		rc = listSplit(pList, sv);
		if(rc == 0)
		{
			EVENT_DATA ed;
			std::vector<std::string> value;
			ved.reserve(sv.size());

			for (std::vector<std::string>::size_type i = 0; i < sv.size(); i++)
			{
				// 每一行: CEID, NAME, DES
				rc = listSplit(sv[i], value);
				if(rc != 0)
				{
					break;
				}

				if(value.size() != 3)
				{
					continue;
				}

				//提取
				ed.nCEID = ::atoi(value[0].c_str());
				ed.pName = value[1];
				ed.pDescription = value[2];
				ved.push_back(ed);
			}
		}
	}
	return rc;
}




RcResult CSecsEquip::EventAdd(int nCEID, std::string pDescription, std::string pEventName, bool bEnable)
{		
	return m_impl.EventAdd(nCEID, pDescription, pEventName, bEnable);
}

// 事件启用/禁用
RcResult CSecsEquip::EventEnable(int nCEID, bool bEnable)
{
	return m_impl.EventEnable(nCEID, bEnable);
}

// 事件是否启用/禁用
RcResult CSecsEquip::EventIsEnable(int nECID, bool& bEnable)
{
	return m_impl.EventIsEnable(nECID, bEnable);
}

// 事件DVVAL绑定
RcResult CSecsEquip::EventDvvals(std::string pEventName, std::vector<std::string> &dvvalName)
{	
	std::string dvvalList = listJoin(dvvalName);
	return m_impl.EventDvvals(pEventName, dvvalList);
}

// 事件S6,F3发送: CEID
RcResult CSecsEquip::EventDiscreteVarPos(int nCEID)
{
	return m_impl.EventDiscreteVarPos(nCEID);
}

// 事件DVVAL绑定
RcResult CSecsEquip::EventDvvals(int nECID, std::vector<int> &dvval)
{
	std::vector<std::string> dvvalString;
	for (std::vector<int>::size_type i = 0; i < dvval.size(); i++)
	{
		dvvalString.push_back(IntToString(dvval[i]));
	}
	std::string dvvalList = listJoin(dvvalString);
	return m_impl.EventDvvals(nECID, dvvalList);
}

// 事件发送: CEID 
RcResult CSecsEquip::EventPos(int nECID, bool bWaitReply)
{
	return m_impl.EventPos(nECID, bWaitReply);
}

// 事件发送: 事件名称 
RcResult CSecsEquip::EventPos(std::string EventName, bool bWaitReply)
{
	return m_impl.EventPos(EventName, bWaitReply);
}



// 事件-报表关联
RcResult CSecsEquip::EventReportLink(int nECID, int report)
{
	std::vector<int> listReport;
	listReport.push_back(report);
	return EventReportLink(nECID, listReport);
}

// 事件-报表取消关联
RcResult CSecsEquip::EventReportLink(int nECID, std::vector<int>& report)
{
	std::vector<std::string> reportString;
	for (std::vector<int>::size_type i = 0; i < report.size(); i++)
	{
		reportString.push_back(IntToString(report[i]));
	}
	std::string reportList = listJoin(reportString);
	return m_impl.EventReportLink(nECID, reportList);
}

// 事件-报表取消关联
RcResult CSecsEquip::EventReportUnlink(int nECID)
{
	return m_impl.EventReportUnlink(nECID);
}

// 报表定义
RcResult CSecsEquip::ReportDefine(int nReport, std::vector<int>& listVarID)
{
	std::vector<std::string> varString;
	for (std::vector<int>::size_type i = 0; i < listVarID.size(); i++)
	{
		varString.push_back(IntToString(listVarID[i]));
	}
	std::string varList = listJoin(varString);
	return m_impl.ReportDefine(nReport, varList);
}

// 获取报表定义
RcResult CSecsEquip::ReportDefineGet(int nReport, std::vector<int>& listVarID)
{
	std::string varList;
	RcResult rc = m_impl.ReportDefineGet(nReport, varList);
	if(rc.rc == 0)
	{
		varList = listElement(varList, 0, 0);		
		int nID;
		std::vector<std::string> svID;
		if(listSplit(varList, svID) == 0)
		{
			for (std::vector<std::string>::size_type i = 0; i < svID.size(); i++)
			{
				nID = ::atoi(svID[i].c_str());
				listVarID.push_back(nID);
			}
		}
	}
	return rc;
}

// 删除报表
RcResult CSecsEquip::ReportDelete(int nReport)
{
	return m_impl.ReportDelete(nReport);
}

// 清除报表所有与之相关的事件
RcResult CSecsEquip::ReportUnlink(int nReport)
{
	return m_impl.ReportUnlink(nReport);
}

// 清除所有报告定义，并且清除所有事件与报告之间的并联
RcResult CSecsEquip::ReportClear()
{
	return m_impl.ReportClear();
}


// 报告严格按照标准规范处理：E5标准的处理及返回值
RcResult CSecsEquip::ReportStrictlyFollowStandard(bool bFollow)
{
	return m_impl.ReportStrictlyFollowStandard(bFollow);
}

// 报告保存服务器配置到本地
RcResult CSecsEquip::ReportAutoSaveHostLinkConfig(bool bEnable)
{
	return m_impl.ReportAutoSaveHostLinkConfig(bEnable);
}

// 变量增加  
RcResult CSecsEquip::VariableAdd(int varID, std::string varName, std::string description,
	std::string valueType, std::string initValue, std::string units, std::string varClass)
{
	return m_impl.VariableAdd(varID, varName, description, 
		valueType, initValue, units, varClass);
}

// 设置变量新值  
RcResult CSecsEquip::VariableSet(int varID, std::string newValue)
{
	return m_impl.VariableSet(varID, newValue);

}

// 获取变量的值  
RcResult CSecsEquip::VariableGet(int varID, std::string& pValue)
{
	std::string pTypeAndValue;
	RcResult rcr = m_impl.VariableGet(varID, pTypeAndValue);

	if(rcr.rc != 0) 
	{
		return rcr; // 错误，空值
	}
	std::vector<std::string> vargv;
	rcr = listSplit(pTypeAndValue, vargv);	
	if ( vargv.size() == 2 ) 
	{ 
		pValue = vargv[1]; 
	}
	return rcr;
}

// 变量列表获取
RcResult CSecsEquip::VariableListGet(std::vector<VARIABLE_DATA>& vvd)
{
	std::string pList;
	RcResult rc = m_impl.VariableGetList(pList);

	if(rc.rc == 0)
	{
		std::vector<std::string> sv;
		rc = listSplit(pList, sv);
		if(rc == 0)
		{
			VARIABLE_DATA vd;
			std::vector<std::string> value;
			vvd.reserve(sv.size());

			for (std::vector<std::string>::size_type i = 0; i < sv.size(); i++)
			{				
				rc = listSplit(sv[i], value);
				if(rc != 0)
				{
					break;
				}

				if(value.size() != 8)
				{
					continue;
				}

				//提取
				vd.VID = value[0];
				vd.VarName = value[1];
				vd.Description = value[2];
				vd.VarClass = value[3];
				vd.Type = value[4];
				vd.Value = value[5];
				vd.Units = value[6];
				vd.bInside = (::atoi(value[7].c_str()) != 0);
				vvd.push_back(vd);
			}
		}
	}
	return rc;
}

// 设置处理方法，统一方法
RcResult CSecsEquip::VariableSetMethod(int varID, bool bCallback)	
{
	return m_impl.VariableSetMethod(varID, bCallback);
}

// 设置处理方法
RcResult CSecsEquip::VariableSetMethod(int varID, SecsVarValueProc *pCallback)
{
	bool bEnable = false;

	std::map<int,SecsVarValueProc*>::iterator pos;  
	{
		vLocker lock(&m_lockVarMethod);  
		// allow update
		pos = m_mapVarValueCallback.find(varID);
		if(pos != m_mapVarValueCallback.end()) 
		{
			m_mapVarValueCallback.erase(pos);
		}
		if (pCallback != NULL)
		{
			bEnable = true;
			m_mapVarValueCallback.insert(std::make_pair(varID, pCallback));
		}
	}
	return m_impl.VariableSetMethod(varID, bEnable);
}


void CSecsEquip::VarValueRequest (const char *varList, std::vector<std::string> &values)
{
	int nID;	
	const char* pVID = "";
	const char* pTmpData = NULL; 
	SecsVarValueProc* pCallback;
	std::map<int,SecsVarValueProc*>::iterator ite;
	std::vector<std::string> listVarID;
	listSplit(varList, listVarID);

	if(listVarID.size() <= 1)
	{			
		// 第一位是控制符
		return;
	}

	vLocker lock(&m_lockVarMethod);
	try 
	{
		for(unsigned i=1; i < listVarID.size(); i++) 
		{
			pTmpData = NULL;
			pVID = listVarID[i].c_str();
			nID = ::atoi(pVID);			
			ite = m_mapVarValueCallback.find(nID);
			if(ite != m_mapVarValueCallback.end()) 
			{
				// 指定的回调
				pCallback = ite->second;
				if(pCallback != NULL)
				{
					pTmpData = pCallback(this, nID);					
				}
			} 
			else if(m_pVarValueProc != NULL)
			{
				// 通用回调
				pTmpData = m_pVarValueProc(this, nID);				
			}

			// 添加值
			if (pTmpData != NULL)
			{
				values.push_back(pTmpData);
			}
			else 
			{				
				values.push_back("");
			}
		}
	}
	catch (...) 
	{
		std::string msg("更新变量错误, varID=");
		if (pVID != NULL)
		{
			msg += pVID;
		}		
		::OutputDebugStringA(msg.c_str());		
	}
}


void CSecsEquip::ConstantValueRequest(std::string ConstantList, std::vector<std::string> &values)
{
	int nID;	
	const char* pECID = "";
	SecsConstantValueProc* pCallback;
	std::map<int,SecsConstantValueProc*>::iterator ite;
	std::vector<std::string> listConstantID;
	listSplit(ConstantList, listConstantID);

	if(listConstantID.size() <= 1)
	{			
		// 第一位是控制符
		return;
	}

	vLocker lock(&m_lockConstantMethod);
	try 
	{
		const char* pTmpData = NULL; 
		for(unsigned i=1; i < listConstantID.size(); i++) 
		{
			pTmpData = NULL;
			pECID = listConstantID[i].c_str();
			nID = ::atoi(pECID);			
			ite = m_mapConstantValueCallback.find(nID);
			if(ite != m_mapConstantValueCallback.end()) 
			{
				// 指定的回调
				pCallback = ite->second;
				if(pCallback != NULL)
				{
					pTmpData = pCallback(this, nID);					
				}
			} 
			else if(m_pConstantValueProc != NULL)
			{
				// 通用
				pTmpData = m_pConstantValueProc(this, nID);				
			}

			// 添加值
			if (pTmpData != NULL)
			{
				values.push_back(pTmpData);
			}
			else 
			{				
				values.push_back("");
			}
		}
	}
	catch (...) 
	{
		std::string msg("更新常量错误, varID=");
		if (pECID != NULL)
		{
			msg += pECID;
		}		
		::OutputDebugStringA(msg.c_str());		
	}
}


// 常量
// 添加常量  
RcResult CSecsEquip::ConstantsAdd(int varID, std::string name, std::string description, std::string Type, 
	std::string Units, std::string MinValue, std::string MaxValue, std::string DefValue)     
{
	return m_impl.ConstantsAdd(varID, name, description, Type, 
		Units, MinValue, MaxValue, DefValue);
}

// 常量获取
RcResult CSecsEquip::ConstantsGet(int nECID, std::string& pValue)
{	
	std::string pTypeAndValue;
	RcResult rcr = m_impl.ConstantsGet(nECID, pTypeAndValue);

	if(rcr.rc != 0) 
	{
		return rcr; // 错误，空值
	}
	std::vector<std::string> vargv;
	rcr = listSplit(pTypeAndValue, vargv);	
	if ( vargv.size() == 2 ) 
	{ 
		pValue = vargv[1]; 
	}
	return rcr;	
}

// 设置变量新值  
RcResult CSecsEquip::ConstantsSet(int varID, std::string newValue)	
{
	return m_impl.ConstantsSet(varID, newValue);
}

// 获取常量信息  
RcResult CSecsEquip::ConstantsInfoGet(std::vector<VARIABLE_DATA>& info)	
{
	std::string pList;
	RcResult rc = m_impl.ConstantsInfoGet(pList);

	if(rc.rc == 0)
	{
		std::vector<std::string> sv;
		rc = listSplit(pList, sv);
		if(rc == 0)
		{
			VARIABLE_DATA vd;
			std::vector<std::string> value;
			info.reserve(sv.size());

			for (std::vector<std::string>::size_type i = 0; i < sv.size(); i++)
			{			
				rc = listSplit(sv[i], value);
				if(rc != 0)
				{
					break;
				}

				if(value.size() != 9)
				{
					continue;
				}

				//提取
				vd.VID			  = value[0];
				vd.VarName		  = value[1];
				vd.Description	  = value[2];
				vd.Type			  = value[3];
				vd.Value		  = value[4];
				vd.Units		  = value[5];
				vd.MaxValue		  = value[6];
				vd.MinValue		  = value[7];
				vd.DefValue		  = value[8];

				info.push_back(vd);
			}
		}
	}
	return rc;

}

// 设置处理方法，统一方法
RcResult CSecsEquip::ConstantsSetMethod(int nECID, bool bCallback)	
{
	return m_impl.ConstantsSetMethod(nECID, bCallback);
}

// 设置处理方法
RcResult CSecsEquip::ConstantsSetMethod(int nECID, SecsConstantValueProc *pCallback)
{
	bool bEnable = false;

	std::map<int,SecsConstantValueProc*>::iterator pos;  
	{
		vLocker lock(&m_lockConstantMethod);  
		// allow update
		pos = m_mapConstantValueCallback.find(nECID);
		if(pos != m_mapConstantValueCallback.end()) 
		{
			m_mapConstantValueCallback.erase(pos);
		}
		if (pCallback != NULL)
		{
			bEnable = true;
			m_mapConstantValueCallback.insert(std::make_pair(nECID, pCallback));
		}
	}
	return m_impl.ConstantsSetMethod(nECID, bEnable);
}

// 启用/禁用常量改变发送事件         
RcResult CSecsEquip::ConstantChangeSendEventEnable(bool bEnable)
{
	return m_impl.ConstantChangeSendEventEnable(bEnable);
}


// 响应状态改变处理
void CSecsEquip::OnStateChangeHandler(const char *data)
{
	std::vector<std::string> sv;
	if(listSplit(data, sv) == 0 && sv.size() >= 1)
	{
		std::string pType = sv[0];
		if( pType == "comm_state" || 
			pType == "control_state")
		{
			if(sv.size() == 2)
			{
				// 状态
				int nState = ::atoi(sv[1].c_str());
				if(m_pStateChangeCallback != NULL)
				{
					m_pStateChangeCallback(this, pType.c_str(), nState);
				}
			}
		}				
	}
}


// 发送终端服务
RcResult CSecsEquip::SendSingleTerminal(std::string pContent)
{
	return m_impl.SendSingleTerminal(pContent);
}

RcResult CSecsEquip::SendMultipleTerminal(std::vector<std::string> svContent)
{
	return m_impl.SendMultipleTerminal(svContent);
}


// 响应终端服务处理
void CSecsEquip::OnTerminalHandler(std::string pReplyMailbox, std::string Data)		
{
	std::string pShow = "2";
	std::vector<std::string> sv;
	if(listSplit(Data, sv) == 0 && sv.size() >= 1)
	{		
		if(sv.size() == 3)
		{			
			std::string pTID = sv[1];
			std::string pText = sv[2];

			TERMINAL_DATA td;
			td.nTid = ::atoi(pTID.c_str());
			td.nSize = (int)pText.size() / 2;

			// 提取数据
			char* pTmp = (char*)malloc(td.nSize+5);
			memset(pTmp, 0, td.nSize+5);
			for (int i = 0; i < td.nSize; i++)
			{
				pTmp[i] = HexToDec(pText[i*2], pText[i*2+1]);
			}
			td.pText = pTmp;

			// 回调
			if(m_pTerminalCallback != NULL)
			{				
				int nAck = m_pTerminalCallback(this, td);	
				pShow = IntToString(nAck);			
			}

			free(pTmp);
		}				
	}
	m_impl.Reply(pReplyMailbox, pShow);  
}

// 响应远程命令处理
void CSecsEquip::OnRemoteHandler(std::string pReplyMailbox, const char *data)			
{
	REMOTE_REPLY nHCACK = ::eCOMMAND_NOT_EXIST;
	REMOTE_DATA rd;	

	std::vector<std::string> sv;
	if(listSplit(data, sv) == 0 && sv.size() >= 1)
	{		
		if(sv.size() == 3)
		{					
			rd.pRCMD = sv[1];

			// 参数
			std::vector<std::string> svParam;
			if(listSplit(sv[2], svParam) == 0)
			{
				for (std::vector<std::string>::size_type i = 1; i < svParam.size(); i += 2)
				{					
					std::string pName = svParam[i-1];
					std::string pValue = svParam[i];
					rd.mapParam.insert(std::make_pair(pName, pValue));
				}		

				// 回调
				if(m_pRemoteCallback != NULL)
				{
					nHCACK = m_pRemoteCallback(this, &rd);						
				}
				else if (m_pRemoteExCallback != NULL)
				{				
					// 远程控制，扩展型。由用户主动反馈结果
					m_pRemoteExCallback(this, pReplyMailbox, rd);
					return;
				}
			}		
		}				
	}
	else
	{
		rd.AddErrorCode(3, "listSplit(data, sv) and sv.size() error ");
	}

	RemoteCmdReply(pReplyMailbox, nHCACK, rd.listErrorCode);  
}

// 响应常量改变处理
void CSecsEquip::OnConstantsChangeHandler(const char *data)			
{
	std::vector<std::string> argv;
	RcResult rc = listSplit(data, argv);
	if( rc == 0 && argv.size() >= 3 && (argv.size()%2 == 1) )
	{
		int nID = 0;
		for (std::vector<std::string>::size_type i = 1; i < argv.size(); i += 2)
		{
			nID = ::atoi(argv[i].c_str());

			// 每个常量通知一次
			if (m_pConstantsChangeCallback != NULL) 
			{
				m_pConstantsChangeCallback(this, nID, argv[i+1].c_str());
			}
		}		
	}			
}


// 响应处理程序改变处理
void CSecsEquip::OnPPChangeNotifyHandler(const char *data)			
{	
	std::vector<std::string> argv;
	RcResult rc = listSplit(data, argv);
	if( rc == 0 && argv.size() == 2 ) 
	{
		std::string varname = argv[0];
		std::string varvalue = argv[1];
		
		bool bNotify = false;
		PP_CHANGE_NOTIFY nEvent;
		if (varname == "pp_download")
		{
			bNotify = true;
			nEvent = ePPDownChangeNotify;
		}
		else if (varname == "pp_delete")
		{
			bNotify = true;
			nEvent = ePPDeleteChangeNotify;
		}
		else if (varname == "pp_load")
		{
			bNotify = true;
			nEvent = ePPLoadChangeNotify;
		}
		if (m_pPPChangeNotifyProc != NULL &&
			bNotify) 
		{
			m_pPPChangeNotifyProc(this, nEvent, varvalue.c_str());
		}

	}
}


// 响应时间改变处理
void CSecsEquip::OnClockHandler(const char *data)			
{
	RcResult rc;
	std::vector<std::string> argv;
	rc = listSplit(data, argv);
	if( rc == 0 && argv.size() == 3 ) 
	{
		std::string pClockOffset = argv[1];
		std::string pTime = argv[2];	

		// host time
		SYSTEMTIME host_time;
		GetLocalTime(&host_time);
		if(pTime.size() == 16)
		{
			std::string pYear = pTime.substr(0, 4);
			std::string pMonth = pTime.substr(4, 2);			
			std::string pDay = pTime.substr(6, 2);
			std::string pHour = pTime.substr(8, 2);
			std::string pMinute = pTime.substr(10, 2);
			std::string pSecond = pTime.substr(12, 2);
			std::string pMilliseconds = pTime.substr(14, 2);

			host_time.wYear = ::atoi(pYear.c_str());
			host_time.wMonth = ::atoi(pMonth.c_str());		
			host_time.wDay = ::atoi(pDay.c_str());
			host_time.wHour = ::atoi(pHour.c_str());
			host_time.wMinute = ::atoi(pMinute.c_str());
			host_time.wSecond = ::atoi(pSecond.c_str());
			host_time.wMilliseconds = ::atoi(pMilliseconds.c_str()) * 10;	

		}

		if (m_pClockProc != NULL) 
		{
			m_pClockProc(this, pClockOffset.c_str(), host_time);
		}	
		else if(m_bAutoResponseTimeSync)
		{
			SetLocalTime(&host_time);
		}			
	}
}

// 响应变量值请求处理
void CSecsEquip::OnVarValueHandler(std::string pReplyMailbox, std::string Data)
{
	std::vector<std::string> listValue;
	VarValueRequest(Data.c_str(), listValue);
	std::string pValue = listJoin(listValue);
	m_impl.Reply(pReplyMailbox, pValue);  
}


// 响应常量值请求处理
void CSecsEquip::OnConstantValueHandler(std::string pReplyMailbox, std::string pData)
{
	std::vector<std::string> listValue;
	ConstantValueRequest(pData, listValue);
	std::string pValue = listJoin(listValue);
	m_impl.Reply(pReplyMailbox, pValue);  
}


// 响应主机获取Recipe变量值
void CSecsEquip::OnPPFormatValueHandler(std::string pReplyMailbox, std::string pData)
{
	std::vector<std::string> listValue;
	PPFormatValueRequest(pData, listValue);
	std::string pValue = listJoin(listValue);
	m_impl.Reply(pReplyMailbox, pValue);  
}

// 响应主机获取Recipe变量值
void CSecsEquip::OnPPFormatValueDynamicHandler(std::string pReplyMailbox, std::string pData)
{
	const char* pCmdCode = "";	
	std::vector<std::string> listPPID;
	listSplit(pData, listPPID);
	std::vector<std::string> listValue;

	if(listPPID.size() == 2)
	{	
		std::string ppid = listPPID[1];
		vLocker lock(&m_lockPPFormat);
		try 
		{
			// 获取值
			std::list<PP_FORMAT_DYNAMIC_HANDLE> listParam;
			SecsPPFormatValueDynamicProc* pPPFormatValueDynamicProc = m_pPPFormatValueDynamicProc;
			if(pPPFormatValueDynamicProc != NULL)
			{
				pPPFormatValueDynamicProc(this, ppid.c_str(), listParam);

				// 序列化
				std::list<PP_FORMAT_DYNAMIC_HANDLE>::iterator ite;
				std::vector<PP_FORMAT_PARAMENT>::iterator iteParam;

				for (ite = listParam.begin(); ite != listParam.end(); ite++)
				{
					std::list<std::string> listOneFormat;
					std::list<std::string> listParamnet;
					
					// 参数
					for (iteParam = ite->vecParam.begin(); iteParam != ite->vecParam.end(); iteParam++)
					{
						listParamnet.push_back(listJoin(iteParam->pType.c_str(), iteParam->pValue.c_str()));			
					}
					listOneFormat.push_back(ite->pCCode);
					listOneFormat.push_back(listJoin(listParamnet));

					listValue.push_back(listJoin(listOneFormat));
				}			
			}
		}
		catch (...) 
		{
			std::string msg("更新PP错误, cmd_code");
			::OutputDebugStringA(msg.c_str());		
		}
	}

	std::string pValue = listJoin(listValue);
	m_impl.Reply(pReplyMailbox, pValue);  
}


void CSecsEquip::PPFormatValueRequest(std::string varList, std::vector<std::string> &values)
{	
	const char* pCmdCode = "";	
	std::vector<std::string> listPPID;
	listSplit(varList, listPPID);

	if(listPPID.size() < 2)
	{			
		// 第一位是控制符
		return;
	}

	std::string ppid = listPPID[1];
	vLocker lock(&m_lockPPFormat);
	try 
	{
		SecsPPFormatValueProc* pPPFormatValueProc = m_pPPFormatValueProc;
		if(pPPFormatValueProc != NULL)
		{
			// 加载recipe
			PP_FORMAT_HANDLE pPpFormat;
			pPpFormat.nEvent = ::eLOAD_TMP_PPID;
			pPpFormat.pPPID = ppid;
			pPPFormatValueProc(this, &pPpFormat);
			if (pPpFormat.nAck != ePPSuccess)
			{
				// 出错情况
				return;
			}

			// get value
			for(unsigned i=2; i < listPPID.size(); i++) 
			{	
				// 通用
				pPpFormat.pPPID = ppid;
				pPpFormat.nEvent = ::eGET_PPID_VALUE;
				pPpFormat.pCCode = listPPID[i];	
				pPpFormat.vecParamValue.clear();
				pPPFormatValueProc(this, &pPpFormat);
				
				std::string pTmp = listJoin(pPpFormat.vecParamValue);
				values.push_back(pTmp);
			}

			// 结束通知
			pPpFormat.nEvent = ::eGET_PPID_VALUE_FINSH;
			pPPFormatValueProc(this, &pPpFormat);
		}
	}
	catch (...) 
	{
		std::string msg("更新PP错误, cmd_code");
		::OutputDebugStringA(msg.c_str());		
	}
}




// 响应主机修改Recipe变量值
void CSecsEquip::OnPPFormatChangeHandler(std::string pReplyMailbox, std::string pData)
{
	std::vector<std::string> listValue;
	int nAck = PPFormatValueChange(pData.c_str(), listValue);
	std::string pValue = listJoin(IntToString(nAck).c_str());
	m_impl.Reply(pReplyMailbox, pValue);  
}

// 数据发生改变
PP_HANDLE_REPLY CSecsEquip::PPFormatValueChange(const char *varList, std::vector<std::string> values)
{	
	const char* pCmdCode = "";	
	std::vector<std::string> listPPID;
	listSplit(varList, listPPID);

	if(listPPID.size() < 2)
	{			
		// 第一位是控制符
		return ::ePPOtherError;
	}
	
	// 参数
	std::string ppid = listPPID[1];
	PP_FORMAT_HANDLE pPpFormat;
	pPpFormat.nAck = ::ePPSuccess;

	vLocker lock(&m_lockPPFormat);
	try 
	{
		if(m_pPPFormatChangeProc != NULL)
		{
			// 加载recipe			
			pPpFormat.nEvent = ::eSET_PPID_VALUE_BEGIN;
			pPpFormat.pPPID = ppid;
			m_pPPFormatChangeProc(this, &pPpFormat);
			if (pPpFormat.nAck != ePPSuccess)
			{
				// 出错情况
				return pPpFormat.nAck;
			}

			// 设置PP的值
			for(unsigned i=2; i < listPPID.size(); i++) 
			{								
				std::vector<std::string> vecOneData;
				if(listSplit(listPPID[i], vecOneData) == 0 &&
					vecOneData.size() == 2)
				{					
					pPpFormat.nEvent = eSET_PPID_VALUE;
					pPpFormat.pCCode = vecOneData[0];
					listSplit(vecOneData[1], pPpFormat.vecParamValue);
					m_pPPFormatChangeProc(this, &pPpFormat);
					if (pPpFormat.nAck != ePPSuccess)
					{
						// 出错情况
						return pPpFormat.nAck;
					}
				}
				else
				{
					pPpFormat.nAck = ::ePPOtherError;
					break;
				}
			}	

			// 更新recipe完成			
			pPpFormat.nEvent = ::eSET_PPID_VALUE_FINSH;
			pPpFormat.pPPID = ppid;
			m_pPPFormatChangeProc(this, &pPpFormat);
			if (pPpFormat.nAck != ePPSuccess)
			{
				// 出错情况
				return pPpFormat.nAck;
			}
		}
	}
	catch (...) 
	{	
	}
	return pPpFormat.nAck;
}

 // 响应主机修改Recipe变量值
void CSecsEquip::OnPPFormatChangeDynamicHandler(std::string pReplyMailbox, std::string pData)
{	
	const char* pCmdCode = "";	
	std::vector<std::string> listPPID;
	listSplit(pData, listPPID);
	int nAck = ePPOtherError;

	if(listPPID.size() < 3)
	{			
		// 第一位是控制符
		return ;
	}

	// 参数
	std::string ppid = listPPID[1];
	PP_FORMAT_DYNAMIC_HANDLE pPpFormat;
	 
	vLocker lock(&m_lockPPFormat);
	try 
	{
		if(m_pPPFormatChangeDynamicProc != NULL)
		{
			std::list<PP_FORMAT_DYNAMIC_HANDLE> listParam;

			// 解析数据
			std::list<std::string> listParamentAll;
			std::list<std::string>::iterator ite;
			std::list<std::string>::iterator iteParament;
			listSplit(listPPID[2], listParamentAll);
			for (ite = listParamentAll.begin(); ite != listParamentAll.end(); ite ++)
			{
				// 单个CCODE数据
				std::vector<std::string> listCCodeOne;
				listSplit(*ite, listCCodeOne);
				if (listCCodeOne.size() == 2)
				{
					PP_FORMAT_DYNAMIC_HANDLE pOneData;
					pOneData.pCCode = listCCodeOne[0];
									
					// 单个Parament数据
					std::list<std::string> listParament;
					listSplit(listCCodeOne[1], listParament);
					for (iteParament = listParament.begin(); iteParament != listParament.end(); iteParament++)
					{
						PP_FORMAT_PARAMENT pOneParament;
						pOneParament.pType = listElement(*iteParament, 0);
						pOneParament.pValue = listElement(*iteParament, 1);
						pOneData.vecParam.push_back(pOneParament);
					}					
					listParam.push_back(pOneData);	
				}				
			}

			nAck = m_pPPFormatChangeDynamicProc(this, ppid.c_str(), listParam);
		}
	}
	catch (...) 
	{	
	}	

	std::string pValue = listJoin(IntToString(nAck).c_str());
	m_impl.Reply(pReplyMailbox, pValue);  
}


// 响应PP自定义改变处理
void CSecsEquip::OnPPChangeCostomizeHandler(std::string pReplyMailbox, std::string Data)
{
	std::string pValue;
	std::vector<std::string> argv;
	RcResult rc = listSplit(Data, argv);
	if( rc == 0 && 
		argv.size() > 0)
	{		
		// get list
		if(argv[0] == "pp_recipe_list_request")
		{
			vLocker lock(&m_lockPPChange);
			try
			{
				if (m_pPPNameListProc != NULL)
				{
					std::list<std::string> pList = m_pPPNameListProc(this);
					pValue = listJoin(pList);
				}
			}
			catch (...)
			{			
			}
		}

		// get ppid
		else if(argv[0] == "pp_process_program_data_request")
		{
			vLocker lock(&m_lockPPChange);
			if(argv.size() == 2)
			{
				std::string ppid = argv[1];
				if (m_pPPEventProc != NULL)
				{
					try
					{
						// data
						PP_HANDLE_DATA pHandleData;
						pHandleData.nEvent = ::ePPEventLoadData;
						pHandleData.pPPID = ppid.c_str();						
						pHandleData.pPPData = NULL;
						pHandleData.nLength = 0;

						m_pPPEventProc(this, &pHandleData);
						if(pHandleData.pPPData != NULL)
						{
							char cHightHex;
							char cLowHex;
							pValue.reserve(pHandleData.nLength * 2);

							for (int i = 0; i < pHandleData.nLength; i++)
							{
								DecToHex(pHandleData.pPPData[i], cHightHex, cLowHex);
								pValue += cHightHex;
								pValue += cLowHex;
							}

							// PP数据存在
							pValue = listJoin("1", pValue.c_str());
						}
						else
						{
							// PP数据不存在
							pValue = listJoin("0", "");
						}
					}
					catch (...)
					{	
					}
				}				
			}			
		}	

		// update ppid
		else if(argv[0] == "pp_process_program_data_update")
		{
			vLocker lock(&m_lockPPChange);
			pValue = "65";

			if(argv.size() == 3)
			{
				std::string ppid = argv[1];
				std::string pHex = argv[2];

				if (m_pPPEventProc != NULL)
				{
					int nSize = (int)(pHex.size() / 2);
					char* pPPData = (char*)malloc(nSize+5);					
					if (pPPData != NULL)
					{
						memset(pPPData, 0, nSize+5);
						for (int i = 0; i < nSize; i++)
						{
							pPPData[i] = HexToDec(pHex[i*2], pHex[i*2+1]);	
						}

						// data
						PP_HANDLE_DATA pHandleData;
						pHandleData.nEvent = ::ePPEventDownData;
						pHandleData.pPPID = ppid.c_str();						
						pHandleData.pPPData = pPPData;
						pHandleData.nLength = nSize;

						// callback
						try
						{													
							m_pPPEventProc(this, &pHandleData);
							pValue = IntToString(pHandleData.nAck & 0xFF);	
						}
						catch (...)
						{	
						}
						free(pPPData);
					}					
				}				
			}			
		}

		// delete ppid
		if(argv[0] == "pp_process_program_delete")
		{									
			pValue = "65";
			if(argv.size() == 3)
			{
				std::list<std::string> listPPID;
				std::list<std::string>::iterator ite;
				PP_HANDLE_DATA pHandleData;
				bool bDeleteAll = (argv[1] == "1");
				listSplit(argv[2], listPPID);

				vLocker lock(&m_lockPPChange);
				try
				{					
					if (m_pPPEventProc != NULL)
					{						
						if (bDeleteAll)
						{
							pHandleData.nEvent = ::ePPEventDeleteAll;
							m_pPPEventProc(this, &pHandleData);
						}
						else
						{												
							for (ite = listPPID.begin(); ite != listPPID.end(); ite++)
							{
								pHandleData.nEvent = ::ePPEventDelete;
								pHandleData.pPPID = ite->c_str();
								m_pPPEventProc(this, &pHandleData);
								if (pHandleData.nAck != ::ePPSuccess)
								{
									break;
								}							
							}
						}
						pValue = IntToString(pHandleData.nAck & 0xFF);	
					}
				}
				catch (...)
				{			
				}
			}
		}

		// load ppid
		if(argv[0] == "pp_load_inquire")
		{									
			pValue = "5";
			if(argv.size() == 3)
			{
				PP_HANDLE_DATA pHandleData;
				pHandleData.pPPID = argv[1].c_str();
				pHandleData.nLength = ::atoi(argv[2].c_str());
				pHandleData.nEvent = ::ePPEventLoadInquire;

				vLocker lock(&m_lockPPChange);
				try
				{					
					if (m_pPPEventProc != NULL)
					{		
						
						m_pPPEventProc(this, &pHandleData);
						pValue = IntToString(pHandleData.nAck & 0xFF);	
					}
				}
				catch (...)
				{			
				}
			}
		}
	}
	
	m_impl.Reply(pReplyMailbox, pValue); 
}


// 获取程式目录
std::string CSecsEquip::GetRecipeDirectory()
{
	return m_pRecipeDir;           
}

// 设置程式目录
void CSecsEquip::SetRecipeDirectory(std::string dir)
{
	m_pRecipeDir = dir;
	m_impl.SetRecipeDirectory(m_pRecipeDir);		
}

// 设置程式目录
// ppid: recipe名
RcResult CSecsEquip::ProcessProgramUpload(std::string ppid)
{
	if (ppid == "")
	{
		return RcResult("ppid 为空");
	}
	return m_impl.ProcessProgramUpload(ppid);
}

// 设置程式目录
// ppid: recipe名
RcResult CSecsEquip::ProcessProgramDownload(std::string ppid)
{
	if (ppid == "")
	{
		return RcResult("ppid 为空");
	}
	return m_impl.ProcessProgramDownload(ppid);
}

// 允许主机下载
RcResult CSecsEquip::PPAllowHostDowmload(bool bAllow)
{
	return m_impl.PPAllowHostDowmload(bAllow);
}

// PP处理模式
RcResult CSecsEquip::PPHandleMode(PP_HANDLE_MODE nMode)
{
	return m_impl.PPHandleMode(nMode);
}

// 设置PP是文件夹目录
RcResult CSecsEquip::PPIsFolderDir(bool bAllow)
{
	return m_impl.PPIsFolderDir(bAllow);
}

// 设置winrar目录
RcResult CSecsEquip::SetWinrarPath(std::string dir)
{
	return m_impl.SetWinrarPath(dir);
}

// 设置扩展名
RcResult CSecsEquip::PPSetFilenameExtension(std::string pFileExten)
{
	return m_impl.PPSetFilenameExtension(pFileExten);
}

// PP序列化参数对象添加 
RcResult CSecsEquip::PPFormatAdd(std::string pCmdCode, std::string pName, std::string pValueType)
{
	return m_impl.PPFormatAdd(pCmdCode, pName, pValueType);
}

// PP序列化上传
RcResult CSecsEquip::PPFormatSend(std::string ppid)
{
	return m_impl.PPFormatSend(ppid);
}

// PP序列化下载
RcResult CSecsEquip::PPFormatRequest(std::string ppid)
{
	return m_impl.PPFormatRequest(ppid);
}

// PP序列化设置模式
RcResult CSecsEquip::PPFormatSetCodeMode(PP_FORMAT_MODE nMode)
{
	return m_impl.PPFormatSetCodeMode(nMode);
}

// 自动响应时间同步
void CSecsEquip::AutoResponseTimeSync(bool bAuto)
{
	m_bAutoResponseTimeSync = bAuto;
}

// 主动请求主机时间进行同步
RcResult CSecsEquip::ActiveTimeSynchronizeRequest()
{
	return m_impl.ActiveTimeSynchronizeRequest();
}

// 当设置远程控制响应扩展型时候，需要用户主动答复结果
void CSecsEquip::RemoteCmdReply(std::string pReplyMailbox, REMOTE_REPLY nHCACK, std::list<ERROR_CODE_DESCRIPTION> listErrorCode)
{
	std::vector<std::string> param;
	std::list<ERROR_CODE_DESCRIPTION>::iterator ite;

	param.push_back(IntToString(nHCACK));
	for (ite = listErrorCode.begin(); ite != listErrorCode.end(); ite++)
	{
		param.push_back(ite->pDescription);
		param.push_back(IntToString(ite->nCode));		
	}
	std::string pReplyParam = listJoin(param);
	m_impl.Reply(pReplyMailbox, pReplyParam);
}


// 扩展操作
RcResult CSecsEquip::SendSecsMsgAsync(int nStream, int nFunction, 
	bool bReply, std::string pData, int64& nMsgID)
{
	return m_impl.SendSecsMsgAsync(nStream, nFunction, bReply, pData, nMsgID);
}

RcResult CSecsEquip::SendSecsMsgSync(int nStream, int nFunction, bool bReply,
	std::string pData, std::string& pReplyData)
{
	return m_impl.SendSecsMsgSync(nStream, nFunction, bReply, pData, pReplyData);
}

RcResult CSecsEquip::SendReply(int nStream, int nFunction, int nTransactionID, std::string pData)
{
	return m_impl.SendReply(nStream, nFunction, nTransactionID, pData);
}

RcResult CSecsEquip::MessageTypeAdd(int nStream, int nFunction,
	SecsMessageReceiveProc pCallback, void* pClientData)
{
	return m_impl.MessageTypeAdd(nStream, nFunction, pCallback, pClientData);
}



RcResult CSecsEquip::MessageTypeRemove(int nStream, int nFunction)
{
	return m_impl.MessageTypeRemove(nStream, nFunction);
}


// wafer map
// 晶圆图上传
RcResult CSecsEquip::WaferMapUpload(WAFER_MAP pWaferMap)
{		
	// map data
	std::list<std::string> listMapData;
	for (std::vector<WAFER_MAP_REFERENCE_POINT>::size_type i = 0; i < pWaferMap.listReferPoint.size(); i++)
	{
		std::list<std::string> listArrar;		
		listArrar.push_back(IntToString(pWaferMap.listReferPoint[i].nX));	
		listArrar.push_back(IntToString(pWaferMap.listReferPoint[i].nY));		
		listMapData.push_back(listJoin(listArrar));
	}
	std::string pMapData = listJoin(listMapData);
	
	// 全部数据
	std::list<std::string> listWaferMap;
	listWaferMap.push_back(pWaferMap.pMID);
	listWaferMap.push_back(IntToString(pWaferMap.nIDTYP));
	listWaferMap.push_back(IntToString(pWaferMap.nFNLOC));
	listWaferMap.push_back(IntToString(pWaferMap.nFFROT));
	listWaferMap.push_back(IntToString(pWaferMap.nCOLCT));
	listWaferMap.push_back(IntToString(pWaferMap.nRPSEL));
	listWaferMap.push_back(pMapData);
	listWaferMap.push_back(pWaferMap.pDUTMS);
	listWaferMap.push_back(ToString(pWaferMap.dbXDies));
	listWaferMap.push_back(ToString(pWaferMap.dbYDies));
	listWaferMap.push_back(ToString(pWaferMap.nROWCT));
	listWaferMap.push_back(ToString(pWaferMap.nCOLCT));
	listWaferMap.push_back(pWaferMap.pMapBin);
	listWaferMap.push_back(ToString(pWaferMap.nPRDCT));
	listWaferMap.push_back(ToString(pWaferMap.nPRAXI));

	std::string pTmpData = listJoin(listWaferMap);
	return m_impl.WaferMapUpload(pTmpData);
}

// 晶圆图下传请求
RcResult CSecsEquip::WaferMapDownload(WAFER_MAP& pRequstInfo, WAFER_MAP& pWaferMap)
{
	// map data
	std::list<std::string> listMapData;
	for (std::vector<WAFER_MAP_REFERENCE_POINT>::size_type i = 0; i < pRequstInfo.listReferPoint.size(); i++)
	{
		std::list<std::string> listArrar;		
		listArrar.push_back(IntToString(pRequstInfo.listReferPoint[i].nX));		
		listArrar.push_back(IntToString(pRequstInfo.listReferPoint[i].nY));
		listMapData.push_back(listJoin(listArrar));
	}
	std::string pMapData = listJoin(listMapData);

	// 全部数据
	std::list<std::string> listWaferMap;
	listWaferMap.push_back(pRequstInfo.pMID);
	listWaferMap.push_back(IntToString(pRequstInfo.nIDTYP));
	listWaferMap.push_back(IntToString(pRequstInfo.nFNLOC));
	listWaferMap.push_back(IntToString(pRequstInfo.nFFROT));
	listWaferMap.push_back(IntToString(pRequstInfo.nORLOC));
	listWaferMap.push_back(ToString(pRequstInfo.nPRAXI));
	listWaferMap.push_back(pRequstInfo.pNULBC);
	listWaferMap.push_back(pRequstInfo.pMapBin);

	std::string pTmpData = listJoin(listWaferMap);
	std::string pReplyWaferMap;
	RcResult rc = m_impl.WaferMapDownload(pTmpData, pReplyWaferMap);
	if (rc.rc == 0)
	{
		GetWaferMap(pReplyWaferMap, pWaferMap);
	}
	
	return rc;
}

// 条带图下传请求
RcResult CSecsEquip::StripMapDownload(std::string pStripID, STRIP_MAP& pStripMap)
{
	// map data

	std::string pTmpData = listJoin(pStripID.c_str());
	std::string pReplyWaferMap;
	RcResult rc = m_impl.StripMapDownload(pTmpData, pReplyWaferMap);
	if (rc.rc == 0)
	{
		pStripMap.pMapDataByXml = listElement(pReplyWaferMap, 0);		
	}

	return rc;
}


long CSecsEquip::GetWaferMap(std::string pData, WAFER_MAP& pWaferMap)
{
	std::vector<std::string> listMapData;
	RcResult rc = listSplit(pData, listMapData);
	if (rc.rc != 0)
	{
		return rc.rc;
	}

	// 个数跟请求不一致
	if (listMapData.size() != 18)
	{		
		return 1000;
	}

	// 提取数据
	pWaferMap.pMID = listMapData[0];
	pWaferMap.nIDTYP = (MATERIAL_ID_TYPE::ENUM )::atoi(listMapData[1].c_str());
	pWaferMap.nFNLOC = (WAFER_FLAT_NOTCH_ANGLE::ENUM )::atoi(listMapData[2].c_str());
	pWaferMap.nFFROT = (WAFER_FILM_FRAME_ANGLE::ENUM )::atoi(listMapData[3].c_str());
	pWaferMap.nORLOC = (ORIGIN_LOCATION::ENUM )::atoi(listMapData[4].c_str());
	pWaferMap.nRPSEL = ::atoi(listMapData[5].c_str());

	//	// map data
	//	list<string> listMapData2D;
	//	list<string>::iterator ite;
	//	list<string>::iterator iteArrar;
	//	listSplit(pMapData, listMapData2D);	
	//	for (ite = listMapData2D.begin(); ite != listMapData2D.end(); ite++)
	//	{
	//		// 一维的
	//		vector<int> listNum;
	//		list<string> listArrar;
	//		listSplit(*ite, listArrar);				
	//		for (iteArrar = listArrar.begin(); iteArrar != listArrar.end(); iteArrar++)
	//		{
	//			listNum.push_back(::atoi(iteArrar->c_str()));
	//		}
	//		pWaferMap.pMapData.push_back(listNum);
	//	}

	pWaferMap.pDUTMS = listMapData[7];
	pWaferMap.dbXDies = ::atof(listMapData[8].c_str());
	pWaferMap.dbYDies = ::atof(listMapData[9].c_str());

	pWaferMap.nROWCT = ::atoi(listMapData[10].c_str());
	pWaferMap.nCOLCT = ::atoi(listMapData[11].c_str());
	pWaferMap.pMapBin = listMapData[12];
	pWaferMap.nPRDCT = ::atoi(listMapData[13].c_str());
	pWaferMap.nPRAXI = (PROCESS_AXIS::ENUM)::atoi(listMapData[14].c_str());	
	pWaferMap.pNULBC = listMapData[15];
	pWaferMap.pBINLT = listMapData[16];
	pWaferMap.nMLCL = ::atoi(listMapData[17].c_str());

	return 0;
}

// 响应S9错误处理后通知
void CSecsEquip::OnS9ErrorNotifyHandler(std::string pReplyMailbox, std::string Data)
{	
	std::vector<std::string> sv;
	if(listSplit(Data, sv) == 0 
		&& sv.size() == 2)
	{			
		std::string pType = sv[1];
		S9_ERROR::ENUM nType = (S9_ERROR::ENUM)::atoi(pType.c_str());

		// 回调
		if(m_pS9ErrorNotifyProc != NULL)
		{				
			m_pS9ErrorNotifyProc(this, nType);					
		}

	}
}


	// 响应Wafer信息处理
void CSecsEquip::OnWaferMapSubstrateHandler(std::string pReplyMailbox, std::string Data)
{
	STRIP_MAP pStripMap;
	std::vector<std::string> sv;
	if(listSplit(Data, sv) == 0 
		&& sv.size() == 2)
	{			
		std::string pObjectID = sv[1];
	
		// 回调
		if(m_pWaferMapSubstrateProc != NULL)
		{				
			pStripMap = m_pWaferMapSubstrateProc(this, pObjectID.c_str());							
		}
			
	}
	
	m_impl.Reply(pReplyMailbox, pStripMap.pMapDataByXml);  	
}







