Browse Source

add project

lihz 8 years ago
commit
dfaa1bb886
47 changed files with 11491 additions and 0 deletions
  1. 262 0
      Card.cpp
  2. 45 0
      Card.h
  3. 137 0
      ClientSocket.cpp
  4. 46 0
      ClientSocket.h
  5. 468 0
      DBConnPool.cpp
  6. 134 0
      DBConnPool.h
  7. 139 0
      DbSettingDlg.cpp
  8. 41 0
      DbSettingDlg.h
  9. 62 0
      DownloadManager.h
  10. 244 0
      DownloadManagerImpl.cpp
  11. 72 0
      DownloadManagerImpl.h
  12. 63 0
      LogSetting.cpp
  13. 28 0
      LogSetting.h
  14. 305 0
      MysqlConnPool.cpp
  15. 135 0
      MysqlConnPool.h
  16. 77 0
      ReadMe.txt
  17. 28 0
      ServerSockert.cpp
  18. 24 0
      ServerSockert.h
  19. 104 0
      SysSetting.cpp
  20. 38 0
      SysSetting.h
  21. BIN
      YAServer.aps
  22. 291 0
      YAServer.cpp
  23. 93 0
      YAServer.h
  24. BIN
      YAServer.rc
  25. 251 0
      YAServer.vcxproj
  26. 279 0
      YAServer.vcxproj.filters
  27. 4 0
      YAServer.vcxproj.user
  28. 5227 0
      YAServerDlg.cpp
  29. 337 0
      YAServerDlg.h
  30. 651 0
      classdef.cpp
  31. 572 0
      classdef.h
  32. 207 0
      client_thread.cpp
  33. 206 0
      constdef.h
  34. 60 0
      def.h
  35. 92 0
      listening_thread.cpp
  36. 490 0
      locate_algorithm.cpp
  37. 29 0
      locate_algorithm.h
  38. 58 0
      log_def.h
  39. BIN
      res/YAServer.ico
  40. BIN
      res/YAServer.rc2
  41. BIN
      resource.h
  42. 31 0
      send_content.cpp
  43. 54 0
      send_head.cpp
  44. 85 0
      sever_thread.cpp
  45. 8 0
      stdafx.cpp
  46. 6 0
      stdafx.h
  47. 8 0
      targetver.h

+ 262 - 0
Card.cpp

@@ -0,0 +1,262 @@
+#include "StdAfx.h"
+#include "Card.h"
+
+
+CCard::CCard(void)
+{
+}
+
+
+CCard::~CCard(void)
+{
+}
+
+void CCard::getCordinate()
+{
+	//#include "stdio.h" 
+#include "stdlib.h" 
+#include <math.h> 
+	//坐标 
+	double ax,ay,bx,by,cx,cy,zx,zy; 
+	//距离 
+	double la,lb,lc; 
+	double cx1,cy1,cx2,cy2,cx3,cy3,cx4,cy4; 
+	int main(void) 
+	{ 
+		int i = 0,j = 0,n = 0; 
+		int okflag = 0; 
+		int err = 0; 
+		int aberr = 0; 
+		int acerr = 0; 
+		int abcerr = 0; 
+		int len; 
+		int abrequery = 0; 
+		int acrequery = 0; 
+		int requery1 = 0; 
+		int loopnum = 1; 
+		int option = 0; 
+		double cax,cay,cbx,cby,ccx,ccy; 
+		double cax_abeyance1[6000],cay_abeyance1[6000]; 
+		double cbx_abeyance1[6000],cby_abeyance1[6000]; 
+		double ccx_abeyance1[6000],ccy_abeyance1[6000]; 
+		double cabx_abeyance1[10],caby_abeyance1[10],cabx_abeyance2[10],caby_abeyance2[10]; 
+		double cacx_abeyance1[10],cacy_abeyance1[10],cacx_abeyance2[10],cacy_abeyance2[10]; 
+		//遍历圆周上所有点 
+		printf("use 'Enter' to divide x y\n"); 
+		printf("input A coordinate:\n"); 
+		scanf("%lf%lf",&ax,&ay); 
+		if((ax > 1000)||(bx > 1000)) 
+		{ 
+			printf("figure is too big! input A coordinate again:\n"); 
+			scanf("%lf%lf",&ax,&ay); 
+		} 
+		printf("input B coordinate:\n"); 
+		scanf("%lf%lf",&bx,&by); 
+		if((bx > 1000)||(bx > 1000)) 
+		{ 
+			printf("figure is too big! input B coordinate again:\n"); 
+			scanf("%lf,%lf",&bx,&by);   
+		} 
+		printf("input C coordinate:\n"); 
+		scanf("%lf%lf",&cx,&cy); 
+		if((cx > 1000)||(cx > 1000)) 
+		{ 
+			printf("figure is too big! input C coordinate again:\n"); 
+			scanf("%lf%lf",&cx,&cy); 
+		} 
+		printf("input distance from A to Z:\n"); 
+		scanf("%lf",&la); 
+		if(la > 1000) 
+		{ 
+			printf("figure is too big! inputdistance from A to Z again:\n"); 
+			scanf("%lf",&la); 
+		} 
+		printf("input distance from B to Z:\n"); 
+		scanf("%lf",&lb); 
+		if(lb > 1000) 
+		{ 
+			printf("figure is too big! inputdistance from B to Z again:\n"); 
+			scanf("%lf",&lb); 
+		} 
+		printf("input distance from C to Z:\n"); 
+		scanf("%lf",&lc); 
+		if(lc > 1000) 
+		{ 
+			printf("figure is too big! inputdistance from C to Z again:\n"); 
+			scanf("%lf",&lc); 
+		} 
+		printf("\n"); 
+		printf("A(%lf,%lf)\n",ax,ay); 
+		printf("B(%lf,%lf)\n",bx,by); 
+		printf("C(%lf,%lf)\n",cx,cy); 
+		printf("AZ = %lf\n",la); 
+		printf("BZ = %lf\n",lb); 
+		printf("CZ = %lf\n",lc); 
+		//INPUT: 
+		for(zx = ax -la;zx <= ax + la;zx++) 
+		{ 
+			do 
+			{ 
+				for(zy = ay -la;zy <= ay + la;zy++) 
+				{ 
+					cax = zx - ax; 
+					cax = fabs(cax); 
+					cax = pow(cax,2); 
+					cay = zy - ay; 
+					cay = fabs(cay); 
+					cay = pow(cay,2); 
+					if(((cax + cay) > (la*la - err))&&((cax + cay) < (la*la + err))) 
+					{ 
+						okflag = 1; 
+						cax_abeyance1[i] = zx; 
+						cay_abeyance1[i] = zy; 
+						n++; 
+					} 
+				} 
+				if(!okflag)err++; 
+			} while (okflag == 0); 
+			i++; 
+			err = 0; 
+			okflag = 0; 
+		} 
+		printf("query...\n"); 
+		i = 0; 
+		for(zx = bx -lb;zx <= bx + lb;zx++) 
+		{ 
+			do 
+			{ 
+				for(zy = by -lb;zy <= by + lb;zy++) 
+				{ 
+					cbx = zx - bx; 
+					cbx = fabs(cbx); 
+					cbx = pow(cbx,2); 
+					cby = zy - by; 
+					cby = fabs(cby); 
+					cby = pow(cby,2); 
+					if(((cbx + cby) > (lb*lb - err))&&((cbx + cby) < (lb*lb + err))) 
+					{ 
+						okflag = 1; 
+						cbx_abeyance1[i] = zx; 
+						cby_abeyance1[i] = zy; 
+					} 
+				} 
+				if(!okflag)err++;       
+			} while (okflag == 0); 
+			i++; 
+			err = 0; 
+			okflag = 0; 
+		} 
+		printf("query...\n"); 
+		getchar(); 
+		i = 0; 
+		for(zx = cx -lc;zx <= cx + lc;zx++) 
+		{ 
+			do 
+			{ 
+				for(zy = cy -lc;zy <= cy + lc;zy++) 
+				{ 
+					ccx = zx - cx; 
+					ccx = fabs(ccx); 
+					ccx = pow(ccx,2); 
+					ccy = zy - cy; 
+					ccy = fabs(ccy); 
+					ccy = pow(ccy,2); 
+					if(((ccx + ccy) > (lc*lc - err))&&((ccx + ccy) < (lc*lc + err))) 
+					{ 
+						okflag = 1; 
+
+						ccx_abeyance1[i] = zx; 
+						ccy_abeyance1[i] = zy; 
+						n++; 
+					} 
+				} 
+				if(!okflag)err++; 
+			} while (okflag == 0); 
+			i++; 
+			err = 0; 
+			okflag = 0; 
+		} 
+		printf("query a b c over!\n"); 
+		printf("press Enter to continue!\n"); 
+		//必须加不然运行出错,但不会停止 
+		getchar(); 
+		do 
+		{ 
+			//找ab 交点,因为距离的偏差,所以坐标会有偏差 
+			aberr =0; 
+			do 
+			{ 
+				for(i = 0;i <= 2*la;i++) 
+				{ 
+					for(j = 0;j <= 2*lb;j++) 
+					{ 
+						if(cax_abeyance1[i] == cbx_abeyance1[j]) 
+						{ 
+
+							if((cay_abeyance1[i]  >  (cby_abeyance1[j]  -  aberr  - abcerr))&&(cay_abeyance1[i] < (cby_abeyance1[j] + aberr + abcerr))) 
+							{ 
+								cabx_abeyance1[abrequery] = cax_abeyance1[i]; 
+								caby_abeyance1[abrequery] = cay_abeyance1[i]; 
+								printf("cabx_abeyance1[%d]=%f",abrequery,cabx_abeyance1[abrequery]); 
+								printf("caby_abeyance1[%d]=%f\n\n",abrequery,caby_abeyance1[abrequery]); 
+								abrequery++; 
+							} 
+						} 
+					} 
+				}   
+				if(abrequery < loopnum)aberr++; 
+			}while(abrequery < loopnum); 
+			acerr =0; 
+			//找ac 交点 
+			do 
+			{ 
+				for(i = 0;i <= 2*la;i++) 
+				{ 
+					for(j = 0;j <= 2*lc;j++) 
+					{ 
+						if(cax_abeyance1[i] == ccx_abeyance1[j]) 
+						{ 
+							if((cay_abeyance1[i]  >  (ccy_abeyance1[j]  -  acerr  - abcerr))&&(cay_abeyance1[i] < (ccy_abeyance1[j] + acerr + abcerr))) 
+							{ 
+								cacx_abeyance1[acrequery] = cax_abeyance1[i]; 
+								cacy_abeyance1[acrequery] = cay_abeyance1[i]; 
+								acrequery++; 
+							} 
+						} 
+					} 
+				} 
+				if(acrequery < loopnum)acerr++; 
+			}while(acrequery < loopnum); 
+			//找交点的交点 
+			for(i = 0;i < abrequery;i++) 
+			{ 
+				for(j = 0;j < acrequery;j++) 
+				{ 
+					if(cabx_abeyance1[i] == cacx_abeyance1[j]) 
+					{ 
+						requery1 = 1; 
+						printf("final result is (%f,%f)\n",cabx_abeyance1[i],caby_abeyance1[i]); 
+					} 
+				} 
+			} 
+			if(requery1 == 0) 
+			{ 
+				loopnum++; 
+				abcerr++; 
+			} 
+			if(loopnum == 10) 
+			{ 
+				printf("chech input figure is right\n"); 
+			} 
+		}while(requery1 ==0); 
+		printf("finish!\n"); 
+		getchar(); 
+		return 0; 
+	}  
+
+}
+
+int CCard::addReader( READERINFO* pReader )
+{
+
+}

+ 45 - 0
Card.h

@@ -0,0 +1,45 @@
+#pragma once
+
+#include <list>
+
+using namespace std;
+
+struct READERINFO{
+	double x;
+	double y;
+	double dist;
+};
+
+class CCard
+{
+public:
+	CCard(void);
+	virtual ~CCard(void);
+
+	LONG64 CardId;
+	int CardType;
+
+	LONG64 lTime;
+	int Power;
+	int RangingType;
+	int Acceleration;
+	double Distance;
+	WORD Timestamp;
+
+	WORD ReaderId;
+	WORD ReaderTimestamp;
+	int Antenna;
+
+	CString strRecTime; // ½ÓÊÕʱ¼ä
+	int X;
+	int Y;
+	int lastX;
+	int lastY;
+
+	STAFFER * pStaffer;
+	VEHICLE * pVehicle;
+
+public:
+	void getCordinate();
+};
+

+ 137 - 0
ClientSocket.cpp

@@ -0,0 +1,137 @@
+// ClientSocket.cpp : 实现文件
+//
+
+#include "stdafx.h"
+#include "YAServer.h"
+#include "ClientSocket.h"
+#include "YAServerDlg.h"
+#include "Functions/Functions.h"
+#include "socketdef.h"
+#include "socketdef.h"
+
+// CClientSocket
+
+CClientSocket::CClientSocket(CYAServerDlg* pDlg)
+{
+	m_pDlg = pDlg;
+	m_bClosed = FALSE;
+	bError = false;
+
+	m_wReadLength = 0;
+	m_wDataLength = 0;
+	m_wCharacterWord = 0;
+	reader_id = 0;
+	m_ReceiveBuffer = (BYTE*)malloc(LENGTH_MSG_4K);
+}
+
+CClientSocket::~CClientSocket()
+{
+	free(m_ReceiveBuffer);
+	//delete UserCallInfo;
+}
+
+void CClientSocket::Init()
+{
+
+}
+
+void CClientSocket::Abort()
+{
+
+}
+
+BOOL CClientSocket::SendData( WORD wCharacterWord, int wLength, BYTE* DataBuffer )
+{
+	BYTE SendBuffer[LENGTH_MSG_4K];
+	WORD nlength = wLength + sizeof(WORD) + sizeof(WORD); //socket的数据长度 数据的长度(n) + 特征字(2) + 校验码(2)
+	memset(SendBuffer, 0, LENGTH_MSG_4K);
+
+	int nPos = 0;
+	CFunctions::memcpyWord(SendBuffer, nlength, nPos);//长度
+	nPos += sizeof(WORD);
+	CFunctions::memcpyWord(SendBuffer, wCharacterWord, nPos);
+	nPos += sizeof(WORD);
+	memcpy(&SendBuffer[nPos], &DataBuffer[0], wLength);
+	nPos += wLength;
+
+	WORD wCrc = CFunctions::getCRC(&SendBuffer[sizeof(WORD)], wLength + sizeof(WORD)); // 数据长度 + 特征字
+	CFunctions::memcpyWord(SendBuffer, wCrc, nPos);
+	nPos += sizeof(WORD);
+
+	int sRet = Send(SendBuffer, nPos);
+	Sleep(20);
+
+	if(sRet == SOCKET_ERROR)
+	{
+		return FALSE;
+	}
+	return TRUE;
+}
+
+void CClientSocket::OnSend(int nErrorCode)
+{
+	switch(nErrorCode)
+	{
+		case 0:
+			break;
+		case WSAENETDOWN:
+			bError = true;			
+			//m_pDlg->showerr();
+			break;
+		default:
+			break;
+	}
+	CAsyncSocket::OnSend(nErrorCode);
+}
+void CClientSocket::OnReceive(int nErrorCode)
+{
+	if( nErrorCode != 0 )
+	{
+		bError = true;
+		return;
+	}
+	bError = false;
+	m_bClosed = FALSE;
+	m_pDlg->receive_data(this);
+	
+	CAsyncSocket::OnReceive(nErrorCode);
+}
+void CClientSocket::OnConnect(int nErrorCode)
+{
+	if(0 != nErrorCode){
+		m_pDlg->remove_socket(this);
+	}
+}
+void CClientSocket::OnClose(int nErrorCode)
+{
+	bError = true;
+	CAsyncSocket::OnClose(nErrorCode);
+	//CString sMsg;
+	//switch(nErrorCode)
+	//{
+	//	case WSAENETDOWN://套接字操作遇到一个不活动的网络
+	//		sMsg="网络不可用:";
+	//		break;
+	//	case WSAECONNRESET://远程主机强制关闭
+	//		sMsg="客户端强制关闭:";
+	//		break;
+	//	case WSAECONNABORTED://一个已建立的连接被你的主机上的软件终止,可能是因为一次数据传输超时或是协议错误。
+	//		sMsg="关闭客户端:";
+	//		break;
+	//	case 0://正常退出
+	//		sMsg="正常退出:";
+	//		break;
+	//	default:
+	//		sMsg="退出:";
+	//		break;
+	//}
+	if(m_bClosed){
+		return;
+	}
+	m_pDlg->remove_socket(this);
+	m_bClosed = TRUE;
+	ShutDown();
+	//delete this;
+}
+
+IMPLEMENT_DYNAMIC(CClientSocket, CAsyncSocket)

+ 46 - 0
ClientSocket.h

@@ -0,0 +1,46 @@
+#ifndef YASERVER_CLIENTSOCKET_H_
+#define YASERVER_CLIENTSOCKET_H_
+
+// CClientSocket 命令目标
+
+class CYAServerDlg;
+
+class CClientSocket : public CAsyncSocket
+{
+	DECLARE_DYNAMIC(CClientSocket);
+private:
+	CClientSocket(const CClientSocket& rSrc);
+	void operator=(const CClientSocket& rSrc);
+public:
+	CClientSocket(CYAServerDlg* pDlg);
+	virtual ~CClientSocket();
+
+	virtual void OnClose(int nErrorCode);
+	virtual void OnConnect(int nErrorCode);
+public:
+	CYAServerDlg* m_pDlg;
+	CString rAddress;//IP
+	//BOOL bCollServer;//是否采集服务器
+	//DATE mReceiveDateTimeSock;
+	//int RetryTimes; //重试次数,如果失去连接3次,则认为已经关断。
+	//BOOL ReceiveData;//是否接收采集的数据
+	DWORD m_wReadLength;
+	WORD m_wDataLength;
+	WORD m_wCharacterWord;
+
+	BYTE* m_ReceiveBuffer;
+	bool bError; //是否出错
+	BOOL m_bClosed;
+	//BOOL m_bNeedRemallocMem;
+	DWORD reader_id;
+public:
+	void Init();
+	void Abort();
+	BOOL SendData(WORD wCharacterWord,int wLength,BYTE* DataBuffer);
+protected:
+	virtual void OnReceive(int nErrorCode);
+	virtual void OnSend(int nErrorCode);
+};
+
+#endif // YASERVER_CLIENTSOCKET_H_
+

+ 468 - 0
DBConnPool.cpp

@@ -0,0 +1,468 @@
+// DBConnPool.cpp: implementation of the DBConnPool class.
+//
+//////////////////////////////////////////////////////////////////////
+#include "stdafx.h"
+#include "DBConnPool.h"
+DBConnect * pDBConn = NULL;
+void InitDBIterface(LPCSTR strDstAddress, LPCSTR strUsername, LPCSTR strPassword, LPCSTR strDBName,int minConn,int maxConn)
+{
+	DBConnPool::Instanse()->SetDBInfo(strDstAddress,strUsername,strPassword,strDBName,minConn,maxConn);
+	int cout = DBConnPool::Instanse()->InitializeAllDBConnections();
+}
+DBConnect * GetAConnect()
+{
+	DBConnGuard oConnGuard(pDBConn);
+	return pDBConn;
+}
+//////////////////////////////////////DBConnect/////////////////////////
+DBConnect::DBConnect(LPCTSTR strDstAddress, LPCTSTR strUsername, LPCTSTR strPassword, LPCTSTR strDBName,BOOL &state)
+{
+	m_bDBOpen = false;
+	if (0 == Open(strDstAddress,strUsername,strPassword,strDBName))
+	{
+		state =true;
+	}
+	else
+	{
+		state = false;
+	}
+}
+DBConnect::~DBConnect()
+{
+	Close();
+}
+int DBConnect::Open(LPCTSTR strDstAddress, LPCTSTR strUsername, LPCTSTR strPassword, LPCTSTR strDBName)
+{
+	_strDstAddress = strDstAddress;
+	_strDBName       = strDBName;
+	_strUsername     = strUsername;
+	_strPassword     = strPassword;
+
+	HRESULT comhr = ::CoInitialize(NULL);
+	if (FAILED(comhr))
+
+	{
+		return -1;
+	}
+	HRESULT hr = _connection_ptr.CreateInstance(__uuidof(Connection));
+
+	if (FAILED(hr))
+	{
+		return -1;
+	}
+
+	char szSQL[SQL_BUFFER_LEN] = {0};
+	memset(szSQL, 0, SQL_BUFFER_LEN);
+	sprintf(szSQL, "Driver=SQL Server;Server=%s;DATABASE=%s", strDstAddress, strDBName);
+
+	try
+	{
+		// 连接到服务器上数据库
+		_connection_ptr->Open(szSQL, strUsername, strPassword,adModeUnknown) ;
+		if (FAILED(hr))
+			return -1;
+	}
+	catch (_com_error &err)
+	{
+		TRACE(_T("数据库操作失败! 错误信息:%s, 文件:%s, 行:%d./n"), err.ErrorMessage(), __FILE__, __LINE__);
+
+		return -1;
+	}
+
+	m_bDBOpen = TRUE;
+
+	return 0;
+}
+int DBConnect::Close()
+{
+	if (m_bDBOpen)
+	{
+		HRESULT hr =_connection_ptr->Close();
+
+		if (FAILED(hr))
+		{
+			return -1;
+		}
+		::CoUninitialize();
+		m_bDBOpen = FALSE;
+	}
+
+	return 0;
+}
+int DBConnect::UserLogin(LPCSTR name,LPCSTR password)
+{
+	if (!m_bDBOpen)
+	{
+		return -1;
+	}
+	// 创建Command对象
+	_CommandPtr cmd;
+	HRESULT hr = cmd.CreateInstance(__uuidof(Command));
+	if (FAILED(hr))
+	{
+		return -1;
+	}
+
+	char szSQL[SQL_BUFFER_LEN] = {0};
+	sprintf(szSQL, "select count(*) as count from t_user where name =/'%s/' and password =/'%s/'",
+		name,password);
+	cmd->ActiveConnection = _connection_ptr;
+	cmd->CommandText = _bstr_t(szSQL);
+	cmd->CommandType = adCmdText;
+	try 
+	{
+		_RecordsetPtr rs = cmd->Execute(NULL, NULL, adCmdUnknown);
+
+		if (FAILED(hr)) 
+		{
+			return -1;
+		}
+		_variant_t count;
+		while (!rs->ADOEOF)
+		{     
+			count = rs->GetCollect("count");
+			rs->MoveNext() ;
+		}
+		if(count.intVal == 0)
+			return -1;
+	}
+	catch (_com_error &err)
+	{
+		TRACE(_T("数据库操作失败! 错误信息:%s, 文件:%s, 行:%d./n"), err.ErrorMessage(), __FILE__, __LINE__);
+
+		return -1;
+	}
+	return 0;
+}
+int DBConnect::GetSubmitInfo(vector<SOAP_SUBMIT_SMS> &vecsoapSms)
+{
+	if (!m_bDBOpen)
+	{
+		return -1;
+	}
+	// 创建Command对象
+	_CommandPtr cmd;
+	HRESULT hr = cmd.CreateInstance(__uuidof(Command));
+	if (FAILED(hr))
+	{
+		return -1;
+	}
+	string strSql = "exec SP_SMS_GETSUBMIT";
+	cmd->ActiveConnection = _connection_ptr;
+	cmd->CommandText = _bstr_t(strSql.c_str());
+	cmd->CommandType = adCmdText;
+	try 
+	{
+		_RecordsetPtr rs = cmd->Execute(NULL, NULL, adCmdUnknown);
+
+		if (FAILED(hr)) 
+		{
+			return -1;
+		}
+		while (!rs->ADOEOF)
+		{     
+			_variant_t  id;
+			_variant_t  recverid;
+			_variant_t  recvertel;
+			_variant_t  messagecontent;
+			_variant_t  recverphonetype;
+			_variant_t  inout;
+			_variant_t  sendtime;
+			_variant_t  cardtime;
+			_variant_t  schoolid;
+			_variant_t  classid;
+			_variant_t  rfidno;
+
+			id = rs->GetCollect("id");
+			recverid = rs->GetCollect("recverid");
+			recvertel = rs->GetCollect("recvertel");
+			messagecontent = rs->GetCollect("messagecontent");
+			recverphonetype = rs->GetCollect("recverphonetype");
+			inout = rs->GetCollect("inout");
+			sendtime = rs->GetCollect("sendtime");
+			cardtime = rs->GetCollect("cardtime");
+			schoolid = rs->GetCollect("schoolid");
+			classid = rs->GetCollect("classid");
+			rfidno = rs->GetCollect("rfidno");
+			SOAP_SUBMIT_SMS submitsms;
+			submitsms.id = (int)(long)id;
+			VarientToString(recverid, submitsms.recverid);
+			VarientToString(recvertel, submitsms.recvertel);
+			VarientToString(messagecontent, submitsms.messagecontent);
+			VarientToString(recverphonetype, submitsms.recverphonetype);
+			submitsms.inout = (int)(long)inout;
+			VarientToString(sendtime, submitsms.sendtime);
+			VarientToString(cardtime, submitsms.cardtime);
+			VarientToString(rfidno, submitsms.rfidno);
+			submitsms.schoolid = (int)(long)schoolid;
+			submitsms.classid = (int)(long)classid;
+			vecsoapSms.push_back(submitsms);
+			rs->MoveNext() ;
+		}
+	}
+	catch (_com_error &err)
+	{
+		TRACE(_T("数据库操作失败! 错误信息:%s, 文件:%s, 行:%d./n"), err.ErrorMessage(), __FILE__, __LINE__);
+
+		return -1;
+	}
+	return 0;
+}
+int DBConnect::InsertHistory(int id)
+{
+	if (!m_bDBOpen)
+	{
+		return -1;
+	}
+	// 创建Command对象
+	_CommandPtr cmd;
+	HRESULT hr = cmd.CreateInstance(__uuidof(Command));
+	if (FAILED(hr))
+	{
+		return -1;
+	}
+	char szSQL[SQL_BUFFER_LEN] = {0};
+	sprintf(szSQL, "exec SP_SMS_SUBMITRESULT %d", id);
+	try
+	{
+		cmd->ActiveConnection = _connection_ptr;
+		cmd->CommandText = _bstr_t(szSQL);
+		cmd->CommandType = adCmdText;
+		cmd->Execute(NULL, NULL, adCmdUnknown);
+	}
+	catch (_com_error &err)
+	{
+		TRACE(_T("数据库操作失败! 错误信息:%s, 文件:%s, 行:%d./n"), err.ErrorMessage(), __FILE__, __LINE__);
+
+		return -1;
+	}
+	return 0;
+}
+void DBConnect::VarientToString(_variant_t var, string& str)
+{
+	if (VT_NULL == var.vt)
+	{
+		str = "";
+	}
+	else
+	{
+		str = (char*)_bstr_t(var);
+	}
+}
+//////////////////////////////////////End//////////////////////////////
+//////////////////////////////////////////////////////////////////////
+// Construction/Destruction
+//////////////////////////////////////////////////////////////////////
+DBConnPool* DBConnPool::m_pInstanse = NULL;
+DBConnPool::DBConnPool()
+{
+	m_bNeedStop = FALSE;
+	m_bNeedConnection = FALSE;
+	m_hMaintanceThread = INVALID_HANDLE_VALUE;
+
+	// 线程控制
+	m_hHaveData = CreateEvent (NULL, TRUE, FALSE, _T("DataConnPool"));
+
+	InitializeCriticalSection(&m_csIdleConnList);
+	InitializeCriticalSection(&m_csBusyConnList);
+}
+void DBConnPool::SetDBInfo(LPCSTR strDstAddress, LPCSTR strUsername, LPCSTR strPassword, LPCSTR strDBName,int minConn,int maxConn)
+{
+	_strDBName = strDBName;
+	_strDstAddress = strDstAddress;
+	_strPassword = strPassword;
+	_strUsername = strUsername;
+	m_nMaxCount = maxConn;
+	m_nMinCount = minConn;
+}
+DBConnPool::~DBConnPool()
+{
+	m_hMaintanceThread = INVALID_HANDLE_VALUE;
+	m_bNeedStop = TRUE;
+	CloseHandle(m_hHaveData);
+	CloseHandle(m_hMaintanceThread);
+
+	DeleteCriticalSection(&m_csIdleConnList);
+	DeleteCriticalSection(&m_csBusyConnList);
+}
+DBConnPool *DBConnPool::Instanse()
+{
+	if (NULL == m_pInstanse)
+	{
+		m_pInstanse = new DBConnPool();
+	}
+	return m_pInstanse;
+}
+int DBConnPool::InitializeAllDBConnections()
+{
+	// 先清除现有的数据
+	DestroyAllDBConnections();
+	// 开始按照最小数量开始创建
+	DBConnect * pDBConnect = NULL;
+	int nCount = 0;
+	for (int i = 0; i < m_nMinCount; i++)
+	{
+		nCount = InitializeAConnection();
+	}
+	// 创建一个工作线程,用来进行一些后台维护工作
+	if (INVALID_HANDLE_VALUE == m_hMaintanceThread)
+	{
+		m_hMaintanceThread = CreateThread(NULL, NULL, thread_run, (LPVOID)this, 0, NULL);
+	}
+	return nCount;
+}
+void DBConnPool::DestroyAllDBConnections()
+{
+	// 销毁数据库连接可以使用大锁
+	EnterCriticalSection(&m_csIdleConnList);
+	DBConnectList::iterator itIdle = m_listIdleConnection.begin();
+	DBConnectList::iterator itIdleEnd = m_listIdleConnection.end();
+	while (itIdle != itIdleEnd)
+	{
+		if (NULL != (*itIdle))
+		{
+			(*itIdle)->Close();
+			delete (*itIdle);
+		}
+		// erase本身就会把跌代器指向下一个
+		itIdle = m_listIdleConnection.erase(itIdle);
+	}
+	LeaveCriticalSection(&m_csIdleConnList);
+	// 还有使用中的连接
+	EnterCriticalSection(&m_csBusyConnList);
+	DBConnectList::iterator itBusy = m_listBusyConnection.begin();
+	DBConnectList::iterator itBusyEnd = m_listBusyConnection.end();
+	while (itBusy != itBusyEnd)
+	{
+		if (NULL != (*itBusy))
+		{
+			(*itBusy)->Close();
+			delete (*itBusy);
+		}
+		// erase本身就会把跌代器指向下一个
+		itBusy = m_listBusyConnection.erase(itBusy);
+	}
+	LeaveCriticalSection(&m_csBusyConnList);
+}
+int DBConnPool::InitializeAConnection()
+{
+	BOOL bSuccess = FALSE;
+	DBConnect * pDBEngine = new DBConnect(_strDstAddress, _strUsername, _strPassword, _strDBName, bSuccess);
+	if (bSuccess)
+	{
+		m_bNeedConnection = FALSE;
+		return RestoreAConnection(pDBEngine);
+	}
+	else
+	{
+		delete pDBEngine;
+		return m_listIdleConnection.size();
+	}
+}
+void DBConnPool::CloseAConnection(DBConnect* pDBEngine)
+{
+	pDBEngine->Close();
+	// 从空闲队列将其删除
+	EnterCriticalSection(&m_csIdleConnList);
+	m_listIdleConnection.remove(pDBEngine);
+	LeaveCriticalSection(&m_csIdleConnList);
+}
+DBConnect * DBConnPool::GetAConnection()
+{
+	DBConnect * pDBEngine = NULL;
+	// 做一个循环,反复尝试五次取连接,每次间隔1秒钟
+	int nTimes = 0;
+	while ((m_listIdleConnection.size() <= 0) && (nTimes < 5))
+	{
+		Sleep(1000);
+		nTimes++;
+	}
+	if (5 == nTimes)
+	{
+		// 这样狼狈的进来肯定是没有可用连接了,记录日志退出
+		// g_pSvrLog->AddRunLog(LL_ERROR, _T("Waiting for a connection for a long time, but failed."));
+		return pDBEngine;
+	}
+	// 从空闲队列中取出,并且加入到使用队列中
+	EnterCriticalSection(&m_csIdleConnList);
+	if (m_listIdleConnection.size() > 0)
+	{
+		pDBEngine = m_listIdleConnection.front();
+		m_listIdleConnection.pop_front();
+		// 加入使用的连接队列
+		EnterCriticalSection(&m_csBusyConnList);
+		m_listBusyConnection.push_back(pDBEngine);
+		LeaveCriticalSection(&m_csBusyConnList);
+	}
+	LeaveCriticalSection(&m_csIdleConnList);
+	if (m_listIdleConnection.size() <= 1)
+	{
+		// 剩余空闲连接的数目小于等于1个时候需要检查开始创建
+		if ((m_listIdleConnection.size() + m_listBusyConnection.size()) < m_nMaxCount)
+		{
+			// 还小于最大限制,可以创建
+			SetEvent(m_hHaveData);
+			m_bNeedConnection = TRUE;
+		}
+		else
+		{
+			// 超出限制了,做个记录吧
+			//g_pSvrLog->AddRunLog(LL_ERROR, _T("Database connection reached max count."));
+		}
+	}
+	return pDBEngine;
+}
+int DBConnPool::RestoreAConnection(DBConnect* pDBEngine)
+{
+	if (NULL != pDBEngine)
+	{
+		// 从使用中的队列取出
+		EnterCriticalSection(&m_csBusyConnList);
+		m_listBusyConnection.remove(pDBEngine);
+		LeaveCriticalSection(&m_csBusyConnList);
+		// 加入到空闲队列中
+		EnterCriticalSection(&m_csIdleConnList);
+		m_listIdleConnection.push_back(pDBEngine);
+		LeaveCriticalSection(&m_csIdleConnList);
+	}
+	EnterCriticalSection(&m_csIdleConnList);
+	int nCount = m_listIdleConnection.size();
+	LeaveCriticalSection(&m_csIdleConnList);
+	return nCount;
+}
+void DBConnPool::StopThread()
+{
+	m_bNeedStop = TRUE;
+	// 因为线程是无限制等待信号的,所以这里先把标志位置为停止,然后发信号让线程检测
+	SetEvent(m_hHaveData);
+	// 等待退出
+	WaitForSingleObject(m_hMaintanceThread, INFINITE);
+	CloseHandle(m_hMaintanceThread);
+}
+BOOL DBConnPool::IsNeedStop()
+{
+	return m_bNeedStop;
+}
+BOOL DBConnPool::IsNeedConnection()
+{
+	return m_bNeedConnection;
+}
+/************************************************************************/
+/* 维护线程                                                             */
+/************************************************************************/
+DWORD WINAPI DBConnPool::thread_run( LPVOID pdata)
+{
+	DBConnPool * pConPool = (DBConnPool *) pdata;
+	while (!pConPool->IsNeedStop())
+	{
+		// 设置事件为无信号, 并且无限制等待
+		ResetEvent(pConPool->m_hHaveData);  
+		WaitForSingleObject(pConPool->m_hHaveData, INFINITE);
+		if (pConPool->IsNeedConnection())
+		{
+			// g_pSvrLog->AddRunLog(LL_DEBUG, _T("Create a new DB connection."));
+			pConPool->InitializeAConnection();
+		}
+	}
+	return 0;
+}

+ 134 - 0
DBConnPool.h

@@ -0,0 +1,134 @@
+// !defined(AFX_DBCONNPOOL_H__42089E9A_FD85_4DD4_A973_64A4980332A5__INCLUDED_)  
+// DBConnPool.h: interface for the DBConnPool class.
+//
+//////////////////////////////////////////////////////////////////////
+#if !defined(AFX_DBCONNPOOL_H__42089E9A_FD85_4DD4_A973_64A4980332A5__INCLUDED_)
+#define AFX_DBCONNPOOL_H__42089E9A_FD85_4DD4_A973_64A4980332A5__INCLUDED_
+#define  SQL_BUFFER_LEN 1024
+#import "C:/Program Files/Common Files/System/ado/msado15.dll" rename("EOF","ADOEOF")
+#include <list>
+#include <windows.h>
+#include <string>
+#include <vector>
+//#include  "DBDefine.h"
+using namespace ADODB;
+using namespace std;
+
+class RFIDAPI DBConnect
+{
+public:
+	DBConnect(LPCSTR strDstAddress, 
+		LPCSTR strUsername, 
+		LPCSTR strPassword, 
+		LPCSTR strDBName,
+		BOOL &state);
+	~DBConnect();
+public:
+	// 连接到数据库
+
+	int Open(LPCTSTR strDstAddress, LPCTSTR strUsername, LPCTSTR strPassword, LPCTSTR strDBName);
+	// 关闭数据库
+
+	int Close();
+	// 数据库是否已连接
+
+	BOOL IsOpen() const;
+public:
+private:
+	ADODB::_ConnectionPtr           _connection_ptr;   //ADO的数据库连接智能指针
+	bool                            _isAdoValid;       //ADO环境是否已经初化成功标志量
+	bool       m_bDBOpen;
+
+	LPCSTR       _strDstAddress;    //数据源地址或服务名
+	LPCSTR       _strUsername;      //数据库用户名
+	LPCSTR       _strPassword;      //数据库密码
+	LPCSTR       _strDBName;        //数据库名称
+	void         VarientToString(_variant_t var, string& str);
+	//对外公共接口
+public:
+	int          GetSubmitInfo(vector<SOAP_SUBMIT_SMS> &vecsoapSms);    
+
+	int          InsertHistory(int id);
+	int          UserLogin(LPCSTR name,LPCSTR password);
+}; 
+typedef std::list<DBConnect*> DBConnectList;
+class  DBConnPool  
+{
+public:
+	DBConnPool();
+	virtual ~DBConnPool();
+	// 获取实例指针
+	static DBConnPool * Instanse();
+	// 初始化所有连接
+	int InitializeAllDBConnections();
+
+	// 关闭所有连接
+	void DestroyAllDBConnections();
+	// 获取一个空闲连接
+	DBConnect* GetAConnection();
+	// 交还连接给空闲队列
+	int RestoreAConnection(DBConnect* pDBEngine);
+	void SetDBInfo(LPCSTR strDstAddress, LPCSTR strUsername, LPCSTR strPassword, LPCSTR strDBName,int minConn,int maxConn);
+private:
+
+	// 创建一个连接
+	int InitializeAConnection();
+	// 关闭一个连接
+	void CloseAConnection(DBConnect* pDBEngine);
+	// 停止工作线程
+	void StopThread();
+
+	// 判断是否需要停止
+	BOOL IsNeedStop();
+	BOOL IsNeedConnection();
+	// 将守卫类作为连接池类的友元类
+	friend class ConnGuard;
+	// 唯一实例
+	static DBConnPool *m_pInstanse;
+
+	// 空闲数据库连接队列
+	DBConnectList m_listIdleConnection;
+	// 在使用的数据库连接
+	DBConnectList m_listBusyConnection;
+
+	// 队列保护的临界区
+	CRITICAL_SECTION m_csIdleConnList;
+	CRITICAL_SECTION m_csBusyConnList;
+
+	// 可用连接总数的三个指标:最大、最小
+	int m_nMaxCount;
+	int m_nMinCount;
+
+	//  // 数据库信息
+	LPCSTR       _strDstAddress;    //数据源地址或服务名
+	LPCSTR       _strUsername;      //数据库用户名
+	LPCSTR       _strPassword;      //数据库密码
+	LPCSTR       _strDBName;        //数据库名称
+
+	// 维护线程
+	HANDLE m_hMaintanceThread; // 线程句柄
+	HANDLE m_hHaveData; // 信号
+
+	BOOL m_bNeedStop; // 管理线程起停的标志位
+	BOOL m_bNeedConnection; // 需要创建连接的标志
+	static DWORD WINAPI thread_run( LPVOID pdata);
+};
+// 守卫类,利用构造和析构函数保证连接取出和归还必须成对,防止资源泄露
+class  DBConnGuard
+{
+public:
+	DBConnGuard(DBConnect*& DBConn)
+	{
+		DBConn = DBConnPool::Instanse()->GetAConnection();
+		m_pDBConn = DBConn;
+	}
+	virtual ~DBConnGuard()
+	{
+		DBConnPool::Instanse()->RestoreAConnection(m_pDBConn);
+	}
+private:
+	DBConnect *m_pDBConn;
+};
+RFIDAPI void  InitDBIterface(LPCSTR strDstAddress, LPCSTR strUsername, LPCSTR strPassword, LPCSTR strDBName,int minConn,int maxConn);
+RFIDAPI DBConnect * GetAConnect();
+#endif // !defined(AFX_DBCONNPOOL_H__42089E9A_FD85_4DD4_A973_64A4980332A5__INCLUDED_)

+ 139 - 0
DbSettingDlg.cpp

@@ -0,0 +1,139 @@
+// DbSettingDlg.cpp : 实现文件
+//
+
+#include "stdafx.h"
+#include "YAServer.h"
+#include "DbSettingDlg.h"
+#include "afxdialogex.h"
+#include "def.h"
+#include "INIFILE.h"
+#include "Functions/Functions.h"
+
+
+// CDbSettingDlg 对话框
+
+IMPLEMENT_DYNAMIC(CDbSettingDlg, CDialogEx)
+
+CDbSettingDlg::CDbSettingDlg(CWnd* pParent /*=NULL*/)
+	: CDialogEx(CDbSettingDlg::IDD, pParent)
+	, m_host_master(_T(""))
+	, m_port_master(0)
+	, m_pwd_master(_T(""))
+	, m_user_master(_T(""))
+	, m_db_master(_T(""))
+	, m_use_slave(FALSE)
+	, m_host_slave(_T(""))
+	, m_port_slave(0)
+	, m_user_slave(_T(""))
+	, m_pwd_slave(_T(""))
+	, m_db_slave(_T(""))
+{
+	
+}
+
+CDbSettingDlg::~CDbSettingDlg()
+{
+}
+
+void CDbSettingDlg::DoDataExchange(CDataExchange* pDX)
+{
+	CDialogEx::DoDataExchange(pDX);
+	DDX_Text(pDX, IDC_EDIT1, m_host_master);
+	DDX_Text(pDX, IDC_EDIT4, m_port_master);
+	DDX_Text(pDX, IDC_EDIT6, m_pwd_master);
+	DDX_Text(pDX, IDC_EDIT3, m_user_master);
+	DDX_Text(pDX, IDC_EDIT2, m_db_master);
+	DDX_Control(pDX, IDC_ENCODE_MASTER, m_encode_master);
+	DDX_Check(pDX, IDC_CHECK1, m_use_slave);
+	DDX_Text(pDX, IDC_HOST_SLAVE, m_host_slave);
+	DDX_Text(pDX, IDC_PORT_SLAVE, m_port_slave);
+	DDX_Text(pDX, IDC_USER_SLAVE, m_user_slave);
+	DDX_Text(pDX, IDC_PWD_SLAVE, m_pwd_slave);
+	DDX_Text(pDX, IDC_DB_SLAVE, m_db_slave);
+	DDX_Control(pDX, IDC_ENCODE_SLAVE, m_encode_slave);
+}
+
+
+BEGIN_MESSAGE_MAP(CDbSettingDlg, CDialogEx)
+	ON_BN_CLICKED(IDOK, &CDbSettingDlg::OnBnClickedOk)
+	ON_BN_CLICKED(IDC_CHECK1, &CDbSettingDlg::OnBnClickedCheck1)
+END_MESSAGE_MAP()
+
+void CDbSettingDlg::OnBnClickedOk()
+{
+	UpdateData();
+	CString strCBText;
+	theApp.dbhost = CFunctions::wc2c(m_host_master.GetBuffer(0));
+	theApp.dbuser =  CFunctions::wc2c(m_user_master.GetBuffer(0));
+	theApp.dbpwd =  CFunctions::wc2c(m_pwd_master.GetBuffer(0));
+	theApp.dbname =  CFunctions::wc2c(m_db_master.GetBuffer(0));
+	int nIndex = m_encode_master.GetCurSel();
+	m_encode_master.GetLBText( nIndex, strCBText);
+	theApp.dbencoding = CFunctions::wc2c(strCBText.GetBuffer(0));
+	theApp.dbport = m_port_master;
+	theApp.dbbackup =  m_use_slave ? "1" : "0";
+
+	theApp.dbhost_bk = CFunctions::wc2c(m_host_slave.GetBuffer(0));
+	theApp.dbuser_bk =  CFunctions::wc2c(m_user_slave.GetBuffer(0));
+	theApp.dbpwd_bk =  CFunctions::wc2c(m_pwd_slave.GetBuffer(0));
+	theApp.dbname_bk =  CFunctions::wc2c(m_db_slave.GetBuffer(0));
+	nIndex = m_encode_slave.GetCurSel();
+	if(nIndex == -1) {
+		nIndex = 0;
+	}
+	m_encode_master.GetLBText( nIndex, strCBText);
+	theApp.dbencoding_bk = CFunctions::wc2c(strCBText.GetBuffer(0));
+	theApp.dbport_bk = m_port_slave;
+
+	theApp.save_db_conf();
+	CDialogEx::OnOK();
+}
+
+BOOL CDbSettingDlg::OnInitDialog()
+{
+	CDialog::OnInitDialog();
+
+	CString strTemp;
+	strTemp.Format(_T("gb2312"));
+	m_encode_slave.AddString(strTemp);
+	m_encode_master.AddString(_T("gb2312"));
+	strTemp.Format(_T("utf8"));
+	m_encode_slave.AddString(strTemp);
+	m_encode_master.AddString(strTemp);
+
+	init_ui();
+	return TRUE;
+}
+
+void CDbSettingDlg::init_ui()
+{
+	m_host_master = CFunctions::c2wc(theApp.dbhost.c_str());
+	m_user_master = CFunctions::c2wc(theApp.dbuser.c_str());
+	m_pwd_master = CFunctions::c2wc(theApp.dbpwd.c_str());
+	m_db_master = CFunctions::c2wc(theApp.dbname.c_str());
+	int nIndex = m_encode_master.FindString(0, CFunctions::c2wc(theApp.dbencoding.c_str()));
+	m_encode_master.SetCurSel(nIndex); //设置第nIndex项为显示的内容
+	m_port_master = theApp.dbport;
+	m_use_slave = (theApp.dbbackup == "1");
+
+	m_host_slave = CFunctions::c2wc(theApp.dbhost_bk.c_str());
+	m_user_slave = CFunctions::c2wc(theApp.dbuser_bk.c_str());
+	m_pwd_slave = CFunctions::c2wc(theApp.dbpwd_bk.c_str());
+	m_db_slave = CFunctions::c2wc(theApp.dbname_bk.c_str());
+	nIndex = m_encode_slave.FindString(0, CFunctions::c2wc(theApp.dbencoding_bk.c_str()));
+	m_encode_slave.SetCurSel(nIndex); //设置第nIndex项为显示的内容
+	//m_encode_slave.SetWindowTextW(CFunctions::c2wc(theApp.dbencoding_bk.c_str()));
+	m_port_slave = theApp.dbport_bk;
+	UpdateData(FALSE);
+}
+
+void CDbSettingDlg::OnBnClickedCheck1()
+{
+	m_encode_slave.EnableWindow(!m_use_slave);
+	(CComboBox*)GetDlgItem(IDC_HOST_SLAVE)->EnableWindow(!m_use_slave);
+	(CComboBox*)GetDlgItem(IDC_PORT_SLAVE)->EnableWindow(!m_use_slave);
+	(CComboBox*)GetDlgItem(IDC_USER_SLAVE)->EnableWindow(!m_use_slave);
+	(CComboBox*)GetDlgItem(IDC_PWD_SLAVE)->EnableWindow(!m_use_slave);
+	(CComboBox*)GetDlgItem(IDC_DB_SLAVE)->EnableWindow(!m_use_slave);
+	UpdateData();
+}

+ 41 - 0
DbSettingDlg.h

@@ -0,0 +1,41 @@
+#pragma once
+#include "afxwin.h"
+
+
+// CDbSettingDlg 对话框
+
+class CDbSettingDlg : public CDialogEx
+{
+	DECLARE_DYNAMIC(CDbSettingDlg)
+
+public:
+	CDbSettingDlg(CWnd* pParent = NULL);   // 标准构造函数
+	virtual ~CDbSettingDlg();
+
+// 对话框数据
+	enum { IDD = IDD_DBSETTING };
+
+protected:
+	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持
+	virtual BOOL OnInitDialog();
+
+	DECLARE_MESSAGE_MAP()
+public:
+	CString m_host_master;
+	UINT m_port_master;
+	CString m_pwd_master;
+	CString m_user_master;
+	CString m_db_master;
+	CComboBox m_encode_master;
+	BOOL m_use_slave;
+	CString m_host_slave;
+	UINT m_port_slave;
+	CString m_user_slave;
+	CString m_pwd_slave;
+	CString m_db_slave;
+	CComboBox m_encode_slave;
+	afx_msg void OnBnClickedOk();
+public:
+	void init_ui();
+	afx_msg void OnBnClickedCheck1();
+};

+ 62 - 0
DownloadManager.h

@@ -0,0 +1,62 @@
+#ifndef COMMON_DOWNLOADMANAGER_H_
+#define COMMON_DOWNLOADMANAGER_H_
+
+#include <list>
+
+typedef void* TaskID;
+
+#define  TaskIDNULL NULL
+
+enum HttpMethod
+{
+	HM_GET = 0,
+	HM_POST,
+	HM_END,
+};
+
+struct DownloadProgress
+{
+	double fNow;
+	double fTotal;
+};
+
+struct DownloadData{
+	void* ptr;
+	unsigned int nLen;
+};
+
+struct TaskInitData
+{
+	typedef std::list<std::pair<std::string, std::string>> ParamList;
+	std::string strRequestURL;
+	std::string strFilename;
+	HttpMethod hm;
+	std::string strParam;
+	//ParamList lsParams;
+};
+
+struct DownloadManager
+{
+	virtual TaskID CreateTask(TaskInitData* pInit) = 0;
+	virtual bool StartTask(TaskID taskID) = 0;
+	virtual bool StopTask(TaskID taskID) = 0;
+};
+
+struct ParamConstructor 
+{
+	virtual void ParamAlloc(
+		unsigned int nEvent,
+		unsigned int nSubEvent,
+		void** param1,
+		void** param2
+		) = 0;
+
+	virtual void ParamFree(
+		unsigned int nEvent,
+		unsigned int nSubEvent,
+		void* param1,
+		void* param2
+		) = 0;
+};
+
+#endif // COMMON_DOWNLOADMANAGER_H_

+ 244 - 0
DownloadManagerImpl.cpp

@@ -0,0 +1,244 @@
+#include "StdAfx.h"
+#include "DownloadManagerImpl.h"
+#include <boost/make_shared.hpp>
+
+#define BUFFER_STEP_SIZE 1024
+#define	MSG_COMPLETE_FILE	WM_USER + 100
+#define MSG_COMPLETE_BUFFER	WM_USER + 101
+#define MSG_ERROR			WM_USER + 102
+
+
+DownloadManagerImpl::~DownloadManagerImpl(void)
+{
+}
+
+void DownloadManagerImpl::init(HWND hWnd)
+{
+	m_hParent = hWnd;
+	mspTaskManager = UEFactory::getTaskManager(emProtocol_Http);
+	mspTaskManager->initTaskManager();
+}
+
+void DownloadManagerImpl::uninit( void )
+{
+	mspTaskManager->uninitTaskManager();
+	mspTaskManager.reset();
+
+	m_hParent = NULL;
+}
+
+TaskID DownloadManagerImpl::CreateTask( TaskInitData* pInit )
+{
+	if (!mspTaskManager)
+	{
+		return NULL;
+	}
+
+	nsURLEngine::IUETaskPtr spNewTask = mspTaskManager->getNewTask();
+	TaskID taskID = reinterpret_cast<TaskID>(spNewTask.get());
+	TaskDataPtr spTaskData = boost::make_shared<TaskData>(); 
+
+	spNewTask->setCallback(static_cast<IUETaskCallback*>(this));
+	spNewTask->setURL(pInit->strRequestURL.c_str());
+	spNewTask->setMethod(pInit->hm == HM_POST ? emMethod_Post : emMethod_Get);
+	spNewTask->setParam(pInit->strParam.c_str());
+
+	//TaskInitData::ParamList::iterator itParam = pInit->lsParams.begin();
+	//while (itParam != pInit->lsParams.end())
+	//{
+	//	spNewTask->addParam(itParam->first.c_str(),itParam->second.c_str());
+	//	itParam++;
+	//}
+
+	if (!pInit->strFilename.empty())
+	{
+		spNewTask->setLocalFile(pInit->strFilename.c_str());
+		spTaskData->strFile = pInit->strFilename;
+	}
+	else
+	{
+		spTaskData->vecData.reserve(BUFFER_STEP_SIZE);
+	}
+
+	spTaskData->spTask = spNewTask;
+
+	TaskDataMap::iterator it = mmTasks.find(taskID);
+
+	if (it != mmTasks.end())
+	{
+		mmTasks.erase(it);
+	}
+
+	mmTasks.insert(std::make_pair(taskID,spTaskData));
+
+	return taskID;
+}
+
+bool DownloadManagerImpl::StartTask( TaskID taskID )
+{
+	TaskDataMap::iterator it = mmTasks.find(taskID);
+
+	if (it != mmTasks.end())
+	{
+		mspTaskManager->startTask(it->second->spTask);
+
+		return true;
+	}
+
+	return false;
+}
+
+void* DownloadManagerImpl::AllocCompleteBuffer( TaskID taskID )
+{
+	TaskDataMap::iterator it = mmTasks.find(taskID);
+
+	if (it == mmTasks.end())
+	{
+		return NULL;
+	}
+
+	DownloadData* pData = new DownloadData();
+
+	if (it->second->strFile.empty())
+	{
+		pData->nLen = it->second->vecData.size();
+		pData->ptr = new char[pData->nLen];
+		memcpy(pData->ptr,&(it->second->vecData[0]),pData->nLen);
+	}
+	else
+	{
+		pData->nLen = it->second->strFile.size() + 1;
+		pData->ptr = new char[pData->nLen];
+		memcpy(pData->ptr,it->second->strFile.c_str(),pData->nLen);
+	}
+
+	return reinterpret_cast<void*>(pData);
+}
+
+void DownloadManagerImpl::OnTaskProgress( double fNow,double fTotal,UETaskID taskid )
+{
+
+}
+
+void DownloadManagerImpl::OnTaskEvent( emTaskEvent event,emEngineErrCode errCode,UETaskID taskid )
+{
+	if (event == emEvent_Complete)
+	{
+		TaskDataMap::iterator it = mmTasks.find(taskid);
+		if (it != mmTasks.end())
+		{
+			try{
+				ParamConstructor* pConstructor = static_cast<ParamConstructor*>(this);
+				DownloadData* pData = NULL;
+				pConstructor->ParamAlloc(it->second->strFile.empty() ? MSG_COMPLETE_BUFFER : MSG_COMPLETE_FILE,0,&taskid,reinterpret_cast<void**>(&pData));
+
+				PostMessage(m_hParent, it->second->strFile.empty() ? MSG_COMPLETE_BUFFER : MSG_COMPLETE_FILE,
+					(WPARAM)taskid, (LPARAM)pData);
+/*				eventMgr->postEvent(
+					EVENT_DOWNLOADMANAGER_COMPLETE,
+					it->second->strFile.empty() ? DOWNLOADCOMPLETE_BUFFER : DOWNLOADCOMPLETE_FILE,
+					taskid,
+					pData,
+					pConstructor
+					);*/	
+			}
+			catch(...)
+			{
+				PostMessage(m_hParent, MSG_ERROR, (WPARAM)&taskid, NULL);
+				//eventMgr->postEvent(EVENT_DOWNLOADMANAGER_ERROR,0,taskid,NULL);
+			}
+		}
+
+		mmTasks.erase(taskid);
+	}
+	else if (event == emEvent_Error)
+	{
+		//eventMgr->postEvent(EVENT_DOWNLOADMANAGER_ERROR,0,taskid,NULL);
+		mmTasks.erase(taskid);
+	}
+}
+
+void DownloadManagerImpl::OnTaskData( UEVoidPtr ptr,unsigned int nLen,UETaskID taskid )
+{
+	TaskDataMap::iterator it = mmTasks.find(taskid);
+
+	if (it != mmTasks.end())
+	{
+		if (it->second->strFile.empty())
+		{
+			std::vector<unsigned char>::size_type nSize = it->second->vecData.size();
+			std::vector<unsigned char>::size_type nCaps = it->second->vecData.capacity();
+			if (nSize + nLen > nCaps)
+			{
+				it->second->vecData.reserve(nSize + nLen + BUFFER_STEP_SIZE);
+			}
+
+			it->second->vecData.resize(nSize + nLen);
+			memcpy(&(it->second->vecData[nSize]),ptr,nLen);
+		}
+	}
+}
+
+bool DownloadManagerImpl::StopTask( TaskID taskID )
+{
+	TaskDataMap::iterator it = mmTasks.find(taskID);
+
+	if (it != mmTasks.end())
+	{
+		if (it->second->spTask)
+		{
+			it->second->spTask->cancel();
+			return true;
+		}
+	}	
+
+	return false;
+}
+
+void DownloadManagerImpl::ParamAlloc( unsigned int nEvent, unsigned int nSubEvent, void** param1, void** param2 )
+{
+	switch (nEvent)
+	{
+	//case EVENT_DOWNLOADMANAGER_PROGRESS:
+	//	*param2 = reinterpret_cast<void*>(new DownloadProgress());
+	//	break;
+	case MSG_COMPLETE_BUFFER:
+		*param2 = AllocCompleteBuffer(*param1);
+		break;
+	case MSG_COMPLETE_FILE:
+		*param2 = AllocCompleteBuffer(*param1);
+		break;
+	}
+}
+
+void DownloadManagerImpl::ParamFree( unsigned int nEvent, unsigned int nSubEvent, void* param1, void* param2 )
+{
+	switch (nEvent)
+	{
+	//case EVENT_DOWNLOADMANAGER_PROGRESS:
+	//	if (param2)
+	//	{
+	//		delete param2;
+	//	}	
+	//	break;
+	case MSG_COMPLETE_BUFFER || MSG_COMPLETE_FILE:
+		{
+			DownloadData* pData = reinterpret_cast<DownloadData*>(param2);
+			if (pData)
+			{
+				if (pData->ptr)
+				{
+					delete []pData;
+				}
+
+				delete pData;
+			}
+		}
+		break;
+	}
+}
+
+DownloadManagerImpl::DownloadManagerImpl( void )
+{
+
+}

+ 72 - 0
DownloadManagerImpl.h

@@ -0,0 +1,72 @@
+#ifndef COMMON_DOWNLOADMANAGERIMPL_H_
+#define COMMON_DOWNLOADMANAGERIMPL_H_
+
+#include "DownloadManager.h"
+#include "../common/URLEngine/UEFactory.h"
+#include <vector>
+#include <map>
+#include <Windows.h>
+
+using namespace nsURLEngine;
+
+class DownloadManagerImpl : 
+	public DownloadManager,
+	public nsURLEngine::IUETaskCallback,
+	public ParamConstructor
+{
+	struct TaskData{
+		IUETaskPtr spTask;
+		std::string strFile;
+		std::vector<unsigned char> vecData;
+	};
+
+	typedef boost::shared_ptr<TaskData> TaskDataPtr;
+	typedef std::map<TaskID, TaskDataPtr> TaskDataMap;
+public:
+	~DownloadManagerImpl(void);
+	static DownloadManagerImpl& getInstance(void)
+	{
+		static DownloadManagerImpl s_instance;
+		return s_instance;
+	}
+
+	virtual TaskID CreateTask(TaskInitData* pInit);
+	virtual bool StartTask(TaskID taskID);
+	virtual bool StopTask(TaskID taskID);
+
+	void init(HWND hWnd);
+	void uninit(void);
+
+	//任务进度回调
+	virtual void OnTaskProgress(double fNow,double fTotal,UETaskID taskid);
+	//任务事件回调
+	virtual void OnTaskEvent(emTaskEvent event,emEngineErrCode errCode,UETaskID taskid);
+	//任务数据回调
+	virtual void OnTaskData(UEVoidPtr ptr,unsigned int nLen,UETaskID taskid);
+
+	virtual void ParamAlloc(
+		unsigned int nEvent,
+		unsigned int nSubEvent,
+		void** param1,
+		void** param2
+		);
+	virtual void ParamFree(
+		unsigned int nEvent,
+		unsigned int nSubEvent,
+		void* param1,
+		void* param2
+		);
+
+protected:
+	void* AllocCompleteBuffer(TaskID taskID);
+
+private:
+	TaskDataMap mmTasks;
+	IUETaskManagerPtr mspTaskManager;
+	HWND m_hParent;
+	DownloadManagerImpl(void);
+};
+
+#define GetDownloadManager() DownloadManagerImpl::getInstance()
+
+#endif //COMMON_DOWNLOADMANAGERIMPL_H_

+ 63 - 0
LogSetting.cpp

@@ -0,0 +1,63 @@
+// LogSetting.cpp : 实现文件
+//
+
+#include "stdafx.h"
+#include "YAServer.h"
+#include "LogSetting.h"
+#include "afxdialogex.h"
+
+
+// CLogSetting 对话框
+
+IMPLEMENT_DYNAMIC(CLogSetting, CDialogEx)
+
+CLogSetting::CLogSetting(CWnd* pParent /*=NULL*/)
+	: CDialogEx(CLogSetting::IDD, pParent)
+	, m_log_status(FALSE)
+	, m_log_raw_data(FALSE)
+	, m_log_parse_data(FALSE)
+	, m_log_send_event(FALSE)
+	, m_log_rev_pakage(FALSE)
+{
+	m_log_status = theApp.log_status;
+	m_log_raw_data = theApp.log_raw_data;
+	m_log_parse_data = theApp.log_parse_data;
+	m_log_rev_pakage = theApp.log_rev_pakage;
+	m_log_send_event = theApp.log_send_event;
+}
+
+CLogSetting::~CLogSetting()
+{
+}
+
+void CLogSetting::DoDataExchange(CDataExchange* pDX)
+{
+	CDialogEx::DoDataExchange(pDX);
+	DDX_Check(pDX, IDC_CHECK2, m_log_status);
+	DDX_Check(pDX, IDC_CHECK1, m_log_raw_data);
+	DDX_Check(pDX, IDC_CHECK3, m_log_parse_data);
+	DDX_Check(pDX, IDC_CHECK5, m_log_send_event);
+	DDX_Check(pDX, IDC_CHECK4, m_log_rev_pakage);
+}
+
+
+BEGIN_MESSAGE_MAP(CLogSetting, CDialogEx)
+	ON_BN_CLICKED(IDOK, &CLogSetting::OnBnClickedOk)
+END_MESSAGE_MAP()
+
+
+// CLogSetting 消息处理程序
+
+
+void CLogSetting::OnBnClickedOk()
+{
+	UpdateData(TRUE);
+	theApp.log_status = m_log_status;
+	theApp.log_raw_data = m_log_raw_data;
+	theApp.log_parse_data = m_log_parse_data;
+	theApp.log_rev_pakage = m_log_rev_pakage;
+	theApp.log_send_event = m_log_send_event;
+
+	theApp.save_log_conf();
+	CDialogEx::OnOK();
+}

+ 28 - 0
LogSetting.h

@@ -0,0 +1,28 @@
+#pragma once
+
+
+// CLogSetting 对话框
+
+class CLogSetting : public CDialogEx
+{
+	DECLARE_DYNAMIC(CLogSetting)
+
+public:
+	CLogSetting(CWnd* pParent = NULL);   // 标准构造函数
+	virtual ~CLogSetting();
+
+// 对话框数据
+	enum { IDD = IDD_LOGSETTING };
+
+protected:
+	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持
+
+	DECLARE_MESSAGE_MAP()
+public:
+	BOOL m_log_status;
+	BOOL m_log_raw_data;
+	BOOL m_log_parse_data;
+	BOOL m_log_send_event;
+	BOOL m_log_rev_pakage;
+	afx_msg void OnBnClickedOk();
+};

+ 305 - 0
MysqlConnPool.cpp

@@ -0,0 +1,305 @@
+#include "StdAfx.h"
+#include "MysqlConnPool.h"
+
+
+CMysqlConnPool::CMysqlConnPool()
+{
+	m_nMinCount = 3;
+	m_nMaxCount = 12;
+	m_bNeedStop = FALSE;
+	m_bNeedConnection = FALSE;
+	m_hMaintanceThread = INVALID_HANDLE_VALUE;
+
+	m_hMaintanceThread = CreateEvent(NULL, TRUE, FALSE, _T("DataConnPool"));
+	// 划定临界区
+	InitializeCriticalSection(&m_csIdleConnList);
+	InitializeCriticalSection(&m_csBusyConnList);
+}
+
+
+CMysqlConnPool::~CMysqlConnPool()
+{
+	m_hMaintanceThread = INVALID_HANDLE_VALUE;
+	m_bNeedStop = TRUE;
+	CloseHandle(m_hHaveData);
+	CloseHandle(m_hMaintanceThread);
+
+	DeleteCriticalSection(&m_csIdleConnList);
+	DeleteCriticalSection(&m_csBusyConnList);
+}
+
+int CMysqlConnPool::InitAllConn()
+{
+	CloseAllConn();
+	// 按照最小数量创建
+	//CMysqlConn * pMysqlConn = NULL;
+	int nCount = 0;
+	for(unsigned int i = 0; i < m_nMinCount; i++)
+	{
+		nCount = InitNewConn();
+	}
+
+	// 创建守护线程,用来进行维护工作
+	if(INVALID_HANDLE_VALUE == m_hMaintanceThread)
+	{
+		m_hMaintanceThread = CreateThread(NULL, NULL, thread_run, (LPVOID)this, 0, NULL);
+	}
+	return nCount;
+}
+
+void CMysqlConnPool::CloseAllConn()
+{
+	// 销毁数据连接,使用大锁
+	EnterCriticalSection(&m_csIdleConnList);
+	DBConnectList::iterator itIdle = m_listIdleConnection.begin();
+	for (; itIdle != m_listIdleConnection.end(); ++itIdle)
+	{
+		if(NULL != (*itIdle)){
+			(*itIdle)->Close();
+			delete (*itIdle);
+		}
+
+		//m_listIdleConnection.erase(itIdle);
+	}
+	LeaveCriticalSection(&m_csIdleConnList);
+	
+	// 使用中的链接
+	EnterCriticalSection(&m_csBusyConnList);
+	DBConnectList::iterator itBusy = m_listBusyConnection.begin();
+	for(; itBusy != m_listBusyConnection.end(); ++itBusy)
+	{
+		if(NULL != (*itBusy))
+		{
+			(*itBusy)->Close();
+			delete(*itBusy);
+		}
+		// m_listBusyConnection.erase(itBusy);
+	}
+	LeaveCriticalSection(&m_csBusyConnList);
+}
+
+CMysqlConn* CMysqlConnPool::GetNewConn()
+{
+	CMysqlConn * pDBEngine = NULL;
+	// 做一个循环,反复尝试五次取连接,每次间隔1秒钟
+	int nTimes = 0;
+	while ((m_listIdleConnection.size() <= 0) && (nTimes < 5))
+	{
+		Sleep(1000);
+		nTimes++;
+	}
+	if (5 == nTimes)
+	{
+		// 这样狼狈的进来肯定是没有可用连接了,记录日志退出
+		// g_pSvrLog->AddRunLog(LL_ERROR, _T("Waiting for a connection for a long time, but failed."));
+		return pDBEngine;
+	}
+	// 从空闲队列中取出,并且加入到使用队列中
+	EnterCriticalSection(&m_csIdleConnList);
+	if (m_listIdleConnection.size() > 0)
+	{
+		pDBEngine = m_listIdleConnection.front();
+		m_listIdleConnection.pop_front();
+		// 加入使用的连接队列
+		EnterCriticalSection(&m_csBusyConnList);
+		m_listBusyConnection.push_back(pDBEngine);
+		LeaveCriticalSection(&m_csBusyConnList);
+	}
+	LeaveCriticalSection(&m_csIdleConnList);
+	if (m_listIdleConnection.size() <= 1)
+	{
+		// 剩余空闲连接的数目小于等于1个时候需要检查开始创建
+		if ((m_listIdleConnection.size() + m_listBusyConnection.size()) < m_nMaxCount)
+		{
+			// 还小于最大限制,可以创建
+			SetEvent(m_hHaveData);
+			m_bNeedConnection = TRUE;
+		}
+		else
+		{
+			// 超出限制了,做个记录吧
+			//g_pSvrLog->AddRunLog(LL_ERROR, _T("Database connection reached max count."));
+		}
+	}
+	return pDBEngine;
+}
+
+int CMysqlConnPool::RestoreConn( CMysqlConn* pDBEngine )
+{
+	if (NULL != pDBEngine)
+	{
+		// 从使用中的队列取出
+		EnterCriticalSection(&m_csBusyConnList);
+		m_listBusyConnection.remove(pDBEngine);
+		LeaveCriticalSection(&m_csBusyConnList);
+		// 加入到空闲队列中
+		EnterCriticalSection(&m_csIdleConnList);
+		m_listIdleConnection.push_back(pDBEngine);
+		LeaveCriticalSection(&m_csIdleConnList);
+	}
+	EnterCriticalSection(&m_csIdleConnList);
+	int nCount = m_listIdleConnection.size();
+	LeaveCriticalSection(&m_csIdleConnList);
+	return nCount;
+}
+
+void CMysqlConnPool::Init(const char* szOption, const char *szHost, const char *szUser, const char *szPwd, const char *szDbName, unsigned int nPort, const char * szUnixSocket, unsigned long nClientFlag )
+{
+	m_strOption = szOption;
+	m_strHost = szHost;
+	m_strUser = szUser;
+	m_strPwd = szPwd;
+	m_strDbName = szDbName;
+	m_nPort = nPort;
+	if(szUnixSocket != NULL){
+		m_strUnixSocket = szUnixSocket;
+	}
+	m_nClientFlag = nClientFlag;
+}
+
+int CMysqlConnPool::InitNewConn()
+{
+	bool bSuccess = false;
+	CMysqlConn * pDBEngine = new CMysqlConn(m_strOption.c_str(), m_strHost.c_str(), m_strUser.c_str(), m_strPwd.c_str(), m_strDbName.c_str(), 
+		m_nPort, m_strUnixSocket.c_str(), m_nClientFlag, bSuccess);
+	if (bSuccess)
+	{
+		m_bNeedConnection = FALSE;
+		return RestoreConn(pDBEngine);
+	}
+	else
+	{
+		delete pDBEngine;
+		return m_listIdleConnection.size();
+	}
+}
+
+void CMysqlConnPool::CloseConn( CMysqlConn* pDBEngine )
+{
+	pDBEngine->Close();
+	// 从空闲队列将其删除
+	EnterCriticalSection(&m_csIdleConnList);
+	m_listIdleConnection.remove(pDBEngine);
+	LeaveCriticalSection(&m_csIdleConnList);
+}
+
+void CMysqlConnPool::StopThread()
+{
+	m_bNeedStop = TRUE;
+	// 因为线程是无限制等待信号的,所以这里先把标志位置为停止,然后发信号让线程检测
+	SetEvent(m_hHaveData);
+	// 等待退出
+	WaitForSingleObject(m_hMaintanceThread, INFINITE);
+	CloseHandle(m_hMaintanceThread);
+}
+
+BOOL CMysqlConnPool::IsNeedStop()
+{
+	return m_bNeedStop;
+}
+
+BOOL CMysqlConnPool::IsNeedConnection()
+{
+	return m_bNeedConnection;
+}
+
+DWORD WINAPI CMysqlConnPool::thread_run( LPVOID pdata )
+{
+	CMysqlConnPool * pConPool = (CMysqlConnPool *) pdata;
+	while (!pConPool->IsNeedStop())
+	{
+		// 设置事件为无信号, 并且无限制等待
+		ResetEvent(pConPool->m_hHaveData);  
+		WaitForSingleObject(pConPool->m_hHaveData, INFINITE);
+		if (pConPool->IsNeedConnection())
+		{
+			// g_pSvrLog->AddRunLog(LL_DEBUG, _T("Create a new DB connection."));
+			pConPool->InitNewConn();
+		}
+	}
+	return 0;
+}
+
+CMysqlConn::CMysqlConn( const char *option, const char *host, const char *user, const char *password, 
+	const char* dbname, unsigned int port, const char *unix_socket, unsigned long clientflag, bool &state )
+{
+	m_option = option;
+	m_host = host;
+	m_user = user;
+	m_pwd = password;
+	m_db = dbname;
+	m_port = port;
+	m_unix_socket = unix_socket;
+	m_clientflag = clientflag;
+
+	m_bOpen = false;
+
+	m_pConn = mysql_init(NULL);
+
+	if( 0 == SetOption())
+	{
+		if(0 == Open())
+		{
+			state = true;
+		}else{
+			state = false;
+		}
+	}else{
+		state = false;
+	}
+}
+
+CMysqlConn::~CMysqlConn()
+{
+	Close();
+}
+
+int CMysqlConn::SetOption()
+{
+	if(mysql_options(m_pConn, MYSQL_SET_CHARSET_NAME, m_option))
+		return 1;
+	return 0;
+}
+
+int CMysqlConn::Open()
+{
+	HRESULT hr = ::CoInitialize(NULL);
+	if(FAILED(hr))
+		return -1;
+
+	if(!mysql_real_connect(m_pConn, m_host, m_user, m_pwd, m_db, m_port, m_unix_socket, m_clientflag))
+		return 1;
+
+	m_bOpen = true;
+	return 0;
+}
+
+int CMysqlConn::Close()
+{
+	if (m_bOpen)
+	{
+		mysql_close(m_pConn);
+		::CoUninitialize();
+		m_bOpen = false;
+	}
+
+	return 0;
+}
+
+bool CMysqlConn::IsOpen() const
+{
+	return m_bOpen;
+}
+
+MYSQL_RES * CMysqlConn::Execute( const char * strSQL,int &err)
+{
+	MYSQL_RES * pRes;
+	int _error = mysql_query(m_pConn, strSQL);
+	err = _error;
+	if(_error){
+		return NULL;
+	}
+
+	pRes = mysql_use_result(m_pConn);
+	return pRes;
+}

+ 135 - 0
MysqlConnPool.h

@@ -0,0 +1,135 @@
+#ifndef YASERVER_MYSQLCONNPOOL_H_
+#define YASERVER_MYSQLCONNPOOL_H_
+
+#include <mysql.h>
+#include <list>
+
+using namespace std;
+
+class CMysqlConn{
+public:
+	CMysqlConn(const char *option, const char *host, const char *user,
+		const char *password, const char* dbname, unsigned int port, 
+		const char *unix_socket, unsigned long clientflag, bool &state);
+	virtual ~CMysqlConn();
+public:
+	// 连接到数据库
+	int SetOption();
+	int Open();
+	// 关闭数据库clei
+	int Close();
+	// 数据库是否已连接
+	bool IsOpen() const;
+	// query
+
+	MYSQL_RES * Execute(const char * strSQL, int &err);
+
+private:
+	MYSQL * m_pConn;
+	bool m_bValid; // 已被初始化成功标识
+	bool m_bOpen;
+
+	const char * m_option;
+	const char * m_host;
+	const char * m_user;
+	const char * m_pwd;
+	const char * m_db;
+	unsigned int m_port;
+	const char * m_unix_socket;
+	unsigned long m_clientflag;
+};
+
+typedef std::list<CMysqlConn*> DBConnectList;
+
+class CMysqlConnPool
+{
+public:
+	// 获取实例指针
+	static CMysqlConnPool &Instanse(){
+		static CMysqlConnPool m_pInstanse;
+		return m_pInstanse;
+	};
+
+	// 初始化所有连接
+	int InitAllConn();
+
+	// 关闭所有连接
+	void CloseAllConn();
+	// 获取一个空闲连接
+	CMysqlConn* GetNewConn();
+	// 交还连接给空闲队列
+	int RestoreConn(CMysqlConn* pDBEngine);
+	void Init(const char* szOption, const char *szHost, const char *szUser, const char *szPwd, const char *szDbName,
+		unsigned int nPort, const char * szUnixSocket, unsigned long nClientFlag);
+private:
+	// 唯一实例
+	CMysqlConnPool();
+	virtual ~CMysqlConnPool();
+	// 创建一个连接
+	int InitNewConn();
+	// 关闭一个连接
+	void CloseConn(CMysqlConn* pDBEngine);
+	// 停止工作线程
+	void StopThread();
+
+	// 判断是否需要停止
+	BOOL IsNeedStop();
+	BOOL IsNeedConnection();
+	// 将守卫类作为连接池类的友元类
+	friend class CDBConnGuard;
+
+	// 空闲数据库连接队列
+	DBConnectList m_listIdleConnection;
+	// 在使用的数据库连接
+	DBConnectList m_listBusyConnection;
+
+	// 队列保护的临界区
+	CRITICAL_SECTION m_csIdleConnList;
+	CRITICAL_SECTION m_csBusyConnList;
+
+	// 可用连接总数的三个指标:最大、最小
+	unsigned int m_nMaxCount;
+	unsigned int m_nMinCount;
+
+	// 数据库信息
+	std::string m_strHost;
+	std::string m_strUser;
+	std::string m_strPwd;
+	std::string m_strUnixSocket;
+	std::string m_strOption;
+	std::string m_strDbName;
+	//const char * m_strHost;
+	//const char * m_strUser;
+	//const char * m_strPwd;
+	//const char * m_strUnixSocket;
+	//const char * m_strOption;
+	//const char * m_strDbName;
+	unsigned int m_nPort;
+	unsigned long m_nClientFlag;
+
+	// 维护线程
+	HANDLE m_hMaintanceThread; // 线程句柄
+	HANDLE m_hHaveData; // 信号
+
+	BOOL m_bNeedStop; // 管理线程起停的标志位
+	BOOL m_bNeedConnection; // 需要创建连接的标志
+	static DWORD WINAPI thread_run( LPVOID pdata);
+};
+
+class CDBConnGuard{
+public:
+	CDBConnGuard(CMysqlConn* &pDbConn){
+		pDbConn = CMysqlConnPool::Instanse().GetNewConn();
+		m_pDbConn = pDbConn;
+	}
+	virtual ~CDBConnGuard()
+	{
+		CMysqlConnPool::Instanse().RestoreConn(m_pDbConn);
+	}
+private:
+	CMysqlConn * m_pDbConn;
+};
+
+#define GetConnPool() CMysqlConnPool::Instanse()
+
+#endif //YASERVER_MYSQLCONNPOOL_H_

+ 77 - 0
ReadMe.txt

@@ -0,0 +1,77 @@
+================================================================================
+MICROSOFT 基础类库: YAServer 项目概述
+===============================================================================
+
+应用程序向导已为您创建了这个 YAServer 应用程序。此应用程序不仅演示 Microsoft 基础类的基本使用方法,还可作为您编写应用程序的起点。
+
+本文件概要介绍组成 YAServer 应用程序的每个文件的内容。
+
+YAServer.vcxproj
+这是使用应用程序向导生成的 VC++ 项目的主项目文件。 
+它包含生成该文件的 Visual C++ 的版本信息,以及有关使用应用程序向导选择的平台、配置和项目功能的信息。
+
+YAServer.vcxproj.filters
+    这是使用“应用程序向导”生成的 VC++ 项目筛选器文件。
+    它包含有关项目文件与筛选器之间的关联信息。在 IDE 中,通过这种关联,在特定节点下以分组形式显示具有相似扩展名的文件。例如,“.cpp”文件与“源文件”筛选器关联。
+
+YAServer.h
+这是应用程序的主要头文件。它包括其他项目特定的头文件(包括 Resource.h),并声明 CYAServerApp 应用程序类。
+
+YAServer.cpp
+这是包含应用程序类 CYAServerApp 的主要应用程序源文件。
+
+YAServer.rc
+这是程序使用的所有 Microsoft Windows 资源的列表。它包括 RES 子目录中存储的图标、位图和光标。此文件可以直接在 Microsoft Visual C++ 中进行编辑。项目资源位于 2052 中。
+
+res\YAServer.ico
+这是用作应用程序图标的图标文件。此图标包括在主要资源文件 YAServer.rc 中。
+
+res\YAServer.rc2
+此文件包含不在 Microsoft Visual C++ 中进行编辑的资源。您应该将不可由资源编辑器编辑的所有资源放在此文件中。
+
+
+/////////////////////////////////////////////////////////////////////////////
+
+应用程序向导创建一个对话框类:
+
+YAServerDlg.h,YAServerDlg.cpp - 对话框
+这些文件包含 CYAServerDlg 类。该类定义应用程序主对话框的行为。该对话框的模板位于 YAServer.rc 中,该文件可以在 Microsoft Visual C++ 中进行编辑。
+
+
+/////////////////////////////////////////////////////////////////////////////
+
+其他功能:
+
+ActiveX 控件
+应用程序包括对使用 ActiveX 控件的支持。
+
+Windows Sockets
+应用程序支持通过 TCP/IP 网络建立通信。
+
+/////////////////////////////////////////////////////////////////////////////
+
+其他标准文件:
+
+StdAfx.h,StdAfx.cpp
+这些文件用于生成名为 YAServer.pch 的预编译头 (PCH) 文件和名为 StdAfx.obj 的预编译类型文件。
+
+Resource.h
+这是标准头文件,它定义新的资源 ID。
+Microsoft Visual C++ 读取并更新此文件。
+
+YAServer.manifest
+	应用程序清单文件供 Windows XP 用来描述应用程序
+	对特定版本并行程序集的依赖性。加载程序使用此
+	信息从程序集缓存加载适当的程序集或
+	从应用程序加载私有信息。应用程序清单可能为了重新分发而作为
+	与应用程序可执行文件安装在相同文件夹中的外部 .manifest 文件包括,
+	也可能以资源的形式包括在该可执行文件中。 
+/////////////////////////////////////////////////////////////////////////////
+
+其他注释:
+
+应用程序向导使用“TODO:”指示应添加或自定义的源代码部分。
+
+如果应用程序在共享的 DLL 中使用 MFC,则需要重新发布这些 MFC DLL;如果应用程序所用的语言与操作系统的当前区域设置不同,则还需要重新发布对应的本地化资源 MFC100XXX.DLL。有关这两个主题的更多信息,请参见 MSDN 文档中有关 Redistributing Visual C++ applications (重新发布 Visual C++ 应用程序)的章节。
+
+/////////////////////////////////////////////////////////////////////////////

+ 28 - 0
ServerSockert.cpp

@@ -0,0 +1,28 @@
+// ServerSockert.cpp : ʵÏÖÎļþ
+//
+
+#include "stdafx.h"
+#include "YAServer.h"
+#include "ServerSockert.h"
+#include "YAServerDlg.h"
+
+// CServerSockert
+
+CServerSockert::CServerSockert( CYAServerDlg* pDlg )
+{
+	m_pDlg = pDlg;
+}
+
+CServerSockert::~CServerSockert()
+{
+}
+
+void CServerSockert::OnAccept( int nErrorCode )
+{
+	CAsyncSocket::OnAccept(nErrorCode);
+	m_pDlg->parse_accept();
+}
+
+// CServerSockert ³ÉÔ±º¯Êý
+
+IMPLEMENT_DYNAMIC(CServerSockert, CAsyncSocket);

+ 24 - 0
ServerSockert.h

@@ -0,0 +1,24 @@
+#ifndef YASERVER_SERVERSOCKET_H_
+#define YASERVER_SERVERSOCKET_H_
+
+class CYAServerDlg;
+// CServerSockert ÃüÁîÄ¿±ê
+
+class CServerSockert : public CAsyncSocket
+{
+	DECLARE_DYNAMIC(CServerSockert);
+private:
+	CServerSockert(const CServerSockert& rSrc);
+	void operator=(const CServerSockert& rSrc);
+
+public:
+	CServerSockert(CYAServerDlg* pDlg);
+	virtual ~CServerSockert();
+
+	CYAServerDlg* m_pDlg;
+protected:
+	virtual void OnAccept(int nErrorCode);
+
+};
+
+#endif //YASERVER_SERVERSOCKET_H_

+ 104 - 0
SysSetting.cpp

@@ -0,0 +1,104 @@
+// SysSetting.cpp : 实现文件
+//
+
+#include "stdafx.h"
+#include "YAServer.h"
+#include "SysSetting.h"
+#include "afxdialogex.h"
+#include "Functions/Functions.h"
+
+// CSysSetting 对话框
+
+IMPLEMENT_DYNAMIC(CSysSetting, CDialogEx)
+
+	CSysSetting::CSysSetting(CWnd* pParent /*=NULL*/)
+	: CDialogEx(CSysSetting::IDD, pParent)
+	, m_host_master(_T(""))
+	, m_recon_server(0)
+	, m_host_slave(_T(""))
+	, m_recon_db(0)
+	, m_reader_lost(0)
+	, m_card_lost(0)
+	, m_timing_interval(0)
+	, m_coor_error(0)
+	, m_ranging_error(0)
+	, m_move_error(0)
+	, m_sampling_interval(0)
+	, m_use_filter(FALSE)
+	, m_db_z_offset(0)
+{
+	m_host_master = CFunctions::c2wc(theApp.ws_url.c_str());
+	m_host_slave = CFunctions::c2wc(theApp.ws_url_bk.c_str());
+	m_recon_db = theApp.recon_db;
+	m_recon_server = theApp.recon_server;
+	m_reader_lost = theApp.reader_lost;
+	m_card_lost = theApp.card_lost;
+	m_timing_interval = theApp.timing_interval;
+	m_sampling_interval = theApp.sampling_interval;
+	m_coor_error = theApp.coor_error;
+	m_ranging_error = theApp.ranging_error;
+	m_move_error = theApp.move_error;
+	m_use_filter = theApp.use_filter;
+	m_db_z_offset = theApp.z_offset;
+}
+
+CSysSetting::~CSysSetting()
+{
+}
+
+void CSysSetting::DoDataExchange(CDataExchange* pDX)
+{
+	CDialogEx::DoDataExchange(pDX);
+	DDX_Text(pDX, IDC_EDIT1, m_host_master);
+	DDV_MaxChars(pDX, m_host_master, 255);
+	DDX_Text(pDX, IDC_EDIT15, m_recon_server);
+	DDX_Text(pDX, IDC_EDIT5, m_host_slave);
+	DDX_Text(pDX, IDC_EDIT13, m_recon_db);
+	DDX_Text(pDX, IDC_EDIT8, m_reader_lost);
+	DDV_MinMaxInt(pDX, m_reader_lost, 15, 7200);
+	DDX_Text(pDX, IDC_EDIT10, m_card_lost);
+	DDX_Text(pDX, IDC_EDIT11, m_timing_interval);
+	DDX_Text(pDX, IDC_EDIT9, m_coor_error);
+	DDX_Text(pDX, IDC_EDIT14, m_ranging_error);
+	DDX_Text(pDX, IDC_EDIT7, m_move_error);
+	DDX_Text(pDX, IDC_EDIT12, m_sampling_interval);
+	DDX_Check(pDX, IDC_CHECK2, m_use_filter);
+	DDX_Text(pDX, IDC_EDIT16, m_db_z_offset);
+}
+
+
+BEGIN_MESSAGE_MAP(CSysSetting, CDialogEx)
+	ON_BN_CLICKED(IDOK, &CSysSetting::OnBnClickedOk)
+END_MESSAGE_MAP()
+
+BOOL CSysSetting::OnInitDialog()
+{
+	CDialog::OnInitDialog();
+
+	return TRUE;
+}
+
+
+// CSysSetting 消息处理程序
+
+
+void CSysSetting::OnBnClickedOk()
+{
+	UpdateData();
+	theApp.ws_url = CFunctions::wc2c(m_host_master);
+	theApp.ws_url_bk = CFunctions::wc2c(m_host_slave);
+	theApp.recon_db = m_recon_db;
+	theApp.recon_server = m_recon_server;
+	theApp.reader_lost = m_reader_lost;
+	theApp.card_lost = m_card_lost;
+	theApp.timing_interval = m_timing_interval;
+	theApp.sampling_interval = m_sampling_interval;
+	theApp.coor_error = m_coor_error;
+	theApp.ranging_error = m_ranging_error;
+	theApp.move_error = m_move_error;
+	theApp.use_filter = m_use_filter;
+	theApp.z_offset = m_db_z_offset;
+
+	theApp.save_sys_conf();
+	CDialogEx::OnOK();
+}

+ 38 - 0
SysSetting.h

@@ -0,0 +1,38 @@
+#pragma once
+
+
+// CSysSetting 对话框
+
+class CSysSetting : public CDialogEx
+{
+	DECLARE_DYNAMIC(CSysSetting)
+
+public:
+	CSysSetting(CWnd* pParent = NULL);   // 标准构造函数
+	virtual ~CSysSetting();
+
+// 对话框数据
+	enum { IDD = IDD_SYSSETTING };
+
+protected:
+	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持
+	virtual BOOL OnInitDialog();
+
+	DECLARE_MESSAGE_MAP()
+public:
+	CString m_host_master;
+	int m_recon_server;
+	CString m_host_slave;
+	int m_recon_db;
+	int m_reader_lost;
+	int m_card_lost;
+	int m_timing_interval;
+	double m_coor_error;
+	double m_ranging_error;
+	double m_move_error;
+	double m_sampling_interval;
+	BOOL m_use_filter;
+
+	afx_msg void OnBnClickedOk();
+	double m_db_z_offset;
+};

BIN
YAServer.aps


+ 291 - 0
YAServer.cpp

@@ -0,0 +1,291 @@
+
+// YAServer.cpp : 定义应用程序的类行为。
+//
+
+#include "stdafx.h"
+#include "YAServer.h"
+#include "YAServerDlg.h"
+#include "def.h"
+#include "INIFILE.h"
+#include "Functions/Functions.h"
+
+#ifdef _DEBUG
+#define new DEBUG_NEW
+#endif
+
+// CYAServerApp
+
+BEGIN_MESSAGE_MAP(CYAServerApp, CWinApp)
+	ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
+END_MESSAGE_MAP()
+
+
+// CYAServerApp 构造
+
+CYAServerApp::CYAServerApp()
+{
+	// 支持重新启动管理器
+	m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART;
+
+	// TODO: 在此处添加构造代码,
+	// 将所有重要的初始化放置在 InitInstance 中
+}
+
+
+// 唯一的一个 CYAServerApp 对象
+
+CYAServerApp theApp;
+
+
+// CYAServerApp 初始化
+
+BOOL CYAServerApp::InitInstance()
+{
+	// 如果一个运行在 Windows XP 上的应用程序清单指定要
+	// 使用 ComCtl32.dll 版本 6 或更高版本来启用可视化方式,
+	//则需要 InitCommonControlsEx()。否则,将无法创建窗口。
+
+	CreateMutex(NULL, FALSE, _T("MyMux"));
+	if(GetLastError() == ERROR_ALREADY_EXISTS){
+		HWND hWnd = ::FindWindow(NULL, _T("永安信通数据采集系统"));
+		::PostMessage(hWnd, WM_QUIT, 0, 0);
+		//caption改为你窗口的具体caption
+		//::ShowWindow(hWnd,SW_SHOW);
+		//::SetForegroundWindow(hWnd); // 激活
+		//return FALSE;
+	}
+
+	INITCOMMONCONTROLSEX InitCtrls;
+	InitCtrls.dwSize = sizeof(InitCtrls);
+	// 将它设置为包括所有要在应用程序中使用的
+	// 公共控件类。
+	InitCtrls.dwICC = ICC_WIN95_CLASSES;
+	InitCommonControlsEx(&InitCtrls);
+
+	CWinApp::InitInstance();
+	
+	AfxEnableControlContainer();
+
+	// 创建 shell 管理器,以防对话框包含
+	// 任何 shell 树视图控件或 shell 列表视图控件。
+	CShellManager *pShellManager = new CShellManager;
+
+	// 标准初始化
+	// 如果未使用这些功能并希望减小
+	// 最终可执行文件的大小,则应移除下列
+	// 不需要的特定初始化例程
+	// 更改用于存储设置的注册表项
+	// TODO: 应适当修改该字符串,
+	// 例如修改为公司或组织名
+	SetRegistryKey(_T("应用程序向导生成的本地应用程序"));
+
+	init_param();
+	load_db_conf();
+	load_sys_conf();
+	load_log_conf();	
+
+	CYAServerDlg dlg;
+	m_pMainWnd = &dlg;
+	INT_PTR nResponse = dlg.DoModal();
+	if (nResponse == IDOK)
+	{
+		// TODO: 在此放置处理何时用
+		//  “确定”来关闭对话框的代码
+	}
+	else if (nResponse == IDCANCEL)
+	{
+		// TODO: 在此放置处理何时用
+		//  “取消”来关闭对话框的代码
+	}
+
+	// 删除上面创建的 shell 管理器。
+	if (pShellManager != NULL)
+	{
+		delete pShellManager;
+	}
+
+	// 由于对话框已关闭,所以将返回 FALSE 以便退出应用程序,
+	//  而不是启动应用程序的消息泵。
+	return FALSE;
+}
+
+void CYAServerApp::writeini( string section, string key, string value )
+{
+	WritePrivateProfileStringA(section.c_str(), key.c_str(), value.c_str(), FILEPATH_SERVER_CONFIG);
+}
+
+void CYAServerApp::load_db_conf()
+{
+	IniFile ini;
+	if(ini.open(FILEPATH_SERVER_CONFIG)){
+		dbhost = ini.read(CONF_SECT_DB, CONF_DB_KEY_HOST);
+		dbuser = ini.read(CONF_SECT_DB, CONF_DB_KEY_USER);
+		dbpwd = ini.read(CONF_SECT_DB, CONF_DB_KEY_PWD);
+		dbname = ini.read(CONF_SECT_DB, CONF_DB_KEY_DBNAME);
+		dbbackup = ini.read(CONF_SECT_DB, CONF_DB_KEY_DB_BACKUP);
+		dbport = atoi(ini.read(CONF_SECT_DB, CONF_DB_KEY_PORT).c_str());
+		dbencoding = ini.read(CONF_SECT_DB, CONF_DB_KEY_ENCODING);
+
+		dbhost_bk = ini.read(CONF_SECT_DB_BK, CONF_DB_KEY_HOST);
+		dbuser_bk = ini.read(CONF_SECT_DB_BK, CONF_DB_KEY_USER);
+		dbpwd_bk = ini.read(CONF_SECT_DB_BK, CONF_DB_KEY_PWD);
+		dbname_bk = ini.read(CONF_SECT_DB_BK, CONF_DB_KEY_DBNAME);
+		dbport_bk = atoi(ini.read(CONF_SECT_DB_BK, CONF_DB_KEY_PORT).c_str());
+		dbencoding_bk = ini.read(CONF_SECT_DB_BK, CONF_DB_KEY_ENCODING);
+	}
+}
+
+void CYAServerApp::save_db_conf()
+{
+	char t[20];
+	string s;
+	sprintf_s(t, "%d", dbport);
+	s = t;
+	writeini(CONF_SECT_DB, CONF_DB_KEY_HOST, dbhost);
+	writeini(CONF_SECT_DB, CONF_DB_KEY_USER, dbuser);
+	writeini(CONF_SECT_DB, CONF_DB_KEY_PWD, dbpwd);
+	writeini(CONF_SECT_DB, CONF_DB_KEY_DBNAME, dbname);
+	writeini(CONF_SECT_DB, CONF_DB_KEY_DB_BACKUP, dbbackup);
+	writeini(CONF_SECT_DB, CONF_DB_KEY_ENCODING, dbencoding);
+	writeini(CONF_SECT_DB, CONF_DB_KEY_PORT, s);
+
+	sprintf_s(t, "%d", dbport_bk);
+	s = t;
+	writeini(CONF_SECT_DB_BK, CONF_DB_KEY_HOST, dbhost_bk);
+	writeini(CONF_SECT_DB_BK, CONF_DB_KEY_USER, dbuser_bk);
+	writeini(CONF_SECT_DB_BK, CONF_DB_KEY_PWD, dbpwd_bk);
+	writeini(CONF_SECT_DB_BK, CONF_DB_KEY_DBNAME, dbname_bk);
+	writeini(CONF_SECT_DB_BK, CONF_DB_KEY_ENCODING, dbencoding_bk);
+	writeini(CONF_SECT_DB_BK, CONF_DB_KEY_PORT, s);
+}
+
+void CYAServerApp::load_sys_conf()
+{
+	locate_type = 0;
+	IniFile ini;
+	if(ini.open(FILEPATH_SERVER_CONFIG)){
+		ws_url = ini.read(CONF_SECT_SERVER_SETTING, CONF_SERVER_WS_URL);
+		ws_url_bk = ini.read(CONF_SECT_SERVER_SETTING, CONF_SERVER_WS_URL_BK);
+		use_filter = (atoi(ini.read(CONF_SECT_SERVER_SETTING, CONF_LOG_PARSE_DATA).c_str()) == 0 ? FALSE : TRUE);
+		recon_server = atoi(ini.read(CONF_SECT_SERVER_SETTING, CONF_SERVER_RECON_SERVER).c_str());
+		recon_db = atoi(ini.read(CONF_SECT_SERVER_SETTING, CONF_SERVER_RECON_DB).c_str());
+		reader_lost = atoi(ini.read(CONF_SECT_SERVER_SETTING, CONF_SERVER_READER_LOST).c_str());
+		card_lost = atoi(ini.read(CONF_SECT_SERVER_SETTING, CONF_SERVER_CARD_LOST).c_str());
+		timing_interval = atoi(ini.read(CONF_SECT_SERVER_SETTING, CONF_SERVER_TIMING_INTERVAL).c_str());
+		sampling_interval = atoi(ini.read(CONF_SECT_SERVER_SETTING, CONF_SERVER_SAMPLING_INTERVAL).c_str());
+		coor_error = atof(ini.read(CONF_SECT_SERVER_SETTING, CONF_SERVER_COORDINATE_ERROR).c_str());
+		ranging_error = atof(ini.read(CONF_SECT_SERVER_SETTING, CONF_SERVER_RANGING_ERROR).c_str());
+		move_error = atof(ini.read(CONF_SECT_SERVER_SETTING, CONF_SERVER_MOVING_ERROR).c_str());
+		z_offset = atof(ini.read(CONF_SECT_SERVER_SETTING, CONF_SERVER_Z_OFFSET).c_str());
+		locate_type = atoi(ini.read(CONF_SECT_SERVER_SETTING, CONF_SERVER_LOCATE_TYPE).c_str());
+
+		send_json_postion = atoi(ini.read(CONF_SECT_SERVER_SETTING, CONF_SEND_JSON_POSION).c_str());
+		send_json_counting = atoi(ini.read(CONF_SECT_SERVER_SETTING, CONF_SEND_JSON_COUNTING).c_str());
+		send_json_alarm = atoi(ini.read(CONF_SECT_SERVER_SETTING, CONF_SEND_JSON_ALARM).c_str());
+		send_json_device = atoi(ini.read(CONF_SECT_SERVER_SETTING, CONF_SEND_JSON_DEVICE).c_str());
+	}
+}
+
+void CYAServerApp::save_sys_conf()
+{
+	char t[20];
+	string s;
+	writeini(CONF_SECT_SERVER_SETTING, CONF_SERVER_WS_URL, ws_url);
+	writeini(CONF_SECT_SERVER_SETTING, CONF_SERVER_WS_URL_BK, ws_url_bk);
+	writeini(CONF_SECT_SERVER_SETTING, CONF_SERVER_USE_FILTER, use_filter ? "1" : "0");
+	sprintf_s(t, "%d", recon_server);
+	s = t;
+	writeini(CONF_SECT_SERVER_SETTING, CONF_SERVER_RECON_SERVER, s);
+	sprintf_s(t, "%d", recon_db);
+	s = t;
+	writeini(CONF_SECT_SERVER_SETTING, CONF_SERVER_RECON_DB, s);
+	sprintf_s(t, "%d", reader_lost);
+	s = t;
+	writeini(CONF_SECT_SERVER_SETTING, CONF_SERVER_READER_LOST, s);
+	sprintf_s(t, "%d", card_lost);
+	s = t;
+	writeini(CONF_SECT_SERVER_SETTING, CONF_SERVER_CARD_LOST, s);
+	sprintf_s(t, "%d", timing_interval);
+	s = t;
+	writeini(CONF_SECT_SERVER_SETTING, CONF_SERVER_TIMING_INTERVAL, s);
+	sprintf_s(t, "%d", sampling_interval);
+	s = t;
+	writeini(CONF_SECT_SERVER_SETTING, CONF_SERVER_SAMPLING_INTERVAL, s);
+	sprintf_s(t, "%f", z_offset);
+	s = t;
+	writeini(CONF_SECT_SERVER_SETTING, CONF_SERVER_Z_OFFSET, s);
+	sprintf_s(t, "%f", coor_error);
+	s = t;
+	writeini(CONF_SECT_SERVER_SETTING, CONF_SERVER_COORDINATE_ERROR, s);
+	sprintf_s(t, "%f", ranging_error);
+	s = t;
+	writeini(CONF_SECT_SERVER_SETTING, CONF_SERVER_RANGING_ERROR, s);
+	sprintf_s(t, "%f", move_error);
+	s = t;
+	writeini(CONF_SECT_SERVER_SETTING, CONF_SERVER_MOVING_ERROR, s);
+}
+
+void CYAServerApp::load_log_conf()
+{
+	IniFile ini;
+	if(ini.open(FILEPATH_SERVER_CONFIG)){
+		log_status = (atoi(ini.read(CONF_SECT_SERVER_LOG, CONF_LOG_SYS_STATUS).c_str()) == 0 ? FALSE : TRUE);
+		log_raw_data = (atoi(ini.read(CONF_SECT_SERVER_LOG, CONF_LOG_RAW_DATA).c_str()) == 0 ? FALSE : TRUE);
+		log_parse_data = (atoi(ini.read(CONF_SECT_SERVER_LOG, CONF_LOG_PARSE_DATA).c_str()) == 0 ? FALSE : TRUE);
+		log_send_event = (atoi(ini.read(CONF_SECT_SERVER_LOG, CONF_LOG_SEND_EVENT).c_str()) == 0 ? FALSE : TRUE);
+		log_rev_pakage = (atoi(ini.read(CONF_SECT_SERVER_LOG, CONF_LOG_REV_EVENT).c_str()) == 0 ? FALSE : TRUE);
+	}
+}
+
+void CYAServerApp::save_log_conf()
+{
+	writeini(CONF_SECT_SERVER_LOG, CONF_LOG_SYS_STATUS, log_status ? "1" : "0");
+	writeini(CONF_SECT_SERVER_LOG, CONF_LOG_RAW_DATA, log_raw_data ? "1" : "0");
+	writeini(CONF_SECT_SERVER_LOG, CONF_LOG_PARSE_DATA, log_parse_data ? "1" : "0");
+	writeini(CONF_SECT_SERVER_LOG, CONF_LOG_SEND_EVENT, log_send_event ? "1" : "0");
+	writeini(CONF_SECT_SERVER_LOG, CONF_LOG_REV_EVENT, log_rev_pakage ? "1" : "0");
+}
+
+void CYAServerApp::set_server_handle(HWND hwd)
+{
+	char t[20];
+	char szAppdir[MAX_PATH+1] = {0};
+	GetModuleFileNameA(NULL, szAppdir , MAX_PATH);
+	sprintf_s(t, "%d", DWORD(hwd));
+	writeini(CONF_SECT_MONITOR, CONF_MONITOR_SERVER_HANDLE, t);
+	writeini(CONF_SECT_MONITOR, CONF_MONITOR_SERVER_PATH, szAppdir);
+}
+
+void CYAServerApp::load_monitor_conf()
+{
+	IniFile ini;
+	if(ini.open(FILEPATH_SERVER_CONFIG)){
+		m_hwnd_monitor = HWND(atoi(ini.read(CONF_SECT_MONITOR, CONF_MONITOR_MONITOR_HANDLE).c_str()));
+		string path = ini.read(CONF_SECT_MONITOR, CONF_MONITOR_MONITOR_PATH);
+		sprintf_s(m_path_monitor, MAX_PATH, "%s", path.c_str());
+		//sprintf( m_path_monitor, "%s", path.c_str());
+	}
+}
+
+void CYAServerApp::init_param()
+{
+	m_path_monitor = new char[MAX_PATH];
+}
+
+void CYAServerApp::save_interval_conf()
+{
+	char t[20];
+	string s;
+	sprintf_s(t, "%d", send_json_postion);
+	s = t;
+	writeini(CONF_SECT_SERVER_SETTING, CONF_SEND_JSON_POSION, s);
+	sprintf_s(t, "%d", send_json_counting);
+	s = t;
+	writeini(CONF_SECT_SERVER_SETTING, CONF_SEND_JSON_COUNTING, s);
+	sprintf_s(t, "%d", send_json_alarm);
+	s = t;
+	writeini(CONF_SECT_SERVER_SETTING, CONF_SEND_JSON_ALARM, s);
+	sprintf_s(t, "%d", send_json_device);
+	s = t;
+	writeini(CONF_SECT_SERVER_SETTING, CONF_SEND_JSON_DEVICE, s);
+}

+ 93 - 0
YAServer.h

@@ -0,0 +1,93 @@
+
+// YAServer.h : PROJECT_NAME 应用程序的主头文件
+//
+
+#pragma once
+
+#ifndef __AFXWIN_H__
+	#error "在包含此文件之前包含“stdafx.h”以生成 PCH 文件"
+#endif
+
+#include "resource.h"		// 主符号
+#include <string>
+using namespace std;
+
+
+// CYAServerApp:
+// 有关此类的实现,请参阅 YAServer.cpp
+//
+
+class CYAServerApp : public CWinApp
+{
+public:
+	CYAServerApp();
+
+// 重写
+public:
+	virtual BOOL InitInstance();
+
+// 实现
+public:
+	// db
+	string dbhost;
+	string dbuser;
+	string dbpwd;
+	string dbname;
+	string dbencoding;
+	int dbport;
+	string dbbackup;
+
+	string dbhost_bk;
+	string dbuser_bk;
+	string dbpwd_bk;
+	string dbname_bk;
+	string dbencoding_bk;
+	int dbport_bk;
+	bool bRunning;
+	
+	// sys
+	string ws_url;	
+	string ws_url_bk;
+	BOOL use_filter;
+	int recon_server;	
+	int recon_db;
+	int reader_lost;
+	int card_lost;
+	int timing_interval;
+	double z_offset;
+	double coor_error;
+	double ranging_error;
+	double move_error;
+	double sampling_interval;
+	int locate_type; // 0 按照tof计算坐标; 1 按照分站计算
+	// interval
+	int send_json_postion; // 毫秒
+	int send_json_counting;
+	int send_json_alarm;
+	int send_json_device; 
+	// log
+	BOOL log_status;
+	BOOL log_raw_data;
+	BOOL log_parse_data;
+	BOOL log_send_event;
+	BOOL log_rev_pakage;
+	// monitor
+	HWND m_hwnd_monitor; // monitor 句柄
+	char* m_path_monitor; // monitor 路径
+
+	void writeini(string section, string key, string value);
+	void load_db_conf();
+	void save_db_conf();
+	void load_sys_conf();
+	void save_sys_conf();
+	void load_log_conf();
+	void save_log_conf();
+	void load_monitor_conf();
+	void set_server_handle(HWND hwd);
+	void save_interval_conf();
+	void init_param();
+
+	DECLARE_MESSAGE_MAP()
+};
+
+extern CYAServerApp theApp;

BIN
YAServer.rc


+ 251 - 0
YAServer.vcxproj

@@ -0,0 +1,251 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{4DB4D27B-7F2C-474A-8CA5-0B6CCEF59B3B}</ProjectGuid>
+    <RootNamespace>YAServer</RootNamespace>
+    <Keyword>MFCProj</Keyword>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <CharacterSet>Unicode</CharacterSet>
+    <UseOfMfc>Dynamic</UseOfMfc>
+    <PlatformToolset>v110</PlatformToolset>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+    <UseOfMfc>Dynamic</UseOfMfc>
+    <PlatformToolset>v110</PlatformToolset>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <LinkIncremental>true</LinkIncremental>
+    <OutDir>$(SolutionDir)..\..\output\$(Configuration)\bin\</OutDir>
+    <IntDir>$(SolutionDir)..\IntDir\$(PlatformName)\$(Configuration)\$(ProjectName)\</IntDir>
+    <IncludePath>$(BOOST)\;..\common\;..\thirdparty\include\socket.io-client-cpp\src\;..\thirdparty\include\rapidjson\include\;..\thirdparty\include\websocketpp\;..\thirdparty\include\mysql\;..\thirdparty\include\iocp\common\Src\;$(IncludePath)</IncludePath>
+    <LibraryPath>$(BOOST)\stage_11\lib;..\thirdparty\lib\mysql\;$(LibraryPath)</LibraryPath>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <LinkIncremental>false</LinkIncremental>
+    <OutDir>$(SolutionDir)..\..\output\$(Configuration)\bin\</OutDir>
+    <IntDir>$(SolutionDir)..\IntDir\$(PlatformName)\$(Configuration)\$(ProjectName)\</IntDir>
+    <IncludePath>$(BOOST)\;..\common\;..\thirdparty\include\socket.io-client-cpp\src\;..\thirdparty\include\rapidjson\include\;..\thirdparty\include\websocketpp\;..\thirdparty\include\mysql\;..\thirdparty\include\iocp\common\Src\;$(IncludePath)</IncludePath>
+    <LibraryPath>$(BOOST)\stage_11\lib;..\thirdparty\lib\mysql\;$(LibraryPath)</LibraryPath>
+    <ExtensionsToDeleteOnClean>*.aps;$(ExtensionsToDeleteOnClean)</ExtensionsToDeleteOnClean>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <PrecompiledHeader>Use</PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>..\common\json;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+    </ClCompile>
+    <Link>
+      <SubSystem>Windows</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <ProgramDatabaseFile>$(OutDir)\..\Symbol\$(TargetName).pdb</ProgramDatabaseFile>
+      <AdditionalLibraryDirectories>..\lib\$(Configuration)\;..\thirdparty\lib\mysql\</AdditionalLibraryDirectories>
+      <AdditionalDependencies>jsoncpp_110.lib;libmysql.lib;libboost_system-vc110-mt-gd-1_58.lib;libboost_date_time-vc110-mt-gd-1_58.lib;libboost_random-vc110-mt-gd-1_58.lib</AdditionalDependencies>
+    </Link>
+    <Midl>
+      <MkTypLibCompatible>false</MkTypLibCompatible>
+      <ValidateAllParameters>true</ValidateAllParameters>
+      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+    </Midl>
+    <ResourceCompile>
+      <Culture>0x0804</Culture>
+      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>$(IntDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+    </ResourceCompile>
+    <PostBuildEvent>
+      <Command>xcopy "$(SolutionDir)..\..\output\$(Configuration)\bin\YAServer.exe" "D:\0a-share\$(Configuration)\" /Y /C /D /S</Command>
+    </PostBuildEvent>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <PrecompiledHeader>Use</PrecompiledHeader>
+      <Optimization>MaxSpeed</Optimization>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>..\common\json;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+    </ClCompile>
+    <Link>
+      <SubSystem>Windows</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+      <ProgramDatabaseFile>$(OutDir)\..\Symbol\$(TargetName).pdb</ProgramDatabaseFile>
+      <AdditionalLibraryDirectories>..\lib\$(Configuration)\;..\thirdparty\lib\mysql\</AdditionalLibraryDirectories>
+      <AdditionalDependencies>jsoncpp_110.lib;libmysql.lib;libboost_system-vc110-mt-1_58.lib;libboost_date_time-vc110-mt-1_58.lib;libboost_random-vc110-mt-1_58.lib;%(AdditionalDependencies)</AdditionalDependencies>
+    </Link>
+    <Midl>
+      <MkTypLibCompatible>false</MkTypLibCompatible>
+      <ValidateAllParameters>true</ValidateAllParameters>
+      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+    </Midl>
+    <ResourceCompile>
+      <Culture>0x0804</Culture>
+      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>$(IntDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+    </ResourceCompile>
+    <PreBuildEvent>
+      <Command>xcopy "..\..\..\..\..\..\common\third-party\lib_110\Lib $(Configuration)\jsoncpp_110.lib" "..\lib\$(Configuration)\" /Y /C /D /S</Command>
+    </PreBuildEvent>
+    <PostBuildEvent>
+      <Command>xcopy "$(SolutionDir)..\..\output\$(Configuration)\bin\YAServer.exe" "D:\0a-share\$(Configuration)\" /Y /C /D /S
+xcopy "$(SolutionDir)..\config.ini" "D:\0a-share\$(Configuration)\" /Y /C /D /S</Command>
+    </PostBuildEvent>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <None Include="..\config.ini" />
+    <None Include="ReadMe.txt" />
+    <None Include="res\YAServer.ico" />
+    <None Include="res\YAServer.rc2" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\common\def_msg.h" />
+    <ClInclude Include="..\common\Functions\deca_range_optimize.h" />
+    <ClInclude Include="..\common\Functions\Functions.h" />
+    <ClInclude Include="..\common\json\json.h" />
+    <ClInclude Include="..\common\kalman\locate.h" />
+    <ClInclude Include="..\common\matrix\_Matrix.h" />
+    <ClInclude Include="..\common\ReportCtrl\ReportCtrl.h" />
+    <ClInclude Include="..\common\strconv\strconv.h" />
+    <ClInclude Include="..\common\structdef.h" />
+    <ClInclude Include="..\thirdparty\include\iocp\common\Src\bufferpool.h" />
+    <ClInclude Include="..\thirdparty\include\iocp\common\Src\bufferptr.h" />
+    <ClInclude Include="..\thirdparty\include\iocp\common\Src\CriticalSection.h" />
+    <ClInclude Include="..\thirdparty\include\iocp\common\Src\Event.h" />
+    <ClInclude Include="..\thirdparty\include\iocp\common\Src\GeneralHelper.h" />
+    <ClInclude Include="..\thirdparty\include\iocp\common\Src\PrivateHeap.h" />
+    <ClInclude Include="..\thirdparty\include\iocp\common\Src\RWLock.h" />
+    <ClInclude Include="..\thirdparty\include\iocp\common\Src\Semaphore.h" />
+    <ClInclude Include="..\thirdparty\include\iocp\common\Src\STLHelper.h" />
+    <ClInclude Include="..\thirdparty\include\iocp\common\Src\SysHelper.h" />
+    <ClInclude Include="..\thirdparty\include\iocp\common\Src\WaitFor.h" />
+    <ClInclude Include="..\thirdparty\include\iocp\common\Src\Win32Helper.h" />
+    <ClInclude Include="..\thirdparty\include\iocp\Global\helper.h" />
+    <ClInclude Include="..\thirdparty\include\iocp\Src\SocketHelper.h" />
+    <ClInclude Include="..\thirdparty\include\iocp\Src\SocketInterface.h" />
+    <ClInclude Include="..\thirdparty\include\iocp\Src\TcpServer.h" />
+    <ClInclude Include="..\thirdparty\include\socket.io-client-cpp\src\internal\sio_client_impl.h" />
+    <ClInclude Include="..\thirdparty\include\socket.io-client-cpp\src\internal\sio_packet.h" />
+    <ClInclude Include="..\thirdparty\include\socket.io-client-cpp\src\sio_client.h" />
+    <ClInclude Include="..\thirdparty\include\socket.io-client-cpp\src\sio_socket.h" />
+    <ClInclude Include="classdef.h" />
+    <ClInclude Include="constdef.h" />
+    <ClInclude Include="DbSettingDlg.h" />
+    <ClInclude Include="def.h" />
+    <ClInclude Include="LogSetting.h" />
+    <ClInclude Include="log_def.h" />
+    <ClInclude Include="MysqlConnPool.h" />
+    <ClInclude Include="Resource.h" />
+    <ClInclude Include="stdafx.h" />
+    <ClInclude Include="SysSetting.h" />
+    <ClInclude Include="targetver.h" />
+    <ClInclude Include="YAServer.h" />
+    <ClInclude Include="YAServerDlg.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\common\Functions\deca_range_optimize.cpp" />
+    <ClCompile Include="..\common\Functions\Functions.cpp" />
+    <ClCompile Include="..\common\kalman\locate.cpp">
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
+    </ClCompile>
+    <ClCompile Include="..\common\kalman\Smoother.cpp">
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
+    </ClCompile>
+    <ClCompile Include="..\common\matrix\_Matrix.cpp" />
+    <ClCompile Include="..\common\ReportCtrl\ReportCtrl.cpp" />
+    <ClCompile Include="..\common\strconv\strconv.cpp">
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
+    </ClCompile>
+    <ClCompile Include="..\thirdparty\include\iocp\common\Src\bufferpool.cpp" />
+    <ClCompile Include="..\thirdparty\include\iocp\common\Src\RWLock.cpp" />
+    <ClCompile Include="..\thirdparty\include\iocp\common\Src\SysHelper.cpp" />
+    <ClCompile Include="..\thirdparty\include\iocp\common\Src\WaitFor.cpp" />
+    <ClCompile Include="..\thirdparty\include\iocp\Global\helper.cpp" />
+    <ClCompile Include="..\thirdparty\include\iocp\Src\SocketHelper.cpp" />
+    <ClCompile Include="..\thirdparty\include\iocp\Src\TcpServer.cpp" />
+    <ClCompile Include="..\thirdparty\include\socket.io-client-cpp\src\internal\sio_client_impl.cpp">
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
+    </ClCompile>
+    <ClCompile Include="..\thirdparty\include\socket.io-client-cpp\src\internal\sio_packet.cpp">
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
+    </ClCompile>
+    <ClCompile Include="..\thirdparty\include\socket.io-client-cpp\src\sio_client.cpp">
+      <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">..\common\json;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
+    </ClCompile>
+    <ClCompile Include="..\thirdparty\include\socket.io-client-cpp\src\sio_socket.cpp">
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
+    </ClCompile>
+    <ClCompile Include="classdef.cpp" />
+    <ClInclude Include="locate_algorithm.h">
+      <FileType>CppCode</FileType>
+    </ClInclude>
+    <ClCompile Include="DbSettingDlg.cpp" />
+    <ClCompile Include="locate_algorithm.cpp" />
+    <ClCompile Include="LogSetting.cpp" />
+    <ClCompile Include="MysqlConnPool.cpp" />
+    <ClCompile Include="stdafx.cpp">
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
+      <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
+    </ClCompile>
+    <ClCompile Include="SysSetting.cpp" />
+    <ClCompile Include="YAServer.cpp" />
+    <ClCompile Include="YAServerDlg.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ResourceCompile Include="YAServer.rc" />
+  </ItemGroup>
+  <ItemGroup>
+    <Reference Include="System" />
+    <Reference Include="System.Data" />
+    <Reference Include="System.Drawing" />
+    <Reference Include="System.Windows.Forms" />
+    <Reference Include="System.Xml" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+  <ProjectExtensions>
+    <VisualStudio>
+      <UserProperties RESOURCE_FILE="YAServer.rc" />
+    </VisualStudio>
+  </ProjectExtensions>
+</Project>

+ 279 - 0
YAServer.vcxproj.filters

@@ -0,0 +1,279 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="源文件">
+      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="头文件">
+      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+    <Filter Include="资源文件">
+      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
+    </Filter>
+    <Filter Include="webscoket">
+      <UniqueIdentifier>{f5e2d47b-bde5-4f1f-b87c-dcfbb31e2dad}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="mysql">
+      <UniqueIdentifier>{3381c5a9-a71d-4239-b56f-9e4a8b4de663}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="algorithm">
+      <UniqueIdentifier>{4ea56584-f690-48ed-97c9-9415d60471ea}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="parse_data_byte">
+      <UniqueIdentifier>{878cb145-dfd2-4d04-9a5f-0a9917a74d5b}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="function">
+      <UniqueIdentifier>{1492031a-5aa5-40ea-83e9-d73e1b483336}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="rpt">
+      <UniqueIdentifier>{386583be-5214-407f-b613-02bd86cdb68d}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="strconv">
+      <UniqueIdentifier>{c6967317-0711-4c19-9bbd-9776323bfee0}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="hp-socket">
+      <UniqueIdentifier>{78581a6f-c432-43b8-80b9-2b2d1cc4f92f}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="hp-socket\global">
+      <UniqueIdentifier>{f154eeae-b1e7-471d-b166-9bb0169820ca}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="hp-socket\common">
+      <UniqueIdentifier>{c1a6b36f-ded8-4f87-ac95-51d01329cace}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="hp-socket\socket">
+      <UniqueIdentifier>{32cd81c8-6205-4f08-a0a2-e8bfd65cc014}</UniqueIdentifier>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="ReadMe.txt" />
+    <None Include="res\YAServer.rc2">
+      <Filter>资源文件</Filter>
+    </None>
+    <None Include="res\YAServer.ico">
+      <Filter>资源文件</Filter>
+    </None>
+    <None Include="..\config.ini" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="YAServer.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+    <ClInclude Include="YAServerDlg.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+    <ClInclude Include="stdafx.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+    <ClInclude Include="targetver.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+    <ClInclude Include="Resource.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+    <ClInclude Include="constdef.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+    <ClInclude Include="..\common\json\json.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+    <ClInclude Include="..\common\structdef.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+    <ClInclude Include="classdef.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+    <ClInclude Include="def.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+    <ClInclude Include="MysqlConnPool.h">
+      <Filter>mysql</Filter>
+    </ClInclude>
+    <ClInclude Include="locate_algorithm.h">
+      <Filter>algorithm</Filter>
+    </ClInclude>
+    <ClInclude Include="..\common\def_msg.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+    <ClInclude Include="log_def.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+    <ClInclude Include="DbSettingDlg.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+    <ClInclude Include="SysSetting.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+    <ClInclude Include="LogSetting.h">
+      <Filter>头文件</Filter>
+    </ClInclude>
+    <ClInclude Include="..\common\kalman\locate.h">
+      <Filter>algorithm</Filter>
+    </ClInclude>
+    <ClInclude Include="..\common\Functions\deca_range_optimize.h">
+      <Filter>function</Filter>
+    </ClInclude>
+    <ClInclude Include="..\common\Functions\Functions.h">
+      <Filter>function</Filter>
+    </ClInclude>
+    <ClInclude Include="..\common\ReportCtrl\ReportCtrl.h">
+      <Filter>rpt</Filter>
+    </ClInclude>
+    <ClInclude Include="..\thirdparty\include\socket.io-client-cpp\src\sio_client.h">
+      <Filter>webscoket</Filter>
+    </ClInclude>
+    <ClInclude Include="..\thirdparty\include\socket.io-client-cpp\src\sio_socket.h">
+      <Filter>webscoket</Filter>
+    </ClInclude>
+    <ClInclude Include="..\thirdparty\include\socket.io-client-cpp\src\internal\sio_client_impl.h">
+      <Filter>webscoket</Filter>
+    </ClInclude>
+    <ClInclude Include="..\thirdparty\include\socket.io-client-cpp\src\internal\sio_packet.h">
+      <Filter>webscoket</Filter>
+    </ClInclude>
+    <ClInclude Include="..\common\strconv\strconv.h">
+      <Filter>strconv</Filter>
+    </ClInclude>
+    <ClInclude Include="..\common\matrix\_Matrix.h">
+      <Filter>algorithm</Filter>
+    </ClInclude>
+    <ClInclude Include="..\thirdparty\include\iocp\Global\helper.h">
+      <Filter>hp-socket\global</Filter>
+    </ClInclude>
+    <ClInclude Include="..\thirdparty\include\iocp\Src\SocketHelper.h">
+      <Filter>hp-socket\socket</Filter>
+    </ClInclude>
+    <ClInclude Include="..\thirdparty\include\iocp\Src\SocketInterface.h">
+      <Filter>hp-socket\socket</Filter>
+    </ClInclude>
+    <ClInclude Include="..\thirdparty\include\iocp\Src\TcpServer.h">
+      <Filter>hp-socket\socket</Filter>
+    </ClInclude>
+    <ClInclude Include="..\thirdparty\include\iocp\common\Src\bufferpool.h">
+      <Filter>hp-socket\common</Filter>
+    </ClInclude>
+    <ClInclude Include="..\thirdparty\include\iocp\common\Src\bufferptr.h">
+      <Filter>hp-socket\common</Filter>
+    </ClInclude>
+    <ClInclude Include="..\thirdparty\include\iocp\common\Src\CriticalSection.h">
+      <Filter>hp-socket\common</Filter>
+    </ClInclude>
+    <ClInclude Include="..\thirdparty\include\iocp\common\Src\Event.h">
+      <Filter>hp-socket\common</Filter>
+    </ClInclude>
+    <ClInclude Include="..\thirdparty\include\iocp\common\Src\GeneralHelper.h">
+      <Filter>hp-socket\common</Filter>
+    </ClInclude>
+    <ClInclude Include="..\thirdparty\include\iocp\common\Src\PrivateHeap.h">
+      <Filter>hp-socket\common</Filter>
+    </ClInclude>
+    <ClInclude Include="..\thirdparty\include\iocp\common\Src\RWLock.h">
+      <Filter>hp-socket\common</Filter>
+    </ClInclude>
+    <ClInclude Include="..\thirdparty\include\iocp\common\Src\Semaphore.h">
+      <Filter>hp-socket\common</Filter>
+    </ClInclude>
+    <ClInclude Include="..\thirdparty\include\iocp\common\Src\STLHelper.h">
+      <Filter>hp-socket\common</Filter>
+    </ClInclude>
+    <ClInclude Include="..\thirdparty\include\iocp\common\Src\SysHelper.h">
+      <Filter>hp-socket\common</Filter>
+    </ClInclude>
+    <ClInclude Include="..\thirdparty\include\iocp\common\Src\WaitFor.h">
+      <Filter>hp-socket\common</Filter>
+    </ClInclude>
+    <ClInclude Include="..\thirdparty\include\iocp\common\Src\Win32Helper.h">
+      <Filter>hp-socket\common</Filter>
+    </ClInclude>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="YAServer.cpp">
+      <Filter>源文件</Filter>
+    </ClCompile>
+    <ClCompile Include="YAServerDlg.cpp">
+      <Filter>源文件</Filter>
+    </ClCompile>
+    <ClCompile Include="stdafx.cpp">
+      <Filter>源文件</Filter>
+    </ClCompile>
+    <ClCompile Include="classdef.cpp">
+      <Filter>源文件</Filter>
+    </ClCompile>
+    <ClCompile Include="MysqlConnPool.cpp">
+      <Filter>mysql</Filter>
+    </ClCompile>
+    <ClCompile Include="locate_algorithm.cpp">
+      <Filter>algorithm</Filter>
+    </ClCompile>
+    <ClCompile Include="DbSettingDlg.cpp">
+      <Filter>源文件</Filter>
+    </ClCompile>
+    <ClCompile Include="SysSetting.cpp">
+      <Filter>源文件</Filter>
+    </ClCompile>
+    <ClCompile Include="LogSetting.cpp">
+      <Filter>源文件</Filter>
+    </ClCompile>
+    <ClCompile Include="..\common\kalman\locate.cpp">
+      <Filter>algorithm</Filter>
+    </ClCompile>
+    <ClCompile Include="..\common\Functions\deca_range_optimize.cpp">
+      <Filter>function</Filter>
+    </ClCompile>
+    <ClCompile Include="..\common\Functions\Functions.cpp">
+      <Filter>function</Filter>
+    </ClCompile>
+    <ClCompile Include="..\common\ReportCtrl\ReportCtrl.cpp">
+      <Filter>rpt</Filter>
+    </ClCompile>
+    <ClCompile Include="..\thirdparty\include\socket.io-client-cpp\src\sio_client.cpp">
+      <Filter>webscoket</Filter>
+    </ClCompile>
+    <ClCompile Include="..\thirdparty\include\socket.io-client-cpp\src\sio_socket.cpp">
+      <Filter>webscoket</Filter>
+    </ClCompile>
+    <ClCompile Include="..\thirdparty\include\socket.io-client-cpp\src\internal\sio_client_impl.cpp">
+      <Filter>webscoket</Filter>
+    </ClCompile>
+    <ClCompile Include="..\thirdparty\include\socket.io-client-cpp\src\internal\sio_packet.cpp">
+      <Filter>webscoket</Filter>
+    </ClCompile>
+    <ClCompile Include="..\common\strconv\strconv.cpp">
+      <Filter>strconv</Filter>
+    </ClCompile>
+    <ClCompile Include="..\common\kalman\Smoother.cpp">
+      <Filter>algorithm</Filter>
+    </ClCompile>
+    <ClCompile Include="..\common\matrix\_Matrix.cpp">
+      <Filter>algorithm</Filter>
+    </ClCompile>
+    <ClCompile Include="..\thirdparty\include\iocp\Global\helper.cpp">
+      <Filter>hp-socket\global</Filter>
+    </ClCompile>
+    <ClCompile Include="..\thirdparty\include\iocp\Src\SocketHelper.cpp">
+      <Filter>hp-socket\socket</Filter>
+    </ClCompile>
+    <ClCompile Include="..\thirdparty\include\iocp\Src\TcpServer.cpp">
+      <Filter>hp-socket\socket</Filter>
+    </ClCompile>
+    <ClCompile Include="..\thirdparty\include\iocp\common\Src\bufferpool.cpp">
+      <Filter>hp-socket\common</Filter>
+    </ClCompile>
+    <ClCompile Include="..\thirdparty\include\iocp\common\Src\RWLock.cpp">
+      <Filter>hp-socket\common</Filter>
+    </ClCompile>
+    <ClCompile Include="..\thirdparty\include\iocp\common\Src\SysHelper.cpp">
+      <Filter>hp-socket\common</Filter>
+    </ClCompile>
+    <ClCompile Include="..\thirdparty\include\iocp\common\Src\WaitFor.cpp">
+      <Filter>hp-socket\common</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ResourceCompile Include="YAServer.rc">
+      <Filter>资源文件</Filter>
+    </ResourceCompile>
+  </ItemGroup>
+</Project>

+ 4 - 0
YAServer.vcxproj.user

@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup />
+</Project>

File diff suppressed because it is too large
+ 5227 - 0
YAServerDlg.cpp


+ 337 - 0
YAServerDlg.h

@@ -0,0 +1,337 @@
+
+// YAServerDlg.h : 头文件
+//
+
+#pragma once
+#include "afxwin.h"
+
+#include "resource.h"
+#include "structdef.h"
+#include "constdef.h"
+#include "classdef.h"
+#include "def_msg.h"
+#include "socketdef.h"
+#include "ReportCtrl/ReportCtrl.h"
+
+#include <sio_client.h>
+#include "../thirdparty/include/iocp/Src/TcpServer.h"
+#include "../thirdparty/include/iocp/Global/helper.h"
+#include "afxcmn.h"
+using namespace sio;
+using namespace std;
+
+struct  _SLS // system_limit_setting
+{
+	unsigned int over_count_person;
+	unsigned int over_count_vehicle;
+	unsigned int over_time_person;
+	unsigned int over_time_vehicle;
+	double over_speed;
+};
+
+struct _DBS // db setting
+{
+	string host;
+	string user;
+	string password;
+	string dbname;
+	string encoding;
+	int port;
+};
+
+struct _SOCK
+{
+	CString sip;
+	DWORD dwConnID;
+	int state; // 0 连接
+	DWORD reader_id; // 分站号
+};
+struct _SOCKET_BUFFER
+{
+	DWORD dwConnID;
+	BYTE pData[LENGTH_MSG_4K]; 
+	WORD wLen;
+	WORD wReadLen;
+};
+
+// CYAServerDlg 对话框
+class CYAServerDlg : public CDialogEx, public CTcpServerListener
+{
+	typedef map<string, Card*> CardMap;
+	typedef map<CString, _SOCK*> SocketMap;
+	typedef map<DWORD, _SOCKET_BUFFER*> SocketBufferMap;
+	// 构造
+public:
+	CYAServerDlg(CWnd* pParent = NULL);	// 标准构造函数
+	~CYAServerDlg();
+	// 对话框数据
+	enum { IDD = IDD_YASERVER_DIALOG };
+
+protected:
+	virtual void DoDataExchange(CDataExchange* pDX);	// DDX/DDV 支持
+private:
+	virtual EnHandleResult OnPrepareListen(SOCKET soListen);
+	virtual EnHandleResult OnAccept(CONNID dwConnID, SOCKET soClient);
+	virtual EnHandleResult OnSend(CONNID dwConnID, const BYTE* pData, int iLength);
+	virtual EnHandleResult OnReceive(CONNID dwConnID, const BYTE* pData, int iLength);
+	virtual EnHandleResult OnClose(CONNID dwConnID, EnSocketOperation enOperation, int iErrorCode);
+	virtual EnHandleResult OnShutdown();
+	// 实现
+protected:
+	HICON m_hIcon;
+
+	// 生成的消息映射函数
+	virtual BOOL OnInitDialog();
+	afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
+	afx_msg void OnPaint();
+	afx_msg HCURSOR OnQueryDragIcon();
+	DECLARE_MESSAGE_MAP()
+public:
+	CButton m_btStart;
+	CButton m_btStop;
+	CMenu m_mnMain;
+	afx_msg LRESULT on_monitor(WPARAM wParam, LPARAM lParam);
+	afx_msg void OnTimer(UINT nIDEvent);
+	afx_msg void OnBnStop();
+	afx_msg void OnBnStart();	
+	afx_msg void OnBnExit();
+	afx_msg void OnBnSyncTime();
+	afx_msg void OnMenuDb();
+	afx_msg void OnMenuLog();
+	afx_msg void OnMenuParam();
+	afx_msg void OnBnCallHisData();
+public: 
+	// ui operation
+	CTcpServer _server;
+	EnAppState m_enState;
+	CStdioFile cfErrorLog;
+	CRITICAL_SECTION m_csWriteLog;
+	CRITICAL_SECTION m_csRemoveSocket;
+
+	void set_app_state(EnAppState eas);
+	void start_tcp_server();
+	void stop_tcp_server();	
+public:
+	CString m_strConncetion; // 数据库连接字符串
+	int m_nPort; // 启动端口
+	int m_nCountClick;
+
+	CWinThread* m_thread_monitor; // 与监控程序通信线程
+	CWinThread* m_thread_timer; // timer的线程,脱离UI线程,不使用ontimer
+	unsigned int m_uint_state; // 采集状态
+	// bit 0, 服务状态,运行或者关闭
+	// bit 1, 采集状态,正常或异常
+	// bit 2, 分站状态,有中断或没有
+	// bit 3, websocket状态,连接未连接
+	// bit 4, 数据库状态,连接未连接
+	time_t m_time_last_rec; // 最后接收到分站数据的时间
+	bool is_websocket_ok; //
+	bool is_websocket_login;
+	bool is_server_ok; // 
+	bool is_database_ok; //
+
+	time_t time_over_count_vehicle;
+	time_t time_over_count_person;
+
+
+	BOOL m_bListen;
+	SocketMap mp_socket_list;
+	SocketBufferMap mp_socket_buffer_list;
+
+	CardMap mp_card_list_all; // 所有卡
+	ReaderMap mp_reader_list; // 所有分站
+	AreaMap mp_area_list; // 所有区域
+	MapInfoMap mp_map_list; // 所有地图
+	DeptMap mp_dept_list; // 所有部门
+	AlarmTypeMap mp_alarm_type_list;
+
+	CardMap mp_card_list_down_vehicle; // 井下车辆
+	CardMap mp_card_list_down_person; // 井下人员
+
+	CardMap mp_card_list_over_time_person; // 
+	CardMap mp_card_list_forbidden_person;
+	CardMap mp_card_list_help;
+	CardMap mp_card_list_area_over_time_person;
+	CardMap mp_card_list_forbidden_vehicle;
+	CardMap mp_card_list_over_time_vehicle;	
+	CardMap mp_card_list_over_speed_vehicle;
+	CardMap mp_card_list_area_over_time_vehicle;
+
+	AreaMap mp_area_over_count_person;
+	AreaMap mp_area_over_time_person;
+	AreaMap mp_area_forbidden_person;
+	AreaMap mp_area_over_count_vehicle;
+	AreaMap mp_area_over_time_vehicle;
+	AreaMap mp_area_forbidden_vehicle;
+
+	CallInfoReaderMap mp_call_info;
+
+	_SLS sls_setting;
+	_DBS m_db_setting;
+	string m_ws_url;
+	DWORD dw_last_send_time;
+
+	void init_ui();
+	void init_param();
+	void load_param_from_ini();
+	void database_connect();
+	void stop_and_exit();
+	void stop_timer();
+	void set_run_state();
+	// 从数据库中初始化数据 
+	void init_base_data();
+	int init_setting(); // 系统配置
+	int init_alarm_type(); // 报警类型
+	int init_dept(); // 部门列表
+	int init_card(string card_id = "");
+	int init_staffer(string staff_id = "", bool is_card = false); // 人员
+	int init_vehicle(string vehicle_id = "", bool is_card = false); // 车辆
+	//int init_adhoc(string adhoc_id = ""); // 自组网卡
+	int init_map(int map_id = 0); // 地图
+	int init_area(int area_id = 0); // 区域
+	int init_reader(int reader_id = 0); // 分站
+	int init_antenna(int reader_id = 0); // 天线
+	int init_dev_adhoc(int reader_id = 0); // 自组网坐标
+	// 载入历史数据
+	void load_his_data();
+	void load_his_down(); // 入井状态
+	void load_his_area(); // 所在区域
+	void load_his_reader(); // 分站状态
+	void load_his_card_postion(); // 所在位置
+	void load_his_card_state();
+	// 载入报警数据
+	void load_alarm_reader();
+	//void load_alarm_area();
+	//void load_alarm_mine();
+	// 接口数据解析
+	void parse_edit_map(int map_id);
+	void parse_edit_area(int area_id);
+	void parse_edit_reader(int reader_id);
+	void parse_edit_card(string card_id);
+	void parse_edit_staffer(string staffer_id);
+	void parse_edit_vehicle(string vehicle_id);
+	void parse_edit_path(int path_id);
+	void parse_set_limit_value();
+	void parse_call_card();
+	void parse_clear_card();
+	void parse_deal_help();
+	// 初始化websocket
+	void ws_init();
+	void ws_open();
+	void ws_close();
+	void ws_login();
+	void ws_logout();
+
+	void clear_listener();
+	void clear_all_list();
+	// socket接收数据
+	void parse_data(const BYTE *pData, int nLen, DWORD dwConnID);
+	void parse_data_receive(BYTE *pData, int nLen, DWORD dwConnID);
+	void parse_package_data(BYTE* DataBuffer, int nLen, DWORD dwConnID);
+	void parse_data_locate_reader(BYTE * DataBuffer, int& nCurPos, int nLen, DWORD dwConnID, int& reader_id);
+	void parse_data_locate_card(BYTE* DataBuffer, int& nCurPos,  int reader_id);
+	void parse_data_adhoc(BYTE* DataBuffer, int& nCurPos,  int reader_id);
+	void parse_data_locate_card_vehicle(BYTE* DataBuffer, int& nCurPos,  Card* card);
+	_SOCK* get_socket_by_count(DWORD dwConnID);
+	void add_socket_to_list(DWORD dwConnID, DWORD reader_id);
+	void remove_socket(DWORD dwConnID);
+
+	// 获取json串
+	string get_json_login();
+	string get_json_logout();
+	//string get_json_down_mine();
+	//string get_json_up_mine();
+	string get_json_down_and_up(Card* card);
+	string get_json_counting();
+	string get_json_postion();
+	string get_json_postion_all();
+	string get_json_device_state();
+	string get_json_alarm();
+	string get_json_call_test();
+	// string get_json_postion_test();
+	// void send_json_data(string url, string cmd, string data, string ver, string user);
+	void send_json_data(string cmd, string data, bool is_login = false);
+	// 业务处理
+	void deal_readers();
+	void deal_areas();
+	void deal_card(Card* card, bool is_hist = false);
+	void deal_hist_card_postion();
+	void deal_hist_card_alarm();
+	void deal_hist_area();
+	void card_enter_mine(Card* card);
+	void card_down_mine(Card* card);
+	void card_up_mine(Card* card);
+	void card_enter_park(Card* card);
+	void card_enter_map(Card* card);
+	void card_enter_area(Card* card);
+	void card_leave_area(Card* card, Area* area);
+	void deal_card_state(Card* card);
+	void deal_alarm_card(Card* card, CardMap* dest_card_list, bool is_alarm, ALARM_FLAG tag);
+	void deal_alarm_area(Area* area, AreaMap* dest_area_list, bool is_alarm, ALARM_FLAG tag);
+	void reset_map_card();
+	//void reset_area_card();
+	bool is_in_rectangle(_point p, double dblleft, double dbltop, double dblright, double dblbottom);
+	bool is_in_circle(_point p1, _point p2, double r, double scale);
+	// save to database
+	void execute_sql(const char* sql); // 保存到数据库
+	void save_card_postion(Card* card);
+	void store_data_card(Card* card, int tag);
+	void store_data_area(Area* area, time_t cur_time, time_t start_time, int tag);
+	void store_data_reader(Reader* reader, int tag);
+	void store_data_mine(int tag);
+	//void store_data_system();
+
+	// 打包数据
+	void package_data();
+	void package_data_test();
+	// 通用方法
+	int API_TimeToString(string &strDateStr,const time_t &timeData);
+	int API_StringToTime(const string &strDateStr,time_t &timeData);
+
+	void formatByteArray(CString &strBuf, BYTE * buf, int nLen);
+	void writeErrorLog(const CString strFile, const CString strErr ,bool bTime = true);
+	BOOL openLogFile(const CString strFile);
+	void show_log( LPCTSTR szlog, BOOL bSave = true);
+	void AddItem(CString strvalue, int readerid, BOOL is_closed = false);
+	// 响应接口
+	void parse_json_data_set_limit_value(const char* sz);
+	void parse_json_data_call_card(const char* sz);
+	void parse_json_data_clear_card(const char* sz);
+	void parse_json_data_deal_help(const char* sz);
+	//void parse_json_data_edit_map(const char* sz);
+	//void parse_json_data_edit_area(const char* sz);
+	//void parse_json_data_edit_reader(const char* sz);
+	////void parse_json_data_edit_path(const char* sz);
+	//void parse_json_data_edit_card(const char* sz);
+	//void parse_json_data_edit_staffer(const char* sz);
+	//void parse_json_data_edit_vehicle(const char* sz);
+	void deal_call_edit_map(int id, EDIT_TYPE_ID edit_type_id);
+	void deal_call_edit_area(int id, EDIT_TYPE_ID edit_type_id);
+	void deal_call_edit_reader(int id, EDIT_TYPE_ID edit_type_id);
+	void deal_call_edit_card(string id, EDIT_TYPE_ID edit_type_id);
+	void deal_call_edit_staff(string id, EDIT_TYPE_ID edit_type_id);
+	void deal_call_edit_vehicle(string id, EDIT_TYPE_ID edit_type_id);
+	void remove_card(string card_id);
+
+	void send_call_info();
+	void send_call_his_data();
+	void send_sync_reader();
+	void clear_call_info();
+	int get_card_id_len(int card_type);
+public:
+	std::unique_ptr<client> _io;
+	CListBox m_list_log;
+	CReportCtrl m_listctrl_reader;
+
+	void OnPushMessage();
+	void OnCallMessage(string const& name, message::ptr const& data, bool isAck,message::list &ack_resp); 
+	//void OnCallMessage(string const& name, message::ptr const& data, bool isAck = false,message::list &ack_resp = nullptr); 
+	void OnLoginCallBack(message::list const& msglist = nullptr);
+	void OnLogin(string const& name, message::ptr const& data, bool isAck, message::list &ack_resp);
+
+	void OnConnected();
+	void OnClosed(client::close_reason const& reason);
+	void OnFailed();
+protected:
+	afx_msg LRESULT OnMsgRefreshIpList(WPARAM wParam, LPARAM lParam);
+};

+ 651 - 0
classdef.cpp

@@ -0,0 +1,651 @@
+#include "stdafx.h"
+#include "classdef.h"
+#include "constdef.h"
+#include "structdef.h"
+#include "locate_algorithm.h"
+
+#include <math.h>
+
+Card::Card( string cardid, int cardtype, double z_offset, double offset_x /*= 12.0*/, double offset_y /*=12.0*/ )
+{
+	card_type = cardtype;
+	card_id = cardid;
+	coor_offset_x = offset_x;
+	coor_offset_y = offset_y;
+	this->z_offset = z_offset;
+
+	down_time = up_time = enter_area_time = enter_reader_time = deal_time = rec_time = time(NULL);
+	time_over_time = time_area_over_time = time_area_forbidden = time_over_speed = time_low_power = time(NULL);
+
+	x =	y = z = last_x = last_y = last_z =0;
+	xx = yy = zz = 0;
+	x1 = y1 = z1 = x2 = y2 = z2 = x3 = y3 = z3 = x4 = y4 = z4 = 0;
+	a = 0;
+	t = 0;
+	init_postion = false;
+	is_first_location = true;
+
+	map_id = map_id_old = area_id = reader_id = 0;
+	state = 0;
+	pos_state = pos_state_count = pos_state_old = 0;
+	dept_id = group_id = 0;
+	power_state = power_state_last = 0;
+
+	isdealed = isreceive = is_pos_changed = is_hist = is_need_cal = false;
+	is_area_over_time = is_mine_over_time = false;
+
+	id = name = number = department = group = worktype = "";
+
+	reader_tickcount = time_stamp = time_stamp_last = 0;
+
+	p_dists = new _coordinate*[DIST_COUNT];
+	p_dists_locate = new _coordinate*[DIST_COUNT];
+	time_stamp_max = 0;
+	for(int i = 0; i < DIST_COUNT; i++){
+		p_dists[i] = NULL;
+		p_dists_locate[i] = NULL;
+	}
+	//cal_location = new CalLocation(KALMAN_OFFSET_COOR, KALMAN_OFFSET_MOVE, KALMAN_OFFSET_RANGING, KALMAN_INTERVAL);
+	//p2_anchors = new Point2[ANCHOR_COUNT];
+	//cal_location3 = new CalLocation3(KALMAN_OFFSET_COOR_TRI, KALMAN_OFFSET_COOR_TRI, KALMAN_OFFSET_COOR_TRI,
+	//	KALMAN_OFFSET_MOVE_TRI, KALMAN_OFFSET_MOVE_TRI, 0, KALMAN_OFFSET_RANGING_TRI, KALMAN_INTERVAL_TRI);
+	cal_location3 = new CalLocation3(KALMAN_OFFSET_COOR_TRI, KALMAN_OFFSET_MOVE_TRI, KALMAN_OFFSET_RANGING_TRI, KALMAN_INTERVAL_TRI);
+	p3_anchors = new Point3[ANCHOR_COUNT];
+	is_init_kalman = false;
+}
+
+Card::Card( void )
+{
+	
+}
+
+//void Card::set_pos_state( int val )
+//{ 
+//	if(val == pos_state) {
+//		pos_state_count++;
+//		return;
+//	}
+//	pos_state = val; 
+//	pos_state_count = 1;
+//}
+
+void Card::set_reader( Reader* preader ) // 设置卡时间
+{	
+	this->rec_time = time(NULL);
+	if(preader->reader_id == this->reader_id){ // 所在分站没有发生变化
+		this->pos_state_count++;
+	}else{ // 分站变化
+		this->p_reader = preader;
+		this->reader_id = preader->reader_id;
+		this->enter_reader_time = this->rec_time;
+		
+		//if(preader->area_id != this->area_id){ // 区域变化 // note 根据区域坐标计算
+		//	this->area_id = preader->area_id;
+		//	this->enter_area_time = this->rev_time;
+		//} 
+		this->map_id_old = this->map_id;
+		this->map_id = preader->map_id;
+
+		//if(this->pos_state == preader->pos_state){
+		//	this->pos_state_count++;
+		//}else{ // 井上,井下位置变化
+		//	this->pos_state_last = this->pos_state;
+		//	this->pos_state = preader->pos_state;
+		//	this->pos_state_count = 0;
+		//}
+	}
+}
+
+bool Card::is_pos_state_changed( int nval )  // 考勤
+{
+	if(this->pos_state == this->pos_state_old){ 
+		return false;
+	}
+	//if(this->pos_state_count < nval ){ // 未达到确认次数
+	//	return false;
+	//}
+	this->pos_state_old = this->pos_state;
+	return true;
+	//if(last_area_type_id != cur_area_type_id){
+	//	if(0 ==last_area_type_id || 0==cur_area_type_id){
+	//		return true;
+	//	}
+	//}
+	//return false;
+	//return (this->last_area_type_id != this->cur_area_type_id && 0 == (this->cur_area_type_id & this->last_area_type_id));
+}
+
+void Card::add_dist( _coordinate* dist )
+{
+	string s = concat(dist->reader_id, dist->antenna_id);
+	if(0 == _dists.size()){
+		DistQueItem* p = new DistQueItem;
+		p->t = dist->t;
+		p->mp_dist.insert(make_pair(s, dist));
+		_dists.push_back(p);
+		return ;
+	}
+	if(_dists.front()->t == dist->t){ 
+		DistMap::iterator it = _dists.front()->mp_dist.find(s);
+		if(it != _dists.front()->mp_dist.end()){
+			it->second->x = dist->x;
+			it->second->y = dist->y;
+			it->second->z = dist->z;
+			it->second->a = dist->a;
+		}else{
+			_dists.front()->mp_dist.insert(make_pair(s, dist));
+		}
+	}else if(_dists.back()->t == dist->t){
+		DistMap::iterator it = _dists.back()->mp_dist.find(s);
+		if(it != _dists.back()->mp_dist.end()){
+			it->second->x = dist->x;
+			it->second->y = dist->y;
+			it->second->z = dist->z;
+			it->second->a = dist->a;
+		}else{
+			_dists.back()->mp_dist.insert(make_pair(s, dist));
+		}
+	}else{ // 新数据
+		DistQueItem* p = new DistQueItem;
+		p->t = dist->t;
+		p->mp_dist.insert(make_pair(s, dist));
+		if(_dists.size() > 1){ // 大于一个
+			_dists.pop_front();
+		}
+		_dists.push_back(p);
+		get_coordinate();
+	}		
+
+	//// new reader, replace the earliest or the null
+	//bool b_exist = false;
+	//int min_stamp = dist->t, min_stamp_index = -1;
+	//// when dist->t is the latest data, calc the last timestamp data (the second latest data)
+	//// (dist->t > 0 && time_stamp_max < dist->t) || (dist->t == 0 && time_stamp_max == 0xFFFF)
+	//is_need_cal = (dist->t > 0 && time_stamp_max < dist->t) || (dist->t < 10 && abs(dist->t - time_stamp_max) > 100);
+
+	//time_stamp_max = dist->t;
+	//for(int i = 0; i < DIST_COUNT; i++ ){
+	//	if(p_dists[i] == NULL){
+	//		p_dists[i] = dist;
+	//		is_anchor_changed = true;
+	//		b_exist = true;
+	//		break;
+	//	}
+	//	//if(p_dists[i]->reader_id == dist->reader_id){ 
+	//	if(p_dists[i]->x == dist->x && p_dists[i]->y == dist->y 
+	//		&& p_dists[i]->z == dist->z && p_dists[i]->a == dist->a){ // 同一分站,新数据有效
+	//			dist->d_offset = p_dists[i]->d_offset; // 同一分站的偏移
+	//			if(dist->t >= p_dists[i]->t){
+	//				p_dists[i] = dist;
+	//			}else if(abs(dist->t - p_dists[i]->t) > 100){
+	//				p_dists[i] = dist;
+	//			}
+	//			b_exist = true;
+	//			break;
+	//	}
+	//	if(min_stamp >= p_dists[i]->t && abs(min_stamp-p_dists[i]->t) <100){
+	//		min_stamp = p_dists[i]->t;
+	//		min_stamp_index = i;
+	//	}else if(min_stamp < p_dists[i]->t && abs(min_stamp - p_dists[i]->t) >= 100){
+	//		min_stamp = p_dists[i]->t;
+	//		min_stamp_index = i;
+	//	}
+	//}
+	//if(!b_exist){
+	//	p_dists[min_stamp_index] = dist;
+	//	is_anchor_changed = true;
+	//}
+}
+
+time_t Card::get_working_time()
+{
+	//return (card_type == CT_VEHICLE) ? leave_park_time : down_time;
+	return down_time;
+}
+
+int Card::get_effictive_dist_count( int offset /*= 0*/ )
+{
+	if(0 == _dists.size()) return 0;
+	return _dists.front()->mp_dist.size();
+
+	//int nTimeStamp;
+	//if(time_stamp_max == 0 && offset != 0){
+	//	nTimeStamp = 0xFFFF;
+	//}else{
+	//	nTimeStamp = time_stamp_max - offset;
+	//}
+	//int ret = 0, tmp = -1;
+	//for(int i = 0; i < DIST_COUNT; i++){
+	//	if(NULL == p_dists[i]) break;
+	//	if(p_dists[i]->t == nTimeStamp){
+	//		ret++;
+	//	}
+	//}
+	//return ret;
+}
+
+Card::~Card(void)
+{
+}
+
+void Card::get_coordinate_2d( int cnt )
+{
+	//double d_dist[3];
+	//Point2 pt2, pt2_1;
+	//for(int i = 0; i < cnt; i++){
+	//	d_dist[i] = p_dists_locate[i]->d;
+
+	//}
+	//for(int i=0; i< cnt; i++){
+	//	if(p_dists[i]->reader_id == 1){
+	//		p2_anchors[0].x = p_dists[i]->x;
+	//		p2_anchors[0].y = p_dists[i]->y;
+	//		d_dist[0] = p_dists[i]->d;
+	//	}else if(p_dists[i]->reader_id == 2){
+	//		p2_anchors[1].x = p_dists[i]->x;
+	//		p2_anchors[1].y = p_dists[i]->y;
+	//		d_dist[1] = p_dists[i]->d;
+	//	}if(p_dists[i]->reader_id == 3){
+	//		p2_anchors[2].x = p_dists[i]->x;
+	//		p2_anchors[2].y = p_dists[i]->y;
+	//		d_dist[2] = p_dists[i]->d;
+	//	}
+	//}
+	//Mat mat(3, 1, d_dist);
+
+	//if(is_anchor_changed){
+	//	cal_location->setAnchors(p2_anchors);
+	//	pt2 = cal_location->initPos(mat);
+	//} else{
+	//	pt2 = cal_location->estiPos(mat);
+	//}
+	//pt2_1 = cal_location->getError();
+	//x = pt2.x;
+	//y = pt2.y;
+	//z = 0;
+	//x1 = pt2_1.x;
+	//y1 = pt2_1.y;
+	//z1 = 0;
+}
+
+void Card::get_coordinate_3d( int cnt )
+{
+	double d_dist[ANCHOR_COUNT];
+	Point3 pt3, pt3_1;
+	for(int i = 0; i < cnt; i++){
+		d_dist[i] = p_dists_locate[i]->d;
+	}
+
+	Mat mat(ANCHOR_COUNT, 1, d_dist);
+	if(is_anchor_changed){
+		set_anchors(cnt);
+		pt3 = cal_location3->initPos(mat);
+	} else{
+		pt3 = cal_location3->estiPos(mat);
+	}
+	pt3_1 = cal_location3->getError();
+
+	x = pt3.x;
+	y = pt3.y;
+	z = pt3.z;
+	x1 = pt3_1.x;
+	y1 = pt3_1.y;
+	z1 = pt3_1.z;
+}
+
+double Card::get_speed()
+{
+	double speed = 0; 
+	// 计算速度
+	return speed;
+}
+
+void Card::set_anchors( int cnt )
+{
+	for(int i = 0; i < cnt; i++){
+		p3_anchors[i].x = p_dists[i]->x;
+		p3_anchors[i].y = p_dists[i]->y;
+		p3_anchors[i].z = p_dists[i]->z;
+	}
+	cal_location3->setAnchors(p3_anchors, ANCHOR_COUNT);
+	is_anchor_changed = false;
+}
+
+void Card::get_coordinate( int cnt )
+{
+//	if(cnt < 2) return; // 只有一个测量值,忽略不计算
+
+	int i = 0;
+	DistMap::iterator it = _dists.front()->mp_dist.begin();
+	for(; it != _dists.front()->mp_dist.end(); ++it, i++){
+		p_dists_locate[i] = it->second;
+	}
+
+	//int i = 0;
+	//int j = 0;
+	//for(int k = j; k < DIST_COUNT; k++,j++){
+	//	if(p_dists[k] == NULL) return;
+	//	//if(p_dists[k]->t == time_stamp_max){ // with the latest data
+	//	if(p_dists[k]->t == time_stamp_max - 1){  // with the last data
+	//		p_dists_locate[i] = p_dists[k];
+	//		i++;
+	//		if(i >= cnt) break;
+	//	}
+	//}
+	//if(cnt > 3){
+	////get_coordinate_3d(cnt);
+	////}else if(cnt > 2){
+	////	get_coordinate_2d(cnt);
+	//}else /*if(cnt > 1)*/{
+		_coordinate* coor_hist = new _coordinate;
+		_coordinate* coor_dest = new _coordinate;
+		if(!init_postion){
+			this->x = p_dists_locate[0]->x;
+			this->y = p_dists_locate[0]->y;
+			this->z = p_dists_locate[0]->z;
+			this->a = p_dists_locate[0]->a;
+			this->distance = p_dists_locate[0]->d;
+			this->t = p_dists_locate[0]->t;
+
+			this->last_x = p_dists_locate[0]->x;
+			this->last_y = p_dists_locate[0]->y;
+			this->last_z = p_dists_locate[0]->z;
+
+			init_postion = true;
+		}
+		coor_hist->x = this->x;
+		coor_hist->y = this->y;
+		coor_hist->z = this->z;
+		coor_hist->a = this->a;
+		coor_hist->t = this->t;
+		coor_hist->d = this->distance;
+		coor_hist->v = this->get_speed();
+
+		coor_dest->x = this->x;
+		coor_dest->y = this->y;
+		coor_dest->z = this->z;
+		coor_dest->a = this->a;
+		coor_dest->v = coor_hist->v;
+		//coor_dest->d = this->distance;
+		//coor_dest->d_offset = 0;
+		//coor_dest->reader_id = this->reader_id;
+		if(is_first_location){
+			algorithm_locate_ex(p_dists_locate, cnt, NULL, coor_dest, 500);
+		}else{
+			algorithm_locate_ex(p_dists_locate, cnt, coor_hist, coor_dest, 500);
+		}
+		//algorithm_locate(p_dists_locate, cnt, coor_hist, coor_dest, 500, z_offset);
+		this->x = coor_dest->x;
+		this->y = coor_dest->y;
+		this->a = coor_dest->a;
+		this->t = coor_dest->t;
+	//}
+	//this->x -= coor_offset_x;
+	//this->y -= coor_offset_y;
+}
+
+void Card::get_coordinate()
+{
+	get_coordinate(get_effictive_dist_count());
+}
+
+std::string Card::get_state_text()
+{
+	//if(this->state == 0){
+	//	return "正常";
+	//}
+	string ret = "";
+	if(status_help == STATUS_ERROR){
+		ret += "呼救,";
+	}
+	if(status_area_over_time == STATUS_ERROR){
+		ret += "区域超时,";
+	}else if(status_area_over_time == STATUS_ERROR){
+		ret += "超时,";
+	}
+	if(status_area_over_speed == STATUS_ERROR){
+		ret += "区域超速,";
+	}else if(status_over_speed == STATUS_ERROR){
+		ret += "超速,";
+	}
+	if(status_area_forbidden == STATUS_ERROR){
+		ret += "进入限制区域,";
+	}
+	if(status_call == STATUS_ERROR){
+		ret += "呼叫,";
+	}
+	if(status_power == STATUS_ERROR){
+		ret += "电量低,";
+	}else if(status_power == STATUS_ERROR_SERIOUS){
+		ret += "电量极低,";
+	}
+	if(status_lost == STATUS_ERROR){
+		ret += "进入盲区,";
+	}
+	if(ret.length() > 0){
+		ret = ret.substr(0, ret.length() - 1);
+		state = 1;
+	}else{
+		ret = "正常";
+		state = 0;
+	}
+	return ret;
+}
+
+std::string Card::get_acc_text()
+{
+	string ret = "";
+	status_moving = (accelerate_state && 0x01)? STATUS_ERROR : STATUS_NORMAL;
+
+	if(status_moving == STATUS_NORMAL){
+		ret += "静止";
+	}else if(status_moving == STATUS_ERROR){
+		ret += "运动";
+	}
+	return ret;
+}
+
+std::string Card::concat( int reader_id, int ant_id )
+{
+	char s[10];
+	sprintf(s, "%d-%d", reader_id, ant_id);
+	return s;
+}
+
+Reader::Reader(void)
+{
+	rec_time = reader_time = lost_time = time(NULL);
+	state = STATUS_DEVICE_NORMAL;
+}
+
+
+Reader::~Reader(void)
+{
+}
+
+std::string Reader::get_state_text()
+{
+	string ret = "";
+	if(state == STATUS_DEVICE_ERROR){
+		ret = "故障";
+	}else if(state == STATUS_DEVICE_NORMAL){
+		ret = "正常";
+	}
+	return ret;
+}
+
+Antenna::Antenna(void)
+{
+}
+
+
+Antenna::~Antenna(void)
+{
+}
+
+
+Area::Area(void)
+{
+	polygon_count = 0;
+	polygon = NULL;
+	map_id = area_id = area_type_id = 0 ;
+	area_name = area_type_name = path = "";
+	over_count_person = over_time_person = under_count_person = under_time_person = 0;
+	over_count_vehicle = over_time_vehicle = under_count_vehicle = under_time_vehicle = 0;
+
+	count_person = count_vehicle = count_card = 0;
+	is_area_over_time_person = is_area_over_time_vehicle = false; 
+	count_area_over_time_person = count_area_over_time_vehicle = 0;
+	time_over_time_person = time_over_time_vehicle = time(NULL);
+
+	is_area_over_count_person = is_area_over_count_vehicle = false;
+	count_area_over_count_person = count_area_over_count_vehicle = 0;
+	time_over_count_person = time_over_count_vehicle = time(NULL); 
+
+	is_area_forbidden_person = is_area_forbidden_vehicle = 0;
+	count_area_forbidden_person = count_area_forbidden_vehicle = 0;
+	time_forbidden_person = time_forbidden_vehicle = time(NULL); 
+}
+
+
+Area::~Area(void)
+{
+	if(polygon){
+		delete[] polygon;
+		polygon = NULL;
+	}
+}
+
+void Area::init_border( string sz_path )
+{
+	//std::vector<std::string> vec = split(sz_path, ",");
+	//if(vec.size() >= 4){
+	//	rect_left = atoi(vec[0].c_str());
+	//	rect_top = atoi(vec[1].c_str());
+	//	rect_right = atoi(vec[2].c_str());		
+	//	rect_bottom = atoi(vec[3].c_str());
+	//}else{
+	//	rect_left = rect_right = rect_top = rect_bottom = 0;
+	//}
+	std::vector<std::string> vec = split(sz_path, " ");
+	std::vector<std::string>::iterator it = vec.begin();
+	if(polygon){
+		delete[] polygon;
+		polygon = NULL;
+	}
+	polygon = new _point[vec.size()];
+	polygon_count = 0;
+	for(; it != vec.end(); ++it){
+		std::vector<std::string> subvec = split(it->c_str(), ",");
+		_point p;
+		p.x = get_vertex(subvec[0]);
+		p.y = get_vertex(subvec[1]);
+		p.z = 0;
+		polygon[polygon_count] = p;
+		polygon_count++;
+	}
+}
+
+std::vector<std::string> Area::split( std::string str,std::string pattern )
+{
+	std::string::size_type pos;  
+	std::vector<std::string> result;  
+	str+=pattern;//扩展字符串以方便操作  
+	unsigned int size=str.size();  
+
+	for(unsigned int i=0; i<size; i++){  
+		pos=str.find(pattern,i);  
+		if(pos<size){  
+			std::string s=str.substr(i,pos-i);  
+			result.push_back(s);  
+			i=pos+pattern.size()-1;  
+		}  
+	}  
+	return result; 
+}
+
+double Area::get_vertex( std::string src)
+{
+	std::string dest = "";
+	for(unsigned int i = 0; i < src.length(); i++){
+		if((src[i] >= '0' && src[i]<='9') || src[i]=='-' || src[i] == '.'){
+			dest += src[i];
+		}
+	}
+	return atof(dest.c_str());
+}
+
+bool Area::is_in_polygon( _point p )
+{
+	//int   i,j=polySides-1 ;
+	//bool  oddNodes=NO     ;
+
+	//for (i=0;i<polySides; i++) {
+	//	if((polyY[i]< y && polyY[j]>=y
+	//		||   polyY[j]<y && polyY[i]>=y)
+	//		&& (polyX[i]<=x || polyX[j]<=x)) {
+	//			oddNodes^=(polyX[i]+(y-polyY[i])/(polyY[j]-polyY[i])*(polyX[j]-polyX[i])<x);}
+	//	j=i;}
+
+	//returnoddNodes;
+
+	int counter = 0;
+	int i;
+	double xinters;
+	_point p1,p2;
+
+	p1 = polygon[0];
+	for (int i=1;i<= polygon_count;i++) {
+		p2 = polygon[i % polygon_count];
+		if (p.y > MIN(p1.y,p2.y)) {
+			if (p.y <= MAX(p1.y,p2.y)) {
+				if (p.x <= MAX(p1.x,p2.x)) {
+					if (p1.y != p2.y) {
+						xinters = (p.y-p1.y)*(p2.x-p1.x)/(p2.y-p1.y)+p1.x;
+						if (p1.x == p2.x || p.x <= xinters)
+							counter++;
+					}
+				}
+			}
+		}
+		p1 = p2;
+	}
+	return (counter % 2 == 0) ? false : true;
+}
+
+MapInfo::MapInfo( void )
+{
+
+}
+
+MapInfo::~MapInfo( void )
+{
+
+}
+
+Dept::Dept( int id, string name )
+{
+	dept_id = id;
+	dept_name = name;
+}
+
+Dept::Dept()
+{
+}
+
+Dept::~Dept()
+{
+}
+
+Adhoc::Adhoc()
+{
+	adhoc_id = 0;
+	x = 0;
+	y = 0;
+	z = 0;
+	idx = 0;
+}
+
+Adhoc::~Adhoc()
+{
+}

+ 572 - 0
classdef.h

@@ -0,0 +1,572 @@
+#ifndef YASERVER_CLASSDEF_H_
+#define YASERVER_CLASSDEF_H_
+
+#define DIST_COUNT 4
+#define ANCHOR_COUNT 4
+
+#define KALMAN_OFFSET_COOR 0.01
+#define KALMAN_OFFSET_MOVE 1
+#define KALMAN_OFFSET_RANGING 0.01
+#define KALMAN_INTERVAL 0.3
+
+#define KALMAN_OFFSET_COOR_TRI 0.01
+#define KALMAN_OFFSET_MOVE_TRI 1
+#define KALMAN_OFFSET_RANGING_TRI 0.09
+#define KALMAN_INTERVAL_TRI 1
+
+#define ANTENNA_COUNT 2
+#define ADHOC_COUNT 4
+#define READER_TIMEOUT 20
+#define OVER_TIME 480 * 60
+
+#define CARD_TYPE_ADHOC 3
+#define MAX_SEMACOUNT 64
+
+#include <string>
+#include <ctime>
+#include <map>
+#include <iostream>  
+#include <string>  
+#include <vector>
+#include <deque>
+//#include "winsock2.h"
+#include <kalman\locate.h>
+
+#define MIN(x,y) (x < y ? x : y)
+#define MAX(x,y) (x > y ? x : y)
+
+using namespace std;
+
+enum TIMER_ID
+{
+	TMR_SEND_COUNTING = 1,
+	TMR_SEND_ALARM,
+	TMR_SEND_DEVICE_STATE,
+	TMR_SEND_POSTION,
+	TMR_SYNC_READER_TIME,
+	TMR_CLEAR_CALL_TIMER,
+	TMR_SEND_CALL
+};
+
+enum ALARM_FLAG{
+	AF_CARD_OVER_COUNT = 1,
+	AF_CARD_OVER_TIME,
+	AF_CARD_OVER_SPEED,
+	AF_CARD_AREA_OVER_TIME,
+	AF_CARD_AREA_OVER_COUNT,
+	AF_CARD_AREA_FORBIDDEN,
+	AF_AREA_OVER_COUNT,
+	AF_AREA_OVER_TIME,
+	AF_AREA_FORBIDDEN
+};
+
+enum EDIT_TYPE_ID{
+	ET_INSERT = 0,
+	ET_UPDATE,
+	ET_DELETE
+};
+
+enum ALARM_TYPE_ID
+{
+	ATID_OVER_COUNT_PERSON = 1,
+	ATID_OVER_TIME_PERSON,
+	ATID_AREA_OVER_COUNT_PERSON,
+	ATID_AREA_OVER_TIME_PERSON,
+	ATID_AREA_LIMIT_PERSON,
+	ATID_AREA_FORBIDDEN_PERSON,
+	ATID_READER,
+	ATID_OVER_SPEED,
+	ATID_RUN_THE_RED_LIGHT,
+	ATID_POWER,
+	ATID_OVER_COUNT_VEHICLE,
+	ATID_OVER_TIME_VEHICLE,
+	ATID_AREA_OVER_COUNT_VEHICLE,
+	ATID_AREA_OVER_TIME_VEHICLE,
+	ATID_AREA_LIMIT_VEHICLE,
+	ATID_AREA_FORBIDDEN_VEHICLE
+};
+enum STATUS_DEVICE{
+	STATUS_DEVICE_NORMAL = 1,
+	STATUS_DEVICE_ERROR,
+};
+enum STATUS_CARD
+{
+	STATUS_NORMAL = 0,
+	STATUS_ERROR,
+	STATUS_ERROR_SERIOUS,
+	STATUS_ERROR_DEALED,
+	//STATUS_OVER_TIME = 1,
+	//STATUS_OVER_COUNT = 1,
+	//STATUS_OVER_SPEED = 1,
+	//STATUS_AREA_OVER_TIME = 1,
+	//STATUS_AREA_OVER_COUNT = 1,
+	//STATUS_AREA_OVER_SPEED = 1,
+	//STATUS_AREA_FORBIDDEN = 1,
+	//STATUS_HELP = 1,
+	//STATUS_HELP_DEALED,
+	//STATUS_CALL = 1,
+	//STATUS_POWER_LOWER = 1,
+	//STATUS_LOST = 1
+};
+
+enum STORE_CARD_DATA_FLAG{
+	TEST_LOCATE_COMPARE = 0,
+	TEST_LOCATE_DATA,
+	HIS_LOCATION,
+	HIS_RAW_DATA,
+	HIS_AREA_LOCATION_ENTER,
+	HIS_AREA_LOCATION_LEAVE,
+	RPT_ATTEND_DOWN,
+	RPT_ATTEND_UP,
+	ALARM_CARD_OVER_TIME_START,
+	ALARM_CARD_OVER_TIME_END,
+	ALARM_CARD_OVER_SPEED_START,
+	ALARM_CARD_OVER_SPEED_END,
+	//ALARM_CARD_LOST_START,
+	//ALARM_CARD_LOST_END,
+	ALARM_CARD_LOW_POWER_START,
+	ALARM_CARD_LOW_POWER_END,
+	ALARM_CARD_OVER_TIME_AREA_START,
+	ALARM_CARD_OVER_TIME_AREA_END,
+	ALARM_CARD_OVER_SPEED_AREA_START,
+	ALARM_CARD_OVER_SPEED_AREA_END,
+	ALARM_CARD_AREA_FORBIDDEN_START,
+	ALARM_CARD_AREA_FORBIDDEN_END,
+	ALARM_CARD_HELP_START,
+	ALARM_CARD_HELP_END
+};
+enum STORE_AREA_DATA_FLAG{
+	ALARM_AREA_OVER_COUNT_PERSON_START = 0,
+	ALARM_AREA_OVER_COUNT_PERSON_END,
+	ALARM_AREA_OVER_COUNT_VEHICLE_START,
+	ALARM_AREA_OVER_COUNT_VEHICLE_END,
+	ALARM_AREA_FORBIDDEN_PERSON_START,
+	ALARM_AREA_FORBIDDEN_PERSON_END,
+	ALARM_AREA_FORBIDDEN_VEHICLE_START,
+	ALARM_AREA_FORBIDDEN_VEHICLE_END,
+};
+
+enum STORE_READER_DATA_FLAG{
+	ALARM_READER = 0,
+	ALARM_READER_LOST_START,
+	ALARM_READER_LOST_END
+};
+
+enum STORE_MINE_DATA_FLAG{
+	ALARM_MINE_OVER_COUNT_PERSON_START = 0,
+	ALARM_MINE_OVER_COUNT_PERSON_END,
+	ALARM_MINE_OVER_COUNT_VEHICLE_START,
+	ALARM_MINE_OVER_COUNT_VEHICLE_END
+};
+
+enum LOCATE_TYPE
+{
+	LT_COORDINATE = 0,
+	LT_READER,
+};
+
+struct SQLTHREAD_DATA//写数据库线程传递的参数
+{
+	char* pText;//数据库语句地址指针
+	int nRepeatTimes;//已经重试几次
+};
+
+// 定位坐标
+struct _coordinate{
+	_coordinate(){}
+	int t; // 定位时间戳
+	int reader_id;
+	double d; // 距离
+
+	double x; // x坐标
+	double y; // y坐标
+	double z; // z坐标
+	double a; // 平面角度
+	double v; // 速度
+	int antenna_id;
+	double d_offset; // 与显示距离的偏移,用来修正单基站的情况
+};
+
+struct _point{ // 坐标
+	double x;
+	double y;
+	double z;
+};
+
+struct _call_info_card
+{
+	int card_id;
+	int card_type;
+	int call_type;
+	string str_card_id;
+	time_t start_time;
+	int time_out;
+	bool is_success;
+};
+typedef map<std::string, _call_info_card*> CallInfoCardMap;
+
+struct _call_info_reader
+{
+	bool is_call_all;
+	BYTE call_type;
+	int cards_count;
+	CallInfoCardMap mpCard;
+};
+typedef map<int, _call_info_reader*> CallInfoReaderMap;
+
+class Mine;
+class Area;
+class Reader;
+class Card;
+class MapInfo;
+class Dept;
+
+typedef map<string, Card*> CardMap;
+typedef map<int, Area*> AreaMap;
+typedef map<int, Reader*> ReaderMap;
+typedef map<int, MapInfo*> MapInfoMap;
+typedef map<int, Dept*> DeptMap;
+typedef map<int, string> AlarmTypeMap;
+typedef map<string, _coordinate*> DistMap;
+
+struct DistQueItem
+{
+	unsigned int t;
+	DistMap mp_dist;
+};
+
+// 地图
+class MapInfo{
+public:
+	MapInfo(void);
+	~MapInfo(void);
+public:
+	int map_id;
+	string map_path;
+	string map_name;
+	double map_width;
+	double map_height;
+	double map_scale;
+	int map_type;
+
+	AreaMap map_area_list;
+	ReaderMap map_reader_list;
+	CardMap map_card_list_person;
+	CardMap map_card_list_vehicle;
+};
+
+// 区域
+class Area  // 矩形
+{
+private:
+	std::vector<std::string> split(std::string str,std::string pattern);
+	double get_vertex(std::string src); // 顶点
+public:
+	Area(void);
+	~Area(void);
+	void init_border(string sz_path);
+	bool is_in_polygon(_point p);
+public:
+	int map_id;
+	int area_id;
+	string area_name;
+	string area_type_name;
+	int area_type_id;
+	string path; // 多边形
+	// 人员
+	int over_count_person;
+	int over_time_person;
+	int under_count_person;
+	int under_time_person;
+	// 车辆
+	int over_count_vehicle;
+	int over_time_vehicle;
+	int under_count_vehicle;
+	int under_time_vehicle;
+
+	int polygon_count;
+	_point* polygon;
+	// 坐标
+	//double x;
+	//double y;
+	//double z;
+	//double sr; // 短半径
+	//double lr; // 长半径
+
+	//double x1, y1, z1; // 矩形四个顶点
+	//double x2, y2, z2;
+	//double x3, y3, z3;
+	//double x4, y4, z4;
+
+	double rect_left;
+	double rect_right;
+	double rect_top;
+	double rect_bottom;
+
+	// 区域人数
+	int count_person;
+	int count_vehicle;
+	int count_card;
+	//
+	bool is_area_over_time_person; // 车辆超时
+	bool is_area_over_time_vehicle; // 人员超时
+	int count_area_over_time_person; // 超时人数
+	int count_area_over_time_vehicle; // 超时车数
+	time_t time_over_time_person; // 开始超时时间
+	time_t time_over_time_vehicle; // 开始超时时间
+
+	bool is_area_over_count_person; // 人员超员
+	bool is_area_over_count_vehicle; // 车辆超员
+	int count_area_over_count_person;
+	int count_area_over_count_vehicle;
+	time_t time_over_count_person; // 开始时间
+	time_t time_over_count_vehicle; // 开始时间
+
+	bool is_area_forbidden_person;
+	bool is_area_forbidden_vehicle;
+	int count_area_forbidden_person;
+	int count_area_forbidden_vehicle;
+	time_t time_forbidden_person; // 开始时间
+	time_t time_forbidden_vehicle; // 开始时间
+
+	CardMap area_card_list_person;
+	CardMap area_card_list_vehicle;
+};
+// 自组网预置坐标
+class Adhoc
+{
+public:
+	Adhoc();
+	~Adhoc();
+public:
+	int adhoc_id;
+	double x;
+	double y;
+	double z;
+	int idx;
+};
+
+// 天线
+class Antenna
+{
+public:
+	Antenna(void);
+	~Antenna(void);
+public:
+	int antenna_id;
+	double antenna_x;
+	double antenna_y;
+	double antenna_z;
+	double antenna_angle;
+};
+// 分站
+class Reader
+{
+public:
+	Reader(void);
+	~Reader(void);
+public:
+	int reader_id; // 分站号
+	string reader_name; // 分站名称
+	int device_type_id;
+	int pos_state; // 位置状态 1井上,2井下
+	string ip;
+	double reader_x; 
+	double reader_y;
+	double reader_z;
+	double reader_angle;
+
+	int map_id; // 所在地图
+	int area_id; // 所属区域
+	double map_scale; // 比例尺
+
+	//double rec_time; // 接收数据时间
+	time_t rec_time; 
+	time_t reader_time; // 分站时间
+	time_t lost_time;
+	int temperature; // 温度
+	int tick_count; // 计数器
+	int state; // 状态 0 正常, 1 故障
+
+	int state_old; // 上一次状态
+	Antenna* ant[ANTENNA_COUNT]; // 两个天线
+	Adhoc* adhoc[ADHOC_COUNT];// 自组网节点预置坐标
+	string get_state_text();
+};
+
+// 卡
+class Card
+{
+public:
+	Card(void);
+	~Card(void);
+	Card(string cardid, int cardtype,double z_offset, double offset_x = 12.0, double offset_y =12.0);
+public:
+	int card_type; // 卡类型 0x01人, 0x02车
+	//int64_t card_id; // 卡唯一标识, 高位为卡号,低位为卡类型, ((card_id << 8) | card_type)
+	string card_id;
+	
+	// 人员
+	string level; // 级别
+	string occupation; // 职务
+	// 人员、车辆
+	string id; // 编号,人员或车辆
+	string name; // 姓名、车辆名称
+	string number; // 身份证号码,车牌号码
+	string photo; // 照片
+	string company; // 单位
+	string department; // 部门
+	int dept_id;
+	int group_id;
+	string group; // 班组 
+	string worktype; // 工种、车辆类型
+
+	time_t deal_time; // 最后处理卡逻辑时间
+	time_t rec_time; // 最后接收时间
+	time_t down_time; // 入井时间
+	time_t up_time; // 升井时间
+	time_t enter_area_time; // 进入区域时间
+	time_t enter_reader_time; // 进入分站时间
+	time_t low_power_time; // 电量低开始时间
+	//time_t enter_park_time; // 回场时间
+	//time_t leave_park_time; // 出场时间, 开始工作时间
+	double coor_offset_x;
+	double coor_offset_y;
+	double x;
+	double y;
+	double z;
+	double a; // 上次定位时的角度
+	int t; // 上次定位时的时间戳
+	double z_offset;
+	bool init_postion;
+	bool is_first_location;
+
+	double xx;
+	double yy;
+	double zz;
+
+	double x1, x2, x3, x4;
+	double y1, y2, y3, y4;
+	double z1, z2, z3, z4;
+
+	double last_x;
+	double last_y;
+	double last_z;
+
+	int state;	// 0 正常, 共32bit,每个bit代表一个状态,从右起:
+				// 第一位 0x01 井下超时, 第二位 0x02 区域超时, 第三位 0x04 超速, 第四位 0x08, 进入限制区域
+
+				// 电量低、 呼叫、呼救
+	int status_over_time; // 0 未超时,1 超时
+	int status_over_speed; // 0 未超速,1 超速
+	int status_area_over_time; // 0 未区域超时, 1 区域超时
+	int status_area_over_speed; // 0 未区域超速, 1 区域超速
+	int status_area_forbidden; // 0 未进入限制区域, 1 进入限制区域
+	int status_help; // 0 未呼救, 1 呼救, 2 已处理呼救
+	int status_call; // 0 未呼叫 1 呼叫
+	int status_power; // 0 电量正常,1 电量低
+	int status_lost; // 0 未进入盲区,1 盲区状态
+	int status_moving; // 运动状态, 0 静止,1 启动
+
+	int map_id; // 当前地图
+	int map_id_old; // 上次测距所在地图
+	int area_id; // 当前区域	
+	int reader_id; // 当前分站
+	Reader* p_reader;
+	_coordinate** p_dists;
+	_coordinate** p_dists_locate;
+
+	deque<DistQueItem*> _dists;
+	int time_stamp_max; // 最大时间戳,即需要计算定位的时间戳
+	//int get_pos_state() const { return pos_state; }
+	//void set_pos_state(int val) ;
+	//int get_pos_state_count() const { return pos_state_count; }
+
+	int pos_state; // 位置状态,0初始化,1井下,2井上,3车场分站
+	int pos_state_old;
+	int pos_state_last;
+	int pos_state_count; // 当前位置状态确认次数
+
+	//int last_area_type_id;
+	//int cur_area_type_id;
+
+	bool issent; // true 已发送至客户端,false 新数据,需要发送至客户端
+	bool issaved; //true 已保存到数据库,false 生成新的考勤记录,需要保存到数据库
+	bool isdealed; // 已经处理
+	bool isreceive; // 接收到
+	bool is_pos_changed;
+	bool is_init_kalman ;
+	bool is_hist;
+	bool is_need_cal;
+
+	bool is_mine_over_time; // 是否井下超时
+	bool is_area_over_time; // 是否区域超时, 区域超时分车辆超时、人员超时
+	time_t time_area_over_time; // 区域超时开始时间
+	time_t time_over_time; // 井下超时开始时间
+	time_t time_area_forbidden; // 进入限制区域时间
+	time_t time_over_speed; // 超速开始时间
+	time_t time_low_power;
+
+	void set_reader(Reader* preader);
+	bool is_pos_state_changed(int nval); // 入\升井状态变化
+	void add_dist(_coordinate* dist);
+	string concat(int reader_id, int ant_id);
+	time_t get_working_time();
+	string get_state_text();
+	string get_acc_text();
+	double get_speed();
+	int get_effictive_dist_count(int offset = 0);
+public:
+	// 滤波算法相关
+	//CalLocation* cal_location;
+	CalLocation3* cal_location3;
+	//Point2* p2_anchors;
+	Point3* p3_anchors;
+	//bool is_init_kalman;
+	//int m_max_stamp; // 最大的时间戳,即最近采集的数据
+	bool is_anchor_changed;
+	void get_coordinate();
+	void get_coordinate(int cnt);
+	void get_coordinate_3d(int cnt);
+	void get_coordinate_2d(int cnt);
+	void set_anchors(int cnt);
+public: // 采集到的底层数据
+	int reader_tickcount; 
+	int time_stamp; // 定位时间戳
+	int ranging_type; // 报文类型 tof,tdoa
+	int accelerate_state; // 加速度
+	int antenna_id; // 天线号
+	double antenna_angle; // 天线角度
+	double distance; // 距离
+	int64_t flying_time; // 飞行时间
+	int power_state; // 电量
+
+	int time_stamp_last; // 定位时间戳
+	int context_type_last; // 报文类型 tof,tdoa
+	int accelerate_state_last; // 加速度
+	int antenna_id_last; // 天线号
+	double antenna_angle_last; // 天线角度
+	double distance_last; // 距离	
+	int64_t flying_time_last; // 飞行时间
+	int power_state_last; // 电量
+
+	string str_his_time;
+	string str_rec_time;
+};
+
+class Dept
+{
+public:
+	Dept();
+	~Dept();
+	Dept(int id, string name);
+private:
+public:
+	int dept_id;
+	string dept_name;
+	
+	CardMap dept_card_list_person;
+	CardMap dept_card_list_vehicle;
+};
+
+#endif //YASERVER_CLASSDEF_H_

+ 207 - 0
client_thread.cpp

@@ -0,0 +1,207 @@
+#include "stdafx.h"
+#include "classdef.h"
+#include "winsock2.h"
+#include "constdef.h"
+#include <sys/stat.h>
+#include <map>
+using namespace std;
+
+void sendHead(SOCKET s, int state, char* fileExtension, char* version);
+bool sendContent(SOCKET s, char* filePath);
+map<string, string> map_param;
+
+char ascii_string[10000];
+char *char_to_ascii(char ch){
+	char *ascii_str;
+	ascii_string[0] = 0;
+	ascii_str = ascii_string;
+	if(isgraph(ch)){
+		*ascii_str++ = ch;
+	}else if(ch == ' '){
+		*ascii_str++ =ch;
+	}else if(ch == '\n' || ch == '\r'){
+		*ascii_str++ =ch;
+	}else{
+		*ascii_str++ ='.';
+	}
+	*ascii_str = 0;
+	return ascii_string;
+}
+
+void parse_interface(){
+	string username, inter_face, json_data, version; 
+	map<string, string>::iterator it_para = map_param.begin();
+	for(; it_para != map_param.end(); ++it_para){
+		if(it_para->first == PARAM_NAME_USERNAME){
+			username = it_para->second;
+		}else if(it_para->first == PARAM_NAME_INTERFACE){
+			inter_face = it_para->second;
+		}else if(it_para->first == PARAM_NAME_DATA){
+			json_data = it_para->second;
+		}else if(it_para->first == PARAM_NAME_VERSION){
+			version = it_para->second;
+		}
+	}
+	//
+	if(version == "1.0"){
+		if(inter_face == INTERFACE_NAME_SETLIMITVALUE){
+
+		}else if(inter_face == INTERFACE_NAME_CALLCARD){
+
+		}else if(inter_face == INTERFACE_NAME_CLEARCARD){
+
+		}else if(inter_face == INTERFACE_NAME_EDITAREA){
+
+		}else if(inter_face == INTERFACE_NAME_EDITSTATION){
+
+		}else if(inter_face == INTERFACE_NAME_EDITPATH){
+
+		}else if(inter_face == INTERFACE_NAME_EDITCARD){
+
+		}else if(inter_face == INTERFACE_NAME_EDITSTAFFER){
+
+		}else if(inter_face == INTERFACE_NAME_EDITVEHICLE){
+
+		}
+	}
+}
+
+void parse_param_data(char content[], int number){
+	//char temp[1000];
+	int i,j = 0;
+	bool bkey = true;
+	string para_key = "", para_value = "";
+
+	for(i = 0; i < number; i++){
+		if(content[i] == '&'){
+			bkey = true;
+			para_value += '\0';
+			i++;
+			map_param.insert(make_pair(para_key, para_value));
+			para_key = "";
+			para_value = "";
+			j = 0;
+		}
+		if(content[i] == '='){
+			bkey = false;
+			para_key += '\0';
+			i++;
+			j = 0;
+		}		
+		if(bkey){
+			para_key += content[i];
+		}else{
+			para_value += content[i];
+		}
+		j++;
+	}
+	para_value += '\0';
+	map_param.insert(make_pair(para_key, para_value));
+}
+
+void parse_server_data(char content[], size_t number){
+	char temp[1024];
+	char str1[1024];
+	char str2[1024];
+	char str3[1024];
+	char paralen[20];
+	size_t i, j, k = 0, m = 0;
+	char entity_content[1024];
+
+	for(i = 0; i < number; i++){
+		if(content[i] != '\n'){
+			k++;
+			continue;
+		}
+		for(j = 0; j < k; j++)
+			temp[j] = content[j + i - k];
+		temp[j] = '\0';
+		if(strstr(temp, "GET") || strstr(temp, "POST")){ // 请求行为
+			sscanf_s(temp, "%s %s %s", str1, str2, str3); // 命令,路径,协议版本
+		}
+		//if(strstr(temp, "Accept:")){ // 数据文件包括(Accept:)
+
+		//}
+		//if(strstr(temp, "Referer")){ // 转移地址(Referer)
+
+		//}
+		//if(strstr(temp, "Accept-Language")){ // 使用的语言 
+
+		//}
+		//if(strstr(temp, "Accept-Encoding")){ // 编码方式
+
+		//}
+		//if(strstr(temp, "If-Modified-Since")){ // 上次修改时间
+
+		//}
+		//if(strstr(temp, "If-Node-Match")){ // 
+
+		//}
+		//if(strstr(temp, "User-Agent")){ // 用户浏览器信息
+
+		//}
+		//if(strstr(temp, "Host")){ // 访问的主机
+
+		//}
+		//if(strstr(temp, "Connection")){ // 连接状态
+
+		//}
+		//if(strstr(temp, "Cookie")){ // cookie
+
+		//}
+		//if(strstr(temp, "Cache-Control:")){ // 
+
+		//}
+		//if(strstr(temp, "Content-Type:")){ // 实体数据格式
+		//
+		//}
+		if(strstr(temp, "Content-Length:")){ // 数据长度
+			//sscanf(temp, "%s%d", temp, paralen);
+			m = 0;
+			for(j = 15; j < strlen(temp); j++){
+				if(temp[j] != ' ' && temp[j] != '\n'){
+					paralen[m] = temp[j];
+					m++;
+				}
+			}
+			paralen[m] = '\0';
+			m = atoi(paralen);
+		}
+		// 实体数据
+		if((content[i]  == '\n') && content[i + 1] == '\r' && content[i + 2] == '\n'){
+			if(i + 3 == strlen(content)){ // 无数据
+				break;
+			}
+			//for (j = 0; j < strlen(content) - i - 3; j++){
+			for(j = 0; j < m; j++){
+				entity_content[j] = content[i + 3 + j];
+			}
+			entity_content[j] = '\0';
+
+			string estr = entity_content;
+			// 解析参数
+			parse_param_data(entity_content, m);
+			break;
+		}
+		k = 0;		
+	}
+}
+
+DWORD WINAPI clientThread(LPVOID lparam)
+{
+	PARA* para = (PARA*)lparam;
+	char buf[MAXSIZE], filePath[200], cmd[50], version[50], fileExtension[50]={'\0'};
+	int recvCount;
+
+	filePath[0]='.';
+	//int aa, bb, cc = 0;
+	//char temp1[200], temp2[200] = {0};
+	recvCount = recv(para->s, buf, MAXSIZE, 0);
+	sscanf_s(buf, "%s %s %s", cmd, filePath + 1, version);
+
+	parse_server_data(buf, recvCount);
+
+	closesocket(para->s);
+	delete para;
+	return 0;
+}

+ 206 - 0
constdef.h

@@ -0,0 +1,206 @@
+#ifndef _SERVER_CONST_DEF_H_
+#define _SERVER_CONST_DEF_H_
+
+#define TEST_WEB_URL "http://localhost:8080/yaloc/servlet/main?"
+//#define TEST_WS_URL  "ws://localhost:8086" 
+//#define TEST_WS_URL  "ws://192.168.0.36:8086"
+#define TEST_WS_URL  "ws://182.92.224.191:8086"
+#define TEST_CONFIRM_COUNT 1
+#define PARAM_NAME_USERNAME "username"
+#define PARAM_NAME_INTERFACE "interface"
+#define PARAM_NAME_DATA	"data"
+#define PARAM_NAME_VERSION "version"
+#define JSON_ROOT_KEY_CMD "cmd"
+#define JSON_ROOT_KEY_DATA "data"
+// 采集端接收接口
+#define JSON_CMD_VALUE_SET_LIMIT_VALUE "set_limit_value"
+#define JSON_CMD_VALUE_CALL_CARD_START "call_card_start"
+#define JSON_CMD_VALUE_CALL_CARD_CANCEL "call_card_cancel"
+#define JSON_CMD_VALUE_CLEAR_CARD "clear_card"
+#define JSON_CMD_VALUE_DEAL_HELP "deal_help"
+#define JSON_CMD_VALUE_META_DATA_CHANGED "meta_data_changed"
+#define JSON_KEY_NAME "name"
+#define JSON_KEY_ID "id"
+#define JSON_KEY_OP_TYPE "op_type"
+
+#define JSON_KEY_NAME_MAP "map"
+#define JSON_KEY_NAME_AREA "area"
+#define JSON_KEY_NAME_PATH "path"
+#define JSON_KEY_NAME_READER "reader"
+#define JSON_KEY_NAME_CARD "card"
+#define JSON_KEY_NAME_STAFF "staff"
+#define JSON_KEY_NAME_VEHICLE "vehicle"
+#define JSON_KEY_OP_TYPE_INSERT "INSERT"
+#define JSON_KEY_OP_TYPE_UPDATE "UPDATE"
+#define JSON_KEY_OP_TYPE_DELETE "DELETE"
+//#define JSON_CMD_VALUE_EDIT_MAP "edit_map"
+//#define JSON_CMD_VALUE_EDIT_AREA "edit_area"
+//#define JSON_CMD_VALUE_EDIT_STATION "edit_station"
+//#define JSON_CMD_VALUE_EDIT_PATH "edit_path"
+//#define JSON_CMD_VALUE_EDIT_CARD "edit_card"
+//#define JSON_CMD_VALUE_EDIT_STAFFER "edit_staffer"
+//#define JSON_CMD_VALUE_EDIT_VEHICLE "edit_vehicle"
+#define JSON_CMD_VALUE_REQUEST_ALL_POSTION "request_all_postion"
+
+#define JSON_KEY_CALL_CARD_CALL_TIME_OUT "call_time_cout"
+#define JSON_KEY_CALL_CARD_CALL_TIME "call_time"
+#define JSON_KEY_CALL_CARD_CALL_TYPE "call_type_id"
+#define JSON_KEY_CALL_CARD_USER_NAME "user_name"
+#define JSON_KEY_CALL_CARD_CALL_TIME "call_time"
+#define JSON_KEY_CALL_CARD_STATIONS "stations"
+#define JSON_KEY_CALL_CARD_STATION_ID "stationid"
+#define JSON_KEY_CALL_CARD_CARDS "cards"
+#define JSON_KEY_CALL_CARD_CARD_ID "cardid"
+#define JSON_KEY_CALL_CARD_CARD_TYPE_ID "cardtype"
+
+#define JSON_KEY_EDIT_MAP_ID "map_id"
+#define JSON_KEY_EDIT_AREA_ID "areaid"
+#define JSON_KEY_EDIT_READER_ID "stationid"
+#define JSON_KEY_EDIT_CARD_ID "cardid"
+#define JSON_KEY_EDIT_CARD_TYPE "cardtype"
+#define JSON_KEY_EDIT_STAFFER_ID "stafferid"
+#define JSON_KEY_EDIT_VEHICLE_ID "vehicleid"
+#define JSON_KEY_EDIT_EDIT_TYPE_ID "edittype"
+
+// 采集端调用接口
+#define JSON_CMD_VALUE_LOGIN "login"
+#define JSON_CMD_VALUE_LOGOUT "logout"
+#define JSON_KEY_USERNAME "user_name"
+#define JSON_KEY_PASSWORD "user_pass"
+#define JSON_VALUE_USERNAME "COLLECTOR"
+#define JSON_VALUE_PASSWORD "666666"
+//#define JSON_VALUE_USERNAME "lihz"
+//#define JSON_VALUE_PASSWORD "000"
+//#define JSON_KEY_VEHICLE_ID "编号"
+//#define JSON_KEY_VEHICLE_TYPE "车辆类型"
+//#define JSON_KEY_VEHICLE_DEPT "部门"
+//#define JSON_KEY_VEHICLE_NO "车牌号"
+#define JSON_KEY_CARD_ID "card_id" //"卡号"
+#define JSON_KEY_CARD_TYPE_ID "card_type_id"
+#define JSON_KEY_CARD_NUM "number" //"编号"
+#define JSON_KEY_CARD_NAME "name" // "名称"
+#define JSON_KEY_CARD_WORKTYPE "work_type" // "类型"
+#define JSON_KEY_CARD_COMP "company" // "单位"
+#define JSON_KEY_CARD_DEPT "dept" // "部门"
+#define JSON_KEY_REC_TIME "rec_time" // "接收时间"
+#define JSON_KEY_DOWN_TIME "down_time" // "入井时间"
+#define JSON_KEY_UP_TIME "up_time" // "升井时间"
+#define JSON_KEY_ENTER_PARK_TIME "enter_park_time" // "回场时间"
+#define JSON_KEY_LEAVE_PARK_TIME "leave_park_time" // "出场时间"
+#define JSON_KEY_WORK_TIME "work_time" // "工作时间"
+#define JSON_KEY_ENTER_AREA_TIME "enter_area_time" // "进入区域时间"
+#define JSON_KEY_ENTER_READER_TIME "enter_reader_time" // "进入分站时间"
+#define JSON_KEY_CORDINATE_X "x"
+#define JSON_KEY_CORDINATE_Y "y"
+#define JSON_KEY_CORDINATE_Z "z"
+#define JSON_KEY_STATE "state" // "状态"
+#define JSON_KEY_STATE_DESC "state_desc" // "状态"
+#define JSON_KEY_MOVING_STATE "status_moving" // 运动状态
+#define JSON_KEY_ANGLE "angle" // "角度"
+#define JSON_KEY_MAP_ID "map_id" // "地图编号"
+#define JSON_KEY_MAP_NAME "map_name" // "地图名称"
+#define JSON_KEY_MAP_PATH "map_path" // "地图路径"
+#define JSON_KEY_MAP_HEIGHT "map_height" // "地图高度"
+#define JSON_KEY_MAP_WIDTH "map_width" // "地图宽度"
+#define JSON_KEY_MAP_SCALE "map_scale" // "地图比例"
+#define JSON_KEY_MAP_TYPE "map_type" // "地图类型"
+#define JSON_KEY_DEPT_ID "dept_id"
+// id, name, type, map_id
+#define JSON_KEY_AREA_ID "area_id" // "区域编号"
+#define JSON_KEY_AREA_TYPE "area_type" // "区域类型"
+#define JSON_KEY_AREA_NAME "area_name" // "区域名称"
+#define JSON_KEY_AREA_X "area_x" // "区域坐标"
+#define JSON_KEY_AREA_Y "area_y" // 
+#define JSON_KEY_AREA_Z "area_z" // 
+#define JSON_KEY_AREA_R "area_radius" // "区域半径"
+// id, name, angle, x, y, z, type, map_id, area_id
+#define JSON_KEY_READER_ID "reader_id" // "分站编号"
+#define JSON_KEY_READER_NAME "reader_name" // "分站名称"
+#define JSON_KEY_READER_POS_STATE "reader_type" // "分站类型"
+#define JSON_KEY_READER_STATE "reader_state" // "分站状态"
+#define JSON_KEY_ANTENNA_ID "ant_id" // "天线编号"
+#define JSON_KEY_ANTENNA_NAME "ant_name" // "天线名称"
+#define JSON_KEY_DEV_MAP "dev_map"
+#define JSON_KEY_DEV_AREA "dev_area"
+#define JSON_KEY_DEV_READER "dev_reader"
+#define JSON_KEY_DEV_CARD "dev_card"
+#define JSON_KEY_DEV_TRAFFIC "dev_traffic"
+#define JSON_KEY_DEV_TURNOUT "dev_turnout"
+#define JSON_KEY_DEV_LOUDSPEEKER "dev_loudspeeker"
+// down_mine,up_mine
+#define JSON_CMD_VALUE_DOWN_MINE "down_mine"
+#define JSON_CMD_VALUE_UP_MINE "up_mine"
+#define JSON_CMD_VALUE_COUNTING "counting"
+#define JSON_CMD_VALUE_DEV_STATE "device_state"
+#define JSON_CMD_VALUE_ALARM "alarm"
+#define JSON_CMD_VALUE_CALL "CALL"
+#define JSON_CMD_VALUE_PUSH "PUSH"
+#define JSON_CMD_VALUE_USER "USER"
+#define JSON_CMD_VALUE_WS_ERR "WS_ERR"
+// pos_map
+#define JSON_CMD_VALUE_POS_MAP "pos_map"
+#define JSON_CMD_VALUE_POSITION_ALL "position_all"
+#define JSON_KEY_POS_CARD "pos_card"
+#define JSON_KEY_POS_MAP "pos_map"
+// device state, stat_map
+#define JSON_KEY_DEV_STATE_MAP_ID "map_id"
+#define JSON_KEY_DEV_STATE_DEVICES "devices"
+#define JSON_KEY_DEV_STATE_DEVICE_ID "device_id"
+#define JSON_KEY_DEV_STATE_STATE "state"
+#define JSON_KEY_DEV_STATE_STATE_DESC "state_desc"
+#define JSON_KEY_DEV_STATE_DEVICE_TYPE_ID "device_type_id"
+#define JSON_KEY_DEV_STATE_TIME "time"
+//#define JSON_KEY_STAT_MAP_STAT_TRAFFIC "stat_traffic"
+//#define JSON_KEY_STAT_MAP_STAT_TURNOUT "stat_turnout"
+//#define JSON_KEY_STAT_MAP_STAT_LOUDSPEEKER "stat_loudspeeker"
+// counting
+#define JSON_KEY_COUNTING_COUNT_TOTAL "total" // 总卡数
+#define JSON_KEY_COUNTING_COUNT_VEHICLE "vehicle" // 总车数
+#define JSON_KEY_COUNTING_COUNT_PERSON "staff" // 总人数
+#define JSON_KEY_COUNTING_MAP_COUNT "maps"
+#define JSON_KEY_COUNTING_MAP_ID "id"
+#define JSON_KEY_COUNTING_MAP_COUNT_TOTAL "total" // 当前图中总数
+#define JSON_KEY_COUNTING_MAP_COUNT_PERSON "staff" // "map_count_vehicle" // 当前图车数
+#define JSON_KEY_COUNTING_MAP_COUNT_VEHICLE "vehicle"// "map_count_person" // 当前图车数
+#define JSON_KEY_COUNTING_AREA_COUNT "areas" 
+#define JSON_KEY_COUNTING_AREA_ID "id" 
+#define JSON_KEY_COUNTING_AREA_COUNT_TOTAL "total" // 区域总卡数
+#define JSON_KEY_COUNTING_AREA_COUNT_PERSON "staff" // 区域人数
+#define JSON_KEY_COUNTING_AREA_COUNT_VEHICLE "vehicle" // 区域车数
+#define JSON_KEY_COUNTING_DEPT_COUNT "depts" 
+#define JSON_KEY_COUNTING_DEPT_ID "id"
+//#define JSON_KEY_COUNTING_DEPT_NAME "dept_name"
+#define JSON_KEY_COUNTING_DEPT_COUNT_TOTAL "total"
+#define JSON_KEY_COUNTING_DEPT_COUNT_VEHICLE "vehicle"
+#define JSON_KEY_COUNTING_DEPT_COUNT_PERSON "staff"
+// alarm
+#define JSON_KEY_ALARM_OVER_COUNT_PERSON "over_count_person"
+#define JSON_KEY_ALARM_OVER_COUNT_VEHICLE "over_count_vehicle"
+#define JSON_KEY_ALARM_OVER_TIME_PERSON "over_time_person"
+#define JSON_KEY_ALARM_OVER_TIME_VEHICLE "over_time_vehicle"
+#define JSON_KEY_ALARM_OVER_SPEED_VEHICLE "over_speed_vehicle"
+#define JSON_KEY_ALARM_AREA_FORBIDDEN "area_forbidden"
+
+#define JSON_KEY_ALARM_GLOBAL "global"
+#define JSON_KEY_ALARM_ITEM "item"
+#define JSON_KEY_ALARM_DETAIL "detail"
+#define JSON_KEY_ALARM_MAX "max"
+#define JSON_KEY_ALARM_CURRENT "current"
+#define JSON_KEY_ALARM_AREA "areas"
+#define JSON_KEY_ALARM_AREA_ID "area_id"
+
+#define JSON_KEY_ALARM_ALARMS "alarms"
+#define JSON_KEY_ALARM_PERSON "person"
+#define JSON_KEY_ALARM_VEHICLE "vehicle"
+
+#define JSON_KEY_ALARM_READER "readers"
+#define JSON_KEY_ALARM_READER_ID "reader_id"
+#define JSON_KEY_ALARM_TYPE_ID "alarm_type_id"
+#define JSON_KEY_ALARM_TYPE_NAME "alarm_type_name"
+#define JSON_KEY_ALARM_START_TIME "alarm_start_time"
+
+#define JSON_KEY_ALARM_STAFF "staff"
+#define JSON_KEY_ALARM_STAFFER_ID "staffer_id"
+#define JSON_KEY_ALARM_VEHICLE_ID "vehicle_id"
+
+#endif // !_SERVER_CONST_DEF_H_

+ 60 - 0
def.h

@@ -0,0 +1,60 @@
+#ifndef _SERVER_DEF_H
+#define _SERVER_DEF_H
+
+#define SERVER_NULLSTRING_W L""
+#define SERVER_NULLSTRING ""
+
+//DB
+#define FILEPATH_SERVER_CONFIG "..\\config.ini"
+#define CONF_SECT_DB "DB"
+#define CONF_SECT_DB_BK "DB_2"
+#define CONF_DB_KEY_HOST "host"
+#define CONF_DB_KEY_USER "user"
+#define CONF_DB_KEY_PWD "password"
+#define CONF_DB_KEY_DBNAME "dbname"
+#define CONF_DB_KEY_ENCODING "encoding"
+#define CONF_DB_KEY_PORT "port"
+#define CONF_DB_KEY_DB_BACKUP "dbbackup"
+
+#define CONF_DB_DEFAULT_VALUE_HOST "123.57.155.179"
+#define CONF_DB_DEFAULT_VALUE_USER "root"
+#define CONF_DB_DEFAULT_VALUE_PWD "password"
+#define CONF_DB_DEFAULT_VALUE_DBNAME "yaloc"
+#define CONF_DB_DEFAULT_VALUE_ENCODING "gb2312"
+
+#define CONF_SECT_SERVER_SETTING "SERVER_SETTING"
+#define CONF_SERVER_WS_URL "websocket_url"
+#define CONF_SERVER_WS_URL_BK "websocket_url_bk"
+#define CONF_SERVER_USE_FILTER "use_filter"
+#define CONF_SERVER_RECON_SERVER "recon_server"
+#define CONF_SERVER_RECON_DB "recon_db"
+#define CONF_SERVER_READER_LOST "reader_lost"
+#define CONF_SERVER_CARD_LOST "card_lost"
+#define CONF_SERVER_TIMING_INTERVAL "timing_interval"
+#define CONF_SEND_JSON_POSION "interval_send_json_postion"
+#define CONF_SEND_JSON_COUNTING "interval_send_json_counting"
+#define CONF_SEND_JSON_ALARM "interval_send_json_alarm"
+#define CONF_SEND_JSON_DEVICE "interval_send_json_device"
+#define CONF_SERVER_SAMPLING_INTERVAL "sampling_interval"
+#define CONF_SERVER_COORDINATE_ERROR "coor_error"
+#define CONF_SERVER_RANGING_ERROR "ranging_error"
+#define CONF_SERVER_MOVING_ERROR "moving_error"
+#define CONF_SERVER_Z_OFFSET "z_offset"
+#define CONF_SERVER_LOCATE_TYPE "locate_type"
+
+#define CONF_SECT_SERVER_LOG "SERVER_LOG"
+#define CONF_LOG_SYS_STATUS "system_status"
+#define CONF_LOG_RAW_DATA "raw_data"
+#define CONF_LOG_PARSE_DATA "parse_data"
+#define CONF_LOG_SEND_EVENT "send_event"
+#define CONF_LOG_REV_EVENT "rev_event"
+
+#define CONF_SECT_MONITOR "MONITOR"
+#define CONF_MONITOR_SERVER_HANDLE "server_handle"
+#define CONF_MONITOR_SERVER_PATH "server_path"
+#define CONF_MONITOR_MONITOR_HANDLE "monitor_handle"
+#define CONF_MONITOR_MONITOR_PATH "monitor_path"
+#define CONF_MONITOR_IS_MASTER "is_master"
+#define CONF_MONITOR_IS_DEAFAULT "is_default"
+
+#endif

+ 92 - 0
listening_thread.cpp

@@ -0,0 +1,92 @@
+#include "stdafx.h"
+
+#include <stdio.h>
+#include "winsock2.h"
+#include "classdef.h"
+#include "constdef.h"
+#include <process.h>
+
+#pragma comment (lib, "Ws2_32.lib")
+
+DWORD WINAPI clientThread(LPVOID lparam);
+
+unsigned int __stdcall listeningThread(void *param)
+{
+	SOCKET local_socket, client_socket;
+	sockaddr_in service, client_sock_addr;
+	PARA* clientInfo;
+
+	local_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+	if(local_socket == INVALID_SOCKET)
+	{
+		//printf("socket failed\n");
+		exit(0);
+	}
+
+	service.sin_family = AF_INET;
+	service.sin_addr.S_un.S_addr = INADDR_ANY;
+	service.sin_port = htons(int(param));
+
+
+	if(bind(local_socket, (sockaddr*)&service, sizeof(sockaddr)) == SOCKET_ERROR)
+	{
+		//printf("bind failed\n");
+		exit(0);
+	}
+
+	if(listen(local_socket, BACKLOG) == SOCKET_ERROR)
+	{
+		//printf("listen failed\n");
+		exit(0);
+	}
+
+	//printf("****************************Web server start up!****************************\n\n");
+
+	while(1)
+	{
+		int sockaddrLength = sizeof(sockaddr);
+		client_socket = accept(local_socket, (sockaddr*)&client_sock_addr, &sockaddrLength);
+		if(client_socket == INVALID_SOCKET)
+		{
+			//printf("accept failed\n");
+			continue;
+		}
+
+		clientInfo = new PARA;
+		clientInfo->s = client_socket;
+		memcpy((void*)&(clientInfo->addr), &client_sock_addr, sizeof(client_sock_addr));
+		//clientInfo.addr=clientSockaddr;
+
+		clientThread((LPVOID)clientInfo);
+
+		//DWORD lpThreadId;
+		//HANDLE hThread;
+		//hThread = CreateThread(NULL, 0, clientThread, (LPVOID)clientInfo, 0, &lpThreadId);
+		//if(hThread != NULL)
+		//{
+		//	//printf("------------------Start one connect!------------------\n");
+		//}
+		//else
+		//{
+		//	//printf("------------------One client connection failed!\n------------------");
+		//}
+	}
+	//closesocket(local_socket);
+	//WSACleanup();
+}
+
+//void main()
+//{
+//	WORD wVersionRequested;
+//	WSADATA wsaData;
+//	int err;
+//	wVersionRequested = MAKEWORD(2, 2);
+//	err = WSAStartup(wVersionRequested, &wsaData);
+//	if (err != 0) {
+//		return;
+//	}
+//
+//	_beginthreadex(NULL, 0, listeningThread, (void *) 8120, 0, NULL);
+//	_beginthreadex(NULL, 0, listeningThread, (void *) 8121, 0, NULL);
+//	Sleep(INFINITE);
+//}

+ 490 - 0
locate_algorithm.cpp

@@ -0,0 +1,490 @@
+#include "stdafx.h"
+#include "locate_algorithm.h"
+#include <math.h>
+#include <algorithm>
+#include "../common/matrix/_Matrix.h"
+using namespace std;
+
+// ant 天线, tar定位目标, d 测距
+void AOAformula( struct _coordinate* ant, double angle, struct _coordinate* tar, bool is_line /*= false*/, double z_offset /*= 0*/ )
+{
+	double aa = sin(angle);
+	double bb = cos(angle);
+	double h = ant->z;
+	if(is_line){
+		h = z_offset;
+	}
+	tar->x = ant->x + sqrt(ant->d * ant->d - h * h) * cos(angle); 
+	tar->y = ant->y + sqrt(ant->d * ant->d - h * h) * sin(angle);
+	tar->z = ant->z; // 高度
+	tar->a = ant->a; // 角度
+	tar->t = ant->t; // 时间戳
+	tar->d_offset = ant->d_offset;
+	tar->reader_id = ant->reader_id;
+	tar->d = ant->d;
+}
+
+// ant 天线, last 上次坐标
+double Distanceformula( struct _coordinate* ant, struct _coordinate* last )
+{
+	double x0,y0;
+	double tan_diff = tan(last->a) - tan(ant->a);
+	double ret = 0;
+	if(tan_diff == 0){
+		ret = sqrt((ant->x - last->x) * (ant->x - last->x) +  (ant->y - last->y) * (ant->y - last->y));
+	}else{
+		x0 = (last->x * tan(last->a) - ant->x * tan(ant->a) + ant->y - last->y) / (tan(last->a) - tan(ant->a));
+		y0 = (((last->x - ant->x) * tan(last->a) * tan(ant->a)) + ant->y * tan(last->a) - last->y * tan(ant->a)) / (tan(last->a) - tan(ant->a));
+		ret = sqrt((x0 - ant->x) * (x0 - ant->x) + (y0 - ant->y) * (y0 - ant->y)) 
+			+ sqrt((x0 - last->x) * (x0 - last->x) + (y0 - last->y) * (y0 - last->y));
+	}
+	// n = Nodeformula( n1, n2);
+	return ret;
+}
+
+// 接收到的新数据
+void algorithm_locate( struct _coordinate** coor_list, int coor_size, struct _coordinate* hist, struct _coordinate* dest, double dist_limit, double z_offset)
+{
+	double d0;  //历史定位坐标与实时定位坐标之间的距离;
+	double dN;  //利用速率V和时间戳理论计算出行进距离;
+	double Angle1,Angle2,Angle3;  //三个坐标时,任何2坐标的角度
+	double Angle;   //两个坐标之间的角度
+	double dLong;
+	double dLenth;
+	int position;  //定位点位置
+
+	switch(coor_size){		
+	case 1: // 1条定位数据,5.3.1
+		{
+			if(coor_list[0]->d > dist_limit){ // 如果测距的距离大于某个固定值,此时判断此位置与天线角度一致
+				//coor_list[0]->d -= coor_list[0]->d_offset;
+				AOAformula(coor_list[0], coor_list[0]->a, dest, true, z_offset);
+			}else { // 测距距离小于某值
+				//利用速率V和时间戳理论计算出行进距离
+				dN = coor_list[0]->v * (coor_list[0]->t - hist->t);
+				//计算实时定位分站(天线)坐标和历史定位坐标之间的距离
+				d0 = Distanceformula(coor_list[0], hist);
+				if(hist->x - coor_list[0]->x == 0){
+					Angle = (coor_list[0]->y >= hist->y) ? 90 : 270;
+					Angle = Angle * M_PI / 180;
+				}else{
+					//计算历史坐标与实时分站坐标的角度,用来表明历史坐标位于定位坐标的方向
+					Angle = atan((hist->y - coor_list[0]->y)/(hist->x - coor_list[0]->x));
+				}
+
+				// 与历史坐标同向		
+				//如果定位距离小于两个坐标之间的距离,说明定位位置在两个坐标之内
+				if(d0 >= coor_list[0]->d){
+					if(dN >= coor_list[0]->d){
+						Angle += M_PI;  //与历史坐标反方向
+					}
+				}else{  
+					//如果定位距离大于两个坐标之间的距离,说明定位位置在两个坐标之外,接下来只要判断在哪个yu坐标的位置即可
+					//如果理论进行距离大于两者坐标之间的距离,则说明与历史坐标在同一方向,反之在反方向
+					if(dN < coor_list[0]->d){ 
+						Angle += M_PI;  //与历史坐标反方向
+					}
+				}
+				//coor_list[0]->d -= coor_list[0]->d_offset;
+				AOAformula(coor_list[0], Angle, dest, true, z_offset);  //最终定位坐标计算
+			}
+			break;
+		}
+	case 2: //2条定位数据,5.3.2
+		{
+			//2条定位数据中分站(天线)坐标与历史定位坐标之间的角度,以此推出这三个坐标是否在一条直线上或者呈三角形
+			if(coor_list[0]->x == hist->x ){
+				Angle1 = (coor_list[0]->y == hist->y) ? 0 : ((coor_list[0]->y > hist->y) ? 90 : 270);
+				Angle1 = Angle1 * M_PI / 180;
+			}else{
+				Angle1 = atan((coor_list[0]->y - hist->y) / (coor_list[0]->x - hist->x)); 
+			}
+			if(coor_list[1]->x == hist->x ){
+				Angle2 = (coor_list[1]->y == hist->y) ? 0 : ((coor_list[1]->y > hist->y)? 90 : 270);
+				Angle2 = Angle2 * M_PI / 180;
+			}else{
+				Angle2 = atan((coor_list[1]->y - hist->y) / (coor_list[1]->x - hist->x)); 
+			}
+			if(coor_list[1]->x == coor_list[0]->x ){
+				Angle3 = (coor_list[1]->y >= coor_list[0]->y) ? 90 : 270; // 必须在不同点
+				Angle3 = Angle3 * M_PI / 180;
+			}else{
+				Angle3 = atan((coor_list[1]->y - coor_list[0]->y) / (coor_list[1]->x - coor_list[0]->x)); 
+				if(Angle3 > M_PI){
+					Angle3 -= M_PI;
+				}
+				/*if(coor_list[0]->x > coor_list[1]->x)
+				Angle3 += M_PI;*/
+			}
+			//2个角度相同或者相差180度说明在一条直线上
+			//if(coor_list[0]->a == coor_list[1]->a || coor_list[0]->a == coor_list[1]->a + M_PI || coor_list[0]->a == coor_list[1]->a - M_PI){
+			if(Angle1 == Angle2 || Angle1 == Angle2 + M_PI || Angle1 == Angle2 - M_PI){
+				//取两个距离之间的最大值,保存最短距离的数据作为定位点
+				dLong = max(coor_list[0]->d, coor_list[1]->d);
+				position = (coor_list[0]->d > coor_list[1]->d) ? 1 : 0;
+				dLenth = Distanceformula(coor_list[0], coor_list[1]);
+				if(dLong > dLenth){
+					Angle = Angle3 + ((position + 1)%2) * M_PI; 
+				}else{
+					Angle = Angle3 +  position * M_PI;
+				}
+				//2个坐标的距离小于其2个距离中的最大值,则说明定位点在2个坐标的外侧,
+				//且在距离短的那条作为定位坐标,定位角度与此相同
+				//2个坐标的距离大于这两条距离中的任何一个,则说明定位点在两个坐标之间,取任意一条作为定位点,定位角度与其角度相反(+180)
+				// AOAformula(coor_list[position], Angle, dest);  //最终定位坐标计算
+
+				// 根据测量的结果,调整距离d 
+				// x2 - (d2 - ((d1+d2) - (x2-x1))/2) 靠近x2  x2 > x1,d1 > d2
+				// x1 + (d1 - ((d1+d2) - (x2-x1))/2) 靠近x1  x2 > x1,d1 < d2
+				// 化简得到 (x1 + x2 + d1 - d2)/2
+				// 显示的d = ((d1 + d2) - abs(x2-x1))/2
+				double d_offset;
+				if(abs(coor_list[0]->x - coor_list[1]->x) > abs(coor_list[0]->y - coor_list[1]->y)){ // 水平方向
+					d_offset = (coor_list[0]->d + coor_list[1]->d - abs(coor_list[0]->x - coor_list[1]->x))/2;
+				}else{ // 垂直方向
+					d_offset = (coor_list[0]->d + coor_list[1]->d - abs(coor_list[0]->y - coor_list[1]->y))/2;
+				}
+				dest->d_offset = d_offset;
+				coor_list[0]->d_offset = d_offset;
+				coor_list[1]->d_offset = d_offset;
+				coor_list[position]->d -= d_offset;
+				AOAformula(coor_list[position], Angle, dest, true, z_offset);
+			}
+			//岔路口形式
+			else {
+				dLenth = Distanceformula(coor_list[0], coor_list[1]); //2个天线坐标之间的距离
+				if(dLenth > (coor_list[0]->d  + coor_list[1]->d)) { //取一条作为定位参考数据,采用1条定位数据算法,参考5.3.1
+					//如果测距的距离大于某个固定值,此时判断此位置与天线角度一致,
+					if(coor_list[0]->d > dist_limit){
+						AOAformula(coor_list[0], coor_list[0]->a, dest);  //最终定位坐标计算
+					}
+					//测距距离小于某值
+					else{
+						dN = coor_list[0]->v * ( hist->t - coor_list[0]->t);  //利用速率V和时间戳理论计算出行进距离;
+						d0 = Distanceformula(coor_list[0], hist);  //计算实时定位分站(天线)坐标和历史定位坐标之间的距离
+						if(hist->x == coor_list[0]->x){
+							Angle = (hist->y >= coor_list[0]->y) ? 90 : 270; //计算历史坐标与实时分站坐标的角度,用来表明历史坐标位于定位坐标的方向
+							Angle = Angle * M_PI / 180;
+						}else{
+							Angle = atan((hist->y - coor_list[0]->y) / (hist->x - coor_list[0]->x));
+						}
+
+						//如果定位距离小于两个坐标之间的距离,说明定位位置在两个坐标之内
+						if(d0 > coor_list[0]->d){
+							if(dN >= coor_list[0]->d){
+								Angle += M_PI; //与历史坐标反方向
+							}
+						}
+						else{
+							//如果定位距离大于两个坐标之间的距离,说明定位位置在两个坐标之外,接下来只要判断在哪个坐标的位置即可
+							//如果理论进行距离大于两者坐标之间的距离,则说明与历史坐标在同一方向,反之在反方向
+							if(dN < coor_list[0]->d){
+								Angle += M_PI;
+							}
+						}
+						AOAformula(coor_list[0], Angle, dest, true, z_offset);  //最终定位坐标计算
+					}
+				}
+				else { //采用2条定位数据算法,采用5.3.2				
+					//取两个距离之间的最大值,保存最短距离的数据作为定位点
+					dLong = max(coor_list[0]->d, coor_list[1]->d);
+					position = (coor_list[0]->d > coor_list[1]->d) ? 1 : 0;
+					dLenth = Distanceformula(coor_list[0], coor_list[1]);
+					//2个坐标的距离小于其2个距离中的最大值,则说明定位点在2个坐标的外侧,
+					//且在距离短的那条作为定位坐标,定位角度与此相同
+					//2个坐标的距离大于这两条距离中的任何一个,则说明定位点在两个坐标之间,取任意一条作为定位点,定位角度与其角度相反
+					if(dLong > dLenth){
+						Angle = Angle3 + ((position + 1)%2) * M_PI; 
+					}else{
+						Angle = Angle3 +  position * M_PI;
+					}
+					AOAformula(coor_list[position], Angle, dest, true, z_offset);  //最终定位坐标计算
+				}
+			}
+			break;
+		}
+	case 3: // 3条定位数据,三点定位法 
+		{
+			// 在同一直线上不能使用三点定位
+			locatebycordinate(coor_list, dest);
+
+			break;
+		}
+	case 4: // 4条数据,取前3条
+		{
+			locatebycordinate(coor_list, dest);
+			break;
+		}
+	default:
+		{
+			dest->x = -1;
+			dest->y = -1;
+			dest->a = 0;
+			break;
+		}
+	}
+}
+
+void locatebycordinate( struct _coordinate** coor_list, struct _coordinate* dest )
+{
+	double h = 0;
+	int i = 0;
+	int j = 0;
+	double temp = 0;
+
+	double x[3]; // 坐标
+	double y[3]; // 坐标
+	double z[3];
+	double d[3];
+	double p[2]; 
+	_Matrix pi;
+
+	matrix_set(&pi,3,2);
+	matrix_init(&pi);
+
+	for(i=0;i<3;i++){
+		x[i] = coor_list[i]->x;
+		y[i] = coor_list[i]->y;
+		z[i] = coor_list[i]->z;
+		d[i] = coor_list[i]->d; // d * CM_PIX * 100;
+	}
+	//获得坐标
+	matrix_write(&pi,0,0,x[0]);
+	matrix_write(&pi,0,1,y[0]);
+	h = z[0];
+	d[0] = sqrt(d[0] * d[0] - h * h);
+
+	matrix_write(&pi,1,0,x[1]);
+	matrix_write(&pi,1,1,y[1]);
+	h = z[1];
+	d[1] = sqrt(d[1] * d[1]- h * h);
+
+	matrix_write(&pi,2,0,x[2]);
+	matrix_write(&pi,2,1,y[2]);
+	h = z[2];
+	d[2] = sqrt(d[2] * d[2] - h * h);
+
+	if (locate(&pi,d,p) > 0)
+	{
+		dest->x = p[0];
+		dest->y = p[1];
+	}else
+	{
+		dest->x = -1;
+		dest->y = -1;
+	}
+}
+
+void algorithm_locate_ex( _coordinate** coor_list, int coor_size, _coordinate* hist, _coordinate* dest, double dist_limit )
+{
+	switch (coor_size)
+	{
+	case 1:
+		{
+			if(!hist){ // 初次计算,只有一个分站数据的时候跳出,不计算坐标
+				return;
+			}
+			// 获取历史节点与当前分站的角度,判断是否仍在同一直线
+			double angle = getAngleByAngle(coor_list[0], hist);
+			if(0 == tan(angle)){ // 在同一直线
+				double dist_temp = getDistance(hist, coor_list[0]); // 获得上一次的距离
+				// 获得移动的距离
+				double dist_mv = abs(dist_temp - coor_list[0]->d);
+				// 沿着原移动方向运动
+				calcCoordinate(hist, dist_mv, hist->a, dest); //
+			}else{ // 有角度,找交点
+				_coordinate* pt_cross = getCross(hist, coor_list[0]);
+				double dist_temp = getDistance(pt_cross, coor_list[0]);
+				if(dist_temp >= coor_list[0]->d){
+					// 避免动画穿墙,先将该点定位到交点上
+					dest->x = pt_cross->x;
+					dest->y = pt_cross->y;
+					dest->z = coor_list[0]->z;
+					dest->a = getAngleByCoordinate(pt_cross, coor_list[0]); // 运行方向
+				}else{ // 在当前方向上运行, 理论上不存在
+					dist_temp = (getDistance(hist, pt_cross) - (coor_list[0]->d - dist_temp)); // 位移
+					calcCoordinate(hist, dist_temp, hist->a, dest);
+				}
+			}
+			break;
+		}
+	case 2:
+		{
+			double angle_anc = getAngleByAngle(coor_list[0], coor_list[1]);
+			if(0 == tan(angle_anc)){ // 在同一直线
+				double dist_anc = getDistance(coor_list[0], coor_list[1]);
+				double dist_offset = coor_list[0]->d + coor_list[1]->d - dist_anc;
+				if(dist_offset > 0){
+					if(abs(coor_list[0]->d - coor_list[1]->d) < dist_anc){ // 不考虑误差,在两分站之间,投影
+						calcCoordinate(coor_list[0], coor_list[0]->d - dist_offset / 2, getAngleByCoordinate(coor_list[0], coor_list[1]), dest);
+					}else{ // 在两分站同一侧
+						double angle_anc_run = getAngleByCoordinate(coor_list[0], coor_list[1]); // 分站2一侧
+						if(coor_list[0]->d < coor_list[1]->d){ // 分站1一侧
+							angle_anc_run += M_PI;
+						}
+						calcCoordinate(coor_list[0], coor_list[0]->d - dist_offset / 2, angle_anc_run, dest);
+					}
+				}else { // <= 有误差, 在两分站之间
+					calcCoordinate(coor_list[0], coor_list[0]->d + dist_offset / 2, getAngleByCoordinate(coor_list[0], coor_list[1]), dest);
+				}
+			}else{ // 有夹角, 一定在两分站之间
+				if(hist){
+					double angle_anc1 = getAngleByAngle(coor_list[0], hist);
+					double angle_anc2 = getAngleByAngle(coor_list[1], hist);
+					// 找到交点
+					_coordinate* pt_cross = getCross(coor_list[0], coor_list[1]);
+					// 交点到分站的距离
+					double dist_anc1 = getDistance(pt_cross, coor_list[0]);
+					double dist_anc2 = getDistance(pt_cross, coor_list[1]);
+
+					if(0 == tan(angle_anc1)){
+						if(dist_anc1 >= coor_list[0]->d){ // 以直线上为准
+							calcCoordinate(hist, abs(dist_anc1 - coor_list[0]->d), hist->a, dest);
+							//calcCoordinate(coor_list[0], coor_list[0]->d, getAngleByCoordinate(coor_list[0], hist), dest);
+						}else{ // 超过直接定位到交点上
+							dest->x = pt_cross->x;
+							dest->y = pt_cross->y;
+							dest->a = getAngleByCoordinate(pt_cross, coor_list[1]);
+						}
+					}else if(0 == tan(angle_anc2)){ // 与分站1在同一直线
+						if(dist_anc2 >= coor_list[1]->d){ // 以直线上为准
+							calcCoordinate(hist, abs(dist_anc2 - coor_list[1]->d), hist->a, dest);
+							//calcCoordinate(coor_list[1], coor_list[1]->d, getAngleByCoordinate(coor_list[1], hist), dest);
+						}else{ // 超过直接定位到交点上
+							dest->x = pt_cross->x;
+							dest->y = pt_cross->y;
+							dest->a = getAngleByCoordinate(pt_cross, coor_list[0]);
+						}
+					}else { // 三叉口
+						// 找到交点
+						_coordinate* pt_cross1 = getCross(hist, coor_list[0]);
+						_coordinate* pt_cross2 = getCross(hist, coor_list[1]);
+
+						if(coor_list[0]->d >= coor_list[1]->d){
+							dest->x = pt_cross2->x;
+							dest->y = pt_cross2->y;							
+							dest->z = coor_list[1]->z;
+							dest->a = coor_list[1]->a;
+						}else{
+							dest->x = pt_cross1->x;
+							dest->y = pt_cross1->y;							
+							dest->z = coor_list[0]->z;
+							dest->a = coor_list[0]->a;
+						}
+					}
+				}else{ // 先定位到交点,避免穿墙
+					_coordinate* pt_cross = getCross(coor_list[0], coor_list[1]);
+					dest->x = pt_cross->x;
+					dest->y = pt_cross->y;
+					// 比较距离,定位到距离近的方向上
+					if(abs(getDistance(pt_cross, coor_list[0]) - coor_list[0]->d) >= abs(getDistance(pt_cross, coor_list[1]) - coor_list[1]->d)){
+						dest->z = coor_list[1]->z;
+						dest->a = coor_list[1]->a;
+					}else{
+						dest->z = coor_list[0]->z;
+						dest->a = coor_list[0]->a;
+					}
+				}
+			}
+			break;
+		}
+	case 3:
+		{
+			// 双天线情况,判断是否在同一直线上
+
+			locatebycordinate(coor_list, dest);
+			break;
+		}
+	case 4:
+		{
+			// 双天线情况,判断是否在同一直线上
+			locatebycordinate(coor_list, dest);
+			break;
+		}
+	default:
+		break;
+	}
+}
+
+double getAngleByAngle( _coordinate* p1, _coordinate* p2 )
+{
+	if(p1->x == p2->x) return 0;
+	if(p1->y == p2->y) return 0;
+	return double(p2->a - p1->a);
+}
+
+double getAngleByCoordinate( _coordinate* p1, _coordinate* p2 )
+{
+	if(p1->x == p2->x && p1->y == p2->y){ // 如果坐标相等,则跨越,不考虑折返情况
+		return p1->a;
+	}
+	if(p1->x == p2->x){
+		if(p1->y >= p2->y){
+			return M_PI_2 * 3;
+		}
+		return M_PI_2;
+	}
+	if(p1->y == p2->y){
+		if(p1->x > p2->x){
+			return M_PI;
+		}
+		return 0;
+	}
+	return atan((p2->y - p1->y) / (p2->x - p1->x));
+}
+
+_coordinate* getCross( _coordinate* p1, _coordinate* p2 )
+{
+	_coordinate* p = new _coordinate; 
+	double b1 = p1->y - tan(p1->a) * p1->x;
+	double b2 = p2->y - tan(p2->a) * p2->x;
+
+	if(p1->a == 0 || p1->a == M_PI){ // 第一个点水平
+		p->y = p1->y;
+		if(p2->a == M_PI_2 || p2->a == M_PI_2 * 3){ // 第二个点垂直
+			p->x = p2->x;
+		}else{ // 第二个点有角度
+			p->x = (p->y - b2) / tan(p2->a);
+		}
+		return p;
+	}else if(p1->a == M_PI_2 || p1->a == M_PI_2 * 3){ // 第一个点垂直
+		p->x = p1->x;
+		if(p2->a == 0 || p2->a == M_PI){ // 第二个点水平
+			p->y = p2->y;
+		}else{ // 第二个点有角度
+			p->y = tan(p2->a) * p->x + b2;
+		}
+		return p;
+	}else { // 有角度
+		if(p2->a == 0 || p2->a == M_PI){ // 第二点水平
+			p->y = p2->y;
+			p->x = (p->y - b1) / tan(p1->a);
+			return p;
+		}else if(p2->a == M_PI_2 || p2->a == M_PI_2 * 3){ // 第二点垂直
+			p->x = p2->x;
+			p->y = p->x * tan(p1->a) + b1;
+			return p;
+		}
+	}
+	p->x = (b1-b2)/(tan(p2->a) - tan(p1->a));
+	p->y = tan(p1->a) * p->x + b1;
+	return p;
+}
+
+// 不考虑折返
+void calcCoordinate( _coordinate* p1, double dist, double angle, _coordinate* dest )
+{
+	dest->x = p1->x;
+	dest->y = p1->y;
+	dest->z = p1->z;
+
+	dest->x += dist * cos(angle);
+	dest->y += dist * sin(angle);
+
+	dest->a = angle;
+}
+
+double getDistance( _coordinate* p1, _coordinate *p2 )
+{
+	return sqrt(pow(p1->x - p2->x, 2) + pow(p1->y - p2->y, 2));
+}

+ 29 - 0
locate_algorithm.h

@@ -0,0 +1,29 @@
+#ifndef _LOCATE_ALGORITHM_H
+#define _LOCATE_ALGORITHM_H
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "classdef.h"
+
+#define M_PI       3.14159265358979323846 // 角度转弧度 角度 * pi / 180
+#define M_PI_2     1.57079632679489661923
+#define M_PI_4     0.785398163397448309616
+
+
+// 最终定位坐标计算公式
+void AOAformula(struct _coordinate* ant, double angle, struct _coordinate* tar, bool is_line = false, double z_offset = 0);
+// 两个坐标之间的距离计算公式
+double Distanceformula(struct _coordinate* ant, struct _coordinate* last);
+// 三点定位
+void locatebycordinate(struct _coordinate** coor_list, struct _coordinate* dest);
+// 定位算法
+void algorithm_locate(struct _coordinate** coor_list, int size, struct _coordinate* hist, struct _coordinate* dest, double dist_limit, double z_offset);
+
+void algorithm_locate_ex(_coordinate** coor_list, int coor_size, _coordinate* hist, _coordinate* dest, double dist_limit);
+
+double getAngleByCoordinate(_coordinate* p1, _coordinate* p2);
+double getAngleByAngle(_coordinate* p1, _coordinate* p2);
+double getDistance(_coordinate* p1, _coordinate *p2);
+_coordinate* getCross(_coordinate* p1, _coordinate* p2);
+void calcCoordinate(_coordinate* p1, double dist, double angle, _coordinate* dest);
+#endif

+ 58 - 0
log_def.h

@@ -0,0 +1,58 @@
+#ifndef _SERVER_LOG_DEF_H_
+#define _SERVER_LOG_DEF_H_
+
+#define LOG_LOAD_CONFIG "加载配置信息"
+#define LOG_LOAD_CONFIG_SUCCESS "加载配置信息成功"
+#define LOG_LOAD_CONFIG_FAIL "加载配置信息失败"
+#define LOG_CONNECT_DB "连接数据库"
+#define LOG_CONNECT_DB_SUCCESS "连接数据库成功"
+#define LOG_CONNECT_DB_FAIL "连接数据库失败,请检查系统配置"
+#define LOG_INIT_SETTING "初始化系统参数信息"
+#define LOG_INIT_ALARM_TYPE "初始化报警类型信息"
+#define LOG_INIT_DEPT "初始化部门信息"
+#define LOG_INIT_CARD "初始化标识卡信息"
+#define LOG_INIT_STAFF "初始化人员信息"
+#define LOG_INIT_VEHICLE "初始化车辆信息"
+#define LOG_INIT_MAP "初始化地图信息"
+#define LOG_INIT_AREA "初始化区域信息"
+#define LOG_INIT_READER "初始化分站信息"
+#define LOG_INIT_ANTENNA "初始化分站天线信息"
+#define LOG_INIT_ADHOC "初始化自组网设备预置坐标信息"
+#define LOG_LOAD_HIS_AREA "载入区域历史数据"
+#define LOG_LOAD_HIS_POSTION "载入位置历史数据"
+#define LOG_LOAD_HIS_STATE "载入状态历史数据"
+#define LOG_LOAD_HIS_READER "载入分站历史数据"
+#define LOG_RECORD_COUNT "条记录"
+#define LOG_SEND_JSON_DATA "发送Json数据"
+#define LOG_RECIEVE_COLLECTOR_DATA "接收采集数据"
+#define LOG_SOCKET_IP "地址"
+#define LOG_DATA_LENGTH_BYTE "字节"
+#define LOG_TIME_FORMAT "%H:%M:%S"
+#define LOG_CLEAR_LOG "清除记录"
+#define LOG_EXEC_SQL_ERROR "执行SQL语句错误"
+#define LOG_CONNECT_WEB_SERVER "连接服务器"
+#define LOG_LOGIN_WEB_SERVER "登录服务器"
+#define LOG_LOGOUT_WEB_SERVER "退出服务器"
+#define LOG_LISTEN_START "启动监听服务"
+#define LOG_LISTEN_FAIL "启动监听服务失败"
+#define LOG_LISTEN_STOP "停止监听服务"
+
+#define LOG_SUCCESS "成功"
+#define LOG_FAIL "失败"
+#define LOG_SET_LIMIT_VALUE "设置限值"
+#define LOG_CALL_CARD "呼叫"
+#define LOG_CLEAR_CARD "清除盲区卡"
+#define LOG_DEAL_HELP "处理呼救信息"
+#define LOG_EDIT_MAP "编辑地图"
+#define LOG_EDIT_AREA "编辑区域"
+#define LOG_EDIT_READER "编辑分站"
+#define LOG_EDIT_PATH "编辑预置路径"
+#define LOG_EDIT_CARD "编辑标识卡"
+#define LOG_EDIT_STAFFER "编辑员工"
+#define LOG_EDIT_VEHICLE "编辑车辆"
+#define LOG_REQUEST_ALL_POSTION "请求所有位置信息"
+
+#define LOG_INVALID_PARSE "非法数据解析"
+
+
+#endif // !_SERVER_LOG_DEF_H_

BIN
res/YAServer.ico


BIN
res/YAServer.rc2


BIN
resource.h


+ 31 - 0
send_content.cpp

@@ -0,0 +1,31 @@
+#include "stdafx.h"
+#include <winsock2.h>
+#include "constdef.h"
+
+bool sendContent(SOCKET s, char* filePath)
+{
+	char buf[MAXSIZE] = {'\0'};
+	FILE* filePtr;
+	fopen_s(&filePtr, filePath, "rb");
+	if(filePtr == NULL)
+	{
+		//printf("Failed to open the file\n");
+		return false;
+	}
+	else
+	{
+		int sendCount;
+		while(!feof(filePtr))
+		{
+			sendCount = fread(buf,sizeof(char), MAXSIZE, filePtr);
+			send(s, buf, sendCount, 0);
+			if(ferror(filePtr))
+			{
+				//printf("File read error\n");
+				return false;
+			}
+		}
+	}
+	fclose(filePtr);
+	return true;
+}

+ 54 - 0
send_head.cpp

@@ -0,0 +1,54 @@
+#include "stdafx.h"
+#include <winsock2.h>
+#include "constdef.h"
+
+void sendHead(SOCKET s, int state, char* fileExtension, char* version)
+{
+	char buf[MAXSIZE] = {'\0'}, *content = "text/plain", *stateStr = NULL;
+	switch(state)
+	{
+	case 200:
+		stateStr = "OK";
+		break;
+	case 400:
+		stateStr = "Bad Request";
+		break;
+	case 404:
+		stateStr = "Not Found";
+		break;
+	default:
+		stateStr = "Unknown";
+		break;
+	}
+
+	if(strcmp(fileExtension, "html") == 0 || strcmp(fileExtension, "htm") == 0)
+	{
+		content = "text/html";
+	}
+	else if(strcmp(fileExtension, "css") == 0)
+	{
+		content = "text/css";
+	}
+	else if(strcmp(fileExtension, "gif") == 0)
+	{
+		content = "image/gif";
+	}
+	else if(strcmp(fileExtension, "jpeg") == 0)
+	{
+		content ="image/jpeg";
+	}
+	else if(strcmp(fileExtension, "jpg") == 0)
+	{
+		content = "image/jpg";
+	}
+	else if(strcmp(fileExtension,"png") == 0)
+	{
+		content = "image/png";
+	}
+	sprintf_s(buf, "%s %d %s \r\nContent-Type: %s \r\n\r\n", version, state, stateStr, content);
+
+	int sendCount = strlen(buf);
+	//for(;buf[sendCount]!='\0';sendCount++);
+	send(s, buf, sendCount, 0);
+	return ;
+}

+ 85 - 0
sever_thread.cpp

@@ -0,0 +1,85 @@
+#include <stdio.h> 
+#include <Winsock2.h> 
+#include <process.h> 
+#pragma comment (lib, "Ws2_32.lib") 
+
+unsigned int __stdcall listeningThread(void *param)
+{ 
+	SOCKET sockSrv = socket(AF_INET, SOCK_STREAM, 0); 
+	SOCKADDR_IN addrSrv; 
+
+	addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY); 
+
+	addrSrv.sin_family = AF_INET; 
+
+	addrSrv.sin_port = htons((int)param); 
+
+
+
+	int ret = bind(sockSrv, (SOCKADDR*) &addrSrv, sizeof(SOCKADDR)); 
+
+	ret = listen(sockSrv, 5); 
+
+	SOCKADDR_IN addrClient; 
+
+	int len = sizeof(SOCKADDR); 
+
+	while (1) 
+
+	{ 
+
+		SOCKET sockConn = accept(sockSrv, (SOCKADDR*) &addrClient, &len); 
+
+		char sendBuf [] = "Hello World !"; 
+
+
+
+		send(sockConn, sendBuf, strlen(sendBuf) + 1, 0); 
+
+		char recvBuf[50]; 
+
+		recv(sockConn, recvBuf, 50, 0); 
+
+		printf("%s\n", recvBuf); 
+
+		closesocket(sockConn); 
+
+	} 
+
+	return 0; 
+
+} 
+
+void main() 
+
+{ 
+
+	WORD wVersionRequested; 
+
+	WSADATA wsaData; 
+
+	int err; 
+
+
+
+	wVersionRequested = MAKEWORD(2, 2); 
+
+
+
+	err = WSAStartup(wVersionRequested, &wsaData); 
+
+	if (err != 0) { 
+
+		return; 
+
+	} 
+
+
+
+	_beginthreadex(NULL, 0, listeningThread, (void *) 8120, 0, NULL); 
+
+	_beginthreadex(NULL, 0, listeningThread, (void *) 8121, 0, NULL); 
+
+	Sleep(INFINITE); 
+
+}

+ 8 - 0
stdafx.cpp

@@ -0,0 +1,8 @@
+
+// stdafx.cpp : 只包括标准包含文件的源文件
+// YAServer.pch 将作为预编译头
+// stdafx.obj 将包含预编译类型信息
+
+#include "stdafx.h"
+
+

+ 6 - 0
stdafx.h

@@ -0,0 +1,6 @@
+#pragma once
+
+#define _USE_MFC
+#define _DETECT_MEMORY_LEAK
+
+#include <GeneralHelper.h>

+ 8 - 0
targetver.h

@@ -0,0 +1,8 @@
+#pragma once
+
+// 包括 SDKDDKVer.h 将定义最高版本的可用 Windows 平台。
+
+// 如果要为以前的 Windows 平台生成应用程序,请包括 WinSDKVer.h,并将
+// WIN32_WINNT 宏设置为要支持的平台,然后再包括 SDKDDKVer.h。
+
+#include <SDKDDKVer.h>