// YAServerDlg.cpp : 实现文件
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <cstdio>
#include <process.h>
#include <exception> 
#include <algorithm>
#include "YAServer.h"	
#include "YAServerDlg.h"
#include "afxdialogex.h"
#include <sio_client.h>
#include <condition_variable>
#include <string>
#include "def.h"
#include "socketdef.h"
#include <Functions/Functions.h>
#include "MysqlConnPool.h"
#include "locate_algorithm.h"
#include <strconv/strconv.h>
#include <kalman/locate.h>
#include "log_def.h"
#include "DbSettingDlg.h"
#include "LogSetting.h"
#include "SysSetting.h"
#include "uwb_msg_def.h"
#include "ProcessRemodule.h"
#include "log_process_module.h"
#include "./system_basic_info/SystemAnalysis.h"
#include "./debug_server/debug_server_socket.h"
#include "./system_basic_info/SystemAnalysis.h"
#include "./CSVparser/CSVparser.h"
#include "./KNN/KNN.h"
#include "algorithm/Fit.h"
#include "mylog/log_module.h"

#include <boost/numeric/ublas/matrix.hpp>
#include "../thirdparty/include/rapidjson/include/rapidjson/rapidjson.h"

#include "monkeycar_area.h"
#include "base_card.h"
#include "cacti/util/StringUtil.h"
#include <cstdlib>
#include "his_location.h"

using namespace sio;

// 用来跟踪内存使用情况
#define TRACE_MEMORY_WRITELOG
#define TRACE_MEMORY_PARSE_PACKAGE
#define TRACE_MEMORY_PARSE_SERVER
#define TRACE_MEMORY_SYNCTIMEMSG
#define TRACE_MEMORY_TAGMSG
// -- 用来跟踪内存使用情况

#undef new

BOOL m_log_sys_status = false;
const int ms = 1000;
int g_anchorNum  = 0;
std::string g_position_string = "";
bool g_position_build = false;

char* InavMovingStatusStr[] = {"Static", 
	"Moving"};
char *InavDirectoryStr[] = {"No Directory",
	"Forward",
	"Backward",
	"Leftward",
	"Rightward"};
char * InavAccerateStatusStr[] = {"Not Accerate",
	"Accerate",
	"SlowDown"};

const std::string testJson = "{\"cmd\":\"pos_map\",\"data\":{\"s\":{\"detail\":[\
							 [\"0010000000002\",3231.210,75.0,1499515328000.0,1499515328000.0,1499515472000.0,147000.0,5,2,2,0,1,0,0.0,6,4,1243.0,4], \
							 [\"0010000000044\",4917.260,147.620,1499514950000.0,1499515018000.0,1499515475000.0,525000.0,5,4,2,0,1,0,0.0,8,4,63.0,4], \
							 [\"0010000000079\",4727.0,-71.51000000000001,1499514756000.0,1499514892000.0,1499514892000.0,719000.0,5,1,2,0,1,0,0.0,9,1,75.0,4]],\
							 \"stat\":{\"dept\":{\"2\":{\"area\":[[2,2],[1,2],[5,1],[3,1],[4,1]],\"dept\":[[2,7]],\"occupation_level\":[[4,7]],\"sum\":7}},\
							 \"glbl\":{\"area\":[[2,2],[1,2],[5,1],[3,1],[4,1]],\"dept\":[[2,7]],\"occupation_level\":[[4,7]],\"sum\":7}}},\"v\":\
							 {\"detail\":[[\"0020000001001\",4747.660,-75.410,1499514870000.0,1499514870000.0,1499515082000.0,605000.0,5,5,2,0,0,0,0.0,10,3,71.0,0]],\
							 \"stat\":{\"dept\":{\"2\":{\"area\":[[5,25],[7,2],[6,4],[28,1],[3,2],[9,4],[22,1],[26,3],[2,3],[4,1]],\"dept\":[[2,46]],\"sum\":46}},\
							 \"glbl\":{\"area\":[[5,25],[7,2],[6,4],[28,1],[3,2],[9,4],[22,1],[26,3],[2,3],[4,1]],\"dept\":[[2,46]],\"sum\":46}}}},\"version\":\"1.0.0.4\"}";

// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
#include "ProcessRemodule.h"

bool g_is_rec_hist = false;

#pragma warning(disable: 4244)
#pragma warning(disable: 4018)

struct LogInfo_
{
	LogInfo_(std::string s)
		:start(0),name(s)
	{
		start = time(NULL);
	}
	~LogInfo_()
	{
		std::time_t end = time(NULL);
		if(end-start > 1)
		{
			debug_print_syslog(0,"[Warning_]%s,diff_time:%d",name.c_str(),end-start);
		}
	}
	std::time_t start;
	std::string name;

};
static double get_absolute_distance(std::shared_ptr<Card> &c1,std::shared_ptr<Card> &c2)
{
	NAMESPACE_POINT::point p1(c1->x,-c1->y);
	NAMESPACE_POINT::point p2(c2->x,-c2->y);
	
	if (fabs(c1->m_arg-c2->m_arg)<1e-10)
		return p1.dist(p2);
	std::stringstream ss;
	std::vector<NAMESPACE_POINT::point> v = NAMESPACE_POINT::card_path::inst().find_path(p1,p2);
	NAMESPACE_POINT::point pt = p1;double dis = 0;
	debug_print_syslog(0,"vehicle_alarm_here %s&%s(%.2f,%.2f)-->(%.2f,%.2f)",c1->card_id.c_str(),c2->card_id.c_str(),p1.x,p1.y,p2.x,p2.y);
	for (const auto & p:v)
	{
		debug_print_syslog(0,"vehicle_alarm_here %s&%s,(%.2f,%.2f)",c1->card_id.c_str(),c2->card_id.c_str(),p.x,p.y);
		dis += pt.dist(p);
		pt=p;
	}
	dis += pt.dist(p2);
//	debug_print_syslog(0,"vehicle_alarm_here %s&%s,%.2f",c1->card_id.c_str(),c2->card_id.c_str(),dis);
	return dis;
}
static bool rear_end_arg_algo(std::shared_ptr<Card> &c1,std::shared_ptr<Card> &c2)
{
	NAMESPACE_POINT::point p_1(c1->last_x,c1->last_y);NAMESPACE_POINT::point p_2(c2->last_x,c2->last_y);
	debug_print_syslog(0,"[vehicle_alarm_begin_algo]%s&%s  %f,%f (%s)(%s)--(%.2f,%.2f)(%.2f,%.2f)",c1->card_id.c_str(),c2->card_id.c_str(),c1->m_arg,c2->m_arg,c1->m_line.to_string().c_str(),c2->m_line.to_string().c_str(),
		p_1.x,p_1.y,p_2.x,p_2.y);
	double arg_1=c1->m_arg;double arg_2=c2->m_arg;
	if (NAMESPACE_POINT::point::eq(arg_1,0x12345678,1e-10) || NAMESPACE_POINT::point::eq(arg_2,0x12345678,1e-10))
	{
		debug_print_syslog(0,"[vehicle_alarm_invalid]%s&%s  %f,%f",c1->card_id.c_str(),c2->card_id.c_str(),arg_1,arg_2);
		return false;
	}
	if (!NAMESPACE_POINT::point::eq(arg_1,0,1e-10))
		if (fabs(fabs(arg_1-arg_2)-3.141593)< 0.000005)
		{
			debug_print_syslog(0,"[vehicle_alarm_opposite]%s&%s",c1->card_id.c_str(),c2->card_id.c_str());
			return false;
		}
	if (NAMESPACE_POINT::point::eq(arg_1,arg_2,1e-10))
	{
		double arg = std::arg(std::complex<double>(p_1.x,p_1.y)-std::complex<double>(p_2.x,p_2.y));
		if (!(fabs(fabs(arg)-fabs(arg_1))<1e-10 || fabs(fabs(arg)+fabs(arg_2)-3.141593)< 0.000005))
		{
			debug_print_syslog(0,"[vehicle_alarm_parallel]%s&%s  %f,%f()",c1->card_id.c_str(),c2->card_id.c_str(),arg,arg_1);
			return false;
		}
	}
	if(!NAMESPACE_POINT::point::eq(arg_1,arg_2,1e-10))
	{
		NAMESPACE_POINT::point p = c1->m_line.line::crossing(c2->m_line);
		if (p==c1->m_line[1] || p==c2->m_line[1])
		{
			debug_print_syslog(0,"[vehicle_alarm_point]%s&%s  %f,%f (%.2f,%.2f)(%s)(%s)",c1->card_id.c_str(),c2->card_id.c_str(),c1->m_arg,c2->m_arg,p.x,p.y,c1->m_line.to_string().c_str(),c2->m_line.to_string().c_str());
			return true;
		}
		double arg1 = std::arg(std::complex<double>(p.x,p.y)-std::complex<double>(c1->m_line[1].x,c1->m_line[1].y));
		double arg2 = std::arg(std::complex<double>(p.x,p.y)-std::complex<double>(c2->m_line[1].x,c2->m_line[1].y));
		if (fabs(fabs(arg1-arg_1)-3.141593)<0.000005 && fabs(fabs(arg2-arg_2)-3.141593)<0.000005)
		{
			debug_print_syslog(0,"[vehicle_alarm_backfired]%s&%s",c1->card_id.c_str(),c2->card_id.c_str());
			return false;
		}
	}
	debug_print_syslog(0,"[vehicle_alarm_end]%s&%s  %f,%f",c1->card_id.c_str(),c2->card_id.c_str(),arg_1,arg_2);
	return true;
}
class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

	// 对话框数据
	enum { IDD = IDD_ABOUTBOX };

protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

	// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()

// CYAServerDlg 对话框

CYAServerDlg::CYAServerDlg(CWnd* pParent /*=NULL*/)
	: CDialogEx(CYAServerDlg::IDD, pParent),
	_server(this)
	, _io(new client())
	, _io_ex(new client())
	, m_reader_id_hist(0)
{
	ws_init();
	ws_init_ex();
	init_smart_pointer_var();
	Log::init_log_module();

	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);

	m_bStop=false;
	time_interval=0;
	m_carmanage = new NAMESPACE_POINT::CarManager(this);
}
void CYAServerDlg::run_sensor()
{
	time_t t = time(NULL);
	if (t-time_interval>3*60)
	{
		time_interval =t;
		auto map = mp_driving_face_card_list;
		MYSQL_ROW pRow;
		MYSQL_RES *pRes = NULL;
		int err = 0;
		char strsql[LENGTH_SQL] = {0};	
		for(const auto &x:map)
		{
			auto pcard=x.second;
			if(pcard->m_sensor_id.empty())
				continue;
			pRes=NULL;
			memset(strsql,0,LENGTH_SQL);
			sprintf_s(strsql, "SELECT data_value FROM his_sensor_data WHERE sensor_id = %d ORDER BY write_time DESC LIMIT 3;",pcard->m_sensor_id[0]);
			//debug_print_syslog(0,"[reverse_alarm]%s",strsql);
			pRes = getMysqlRes(strsql);
			if (NULL == pRes)
				continue;
			double prenum=-1;
			double nrow=0;double sum=0;bool f=false;
			while(pRow = mysql_fetch_row(pRes)){
				double num = atof(pRow[0]);
				if (op::point::eq(num,0,1e-10))continue; //0异常数据抛掉
				if(op::point::eq(num,-1,1e-10)){ //如果没有参考数据，则判断，如果有历史数据，用历史，没有则用第一个数据。
					if(pcard->empty()) prenum=num; else prenum=pcard->back();
				}
				if (prenum-num>0.1){ //异常数据 如果之前存在正常数据则继续，如果没有则本次不作参考。0.1暂定
					if(pcard->empty()){
						f=true;break;
					}
					else continue;
				}
				nrow++;sum+=num;		
			}
			if (!f && nrow!=0){
				double result=sum/nrow;
				debug_print_syslog(0,"reverse_alarm_push %s,%.3f",pcard->card_id.c_str(),result);
				if(pcard->push(result)){//满足三个并且呈现上升趋势
					debug_print_syslog(0,"reverse_alarm_up %s",pcard->card_id.c_str());
					if (!pcard->warning())
						pcard->set_true();//置true,主进程开始抓取数据。
				}
			}
			mysql_free_result(pRes);
			if (pcard->timeout()){//时间满足，判断是否告警
				auto reader_it = mp_reader_list.find(pcard->reader_id());
				if (reader_it == mp_reader_list.end()){
					pcard->clear_sensor();
					continue;
				}
				std::string msg;
				if(pcard->check_location_reversal(msg))//满足告警条件，查看是否已经存在告警，没有产生告警
				{
					debug_print_syslog(0,"reverse_alarm_create:%s",pcard->card_id.c_str());
					deal_readers_event(ET_READER_LOCATION_REVERSAL,true,reader_it->second);
				}
				else  //不满足告警条件，查看是否已经存在告警，存在则取消告警。
				{
					debug_print_syslog(0,"reverse_alarm_delete:%s",pcard->card_id.c_str());
					deal_readers_event(ET_READER_LOCATION_REVERSAL,false,reader_it->second);
				}
				debug_print_syslog(0,"%s",msg.c_str());
				pcard->clear_sensor();//清除数据，重新判断
			}
		}
	}
}
void CYAServerDlg::run()
{
	while(!m_bStop)
	{
		run_sensor();
		std::this_thread::sleep_for(std::chrono::seconds(3));
		auto map_vechile = mp_card_list_down_vehicle;
		auto it = map_vechile.begin();
		uint64_t t = time(0)*1000;
		//去除大与1分钟没信号的井下车辆
		for (;it!=map_vechile.end();)
		{
			uint64_t ct = it->second->m_ct_time;
			uint64_t rt = t>ct?t-ct:ct-t; 
			NAMESPACE_POINT::point p(it->second->x,it->second->y);
			if (rt > 45*1000 || p.invalid())
			{
				debug_print_syslog(0,"vehicle_alarm step1:%s,%lld - %lld = %lld > 60*1000,(%.2f,%.2f)",it->second->card_id.c_str(),t,ct,rt,p.x,p.y);
				it = map_vechile.erase(it);
			}
			else
				it++;
		}
		//去除距离大与设置的距离阈值，以及反向行驶，平行行驶，背离行驶的车辆
		//debug_print_syslog(0,"vehicle_alarm stpe2 last %d vehicles",map_vechile.size());
		it=map_vechile.begin();
		for (;it!=map_vechile.end();it++)
		{
			NAMESPACE_POINT::point p(it->second->x,it->second->y);
			if (p.invalid())
				continue;
			double map_scale = it->second->map_scale;
			std::string cid=it->second->card_id;
			auto c = it->second;
			for (auto prv_it=std::next(it);prv_it!=map_vechile.end();++prv_it)
			{
				NAMESPACE_POINT::point p1(prv_it->second->x,prv_it->second->y);
				if (p1.invalid())
					continue;
				double dis = p.dist(p1)*map_scale;
				debug_print_syslog(0,"vehicle_alarm stpe3 : cid1:%s,cid2:%s (%.2f,%.2f),(%.2f,%.2f) %.2f,%f",cid.c_str(),prv_it->second->card_id.c_str(),p.x,p.y,p1.x,p1.y,dis,map_scale);
				if(dis>sls_setting.rear_end_d)
					continue;
				//判断反向行驶，平行行驶，背离行驶的车辆
				if (!rear_end_arg_algo(c,prv_it->second))
					continue;
				//
				vInfo v;
				v.push(cid,prv_it->second->card_id);
				std::string cardid=v.getKey();
				if(m_CloserVehicle.find(cardid) == m_CloserVehicle.end())
				{
					m_CloserVehicle.insert(std::make_pair(cardid,v));
					debug_print_syslog(0,"vehicle_alarm_insert %s",cardid.c_str());
				}
			}
		}

		//遍历卡列表
		auto it_cv=m_CloserVehicle.begin();
		for (;it_cv != m_CloserVehicle.end();)
		{
			vInfo & vinfo = it_cv->second;
			std::string vvid = it_cv->first;
			CardMap::iterator it_vlist_1 = mp_card_list_all.find(vinfo.m_cid[0]);
			CardMap::iterator it_vlist_2 = mp_card_list_all.find(vinfo.m_cid[1]);
			if (it_vlist_1 == mp_card_list_all.end() || it_vlist_2 == mp_card_list_all.end())
			{
				debug_print_syslog(0,"vehicle_alarm_nullptr %s",vvid.c_str());
				if (vinfo.is_alarm)
					deal_alarm_vehicle(vvid);
				it_cv = m_CloserVehicle.erase(it_cv);
				continue;
			}
			uint64_t ct=it_vlist_1->second->m_ct_time; uint64_t rt = t>ct?t-ct:ct-t;
			uint64_t ct_=it_vlist_2->second->m_ct_time; uint64_t rt_ = t>ct_?t-ct_:ct_-t;
			//debug_print_syslog(0,"vehicle_alarm_begin %s %llu,%llu",vvid.c_str(),rt,rt_);
			if (rt>45*1000 || rt_>45*1000 )
			{
				debug_print_syslog(0,"vehicle_alarm_time_ %s",vvid.c_str());
				if (vinfo.is_alarm)
					deal_alarm_vehicle(vvid,it_vlist_2->second);
				it_cv = m_CloserVehicle.erase(it_cv);
				continue;
			}
			double dis = get_absolute_distance(it_vlist_1->second,it_vlist_2->second)*it_vlist_1->second->map_scale;
			debug_print_syslog(0,"vehicle_alarm_distance %s %f",vvid.c_str(),dis);

			time_t tt = time(0);
			if (dis>sls_setting.rear_end_d ||!rear_end_arg_algo(it_vlist_1->second,it_vlist_2->second))
			{
				if (vinfo.backfired_start_time==0)
					vinfo.backfired_start_time=tt;
				vinfo.real_end_start_time=0;
				if (tt-vinfo.backfired_start_time>sls_setting.rear_end_t)
				{
					debug_print_syslog(0,"vehicle_alarm_backfired_timeout %s",vvid.c_str());
					if(vinfo.is_alarm)
						deal_alarm_vehicle(vvid,it_vlist_1->second);
					it_cv = m_CloserVehicle.erase(it_cv);
					continue;
				}
			}
			else
			{
				vinfo.backfired_start_time =0;
				if (vinfo.real_end_start_time==0)
					vinfo.real_end_start_time=tt;
				if (tt-vinfo.real_end_start_time>sls_setting.rear_end_t)
				{
				//	debug_print_syslog(0,"vehicle_alarm_real_end_timeout %s",vvid.c_str());
					if (!vinfo.is_alarm)
					{
						debug_print_syslog(0,"vehicle_alarm_real_end_timeout_exec %s",vvid.c_str());
						deal_alarm_vehicle(vvid,it_vlist_1->second);
						vinfo.is_alarm = true;
					}
				}
			}
			++it_cv;
		}
	}
}
void CYAServerDlg::uwb_putDb(std::vector<std::string> &v)
{
	//std::string s("0010000000333&0010000000273,1523263861,1523267461,1523263861&491.717&329,1523264761&674&447,1523265662&588&393,1523266561&885&587,");
	//cacti::StringUtil::split(v,s,",");
	std::stringstream ss;
	ss<<"REPLACE INTO uwb_more_card_info(uwb_cardone,uwb_cardtwo,uwb_timestamp,uwb_totaldis,uwb_ctindex) VALUES ";
	std::string card1 = v[0].substr(0,v[0].find('&'));
	std::string card2 = v[0].substr(v[0].find('&')+1);

	for (auto it = v.begin()+3;it != v.end()-1;it++)
	{
		std::vector<std::string> vt;
		cacti::StringUtil::split(vt,*it,"&");
		time_t time_T=0;
		time_T = atol(vt[0].c_str());
		//struct tm *tmTime;
		//tmTime = localtime(&time_T);
		//char* format = "%Y-%m-%d %H:%M:%S";
		//char strTime[100];
		//strftime(strTime, sizeof(strTime), format, tmTime);
		std::string strTime = CFunctions::timet_to_string_with_ms(time_T*1000);
		ss<<"('"<<card1<<"','"<<card2<<"','"<<strTime<<"',"<<vt[1]<<","<<vt[2]<<"),";
	}
	std::string sql = ss.str();
	sql.pop_back();
	sql+=";";
	//debug_print_syslog(0,"LemonHash SQL:%s",sql.c_str());
	//push db....
	m_qsmSQL->AddString(sql.c_str());
}
void CYAServerDlg::uwb_alarm(std::map<uint64_t,std::string>&m,bool flag,std::shared_ptr<NAMESPACE_POINT::card_interface>c)
{
	std::shared_ptr<Card> bc = std::dynamic_pointer_cast<Card>(c);
	if(flag)//spart and del alarm...
	{
		for (auto it:m)
		{
			EventMap::iterator it_ev = mp_event_list->find(it.first);
			if(it_ev != mp_event_list->end())
			{
				it_ev->second->status = ES_END;
				it_ev->second->cur_time = time(NULL);
				it_ev->second->obj_id  = bc->card_id;
				it_ev->second->map_id = bc->map_id;
				it_ev->second->area_id = bc->area_id;
				it_ev->second->x = bc->x;
				it_ev->second->y = bc->y;
				//it_ev->second->cur_value = ndiff;
				it_ev->second->is_sent = false;
				store_data_event(it_ev->second);
				add_event(it_ev->second);
			}
		}
	}
	else  //together and alarm
	{
		for (const auto it:m)  //it->second ...string for info 
		{	//"111&123,123123123,123123123,11&12&13,"
			INT64 ev_id = it.first;
			std::vector<std::string> v;
			cacti::StringUtil::split(v,it.second,",");
			uwb_putDb(v);
			EventMap::iterator it_ev = mp_event_list->find(ev_id);
			if(it_ev == mp_event_list->end())
			{
				std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
				ev->status = ES_START;
				ev->ev_type = ET_UWB_MORE_CARD;
				ev->obj_type = OT_UWB_MORE_CARD;
				ev->obj_id = v[0];
				ev->cur_time =std::atol(v[1].c_str());

				ev->map_id =bc->map_id;
				ev->area_id = bc->area_id;
				ev->x = bc->x;
				ev->y = bc->y;
				time_t tmp = std::atol(v[2].c_str());
				ev->cur_value = *((int64_t*)&tmp)*ms;
				//ev->limit_value = READER_TIMEOUT;
				//ev->cur_value = ndiff;
				ev->is_sent = false;
				ev->desc = v[0];
				store_data_event(ev);
				add_event(ev);
			}
			else
			{
				it_ev->second->is_sent = false;
				//it_ev->second->cur_time = std::atol(v[1].c_str());
				time_t tmp = std::atol(v[2].c_str());
				it_ev->second->cur_value = *((int64_t*)&tmp)*ms;
				//new string...
			}		
		}
	}
}
void CYAServerDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_BTN_START, m_btStart);
	DDX_Control(pDX, IDC_BTN_STOP, m_btStop);
	DDX_Control(pDX, IDC_LIST_READER, m_listctrl_reader);
	DDX_Control(pDX, IDC_LIST_LOG, m_list_log);	
	DDX_Text(pDX, IDC_EDIT_READERID, m_reader_id_hist);
}

BEGIN_MESSAGE_MAP(CYAServerDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BTN_START, &CYAServerDlg::OnBnStart)
	ON_BN_CLICKED(IDC_BTN_STOP, &CYAServerDlg::OnBnStop)
	ON_BN_CLICKED(IDC_BTN_EXIT, &CYAServerDlg::OnBnExit)
	ON_BN_CLICKED(IDC_BTN_SYNCTIME, &CYAServerDlg::OnBnSyncTime)
	ON_MESSAGE(WM_ON_MONITOR, on_monitor)
	ON_COMMAND(ID_START, &CYAServerDlg::OnBnStart)
	ON_COMMAND(ID_STOP, &CYAServerDlg::OnBnStop)
	ON_COMMAND(ID_EXIT, &CYAServerDlg::OnBnExit)
	ON_COMMAND(ID_MENU_DB, &CYAServerDlg::OnMenuDb)
	ON_COMMAND(ID_MENU_LOG, &CYAServerDlg::OnMenuLog)
	ON_COMMAND(ID_MENU_PARAM, &CYAServerDlg::OnMenuParam)
	ON_BN_CLICKED(IDC_BTN_HIS, &CYAServerDlg::OnBnCallHisData)
	ON_MESSAGE(WM_REFRESH_IP_LIST, &CYAServerDlg::OnMsgRefreshIpList)
	ON_MESSAGE(WM_REMOVE_SOCKET, &CYAServerDlg::OnRemoveSocket)
	ON_EN_UPDATE(IDC_EDIT_READERID, &CYAServerDlg::OnEnUpdateEditReaderid)
	ON_COMMAND(ID_ABOUT, &CYAServerDlg::OnAbout)
	ON_BN_CLICKED(IDC_BUTTON1, &CYAServerDlg::OnBnTest)
END_MESSAGE_MAP()

// CYAServerDlg 消息处理程序

UINT WaitForS(int nSecond,bool bSleep=false)//用于等待一段时间的函数,普通精度的，参数单位秒	
{
	COleDateTime start_time = COleDateTime::GetCurrentTime();
	COleDateTimeSpan end_time = COleDateTime::GetCurrentTime()-start_time;
	while(end_time.GetTotalSeconds() < nSecond){
		if(!bSleep){
			MSG msg;
			PeekMessage(&msg,NULL,0,0,PM_NOREMOVE);
			TranslateMessage(&msg); 
			DispatchMessage(&msg);
			//以上四行是实现在延时或定时期间能处理其他的消息，降低CPU的占有率，但也降低延时或定时精度
		}
		Sleep(80);
		end_time = COleDateTime::GetCurrentTime() - start_time;
	}
	return 0;
}

UINT WaitForMS(int mSecond,bool bSleep=false)//高精度的等待函数，参数单位毫秒
{
	double dfFreq; 
	LARGE_INTEGER litmp; 
	QueryPerformanceFrequency(&litmp);
	dfFreq = (double)litmp.QuadPart;// 获得计数器的时钟频率

	QueryPerformanceCounter(&litmp);
	LONGLONG QPart0 = litmp.QuadPart;// 获得初始值
	while((double)(litmp.QuadPart-QPart0)/dfFreq < double(mSecond/1000)){
		if(!bSleep){
			MSG msg;
			PeekMessage(&msg,NULL,0,0,PM_NOREMOVE);
			TranslateMessage(&msg); 
			DispatchMessage(&msg);
			//以上四行是实现在延时或定时期间能处理其他的消息，降低CPU的占有率，但也降低延时或定时精度
		}
		QueryPerformanceCounter(&litmp);
	}
	return 0;
}
std::time_t time_recode_staff_number;
DWORD time_send_json_device_state;
DWORD time_send_json_alarm;
DWORD time_send_json_postion;
DWORD time_send_call;
DWORD time_send_help;
DWORD time_send_leader;
DWORD time_load_leader;
DWORD time_cal_vehicle_meeting;
DWORD time_ws_connect;
DWORD time_ws_connect_ex;
DWORD time_send_heart;
DWORD time_driving_face_check_interval;
DWORD time_driving_face_check_interval_alarm; //lemon
DWORD time_send_ins_adjust;
DWORD time_exec_sql;
DWORD time_send_person_on_car;
DWORD time_monkeycar_distance_adjust;
DWORD time_send_sync_time;

bool g_exit=false;
volatile LONG g_QueueItemCount = 0;

CMysqlConnPool* g_pConnPool = NULL;
CMysqlConnPool* g_pConnPool_Bk = NULL;
bool g_StoreMultDatabase = false;

DWORD WINAPI _exec_sql(const char * lparam)
{
	if (g_pConnPool->m_needConnect)
	{
		debug_print_syslog(0, "_EXEC_SQL_ERROR_FOR_LOST_SERVER:%s",lparam);
		return 1;
	}
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_85);
	::InterlockedIncrement(&g_QueueItemCount);
	if(NULL == lparam)
	{
		debug_print_syslog(0, "_exec_sql error: lparam is NULL");
		return 1;
	}

	debug_print_syslog(0, "[lemon]_exec_sql [%s]",lparam);

	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn, g_pConnPool);

	//MYSQL_RES *pRes = NULL;
	//pRes = getMysqlRes(strsql);

	if(pConn == NULL)
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_86);
		::InterlockedDecrement(&g_QueueItemCount);
		return 1;
	}
	int err = 0;

	pConn->MultiExecute(lparam, err);
	switch (err)
	{
	case CR_COMMANDS_OUT_OF_SYNC:
		break;
	case CR_SERVER_GONE_ERROR:
	case CR_SERVER_LOST:
		{	
			pDbGuard.isVaild();
		}
		break;
	case CR_UNKNOWN_ERROR:

	default:
		break;
	}
	if(err > 0){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_87);
		debug_print_syslog(0, "sql error: [%d] , %s", err,lparam);
	}
	if(g_StoreMultDatabase){
		CMysqlConn* pConnBk = NULL;
		CDBConnGuard pDbGuardBk(pConnBk, g_pConnPool_Bk);
		if(pConnBk == NULL)
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_267);
			::InterlockedDecrement(&g_QueueItemCount);
			return 1;
		}
		err = 0;

		pConnBk->MultiExecute(lparam, err);
		switch (err)
		{
		case CR_COMMANDS_OUT_OF_SYNC:
			break;
		case CR_SERVER_GONE_ERROR:
		case CR_SERVER_LOST:
			{			
				pDbGuardBk.isVaild();
			}
			break;
		case CR_UNKNOWN_ERROR:

		default:
			break;
		}
		if(err > 0){
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_268);
			debug_print_syslog(0, "sql_bk error: [%d]%s", err,lparam);

		}
	}
	::InterlockedDecrement(&g_QueueItemCount);
	return 0;
}

DWORD WINAPI _parse_package_data(LPVOID lparam)
{
	::InterlockedIncrement(&g_QueueItemCount);
	ParseData* data =  (ParseData*)lparam;
	CYAServerDlg* dlg = reinterpret_cast<CYAServerDlg*>(data->handle);
#ifdef TRACE_MEMORY_PARSE_PACKAGE
	dlg->parse_package_data(data->buf, data->len, data->dwConnID);
#endif // TRACE_MEMORY_PARSE_PACKAGE

	free(data);
	::InterlockedDecrement(&g_QueueItemCount);
	return 0;
}

DWORD WINAPI _parse_data_server(LPVOID lparam)
{
	::InterlockedIncrement(&g_QueueItemCount);
	ParseData* data =  (ParseData*)lparam;
	CYAServerDlg* dlg = reinterpret_cast<CYAServerDlg*>(data->handle);
#ifdef TRACE_MEMORY_PARSE_SERVER
	dlg->parse_data_server(data->buf, data->len, data->dwConnID);
#endif 
	data->handle->m_nMallocTimes--;
	delete data;
	data = NULL;
	Sleep(1);
	::InterlockedDecrement(&g_QueueItemCount);
	return 0;
}

UINT _thread_timer(LPVOID lparam)//给web发送的定时器线程make
{
	//debug_print_syslog(0,"enter _thread_timer: %s %d",__FILE__,__LINE__);
	CYAServerDlg* dlg = reinterpret_cast<CYAServerDlg*>(lparam);
	ULONGLONG cur_time = ::GetTickCount();
	while(!g_exit){
		//debug_print_syslog(0,"enter _thread_timer: %s %d ,%ulld",__FILE__,__LINE__,cur_time);
		cur_time = ::GetTickCount();
		if(cur_time - time_send_json_alarm > theApp.send_json_alarm){
			LogInfo_ li(std::string("deal_areas"));
			time_send_json_alarm = cur_time; 
			//处理区域超员告警
			dlg->deal_areas();
			dlg->send_json_data(JSON_CMD_VALUE_PUSH, dlg->get_json_event());
		}
		//debug_print_syslog(0,"core dump 1 in _thread_timer: %s %d ,%ulld",__FILE__,__LINE__,cur_time);
		// send_json_device
		if(cur_time - time_send_json_device_state > theApp.send_json_device){
			LogInfo_ li(std::string("deal_readers"));
			time_send_json_device_state = cur_time; 
			dlg->deal_readers();
			dlg->send_json_data(JSON_CMD_VALUE_PUSH, dlg->get_json_device_state());
			dlg->deal_lamp_light_alarm();
		}
		//debug_print_syslog(0,"core dump 2 in _thread_timer: %s %d ,%ulld",__FILE__,__LINE__,cur_time);
		//send_json_postion;//（唯一发定位坐标的地方入口）
		if(cur_time - time_send_json_postion > theApp.send_json_postion - 200 && !g_position_build)
		{
			LogInfo_ li(std::string("package_data"));
			// lihongzhen  2017/10/24 提前200ms预生成json串，保证前端流畅
			//猴车现在这里处理
			//dlg->change_monkeycar_index();
			dlg->modify_card_speed(5);
			dlg->deal_card_lost_state();
			dlg->package_data();
			g_position_build = true;
		}
		//debug_print_syslog(0,"core dump 3  in _thread_timer: %s %d ,%ulld",__FILE__,__LINE__,cur_time);
		if(cur_time - time_send_json_postion > theApp.send_json_postion)
		{
			//观察定时器的定时效果
			//unsigned long long now_time = time(NULL) * 1000;
			//std::stringstream _ss_log;
			//_ss_log<<"+++++thread_time+++++:"<<now_time ;
			//debug_print_syslog(0,"%s", _ss_log.str().c_str());
			time_send_json_postion = cur_time;
			if(g_position_build)
			{
				//if(m_log_send_package)
				if(g_position_string != ""){
					Log::write_log(FILE_TYPE::JSON_S, g_position_string, true);
				}
				dlg->send_json_data(JSON_CMD_VALUE_PUSH, g_position_string);
				g_position_build = false;
				// 发送开关机状态信息给Web
				if(dlg->mp_coaldringface_card_list.size() != 0)
				{
					std::string strVehicleState = dlg->get_json_vehicle_state();
					dlg->send_json_data(JSON_CMD_VALUE_PUSH,strVehicleState);
					Log::write_log(FILE_TYPE::JSON_S, strVehicleState, true);
				}
			}
		}
		//debug_print_syslog(0,"core dump 4 in _thread_timer: %s %d ,%ulld",__FILE__,__LINE__,cur_time);
		//send help 
		if(cur_time - time_send_help > theApp.send_json_alarm){
			LogInfo_ li(std::string("deal_help"));
			time_send_help = cur_time;
			if(dlg->get_help_card_nums() > 0){				
				dlg->send_json_data(JSON_CMD_VALUE_PUSH,dlg->get_json_help());
			}	
		}
		//debug_print_syslog(0,"core dump 5 in _thread_timer: %s %d ,%ulld",__FILE__,__LINE__,cur_time);
		// send_call_data
		if(cur_time - time_send_call > theApp.time_send_call){
			LogInfo_ li(std::string("call_list"));
			std::string call_list = "";
			call_list = dlg->get_json_call_list();
			if (call_list != "")
			{
				dlg->send_json_data(JSON_CMD_VALUE_PUSH,call_list);
			}

			time_send_call = cur_time;
			dlg->clear_call_info();
			dlg->send_call_info();			
		}
		//debug_print_syslog(0,"core dump 6 in _thread_timer: %s %d ,%ulld",__FILE__,__LINE__,cur_time);
		if(!dlg->is_websocket_login && cur_time - time_ws_connect > theApp.ws_connect_interval){
			time_ws_connect = cur_time;
			if(!dlg->is_websocket_ok){
				dlg->ws_open();
			}
			dlg->ws_login();
		}
		//debug_print_syslog(0,"core dump 7 in _thread_timer: %s %d ,%ulld",__FILE__,__LINE__,cur_time);
		if(!dlg->is_websocket_login_ex && cur_time - time_ws_connect_ex > theApp.ws_connect_interval){
			time_ws_connect_ex = cur_time;
			if(!dlg->is_websocket_ok_ex){
				dlg->ws_open_ex();
			}
			dlg->ws_login_ex();
		}
		//debug_print_syslog(0,"core dump 8 in _thread_timer: %s %d ,%ulld",__FILE__,__LINE__,cur_time);
		//当掘进机有数据的时候再来进行操作。
		// update driving face status
		if(cur_time - time_driving_face_check_interval > theApp.send_json_drivingface){
			LogInfo_ li(std::string("driving_face"));
			time_driving_face_check_interval = cur_time;	
			//check driving face shift state
			dlg->driving_face_shift_start();
			dlg->send_drivingface_card_position_json();
		}
		//debug_print_syslog(0,"core dump 9 in _thread_timer: %s %d ,%ulld",__FILE__,__LINE__,cur_time);
		if(cur_time - time_send_leader > theApp.send_json_leader)
		{
			LogInfo_ li(std::string("get_json_leader_arrange"));
			time_send_leader = cur_time;
			dlg->send_json_data(JSON_CMD_VALUE_PUSH, dlg->get_json_leader_arrange());
		}
		//debug_print_syslog(0,"core dump 10 in _thread_timer: %s %d ,%ulld",__FILE__,__LINE__,cur_time);
		if(cur_time - time_load_leader > theApp.load_leader)
		{
			LogInfo_ li(std::string("init_leader_arrange"));
			time_load_leader = cur_time;
			dlg->init_leader_arrange();
			//TRACE(_T("init_leader_arrange"));
		}
		//debug_print_syslog(0,"core dump 11 in _thread_timer: %s %d ,%ulld",__FILE__,__LINE__,cur_time);
		if (false)
		{
			dlg->deal_drivingface_regular_cycle();
			dlg->deal_drivingface_real_distance();
			dlg->check_reader_simulate_status();
			dlg->send_change_reader_to_card();
		}
		//debug_print_syslog(0,"core dump 12 in _thread_timer: %s %d ,%ulld",__FILE__,__LINE__,cur_time);
		if(cur_time - time_exec_sql > 3000)
		{
			LogInfo_ li(std::string("Execute"));
			time_exec_sql = cur_time;
			if(dlg->m_qsmSQL){
				dlg->m_qsmSQL->Execute(false);
			}
		}
		//debug_print_syslog(0,"core dump 13 in _thread_timer: %s %d ,%ulld",__FILE__,__LINE__,cur_time);
		//后续如果需要三率功能，需要开启此处
		if (false)
		{
			// 采煤机与掘进机超时关机处理 
			EnterCriticalSection(&dlg->m_csCoalDrvingFaceList);
			time_t tCurTime = time(NULL);
			auto it_card = dlg->mp_coaldringface_card_list.begin();
			for(;it_card != dlg->mp_coaldringface_card_list.end(); it_card++) 
			{
				time_t tStaTime = it_card->second->m_lastrecv_time;
				if(tCurTime - tStaTime > theApp.shutdown_timeout_threshold && it_card->second->m_bOpen)
				{
					dlg->close_machine(it_card->second);
					debug_print_syslog(0,"_thread_timer card: %s , close time: %ld", it_card->second->card_id.c_str(),tCurTime);
					char chLog[MAX_LOG_LENGTH] = {0};
					std::string log = "";
					sprintf_s(chLog,"_thread_timer card:%s, close time: %ld",it_card->second->card_id.c_str(),tCurTime);
					log = chLog;
					Log::write_log(FILE_TYPE::STARTUP_RATIO,log,true);
				}
			}
			LeaveCriticalSection(&dlg->m_csCoalDrvingFaceList);
		}
		
		Sleep(10);
		//debug_print_syslog(0,"end one loop in _thread_timer: %s %d ,%ulld",__FILE__,__LINE__,cur_time);
	}
	return 0;
}

UINT _thread_monitor(LPVOID lparam)
{
	CYAServerDlg* dlg = reinterpret_cast<CYAServerDlg*>(lparam);
	time_t time_end = time(NULL);
	while (!g_exit){
		time_t time_current = time(NULL);
		// 判断采集状态， 20s没有接收到数据认为采集中断 
		dlg->is_server_ok = (difftime(time_current, dlg->m_time_last_rec) > 20) ? false : true;
		dlg->set_run_state(); // 更新采集运行状态

		if(!IsWindow(theApp.m_hwnd_monitor)){ // 监控程序没有打开
			theApp.m_hwnd_monitor = NULL;
			//// 启动监控程序
			//if(strlen(theApp.m_path_monitor)<=0){
			//	strcpy(theApp.m_path_monitor, "YAMonitor.exe");//启动同目录下的monitor
			//}
			//WinExec(theApp.m_path_monitor, SW_HIDE);
		}
		// 发送给监控程序
		if(theApp.m_hwnd_monitor && dlg->is_start_tcp ){
			WPARAM wpSERVERSTATE=WPARAM(dlg->m_uint_state);
			::PostMessage(theApp.m_hwnd_monitor, WM_ON_MONITOR, wpSERVERSTATE, LPARAM(dlg->m_hWnd));
		}
		//WaitForS(10);
		Sleep(10);
	}
	return 0;
}

BOOL CYAServerDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	//加载系统配置
	m_bUseFilter = theApp.use_filter;
	if(m_bUseFilter){
		m_nFilterType = FILTER_KALMAN;
	}else{
		m_nFilterType = NO_FILTER;
	}

	m_log_sys_status = theApp.log_sys_status;
	m_log_raw_data   = theApp.log_raw_data;
	m_log_parse_data = theApp.log_parse_data;
	m_log_send_package = theApp.log_send_package;
	m_log_recv_package = theApp.log_recv_package;
	m_log_locate_data  = theApp.log_locate_data;

	m_reader_interval_time = theApp.reader_interval_time * 1.0 / 1000.0;
	cur_shift_id = 0;
	m_bYAserverBoot = true;
	m_bZero = false;
	m_nMallocTimes = 0;

	//初始化线程池
	//m_LogThreadPool.Initialize((void*)100,THREADPOOL_SIZE);
	// 设置此对话框的图标。当应用程序主窗口不是对话框时，框架将自动
	// 执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	init_queuestring();
	init_param();
	init_ui();

	init_base_data();
	load_his_data();


	theApp.set_server_handle(this->m_hWnd);	
	theApp.load_monitor_conf();

	RECT rc;
	GetWindowRect(&rc);
	rc.left=rc.right;
	rc.right+=250;

	//创建菜单
	m_mnMain.LoadMenu(IDR_MENUMAIN);
	SetMenu(&m_mnMain);
	CString strInfo;

	//// 将图标放入系统托盘
	//nd.cbSize	= sizeof (NOTIFYICONDATA);
	//nd.hWnd	= m_hWnd;
	//nd.uID	= IDI_ICON;
	//nd.uFlags	= NIF_ICON|NIF_MESSAGE|NIF_TIP;
	//nd.uCallbackMessage= WM_NOTIFYICON;
	//nd.hIcon	= m_hIcon;

	//strcpy(nd.szTip, "采集应用服务器");
	//Shell_NotifyIcon(NIM_ADD, &nd);

	m_Pthread.reset(new std::thread(std::bind(&CYAServerDlg::run,this)));

	m_thread_monitor = ::AfxBeginThread(_thread_monitor, this, THREAD_PRIORITY_HIGHEST);
	time_recode_staff_number = 0;
	time_send_json_device_state=time_send_json_alarm=time_send_json_postion= ::GetTickCount();
	time_send_call=time_send_help=time_driving_face_check_interval = ::GetTickCount();
	time_load_leader = time_send_leader = time_cal_vehicle_meeting = ::GetTickCount();
	time_exec_sql = ::GetTickCount();
	time_send_ins_adjust = time_send_person_on_car = ::GetTickCount();
	time_monkeycar_distance_adjust = ::GetTickCount();
	m_thread_timer = ::AfxBeginThread(_thread_timer, this, THREAD_PRIORITY_HIGHEST);

	SetWindowText(_T("永安信通数据采集系统"));
	OnBnStart();

	UpdateData(FALSE);
	debug_print_syslog(0, "Server dialog init success.");
	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

void CYAServerDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void CYAServerDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文or

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CYAServerDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

/*
* 点击启动按钮
*		登录websocket服务器
*		启动tcp server
*
* param
*		无
*
* return
*		无
*
*/
void CYAServerDlg::OnBnStart()
{
	if(!is_websocket_login){
		ws_login();
	}

	if(!is_websocket_login_ex){
		ws_login_ex();
	}
	start_tcp_server();
}

/*
* 点击停止按钮
*		退出websocket服务器
*		停止tcp server
*
* param
*		无
*
* return
*		无
*
*/
void CYAServerDlg::OnBnStop()
{
	stop_tcp_server();
	if(is_websocket_login){
		ws_logout();
	}

	if(is_websocket_login_ex){
		ws_logout_ex();
	}
}

LRESULT CYAServerDlg::on_monitor(WPARAM wParam, LPARAM lParam)
{
	if(is_start_tcp){
		m_uint_state = wParam ;
	}
	if(wParam == 0xFFFF){
		stop_and_exit();
	}
	return S_OK;
}

int CYAServerDlg::init_smart_pointer_var()
{
	mp_reader_path_list_tdoa = std::make_shared<TDOAReaderPathMap>();
	mp_reader_path_list_tof = std::make_shared<ReaderPathMap>();

	mp_card_list_over_time_person = std::make_shared<CardMap>();
	mp_card_list_forbidden_person = std::make_shared<CardMap>();
	mp_card_list_help = std::make_shared<CardMap>();
	mp_card_list_area_over_time_person = std::make_shared<CardMap>();
	mp_card_list_forbidden_vehicle = std::make_shared<CardMap>();
	mp_card_list_over_time_vehicle = std::make_shared<CardMap>();
	mp_card_list_over_speed_vehicle = std::make_shared<CardMap>();
	mp_card_list_area_over_time_vehicle = std::make_shared<CardMap>();
	mp_card_list_over_count_person = std::make_shared<CardMap>();
	mp_card_list_over_count_vehicle = std::make_shared<CardMap>();

	mp_card_warning_point_alarm = std::make_shared<CardMap>();//lemon
	mp_card_geofault_alarm = std::make_shared<CardMap>();//lemon
	mp_card_list_motionless = std::make_shared<CardMap>();
	mp_area_list_ = std::make_shared<Area_Map>();//lemon 2017/11/20

	mp_area_over_count_person = std::make_shared<AreaMap>();
	mp_area_over_time_person = std::make_shared<AreaMap>();
	mp_area_forbidden_person = std::make_shared<AreaMap>();
	mp_area_over_count_vehicle = std::make_shared<AreaMap>();
	mp_area_over_time_vehicle = std::make_shared<AreaMap>();
	mp_area_forbidden_vehicle = std::make_shared<AreaMap>();

	mp_event_list = std::make_shared<EventMap>();
	mp_light_call_list = std::make_shared<LightCallMap>();
	mp_ins_cal_data_list = std::make_shared<CalDataMap>();
	//mp_card_hand_up_list = std::make_shared<HandUpVehicleMap>();

	mp_card_hand_up_list.swap(std::make_shared<HandUpVehicleMap>());
	mp_moving_reader_list = std::make_shared<MovingReaderMap>();

	return 0;
}

int CYAServerDlg::init_reader_boundary_area(int reader_id /*= 0*/)
{
	char strsql[LENGTH_SQL] = {0};	
	if(reader_id == 0){
		sprintf_s(strsql, "SELECT boundary_area_id,name,map_id,reader_id,path FROM dat_boundary_area;;");
	}else{
		sprintf_s(strsql, "SELECT boundary_area_id,name,map_id,reader_id,path FROM dat_boundary_area WHERE reader_id = %d; ", reader_id);
	}

	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	//pRes = getMysqlRes("select * from dat_chamber;");
	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}

	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))	{
		int reader_id = (pRow[3] == NULL? 0 : atoi(pRow[3]));
		ReaderMap::iterator it_reader = mp_reader_list.find(reader_id);
		if (it_reader == mp_reader_list.end())
		{
			continue;
		}
		if (it_reader->second->pBoundaryArea == nullptr)
		{
			it_reader->second->pBoundaryArea = std::make_shared<BoundaryArea>();
		}
		it_reader->second->pBoundaryArea->boundary_area_id = (pRow[0] == NULL? 0 : atoi(pRow[0]));
		it_reader->second->pBoundaryArea->name = pRow[1];
		it_reader->second->pBoundaryArea->map_id = (pRow[2] == NULL? 0 : atoi(pRow[2]));
		it_reader->second->pBoundaryArea->reader_id = reader_id;
		it_reader->second->pBoundaryArea->path = (pRow[4] == NULL)? "" : pRow[4];

		it_reader->second->pBoundaryArea->init_border(it_reader->second->pBoundaryArea->path);

		nRow++;
	}

	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_BOUNDARY_AREA), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

/*

* 初始化移动分站id，以及移动分站绑定车卡的信息
*
* param
*		reader_id			查询的移动分站id
*
* return
*		成功返回0，失败返回非零值
*
*/
int CYAServerDlg::init_moving_reader(int reader_id /*= 0*/)
{
	char strsql[LENGTH_SQL] = {0};	
	if(reader_id == 0){
		sprintf_s(strsql, "SELECT moving_reader_id,card_id FROM dat_moving_reader;");
	}else{
		sprintf_s(strsql, "SELECT moving_reader_id,card_id FROM dat_moving_reader WHERE moving_reader_id = %d; ", reader_id);
	}

	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}

	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))	{
		int moving_reader_id = 0;
		moving_reader_id = (pRow[0] == NULL)?0:atoi(pRow[0]);

		MovingReaderMap::iterator it = mp_moving_reader_list->find(moving_reader_id);
		if (it == mp_moving_reader_list->end())
		{
			std::shared_ptr<MovingReader> pMovingReader = std::make_shared<MovingReader>();
			mp_moving_reader_list->insert(std::make_pair(moving_reader_id,pMovingReader));
			it = mp_moving_reader_list->find(moving_reader_id);
		}

		it->second->moving_reader_id = moving_reader_id;

		//移动分站绑定的车卡
		std::string card_id = "";
		card_id = (pRow[1] == NULL)?"":pRow[1];
		CardMap::iterator it_card = mp_card_list_all.find(card_id);
		if (card_id == "" || it_card == mp_card_list_all.end())
		{
			it->second->pVehicleCard = nullptr;
		}else{
			it->second->pVehicleCard = it_card->second;
		}

		nRow++;
	}

	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_MOVING_READER), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

/*
* 初始化对话框ui
*
* param
*		无
*
* return
*		无
*
*/
void CYAServerDlg::init_ui()
{
	set_app_state(ST_STOPPED);
	m_listctrl_reader.SetColumnHeader(_T("分站号,50;分站地址,100;状态,50;类型,60"));
	m_listctrl_reader.SetGridLines(TRUE);
	m_listctrl_reader.SetEditable(FALSE);
	m_listctrl_reader.SetSortable(FALSE);

	Invalidate(FALSE);
}

void CYAServerDlg::set_app_state( EnAppState eas )
{
	m_enState = eas;

	if(this->GetSafeHwnd() == nullptr)
		return;

	m_btStart.EnableWindow(m_enState == ST_STOPPED);
	m_btStop.EnableWindow(m_enState == ST_STARTED);

	GetDlgItem(IDC_BTN_HIS)->EnableWindow(m_enState == ST_STARTED);
	GetDlgItem(IDC_BTN_SYNCTIME)->EnableWindow(m_enState == ST_STARTED);

	CMenu* pMenu = GetMenu();
	ASSERT_VALID (pMenu);
	if(m_enState == ST_STOPPED){
		pMenu->EnableMenuItem(ID_START,MF_BYCOMMAND | MF_ENABLED);//启用
		pMenu->EnableMenuItem(ID_STOP,MF_BYCOMMAND | MF_GRAYED);//禁用
	}else if(m_enState == ST_STARTED){
		pMenu->EnableMenuItem(ID_START,MF_BYCOMMAND | MF_GRAYED);//禁用
		pMenu->EnableMenuItem(ID_STOP,MF_BYCOMMAND | MF_ENABLED);//启用		
	}
}

void CYAServerDlg::init_param()
{
	::SetMainWnd(this);
	::SetInfoList(&m_list_log);

	sls_setting.over_count_person = 1000;
	sls_setting.over_count_vehicle = 100;
	sls_setting.over_speed = 30;
	sls_setting.over_time_person = 36000;
	sls_setting.over_time_vehicle = 18000;
	sls_setting.att_endtime_offset_staff = 600;
	sls_setting.att_endtime_offset_vehicle = 600;
	sls_setting.att_starttime_offset_staff = 900;
	sls_setting.att_starttime_offset_vehicle = 600;
	sls_setting.geofault_warn_dis=50;

	g_pConnPool = new CMysqlConnPool();
	g_pConnPool_Bk = new CMysqlConnPool();

	m_time_last_rec = time(NULL);

	m_nPort = PORT_SERVER_MASTER;
	m_nCountClick = 0;
	m_ws_url = TEST_WS_URL;
	m_ws_url_ex = TEST_WS_URL;
	m_tcp_host = LOCAL_ADDRESS;

	is_server_ok = true;
	is_start_tcp = false;
	g_exit = false;

	GetCurShiftStartTime(m_shift_id);
	umpRootSyncNum.swap(unordered_map<unsigned long long, unsigned short>());

	for(int i = 0; i < MINE_EVENT_COUNT; i++){
		m_event_list[i] = 0;
	}

	InitializeCriticalSectionAndSpinCount(&m_csRefreshList, MAXCRITICALSECTIONSPINCOUNT);	
	InitializeCriticalSectionAndSpinCount(&m_csRemoveSocket, MAXCRITICALSECTIONSPINCOUNT);
	InitializeCriticalSectionAndSpinCount(&m_csParseDataServer, MAXCRITICALSECTIONSPINCOUNT);
	InitializeCriticalSectionAndSpinCount(&m_csSyncTime, MAXCRITICALSECTIONSPINCOUNT);
	InitializeCriticalSectionAndSpinCount(&m_csCallInfo, MAXCRITICALSECTIONSPINCOUNT);
	InitializeCriticalSectionAndSpinCount(&m_csHandUp, MAXCRITICALSECTIONSPINCOUNT);
	InitializeCriticalSectionAndSpinCount(&m_MC_Lock, MAXCRITICALSECTIONSPINCOUNT);
	InitializeCriticalSectionAndSpinCount(&m_csAreaList, MAXCRITICALSECTIONSPINCOUNT);
	InitializeCriticalSectionAndSpinCount(&m_csCoalDrvingFaceList, MAXCRITICALSECTIONSPINCOUNT);

	//从配置中读取(regedit)
	load_param_from_ini();
	std::string Error;
	//创建连接池
	if ( !sDBConnPool.Create( m_DBSetting, Error ) )
	{
		//printf("线程池创建失败,Err=%s\n", Error.c_str());
		debug_print_syslog(0,"init_param Err: Failed to create thread pool! Err=%s", Error.c_str());
		char chLog[MAX_LOG_LENGTH] = {0};
		std::string log = "";
		sprintf_s(chLog,"init_param Err: Failed to create thread pool! Err=%s", Error.c_str());
		log = chLog;
		Log::write_log(FILE_TYPE::STARTUP_RATIO,log,true);
		return;
	}
	database_connect();
}

void CYAServerDlg::stop_and_exit()
{
	if(is_start_tcp){
		stop_tcp_server();
	}
	if(is_websocket_login){
		ws_logout();
	}
	if(is_websocket_login_ex){
		ws_logout_ex();
	}
	g_exit = true;
	if(m_thread_monitor){
		WaitForSingleObject(m_thread_monitor->m_hThread, 0);
	}
	m_thread_monitor = NULL;
	if(m_thread_timer){
		WaitForSingleObject(m_thread_timer->m_hThread, 0);
	}
	m_thread_timer = NULL;

	if(m_qsmSQL){
		m_qsmSQL->Execute();
	}

	CString strlog;
	while(g_QueueItemCount >0){
		strlog.Format(_T("%s: %d"), _T(LOG_LEFT_THREAD), g_QueueItemCount);
		show_log(strlog);
		WaitForS(3);
	}

	::SetMainWnd(NULL);
	::SetInfoList(NULL);

	clear_all_list();

	g_pConnPool->CloseAllConn();
	g_pConnPool_Bk->CloseAllConn();

	DeleteCriticalSection(&m_csParseDataServer);
	DeleteCriticalSection(&m_csRemoveSocket);
	DeleteCriticalSection(&m_csRefreshList);
	DeleteCriticalSection(&m_csSyncTime);
	DeleteCriticalSection(&m_csCallInfo);
	DeleteCriticalSection(&m_csHandUp);
	DeleteCriticalSection(&m_csAreaList);
	DeleteCriticalSection(&m_MC_Lock);
	DeleteCriticalSection(&m_csCoalDrvingFaceList);

	CDialogEx::OnCancel();
	exit(0);
}

void CYAServerDlg::set_run_state()
{
	m_uint_state = 0;
	if(!is_server_ok){
		m_uint_state |= 0x10; // 长时间未接收到采集数据（网络故障，采集故障）
	}
}
int CYAServerDlg::init_rules(int id)
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	if(id == 0){
		sprintf_s(strsql, "SELECT rules_id ,STATUS FROM dat_rules;");
	}else{
		sprintf_s(strsql, "SELECT rules_id ,STATUS FROM dat_rules WHERE rules_id = %d; ", id);
	}
	pRes = getMysqlRes(strsql);

	if (NULL == pRes)
	{
		return 1;
	}
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes)){
		RulesMap::iterator it = m_rules_list.find(atoi(pRow[0]));
		if(it != m_rules_list.end()){
			it->second = atoi(pRow[1]);
		}else{
			m_rules_list.insert(make_pair(atoi(pRow[0]),atoi(pRow[1])));
			nRow++;
		}
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_RULES), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

void CYAServerDlg::init_coordinate_string2vec(string  monkeycar_coorninate,std::vector<point_2> &db_vector)
{
	if (monkeycar_coorninate.empty())
	{
		return;
	}
	vector<string> tmp = CFunctions::split(monkeycar_coorninate,";",true);
	if (tmp.size() <= 1)
	{
		return ;
	}
	//vector<point> tmp_vp;
	for (int i=0;i<tmp.size();i++)
	{
		//point mp;
		vector<string> t = CFunctions::split(tmp[i],",",true);
		if (t.size() !=2 )
		{
			return ;
		}
		point_2 mp;
		mp.x_ = CFunctions::round(atof((t[0]).c_str()),3);
		mp.y_ = CFunctions::round(atof((t[1]).c_str()),3);
		db_vector.push_back(mp);
	}
}
void CYAServerDlg::init_monkeycar_base_info()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	sprintf(strsql,"%s","SELECT monkeycar_id , monkeycar_areaid ,monkeycar_coordinate,monkeycar_speed FROM dat_monkeycar_base_info;");
	pRes = getMysqlRes(strsql);

	if (NULL == pRes)
	{
		return ;
	}
	int nRow = 0;

	while(pRow = mysql_fetch_row(pRes)){
		std::shared_ptr<db_area> db_area_ptr = std::make_shared<db_area>();
		db_area_ptr->m_areaid = atoi(pRow[1]);
		db_area_ptr->m_default_speed = atof(pRow[3]);
		init_coordinate_string2vec(pRow[2],db_area_ptr->m_point);
	

		std::shared_ptr<area> ma_ptr = std::make_shared<monkey_area>(db_area_ptr);
		mp_area_list_->insert(make_pair(db_area_ptr->m_areaid,ma_ptr));
		nRow++;
	}
	debug_print_syslog(0,"[Framework New Init]init %d infos",nRow);
	mysql_free_result(pRes);
	return ;
}

int CYAServerDlg::init_staffer(string staff_id /* = "" */, bool is_card /*= false*/ )
{
	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	if(staff_id.length() == 0){
		sprintf_s(buf, "SELECT s.staff_id, s.card_id, c.card_type_id, s.dept_id, s.group_id, s.occupation_id, \
					   ol.occupation_level_id,s.worktype_id,s.need_display,s.work_line,ds.name,dd.name \
					   FROM dat_staff_extend s \
					   LEFT JOIN dat_staff ds ON ds.staff_id = s.staff_id \
					   LEFT JOIN dat_dept dd ON dd.dept_id = s.dept_id \
					   LEFT JOIN dat_card c ON s.card_id = c.card_id \
					   LEFT JOIN dat_occupation o ON s.occupation_id = o.occupation_id \
					   LEFT join dat_occupation_level ol on ol.occupation_level_id = o.occupation_level_id \
					   WHERE c.card_type_id = 1 and s.duty_id = 0 and c.state_id = 0;");
	}else if(is_card){
		sprintf_s(buf, "SELECT staff_id, s.card_id, c.card_type_id, s.dept_id, s.group_id, s.occupation_id, \
					   ol.occupation_level_id,s.worktype_id,s.need_display,s.work_line,ds.name,dd.name \
					   FROM dat_staff_extend s \
					   LEFT JOIN dat_staff ds ON ds.staff_id = s.staff_id \
					   LEFT JOIN dat_dept dd ON dd.dept_id = s.dept_id \
					   LEFT JOIN dat_card c ON s.card_id = c.card_id \
					   LEFT JOIN dat_occupation o ON s.occupation_id = o.occupation_id \
					   LEFT join dat_occupation_level ol on ol.occupation_level_id = o.occupation_level_id \
					   WHERE c.card_type_id = 1 and s.duty_id = 0 AND c.state_id = 0 AND s.card_id = '%s';", staff_id.c_str());
	}else{
		sprintf_s(buf, "SELECT staff_id, s.card_id, c.card_type_id, s.dept_id, s.group_id, s.occupation_id, \
					   ol.occupation_level_id,s.worktype_id,s.need_display,s.work_line,ds.name,dd.name \
					   FROM dat_staff_extend s \
					   LEFT JOIN dat_staff ds ON ds.staff_id = s.staff_id \
					   LEFT JOIN dat_dept dd ON dd.dept_id = s.dept_id \
					   LEFT JOIN dat_card c ON s.card_id = c.card_id \
					   LEFT JOIN dat_occupation o ON s.occupation_id = o.occupation_id \
					   LEFT join dat_occupation_level ol on ol.occupation_level_id = o.occupation_level_id \
					   WHERE c.card_type_id = 1 and s.duty_id = 0 AND c.state_id = 0 AND staff_id = '%s';");
	}

	pRes = getMysqlRes(buf);
	if (NULL == pRes)
	{
		return 1;
	}
	std::shared_ptr<Card> pCard = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))	{
		CardMap::iterator it = mp_card_list_all.find(pRow[1]);
		if(it != mp_card_list_all.end()){
			pCard = it->second;
			nRow++;
		}else{
			pCard = std::make_shared<Card>(pRow[1], atoi(pRow[2]), theApp.z_offset);
			pCard->is_registered = false;			
			pCard->set_reader_path(mp_reader_path_list_tof, mp_reader_path_list_tdoa);
			//mp_card_list_all.insert(make_pair(pCard->card_id,pCard));
		}

		// lihongzhen  2017/8/26 避免部门列表中产生冗余数据
		if(staff_id.length() > 0 && pCard->dept_id != atoi(pRow[3]))
		{
			deal_card_dept_changed(pCard, atoi(pRow[3]));
		}
		if (staff_id.length() > 0 && (pCard->worktype_id == 16 || pCard->worktype_id ==40))
		{
			if (pCard->id !=  atoi(pRow[0])  || pCard->dept_id != (pRow[3] == NULL)?0:atoi(pRow[3])||pCard->worktype_id != (pRow[7] == NULL)?0:atoi(pRow[7]) )
			{
				remove_person_meanpos(pCard);
			}
		}
		pCard->id = atoi(pRow[0]);
		pCard->dept_id = (pRow[3] == NULL)?0:atoi(pRow[3]);
		pCard->group_id = (pRow[4] == NULL)?0:atoi(pRow[4]);
		pCard->occ_id = (pRow[5] == NULL)?0:atoi(pRow[5]);
		pCard->level_id = (pRow[6] == NULL) ? 0 : atoi(pRow[6]);
		pCard->worktype_id = (pRow[7] == NULL)?0:atoi(pRow[7]);

		pCard->need_display = (pRow[8] == NULL)?0:atoi(pRow[8]);//lmeon 2017/08/01
		pCard->m_staff_type=(pRow[9] == NULL)?0:atoi(pRow[9]);
		pCard->m_staffName=pRow[10]==NULL?"":pRow[10];

		pCard->m_deptName=pRow[11]==NULL?"":pRow[11];
		if (staff_id.length() > 0 && (pCard->worktype_id == 16 || pCard->worktype_id ==40))
		{
			add_person_meanpos(pCard);
		}
		if(m_bUseFilter){
			if(theApp.use_filter_odd){
				std::string temp = pRow[1];
				int a = atoi(temp.substr(temp.length() - 1 , 1).c_str());
				if(0 == a%2){
					pCard->EnableFilter(m_nFilterType);
				}
			}else{
				pCard->EnableFilter(m_nFilterType);
			}
		}
	}
	mysql_free_result(pRes);

	CString strlog = _T("");
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_STAFF), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

/*
* 初始化所有车卡信息
*
* param
*		vehicle_id ------	车卡id
*      is_card    ------	是否是卡
*
* return
*		成功返回0，失败返回1
*
*/
int CYAServerDlg::init_vehicle(string vehicle_id /* = "" */, bool is_card /*= false*/)
{
	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	if(vehicle_id.length() == 0){
		sprintf_s(buf, "SELECT ve.vehicle_id, ve.card_id, c.card_type_id, \
					   ve.dept_id, ve.group_id, v.vehicle_type_id, vt.vehicle_level_id, \
					   vt.is_railroad as vt_is_railroad,ve.need_display ,ve.power_alarm,\
					   vt.vehicle_category_id,v.bigger_car_flag,vc.over_speed \
					   FROM dat_vehicle_extend ve \
					   LEFT JOIN dat_vehicle v ON ve.vehicle_id = v.vehicle_id \
					   LEFT JOIN dat_card c ON ve.card_id = c.card_id \
					   LEFT JOIN dat_dept d ON ve.dept_id = d.dept_id \
					   LEFT JOIN dat_group g ON ve.group_id = g.group_id \
					   LEFT JOIN dat_vehicle_type vt ON v.vehicle_type_id = vt.vehicle_type_id \
					   LEFT JOIN dat_vehicle_category vc ON vc.vehicle_category_id = vt.vehicle_category_id \
					   WHERE (c.card_type_id = 2 or c.card_type_id = 4 or c.card_type_id = 5) and c.state_id = 0;");
	}else if(is_card){
		sprintf_s(buf, "SELECT ve.vehicle_id, ve.card_id, c.card_type_id, \
					   ve.dept_id, ve.group_id, v.vehicle_type_id, vt.vehicle_level_id, \
					   vt.is_railroad as vt_is_railroad,ve.need_display,ve.power_alarm,vt.vehicle_category_id,v.bigger_car_flag,vc.over_speed \
					   FROM dat_vehicle_extend ve \
					   LEFT JOIN dat_vehicle v ON ve.vehicle_id = v.vehicle_id \
					   LEFT JOIN dat_card c ON ve.card_id = c.card_id \
					   LEFT JOIN dat_dept d ON ve.dept_id = d.dept_id \
					   LEFT JOIN dat_group g ON ve.group_id = g.group_id \
					   LEFT JOIN dat_vehicle_type vt ON v.vehicle_type_id = vt.vehicle_type_id \
					   LEFT JOIN dat_vehicle_category vc ON vc.vehicle_category_id = vt.vehicle_category_id \
					   WHERE (c.card_type_id = 2 or c.card_type_id = 4 or c.card_type_id = 5) and c.state_id = 0 AND ve.card_id ='%s';", vehicle_id.c_str());
	}else{
		sprintf_s(buf, "SELECT ve.vehicle_id, ve.card_id, c.card_type_id, \
					   ve.dept_id, ve.group_id, v.vehicle_type_id, vt.vehicle_level_id, \
					   vt.is_railroad as vt_is_railroad,ve.need_display,ve.power_alarm,vt.vehicle_category_id,v.bigger_car_flag,vc.over_speed \
					   FROM dat_vehicle_extend ve \
					   LEFT JOIN dat_vehicle v ON ve.vehicle_id = v.vehicle_id \
					   LEFT JOIN dat_card c ON ve.card_id = c.card_id \
					   LEFT JOIN dat_dept d ON ve.dept_id = d.dept_id \
					   LEFT JOIN dat_group g ON ve.group_id = g.group_id \
					   LEFT JOIN dat_vehicle_type vt ON v.vehicle_type_id = vt.vehicle_type_id \
	                   LEFT JOIN dat_vehicle_category vc ON vc.vehicle_category_id = vt.vehicle_category_id \
					   WHERE (c.card_type_id = 2 or c.card_type_id = 4 or c.card_type_id = 5) and c.state_id = 0 AND ve.vehicle_id='%s';", vehicle_id.c_str());
	}

	pRes = getMysqlRes(buf);
	if (NULL == pRes)
	{
		return 1;
	}
	std::shared_ptr<Card> pCard = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))
	{
		CardMap::iterator it = mp_card_list_all.find(pRow[1]);
		if(it != mp_card_list_all.end()){
			pCard = it->second;
			nRow++;
		}else{
			continue;
			//pCard = std::make_shared<Card>(pRow[1], atoi(pRow[2]), theApp.z_offset);
			//pCard->is_registered = false;
			//pCard->set_reader_path(mp_reader_path_list_tof, mp_reader_path_list_tdoa);
			//mp_card_list_all.insert(make_pair(pCard->card_id,pCard));
		}

		// lihongzhen  2017/8/26 避免部门列表中产生冗余数据
		if(vehicle_id.length() > 0 && pCard->dept_id != atoi(pRow[3]))
		{
			deal_card_dept_changed(pCard, atoi(pRow[3]));
		}
		double cardischanged = true;
		if (vehicle_id.length()> 0 && (pCard->card_type ==CT_COALMINING_MACHINE || pCard->card_type ==CT_TUNNELBORING_MACHINE ))
		{
			if (pCard->dept_id == atoi(pRow[3]) || pCard->id == atoi(pRow[0])||pCard->vehice_type_id == (pRow[5] == NULL) ? 0 : atoi(pRow[5]))
			{
				cardischanged =false;
			}
			else
			{
				remove_vehicle_meanpos(pCard);
			}
		}
		pCard->id = atoi(pRow[0]);
		pCard->dept_id = (pRow[3] == NULL) ? 0 : atoi(pRow[3]);
		pCard->group_id = atoi(pRow[4]);
		pCard->vehice_type_id  = (pRow[5] == NULL) ? 0 : atoi(pRow[5]);
		pCard->level_id  = (pRow[6] == NULL) ? 0 : atoi(pRow[6]);
		pCard->m_nIsRailroad = (pRow[7] == NULL) ? 0 : atoi(pRow[7]);
		pCard->need_display = atoi(pRow[8]);//lemon 2017/08/01
		pCard->power_alarm_display = (pRow[9] == NULL) ? 1 : atoi(pRow[9]);//lemon 2018/01/15
		pCard->vehicle_category_id = pRow[10]==NULL ? "":pRow[10]; //lemon 2018/04/11
		pCard->m_bigCarFlag = (atoi(pRow[11])==1)?true:false;
		pCard->m_overSpeed = atof(pRow[12]);
		if (cardischanged&& (pCard->card_type ==CT_COALMINING_MACHINE || pCard->card_type ==CT_TUNNELBORING_MACHINE ))
		{
			Init_data_vehicle_meanpos(pCard);
		}
		if(m_bUseFilter){
			if(theApp.use_filter_odd){
				std::string temp = pRow[1];
				int a = atoi(temp.substr(temp.length() - 1 , 1).c_str());
				if(0 == a%2){
					pCard->EnableFilter(m_nFilterType);
				}
			}else{
				pCard->EnableFilter(m_nFilterType);
			}
		}
	}
	mysql_free_result(pRes);
	
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_VEHICLE), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

/*
* 初始化所有自组网卡信息
*
* param
*		adhoc_id   ------	自组网卡id
*       is_card    ------	是否是卡
*
* return
*		成功返回0，失败返回1
*
*/
int CYAServerDlg::init_adhoc(string adhoc_id /*= ""*/,bool is_card /*= false*/)
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	if(adhoc_id.length() == 0){
		sprintf_s(buf,"select adhoc_id,v.card_id,v.dept_id, \
					  d.name as dname \
					  from dat_adhoc v \
					  LEFT JOIN dat_card c ON v.card_id = c.card_id \
					  LEFT JOIN dat_dept d ON v.dept_id = d.dept_id \
					  where c.card_type_id = 3 and v.state = 0 ;");
	}else if(is_card){
		sprintf_s(buf,"select adhoc_id,v.card_id,v.dept_id, \
					  d.name as dname \
					  from dat_adhoc v \
					  LEFT JOIN dat_card c ON v.card_id = c.card_id \
					  LEFT JOIN dat_dept d ON v.dept_id = d.dept_id \
					  where c.card_type_id = 3 and v.state = 0 and v.card_id ='%s';",adhoc_id.c_str());
	}else{
		sprintf_s(buf,"select adhoc_id,v.card_id,v.dept_id, \
					  d.name as dname \
					  from dat_adhoc v \
					  LEFT JOIN dat_card c ON v.card_id = c.card_id \
					  LEFT JOIN dat_dept d ON v.dept_id = d.dept_id \
					  where c.card_type_id = 3 and v.state = 0 and v.adhoc_id ='%s';",adhoc_id.c_str());
	}

	pRes = getMysqlRes(buf);
	if (NULL == pRes)
	{
		return 1;
	}
	std::shared_ptr<Card> pCard = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes)){
		CardMap::iterator it = mp_card_list_all.find(pRow[1]);
		if(it != mp_card_list_all.end()){
			pCard = it->second;
			nRow++;
		}else{
			pCard = std::make_shared<Card>(pRow[1], CT_ADHOC, theApp.z_offset);
			pCard->is_registered = false;
			//mp_card_list_all.insert(make_pair(pCard->card_id, pCard));
		}
		pCard->id = atoi(pRow[0]); // (pRow[0] == NULL) ? "" : pRow[0];
		pCard->card_id = (pRow[1] == NULL) ? "" : pRow[1];
		pCard->dept_id = (pRow[2] == NULL) ? 0:atoi(pRow[2]);
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_ADHOC), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

int CYAServerDlg::init_map(int map_id /*= 0*/)
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	if(map_id == 0){
		sprintf_s(strsql, "SELECT map_id, name, scale FROM dat_map;");
	}else{
		sprintf_s(strsql, "SELECT map_id, name, scale FROM dat_map WHERE map_id = %d; ", map_id);
	}
	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}

	std::shared_ptr<MapInfo> pMap = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes)){
		MapInfoMap::iterator it = mp_map_list.find(atoi(pRow[0]));
		if(it != mp_map_list.end()){
			pMap = it->second;
		}else{
			pMap = std::make_shared<MapInfo>();
			pMap->map_id = atoi(pRow[0]);
			mp_map_list.insert(make_pair(pMap->map_id, pMap));
			nRow++;
		}
		pMap->map_name = pRow[1];
		pMap->map_scale = atof(pRow[2]);
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_MAP), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

int CYAServerDlg::init_area(int area_id /* = 0 */)
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	if(0 == area_id){
		sprintf_s(strsql, "SELECT area_id, name, map_id, area_type_id, path, \
						  over_count_person, over_count_vehicle, over_time_person, over_time_vehicle, over_speed_vehicle, is_attendance \
						  ,is_work_area FROM dat_area;");
	}else{
		sprintf_s(strsql, "SELECT area_id, name, map_id, area_type_id, path, \
						  over_count_person, over_count_vehicle, over_time_person, over_time_vehicle, over_speed_vehicle, is_attendance \
						  ,is_work_area FROM dat_area WHERE area_id = %d; ", area_id);
	}
	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}
	std::shared_ptr<Area> pArea = nullptr;

	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes)){
		AreaMap::iterator it = mp_area_list.find(atoi(pRow[0]));		
		if(it != mp_area_list.end()){
			pArea = it->second;
		}else{
			pArea = std::make_shared<Area>();
			pArea->area_id = atoi(pRow[0]);
			mp_area_list.insert(make_pair(pArea->area_id, pArea));
		}
		nRow++;
		pArea->map_id = atoi(pRow[2]);
		MapInfoMap::iterator map_it = mp_map_list.find(pArea->map_id);
		if(map_it != mp_map_list.end()){
			AreaMap::iterator area_it = map_it->second->map_area_list.find(pArea->area_id);
			if(area_it == map_it->second->map_area_list.end()){
				map_it->second->map_area_list.insert(make_pair(pArea->area_id, pArea));
			}
		}
		pArea->area_name = pRow[1];
		pArea->area_type_id = atoi(pRow[3]);
		pArea->path = pRow[4]; // 多边形
		pArea->over_count_person = atoi(pRow[5]);
		pArea->over_count_vehicle = atoi(pRow[6]);
		pArea->over_time_person = atoi(pRow[7]) * 60; // 转为秒
		pArea->over_time_vehicle = atoi(pRow[8]) * 60; // 转为秒
		pArea->over_speed_vehicle = atof(pRow[9]);
		pArea->is_att = atoi(pRow[10]);
		pArea->init_border(pRow[4]);
		pArea->m_is_work_area=atoi(pRow[11])==0?false:true;
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_AREA), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}

int CYAServerDlg::init_special_area_entry(void)
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	sprintf_s(strsql, "SELECT serial_num, start_point_x, start_point_y, start_point_z, end_point_x, end_point_y, \
					  end_point_z, special_area_id,car_type,union_area FROM dat_special_area_entry;");

	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}
	std::shared_ptr<SpecialAreaEntry> pSpecialAreaEntry = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes)){
		SpecilaAreaEntryMap::iterator it = mp_special_area_entry_list.find(atoi(pRow[0]));		
		if(it != mp_special_area_entry_list.end()){
			pSpecialAreaEntry = it->second;
		}else{
			pSpecialAreaEntry = std::make_shared<SpecialAreaEntry>();
			mp_special_area_entry_list.insert(make_pair(atoi(pRow[0]), pSpecialAreaEntry));
			nRow++;
		}

		pSpecialAreaEntry->start_point_x = atof(pRow[1]);
		pSpecialAreaEntry->start_point_y = atof(pRow[2]);
		pSpecialAreaEntry->start_point_z = atof(pRow[3]);
		pSpecialAreaEntry->end_point_x = atof(pRow[4]);
		pSpecialAreaEntry->end_point_y = atof(pRow[5]);
		pSpecialAreaEntry->end_point_z = atof(pRow[6]);
		pSpecialAreaEntry->special_area_id = atoi(pRow[7]);
		pSpecialAreaEntry->car_type = pRow[8]==NULL?"":pRow[8];
		pSpecialAreaEntry->union_area_id = pRow[9]==NULL?0:atoi(pRow[9]);
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_AREA), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}
int CYAServerDlg::init_drivingface_permission_card()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	sprintf_s(strsql, "SELECT worktype_id,worktype_des FROM dat_drivingface_worktype_permission;");
	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes)){
		WorkTypePermissionMap::iterator it = mp_worktype_permission_list.find(atoi(pRow[0]));		
		if(it == mp_worktype_permission_list.end())
		{
			mp_worktype_permission_list.insert(make_pair(atoi(pRow[0]),pRow[1]));
			nRow++;
		}
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_AREA), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}
int CYAServerDlg::init_sensor()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	sprintf_s(strsql, "SELECT sensor_id,card_id FROM dat_sensor a,dat_vehicle_extend b WHERE a.vehicle_id = b.vehicle_id AND a.sensor_type_id =1;");
	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes)){
		DrivingfaceCardMap::iterator it = mp_driving_face_card_list.find(pRow[1]);				
		if(it != mp_driving_face_card_list.end())
		{
			it->second->m_sensor_id.push_back(atoi(pRow[0]));
			nRow++;
		}
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T("init sensor_id"), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}
/*
 * 从数据库初始化掘进面的基准点列表信息
 * 掘进面基准点信息，即允许掘进面可以有多个基准点，默认在drivingface_id相同的情况下，将index最大值的数据做为当前使用的基准点
*/
int CYAServerDlg::init_drivingface_ref_points()
{
	char strsql[LENGTH_SQL] = {0};	
	sprintf_s(strsql, "select drivingface_id,idx,base_x,base_y,base_z,offset from dat_drivingface_ref_point;");
	
	MYSQL_RES *pRes = NULL;
	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}

	MYSQL_ROW pRow;
	int nRow = 0;
	int err = 0;
	while(pRow = mysql_fetch_row(pRes)){
		int drivingface_id = pRow[0] == NULL?0:atoi(pRow[0]);
		for (auto it = mp_driving_face_card_list.begin();it!=mp_driving_face_card_list.end();++it)
		{
			if (it->second->drivingface_id == drivingface_id)
			{
				int index = pRow[1] == NULL?0:atoi(pRow[1]);
				if (index > it->second->m_vt_ref_point_list.size())
				{
					op::point p;
					p.x = pRow[2] == NULL?0:atof(pRow[2]);
					p.y = pRow[3] == NULL?0:atof(pRow[3]);
					//p.z = pRow[4] == NULL?0:atof(pRow[4]);
					it->second->m_vt_ref_point_list.push_back(p);
					nRow++;
				}
				it->second->m_fOffset = (pRow[5]== NULL ? 0:atof(pRow[5]));
			}
		}
	}
	mysql_free_result(pRes);

	CString strlog = _T("");
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_DRIVFACE_REF_POINT), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

int CYAServerDlg::init_drivingface_card()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	sprintf_s(strsql, "SELECT c.card_id, b.base_point_x, b.base_point_y, b.base_point_z, b.drivingface_id, \
					  a.area_id,a.warning_threshold ,a.over_count_num,b.map_id,b.drivingface_type, \
					  a.small_reader_id,a.big_reader_id,a.schedule_work_time,a.schedule_tunnelling_times,b.drifting_footage_unit,c.dept_id,a.vehicle_id,a.relay_small_reader_id, \
					  b.driver_dist,b.driver_dist_time,a.vehicle_id\
					  FROM dat_drivingface_vehicle a,dat_drivingface b,dat_vehicle_extend c \
					  WHERE	a.vehicle_id = c.vehicle_id AND a.drivingface_id = b.drivingface_id;");

	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}
	std::shared_ptr<WorkfaceDriverAlarm> pWorkfaceDriverAlarm = nullptr;
	std::shared_ptr<DrivingfaceCard> pDrivingfaceCard = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes)){
		DrivingfaceCardMap::iterator it = mp_driving_face_card_list.find(pRow[0]);		
		if(it != mp_driving_face_card_list.end()){
			pDrivingfaceCard = it->second;
		}else{
			pDrivingfaceCard = std::make_shared<DrivingfaceCard>();
			mp_driving_face_card_list.insert(make_pair(pRow[0], pDrivingfaceCard));
			nRow++;
		}

		pDrivingfaceCard->drivingface_id = pRow[4]==NULL?0:atoi(pRow[4]);
		pDrivingfaceCard->card_id = pRow[0];
		pDrivingfaceCard->x = atof(pRow[1]);
		pDrivingfaceCard->y = atof(pRow[2]);
		pDrivingfaceCard->z = atof(pRow[3]);
		pDrivingfaceCard->area_id = pRow[5]==NULL?0:atoi(pRow[5]);
		pDrivingfaceCard->warning_threshold = pRow[6]==NULL?0:atoi(pRow[6]);
		pDrivingfaceCard->m_overcount = pRow[7]==NULL?0:atoi(pRow[7]);
		pDrivingfaceCard->m_mapId = pRow[8]==NULL?0:atoi(pRow[8]);;
		pDrivingfaceCard->m_drivingface_type = pRow[9]==NULL?0:atoi(pRow[9]);
		pDrivingfaceCard->m_small_reader_id = atoi((pRow[10] == NULL?"0":pRow[10]));
		pDrivingfaceCard->m_big_reader_id = atoi((pRow[11] == NULL?"0":pRow[11]));
		pDrivingfaceCard->m_schedule_work_times = atof((pRow[12] == NULL?"0":pRow[12]));
		pDrivingfaceCard->m_schedule_tunnelling_times = atof((pRow[13] == NULL?"0":pRow[13]));
		pDrivingfaceCard->m_drifting_footage_unit = atof((pRow[14] == NULL?"0":pRow[14]));
		pDrivingfaceCard->m_dept_id = atoi((pRow[15] == NULL?"0":pRow[15]));
		pDrivingfaceCard->m_relay_small_reader_id = atoi((pRow[17] == NULL?"0":pRow[17]));
		pDrivingfaceCard->m_driver_dist = atof((pRow[18] == NULL?"0":pRow[18]));
		pDrivingfaceCard->m_driver_dist_time = atoi((pRow[19] == NULL?"0":pRow[19]));

		//初始化工作司机与机器的距离告警
		int vehicle_id = atoi((pRow[20] == NULL?"0":pRow[20]));
		pWorkfaceDriverAlarm = std::make_shared<WorkfaceDriverAlarm>();
		m_WorkfaceDriverAlarmMap.insert(make_pair(vehicle_id, pWorkfaceDriverAlarm));

		pWorkfaceDriverAlarm->Vehicle_id = vehicle_id;
		pWorkfaceDriverAlarm->dist = pDrivingfaceCard->m_driver_dist;
		pWorkfaceDriverAlarm->dist_time = pDrivingfaceCard->m_driver_dist_time;

		CardMap::iterator it_card = mp_card_list_all.find(pRow[0]);
		if (it_card != mp_card_list_all.end())
		{
			MapInfoMap::iterator it_map = mp_map_list.find(atoi(pRow[8]));
			if (it_map != mp_map_list.end())
			{
				it_card->second->map_scale = it_map->second->map_scale;
			}
			it_card->second->vehicle_id = (pRow[16]==NULL?"":pRow[16]);
			it_card->second->m_fScheduleStartupTime = pDrivingfaceCard->m_schedule_work_times;
		}

		DrivinfaceReaderTopology drt;
		drt.m_big_reader_id = pDrivingfaceCard->m_big_reader_id;
		//存放规则：1.首先放用于定位掘进机的小分站id
		if (pDrivingfaceCard->m_small_reader_id>0)
		{
			drt.m_small_reader_id[0] = pDrivingfaceCard->m_small_reader_id;
			drt.m_counts++;
		}
		//存放规则：2.然后放用于节约定位掘进机的小分站和大分站之间的中继分站id
		if (pDrivingfaceCard->m_relay_small_reader_id>0)
		{
			drt.m_small_reader_id[1] = pDrivingfaceCard->m_relay_small_reader_id;
			drt.m_counts++;
		}
		if (drt.m_big_reader_id > 0)
		{
			vt_drivingface_reader_topology.push_back(drt);
		}
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_DRIVFACE_MACHINE), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}

int CYAServerDlg::init_coalface_driver_warningparam()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	sprintf_s(strsql, "SELECT b.vehicle_id, a.driver_dist,a.driver_dist_time FROM dat_coalface a,dat_coalface_vehicle b \
		WHERE	a.coalface_id = b.coalface_id;");
	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}

	std::shared_ptr<WorkfaceDriverAlarm> pWorkfaceDriverAlarm = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))
	{
		int Vehicle_id = atoi(pRow[0]);
		WorkfaceDriverAlarmMap::iterator it = m_WorkfaceDriverAlarmMap.find(Vehicle_id);		
		pWorkfaceDriverAlarm = std::make_shared<WorkfaceDriverAlarm>();
		m_WorkfaceDriverAlarmMap.insert(make_pair(Vehicle_id, pWorkfaceDriverAlarm));

		pWorkfaceDriverAlarm->Vehicle_id = atoi(pRow[0]);
		pWorkfaceDriverAlarm->dist = atof(pRow[1]);
		pWorkfaceDriverAlarm->dist_time = atoi(pRow[2]);
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_VEHICLE_DRIVER), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}

void CYAServerDlg::load_drivingface_card_curshift_position()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	int nRow = 0;
	char strsql[LENGTH_SQL] = {0};
	int shift_id = 0;
	time_t start_time_t = GetCurShiftStartTime(shift_id);
	std::string cur_shift_time = CFunctions::time_t2string(start_time_t);

	std::shared_ptr<DrivingfaceCard> pDrivingfaceCard = nullptr;
	DrivingfaceCardMap::iterator it_card = mp_driving_face_card_list.begin();
	for(;it_card != mp_driving_face_card_list.end();it_card++)
	{
		//current shift history is exist
		sprintf_s(strsql, " SELECT drivingface_id,start_x,start_y,start_z,end_x,end_y,end_z,total_length,finish_length FROM his_drivingface_shift_finish_length\
						  where card_id = '%s'  and cur_time = '%s';", 
						  (it_card->first).c_str(),
						  cur_shift_time.c_str());
		debug_print_syslog(0, "init driving face by current shift data: %s", strsql);
		pRes = getMysqlRes(strsql);
		if (NULL == pRes)
		{
			return ;
		}	

		while(pRow = mysql_fetch_row(pRes))
		{
			CardMap::iterator it = mp_card_list_all.find(it_card->first);
			if(it != mp_card_list_all.end())
			{
				it->second->is_drivingface_Initialization = true;
				it->second->shift_id = shift_id;
				it->second->driving_face_id = atoi(pRow[0]);
				it->second->driving_face_cur_shift_start_x = atof(pRow[1]);
				it->second->driving_face_cur_shift_start_y = atof(pRow[2]);
				it->second->driving_face_cur_shift_start_z = atof(pRow[3]);
				it->second->driving_face_cur_shift_x = atof(pRow[4]);
				it->second->driving_face_cur_shift_y = atof(pRow[5]);
				it->second->driving_face_cur_shift_z = atof(pRow[6]);
				it->second->x = atof(pRow[4]);
				it->second->y =	atof(pRow[5]);
				it->second->z = atof(pRow[6]);
				it->second->drving_face_cur_shift_max_speed = 0;
				it->second->m_cur_total_finish_length = atof(pRow[7]) + atof(pRow[8]);
				it->second->m_curshift_finish_length = atof(pRow[8]);
			}
			nRow++;
		}

		if(0 == nRow)
		{
			sprintf_s(strsql, " SELECT drivingface_id,start_x,start_y,start_z,end_x,end_y,end_z,total_length,finish_length FROM his_drivingface_shift_finish_length\
							  where card_id = '%s'  and cur_time < '%s' order by cur_time desc limit 1;", 
							  (it_card->first).c_str(),
							  cur_shift_time.c_str());
			debug_print_syslog(0, "init cur shift driving face by last log: %s", strsql);
			pRes = getMysqlRes(strsql);
			if (NULL == pRes)
			{
				return ;
			}
			int nRow = 0;
			while(pRow = mysql_fetch_row(pRes))
			{
				CardMap::iterator it = mp_card_list_all.find(it_card->first);
				if(it != mp_card_list_all.end())
				{
					it->second->is_drivingface_Initialization = true;
					it->second->driving_face_id = atoi(pRow[0]);
					it->second->driving_face_cur_shift_start_x = atof(pRow[4]);
					it->second->driving_face_cur_shift_start_y = atof(pRow[5]);
					it->second->driving_face_cur_shift_start_z = atof(pRow[6]);
					it->second->driving_face_cur_shift_x = atof(pRow[4]);
					it->second->driving_face_cur_shift_y = atof(pRow[5]);
					it->second->driving_face_cur_shift_z = atof(pRow[6]);
					it->second->x = atof(pRow[4]);
					it->second->y = atof(pRow[5]);
					it->second->z = atof(pRow[6]);
					it->second->drving_face_cur_shift_max_speed = 0;
					it->second->m_cur_total_finish_length = atof(pRow[7]) + atof(pRow[8]);
					it->second->m_curshift_finish_length = atof(pRow[8]);
				}
				debug_print_syslog(0, "init driving face start point error.");
				nRow++;
			}
		}
	}
	return;
}

//初始化地标信息
int CYAServerDlg::init_landmark(void)
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	sprintf_s(strsql, "select landmark_id, name, map_id, area_id, x, y, z from dat_landmark;");

	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}
	std::shared_ptr<LandmarkInfo> pLandmarkInfo = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes)){
		LandmarkInfoMap::iterator it = mp_landmark_list.find(atoi(pRow[0]));		
		if(it != mp_landmark_list.end()){
			pLandmarkInfo = it->second;
		}else{
			pLandmarkInfo = std::make_shared<LandmarkInfo>();
			mp_landmark_list.insert(make_pair(atoi(pRow[0]), pLandmarkInfo));
			nRow++;
		}

		pLandmarkInfo->landmark_id = atoi(pRow[0]);
		pLandmarkInfo->landmark_name = pRow[1];
		pLandmarkInfo->map_id = atoi(pRow[2]);
		pLandmarkInfo->area_id = atoi(pRow[3]);
		pLandmarkInfo->x = atof(pRow[4]);
		pLandmarkInfo->y = atof(pRow[5]);
		pLandmarkInfo->z = atof(pRow[6]);
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_AREA), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	debug_print_syslog(0, "Init landmark info num: %d", nRow);
	return 0;
}

//初始化地图方向数据
int CYAServerDlg::init_map_direction(void)
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	sprintf_s(strsql, "select map_direction_id, map_id, north_angle from dat_map_direction;");

	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}
	std::shared_ptr<MapDirectionInfo> pMapDirectionInfo = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes)){
		MapDirectionInfoMap::iterator it = mp_map_direction_list.find(atoi(pRow[1]));		
		if(it != mp_map_direction_list.end()){
			pMapDirectionInfo = it->second;
		}else{
			pMapDirectionInfo = std::make_shared<MapDirectionInfo>();
			mp_map_direction_list.insert(make_pair(atoi(pRow[1]), pMapDirectionInfo));
			nRow++;
		}

		pMapDirectionInfo->map_direction_id = atoi(pRow[0]);
		pMapDirectionInfo->map_id = atoi(pRow[1]);
		pMapDirectionInfo->north_angle = atoi(pRow[2]);
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_AREA), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}

int CYAServerDlg::init_reader(int reader_id /* = 0 */)
{
	// 从数据库中读取
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	if(reader_id == 0){

		sprintf_s(strsql, "SELECT reader_id, map_id, area_id, name, x, y, z, angle, state, ip, device_type_id, reader_type_id, isSpecial,dimension,enable_simulate_card,need_power_alarm FROM dat_reader WHERE state=0;");
	}else{
		sprintf_s(strsql, "SELECT reader_id, map_id, area_id, name, x, y, z, angle, \
						  state, ip, device_type_id, reader_type_id,isSpecial,dimension, enable_simulate_card,need_power_alarm \
						  FROM dat_reader WHERE state=0 AND reader_id = %d; ", reader_id);
	}
	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}
	std::shared_ptr<Reader> pReader = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))	{
		ReaderMap::iterator it = mp_reader_list.find(atoi(pRow[0]));		
		if(it != mp_reader_list.end()){
			pReader = it->second;
		}else{
			pReader = std::make_shared<Reader>();
			pReader->reader_interval_time = m_reader_interval_time;
			pReader->reader_id = atoi(pRow[0]);
			mp_reader_list.insert(make_pair(pReader->reader_id, pReader));
			nRow++;
		}

		pReader->map_id = atoi(pRow[1]);
		MapInfoMap::iterator map_it = mp_map_list.find(pReader->map_id);
		if(map_it != mp_map_list.end()){
			ReaderMap::iterator reader_it = map_it->second->map_reader_list.find(pReader->reader_id);
			if(reader_it == map_it->second->map_reader_list.end()){
				map_it->second->map_reader_list.insert(make_pair(pReader->reader_id, pReader));
			}
			pReader->map_scale = map_it->second->map_scale;
		}
		pReader->area_id = atoi(pRow[2]);
		pReader->reader_name = pRow[3];
		pReader->reader_x = atof(pRow[4]);
		pReader->reader_y = atof(pRow[5]);
		pReader->reader_z = atof(pRow[6]);
		pReader->reader_angle = atof(pRow[7]) * M_PI /180;
		pReader->ip = pRow[9];
		pReader->device_type_id = atoi(pRow[10]);
		pReader->pos_state = atoi(pRow[11]);
		pReader->m_nIsSpecial = atoi(pRow[12]);
		pReader->dimension = atoi(pRow[13]);
		pReader->is_simulation_card = atoi((pRow[14]==NULL?"0":pRow[14]));
		pReader->m_bNeedPowerAlarm = (atoi((pRow[15]==NULL?"0":pRow[15]))==0)?false:true;
		//pReader->is_parent = atoi(pRow[14]) == 1?true:false;
		//pReader->parent_anchor_id = atoi(pRow[15]);

		if (pReader->is_simulation_card)
		{
			std::string simulate_card = CFunctions::getstrwithzero(CT_SIMULATE_CARD,3)+CFunctions::getstrwithzero(pReader->reader_id+SIMULATOR_CARD_START_NO,10);
			auto it = mp_card_list_all.find(simulate_card);
			if (it == mp_card_list_all.end())
			{
				std::shared_ptr<Card> pCard = std::make_shared<Card>(simulate_card,CT_SIMULATE_CARD,theApp.z_offset);
				mp_card_list_all.insert(std::make_pair(simulate_card,pCard));
			}
		}

		// 初始化天线
		// 分站天线赋值
		for(auto i = 0; i < ANTENNA_COUNT;i++)
		{
			std::shared_ptr<Antenna> ant = std::make_shared<Antenna>();
			ant->antenna_id = 0;
			ant->antenna_x = pReader->reader_x;
			ant->antenna_y = pReader->reader_y;
			ant->antenna_z = pReader->reader_z;
			ant->antenna_angle = pReader->reader_angle;
			pReader->ant[i] = ant;
			pReader->ant[i]->antenna_id = i+1;
		}
		//pReader->ant[0] = pReader->ant[1] = ant;
		//pReader->ant[1]->antenna_id = 1;
	}
	mysql_free_result(pRes);

	init_antenna(reader_id);				//lemon smooth 1  ant
	init_all_readers_coverage(reader_id);	//lemon smooth 2  reader
	m_carmanage->init_cardpath();			//lemon smooth 3  card_path
	init_reader_boundary_area(reader_id);

	CString strlog;
	strlog.Format(_T("%s%d%s_____"), _T(LOG_INIT_READER), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

int CYAServerDlg::init_ctrl_reader( int reader_id /*= 0*/ )
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	if(reader_id == 0){
		sprintf_s(strsql, "SELECT ctrl_reader_id, map_id, area_id, name, x, y, z, angle, \
						  state, ip, device_type_id, reader_type_id,isSpecial \
						  FROM dat_ctrl_reader WHERE state=0;");
	}else{
		sprintf_s(strsql, "SELECT ctrl_reader_id, map_id, area_id, name, x, y, z, angle, \
						  state, ip, device_type_id, reader_type_id,isSpecial \
						  FROM dat_ctrl_reader WHERE state=0 AND ctrl_reader_id = %d; ", reader_id);
	}
	pRes = getMysqlRes(strsql);

	if (NULL == pRes)
	{
		return 1;
	}

	std::shared_ptr<Reader> pReader = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))	{
		ReaderMap::iterator it = mp_ctrl_reader_list.find(atoi(pRow[0]));		
		if(it != mp_ctrl_reader_list.end()){
			pReader = it->second;
		}else{
			pReader = std::make_shared<Reader>();
			pReader->reader_interval_time = m_reader_interval_time;
			pReader->reader_id = atoi(pRow[0]);
			mp_ctrl_reader_list.insert(make_pair(pReader->reader_id, pReader));
			nRow++;
		}

		pReader->map_id = atoi(pRow[1]);
		MapInfoMap::iterator map_it = mp_map_list.find(pReader->map_id);
		if(map_it != mp_map_list.end()){
			ReaderMap::iterator reader_it = map_it->second->map_ctrl_reader_list.find(pReader->reader_id);
			if(reader_it == map_it->second->map_ctrl_reader_list.end()){
				map_it->second->map_ctrl_reader_list.insert(make_pair(pReader->reader_id, pReader));
			}
			pReader->map_scale = map_it->second->map_scale;
		}
		pReader->area_id = atoi(pRow[2]);
		pReader->reader_name = pRow[3];
		pReader->reader_x = atof(pRow[4]);
		pReader->reader_y = atof(pRow[5]);
		pReader->reader_z = atof(pRow[6]);
		pReader->reader_angle = atof(pRow[7]) * M_PI /180;
		pReader->ip = pRow[9];
		pReader->device_type_id = atoi(pRow[10]);
		pReader->pos_state = atoi(pRow[11]);
		pReader->m_nIsSpecial = atoi(pRow[12]);
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_CTRL_READER), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}

/*
* 初始化天线信息
*
* param
*		reader_id		分站id
*
* return
*		执行成功返回0，失败返回1
*
*/
int CYAServerDlg::init_antenna(int reader_id /* = 0 */)
{
	char strsql[LENGTH_SQL] = {0};	
	if(reader_id == 0){
		sprintf_s(strsql, "SELECT antenna_id, a.reader_id, idx, a.x, a.y, a.z, a.angle \
						  FROM dat_antenna a, dat_reader r \
						  WHERE a.reader_id = r.reader_id;");
	}else{
		sprintf_s(strsql, "SELECT antenna_id, a.reader_id, idx, a.x, a.y, a.z, a.angle \
						  FROM dat_antenna a, dat_reader r \
						  WHERE a.reader_id = r.reader_id AND reader_id = %d; ", reader_id);
	}


	MYSQL_RES *pRes = NULL;
	pRes = getMysqlRes(strsql);

	if(pRes == NULL)
	{
		return 1;
	}
	MYSQL_ROW pRow;

	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes)){
		ReaderMap::iterator it = mp_reader_list.find(atoi(pRow[1]));
		if(it != mp_reader_list.end()){
			std::shared_ptr<Reader> pReader = nullptr;
			pReader = it->second;

			std::shared_ptr<Antenna> ant = std::make_shared<Antenna>();
			ant->antenna_id = atoi(pRow[2]);
			ant->antenna_x = atof(pRow[3]);
			ant->antenna_y = atof(pRow[4]);
			ant->antenna_z = atof(pRow[5]);
			ant->antenna_angle = atof(pRow[6]) * M_PI / 180.0;

			int idx = atoi(pRow[2]) - 1;		

			pReader->ant[idx] = ant;

			//-----init ant-----
			m_carmanage->init_sit_list(pReader->reader_id,idx,ant->antenna_x,ant->antenna_y,pReader->map_scale);
			//-----init end-----
			nRow++;
		}
	}
	mysql_free_result(pRes);

	//-----init ant-----
	m_carmanage->init_sit_list();
	//-----init end-----

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_ANTENNA), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

int CYAServerDlg::init_dev_adhoc( int reader_id /*= 0*/ )
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	if(reader_id == 0){//dat_dev_adhoc
		sprintf_s(strsql, "select ad.id, ad.reader_id, ad.level, ad.x, ad.y, ad.z from dat_dev_adhoc ad, dat_reader r \
						  where ad.reader_id = r.reader_id;");
	}else{
		sprintf_s(strsql, "select ad.id, ad.reader_id, ad.level, ad.x, ad.y, ad.z from dat_dev_adhoc ad, dat_reader r \
						  where ad.reader_id = r.reader_id and ad.reader_id = %d; ", reader_id);
	}
	pRes = getMysqlRes(strsql);

	if (NULL == pRes)
	{
		return 1;
	}
	int nRow = 0;
	int idx = 0;

	while(pRow = mysql_fetch_row(pRes)){
		ReaderMap::iterator it = mp_reader_list.find(atoi(pRow[1]));
		if(it != mp_reader_list.end()){
			std::shared_ptr<Adhoc> adhoc = std::make_shared<Adhoc>();
			adhoc->adhoc_id = atoi(pRow[0]);
			adhoc->idx = atoi(pRow[2]);
			adhoc->x = atof(pRow[3]);
			adhoc->y = atof(pRow[4]);
			adhoc->z = atof(pRow[5]);
			idx = (adhoc->idx < ADHOC_COUNT)?adhoc->idx:0;
			it->second->adhoc[idx] = adhoc;
			nRow++;
		}
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_ADHOC_LOCATE), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

/*
* 函数名：init_all_readers_coverage
* 从数据库的dat_reader_path表中读取指定map_id和reader_id的地图范围集，
* 将此分站的地图范围集保存在分站类中的readerCoverage中；
* 如果指定了相同的地图范围集的reader_id,则直接将指定的reader_id的地图范围集赋值给此reader_id的地图范围集
* 然后将地图集赋值给station
* 
*
* @param
*		reader_id		分站id号
*
* @return
*		-1，表示在分站map中未找到此分站信息或者未正常执行；0，表示正常执行
*
*/
int CYAServerDlg::init_all_readers_coverage(int reader_id)
{
	init_tof_all_readers_coverage(reader_id);
	init_tdoa_all_readers_coverage(reader_id);
	return 0;
}

/*

* 初始化TOF分站的覆盖范围的信息
*
* param
*		reader_id		分站id
*
* return
*		初始化成功返回0，否则返回非零值
*
*/
int CYAServerDlg::init_tof_all_readers_coverage(int reader_id /*= 0*/)
{
	char sql[LENGTH_SQL] = {0};
	if(reader_id == 0){
		sprintf_s(sql, "select p.same_config_reader, p.reader_id,p.break_point_idx,p.x,p.y,p.z,p.is_bezier,p.link_reader from dat_reader_path_tof p ,dat_reader r where p.reader_id = r.reader_id;");
	}else{
		sprintf_s(sql, "select p.same_config_reader,p.reader_id,p.break_point_idx,p.x,p.y,p.z,p.is_bezier,p.link_reader from dat_reader_path_tof p ,dat_reader r where p.reader_id = %d; ", reader_id);
	}

	MYSQL_RES* pRes = NULL;	

	pRes = getMysqlRes(sql);

	if (pRes == NULL)
	{
		return 1;
	}

	MYSQL_ROW pRow;
	int err = 0;
	int nRow = 0;

	//从数据库获得信息赋给分站对象的地图集
	while(pRow = mysql_fetch_row(pRes)){
		int nReaderId = atoi(pRow[1]);
		ReaderMap::iterator it = mp_reader_list.find(nReaderId);
		if (it == mp_reader_list.end())
		{
			continue;
		}

		int nSameConfigReader = atoi(pRow[0]);
		int nIdx = atoi(pRow[2]);
		//判断地图集信息是否可利用其它分站的覆盖范围，如果可用，则使用其它分站的覆盖范围
		//-1表示不可用，否则表示可复用分站id号为nSameConfigReader的地图集覆盖范围
		if(nSameConfigReader == -1){
			_point p;
			p.x = atof(pRow[3]);
			p.y = atof(pRow[4]);
			p.z = atof(pRow[5]);
			it->second->readerCoveragePath.insert(make_pair(nIdx,p));
			it->second->bIsInitCoverage = true;
			nRow++;
			//-----lemon smooth----
			std::string link_readerlist = (pRow[7] == NULL)?"":pRow[7];
			if ("0" == link_readerlist)
			{
				link_readerlist = "";
			}
			std::vector<string> vs;
			if(!link_readerlist.empty())
			{
				int count = cacti::StringUtil::split(vs,link_readerlist,",;");
				assert(count%2 == 0);
			}
			m_carmanage->init_ant_path(nReaderId,nIdx-1,p.x,p.y,vs.begin(),vs.end());
			//---lemon end------	

		}else{
			it->second->readerCoveragePath = mp_reader_list.find(nSameConfigReader)->second->readerCoveragePath;
			it->second->bIsInitCoverage = true;
			nRow++;
		}
	}
	mysql_free_result(pRes);

	//---lemon smooth---
	m_carmanage->init_ant_path();
	//---lemon end------

	//输出操作数据库的日志信息
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_TOF_READER_PATH), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	//根据获得地图集将其赋给mp_reader_path_list
	for(ReaderMap::iterator it = mp_reader_list.begin();it!=mp_reader_list.end();it++){
		if(it->second->bIsInitCoverage){
			int nReaderId = it->second->reader_id;
			double dMapScale = mp_map_list.find(it->second->map_id)->second->map_scale;
			std::shared_ptr<ReaderPath> pReaderPath = nullptr;
			ReaderPathMap::iterator prpIt = mp_reader_path_list_tof->find(nReaderId);
			if(prpIt != mp_reader_path_list_tof->end()){
				pReaderPath = prpIt->second;
			}else{
				pReaderPath = std::make_shared<ReaderPath>();
				mp_reader_path_list_tof->insert(make_pair(nReaderId,pReaderPath));
			}
			pReaderPath->nRealCalcPoints = it->second->readerCoveragePath.size();
			for(int i = 0;i < 2;i++){
				pReaderPath->x[i] = it->second->ant[i]->antenna_x*dMapScale;
				pReaderPath->y[i] = it->second->ant[i]->antenna_y*dMapScale;
				pReaderPath->z[i] = it->second->ant[i]->antenna_z*dMapScale;
			}

			for(size_t j = 1;j <= it->second->readerCoveragePath.size(); j++){
				pReaderPath->px[j - 1] = it->second->readerCoveragePath.find(j)->second.x*dMapScale;
				pReaderPath->py[j - 1] = it->second->readerCoveragePath.find(j)->second.y*dMapScale;
				pReaderPath->pz[j - 1] = it->second->readerCoveragePath.find(j)->second.z*dMapScale;
			}
		}
	}

	return 0;
}

/*
* 函数名：init_tdoa_all_readers_coverage
* 实现初始化TDOA方式的地图集描述，并存储冗余数据
* 冗余数据的主要作用在于：例如存在分站<B1,B2>之间的地图集描述，那么也存在<B2,B1>的对应关系
*
* param 
*		reader_id	------	分站id号
*
* return
*		执行失败，返回1
*		正确执行，返回0
*
*/
int CYAServerDlg::init_tdoa_all_readers_coverage(int reader_id)
{
	char sql[LENGTH_SQL] = {0};
	if(reader_id == 0){
		sprintf_s(sql, "select p.start_reader_id,p.end_reader_id,p.idx,p.x,p.y,p.z,p.is_bezier,rpc.ncount \
					   from dat_reader_path_tdoa p ,dat_reader r, \
					   (select count(*) as ncount, start_reader_id, end_reader_id from dat_reader_path_tdoa group by start_reader_id, end_reader_id) rpc\
					   where p.start_reader_id = r.reader_id \
					   and p.start_reader_id = rpc.start_reader_id and p.end_reader_id = rpc.end_reader_id \
					   order by p.start_reader_id, p.end_reader_id, p.idx;"); 
	}else{
		sprintf_s(sql, "select p.start_reader_id,p.end_reader_id,p.idx,p.x,p.y,p.z,p.is_bezier,rpc.ncount \
					   from dat_reader_path_tdoa p ,dat_reader r, \
					   (select count(*) as ncount, start_reader_id, end_reader_id from dat_reader_path_tdoa group by start_reader_id, end_reader_id) rpc\
					   where p.start_reader_id = r.reader_id \
					   and p.start_reader_id = rpc.start_reader_id and p.end_reader_id = rpc.end_reader_id \
					   and (p.start_reader_id =%d or p.end_reader_id = %d) \
					   order by p.start_reader_id, p.end_reader_id, p.idx;", reader_id, reader_id);
	}

	MYSQL_RES* pRes = NULL;
	MYSQL_ROW pRow;
	int err = 0;
	int nRow = 0;

	//查询数据库
	pRes = getMysqlRes(sql);

	if (NULL == pRes)
	{
		return 0;
	}

	double mapScale = 0.0;
	while(pRow = mysql_fetch_row(pRes)){
		int start_reader_id = atoi(pRow[0]);
		int end_reader_id   = atoi(pRow[1]);
		int ndx = atoi(pRow[2]);
		int nTotal = atoi(pRow[7]);

		ReaderMap::iterator it_reader = mp_reader_list.find(start_reader_id);
		if (it_reader == mp_reader_list.end())
		{
			continue;
		}
		it_reader = mp_reader_list.find(end_reader_id);
		if (it_reader == mp_reader_list.end())
		{
			continue;
		}

		//后缀_r都为冗余信息
		std::shared_ptr<ReaderPath> prp = nullptr;
		std::shared_ptr<ReaderPath> prp_r = nullptr;

		TDOAReaderPathMap::iterator it = mp_reader_path_list_tdoa->find(start_reader_id);	

		if(it == mp_reader_path_list_tdoa->end()){
			std::shared_ptr<ReaderPathMap> prpm = std::make_shared<ReaderPathMap>();
			std::shared_ptr<ReaderPath> prp1 = std::make_shared<ReaderPath>();
			prpm->insert(make_pair(end_reader_id,prp1));
			mp_reader_path_list_tdoa->insert(make_pair(start_reader_id,prpm));	

			//冗余数据
			std::shared_ptr<ReaderPathMap> prpm_r = std::make_shared<ReaderPathMap>();
			std::shared_ptr<ReaderPath> prp1_r = std::make_shared<ReaderPath>();
			prpm_r->insert(make_pair(start_reader_id,prp1_r));
			mp_reader_path_list_tdoa->insert(make_pair(end_reader_id,prpm_r));		
		}else{
			ReaderPathMap::iterator it2 = it->second->find(end_reader_id);
			if(it2 == it->second->end()){
				std::shared_ptr<ReaderPath> prp1 = std::make_shared<ReaderPath>();
				it->second->insert(make_pair(end_reader_id,prp1));		
			}
		}

		TDOAReaderPathMap::iterator it_r = mp_reader_path_list_tdoa->find(end_reader_id);
		if(it_r == mp_reader_path_list_tdoa->end()){
			std::shared_ptr<ReaderPathMap> prpm = std::make_shared<ReaderPathMap>();
			std::shared_ptr<ReaderPath> prp1 = std::make_shared<ReaderPath>();
			prpm->insert(make_pair(start_reader_id,prp1));
			mp_reader_path_list_tdoa->insert(make_pair(end_reader_id,prpm));	
		}else{
			ReaderPathMap::iterator it2 = it_r->second->find(start_reader_id);
			if(it2 == it_r->second->end()){
				std::shared_ptr<ReaderPath> prp1 = std::make_shared<ReaderPath>();
				it_r->second->insert(make_pair(start_reader_id,prp1));		
			}
		}

		ReaderPathMap::iterator it_rpm = mp_reader_path_list_tdoa->find(start_reader_id)->second->find(end_reader_id);
		if(it_rpm!=mp_reader_path_list_tdoa->find(start_reader_id)->second->end()){
			prp = it_rpm->second;
		}else{
			prp = std::make_shared<ReaderPath>();
			mp_reader_path_list_tdoa->find(start_reader_id)->second->insert(make_pair(end_reader_id,prp));
		}

		//冗余信息
		ReaderPathMap::iterator it_rpm_r = mp_reader_path_list_tdoa->find(end_reader_id)->second->find(start_reader_id);
		if(it_rpm_r!=mp_reader_path_list_tdoa->find(end_reader_id)->second->end()){
			prp_r = it_rpm_r->second;
		}else{
			prp_r = std::make_shared<ReaderPath>();
			mp_reader_path_list_tdoa->find(end_reader_id)->second->insert(make_pair(start_reader_id,prp));
		}

		//获得地图比例
		int map_id = mp_reader_list.find(start_reader_id)->second->map_id;
		MapInfoMap::iterator mit = mp_map_list.find(map_id);
		if(mit == mp_map_list.end()){
			//没有相关地图信息，要输出错误日志
			AfxMessageBox(_T("分站所在地图不存在！"));
			break;
		}
		mapScale = mp_map_list.find(map_id)->second->map_scale;

		if(prp->nRealCalcPoints < ndx){
			prp->nRealCalcPoints = ndx;
		}
		if(prp_r->nRealCalcPoints < ndx){
			prp_r->nRealCalcPoints = ndx;
		}

		if(!prp->bIsInit){
			//获得分站坐标，其中索引0表示起始分站坐标，索引1表示结束分站坐标
			prp->x[0] = mp_reader_list.find(start_reader_id)->second->reader_x*mapScale;
			prp->y[0] = mp_reader_list.find(start_reader_id)->second->reader_y*mapScale;
			prp->z[0] = 0;
			prp->x[1] = mp_reader_list.find(end_reader_id)->second->reader_x*mapScale;
			prp->y[1] = mp_reader_list.find(end_reader_id)->second->reader_y*mapScale;
			prp->z[1] = 0;	
			prp->bIsInit = true;
		}

		if(prp->px[ndx-1] == 0){
			prp->px[ndx-1] = atof(pRow[3])*mapScale;
			prp->py[ndx-1] = atof(pRow[4])*mapScale;
		}

		if(!prp_r->bIsInit){
			//冗余信息
			prp_r->x[0] = mp_reader_list.find(end_reader_id)->second->reader_x*mapScale;
			prp_r->y[0] = mp_reader_list.find(end_reader_id)->second->reader_y*mapScale;
			prp_r->z[0] = 0;
			prp_r->x[1] = mp_reader_list.find(start_reader_id)->second->reader_x*mapScale;
			prp_r->y[1] = mp_reader_list.find(start_reader_id)->second->reader_y*mapScale;
			prp_r->z[1] = 0;
			prp_r->bIsInit = true;
		}

		if(prp_r->px[nTotal - ndx] == 0){
			prp_r->px[nTotal - ndx] = atof(pRow[3])*mapScale;
			prp_r->py[nTotal - ndx] = atof(pRow[4])*mapScale;
		}
		nRow++;
	}
	mysql_free_result(pRes);

	//输出操作结果信息
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_TDOA_READER_PATH), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

/*
* 初始化硐室表
*
* param
*		无
*
* return
*		成功返回0，失败返回1
*
*/
int CYAServerDlg::init_chamber(int chamber_id)
{
	char sql[LENGTH_SQL] = {0};
	if (chamber_id == 0)
	{
		sprintf_s(sql, "select chamber_id,path,name,is_used,section_id,map_id from dat_chamber;"); 
	} 
	else
	{
		sprintf_s(sql, "select chamber_id,path,name,is_used,section_id,map_id from dat_chamber where chamber_id = %d;",chamber_id); 
	}


	MYSQL_RES* pRes = NULL;
	MYSQL_ROW pRow;
	int err = 0;
	int nRow = 0;

	//查询数据库
	pRes = getMysqlRes(sql);

	if (NULL == pRes)
	{
		return 1;
	}

	while (pRow = mysql_fetch_row(pRes))
	{
		std::shared_ptr<Chamber> pChamber = nullptr;

		int chamber_id = atoi(pRow[0]);
		ChamberMap::iterator it_chamber = mp_chamber_list.find(chamber_id);
		if (it_chamber != mp_chamber_list.end())
		{
			pChamber = it_chamber->second;
		}else{
			pChamber = std::make_shared<Chamber>();
			mp_chamber_list.insert(make_pair(chamber_id,pChamber));
		}

		pChamber->m_nID = chamber_id;
		pChamber->m_strPath = pRow[1];
		pChamber->m_strName = pRow[2];
		pChamber->m_nIsUsed = atoi(pRow[3]);
		pChamber->m_nSectionID = atoi(pRow[4]);
		pChamber->m_nMapID = atoi(pRow[5]);

		if (pChamber->m_strPath!="")
		{
			pChamber->init_border(pChamber->m_strPath);
		}

		MapInfoMap::iterator it_map = mp_map_list.find(pChamber->m_nMapID);
		if (it_map != mp_map_list.end())
		{
			ChamberMap::iterator it_chamber = it_map->second->map_chamber_list.find(pChamber->m_nID);
			if (it_chamber == it_map->second->map_chamber_list.end())
			{
				it_map->second->map_chamber_list.insert(make_pair(pChamber->m_nID,pChamber));
			}
		}

		nRow++;
	}
	mysql_free_result(pRes);

	//输出操作结果信息
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_CHAMBER), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

/*
* 初始化红绿灯表
*
* param
*		无
*
* return 
*		成功返回0，失败返回1
*
*/
int CYAServerDlg::init_traffic_lights(int light_id)
{
	char sql[LENGTH_SQL] = {0};
	if (light_id == 0)
	{
		sprintf_s(sql, "SELECT light_id,lights_group_id,ip,X,Y,reader_id,special_flag,port,physics_light_id,physics_light_direction FROM dat_light WHERE state = 0;"); 
	} 
	else
	{
		sprintf_s(sql, "SELECT light_id,lights_group_id,ip,X,Y,reader_id,special_flag,port,physics_light_id,physics_light_direction FROM dat_light WHERE state = 0 and light_id = %d;",light_id); 
	}

	MYSQL_RES* pRes = NULL;
	MYSQL_ROW pRow;
	int err = 0;
	int nRow = 0;

	//查询数据库
	pRes = getMysqlRes(sql);

	if (NULL == pRes)
	{
		return 0;
	}

	while (pRow = mysql_fetch_row(pRes))
	{
		nRow++;
		int gid = atoi(pRow[1]);
		auto pTraGroup = (*m_carmanage)[gid];
		if (pTraGroup == nullptr)
			continue;
		int lightId = atoi(pRow[0]);
		std::string ip = pRow[2];
		double x = atof(pRow[3]);
		double y = -atof(pRow[4]);
		int readerid = atoi(pRow[5]);
		int specialflag = atoi(pRow[6]);
		int port = atoi(pRow[7]);
		int phy_light_id = pRow[8]==NULL?0:atoi(pRow[8]);
		int phy_light_dir = pRow[9]==NULL?0:atoi(pRow[9]);
		std::shared_ptr<op::TrafficLight> tlp = pTraGroup->get(lightId);
		if (tlp == nullptr)
		{
			std::shared_ptr<op::TrafficLight> tlp = std::make_shared<op::TrafficLight>(lightId,x,y,0.0,readerid,ip,specialflag,port,phy_light_id,phy_light_dir);
			pTraGroup->put(tlp);
		}
		else
		{
			tlp->set(x,y,ip,specialflag,readerid,port,phy_light_id,phy_light_dir);
		}
	}
	mysql_free_result(pRes);

	//输出操作结果信息
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_LIGHTS), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	m_carmanage->showInfo();
	//start work...
	m_carmanage->initRule();
	return 0;
}

/*
* 初始化路段表
*
* param
*		无
*
* return
*		成功返回0，失败返回1
*
*/
int CYAServerDlg::init_section(int section_id)
{
	char sql[LENGTH_SQL] = {0};
	if (section_id == 0)
	{
		sprintf_s(sql, "select id,path,name,label,map_id,property from dat_section;"); 
	} 
	else
	{
		sprintf_s(sql, "select id,path,name,label,map_id,property from dat_section where id = %d;",section_id); 
	}

	MYSQL_RES* pRes = NULL;
	MYSQL_ROW pRow;
	int err = 0;
	int nRow = 0;

	//查询数据库
	pRes = getMysqlRes(sql);
	if (NULL == pRes)
	{
		return 0;
	}

	while (pRow = mysql_fetch_row(pRes))
	{
		std::shared_ptr<Section> pSection = nullptr;
		int nSectionId = atoi(pRow[0]);

		SectionMap::iterator it = mp_section_list.find(nSectionId);
		if (it != mp_section_list.end())
		{
			pSection = it->second;
		} 
		else
		{
			pSection = make_shared<Section>();
			mp_section_list.insert(make_pair(nSectionId,pSection));
		}

		pSection->m_nID = atoi(pRow[0]);
		pSection->m_strPath  = pRow[1];
		pSection->m_strName  = pRow[2];
		pSection->m_strLabel = pRow[3];
		pSection->m_nMapId   = atoi(pRow[4]);

		if (pSection->m_strPath != "")
		{
			pSection->init_border(pSection->m_strPath);
		}

		LightMap::iterator it_light = mp_light_list.begin();
		for (;it_light != mp_light_list.end();++it_light)
		{
			if (it_light->second->m_nSectionID == pSection->m_nID)
			{
				pSection->mp_light_list.insert(make_pair(it_light->second->m_nID,it_light->second));
			}
		}

		ChamberMap::iterator it_chamber = mp_chamber_list.begin();
		for (;it_chamber!=mp_chamber_list.end();++it_chamber)
		{
			if (it_chamber->second->m_nMapID == pSection->m_nMapId && it_chamber->second->m_nSectionID == pSection->m_nID)
			{
				//从硐室表找到和路段相同地图，且硐室信息中的路段id和此id相同的数据
				ChamberMap::iterator it_section_chamber = pSection->mp_champer_list.find(it_chamber->second->m_nID);
				if (it_section_chamber == pSection->mp_champer_list.end())
				{
					std::shared_ptr<Chamber> pChamber(it_chamber->second);
					pSection->mp_champer_list.insert(make_pair(pChamber->m_nID,pChamber));
				}
			}
		}

		MapInfoMap::iterator it_map = mp_map_list.find(pSection->m_nMapId);
		if (it_map != mp_map_list.end())
		{
			SectionMap::iterator it_section = it_map->second->map_section_list.find(pSection->m_nID);
			if (it_section == it_map->second->map_section_list.end())
			{
				it_map->second->map_section_list.insert(make_pair(pSection->m_nID,pSection));
			}
		}
		nRow++;
	}

	mysql_free_result(pRes);

	//输出操作结果信息
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_SECTIONS), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

/*
* 初始化红绿灯组
*
* param
*		无
*
* return
*		成功返回0，失败返回1
*
*/
int CYAServerDlg::init_light_group(int group_id /*= 0*/)
{
	char sql[LENGTH_SQL] = {0};
	if (group_id == 0)
	{
		sprintf_s(sql,"SELECT lights_group_id,X,Y,z,scope,map_id,area_id,manual_control_time,light_auto_interval FROM dat_lights_group;");
	} 
	else
	{
		sprintf_s(sql,"SELECT lights_group_id,X,Y,z,scope,map_id,area_id,manual_control_time,light_auto_interval FROM dat_lights_group where state = 0 and lights_group_id = %d;",group_id);
	}

	MYSQL_RES* pRes = NULL;
	MYSQL_ROW pRow;
	int err = 0;
	int nRow = 0;

	//查询数据库
	pRes = getMysqlRes(sql);
	if (NULL == pRes)
	{
		return 0;
	}

	while (pRow = mysql_fetch_row(pRes))
	{
		int nGroupId = atoi(pRow[0]);
		std::shared_ptr<op::TrafficLightGroup> pLightGroup = (*m_carmanage)[nGroupId];

		double x = atof(pRow[1]);
		double y = -atof(pRow[2]);
		double scope = atof(pRow[4]);
		uint32_t mapid = atoi(pRow[5]);
		uint32_t areaid = atoi(pRow[6]);
		uint32_t ctTime = atoi(pRow[7]);
		uint32_t lat = pRow[8] == NULL?0:atoi(pRow[8]);
		if(pLightGroup==nullptr)
		{
			pLightGroup = std::make_shared<op::TrafficLightGroup>(x,y,0.0,nGroupId,mapid,areaid,scope,ctTime,lat);
			m_carmanage->put(pLightGroup,nGroupId);
		}
		else
			pLightGroup->set(x,y,mapid,areaid,ctTime,lat);
		nRow++;
	}

	mysql_free_result(pRes);

	//输出操作结果信息
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_LIGHTS_GROUP), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

int CYAServerDlg::init_light_state(CONNID dwConnID,std::string strIp)
{
	std::string ip = strIp;
	if (ip == "")
	{
		return 1;
	}

	bool is_exist = false;

	ReaderMap::iterator it_reader = mp_ctrl_reader_list.begin();
	for (it_reader;it_reader!=mp_ctrl_reader_list.end();++it_reader)
	{
		if(it_reader->second->ip == ip){
			is_exist = true;
			break;
		}
	}

	if (!is_exist)
	{
		return 1;
	}

	if (!it_reader->second->init_ctrl_reader_state)
	{
		for (it_reader;it_reader!=mp_ctrl_reader_list.end();++it_reader)
		{
			LightMap::iterator it_light = mp_light_list.begin();
			for (it_light;it_light!=mp_light_list.end();++it_light)
			{
				if(it_light->second->m_nReaderID == it_reader->second->reader_id){
					send_call_light(CC_REQ_LIGTHS_STATE,it_light->second->m_nID,LIGHT_CTRL_STATE::CTRL_STATE_AUTO,1,0);
					it_reader->second->init_ctrl_reader_state = true;
				}
			}
		}
	}

	return 0;
}

void CYAServerDlg::ws_init()
{
	is_websocket_ok = false;
	is_websocket_login = false;

	_io->set_reconnect_attempts(0);
	using std::placeholders::_1;
	using std::placeholders::_2;
	using std::placeholders::_3;
	using std::placeholders::_4;   
	socket::ptr sock = _io->socket();

	sock->on(JSON_CMD_VALUE_USER, sio::socket::event_listener_aux(std::bind(&CYAServerDlg::OnLogin, this, _1,_2,_3,_4)));
	sock->on(JSON_CMD_VALUE_CALL, sio::socket::event_listener_aux(std::bind(&CYAServerDlg::OnCallMessage,this,_1,_2,_3,_4)));
	sock->on(JSON_CMD_VALUE_PUSH, sio::socket::event_listener(std::bind(&CYAServerDlg::OnPushMessage, this)));

	//default socket opened, also we have "set_open_listener" for monitoring physical connection opened.
	_io->set_socket_open_listener(std::bind(&CYAServerDlg::OnConnected, this));
	//physical connection closed or drop.
	_io->set_close_listener(std::bind(&CYAServerDlg::OnClosed,this, std::placeholders::_1));
	_io->set_reconnect_listener(std::bind(&CYAServerDlg::OnReConnect, this, std::placeholders::_1, std::placeholders::_2));
	//physical connection fail to establish.
	_io->set_fail_listener(std::bind(&CYAServerDlg::OnFailed,this));
}

void CYAServerDlg::ws_close()
{
}

void CYAServerDlg::ws_login()
{
	USES_CONVERSION;
	CC2UTF8 conv = (char*)get_json_login().c_str();
	string szlogin = conv.c_str();
	_io->socket()->emit(JSON_CMD_VALUE_USER, szlogin, [&](sio::message::list const& msglist){
		message::ptr msg_ptr = msglist[0];
		int n =(int)msg_ptr->get_map()["code"]->get_int();
		is_websocket_login = (0 == n) ? true : false;
		CString strlog;
		wchar_t* p_url = CFunctions::c2wc(m_ws_url.c_str());
		if(is_websocket_login){
			strlog.Format(_T("%s: %s"), _T(LOG_LOGIN_WEB_SERVER), p_url);
		}else{
			p_url = CFunctions::c2wc(m_ws_url.c_str());
			strlog.Format(_T("%s: %s, err: %d"), _T(LOG_LOGIN_WEB_SERVER_FAILED), p_url, n);
		}
		show_log(strlog);

		if(p_url){
			free(p_url);
			p_url = NULL;
		}
	});
}

void CYAServerDlg::ws_logout()
{
	USES_CONVERSION;
	CC2UTF8 conv = (char*)get_json_logout().c_str();
	string szlogout = conv.c_str();
	_io->socket()->emit(JSON_CMD_VALUE_USER, szlogout, [&](sio::message::list const& msglist){
		message::ptr msg_ptr = msglist[0];
		int n =(int)msg_ptr->get_map()["code"]->get_int();
		CString strlog;
		wchar_t* p_url = CFunctions::c2wc(m_ws_url.c_str());
		if(n == 0){
			strlog.Format(_T("%s: %s"), _T(LOG_LOGOUT_WEB_SERVER), p_url);
			is_websocket_login = false;
		}else{
			p_url = CFunctions::c2wc(m_ws_url.c_str());
			strlog.Format(_T("%s: %s, err: %d"), _T(LOG_LOGOUT_WEB_SERVER_FAILED), p_url, n);
		}
		show_log(strlog);

		if(p_url){
			free(p_url);
			p_url = NULL;
		}
	});
}

void CYAServerDlg::start_tcp_server()
{
	if(m_enState == ST_STARTED){
		return;
	}

	set_app_state(ST_STARTING);

	if(_server.Start(m_tcp_host, m_nPort))
	{
		::LogServerStart(m_tcp_host, m_nPort);
		set_app_state(ST_STARTED);
		is_start_tcp = true;
	}
	else
	{
		::LogServerStartFail(_server.GetLastError(), _server.GetLastErrorDesc());
		set_app_state(ST_STOPPED);
	}
}

void CYAServerDlg::stop_tcp_server()
{
	if(m_enState == ST_STOPPED){
		return;
	}
	set_app_state(ST_STOPPING);
	if(_server.Stop()){
		::LogServerStop();
		set_app_state(ST_STOPPED);
		is_start_tcp = false;
	}
	else{
		//ASSERT(FALSE);
	}
}

void CYAServerDlg::clear_listener()
{
}

void CYAServerDlg::clear_all_list()
{
	// 清空创建的对象
}

void CYAServerDlg::parse_package_data(BYTE* DataBuffer, int nLen, CONNID dwConnID )
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_274);
	//string tmpbuf = "";
	//formatByteArray(tmpbuf, const_cast<BYTE*>(DataBuffer), nLen);
	//debug_print_syslog(0,"[parse_package_data],pData&%s&%d&",tmpbuf.c_str(),nLen);
	unsigned long long  tmp_count = 0;
	int tmp_position_num = 0;
	if(DataBuffer == NULL){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_36);
		return;
	}
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_61);

	std::string strBuf = "";
	if(m_log_raw_data){
		std::string ip = get_ip_by_id(dwConnID);
		//tmp_count = formatByteArray(strBuf, DataBuffer, nLen);
		tmp_count = formatByteArray_s(strBuf, ip, DataBuffer, nLen);
		Log::write_log(FILE_TYPE::RAW_S, strBuf, false);
	}

	int nCurPos = 0;
	nCurPos += sizeof(WORD);
	nLen -= sizeof(WORD); // 减去数据长度 

	WORD wCrc = CFunctions::getCRC(&DataBuffer[nCurPos], nLen - sizeof(WORD)); // CRC校验码
	WORD w ;

	CFunctions::getWord(&DataBuffer[nCurPos], &w, nLen - sizeof(WORD));
#ifndef _DEBUG
	if( w  != wCrc ){ // 校验不对
		if(m_log_raw_data){
			strBuf = "CRC校验不通过";
			Log::write_log(FILE_TYPE::POSITION_ORIGIN, strBuf, false);
		}
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_37);
		return;
	}
#endif

	WORD wChr = 0;
	CFunctions::getWord(DataBuffer, &wChr, nCurPos);
	nCurPos += sizeof(WORD);

	int reader_id = 0;
	int nTick = 0;
	CString strtime = _T("");
	INT codeType = wChr;
	switch (wChr){
	case CHAR_LOCATEDATA_EXTEND:
	case CHAR_LOCATEDATA: // 定位数据
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_0);
			parse_data_locate_reader(DataBuffer, nCurPos, nLen, dwConnID, reader_id);
			ReaderMap::iterator it = mp_reader_list.find(reader_id);
			if(it != mp_reader_list.end()){ 
				it->second->last_parse_card_id = "";
				it->second->reader_package_end_pos = nLen;
				while(nCurPos < nLen - (int)sizeof(WORD)){ // 减去crc // 可能会有死循环
					tmp_position_num++;
					if (parse_data_locate_card(DataBuffer, nCurPos, reader_id, wChr,tmp_count,tmp_position_num)){
						LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_234);
						break;
					}
				}
			}
			else
			{
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_1);
				debug_print_syslog(0, "[LOCATION_SYSTEM_BRANCH_62]reader not registered: %d", reader_id);
			}
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_13);
			break;
		}
	case CHAR_LOCATEDATA_TDOA:
	case CHAR_LOCATEDATA_TDOA_EXTEND:
		{
			parse_data_locate_reader(DataBuffer, nCurPos, nLen, dwConnID, reader_id);

			ReaderMap::iterator it = mp_reader_list.find(reader_id);
			if(it != mp_reader_list.end()){
				while(nCurPos < nLen - (int)sizeof(WORD)){ // 减去crc
					LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_14);
					if(parse_data_locate_card(DataBuffer, nCurPos, reader_id, wChr))
					{
						LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_235);
						break;
					}
				}
			}
			else
			{
				debug_print_syslog(0, "【LOCATION_SYSTEM_BRANCH_35】reader not registered: %d", reader_id);
			}
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_62);

			break;
		}
	case CHAR_LOCATEDATA_HIS_EXTEND:
	case CHAR_LOCATEDATAHIS:
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_2);
			g_is_rec_hist = true;
			parse_data_locate_reader_his(DataBuffer, nLen, nCurPos, reader_id, nTick, strtime, wChr);
			while(nCurPos < nLen - (int)sizeof(WORD)){ // 减去crc
				//debug_print_syslog(0, "CHAR_LOCATEDATAHIS reader_id:%d\n", reader_id);
				parse_data_locate_card_his(DataBuffer, nCurPos, reader_id, nTick, strtime, wChr);
			}
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_64);
			break;
		}
	case CHAR_LOCATEDATAHIS_TDOA:
	case CHAR_LOCATEDATAHIS_TDOA_EXTEND:
		{
			g_is_rec_hist = true;
			parse_data_locate_reader_his(DataBuffer, nLen, nCurPos, reader_id, nTick, strtime, wChr);

			BYTE* bt = new BYTE[nLen];
			while(nCurPos < nLen - (int)sizeof(WORD)){ // 减去crc
				// 获取一条记录的长度
				WORD wframelen  = 0;
				CFunctions::getWord(DataBuffer, &wframelen, nCurPos);
				nCurPos += sizeof(WORD);

				if(bt){
					memset(bt, 0, nLen);
					memcpy(bt, &DataBuffer[nCurPos], wframelen);
					parse_data_locate_card_his_tdoa(bt, wframelen, reader_id, nTick, strtime);
				}
				nCurPos += nLen;
			}
			delete[] bt;
			bt = NULL;
			break;
		}
	case CHAR_HIST_DATA_FINISH:
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_4);
			g_is_rec_hist = false;
			// 完成历史数据上传，可点名下一分站
			break;
		}
	case CHAR_READER_SYNC_TIME:
	case CHAR_READER_SYNC_TIME_EXTEND:
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_5);
			//parse_data_reader_synctime(DataBuffer, nLen, nCurPos, CHAR_READER_SYNC_TIME);
			parse_data_reader_synctime(DataBuffer, nLen, nCurPos, wChr);
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_66);

			break;
		}
	case CHAR_READER_SYNC_TIME_ROOT:
	case CHAR_READER_SYNC_TIME_ROOT_EXTEND:
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_6);
			//parse_data_reader_synctime(DataBuffer, nLen, nCurPos, CHAR_READER_SYNC_TIME_ROOT);
			parse_data_reader_synctime(DataBuffer, nLen, nCurPos, wChr);
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_35);

			break;
		}
	case CHAR_ADHOC:
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_7);
			parse_data_locate_reader(DataBuffer, nCurPos, nLen, dwConnID, reader_id);
			ReaderMap::iterator it = mp_reader_list.find(reader_id);
			if(it != mp_reader_list.end()){
				while(nCurPos < nLen - (int)sizeof(WORD)){ // 减去crc
					parse_data_adhoc(DataBuffer, nCurPos, reader_id);
				}
			}
			else{
				debug_print_syslog(0, "【parse_package_data】reader not registered: %d", reader_id);
			}
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_67);

			break;
		}
	case CHAR_CTRL_READER_CMD:
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_282);
			parse_data_ctrl_reader(DataBuffer, nCurPos, nLen, dwConnID, reader_id);
			ReaderMap::iterator it = mp_ctrl_reader_list.find(reader_id);
			if(it != mp_ctrl_reader_list.end()){
				while (nCurPos < nLen - (int)sizeof(WORD)){
					parse_data_lights_state(DataBuffer, nCurPos, reader_id, CHAR_CTRL_READER_CMD);
				}
			}
			else
			{
				debug_print_syslog(0, "【CHAR_CTRL_READER_CMD】reader not registered: %d", reader_id);
			}
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_68);

			break;
		}
	case INAV_LOCATE_DATA:
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_230);
			int card_num = parse_inav_msg((INAVLocateMsg *)DataBuffer);
			deal_inav_locate_msg((INAVLocateMsg *)DataBuffer, card_num);
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_283);

			break;
		}
	case RECV_TOF_DATA_AND_INS:
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_284);
			// 接收tof协议中带惯导的数据
			parse_data_locate_reader(DataBuffer, nCurPos, nLen, dwConnID, reader_id);
			ReaderMap::iterator it = mp_reader_list.find(reader_id);
			if(it != mp_reader_list.end()){
				while(nCurPos < nLen - (int)sizeof(WORD)){ // 减去crc // 可能会有死循环
					if (parse_data_locate_card(DataBuffer, nCurPos, reader_id, wChr)){
						LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_293);
						break;
					}
				}
			}
			else
			{
				debug_print_syslog(0, "【RECV_TOF_DATA_AND_INS】reader not registered: %d\n", reader_id);
			}
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_285);
			break;
		}
	case REQ_SYNC_TIME:
		send_sync_reader(dwConnID);
		break;
	case RECV_MOVING_READER_DATA:
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_286);
			parse_data_locate_reader(DataBuffer, nCurPos, nLen, dwConnID, reader_id);
			ReaderMap::iterator it = mp_reader_list.find(reader_id);
			if(it != mp_reader_list.end()){
				while (nCurPos < nLen - (int)sizeof(WORD))
				{
					//parse_data_moving_reader(DataBuffer, nCurPos, nLen, dwConnID, reader_id);
				}
			}
			else
			{
				debug_print_syslog(0, "【RECV_MOVING_READER_DATA】reader not registered: %d\n", reader_id);
			}
		}
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_281);

		break;
	case CHAR_LIGHT_STATUS_HEARD:
		{
			parse_data_signal_lamp(DataBuffer, nCurPos, nLen, dwConnID);
		}
		break;
	case REQ_SIGNAL_LAMP_STATUS:
		{
			//debug_print_syslog(0,"start req_signal_lamp_status: %s %d",__FILE__,__LINE__);
			uint32_t light_id = 0;
			parse_data_signal_lamp_req_status(DataBuffer, nCurPos, dwConnID,light_id);
			send_signal_lamp_status(light_id);
			deal_light_auto_control_param(light_id,dwConnID);
			//debug_print_syslog(0,"end req_signal_lamp_status: %s %d",__FILE__,__LINE__);
		}
		break;
	default:
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_8);
		break;
	}
	strtime.ReleaseBuffer();

	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_287);
}

void CYAServerDlg::parse_data_locate_reader(BYTE * DataBuffer, int& nCurPos, int nLen, CONNID dwConnID, int& reader_id )
{
	//debug_print_syslog(0,"enter parse_data_locate_reader: %s %d",__FILE__,__LINE__);
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_15);
	// 分站号
	DWORD dwReaderID;
	CFunctions::getDWord(DataBuffer, &dwReaderID, nCurPos);
	nCurPos += sizeof(DWORD);

	reader_id = dwReaderID;
	ReaderMap::iterator itReader = mp_reader_list.find(dwReaderID);
	std::shared_ptr<Reader> pReader = nullptr;
	bool isErrorReader = false;

	if(itReader != mp_reader_list.end()){
		pReader = itReader->second;
		add_socket_to_list(dwConnID, reader_id, DEVICE_TYPE::DT_CARD_READER);
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_16);
	}else{
		pReader = std::make_shared<Reader>();
		pReader->reader_id = dwReaderID;
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_17);
	}

	// 接收数据时间
	pReader->rec_time = time(NULL); 
	m_time_last_rec = pReader->rec_time; // 更新最后信号时间
	// 分站时间戳
	WORD wTickCount = 0;
	CFunctions::getWord(DataBuffer, &wTickCount, nCurPos);
	nCurPos += sizeof(WORD);
	pReader->tick_count = wTickCount;
	// 分站时间
	// 7字节 从第一个字节开始，分别表示秒、分、时、天、周、月、年
	BYTE btSec = 0;
	memcpy(&btSec, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btMin = 0;
	memcpy(&btMin, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btHour = 0;
	memcpy(&btHour, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btDay = 0;
	memcpy(&btDay, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btWeek = 0;
	memcpy(&btWeek, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btMonth = 0;
	memcpy(&btMonth, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btYear = 0;
	memcpy(&btYear, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	struct tm reader_time;
	reader_time.tm_sec = btSec;
	reader_time.tm_min = btMin;
	reader_time.tm_hour = btHour;
	reader_time.tm_mday = btDay;
	reader_time.tm_wday = btWeek;
	reader_time.tm_mon = btMonth - 1;
	reader_time.tm_year = btYear + 100;  // + 2000 - 1900
	pReader->reader_time = mktime(&reader_time);

	// 温度

	/*BYTE btTemperature = 0;	
	memcpy(&btTemperature, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	pReader->temperature = btTemperature;*/
	//改为大小分站信息,最高位第7位表示大小分站，1表示大分站，0表示小分站
	//高6位表示分站(大或小)在大分站的左侧或右侧，1代表在大分站的左侧，0表示在大分站的右侧
	//高5位预留位，用于区分是读卡分站还是大小分站
	BYTE btReaderInfo = 0;
	memcpy(&btReaderInfo, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	uint8_t reader_type = btReaderInfo >>7;			//大小分站的区别
	uint8_t reader_dir = (btReaderInfo >>6)&0x01;
	uint8_t reader_type_locate = (btReaderInfo >>5)&0x01;	//大小分站与读卡分站的区别
	uint8_t relay_counts = btReaderInfo&0x0F;
	/*switch (reader_type)
	{
	case 0:
	pReader->device_type_id = DEVICE_TYPE::DT_SMALL_READER;
	break;
	case 1:
	pReader->device_type_id = DEVICE_TYPE::DT_BIG_READER;
	break;
	}*/
	pReader->reader_dir = reader_dir;
	pReader->relay_counts = relay_counts;

	// 状态
	/*WORD wState = 0;
	CFunctions::getWord(&DataBuffer[nCurPos], &wState, sizeof(WORD));
	nCurPos += sizeof(WORD);*/

	BYTE btState = 0;	
	memcpy(&btState, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	BYTE btReaderPower = 0;
	memcpy(&btReaderPower, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	reader_power_battery_alarm(dwReaderID,btReaderPower);

	if(m_log_parse_data){
		char chlog[MAX_LOG_LENGTH];
		memset(chlog,0,MAX_LOG_LENGTH*sizeof(char));
		sprintf_s(chlog, "id:%d, n:%d, %.2d-%.2d-%.2d %.2d:%.2d:%.2d, sta: %d,reader_power: %d,reader_type: %d,is_big_reader: %d,is_left: %d, counts: %d",
			dwReaderID, wTickCount, btYear, btMonth, btDay, btHour, btMin, btSec, btState,btReaderPower,reader_type_locate,reader_type,reader_dir,relay_counts);/*tep:%d,*/
		std::string strlog = chlog;
		Log::write_log(FILE_TYPE::PARSE_S, strlog, true);
		//debug_print_syslog(0,"[reader_parse] %s",chlog);
	}
	//debug_print_syslog(0,"leave parse_data_locate_reader: %s %d ",__FILE__,__LINE__);
}

void CYAServerDlg::parse_data_ctrl_reader( BYTE * DataBuffer, int& nCurPos, int nLen, CONNID dwConnID, int& reader_id )
{
	DWORD dwReaderID;
	CFunctions::getDWord(DataBuffer, &dwReaderID, nCurPos);
	nCurPos += sizeof(DWORD);

	reader_id = dwReaderID;
	ReaderMap::iterator itReader = mp_ctrl_reader_list.find(dwReaderID);
	std::shared_ptr<Reader> pReader = nullptr;
	bool isErrorReader = false;

	if(itReader != mp_ctrl_reader_list.end()){
		pReader = itReader->second;
		add_socket_to_list(dwConnID, reader_id, DEVICE_TYPE::DT_CTRL_READER);
		//add_socket_to_list(dwConnID, reader_id, DEVICE_TYPE::DT_CARD_READER,TRUE);
		init_light_state(dwConnID,itReader->second->ip);
	}else{
		pReader = std::make_shared<Reader>();
		pReader->reader_id = dwReaderID;
	}

	// 接收数据时间
	pReader->rec_time = time(NULL); 
	m_time_last_rec = pReader->rec_time; // 更新最后信号时间
	// 分站时间戳
	WORD wTickCount = 0;
	CFunctions::getWord(DataBuffer, &wTickCount, nCurPos);
	nCurPos += sizeof(WORD);
	pReader->tick_count = wTickCount;
	// 分站时间
	// 7字节 从第一个字节开始，分别表示秒、分、时、天、周、月、年
	BYTE btSec = 0;
	memcpy(&btSec, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btMin = 0;
	memcpy(&btMin, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btHour = 0;
	memcpy(&btHour, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btDay = 0;
	memcpy(&btDay, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btWeek = 0;
	memcpy(&btWeek, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btMonth = 0;
	memcpy(&btMonth, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btYear = 0;
	memcpy(&btYear, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	struct tm reader_time;
	reader_time.tm_sec = btSec;
	reader_time.tm_min = btMin;
	reader_time.tm_hour = btHour;
	reader_time.tm_mday = btDay;
	reader_time.tm_wday = btWeek;
	reader_time.tm_mon = btMonth - 1;
	reader_time.tm_year = btYear + 100;  // + 2000 - 1900
	pReader->reader_time = mktime(&reader_time);

	// 温度
	BYTE btTemperature = 0;	
	memcpy(&btTemperature, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	pReader->temperature = btTemperature;
	// 状态
	WORD wState = 0;
	CFunctions::getWord(DataBuffer, &wState, sizeof(WORD));
	nCurPos += sizeof(WORD);

	if(m_log_parse_data){
		char chlog[MAX_LOG_LENGTH];
		sprintf_s(chlog, "id:%d, n:%d, %.2d-%.2d-%.2d %.2d:%.2d:%.2d, tep:%d, sta:%d",
			dwReaderID, wTickCount, btYear, btMonth, btDay, btHour, btMin, btSec, btTemperature, wState);
		std::string strlog = chlog;
		Log::write_log(FILE_TYPE::PARSE_S, strlog, true);
	}
}

/*
 * 解析红绿灯状态数据，用于红绿灯心跳检测
 *
 * param
 *		DataBuffer		接收分站上传的红绿灯数据区内容
 *		nCurPos			红绿灯数据区起始位置
 *		nLen			数据区长度
 *		dwConnID		红绿灯所接带IP大分站连接号
 *
 * return
 *		无
 *
*/
void CYAServerDlg::parse_data_signal_lamp(BYTE * DataBuffer, int& nCurPos, int nLen, CONNID dwConnID)
{
	//debug_print_syslog(0,"enter parse_data_signal_lamp: %s %d",__FILE__,__LINE__);
	//灯号
	DWORD dwLightId = 0;
	CFunctions::getDWord(DataBuffer,&dwLightId,nCurPos);
	nCurPos += sizeof(DWORD);

	auto it = m_carmanage->getPhysicsTrafficLightId(dwLightId);
	if (it.empty())
	{
		std::shared_ptr<op::TrafficLight> pPosTrafficLight = std::make_shared<op::TrafficLight>(1,0,0,0,0,"",0,0,dwLightId,1);
		pPosTrafficLight->m_physics_light_id = dwLightId;
		std::shared_ptr<op::TrafficLight> pNegTrafficLight = std::make_shared<op::TrafficLight>(2,0,0,0,0,"",0,0,dwLightId,0);
		pNegTrafficLight->m_physics_light_id = dwLightId;
	}else{
		//加入到灯组
		add_socket_to_list(dwConnID,dwLightId,DEVICE_TYPE::DT_LIGHT,true);
	}

	//灯计数序号
	WORD wTickCount = 0;
	CFunctions::getWord(DataBuffer,&wTickCount,nCurPos);
	nCurPos += sizeof(WORD);

	//can总线ID
	BYTE btCanId = 0;
	memcpy(&btCanId,&DataBuffer[nCurPos],sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	//正面状态
	BYTE btPostiveStatus = 0;
	memcpy(&btPostiveStatus,&DataBuffer[nCurPos],sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	//反面状态
	BYTE btNegativeStatus = 0;
	memcpy(&btNegativeStatus,&DataBuffer[nCurPos],sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	//四字节预留
	DWORD dwReserve = 0;
	CFunctions::getDWord(DataBuffer,&dwReserve,nCurPos);
	nCurPos += sizeof(dwReserve);

	for (auto it_light_id : it)
	{
		auto it_light = m_carmanage->getTrafficLight(it_light_id);
		if (it_light != nullptr)
		{
			it_light->m_rec_time = time(NULL);
		}
	}

	if(m_log_parse_data){
		char chlog[MAX_LOG_LENGTH];
		sprintf_s(chlog, "id: %d, n: %d, can_id: %d, postive: %d, negative: %d",
			dwLightId,wTickCount,btCanId,btPostiveStatus,btNegativeStatus);
		std::string strlog = chlog;
		Log::write_log(FILE_TYPE::PARSE_LIGHT_S, strlog, true);
	}
	//debug_print_syslog(0,"leave parse_data_signal_lamp: %s %d",__FILE__,__LINE__);
}

int CYAServerDlg::parse_inav_msg(INAVLocateMsg* msgPtr)
{
	if(NULL == msgPtr)
	{
		return -1;
	}
	int len = sizeof(INAVLocateMsg);
	int len_header = sizeof(MsgHeader);
	int len_anchor = sizeof(LocateAnchorInfo);
	int len_one_inav = sizeof(INAVLocateData);
	msgPtr->Header.MsgCode = ntohs(msgPtr->Header.MsgCode);
	msgPtr->Header.MsgLen = ntohs(msgPtr->Header.MsgLen);
	msgPtr->AnchorInfo.AnchorNum = ntohl(msgPtr->AnchorInfo.AnchorNum);
	msgPtr->AnchorInfo.MsgSerialNum = ntohs(msgPtr->AnchorInfo.MsgSerialNum);
	msgPtr->AnchorInfo.State = ntohs(msgPtr->AnchorInfo.State);

	int msg_len = msgPtr->Header.MsgLen - sizeof(MsgHeader) - sizeof(LocateAnchorInfo);
	int card_num = msg_len / sizeof(INAVLocateData);
	for(int i=0; i < card_num ; i++)
	{
		msgPtr->INAVLocateInfo[i].CardId = ntohl(msgPtr->INAVLocateInfo[i].CardId);
		msgPtr->INAVLocateInfo[i].INAVPeriod= ntohs(msgPtr->INAVLocateInfo[i].INAVPeriod);
		msgPtr->INAVLocateInfo[i].AccerateData_X= ntohs(msgPtr->INAVLocateInfo[i].AccerateData_X);
		msgPtr->INAVLocateInfo[i].AccerateData_Y= ntohs(msgPtr->INAVLocateInfo[i].AccerateData_Y);
		msgPtr->INAVLocateInfo[i].AccerateData_Z= ntohs(msgPtr->INAVLocateInfo[i].AccerateData_Z);
		msgPtr->INAVLocateInfo[i].MagneticData_X= ntohs(msgPtr->INAVLocateInfo[i].MagneticData_X);
		msgPtr->INAVLocateInfo[i].MagneticData_Y= ntohs(msgPtr->INAVLocateInfo[i].MagneticData_Y);
		msgPtr->INAVLocateInfo[i].MagneticData_Z= ntohs(msgPtr->INAVLocateInfo[i].MagneticData_Z);
		msgPtr->INAVLocateInfo[i].Gyroscope_X= ntohs(msgPtr->INAVLocateInfo[i].Gyroscope_X);
		msgPtr->INAVLocateInfo[i].Gyroscope_Y= ntohs(msgPtr->INAVLocateInfo[i].Gyroscope_Y);
		msgPtr->INAVLocateInfo[i].Gyroscope_Z= ntohs(msgPtr->INAVLocateInfo[i].Gyroscope_Z);
		msgPtr->INAVLocateInfo[i].Displacement_X= ntohs(msgPtr->INAVLocateInfo[i].Displacement_X);
		msgPtr->INAVLocateInfo[i].Displacement_Y= ntohs(msgPtr->INAVLocateInfo[i].Displacement_Y);
		msgPtr->INAVLocateInfo[i].Displacement_Z= ntohs(msgPtr->INAVLocateInfo[i].Displacement_Z);
		msgPtr->INAVLocateInfo[i].AngleChange_X= ntohs(msgPtr->INAVLocateInfo[i].AngleChange_X);
		msgPtr->INAVLocateInfo[i].AngleChange_Y= ntohs(msgPtr->INAVLocateInfo[i].AngleChange_Y);
		msgPtr->INAVLocateInfo[i].AngleChange_Z= ntohs(msgPtr->INAVLocateInfo[i].AngleChange_Z);
	}
	msg_len = 0;
	return card_num;
}

int g_magic_offset_x = 0;
int g_magic_offset_y = 0;
int g_magic_offset_z = 0;

int tmp_magic_max_x = 0;
int tmp_magic_min_x = 0;
int tmp_magic_max_y = 0;
int tmp_magic_min_y = 0;
int tmp_magic_max_z = 0;
int tmp_magic_min_z = 0;

int init_times = 100;

int g_magic_is_init = 0;

bool init_magic_offset(INAVLocateData cardData)
{
	if(init_times > 0)
	{
		return false;
	}
	else
	{
		g_magic_offset_x = (tmp_magic_max_x + tmp_magic_min_x) / 2;
		g_magic_offset_y = (tmp_magic_max_y + tmp_magic_min_y) / 2;
		g_magic_offset_z = (tmp_magic_max_z + tmp_magic_min_z) / 2;
		debug_print_syslog(0, "Magic init successful: magic_offset_x: %d, magic_offset_x: %d, magic_offset_x: %d", 
			g_magic_offset_x, g_magic_offset_y, g_magic_offset_z);
		return true;
	}
	if(cardData.MagneticData_X > tmp_magic_max_x)
	{
		tmp_magic_max_x = cardData.MagneticData_X;
	}
	if(cardData.MagneticData_Y> tmp_magic_max_y)
	{
		tmp_magic_max_y = cardData.MagneticData_X;
	}
	if(cardData.MagneticData_Z > tmp_magic_max_z)
	{
		tmp_magic_max_z = cardData.MagneticData_Z;
	}
	if(cardData.MagneticData_X < tmp_magic_min_x)
	{
		tmp_magic_min_x = cardData.MagneticData_X;
	}
	if(cardData.MagneticData_X < tmp_magic_min_y)
	{
		tmp_magic_min_y = cardData.MagneticData_X;
	}
	if(cardData.MagneticData_Z < tmp_magic_min_z)
	{
		tmp_magic_min_z = cardData.MagneticData_Z;
	}

	init_times--;
}

void write_magic_locate_map(INAVLocateData* msgPtr, std::shared_ptr<Card> card)
{
	csv::Parser file = csv::Parser("magic_locate_data.csv");  
	vector<string> tmpRow;
	int magic_x = msgPtr->MagneticData_X;
	int magic_y = msgPtr->MagneticData_Y;
	int magic_z = msgPtr->MagneticData_Z;
	int x = card->x;
	int y = card->y;
	int z = card->z;
	char str[20];
	sprintf_s(str,"%d", magic_x);
	tmpRow.push_back(str);
	sprintf_s(str,"%d", magic_y);
	tmpRow.push_back(str);
	sprintf_s(str,"%d", magic_z);
	tmpRow.push_back(str);
	sprintf_s(str,"%d", x);
	tmpRow.push_back(str);
	sprintf_s(str,"%d", y);
	tmpRow.push_back(str);
	file.addRow(0, tmpRow);
	file.sync();
}

void CYAServerDlg::deal_inav_locate_msg(INAVLocateMsg* msgPtr, int card_num)
{
	if(NULL == msgPtr)
	{
		return;
	}
	for(int i=0; i<card_num; i++)
	{
		string str_card_id = CFunctions::getstrwithzero(msgPtr->INAVLocateInfo[i].CardType, 3) + CFunctions::getstrwithzero(msgPtr->INAVLocateInfo[i].CardId, 10);

		std::shared_ptr<Card> card = nullptr;
		bool isErrorCard = false;

		CardMap::iterator it_card = mp_card_list_all.find(str_card_id);
		if(it_card != mp_card_list_all.end())
		{
			card = it_card->second;
		}
		else
		{
			isErrorCard = true;
			card = std::make_shared<Card>(str_card_id, 
				msgPtr->INAVLocateInfo[i].CardType, 
				theApp.z_offset);
			card->is_registered = false;
			card->set_reader_path(mp_reader_path_list_tof, mp_reader_path_list_tdoa);		
		}
#if 0

		std::shared_ptr<MapInfo> pMap = nullptr;
		MapInfoMap::iterator it = mp_map_list.find(card->map_id);
		if(it != mp_map_list.end()){
			pMap = it->second;
		}
		else
		{
			return;
		}
		card->x = card->x + msgPtr->INAVLocateInfo[i].Displacement_X / 1000 / pMap->map_scale;
		card->y= card->y + msgPtr->INAVLocateInfo[i].Displacement_Y / 1000 / pMap->map_scale;
		card->z= card->z + msgPtr->INAVLocateInfo[i].Displacement_Z / 1000 / pMap->map_scale;

		//init magic offset
		if(init_magic_offset(msgPtr->INAVLocateInfo[i]))
		{
			g_magic_is_init = 1;
		}
		//write magic data
		if(1 == g_magic_is_init)
		{
			write_magic_locate_map(INAVLocateMsg* msgPtr, std::shared_ptr<Card> card)
		}
#else if

		card->x = card->x + msgPtr->INAVLocateInfo[i].Displacement_X / 1000;
		card->y= card->y + msgPtr->INAVLocateInfo[i].Displacement_Y / 1000;
		card->z= card->z + msgPtr->INAVLocateInfo[i].Displacement_Z / 1000;
#endif
		INAV_STATUS card_state = calculate_inav_state(&(msgPtr->INAVLocateInfo[i]));
		//calculate_inav_locate_by_magic(card, &(msgPtr->INAVLocateInfo[i]));
		//write_inav_locate_magic_data(card, &(msgPtr->INAVLocateInfo[i]));
		log_card_inav_state(card_state, str_card_id);
		save_card_postion(card);
		card_enter_map(card); // 切换地图
		card_enter_area(card);
		card_enter_mine(card);
		deal_card_state(card);
		if (card->card_type == CT_VEHICLE || CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type)
		{
			deal_traffic_lights(card);
			//select_pos_output(card);
		}
		card->isdealed = true;
		if(LT_READER != theApp.locate_type){
			card->issent = false;
		}
	}

	return;
}

INAV_STATUS CYAServerDlg::calculate_inav_state(INAVLocateData* cardData)
{
	INAV_STATUS state = {INAV_STATIC, INAV_NO_DIRECTORY, INAV_NO_ACCERATE};
	double accelerate_x = cardData->AccerateData_X * 2 * GRAVITY_ACCERATION / INAV_READING_MAX;
	double accelerate_y = cardData->AccerateData_Y * 2 * GRAVITY_ACCERATION / INAV_READING_MAX;
	double accelerate_z = cardData->AccerateData_Z * 2 * GRAVITY_ACCERATION / INAV_READING_MAX;

	double join_accerate = sqrt(pow(accelerate_x, 2) + pow(accelerate_y, 2) + pow(accelerate_z, 2));

	debug_print_syslog(0, "displacement_x: %d, displacement_y: %d, displacement_z: %d", 
		cardData->Displacement_X, cardData->Displacement_Y, cardData->Displacement_Z);
	double join_diff = abs(join_accerate - GRAVITY_ACCERATION);
	debug_print_syslog(0, "joint force: %10f", join_diff);
	if(join_diff > JOIN_ACCERATE_THRESHOLD)
	{
		state.Status = INAV_MOVING;
	}
	else
	{
		state.Status = INAV_STATIC;
	}

	if(INAV_MOVING == state.Status)
	{
		//X+ is the forward
#if 0
		bool right_forward_condition = (abs(accelerate_x) > MOVING_THRESHOLD) &&(abs(accelerate_y) < MOVING_THRESHOLD) && (accelerate_x < 0);
		bool left_forward_condition = (abs(accelerate_x) > MOVING_THRESHOLD) && (abs(accelerate_y) < MOVING_THRESHOLD) && (accelerate_x > 0);
		bool forward_condition      = (abs(accelerate_y) > MOVING_THRESHOLD) && (abs(accelerate_x) < MOVING_THRESHOLD) && (accelerate_y < 0);
		bool backward_condition     = (abs(accelerate_y) > MOVING_THRESHOLD) && (abs(accelerate_x) < MOVING_THRESHOLD) && (accelerate_y > 0);
#endif
		bool forward_condition = (abs(accelerate_x) > MOVING_THRESHOLD) &&(abs(accelerate_y) < MOVING_THRESHOLD) && (accelerate_x > 0);
		bool backward_condition = (abs(accelerate_x) > MOVING_THRESHOLD) && (abs(accelerate_y) < MOVING_THRESHOLD) && (accelerate_x < 0);
		bool left_forward_condition      = (abs(accelerate_y) > MOVING_THRESHOLD) && (abs(accelerate_x) < MOVING_THRESHOLD) && (accelerate_y < 0);
		bool right_forward_condition     = (abs(accelerate_y) > MOVING_THRESHOLD) && (abs(accelerate_x) < MOVING_THRESHOLD) && (accelerate_y > 0);
		debug_print_syslog(0, "accelerate_x: %f, accelerate_y: %f", 
			accelerate_x, accelerate_y);
		debug_print_syslog(0, "right_forward_condition: %d, left_forward_condition: %d, forward_condition: %d, backward_condition: %d", 
			right_forward_condition, left_forward_condition, forward_condition, backward_condition);
		bool displace_forward_condition = (abs(cardData->Displacement_X) > DISPLACE_MENT_MOVING_THRESHOLD) &&(abs(cardData->Displacement_Y) < DISPLACE_MENT_MOVING_THRESHOLD) && (cardData->Displacement_X > 0);
		bool displace_backward_condition = (abs(cardData->Displacement_X) > DISPLACE_MENT_MOVING_THRESHOLD) && (abs(cardData->Displacement_Y) < DISPLACE_MENT_MOVING_THRESHOLD) && (cardData->Displacement_X < 0);
		bool displace_left_forward_condition      = (abs(cardData->Displacement_Y) > DISPLACE_MENT_MOVING_THRESHOLD) && (abs(cardData->Displacement_X) < DISPLACE_MENT_MOVING_THRESHOLD) && (cardData->Displacement_Y < 0);
		bool displace_right_forward_condition     = (abs(cardData->Displacement_Y) > DISPLACE_MENT_MOVING_THRESHOLD) && (abs(cardData->Displacement_X) < DISPLACE_MENT_MOVING_THRESHOLD) && (cardData->Displacement_Y > 0);

		debug_print_syslog(0, "displacement right_forward_condition: %d, displacement left_forward_condition: %d, displacement forward_condition: %d, displacement backward_condition: %d", 
			displace_right_forward_condition, displace_left_forward_condition, displace_forward_condition, displace_backward_condition);
		if(right_forward_condition)
		{
			state.Directory = INAV_RIGHTWARD;
		}
		if(left_forward_condition)
		{
			state.Directory = INAV_LEFTWARD;
		}
		if(forward_condition)
		{
			state.Directory = INAV_FORWARD;
		}
		if(backward_condition)
		{
			state.Directory = INAV_BACKWARD;
		}
	}
	if(INAV_MOVING == state.Status)
	{
		if(cardData->Displacement_Y > 0 && accelerate_y > MOVING_THRESHOLD)
		{
			state.AccerateStatus = INAV_ACCERATE;
		}
		if(cardData->Displacement_Y > 0 && accelerate_y < -1 * MOVING_THRESHOLD)
		{
			state.AccerateStatus = INAV_SLOW_DOWN;
		}
		if(cardData->Displacement_Y < 0 && accelerate_y > MOVING_THRESHOLD)
		{
			state.AccerateStatus = INAV_ACCERATE;
		}
		if(cardData->Displacement_Y < 0 && accelerate_y < -1 * MOVING_THRESHOLD)
		{
			state.AccerateStatus = INAV_SLOW_DOWN;
		}
	}

	return state;
}

void CYAServerDlg::calculate_inav_locate_by_magic(std::shared_ptr<Card> card, INAVLocateData* cardData)
{
	int magic_x = cardData->MagneticData_X;
	int magic_y = cardData->MagneticData_Y;
	int magic_z = cardData->MagneticData_Z;
	KNN knn(magic_x, magic_y, magic_z);  
	knn.get_all_distance();  
	tLabel tmp_lable = knn.get_max_freq_label();
	debug_print_syslog(0, "magic__x: %10d, magic_y: %10d, magic_z: %10d", magic_x, magic_y, magic_z);
	debug_print_syslog(0, "magic_position_x: %10d, magic_position_y: %10d", tmp_lable.x, tmp_lable.y);
	return;
}

void CYAServerDlg::write_inav_locate_magic_data(std::shared_ptr<Card> card, INAVLocateData* cardData)
{
	csv::Parser file = csv::Parser("d:/magic_map/trainning_data_magic.csv");  
	vector<string> tmpRow;
	int magic_x = cardData->MagneticData_X;
	int magic_y = cardData->MagneticData_Y;
	int magic_z = cardData->MagneticData_Z;
	int x = card->x;
	int y = card->y;
	char str[10];
	sprintf_s(str,"%d",magic_x);
	tmpRow.push_back(str);
	sprintf_s(str,"%d",magic_y);
	tmpRow.push_back(str);
	sprintf_s(str,"%d",magic_z);
	tmpRow.push_back(str);
	sprintf_s(str,"%d",x);
	tmpRow.push_back(str);
	sprintf_s(str,"%d",y);
	tmpRow.push_back(str);

	file.addRow(0, tmpRow);
	file.sync();
	return;
}

void CYAServerDlg::log_card_inav_state(INAV_STATUS card_state, string card_id)
{
	char card_log_str[MAX_LOG_LENGTH] = {'\0'};
	sprintf_s(card_log_str, MAX_LOG_LENGTH, 
		"Card %s: Moving status: %s, Directory: %s, Accerate status: %s", 
		card_id.c_str(),
		InavMovingStatusStr[card_state.Status],
		InavDirectoryStr[card_state.Directory - INAV_NO_DIRECTORY],
		InavAccerateStatusStr[card_state.AccerateStatus - INAV_NO_ACCERATE]);
	debug_print_syslog(0, "%s", card_log_str);
	return;
}

int CYAServerDlg::get_locate_msg_type(BYTE* DataBuffer)
{
	if(NULL == DataBuffer)
	{
		return -1;
	}
	TofLocateMsg* msgPtr = (TofLocateMsg *)DataBuffer;
	int msgLen = ntohs(msgPtr->Header.MsgLen);

	if((msgLen < sizeof(MsgHeader) + sizeof(LocateAnchorInfo) + sizeof(TofCardInfo))
		|| (msgLen > sizeof(TofLocateMsg)))
	{
		return -1;
	}

	return (msgPtr->TofCardInfo[0].MsgType_BatterInfo >> 4) & 0x0f;
}

std::shared_ptr<Card> CYAServerDlg::parse_tof_locate_msg(TofLocateMsg* DataBuffer, int cardNum)
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_258);
	TofLocateMsg msgLocatBuf = {0};
	int length = sizeof(TofLocateMsg);
	memcpy(&msgLocatBuf, DataBuffer, sizeof(TofLocateMsg));

	msgLocatBuf.Header.MsgCode = ntohs(msgLocatBuf.Header.MsgCode);
	msgLocatBuf.Header.MsgLen= ntohs(msgLocatBuf.Header.MsgLen);
	msgLocatBuf.AnchorInfo.AnchorNum = ntohl(msgLocatBuf.AnchorInfo.AnchorNum);
	msgLocatBuf.AnchorInfo.MsgSerialNum = ntohs(msgLocatBuf.AnchorInfo.MsgSerialNum);
	msgLocatBuf.AnchorInfo.State = ntohs(msgLocatBuf.AnchorInfo.State);

	msgLocatBuf.TofCardInfo[cardNum].CardId = ntohl(msgLocatBuf.TofCardInfo[cardNum].CardId);
	msgLocatBuf.TofCardInfo[cardNum].MsgSerialNum = ntohs(msgLocatBuf.TofCardInfo[cardNum].MsgSerialNum);

	LONG64 flyTime = 0;
	DWORD dwTemp = 0;
	CFunctions::getDWord(msgLocatBuf.TofCardInfo[cardNum].LocateTimeStamp, &dwTemp, 0);
	flyTime = dwTemp;
	flyTime =  (flyTime & 0xffffffff);
	flyTime = flyTime<<8;
	flyTime = flyTime + msgLocatBuf.TofCardInfo[cardNum].LocateTimeStamp[4];

	double dist = CFunctions::getDistance(flyTime, CFunctions::TOF);

	string str_card_id = CFunctions::getstrwithzero(msgLocatBuf.TofCardInfo[cardNum].CardType, 3) 
		+ CFunctions::getstrwithzero(msgLocatBuf.TofCardInfo[cardNum].CardId, 10);

	std::shared_ptr<Card> card = nullptr;
	bool isErrorCard = false;

	ReaderMap::iterator it = mp_reader_list.find(msgLocatBuf.AnchorInfo.AnchorNum);
	CardMap::iterator it_card = mp_card_list_all.find(str_card_id);
	if(it_card != mp_card_list_all.end()){
		card = it_card->second;
	}else{
		isErrorCard = true;
		card = std::make_shared<Card>(str_card_id, msgLocatBuf.TofCardInfo[cardNum].CardType, theApp.z_offset);
		card->is_registered = false;
		//mp_card_list_all.insert(make_pair(card->card_id,card));
	}
	// 设置当前分站， 进入分站时间、进入区域时间，当前区域，当前地图
	std::shared_ptr<Reader> pReader(it->second);
	int n = it->second.use_count();
	card->set_reader(pReader);
	card->reader_tickcount = pReader->tick_count;
	card->time_stamp = msgLocatBuf.TofCardInfo[cardNum].MsgSerialNum;
	card->ranging_type = msgLocatBuf.TofCardInfo[cardNum].MsgType_BatterInfo & 0x0f;
	card->power_state = (msgLocatBuf.TofCardInfo[cardNum].MsgType_BatterInfo >> 4) & 0x0f;
	card->accelerate_state = msgLocatBuf.TofCardInfo[cardNum].AccelerateSpeed;
	card->flying_time = flyTime;
	//card->antenna_id = ((msgLocatBuf.TofCardInfo[cardNum].AntNum & 0xFF) == 1) ? 0 : 1;
	card->antenna_id = (msgLocatBuf.TofCardInfo[cardNum].AntNum & 0xFF) - 1;
	card->distance = dist;
	card->is_hist = false;
	card->state_moving = 1;
	return card;
}

int CYAServerDlg::parse_data_signal_lamp_req_status(BYTE * DataBuffer, int& nCurPos, CONNID dwConnID, uint32_t& id)
{
	DWORD dwLightID = 0;
	CFunctions::getDWord(DataBuffer,&dwLightID,nCurPos);
	nCurPos += sizeof(DWORD);
	id = dwLightID;

	BYTE deveiceType = 0;
	memcpy(&deveiceType,&DataBuffer[nCurPos],sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	std::string ip = "";
	ip = get_ip_by_id(dwConnID);

	auto it = m_carmanage->getPhysicsTrafficLightId(dwLightID);
	for (auto it_light : it)
	{
		auto it_traffic_light = m_carmanage->getTrafficLight(it_light);
		it_traffic_light->m_ip = ip;
	}

	if (m_log_parse_data)
	{
		char log[MAX_LOG_LENGTH] = {0};
		sprintf_s(log,"[traffic light request status] light_id: %d, device_type: %d",dwLightID,deveiceType);
		Log::write_log(FILE_TYPE::PARSE_LIGHT_S,log,true);
	}
	return 0;
}

void CYAServerDlg::send_signal_lamp_status(const uint32_t& id)
{
	auto it_lights = m_carmanage->getPhysicsTrafficLightId(id);
	if (it_lights.empty())
	{
		return;
	}

	std::shared_ptr<op::TrafficLight> pFirstLight = m_carmanage->getTrafficLight(it_lights[0]);
	std::shared_ptr<op::TrafficLight> pSecondLight = m_carmanage->getTrafficLight(it_lights[1]);

	std::string ip = pFirstLight==nullptr?pSecondLight->getip():pFirstLight->getip();
	if (nullptr == pFirstLight || nullptr == pSecondLight)
	{
		debug_print_syslog(0,"[traffic light] send status to light is failed.");
		return;
	}

	BYTE buf[LENGTH_SEND_BUF];
	memset(buf,0,LENGTH_SEND_BUF*sizeof(BYTE));
	SocketMap::iterator it_sock = mp_socket_list.end();
	it_sock = mp_socket_list.find(CFunctions::c2wc(ip.c_str()));
	if (it_sock == mp_socket_list.end())
	{
		return;
	}

	uint8_t npos = 0;
	CFunctions::memcpyDWord(&buf[0], id, npos);		  // 设备id号
	npos+=sizeof(DWORD);

	BYTE deviceType = (BYTE)(DEVICE_TYPE::DT_LIGHT);
	memcpy(&buf[npos], &deviceType, sizeof(BYTE));			  // 设备类型
	npos += sizeof(BYTE);

	LIGHT_SHAPE postiveColor = INIT_SHAPE;
	LIGHT_SHAPE negativeColor = INIT_SHAPE;

	if (pFirstLight->m_physics_direction == 1)
	{
		postiveColor = get_light_sharp(pFirstLight->getState());
	}else{
		negativeColor = get_light_sharp(pFirstLight->getState());
	}

	if (pSecondLight->m_physics_direction == 1)
	{
		postiveColor = get_light_sharp(pSecondLight->getState());
	}else{
		negativeColor = get_light_sharp(pSecondLight->getState());
	}

	memcpy(&buf[npos], &postiveColor, sizeof(BYTE));				  // 正面形状
	npos += sizeof(BYTE);

	memcpy(&buf[npos], &negativeColor, sizeof(BYTE));				  // 反面形状
	npos += sizeof(BYTE);

	BOOL ret = SendData(it_sock->second->dwConnID,REQ_SIGNAL_LAMP_STATUS, npos, buf);
	if (ret)
	{
		char log[MAX_LOG_LENGTH] = {0};
		sprintf_s(log,
			"[response req: send traffic light current status] light_id: %d, postive_sharp: %d, negative_sharp: %d", id, postiveColor, negativeColor);
		Log::write_log(FILE_TYPE::PARSE_LIGHT_S,log,true);
	}
}

unsigned long long  CYAServerDlg::parse_data_locate_card(BYTE* DataBuffer, int& nCurPos, int reader_id, unsigned short wChr,unsigned long long ct_count /*=0*/,int pos_num /*=0*/)
{
	//debug_print_syslog(0,"enter parse_data_locate_card: %s %d",__FILE__,__LINE__);
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_18);
	ReaderMap::iterator it = mp_reader_list.find(reader_id);
	if (it == mp_reader_list.end())
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_70);
		return 1;  // 可能会死循环
	}
	// 卡类型
	BYTE btCardType = 0;
	memcpy(&btCardType, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	// 卡号
	DWORD dwCardId;
	CFunctions::getDWord(DataBuffer, &dwCardId, nCurPos);
	nCurPos += sizeof(DWORD);

#ifdef _DEBUG
	//TRACE(_T("card_id : %d.\n"),dwCardId);
#endif
	// 获取标识卡编号, 3位卡类型 + 10位卡号
	string str_card_id = CFunctions::getstrwithzero(btCardType, 3) + CFunctions::getstrwithzero(dwCardId, 10);

	std::shared_ptr<Card> card = nullptr;
	bool isErrorCard = false;
	//TRACE(str_card_id.c_str());
	//TRACE(_T("\n"));
	CardMap::iterator it_card = mp_card_list_all.find(str_card_id);
	if(it_card != mp_card_list_all.end()){
		card = it_card->second;
	}else{
		isErrorCard = true;
		card = std::make_shared<Card>(str_card_id, btCardType, theApp.z_offset);
		card->is_registered = false;
		card->set_reader_path(mp_reader_path_list_tof, mp_reader_path_list_tdoa);
		//mp_card_list_all.insert(make_pair(card->card_id,card));
	}
	// 设置当前分站， 进入分站时间、进入区域时间，当前区域，当前地图
	std::shared_ptr<Reader> pReader(it->second);
	card->set_reader(pReader);
	card->reader_tickcount = pReader->tick_count;
	card->is_hist = false;
	//add by lemon At 2017/10/24
	card->m_ct_time = ct_count - 1000 + pos_num*45;
	card->m_positon = pos_num;
	card->m_nCardId = dwCardId;

	parse_data_locate_card_vehicle(DataBuffer, nCurPos, card, wChr);

	debug_print_syslog(0,"[2lemon1%s]",card->card_id.c_str());
	card->no_need_add_dist = false;
	deal_card_msg(card);
	
	//debug_print_syslog(0,"leave parse_data_locate_card: %s %d",__FILE__,__LINE__);
	return 0;
}

/*

* 解析移动分站号以及移动分站号所带卡的数据
*
* author & date
*		zhuyf 2017/10/18
*
* param
*		DataBuffer
*		nCurPos
*		nLen
*		dwConnID
*		reader_id
*
* return
*		成功返回0，否则返回非零值
*
*/
int CYAServerDlg::parse_data_moving_reader(BYTE * DataBuffer, int& nCurPos, int nLen, CONNID dwConnID, int& reader_id)
{
	//解析完一个移动分站所有卡的数据后，进行一次人上车业务处理，循环之，
	//因为通信分站可能会一次上传多个移动分站（可能相同）的数据
	//长度,指的是移动分站携带卡数据的长度
	BYTE len;
	len = DataBuffer[nCurPos];
	nCurPos += sizeof(BYTE);

	// 移动分站号
	DWORD dwReaderID;
	CFunctions::getDWord(DataBuffer, &dwReaderID, nCurPos);
	nCurPos += sizeof(DWORD);

	MovingReaderMap::iterator it = mp_moving_reader_list->find(dwReaderID);
	std::shared_ptr<MovingReader> pMovingReader = nullptr;
	if (it == mp_moving_reader_list->end())
	{
		//如果移动分站号在数据库不存在，则创建新的对象
		pMovingReader = std::make_shared<MovingReader>();
		//关联的车卡默认不存在
		pMovingReader->pVehicleCard = nullptr;
#if ENABLE_DEBUG_PERSON_IN_CAR_LOG
		char debug_log[MAX_LOG_LENGTH];
		memset(debug_log,0,MAX_LOG_LENGTH*sizeof(char));
		sprintf_s(debug_log,"reader: %d is not exist.please check the configuration of dat_moving_reader's table.",dwReaderID);
		Log::write_log(SYS_S,debug_log,true);
#endif
	}else{
		pMovingReader = it->second;
	}
	pMovingReader->moving_reader_id = dwReaderID;

	int start_pos = nCurPos;
	//解析此移动分站收到的所有车卡,数据长度减去(四字节的移动分站的数据）
	while(nCurPos - start_pos < len - sizeof(DWORD)){//
		if (parse_data_moving_reader_card(DataBuffer, nCurPos, dwReaderID)){
			break;
		}
	}

	//如果移动分站对应的车卡存在，则走如下逻辑判断人是否上车
	if (pMovingReader->pVehicleCard)
	{
		deal_relationship_between_person_and_vehicle(pMovingReader);
	}

	return 0;
}

/*
 
* 解析移动分站上传的所有人卡数据
* author & date
*		zhuyf 2017/10/18
*
* param
*		DataBuffer			原始数据区
*		nCurPos				原始数据其实位置
*		reader_id			移动分站号
*
* return
*		成功返回0，失败返回非零值
*
*/
int CYAServerDlg::parse_data_moving_reader_card(BYTE* DataBuffer, int& nCurPos, int reader_id)
{
	// 卡号 byte*2
	WORD cardId;
	CFunctions::getWord(DataBuffer, &cardId, nCurPos);
	nCurPos += sizeof(WORD);
	// 这里指定接收的是人卡
	string str_card_id = CFunctions::getstrwithzero(CT_PERSON, 3) + CFunctions::getstrwithzero(cardId, 10);

	// 卡时间戳 byte*2
	WORD timeStamp;
	CFunctions::getWord(DataBuffer, &timeStamp, nCurPos);
	nCurPos += sizeof(WORD);

	// 卡定位时间戳 byte*5
	LONG64 lTime1 = 0;
	BYTE btTemp = 0;
	int nRangingPos = nCurPos;
	memcpy(&btTemp, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	DWORD dwTemp = 0;
	CFunctions::getDWord(DataBuffer, &dwTemp, nCurPos);
	nCurPos += sizeof(DWORD);
	lTime1 = btTemp;
	lTime1 = lTime1 << 32;
	lTime1 |=  ((long long)dwTemp & 0xffffffff);
	// 距离
	double dldist = 0;

	CardMap::iterator it_card = mp_card_list_all.end();
	it_card = mp_card_list_all.find(str_card_id);
	if (it_card != mp_card_list_all.end())
	{
		// 人卡存在，获得人卡的ct号
		it_card->second->time_stamp = timeStamp;
		// 计算测距的距离信息
		dldist = it_card->second->distance = CFunctions::getDistance(lTime1,CFunctions::TOF);	

		// 查找此移动分站是否存在
		MovingReaderMap::iterator it_moving_reader = mp_moving_reader_list->find(reader_id);
		if (it_moving_reader != mp_moving_reader_list->end())
		{
			// 移动分站存在,将此卡信息放入到移动分站所获得的列表中
			// 先检查此卡是否在移动分站内
			CardMap::iterator it_person_card = it_moving_reader->second->mp_person_card.end();
			it_person_card = it_moving_reader->second->mp_person_card.find(it_card->first);	//123456789
			if (it_person_card == it_moving_reader->second->mp_person_card.end())
			{
				// 人卡原来不在移动分站的人员列表中，加入此人卡
				it_card->second->recevie_by_moving_reader = 0;	//重置0
				it_moving_reader->second->mp_person_card.insert(std::make_pair(it_card->first,it_card->second));
			}
			// 更新人卡的数据：接收时间，并统计此人卡接收的次数
			it_card->second->rec_time = time_t(NULL);
			it_card->second->recevie_by_moving_reader++;
		}
	}

	if (m_log_parse_data)
	{
		char chLog[MAX_LOG_LENGTH];
		memset(chLog,0,MAX_LOG_LENGTH*sizeof(char));
		sprintf_s(chLog,"moving_reader_id: %d, card_id: %s, ct: %d, distance: %.3f",reader_id,str_card_id.c_str(),timeStamp,dldist);
		Log::write_log(FILE_TYPE::MOVING_READER_PARSE_DATA,chLog,true);
	}

	return 0;
}
/*
* 从工作面排班表中获取计划开机时间更新开机表中的字段
*
* param
*       cardType                          车卡类型
*		scheduleStartupTime               工作面排班表记录的开机时间
*       nCardId                           车卡ID
*       strDate                           日期
* return
*       无
*/
void CYAServerDlg::get_schedulestartuptime(int cardType, std::string strCard, double &scheduleStartupTime,std::string strDate)
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	// 查计划开机时间
	if(CT_COALMINING_MACHINE == cardType)
	{
		//sprintf_s(strsql,LENGTH_SQL,"SELECT b.schedule_startup_time FROM dat_coalface_vehicle a, dat_workface_scheduling b, dat_vehicle_extend c  "
			//"WHERE  b.workface_type = 1 and b.workface_id = a.coalface_id and a.vehicle_id = c.vehicle_id and c.card_id = %s and b.schedule_date='%s';",strCard.c_str(),strDate.c_str());

		sprintf_s(strsql,LENGTH_SQL,"SELECT schedule_startup_time FROM dat_workface_scheduling"  
			"WHERE schedule_date='%s'" 
			"and workface_id = (select coalface_id from dat_coalface_vehicle"
			"where vehicle_id = (select vehicle_id from dat_vehicle_extend"
			"where card_id = %s));",strCard.c_str(),strDate.c_str());
		scheduleStartupTime = 0.0; // 采煤机计划开机时间数据库未配置，默认取0
	}
	else if(CT_TUNNELBORING_MACHINE == cardType)
	{
		//sprintf_s(strsql,LENGTH_SQL, "SELECT b.schedule_startup_time FROM dat_drivingface_vehicle a, dat_workface_scheduling b, dat_vehicle_extend c  "
			//"WHERE  b.workface_type = 2 and b.workface_id = a.drivingface_id and a.vehicle_id = c.vehicle_id and c.card_id = %s and b.schedule_date='%s';",strCard.c_str(),strDate.c_str());

		sprintf_s(strsql,LENGTH_SQL, "SELECT schedule_startup_time FROM dat_workface_scheduling"  
			"WHERE schedule_date='%s'" 
			"and workface_id = (select drivingface_id from dat_drivingface_vehicle"
		    "where vehicle_id = (select vehicle_id from dat_vehicle_extend"
		    "where card_id = %s));",strCard.c_str(),strDate.c_str());
		scheduleStartupTime = 0.0; // 掘进机计划开机时间数据库未配置，默认取0
	}
	else
		return;
	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return ;
	}
	pRow = mysql_fetch_row(pRes);
	if(pRow)
	{
		scheduleStartupTime = atof(pRow[0]);
	}
	mysql_free_result(pRes);
	return ;

}

std::string CYAServerDlg::get_json_vehicle_state()
{
	Json::Value root;
	Json::Value data;
	std::string ret = "";
	
	auto it_card = mp_coaldringface_card_list.begin();
	for(;it_card != mp_coaldringface_card_list.end(); it_card++) 
	{
		Json::Value meta;
		int nState = it_card->second->m_bOpen;
		std::string sCard = it_card->second->card_id;
		meta.append(sCard);
		meta.append(nState);
		data.append(meta);
	}
	if(data.size() > 0){
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_VEHICLE_STATE;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION;
		root[JSON_ROOT_KEY_DATA] = data;
		ret = root.toFastString();
	}
	return ret;
}
/*
* 开机存库
*
* param
*       card                          采煤机/掘进机车卡
* return
*       无
*/
void CYAServerDlg::open_machine(std::shared_ptr<Card> card)
{
	card->m_bOpen = true;
	auto it_drivingface_card = mp_driving_face_card_list.find(card->card_id);
	if (it_drivingface_card != mp_driving_face_card_list.end())
	{
		it_drivingface_card->second->m_cur_state = true;
		if (!it_drivingface_card->second->m_old_state && it_drivingface_card->second->m_cur_state)
		{
			set_reader_simulate_status(it_drivingface_card->second->m_small_reader_id,false);
			set_reader_simulate_status(it_drivingface_card->second->m_relay_small_reader_id,false);
			/*auto it_reader = mp_reader_list.find(it_drivingface_card->second->m_small_reader_id);
			if(it_reader != mp_reader_list.end()){
			it_reader->second->b_simulation_status = false;
			debug_print_syslog(0,"[simulator card: turn off simulate card when drivingface machine turn on] card_id: %s, reader_id: %d, old_state: %d, cur_state: %d, simulate_status: %d.",
			card->card_id.c_str(),
			it_reader->second->reader_id,
			it_drivingface_card->second->m_old_state,
			it_drivingface_card->second->m_cur_state,
			it_reader->second->b_simulation_status);
			}
			it_reader = mp_reader_list.end();
			it_reader = mp_reader_list.find(it_drivingface_card->second->m_relay_small_reader_id);
			if(it_reader != mp_reader_list.end()){
			it_reader->second->b_simulation_status = false;
			debug_print_syslog(0,"[simulator card: turn off simulate card when drivingface machine turn on] card_id: %s, reader_id: %d, old_state: %d, cur_state: %d, simulate_status: %d.",
			card->card_id.c_str(),
			it_reader->second->reader_id,
			it_drivingface_card->second->m_old_state,
			it_drivingface_card->second->m_cur_state,
			it_reader->second->b_simulation_status);
			}*/
		}
		it_drivingface_card->second->m_old_state = it_drivingface_card->second->m_cur_state;
	}

	time_t tCurTime = time(NULL);
	card->m_startup_time = tCurTime;
	std::string strStartTime = CFunctions::time_t2string(card->m_startup_time);

	// 从工作面排班表中获取计划开机时间
	double scheduleStartupTime = 0.0;
	int deptId = card->dept_id;
	//int nVehicleID = m_card_vehicle[card->card_id];
	int nWorkfaceID = -1;
	auto it_map_workface = m_card_workface.find(card->card_id);
	if(it_map_workface != m_card_workface.end())
	{
		nWorkfaceID = m_card_workface[card->card_id];
	}
	
	std::string strDate = strStartTime.substr(0,10);  // 截取日期字符串前10位	
	get_schedulestartuptime(card->card_type, card->card_id, scheduleStartupTime, strDate);

	//debug_print_syslog(0,"open_machine time: %s, card: %s ,reader: %d,scheduleTime: %.3f, deptId: %d, open state: %d",
	//	strStartTime.c_str(), card->card_id.c_str(),card->reader_id,scheduleStartupTime,deptId,card->m_bOpen);

	char sql[LENGTH_SQL] = { 0 };
	sprintf_s(sql, LENGTH_SQL, 
		"INSERT IGNORE INTO his_startup_detail(work_face_id, start_up_time,schedule_work_time,dept_id) VALUES(%d, '%s',%.3f,%d);",  
		nWorkfaceID,strStartTime.c_str(),scheduleStartupTime,deptId);

	std::string Error;
	std::string strUptSQL;
	strUptSQL = sql;
	if ( sDBConnPool.ExecuteSql( strUptSQL.c_str(), Error ) < 0 )
	{
		debug_print_syslog(0,"open_machine Err：Failed to ExecuteSql:%s,Err=%s\n", strUptSQL.c_str(), Error.c_str());
	}

	//debug_print_syslog(0,"open_machine Insert, SQL: %s",sql);
	char chLog[MAX_LOG_LENGTH] = {0};
	std::string log = "";
	sprintf_s(chLog,"open_machine time: %s,card: %s,open state: %d,scheduleTime: %.3f,deptId: %d,Update: %s",
		strStartTime.c_str(),card->card_id.c_str(), card->m_bOpen,scheduleStartupTime,deptId,sql);
	log = chLog;
	Log::write_log(FILE_TYPE::STARTUP_RATIO,log,true);
}

/*
* 关机存库
*
* param
*       card                          采煤机/掘进机车卡
*       bTimeOut                      关机类型（默认是超时关机）
* return
*       无
*/
void CYAServerDlg::close_machine(std::shared_ptr<Card> card, bool bTimeOut)
{
	card->m_bOpen = false;
	//add by zhuyf 实现让小分站切换为车卡模式
	auto it_drivingface_card = mp_driving_face_card_list.find(card->card_id);
	if (it_drivingface_card != mp_driving_face_card_list.end())
	{
		it_drivingface_card->second->m_cur_state = false;
		if ((it_drivingface_card->second->m_old_state && !it_drivingface_card->second->m_cur_state))
		{
			set_reader_simulate_status(it_drivingface_card->second->m_small_reader_id,true);
			set_reader_simulate_status(it_drivingface_card->second->m_relay_small_reader_id,true);
			/*auto it_reader = mp_reader_list.find(it_drivingface_card->second->m_small_reader_id);
			if(it_reader != mp_reader_list.end()){
			it_reader->second->b_simulation_status = true;
			debug_print_syslog(0,"[simulator card: turn on simulate card when drivingface machine turn off] card_id: %s, old_state: %d, cur_state: %d, simulate_status: %d.",
			card->card_id.c_str(),
			it_reader->second->reader_id,
			it_drivingface_card->second->m_old_state,
			it_drivingface_card->second->m_cur_state,
			it_reader->second->b_simulation_status);
			}
			it_reader = mp_reader_list.end();
			it_reader = mp_reader_list.find(it_drivingface_card->second->m_relay_small_reader_id);
			if(it_reader != mp_reader_list.end()){
			it_reader->second->b_simulation_status = true;
			debug_print_syslog(0,"[simulator card: turn on simulate card when drivingface machine turn off] card_id: %s, old_state: %d, cur_state: %d, simulate_status: %d.",
			card->card_id.c_str(),
			it_reader->second->reader_id,
			it_drivingface_card->second->m_old_state,
			it_drivingface_card->second->m_cur_state,
			it_reader->second->b_simulation_status);
			}*/
		}
		it_drivingface_card->second->m_old_state = it_drivingface_card->second->m_cur_state;
	}

	char sql[LENGTH_SQL] = { 0 };
	time_t tCurTime = time(NULL);
	if(bTimeOut)  // 超时关机，因为延时值不是有效开机时间，需减去延时值
	{
		tCurTime -= theApp.shutdown_timeout_threshold;
	}
	std::string strCurTime = CFunctions::time_t2string(tCurTime);
	std::string strStartTime = CFunctions::time_t2string(card->m_startup_time);
	//int nVehicleID = m_card_vehicle[card->card_id];
	int nWorkfaceID = -1;
	auto it_map_workface = m_card_workface.find(card->card_id);
	if(it_map_workface != m_card_workface.end())
	{
		nWorkfaceID = m_card_workface[card->card_id];
	}
	double timeInterval = (tCurTime - card->m_startup_time)/SEC_TO_HOUR;

	sprintf_s(sql, LENGTH_SQL, "Update his_startup_detail set shut_down_time ='%s',real_startup_time=%.3f, proc_tag = 1 where start_up_time='%s' and work_face_id=%d;",  
		strCurTime.c_str(),timeInterval, strStartTime.c_str(),nWorkfaceID);

	std::string Error;
	std::string strUptSQL;
	strUptSQL = sql;
	if ( sDBConnPool.ExecuteSql( strUptSQL.c_str(), Error ) < 0 )
	{
		debug_print_syslog(0,"close_machine Err：Failed to ExecuteSql:%s,Err=%s\n", strUptSQL.c_str(), Error.c_str());
	}

	//debug_print_syslog(0,"close_machine time: %s, open state: %d, Update: %s",strCurTime.c_str(), card->m_bOpen,sql);
	char chLog[MAX_LOG_LENGTH] = {0};
	std::string log = "";
	sprintf_s(chLog,"close_machine time: %s, open state: %d, Update: %s",strCurTime.c_str(), card->m_bOpen,sql);
	log = chLog;
	Log::write_log(FILE_TYPE::STARTUP_RATIO,log,true);

	// 循环队列置位
	for (int index = 0; index < card->m_cb_state.size(); index++)
	{
		card->m_cb_state[index] = 0;
	}
}

/*
* 重启时处理未更新关机时间的记录
*
* param
*      无
* return
*		函数正常执行返回0，否则返回1
*/
int CYAServerDlg::restart_update_unprocess_record()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	char strsql[LENGTH_SQL] = {0};	
	//sprintf_s(strsql,LENGTH_SQL, "SELECT vehicle_id,start_up_time FROM his_startup_detail WHERE proc_tag=0;");
	sprintf_s(strsql,LENGTH_SQL, "SELECT work_face_id,start_up_time FROM his_startup_detail WHERE proc_tag=0;");
	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		char chLog[MAX_LOG_LENGTH] = {0};
		std::string log = "";
		sprintf_s(chLog,"restart_update_unprocess_record select no record!");
		log = chLog;
		Log::write_log(FILE_TYPE::STARTUP_RATIO,log,true);
		return 1;
	}
	while(pRow = mysql_fetch_row(pRes))
	{
		// 局部变量初始化
		int nCardId = 0;
		std::string strStartTime = "";
		// 取数据表记录
		nCardId = atoi(pRow[0]);
		strStartTime = pRow[1];
		// 时间处理
		time_t tCurTime = time(NULL);
		std::string strCurTime = CFunctions::time_t2string(tCurTime);
		time_t tStartTime = CFunctions::string2time_t(strStartTime);
		double timeInterval = (tCurTime - tStartTime)/SEC_TO_HOUR;
		// 处理未关机的记录，包括重启和零点的情况
		sprintf_s(strsql, LENGTH_SQL, "Update his_startup_detail set shut_down_time ='%s',real_startup_time=%.3f, proc_tag = 1 where start_up_time='%s' and work_face_id=%d;",  
			strCurTime.c_str(),timeInterval, strStartTime.c_str(),nCardId);
		std::string Error;
		std::string strUptSQL;
		strUptSQL = strsql;
		if ( sDBConnPool.ExecuteSql( strUptSQL.c_str(), Error ) < 0 )
		{
			debug_print_syslog(0,"restart_update_unprocess_record Err：Failed to ExecuteSql:%s,Err=%s\n", strUptSQL.c_str(), Error.c_str());
		}
        // 日志
		//debug_print_syslog(0,"restart time: %s, Update: %s",strCurTime.c_str(),strsql);
		char chLog[MAX_LOG_LENGTH] = {0};
		std::string log = "";
		sprintf_s(chLog,"restart_update_unprocess_record time: %s, Update: %s",strCurTime.c_str(),strsql);
		log = chLog;
		Log::write_log(FILE_TYPE::STARTUP_RATIO,log,true);
	}

	mysql_free_result(pRes);
	return 0;
}

/*
* 查找卡对应的车卡号
*
* param
*      无
* return
*		函数正常执行返回0，否则返回1
*/
int CYAServerDlg::bind_card_vehicle()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	// 查卡号对应的车卡号
	sprintf_s(strsql,LENGTH_SQL,"SELECT vehicle_id, card_id FROM dat_vehicle_extend");
	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}
	while(pRow = mysql_fetch_row(pRes))
	{
		int vehicleID = atoi(pRow[0]);
		std::string strCard = pRow[1];
		m_card_vehicle.insert(make_pair(strCard,vehicleID));
	}
	mysql_free_result(pRes);
	return 0;
}

/*
* 查找车卡对应的工作面
*
* param
*      无
* return
*		函数正常执行返回0，否则返回1
*/
int CYAServerDlg::bind_card_workface()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	// 查卡号对应的工作面
	sprintf_s(strsql,LENGTH_SQL,"SELECT b.coalface_id , a.card_id "
		"FROM dat_vehicle_extend a, dat_coalface_vehicle b "
	    "where a.vehicle_id = b.vehicle_id "
		"UNION " 
		"SELECT b.drivingface_id , a.card_id " 
		 "FROM dat_vehicle_extend a, dat_drivingface_vehicle b "
	     "where a.vehicle_id = b.vehicle_id;");
	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}
	while(pRow = mysql_fetch_row(pRes))
	{
		int workfaceID = atoi(pRow[0]);
		std::string strCard = pRow[1];
		strCard = "00" + strCard; 
		m_card_workface.insert(make_pair(strCard,workfaceID));
	}
	mysql_free_result(pRes);
	return 0;
}
/*
* 取车卡震动阈值
*
* param
*      无
* return
*	   无
*/
void CYAServerDlg::get_shakethrethold(std::shared_ptr<Card> card, int& threshold)
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};
	// 查卡号对应的震动阈值
	if(CT_COALMINING_MACHINE == card->card_type)
	{
		sprintf_s(strsql,LENGTH_SQL,"SELECT a.shake_threshold FROM dat_coalface_vehicle a, dat_vehicle_extend b WHERE a.vehicle_id = b.vehicle_id AND b.card_id = %s;",card->card_id.c_str());

	}
	else
	{
		sprintf_s(strsql,LENGTH_SQL,"SELECT a.shake_threshold FROM dat_drivingface_vehicle a, dat_vehicle_extend b WHERE a.vehicle_id = b.vehicle_id AND b.card_id = %s;",card->card_id.c_str());
	}
	
	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return ;
	}
	pRow = mysql_fetch_row(pRes);
	if(pRow)
	{
		threshold = atoi(pRow[0]);
	}
	mysql_free_result(pRes);
}

/*
* 零点时关机再开机
*
* param
*      tCurTime 'xxxx-xx-xx 23:59:59'
* return
*		函数正常执行返回0，否则返回1
*/
int CYAServerDlg::zero_update_unprocess_record(time_t tCurTime)
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	char strsql[LENGTH_SQL] = {0};	
	//sprintf_s(strsql,LENGTH_SQL, 
	//"SELECT a.vehicle_id,a.start_up_time,a.schedule_work_time,a.dept_id,b.card_id FROM his_startup_detail a, dat_vehicle_extend b WHERE a.proc_tag = 0 and a.vehicle_id = b.vehicle_id;");

	sprintf_s(strsql,LENGTH_SQL, 
		"(SELECT a.work_face_id,a.start_up_time,a.schedule_work_time,a.dept_id,f.card_id, a.proc_tag "
		"FROM his_startup_detail a, (select e.card_id, b.coalface_id " 
		"from dat_vehicle_extend e, dat_coalface_vehicle b "
	    "where b.vehicle_id = e.vehicle_id) f "
	    "WHERE a.proc_tag = 0 and  f.coalface_id = a.work_face_id)"
	"union"
		"(SELECT a.work_face_id,a.start_up_time,a.schedule_work_time,a.dept_id,f.card_id, a.proc_tag "
		"FROM his_startup_detail a, (select e.card_id, b.drivingface_id " 
		"from dat_vehicle_extend e, dat_drivingface_vehicle b "
	    "where b.vehicle_id = e.vehicle_id) f "
	    "WHERE a.proc_tag = 0 and  f.drivingface_id = a.work_face_id);");

	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		char chLog[MAX_LOG_LENGTH] = {0};
		std::string log = "";
		sprintf_s(chLog,"zero_update_unprocess_record select no record!");
		log = chLog;
		Log::write_log(FILE_TYPE::STARTUP_RATIO,log,true);
		return 1;
	}
	// 零点分割，开机时间更新到“xxxx-xx-xx 00:00:00”
	time_t tTime = tCurTime + 1;
	while(pRow = mysql_fetch_row(pRes))
	{
		// 局部变量初始化
		int nCardId = 0;
		std::string strStartTime = "";
		double fScheduleWorkTime = 0.0;
		int nDeptId = -1;
		std::string sCardId ="00";
		// 取数据表记录
		nCardId = atoi(pRow[0]);
		strStartTime = pRow[1];
		fScheduleWorkTime = atof(pRow[2]);
		nDeptId = atoi(pRow[3]);
		sCardId += pRow[4];
		// 时间处理
		std::string strCurTime = CFunctions::time_t2string(tCurTime);
		time_t tStartTime = CFunctions::string2time_t(strStartTime);
		double timeInterval = (tCurTime - tStartTime)/SEC_TO_HOUR;
		// 处理未关机的记录
		sprintf_s(strsql, LENGTH_SQL, "Update his_startup_detail set shut_down_time ='%s',real_startup_time=%.3f, proc_tag = 1 where start_up_time='%s' and work_face_id=%d;",  
			strCurTime.c_str(),timeInterval, strStartTime.c_str(),nCardId);
		std::string Error;
		std::string strUptSQL;
		strUptSQL = strsql;
		if ( sDBConnPool.ExecuteSql( strUptSQL.c_str(), Error ) < 0 )
		{
			debug_print_syslog(0,"update_unprocess_record Err：Failed to ExecuteSql:%s,Err=%s\n", strUptSQL.c_str(), Error.c_str());
		}

		char cLog[MAX_LOG_LENGTH] = {0};
		std::string clog = "";
		sprintf_s(cLog,"update_unprocess_record zero time: %s, Update: %s",strStartTime.c_str(),strsql);
		clog = cLog;
		Log::write_log(FILE_TYPE::STARTUP_RATIO,clog,true);

		// 关机后重开
		strStartTime = CFunctions::time_t2string(tTime);
		// 更新卡对应的开机时间
		auto it_card = mp_coaldringface_card_list.find(sCardId);
		if(it_card != mp_coaldringface_card_list.end())
		{
			it_card->second->m_lastrecv_time = tTime;
			it_card->second->m_startup_time = tTime;
		}
		else
		{
			debug_print_syslog(0,"update_unprocess_record Err：Failed to Find vehicle card\n");
		}
		// 零点插入时重新获取计划开机时间
		double zeroScheduleStartupTime = 0.0;
		std::string strDate = strStartTime.substr(0,10);  // 截取日期字符串前10位	
		std::string strType = sCardId.substr(0,3); // 截取卡字符串前3位
		int type = 0;
		if("004" == strType)
		{
			type = CT_COALMINING_MACHINE;
		}
		else if ("005" == strType)
		{
			type = CT_TUNNELBORING_MACHINE;
		}
		else
		{
			debug_print_syslog(0,"zero_update_unprocess_record Err：Wrong card type\n");
		}
		get_schedulestartuptime(type, sCardId, zeroScheduleStartupTime, strDate);


		// 写库
		sprintf_s(strsql, LENGTH_SQL, 
			"INSERT IGNORE INTO his_startup_detail(work_face_id, start_up_time,schedule_work_time,dept_id) VALUES(%d, '%s',%.3f,%d);",  
			nCardId,strStartTime.c_str(),zeroScheduleStartupTime,nDeptId);
		strUptSQL = strsql;
		if ( sDBConnPool.ExecuteSql( strUptSQL.c_str(), Error ) < 0 )
		{
			debug_print_syslog(0,"update_unprocess_record Err：Failed to ExecuteSql:%s,Err=%s\n", strUptSQL.c_str(), Error.c_str());
		}

		//debug_print_syslog(0,"zero time reinsert: %s, Update: %s",strStartTime.c_str(),strsql);
	
		// 日志
		char chLog[MAX_LOG_LENGTH] = {0};
		std::string log = "";
		sprintf_s(chLog,"zero time reinsert: %s, Update: %s",strStartTime.c_str(),strsql);
		log = chLog;
		Log::write_log(FILE_TYPE::STARTUP_RATIO,log,true);
	}

	mysql_free_result(pRes);
	return 0;
}

/*
* 存储采煤机/掘进机开关机时间段到数据库
*
* param
*		card	---		定位卡对象
* return
*		函数正常执行返回0，否则返回1
*/
int CYAServerDlg::store_machine_state(std::shared_ptr<Card> card)
{
	EnterCriticalSection(&m_csCoalDrvingFaceList);
	int bopen = card->m_bOpen;	
	// 分割跨日的开机记录
	time_t tCurTime = time(NULL);
	std::string strCurTime = CFunctions::time_t2string(tCurTime);
	std::string substrCurTime = strCurTime.substr(11,8);  // 截取日期字符串后八位	
	if("23:59:59" == substrCurTime &&  !m_bZero)
	{
		m_bZero = true;
		//debug_print_syslog(0,"store_machine_state zero flow, card: %s, zero time: %s",card->card_id.c_str(), strCurTime.c_str());
		char chLog[MAX_LOG_LENGTH] = {0};
		std::string log = "";
		sprintf_s(chLog,"store_machine_state zero flow, card: %s, zero time: %s",card->card_id.c_str(), strCurTime.c_str());
		log = chLog;
		Log::write_log(FILE_TYPE::STARTUP_RATIO,log,true);
		zero_update_unprocess_record(tCurTime);
	}
	if("00:00:02" == substrCurTime)
	{
		m_bZero = false;  // 后续零点初始化
	}
	if(m_bYAserverBoot) // 采集重启，更新his_startup_detail表中未处理的记录
	{
		m_bYAserverBoot = false;
		bind_card_vehicle();
		bind_card_workface();
		restart_update_unprocess_record();
	}
	if(CT_COALMINING_MACHINE == card->card_type|| CT_TUNNELBORING_MACHINE == card->card_type)
	{
		// 未注册的车卡,直接返回
		auto card_vehicle_it = m_card_vehicle.find(card->card_id);
		if(card_vehicle_it == m_card_vehicle.end())  
		{
			LeaveCriticalSection(&m_csCoalDrvingFaceList);
			return 1;
		}
		//
		string cardId = card->card_id;
		card->m_lastrecv_time = tCurTime;
		auto it_card = mp_coaldringface_card_list.find(cardId);
		if(it_card == mp_coaldringface_card_list.end()) 
		{
			mp_coaldringface_card_list.insert(make_pair(cardId,card));
		}	
		int sum = std::accumulate(card->m_cb_state.begin(), card->m_cb_state.end(), 0);
		//debug_print_syslog(0,"store_machine_state card: %s,card->card_type: %d,startup time: %ld", card->card_id.c_str(),card->card_type,card->m_startup_time);
		//debug_print_syslog(0,"store_machine_state card: %s,open state: %d,cb_sum: %d",card->card_id.c_str(),bopen,sum);

		// 判断采煤机/掘进机惯导开关标记
		int threshold = 1; 
		get_shakethrethold(card,threshold); 
		int openThreshold = STARTUP_STATE_COUNT* threshold;
		if(sum >= openThreshold && !card->m_bOpen)  // 设置为开机，开机的时候insert card_id,start_up_time，schedule_startup_time,dept_id字段
		{
			open_machine(card);
		}
		int closeThreshold = SHUTDOWN_STATE_COUNT * threshold;
		bool bCloseCondition = sum <= closeThreshold && card->m_startup_time != 0 && card->m_bOpen;
		if(bCloseCondition) // 设置为关机,关机的时候update关机时间shut_down_time,real_startup_time字段
		{
			close_machine(card, false);
		}
		LeaveCriticalSection(&m_csCoalDrvingFaceList);
		return 0;
	}
	else
	{
		LeaveCriticalSection(&m_csCoalDrvingFaceList);
		return 1;
	}
}

void CYAServerDlg::parse_data_locate_card_vehicle(BYTE* DataBuffer, int& nCurPos, std::shared_ptr<Card> card /*Card* card*/, unsigned short wChr )
{
	//debug_print_syslog(0,"enter parse_data_locate_card_vehicle: %s %d",__FILE__,__LINE__);
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_22);
	if(LT_READER == theApp.locate_type){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_23);
		card->isdealed = false;
		card->isreceive = true;
		card->issent = false;
	}
	// 报文时间
	WORD wCardTickCount;
	CFunctions::getWord(DataBuffer, &wCardTickCount, nCurPos);
	nCurPos += sizeof(WORD);

	BYTE btTypeAndPower;
	memcpy(&btTypeAndPower, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	//报文类型
	BYTE btType;
	btType = (btTypeAndPower>>4) & 0x0F;
	//电池电量
	BYTE btPower;
	btPower = btTypeAndPower & 0x0F;	//0代表100%，1代表50%，2代表20%

	BYTE btCallType = 0;
	BYTE btAngularVelocity = 0;
	BYTE btState = 0;
	switch (card->card_type)
	{
	case CT_PERSON:
		//呼叫呼救状态位: 0x10全员一般；0x11为全员紧急；0x20为定员一般呼叫；0x21为定员紧急呼叫
		memcpy(&btCallType, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);
		break;
	case CT_VEHICLE:
	case CT_COALMINING_MACHINE:
	case CT_TUNNELBORING_MACHINE:
		//角速度值：间隔1代表3度，有正负区分
		memcpy(&btAngularVelocity, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);
		break;
	default:
		//角速度值：间隔1代表3度，有正负区分
		memcpy(&btAngularVelocity, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);
		break;
	}

	////呼救
	////呼叫呼救状态位
	////0x10全员一般；0x11为全员紧急；
	////0x20为定员一般呼叫；0x21为定员紧急呼叫
	//BYTE btCallType = 0;
	//memcpy(&btCallType, &DataBuffer[nCurPos], sizeof(BYTE));
	//nCurPos += sizeof(BYTE);

	BYTE btAcceleration = 0;
	BYTE btInsStatus = 0;
	float fx = 0.0f;		//惯导上传的x坐标
	float fy = 0.0f;		//惯导上传的y坐标
	bool bHasIns = false;	//是否有惯导数据
	if (RECV_TOF_DATA_AND_INS == wChr)
	{
		//惯导校准状态
		BYTE btVal = 0;
		memcpy(&btVal, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);
		//惯导状态，0正常，1请求校准
		btInsStatus = (btVal>>7)&0x01;

		//如果上传的数据格式是带惯导的tof数据
		bHasIns = true;
		union Float2Dword{
			float fVal;
			BYTE bVal[4];
		}f2d;

		memcpy(f2d.bVal,&DataBuffer[nCurPos],sizeof(float));
		fx = f2d.fVal;
		nCurPos += sizeof(float);
		memcpy(f2d.bVal,&DataBuffer[nCurPos],sizeof(float));
		fy = f2d.fVal;
		nCurPos += sizeof(float);
	}else{
		//加速度,
		//如果是人卡，这里的值表示加速度状态
		//如果是车卡，这里表示加速度值，满足间隔1代表0.01，有正负区分
		if(CT_COALMINING_MACHINE == card->card_type || CT_TUNNELBORING_MACHINE == card->card_type)
		{
			//采煤机/掘进机开关标记 1是开，0是关
			memcpy(&btState, &DataBuffer[nCurPos], sizeof(BYTE));
			
			char chLog[MAX_LOG_LENGTH] = {0};
			std::string log = "";
			sprintf_s(chLog,"%s, %d", card->card_id.c_str(), btState);
			log = chLog;
			Log::write_log(FILE_TYPE::VIBRATE_S ,log,true);

			btAcceleration = btState;
			card->m_cb_state.push_back(btState);
			nCurPos += sizeof(BYTE);	
	//		debug_print_syslog(0,"store_machine_state cb1=%d , cb2=%d, cb3=%d, cb4=%d, cb5=%d, cb6=%d , cb7=%d, cb8=%d, cb9=%d, cb10=%d", 
		//		card->m_cb_state[0],card->m_cb_state[1],card->m_cb_state[2],card->m_cb_state[3],card->m_cb_state[4],card->m_cb_state[5],
			//	card->m_cb_state[6],card->m_cb_state[7],card->m_cb_state[8],card->m_cb_state[9]);
		}
		else
		{
			memcpy(&btAcceleration, &DataBuffer[nCurPos], sizeof(BYTE));
			nCurPos += sizeof(BYTE);
		}
	}
	if (CT_COALMINING_MACHINE == card->card_type|| CT_TUNNELBORING_MACHINE == card->card_type)
	{
		store_machine_state(card);
	}

	//定位时间戳Tsp // 字序
	LONG64 lTime1 = 0;
	BYTE btTemp = 0;
	int nRangingPos = nCurPos;
	memcpy(&btTemp, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	DWORD dwTemp = 0;
	CFunctions::getDWord(DataBuffer, &dwTemp, nCurPos);
	nCurPos += sizeof(DWORD);
	lTime1 = btTemp;
	lTime1 = lTime1 << 32;
	lTime1 |=  ((long long)dwTemp & 0xffffffff);
	// 距离
	double dldist = 0;
	// 天线
	BYTE btAntenna;
	memcpy(&btAntenna, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	//TRACE(_T("ct: %d, antenna : %d\r\n"),wCardTickCount,btAntenna);

	WORD wSyncNum = 0;
	WORD wStrength = 0;
	WORD wRxpacc = 0;
	double recv_signal_power = 0.0;
	//modify by zhuyf 2018/04/16
	//if(CHAR_LOCATEDATA_TDOA == wChr){
	if (CHAR_LOCATEDATA_TDOA == wChr ||
		CHAR_LOCATEDATA_TDOA_EXTEND == wChr || 
		CHAR_LOCATEDATAHIS_TDOA_EXTEND == wChr)
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_24);
		// 分站时间同步序列号 
		CFunctions::getWord(DataBuffer, &wSyncNum, nCurPos);
		nCurPos += sizeof(WORD);
		// 信号强度		
		CFunctions::getWord(DataBuffer, &wStrength, nCurPos);
		nCurPos += sizeof(WORD);

	}else if(CHAR_LOCATEDATA == wChr){
		dldist = CFunctions::getDistance(lTime1, CFunctions::TOF);
		if(-1 == dldist)
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_71);
		}
	}
	else if(CHAR_LOCATEDATA_EXTEND == wChr)
	{
		dldist = CFunctions::getDistance(lTime1, CFunctions::TOF);
		if(-1 == dldist)
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_71);
		}
		// 信号强度
		CFunctions::getWord(DataBuffer, &wStrength, nCurPos);
		nCurPos += sizeof(WORD);

		//接受信号功率
		CFunctions::getWord(DataBuffer, &wRxpacc, nCurPos);
		nCurPos += sizeof(WORD);

		recv_signal_power = 10*log10(wStrength*pow(2,17)/pow(wRxpacc - 64,2)) - 121.74;
	}
	else if (RECV_TOF_DATA_AND_INS == wChr)
	{
		//如果上传的数据格式是带惯导的tof数据
		bHasIns = true;
		//计算距离
		dldist = CFunctions::getDistance(lTime1, CFunctions::TOF);
		//保存惯导请求校准状态：0为正常，即是tof数据可以进行定位，1为请求校准
		card->ins_request_check = btInsStatus;
		if (LOCATEDATATYPE::LDT_TDOA_INS == btType)
		{
			//如果输出惯导坐标，则保存惯导坐标
			if (card->cur_ins_pos == nullptr)
			{
				card->cur_ins_pos = std::make_shared<POS>();
			}
			card->cur_ins_pos->posx = fx;
			card->cur_ins_pos->posy = fy;
		}
	}

	//add by zhuyf ,2018/04/11
	//tdoa协议增加信号功率解析和计算
	if (CHAR_LOCATEDATA_TDOA_EXTEND == wChr || CHAR_LOCATEDATAHIS_TDOA_EXTEND == wChr)
	{
		// 信号强度
		CFunctions::getWord(DataBuffer, &wStrength, nCurPos);
		nCurPos += sizeof(WORD);

		//接受信号功率
		CFunctions::getWord(DataBuffer, &wRxpacc, nCurPos);
		nCurPos += sizeof(WORD);

		recv_signal_power = 10*log10(wStrength*pow(2,17)/pow(wRxpacc - 64,2)) - 121.74;
	}

	//如果是tof的车卡数据，保留字节数据为角速度值，加速度状态值为加速度值
	if ((CT_VEHICLE == card->card_type || CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type)
		&& CHAR_LOCATEDATA_EXTEND == wChr)
	{
		int flag = 0;
		int sign = 0;
		flag = btAngularVelocity>>7;
		switch (flag)
		{
		case 0:
			sign = 1;
			break;
		case 1:
			sign = -1;
			break;
		default:
			break;
		}
		int value = 0;
		double dv = 0.0;
		value = btAngularVelocity&0x7F;
		dv = value*sign*3;
		card->pGyroscopeSensor->SetValue(dv);

		flag = 0;
		sign = 0;
		flag = btAcceleration>>7;
		switch (flag)
		{
		case 0:
			sign = 1;
			break;
		case 1:
			sign = -1;
			break;
		default:
			break;
		}
		value = 0;
		dv = 0.0;
		value = btAcceleration&0x7F;

		dv = value* sign * 0.01;
		card->pAcceSensor->SetValue(dv);
	} 
	else
	{
		card->accelerate_state = btAcceleration;
		card->pAcceSensor->SetValue(0);
		card->pGyroscopeSensor->SetValue(0);
	}

	if(LT_COORDINATE == theApp.locate_type){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_25);
		if(card->time_stamp != wCardTickCount)
		{
			card->time_stamp_last = card->time_stamp;
		}
		card->time_stamp = wCardTickCount;
		card->ranging_type = btType;
		card->power_state = btPower;
		card->call_type_id = btCallType;
		if (btCallType != 0)
		{
			card->vt_deal_call_reader_id.push_back(card->reader_id);
			btCallType &= 0x80;
			if (btCallType == 0x80)
			{
				if(PDT_DOWN == card->p_reader->pos_state)
				{
					debug_print_syslog(0,"[lemon_call_help]%s,%d",card->card_id.c_str(),card->status_help);
					//if(card->status_help < 2)
					{
						card->status_help = STATUS_ERROR;
					}
				}
				else
				{
					card->status_help = STATUS_NORMAL;
				}
			}
		}

		card->flying_time = lTime1;
		card->sync_num = wSyncNum;
		card->strength = wStrength;
		card->recv_signal_power = recv_signal_power;
		card->antenna_id = (btAntenna & 0xFF) - 1;
		card->distance = dldist;

		if(m_log_parse_data){
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_26);
			char chlog[MAX_LOG_LENGTH];
			sprintf_s(chlog, "id:%s, n:%d, type:%d, power:%d, acc:%d, ft:%I64u, d:%f, ant:%d, sn:%d, strength:%d, power: %.2f",
				card->card_id.c_str(), wCardTickCount, btType, btPower, btAcceleration, lTime1, dldist, btAntenna, wSyncNum, wStrength,recv_signal_power);
			std::string strlog = chlog;
			Log::write_log(FILE_TYPE::PARSE_CARD_S, strlog, true);
		}
	}else if(LT_READER == theApp.locate_type){
		if(card->time_stamp < 0xFF && card->time_stamp < wCardTickCount){
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_27);
			if(card->time_stamp != wCardTickCount)
			{
				card->time_stamp_last = card->time_stamp;
			}	
			card->time_stamp = wCardTickCount;
			card->ranging_type = btType;
			card->power_state = btPower;
			//card->accelerate_state = btAcceleration;
			card->flying_time = lTime1;
			card->sync_num = wSyncNum;
			//card->antenna_id = ((btAntenna & 0xFF) == 1) ? 0 : 1;
			card->antenna_id = (btAntenna & 0xFF) - 1;
			card->distance = dldist;
		}else if(0xFF == card->time_stamp && wCardTickCount == 0){
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_28);
			if(card->time_stamp != wCardTickCount)
			{
				card->time_stamp_last = card->time_stamp;
			}	
			card->time_stamp = wCardTickCount;
			card->ranging_type = btType;
			card->power_state = btPower;
			card->accelerate_state_last = card->accelerate_state;
			//card->accelerate_state = btAcceleration;
			card->flying_time = lTime1;
			card->sync_num = wSyncNum;
			//card->antenna_id = ((btAntenna & 0xFF) == 1) ? 0 : 1;
			card->antenna_id = (btAntenna & 0xFF) - 1;
			card->distance = dldist;
		}
	}
	//debug_print_syslog(0,"leave parse_data_locate_card_vehicle: %s %d",__FILE__,__LINE__);
}

void CYAServerDlg::parse_data_adhoc( BYTE* DataBuffer, int& nCurPos, int reader_id )
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_29);
	ReaderMap::iterator it = mp_reader_list.find(reader_id);
	if (it == mp_reader_list.end())
	{
		return ;
	}
	BYTE nlen = 0, nDeal = nCurPos;
	//获取自组网数据长度,1字节
	memcpy(&nlen, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	while (nlen > nCurPos - nDeal){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_30);
		//获取命令字，1字节
		BYTE btCmd = 0;
		memcpy(&btCmd, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);
		btCmd = btCmd&0x3F;
		//获取源地址ID，1字节
		BYTE btId = 0;
		memcpy(&btId, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);
		//时间戳，1字节
		BYTE btTickcount = 0;
		memcpy(&btTickcount, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);
		//节点级别，1字节
		BYTE btIdx = 0;
		memcpy(&btIdx, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);

		if(btId != 0){
			string str_card_id = CFunctions::getstrwithzero(CT_ADHOC, 3) + CFunctions::getstrwithzero(btId, 10);
			std::shared_ptr<Card> card = nullptr;
			CardMap::iterator it_card = mp_card_list_all.find(str_card_id);
			if(it_card != mp_card_list_all.end()){
				card = it_card->second;
			}else{
				card = std::make_shared<Card>(str_card_id, CT_ADHOC, theApp.z_offset);
				//mp_card_list_all.insert(make_pair(str_card_id, card));
			}
			CardMap::iterator it_adhoc_card = mp_card_list_down_adhoc.find(str_card_id);
			if(it_adhoc_card==mp_card_list_down_adhoc.end()&&it_card!=mp_card_list_all.end()){
				if(card == NULL){
					mp_card_list_down_adhoc.insert(make_pair(str_card_id, it_card->second));
				}else{
					mp_card_list_down_adhoc.insert(make_pair(str_card_id, card));
				}
			}
			//设置当前分站， 进入分站时间、进入区域时间，当前区域，当前地图
			std::shared_ptr<Reader> pReader(it->second);
			card->set_reader(pReader);
			//card->set_reader(it->second);
			if(btIdx < 0 || btIdx >= ADHOC_COUNT){
				btIdx = 0;
			}
			if(it->second->adhoc[btIdx]){
				card->x = it->second->adhoc[btIdx]->x;
				card->y = it->second->adhoc[btIdx]->y;
				card->z = it->second->adhoc[btIdx]->z;
			}

			if(btCmd & 0x01){ // 呼救
				if(card->status_help < 2)
				{
					card->status_help = STATUS_ERROR;
				}				
			}else if(btCmd & 0x02){ // 呼叫应答，即呼叫成功
				card->status_call = STATUS_NORMAL;
				card->status_help = STATUS_NORMAL;
			}else {
				card->status_call = STATUS_NORMAL;
				card->status_help = STATUS_NORMAL;
			}
			card->issent = false;
			//debug_print_syslog(0,"[3lemon]%s",card->card_id.c_str());
			deal_card_msg(card);
		}
	}
}

void CYAServerDlg::add_socket_to_list(CONNID dwConnID, DWORD reader_id, DEVICE_TYPE rt)
{
	if(m_enState != ST_STARTED){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_38);
		return;
	}
	TCHAR szAddress[40];
	int iAddressLen = sizeof(szAddress) / sizeof(TCHAR);
	USHORT usPort;
	if(	_server.GetRemoteAddress(dwConnID, szAddress, iAddressLen, usPort)){
		SocketMap::iterator itSock = mp_socket_list.find(szAddress);
		if(itSock != mp_socket_list.end()){
			itSock->second->dwConnID = dwConnID;
			//itSock->second->state = 0;
			if (itSock->second->findReader(reader_id))
			{
				auto r = itSock->second->get(reader_id);
				r.reader_id = reader_id;
				r.reader_type = rt;
				r.state = 0;
			}
			else
			{
				ReaderInfo_ r;
				r.reader_id = reader_id;
				r.reader_type = rt;
				r.state = 0;
				itSock->second->m_reader.push_back(r);
				::PostMessage(this->GetSafeHwnd(), WM_REFRESH_IP_LIST, 1, 0);
			}
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_39);
		}else{
			std::shared_ptr<_SOCK> sock = std::make_shared<_SOCK>();
			ReaderInfo_ r;
			sock->sip = szAddress;
			sock->dwConnID = dwConnID;
			r.state = 0;
			r.reader_type = rt;
			r.reader_id = reader_id;
			sock->m_reader.push_back(r);
			mp_socket_list.insert(make_pair(sock->sip, sock));

			TRACE(_T("receive client connectting \r\n"));

			::PostMessage(this->GetSafeHwnd(), WM_REFRESH_IP_LIST, 1, 0);
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_40);
		}
	}
}

int CYAServerDlg::add_socket_to_list(CONNID dwConnID, DWORD reader_id, DEVICE_TYPE rt,BOOL refresh)
{
	if(m_enState != ST_STARTED){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_38);
		return 1;
	}

	TCHAR szAddress[40];
	int iAddressLen = sizeof(szAddress) / sizeof(TCHAR);
	USHORT usPort;
	bool exist = false;
	if(	_server.GetRemoteAddress(dwConnID, szAddress, iAddressLen, usPort)){
		SocketMap::iterator itSock = mp_socket_list.find(szAddress);
		if(itSock != mp_socket_list.end()){
			itSock->second->dwConnID = dwConnID;
			//itSock->second->state = 0;
			if (itSock->second->findReader(reader_id))
			{
				auto r = itSock->second->get(reader_id);
				r.reader_id = reader_id;
				r.reader_type = rt;
				r.state = 0;
			}
			else
			{
				ReaderInfo_ r;
				r.reader_id = reader_id;
				r.reader_type = rt;
				r.state = 0;
				itSock->second->m_reader.push_back(r);
			}
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_39);
		}else{
			std::shared_ptr<_SOCK> sock = std::make_shared<_SOCK>();
			ReaderInfo_ r;
			sock->sip = szAddress;
			sock->dwConnID = dwConnID;
			r.reader_type = rt;
			r.reader_id = reader_id;
			r.state = 0;
			sock->m_reader.push_back(r);
			mp_socket_list.insert(make_pair(sock->sip, sock));

			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_40);
		}
	}

	if (refresh)
	{
		::PostMessage(this->GetSafeHwnd(), WM_REFRESH_IP_LIST, 1, 0);
	}

	return 0;
}

/*
 
* 从连接id获得其ip地址
*
* 参数
*      dwConnID		连接id
*
* 返回值
*		返回连接id的ip地址
*/
std::string CYAServerDlg::get_ip_by_id(const CONNID& dwConnID)
{
	TCHAR szAddress[40];
	int iAddressLen = sizeof(szAddress) / sizeof(TCHAR);
	USHORT usPort;
	string ip = "";
	if(	_server.GetRemoteAddress(dwConnID, szAddress, iAddressLen, usPort)){
		ip = CFunctions::TCHAR2string(szAddress);
	}

	return ip;
}

void CYAServerDlg::remove_socket(CONNID dwConnID )
{
	EnterCriticalSection(&m_csRemoveSocket);
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_41);
	bool bNeedRefresh = false;
	SocketMap::iterator _sock = mp_socket_list.begin();
	while(_sock != mp_socket_list.end()){
		if(_sock->second->dwConnID == dwConnID){
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_42);
			EnterCriticalSection(&m_csParseDataServer);
			TCHAR szAddress[40];
			int iAddressLen = sizeof(szAddress)/sizeof(TCHAR);
			USHORT usPort;
			if (_server.GetRemoteAddress(dwConnID,szAddress,iAddressLen,usPort))
			{
				SocketBufferMap::iterator it = mp_socket_buffer_list.find(szAddress);
				if (it!=mp_socket_buffer_list.end())
				{
					it->second->wLen = 0;
					it->second->wReadLen = 0;
					it->second->dwConnID = dwConnID;
					mp_socket_buffer_list.erase(it);
				}
			}
			LeaveCriticalSection(&m_csParseDataServer);
			//删除之前，判断此连接是否为信号灯控制分站，如果是，则需要将此控制分站所控制的红绿灯的状态设置为不可用
			_sock = mp_socket_list.erase(_sock);
			bNeedRefresh = true;
		}else{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_43);
			++_sock;
		}
	}
	if(bNeedRefresh){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_44);
		::PostMessage(this->GetSafeHwnd(), WM_REFRESH_IP_LIST, 0, 0);
	}
	LeaveCriticalSection(&m_csRemoveSocket);
}

// 获取设备状态信息, 分站、红绿灯、道岔、扩音器
std::string CYAServerDlg::get_json_device_state()
{
	std::string ret = "";
	Json::Value root;	
	Json::Value data;

	MapInfoMap::iterator it_map = mp_map_list.begin();

	for(; it_map != mp_map_list.end(); ++it_map){
		//定位分站列表
		ReaderMap::iterator it_reader = mp_reader_list.begin();
		for (it_reader;it_reader!=mp_reader_list.end();++it_reader)
		{
			if (it_reader->second->map_id != it_map->second->map_id)
			{
				continue;
			}

			if(it_reader->second->reader_state != it_reader->second->reader_state_old || difftime(time(NULL), it_reader->second->last_send_time) > READER_SEND_STATE_TIMEOUT)
			{
				Json::Value state_dev;
				state_dev.append(it_reader->second->reader_id);
				state_dev.append(it_reader->second->device_type_id);
				state_dev.append(it_reader->second->reader_state);
				//入井时间戳
				double t = *((int64_t*)&it_reader->second->rec_time)*ms;
				state_dev.append(t);
				state_dev.append(it_map->second->map_id);
				state_dev.append(it_reader->second->reader_state);
				data.append(state_dev);

				it_reader->second->reader_state_old = it_reader->second->reader_state;
				it_reader->second->last_send_time = time(NULL);
			}
		}

		//通信分站列表
		ReaderMap::iterator it_ctrl_reader = mp_ctrl_reader_list.begin();
		for (it_ctrl_reader;it_ctrl_reader!=mp_ctrl_reader_list.end();++it_ctrl_reader)
		{
			if (it_ctrl_reader->second->map_id != it_map->second->map_id)
			{
				continue;
			}

			//实现增量上报，按时上报
			if(it_ctrl_reader->second->reader_state != it_ctrl_reader->second->reader_state_old || difftime(time(NULL), it_ctrl_reader->second->last_send_time) > READER_SEND_STATE_TIMEOUT)
			{
				Json::Value state_dev;
				state_dev.append(it_ctrl_reader->second->reader_id);
				state_dev.append(it_ctrl_reader->second->device_type_id);
				state_dev.append(it_ctrl_reader->second->reader_state);
				//入井时间戳
				double t = *((int64_t*)&it_ctrl_reader->second->rec_time)*ms;
				state_dev.append(t);
				state_dev.append(it_map->second->map_id);
				state_dev.append(it_ctrl_reader->second->reader_state);
				data.append(state_dev);
				it_ctrl_reader->second->reader_state_old = it_ctrl_reader->second->reader_state;
				it_ctrl_reader->second->last_send_time = time(NULL);
			}
		} 
		//红绿灯
		if (m_carmanage)
		{
			debug_print_syslog(0,"size:%d %s %d",m_carmanage->m_Map.size(),__FILE__,__LINE__);
			
			for (auto it_group :m_carmanage->m_Map)
			{
				Json::Value light_data;
				for (auto it_light : it_group.second->m_pTrafficLight)
				{
					if (difftime(time(NULL), it_light->m_rec_time) > LIGHT_SEND_STATE_TIMEOUT)
					{
						Json::Value state_dev;
						state_dev.append(it_light->m_id);
						state_dev.append(DEVICE_TYPE::DT_LIGHT);
						state_dev.append(get_light_sharp(it_light->getState()));
						double t = 0;
						//最后一次接受信号时间戳
						t = *((int64_t*)&it_light->m_rec_time)*ms;				
						state_dev.append(t);
						state_dev.append(it_map->second->map_id);
						state_dev.append(it_light->getState());
						data.append(state_dev);
						light_data.append(state_dev);
					}
				}
				if(light_data.size() > 0)
				{
					debug_print_syslog(0,"light_state:%s %s %d",light_data.toFastString().c_str(),__FILE__,__LINE__);
				}
			}	
		}
	}

	if (data.size() > 0)
	{
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_DEV_STATE;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION_1_4;
		root[JSON_ROOT_KEY_DATA] = data;
		ret = root.toFastString();
	}

	return ret;
}

int CYAServerDlg::get_help_card_nums()
{
	int nRet = 0;

	//统计自组网卡的呼救
	if (mp_card_list_down_adhoc.size() == 0)
	{
		CardMap::iterator it = mp_card_list_down_adhoc.begin();
		for(it;it!=mp_card_list_down_adhoc.end();++it){
			if(it->second->status_help == STATUS_ERROR){
				nRet++;
			}
		}
	}

	//统计人员的呼救
	if (mp_card_list_down_person.size() == 0)
	{
		CardMap::iterator it = mp_card_list_down_person.begin();
		for(it;it!=mp_card_list_down_person.end();++it){
			if(it->second->status_help == STATUS_ERROR){
				nRet++;
			}
		}
	}

	return nRet;
}

int CYAServerDlg::parse_json_data_reader_pos_change(message::ptr const& data)
{
	init_reader();
	//debug_print_syslog(0, "Init reader postion success.");
	init_drivingface_card();//lemon 2017/07/31
	//debug_print_syslog(0, "Init drivingface render success.");
	return 0;
}

/**/
string CYAServerDlg::parse_json_data_person_on_car(sio::message::ptr const& data)
{
	vector<message::ptr> vt_data = data->get_map()[JSON_ROOT_KEY_DATA]->get_vector();

	std::string user = "";
	if (vt_data.size() <= 0)
	{
		return user;
	}


	vector<message::ptr>::const_iterator it = vt_data.begin();

	user = (*it)->get_string();

	return user;
}

std::string CYAServerDlg::get_json_help()
{
	Json::Value root;
	Json::Value alarms;
	Json::Value adhoc;
	char _time[STR_LEN_TIME];
	struct tm local_time;

	CardMap::iterator it_adhoc = mp_card_list_down_adhoc.begin();

	for(;it_adhoc!=mp_card_list_down_adhoc.end();++it_adhoc){
		if(it_adhoc->second->status_help == STATUS_NORMAL){
			continue;
		}
		if (!need_display_verification(it_adhoc->second))
		{
			continue;
		}
		Json::Value alarm;
		if(it_adhoc->second->status_help == STATUS_ERROR){		
			alarm[JSON_KEY_CARD_ID] = it_adhoc->second->card_id;
			alarm[JSON_KEY_CARD_TYPE_ID] = it_adhoc->second->card_type;
			localtime_s(&local_time, &it_adhoc->second->enter_reader_time);
			strftime(_time, STR_LEN_TIME, "%Y-%m-%d %H:%M:%S", &local_time);
			alarm["start_time"] = _time;
		}
		if(!alarm.isNull()){
			alarms.append(alarm);
		}
	}

	for(CardMap::iterator it_person = mp_card_list_down_person.begin();it_person!=mp_card_list_down_person.end();++it_person){
		if(it_person->second->status_help == STATUS_NORMAL){
			continue;
		}
		if (!need_display_verification(it_person->second))
		{
			continue;
		}
		Json::Value alarm;
		if(it_person->second->status_help == STATUS_ERROR){		
			alarm[JSON_KEY_CARD_ID] = it_person->second->card_id;
			alarm[JSON_KEY_CARD_TYPE_ID] = it_person->second->card_type;
			localtime_s(&local_time, &it_person->second->enter_reader_time);
			strftime(_time, STR_LEN_TIME, "%Y-%m-%d %H:%M:%S", &local_time);
			alarm["start_time"] = _time;
		}
		if(!alarm.isNull()){
			alarms.append(alarm);
		}
	}

	if(!alarms.isNull()){
		root[JSON_ROOT_KEY_CMD] = "helpme_req";
		root[JSON_ROOT_KEY_DATA] = alarms; 
	}
	return root.toFastString();
}

Json::Value CYAServerDlg::get_section_json_alarm()
{	
	int nTotals = 0;

	Json::Value sections;
	Json::Value data;

	sections[JSON_ROOT_KEY_CMD]   = JSON_KEY_ALARM_SECTION;

	SectionMap::iterator it = mp_section_list.begin();
	for (;it != mp_section_list.end(); ++it)
	{
		//正常路段不报警
		if (it->second->get_section_state() == SECTION_STATE_NORMAL)
		{
			continue;
		}

		Json::Value tmp;
		Json::Value section;

		//路段id
		tmp[JSON_KEY_ALARM_SECTION_ID] = it->second->m_nID;
		section.append(tmp[JSON_KEY_ALARM_SECTION_ID]);
		//地图id
		tmp[JSON_KEY_MAP_ID] = it->second->m_nMapId;
		section.append(tmp[JSON_KEY_MAP_ID]);
		//路段内车辆总数
		tmp[JSON_KEY_ALARM_SECTION_VEHICLE_COUNTS] = it->second->get_section_vehicle_counts();
		section.append(tmp[JSON_KEY_ALARM_SECTION_VEHICLE_COUNTS]);
		//路段内人员总数
		tmp[JSON_KEY_ALARM_SECTION_STAFFER_COUNTS] = it->second->get_section_staffer_counts();
		section.append(tmp[JSON_KEY_ALARM_SECTION_STAFFER_COUNTS]);
		//路段状态
		tmp[JSON_KEY_ALARM_SECTION_STATE] = it->second->get_section_state();
		section.append(tmp[JSON_KEY_ALARM_SECTION_STATE]);
		//路段开始报警时间
		double t = *((int64_t*)&it->second->alarm_start_time)*ms;
		tmp[JSON_KEY_ALARM_START_TIME] = t;
		section.append(tmp[JSON_KEY_ALARM_START_TIME]);

		if (!section.isNull())
		{
			data.append(section);
		}

		nTotals++;
	}
	sections[JSON_ROOT_KEY_TOTAL] = nTotals;

	if (data != NULL)
	{
		sections[JSON_ROOT_KEY_DATA] = data;
	}
	return sections;
}

Json::Value CYAServerDlg::get_light_json_alarm()
{
	Json::Value lights;
	Json::Value data;

	//cmd
	lights[JSON_ROOT_KEY_CMD] = JSON_KEY_ALARM_LIGHT;

	//data
	LightMap::iterator it = mp_light_list.begin();
	for (;it != mp_light_list.end();++it)
	{
		if (it->second->m_nState == STATUS_NORMAL && it->second->m_nStateBiz == STATUS_NORMAL)
		{
			//continue;
		}

		Json::Value tmp;
		Json::Value light;

		//light_id
		tmp[JSON_KEY_ALARM_LIGHT_ID] = it->second->m_nID;
		light.append(tmp[JSON_KEY_ALARM_LIGHT_ID]);

		//light_group_id,light_group_name,vehicle_id(控制此灯组id)
		LightGroupMap::iterator lgm = mp_light_group_list.find(it->second->m_nLightsGroupID);
		if (lgm != mp_light_group_list.end())
		{
			tmp[JSON_KEY_ALARM_LIGHT_GROUP_ID] = lgm->second->m_nID;
			light.append(tmp[JSON_KEY_ALARM_LIGHT_GROUP_ID]);

			tmp[JSON_KEY_ALARM_LIGHT_GROUP_NAME] = lgm->second->m_strName;
			light.append(tmp[JSON_KEY_ALARM_LIGHT_GROUP_NAME]);

			tmp[JSON_KEY_ALARM_VEHICLE_ID] = lgm->second->m_strVechileId;
			light.append(tmp[JSON_KEY_ALARM_VEHICLE_ID]);

		}else{
			tmp[JSON_KEY_ALARM_LIGHT_GROUP_ID] = 0;
			light.append(tmp[JSON_KEY_ALARM_LIGHT_GROUP_ID]);

			tmp[JSON_KEY_ALARM_LIGHT_GROUP_NAME] = "";
			light.append(tmp[JSON_KEY_ALARM_LIGHT_GROUP_NAME]);

			tmp[JSON_KEY_ALARM_VEHICLE_ID] = "";
			light.append(tmp[JSON_KEY_ALARM_VEHICLE_ID]);
		}

		if (it->second->m_nState == STATUS_NORMAL)
		{
			tmp[JSON_KEY_STATE] = STATUS_NORMAL;
			tmp[JSON_KEY_STATE_BIZ] = STATUS_NORMAL;
		}else{
			tmp[JSON_KEY_STATE] = it->second->m_nState;
			tmp[JSON_KEY_STATE_BIZ] = it->second->m_nStateBiz;
		}
		light.append(tmp[JSON_KEY_STATE]);
		light.append(tmp[JSON_KEY_STATE_BIZ]);

		//路段开始报警时间
		double t = *((int64_t*)&it->second->alarm_start_time)*ms;
		tmp[JSON_KEY_ALARM_START_TIME] = t;
		light.append(tmp[JSON_KEY_ALARM_START_TIME]);

		if (!light.isNull())
		{
			data.append(light);
		}
	}
	if (!data.isNull())
	{
		lights[JSON_ROOT_KEY_DATA] = data;
	}

	return lights;
}

/*
* 闯红灯告警json
*
* param
*		无
*
* return
*		json对象
*
*/
Json::Value CYAServerDlg::get_red_light_json_alarm()
{
	Json::Value redLightEvent;
	Json::Value data;

	redLightEvent[JSON_ROOT_KEY_CMD] = JSON_KEY_ALARM_TRAFFIC_RED_LIGHT;

	CardMap::iterator it = mp_card_list_all.begin();
	for (;it != mp_card_list_all.end();++it)
	{
		//如果此卡闯红灯了
		if (!it->second->is_red_light)
		{
			Json::Value redLight;
			Json::Value record;

			//闯红灯车辆id，被闯灯id，闯红灯时间，司机id
			redLight[JSON_KEY_ALARM_VEHICLE_ID] = it->second->card_id;
			record.append(redLight[JSON_KEY_ALARM_VEHICLE_ID]);

			redLight[JSON_KEY_ALARM_LIGHT_ID] = it->second->light_id;
			record.append(redLight[JSON_KEY_ALARM_LIGHT_ID]);

			double t = *((int64_t*)&it->second->time_red_light)*ms;
			redLight[JSON_KEY_ALARM_START_TIME] = t;
			record.append(redLight[JSON_KEY_ALARM_START_TIME]);

			redLight[JSON_KEY_ALARM_STAFFER_ID] = it->second->driver_id;
			record.append(redLight[JSON_KEY_ALARM_STAFFER_ID]);

			if (!record.isNull())
			{
				data.append(record);
			}
		}
	}

	if (!data.isNull())
	{
		redLightEvent[JSON_ROOT_KEY_DATA] = data;
	}

	return redLightEvent;
}

std::string CYAServerDlg::get_json_special_area_process(std::shared_ptr<Card> card /*Card* card*/ )
{
	//是否特殊区域
	AreaMap::iterator it_area_cur = mp_area_list.find(card->area_id);
	if(it_area_cur == mp_area_list.end())
	{
		return "";
	}

	//新json格式
	Json::Value root;
	Json::Value val_card;
	Json::Value val_cards;

	//卡号
	val_card[JSON_KEY_CARD_ID] = card->card_id;
	val_cards.append(val_card[JSON_KEY_CARD_ID]);

	//x,y坐标
	val_card[JSON_KEY_CORDINATE_X] = CFunctions::round(card->x_offset_after(),2);
	val_cards.append(val_card[JSON_KEY_CORDINATE_X]);
	val_card[JSON_KEY_CORDINATE_Y] = CFunctions::round(card->y_offset_after(),2);
	val_cards.append(val_card[JSON_KEY_CORDINATE_Y]);

	//入井时间戳
	double t = *((int64_t*)&card->down_time)*ms;	//转为ms
	val_card[JSON_KEY_DOWN_TIME] = t;
	val_cards.append(val_card[JSON_KEY_DOWN_TIME]);

	//进入区域时间戳
	time_t eat = CFunctions::systime_to_timet(card->enter_area_time);
	t = *((int64_t*)&eat)*ms;
	val_card[JSON_KEY_ENTER_AREA_TIME] = t;
	val_cards.append(val_card[JSON_KEY_ENTER_AREA_TIME]);

	if(card->PosState() == PDT_DOWN){
		//接收时间戳
		t = *((int64_t*)&card->rec_time)*ms;
		val_card[JSON_KEY_REC_TIME] = t;
		val_cards.append(val_card[JSON_KEY_REC_TIME]);
		//工作时长
		t = (int)(difftime(time(NULL), card->down_time))*ms;
		val_card[JSON_KEY_WORK_TIME] = t;
		val_cards.append(val_card[JSON_KEY_WORK_TIME]);
	}else{
		//接收时间戳
		val_card[JSON_KEY_REC_TIME] = 0;
		val_cards.append(val_card[JSON_KEY_REC_TIME]);
		//工作时长
		//t = (int)(difftime(time(NULL), card->down_time));
		val_card[JSON_KEY_WORK_TIME] = 0;
		val_cards.append(val_card[JSON_KEY_WORK_TIME]);
	}

	//地图编号
	val_card[JSON_KEY_MAP_ID] = card->map_id;
	val_cards.append(val_card[JSON_KEY_MAP_ID]);
	//区域编号
	val_card[JSON_KEY_AREA_ID] = card->area_id;
	val_cards.append(val_card[JSON_KEY_AREA_ID]);

	//val_card[JSON_KEY_AREA_IS_SPECIAL] = it_area_cur->second->is_special();
	//val_cards.append(val_card[JSON_KEY_AREA_IS_SPECIAL]);

	//部门编号
	val_card[JSON_KEY_DEPT_ID] = card->dept_id;
	val_cards.append(val_card[JSON_KEY_DEPT_ID]);

	if(card->PosState() == PDT_DOWN){
		//状态
		val_card[JSON_KEY_STATE] = card->get_state();
		val_cards.append(val_card[JSON_KEY_STATE]);

		//运行状态
		int state = card->get_state_moving();
		if (determine_Save_Point_Or_Not(card))
		{
			state = STATE_ACCE_GETON_MONKEYCAR;
		}
	

		val_card[JSON_KEY_STATE_MOVING] = state;
		val_cards.append(val_card[JSON_KEY_STATE_MOVING]);

		//业务状态
		val_card[JSON_KEY_STATE_BIZ] = card->StateBiz();
		val_cards.append(val_card[JSON_KEY_STATE_BIZ]);

		//速度
		val_card[JSON_KEY_SPEED] =  CFunctions::round(card->get_speed(),0);
		val_cards.append(val_card[JSON_KEY_SPEED]);
	}else{
		//状态
		val_card[JSON_KEY_STATE] = 0;
		val_cards.append(val_card[JSON_KEY_STATE]);

		//运行状态
		val_card[JSON_KEY_STATE_MOVING] = 0;
		val_cards.append(val_card[JSON_KEY_STATE_MOVING]);

		//业务状态
		val_card[JSON_KEY_STATE_BIZ] = 0;
		val_cards.append(val_card[JSON_KEY_STATE_BIZ]);

		//速度
		val_card[JSON_KEY_SPEED] = 0;
		val_cards.append(val_card[JSON_KEY_SPEED]);
	}

	root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_SPECIAL_AREA_UP_MINE;
	root[JSON_ROOT_KEY_DATA].append(val_cards);

	return root.toFastString();
}


std::string CYAServerDlg::get_json_all_special_area_data()
{
	//新json格式
	Json::Value root;
	Json::Value data;

	for (CardMap::iterator it_card = mp_card_list_down_vehicle.begin();it_card != mp_card_list_down_vehicle.end();++it_card)
	{
		Json::Value val_card;
		Json::Value val_cards;

		if (_isnan(it_card->second->x) || _isnan(it_card->second->y) || _isnan(it_card->second->get_speed()))
		{
			continue;
		}
		if (fabs(it_card->second->x) < 1E-4 && fabs(it_card->second->y) < 1E-4)
		{
			continue;
		}
		if(INVALID_COORDINATE == it_card->second->x || INVALID_COORDINATE == it_card->second->y)
		{
			continue;
		}

		if(0 == it_card->second->area_id)
		{
			continue; 
		}
		//lemon 2017/08/01
		if (!need_display_verification(it_card->second))
		{
			continue;
		}
		//卡号
		val_cards.append(it_card->second->card_id);

		//x,y坐标
		val_cards.append(CFunctions::round(it_card->second->x_offset_after(),2));
		val_cards.append(CFunctions::round(it_card->second->y_offset_after(),2));

		//入井时间戳
		double t = *((int64_t*)&it_card->second->down_time)*ms;	//转为ms
		val_cards.append(t);

		//进入区域时间戳
		time_t eat = CFunctions::systime_to_timet(it_card->second->enter_area_time);
		t = *((int64_t*)&eat)*ms;
		val_cards.append(t);

		//接收时间戳
		t = *((int64_t*)&it_card->second->rec_time)*ms;
		val_cards.append(t);

		//工作时长
		t = difftime(it_card->second->rec_time, it_card->second->down_time)*ms;
		val_cards.append(t);

		//地图编号
		val_cards.append(it_card->second->map_id);
		//区域编号s
		val_cards.append(it_card->second->area_id);

		//是否特殊区域
		AreaMap::iterator it_area_cur = mp_area_list.find(it_card->second->area_id);
		if(it_area_cur != mp_area_list.end())
		{
			if (it_area_cur->second->is_special())
			{
				val_cards.append(it_area_cur->second->is_special());
			}
			else
			{
				continue;
			}		
		}
		else
		{
			continue;
		}

		//部门编号
		val_cards.append(it_card->second->dept_id);

		//状态
		val_cards.append(0);

		//运行状态
		val_cards.append(0);

		//业务状态
		val_cards.append(0);

		//速度s
		val_cards.append(0);

		std::string sc="";
		sc = val_cards.toFastString();

		if (val_cards.size() > 0)
		{
			data.append(val_cards);
		}
	}

	std::string ret = "";
	if (data.size() > 0)
	{
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_SPECIAL_AREA_UP_MINE;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION;
		root[JSON_ROOT_KEY_DATA] = data;

		ret = root.toFastString();
	}

	return ret;
}
/************************************************************************/
/* 如果返回true表明正常走需要推送
如果返回false 表明这标识卡不允许推送到web*/
/************************************************************************/
bool CYAServerDlg::need_display_verification(std::shared_ptr<Card> card)
{
	RulesMap::iterator it = m_rules_list.find(NEED_DISPLAY_RULES);
	if (it != m_rules_list.end())
	{
		if (NEED_DISPLAY_VALID == it->second )
		{
			if (0 == card->need_display)
			{
				return false;
			}
			else
			{
				return true;
			}
		}
		else
		{
			return true;
		}
	}
	return true;
}
std::string CYAServerDlg::get_json_down_and_up(std::shared_ptr<Card> card /*Card* card*/ )
{
	//新json格式
	Json::Value root;
	Json::Value val_card;
	Json::Value val_cards;

	//卡号
	val_cards.append(card->card_id);

	//x,y坐标
	val_cards.append( CFunctions::round(card->x_offset_after(),2));
	val_cards.append(CFunctions::round(card->y_offset_after(),2));

	//入井时间戳
	double t = *((int64_t*)&card->down_time)*ms;	//转为ms
	val_cards.append(t);

	//进入区域时间戳
	time_t eat = CFunctions::systime_to_timet(card->enter_area_time);
	t = *((int64_t*)&eat)*ms;
	val_cards.append(t);

	if(card->PosState() == PDT_DOWN){
		//接收时间戳
		t = *((int64_t*)&card->rec_time)*ms;
		val_cards.append(t);
		//工作时长
		t = (difftime(time(NULL), card->down_time))*ms;
		val_cards.append(t);
	}else{
		val_cards.append(0);
		//工作时长
		val_cards.append(0);
	}

	//地图编号
	val_cards.append(card->map_id);
	//区域编号
	val_cards.append(card->area_id);
	//部门编号
	val_cards.append(card->dept_id);

	if(card->PosState() == PDT_DOWN){
		//状态
		val_cards.append(card->get_state());

		//运行状态
		int state = card->get_state_moving();
		if (determine_Save_Point_Or_Not(card))
		{
			state = STATE_ACCE_GETON_MONKEYCAR;
		}
		val_cards.append(state);

		//业务状态
		val_cards.append(card->StateBiz());

		//速度
		val_cards.append(CFunctions::round(card->get_speed(), 0));
	}else{
		//状态
		val_cards.append(0);

		//运行状态
		val_cards.append(0);

		//业务状态
		val_cards.append(0);

		//速度
		val_cards.append(0);
	}

	root[JSON_ROOT_KEY_CMD] = (PDT_DOWN == card->PosState())? JSON_CMD_VALUE_DOWN_MINE : JSON_CMD_VALUE_UP_MINE;
	root[JSON_ROOT_KEY_DATA].append(val_cards);

	return root.toFastString();
}

time_t CYAServerDlg::GetCurShiftStartTime(int& shift_id)
{
	time_t t = time(NULL);
	struct tm* current_time = localtime(&t);

	shift_id = GetCurShiftId(current_time);

	switch (shift_id)
	{
	case 1:
		current_time->tm_hour = 0;
		break;
	case 2:
		current_time->tm_hour = 8;
		break;
	case 3:
		current_time->tm_hour = 16;
	default:
		break;
	}

	current_time->tm_min = 0;
	current_time->tm_sec = 0;
	t = mktime(current_time);
	current_time = localtime(&t);

	return t;
}

time_t CYAServerDlg::GetLastShiftStartTime(int& shift_id)
{
	time_t t = time(NULL);
	struct tm* current_time = localtime(&t);

	shift_id = GetCurShiftId(current_time);

	switch (shift_id)
	{
	case 1:
		current_time->tm_hour = 0;
		break;
	case 2:
		current_time->tm_hour = 8;
		break;
	case 3:
		current_time->tm_hour = 16;
		current_time->tm_mday  = current_time->tm_mday - 1;
	default:
		break;
	}
	current_time->tm_min = 0;
	current_time->tm_sec = 0;
	t = mktime(current_time);
	current_time = localtime(&t);
	return t;
}

time_t CYAServerDlg::GetCurShiftEndTime()
{
	time_t t = time(NULL);
	struct tm* current_time = localtime(&t);

	int shift_id = GetCurShiftId(current_time);
	switch (shift_id)
	{
	case 1:
		current_time->tm_hour = 8;
		break;
	case 2:
		current_time->tm_hour = 16;
		break;
	case 3:
		current_time->tm_hour = 0;
		current_time->tm_mday = current_time->tm_mday + 1;
		break;
	default:
		break;
	}

	current_time->tm_min = 0;
	current_time->tm_sec = 0;
	t = mktime(current_time);
	current_time = localtime(&t);
	return t;
}

std::string CYAServerDlg::get_json_drivingface_card_position(std::shared_ptr<Card> card)
{

	Json::Value root;

	int cnt = 0;
	double cur_shift_work_time_length = 0.0;

	Json::Value pos_cards;
	Json::Value pos_card;

	card->isdealed = false;
	card->issent = true;
	card->isoutput = false;

	float last_total_finsh_length = 0;
	float cur_total_finish_length = 0;
	float diff_length_flag = 0;
	float cur_shift_finish_length = 0;
	//std::shared_ptr<DrivingfaceRender> pDrivingfaceRender = nullptr;
	//DrivingfaceRenderMap::iterator it = mp_driving_face_render_list.find(card->reader_id);
	//DrivingfaceRenderMap::iterator it = mp_driving_face_render_list.find(501);
	std::shared_ptr<DrivingfaceCard> pDrivingfaceCard = nullptr;
	DrivingfaceCardMap::iterator it = mp_driving_face_card_list.find(card->card_id);
	if(it == mp_driving_face_card_list.end()){
		return "";
	}
	else
	{
		pDrivingfaceCard = it->second;
	}

	//卡号
	pos_cards.append(card->card_id);

	//x,y坐标
	pos_card[JSON_KEY_CORDINATE_X] = CFunctions::round(card->x, 2);
	pos_cards.append(pos_card[JSON_KEY_CORDINATE_X]);
	pos_card[JSON_KEY_CORDINATE_Y] = CFunctions::round(card->y, 2);
	pos_cards.append(pos_card[JSON_KEY_CORDINATE_Y]);

	//入井时间戳
	int shift_id = 0;
	time_t start_time_t = GetCurShiftStartTime(shift_id);
	double t = *((int64_t*)&start_time_t)*ms;
	pos_card[JSON_KEY_DOWN_TIME] = t;
	pos_cards.append(pos_card[JSON_KEY_DOWN_TIME]);

	//最后接收时间戳
	t = *((int64_t*)&card->rec_time)*ms;
	pos_card[JSON_KEY_REC_TIME] = t;
	pos_cards.append(pos_card[JSON_KEY_REC_TIME]);

	//工作时长
	t = (difftime(time(NULL), start_time_t))*ms;
	cur_shift_work_time_length = CFunctions::round(t / 1000 / 3600.0, 1);
	pos_card[JSON_KEY_WORK_TIME] = cur_shift_work_time_length;
	pos_cards.append(pos_card[JSON_KEY_WORK_TIME]);

	//地图编号
	pos_card[JSON_KEY_MAP_ID] = card->map_id;
	pos_cards.append(pos_card[JSON_KEY_MAP_ID]);

	//区域编号
	pos_card[JSON_KEY_AREA_ID] = card->area_id;
	pos_cards.append(pos_card[JSON_KEY_AREA_ID]);

	//部门编号
	pos_card[JSON_KEY_DEPT_ID] = card->dept_id;
	pos_cards.append(pos_card[JSON_KEY_DEPT_ID]);

	//状态
	card->get_state();
	card->StateBiz();
	pos_card[JSON_KEY_STATE] = (card->is_driving_face_start == 0) ? 0 : 3; 
	pos_cards.append(pos_card[JSON_KEY_STATE]);


	//工作时长
	t = difftime(time(NULL), card->down_time)*ms;
	pos_card[JSON_KEY_WORK_TIME] = t;
	pos_cards.append(pos_card[JSON_KEY_WORK_TIME]);

	//运行状态
	card->get_state_moving();
	pos_card[JSON_KEY_STATE_MOVING] = (card->is_driving_face_start == 0) ? 0 : 3;
	pos_cards.append(pos_card[JSON_KEY_STATE_MOVING]);

	//业务状态
	pos_card[JSON_KEY_STATE_BIZ] = card->StateBiz();
	pos_cards.append(pos_card[JSON_KEY_STATE_BIZ]);

	//速度
	double average_speed = 0;
	if(cur_shift_work_time_length != 0)
	{
		average_speed = card->m_curshift_finish_length / cur_shift_work_time_length;
	}
	if(average_speed > card->drving_face_cur_shift_max_speed)
	{
		card->drving_face_cur_shift_max_speed = average_speed;
	}

	//平均速度
	pos_card[JSON_KEY_SPEED] = CFunctions::round(average_speed, 2);
	pos_cards.append(pos_card[JSON_KEY_SPEED]);

	//最大速度
	debug_print_syslog(0, "average time: %3f, cur_finish_length: %3f, ", cur_shift_work_time_length, card->m_curshift_finish_length);
	pos_card[JSON_KEY_SPEED] = CFunctions::round(card->drving_face_cur_shift_max_speed, 2);
	pos_cards.append(pos_card[JSON_KEY_SPEED]);

	//掘进距离
	pos_card[JSON_KEY_DRIVINGFACE_DIS] = CFunctions::round(card->m_curshift_finish_length, 2);
	pos_cards.append(pos_card[JSON_KEY_DRIVINGFACE_DIS]);

	get_drivingface_warning_point_dis(card);
	double tmpdistance;
	int tmpid;
	if (card->m_minDistanceToWarningpoint == DBL_MAX)
	{
		tmpdistance = 0;
		tmpid =0;
		Log::write_log(SYS_S,"【lemon】dirvingface there is no warningPoint ....",true);
	}
	else
	{
		tmpdistance = card->m_minDistanceToWarningpoint;
		tmpid = card->m_warning_point_id;
	}

	//掘进面警戒点距离
	pos_card[JSON_KEY_DRIVINGFACE_WARNING_POINT_DIS] = CFunctions::round(tmpdistance, 2);
	pos_cards.append(pos_card[JSON_KEY_DRIVINGFACE_WARNING_POINT_DIS]);

	//掘进面警戒点ID lemon
	pos_card[JSON_KEY_DRIVINGFACE_WARNING_POINT_ID] = tmpid;
	pos_cards.append(pos_card[JSON_KEY_DRIVINGFACE_WARNING_POINT_ID]);

	//当前完成的长度
	pos_card[JSON_KEY_DRIVINGFACE_CURSHIFT_LENGTH] = CFunctions::round(card->m_cur_total_finish_length,2);
	pos_cards.append(pos_card[JSON_KEY_DRIVINGFACE_CURSHIFT_LENGTH]);

	if(!pos_cards.isNull()){
		root[JSON_ROOT_KEY_DATA].append(pos_cards);
		cnt++;
	}

	std::string ret = "";
	if(cnt > 0){
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_DRIVING_FACE_STATE;	
		ret = root.toFastString().c_str();
	}

	debug_print_syslog(0, "send drivingface stat: %s", ret.c_str());
	Log::write_log(JSON_S,ret,true);
	return ret;


}

int CYAServerDlg::insert_data(int index, int key, StatisticDataStr** header)
{
	StatisticDataStr* tmpPtr = *header;
	StatisticDataStr* second = *header;
	if(NULL == tmpPtr)
	{
		KeyValuePair* keyValuePtr = new KeyValuePair;
		keyValuePtr->key = key;
		keyValuePtr->value = 1;
		keyValuePtr->next = NULL;
		StatisticDataStr* deptStatisticData = new StatisticDataStr;
		deptStatisticData->index = index;
		deptStatisticData->data_info = keyValuePtr;
		deptStatisticData->next = NULL;
		tmpPtr = deptStatisticData;
		*header = tmpPtr;
		return 0;
	}
	while(tmpPtr != NULL)
	{
		if(tmpPtr->index == index)
		{
			break;
		}
		second = tmpPtr;
		tmpPtr = tmpPtr->next;
	}
	if(NULL == tmpPtr)
	{
		KeyValuePair* keyValuePtr = new KeyValuePair;
		keyValuePtr->key = key;
		keyValuePtr->value = 1;
		keyValuePtr->next = NULL;
		StatisticDataStr* deptStatisticData = new StatisticDataStr;
		deptStatisticData->index = index;
		deptStatisticData->data_info = keyValuePtr;
		deptStatisticData->next = NULL;
		if(NULL != second)
		{
			second->next = deptStatisticData;
		}
		else
		{
			tmpPtr = deptStatisticData;
		}
	}
	else
	{
		KeyValuePair* keyValuePtr = tmpPtr->data_info;
		KeyValuePair* keyValuePtrSecond = tmpPtr->data_info;
		while(keyValuePtr != NULL )
		{
			if(keyValuePtr->key == key)
			{
				break;
			}
			keyValuePtrSecond = keyValuePtr;
			keyValuePtr = keyValuePtr->next;
		}
		if(NULL == keyValuePtr)
		{
			KeyValuePair* keyValueData = new KeyValuePair;
			keyValueData->key = key;
			keyValueData->value = 1;
			keyValueData->next = NULL;
			keyValuePtrSecond->next = keyValueData;
		}
		else
		{
			keyValuePtr->value = keyValuePtr->value + 1;
		}
	}
	return 0;
}

void CYAServerDlg::delete_memory(StatisticDataStr *header)
{
	if(NULL == header)
	{
		return;
	}

	while(NULL != header)
	{
		KeyValuePair* tmpKeyValuePtr = header->data_info;
		while(NULL != tmpKeyValuePtr)
		{
			KeyValuePair* tmpKPtr = tmpKeyValuePtr;
			tmpKeyValuePtr = tmpKeyValuePtr->next;
			delete tmpKPtr;
		}
		StatisticDataStr* tmpStatisticDataStrPtr = header;
		header=header->next;
		delete tmpStatisticDataStrPtr;
	}
	return;
}

Json::Value CYAServerDlg::get_json_statistic_data( StatisticDataStr* header )
{
	Json::Value data;
	while(NULL != header)
	{
		KeyValuePair* tmpKeyValuePtr = header->data_info;
		while(NULL != tmpKeyValuePtr)
		{
			KeyValuePair* tmpKPtr = tmpKeyValuePtr;
			tmpKeyValuePtr = tmpKeyValuePtr->next;
			Json::Value ttemp;

			ttemp.append(tmpKPtr->key);
			ttemp.append(tmpKPtr->value);
			data.append(ttemp);
		}
		header=header->next;
	}
	return data; 
}

/*
下面这个函数就是为了构造json的单条卡的定位信息，detail是多卡，但是下面是填写单卡，如下：
"detail":[
["0020000001037",3486.530,75.0,1499512539000.0,1499512530000.0,1499512559000.0,20000.0,5,1,1,0,2,0,0.0,0,0,0.0,0]
]
*/
int CYAServerDlg::get_json_node_position( std::shared_ptr<Card> ccard, Json::Value &detailNode )
{
	int handup_status = 0;
	int list_area_id = 0;

	// 卡号
	detailNode.append(ccard->card_id); // 0
	//写数据库需要的相关变量
	char _time[STR_LEN_TIME], _time_ex[STR_LEN_TIME];
	char sql[LENGTH_SQL] = {0};
	//需要考虑 坐标为零的数据
	//lemon smooth------------------
	NAMESPACE_POINT::loc_point lp = m_carmanage->getpoint(ccard->card_id);
	//------------------------------
	//if (VT_DIGGINGCOAL_MACHINE == ccard->vehice_type_id || VT_DRIVINGFACE_MACHINE == ccard->vehice_type_id)
	//if (VT_DRIVINGFACE_MACHINE == ccard->vehice_type_id)
	if(CT_TUNNELBORING_MACHINE == ccard->card_type)
	{
		detailNode.append( CFunctions::round(ccard->x, 2)); // 1
		detailNode.append( CFunctions::round(ccard->y, 2)); // 2
	}else if(CT_COALMINING_MACHINE == ccard->card_type){
		auto it_card = mp_card_list_all.find(ccard->card_id);
		if (it_card != mp_card_list_all.end())
		{
			auto it = m_coalmining_regularcycle_list.find(it_card->second->id);
			bool b_use_default = false;
			if (it!= m_coalmining_regularcycle_list.end())
			{
				auto it_coalface = m_coalmining_area_list.find(it->second->coalface_id);
				if (it_coalface != m_coalmining_area_list.end())
				{
					double output_x = ccard->x + it_coalface->second->m_x_offset;
					double output_y = ccard->y + it_coalface->second->m_y_offset;
					detailNode.append( CFunctions::round(output_x, 2)); // 1
					detailNode.append( CFunctions::round(output_y, 2)); // 2
					b_use_default = true;
					debug_print_syslog(0,"[three rates: cmj]coalface_id: %d, card_id: %s, x: %.4f, y: %.4f, x_offset: %.4f, y_offset: %.4f",ccard->id,ccard->card_id.c_str(),output_x,output_y,it_coalface->second->m_x_offset,it_coalface->second->m_y_offset);
				}else{
					debug_print_syslog(0,"[three rates: cmj] coalface_id: %d is not exist.",ccard->id);
				}
			}else{
				debug_print_syslog(0,"[three rates: cmj]card_id: %s ,vehicle_id: %d. the card is not in regularcycle list.",ccard->card_id.c_str(),it_card->second->id);
			}
			if (!b_use_default)
			{
				detailNode.append( CFunctions::round(ccard->x, 2)); // 1
				detailNode.append( CFunctions::round(ccard->y+3, 2)); // 2
				debug_print_syslog(0,"[three rates: cmj] card_id: %s use default offset.",ccard->card_id.c_str());
			}
		}
		
		//detailNode.append( CFunctions::round(ccard->x, 2)); // 1
		//detailNode.append( CFunctions::round(ccard->y+3, 2)); // 2
		//debug_print_syslog(0,"[three rates: cmj]%s,x:%f,y:%f",ccard->card_id.c_str(),ccard->x,ccard->y+3);
	}
	else
	{
		double real_x=0,real_y = 0;
		//------lemon smooth--------------
		if (lp.empty())
		{
			real_x = CFunctions::round(ccard->x_offset_after(), 2);
			real_y = CFunctions::round(ccard->y_offset_after(), 2);
			//debug_print_syslog(0,"[zcm person]%s,x:%f,y:%f",ccard->card_id.c_str(),ccard->x,ccard->y);
		}
		else
		{
			real_x = lp.x;
			real_y = -lp.y;
			debug_print_syslog(0,"[lemon getpoint xy not empty]%s,x:%f,y:%f,v:%.3f,state:%d,dist=%f",ccard->card_id.c_str(),real_x,real_y,lp.m_speed,lp.m_stat,lp.m_dist2);
		}
		//--------------------------------

		//如果区域信息中含有该卡，则坐标选择该坐标。
		if (!ccard->m_card_ptr.expired())
		{
			std::shared_ptr<card> spc = ccard->m_card_ptr.lock();
			point_2 p = spc->get_position();
			if (point_2::is_valid(p))
			{
				real_x = p.x_;
				real_y = p.y_;
				//exec sql
				string sql = ccard->store_data_card(HIS_LOCATION,real_x,real_y);
				m_qsmSQL->AddString(sql.c_str());
			}
		}

		//手动移动车辆图标，需要区分是传真实坐标还是hand_up_list中的坐标
		if(mp_card_hand_up_list->size()>0)
		{
			//进入临界区，防止多个线程同时操作map
			EnterCriticalSection(&m_csHandUp);

			//mp_card_hand_up_list不为空,在list中查找以确定传什么坐标
			HandUpVehicleMap::iterator it_hand_up= mp_card_hand_up_list->find(ccard->card_id);
			if(it_hand_up != mp_card_hand_up_list->end())
			{
				//在hand up list中存在ccard id
				double list_x = it_hand_up->second->point_x;
				double list_y = it_hand_up->second->point_y;
				list_area_id = it_hand_up->second->area_id;
				int ret_Hangup = is_in_handup_area(real_x, real_y, list_x, list_y);
				if((0 == ret_Hangup) || (STATUS_LOST == ccard->StateBiz()))
				{
					//实时坐标没有超出半径区域或者仍然在信号丢失状态,将list中的坐标传到web
					detailNode.append(list_x); // 1
					detailNode.append(list_y); // 2

					//设置handup status
					handup_status = IN_HANDUP_LIST_AREA_IN;
				}
				else
				{
					//实时坐标超出半径,将实时坐标传到web
					detailNode.append(real_x); // 1
					detailNode.append(real_y); // 2
				
					//擦除数据库中此卡的信息
					erase_handup_vehicle(ccard->card_id);
				
					//list中删除此条记录
					mp_card_hand_up_list->erase(it_hand_up);

					//设置handup status
					handup_status = IN_HANDUP_LIST_AREA_OUT;
				}
			}
			else
			{
				//在hand up list中不存在ccard id,直接传真实坐标到web
				detailNode.append(real_x); // 1
				detailNode.append(real_y); // 2

				//设置handup status
				handup_status = NOT_IN_HANDUP_LIST;
			}		
			//退出临界区
			LeaveCriticalSection(&m_csHandUp);
		}
		else
		{
			//mp_card_hand_up_list为空,直接传真实坐标到web
			detailNode.append(real_x); // 1
			detailNode.append(real_y); // 2

			//设置handup status
			handup_status = NOT_IN_HANDUP_LIST;
		}	
	}

	//入井时间戳
	double t = *((int64_t*)&ccard->down_time)*ms;
	detailNode.append(t); // 3
	//进入区域时间戳
	time_t eat = CFunctions::systime_to_timet(ccard->enter_area_time);
	t = *((int64_t*)&eat)*ms;
	detailNode.append(t); // 4
	//最后接收时间戳
	t = *((int64_t*)&ccard->rec_time)*ms;
	detailNode.append(t); // 5

	if(POS_DEVICE_TYPE::PDT_DOWN == ccard->PosState())
	{
		//工作时长
		t = difftime(time(NULL), ccard->down_time)*ms;
	}
	else
	{
		t = 0; // lihongzhen  2017/8/17 16:53 结束考勤不推送时长数据
	}
	detailNode.append(t); // 6
	//地图编号
	detailNode.append(ccard->map_id); // 7
	//区域编号,含特殊区域
	if(IN_HANDUP_LIST_AREA_IN == handup_status)
	{
		//手动挪车了，推送挪车之后的area_id
		detailNode.append(list_area_id); // 8

		//更新area_card_list_vehicle表，用于更新车辆区域统计
		if(list_area_id != ccard->area_id)
		{
			//删除原area list中的ccard
			AreaMap::iterator it_area = mp_area_list.find(ccard->area_id);
	
			//进入临界区，防止多个线程同时操作map
			EnterCriticalSection(&m_csAreaList);
			if(it_area != mp_area_list.end()){
				CardMap::iterator it_area_card = it_area->second->area_card_list_vehicle->find(ccard->card_id);
				if(it_area_card != it_area->second->area_card_list_vehicle->end()){
					it_area->second->area_card_list_vehicle->erase(it_area_card);
				}
			}

			//在新的area list中增加card_id
			it_area = mp_area_list.find(list_area_id);
			ccard->area_id = list_area_id;
			if(it_area != mp_area_list.end()){
				it_area->second->area_card_list_vehicle->insert(make_pair(ccard->card_id, ccard));
			}
			//退出临界区
			LeaveCriticalSection(&m_csAreaList);
		}
	}
	else
	{
		detailNode.append(ccard->area_id); // 8
	}
	//部门编号
	detailNode.append(ccard->dept_id); // 9
	//状态
	detailNode.append(ccard->get_state()); // 10
	//运行状态
	//这里对运行状态进行赋值
	ccard->state_moving = lp.m_stat;
	int state = ccard->get_state_moving();

	double tmp_v = 0;
	//ensure when person on monkeycar.then speed should not be equal to zero.
	if (determine_Save_Point_Or_Not(ccard))
	{
		state = STATE_ACCE_GETON_MONKEYCAR;
		if (abs(ceil(lp.m_speed)) > 0)
		{
			tmp_v = abs(ceil(lp.m_speed));
			ccard->final_v = lp.m_speed;
		}
		else
		{
			tmp_v = abs(ceil(ccard->final_v));
		}
	}
	else
	{
		//tmp_v = abs(ceil(lp.m_speed));
		if (CT_PERSON == ccard->card_type)
		{
			tmp_v = abs(CFunctions::round(lp.m_speed,2));
		}else{
			tmp_v = abs(ceil(lp.m_speed));
		}
	
		ccard->final_v = lp.m_speed;
	}
	detailNode.append(state); // 11
	//业务状态
	detailNode.append(ccard->StateBiz()); // 12
	//速度
	double area_over_speed = 0;

	AreaMap::iterator it_area = mp_area_list.find(ccard->area_id);
	if(it_area != mp_area_list.end())
	{
		area_over_speed = it_area->second->over_speed_vehicle;
	}
	//若超速超过最大次数，则上报实时速度；否则上报区域最大速度阈值
	//速度为0为不限速
	//if (((ccard->is_area_over_speed == FALSE) && (ccard->get_speed() > area_over_speed) && (area_over_speed != 0) && (STATUS_LOST != ccard->StateBiz()))
	//	|| ((ccard->is_area_over_speed == TRUE) && (ccard->get_speed() <= area_over_speed) && (area_over_speed != 0) && (STATUS_LOST != ccard->StateBiz())))
	if (((ccard->is_area_over_speed == FALSE) && (tmp_v > area_over_speed) && (area_over_speed != 0) && (STATUS_LOST != ccard->StateBiz()))
		|| ((ccard->is_area_over_speed == TRUE) && (tmp_v <= area_over_speed) && (area_over_speed != 0) && (STATUS_LOST != ccard->StateBiz())))
	{
		detailNode.append(area_over_speed); // 13
	}
	else
	{
		detailNode.append(tmp_v);// 13
	}
	//地标编号
	detailNode.append(ccard->landmark_id); // 14
	//地标方向
	detailNode.append(ccard->landmark_direction); // 15
	//距离地标的距离
	detailNode.append(CFunctions::round(ccard->landmark_dis, 0)); // 16
	// 级别编号
	detailNode.append(ccard->level_id); //17
	//获取当天出勤的车辆标识。
	time_t zeroTime = CFunctions::getMorningTime();
	detailNode.append(ccard->down_time > zeroTime ? 1:0);//18
	//debug_print_syslog(0,"card_attence_vehicle.[%s]zero_time:%ld,down_time:%ld",ccard->card_id.c_str(),zeroTime,ccard->get_working_time());
	// 升入井状态，测试用
	//detailNode.append(ccard->pos_state); // 18
	//json的所有数据准备完毕，下面函数返回，接下来的代码应该是发送
	//返回0 表示成功
	return 0;
}

// 构造车辆的json数据
Json::Value CYAServerDlg::get_json_statistic_vehicle_data(Json::Value& vehicle_data)
{
	Json::Value stat;
	Json::Value detail;

	Json::Value glbl;
	Json::Value depts;

	Json::Value global_area;
	Json::Value global_dept;

	Json::Value testArea;
	Json::Value testAll;

	int dept_sum = 0;
	int all_verhicle_num = 0;

	StatisticDataStr* areaStatisticHeader = NULL;

	for(DeptMap::iterator it_dept = mp_dept_list.begin(); it_dept != mp_dept_list.end(); ++it_dept)
	{
		dept_sum = it_dept->second->dept_card_list_vehicle.size();
		if(dept_sum > 0)
		{
			Json::Value per_dept;
			Json::Value dept_areas;

			StatisticDataStr* deptStatisticHeader = NULL;

			CardMap dept_card_map = it_dept->second->dept_card_list_vehicle;
			for(CardMap::iterator it_card = dept_card_map.begin(); it_card != dept_card_map.end(); ++it_card)
			{
				// 非法坐标不推
				if (_isnan(it_card->second->x) || _isnan(it_card->second->y) || _isnan(it_card->second->get_speed()))
				{
					dept_sum--;
					continue;
				}
				if (fabs(it_card->second->x) < 1E-4 && fabs(it_card->second->y) < 1E-4)
				{
					dept_sum--;
					continue;
				}
				if(INVALID_COORDINATE == it_card->second->x || INVALID_COORDINATE == it_card->second->y)
				{
					dept_sum--;
					continue;
				}
				if(0 == it_card->second->area_id)
				{
					dept_sum--;
					continue; 
				}
				if(!it_card->second->is_registered)
				{
					dept_sum--;
					continue;
				}


				//				if(VT_DRIVINGFACE_MACHINE == it_card->second->vehice_type_id || VT_DIGGINGCOAL_MACHINE == it_card->second->vehice_type_id)
				//				{
				//					dept_sum--;
				//					continue;
				//				}

				//lemon 2017/08/01
				if (!need_display_verification(it_card->second))
				{
					dept_sum--;
					continue;
				}

				// 组装每个部门的区域统计
				insert_data(it_card->second->dept_id, it_card->second->area_id, &deptStatisticHeader);
				insert_data(0, it_card->second->area_id, &areaStatisticHeader);

				all_verhicle_num++;
				// 获取明细
				Json::Value vehicle;
				get_json_node_position(it_card->second, vehicle);
				if(!vehicle.isNull()){
					detail.append(vehicle);
				}
			}

			if(dept_sum > 0)
			{
				Json::Value single_dept;
				single_dept.append(it_dept->first);
				single_dept.append(dept_sum);
				global_dept.append(single_dept);

				dept_areas = get_json_statistic_data(deptStatisticHeader);
				if(!dept_areas.isNull()){
					per_dept[JSON_ROOT_KEY_STATISTIC_SUM] = dept_sum;
					per_dept[JSON_ROOT_KEY_STATISTIC_AREA] = dept_areas;
					per_dept[JSON_ROOT_KEY_STATISTIC_DEPT].append(single_dept);
					char dept_id[20];
					sprintf_s(dept_id, "%d", it_dept->first);
					depts[dept_id] = per_dept;
				}
			}
		}
	}

	global_area = get_json_statistic_data(areaStatisticHeader);

	glbl[JSON_ROOT_KEY_STATISTIC_SUM] = all_verhicle_num;
	if(!global_area.isNull()){
		glbl[JSON_ROOT_KEY_STATISTIC_AREA] = global_area;
	}
	if(!global_dept.isNull()){
		glbl[JSON_ROOT_KEY_STATISTIC_DEPT] = global_dept;
	}
	if(!glbl.isNull()){
		stat[JSON_ROOT_KEY_STATISTIC_GLOBAL] = glbl;
	}
	if(!depts.isNull()){
		stat[JSON_ROOT_KEY_STATISTIC_DEPT] = depts;
	}
	if(!stat.isNull()){
		vehicle_data[JSON_ROOT_KEY_STATISTIC_STAT] = stat;
	}
	if(!detail.isNull()){
		vehicle_data[JSON_ROOT_KEY_STATISTIC_DETAIL] = detail;
	}

	return vehicle_data;
}

// 构造人员的统计数据
Json::Value CYAServerDlg::get_json_statistic_staff_data(Json::Value& staff_data)
{
	Json::Value stat;
	Json::Value detail;

	Json::Value glbl;
	Json::Value depts;

	Json::Value global_area;
	Json::Value global_dept;
	Json::Value global_level;

	int all_staff_num = 0;
	int dept_sum = 0;

	StatisticDataStr* areaStatisticHeader = NULL;
	StatisticDataStr* lvlStatisticHeader = NULL;

	for(DeptMap::iterator it_dept = mp_dept_list.begin(); it_dept != mp_dept_list.end(); ++it_dept)
	{
		dept_sum = it_dept->second->dept_card_list_person.size();
		if(dept_sum > 0)
		{
			Json::Value per_dept;
			Json::Value dept_areas;
			Json::Value dept_levels;

			StatisticDataStr* deptStatisticHeader = NULL;
			StatisticDataStr* occLevelStatisticHeader = NULL;

			CardMap dept_card_map = it_dept->second->dept_card_list_person;
			for(CardMap::iterator it_card = dept_card_map.begin(); it_card != dept_card_map.end(); ++it_card)
			{
				if (_isnan(it_card->second->x) || _isnan(it_card->second->y) || _isnan(it_card->second->get_speed()))
				{
					dept_sum--;
					continue;
				}
				if (fabs(it_card->second->x) < 1E-4 && fabs(it_card->second->y) < 1E-4)
				{
					dept_sum--;
					continue;
				}
				if(INVALID_COORDINATE == it_card->second->x || INVALID_COORDINATE == it_card->second->y)
				{
					dept_sum--;
					continue;
				}
				if(0 == it_card->second->area_id)
				{
					dept_sum--;
					continue; 
				}
				if(!it_card->second->is_registered)
				{
					dept_sum--;
					continue;
				}
				//lemon 2017/08/01 
				if (!need_display_verification(it_card->second))
				{
					dept_sum--;
					continue;
				}
				// 组装每个部门的区域统计
				insert_data(it_card->second->dept_id, it_card->second->area_id, &deptStatisticHeader);
				insert_data(it_card->second->dept_id, it_card->second->level_id, &occLevelStatisticHeader);
				insert_data(0, it_card->second->area_id, &areaStatisticHeader);
				insert_data(0, it_card->second->level_id, &lvlStatisticHeader);

				all_staff_num++;
				// 获取明细
				Json::Value detailNode;
				get_json_node_position(it_card->second, detailNode);
				if(!detailNode.isNull()){
					detail.append(detailNode);
				}
			}
			if(dept_sum>0){
				dept_areas = get_json_statistic_data(deptStatisticHeader);
				dept_levels = get_json_statistic_data(occLevelStatisticHeader);

				Json::Value single_dept;
				single_dept.append(it_dept->first);
				single_dept.append(dept_sum);
				global_dept.append(single_dept);

				per_dept[JSON_ROOT_KEY_STATISTIC_SUM] = dept_sum;

				if(!dept_areas.isNull()){
					per_dept[JSON_ROOT_KEY_STATISTIC_AREA] = dept_areas;
				}
				if(!dept_levels.isNull()){
					per_dept[JSON_ROOT_KEY_STATISTIC_LEVEL] = dept_levels;
				}
				if(!single_dept.isNull()){
					per_dept[JSON_ROOT_KEY_STATISTIC_DEPT].append(single_dept);
					char dept_id[20];
					sprintf_s(dept_id, "%d", it_dept->first);
					depts[dept_id] = per_dept;
				}
			}
		}
	}

	global_area = get_json_statistic_data(areaStatisticHeader);
	global_level = get_json_statistic_data(lvlStatisticHeader);

	glbl[JSON_ROOT_KEY_STATISTIC_SUM] = all_staff_num;
	if(!global_area.isNull()){
		glbl[JSON_ROOT_KEY_STATISTIC_AREA] = global_area;
	}
	if(!global_dept.isNull()){
		glbl[JSON_ROOT_KEY_STATISTIC_DEPT] = global_dept;
	}
	if(!global_level.isNull()){
		glbl[JSON_ROOT_KEY_STATISTIC_LEVEL] = global_level;
	}
	if(!glbl.isNull()){
		stat[JSON_ROOT_KEY_STATISTIC_GLOBAL] = glbl;
	}
	if(!depts.isNull()){
		stat[JSON_ROOT_KEY_STATISTIC_DEPT] = depts;
	}
	if(!stat.isNull()){
		staff_data[JSON_ROOT_KEY_STATISTIC_STAT] = stat;
	}
	if(!detail.isNull()){
		staff_data[JSON_ROOT_KEY_STATISTIC_DETAIL] = detail;
	}
	if (all_staff_num>0)
	{
		record_staff_count(all_staff_num);
	}
	return staff_data;
}
void CYAServerDlg::record_staff_count(int num)
{
	static int min_num,max_num;
	std::time_t t = time(NULL);

	if (time_recode_staff_number == 0)
	{
		char ti[64] = { 0 };
		strftime(ti,sizeof(ti),"%Y/%m/%d %H:%M:%S",localtime(&t));
		std::string sti(ti);
		int minute = atoi(sti.substr(sti.find_first_of(':')+1,2).c_str());
		if (minute%2 == 1)
		{
			return;
		}
		min_num=max_num=num;
		time_recode_staff_number = t;
	}
	else if(t-time_recode_staff_number>=120)
	{
		std::stringstream ss;
		ss<< "INSERT INTO his_staff_number(max_num,min_num,ave_num) VALUES("<<max_num<<','<<min_num<<','<<(int)CFunctions::round((max_num+min_num)/2,0)<<");";
		debug_print_syslog(0,"staff_number:%s",ss.str().c_str());
		m_qsmSQL->AddString(ss.str().c_str());
		min_num=max_num=num;
		time_recode_staff_number = t;
	}
	else
	{
		if (min_num>num)
		{
			min_num = num;
		}
		if (max_num < num)
		{
			max_num = num;
		}
	}
	return;
}
/*
//刘思平修订的代码Part 8/Sum 8:begin
刘思平修订的代码Part 7/Sum 7:begin
构造json的时候无须考虑人卡和车卡的区别，所以下面的代码变量虽然是veicle，其实暗含了人在内
by lsp on 2017.07.09 @山西长治
这个函数是构造整个json，如果此步完成，那么就json构造完成
这个json包括了车和人，构造成一个json，一次发送
*/
std::string CYAServerDlg::get_json_card_statistic()
{
	Json::Value root;
	Json::Value data;
	Json::Value v;
	Json::Value s;
	//构造veicle的json，如果返回值为1，那么意味着发生了异常，直接返回空串给上一级，表示未成功
	if(get_json_statistic_vehicle_data(v) == 1){
		return "";
	}

	//构造person的json，如果返回值为1，那么意味着发生了异常，直接返回空串给上一级，表示未成功
	if(get_json_statistic_staff_data(s) == 1){
		return "";
	}

	if(!v.isNull()){
		data[JSON_ROOT_KEY_STATISTIC_VEHICLE_DATA] = v;
	}
	if(!s.isNull()){
		data[JSON_ROOT_KEY_STATISTIC_STAFF_DATA] = s;
	}

	std::string ret = "";
	if(!data.isNull()){
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_POS_MAP; // JSON_CMD_VALUE_STATISTIC;
		root[JSON_ROOT_KEY_DATA] = data;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION_1_4;
		ret = root.toFastString();
	}
	return ret; //返回包含json信息的字符串
}

/*
* 此函数生成所有数据的json，含坐标位置，事件，呼叫，特殊区域升井等
* 
* param
*		无
*
* return 
*		生成的json字符串
*
*/
std::string CYAServerDlg::get_json_all_data()
{
	Json::Value root;
	Json::Value data;
	Json::Value pos_data;

	std::string meta_data = "";
	for (int i = 0;i < 5;i++)
	{
		meta_data = "";
		switch(i){
		case 0:
			meta_data = get_json_card_statistic();
			break;
		case 1:
			meta_data = get_json_event(true);
			Log::write_log(FILE_TYPE::KALMAN_S,"req_all_data: event",true);
			Log::write_log(FILE_TYPE::KALMAN_S,meta_data.c_str(),true);
			break;
		case 2:
			meta_data = get_json_call_list();
			break;
		case 3:
			meta_data = get_json_all_special_area_data();
			break;
		case 4:
			meta_data = get_json_all_traffic_lights();
			break;
		}

		if (meta_data != "")
		{
			Json::Reader reader;
			Json::Value tmp;
			reader.parse(meta_data,tmp);
			data.append(tmp);
		}
	}

	std::string ret = "";
	if (data.size() > 0)
	{
		root[JSON_ROOT_KEY_CMD]		= JSON_CMD_VALUE_RESPONSE_ALL_DATA;
		root[JSON_ROOT_KEY_DATA]	= data;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION;
		ret = root.toFastString();
	}

	return ret; 
}

std::string CYAServerDlg::get_json_login()
{
	Json::Value root;
	Json::Value data;
	data[JSON_KEY_USERNAME] = JSON_VALUE_USERNAME;
	data[JSON_KEY_PASSWORD] = JSON_VALUE_PASSWORD;
	root[JSON_ROOT_KEY_CMD] =  JSON_CMD_VALUE_LOGIN;
	root[JSON_ROOT_KEY_DATA] = data;
	return root.toFastString();
}

std::string CYAServerDlg::get_json_logout()
{
	Json::Value root;
	Json::Value data;
	data["name"] = JSON_VALUE_USERNAME;
	root[JSON_ROOT_KEY_CMD] =  JSON_CMD_VALUE_LOGOUT;
	root["user"] = data;
	return root.toFastString();
}

void CYAServerDlg::send_json_data(string cmd, string data, bool is_login /* = false*/)
{
	if(data.length() == 0) return;

	USES_CONVERSION;
	CC2UTF8 conv = (char*)data.c_str();
	string utf8_data = conv.c_str();
	CString strlog;
	if(is_login){
		if(is_websocket_ok){
			_io->socket()->emit(cmd, utf8_data);
			is_websocket_login = true;
			strlog.Format(_T("%s: %s"), _T(LOG_SEND_JSON_DATA), _T("登录数据"));
			show_log(strlog);
		}
		// 备用地址
		if(is_websocket_ok_ex){
			_io_ex->socket()->emit(cmd, utf8_data);
			is_websocket_login_ex = true;
			strlog.Format(_T("%s: %s"), _T(LOG_SEND_JSON_DATA), _T("登录数据"));
			show_log(strlog);
		}
	}
	else
	{
		if(is_websocket_login)
		{
			strlog.Format(_T("%s: %s"), _T(LOG_SEND_JSON_DATA), _T("常规数据"));
			_io->socket()->emit(cmd, utf8_data);
		}
		// 备用地址
		if(is_websocket_login_ex)
		{
			strlog.Format(_T("%s: %s"), _T(LOG_SEND_JSON_DATA), _T("常规数据"));
			_io_ex->socket()->emit(cmd, utf8_data);
		}
	}
	debug_print_syslog(0, "Send json %s.", data.c_str());
}
void CYAServerDlg::deal_readers_event(EVENT_TYPE et,bool flag,const std::shared_ptr<Reader> &r)
{
	//false 取消告警
	int t =(int)difftime(time(NULL), r->rec_time);
	if(!flag){
		INT64 ev_id = r->m_event_list[et];
		if(ev_id > 0){
			EventMap::iterator it_ev = mp_event_list->find(ev_id);
			if(it_ev != mp_event_list->end()){
				it_ev->second->status = ES_END;
				it_ev->second->cur_time = time(NULL);
				it_ev->second->cur_value = t;
				it_ev->second->is_sent = false;
				store_data_event(it_ev->second);
				add_event(it_ev->second);
			}					
		}
		r->m_event_list[et] = 0;
		if (et == ET_READER_ERROR)
			r->reader_state = STATUS_DEVICE_NORMAL;	
	}
	else
	{
		INT64 ev_id = r->m_event_list[et];
		if(ev_id > 0) return;
		if (et == ET_READER_ERROR)
			r->reader_state = STATUS_DEVICE_ERROR;
		r->lost_time = time(NULL);

		ev_id = CFunctions::GetMicroSecond();
		std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
		ev->status = ES_START;
		ev->ev_type = et;
		ev->obj_type = OT_DEVICE_READER;
		ev->obj_id = CFunctions::int2string(r->reader_id);
		ev->cur_time = time(NULL);

		ev->map_id = r->map_id;
		ev->area_id = r->area_id;
		ev->x = r->reader_x;
		ev->y = r->reader_y;

		ev->limit_value = READER_TIMEOUT;
		ev->cur_value = t;
		ev->is_sent = false;

		r->m_event_list[et] = ev_id;
		store_data_event(ev);
		add_event(ev);
		Sleep(1);
	}
}

void CYAServerDlg::deal_lamp_light_event(EVENT_TYPE et,bool flag,const std::shared_ptr<op::TrafficLight>& ptl)
{
	//false 取消告警
	int t =(int)difftime(time(NULL), ptl->m_rec_time);
	if(!flag){
		INT64 ev_id = ptl->m_event_list[et];
		if(ev_id > 0){
			EventMap::iterator it_ev = mp_event_list->find(ev_id);
			if(it_ev != mp_event_list->end()){
				it_ev->second->status = ES_END;
				it_ev->second->cur_time = time(NULL);
				it_ev->second->cur_value = t;
				it_ev->second->is_sent = false;
				store_data_event(it_ev->second);
				add_event(it_ev->second);
			}					
		}
		ptl->m_event_list[et] = 0;
		if (et == ET_READER_ERROR)
			ptl->light_state = STATUS_DEVICE_NORMAL;	
	}
	else
	{
		INT64 ev_id = ptl->m_event_list[et];
		if(ev_id > 0) return;
		if (et == ET_READER_ERROR)
			ptl->light_state = STATUS_DEVICE_ERROR;
		//ptl->lost_time = time(NULL);

		ev_id = CFunctions::GetMicroSecond();
		std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
		ev->status = ES_START;
		ev->ev_type = et;
		ev->obj_type = OT_DEVICE_READER;
		ev->obj_id = CFunctions::int2string(ptl->m_physics_light_id);
		ev->cur_time = time(NULL);

		for (auto it_group : m_carmanage->m_Map)
		{
			for (auto it_light : it_group.second->m_pTrafficLight)
			{
				if (it_light->m_physics_light_id == ptl->m_physics_light_id)
				{
					ev->map_id = it_group.second->m_mapId;
					ev->area_id = it_group.second->m_areaId;
					ev->x = it_group.second->x;
					ev->y = it_group.second->y;
				}
			}
		}

		ev->limit_value = READER_TIMEOUT;
		ev->cur_value = t;
		ev->is_sent = false;

		ptl->m_event_list[et] = ev_id;
		store_data_event(ev);
		add_event(ev);
		Sleep(1);
	}
}

// 处理分站状态
void CYAServerDlg::deal_readers()
{
	ReaderMap::iterator it = mp_reader_list.begin();
	for(; it != mp_reader_list.end(); ++ it){
		int ndiff = (int)difftime(time(NULL), it->second->rec_time);
		if(STATUS_DEVICE_ERROR == it->second->reader_state){ // 异常 
			if(ndiff < READER_TIMEOUT){ // 恢复正常
				deal_readers_event(ET_READER_ERROR,false,it->second);
			}
		}else{
			//分站20秒内未接收到数据，即产生告警
			if(ndiff >= READER_TIMEOUT){ //异常
				deal_readers_event(ET_READER_ERROR,true,it->second);
			}
		}
	}
}

/*
* 处理区域内业务逻辑：包含区域人员超员，人员超时，车辆超员，车辆超时，车辆超速等
*
* param
*		无
*
* return
*		无
*
*/
void CYAServerDlg::deal_areas()
{
	//区域人数，区域超员数，区域超时数
	int count_person, count_vehicle, count_total, count_over_time_person, count_over_time_vehicle;
	int over_time_vehicle, over_time_person, over_time;
	time_t current_time(time(NULL));

	AreaMap::iterator it_Area = mp_area_list.begin();

	for(; it_Area != mp_area_list.end(); ++it_Area)
	{
		count_person = count_vehicle = count_total = count_over_time_vehicle = count_over_time_person = 0;

		//over_time = over_time_vehicle;
		//CardMap::iterator it_card_vehicle = it_Area->second->area_card_list_vehicle->begin();
		//for(;it_card_vehicle != it_Area->second->area_card_list_vehicle->end(); ++it_card_vehicle){
		//	// 计数
		//	count_total++;

		//	count_vehicle++;
		//	// 超时
		//	if(difftime(current_time, CFunctions::systime_to_timet(it_card_vehicle->second->enter_area_time)) > over_time){
		//		is_true = true;
		//		if(!it_card_vehicle->second->is_area_over_time){
		//			it_card_vehicle->second->is_area_over_time = true;
		//			it_card_vehicle->second->time_area_over_time = current_time;

		//			deal_alarm_card(it_card_vehicle->second, mp_card_list_area_over_time_vehicle, is_true, AF_CARD_AREA_OVER_TIME);
		//		}
		//		over_time_vehicle++;
		//	}
		//	deal_area_over_speed(it_card_vehicle->second);
		//	//else if(it_card_vehicle->second->is_area_over_time)
		//		//{ // 理论上不会走这条分支，应该走cards_leave_area()
		//	//	is_true = false;
		//	//	it_card_vehicle->second->is_area_over_time = false;
		//	//	deal_alarm_card(it_card_vehicle->second, mp_card_list_area_over_time_vehicle, is_true, AF_CARD_AREA_OVER_TIME);
		//	//}				
		//}
		//it_Area->second->count_person = it_Area->second->area_card_list_person;
		//it_Area->second->count_vehicle =  it_Area->second->area_card_list_vehicle;
		//it_Area->second->count_area_over_time_person = over_time_person;
		//it_Area->second->count_area_over_time_vehicle = over_time_vehicle;
		//if (AREA_TYPE_FORBIDDEN == it_Area->second->area_type_id)
		//{
		//	count_person = it_Area->second->area_card_list_person->size();
		//	if (count_person > 0)
		//	{
		//		//人员进入禁止区域开始报警
		//		if(!it_Area->second->is_area_forbidden_person){
		//			it_Area->second->is_area_forbidden_person = true;
		//			it_Area->second->count_area_forbidden_person = count_person;
		//			it_Area->second->time_forbidden_person = current_time;

		//			INT64 ev_id = CFunctions::GetMicroSecond();
		//			std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
		//			ev->status = ES_START;
		//			ev->ev_type = ET_CARD_AREA_FORBIDDEN_PERSON;
		//			ev->obj_type = OT_AREA;
		//			ev->obj_id = CFunctions::int2string(it_Area->second->area_id);

		//			ev->map_id = it_Area->second->map_id;
		//			ev->area_id = it_Area->second->area_id;

		//			ev->limit_value = it_Area->second->over_count_person;
		//			ev->cur_value = count_person;
		//			ev->is_sent = false;

		//			it_Area->second->m_event_list[ET_CARD_AREA_FORBIDDEN_PERSON] = ev_id;
		//			store_data_event(ev);
		//			add_event(ev);
		//			debug_print_syslog(0,"[card_enter_forbidden_area] begin alarm : area_id: %d, counts: %d",it_Area->second->area_id,count_person);
		//		}
		//	} 
		//	else
		//	{
		//		if(it_Area->second->is_area_forbidden_person)
		//		{
		//			it_Area->second->is_area_forbidden_person = false; // 结束报警

		//			INT64 ev_id = it_Area->second->m_event_list[ET_CARD_AREA_FORBIDDEN_PERSON];
		//			if(ev_id > 0){
		//				EventMap::iterator it_ev = mp_event_list->find(ev_id);
		//				if(it_ev != mp_event_list->end()){
		//					it_ev->second->status = ES_END;
		//					it_ev->second->cur_time = time(NULL);
		//					it_ev->second->cur_value = count_person;
		//					it_ev->second->is_sent = false;
		//					store_data_event(it_ev->second);
		//					add_event(it_ev->second);
		//				}					
		//			}
		//			it_Area->second->m_event_list[ET_CARD_AREA_FORBIDDEN_PERSON] = 0;
		//			debug_print_syslog(0,"[card_enter_forbidden_area] close alarm: area_id: %d, counts: %d",it_Area->second->area_id,count_person);
		//		}
		//	}
		//}
		if(it_Area->second->over_count_person != 0)
		{
			count_person = it_Area->second->area_card_list_person->size();
			it_Area->second->count_person = count_person;
			if( count_person > it_Area->second->over_count_person )
			{ // 区域人员超员
				string s ;
				for (CardMap::iterator it_card_i = it_Area->second->area_card_list_person->begin();it_card_i != it_Area->second->area_card_list_person->end();it_card_i++)
				{
					s += it_card_i->second->card_id;
					s += "&";
				}
				debug_print_syslog(0,"[lemon area_card_over_person.%d]:%s",it_Area->second->area_id,s.c_str());

				if(!it_Area->second->is_area_over_count_person)
				{
					it_Area->second->is_area_over_count_person = true;
					it_Area->second->count_area_over_count_person = count_person - it_Area->second->over_count_person;
					it_Area->second->time_over_count_person = current_time;

					INT64 ev_id = CFunctions::GetMicroSecond();
					std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
					ev->status = ES_START;
					ev->ev_type = ET_AREA_OVER_COUNT_PERSON;
					ev->obj_type = OT_AREA;
					ev->obj_id = CFunctions::int2string(it_Area->second->area_id);

					ev->map_id = it_Area->second->map_id;
					ev->area_id = it_Area->second->area_id;

					ev->limit_value = it_Area->second->over_count_person;
					ev->cur_value = count_person;
					ev->is_sent = false;

					it_Area->second->m_event_list[ET_AREA_OVER_COUNT_PERSON] = ev_id;
					store_data_event(ev);
					add_event(ev);

					//deal_alarm_area(it_Area->second, mp_area_over_count_person, true, AF_AREA_OVER_COUNT,0);
				}
				else
				{
					INT64 ev_id = it_Area->second->m_event_list[ET_AREA_OVER_COUNT_PERSON];
					if(ev_id > 0)
					{
						EventMap::iterator it_ev = mp_event_list->find(ev_id);
						if(it_ev != mp_event_list->end())
						{
							it_ev->second->limit_value = it_Area->second->over_count_person;
							it_ev->second->cur_value = count_person;
							it_ev->second->is_sent = false;
						}
					}
				}
			}
			else
			{
				if(it_Area->second->is_area_over_count_person){ // 结束超员
					it_Area->second->is_area_over_count_person = false;

					INT64 ev_id = it_Area->second->m_event_list[ET_AREA_OVER_COUNT_PERSON];
					if(ev_id > 0){
						EventMap::iterator it_ev = mp_event_list->find(ev_id);
						if(it_ev != mp_event_list->end()){
							it_ev->second->status = ES_END;
							it_ev->second->cur_time = time(NULL);
							it_ev->second->cur_value = count_person;
							it_ev->second->is_sent = false;
							store_data_event(it_ev->second);
							add_event(it_ev->second);
						}					
					}
					it_Area->second->m_event_list[ET_AREA_OVER_COUNT_PERSON] = 0;

					//deal_alarm_area(it_Area->second, mp_area_over_count_person, false, AF_AREA_OVER_COUNT);
				}
			}
		}
		// 区域人员超时
		//	if(count_over_time_person > 0){
		//		if(!it_Area->second->is_area_over_time_person){
		//			it_Area->second->is_area_over_time_person = true;
		//			it_Area->second->time_over_time_person = current_time;
		//			deal_alarm_area(it_Area->second, mp_area_over_time_person, true, AF_AREA_OVER_TIME);
		//		}			
		//	}else{
		//		if(it_Area->second->is_area_over_time_person){ // 结束
		//			it_Area->second->is_area_over_time_person = false;
		//			deal_alarm_area(it_Area->second, mp_area_over_time_person, false, AF_AREA_OVER_TIME);
		//		}
		//	}
		//}
		//// 区域禁入 车辆
		//if(AREA_TYPE_FORBIDDEN == it_Area->second->area_type_id){
		//	if(count_vehicle > 0){
		//		if(!it_Area->second->is_area_forbidden_vehicle){
		//			it_Area->second->is_area_forbidden_vehicle = true;
		//			it_Area->second->count_area_forbidden_vehicle = count_vehicle;
		//			it_Area->second->time_forbidden_vehicle = current_time;
		//			deal_alarm_area(it_Area->second, mp_area_forbidden_vehicle, true, AF_AREA_FORBIDDEN);
		//		}
		//	}else{
		//		if(it_Area->second->is_area_forbidden_vehicle){
		//			it_Area->second->is_area_forbidden_vehicle = false; // 结束报警
		//			deal_alarm_area(it_Area->second, mp_area_forbidden_vehicle, false, AF_AREA_FORBIDDEN);
		//		}
		//	}
		/*	}
		else */
		if(it_Area->second->over_count_vehicle != 0 )
		{
			count_vehicle = it_Area->second->area_card_list_vehicle->size();
			it_Area->second->count_vehicle = count_vehicle;
			if(count_vehicle > it_Area->second->over_count_vehicle){  // 区域车辆超员
				if(!it_Area->second->is_area_over_count_vehicle){
					it_Area->second->is_area_over_count_vehicle = true;
					it_Area->second->count_area_over_count_vehicle = count_vehicle - it_Area->second->over_count_vehicle;
					it_Area->second->time_over_count_vehicle = current_time;

					INT64 ev_id = CFunctions::GetMicroSecond();
					std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
					ev->status = ES_START;
					ev->ev_type = ET_AREA_OVER_COUNT_VEHICLE;
					ev->obj_type = OT_AREA;
					ev->obj_id = it_Area->second->area_id;
					ev->cur_time = time(NULL);

					ev->map_id = it_Area->second->map_id;
					ev->area_id = it_Area->second->area_id;
					ev->x = 0;
					ev->y = 0;

					ev->limit_value = it_Area->second->over_count_person;
					ev->cur_value = count_vehicle;
					ev->is_sent = false;

					it_Area->second->m_event_list[ET_AREA_OVER_COUNT_VEHICLE] = ev_id;
					store_data_event(ev);
					add_event(ev);

					/*deal_alarm_area(it_Area->second, mp_area_over_count_vehicle, true, AF_AREA_OVER_COUNT);
					Sleep(1);*/
				}
				else
				{
					INT64 ev_id = it_Area->second->m_event_list[ET_AREA_OVER_COUNT_VEHICLE];
					if(ev_id > 0)
					{
						EventMap::iterator it_ev = mp_event_list->find(ev_id);
						if(it_ev != mp_event_list->end())
						{
							it_ev->second->limit_value = it_Area->second->over_count_person;
							it_ev->second->cur_value = count_vehicle;
							it_ev->second->cur_time = time(NULL);
							it_ev->second->is_sent = false;
						}
					}
				}
			}
			else
			{
				it_Area->second->is_area_over_count_vehicle = false; // 结束

				INT64 ev_id = it_Area->second->m_event_list[ET_AREA_OVER_COUNT_VEHICLE];
				if(ev_id > 0){
					EventMap::iterator it_ev = mp_event_list->find(ev_id);
					if(it_ev != mp_event_list->end()){
						it_ev->second->status = ES_END;
						it_ev->second->cur_time = time(NULL);
						it_ev->second->cur_value = count_vehicle;
						it_ev->second->is_sent = false;
						store_data_event(it_ev->second);
						add_event(it_ev->second);
					}					
				}
				it_Area->second->m_event_list[ET_AREA_OVER_COUNT_VEHICLE] = 0;

				//deal_alarm_area(it_Area->second, mp_area_over_count_vehicle, false, AF_AREA_OVER_COUNT);
			}		
			// 区域车辆超时
			//if(count_over_time_vehicle > 0){
			//	if(!it_Area->second->is_area_over_time_vehicle){
			//		it_Area->second->is_area_over_time_vehicle = true;
			//		it_Area->second->time_over_time_vehicle = current_time;
			//		deal_alarm_area(it_Area->second, mp_area_over_time_vehicle, true, AF_AREA_OVER_TIME);
			//	}
			//}else{
			//	if(it_Area->second->is_area_over_time_vehicle){ // 结束
			//		it_Area->second->is_area_over_time_vehicle = false;
			//		deal_alarm_area(it_Area->second, mp_area_over_time_vehicle, false, AF_AREA_OVER_TIME);
			//		// 写入数据库
			//	}
			//}
		}
	}
}

void CYAServerDlg::card_enter_mine(std::shared_ptr<Card> card /*Card* card*/)
{
	if(!card->is_pos_state_changed()){ 
		// 位置没有变化
		//	debug_print_syslog(0,"[lemon card_enter_mine]%s",card->card_id.c_str());
		if(PDT_DOWN == card->PosState())
		{
			if(CT_PERSON == card->card_type){
				if(!card->is_mine_over_time && difftime(time(NULL), card->get_working_time()) > sls_setting.over_time_person && sls_setting.over_time_person != 0){
					deal_alarm_card(card, mp_card_list_over_time_person, true,  AF_CARD_OVER_TIME);
				}
				else if (card->is_mine_over_time && difftime(time(NULL), card->get_working_time()) < sls_setting.over_time_person)
				{
					deal_alarm_card(card, mp_card_list_over_time_person, false,  AF_CARD_OVER_TIME);
				}
				//井下超员
			}else if(CT_VEHICLE == card->card_type|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type)
			{
				if(!card->is_mine_over_time && difftime(time(NULL), card->get_working_time()) > sls_setting.over_time_vehicle && sls_setting.over_time_vehicle != 0){
					deal_alarm_card(card, mp_card_list_over_time_vehicle, true, AF_CARD_OVER_TIME);
				}
				else if (card->is_mine_over_time && difftime(time(NULL), card->get_working_time()) < sls_setting.over_time_vehicle)
				{
					deal_alarm_card(card, mp_card_list_over_time_vehicle, false, AF_CARD_OVER_TIME);
				}
			}
		}
	}else{
		debug_print_syslog(0,"[lemon card_enter_mine_]%s,%d",card->card_id.c_str(),card->PosState());
		card_enter_mine(card, (POS_DEVICE_TYPE)card->PosState());
	}
}

void CYAServerDlg::card_enter_mine( std::shared_ptr<Card> card, POS_DEVICE_TYPE pdt )
{
	card->PosStateOld(pdt);
	card->PosState(pdt);	
	if(CT_PERSON == card->card_type) // 车辆不推送升入井消息
	{
		//lemon 2017/08/01
		if (need_display_verification(card))
		{
			send_json_data(JSON_CMD_VALUE_PUSH, get_json_down_and_up(card));
		}
	}
	if(PDT_DOWN == pdt)
	{ // 入井
		card_down_mine(card);
		if( PATROL_LEVEL_ID == card->level_id){
			init_patrol_info(card->card_id);
		}
	}
	else if(PDT_UP ==pdt)
	{
		debug_print_syslog(0,"[lemon_upmine]%s",card->card_id.c_str());
		// 升井，补全离开区域时间
		//store_data_card(card, HIS_AREA_LOCATION_LEAVE);
		if(PATROL_LEVEL_ID == card->level_id){
			delete_patrol_info(card->card_id);
		}

		//process_driving_face_end_service(card);
		card_up_mine(card);
	}
}

void CYAServerDlg::card_enter_map(std::shared_ptr<Card> card /*Card* card*/ )
{
	if(card->map_id == card->map_id_old) return ;
	// 离开原地图，进入新地图
	MapInfoMap::iterator it_map_old = mp_map_list.find(card->map_id_old);
	if(it_map_old != mp_map_list.end()){
		if(CT_PERSON == card->card_type){
			CardMap::iterator it_card = it_map_old->second->map_card_list_person.find(card->card_id);
			if(it_card != it_map_old->second->map_card_list_person.end()){
				it_map_old->second->map_card_list_person.erase(it_card);
			}
		}else if(CT_VEHICLE == card->card_type|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type){
			CardMap::iterator it_card = it_map_old->second->map_card_list_vehicle.find(card->card_id);
			if(it_card != it_map_old->second->map_card_list_vehicle.end()){
				it_map_old->second->map_card_list_vehicle.erase(it_card);
			}
		}
	}
	card->map_id_old = card->map_id;
	MapInfoMap::iterator it_map = mp_map_list.find(card->map_id);
	if(it_map != mp_map_list.end()){
		card->map_scale = it_map->second->map_scale;
		if(CT_PERSON == card->card_type){
			it_map->second->map_card_list_person.insert(make_pair(card->card_id, card));
		}else  if(CT_VEHICLE == card->card_type|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type){
			it_map->second->map_card_list_vehicle.insert(make_pair(card->card_id, card));
		}
	}
}

//卡card进入区域  异常
void CYAServerDlg::card_enter_area(std::shared_ptr<Card> card /* Card* card*/)
{
	if(CT_TUNNELBORING_MACHINE == card->card_type){
		int area_id = get_drivingface_area_id(card->card_id);
		if (-1 != area_id)
		{
			debug_print_syslog(0,"drivingface area id: %d old_area_id: %d,",area_id,card->area_id);
			card->area_id = area_id;
			return;
		}
	}

	if (card.use_count() == 0)
	{
		return;
	}
	time_t current_time(time(NULL));
	if(card->b_pos_change){
		debug_print_syslog(0,"[card_enter_area]%s...%d  (%.2f,%.2f)",card->card_id.c_str(),card->area_id,card->x,card->y);
		bool b_in_area = false;
		_point p1, p2;
		double r, scale;
		p1.x = card->x, p1.y = card->y, p1.z = card->z;

		AreaMap::iterator it_area_cur = mp_area_list.find(card->area_id);
		int forbidden_area_id = 0;
		forbidden_area_id = get_forbidden_area_id(p1);
		bool need_change = true;
		if (it_area_cur!=mp_area_list.end())
		{
			if (it_area_cur->second->area_type_id!=AREA_TYPE_FORBIDDEN && 0 == forbidden_area_id)
			{
				need_change = false;
			}else if (AREA_TYPE_FORBIDDEN == it_area_cur->second->area_type_id && forbidden_area_id!=0)
			{
				need_change = false;
			}
		}	

		if (!need_change)
		{
			if(it_area_cur != mp_area_list.end()){ 
				// 在区域列表中存在此区域 
				if(it_area_cur->second->is_in_polygon(p1)) { 
					bool is_true = false;
					std::shared_ptr<CardMap> destlist = nullptr;
					// 卡所在区域没有变化  判断是否超时
					if (card->card_type == CT_PERSON)
					{
						is_true = difftime(current_time, CFunctions::systime_to_timet(card->enter_area_time)) > it_area_cur->second->over_time_person;
						destlist = mp_card_list_area_over_time_person;
						if (!is_true && card->is_area_over_time)
						{
							deal_alarm_card(card,destlist,false,AF_CARD_AREA_OVER_TIME);
						}
						if (it_area_cur->second->over_time_person == 0)
						{
							is_true = false;
						}
					}
					else if (card->card_type == CT_VEHICLE|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type)
					{
						is_true = difftime(current_time, CFunctions::systime_to_timet(card->enter_area_time)) > it_area_cur->second->over_time_vehicle;
						destlist = mp_card_list_area_over_time_vehicle;
						if (!is_true && card->is_area_over_time)
						{
							deal_alarm_card(card,destlist,false,AF_CARD_AREA_OVER_TIME);
						}
						//////////////////////////////////////////////////////////////////////////
						//判断是否超速
						deal_area_over_speed(card);
						if (it_area_cur->second->over_time_vehicle == 0)
						{
							is_true = false;
						}
					}
					if(is_true)
					{
						if(!card->is_area_over_time)
						{
							card->is_area_over_time = true;
							card->time_area_over_time = current_time;
							deal_alarm_card(card, destlist, is_true, AF_CARD_AREA_OVER_TIME);
							if (card->card_type == CT_PERSON)
							{
								it_area_cur->second->count_area_over_time_person++;
							}
							else if (card->card_type == CT_VEHICLE|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type)
							{
								it_area_cur->second->count_area_over_time_vehicle++;
							}
						}
					}
	
					return;
				}
			}
		}
		
		debug_print_syslog(0,"[card_enter_area  1]%s...%d  (%.2f,%.2f)",card->card_id.c_str(),card->area_id,card->x,card->y);
		int old_area_id = card->area_id;

		AreaMap::iterator it_area = mp_area_list.begin();
		forbidden_area_id = get_forbidden_area_id(p1);
		if (forbidden_area_id!=0)
		{
			it_area = mp_area_list.find(forbidden_area_id);
			debug_print_syslog(0,"[card_enter_forbidden_area] card_id: %s, area_id: %d, x: %.4f, y: %.4f",card->card_id.c_str(),forbidden_area_id,p1.x,p1.y);
		}else{
			it_area = mp_area_list.begin();
		}
		for(; it_area != mp_area_list.end(); ++it_area){
			if(card->map_id == it_area->second->map_id){ 
				// 必须在同一地图内
				if(it_area->second->is_in_polygon(p1)){ 
					// 在区域内
					if(it_area_cur != mp_area_list.end()){ 
						// 离开区域
						store_data_card(card, HIS_AREA_LOCATION_LEAVE);
						card_leave_area(card, it_area_cur->second);
					}
					card->pre_area_id = card->area_id;
					card->area_id = it_area->second->area_id;
					card->enter_area_time = card->deal_time;
					// lihongzhen  2017/8/28 停车场区域的车辆不要会车效果
					if(AREA_TYPE_NO_COVER == it_area->second->area_type_id || AREA_TYPE_SPECIAL == it_area->second->area_type_id)
					{
						card->bInSpecailArea = true;
					}
					else
					{
						card->bInSpecailArea = false;
					}					
					//处理区域超速告警
					if (card->card_type == CT_VEHICLE|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type)
					{
						//判断是否超速，先将计数器清零再判断
						card->m_indexCardSpeed = 0;
						card->m_indexCardSpeed_normal = 0;
						deal_area_over_speed(card);
					}

					set_card_pos_state(card);

					if(CT_PERSON == card->card_type){
						it_area->second->area_card_list_person->insert(make_pair(card->card_id, card));
						if(AREA_TYPE_FORBIDDEN == it_area->second->area_type_id){
							deal_alarm_card(card, mp_card_list_forbidden_person, true, AF_CARD_AREA_FORBIDDEN);
							debug_print_syslog(0,"[card_enter_forbidden_area] enter forbidden area: area_id: %d",it_area->second->area_id);
						}
						else
						{
							deal_alarm_card(card, mp_card_list_forbidden_person, false, AF_CARD_AREA_FORBIDDEN);
							debug_print_syslog(0,"[card_enter_forbidden_area] leave forbidden area: area_id: %d",it_area->second->area_id);
						}
					}else if(CT_VEHICLE == card->card_type|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type){
						//进入临界区，防止多个线程同时操作map
						EnterCriticalSection(&m_csAreaList);

						it_area->second->area_card_list_vehicle->insert(make_pair(card->card_id, card));

						//退出临界区
						LeaveCriticalSection(&m_csAreaList);
					}
					b_in_area = true;
					break;
				}
			}
		}

		if(!b_in_area){	
			// 找不到区域，使用分站所属区域
			//从区域列表中查找卡所属分站的区域ID
			AreaMap::iterator it_area_reader = mp_area_list.find(card->p_reader->area_id);
			if(it_area_reader == mp_area_list.end()){
				return;
			}
			if(card->area_id == it_area_reader->second->area_id){
				return;
			}

			AreaMap::iterator it_area_exists = mp_area_list.find(card->area_id);
			if(it_area_exists != mp_area_list.end()){ 
				store_data_card(card, HIS_AREA_LOCATION_LEAVE);
				card_leave_area(card, it_area_exists->second);
			}
			card->area_id = it_area_reader->second->area_id;
			card->enter_area_time = card->deal_time;
			card->bInSpecailArea = false;
			//区域超速告警
			if (card->card_type == CT_VEHICLE|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type)
			{
				//判断是否超速，先将计数器清零再判断
				card->m_indexCardSpeed = 0;
				card->m_indexCardSpeed_normal = 0;
				deal_area_over_speed(card);
			}

			set_card_pos_state(card);

			if(CT_PERSON == card->card_type){
				it_area_reader->second->area_card_list_person->insert(make_pair(card->card_id, card));
				if(AREA_TYPE_FORBIDDEN == it_area_reader->second->area_type_id){
					deal_alarm_card(card, mp_card_list_forbidden_person, true, AF_CARD_AREA_FORBIDDEN);
				}
				else
				{
					deal_alarm_card(card, mp_card_list_forbidden_person, false, AF_CARD_AREA_FORBIDDEN);
				}
			}else if(CT_VEHICLE == card->card_type|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type){
				//进入临界区，防止多个线程同时操作map
				EnterCriticalSection(&m_csAreaList);

				it_area_reader->second->area_card_list_vehicle->insert(make_pair(card->card_id, card));

				//退出临界区
				LeaveCriticalSection(&m_csAreaList);
			}
		}
	}
	else
	{
		if(PDT_UP ==  card->p_reader->pos_state || LOCATE_TYPE::LT_READER == theApp.locate_type) // 井上按照分站所属区域划分
		{
			debug_print_syslog(0,"[card_enter_area]%s.preader:%d,careaid:%d,state:%d",card->card_id.c_str(),card->p_reader->area_id,card->area_id,card->PosState());
			// 找不到区域，使用分站所属区域
			AreaMap::iterator it_area_reader = mp_area_list.find(card->p_reader->area_id);
			if(it_area_reader == mp_area_list.end()){
				return;
			}
			if(card->area_id == it_area_reader->second->area_id){
				return;
			}

			AreaMap::iterator it_area_exists = mp_area_list.find(card->area_id);
			if(it_area_exists != mp_area_list.end()){ 
				store_data_card(card, HIS_AREA_LOCATION_LEAVE);
				card_leave_area(card, it_area_exists->second);
			}
			card->area_id = it_area_reader->second->area_id;

			card->enter_area_time = card->deal_time;

			debug_print_syslog(0,"[card_enter_area_]%s.preader:%d,careaid:%d,state:%d",card->card_id.c_str(),card->p_reader->area_id,card->area_id,card->PosState());
			set_card_pos_state(card);
			debug_print_syslog(0,"[card_enter_area_1]%s.preader:%d,careaid:%d,state:%d",card->card_id.c_str(),card->p_reader->area_id,card->area_id,card->PosState());
			if(CT_PERSON == card->card_type){
				it_area_reader->second->area_card_list_person->insert(make_pair(card->card_id, card));
				if(AREA_TYPE_FORBIDDEN == it_area_reader->second->area_type_id){
					deal_alarm_card(card, mp_card_list_forbidden_person, true, AF_CARD_AREA_FORBIDDEN);
				}
				else
				{
					deal_alarm_card(card, mp_card_list_forbidden_person, false, AF_CARD_AREA_FORBIDDEN);
				}
			}else if(CT_VEHICLE == card->card_type || CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type){
				//进入临界区，防止多个线程同时操作map
				EnterCriticalSection(&m_csAreaList);

				it_area_reader->second->area_card_list_vehicle->insert(make_pair(card->card_id, card));

				//退出临界区
				LeaveCriticalSection(&m_csAreaList);
			}
		}
		else
		{
			return ;
		}
	}

	card->m_area_changed = true;
	// 保存区域信息
	store_data_card(card, HIS_AREA_LOCATION_ENTER);
}

void CYAServerDlg::card_enter_special_area(std::shared_ptr<Card> card, int special_area_id)
{
	if (card.use_count() == 0)
	{
		return;
	}

	if(card->area_id == special_area_id){
		return ;
	}
	card->area_id = special_area_id;
	card->enter_area_time = card->deal_time;
	card->bInSpecailArea = true;
	set_card_pos_state(card);

	AreaMap::iterator it_area = mp_area_list.find(special_area_id);
	if(it_area != mp_area_list.end())
	{
		if(CT_PERSON == card->card_type)
		{
			it_area->second->area_card_list_person->insert(make_pair(card->card_id, card));
			if(AREA_TYPE_FORBIDDEN == it_area->second->area_type_id)
			{
				deal_alarm_card(card, mp_card_list_forbidden_person, true, AF_CARD_AREA_FORBIDDEN);
			}
			else
			{
				deal_alarm_card(card, mp_card_list_forbidden_person, false, AF_CARD_AREA_FORBIDDEN);
			}
		}
		else if(CT_VEHICLE == card->card_type|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type)
		{

			//进入临界区，防止多个线程同时操作map
			EnterCriticalSection(&m_csAreaList);

			it_area->second->area_card_list_vehicle->insert(make_pair(card->card_id, card));

			//退出临界区
			LeaveCriticalSection(&m_csAreaList);

			//if(AREA_TYPE_FORBIDDEN == it_area->second->area_type_id)
			//{
			//	deal_alarm_card(card, mp_card_list_forbidden_vehicle, true, AF_CARD_AREA_FORBIDDEN);
			//}
		}
	}
	debug_print_syslog(0, "x: %f, y: %f, lx: %f,ly: %f,area_id: %d", 
		card->x, card->y, card->last_x, card->last_y, card->area_id);

	// 保存区域信息
	store_data_card(card, HIS_AREA_LOCATION_ENTER);
	store_data_card(card,HIS_LOCATION);
}

void CYAServerDlg::card_leave_area(std::shared_ptr<Card> card, std::shared_ptr<Area> area /*Card* card, Area* area*/)
{
	// 从列表中删除
	std::shared_ptr<CardMap> card_map = nullptr;
	std::shared_ptr<CardMap> alarm_card_map = nullptr;
	std::shared_ptr<CardMap> alarm_forbidden_map = nullptr;
	if(CT_PERSON == card->card_type){
		card_map = area->area_card_list_person;
		alarm_card_map = mp_card_list_area_over_time_person;
		alarm_forbidden_map = mp_card_list_forbidden_person;
	}else if(CT_VEHICLE == card->card_type || CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type )
	{
		card_map = area->area_card_list_vehicle;
		alarm_card_map = mp_card_list_area_over_time_vehicle;
		alarm_forbidden_map = mp_card_list_forbidden_vehicle;
	}
	else if(CT_COALMINING_MACHINE == card->card_type || CT_TUNNELBORING_MACHINE == card->card_type || CT_SIMULATE_CARD == card->card_type)
	{
		return;
	}
	//lemon 2017/08/06 这个地方是离开区域进入新区域
	//这里不应该判断吧，而且并没有对is_area_over_time进行赋值
	CardMap::iterator it_card = card_map->find(card->card_id);
	if(it_card != card_map->end()){
		// 如果区域超时 离开时
		if(it_card->second->is_area_over_time){
			it_card->second->is_area_over_time = false;
			deal_alarm_card(card, alarm_card_map, false, AF_CARD_AREA_OVER_TIME);
			if (CT_PERSON == card->card_type)
			{
				area->count_area_over_time_person --;
			}
			else if (CT_VEHICLE == card->card_type|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type)
			{
				area->count_area_over_time_vehicle --;
			}
		}
		// 先处理，后删除-
		if (CT_PERSON == card->card_type  || CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type)
		{
			deal_alarm_card(card, alarm_forbidden_map, false, AF_CARD_AREA_FORBIDDEN);
		}
		deal_alarm_card(card,area->area_card_list_over_speed,false,AF_CARD_AREA_OVER_SPEED);
		card->m_indexCardSpeed  = 0;
		card_map->erase(it_card);
	}
}

void CYAServerDlg::reset_map_card()
{
	MapInfoMap::iterator it_map = mp_map_list.begin();
	for(; it_map != mp_map_list.end(); ++ it_map){
		it_map->second->map_card_list_person.erase(it_map->second->map_card_list_person.begin(), it_map->second->map_card_list_person.end());
		it_map->second->map_card_list_vehicle.erase(it_map->second->map_card_list_vehicle.begin(), it_map->second->map_card_list_vehicle.end());
	}
}

bool CYAServerDlg::is_in_rectangle( _point p, double dblleft, double dbltop, double dblright, double dblbottom )
{
	return (p.x >= dblleft && p.x <= dblright && p.y >= dbltop && p.y <= dblbottom);
}

bool CYAServerDlg::is_in_circle( _point p1, _point p2, double r, double scale )
{
	return sqrt((p2.x - p1.x) * (p2.x - p1.x) +  (p2.y - p1.y) * (p2.y - p1.y)) <= r * scale;
}

//1秒周期中调用了本函数，先构造json，然后发送之
void CYAServerDlg::package_data()
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_223);
	g_position_string = get_json_card_statistic();
	// 定位数据
	if(g_position_string == ""){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_224);
		return ;
	}	
}

void CYAServerDlg::package_data_test()
{
	Json::Value root;
	Json::Value valStaffer;
	Json::Value valStaffers;
	Json::Value valDistance;
	Json::Value valDist;
	Json::Value valReaders;
	Json::Value valReader;
	int nCnt = 0;
	std::string strJson;
	for(int i = 1; i < 4; i++){
		valStaffer["id"] = i;
		valStaffer["x"] = 50 * (m_nCountClick + i);
		valStaffer["y"] = 50 * sin(20.0) * (m_nCountClick + i);
		valStaffers.append(valStaffer);
		nCnt++;
	}
	root["staffer"] = valStaffers;
	root["reader"] = valReaders;
	if(nCnt == 0){
		return;
	}
	strJson = root.toFastString();
	send_json_data(JSON_CMD_VALUE_PUSH, strJson.c_str());
}

time_t CYAServerDlg::formatByteArray( std::string &strBuf, BYTE * buf, int nLen )
{
	char ch[5];
	for(int i = 0; i < nLen; i++)
	{
		sprintf_s(ch, "%.2X ", buf[i]);
		strBuf += ch;
		if((i + 1)%16 == 0)
		{
			strBuf += "\n";
		}
	}

	char _time[STR_LEN_TIME];
	SYSTEMTIME sys;
	GetLocalTime( &sys );
	sprintf(_time,"[%4d-%02d-%02d %02d:%02d:%02d.%03d]\n", sys.wYear, sys.wMonth,  sys.wDay, sys.wHour, sys.wMinute, sys.wSecond,sys.wMilliseconds);
	unsigned long long tmp_localtime = time(NULL) * 1000 + sys.wMilliseconds;
	strBuf = _time + strBuf;

	return tmp_localtime;
}

time_t CYAServerDlg::formatByteArray_s(std::string &strBuf, std::string ip,BYTE * buf, int nLen)
{
	char ch[5];
	for(int i = 0; i < nLen; i++)
	{
		sprintf_s(ch, "%.2X ", buf[i]);
		strBuf += ch;
		if((i + 1)%16 == 0)
		{
			strBuf += "\n";
		}
	}

	char _time[STR_LEN_TIME];
	SYSTEMTIME sys;
	GetLocalTime( &sys );
	sprintf(_time,"[%4d-%02d-%02d %02d:%02d:%02d.%03d],nLen: %d,", sys.wYear, sys.wMonth,  sys.wDay, sys.wHour, sys.wMinute, sys.wSecond,sys.wMilliseconds,nLen);
	unsigned long long tmp_localtime = time(NULL) * 1000 + sys.wMilliseconds;
	strBuf = _time + ip + "\n" + strBuf;

	return tmp_localtime;
}

void CYAServerDlg::OnBnExit()
{
	stop_and_exit();
}

void CYAServerDlg::OnBnSyncTime()
{
	std::map<uint64_t,std::string> m;
	m.insert(std::make_pair(1111,"0010000000333&0010000000273,1527659741,1527663343,1527659741&456.554&374,1527660641&385&361,1527661542&424&358,1527662443&607&520,"));
	uwb_alarm(m,false,nullptr);
}

CYAServerDlg::~CYAServerDlg()
{
	ws_close();

	mp_area_list_->clear();

	if (m_carmanage != NULL)
	{
		delete m_carmanage;
		m_carmanage = NULL;
	}
	m_bStop=true;
	m_Pthread->join();
}

void CYAServerDlg::OnConnected()
{
	is_websocket_ok = true;
	time_ws_connect = ::GetTickCount();
}

void CYAServerDlg::OnClosed( client::close_reason const& reason )
{
	int i = -1;
	if(reason == client::close_reason_drop){
		i = (int) reason;
	}else{
		i = (int) reason;
	}
	is_websocket_login = false;
	is_websocket_ok = false;
}

void CYAServerDlg::OnFailed()
{
	is_websocket_login = false;
	is_websocket_ok = false;
	_io->close();
}

void CYAServerDlg::ws_open()
{
	_io->connect(m_ws_url);

	CString strlog = _T("");

	wchar_t* p = CFunctions::c2wc(m_ws_url.c_str());
	strlog.Format(_T("%s: %s"), _T(LOG_CONNECT_WEB_SERVER), p);
	if(p){
		free(p);
		p = NULL;
	}

	show_log(strlog);
}

void CYAServerDlg::OnPushMessage()
{
}

void CYAServerDlg::store_data_card(std::shared_ptr<Card> card, int tag )
{
	char sql[LENGTH_SQL] = {0};
	char _time[STR_LEN_TIME], _time_ex[STR_LEN_TIME];
	struct tm local_time, local_time_ex; 
	time_t t = time(NULL);

	bool b_exec = false;

	switch(tag){
	case HIS_RAW_DATA:
		t = CFunctions::systime_to_timet(card->deal_time);
		localtime_s(&local_time, &t);
		strftime(_time, 30, "%Y-%m-%d %H:%M:%S", &local_time);
		break;
	case RPT_ATTEND_DOWN:
		localtime_s(&local_time, &card->down_time);
		strftime(_time, 30, "%Y-%m-%d %H:%M:%S", &local_time);
		break;
	case RPT_ATTEND_UP:
		localtime_s(&local_time, &card->up_time);
		strftime(_time, 30, "%Y-%m-%d %H:%M:%S", &local_time);
		break;
	case HIS_AREA_LOCATION_ENTER:
	case HIS_AREA_LOCATION_LEAVE:
	case HIS_LOCATION:
		sprintf_s(_time,
			STR_LEN_TIME,
			"%u-%u-%u %u:%u:%u.%u",
			card->deal_time.wYear,card->deal_time.wMonth,card->deal_time.wDay,
			card->deal_time.wHour,card->deal_time.wMinute,card->deal_time.wSecond,card->deal_time.wMilliseconds);
		break;
	}

	switch(tag){
	case HIS_LOCATION:
		{
			if(card->map_id != 0 && card->area_id != 0){
				b_exec = true;
				switch (card->card_type)
				{
				case CT_PERSON:
					sprintf_s(sql, LENGTH_SQL, 
						"INSERT IGNORE INTO his_location_staff(card_id, staff_id, cur_time, x, y, z, map_id, area_id, state,speed,mileage, landmark_id, direction_mapper_id, landmark_dist) VALUES(%s, %d, '%s', %.3f, %.3f, %.3f, %d, %d, %d,%.3f,%.4f, %d, %d, %.4f);",  
						card->card_id.c_str(), card->id, _time, card->x_offset_after(), card->y_offset_after(), card->z_offset_after(), card->map_id, card->area_id, card->state,card->get_speed(),card->mileage, card->landmark_id, card->landmark_direction, card->landmark_dis);
					break;
				case CT_VEHICLE:
				case CT_COALMINING_MACHINE:
				case CT_TUNNELBORING_MACHINE:
					sprintf_s(sql, LENGTH_SQL, 
						"INSERT IGNORE INTO his_location_vehicle(card_id, vehicle_id, cur_time, x, y, z, map_id, area_id, state,speed,mileage, landmark_id, direction_mapper_id, landmark_dist) VALUES(%s, %d, '%s', %.3f, %.3f, %.3f, %d, %d, %d,%.3f,%.4f, %d, %d, %.4f);",  
						card->card_id.c_str(), card->id, _time, card->x_offset_after(), card->y_offset_after(), card->z_offset_after(), card->map_id, card->area_id, card->state,card->get_speed(),card->mileage, card->landmark_id, card->landmark_direction, card->landmark_dis);
					break;
				}				
			}
			break;
		}
	case HIS_RAW_DATA:
		{
			b_exec = true;
			sprintf_s(sql, LENGTH_SQL,
				"INSERT IGNORE INTO his_raw_data(card_id, reader_id, antenna_id, reader_stamp, card_stamp, \
				fly_time, distance, ranging_type, power_state, accelerate, his_time, rec_time ) \
				VALUES(%s, %d, %d, %d, %d, %lld, %4.f, %d, %d, %d, '%s', '%s');",
				card->card_id.c_str(), card->reader_id, card->antenna_id, card->reader_tickcount, card->time_stamp,
				card->flying_time, card->distance, card->ranging_type, card->power_state, card->accelerate_state,
				card->str_his_time.c_str(), card->str_rec_time.c_str());
			break;
		}
	case HIS_AREA_LOCATION_ENTER:
		{
			if(card->map_id != 0 && card->area_id != 0){
				b_exec = true;
				switch (card->card_type)
				{
				case CT_PERSON:
					sprintf_s(sql, LENGTH_SQL,
						"call add_area_staff(%s, %d, %d, %d, '%s','%s');",
						card->card_id.c_str(), card->id, card->area_id, card->map_id, _time, _time);
					store_worktime_detail(card,tag,_time);
					break;
				case CT_VEHICLE:
				case CT_COALMINING_MACHINE:
				case CT_TUNNELBORING_MACHINE:
					sprintf_s(sql, LENGTH_SQL,
						"call add_area_vehicle(%s, %d, %d, %d, '%s','%s');",
						card->card_id.c_str(), card->id, card->area_id, card->map_id, _time, _time);
					break;
				}
			}
			break;
		}
	case HIS_AREA_LOCATION_LEAVE:
		{
			if(card->map_id != 0 && card->area_id != 0){
				b_exec = true;
				sprintf_s(_time_ex,
					STR_LEN_TIME,
					"%u-%u-%u %u:%u:%u.%u",
					card->enter_area_time.wYear,card->enter_area_time.wMonth,card->enter_area_time.wDay,
					card->enter_area_time.wHour,card->enter_area_time.wMinute,card->enter_area_time.wSecond,card->enter_area_time.wMilliseconds);

				switch (card->card_type)
				{
				case CT_PERSON:
					sprintf_s(sql, LENGTH_SQL,
						"call add_area_staff(%s, %d, %d, %d, '%s','%s');",
						card->card_id.c_str(), card->id, card->area_id, card->map_id, _time_ex, _time);
					store_worktime_detail(card,tag,_time);
					break;
				case CT_VEHICLE:
				case CT_COALMINING_MACHINE:
				case CT_TUNNELBORING_MACHINE:
					sprintf_s(sql, LENGTH_SQL,
						"call add_area_vehicle(%s, %d, %d, %d, '%s','%s');",
						card->card_id.c_str(), card->id, card->area_id, card->map_id, _time_ex, _time);
					break;
				}
			}
			break;
		}
	case RPT_ATTEND_DOWN:
		{
			//if(card->map_id != 0 && card->area_id != 0){
				b_exec = true;	
				switch (card->card_type)
				{
				case CT_PERSON:
					sprintf_s(sql, LENGTH_SQL,
						"CALL add_att_staff(%s, %d, '%s', '%s', %d, %d, %.3f);",
						card->card_id.c_str(), card->id, _time, _time, card->landmark_id, card->landmark_direction, card->landmark_dis);
					//二线工人工时利用率
					break;
				case CT_VEHICLE:
				case CT_COALMINING_MACHINE:
				case CT_TUNNELBORING_MACHINE:
					sprintf_s(sql, LENGTH_SQL,
						"CALL add_att_vehicle(%s, %d, '%s', '%s', %d, %d, %.3f);",
						card->card_id.c_str(), card->id, _time, _time, card->landmark_id, card->landmark_direction, card->landmark_dis);
					break;
				}
			//}
			break;
		}
	case RPT_ATTEND_UP:
		{
			if(card->map_id != 0 && card->area_id != 0){
				b_exec = true;
				string str_down_time = CFunctions::time_t2string(card->down_time);

				switch (card->card_type)
				{
				case CT_PERSON:
					sprintf_s(sql, LENGTH_SQL,
						"CALL add_att_staff(%s, %d, '%s', '%s', %d, %d, %.3f);",
						card->card_id.c_str(), card->id, str_down_time.c_str(), _time,card->landmark_id, card->landmark_direction, card->landmark_dis);
					//二线工人工时利用率
					break;
				case CT_VEHICLE:
				case CT_COALMINING_MACHINE:
				case CT_TUNNELBORING_MACHINE:
					sprintf_s(sql, LENGTH_SQL,
						"CALL add_att_vehicle(%s, %d, '%s', '%s', %d, %d, %.3f);",
						card->card_id.c_str(), card->id, str_down_time.c_str(), _time, card->landmark_id, card->landmark_direction, card->landmark_dis);
					break;
				}
			}
			break;
		}
	default:
		return;
	}

	if(b_exec){
		execute_sql(sql);
		debug_print_syslog(0,"exec_sql:%s",sql);
	}
}

/*
* 从配置文件中载入数据库配置
*
* param
*		无
*
* return
*		无
*/
void CYAServerDlg::load_param_from_ini()
{
	m_tcp_host = CFunctions::c2wc(theApp.tcp_host.c_str());
	m_nPort = theApp.tcp_port;
	m_ws_url = theApp.ws_url;
	m_ws_url_ex = theApp.ws_url_bk;


	if (m_ws_url.length() == 0)
	{
		m_ws_url = "ws://127.0.0.1:8086/";
	}
	// if (m_ws_url_ex == "")
	// {
	// 	m_ws_url_ex = "ws://127.0.0.1:8086/";
	// }

	int nBackup = atoi(theApp.dbbackup.c_str());
	//switch(nBackup){
	//case 0:
	m_db_setting.host = theApp.dbhost;
	m_db_setting.user = theApp.dbuser;
	m_db_setting.password = theApp.dbpwd;
	m_db_setting.dbname = theApp.dbname;
	m_db_setting.encoding = theApp.dbencoding;
	m_db_setting.port = theApp.dbport;
	//	break;
	//case 1:
	m_db_setting_bk.host = theApp.dbhost_bk;
	m_db_setting_bk.user = theApp.dbuser_bk;
	m_db_setting_bk.password = theApp.dbpwd_bk;
	m_db_setting_bk.dbname = theApp.dbname_bk;
	m_db_setting_bk.encoding = theApp.dbencoding_bk;
	m_db_setting_bk.port = theApp.dbport_bk;
	//	break;
	//}
	if((theApp.dbhost_bk.length() >0 && theApp.dbhost_bk != theApp.dbhost) || (theApp.dbname.length()>0 && theApp.dbname_bk != theApp.dbname))
	{
		g_StoreMultDatabase = true;
	}
	// 从配置文件中读取数据库配置
	m_DBSetting.Host = theApp.dbhost;
	m_DBSetting.User = theApp.dbuser;
	m_DBSetting.PWD = theApp.dbpwd;
	m_DBSetting.DBName = theApp.dbname;
	m_DBSetting.CharSet = "utf8";
	m_DBSetting.TimeOut = 5;
	m_DBSetting.PoolSize = 10;
}

int CYAServerDlg::init_dept()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	pRes = getMysqlRes("select dept_id, name from dat_dept order by rank;");
	if(NULL == pRes)
	{
		return 1;
	}

	std::shared_ptr<Dept> dept = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))	{
		DeptMap::iterator it = mp_dept_list.find(atoi(pRow[0]));		
		if(it != mp_dept_list.end()){
			dept = it->second;
		}else{
			dept = std::make_shared<Dept>(atoi(pRow[0]), pRow[1]);
			mp_dept_list.insert(make_pair(dept->dept_id, dept));
			nRow++;
		}
	}
	mysql_free_result(pRes);
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_DEPT), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}

int CYAServerDlg::init_level()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;

	pRes = getMysqlRes("select occupation_level_id from dat_occupation_level;");

	if(NULL == pRes)
	{
		return 1;
	}
	std::shared_ptr<OccLevel> level = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))	{
		OccLevelMap::iterator it = mp_occlevel_list.find(atoi(pRow[0]));		
		if(it != mp_occlevel_list.end()){
			level = it->second;
		}else{
			level = std::make_shared<OccLevel>(atoi(pRow[0]));
			mp_occlevel_list.insert(make_pair(level->occlevel_id, level));
			nRow++;
		}
	}
	mysql_free_result(pRes);
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_LEVEL), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}

/*
* 从数据库的dat_setting表初始化系统阈值，
* 包括：井下人员阈值，井下车辆阈值，人员超时阈值，车辆超时阈值，车辆超速阈值
*
* param
*		无
*
* return
*		无
*/
int CYAServerDlg::init_setting()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	pRes = getMysqlRes("select setting_id, name, type, value from dat_setting;");

	if (NULL == pRes)
	{
		return 1;
	}
	string name, val, type;
	while(pRow = mysql_fetch_row(pRes))	{
		name = pRow[1], type = pRow[2],	val = pRow[3];
		if("over_count_person" == name){
			sls_setting.over_count_person = atoi(val.c_str());
		}else if("over_count_vehicle" == name){
			sls_setting.over_count_vehicle = atoi(val.c_str());
		}else if("over_time_person" == name){
			sls_setting.over_time_person = atoi(val.c_str()) * 60; // 转为秒
		}else if("over_time_vehicle" == name){
			sls_setting.over_time_vehicle = atoi(val.c_str()) * 60; // 转为秒
		}else if("over_speed" == name){
			sls_setting.over_speed = atof(val.c_str());
		}else if("att_starttime_offset_staff" == name){
			sls_setting.att_starttime_offset_staff = atoi(val.c_str()) * 60;
		}else if("att_endtime_offset_staff" == name){
			sls_setting.att_endtime_offset_staff = atoi(val.c_str()) * 60;
		}else if("att_starttime_offset_vehicle" == name){
			sls_setting.att_starttime_offset_vehicle = atoi(val.c_str()) * 60;
		}else if("att_starttime_offset_vehicle" == name){
			sls_setting.att_endtime_offset_vehicle = atoi(val.c_str()) * 60;
		}else if("att_person_thre_hour" == name){
			sls_setting.att_person_thre_hour = atoi(val.c_str())*60*60;
		}else if("rear_end_distance"==name){
			sls_setting.rear_end_d=atof(val.c_str());
		}else if("rear_end_time"==name){
			sls_setting.rear_end_t=atoi(val.c_str());
		}else if ("geofault_warn"==name){
			sls_setting.geofault_warn_dis=atof(val.c_str());
		}
	}
	mysql_free_result(pRes);

	show_log(_T(LOG_INIT_SETTING));

	return 0;
}
void CYAServerDlg::deal_alarm_card_motionless(std::shared_ptr<NAMESPACE_POINT::card_interface> ci,bool flag)
{
	deal_alarm_card(std::dynamic_pointer_cast<Card>(ci),mp_card_list_motionless,flag,AF_CARD_MOTIONLESS);
}

void CYAServerDlg::deal_alarm_card(std::shared_ptr<Card> card, std::shared_ptr<CardMap> dest_card_list, bool is_alarm, ALARM_FLAG tag)
{
	if(is_alarm)
	{
		dest_card_list->insert(make_pair(card->card_id, card));
	}
	else
	{
		CardMap::iterator it_card = dest_card_list->find(card->card_id);
		if(it_card != dest_card_list->end())
		{
			//如果在呼叫列表内，取消呼叫
			if (ET_CARD_AREA_FORBIDDEN_PERSON == tag)
			{
				cancel_call(card->card_id);
			}
			dest_card_list->erase(it_card);
		}
		else
		{
			return;
		}
	}
	EVENT_TYPE et = ET_UNKNOWN;
	double limit_val = 0, cur_val = 0;

	AreaMap::iterator it_area = mp_area_list.find(card->area_id);
	if(it_area != mp_area_list.end()){
		et = ET_UNKNOWN;
		switch (tag)
		{
		case AF_CARD_OVER_TIME:
			{
				et = (card->card_type == CT_VEHICLE|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type)? ET_CARD_OVER_TIME_VEHICLE:ET_CARD_OVER_TIME_PERSON;
				limit_val = (card->card_type == CT_VEHICLE|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type)? sls_setting.over_time_vehicle : sls_setting.over_time_person;
				cur_val = difftime(time(NULL), card->get_working_time());

				card->is_mine_over_time = is_alarm;
				card->time_over_time = is_alarm ? time(NULL) : 0;
				card->status_over_time = is_alarm ? 1 : 0;
				break;
			}
		case AF_CARD_AREA_FORBIDDEN:
			{				
				et = (card->card_type == CT_VEHICLE|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type)? ET_CARD_AREA_FORBIDDEN_VEHICLE:ET_CARD_AREA_FORBIDDEN_PERSON;
				limit_val = (card->card_type == CT_VEHICLE|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type)? it_area->second->count_area_forbidden_vehicle : it_area->second->count_area_forbidden_person;
				cur_val = (card->card_type == CT_VEHICLE|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type)? it_area->second->count_vehicle:it_area->second->count_person;

				card->time_area_forbidden = is_alarm ? time(NULL) : 0;
				card->status_area_forbidden = is_alarm ? 1 : 0;
				auto_call_person(dest_card_list);
				//card->m_CardHasBeenInDrivingfaceAlarm = is_alarm;//lemon 
				break;
			}
		case AF_CARD_MOTIONLESS:
			{
				et=ET_CARD_MOTIONLESS;
				limit_val = 0;
				cur_val =0;
				card->_isMotionless = is_alarm;
				break;
			}
		case AF_CARD_AREA_OVER_TIME:
			{
				et = (card->card_type == CT_VEHICLE|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type)? ET_CARD_AREA_OVER_TIME_VEHICLE:ET_CARD_AREA_OVER_TIME_PERSON;
				limit_val = (card->card_type == CT_VEHICLE|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type)? it_area->second->over_time_vehicle : it_area->second->over_time_person;
				cur_val = difftime(card->time_area_over_time, CFunctions::systime_to_timet(card->enter_area_time));

				card->is_area_over_time = is_alarm;
				card->time_area_over_time = is_alarm ? time(NULL) : 0;
				card->status_area_over_time = is_alarm ? 1 : 0;
				break;
			}
		case AF_CARD_OVER_SPEED:
			{
				et = ET_CARD_OVER_SPEED;
				limit_val = sls_setting.over_speed;
				cur_val = card->get_speed();

				card->is_mine_over_speed = is_alarm;
				card->time_over_speed = is_alarm ? time(NULL) : 0;
				card->status_over_speed = is_alarm ? 1 : 0;
				break;
			}
		case AF_CARD_AREA_OVER_SPEED:
			{
				et = ET_CARD_AREA_OVER_SPEED;
				limit_val = card->m_overAreaSpeed;
				cur_val = card->get_speed();

				card->is_area_over_speed = is_alarm;
				card->time_area_over_speed = is_alarm ? time(NULL) : 0;
				card->status_area_over_speed = is_alarm ? 1 : 0;
				break;
			}
		case AF_CARD_OVER_COUNT:
			{
				//井下人员超员
				et = (card->card_type == CT_VEHICLE|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type)? ET_OVER_COUNT_VEHICLE:ET_OVER_COUNT_PERSON;
				limit_val = (card->card_type == CT_VEHICLE|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type)? sls_setting.over_count_vehicle : sls_setting.over_count_person;
				cur_val = dest_card_list->size();
				break;
			}
		case AF_CARD_NEAR_WARNING_POINT://lemon 2017/07/30 
			{
				et = ET_CARD_DRIVINGFACE_WARNING_AREA;
				limit_val = card->m_warning_threshold;
				cur_val = card->m_minDistanceToWarningpoint;

				card->m_isWarning = is_alarm;
				break;
			}
		case AF_CARD_NEAR_GEOFAULT:
			{
				et = ET_VEHICLE_NEAR_GEOFAULT;
				limit_val = sls_setting.geofault_warn_dis;
				cur_val = card->m_disToWarningPoint;

				card->m_warning_point_alarm = is_alarm;
				break;
			}
		case AF_CARD_NEAR_DRRIVINGFACE_VEHICLE:
			{
				et = ET_CARD_NEAR_DRIVINGFACE_VEHICLE;
				limit_val = card->getDrivingfaceLimitValue();
				cur_val = card->getDrivingfaceCulValue();

				card->time_area_forbidden = is_alarm ? time(NULL) : 0;
				card->status_area_forbidden = is_alarm ? 1 : 0;
				card->m_CardHasBeenInDrivingfaceAlarm = is_alarm;//lemon 
				break;
			}
		default:
			break;
		}
		if( ET_CARD_OVER_TIME_VEHICLE == et || ET_CARD_AREA_OVER_TIME_VEHICLE == et)
		{
			return ;
		}
		if(ET_UNKNOWN != et)
		{
			INT64 ev_id = card->m_event_list[et];
			if(ev_id > 0 )
			{			
				EventMap::iterator it_ev = mp_event_list->find(ev_id);
				if(it_ev != mp_event_list->end())
				{
					it_ev->second->limit_value = limit_val;
					it_ev->second->cur_value = cur_val;					
					it_ev->second->map_id = card->map_id;
					it_ev->second->area_id = card->area_id;
					it_ev->second->x = card->x;
					it_ev->second->y = card->y;
					it_ev->second->landmarkid = card->landmark_id;
					if (tag == AF_CARD_NEAR_GEOFAULT)
						it_ev->second->landmarkid=card->m_wp_id;
					it_ev->second->landmarkdirect = card->landmark_direction;
					it_ev->second->landmarkdist = card->landmark_dis;
					if(is_alarm)
					{
						it_ev->second->is_sent = false;
					}
					else
					{
						it_ev->second->status = ES_END;
						it_ev->second->cur_time = time(NULL);
						it_ev->second->is_sent = false;
						store_data_event(it_ev->second);
						add_event(it_ev->second);

						card->m_event_list[et] = 0;
					}				
				}
			}
			else
			{
				INT64 ev_id = CFunctions::GetMicroSecond();
				std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
				ev->status = ES_START;	
				ev->ev_type = et;
				ev->obj_type = OT_CARD;
				ev->obj_id = card->card_id;
				ev->cur_time = time(NULL);
				ev->cur_value = cur_val;
				ev->limit_value = limit_val;
				ev->map_id = card->map_id;
				ev->area_id = card->area_id;
				ev->x = card->x;
				ev->y = card->y;
				if (tag == AF_CARD_NEAR_GEOFAULT)
					ev->landmarkid=card->m_wp_id;
				else
					ev->landmarkid = card->landmark_id;
				ev->landmarkdirect = card->landmark_direction;
				ev->landmarkdist = card->landmark_dis;
				ev->is_sent = false;
				card->m_event_list[et] = ev_id;
				store_data_event(ev);
				add_event(ev);

				Sleep(1);
			}
		}
	}
}

void CYAServerDlg::deal_alarm_vehicle(const std::string&cid, std::shared_ptr<Card> card)
{
	std::hash<std::string> hsh;
	uint64_t id = hsh(cid);
	EventMap::iterator it_ev = mp_event_list->find(id);
	if(it_ev != mp_event_list->end())
	{
		if (card!=nullptr)
		{
			it_ev->second->map_id = card->map_id;
			it_ev->second->area_id = card->area_id;
			it_ev->second->x = card->x;
			it_ev->second->y = card->x;
			it_ev->second->landmarkid = card->landmark_id;
			it_ev->second->landmarkdirect = card->landmark_direction;
			it_ev->second->landmarkdist = card->landmark_dis;
		}
		it_ev->second->limit_value = sls_setting.rear_end_d;
		it_ev->second->cur_value = 0;					

		it_ev->second->status = ES_END;
		it_ev->second->cur_time = time(NULL);
		it_ev->second->is_sent = false;
		store_data_event(it_ev->second);
		add_event(it_ev->second);	
	}
	else
	{
		std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(id);
		ev->status = ES_START;	
		ev->ev_type = ET_VEHICLE_REAR_END;
		ev->obj_type = OT_CARD;
		ev->desc=cid;
		ev->cur_time = time(NULL);
		ev->cur_value = 0;
		ev->limit_value = sls_setting.rear_end_d;
		if (card != nullptr)
		{
			ev->obj_id = card->card_id;
			ev->map_id = card->map_id;
			ev->area_id = card->area_id;
			ev->x = card->x;
			ev->y = card->y;
			ev->landmarkid = card->landmark_id;
			ev->landmarkdirect = card->landmark_direction;
			ev->landmarkdist = card->landmark_dis;
		}
		ev->is_sent = false;
		store_data_event(ev);
		add_event(ev);
	}
}
void CYAServerDlg::deal_warning_point_alarm(uint64_t key,const std::shared_ptr<Card>&card)
{
	NAMESPACE_POINT::point cp(card->x,card->y);
	if (cp.invalid())
		return;
	auto it = m_WarningPoint_list.find(key);
	std::shared_ptr<WarningPoint> tmp=nullptr;
	double d=-10;
	if (it != m_WarningPoint_list.end())
	{
		for (const auto & wp:it->second)
		{
			for (const auto &p:wp->vp)
			{
				d = cp.dist(p)*card->map_scale;
				if (d<sls_setting.geofault_warn_dis)
				{
					tmp=wp;break;
				}
			}
			if (tmp!=nullptr)
				break;
		}
		if (tmp!=nullptr)
		{
			card->m_workface_index_del=0;
			if(card->m_workface_index++>10)
			{
				debug_print_syslog(0,"geofault %s,%f,%s(%.2f,%.2f)",card->card_id.c_str(),d,tmp->warning_point_name.c_str(),card->x,card->y);
				card->m_wp_id=tmp->warning_point_id;
				card->m_disToWarningPoint=d;
				deal_alarm_card(card,mp_card_geofault_alarm,true,AF_CARD_NEAR_GEOFAULT);
			}
		}
		else
		{
			card->m_workface_index=0;
			if (card->m_warning_point_alarm && card->m_workface_index_del++>10)
			{
				debug_print_syslog(0,"geofault_false,%s, %f (%.2f,%.2f)",card->card_id.c_str(),d,card->x,card->y);
				deal_alarm_card(card,mp_card_geofault_alarm,false,AF_CARD_NEAR_GEOFAULT);
			}
		}
	}
}
/*
掘进机和分站通信距离范围告警功能，是用来提示掘进面移动或新增分站 lemon 
*/
void CYAServerDlg::deal_drivingface_alarm_all(std::shared_ptr<Card> card,std::shared_ptr<DrivingfaceCard> drivingface_card)
{
	if(op::point::eq(card->x,-1000,1e-10) || op::point::eq(card->y,-1000,1e-10)||!(card->p_reader)||
		op::point::eq(card->p_reader->reader_x,-1000,1e-10)||op::point::eq(card->p_reader->reader_y,-1000,1e-10))
	{
		debug_print_syslog(0,"[deal_alarm_face_alarm_all %s] point is invalid",card->card_id.c_str());
		return;
	}
	op::point p1(card->x,card->y);op::point p2(card->p_reader->reader_x,card->p_reader->reader_y);
	if(p1.empty() || p2.empty())
	{
		debug_print_syslog(0,"[deal_alarm_face_alarm_all %s] point is empty",card->card_id.c_str());
		return;
	}
	double dist = p1.dist(p2)*card->map_scale;
	debug_print_syslog(0,"[deal_alarm_face_alarm_all]%s,dist:%.2f,limit_val:%.2f,index:%d,del:%d,waring:%s",
		card->card_id.c_str(),dist,drivingface_card->warning_threshold, card->m_drivingface_index,
		 card->m_drivingface_index_del,card->m_isWarning?"true":"false");
	if (dist > drivingface_card->warning_threshold)
	{
		card->m_drivingface_index_del=0;
		if(!card->m_isWarning && card->m_drivingface_index++>50)
		{
			card->m_warning_threshold=drivingface_card->warning_threshold;
			card->m_minDistanceToWarningpoint=dist;
			deal_alarm_card(card,mp_card_warning_point_alarm,true,AF_CARD_NEAR_WARNING_POINT);
		}
	}
	else
	{
		card->m_drivingface_index=0;
		if (card->m_isWarning && card->m_drivingface_index_del++>50)
		{
			deal_alarm_card(card,mp_card_warning_point_alarm,false,AF_CARD_NEAR_WARNING_POINT);
		}
	}


#if 0
	DrivingfaceCardMap::iterator it_drivingface = mp_driving_face_card_list.begin();
	string card_id;
	for(;it_drivingface != mp_driving_face_card_list.end();++it_drivingface)
	{
		debug_print_syslog(0,"[deal_alarm_face_alarm_all %s] point is invalid",card->card_id.c_str());
		return;
	}
	op::point p1(card->x,card->y);op::point p2(card->p_reader->reader_x,card->p_reader->reader_y);
	if(p1.empty() || p2.empty())
	{
		debug_print_syslog(0,"[deal_alarm_face_alarm_all %s] point is empty",card->card_id.c_str());
		return;
	}
	double dist = p1.dist(p2)*card->map_scale;
	debug_print_syslog(0,"[deal_alarm_face_alarm_all]%s,dist:%.2f,limit_val:%.2f,index:%d,del:%d,waring:%s",
		card->card_id.c_str(),dist,drivingface_card->warning_threshold, card->m_drivingface_index,
		card->m_drivingface_index_del,card->m_isWarning?"true":"false");
	if (dist > drivingface_card->warning_threshold)
	{
		card->m_drivingface_index_del=0;
		if(!card->m_isWarning && card->m_drivingface_index++>50)
		{
			card->m_warning_threshold=drivingface_card->warning_threshold;
			card->m_minDistanceToWarningpoint=dist;
			deal_alarm_card(card,mp_card_warning_point_alarm,true,AF_CARD_NEAR_WARNING_POINT);
		}
	}
	else
	{
		card->m_drivingface_index=0;
		if (card->m_isWarning && card->m_drivingface_index_del++>50)
		{
			deal_alarm_card(card,mp_card_warning_point_alarm,false,AF_CARD_NEAR_WARNING_POINT);
		}
	}
#endif
}
void CYAServerDlg::deal_drivingface_alarm(std::shared_ptr<Card> card, bool is_alarm, ALARM_FLAG tag)
{
	EVENT_TYPE et = ET_UNKNOWN;
	double limit_val = 0, cur_val = 0;

	INT64 ev_id = CFunctions::GetMicroSecond();
	std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
	if(is_alarm)
	{
		ev->status = ES_START;	
		ev->cur_time = time(NULL);
		ev->is_sent = false;
		ev->ev_type = et;
    	
		ev->obj_type = OT_CARD;
		ev->obj_id = card->card_id;
		ev->cur_value = cur_val;
		ev->limit_value = limit_val;

		ev->map_id = card->map_id;
		ev->area_id = card->area_id;
		ev->x = card->x;
		ev->y = card->y;
		card->m_event_list[et] = ev_id;
	}
	else
	{
		ev->status = ES_END;
		ev->cur_time = time(NULL);
		ev->is_sent = false;
		ev->ev_type = et;
    	
		ev->obj_type = OT_CARD;
		ev->obj_id = card->card_id;
		ev->cur_value = cur_val;
		ev->limit_value = limit_val;

		ev->map_id = card->map_id;
		ev->area_id = card->area_id;
		ev->x = card->x;
		ev->y = card->y;
		card->m_event_list[et] = 0;
	}

	store_data_event(ev);
	add_event(ev);
	Sleep(1);
}


void CYAServerDlg::deal_alarm_area(std::shared_ptr<Area> area, std::shared_ptr<AreaMap> dest_area_list /*Area* area, AreaMap* dest_area_list*/, bool is_alarm, ALARM_FLAG tag,int type )
{
	if(is_alarm)
	{
		dest_area_list->insert(make_pair(area->area_id, area));
	}
	else
	{
		AreaMap::iterator it_area = dest_area_list->find(area->area_id);
		if(it_area != dest_area_list->end())
		{
			dest_area_list->erase(it_area);
		}
		else
		{
			return;
		}
	}
}

/*
* 根据车卡位置来实行红绿灯策略
*
* param
*		card		卡信息
*
* return
*		成功返回0，失败返回1
*/
int CYAServerDlg::deal_traffic_lights(std::shared_ptr<Card> card)
{
	if (card->x < 1E-3 && card->y < 1E-3)
	{
		return 1;
	}

	int nMapId  = 0;

	nMapId = card->map_id;

	MapInfoMap::iterator it_map = mp_map_list.find(nMapId);
	if (it_map != mp_map_list.end())
	{
		//车辆位置
		_point p;
		p.x = card->x;
		p.y = card->y;
		p.z = card->z;

		std::shared_ptr<Section> pSection = nullptr;

		//将车辆加入到车辆所在的路段表中
		SectionMap::iterator it_section ;
		it_section = it_map->second->map_section_list.begin();
		for (;it_section != it_map->second->map_section_list.end();++it_section)
		{
			//获得车辆所在的路段
			if (it_section->second->IsInPolygon(p))
			{
				pSection = it_section->second;
				//车辆在此路段内，将其保存到路段数据中
				CardMap::iterator it_card = pSection->mp_vehicle_list.find(card->card_id);
				if (it_card == pSection->mp_vehicle_list.end())
				{
					pSection->mp_vehicle_list.insert(make_pair(card->card_id,card));
				}

				//如果路段内车辆数大于正常数则记录报警时间
				//当路段之前是报警状态，当恢复正常状态，更新报警结束时间
				if (pSection->mp_vehicle_list.size() > 1)
				{
					int nSize = pSection->mp_vehicle_list.size();
					int nState = SECTION_STATE_NORMAL;
					switch (nSize)
					{
					case 1:
						nState = SECTION_STATE_BUSY;
						break;
					case 2:
						nState = SECTION_STATE_CONGESTION;
						break;
					default:
						break;
					}
					//记录告警开始时间
					if(nState != pSection->m_nState){
						pSection->m_nState = nState;
						pSection->alarm_start_time = time(NULL);
						store_data_section(pSection,time(NULL),ALARM_SECTION_START);
					}
				}else{
					if (pSection->m_nState != SECTION_STATE_NORMAL)
					{
						pSection->m_nState = SECTION_STATE_NORMAL;
						time_t cur_time(time(NULL));
						store_data_section(pSection,cur_time,ALARM_SECTION_END);
					}
				}

				//此路段内有有轨车
				//退出
				break;
			}
		}

		if (INIT_STREAM == card->m_nStream)
		{
			return 1;
		}

		//车辆离开路口区域，将红绿灯组的所有灯设置为绿灯
		int nGroupId = 0;
		LightGroupMap::iterator it_lg = it_map->second->map_light_group_list.find(card->m_nLightGroupId);
		if (it_lg != it_map->second->map_light_group_list.end())
		{
			//红绿灯组所在区域即为路口区域
			it_section = it_map->second->map_section_list.find(it_lg->second->m_nSectionId);
			if (!it_section->second->IsInPolygon(p))
			{
				if (card->b_enter_intersection)
				{
					//离开路口区域，将此路口所有红绿灯改为绿色
					for (LightMap::iterator it_ll = it_lg->second->mp_lights_list.begin();it_ll != it_lg->second->mp_lights_list.end();++it_ll)
					{
						it_ll->second->m_nColor = COLOR_GREEN;
						if(LIGHT_CTRL_STATE::CTRL_STATE_AUTO == it_ll->second->m_nIsCtrl){
							send_call_light(CC_SET_LIGHTS_STATE,it_ll->second->m_nID, it_ll->second->m_nIsCtrl, it_ll->second->m_nColor,GREEN_UP);
							Sleep(LIGHT_CTRL_DELAY);
						}
					}
					card->b_enter_intersection = false;

					//发送控制消息给红绿灯组，
					LightGroupMap::iterator it_group = it_map->second->map_light_group_list.find(card->m_nLightGroupId);
					if (it_group != it_map->second->map_light_group_list.end())
					{
						if (it_group->second->isAllLightColor(COLOR_GREEN))
						{
							//释放红绿灯组的控制权
							card->m_nLightGroupId = -1;
							return 0;
						}
					}

					//控制成功，退出；控制失败，报警并退出
					//需要代码实现
				}
			}else{
				card->b_enter_intersection = true;
				//车辆进入路口区域，要判断车辆是否有此红绿灯组控制权，如没有，其即为闯红灯行为
				if (card->m_nLightGroupId != it_lg->second->m_nID)
				{
					LightMap::iterator it_light = it_map->second->map_light_list.find(card->light_id);
					if (it_light != it_map->second->map_light_list.end())
					{
						//记录车辆闯红灯了，将报警发到前端，发完即重置闯红灯状态
						card->is_red_light = true;
						store_data_traffic_red_light(it_light->second,card);
					}
				}
			}
		}	

		//找到路段
		if (pSection != nullptr)
		{
			//从路段中根据车辆上行/下行方向，获得路段中的上行灯/下行灯
			LightMap::iterator it_light = pSection->mp_light_list.begin();
			bool bFind = false;
			for (;it_light!=pSection->mp_light_list.end();++it_light)
			{
				//灯方向和车方向一致
				if (card->m_nStream == it_light->second->m_nStream)
				{
					bFind = true;
					card->light_id = it_light->second->m_nID;
					break;
				}
			}
			//如果没找到此灯，退出
			if (it_light == pSection->mp_light_list.end())
			{
				return 1;
			}
			//判断灯是否正常，不正常，放弃此灯组的控制权
			if (it_light->second->get_light_state() != STATUS_NORMAL)
			{
				it_light->second->m_nState = STATUS_ERROR;
				store_data_light(it_light->second,ALARM_LIGHT_FAULT_START);
				return 1;
			}
			//根据灯ID获取灯组id
			LightGroupMap::iterator it_group = it_map->second->map_light_group_list.end();
			if (it_light != pSection->mp_light_list.end() && bFind)
			{
				bFind = false;
				for (it_group = it_map->second->map_light_group_list.begin();it_group != it_map->second->map_light_group_list.end();++it_group)
				{
					if (it_group->second->isExist(it_light->second))
					{
						bFind = true;
						break;
					}
				}
			}

			if (it_group == it_map->second->map_light_group_list.end())
			{
				return 1;
			}

			if (it_group->second->isAllLightColor(COLOR_GREEN))
			{
				//灯组中的灯全是绿灯，获得此灯组的控制权

				//控制的是否为自己
				if (it_group->second->m_strVechileId == card->card_id)
				{
					//判断车是否长时间不动
					//如果是，则报警，并修改此车不能控制红绿灯功能
				} 
			}else{	
				//是否找到红绿灯所在的灯组
				if (it_group != it_map->second->map_light_group_list.end() && bFind)
				{
					if (it_group->second->m_bIsUsed)
					{
						//如果灯组在使用，
						//判断当前卡的级别是否大于控制灯组卡的级别，如果是，获得控制权
						bool bChangeAuthority = false;
						CardMap::iterator it_card = mp_card_list_all.find(it_group->second->m_strVechileId);
						if (it_card != mp_card_list_all.end())
						{
							//可以更改红绿灯组控制权的条件如下
							//1.存在此卡,车辆级别更高，
							//2.此车在主巷道，被控制的红绿灯组的车在非主巷道
							//3.车辆为上行且原车辆车辆为下行
							bool bRet = false;
							if (card->level_id > it_card->second->level_id)
							{
								bRet = true;
							}
							else if (card->level_id == it_card->second->level_id 
								&& (isInMainTunel(card)&&!isInMainTunel(it_card->second)))
							{
								bRet = true;
							}else if (card->level_id == it_card->second->level_id 
								&& (getTunelProperty(card)==getTunelProperty(it_card->second)&&(getTunelProperty(card)!=0))
								&& (card->m_nStream == UP_STREAM && it_card->second->m_nStream == DOWN_STREAM))
							{
								bRet = true;
							}

							if (bRet)
							{
								bChangeAuthority = true;
								it_group->second->m_strVechileId = card->card_id;
							}
						}

						if (!bChangeAuthority)
						{
							//说明此灯组被控制了，当前车辆无法控制红绿灯组，
							return 1;
							//那么车辆需要进硐室躲避
							card_enter_chamber(card,pSection);
						}
					}
				}else{
					return 1;
				}
			}

			it_group->second->m_bIsUsed = true;
			it_group->second->m_strVechileId = card->card_id;
			card->m_nLightGroupId = it_group->second->m_nID;
			//控制灯的颜色，将当前灯设置为绿色，其他为红色
			for (LightMap::iterator it_glight = it_group->second->mp_lights_list.begin();it_glight != it_group->second->mp_lights_list.end();++it_glight)
			{
				if (it_glight->second->m_nID == it_light->second->m_nID 
					&& it_glight->second->m_nMapID == it_light->second->m_nMapID )
				{
					it_glight->second->m_nColor = COLOR_GREEN;
				}else{
					it_glight->second->m_nColor = COLOR_RED;
				}

				if(LIGHT_CTRL_STATE::CTRL_STATE_AUTO == it_glight->second->m_nIsCtrl){
					switch (it_glight->second->m_nColor)
					{
					case COLOR_GREEN:
						send_call_light(CC_SET_LIGHTS_STATE,it_glight->second->m_nID, it_glight->second->m_nIsCtrl, it_glight->second->m_nColor,GREEN_UP);
						break;
					case COLOR_RED:
						send_call_light(CC_SET_LIGHTS_STATE,it_glight->second->m_nID, it_glight->second->m_nIsCtrl, it_glight->second->m_nColor,RED_CROSS);
						break;
					}
				}
				Sleep(LIGHT_CTRL_DELAY);
			}

			//下发控制消息给红绿灯，如果控制失败，则报警
		}
	}

	return 0;
}

int CYAServerDlg::get_drivingface_area_id(const std::string& card_id)
{
	if ("" == card_id)
	{
		return -1;
	}
	
	auto it = mp_driving_face_card_list.find(card_id);
	if (it== mp_driving_face_card_list.end())
	{
		return -1;
	}

	return it->second->area_id;
}

int CYAServerDlg::deal_over_speed(std::shared_ptr<Card> card)
{
	if(card->get_speed()>card->m_overSpeed)
	{
		card->m_indexMineOverSpeed_normal = 0;
		if(!card->is_mine_over_speed && ++card->m_indexMineOverSpeed >= SUSTAINEDOVERSPEED)
		{
			debug_print_syslog(0,"[OverSpeed_mine]%s,cur_speed:%f,over_speed:%f",card->card_id.c_str(),card->get_speed(),card->m_overSpeed);
			deal_alarm_card(card,mp_card_list_over_speed_vehicle,true, AF_CARD_OVER_SPEED);
		}
	}
	else 
	{
		card->m_indexMineOverSpeed = 0;
		if(card->is_mine_over_speed && ++card->m_indexMineOverSpeed_normal >= SUSTAINEDOVERSPEED)
		{
			deal_alarm_card(card,mp_card_list_over_speed_vehicle,false, AF_CARD_OVER_SPEED);
		}
	}
	return 0;
}
/*:deal_area_over_speed
*	处理区域超速
*
*	param
*		card		车卡信息
*
*	return
*		成功返回0，失败返回1
*
*/
int CYAServerDlg::deal_area_over_speed(std::shared_ptr<Card> card)
{
	int nAreaId = 0;

	nAreaId = card->area_id;

	AreaMap::iterator it_area = mp_area_list.find(nAreaId);
	if (it_area != mp_area_list.end())
	{
		if (it_area->second->over_speed_vehicle == 0)
		{
			return 0;
		}
		if (card->get_speed() > it_area->second->over_speed_vehicle)
		{
			card->m_indexCardSpeed_normal = 0;
			if(!card->is_area_over_speed && ++card->m_indexCardSpeed >= SUSTAINEDOVERSPEED)
			{
				card->m_overAreaSpeed=it_area->second->over_speed_vehicle;
				debug_print_syslog(0,"[OverSpeed]%s,cur_speed:%f,over_speed:%f",card->card_id.c_str(),card->get_speed(),it_area->second->over_speed_vehicle);
				deal_alarm_card(card,it_area->second->area_card_list_over_speed,true, AF_CARD_AREA_OVER_SPEED);
			}
		}
		else 
		{
			card->m_indexCardSpeed = 0;
			if(card->is_area_over_speed && ++card->m_indexCardSpeed_normal >= SUSTAINEDOVERSPEED)
			{
				deal_alarm_card(card,it_area->second->area_card_list_over_speed,false, AF_CARD_AREA_OVER_SPEED);
			}
		}
	}

	return 0;
}

/*
 
* 此函数处理当移动分站收到人卡数据时，处理人与车的状态：是上车还是下车
*
* author & date
*		zhuyf 2017/10/18
*
* param
*		pReader		移动分站
*
* return
*		成功返回0，否则返回非零值
*
*/
int CYAServerDlg::deal_relationship_between_person_and_vehicle(std::shared_ptr<MovingReader> pReader)
{
	int ret = 0;
	//1.前置条件：车卡处于怠速或静止状态，先确定移动分站对应的车卡状态不能为运动状态
	if (pReader->pVehicleCard->state_moving == ACCELERATE_STATE::STATE_ACCE_IDLING || 
		pReader->pVehicleCard->state_moving == ACCELERATE_STATE::STATE_ACCE_STATIC)
	{
	}else{
		ret = 1;
		return ret;
	}

	//map key为车号，结构体里存放：a.统计数，b.<人卡号数组,状态>
	map<string,OnVehicleData> real_on_card_data;
	OnVehicleData ovd;

	map<string,OnVehicleData>::iterator it_vehicle_json = real_on_card_data.end();
	if (pReader->mp_person_card.size() > 0)
	{
		it_vehicle_json = real_on_card_data.find(pReader->pVehicleCard->card_id);
		if (it_vehicle_json == real_on_card_data.end())
		{
			real_on_card_data.insert(std::make_pair(pReader->pVehicleCard->card_id,ovd));
			it_vehicle_json = real_on_card_data.find(pReader->pVehicleCard->card_id);
		}else{
			ovd = it_vehicle_json->second;
			ovd.counts = it_vehicle_json->second.counts;
		}
	}

	//2.确认移动分站接收的人卡此时不在移动分站对应的车卡上，才允许判断是否上车逻辑
	for (CardMap::iterator it_reader_card = pReader->mp_person_card.begin(); it_reader_card != pReader->mp_person_card.end();++it_reader_card)
	{
		//在mp_person_in_vechicle_list表里即表明已经上车了
		switch (it_reader_card->second->person_on_card)
		{
		case PERSON_ON_VEHICLE_STATUS::PERSON_OFF_VEHICLE:
			//判断人卡是否上车：前置条件人卡未上车
			//a.人卡与移动分站的测距距离是否小于阈值
			if(fabs(it_reader_card->second->distance) < THRE_MOVING_READER_DISTANCE &&
				fabs(it_reader_card->second->relative_speed) < THRE_RELATIVE_SPEED){
					it_reader_card->second->satisfy_on_vehicle_counts++;
			}else{
				it_reader_card->second->satisfy_on_vehicle_counts = 0;
			}

			//满足上车确认次数
			if (it_reader_card->second->satisfy_on_vehicle_counts >= CONFIRM_ON_VEHICLE_COUNTS)
			{
				it_reader_card->second->person_on_card = PERSON_ON_VEHICLE_STATUS::PERSON_ON_VEHICLE;
				it_reader_card->second->satisfy_off_vehicle_counts = 0;
				//更新人员所在的车辆信息
				it_reader_card->second->vehicle_id = pReader->pVehicleCard->card_id;

				CardMap::iterator it_person_card = pReader->pVehicleCard->mp_person_in_vechicle_list->find(it_reader_card->first);
				if (it_person_card == pReader->pVehicleCard->mp_person_in_vechicle_list->end())
				{
					//人卡上车，将人卡加入到车的人卡人员表中
					pReader->pVehicleCard->mp_person_in_vechicle_list->insert(std::make_pair(it_reader_card->first,it_reader_card->second));
					it_person_card = pReader->pVehicleCard->mp_person_in_vechicle_list->find(it_reader_card->first);
				}

				//构造json的数据
				it_vehicle_json->second.counts++;
			}
			break;
		case PERSON_ON_VEHICLE_STATUS::PERSON_ON_VEHICLE:
			//判断人卡是否下车的前置条件：人卡已上车
			//人卡被移动分站收到，判断人卡与移动分站的距离是否连续大于指定阈值
			if(fabs(it_reader_card->second->distance) > THRE_MOVING_READER_DISTANCE){
				it_reader_card->second->satisfy_off_vehicle_counts++;
			}else{
				it_reader_card->second->satisfy_off_vehicle_counts = 0;
			}

			//满足下车确认次数
			if (it_reader_card->second->satisfy_off_vehicle_counts >= CONFIRM_OFF_VEHICLE_COUNTS)
			{
				it_reader_card->second->person_on_card = PERSON_ON_VEHICLE_STATUS::PERSON_OFF_VEHICLE;
				it_reader_card->second->satisfy_on_vehicle_counts = 0;
				//更新人员所在的车辆信息
				it_reader_card->second->vehicle_id = "";
				it_reader_card->second->possible_vehicle_id = "";

				//查找对应车上已经上车的人卡信息
				CardMap::iterator it_person_card = pReader->pVehicleCard->mp_person_in_vechicle_list->find(it_reader_card->first);
				if (it_person_card != pReader->pVehicleCard->mp_person_in_vechicle_list->end())
				{
					//人卡下车将人卡从车的上车人员表中删除
					pReader->pVehicleCard->mp_person_in_vechicle_list->erase(it_person_card);
				}
			}else{
				//表示卡在车上，不满足下车条件，构造json的数据
				it_vehicle_json->second.counts++;
			}
			break;
		}

		//把人卡卡号和人卡上车状态提取出来保存到map
		map<string,int>::iterator it_ovd_person_card = it_vehicle_json->second.person_cards.find(it_reader_card->first);
		if (it_ovd_person_card == it_vehicle_json->second.person_cards.end())
		{
			it_vehicle_json->second.person_cards.insert(std::make_pair(it_reader_card->first,it_reader_card->second->person_on_card));
		}else{
			it_ovd_person_card->second = it_reader_card->second->person_on_card;
		}
	}

	if (real_on_card_data.size() > 0)
	{
		send_json_data(JSON_CMD_VALUE_PUSH,get_json_person_on_car(real_on_card_data));
	}

	return ret;
}

/*
 
* 人卡被通信分站收到，判断人上下车关系的处理逻辑
* author & date
*		zhuyf 2017/10/18
*
* param
*		card		通过定位分站定位的人卡对象
*
* return
*		成功返回0，否则返回非零值
*
*/
int CYAServerDlg::deal_relationship_between_person_and_vehicle(std::shared_ptr<Card> card)
{
	//卡不存在或卡的分站id不存在，直接返回
	if (card == nullptr)
	{
		return 1;
	}
	if (card->p_reader->reader_id == 0)
	{
		return 1;
	}

	CardMap::iterator it_vehicle = mp_card_list_all.end();
	//1.先检查人卡是否在车上
	switch (card->person_on_card)
	{
	case PERSON_ON_VEHICLE_STATUS::PERSON_ON_VEHICLE:
		//前置条件：1.人在车上；2.车辆怠速或静止状态
		//人卡在车上，且通过通信分站定位，判断人卡是否下车
		it_vehicle = mp_card_list_all.find(card->vehicle_id);
		if (it_vehicle != mp_card_list_all.end())
		{
			if (it_vehicle->second->state_moving == ACCELERATE_STATE::STATE_ACCE_IDLING || 
				it_vehicle->second->state_moving == ACCELERATE_STATE::STATE_ACCE_STATIC)
			{
			}else{
				return 1;
			}

			double distance = 0.0;
			distance = sqrt(pow(card->x - it_vehicle->second->x,2) + pow(card->y - it_vehicle->second->y,2)) * card->map_scale;
			//人卡定位位置与人卡所在车的距离需要连续大于指定距离的阈值
			if (distance > THRE_MOVING_READER_DISTANCE)
			{
				card->satisfy_off_vehicle_counts++;
			}else{
				card->satisfy_off_vehicle_counts = 0;
			}
			//当满足确认次数
			if (card->satisfy_off_vehicle_counts > CONFIRM_OFF_VEHICLE_COUNTS)
			{
				card->person_on_card = PERSON_ON_VEHICLE_STATUS::PERSON_OFF_VEHICLE;
				card->satisfy_on_vehicle_counts = 0;
				card->vehicle_id = "";
				card->possible_vehicle_id = "";
				CardMap::iterator erase_card = it_vehicle->second->mp_person_in_vechicle_list->find(card->card_id);
				it_vehicle->second->mp_person_in_vechicle_list->erase(erase_card);
			}
		}
		break;
	case PERSON_ON_VEHICLE_STATUS::PERSON_OFF_VEHICLE:
		{
			//计算人卡与车卡（需要遍历）的距离,查找距离此人卡最近的车辆
			double distance = 0.0;
			double min_distance = 999999.9;
			std::string vehicle_id = "";
			bool exist = false;

			//查找距离最近的车卡及计算人卡与车卡的距离
			for(it_vehicle = mp_card_list_all.begin(); it_vehicle != mp_card_list_all.end();++it_vehicle)
			{
				if (CT_VEHICLE == it_vehicle->second->card_type|| CT_COALMINING_MACHINE == it_vehicle->second->card_type 
					||CT_TUNNELBORING_MACHINE == it_vehicle->second->card_type)
				{
					distance = sqrt(pow(card->x - it_vehicle->second->x,2) + pow(card->y - it_vehicle->second->y,2));

					if (distance < min_distance)
					{
						exist = true;
						min_distance = distance;
						vehicle_id = it_vehicle->second->card_id;
					}
				}
			}

			if (exist)
			{
				if (card->possible_vehicle_id == "" && min_distance < THRE_MOVING_READER_DISTANCE)
				{
					//第一次满足条件，不知道可能上车的车卡号，更新可能上车的车卡号，并计数
					card->satisfy_on_vehicle_counts++;
					card->possible_vehicle_id = vehicle_id;
					card->min_distance = min_distance;
				}else if(card->possible_vehicle_id == vehicle_id && min_distance <= THRE_MOVING_READER_DISTANCE){
					//需要连续满足与指定的车卡的距离满足条件
					card->satisfy_on_vehicle_counts++;
				}else if (card->possible_vehicle_id == vehicle_id && min_distance > THRE_MOVING_READER_DISTANCE)
				{
					card->satisfy_on_vehicle_counts = 0;
				}

				//满足上车确认次数
				if (card->satisfy_on_vehicle_counts >= CONFIRM_ON_VEHICLE_COUNTS)
				{
					card->person_on_card = PERSON_ON_VEHICLE_STATUS::PERSON_ON_VEHICLE;
					card->satisfy_off_vehicle_counts = 0;
					card->vehicle_id = vehicle_id;
					it_vehicle = mp_card_list_all.find(vehicle_id);
					if (it_vehicle != mp_card_list_all.end())
					{
						CardMap::iterator it_person_card = it_vehicle->second->mp_person_in_vechicle_list->find(card->card_id);
						if (it_person_card == it_vehicle->second->mp_person_in_vechicle_list->end())
						{
							it_vehicle->second->mp_person_in_vechicle_list->insert(std::make_pair(card->card_id,card));
						}else{
							it_person_card->second->person_on_card = card->person_on_card;
							it_person_card->second->vehicle_id = card->vehicle_id;
						}
					}
				}
			}
		}
		break;
	default:
		break;
	}

	return 0;
}

/*
*	车辆进入硐室
*
*	param
*		card		车卡信息
*
*	return
*		成功返回0，失败返回1
*
*/
int CYAServerDlg::card_enter_chamber(std::shared_ptr<Card> card,std::shared_ptr<Section> section)
{
	return 1;
	ChamberMap::iterator it_chamber = section->mp_champer_list.begin();
	for (;it_chamber != section->mp_champer_list.end();++it_chamber)
	{
		//在路段中查找和车辆位置最近的可用硐室
		double dDistance = 0.0;
		//dDistance = sqrt(card->x);
		if (!it_chamber->second->m_nIsUsed)
		{

		}
	}

	return 0;
}

/*
* 判断坐标输出需不需要选择坐标左边偏移位置
*
* param
*		card	卡信息
* 
* return
*		成功返回0，执行失败返回1		
*
*/
int CYAServerDlg::select_pos_output(std::shared_ptr<Card> card)
{
	return 0;
	

	int nMapId = 0;

	nMapId = card->map_id;

	MapInfoMap::iterator it_map = mp_map_list.find(nMapId);
	for (;it_map != mp_map_list.end();++it_map)
	{
		CardMap::iterator it_vehicle = it_map->second->map_card_list_vehicle.begin();
		for (;it_vehicle != it_map->second->map_card_list_vehicle.end();++it_vehicle)
		{
			
			if (it_vehicle->second->card_id != card->card_id)
			{

				double distance = 0.0;
				distance = sqrt(pow(it_vehicle->second->x - card->x,2) + pow(it_vehicle->second->y - card->y,2));
				//会车距离
				if (distance <= VEHICLE_WIDTH )
				{
					
					//不同方向都靠右
					if (card->m_nMoveDirection != it_vehicle->second->m_nMoveDirection)
					{
						
						card->m_nOutputPosState = RIGHT_POS;
						it_vehicle->second->m_nOutputPosState = RIGHT_POS;
					}else{
						
						//相同方向一左一右
						card->m_nOutputPosState = LEFT_POS;
						it_vehicle->second->m_nOutputPosState = RIGHT_POS;
					}
				}else{
					card->m_nOutputPosState = CENTRAL_POS;
					it_vehicle->second->m_nOutputPosState = CENTRAL_POS;
				}
			}
		}
	}

	return 0;
}

/*
* 从数据库的dat_alarm_type表初始化告警类型和名称
*
* param
*		无
*
* return
*		无
*/
int CYAServerDlg::init_alarm_type()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	pRes = getMysqlRes("select event_type_id, name from dat_event_type;");

	if(NULL == pRes)
	{
		return 1;
	}

	while(pRow = mysql_fetch_row(pRes))	{
		AlarmTypeMap::iterator it = mp_alarm_type_list.find(atoi(pRow[0]));		
		if(it != mp_alarm_type_list.end()){
			it->second = pRow[1];
		}else{
			mp_alarm_type_list.insert(make_pair(atoi(pRow[0]), pRow[1]));
		}
	}
	mysql_free_result(pRes);

	show_log(_T(LOG_INIT_ALARM_TYPE));

	return 0;
}
void CYAServerDlg::AddItem(std::shared_ptr<_SOCK> &s)
{
	CString strRow;
	int nRow = 0;
	bool bFind = false;
	CString strvalue = s->sip;
	for (const auto & r : s->m_reader)
	{
		CString readerId = CFunctions::formatInt(r.reader_id);
		BOOL is_closed = r.state;
		DEVICE_TYPE rt = r.reader_type;
		bFind = false;
		nRow = 0;
		for(int i = 0; i < m_listctrl_reader.GetItemCount(); i++)
		{
			if(strvalue == m_listctrl_reader.GetItemText(i, 1))
			{
				// auto c = m_listctrl_reader.GetItemText(i, 0);
				if (readerId == m_listctrl_reader.GetItemText(i, 0))
				{
					nRow = i;
					bFind = true;
					break;
				}
			}
		}
		if(!bFind){
			nRow = m_listctrl_reader.GetItemCount();
			nRow = m_listctrl_reader.InsertItem(nRow, readerId);
		}
		m_listctrl_reader.SetItemText(nRow, 1, strvalue);
		m_listctrl_reader.SetItemText(nRow, 2, is_closed ? _T("中断"): _T("已连接"));
		m_listctrl_reader.SetItemText(nRow, 3, (rt == DEVICE_TYPE::DT_CARD_READER)? _T("读卡分站"): _T("通信分站"));
	}
}
void CYAServerDlg::AddItem( CString strvalue, int readerid, BOOL is_closed, DEVICE_TYPE rt )
{
	CString strRow;
	int nRow = 0;
	bool bFind = false;
	for(int i = 0; i < m_listctrl_reader.GetItemCount(); i++){
		if(strvalue == m_listctrl_reader.GetItemText(i, 1)){
			nRow = i;
			bFind = true;
			break;
		}
	}
	if(!bFind){
		nRow = m_listctrl_reader.GetItemCount();
		nRow = m_listctrl_reader.InsertItem(nRow, CFunctions::formatInt(readerid));
	}
	m_listctrl_reader.SetItemText(nRow, 1, strvalue);
	m_listctrl_reader.SetItemText(nRow, 2, is_closed ? _T("中断"): _T("已连接"));
	m_listctrl_reader.SetItemText(nRow, 3, (rt == DEVICE_TYPE::DT_CARD_READER)? _T("读卡分站"): _T("通信分站"));
}

void CYAServerDlg::show_log( LPCTSTR szlog, BOOL bSave )
{
	CString sMsg, sLog;
	CString sTime=COleDateTime::GetCurrentTime().Format(_T(LOG_TIME_FORMAT));
	sMsg.Format(_T("%s %s\n"), sTime, szlog);
	try{
		::LogMsg(sMsg);
	}
	catch(...){
		;
	}
}

/*
* 初始化数据库连接
*
* param
*		无
*
* return
*		无
*
*/
void CYAServerDlg::database_connect()
{
	show_log(_T(LOG_CONNECT_DB));

	//GetConnPool().Init(m_db_setting.encoding.c_str(), m_db_setting.host.c_str(), m_db_setting.user.c_str(), 
	//	m_db_setting.password.c_str(), m_db_setting.dbname.c_str(), m_db_setting.port, NULL, 0);
	//int nConn = GetConnPool().InitAllConn();

	g_pConnPool->Init(m_db_setting.encoding.c_str(), m_db_setting.host.c_str(), m_db_setting.user.c_str(), 
		m_db_setting.password.c_str(), m_db_setting.dbname.c_str(), m_db_setting.port, NULL, 0);
	int nConn = g_pConnPool->InitAllConn();

	g_pConnPool_Bk->Init(m_db_setting_bk.encoding.c_str(), m_db_setting_bk.host.c_str(), m_db_setting_bk.user.c_str(), 
		m_db_setting_bk.password.c_str(), m_db_setting_bk.dbname.c_str(), m_db_setting_bk.port, NULL, 0);
	int nConn_bk = g_pConnPool_Bk->InitAllConn();

	if(nConn > 0){
		show_log(_T(LOG_CONNECT_DB_SUCCESS));
	}else{
		show_log(_T(LOG_CONNECT_DB_FAIL));
	}
}

void CYAServerDlg::OnMenuDb()
{
	CDbSettingDlg dlg;
	dlg.DoModal();
}

void CYAServerDlg::OnCallMessage(string const& name, message::ptr const& data, bool isAck,message::list &ack_resp )
{
	if(data->get_flag() == message::flag_object){
		string cmd = data->get_map()[JSON_ROOT_KEY_CMD]->get_string();

		debug_print_syslog(0, "receive web cmd: %s", cmd.c_str());
		if(JSON_CMD_VALUE_META_DATA_CHANGED == cmd){
			map<string,message::ptr> data_map = data->get_map()[JSON_ROOT_KEY_DATA]->get_map();
			string name = data_map[JSON_KEY_NAME]->get_string().c_str();
			string op_type = data_map[JSON_KEY_OP_TYPE]->get_string().c_str();
			EDIT_TYPE_ID edit_type_id = (JSON_KEY_OP_TYPE_INSERT == op_type)? ET_INSERT: ((JSON_KEY_OP_TYPE_UPDATE == op_type)? ET_UPDATE: ET_DELETE);
			debug_print_syslog(0, "receive meta_data_changed: %s", name.c_str());
			if(JSON_KEY_NAME_VEHICLE == name || JSON_KEY_NAME_VEHICLE_EXTEND == name){
				//string id = data_map[JSON_KEY_ID]->get_string().c_str();
				int id = data_map[JSON_KEY_ID]->get_int();
				std::string sid = std::to_string(id);
				deal_call_edit_vehicle(sid, edit_type_id);
			}else if(JSON_KEY_NAME_STAFF == name || JSON_KEY_NAME_STAFF_EXTEND == name){
				//string id = data_map[JSON_KEY_ID]->get_string().c_str();
				int id = data_map[JSON_KEY_ID]->get_int();
				std::string sid = std::to_string(id);
				deal_call_edit_staff(sid, edit_type_id);
			}else if(JSON_KEY_NAME_READER == name){
				int id = atoi(data_map[JSON_KEY_ID]->get_string().c_str());
				deal_call_edit_reader(id, edit_type_id);
			}else if(JSON_KEY_NAME_CARD == name){
				string id = data_map[JSON_KEY_ID]->get_string().c_str();
				deal_call_edit_card(id, edit_type_id);
			}else if(JSON_KEY_NAME_AREA == name){
				int id = atoi(data_map[JSON_KEY_ID]->get_string().c_str());
				deal_call_edit_area(id, edit_type_id);
			}else if(JSON_KEY_NAME_MAP == name){
				int id = atoi(data_map[JSON_KEY_ID]->get_string().c_str());
				deal_call_edit_map(id, edit_type_id);
			}else if(JSON_KEY_NAME_PATROL_TASK == name){
				std::string id = data_map[JSON_KEY_ID]->get_string().c_str();
				deal_call_edit_patrol_task(id, edit_type_id);
			}else if(JSON_KEY_NAME_PATH == name){
				//int id = data_map[JSON_KEY_ID]->get_int();
				//deal_call_edit_path(id, edit_type_id);
			}else if (JSON_KEY_NAME_SECTION == name)
			{
				int id = atoi(data_map[JSON_KEY_ID]->get_string().c_str());
				deal_call_edit_section(id,edit_type_id);
			}else if (JSON_KEY_NAME_LIGHT == name)
			{
				int id = atoi(data_map[JSON_KEY_ID]->get_string().c_str());
				deal_call_edit_light(id,edit_type_id);
			}else if (JSON_KEY_NAME_LIGHT_GROUP == name)
			{
				int id = atoi(data_map[JSON_KEY_ID]->get_string().c_str());
				deal_call_edit_light_group(id,edit_type_id);	
			}else if (JSON_KEY_NAME_CHAMBER == name)
			{
				int id = atoi(data_map[JSON_KEY_ID]->get_string().c_str());
				deal_call_edit_chamber(id,edit_type_id);
			}else if(JSON_KEY_NAME_SHIFT == name)
			{
				init_shift();
			}else if(JSON_KEY_NAME_RULES == name){
				int id = atoi(data_map[JSON_KEY_ID]->get_string().c_str());
				deal_call_edit_rules(id,edit_type_id);
			}else if(JSON_KEY_NAME_SETTING == name){
				//阈值限制接口
				init_setting();
			}else if (JSON_KEY_NAME_DRIVINGFACE == name)
			{
				init_drivingface_card();
			}else if (JSON_KEY_NAME_DRIVINGFACE_WARNING_POINT == name)
			{
				init_drivingface_warning_point();
			}else if (JSON_KEY_NAME_WARNING_POINT == name)
			{
				init_geological_fault();
			}else if (JSON_KEY_NAME_HAND_UP == name)
			{
				//Web界面上手动拖动车辆位置
				string card_id = data_map[JSON_KEY_ID]->get_string();
				int retHandup = refresh_handup_list(card_id);
				if(0 == retHandup)
				{
					parse_json_data_hand_up(card_id);
				}
			}
		}else if(JSON_CMD_VALUE_REQUEST_ALL_POSTION == cmd){
			//请求全部位置信息
			send_json_data(JSON_CMD_VALUE_REQUEST_ALL_POSTION, get_json_card_statistic());
			// send_json_data(JSON_CMD_VALUE_SPECIAL_AREA_UP_MINE, get_json_all_special_area_data());
			//请求所有呼叫信息
			std::string call_list = "";
			call_list = get_json_call_list();
			if (call_list != "")
			{
				send_json_data(JSON_CMD_VALUE_PUSH,call_list);
			}
			debug_print_syslog(0,"client req data: %s",cmd.c_str());
		} else if(JSON_CMD_VALUE_DEAL_HELP == cmd){
			// 处理呼救信息
			//string json_data = data->get_map()[JSON_ROOT_KEY_DATA]->get_string(); 
			parse_json_data_deal_help(data);
		} else if(JSON_CMD_VALUE_CALL_CARD_REQUEST == cmd){
			//呼叫
			parse_json_data_call_card(data);
		} else if(JSON_CMD_VALUE_CALL_CARD_CANCEL_REQUEST == cmd){
			//取消呼叫
			parse_json_data_call_card_cancel(data);
		} else if(JSON_CMD_VALUE_CLEAR_CARD == cmd) {
			// 清楚盲区卡
			//map<string,message::ptr> data_map = data->get_map()[JSON_ROOT_KEY_DATA]->get_map();
			parse_json_data_clear_card(data);
		}
		else if (JSON_CMD_VALUE_LIGHTS_CTRL_REQUEST == cmd)
		{
			parse_json_data_set_light_color(data);
		}
		else if (JSON_CMD_VALUE_REQUEST_ALL_DATA == cmd)
		{
			std::string sd = "";
			sd = get_json_all_data();
			send_json_data(JSON_CMD_VALUE_PUSH, sd);
		}
		else if(JSON_KEY_EVENT_READER_POS_CHANGE == cmd)
		{
			parse_json_data_reader_pos_change(data);
		}else if (JSON_CMD_DRIVING_FACE_STATE == cmd)
		{
			send_drivingface_card_position_json(true);
		}else if(JSON_CMD_REQ_ALL_PERSON_ON_CAR == cmd){
			//web端用户登陆时，一次请求所有人卡上车状态数据
			std::string user = "";
			user = parse_json_data_person_on_car(data);
			std::string send_data = "";
			send_data = get_json_all_person_on_car(user);
			send_json_data(JSON_CMD_VALUE_PUSH,send_data);
		}
	}
}

void CYAServerDlg::parse_json_data_set_limit_value( const char* sz )
{
	Json::Value root;
	Json::Reader reader;
	CString strlog;
	if (!reader.parse(sz,root)){
		strlog.Format(_T("%s%s"), _T(LOG_SET_LIMIT_VALUE), _T(LOG_FAIL));
		show_log(strlog);
		return ;
	}
	sls_setting.over_count_person = root[JSON_KEY_ALARM_OVER_COUNT_PERSON].asInt();
	sls_setting.over_count_vehicle = root[JSON_KEY_ALARM_OVER_COUNT_VEHICLE].asInt();
	sls_setting.over_time_person = root[JSON_KEY_ALARM_OVER_TIME_PERSON].asInt();
	sls_setting.over_time_vehicle = root[JSON_KEY_ALARM_OVER_TIME_VEHICLE].asInt();
	sls_setting.over_speed = root[JSON_KEY_ALARM_OVER_SPEED_VEHICLE].asDouble();

	strlog.Format(_T("%s%s"), _T(LOG_SET_LIMIT_VALUE), _T(LOG_SUCCESS));
	show_log(strlog);

	if(m_log_recv_package){
		std::string strlog = sz;
		Log::write_log(FILE_TYPE::JSON_R, strlog, true);
	}
}

void CYAServerDlg::parse_json_data_call_card(message::ptr const& data)
{
	CString strlog = _T("");
	string user_name = "", call_time = "";
	string cardid = "", readerid = "";
	int call_type_id = 0;
	int call_time_out = 0, reader_count = 0, card_count = 0, call_level_id = 0;
	long long call_time_interval = 0;

	map<string,message::ptr> data_map = data->get_map()[JSON_ROOT_KEY_DATA]->get_map();

	call_type_id	= data_map[JSON_KEY_CALL_CARD_CALL_TYPE]->get_int();
	call_time_out	= data_map[JSON_KEY_CALL_CARD_CALL_TIME_OUT]->get_int();
	call_level_id	= data_map[JSON_KEY_CALL_CARD_CALL_LEVEL]->get_int();
	user_name		= data_map[JSON_KEY_CALL_CARD_USER_NAME]->get_string();
	call_time_interval = data_map[JSON_KEY_CALL_CARD_CALL_TIME]->get_int();

	vector<message::ptr> reader_vec = data_map[JSON_KEY_CALL_CARD_STATIONS]->get_vector();
	vector<message::ptr> card_vec = data_map[JSON_KEY_CALL_CARD_CARDS]->get_vector();

	if(reader_vec.size() == 0 && card_vec.size() == 0)
	{
		return;
	}

	int reader_id = 0, npos = 0;
	shared_ptr<_call_info_user> call_user;
	shared_ptr<_call_info_reader> call_reader;
	std::shared_ptr<_call_info_card> call_card;

	EnterCriticalSection(&m_csCallInfo);

	CallInfoUserMap::iterator it_user_call = mp_user_call_info.find(user_name);
	if(it_user_call != mp_user_call_info.end()){
		call_user = it_user_call->second;
	}else{
		call_user = std::make_shared<_call_info_user>();
		call_user->user_name = user_name;
		mp_user_call_info.insert(make_pair(user_name, call_user));
	}

	vector<message::ptr>::const_iterator it_card = card_vec.begin();
	std::string strCardId = "";
	int cardId = 0;
	int readerId = 0;
	// 全员
	if(CALL_CARD_TYPE::CCT_CALL_ALL == call_type_id)
	{
		// 删除指定用户的所有呼叫信息
		clear_call_card_by_user(user_name);
		// 重置全员呼叫信息
		call_reader = std::make_shared<_call_info_reader>();
		call_reader->call_level = call_level_id;
		call_reader->cards_count = 0;
		call_reader->is_call_all = true;
		call_reader->is_start_call = true;
		call_reader->start_time = time(NULL);
		call_reader->time_out = call_time_out;
		call_user->mpReader.insert(make_pair(reader_id, call_reader));
	}
	else // 定员
	{
		int nCounts = 0;
		int card_id = 0;
		BYTE card_type = 0;	
		string s_card_id = "";
		string s_card_type = "";
		// 如果有全员，定员不生效
		CallInfoReaderMap::iterator it_call_reader = call_user->mpReader.find(reader_id);
		if (it_call_reader == call_user->mpReader.end())
		{
			vector<message::ptr>::const_iterator it_card = card_vec.begin();

			for(; it_card != card_vec.end(); ++it_card){
				card_type = 0;
				s_card_id = "";
				s_card_type = "";

				nCounts++;

				s_card_id = (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_ID]->get_string();		
				card_type =(*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID]->get_int();

				string new_card_id = s_card_id.substr(3, s_card_id.length());
				card_id = atoi(new_card_id.c_str());

				CardMap::iterator it_card = mp_card_list_all.find(s_card_id);
				if (it_card== mp_card_list_all.end())
				{
					continue;
				}

				reader_id = it_card->second->reader_id;
				if (0 == reader_id)
				{
					//如果此卡不属于任何分站，此时其的分站id为零，此卡不参与呼叫
					continue;
				}
				CallInfoReaderMap::iterator it_call_reader = call_user->mpReader.find(reader_id);

				if(it_call_reader != call_user->mpReader.end()){
					call_reader = it_call_reader->second;	
					call_reader->is_start_call = true;
					call_reader->is_call_all = false;
					call_reader->cards_count += 1;
					if(call_reader->call_level > call_level_id){
						call_reader->call_level = call_level_id;
					}
				}else{
					call_reader = std::make_shared<_call_info_reader>();
					call_reader->call_level = call_level_id;
					call_reader->is_call_all = false;
					call_reader->cards_count = 1;
					call_reader->is_start_call = true;
					call_user->mpReader.insert(make_pair(reader_id, call_reader));
				}

				CallInfoCardMap::iterator it_call_card = call_reader->mpCard.find(s_card_id);
				if(it_call_card != call_reader->mpCard.end()){ // 已在呼叫列表
					call_card = it_call_card->second;
					if(call_card->call_level < call_level_id){ // 原呼叫优先级低
						call_card->card_type = card_type;
						call_card->call_level = call_level_id;
						call_card->start_time = time(NULL);
						call_card->time_out = call_time_out;
					}else {
						call_card->start_time = time(NULL);
						call_card->time_out = call_time_out;
					}
				}else{ // 未在呼叫列表
					call_card = std::make_shared<_call_info_card>();
					call_card->card_id = card_id;
					call_card->card_type = card_type;
					call_card->start_time = time(NULL);
					call_card->time_out = call_time_out;
					call_card->call_level = call_level_id;
					call_card->str_card_id = s_card_id;
					call_reader->mpCard.insert(make_pair(s_card_id, call_card));
				}
			}
		}
	}

	LeaveCriticalSection(&m_csCallInfo);
	Json::Value root;
	Json::Value resp_data;

	//收到呼叫信息，即直接返回
	if (0 == call_type_id )
	{
		Json::Value callinfo;
		callinfo.append(user_name);
		callinfo.append(0);
		callinfo.append(0);
		callinfo.append((double)call_time_interval);
		callinfo.append(call_type_id);
		//CALL_STATE::CALL_SUCCESSED,CALL_STATE::CALL_ING,CALL_STATE::CALL_FAILED
		callinfo.append(CALL_STATE::CALL_ING);
		resp_data.append(callinfo);
	}else{
		//是否有选择分站
		if (reader_vec.size() > 0)
		{
			//如果有选择分站
			//根据分站数和卡数量构造返回呼叫返回的json
			for (vector<message::ptr>::const_iterator it_reader = reader_vec.begin();it_reader != reader_vec.end();++it_reader)
			{	
				if (card_vec.size() > 0)
				{
					for (vector<message::ptr>::const_iterator it_card = card_vec.begin();it_card != card_vec.end();++it_card)
					{
						Json::Value callinfo;
						callinfo.append(user_name);
						callinfo.append((*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_ID]->get_string());
						int anchor_id = (int)((*it_reader)->get_map()[JSON_KEY_CALL_CARD_STATION_ID]->get_int());
						callinfo.append((int)((*it_reader)->get_map()[JSON_KEY_CALL_CARD_STATION_ID]->get_int()));
						callinfo.append((double)call_time_interval);
						callinfo.append(call_type_id);
						//CALL_STATE::CALL_SUCCESSED,CALL_STATE::CALL_ING,CALL_STATE::CALL_FAILED
						callinfo.append(CALL_STATE::CALL_ING);
						resp_data.append(callinfo);
					}
				}else{
					Json::Value callinfo;
					callinfo.append(user_name);
					callinfo.append(0);
					callinfo.append((int)((*it_reader)->get_map()[JSON_KEY_CALL_CARD_STATION_ID]->get_int()));
					callinfo.append((double)call_time_interval);
					callinfo.append(call_type_id);
					//CALL_STATE::CALL_SUCCESSED,CALL_STATE::CALL_ING,CALL_STATE::CALL_FAILED
					callinfo.append(CALL_STATE::CALL_ING);
					resp_data.append(callinfo);
				}			
			}
		} 
		else
		{
			//如果无分站信息
			for (vector<message::ptr>::const_iterator it_card = card_vec.begin();it_card != card_vec.end();++it_card)
			{
				Json::Value callinfo;
				callinfo.append(user_name);
				callinfo.append((*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_ID]->get_string());
				callinfo.append(0);
				callinfo.append((double)call_time_interval);
				callinfo.append(call_type_id);
				//CALL_STATE::CALL_SUCCESSED,CALL_STATE::CALL_ING,CALL_STATE::CALL_FAILED
				callinfo.append(CALL_STATE::CALL_ING);
				resp_data.append(callinfo);
			}
		}		
	}

	std::string ret = "";
	if(resp_data.size() > 0){
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_CALL_CARD_RESPONSE;
		root[JSON_ROOT_KEY_DATA] = resp_data;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION;
		ret = root.toFastString();
		send_json_data(JSON_CMD_VALUE_PUSH,ret);
	}

	Log::write_log(FILE_TYPE::SYS_S,"received call message from web.",true);
	strlog.Format(_T("%s%s"), _T(LOG_CALL_CARD), _T(LOG_SUCCESS));
	show_log(strlog);
}

void CYAServerDlg::parse_json_data_clear_card(message::ptr const& data)
{
	vector<message::ptr> card_vec = data->get_map()[JSON_ROOT_KEY_DATA]->get_vector();

	vector<message::ptr>::const_iterator it_card = card_vec.begin();

	if(card_vec.size() == 0 || "" == (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_ID]->get_string()){
		return ;
	}else{
		BYTE card_type = 0;
		for(; it_card != card_vec.end(); ++it_card){
			string s_card_id = (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_ID]->get_string();
			card_type = (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID]->get_int();

			CardMap::iterator itt_card = mp_card_list_all.find(s_card_id);
			if(itt_card != mp_card_list_all.end()){
				if(STATUS_LOST == itt_card->second->status_lost)
				{
					// 升井
					itt_card->second->up_time = time(NULL);
					itt_card->second->PosState(PDT_UP);
					store_data_card(itt_card->second, HIS_AREA_LOCATION_LEAVE);
					card_enter_mine(itt_card->second, POS_DEVICE_TYPE::PDT_UP);
				}
			}	
		}
	}
}

void CYAServerDlg::parse_json_data_deal_help( message::ptr const& data )
{
	map<string, message::ptr> data_map = data->get_map()[JSON_ROOT_KEY_DATA]->get_map();

	INT64 ev_id;
	string cardid = data_map[JSON_KEY_ID]->get_string();
	ev_id = data_map[JSON_KEY_EVENT_EVENT_ID]->get_int();

	CardMap::iterator it_card = mp_card_list_all.find(cardid);
	if(it_card != mp_card_list_all.end()){
		//debug_print_syslog(0,"[lemon_call_help_deal]%s",cardid.c_str());
		it_card->second->status_help_cancel = STATUS_HELP_DEALED;
		it_card->second->status_help = STATUS_HELP_DEALED;
	}

	EventMap::iterator it_ev = mp_event_list->find(ev_id);
	if(it_ev != mp_event_list->end())
	{
		//debug_print_syslog(0,"[lemon_call_help_deal_event]%s",cardid.c_str());
		it_ev->second->status = ES_DEAL_HELP;
	}

	CString strlog;
	strlog.Format(_T("%s%s"), _T(LOG_DEAL_HELP), _T(LOG_SUCCESS));
	show_log(strlog);
}

/*
* 处理web端发送的修改红绿灯颜色功能
* 
* param
*		data	---		前端json
*
* return
*		成功执行返回0，失败返回1
*/
int CYAServerDlg::parse_json_data_set_light_color(message::ptr const& data)
{
	vector<message::ptr> card_vec = data->get_map()[JSON_ROOT_KEY_DATA]->get_vector();
	std::string rec_data = data->get_map()[JSON_ROOT_KEY_DATA]->get_string();
	Log::write_log(FILE_TYPE::JSON_R,rec_data.c_str(),true);

	vector<message::ptr>::const_iterator it_card = card_vec.begin();
	for(; it_card != card_vec.end(); ++it_card)
	{
		int gid = (*it_card)->get_map()["GroupId"]->get_int();
		int lid = (*it_card)->get_map()["LightId"]->get_int();
		int control = (*it_card)->get_map()["Control"]->get_int();
		std::string name = (*it_card)->get_map()["ControlName"]->get_string();
		int state = (*it_card)->get_map()["LightColour"]->get_int();
		if (control == 1)
			m_carmanage->setManual(gid,lid,name,state);
		else
			m_carmanage->cancelManual(gid);
	}

	return 0;
}

void CYAServerDlg::deal_call_edit_map(int id, EDIT_TYPE_ID edit_type_id)
{
	CString strlog = _T("");
	switch (edit_type_id)
	{
	case ET_INSERT:
		{
			init_map(id);
			break;
		}
	case ET_UPDATE:
		{
			init_map(id);
			break;
		}
	case ET_DELETE:
		{
			MapInfoMap::iterator it_map = mp_map_list.find(id);
			if(it_map != mp_map_list.end()){
				mp_map_list.erase(it_map);
			}
			break;
		}
	default:
		break;
	}
	strlog.Format(_T("%s%s"), _T(LOG_EDIT_MAP), _T(LOG_SUCCESS));
	show_log(strlog);
}

void CYAServerDlg::deal_call_edit_area(int id, EDIT_TYPE_ID edit_type_id)
{
	CString strlog;
	switch (edit_type_id)
	{
	case ET_INSERT:
		{
			init_area(id);
			break;
		}
	case ET_UPDATE:
		{
			init_area(id);
			break;
		}
	case ET_DELETE:
		{
			AreaMap::iterator it_area = mp_area_list.find(id);
			if (it_area == mp_area_list.end())
			{
				return;
			}else{
				MapInfoMap::iterator it_map = mp_map_list.find(it_area->second->map_id);
				if(it_map != mp_map_list.end()){
					AreaMap::iterator it_map_area = it_map->second->map_area_list.find(id);
					it_map->second->map_area_list.erase(it_map_area);
				}
				if(it_area != mp_area_list.end()){
					mp_area_list.erase(it_area);
				}

				it_area = mp_area_over_count_person->find(id);
				if(it_area != mp_area_over_count_person->end()){
					mp_area_over_count_person->erase(it_area);
				}
				it_area = mp_area_over_time_person->find(id);
				if(it_area != mp_area_over_time_person->end()){
					mp_area_over_time_person->erase(it_area);
				}
				it_area = mp_area_forbidden_person->find(id);
				if(it_area != mp_area_forbidden_person->end()){
					mp_area_forbidden_person->erase(it_area);
				}
				it_area = mp_area_over_count_vehicle->find(id);
				if(it_area != mp_area_over_count_vehicle->end()){
					mp_area_over_count_vehicle->erase(it_area);
				}
				it_area = mp_area_over_time_vehicle->find(id);
				if(it_area != mp_area_over_time_vehicle->end()){
					mp_area_over_time_vehicle->erase(it_area);
				}
				it_area = mp_area_forbidden_vehicle->find(id);
				if(it_area != mp_area_forbidden_vehicle->end()){
					mp_area_forbidden_vehicle->erase(it_area);
				}
			}
			break;
		}
	default:
		break;
	}
	strlog.Format(_T("%s%s"), _T(LOG_EDIT_AREA), _T(LOG_SUCCESS));
	show_log(strlog);
}

void CYAServerDlg::deal_call_edit_reader(int id, EDIT_TYPE_ID edit_type_id)
{
	CString strlog;
	switch (edit_type_id)
	{
	case ET_INSERT:
		{
			init_reader(id);
			break;
		}
	case ET_UPDATE:
		{
			init_reader(id);
			break;
		}
	case ET_DELETE:
		{
			ReaderMap::iterator it_reader = mp_reader_list.find(id);
			MapInfoMap::iterator it_map = mp_map_list.find(it_reader->second->map_id);
			if(it_map != mp_map_list.end()){
				ReaderMap::iterator it_map_reader = it_map->second->map_reader_list.find(id);
				if(it_map_reader != it_map->second->map_reader_list.end()){
					it_map->second->map_reader_list.erase(it_map_reader);
				}
			}
			if(it_reader != mp_reader_list.end()){
				mp_reader_list.erase(it_reader);
			}
			break;
		}
	default:
		break;
	}
	strlog.Format(_T("%s%s"), _T(LOG_EDIT_READER), _T(LOG_SUCCESS));
	show_log(strlog);
}

void CYAServerDlg::deal_call_edit_card(string id, EDIT_TYPE_ID edit_type_id)
{
	init_card();
	CString strlog;
	CardMap::iterator it_card = mp_card_list_all.find(id);
	if(it_card == mp_card_list_all.end()){
		return;
	}
	int card_type_id = it_card->second->card_type;
	switch (edit_type_id)
	{
	case ET_INSERT:
		{
			if(CT_VEHICLE == card_type_id){
				init_vehicle(id, true);
			}else if(CT_PERSON == card_type_id) {
				init_staffer(id, true);
			}else if(CT_ADHOC == card_type_id){
				init_adhoc(id, true);
			}
			break;
		}
	case ET_UPDATE:
		{
			if(CT_VEHICLE == card_type_id){
				init_vehicle(id, true);
			}else if(CT_PERSON == card_type_id) {
				init_staffer(id, true);
			}else if(CT_ADHOC == card_type_id){
				init_adhoc(id, true);
			}
			break;
		}
	case ET_DELETE:
		{
			remove_card(id);
			break;
		}
	default:
		break;
	}
	strlog.Format(_T("%s%s"), _T(LOG_EDIT_CARD), _T(LOG_SUCCESS));
	show_log(strlog);
}

void CYAServerDlg::deal_call_edit_staff(string id, EDIT_TYPE_ID edit_type_id)
{
	CString strlog;
	switch (edit_type_id)
	{
	case ET_INSERT:
		{
			init_staffer(id);
			break;
		}
	case ET_UPDATE:
		{
			init_staffer(id);
			break;
		}
	case ET_DELETE:
		{
			string cardid = "";
			CardMap::iterator it_card = mp_card_list_down_person.begin();
			for(; it_card != mp_card_list_down_person.end(); ++it_card){
				if(it_card->second->id == atoi(id.c_str())){
					cardid = it_card->second->card_id;
					break;
				}
			}
			remove_card(cardid);
			break;
		}
	default:
		break;
	}
	strlog.Format(_T("%s%s"), _T(LOG_EDIT_STAFFER), _T(LOG_SUCCESS));
	show_log(strlog);
}

void CYAServerDlg::deal_call_edit_vehicle(string id, EDIT_TYPE_ID edit_type_id)
{
	CString strlog;
	switch (edit_type_id)
	{
	case ET_INSERT:
		{
			init_vehicle(id);
			break;
		}
	case ET_UPDATE:
		{
			init_vehicle(id);
			break;
		}
	case ET_DELETE:
		{
			string cardid = "";
			CardMap::iterator it_card = mp_card_list_down_vehicle.begin();
			for(; it_card != mp_card_list_down_vehicle.end(); ++it_card){
				if(it_card->second->id == atoi(id.c_str())){
					cardid = it_card->second->card_id;
					break;
				}
			}
			remove_card(cardid);
			break;
		}
	default:
		break;
	}
	strlog.Format(_T("%s%s"), _T(LOG_EDIT_VEHICLE), _T(LOG_SUCCESS));
	show_log(strlog);
}

void CYAServerDlg::deal_call_edit_adhoc(string id, EDIT_TYPE_ID edit_type_id)
{
	CString strlog;
	switch (edit_type_id)
	{
	case ET_INSERT:
		{
			init_adhoc(id);
			break;
		}
	case ET_UPDATE:
		{
			init_adhoc(id);
			break;
		}
	case ET_DELETE:
		{
			string cardid = "";
			CardMap::iterator it_card = mp_card_list_down_adhoc.begin();
			for(; it_card != mp_card_list_down_adhoc.end(); ++it_card){
				if(it_card->second->id == atoi(id.c_str())){
					cardid = it_card->second->card_id;
					break;
				}
			}
			remove_card(cardid);
			break;
		}
	default:
		break;
	}
	strlog.Format(_T("%s%s"), _T(LOG_EDIT_ADHOC), _T(LOG_SUCCESS));
	show_log(strlog);
}

int CYAServerDlg::deal_call_edit_section(int id,EDIT_TYPE_ID edit_type_id)
{
	switch (edit_type_id)
	{
	case ET_INSERT:
		{
			init_section(id);
			break;
		}
	case ET_UPDATE:
		{
			init_section(id);
			break;
		}
	case ET_DELETE:
		{
			//删除路段后要将硐室表和灯组表中灯的路段信息改写
			ChamberMap::iterator it_chamber = mp_chamber_list.begin();
			for (;it_chamber != mp_chamber_list.end();++it_chamber)
			{
				if (it_chamber->second->m_nSectionID == id)
				{
					it_chamber->second->m_nSectionID = 0;
					break;
				}
			}

			LightGroupMap::iterator it_light_group = mp_light_group_list.begin();
			for (;it_light_group != mp_light_group_list.end();++it_light_group)
			{
				if (it_light_group->second->m_nSectionId == id)
				{
					it_light_group->second->m_nSectionId = 0;
					break;
				}
			}

			//删除路段信息
			SectionMap::iterator it_section = mp_section_list.find(id);
			if (it_section != mp_section_list.end())
			{
				mp_section_list.erase(it_section);
			}


			break;
		}
	default:
		break;
	}

	CString cstrLog = _T("");
	cstrLog.Format(_T("%s%s"), _T(LOG_EDIT_SECTION), _T(LOG_SUCCESS));
	show_log(cstrLog);

	return 0;
}

int CYAServerDlg::deal_call_edit_light(int id,EDIT_TYPE_ID edit_type_id)
{
	switch (edit_type_id)
	{
	case ET_INSERT:
		{
			init_traffic_lights(id);
			break;
		}
	case ET_UPDATE:
		{
			init_traffic_lights(id);
			break;
		}
	case ET_DELETE:
		{
			bool bFind = false;
			//灯组中删除
			LightGroupMap::iterator it_light_group = mp_light_group_list.begin();
			for (;it_light_group != mp_light_group_list.end();++it_light_group)
			{
				LightMap::iterator it_light = it_light_group->second->mp_lights_list.find(id);
				if (it_light != it_light_group->second->mp_lights_list.end())
				{
					it_light_group->second->mp_lights_list.erase(it_light);
					break;
				}
			}

			bFind = false;
			//路段中删除
			SectionMap::iterator it_section = mp_section_list.begin();
			for (;it_section != mp_section_list.end();++it_section)
			{
				LightMap::iterator it_light = it_section->second->mp_light_list.begin();
				for (;it_light != it_section->second->mp_light_list.end();++it_light)
				{
					if (it_light->second->m_nID == id)
					{
						bFind = true;
						it_section->second->mp_light_list.erase(it_light);
						break;
					}
				}
				if (bFind)
				{
					break;
				}
			}

			//从灯表中删除
			LightMap::iterator it = mp_light_list.find(id);
			if (it != mp_light_list.end())
			{
				mp_light_list.erase(it);
			}

			break;
		}
	default:
		break; 
	}

	CString cstrLog = _T("");
	cstrLog.Format(_T("%s%s"), _T(LOG_EDIT_LIGHT), _T(LOG_SUCCESS));
	show_log(cstrLog);

	return 0;
}


int CYAServerDlg::deal_call_edit_light_group(int id,EDIT_TYPE_ID edit_type_id)
{
	init_light_group(id);

	auto it_group = (*m_carmanage)[id];
	if (it_group != nullptr)
	{
		int phy_id = 0;
		for (auto it_light : it_group->m_pTrafficLight)
		{
			if (phy_id != it_light->m_physics_light_id)
			{
				send_light_auto_control_param(it_light->m_physics_light_id,it_group->m_auto_control_interval,it_light->m_ip);
				phy_id = it_light->m_physics_light_id;
			}
		}
	}

	CString cstrLog = _T("");
	cstrLog.Format(_T("%s%s"), _T(LOG_EDIT_LIGHT_GROUP), _T(LOG_SUCCESS));
	show_log(cstrLog);

	return 0;
}

/*
 
* 获得所有卡的惯导校准数据的列表，按分站归置
*
* param
*		无
*
* return
*		成功返回0，失败返回非零值
*
*/
int CYAServerDlg::get_ins_cal_list()
{
	for (CardMap::iterator it_card = mp_card_list_all.begin();it_card != mp_card_list_all.end();++it_card)
	{
		//此条件为有请求状态才按分站组装数据，此处，改为只有有定位结果就放进队列，等待2s周期下发的处理
		//if (YES_INS_REQUEST == it_card->second->ins_request_check)
		//if (!it_card->second->is_send_ins_check)		//控制只发送一次校准坐标
		{
			//it_card->second->is_send_ins_check = true;
			if (!it_card->second->is_deal_by_algo)
			{
				continue;
			}

			if (it_card->second->x == INVALID_COORDINATE && it_card->second->y == INVALID_COORDINATE)
			{
				//TRACE(_T("locate failed! \r\n"));
				continue;
			}

			//如果校准，构造数据存入map中
			int nReaderId = -1;
			nReaderId = it_card->second->reader_id_algo;
			if (-1 == nReaderId || 0 == nReaderId)
			{
				continue;
			}
			//查找此分站对应的校准卡数据是否存在
			map<int,std::shared_ptr<CardCalData>>::iterator it_reader_cal_data = mp_ins_cal_data_list->find(nReaderId);

			if (it_reader_cal_data == mp_ins_cal_data_list->end())
			{
				//如果分站对应的map中不存在需要校准的卡数据map，构造此map
				std::shared_ptr<CardCalData> pCardCalData = nullptr;
				pCardCalData = std::make_shared<CardCalData>();
				mp_ins_cal_data_list->insert(std::make_pair(nReaderId,pCardCalData));
				it_reader_cal_data = mp_ins_cal_data_list->find(nReaderId);
			}else{ 
			}

			//如果分站对应的map中存在需要校准的卡数据
			CardCalData::iterator it_card_cal_data = it_reader_cal_data->second->find(it_card->second->card_id);
			if (it_card_cal_data == it_reader_cal_data->second->end())
			{
				//如果卡数据不存在，构造卡数据
				std::shared_ptr<CAL_DATA> pCalData = nullptr;
				pCalData = std::make_shared<CAL_DATA>();
				it_reader_cal_data->second->insert(std::make_pair(it_card->second->card_id,pCalData));
				it_card_cal_data = it_reader_cal_data->second->find(it_card->second->card_id);
			}
			//卡数据存在，更新卡数据
			it_card->second->ins_cal_type = CAL_DATA_POS;
			it_card_cal_data->second->card_type = it_card->second->card_type;
			it_card_cal_data->second->card_id = it_card->second->card_id;
			it_card_cal_data->second->x = it_card->second->x*it_card->second->map_scale;
			it_card_cal_data->second->y = it_card->second->y*it_card->second->map_scale;
			//it_card_cal_data->second->angle = it_card->second->ins_gyp_angle;
			it_card_cal_data->second->status = it_card->second->ins_cal_type;
		}
	}

	return 0;
}

/*
 
* 构造人上车json
* author&date
*		zhuyf 2017/10/19
*
* param
*		无
* return
*		json字符串
*
*/
std::string CYAServerDlg::get_json_person_on_car()
{
	Json::Value root;
	Json::Value data;

	//如果移动分站存在，车卡不存在
	for (MovingReaderMap::iterator it_reader = mp_moving_reader_list->begin();it_reader != mp_moving_reader_list->end();++it_reader)
	{
		if (it_reader->second->pVehicleCard == nullptr)
		{
			continue;
		}

		Json::Value element;
		Json::Value persons;
		//获得车卡的类型
		element.append(it_reader->second->pVehicleCard->card_type);
		//获得车卡的卡号
		std::string new_card_id = it_reader->second->pVehicleCard->card_id.substr(3, it_reader->second->pVehicleCard->card_id.length());
		element.append(atoi(new_card_id.c_str()));
		//获得当前乘坐此车的总人员总数
		element.append(it_reader->second->pVehicleCard->mp_person_in_vechicle_list->size());

		for (CardMap::iterator it_person_card = it_reader->second->pVehicleCard->mp_person_in_vechicle_list->begin();it_person_card != it_reader->second->pVehicleCard->mp_person_in_vechicle_list->end();++it_person_card)
		{
			Json::Value person;

			//获得人卡的卡类型
			person.append(it_person_card->second->card_type);
			//获得人卡的卡号
			std::string new_card_id = it_person_card->second->card_id.substr(3, it_person_card->second->card_id.length());
			person.append(atoi(new_card_id.c_str()));
			//获得人卡的上车状态
			person.append(it_person_card->second->person_on_card);

			if (!person.empty())
			{
				persons.append(person);
			}
		}

		if (!persons.empty())
		{
			element.append(persons);
		}

		if (!element.empty())
		{
			data.append(element);
		}
	}

	std::string ret = "";
	if (!data.empty())
	{
		root[JSON_ROOT_KEY_CMD] = JSON_KEY_PERSON_ON_CAR;
		root[JSON_ROOT_KEY_DATA] = data;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION_1_3;
		ret = root.toFastString();

		if (ret != "")
		{
			char chLog[MAX_LOG_LENGTH] = {0};
			sprintf_s(chLog,"no params: %s",ret.c_str());
			Log::write_log(FILE_TYPE::SYS_S,chLog,true);
		}
	}

	return ret;
}

/*
 
* 构造人上车json
* author&date
*		zhuyf 2017/10/19
*
* param
*		无
* return
*		json字符串
*
*/
std::string CYAServerDlg::get_json_person_on_car(map<string,OnVehicleData>& real_on_card_data)
{
	Json::Value root;
	Json::Value data;

	for (map<string,OnVehicleData>::iterator it = real_on_card_data.begin();it != real_on_card_data.end();++it)
	{
		Json::Value element;
		Json::Value persons;

		std::string card_id = it->first;
		std::string card_type = card_id.substr(0,3);
		std::string card_ident = card_id.substr(3,card_id.length());

		int nCardType = 0;
		int nCardIdent = 0;

		nCardType = atoi(card_type.c_str());
		nCardIdent = atoi(card_ident.c_str());

		element.append(nCardType);
		element.append(nCardIdent);
		element.append(it->second.counts);
		for (map<string,int>::iterator it_person = it->second.person_cards.begin();it_person != it->second.person_cards.end();++it_person)
		{
			Json::Value person;

			std::string person_card_id = it_person->first;
			std::string person_card_type = person_card_id.substr(0,3);
			std::string person_card_ident = person_card_id.substr(3,person_card_id.length());

			int nPersonCardType = 0;
			int nPersonCardIdent = 0;

			nPersonCardType = atoi(person_card_type.c_str());
			nPersonCardIdent = atoi(person_card_ident.c_str());

			person.append(nPersonCardType);
			person.append(nPersonCardIdent);
			person.append(it_person->second);

			if (!person.empty())
			{
				persons.append(person);
			}
		}

		if (!persons.empty())
		{
			element.append(persons);
		}

		if (!element.empty())
		{
			data.append(element);
		}
	}

	std::string ret = "";
	if (!data.empty())
	{
		root[JSON_ROOT_KEY_CMD] = JSON_KEY_PERSON_ON_CAR;
		root[JSON_ROOT_KEY_DATA] = data;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION_1_3;
		ret = root.toFastString();

		if (ret != "")
		{
			char chLog[MAX_LOG_LENGTH] = {0};
			sprintf_s(chLog,"no params: %s",ret.c_str());
			Log::write_log(FILE_TYPE::SYS_S,chLog,true);
		}
	}

	return ret;
}

Json::Value CYAServerDlg::get_json_all_person_on_car()
{	
	Json::Value data;

	//如果移动分站存在，车卡不存在
	for (MovingReaderMap::iterator it_reader = mp_moving_reader_list->begin();it_reader != mp_moving_reader_list->end();++it_reader)
	{
		if (it_reader->second->pVehicleCard == nullptr)
		{
			continue;
		}

		Json::Value element;
		Json::Value persons;
		//获得车卡的类型
		element.append(it_reader->second->pVehicleCard->card_type);
		//获得车卡的卡号
		std::string new_card_id = it_reader->second->pVehicleCard->card_id.substr(3, it_reader->second->pVehicleCard->card_id.length());
		element.append(atoi(new_card_id.c_str()));
		//获得当前乘坐此车的总人员总数
		element.append(it_reader->second->pVehicleCard->mp_person_in_vechicle_list->size());

		for (CardMap::iterator it_person_card = it_reader->second->pVehicleCard->mp_person_in_vechicle_list->begin();it_person_card != it_reader->second->pVehicleCard->mp_person_in_vechicle_list->end();++it_person_card)
		{
			Json::Value person;

			//获得人卡的卡类型
			person.append(it_person_card->second->card_type);
			//获得人卡的卡号
			std::string new_card_id = it_person_card->second->card_id.substr(3, it_person_card->second->card_id.length());
			person.append(atoi(new_card_id.c_str()));
			//获得人卡的上车状态
			person.append(it_person_card->second->person_on_card);

			if (!person.empty())
			{
				persons.append(person);
			}

			break;
		}
	}

	return 0;
}

void CYAServerDlg::deal_call_edit_rules(int id,EDIT_TYPE_ID edit_type_id)
{
	CString strlog;
	switch (edit_type_id)
	{
	case ET_INSERT:
		{

			init_rules(id);
			break;
		}

	case ET_UPDATE:
		{

			init_rules(id);
			break;
		}
	case ET_DELETE:
		{
			RulesMap::iterator it_rules = m_rules_list.find(id);
			if(it_rules != m_rules_list.end())
				m_rules_list.erase(it_rules);
			break;
		}
	default:
		break;
	}

	strlog.Format(_T("%s%s"), _T(LOG_EDIT_STAFFER), _T(LOG_SUCCESS));
	show_log(strlog);
}

std::string CYAServerDlg::get_json_all_person_on_car(std::string val)
{
	Json::Value root;
	Json::Value data;

	std::string ret = "";

	if (val != "")
	{
		data.append(val);
	}

	Json::Value persons = get_json_all_person_on_car();
	if (!persons.empty())
	{
		data.append(persons);
	}

	if (!data.empty())
	{
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_RESP_ALL_PERSON_ON_CAR;
		root[JSON_ROOT_KEY_DATA] = data;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION_1_3;
		ret = root.toFastString();
	}

	return ret;
}

int CYAServerDlg::deal_call_edit_chamber(int id,EDIT_TYPE_ID edit_type_id)
{
	switch (edit_type_id)
	{
	case ET_INSERT:
		{
			init_chamber(id);
			break;
		}
	case ET_UPDATE:
		{
			init_chamber(id);
			break;
		}
	case ET_DELETE:
		{
			//路段中删除硐室
			SectionMap::iterator it_section = mp_section_list.begin();
			for (;it_section != mp_section_list.end();++it_section)
			{
				ChamberMap::iterator it_chamber = mp_chamber_list.begin();
				for (;it_chamber != mp_chamber_list.end();++it_chamber)
				{
					if (it_chamber->second->m_nID == id)
					{
						mp_chamber_list.erase(it_chamber);
						break;
					}
				}
			}

			//硐室表中删除
			ChamberMap::iterator it = mp_chamber_list.find(id);
			if (it != mp_chamber_list.end())
			{
				mp_chamber_list.erase(it);
			}
			break;
		}
	default:
		break;
	}

	CString cstrLog = _T("");
	cstrLog.Format(_T("%s%s"), _T(LOG_EDIT_CHAMBER), _T(LOG_SUCCESS));
	show_log(cstrLog);

	return 0;
}

void CYAServerDlg::remove_card( string card_id )
{
	if(card_id.length() == 0)
		return;
	int card_type_id = 0;
	CardMap::iterator it_card = mp_card_list_all.find(card_id);
	if(it_card == mp_card_list_all.end()){
		return;
	}
	card_type_id = it_card->second->card_type;

	int map_id = 0,area_id = 0,dept_id = 0, occ_id = 0, level_id = 0;
	map_id = it_card->second->map_id;
	area_id = it_card->second->area_id;
	dept_id = it_card->second->dept_id;
	occ_id = it_card->second->occ_id;
	level_id = it_card->second->level_id;

	clear_card_from_list(it_card->second);

	// 避免状态重置
	mp_card_list_all.erase(it_card);
}

void CYAServerDlg::calculate_card_postion_by_tof(std::shared_ptr<Card> card) // 计算card坐标
{
	g_anchorNum = card->reader_id;
	card->x = card->p_reader->ant[card->antenna_id]->antenna_x;
	card->y = card->p_reader->ant[card->antenna_id]->antenna_y;
	card->z = card->p_reader->ant[card->antenna_id]->antenna_z;
	card->a = card->p_reader->ant[card->antenna_id]->antenna_angle;
	card->area_id = card->p_reader->area_id;
	double sina = sin(card->a);
	double cosa = cos(card->a);
	std::shared_ptr<MapInfo> pMap = nullptr;
	MapInfoMap::iterator it = mp_map_list.find(card->map_id);
	if(it != mp_map_list.end()){
		pMap = it->second;
	}
	else
	{
		return;
	}

	double move_x = card->distance * cos(card->a) / pMap->map_scale;
	double move_y = card->distance * sin(card->a) / pMap->map_scale;
	card->x = card->x + move_x;
	card->y = card->y + move_y;

	return;
}

void CYAServerDlg::process_driving_face_start_service(std::shared_ptr<Card> card)
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_236);

	char sql[LENGTH_SQL] = {'\0'};
	std::string cur_shift_start_time = "";

	//	std::string cur_shift_end_time = "";

	int shift_id = 0;
	cur_shift_start_time = CFunctions::time_t2string(GetCurShiftStartTime(shift_id));
	//cur_shift_end_time = CFunctions::time_t2string(GetCurShiftEndTime());
	std::string drivingface_start_time = CFunctions::time_t2string(time(NULL));
	//掘进机启动时间
	card->m_drivingface_start_time = drivingface_start_time;

	std::shared_ptr<DrivingfaceCard> pDrivingfacecard = nullptr;
	DrivingfaceCardMap::iterator it = mp_driving_face_card_list.find(card->card_id);

	if(it == mp_driving_face_card_list.end()){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_237);
		return;
	}
	else
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_238);
		pDrivingfacecard = it->second;
		int drivingface_id = pDrivingfacecard->drivingface_id;
		std::shared_ptr<MapInfo> pMap = nullptr;
		MapInfoMap::iterator it = mp_map_list.find(card->map_id);
		if(it != mp_map_list.end()){
			pMap = it->second;
		}
		else
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_239);
			return;
		}

		float last_total_finsh_length = 0;
		float cur_total_finish_length = 0;
		float cur_shift_finish_length = 0;
		float diff_dis_flag = 0;

		last_total_finsh_length = sqrt(pow(card->driving_face_cur_shift_x - pDrivingfacecard->x, 2)
			+ pow(card->driving_face_cur_shift_y - pDrivingfacecard->y, 2)
			+ pow(card->driving_face_cur_shift_z - pDrivingfacecard->z, 2)) * card->map_scale;

		cur_total_finish_length = sqrt(pow(card->x - pDrivingfacecard->x, 2)
			+ pow(card->y - pDrivingfacecard->y, 2)
			+ pow(card->z - pDrivingfacecard->z, 2)) * card->map_scale;

		cur_shift_finish_length = sqrt(pow(card->x - card->driving_face_cur_shift_start_x, 2)
			+ pow(card->y - card->driving_face_cur_shift_start_y, 2)
			+ pow(card->z - card->driving_face_cur_shift_start_z, 2)) * card->map_scale;

		diff_dis_flag = (cur_total_finish_length - last_total_finsh_length) * pMap->map_scale;
		if(diff_dis_flag >= 0)
		{
			card->driving_face_cur_shift_x = card->x;
			card->driving_face_cur_shift_y = card->y;
			card->driving_face_cur_shift_z = card->z;
		}
		else
		{
			cur_total_finish_length = last_total_finsh_length;
			cur_shift_finish_length = sqrt(pow(card->driving_face_cur_shift_x - card->driving_face_cur_shift_start_x, 2)
				+ pow(card->driving_face_cur_shift_y - card->driving_face_cur_shift_start_y, 2)
				+ pow(card->driving_face_cur_shift_z - card->driving_face_cur_shift_start_z, 2)) * card->map_scale;
		}


		char buf[LENGTH_SQL] = {0};
		sprintf_s(buf,LENGTH_SQL,"process_driving_face_start_service[lemon]:card->x:%f,card->y:%f,card->driving_face_cur_shift_start_x:%f,card->driving_face_cur_shift_start_y:%f,card->driving_face_cur_shift_x:%f,card->driving_face_cur_shift_y:%f,last_total_finsh_length:%f,cur_total_finish_length:%f",
			card->x,card->y,card->driving_face_cur_shift_start_x,card->driving_face_cur_shift_start_y,card->driving_face_cur_shift_x,card->driving_face_cur_shift_y,last_total_finsh_length,cur_total_finish_length);
		Log::write_log(FILE_TYPE::SQL_S,buf,true);

		//掘进机启动坐标
		card->m_drivingface_start_x = card->driving_face_cur_shift_x;
		card->m_drivingface_start_y = card->driving_face_cur_shift_y;
		card->m_drivingface_start_z = card->driving_face_cur_shift_z;

		sprintf_s(sql, LENGTH_SQL, 
			"INSERT IGNORE INTO his_drivingface_his(drivingface_id, card_id, finsh_length, cur_finish_length, start_time,end_time, start_x, start_y, start_z, end_x, end_y, end_z,shift_id) \
			VALUES(%d, %s, %.3f, %.3f, '%s','%s', %.3f, %.3f, %.3f, %.3f, %.3f, %.3f,%d);",  
			drivingface_id, 
			card->card_id.c_str(), 
			cur_total_finish_length, 
			0.0,
			drivingface_start_time.c_str(), 
			drivingface_start_time.c_str(), 
			card->driving_face_cur_shift_x, 
			card->driving_face_cur_shift_y, 
			card->driving_face_cur_shift_z,
			card->driving_face_cur_shift_x, 
			card->driving_face_cur_shift_y, 
			card->driving_face_cur_shift_z,
			shift_id);

		execute_sql(sql);
		debug_print_syslog(0, "driving face update sql: %s", sql);
		card->is_driving_face_start = 1;
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_240);
		//update_driving_face_data(card);
	}
	return;
}

void CYAServerDlg::send_drivingface_card_position_json(bool approve /*= false*/)
{
	DrivingfaceCardMap::iterator it_card = mp_driving_face_card_list.begin();
	for(;it_card!=mp_driving_face_card_list.end();it_card++)
	{
		string card_id = it_card->first;

		CardMap::iterator it_vehicle = mp_card_list_all.find(card_id);
		if(it_vehicle != mp_card_list_all.end())
		{
			if (((!it_vehicle->second->is_drivingface_Initialization) || (0 == it_vehicle->second->is_driving_face_start)) && !approve )
			{
				continue;
			}
			//begin here lemon 2017/08/01
			if (need_display_verification(it_vehicle->second))
			{
				send_json_data(JSON_CMD_VALUE_PUSH, get_json_drivingface_card_position(it_vehicle->second));
				//debug_print_syslog(0, "find drivingface card: %s.", it_vehicle->second->card_id.c_str());
			}
			else
			{
				debug_print_syslog(0, "find drivingface card: %s.[do not display]", it_vehicle->second->card_id.c_str());
			}
			//update_driving_face_data(it_vehicle->second);
		}
		//debug_print_syslog(0, "period send drivingface card stat.%s", card_id.c_str());
	}
}

void CYAServerDlg::write_drivingface_shift_start_data(std::shared_ptr<Card> card)
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_249);

	char sql[LENGTH_SQL] = {'\0'};

	std::string strCurShiftStartTime = "";
	std::string strCurShiftEndTime = "";

	int shift_id = 0;
	strCurShiftStartTime = CFunctions::time_t2string(GetCurShiftStartTime(shift_id));
	time_t end_time = GetCurShiftEndTime();
	strCurShiftEndTime = CFunctions::time_t2string(end_time);

	std::shared_ptr<DrivingfaceCard> pDrivingfaceCard = nullptr;
	DrivingfaceCardMap::iterator it_card = mp_driving_face_card_list.find(card->card_id);
	if(it_card == mp_driving_face_card_list.end())
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_250);
		return;
	}
	else
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_251);
		pDrivingfaceCard = it_card->second;
		int drivingface_id = pDrivingfaceCard->drivingface_id;
		float last_total_finsh_length = 0;
		float cur_total_finish_length = 0;
		float cur_shift_finish_length = 0;
		float diff_dis_flag = 0;


		last_total_finsh_length = sqrt(pow(card->driving_face_cur_shift_start_x - pDrivingfaceCard->x, 2)
			+ pow(card->driving_face_cur_shift_start_y - pDrivingfaceCard->y, 2)
			+ pow(card->driving_face_cur_shift_start_z - pDrivingfaceCard->z, 2)) * card->map_scale;;

		cur_total_finish_length = sqrt(pow(card->x - pDrivingfaceCard->x, 2)
			+ pow(card->y - pDrivingfaceCard->y, 2)
			+ pow(card->z - pDrivingfaceCard->z, 2)) * card->map_scale;

		cur_shift_finish_length = sqrt(pow(card->x - card->driving_face_cur_shift_start_x, 2)
			+ pow(card->y - card->driving_face_cur_shift_start_y, 2)
			+ pow(card->z - card->driving_face_cur_shift_start_z, 2)) * card->map_scale;

		std::shared_ptr<MapInfo> pMap = nullptr;
		MapInfoMap::iterator it = mp_map_list.find(card->map_id);
		if(it != mp_map_list.end()){
			pMap = it->second;
		}
		else
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_252);
			return;
		}

		diff_dis_flag = (cur_total_finish_length - last_total_finsh_length) * pMap->map_scale;

#ifdef _DEBUG
		char buf[LENGTH_SQL] = {0};
		sprintf_s(buf,"write_drivingface_shift_start_data[lemon]:card->x:%f,card->y:%f,card->driving_face_cur_shift_start_x:%f,card->driving_face_cur_shift_start_y:%f,card->driving_face_cur_shift_x:%f,card->driving_face_cur_shift_y:%f,last_total_finsh_length:%f,cur_total_finish_length:%f",
			card->x,card->y,card->driving_face_cur_shift_start_x,card->driving_face_cur_shift_start_y,card->driving_face_cur_shift_x,card->driving_face_cur_shift_y,last_total_finsh_length,cur_total_finish_length);
		Log::write_log(FILE_TYPE::SQL_S,buf,true);
#endif
#if 0
		if(diff_dis_flag >= 0)
		{
			card->driving_face_cur_shift_x = card->x;
			card->driving_face_cur_shift_y = card->y;
			card->driving_face_cur_shift_z = card->z;
			card->driving_face_cur_shift_start_x = card->driving_face_cur_shift_x;
			card->driving_face_cur_shift_start_y = card->driving_face_cur_shift_y; 
			card->driving_face_cur_shift_start_z = card->driving_face_cur_shift_z;
		}
		else
		{
			card->driving_face_cur_shift_start_x = card->driving_face_cur_shift_x;
			card->driving_face_cur_shift_start_y = card->driving_face_cur_shift_y; 
			card->driving_face_cur_shift_start_z = card->driving_face_cur_shift_z;
			cur_total_finish_length = last_total_finsh_length;
			cur_shift_finish_length = 0;
		}
#endif
		sprintf_s(sql, LENGTH_SQL, 
			"INSERT IGNORE INTO his_drivingface_his(drivingface_id, card_id, finsh_length, cur_finish_length, start_time, end_time, start_x, start_y, start_z, end_x, end_y, end_z) \
			VALUES(%d, %s, %.3f, %.3f, '%s', '%s', %.3f, %.3f, %.3f, %.3f, %.3f, %.3f);",  
			drivingface_id, 
			card->card_id.c_str(), 
			cur_total_finish_length, 
			0.0,
			strCurShiftStartTime.c_str(), 
			strCurShiftEndTime.c_str(), 
			card->driving_face_cur_shift_start_x, 
			card->driving_face_cur_shift_start_y, 
			card->driving_face_cur_shift_start_z,
			card->driving_face_cur_shift_x, 
			card->driving_face_cur_shift_y, 
			card->driving_face_cur_shift_z);
		execute_sql(sql);
		debug_print_syslog(0, "driving face shift start sql: %s", sql);
	}
	return;
}
void CYAServerDlg::driving_face_shift_start()
{
	DrivingfaceCardMap::iterator it = mp_driving_face_card_list.begin();
	string card_id;
	for(;it != mp_driving_face_card_list.end();it++)
	{

		card_id = it->first;
		CardMap::iterator it_vehicle = mp_card_list_all.find(card_id);

		std::shared_ptr<Card> card = nullptr;
		if(it_vehicle != mp_card_list_all.end())
		{
			card = it_vehicle->second;
			if (!card->is_drivingface_Initialization)
			{
				continue;
			}
			if(card)
			{
				int shift_id = 0;
				GetCurShiftStartTime(shift_id);
				if (card->shift_id != shift_id)
				{
					card->shift_id = shift_id;
					cur_shift_id = shift_id;
					//update shift start point
					card->driving_face_cur_shift_start_x = card->driving_face_cur_shift_x;
					card->driving_face_cur_shift_start_y = card->driving_face_cur_shift_y; 
					card->driving_face_cur_shift_start_z = card->driving_face_cur_shift_z;

					//write_drivingface_shift_start_data(card);
					store_driving_face_data(card);
				}

			}
		}
	}
	return; 
}

void CYAServerDlg::process_driving_face_end_service(std::shared_ptr<Card> card)
{

	if(0 == card->is_driving_face_start)
	{
		return ;
	}
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_241);
	DrivingfaceCardMap::iterator it = mp_driving_face_card_list.find(card->card_id);

	if(it == mp_driving_face_card_list.end())
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_242);
		return;
	}
	else
	{
		//跟新一下结束时间。1保证其结束时间的准确性2.确保
		std::string end_time = CFunctions::time_t2string(time(NULL));
		char sql[LENGTH_SQL] = { 0 };
		sprintf_s(sql,LENGTH_SQL,"update his_drivingface_his set end_time = '%s' where card_id = %s and start_time = '%s' ;",
			end_time.c_str(),
			card->card_id.c_str(),
			card->m_drivingface_start_time.c_str());

		Log::write_log(SYS_S,sql,true);
		execute_sql(sql);

		card->is_driving_face_start = 0;
		card->m_drivingface_start_time.clear();
		card->m_drivingface_start_x = 0.0;
		card->m_drivingface_start_y = 0.0;
		card->m_drivingface_start_z = 0.0;
	}
}

void CYAServerDlg::store_driving_face_data(std::shared_ptr<Card> card)
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_259);
	char sql[LENGTH_SQL] = {'\0'};
	int shift_id = 0;
	string str_card_id = card->card_id;
	//string str_card_id = CFunctions::getstrwithzero(2, 3) + CFunctions::getstrwithzero(1014, 10);
	std::string s = CFunctions::time_t2string(this->GetCurShiftStartTime(shift_id));

	if(card)
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_260);
		float last_total_finsh_length = 0;
		float cur_total_finish_length = 0;
		float cur_shift_finish_length = 0;
		float dis_diff_flag = 0;

		std::shared_ptr<DrivingfaceCard> pDrivingfaceCard = nullptr;
		DrivingfaceCardMap::iterator it_card = mp_driving_face_card_list.find(str_card_id);
		if(it_card == mp_driving_face_card_list.end())
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_261);
    	
			return;
		}
		else
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_262);
			pDrivingfaceCard = it_card->second;
		

			last_total_finsh_length = sqrt(pow(card->driving_face_cur_shift_x - pDrivingfaceCard->x, 2)
				+ pow(card->driving_face_cur_shift_y - pDrivingfaceCard->y, 2)
				+ pow(card->driving_face_cur_shift_z - pDrivingfaceCard->z, 2)) * card->map_scale;

			cur_total_finish_length = sqrt(pow(card->x - pDrivingfaceCard->x, 2)
				+ pow(card->y - pDrivingfaceCard->y, 2)
				+ pow(card->z - pDrivingfaceCard->z, 2)) * card->map_scale;

			cur_shift_finish_length = sqrt(pow(card->x - card->driving_face_cur_shift_start_x, 2)
			
				+ pow(card->y - card->driving_face_cur_shift_start_y, 2)
				+ pow(card->z - card->driving_face_cur_shift_start_z, 2)) * card->map_scale;

			dis_diff_flag = (cur_total_finish_length - last_total_finsh_length) * card->map_scale;
			if(dis_diff_flag >= 0)
			{
				card->driving_face_cur_shift_x = card->x;
				card->driving_face_cur_shift_y = card->y;
				card->driving_face_cur_shift_z = card->z;
			}
			else
			{
				cur_total_finish_length = last_total_finsh_length;
				cur_shift_finish_length = sqrt(pow(card->driving_face_cur_shift_x - card->driving_face_cur_shift_start_x, 2)
					+ pow(card->driving_face_cur_shift_y - card->driving_face_cur_shift_start_y, 2)
					+ pow(card->driving_face_cur_shift_z - card->driving_face_cur_shift_start_z, 2)) * card->map_scale;
			}
		}

		char buf[LENGTH_SQL] = {0};
		sprintf_s(buf,LENGTH_SQL,"store_driving_face_data[lemon]:card->x:%f,card->y:%f,card->driving_face_cur_shift_start_x:%f,card->driving_face_cur_shift_start_y:%f,card->driving_face_cur_shift_x:%f,card->driving_face_cur_shift_y:%f,last_total_finsh_length:%f,cur_total_finish_length:%f",
			card->x,card->y,card->driving_face_cur_shift_start_x,card->driving_face_cur_shift_start_y,card->driving_face_cur_shift_x,card->driving_face_cur_shift_y,last_total_finsh_length,cur_total_finish_length);
		Log::write_log(FILE_TYPE::SQL_S,buf,true);
		//产生一条当前班次的一条记录，记录了当前班次的开始的距离，以及当前班次的距离，以及当前班次的开始坐标。
		sprintf_s(
		
			sql, 
			LENGTH_SQL,
			"insert IGNORE into his_drivingface_shift_finish_length (drivingface_id, card_id, total_length, shift_id, finish_length, cur_time,start_x,start_y,start_z,end_x,end_y,end_z) values(%d, %s, %.3f, %d, %.3f,'%s',%.3f,%.3f,%.3f,%.3f,%.3f,%.3f);",
			it_card->second->drivingface_id,
			card->card_id.c_str(),
			last_total_finsh_length,
			card->shift_id,
			0.0,
			s.c_str(),
			card->driving_face_cur_shift_start_x,
			card->driving_face_cur_shift_start_y,
			card->driving_face_cur_shift_start_z,
			card->driving_face_cur_shift_start_x,
			card->driving_face_cur_shift_start_y,
			card->driving_face_cur_shift_start_z);
		debug_print_syslog(0, "store driving face data sql: %s", sql);
		execute_sql(sql);
	}
	return;
}

void CYAServerDlg::update_driving_face_data(std::shared_ptr<Card> card)
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_263);
	char sql[LENGTH_SQL] = {'\0'};
	int shift_id = 0;
	bool is_true = false;
	std::string cur_shift_start_time = CFunctions::time_t2string(this->GetCurShiftStartTime(shift_id));
	if(card)
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_264);
		float last_total_finsh_length = 0;
		float cur_total_finish_length = 0;
		float cur_shift_finish_length = 0;
		float dis_diff_flag = 0;
		std::string drivingface_end_time = CFunctions::time_t2string(time(NULL));
		std::shared_ptr<DrivingfaceCard> pDrivingfacecard  = nullptr;
		DrivingfaceCardMap::iterator it_card = mp_driving_face_card_list.find(card->card_id);


		if(it_card == mp_driving_face_card_list.end())
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_265);
    		
			return;
		}
		else
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_266);
			pDrivingfacecard = it_card->second;
    	 
			//  pDrivingfaceRender = it_render->second;
			last_total_finsh_length = sqrt(pow(card->driving_face_cur_shift_x - pDrivingfacecard->x, 2)
				+ pow(card->driving_face_cur_shift_y - pDrivingfacecard->y, 2)
				+ pow(card->driving_face_cur_shift_z - pDrivingfacecard->z, 2)) * card->map_scale;
			//here get the total_finish_length?????--lemon
			cur_total_finish_length = sqrt(pow(card->x - pDrivingfacecard->x, 2)
				+ pow(card->y - pDrivingfacecard->y, 2)
				+ pow(card->z - pDrivingfacecard->z, 2)) * card->map_scale;

			cur_shift_finish_length = sqrt(pow(card->x - card->driving_face_cur_shift_start_x, 2)
				+ pow(card->y - card->driving_face_cur_shift_start_y, 2)
				+ pow(card->z - card->driving_face_cur_shift_start_z, 2)) * card->map_scale;

			dis_diff_flag = (cur_total_finish_length - last_total_finsh_length) * card->map_scale;
			if(dis_diff_flag >= 0)
			{
				is_true = true;
    		
				card->driving_face_cur_shift_x = card->x;
				card->driving_face_cur_shift_y = card->y;
				card->driving_face_cur_shift_z = card->z;
			}
			else
			{
				cur_total_finish_length = last_total_finsh_length;
				cur_shift_finish_length = sqrt(pow(card->driving_face_cur_shift_x - card->driving_face_cur_shift_start_x, 2)
					+ pow(card->driving_face_cur_shift_y - card->driving_face_cur_shift_start_y, 2)
					+ pow(card->driving_face_cur_shift_z - card->driving_face_cur_shift_start_z, 2)) * card->map_scale;
			}
		}
		//这里更新数据。
		card->m_cur_total_finish_length = cur_total_finish_length;
		card->m_curshift_finish_length = cur_shift_finish_length;

		char buf[LENGTH_SQL] = {0};
		sprintf_s(buf,LENGTH_SQL,"update_driving_face_data[lemon]:card->x:%f,card->y:%f,card->driving_face_cur_shift_start_x:%f,card->driving_face_cur_shift_start_y:%f,card->driving_face_cur_shift_x:%f,card->driving_face_cur_shift_y:%f,last_total_finsh_length:%f,cur_total_finish_length:%f",
			card->x,card->y,card->driving_face_cur_shift_start_x,card->driving_face_cur_shift_start_y,card->driving_face_cur_shift_x,card->driving_face_cur_shift_y,last_total_finsh_length,cur_total_finish_length);
		Log::write_log(FILE_TYPE::SQL_S,buf,true);

		sprintf_s(

			sql, 
			LENGTH_SQL,
			"update his_drivingface_shift_finish_length set  finish_length=%.3f,end_x=%.3f,end_y=%.3f,end_z = %.3f \
			where card_id = %s and cur_time = '%s';",
			cur_shift_finish_length,
			card->driving_face_cur_shift_x,
			card->driving_face_cur_shift_y,
			card->driving_face_cur_shift_z,
			card->card_id.c_str(),
			cur_shift_start_time.c_str());
		if (is_true)
		{
			debug_print_syslog(0, "update driving face shift data sql real: %s", sql);
			execute_sql(sql);
			//如果掘进机启动则更新数据。
			if (1 == card->is_driving_face_start)
			{
				cur_shift_finish_length = sqrt(pow(card->driving_face_cur_shift_x - card->m_drivingface_start_x, 2)
					+ pow(card->driving_face_cur_shift_y - card->m_drivingface_start_y, 2)
					+ pow(card->driving_face_cur_shift_z - card->m_drivingface_start_z, 2)) * card->map_scale;
				sprintf_s(
					sql, 
					LENGTH_SQL,
					"UPDATE his_drivingface_his SET end_time = '%s' ,cur_finish_length = %.3f,end_x=%.3f,end_y=%.3f,end_z=%.3f WHERE card_id = %s AND start_time = '%s';",
					drivingface_end_time.c_str(),
					cur_shift_finish_length,
					card->driving_face_cur_shift_x,
					card->driving_face_cur_shift_y,
					card->driving_face_cur_shift_z,
					card->card_id.c_str(),
					card->m_drivingface_start_time.c_str());
				execute_sql(sql);
			}
		}	
	}

	return;
}

void CYAServerDlg::write_his_drivingface_real(std::shared_ptr<Card> card)
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_245);
	char sql[LENGTH_SQL] = {'\0'};
	time_t tCurTime = time(NULL);
	std::string strCurTime = "";
	strCurTime = CFunctions::time_t2string(tCurTime);
	std::shared_ptr<DrivingfaceCard> pDrivingfaceCard = nullptr;
	DrivingfaceCardMap::iterator it = mp_driving_face_card_list.find(card->card_id);		
	if(it == mp_driving_face_card_list.end()){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_246);
		return;
	}
	else
	{
		//mark lemon 2017/08/16
		if (!card->is_drivingface_Initialization)
		{
			card->is_drivingface_Initialization = true;
			card->driving_face_cur_shift_start_x = card->driving_face_cur_shift_x = card->x;
			card->driving_face_cur_shift_start_y = card->driving_face_cur_shift_y = card->y;
			card->driving_face_cur_shift_start_z = card->driving_face_cur_shift_z = card->z;
		}
		//here 

		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_247);
		pDrivingfaceCard = it->second;
		int drivingface_id = pDrivingfaceCard->drivingface_id;
		float  finsh_length = 0;
		float cur_finish_length = 0;
		finsh_length = sqrt(pow(card->x - pDrivingfaceCard->x, 2)
			+ pow(card->y - pDrivingfaceCard->y, 2)
			+ pow(card->z - pDrivingfaceCard->z, 2));
		sprintf_s(sql, LENGTH_SQL, 
			"INSERT IGNORE INTO his_drivingface_real\
			(drivingface_id, card_id, map_id,area_id, state, dat_state_card, dat_state_boject_state, \
			average_speed, speed, x, y, z, cur_time)\
			VALUES(%d, '%s', %d, %d, '%d', '%d', '%d', %.3f, %.3f, %.3f, %.3f, %.3f, '%s');",  drivingface_id,
			card->card_id.c_str(), card->map_id, card->area_id, card->state, 0, 0, card->v, card->v,
			card->x, card->y, card->z, strCurTime.c_str());
		DWORD cur_time = ::GetTickCount();
		if(cur_time - card->drive_face_location_write_time > WRITE_DRIVINGFACE_REAL_PER_TIME) //last time for write database...
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_240);
			execute_sql(sql);
			card->drive_face_location_write_time = cur_time;

			//lemon 2017/08/16
			//lemon 2017/09/21增加非法点过滤功能。根据掘进面区域来进行判断
			update_driving_face_data(card);
		}
	}
	return;
}

//调用存储过程插入his_location_staff内的z为零
void CYAServerDlg::save_card_postion(std::shared_ptr<Card> card /* Card* card*/ )
{
	if (abs(card->x - INVALID_COORDINATE) < 1E-4 && abs(card->y - INVALID_COORDINATE) <1E-4)
	{
		//如果回到错误点
		return;
	}
	// 位置发生变化
	double moved_dist = sqrt(pow(card->x - card->stored_x, 2) + pow(card->y - card->stored_y, 2));

	if( moved_dist * card->map_scale < 1.0/2.0){ // 移动位置小于半米，不记录数据
		return ;
	}

	if (!card->is_first_location){
		card->mileage = moved_dist * card->map_scale/1000;
	}else{
		card->mileage = 0;
		card->is_first_location = false;
	}

	std::stringstream ss;
	//GetLandmarkInfo(card);

	AreaMap::iterator it_area = mp_workingface_area_list.find(card->area_id);
	//if (it_area != mp_workingface_area_list.end())
	if(CT_TUNNELBORING_MACHINE == card->card_type || CT_COALMINING_MACHINE == card->card_type)
	{
		store_data_card(card, HIS_LOCATION);	
	} 
	else
	{
		auto vt = m_carmanage->makeUpMorePoints(card->card_id,card->x,-card->y,card->m_ct_time,card->p_reader->reader_id);
		for(his_location & hl:vt)
		{
			char sql[LENGTH_SQL] = { 0 };
			if (hl.type==0)
			{
				std::string s = CFunctions::timet_to_string_with_ms(hl.start_time);
				debug_print_syslog(0,"[makeUpMorePoints %s]:%s x:%.3f,y:%.3f,v:%.3f,%lld,%d",card->card_id.c_str(),s.c_str(),hl.start_pt.x,hl.start_pt.y,hl.speed,hl.start_time,card->reader_id);
				switch (card->card_type)
				{
				case CT_PERSON:
					sprintf_s(sql, LENGTH_SQL, 
						"INSERT IGNORE INTO his_location_staff(card_id, staff_id, cur_time, x, y, z, critical_point, map_id, area_id, state,speed,mileage, landmark_id, direction_mapper_id, landmark_dist) VALUES(%s, %d, '%s', %.3f, %.3f, %.3f, %d, %d, %d, %d, %.3f, %.4f, %d, %d, %.4f);",  
						card->card_id.c_str(), card->id, s.c_str(), hl.start_pt.x, -hl.start_pt.y, card->z_offset_after(), hl.m_bCriticalPoint, card->map_id, card->area_id, card->state, ceil(fabs(hl.speed)),card->mileage, card->landmark_id, card->landmark_direction, card->landmark_dis);
					break;
				case CT_VEHICLE:
					sprintf_s(sql, LENGTH_SQL, 
						"INSERT IGNORE INTO his_location_vehicle(card_id, vehicle_id, cur_time, x, y, z, critical_point, map_id, area_id, state,speed,mileage, landmark_id, direction_mapper_id, landmark_dist) VALUES(%s, %d, '%s', %.3f, %.3f, %.3f, %d, %d, %d, %d, %.3f, %.4f, %d, %d, %.4f);",  
						card->card_id.c_str(), card->id, s.c_str(), hl.start_pt.x, -hl.start_pt.y,card->z_offset_after(), hl.m_bCriticalPoint, card->map_id, card->area_id, card->state,ceil(fabs(hl.speed)),card->mileage, card->landmark_id, card->landmark_direction, card->landmark_dis);
				}
				//debug_print_syslog(0,"[makeUpMorePoints %s]:%s",card->card_id.c_str(),sql);
			}
			else if(hl.type == 1)
			{
				std::string s = CFunctions::timet_to_string_with_ms(hl.start_time);
				std::string ss = CFunctions::timet_to_string_with_ms(hl.end_time);
				//debug_print_syslog(0,"[makeUpMorePoints %s]:%s x:%.3f,y:%.3f,v:%.3f,%lld--%lld",card->card_id.c_str(),s.c_str(),hl.start_pt.x,hl.start_pt.y,hl.speed,hl.start_time,hl.end_time);

				switch (card->card_type)
				{
				case CT_PERSON:
					sprintf_s(sql, LENGTH_SQL, 
						"CALL PROC_ADD_HIS_LOCATION_STAFF(%s,'%s','%s',%.3f,%.3f,%.3f,%.3f,2,%d,%d,%d,%.3f,%.4f,%d,%d,%.3f,%d);",  
						card->card_id.c_str(), s.c_str(),ss.c_str(), hl.start_pt.x, -hl.start_pt.y, hl.end_pt.x,-hl.end_pt.y, card->map_id, card->area_id, card->state,ceil(fabs(hl.speed)),card->mileage, card->landmark_id, card->landmark_direction, card->landmark_dis,card->id);
					break;
				case CT_VEHICLE:
					sprintf_s(sql, LENGTH_SQL, 
						"CALL PROC_ADD_HIS_LOCATION_VEHICLE(%s,'%s','%s',%.3f,%.3f,%.3f,%.3f,1,%d,%d,%d,%.3f,%.4f,%d,%d,%.3f,%d);",  
						card->card_id.c_str(), s.c_str(),ss.c_str(), hl.start_pt.x, -hl.start_pt.y, hl.end_pt.x,-hl.end_pt.y, card->map_id, card->area_id, card->state,ceil(fabs(hl.speed)),card->mileage, card->landmark_id, card->landmark_direction, card->landmark_dis,card->id);
				}
				//debug_print_syslog(0,"[makeUpMorePoints %s]:%s",card->card_id.c_str(),sql);
			}
			execute_sql(sql);
		}
	}

	card->stored_x = card->x;
	card->stored_y = card->y;
	card->stored_z = card->z;

}

void CYAServerDlg::save_card_postion_ex( std::shared_ptr<Card> card )
{
	if(card->_storepostions.size() < 4)
	{
		return ;
	}

	_point p1, p2, p3, p4;

	p1.x = card->_storepostions.at(0)->x;
	p1.y = card->_storepostions.at(0)->y;
	p2.x = card->_storepostions.at(1)->x;
	p2.y = card->_storepostions.at(1)->y;
	p3.x = card->_storepostions.at(2)->x;
	p3.y = card->_storepostions.at(2)->y;
	p4.x = card->_storepostions.at(3)->x;
	p4.y = card->_storepostions.at(4)->y;

	int diffms = 0;
	int nCount = 0;
	if(IsInLine(p1, p2, p3)){
		diffms = CFunctions::TimeDiffMS(card->_storepostions.at(1)->save_time, card->_storepostions.at(0)->save_time);
		if(diffms < 1000)
		{ // 小于1秒

		}
		else
		{ // 计算需要补录的条数
			nCount = diffms / 700; 
		}

		card->_storepostions.pop_front();
		return ;
	}
}
/*
* 存储红绿灯信息到数据库
*
* param
*		light	---		红绿灯对象
*		tag		---		事件类型
* 
* return
*		函数正常执行返回0，否则返回1
*/
int CYAServerDlg::store_data_light(std::shared_ptr<Light> light,int tag)
{
	char sql[LENGTH_SQL] = {'\0'};
	time_t tCurTime;
	std::string strCurTime = "";
	std::string strStartTime = "";

	tCurTime = time(NULL);
	strCurTime = CFunctions::time_t2string(tCurTime);

	//1为网络故障，2为控制失败，3为灯故障
	int nAlarmTypeId = 0;
	switch (tag)
	{
	case ALARM_LIGHT_NETWORK_START:
	case ALARM_LIGHT_NETWORK_END:
		nAlarmTypeId = 1;
		break;
	case ALARM_LIGHT_CONTROL_FAILE:
		nAlarmTypeId = 2;
		break;
	case ALARM_LIGHT_FAULT_START:
	case ALARM_LIGHT_FAULT_END:
		nAlarmTypeId = 2;
		break;
	}

	switch (tag)
	{
	case ALARM_LIGHT_NETWORK_START://insert
	case ALARM_LIGHT_CONTROL_FAILE:
	case ALARM_LIGHT_FAULT_START:
		sprintf_s(
			sql,
			LENGTH_SQL,
			"insert IGNORE into his_alarm_light(light_id,alarm_type_id,start_time) values(%d,%d,'%s');",
			light->m_nID,
			nAlarmTypeId,
			strCurTime.c_str());
		break;
	case ALARM_LIGHT_NETWORK_END://update
	case ALARM_LIGHT_FAULT_END:
		strStartTime = CFunctions::time_t2string(light->alarm_start_time);
		sprintf_s(
			sql,
			LENGTH_SQL,
			"UPDATE his_alarm_light SET end_time = '%s' WHERE light_id=%d AND alarm_type_id=%d AND start_time = '%s';",
			strCurTime.c_str(),
			light->m_nID,
			nAlarmTypeId,
			strStartTime.c_str());
		break;
	}

	execute_sql(sql);

	return 0;
}

int CYAServerDlg::store_data_traffic_red_light(std::shared_ptr<Light> light,std::shared_ptr<Card> card)
{
	char sql[LENGTH_SQL] = {'\0'};
	time_t tCurTime;

	tCurTime = time(NULL);

	std::string s = CFunctions::time_t2string(tCurTime);

	sprintf_s(
		sql, 
		LENGTH_SQL,
		"insert IGNORE into his_traffic_red_light (vehicle_id,cur_time,light_id,driver_id) values('%s','%s',%d,'%s');",
		card->card_id.c_str(),
		s.c_str(),
		light->m_nID,
		card->driver_id.c_str());

	execute_sql(sql);

	return 0;
}

/*
* 存储路段信息
*
*/
int CYAServerDlg::store_data_section(std::shared_ptr<Section> section,time_t cur_time,int tag)
{
	//INT64 ev_id = section->m_event_list[ET_SECTION_OVER_COUNT];

	//if(ev_id == 0) // 没有告警
	//{
	//	if(ALARM_SECTION_START == tag){ // 创建新的事件	
	//		ev_id = CFunctions::GetMicroSecond();
	//		std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
	//		ev->status = ES_START;	
	//		ev->ev_type = ET_SECTION_OVER_COUNT;
	//		ev->obj_type = OT_SECTION;
	//		ev->cur_time = time(NULL);
	//		ev->map_id = section->m_nMapId;

	//		ev->is_sent = false;
	//		m_event_list[ET_SECTION_OVER_COUNT] = ev_id;
	//		store_data_event(ev);
	//		add_event(ev);
	//		Sleep(1);
	//	}
	//}
	//else // 已存在告警
	//{
	//	EventMap::iterator it_ev = mp_event_list->find(ev_id);
	//	if(it_ev != mp_event_list->end()){
	//		if(ALARM_SECTION_START == tag){ // 更新事件	
	//			it_ev->second->cur_value = section->mp_vehicle_list.size();
	//			it_ev->second->is_sent = false;
	//		}
	//		else if(ALARM_SECTION_END == tag){
	//			it_ev->second->cur_value = section->mp_vehicle_list.size();
	//			it_ev->second->status = ES_END;
	//			it_ev->second->cur_time = time(NULL);
	//			it_ev->second->is_sent = false;
	//			store_data_event(it_ev->second);
	//			add_event(it_ev->second);

	//			section->m_event_list[ET_SECTION_OVER_COUNT] = 0;
	//		}
	//	}
	//}

	return 0;
}

void CYAServerDlg::execute_sql( const char* sql )
{
	//#ifdef DEBUG
	//	return;
	//#endif // _debug
	//Log::write_log(FILE_TYPE::SQL_S, sql, true);
	//debug_print_syslog(0,sql);
	//m_qsmSQL->AddString(sql);
	std::string error = "";
	if(sDBConnPool.ExecuteSql(sql,error )<0){
		debug_print_syslog(0,"[execute_sql : exec failed sql] %s",sql);
	}
}

/*
* 日志菜单设置
*		将日志菜单设置内容同步更新到主对话框中的相应变量
*
* param
*		无
*
* return
*		无
*/
void CYAServerDlg::OnMenuLog()
{
	CLogSetting dlg;
	dlg.DoModal();

	//m_log_sys_status = theApp.m_log_sys_status;
	m_log_raw_data   = theApp.log_raw_data;
	m_log_parse_data = theApp.log_parse_data;
	m_log_recv_package = theApp.log_recv_package;
	m_log_send_package = theApp.log_send_package;
	m_log_locate_data  = theApp.log_locate_data;
}

void CYAServerDlg::OnMenuParam()
{
	CSysSetting dlg;
	dlg.DoModal();
}

void CYAServerDlg::OnLogin(string const& name, message::ptr const& data, bool isAck, message::list &ack_resp)
{
	int res_code = (int)data->get_map()["code"]->get_int();
	switch (res_code)
	{
	case -100: // 用户未登录
		{
			//ws_login();
			is_websocket_login = false;
			break;
		}
	case 0:
		{
			if("" == data->get_map()["code"]->get_string()){ // 登录成功
				is_websocket_login = true;
			}else{ // 退出登录
				is_websocket_login = false;
			}
			break;
		}
	default:
		break;
	}
}

/*

* 发送呼叫信息
*
* 参数
*		无
*
* 返回值
*		无
*/
void CYAServerDlg::send_call_info()
{
	EnterCriticalSection(&m_csCallInfo);

	CallInfoUserMap::iterator it_call_user = mp_user_call_info.begin();
	if(it_call_user == mp_user_call_info.end()){
		LeaveCriticalSection(&m_csCallInfo);
		return;
	}

	BYTE buf[LENGTH_SEND_BUF] = {0};
	for(it_call_user = mp_user_call_info.begin(); it_call_user != mp_user_call_info.end(); ++it_call_user)
	{
		CallInfoReaderMap::iterator it_call_reader = it_call_user->second->mpReader.begin();
		if(it_call_reader == it_call_user->second->mpReader.end())
		{
			continue;
		}
		if(!it_call_reader->second->is_start_call){
			continue;
		}

		for(; it_call_reader != it_call_user->second->mpReader.end(); ++it_call_reader){
			//初始化
			memset(buf, 0, LENGTH_SEND_BUF);
			int npos = 0, card_count = 0;
			//分站地址 4字节，支持大小分站呼叫协议；added by zhuyf 2018/06/04
			//大小分站的全员呼叫，分站id要求4字节全为FF
			DWORD anchor_id = 0;
			if (it_call_reader->second->is_call_all)
			{
				anchor_id = 0xffffffff;
			}
			else{
				anchor_id = it_call_reader->first;	
			}
			//memcpy(&buf[npos], &anchor_id, 4);
			CFunctions::memcpyDWord(&buf[npos],anchor_id,npos);
			npos += 4*sizeof(BYTE);

			//卡数
			card_count = 0;// it_call_reader->second->mpCard.size(); // it_call_reader->second->cards_count;
			memcpy(&buf[npos], &card_count, sizeof(BYTE));
			npos += sizeof(BYTE);
			//呼叫类型
			memcpy(&buf[npos], &it_call_reader->second->call_level, sizeof(BYTE));
			npos += sizeof(BYTE);

			if(!it_call_reader->second->is_call_all){
				//循环添加卡信息
				CallInfoCardMap::iterator it_call_card = it_call_reader->second->mpCard.begin();
				for(; it_call_card != it_call_reader->second->mpCard.end(); it_call_card++){
					card_count++;
					//呼叫类型
					memcpy(&buf[npos], &it_call_card->second->call_level, sizeof(BYTE));
					npos += sizeof(BYTE);
					//卡类型
					memcpy(&buf[npos], &it_call_card->second->card_type, sizeof(BYTE));
					npos += sizeof(BYTE);
					//卡ID长度
					BYTE id_len = (BYTE)get_card_id_len(it_call_card->second->card_type);
					memcpy(&buf[npos], &id_len, sizeof(BYTE));
					npos += sizeof(BYTE);
					//卡ID
					if(id_len > 1){ // 标准卡id为4个字节，自组网卡为1个字节
						CFunctions::memcpyDWord(buf,(DWORD)it_call_card->second->card_id, npos);
					}else{
						memcpy(&buf[npos], &it_call_card->second->card_id, id_len);
					}
					npos += id_len;
				}
				memcpy(&buf[4], &card_count, sizeof(BYTE));
			}

			for(SocketMap::iterator it_sock= mp_socket_list.begin();it_sock!=mp_socket_list.end();++it_sock){
				//如果分站id为零，表示全员呼叫
				if(0 == it_call_reader->first){
					if(it_sock != mp_socket_list.end())
					{
						//SendData(it_sock->second->dwConnID,CHAR_CALL, npos, buf);
						SendData(it_sock->second->dwConnID,CHAR_CALL_EXTEND, npos, buf);
					}
				}else{
					bool b = it_sock->second->findReader(it_call_reader->first);
					if (b)
					{
						const auto r = it_sock->second->get(it_call_reader->first);
						if (r.reader_type == DEVICE_TYPE::DT_CARD_READER)
						{
							SendData(it_sock->second->dwConnID,CHAR_CALL_EXTEND, npos, buf);
							break;
						}
					}
				}
			}
		}
	}
	LeaveCriticalSection(&m_csCallInfo);
}

void CYAServerDlg::clear_call_info()
{
	EnterCriticalSection(&m_csCallInfo);
	CallInfoUserMap::iterator it_call_user = mp_user_call_info.begin();

	for(; it_call_user != mp_user_call_info.end();)
	{
		time_t current_time = time(NULL);
		CallInfoReaderMap::iterator it_call_reader = it_call_user->second->mpReader.begin();
		for( ;it_call_reader != it_call_user->second->mpReader.end();)
		{
			if(it_call_reader->second->is_call_all)
			{
				if(difftime(current_time, it_call_reader->second->start_time) > it_call_reader->second->time_out * 60)
				{
					it_call_reader = it_call_user->second->mpReader.erase(it_call_reader);
				}
				else
				{
					++it_call_reader;
				}
			}
			else
			{
				CallInfoCardMap::iterator it_call_card = it_call_reader->second->mpCard.begin();
				for(; it_call_card != it_call_reader->second->mpCard.end();)
				{
					if(difftime(current_time, it_call_card->second->start_time) > it_call_card->second->time_out * 60)
					{
						it_call_card = it_call_reader->second->mpCard.erase(it_call_card);
						it_call_reader->second->is_start_call = false;
					}
					else
					{
						++it_call_card;
					}
				}

				if(0 == it_call_reader->second->mpCard.size())
				{
					it_call_reader = it_call_user->second->mpReader.erase(it_call_reader);
				}
				else
				{
					++it_call_reader;
				}	
			}
		}

		if(0 == it_call_user->second->mpReader.size())
		{
			it_call_user = mp_user_call_info.erase(it_call_user);
		}
		else
		{
			++it_call_user;
		}
	}
	LeaveCriticalSection(&m_csCallInfo);
}

int CYAServerDlg::get_card_id_len( int card_type )
{
	switch (card_type)
	{
		//case CT_PERSON:
		//	return 4;
		//case CT_VEHICLE:
		//	return 4;
	case CT_ADHOC:
		return 1;
	default:
		return 4;
		//break;
	}
}

/*
* 检查卡的接收时间和当前时间的间隔，大于5s未收到则重置车卡的速度为0
* 
*
*/
int CYAServerDlg::modify_card_speed(int val)
{
	for (CardMap::iterator it = mp_card_list_all.begin();it != mp_card_list_all.end();++it)
	{
		if (it->second->acce_cur_state == ACCELERATE_STATE::STATE_ACCE_STATIC)
		{
			continue;
		}

		int interval = 0;
		time_t t = time(NULL);
		interval = (int)difftime(t, it->second->last_correct_position_info_time);

		//判断一下当前时间与卡的上一次接收时间的间隔时间是否小于阈值
		//如果小于阈值，则重置状态
		//如果大于阈值，则继续循环，不发送卡信息
		if (interval < val)
		{
			it->second->is_over_interval = false;
		}else{
			if (it->second->is_over_interval)
			{
				continue;
			}else{
				it->second->is_over_interval = true;
			}
		}	

		if (interval > val || it->second->count_idle >= 5 || it->second->acce_cur_state == STATE_ACCE_IDLING)//interval > val || 
		{
			it->second->final_v = 0.0;
			it->second->isdealed = true;	
			it->second->issent = false;
			it->second->isoutput = true;
			it->second->acce_cur_state = ACCELERATE_STATE::STATE_ACCE_STATIC;
		}
	}

	return 0;
}

/*

* 按分站发送所有卡的惯导校准数据
*
* param
*		无
*
* return
*		成功返回0，否则返回1
*/
int CYAServerDlg::send_ins_data()
{
	if (mp_ins_cal_data_list == nullptr)
	{
		return 1;
	}

	if (mp_ins_cal_data_list->size() < 1)
	{
		return 1;
	}

	int nTotals = 0;
	BYTE SendBuffer[MSG_LENGTH_MAX] = {0};

	for (CalDataMap::iterator it = mp_ins_cal_data_list->begin();it != mp_ins_cal_data_list->end();)
	{
		int nReaderId = 0;
		nReaderId = it->first;
		int len = 0;
		float fx = 0.0, fy = 0.0;
		for (CardCalData::iterator it_card = it->second->begin();it_card != it->second->end();)
		{
			if (it_card->second->status == -1)
			{
				continue;
			}
			nTotals++;
			//构造下发校准数据的消息
			len = 1;
			//卡类型
			memcpy(&SendBuffer[len], &it_card->second->card_type, sizeof(BYTE));
			len += sizeof(BYTE);
			//卡id长度
			BYTE id_len = (BYTE)get_card_id_len(it_card->second->card_type);
			memcpy(&SendBuffer[len], &id_len, sizeof(BYTE));
			len += sizeof(BYTE);
			//卡id
			if(id_len > 1){ 
				std::string str_card_id = "";
				str_card_id = it_card->second->card_id;
				string new_card_id = "";
				if (str_card_id!= "")
				{
					new_card_id = str_card_id.substr(3, it_card->second->card_id.length());
				}else{
					//continue;
				}
				int card_id = atoi(new_card_id.c_str());
				CFunctions::memcpyDWord(&SendBuffer[0],(DWORD)card_id, len);
			}else{
				memcpy(&SendBuffer[len], &it_card->second->card_id, id_len);
			}
			len += id_len;
			//校准类型
			BYTE bType = it_card->second->status;
			memcpy(&SendBuffer[len], &bType, sizeof(BYTE));
			len += sizeof(BYTE);
			switch (bType)
			{
			case CAL_DATA_ALL:
				//校准x坐标
				CFunctions::memcpyFloat(&SendBuffer[len],it_card->second->x);
				len += sizeof(float);
				//校准y坐标
				CFunctions::memcpyFloat(&SendBuffer[len],it_card->second->y);
				len += sizeof(float);
				//校准角度
				CFunctions::memcpyFloat(&SendBuffer[len],it_card->second->angle);
				len += sizeof(float);
				break;
			case CAL_DATA_POS:
				//校准x坐标
				CFunctions::memcpyFloat(&SendBuffer[len],it_card->second->x);
				len += sizeof(float);
				//校准y坐标
				CFunctions::memcpyFloat(&SendBuffer[len],it_card->second->y);
				len += sizeof(float);

				fx = it_card->second->x;
				fy = it_card->second->y;
				break;
			case CAL_DATA_ANGLE:
				//校准角度
				CFunctions::memcpyFloat(&SendBuffer[len],it_card->second->angle);
				len += sizeof(float);
				break;
			}
			it->second->erase(it_card);
			it_card = it->second->begin();
		}

		if (it->second->size() == 0)
		{
			mp_ins_cal_data_list->erase(it);
			it = mp_ins_cal_data_list->begin();
		}

		//找到此卡的最近接收分站，
		SocketMap::iterator it_sock = mp_socket_list.end();
		for (it_sock = mp_socket_list.begin();it_sock != mp_socket_list.end();++it_sock)
		{
			if (it_sock->second->findReader(nReaderId))
			{
				break;
			}
		}

		//如果找到连接socket，则下发消息；如果未找到，则不发数据
		if (it_sock != mp_socket_list.end())
		{
			SendBuffer[0] = nTotals;
			BOOL bRet = SendData(it_sock->second->dwConnID, SEND_CHECK_INS_DATA, len, SendBuffer);
			if (bRet)
			{
				TRACE(_T("send position: x = %f, y = %f \r\n"),fx,fy);
				char log[100] = {0};
				sprintf_s(log,"send tof locate pos: x: %.3f, y: %.3f",fx,fy);
				std::string strLog = log;
				Log::write_log(FILE_TYPE::SYS_S,strLog,true);
			}
		}
	}

	return 0;
}

/*
 * 向掘进面的大分站下发指令，请求大分站下的小分站进行模拟卡切换
 *
 * 参数
 *		无
 *
 * 返回值
 *		0表示执行成功；
 *
*/
int CYAServerDlg::send_change_reader_to_card()
{
	for (auto it : vt_drivingface_reader_topology)
	{
		for (decltype(it.m_big_reader_id) i = 0;i<it.m_counts;++i)
		{
			if (it.m_small_reader_id[i] > 0)
			{
				//以下情况都不执行向小分站下发模拟指令：
				//a.小分站id不存在
				//b.小分站在关机逻辑内置模拟状态位true；
				//c.小分站在模拟10分钟后再次更新
				auto it_simulate_reader = mp_reader_list.find(it.m_small_reader_id[i]);
				if (it_simulate_reader==mp_reader_list.end())
				{
					continue;
				}

				//如果此分站不可模拟成车卡，不执行后续处理逻辑
				if(!it_simulate_reader->second->is_simulation_card)
				{
					continue;
				}

				if (!it_simulate_reader->second->b_simulation_status)
				{
					continue;
				}

				time_t cur_time = time(NULL);
				if (cur_time - it_simulate_reader->second->m_start_simulation_time < 10*60)
				{
					continue;
				}

				it_simulate_reader->second->m_start_simulation_time = cur_time;
				//中继分站模拟卡的时间为60秒
				//定位掘进机卡的模拟卡的时间为180秒
				size_t duration = 0;
				switch(i){
				case 0:
					duration = 180;
					break;
				case 1:
					duration = 60;
					break;
				}
				BYTE buf[LENGTH_SEND_BUF] = {0};
				for (auto it_sock: mp_socket_list)
				{
					int pos = 0;
					if (it_sock.second->findReader(it.m_big_reader_id))
					{
						memset(buf,0,LENGTH_SEND_BUF*sizeof(BYTE));
						//分站号
						CFunctions::memcpyDWord(buf,it.m_big_reader_id,pos);
						pos+=sizeof(DWORD);
						//卡类型
						buf[pos++] = CT_SIMULATE_CARD;
						//卡号
						CFunctions::memcpyDWord(buf,it.m_small_reader_id[i] + SIMULATOR_CARD_START_NO,pos);
						pos+=sizeof(DWORD);
						//模拟时间
						CFunctions::memcpyWord(buf,duration,pos);
						pos+=sizeof(WORD);
						BOOL bRet = SendData(it_sock.second->dwConnID,SEND_READER_TO_CARD,pos,buf);
						debug_print_syslog(0,"[three rates: send simulator successed] card_type: %d, card_no: %d, time: %d.",CT_SIMULATE_CARD,it.m_small_reader_id[i] + SIMULATOR_CARD_START_NO,duration);
					}
				}
			}
		}
	}
	return 0;
}

void CYAServerDlg::set_reader_simulate_status(const int& reader_id,bool status)
{
	auto it_reader = mp_reader_list.find(reader_id);
	if(it_reader != mp_reader_list.end()){
		it_reader->second->b_simulation_status = status;
		/*debug_print_syslog(0,"[reader simulator card: turn on simulate card when drivingface machine turn off] reader_id: %d, simulate_status: %d.",
		it_reader->second->reader_id,
		it_reader->second->b_simulation_status);*/
	}
}

/*
 * 如果当前时间和掘进机卡的接收时间超过指定阈值，允许分站模拟卡开始模拟卡的工作
 *
 * param
 *		无
 *
 * return
 *		无
 *
*/
void CYAServerDlg::check_reader_simulate_status()
{
	for (auto it_drivingface_card : mp_driving_face_card_list)
	{
		time_t cur_time = time(NULL);
		//此分站必须是定位掘进机卡的小分站
		auto it_card = mp_card_list_all.find(it_drivingface_card.second->card_id);
		if(it_card==mp_card_list_all.end()){
			continue;
		}
		//如果当前时间与掘进机卡的接收时间超过指定阈值
		if (cur_time - it_card->second->rec_time > 300)	//5分钟
		{
			for (auto it_drivingface_card : mp_driving_face_card_list)
			{
				if (it_drivingface_card.second->m_relay_small_reader_id > 0)
				{
					set_reader_simulate_status(it_drivingface_card.second->m_relay_small_reader_id,true);
				}
				if (it_drivingface_card.second->m_small_reader_id > 0)
				{
					set_reader_simulate_status(it_drivingface_card.second->m_small_reader_id,true);
				}
			}
		}
	}
}

void CYAServerDlg::send_light_auto_control_param(const uint32_t& id,const uint16_t& value,const std::string& ip)
{
	auto it_sock = mp_socket_list.end();
	it_sock = mp_socket_list.find(CFunctions::c2wc(ip.c_str()));
	if (it_sock == mp_socket_list.end())
	{
		return;
	}

	BYTE buffer[LENGTH_SEND_BUF] = {0};
	uint32_t pos = 0;

	//ip
	DWORD dwIp = ntohl(inet_addr(ip.c_str()));
	CFunctions::memcpyDWord(&buffer[0],dwIp,pos);
	pos += sizeof(DWORD);

	//port
	WORD port = 6000;
	CFunctions::memcpyWord(&buffer[0],port,pos);
	pos += sizeof(WORD);

	//红绿灯号
	CFunctions::memcpyDWord(&buffer[0],id,pos);
	pos += sizeof(DWORD);

	//红绿灯类型
	BYTE deviceType = (BYTE)DEVICE_TYPE::DT_LIGHT;
	memcpy(&buffer[pos],&deviceType,sizeof(BYTE));
	pos += sizeof(BYTE);

	//控制命令
	BYTE ctrl_cmd = 0x07;
	memcpy(&buffer[pos],&ctrl_cmd,sizeof(BYTE));
	pos += sizeof(BYTE);

	//控制参数
	memcpy(&buffer[pos],&value,sizeof(WORD));
	pos += sizeof(WORD);

	BOOL ret = SendData(it_sock->second->dwConnID,SET_READERINFO,pos,buffer);
	if (ret)
	{
		char log[100] = {0};
		sprintf_s(log,"[traffic light] light_id: %d, interval: %d.",id,value);
		Log::write_log(FILE_TYPE::MOVING_READER_PARSE_DATA,log,true);
	}
}

void CYAServerDlg::deal_light_auto_control_param(const uint32_t& id,CONNID dwConnID)
{
	//debug_print_syslog(0,"enter deal_light_auto_control_param: %s %d",__FILE__,__LINE__);
	std::string ip = "";
	ip = get_ip_by_id(dwConnID);

	int group_id = m_carmanage->getTrafficGroupId(id);
	if (-1 == group_id)
	{
		char log[100] = {0};
		sprintf_s(log,"[traffic light] it can't get group id by light id %d",id);
		Log::write_log(FILE_TYPE::MOVING_READER_PARSE_DATA,log,true);
		return;
	}
	WORD value = (*m_carmanage)[group_id]->m_auto_control_interval;

	send_light_auto_control_param(id,value,ip);
	//debug_print_syslog(0,"end deal_light_auto_control_param: %s %d",__FILE__,__LINE__);
}

/*

* 处理分站模拟车卡，当满足一定条件时，利用处理后的坐标更新分站坐标
*/
void CYAServerDlg::deal_simulate_card(std::shared_ptr<Card> pCard)
{
	//卡不是分站模拟卡，不处理
	if (CT_SIMULATE_CARD != pCard->card_type)
	{
		return;
	}
	//分站不存在不处理
	int reader_id = atoi(pCard->card_id.substr(3).c_str()) - SIMULATOR_CARD_START_NO;
	if (reader_id <0)
	{
		return;
	}
	auto it_reader = mp_reader_list.find(reader_id);
	if (it_reader == mp_reader_list.end())
	{
		return;
	}

	//删除历史坐标中时间小于当前时间1分钟内的坐标数据
	/*if (it_reader->second->m_vt_his_position.size()>0)
	{
	it_reader->second->m_vt_his_position.erase(std::remove_if(it_reader->second->m_vt_his_position.begin(),it_reader->second->m_vt_his_position.end(),[](TimePosition tp){
	time_t cur_time = time(NULL);

	return (cur_time - tp.cur_time)>60;
	}),std::end(it_reader->second->m_vt_his_position));
	}*/
	//将坐标放入队列
	TimePosition tp(pCard->x,pCard->y);
	it_reader->second->m_vt_his_position.push_back(tp);
#ifdef DEBUG
	TRACE(_T("get position: x: %.3f, y: %.3f.\n"),tp.p.x,tp.p.y);
#endif
	//TRACE(_T("size: %d.\n"),it_reader->second->m_vt_his_position.size());
	//满足指定个数，开始求平均处理
	if (it_reader->second->m_vt_his_position.size()>=10)
	{
		op::point p;
		for (size_t i=0;i<10;++i)
		{
			p.x += it_reader->second->m_vt_his_position[i].p.x;
			p.y += it_reader->second->m_vt_his_position[i].p.y;
		}
		p.x /=10;
		p.y /=10;
#ifdef DEBUG
		TRACE(_T("avg position: x: %.3f, y: %.3f.\n"),p.x,p.y);
#endif
		it_reader->second->m_vt_his_position.erase(it_reader->second->m_vt_his_position.begin(),it_reader->second->m_vt_his_position.end());
		it_reader->second->m_vt_his_position.resize(0);
		if (!p.empty())
		{
			//sql update reader
			char sql[LENGTH_SQL];
			memset(sql,0,LENGTH_SQL*sizeof(char));
			sprintf_s(sql,"CALL update_reader(%.3f, %.3f,%.3f,%d);",p.x,p.y,0.0,reader_id);
			debug_print_syslog(0,"[reader simulator card: update reader position] reader_id: %d, x: %.3f, y: %.3f.",reader_id,p.x,p.y);
			//execute_sql(sql);
			std::string error = "";
			if (sDBConnPool.ExecuteSql(sql,error) < 0)
			{
				debug_print_syslog(0,"[reader simulator card: update reader position when exec sql error] error: ",error.c_str());
			}

			//如果此分站是中继小分站成功更新了坐标，则终止更新坐标，
			//it_reader->second->b_simulation_status = false;
			//如果中继小分站坐标成功更新了，则对与掘进机测距的小分站允许下发切换小分站指令
			for (auto it_drivingface_card : mp_driving_face_card_list)
			{
				if (it_drivingface_card.second->m_relay_small_reader_id == reader_id)
				{
					auto it_small_reader = mp_reader_list.find(it_drivingface_card.second->m_small_reader_id);
					if (it_small_reader != mp_reader_list.end())
					{
						it_small_reader->second->b_simulation_status = true;
						auto it_relay_reader = mp_reader_list.find(it_drivingface_card.second->m_relay_small_reader_id);
						if(it_relay_reader == mp_reader_list.end()){
							it_relay_reader->second->b_simulation_status = false;
						}
					}
				}
			}
		}
	}
}

/*
* 如果卡是掘进机，且其接收分站为小分站，则切换算法；
*/
bool CYAServerDlg::need_drivingface_algo(std::shared_ptr<Card> pCard)
{
	//此卡的接收分站属于掘进面的小分站数据
	for (auto it : mp_driving_face_card_list)
	{
		//如果是小分站和中继小分站，则使用掘进面的定位方式
		if (pCard->reader_id == it.second->m_small_reader_id || pCard->reader_id == it.second->m_relay_small_reader_id)
		{
			return true;
		}
	}

	//如果是小分站模拟的卡数据，只有单天线数据，允许走特殊算法处理逻辑
	uint32_t reader_id = atoi(pCard->card_id.substr(3).c_str());
	if (reader_id < SIMULATOR_CARD_START_NO)
	{
		return false;
	}
	
	reader_id -= SIMULATOR_CARD_START_NO;

	auto it_reader = mp_reader_list.find(reader_id);
	if (it_reader!=mp_reader_list.end())
	{
		if (it_reader->second->b_simulation_status)
		{
			debug_print_syslog(0,"[simulator card by reader] card_id: %s, reader_id: %d",pCard->card_id.c_str(),reader_id);
			return true;
		}
	}

	return false;
}

/*
 * 处理每分钟的排距信息
 * 
 * param
 *		pCard		卡数据
 *		p			1分钟内定位点的平均坐标
 *
 * return
 *		无
*/
void CYAServerDlg::deal_drivingface_regular_cycle(std::shared_ptr<Card> pCard,const op::point& p)
{
	//debug_print_syslog(0,"[regular_cycle : calc row spacing] card_id: %s,x: %.3f,y: %.3f",pCard->card_id.c_str(),p.x,p.y);
	auto it_drivingface_card = mp_driving_face_card_list.find(pCard->cardId());
	//判断此卡是否为掘进机卡
	if (it_drivingface_card != mp_driving_face_card_list.end())
	{
		save_drivingface_regular_cycle_data(pCard,it_drivingface_card->second,p);
	}
}
	
/*
* 当数据条数不够时，切超时2分钟，将缓存数据写入数据库
*/
void CYAServerDlg::deal_drivingface_regular_cycle()
{
	for (auto it_card : mp_card_list_all)
	{
		auto it_drivingface_card = mp_driving_face_card_list.find(it_card.second->cardId());
		if (it_drivingface_card == mp_driving_face_card_list.end())
		{
			continue;
		}
		if (CT_TUNNELBORING_MACHINE == it_card.second->card_type && it_card.second->m_cb_position.size() > 0)
		{
			time_t cur_time = time(NULL);
			size_t len = it_card.second->m_cb_position.size();
			std::string day_end_time = "";
			day_end_time = CFunctions::time_t2string(cur_time);
			day_end_time = day_end_time.substr(11);
			if (cur_time - it_card.second->m_cb_position[len-1].cur_time > 120 || day_end_time=="23:59:59")
			{
				size_t len = it_card.second->m_cb_position.size();
				op::point p;
				for (size_t i = 0; i < len;++i)
				{
					p.x += it_card.second->m_cb_position[i].p.x;
					p.y += it_card.second->m_cb_position[i].p.y;
				}
				p.x/=len;
				p.y/=len;

				if (day_end_time=="23:59:59")
				{
					//debug_print_syslog(0,"[regular_cycle : stop by the day] card_id: %s,x: %.3f ,y: %.3f.",it_card.second->card_id.c_str(),p.x,p.y);
				} 
				else
				{
					//debug_print_syslog(0,"[regular_cycle : time out] card_id: %s,x: %.3f ,y: %.3f.",it_card.second->card_id.c_str(),p.x,p.y);
				}
				
				save_drivingface_regular_cycle_data(it_card.second,it_drivingface_card->second,p);
			}
		}
	}	
}

void CYAServerDlg::deal_drivingface_services(std::shared_ptr<Card> pCard)
{
	//debug_print_syslog(0,"[deal_drivingface_services] : card_id: %s",pCard->card_id.c_str());
	init_drivingface_recently_info(pCard);

	op::point p(pCard->x,pCard->y);
	time_t cur_time = time(NULL);
	TimePosition tp;
	tp.cur_time = cur_time;
	tp.p.x = p.x;
	tp.p.y = p.y;
	pCard->m_cb_position.push_back(tp);
	if (cur_time - pCard->m_cb_position[0].cur_time >= 60)
	{
		size_t len = pCard->m_cb_position.size();
		op::point lp;
		for (size_t i = 0; i < len;++i)
		{
			lp.x += pCard->m_cb_position[i].p.x;
			lp.y += pCard->m_cb_position[i].p.y;
		}
		lp.x/=len;
		lp.y/=len;

		//正规循环率-his_regular_cycle，放排数信息
		deal_drivingface_regular_cycle(pCard,lp);		
	}
	//放距离基准点的距离信息
	deal_drivingface_real_distance(pCard);
}

/*
 * 正常收到定位数据时，保存队列内点的距离以及其的平均距离
 * 
 * param
 *		pCard		卡数据
 *
 * return
 *		无
 *
*/
void CYAServerDlg::deal_drivingface_real_distance(std::shared_ptr<Card> pCard)
{
	auto it_drivingface_card = mp_driving_face_card_list.find(pCard->cardId());
	if (it_drivingface_card!=mp_driving_face_card_list.end())
	{
		char d_sql_log[100];
		memset(d_sql_log,0,100*sizeof(char));

		double cur_distance = 0.0;
		op::point p(pCard->x,pCard->y);

		if (it_drivingface_card->second->m_vt_ref_point_list.size() > 1 && it_drivingface_card->second->m_total_ref_point_dist < ZERO_PRECISION)
		{
			double d = 0.0;
			op::point tp(it_drivingface_card->second->m_vt_ref_point_list[0]);
			for (size_t i = 1;i<it_drivingface_card->second->m_vt_ref_point_list.size();i++)
			{
				op::point ttp(it_drivingface_card->second->m_vt_ref_point_list[i]);
				d+=tp.dist(ttp)*pCard->map_scale;
			}
			it_drivingface_card->second->m_total_ref_point_dist = d;
			debug_print_syslog(0,"[deal_drivingface_real_distance] drivingface_id: %d, trpd: %.4f",it_drivingface_card->second->drivingface_id,it_drivingface_card->second->m_total_ref_point_dist);
		}

		int idx = it_drivingface_card->second->m_vt_ref_point_list.size()-1;
		if (idx < 0)
		{
			debug_print_syslog(0,"[deal_drivingface_real_distance] drivingface_id: %d no ref point info.",it_drivingface_card->second->drivingface_id);
		}
		op::point base_point;
		base_point.set(it_drivingface_card->second->m_vt_ref_point_list[idx]);
		cur_distance = it_drivingface_card->second->m_total_ref_point_dist + p.dist(base_point)*pCard->map_scale + it_drivingface_card->second->m_fOffset;
	
		debug_print_syslog(0,"[deal_drivingface_real_distance] card_id: %s, cur_distance: %.3f, offset: %.3f, x: %.3f, y: %.3f, drivingface_id: %d, ref_totals: %d, ref_idx: %d, ref_x: %.3f, ref_y: %.3f",
			pCard->card_id.c_str(),cur_distance,it_drivingface_card->second->m_fOffset,
			pCard->x,pCard->y,
			it_drivingface_card->second->drivingface_id,it_drivingface_card->second->m_vt_ref_point_list.size(),
			idx,it_drivingface_card->second->m_vt_ref_point_list[idx].x,it_drivingface_card->second->m_vt_ref_point_list[idx].y
			);

		//开始记录数据
		time_t cur_time = time(NULL);
		if (pCard->m_b_first_record)
		{
			pCard->m_b_first_record = false;
			pCard->m_str_record = "";
			pCard->m_record_cycle_start_time = cur_time;
			pCard->m_record_avg_dist += cur_distance;
			pCard->m_record_max_dist = pCard->m_record_min_dist = cur_distance;
			pCard->m_record_totals++;

			sprintf_s(d_sql_log,"%s,%.4f;",CFunctions::time_t2string(cur_time).c_str(),cur_distance);
			pCard->m_str_record = d_sql_log;		

			//debug_print_syslog(0,"[calc distance between base point: first record] card_id: %s, total_distance: %.3f, max_distance: %.3f, min_distance: %.3f",pCard->card_id.c_str(),cur_distance, pCard->m_record_max_dist, pCard->m_record_min_dist);
		}else{
			sprintf_s(d_sql_log,"%s,%.4f;",CFunctions::time_t2string(cur_time).c_str(),cur_distance);
			std::string r = d_sql_log;
			pCard->m_str_record += r;
			pCard->m_record_avg_dist += cur_distance;
			pCard->m_record_max_dist = max(pCard->m_record_max_dist,cur_distance);
			pCard->m_record_min_dist = min(pCard->m_record_min_dist,cur_distance);
			pCard->m_record_totals++;
			//debug_print_syslog(0,"[calc distance between base point: normal record] card_id: %s,cur_time: %lld, record_time: %lld, total_distance: %.3f, max_distance: %.3f, min_distance: %.3f",pCard->card_id.c_str(),cur_time,pCard->m_record_cycle_start_time, pCard->m_record_avg_dist, pCard->m_record_max_dist, pCard->m_record_min_dist);
			//如果有一分钟的数据，则保存结果
			if (cur_time - pCard->m_record_cycle_start_time >= 60)
			{
				if (pCard->m_record_totals>0)
				{
					pCard->m_record_avg_dist /= pCard->m_record_totals;
				}
				
				char t_sql_log[LENGTH_MSG_8K];
				memset(t_sql_log,0,LENGTH_MSG_8K*sizeof(char));

				sprintf_s(t_sql_log,"insert ignore into his_draw_position(work_face_id,position_data,write_time,avg_distance,max_distance,min_distance) values(%d,'%s','%s',%.4f,%.4f,%.4f);",
					//pCard->vehicle_id.c_str(),
					pCard->driving_face_id,
					pCard->m_str_record.c_str(),
					CFunctions::time_t2string(cur_time).c_str(),
					pCard->m_record_avg_dist,
					pCard->m_record_max_dist,
					pCard->m_record_min_dist);
				//debug_print_syslog(0,"[calc distance between base point: data of sql insert his_draw_position] card_id: %s,cur_time: %lld, avg_dist: %.3f, max_dist: %.3f, min_dist: %.3f, sql_length: %d.",pCard->card_id.c_str(),cur_time,pCard->m_record_avg_dist,pCard->m_record_max_dist, pCard->m_record_min_dist, strlen(t_sql_log));
				//getMysqlRes(t_sql_log);	
				std::string error = "";
				if (sDBConnPool.ExecuteSql(t_sql_log,error ) < 0 )
				{
					//debug_print_syslog(0,"calc distance between base point: Failed to ExecuteSql:%s,Err=%s\n", t_sql_log, error.c_str());
				}

				pCard->m_str_record = "";
				pCard->m_record_cycle_start_time = cur_time;
				pCard->m_record_avg_dist = pCard->m_record_max_dist = 0.0;
				pCard->m_record_min_dist = 999999.9;
				pCard->m_record_totals = 0;
			}
		}
	}
}

/*
 * 当超时时，保存队列内剩余点的距离以及其的平均距离
 * 
 * param
 *		无
 *
 * return
 *		无
 *
*/
void CYAServerDlg::deal_drivingface_real_distance()
{
	for (auto it_card : mp_card_list_all)
	{
		time_t cur_time = time(NULL);

		//需同时满足如下条件：
		//a.车卡为掘进机；
		//b.当前时间大于开始记录的起始时间2分钟；
		//c.卡的记录的内容长度大于0
		if (CT_TUNNELBORING_MACHINE == it_card.second->card_type && (cur_time - it_card.second->m_record_cycle_start_time) >= 120 &&it_card.second->m_str_record.length() > 0)
		{
			//计算平均距离
			if (it_card.second->m_record_totals>0)
			{
				it_card.second->m_record_avg_dist /= it_card.second->m_record_totals;
			}

			if (it_card.second->m_record_max_dist < 1E-4)
			{
				it_card.second->m_record_max_dist = max(it_card.second->m_record_max_dist,it_card.second->m_record_avg_dist);
			}
			if (it_card.second->m_record_min_dist >= 999999.9)
			{
				it_card.second->m_record_min_dist = min(it_card.second->m_record_min_dist,it_card.second->m_record_avg_dist);
			}
			
			char t_sql_log[LENGTH_MSG_8K];
			memset(t_sql_log,0,LENGTH_MSG_8K*sizeof(char));
			sprintf_s(t_sql_log,"insert ignore into his_draw_position(work_face_id,position_data,write_time,avg_distance,max_distance,min_distance) values(%d,'%s','%s',%.4f,%.4f,%.4f);",
				//it_card.second->vehicle_id.c_str(),
				it_card.second->driving_face_id,
				it_card.second->m_str_record.c_str(),
				CFunctions::time_t2string(cur_time).c_str(),
				it_card.second->m_record_avg_dist,
				it_card.second->m_record_max_dist,
				it_card.second->m_record_min_dist);

			std::string log = "";
			log = t_sql_log;
			//debug_print_syslog(0,"[calc distance between base point: when time out exec sql] : avg_dist: %.3f, max_dist: %.3f, min_dist: %.3f",it_card.second->m_record_avg_dist,it_card.second->m_record_max_dist, it_card.second->m_record_min_dist);
			//getMysqlRes(t_sql_log);	
			std::string error = "";
			if (sDBConnPool.ExecuteSql(t_sql_log,error ) < 0 )
			{
				//debug_print_syslog(0,"calc distance: Failed to ExecuteSql:%s,Err=%s\n", log.c_str(), error.c_str());
			}

			it_card.second->m_str_record = "";
			it_card.second->m_record_cycle_start_time = 0;
			it_card.second->m_b_first_record = true;
			it_card.second->m_record_avg_dist = it_card.second->m_record_max_dist = 0.0;
			it_card.second->m_record_min_dist = 999999.9;
			it_card.second->m_record_totals = 0;
		}
	}
}

/*
 * 初始化掘进面离当前最近时间点的坐标
 *
 * param
 *		pCard		卡数据
 *
 * return
 *		无
*/
void CYAServerDlg::init_drivingface_recently_info(std::shared_ptr<Card> pCard)
{
	//第一次计算，例如采集重启
	if (pCard->m_b_first_calc)
	{	
		auto it_drivingface_card = mp_driving_face_card_list.find(pCard->card_id);
		if (it_drivingface_card!=mp_driving_face_card_list.end())
		{
			//从正规循化率表中获取最近时间点的坐标
			char sql[LENGTH_SQL];
			memset(sql,0,LENGTH_SQL*sizeof(char));
			// sprintf_s(sql,"select start_x, start_y from his_regular_cycle_detail where start_time = (select max(start_time) from his_regular_cycle_detail where vehicle_id='%s') and vehicle_id='%s' group by vehicle_id;",pCard->vehicle_id.c_str(),pCard->vehicle_id.c_str());

			sprintf_s(sql,"select start_x, start_y from his_regular_cycle_detail where start_time = (select max(start_time) from his_regular_cycle_detail where work_face_id=%d) and work_face_id=%d group by work_face_id;",it_drivingface_card->second->drivingface_id,it_drivingface_card->second->drivingface_id);
			//debug_print_syslog(0,"[regular_cycle : exec sql] ",sql);
			MYSQL_ROW pRow;
			MYSQL_RES *pRes = NULL;
			//pRes = getMysqlRes(sql);
			std::string error = "";
			pRes = sDBConnPool.Query(sql,error);

			if (NULL == pRes)
			{			
				//debug_print_syslog(0,"[init_drivingface_recently_info : query sql failed] %s",sql);
				return;
			}
				
			pCard->m_max_p.set(0,0);

			int nRow = 0;
			while(pRow = mysql_fetch_row(pRes))	{
				double x = pRow[0]==NULL?0:atof(pRow[0]);
				double y = pRow[1]==NULL?0:atof(pRow[1]);
				pCard->m_max_p.set(x,y);
			}
			mysql_free_result(pRes);

			int idx = it_drivingface_card->second->m_vt_ref_point_list.size()-1;
			if (idx < 0)
			{
				debug_print_syslog(0,"[init_drivingface_recently_info] drivingface_id: %d no ref point info.",it_drivingface_card->second->drivingface_id);
			}
			op::point p(it_drivingface_card->second->m_vt_ref_point_list[idx]);
			if (it_drivingface_card->second->m_vt_ref_point_list.size() > 1 && it_drivingface_card->second->m_total_ref_point_dist < ZERO_PRECISION)
			{
				double d = 0.0;
				op::point tp(it_drivingface_card->second->m_vt_ref_point_list[0]);
				for (size_t i = 1;i<it_drivingface_card->second->m_vt_ref_point_list.size();i++)
				{
					op::point ttp(it_drivingface_card->second->m_vt_ref_point_list[i]);
					d+=tp.dist(ttp)*pCard->map_scale;
				}
				it_drivingface_card->second->m_total_ref_point_dist = d;
				debug_print_syslog(0,"[init_drivingface_recently_info] drivingface_id: %d, trpd: %.4f",it_drivingface_card->second->drivingface_id,it_drivingface_card->second->m_total_ref_point_dist);
			}

			//如果历史数据存在，则用历史数据，否则使用当前定位卡数据
			if (pCard->m_max_p.empty())
			{
				//debug_print_syslog(0,"[init_drivingface_recently_info : database no data] card_id: %s",pCard->card_id.c_str());
				pCard->m_max_p.set(pCard->x,pCard->y);
				pCard->m_max_distance = it_drivingface_card->second->m_total_ref_point_dist + pCard->m_max_p.dist(p)*pCard->map_scale + it_drivingface_card->second->m_fOffset;
			}else{
				//debug_print_syslog(0,"[init_drivingface_recently_info : database have data] card_id: %s",pCard->card_id.c_str());
				pCard->m_max_distance = it_drivingface_card->second->m_total_ref_point_dist + pCard->m_max_p.dist(p)*pCard->map_scale + it_drivingface_card->second->m_fOffset;
			}
		}
		
		pCard->m_b_first_calc = false;
	}
	//debug_print_syslog(0,"[init_drivingface_recently_info] card_id: %s, x: %.3f, y: %.3f",pCard->card_id.c_str(),pCard->m_max_p.x,pCard->m_max_p.y);
}

/*
 * 计算本次坐标与基准点的距离，如果距离大于历史记录，则记录并保存到数据库，否则不记录，并清除
 *
 * param
 *		pCard		卡数据
 *		pDrivingfaceCard		卡的掘进面数据
 *		p			1分钟内定位坐标的平均坐标
 * return
 *		无
*/
void CYAServerDlg::save_drivingface_regular_cycle_data(std::shared_ptr<Card> pCard,std::shared_ptr<DrivingfaceCard> pDrivingfaceCard,const op::point& p)
{
	//如果排距为0,则不计算
	if(pDrivingfaceCard->m_drifting_footage_unit<ZERO_PRECISION){
		debug_print_syslog(0,"[regular_cycle : calc row spacing error,footage unit is zero] card_id: %s",pCard->card_id.c_str());
		return;
	}

	//处理时间
	time_t cur_time = time(NULL);
	std::string start_time = CFunctions::time_t2string(pCard->m_cb_position[0].cur_time);
	std::string end_time = CFunctions::time_t2string(cur_time);

	//计算本次定位点p与基准点的距离
	int idx = pDrivingfaceCard->m_vt_ref_point_list.size()-1;
	if (idx < 0)
	{
		debug_print_syslog(0,"[regular_cycle] drivingface_id: %d no ref point info.",pDrivingfaceCard->drivingface_id);
	}
	op::point base_point(pDrivingfaceCard->m_vt_ref_point_list[idx]);
	double cur_distance = 0.0;
	cur_distance = pDrivingfaceCard->m_total_ref_point_dist + p.dist(base_point)*pCard->map_scale + pDrivingfaceCard->m_fOffset;

	char chLog[MAX_LOG_LENGTH] = {0};
	std::string log = "";
	sprintf_s(chLog,"[regular_cycle] card_id: %s, drivingface_id: %d, cur_distance: %.4f, max_distance: %.4f, distanceToRef: %.4f, offset: %.4f, totalRefdist: %.4f, x: %.4f ,y: %.4f"
		,pCard->card_id.c_str(), pDrivingfaceCard->drivingface_id,cur_distance,pCard->m_max_distance,p.dist(base_point)*pCard->map_scale
		,pDrivingfaceCard->m_fOffset,pDrivingfaceCard->m_total_ref_point_dist,p.x, p.y);
	log = chLog;
	Log::write_log(FILE_TYPE::STARTUP_RATIO,log,true);

	debug_print_syslog(0,"[regular_cycle] card_id: %s, drivingface_id: %d, cur_distance: %.4f, max_distance: %.4f",
		pCard->card_id.c_str(),pDrivingfaceCard->drivingface_id,cur_distance,pCard->m_max_distance);
	if (cur_distance > pCard->m_max_distance)
	{
		//计算排数
		double real_driving_distance = 0.0;
		real_driving_distance = cur_distance - pCard->m_max_distance;

		//计算排数信息
		double schedule_value = 0.0;
		//schedule_value = pDrivingfaceCard->m_schedule_tunnelling_times;//*pDrivingfaceCard->m_drifting_footage_unit
		schedule_value = get_drivingface_schedule_value(pDrivingfaceCard->drivingface_id,2);
		double sv = schedule_value*pDrivingfaceCard->m_drifting_footage_unit;
		if (abs(sv) < 1E-4)
		{
			//debug_print_syslog(0,"[smooth_row_spacing] before smooth: card_id: %s , standard_value: %.4f",pCard->card_id.c_str(),sv);
			sv = 8.0;	
		}
		if (real_driving_distance > sv*1.5)
		{
			smooth_row_spacing(real_driving_distance,sv);
		}

		//double row_spacing = real_driving_distance / pDrivingfaceCard->m_drifting_footage_unit;
		double row_spacing = real_driving_distance;
	
		//保存最大进尺和对应的坐标
		pCard->m_max_distance = cur_distance;
		pCard->m_max_p.set(p);
	
		/*debug_print_syslog(0,"[regular_cycle: normal calc row spacing] card_id: %s, row_spacing: %.4f, real_driving_distance: %.3f, footage_unit: %.3f.",
			pCard->cardId().c_str(),
			row_spacing,
			real_driving_distance,
			pDrivingfaceCard->m_drifting_footage_unit);*/

		//将数据入库
		char sql_log[MAX_LOG_LENGTH];
		memset(sql_log,0,MAX_LOG_LENGTH*sizeof(char));
		sprintf_s(sql_log,"insert ignore into his_regular_cycle_detail(work_face_id,detail_type,start_time,end_time,detail_value,schedule_value,dept_id,start_x,start_y) \
						  values(%s,%d,'%s','%s',%.4f,%.4f,%d,%.3f,%.3f);",
						  pDrivingfaceCard->drivingface_id,2,start_time.c_str(),end_time.c_str(),
						  row_spacing,schedule_value,pDrivingfaceCard->m_dept_id,
						  p.x,p.y);
		//debug_print_syslog(0,"[regular_cycle: exec sql] %s",sql_log);
		//execute_sql(sql_log);
		std::string error = "";
		if (sDBConnPool.ExecuteSql(sql_log,error ) < 0 )
		{
			//debug_print_syslog(0,"regular_cycle: Failed to ExecuteSql:%s,Err=%s\n", sql_log, error.c_str());
		}
	}

	//清空队列内的数据
	pCard->m_cb_position.resize(0);
}

/*
 * 获得掘进面基准点的坐标
 *
 * param
 *		pCard		卡数据
 *
 * return
 *		掘进面所对应的基准点的坐标
*/
op::point CYAServerDlg::get_drivingface_base_point(std::shared_ptr<Card> pCard)
{
	op::point p;
	//获得模拟卡对应的分站号
	uint64_t reader_id = atoi(pCard->card_id.substr(3).c_str());
	if (reader_id < SIMULATOR_CARD_START_NO)
	{
		return p;
	}
	reader_id -= SIMULATOR_CARD_START_NO;

	//获得基准点坐标
	for (auto it : mp_driving_face_card_list)
	{
		if (it.second->m_small_reader_id == reader_id)
		{
			int idx = it.second->m_vt_ref_point_list.size()-1;
			if (idx<0)
			{
				continue;
			}
			p.set(it.second->m_vt_ref_point_list[idx].x*pCard->map_scale,it.second->m_vt_ref_point_list[idx].y*pCard->map_scale);
		}
	}

	return std::move(p);
}

/*
 * 平滑掘进机进尺的距离信息
 *
 * param
 *		value		需要平滑的进尺距离
 *		sv			掘进面计划进尺
 *
 * return
 *		无
 *
*/
void CYAServerDlg::smooth_row_spacing(double& value,const double& sv)
{
	//debug_print_syslog(0,"[smooth_row_spacing] before smooth: value: %.4f , standard_value: %.4f",value,sv);
	int m = (int)value/((int)sv);
	double tmp_value = 0.0;
	tmp_value = value - m*sv;

	SYSTEMTIME st;
	GetLocalTime(&st);
	if (st.wHour<=12)
	{
		tmp_value = tmp_value/2;
	}	

	//debug_print_syslog(0,"[smooth_row_spacing] after smooth: value: %.4f , standard_value: %.4f",tmp_value,sv);
	value = tmp_value;
}

int CYAServerDlg::get_forbidden_area_id(const _point& p)
{
	int area_id = 0;
	for (auto it:mp_area_list)
	{
		if (AREA_TYPE_FORBIDDEN == it.second->area_type_id)
		{
			if (it.second->is_in_polygon(p))
			{
				area_id = it.second->area_id;
			}
		}
	}
	return area_id;
}

/*
 * 自动呼叫进入禁入区域的人员
 * 
 * param
 *		person_list		人员列表
 *
 * return
 *		成功返回0，否则返回非零值
*/
int CYAServerDlg::auto_call_person(std::shared_ptr<CardMap>& person_list)
{
	EnterCriticalSection(&m_csCallInfo);

	shared_ptr<_call_info_user> call_user;
	shared_ptr<_call_info_reader> call_reader;
	std::shared_ptr<_call_info_card> call_card;

	int reader_id = 0;
	std::string user_name = "yaserver";

	CallInfoUserMap::iterator it_user_call = mp_user_call_info.find(user_name);
	if(it_user_call != mp_user_call_info.end()){
		call_user = it_user_call->second;
	}else{
		call_user = std::make_shared<_call_info_user>();
		call_user->user_name = user_name;
		mp_user_call_info.insert(make_pair(user_name, call_user));
	}

	CallInfoReaderMap::iterator it_call_reader = call_user->mpReader.find(reader_id);
	if (it_call_reader == call_user->mpReader.end())
	{
		for(auto it_card = person_list->begin(); it_card != person_list->end(); ++it_card){
			int card_type = CT_PERSON;
			int card_id = 0;
			std::string s_card_id = it_card->second->card_id;

			string new_card_id = s_card_id.substr(3, s_card_id.length());
			card_id = atoi(new_card_id.c_str());

			reader_id = it_card->second->reader_id;
			if (0 == reader_id)
			{
				//如果此卡不属于任何分站，此时其的分站id为零，此卡不参与呼叫
				continue;
			}
			CallInfoReaderMap::iterator it_call_reader = call_user->mpReader.find(reader_id);

			if(it_call_reader != call_user->mpReader.end()){
				call_reader = it_call_reader->second;	
				call_reader->is_start_call = true;
				call_reader->is_call_all = false;
				call_reader->cards_count += 1;
				call_reader->call_level = 1;
			}else{
				call_reader = std::make_shared<_call_info_reader>();
				call_reader->call_level = 1;
				call_reader->is_call_all = false;
				call_reader->cards_count = 1;
				call_reader->is_start_call = true;
				call_user->mpReader.insert(make_pair(reader_id, call_reader));
			}

			CallInfoCardMap::iterator it_call_card = call_reader->mpCard.find(s_card_id);
			if(it_call_card != call_reader->mpCard.end()){ 
				// 已在呼叫列表
				/*call_card = it_call_card->second;
				call_card->time_out = 10;*/
			}else{ 
				// 未在呼叫列表
				call_card = std::make_shared<_call_info_card>();
				call_card->card_id = card_id;
				call_card->card_type = card_type;
				call_card->start_time = time(NULL);
				call_card->time_out = 10;
				call_card->call_level = 1;
				call_card->str_card_id = s_card_id;
				call_reader->mpCard.insert(make_pair(s_card_id, call_card));
			}
		}
	}

	debug_print_syslog(0,"[card_enter_forbidden_area] start call: user_name: %s",user_name.c_str());
	LeaveCriticalSection(&m_csCallInfo);

	Json::Value root;
	Json::Value resp_data;

	//如果有卡数据
	if (person_list->size() > 0)
	{
		for(auto it = person_list->begin();it!=person_list->end();++it){
			Json::Value callinfo;
			callinfo.append(user_name);
			callinfo.append(it->second->card_id);//一般：1;紧急：2
			callinfo.append(reader_id);
			callinfo.append(10);
			callinfo.append(1);
			callinfo.append(CALL_STATE::CALL_ING);
			resp_data.append(callinfo);
		}
	}

	std::string ret = "";
	if(resp_data.size() > 0){
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_CALL_CARD_RESPONSE;
		root[JSON_ROOT_KEY_DATA] = resp_data;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION;
		ret = root.toFastString();
		send_json_data(JSON_CMD_VALUE_PUSH,ret);
		debug_print_syslog(0,"[card_enter_forbidden_area] start call of send json: %s",ret.c_str());
	}

	return 0;
}

/*
 * 从呼叫列表中取消指定卡的呼叫
 * 
 * param
 *		card_id		卡号
 *
 * return
 *		成功执行返回0，否则返回非0值
*/
int CYAServerDlg::cancel_call(const std::string& card_id)
{
	BYTE buf[LENGTH_SEND_BUF] = {0};

	std::string user_name = "yaserver";

	std::shared_ptr<_call_info_user> call_user;
	std::shared_ptr<_call_info_reader> call_reader;
	_call_info_card* call_card;
	//对指定卡取消呼叫
	CallInfoUserMap::iterator it_call_user = mp_user_call_info.find(user_name);
	if(it_call_user != mp_user_call_info.end())
	{
		EnterCriticalSection(&m_csCallInfo);

		CallInfoReaderMap::iterator it_reader = it_call_user->second->mpReader.begin();
		for(auto it_reader = it_call_user->second->mpReader.begin(); it_reader != it_call_user->second->mpReader.end();)
		{
			// 删除分站内的卡
			CallInfoCardMap::iterator it_call_card = it_reader->second->mpCard.find(card_id);
			if(it_call_card != it_reader->second->mpCard.end())
			{
				it_reader->second->mpCard.erase(it_call_card);
				debug_print_syslog(0,"[card_enter_forbidden_area] cancel call: card_id: %s",card_id.c_str());
			}

			if(it_reader->second->mpCard.size() > 0)
			{
				++it_reader;
			}
			else
			{
				// 如果分站中卡为空，删除分站
				it_reader = it_call_user->second->mpReader.erase(it_reader);
			}
		}

		LeaveCriticalSection(&m_csCallInfo);

		//取消呼叫
		Json::Value root;
		Json::Value callinfo;
		Json::Value stations;
		Json::Value cards;

		callinfo[JSON_KEY_CALL_CARD_CALL_TYPE] = 1;
		callinfo[JSON_KEY_CALL_CARD_CALL_TIME] = 10.0;
		callinfo[JSON_KEY_CALL_CARD_USER_NAME] = user_name;

		//构造stations和cards
		Json::Value station;
		station[JSON_KEY_CALL_CARD_STATION_ID] = 0;
		stations.append(station);

		Json::Value card;
		card[JSON_KEY_CALL_CARD_CARD_ID] = card_id.substr(9,card_id.length());
		card[JSON_KEY_CALL_CARD_CARD_TYPE_ID] = CT_PERSON;
		cards.append(card);

		callinfo[JSON_KEY_CALL_CARD_STATIONS] = stations;
		callinfo[JSON_KEY_CALL_CARD_CARDS]    = cards;

		std::string ret = "";

		if(callinfo.size() > 0){
			root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_CALL_CARD_CANCEL_RESPONSE;
			root[JSON_ROOT_KEY_DATA] = callinfo;
			root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION;
			ret = root.toFastString();
			send_json_data(JSON_CMD_VALUE_PUSH,ret);
			debug_print_syslog(0,"[card_enter_forbidden_area] cacel call of send json: %s",ret.c_str());
		}
	}
	return 0;
}

std::string CYAServerDlg::get_json_call_test()
{
	Json::Value root;
	Json::Value val_data;
	Json::Value val_stations;
	Json::Value val_station;
	Json::Value val_cards;
	Json::Value val_card;

	char _time[STR_LEN_TIME];
	struct tm local_time;
	time_t tt = time(NULL);

	localtime_s(&local_time, &tt);
	strftime(_time, STR_LEN_TIME, "%Y-%m-%d %H:%M:%S", &local_time);
	val_data[JSON_KEY_CALL_CARD_CALL_TIME] = _time;
	val_data[JSON_KEY_CALL_CARD_CALL_LEVEL] = 0;
	val_data[JSON_KEY_CALL_CARD_USER_NAME] = "aaaaaa";
	val_data[JSON_KEY_CALL_CARD_CALL_TIME_OUT] = 5;

	val_station[JSON_KEY_CALL_CARD_STATION_ID] = 233;
	val_stations.append(val_station);
	val_station[JSON_KEY_CALL_CARD_STATION_ID] = 59;
	val_stations.append(val_station);

	val_card[JSON_KEY_CALL_CARD_CARD_TYPE_ID] = 3;
	val_card[JSON_KEY_CALL_CARD_CARD_ID] = 5;
	val_cards.append(val_card);
	val_card[JSON_KEY_CALL_CARD_CARD_TYPE_ID] = 3;
	val_card[JSON_KEY_CALL_CARD_CARD_ID] = 8;
	val_cards.append(val_card);

	val_data[JSON_KEY_CALL_CARD_STATIONS] = val_stations;
	val_data[JSON_KEY_CALL_CARD_CARDS] = val_cards;

	root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_CALL_CARD_REQUEST;
	root[JSON_ROOT_KEY_DATA] = val_data;
	return root.toFastString();
}

void CYAServerDlg::init_base_data()
{
	init_setting();
	init_alarm_type();
	init_shift();
	init_dept();
	init_level();
	init_map();
	init_area();
	init_special_area_entry();

	init_reader();

	init_dev_adhoc();
	init_antenna_sync();
	init_special_card();
	init_card();
	init_staffer();
	Init_worktime_detail();
	init_vehicle();
	init_adhoc();
	init_rules();//lemon 2017/08/01
	init_monkeycar_base_info();
	init_chamber();
	init_ctrl_reader();

	init_section();
	init_light_group();
	init_traffic_lights();
	//init_patrol_info();
	init_landmark();
	init_map_direction();
	init_drivingface_warning_point();
	init_geological_fault();
	init_leader_arrange();
	init_att_area();
	init_drivingface_card();
	init_sensor();
	init_drivingface_ref_points();
	//handup_vehicle
	init_handup_vehicle();
	init_moving_reader();

	init_workingface_area();
	//初始化综采面机头机尾和范围等信息
	init_data_coalminingface_RegularCycle();
	//初始化采煤机正规循环率中间计算参数
	init_data_coalmining_RegularCycle();
	init_data_pre_coalmining_RegularCycle();
	init_restart_halfcoalmining_regularcycle();

	init_coalface_driver_warningparam();
	debug_print_syslog(0, "Base data init success.");
}

void CYAServerDlg::load_his_data()
{
	load_his_card_postion_vehicle(); // 标识卡所在位置
	load_his_card_postion_staff();
	load_his_card_state();
	deal_hist_card_postion();
	load_his_event_data(); // 分站状态
	//load_drivingface_card_curshift_position();
}

void CYAServerDlg::load_his_area()
{
	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	sprintf_s(buf, "select la.card_id, la.area_id, la.map_id, la.enter_time from his_location_area la \
				   where not exists(select 1 from his_location_area where card_id=la.card_id and enter_time> la.enter_time) \
				   and la.leave_time is null;");
	pRes = getMysqlRes(buf);

	if(NULL == pRes)
	{
		return;
	}
	int nRow = 0;
	std::string enter_time;
	while(pRow = mysql_fetch_row(pRes)){
		CardMap::iterator it = mp_card_list_all.find(pRow[0]);
		if(it != mp_card_list_all.end()){
			it->second->area_id = atoi(pRow[1]);
			it->second->map_id = atoi(pRow[2]);
			enter_time = pRow[3];
			CFunctions::string2systemtime(enter_time,it->second->enter_area_time);
			nRow++;
		}
	}
	mysql_free_result(pRes);
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_LOAD_HIS_AREA), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
}

void CYAServerDlg::load_his_card_postion_vehicle()
{
	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	sprintf_s(buf, "select l.card_id, l.cur_time, l.x, l.y, l.z, l.map_id, la.area_id, l.state, \
				   case when l.cur_time >= date_sub(now(), interval 2 minute) then l.speed else 0 end as speed, \
				   l.mileage, la.enter_time, att.start_time, \
				   case when isnull(att.end_time) then 2 else 1 end as down_state, \
				   l.landmark_id, l.direction_mapper_id, l.landmark_dist \
				   from rt_location l, rt_location_area la, rt_att_vehicle att, dat_card c, dat_vehicle_extend v \
				   where l.card_id = c.card_id and l.card_id = la.card_id and l.card_id = att.card_id and l.card_id=v.card_id \
				   and c.state_id=0;");

	pRes = getMysqlRes(buf);

	if(NULL == pRes)
	{
		return;
	}

	int nRow = 0;
	std::string rec_time, enter_time, start_time;
	while(pRow = mysql_fetch_row(pRes)){
		CardMap::iterator it = mp_card_list_all.find(pRow[0]);
		if(it != mp_card_list_all.end()){
			rec_time = pRow[1];
			API_StringToTime(rec_time, it->second->rec_time);

			it->second->x = atof(pRow[2]);
			it->second->y = atof(pRow[3]);
			it->second->z = atof(pRow[4]);

			it->second->map_id = atoi(pRow[5]);	
			it->second->area_id = atoi(pRow[6]);					
			it->second->state = atoi(pRow[7]);

			if(STATUS_LOST == atoi(pRow[7]))
			{
				it->second->status_lost = STATUS_LOST;
			}

			it->second->set_speed(atof(pRow[8]));
			it->second->mileage = atof(pRow[9]);

			enter_time = pRow[10];
			CFunctions::string2systemtime(enter_time,it->second->enter_area_time);
			start_time = pRow[11];
			API_StringToTime(start_time, it->second->down_time);

			it->second->PosState(atoi(pRow[12]));
			it->second->PosStateOld(atoi(pRow[12]));

			it->second->landmark_id = atoi(pRow[13]);
			it->second-> landmark_direction = atoi(pRow[14]);
			it->second->landmark_dis = atof(pRow[15]);

			it->second->last_x = it->second->x;
			it->second->last_y = it->second->y;
			it->second->last_z = it->second->z;

			::GetLocalTime(&it->second->deal_time);

			it->second->is_hist = true;
			it->second->isdealed = true;
			it->second->isoutput = true;
			it->second->issent = false;

			deal_his_card_list(it->second);

			nRow++;
		}
	}
	mysql_free_result(pRes);
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_LOAD_HIS_POSTION_VEHICLE), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
}

void CYAServerDlg::load_his_card_postion_staff()
{
	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	sprintf_s(buf, "select l.card_id, l.cur_time, l.x, l.y, l.z, l.map_id, la.area_id, l.state, \
				   case when l.cur_time >= date_sub(now(), interval 2 minute) then l.speed else 0 end as speed, \
				   l.mileage, la.enter_time, att.start_time, \
				   case when isnull(att.end_time) then 2 else 1 end as down_state, \
				   l.landmark_id, l.direction_mapper_id, l.landmark_dist \
				   from rt_location l, rt_location_area la, rt_att_staff att, dat_card c, dat_staff_extend s \
				   where l.card_id = c.card_id and l.card_id = la.card_id and l.card_id = att.card_id and l.card_id=s.card_id\
				   and c.state_id=0;");

	pRes = getMysqlRes(buf);

	if(NULL == pRes)
	{
		return;
	}
	int nRow = 0;
	std::string rec_time, enter_time, start_time;
	while(pRow = mysql_fetch_row(pRes)){
		if(PDT_UP == atoi(pRow[12]))
		{
			continue; // 已升井，不再读入
		}
		CardMap::iterator it = mp_card_list_all.find(pRow[0]);
		if(it != mp_card_list_all.end()){
			rec_time = pRow[1];
			API_StringToTime(rec_time, it->second->rec_time);

			it->second->x = atof(pRow[2]);
			it->second->y = atof(pRow[3]);
			it->second->z = atof(pRow[4]);

			it->second->map_id = atoi(pRow[5]);	
			it->second->area_id = atoi(pRow[6]);					
			it->second->state = atoi(pRow[7]);
			it->second->set_speed(atof(pRow[8]));
			it->second->mileage = atof(pRow[9]);

			enter_time = pRow[10];
			CFunctions::string2systemtime(enter_time,it->second->enter_area_time);
			start_time = pRow[11];
			API_StringToTime(start_time, it->second->down_time);

			it->second->PosState(atoi(pRow[12]));
			it->second->PosStateOld(atoi(pRow[12]));

			it->second->landmark_id = atoi(pRow[13]);
			it->second->landmark_direction = atoi(pRow[14]);
			it->second->landmark_dis = atof(pRow[15]);

			it->second->last_x = it->second->x;
			it->second->last_y = it->second->y;
			it->second->last_z = it->second->z;

			::GetLocalTime(&it->second->deal_time);

			it->second->is_hist = true;
			it->second->isdealed = true;
			it->second->isoutput = true;
			it->second->issent = false;

			deal_his_card_list(it->second);

			nRow++;
		}
	}
	mysql_free_result(pRes);
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_LOAD_HIS_POSTION_STAFF), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
}

void CYAServerDlg::load_his_driving_face_card_postion()
{
	//MYSQL_RES* pRes;
	//MYSQL_ROW pRow;
	//int err = 0;
	//char buf[LENGTH_SQL] = {0};
	//sprintf_s(buf, "select * from his_location where cur_time in (select max(cur_time) from his_location where card_id = 0020000001014) and card_id = 0020000001014;");

	//pRes = getMysqlRes(buf);
	//if(NULL == pRes)
	//{
	//	return;
	//}

	//int nRow = 0;
	//std::string rec_time, enter_time, start_time;
	//while(pRow = mysql_fetch_row(pRes)){
	//	CardMap::iterator it = mp_card_list_all.find(pRow[0]);
	//	if(it != mp_card_list_all.end()){
	//		rec_time = pRow[1];
	//		API_StringToTime(rec_time, it->second->rec_time);

	//		it->second->x = atof(pRow[2]);
	//		it->second->y = atof(pRow[3]);
	//		it->second->z = atof(pRow[4]);

	//		it->second->map_id = atoi(pRow[5]); 
	//		it->second->area_id = atoi(pRow[6]);					
	//		it->second->state = atoi(pRow[7]);
	//		it->second->set_speed(atof(pRow[8]));
	//		it->second->mileage = atof(pRow[9]);

	//		it->second->PosState(PDT_DOWN);
	//		it->second->PosStateOld(PDT_DOWN);
	//		::GetLocalTime(&it->second->deal_time);

	//		it->second->is_hist = true;
	//		it->second->isdealed = true;
	//		it->second->isoutput = true;
	//		it->second->issent = false;

	//		deal_his_card_list(it->second);

	//		//send_json_data(JSON_CMD_VALUE_PUSH, get_json_drivingface_card_position(it->second));
	//		nRow++;
	//	}
	//}
	//mysql_free_result(pRes);
	//CString strlog;
	//strlog.Format(_T("%s%d%s"), _T(LOG_LOAD_HIS_POSTION_VEHICLE), nRow, _T(LOG_RECORD_COUNT));
	//show_log(strlog);

}

void CYAServerDlg::load_his_driving_face_card_state()
{
	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};

	int nRow = 0;
	DrivingfaceCardMap::iterator it = mp_driving_face_card_list.begin();
	for(;it!=mp_driving_face_card_list.end();it++)
	{
		sprintf_s(buf, "select * from his_drivingface_his where card_id = '%s' order by end_time desc limit 1;",it->first.c_str());
		pRes = getMysqlRes(buf);

		if(NULL == pRes)
		{
			return;
		}
		std::string rec_time, enter_time, start_time;
		while(pRow = mysql_fetch_row(pRes)){
			CardMap::iterator it = mp_card_list_all.find(pRow[1]);
			if(it != mp_card_list_all.end()){
				rec_time = pRow[5];
				API_StringToTime(rec_time, it->second->rec_time);

				it->second->x = atof(pRow[9]);
				it->second->y = atof(pRow[10]);
				it->second->z = atof(pRow[11]);
				nRow++;
			}
		}
	}

	mysql_free_result(pRes);


	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_LOAD_HIS_DRVING_FACE_STATE), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

}
void CYAServerDlg::init_geological_fault()
{
	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	sprintf_s(buf, "SELECT geofault_id,workface_id,workface_type,geofault_name,pt_data FROM dat_geofault;");
	pRes = getMysqlRes(buf);

	if(NULL == pRes)
	{
		return ;
	}
	while(pRow = mysql_fetch_row(pRes)){
		std::shared_ptr<WarningPoint> wp=std::make_shared<WarningPoint>();
		uint64_t type = atoi(pRow[2]);
		int wid = atoi(pRow[1]);
		int gid = atoi(pRow[0]);
		std::string name = pRow[3];
		std::string pt = pRow[4];
		wp->warning_point_id=gid;wp->warning_point_name=name;
		if (pt.empty())continue;
		std::vector<std::string> tv = CFunctions::split(pt,";",true);
		for (const auto & s:tv)
		{
			std::vector<std::string> x = CFunctions::split(s,",",true);
			if (x.size()!=2)continue;
			NAMESPACE_POINT::point  mp;
			mp.x = CFunctions::round(atof((x[0]).c_str()),3);
			mp.y = CFunctions::round(atof((x[1]).c_str()),3);
			wp->vp.push_back(mp);
		}
		uint64_t k = type<<32|wid;
		auto it = m_WarningPoint_list.find(k);
		if (it!=m_WarningPoint_list.end())
		{
			bool flag = false;
			for (auto & _wp:it->second)
			{
				if (_wp->warning_point_id==gid)
				{
					_wp=wp;break;flag=true;
				}
			}
			if (!flag)
				it->second.push_back(wp);
		}
		else
		{
			std::list<std::shared_ptr<WarningPoint>> li;li.push_back(wp);
			m_WarningPoint_list.insert(std::make_pair(k,li));
		}
	}
	std::stringstream ss;
	for (const auto & pm:m_WarningPoint_list)
	{
		ss<<"workingface_id:"<<pm.first<<"{{";
		for (const auto &pp:pm.second)
		{
			ss<<pp->to_string();
		}
		ss<<"}}";
	}
	debug_print_syslog(0,"init_face:%s",ss.str().c_str());
	mysql_free_result(pRes);
}

void CYAServerDlg::init_drivingface_warning_point()
{
	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	sprintf_s(buf, "select warning_point_id, warning_point_name, drivingface_id, point_x, point_y, point_z, warning_threshold, isvalid from dat_drivingface_warning_point;");
	pRes = getMysqlRes(buf);

	if(NULL == pRes)
	{
		return ;
	}

	int nRow = 0;
	std::string enter_time;
	std::shared_ptr<DrivingfaceWarningPoint> pDrivingfaceWarningPoint = nullptr;
	std::vector<shared_ptr<DrivingfaceWarningPoint>> DrivingfaceWaringPointList;
	while(pRow = mysql_fetch_row(pRes)){
		int flag = 0;
		DrivingfaceWarningPointMapAll::iterator it = mp_drivingface_warning_point_list_all.find(atoi(pRow[2]));
		if(it != mp_drivingface_warning_point_list_all.end())
		{

			DrivingfaceWaringPointList = it->second;
			//pDrivingfaceWarningPoint = it->second;
			//查找vector是否存在该指针，如果存在则复制出来
			for(int i =0;i<DrivingfaceWaringPointList.size();i++)
			{
				if(DrivingfaceWaringPointList[i]->warning_point_id == atoi(pRow[0]))
				{
					flag = 1;
					pDrivingfaceWarningPoint = DrivingfaceWaringPointList[i];
				}
			}//如果不存在，vector插入该指针
			if(flag == 0)
			{
				pDrivingfaceWarningPoint = std::make_shared<DrivingfaceWarningPoint>();
				DrivingfaceWaringPointList.push_back(pDrivingfaceWarningPoint);
			}
		}else{
			pDrivingfaceWarningPoint = std::make_shared<DrivingfaceWarningPoint>();
			DrivingfaceWaringPointList.push_back(pDrivingfaceWarningPoint);
			//mp_drivingface_warning_point_list.insert(make_pair(atoi(pRow[2]), pDrivingfaceWarningPoint));
		}
		pDrivingfaceWarningPoint->warning_point_id = atoi(pRow[0]);
		pDrivingfaceWarningPoint->warning_point_name = pRow[1];
		pDrivingfaceWarningPoint->driving_face_id = atoi(pRow[2]);
		pDrivingfaceWarningPoint->point_x = atof(pRow[3]);
		pDrivingfaceWarningPoint->point_y = atof(pRow[4]);
		pDrivingfaceWarningPoint->point_z = atof(pRow[5]);
		pDrivingfaceWarningPoint->warning_threshold = atof(pRow[6]);
		pDrivingfaceWarningPoint->is_valid = atoi(pRow[7]);
		if(flag == 0)
		{
			mp_drivingface_warning_point_list_all.insert(make_pair(atoi(pRow[2]),DrivingfaceWaringPointList));
		}
	}
	mysql_free_result(pRes);
}

float CYAServerDlg::get_drivingface_warning_point_dis(std::shared_ptr<Card> card)
{

	if(NULL == card)
	{
		return -1;
	}
	double distance = DBL_MAX;//the flag for most bigger...
	double warning_threshold = DBL_MAX;
	DrivingfaceCardMap::iterator it_card = mp_driving_face_card_list.find(card->card_id);
	if(it_card == mp_driving_face_card_list.end())
		return -1;
	int drivingfaceId = it_card->second->drivingface_id;
	DrivingfaceWarningPointMapAll::iterator it = mp_drivingface_warning_point_list_all.find(drivingfaceId);

	//DrivingfaceWarningPointMap::iterator it = mp_drivingface_warning_point_list.find(3305);
	if(it != mp_drivingface_warning_point_list_all.end())
	{
		vector<shared_ptr<DrivingfaceWarningPoint>> vDrivingfaceWarninglist = it->second;
		vector<shared_ptr<DrivingfaceWarningPoint>>::iterator vit = vDrivingfaceWarninglist.begin();
		for(;vit != vDrivingfaceWarninglist.end();vit++)
		{
			_point card_position;
			_point warning_point_position;
			card_position.x = card->x;
			card_position.y = card->y;
			card_position.z = card->z;
			warning_point_position.x = (*vit)->point_x;
			warning_point_position.y = (*vit)->point_y;
			warning_point_position.z = (*vit)->point_z;
			double tmpdistance = GetDistance(card_position, warning_point_position);

			tmpdistance = tmpdistance * card->map_scale;
			double lengthcardpoint  = sqrt(pow(card->x - it_card->second->x, 2)
				+ pow(card->y - it_card->second->y, 2)
				+ pow(card->z - it_card->second->z, 2)) * card->map_scale;
			double lengthwarningpoint = sqrt(pow((*vit)->point_x - it_card->second->x, 2)
				+ pow((*vit)->point_y - it_card->second->y, 2)
				+ pow((*vit)->point_z - it_card->second->z, 2)) * card->map_scale;
			if(lengthcardpoint < lengthwarningpoint)
			{
				if(tmpdistance < distance)
				{
					distance = tmpdistance;
					warning_threshold = (*vit)->warning_threshold;
					card->m_warning_point_id = (*vit)->warning_point_id;
				}
			}

		}
	}

	card->m_warning_threshold = warning_threshold;
	card->m_minDistanceToWarningpoint = distance;
	return distance;
}

int CYAServerDlg::API_TimeToString( string &strDateStr,const time_t &timeData )
{
	char chTmp[100] = {0};
	memset(chTmp, 0, sizeof(chTmp));
	struct tm *p = 0;
	localtime_s(p, &timeData);
	//p = localtime(&timeData);
	p->tm_year = p->tm_year + 1900;
	p->tm_mon = p->tm_mon + 1;
	sprintf_s(chTmp,sizeof(chTmp),"%.4d-%.2d-%.2d %.2d:%.2d:%.2d",
		p->tm_year, p->tm_mon, p->tm_mday,p->tm_hour,p->tm_min,p->tm_sec);
	strDateStr = chTmp;
	return 0;
}

int CYAServerDlg::API_StringToTime( const string &strDateStr,time_t &timeData )
{
	char *pBeginPos = (char*) strDateStr.c_str();
	char *pPos = strstr(pBeginPos,"-");
	if(pPos == NULL){
		//printf("strDateStr[%s] err /n", strDateStr.c_str());
		return -1;
	}
	int iYear = atoi(pBeginPos);
	int iMonth = atoi(pPos + 1);
	pPos = strstr(pPos + 1,"-");
	if(pPos == NULL){
		//printf("strDateStr[%s] err /n", strDateStr.c_str());
		return -1;
	}
	int iDay = atoi(pPos + 1);
	int iHour=0;
	int iMin=0;
	int iSec=0;
	pPos = strstr(pPos + 1," ");
	//为了兼容有些没精确到时分秒的
	if(pPos != NULL){
		iHour=atoi(pPos + 1);
		pPos = strstr(pPos + 1,":");
		if(pPos != NULL){
			iMin=atoi(pPos + 1);
			pPos = strstr(pPos + 1,":");
			if(pPos != NULL){
				iSec=atoi(pPos + 1);
			}
		}
	}
	struct tm sourcedate;
	memset((void*)&sourcedate, 0, sizeof(sourcedate));
	sourcedate.tm_sec = iSec;
	sourcedate.tm_min = iMin;
	sourcedate.tm_hour = iHour;
	sourcedate.tm_mday = iDay;
	sourcedate.tm_mon = iMonth - 1;
	sourcedate.tm_year = iYear - 1900;
	timeData = mktime(&sourcedate);
	return 0;
}

int CYAServerDlg::init_special_card( string name /*= ""*/ )
{
	char buf[LENGTH_SQL] = {0};

	if(name.length() == 0){
		sprintf_s(buf, "SELECT b.vehicle_id,a.special_area FROM dat_special_card a , dat_vehicle b WHERE a.card_name = b.name");
	}else{
		sprintf_s(buf, "SELECT b.vehicle_id,a.special_area FROM dat_special_card a , dat_vehicle b WHERE a.card_name = b.name and a.card_name = '%s';", name.c_str());
	}

	MYSQL_RES* pRes = NULL;
	pRes = getMysqlRes(buf);

	if(NULL == pRes)
	{
		return 1;
	}

	MYSQL_ROW pRow;
	int nRow = 0;

	while(pRow = mysql_fetch_row(pRes)){
		m_sc.insert(atoi(pRow[1]),atoi(pRow[0]));
		nRow ++;
	}
	mysql_free_result(pRes);
	debug_print_syslog(0,"[Special_card:%s]",m_sc.to_str().c_str());
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T("初始化special_card"), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}
int CYAServerDlg::init_card( string card_id /*= ""*/ )
{
	char buf[LENGTH_SQL] = {0};

	if(card_id.length() == 0){
		sprintf_s(buf, "select card_id, card_type_id, state_id, ident from dat_card where state_id = 0;");
	}else{
		sprintf_s(buf, "select card_id, card_type_id, state_id, ident from dat_card where state_id = 0 and card_id='%s';", card_id.c_str());
	}

	MYSQL_RES* pRes = NULL;
	pRes = getMysqlRes(buf);

	if(NULL == pRes)
	{
		return 1;
	}

	MYSQL_ROW pRow;
	int err = 0;
	std::shared_ptr<Card> pCard = nullptr;
	int nRow = 0;

	while(pRow = mysql_fetch_row(pRes)){
		CardMap::iterator it = mp_card_list_all.find(pRow[0]);
		if(it != mp_card_list_all.end()){
			pCard = it->second;
		}else{
			pCard = std::make_shared<Card>(pRow[0], atoi(pRow[1]), theApp.z_offset);
			pCard->set_reader_path(mp_reader_path_list_tof, mp_reader_path_list_tdoa);
			mp_card_list_all.insert(make_pair(pCard->card_id, pCard));
			nRow++;

			if(m_bUseFilter){
				if(theApp.use_filter_odd){
					std::string temp = pRow[1];
					int a = atoi(temp.substr(temp.length() - 1 , 1).c_str());
					if(0 == a%2){
						pCard->EnableFilter(m_nFilterType);
					}
				}else{
					pCard->EnableFilter(m_nFilterType);
				}
			}
		}
	}
	mysql_free_result(pRes);

	//增加需要模拟小分站的卡上路径集
	for (auto it : mp_card_list_all)
	{
		if (CT_SIMULATE_CARD == it.second->card_type)
		{
			it.second->set_reader_path(mp_reader_path_list_tof, mp_reader_path_list_tdoa);

		}
	}

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_CARD), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}
//lemon 2017/08/08
void CYAServerDlg::card_up_mine(std::shared_ptr<Card> card /*Card* card*/)
{
	{
		// lihongzhen  2017/10/24 避免清除盲区卡考勤时间错误，采用清除盲区卡的时间
		time_t cur_time = CFunctions::systime_to_timet(card->deal_time);
		if(card->up_time < cur_time)
		{
			card->up_time = cur_time;
		}
	}
	store_data_card(card, RPT_ATTEND_UP);

	// 升井 删除所有报警信息
	INT64 ev_id = 0;
	for(int i=0; i < CARD_EVENT_COUNT; i++ )
	{
		//if (i == event_type::et_card_low_power_serious)
		//{
		//	continue;
		//}
		ev_id = card->m_event_list[i];		
		if(ev_id > 0 ) // 
		{			
			EventMap::iterator it_ev = mp_event_list->find(ev_id);
			if(it_ev != mp_event_list->end())
			{
				//如果是卡报警这里统一处理
				if (it_ev->second->obj_type == OT_CARD)
				{
					debug_print_syslog(0,"power_alarm_..%lld,%d....%s",ev_id,i,card->card_id.c_str());
					it_ev->second->status = ES_END;
					it_ev->second->cur_time = time(NULL);
					it_ev->second->is_sent = false;
					store_data_event(it_ev->second);
					add_event(it_ev->second);
					card->m_event_list[i] = 0;
				}	
			}

		}
	}

	EVENT_TYPE et = ET_UNKNOWN;
	double limit_val = 0, cur_val = 0;

	if(CT_PERSON == card->card_type){
		CardMap::iterator it_card = mp_card_list_down_person.find(card->card_id);
		if(it_card != mp_card_list_down_person.end()){	
			mp_card_list_up_person.insert(make_pair(it_card->first,it_card->second));
			mp_card_list_down_person.erase(it_card); // 从井下卡列表删除
			if(mp_card_list_down_person.size() < sls_setting.over_count_person){ // 取消报警
				et = ET_OVER_COUNT_PERSON;
				limit_val = sls_setting.over_count_person;
				cur_val = mp_card_list_down_person.size();
			}
		}
	}else if(CT_VEHICLE == card->card_type|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type){
		CardMap::iterator it_card = mp_card_list_down_vehicle.find(card->card_id);
		if(it_card != mp_card_list_down_vehicle.end()){
			//mp_card_list_ down_vehicle.erase(it_card); // 从井下卡列表删除			
			if(mp_card_list_down_vehicle.size() < sls_setting.over_count_vehicle){
				et = ET_OVER_COUNT_VEHICLE;
				limit_val = sls_setting.over_count_vehicle;
				cur_val = mp_card_list_down_vehicle.size();
			}
		}
	}
	if(ET_UNKNOWN != et){
		ev_id = m_event_list[et];
		if(ev_id > 0 ) // 
		{			
			EventMap::iterator it_ev = mp_event_list->find(ev_id);
			if(it_ev != mp_event_list->end())
			{
				it_ev->second->cur_value = cur_val;					
				it_ev->second->status = ES_END;
				it_ev->second->cur_time = time(NULL);
				it_ev->second->is_sent = false;
				store_data_event(it_ev->second);
				add_event(it_ev->second);

				m_event_list[et] = 0;
			}
		}
	}

	if(CT_PERSON == card->card_type)
	{
		clear_card_from_list(card);
	}
}

void CYAServerDlg::card_down_mine(std::shared_ptr<Card> card /*Card* card*/ )
{
	card->down_time = CFunctions::systime_to_timet(card->deal_time);
	EVENT_TYPE et = ET_UNKNOWN;
	double limit_val = 0, cur_val = 0;

	if(CT_PERSON == card->card_type){
		CardMap::iterator it_card = mp_card_list_down_person.find(card->card_id);
		if(it_card == mp_card_list_down_person.end()){
			mp_card_list_down_person.insert(make_pair(card->card_id, card)); // 添加到井下卡列表
			if(mp_card_list_down_person.size() > sls_setting.over_count_person && sls_setting.over_count_person != 0){

				string s;
				for (it_card = mp_card_list_down_person.begin();it_card != mp_card_list_down_person.end();it_card++)
				{
					s += it_card->second->card_id;
					s += "&";
				}
				debug_print_syslog(0,"[lemon mp_card_list_down_person:]:%s",s.c_str());

				et = ET_OVER_COUNT_PERSON;
				limit_val = sls_setting.over_count_person;
				cur_val = mp_card_list_down_person.size();
				//deal_alarm_card(card,mp_card_list_over_count_person,true,AF_CARD_OVER_COUNT);
			}
		}
	}else if(CT_VEHICLE == card->card_type|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type){
		CardMap::iterator it_card = mp_card_list_down_vehicle.find(card->card_id);
		if(it_card == mp_card_list_down_vehicle.end()){
			mp_card_list_down_vehicle.insert(make_pair(card->card_id, card));  // 添加到井下卡列表
			//如果井下车辆总数超过系统设置的车辆阈值，则存储车辆超员告警信息
			if(mp_card_list_down_vehicle.size() > sls_setting.over_count_vehicle && sls_setting.over_count_vehicle != 0){
				et = ET_OVER_COUNT_VEHICLE;
				limit_val = sls_setting.over_count_vehicle;
				cur_val = mp_card_list_down_vehicle.size();
				//deal_alarm_card(card,mp_card_list_over_count_vehicle,true,AF_CARD_OVER_COUNT);
			}
		}	
	}

	if(ET_UNKNOWN != et)
	{
		INT64 ev_id = m_event_list[et];
		if(ev_id > 0 ) // 
		{			
			EventMap::iterator it_ev = mp_event_list->find(ev_id);
			if(it_ev != mp_event_list->end())
			{
				it_ev->second->cur_value = cur_val;					
				it_ev->second->is_sent = false;
			}
		}
		else
		{
			INT64 ev_id = CFunctions::GetMicroSecond();
			std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
			ev->status = ES_START;	
			ev->ev_type = et;
			ev->obj_type = OT_MINE;
			ev->cur_time = time(NULL);
			ev->cur_value= cur_val;
			ev->limit_value = limit_val;
			ev->obj_id = "0";
			ev->is_sent = false;
			m_event_list[et] = ev_id;
			store_data_event(ev);
			add_event(ev);
			Sleep(1);
		}
	}

	DeptMap::iterator it_dept = mp_dept_list.find(card->dept_id);
	if(it_dept != mp_dept_list.end()){
		//TRACE(_T("card_id: %s, dept_id: %d.\n"),CA2W(card->card_id.c_str()),card->dept_id);
		if(CT_PERSON == card->card_type){
			CardMap::iterator it_card = it_dept->second->dept_card_list_person.find(card->card_id);
			if(it_card == it_dept->second->dept_card_list_person.end()){
				debug_print_syslog(0,"[dept_person down_mine_insert]%s,deptId:%d",card->card_id.c_str(),card->dept_id);
				it_dept->second->dept_card_list_person.insert(make_pair(card->card_id, card)); 
			}
		}else if(CT_VEHICLE == card->card_type|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type){
			CardMap::iterator it_card = it_dept->second->dept_card_list_vehicle.find(card->card_id);
			if(it_card == it_dept->second->dept_card_list_vehicle.end()){
				it_dept->second->dept_card_list_vehicle.insert(make_pair(card->card_id, card));
			}
		}
	}

	if(CT_PERSON == card->card_type)
	{
		OccLevelMap::iterator it_level = mp_occlevel_list.find(card->dept_id);
		if(it_level != mp_occlevel_list.end())
		{
			CardMap::iterator it_card_lvl = it_level->second->level_card_list_person.find(card->card_id);
			if(it_card_lvl == it_level->second->level_card_list_person.end())
			{
				it_level->second->level_card_list_person.insert(make_pair(card->card_id, card));
			}
		}
	}
	store_data_card(card, RPT_ATTEND_DOWN);
}

void CYAServerDlg::send_sync_reader()
{
	//modified by zhuyf 2017/10/12
	for(SocketMap::iterator it_sock = mp_socket_list.begin(); it_sock != mp_socket_list.end(); ++it_sock){
		send_sync_reader(it_sock->second->dwConnID);
		Sleep(20);
	}

	//time_t cur_time;
	//struct tm local;
	//int wlen = 0;
	//BYTE SendBuffer[LENGTH_SEND_BUF];
	//BYTE bt_tmp;
	//// 遍历发送数据
	//int nPos = 0;

	//SocketMap::iterator it_sock = mp_socket_list.begin();
	//for(; it_sock != mp_socket_list.end(); ++it_sock){
	//	wlen = 0;
	//	cur_time = time(NULL);
	//	memset(SendBuffer, 0, LENGTH_SEND_BUF);
	//	localtime_s(&local, &cur_time);
	//	bt_tmp = local.tm_sec; 
	//	memcpy(&SendBuffer[wlen], &bt_tmp, sizeof(BYTE));
	//	wlen += sizeof(BYTE);
	//	bt_tmp = local.tm_min;
	//	memcpy(&SendBuffer[wlen], &bt_tmp, sizeof(BYTE));
	//	wlen += sizeof(BYTE);
	//	bt_tmp = local.tm_hour;
	//	memcpy(&SendBuffer[wlen], &bt_tmp, sizeof(BYTE));
	//	wlen += sizeof(BYTE);
	//	bt_tmp = local.tm_mday; 
	//	memcpy(&SendBuffer[wlen], &bt_tmp, sizeof(BYTE));
	//	wlen += sizeof(BYTE);
	//	bt_tmp = local.tm_wday;
	//	memcpy(&SendBuffer[wlen], &bt_tmp, sizeof(BYTE));
	//	wlen += sizeof(BYTE);
	//	bt_tmp = local.tm_mon + 1;
	//	memcpy(&SendBuffer[wlen], &bt_tmp, sizeof(BYTE));
	//	wlen += sizeof(BYTE);
	//	bt_tmp = (local.tm_year + 1900)%100;
	//	memcpy(&SendBuffer[wlen], &bt_tmp, sizeof(BYTE));
	//	wlen += sizeof(BYTE);
	//	SendData(it_sock->second->dwConnID , CHAR_SYNC_TIME, wlen, SendBuffer);

	//	Sleep(20);
	//}
}

int CYAServerDlg::send_sync_reader(CONNID dwConnID)
{
	//debug_print_syslog(0,"enter send_sync_reader: %s %d",__FILE__,__LINE__);
	TCHAR szAddress[40];
	int iAddressLen = sizeof(szAddress) / sizeof(TCHAR);
	USHORT usPort;
	if(_server.GetRemoteAddress(dwConnID, szAddress, iAddressLen, usPort)){
		SocketMap::iterator itSock = mp_socket_list.find(szAddress);
		int wlen = 0;
		BYTE SendBuffer[LENGTH_SEND_BUF];
		memset(SendBuffer, 0, LENGTH_SEND_BUF);
		BYTE bt_tmp;

		SYSTEMTIME st;
		GetLocalTime(&st);

		string strlog =  "send sync time: " + CFunctions::TCHAR2string(szAddress) + " , "+ CFunctions::systime2string(st);
		Log::write_log(FILE_TYPE::SYS_S,strlog,true);

		memcpy(&SendBuffer[wlen], &st.wMilliseconds, sizeof(BYTE)*2);
		wlen += sizeof(BYTE)*2;
		bt_tmp = st.wSecond;
		memcpy(&SendBuffer[wlen], &bt_tmp, sizeof(BYTE));
		wlen += sizeof(BYTE);
		bt_tmp = st.wMinute;
		memcpy(&SendBuffer[wlen], &bt_tmp, sizeof(BYTE));
		wlen += sizeof(BYTE);
		bt_tmp = st.wHour; 
		memcpy(&SendBuffer[wlen], &bt_tmp, sizeof(BYTE));
		wlen += sizeof(BYTE);
		bt_tmp = st.wDay;
		memcpy(&SendBuffer[wlen], &bt_tmp, sizeof(BYTE));
		wlen += sizeof(BYTE);
		bt_tmp = st.wDayOfWeek;
		memcpy(&SendBuffer[wlen], &bt_tmp, sizeof(BYTE));
		wlen += sizeof(BYTE);
		bt_tmp = st.wMonth;
		memcpy(&SendBuffer[wlen], &bt_tmp, sizeof(BYTE));
		wlen += sizeof(BYTE);
		bt_tmp = st.wYear%100;
		memcpy(&SendBuffer[wlen], &bt_tmp, sizeof(BYTE));
		wlen += sizeof(BYTE);

		if(itSock != mp_socket_list.end()){
			SendData(dwConnID , CHAR_SYNC_TIME, wlen, SendBuffer);
		}else{
			std::string client_ip = "";
			client_ip = CFunctions::TCHAR2string(szAddress);
			if (client_ip != ""&&wlen > 0)
			{
				SendData(dwConnID , CHAR_SYNC_TIME, wlen, SendBuffer);
			}
		}
	}

	//debug_print_syslog(0,"leave send_sync_reader: %s %d",__FILE__,__LINE__);
	return 0;
}

/*
* 向红绿灯发送心跳包
*
* param
*		无
*
* return
*		成功返回0，失败返回1
*
*/
int CYAServerDlg::send_heart_package()
{
	BYTE sendBuffer[1];
	for (LightMap::iterator it = mp_light_list.begin();it != mp_light_list.end();++it)
	{
		memset(sendBuffer,0,1);
		string strIp = it->second->m_strIP;
		TCHAR* tcIp = CFunctions::c2wc(strIp.c_str());

		CONNID dwConnID = 0;
		SocketMap::iterator it_sock = mp_socket_list.find(tcIp);
		if (it_sock != mp_socket_list.end())
		{
			SendData(it_sock->second->dwConnID,CHAR_HEART_BEAT,0,sendBuffer);
		}
	}

	return 0;
}

void CYAServerDlg::send_call_his_data()
{
	if(g_is_rec_hist){
		if(MessageBox(_T("正在接受收历史数据，请稍后再试"), _T("接收历史数据"), MB_OK) == IDOK){
			return;
		}
	}
	if (MessageBox(_T("确定要接收历史数据吗？"), _T("接收历史数据"), MB_OKCANCEL) != IDOK){
		return;
	}
	UpdateData(FALSE);

	bool bExit = false;
	SocketMap::iterator it_sock = mp_socket_list.begin();
	for(; it_sock != mp_socket_list.end(); ++it_sock){
		//if(it_sock->second->reader_id == m_reader_id_hist && it_sock->second->reader_type == DEVICE_TYPE::DT_CARD_READER){
		if(it_sock->second->findReader(m_reader_id_hist))
		{
			auto r = it_sock->second->get(m_reader_id_hist);
			if (r.reader_type == DEVICE_TYPE::DT_CARD_READER)
			{
				int wlen = 0;
				WORD wchr = CHAR_LOCATEDATAHIS_TDOA;
				BYTE SendBuffer[LENGTH_SEND_BUF];
				memset(SendBuffer, 0, LENGTH_SEND_BUF);			
				SendData(it_sock->second->dwConnID, wchr, wlen, SendBuffer);
				bExit = true;
				break;
			}

		}
	}
	if(!bExit){
	}
}

void CYAServerDlg::OnBnCallHisData()
{
	send_call_his_data();
}

void CYAServerDlg::deal_hist_card_postion()
{
	CardMap::iterator it_card = mp_card_list_all.begin();
	for(; it_card != mp_card_list_all.end(); ++it_card){
		if(it_card->second->is_hist){
			//if(PDT_DOWN == it_card->pos_state){
			if(CT_VEHICLE == it_card->second->card_type|| CT_COALMINING_MACHINE == it_card->second->card_type ||CT_TUNNELBORING_MACHINE == it_card->second->card_type){
				MapInfoMap::iterator it_map = mp_map_list.find(it_card->second->map_id);
				if(it_map != mp_map_list.end()){
					it_map->second->map_card_list_vehicle.insert(make_pair(it_card->first, it_card->second));
					it_card->second->map_scale = it_map->second->map_scale;
				}
				mp_card_list_down_vehicle.insert(make_pair(it_card->first, it_card->second));
				AreaMap::iterator it_area = mp_area_list.find(it_card->second->area_id);
				if(it_area != mp_area_list.end()){
					//进入临界区，防止多个线程同时操作map
					EnterCriticalSection(&m_csAreaList);

					it_area->second->area_card_list_vehicle->insert(make_pair(it_card->first, it_card->second));

					//退出临界区
					LeaveCriticalSection(&m_csAreaList);

					if(0 == it_area->second->over_count_vehicle){
						mp_card_list_forbidden_vehicle->insert(make_pair(it_card->first, it_card->second));
					}
				}
			}else if(CT_PERSON == it_card->second->card_type){
				MapInfoMap::iterator it_map = mp_map_list.find(it_card->second->map_id);
				if(it_map != mp_map_list.end()){
					it_map->second->map_card_list_person.insert(make_pair(it_card->first, it_card->second));
					it_card->second->map_scale = it_map->second->map_scale;
				}
				mp_card_list_down_person.insert(make_pair(it_card->first, it_card->second));
				AreaMap::iterator it_area = mp_area_list.find(it_card->second->area_id);
				if(it_area != mp_area_list.end()){
					it_area->second->area_card_list_person->insert(make_pair(it_card->first, it_card->second));
					if(0 == it_area->second->over_count_person){
						mp_card_list_forbidden_person->insert(make_pair(it_card->first, it_card->second));
					}
				}
			}
		}
	}
}

void CYAServerDlg::deal_his_card_list( std::shared_ptr<Card> card )
{
	if(CT_VEHICLE == card->card_type|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type){
		// 所在地图
		MapInfoMap::iterator it_map = mp_map_list.find(card->map_id);
		if(it_map != mp_map_list.end()){
			it_map->second->map_card_list_vehicle.insert(make_pair(card->card_id, card));
			card->map_scale = it_map->second->map_scale;
		}
		mp_card_list_down_vehicle.insert(make_pair(card->card_id, card));
		// 所在区域
		AreaMap::iterator it_area = mp_area_list.find(card->area_id);
		if(it_area != mp_area_list.end()){

			//进入临界区，防止多个线程同时操作map
			EnterCriticalSection(&m_csAreaList);

			it_area->second->area_card_list_vehicle->insert(make_pair(card->card_id, card));

			//退出临界区
			LeaveCriticalSection(&m_csAreaList);

			if(0 == it_area->second->over_count_vehicle){
				mp_card_list_forbidden_vehicle->insert(make_pair(card->card_id, card));
			}
		}
		// 所在部门
		DeptMap::iterator it_dept = mp_dept_list.find(card->dept_id);
		if(it_dept != mp_dept_list.end()){
			it_dept->second->dept_card_list_vehicle.insert(make_pair(card->card_id, card));
		}
	}else if(CT_PERSON == card->card_type){
		if(PDT_DOWN == card->PosState()){
			MapInfoMap::iterator it_map = mp_map_list.find(card->map_id);
			if(it_map != mp_map_list.end()){
				it_map->second->map_card_list_person.insert(make_pair(card->card_id, card));
				card->map_scale = it_map->second->map_scale;
			}		
			mp_card_list_down_person.insert(make_pair(card->card_id, card));
			// 所在部门
			DeptMap::iterator it_dept = mp_dept_list.find(card->dept_id);
			if(it_dept != mp_dept_list.end()){
				debug_print_syslog(0,"[dept_person histroy_insert]%s,deptId:%d",card->card_id.c_str(),card->dept_id);
				it_dept->second->dept_card_list_person.insert(make_pair(card->card_id, card));
			}
			// 所在岗位
			OccLevelMap::iterator it_lvl = mp_occlevel_list.find(card->level_id);
			if(it_lvl != mp_occlevel_list.end()){
				it_lvl->second->level_card_list_person.insert(make_pair(card->card_id, card));
			}
		}
		AreaMap::iterator it_area = mp_area_list.find(card->area_id);
		if(it_area != mp_area_list.end()){
			it_area->second->area_card_list_person->insert(make_pair(card->card_id, card));
			if(0 == it_area->second->over_count_person){
				mp_card_list_forbidden_person->insert(make_pair(card->card_id, card));
			}
		}
	}
}

void CYAServerDlg::load_his_event_data()
{	
	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	sprintf_s(buf, "SELECT event_id,event_type_id,obj_type_id,obj_id,map_id,area_id,limit_value,cur_value,X,Y,cur_time FROM his_event_data \
				   WHERE event_id IN (SELECT MAX(event_id) FROM his_event_data \
				   WHERE cur_time > (CASE obj_type_id \
				   WHEN 1 THEN DATE_SUB(NOW(),INTERVAL 2 DAY) \
				   WHEN 2 THEN DATE_SUB(NOW(),INTERVAL 2 DAY)\
				   WHEN 4 THEN DATE_SUB(NOW(),INTERVAL 1 MONTH)\
				   WHEN 9 THEN DATE_SUB(NOW(),INTERVAL 2 DAY) \
				   WHEN 10 THEN DATE_SUB(NOW(),INTERVAL 2 DAY) \
				   END) \
				   AND cur_time < NOW()\
				   GROUP BY event_type_id, obj_id) \
				   AND  event_id NOT IN ( SELECT event_id FROM (SELECT * FROM his_event_data WHERE  stat=100) s);");

	pRes = getMysqlRes(buf);
	if(NULL == pRes)
	{
		return ;
	}
	int nRow = 0;
	INT64 ev_id = 0;
	double cur_value = 0;
	double limit_value = 0;
	double x,y=0;
	int obj_type_id ,event_type_id ,map_id , area_id = 0;
	EVENT_TYPE et;
	std::string rec_time, lost_time,obj_id;
	//event_id 0,event_type_id 1,obj_type_id  2,obj_id 3,map_id 4,area_id 5,limit_value 6,cur_value 7,X 8,Y 9,cur_time 10       
	while(pRow = mysql_fetch_row(pRes))
	{
		ev_id = _atoi64(pRow[0]);
		event_type_id = atoi(pRow[1]);
		obj_type_id = atoi(pRow[2]);
		obj_id = pRow[3];
		map_id = atoi(pRow[4]);
		area_id = atoi(pRow[5]);
		limit_value = atof(pRow[6]);
		cur_value = atof(pRow[7]);
		x = atof(pRow[8]);
		y = atof(pRow[9]);
		lost_time = pRow[10];
		rec_time = pRow[10];
		switch (obj_type_id)
		{
		case OT_MINE:
			{
				std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
				ev->status = ES_START;	
				et =  EVENT_TYPE(event_type_id);
				ev->ev_type = et;
				ev->obj_type = OT_MINE;
				API_StringToTime(lost_time, ev->cur_time);
				//ev->cur_time = time(NULL);
				ev->cur_value= cur_value;
				ev->limit_value = limit_value;
				ev->obj_id = obj_id;
				ev->is_sent = false;

				ev->map_id = map_id;
				ev->area_id = area_id;
				m_event_list[et] = ev_id;
				add_event(ev);
				break;
			}
		case  OT_AREA:
			{
				AreaMap::iterator it_Area = mp_area_list.find(area_id);
				if(it_Area != mp_area_list.end())
				{
					it_Area->second->count_area_over_count_person = cur_value - limit_value;
					API_StringToTime(lost_time,it_Area->second->time_over_count_person);

					std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
					ev->status = ES_START;
					API_StringToTime(lost_time, ev->cur_time);
					switch (event_type_id)
					{
					case ET_AREA_OVER_COUNT_VEHICLE:
						it_Area->second->is_area_over_count_vehicle = true;
						break;
					case ET_AREA_OVER_COUNT_PERSON:
						it_Area->second->is_area_over_count_person = true;
						break;
					default:
						break;
					}
					et = EVENT_TYPE(event_type_id);
					ev->ev_type = et;
					ev->obj_type = OT_AREA;
					ev->obj_id = CFunctions::int2string(atoi(obj_id.c_str()));
					ev->map_id = map_id;
					ev->area_id = area_id;
					ev->limit_value = limit_value;
					ev->cur_value = cur_value;
					ev->is_sent = false;

					it_Area->second->m_event_list[et] = ev_id;
					add_event(ev);
				}
				break;
			}
		case OT_DEVICE_READER:
			{
				ReaderMap::iterator it = mp_reader_list.find(atoi(pRow[3]));
				if(it != mp_reader_list.end())
				{
					std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
					ev->status = ES_START;
					et = EVENT_TYPE(event_type_id);
					ev->ev_type = et;
					ev->obj_type = OT_DEVICE_READER;

					ev->obj_id = CFunctions::int2string(atoi(obj_id.c_str()));
					API_StringToTime(lost_time, ev->cur_time);

					ev->map_id = map_id;
					ev->area_id = area_id;
					ev->x = x;
					ev->y = y;

					ev->limit_value = limit_value;
					ev->cur_value = cur_value;
					ev->is_sent = false;

					API_StringToTime(rec_time, it->second->rec_time);
					API_StringToTime(lost_time, it->second->lost_time);
					it->second->reader_state = STATUS_DEVICE_ERROR;
					it->second->m_event_list[et] = ev_id;
					add_event(ev);
				}
				break;
			}
		case  OT_CARD:
			{
				CardMap::iterator it_card = mp_card_list_all.find(obj_id);
				et = EVENT_TYPE(event_type_id);
				if (it_card != mp_card_list_all.end())
				{
					std::shared_ptr<Card> card = it_card->second;
					switch (et)
					{
					case ET_UNKNOWN:
						break;
					case ET_OVER_COUNT_PERSON:
						break;
					case ET_OVER_COUNT_VEHICLE:
						break;
					case ET_AREA_OVER_COUNT_PERSON:
						break;
					case ET_AREA_OVER_COUNT_VEHICLE:
						break;
					case ET_SECTION_OVER_COUNT:
						break;
					case ET_READER_ERROR:
						break;
					case ET_CTRL_READER_ERROR:
						break;
					case ET_LIGHT_ERROR:
						break;
					case ET_READER_CALL:
						break;
					case ET_READER_CALL_CANCEL:
						break;
					case ET_CARD_LOW_POWER:
						break;
					case ET_CARD_LOW_POWER_SERIOUS:
						card->power_state_last = 2;
						break;
					case ET_CARD_OVER_TIME_PERSON:
						card->is_mine_over_time = true;
						API_StringToTime(lost_time,it_card->second->time_over_time);
						card->status_over_time = 1;
						mp_card_list_over_time_person->insert(make_pair(obj_id,card));
						break;
					case ET_CARD_OVER_TIME_VEHICLE:
						card->is_mine_over_time = true;
						API_StringToTime(lost_time,it_card->second->time_over_time);
						card->status_over_time = 1;
						mp_card_list_over_time_vehicle->insert(make_pair(obj_id,card));
						break;
					case ET_CARD_AREA_OVER_TIME_PERSON:
						API_StringToTime(lost_time,card->time_area_over_time);
						card->status_area_over_time = 1;
						card->is_area_over_time = true;
						mp_card_list_area_over_time_person->insert(make_pair(obj_id,card));
						break;
					case ET_CARD_AREA_OVER_TIME_VEHICLE:
						API_StringToTime(lost_time,card->time_area_over_time);
						card->status_area_over_time = 1;
						card->is_area_over_time = true;
						mp_card_list_area_over_time_vehicle->insert(make_pair(obj_id,card));
						break;
					case ET_CARD_AREA_LIMIT_PERSON:
						break;
					case ET_CARD_AREA_LIMIT_VEHICLE:
						break;
					case ET_CARD_AREA_FORBIDDEN_PERSON:
						card->time_area_forbidden = true;
						card->status_area_forbidden = 1;
						mp_card_list_forbidden_person->insert(make_pair(obj_id,card));
						break;
					case ET_CARD_AREA_FORBIDDEN_VEHICLE:
						card->time_area_forbidden = true;
						card->status_area_forbidden = 1;
						mp_card_list_forbidden_vehicle->insert(make_pair(obj_id,card));
						break;
					case ET_CARD_OVER_SPEED:
						card->is_mine_over_speed = true;
						API_StringToTime(lost_time,card->time_over_speed );
						card->status_over_speed = 1;
						mp_card_list_over_speed_vehicle->insert(make_pair(obj_id,card));
						break;
					case ET_CARD_AREA_OVER_SPEED:
						{
							card->is_area_over_speed = true;
							API_StringToTime(lost_time,card->time_area_over_speed );
							card->status_area_over_speed = 1;
							AreaMap::iterator it_area = mp_area_list.find(area_id);
							if (it_area != mp_area_list.end())
							{
								it_area->second->area_card_list_over_speed->insert(make_pair(obj_id,card));
							}

						}
						break;
					case ET_CARD_RUN_THE_RED_LIGHT:
						break;
					case ET_CARD_HELP:
						card->status_help = STATUS_ERROR;
						break;
					case ET_CARD_CALLED:
						break;
					case ET_CARD_PATROL_ERROR:
						break;
					case ET_CARD_LOST:
						break;
					case ET_CARD_DRIVINGFACE_WARNING_AREA:
						break;
					case ET_CARD_NEAR_DRIVINGFACE_VEHICLE:
						break;
					case ET_CARD_NEAR_DRIVINGFACE_OVERCOUNT:
						break;
					case ET_CARD_MOTIONLESS:
						{
							std::shared_ptr<NAMESPACE_POINT::card_interface> ci(card);
							ci->_isMotionless=true;
							mp_card_list_motionless->insert(make_pair(obj_id,card));
							m_carmanage->push_back(ci);
						}
						break;
					case ET_VEHICLE_NEAR_GEOFAULT:
						card->m_warning_point_alarm=true;
						mp_card_geofault_alarm->insert(make_pair(obj_id,card));
						break;
					case CARD_EVENT_COUNT_MAX:
						break;
					default:
						break;
					}

					std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
					ev->status = ES_START;	
					ev->ev_type = et;

					ev->obj_type = OT_CARD;
					ev->obj_id = obj_id;

					API_StringToTime(lost_time,ev->cur_time);
					ev->cur_value = cur_value;
					ev->limit_value = limit_value;

					ev->map_id = map_id;
					ev->area_id = area_id;
					ev->x = x;
					ev->y = y;

					ev->is_sent = false;
					card->m_event_list[et] = ev_id;
					add_event(ev);
				}
				break;
			}
		case OT_DRIVINGFACE_AREA:
			{
				string card_id;
				card_id.clear();
				et = EVENT_TYPE(event_type_id);
				DrivingfaceCardMap::iterator it_df = mp_driving_face_card_list.begin();
				for (;it_df != mp_driving_face_card_list.end();it_df++)
				{
					if (atoi(pRow[3]) == it_df->second->drivingface_id)
					{
						card_id = it_df->first;
						break;
					}
				}
				if (card_id.empty())
				{
					break;
				}
				CardMap::iterator it_card = mp_card_list_all.find(card_id);
				if (it_card != mp_card_list_all.end())
				{
					switch (et)
					{
					case ET_CARD_DRIVINGFACE_WARNING_AREA:
						it_card->second->m_isWarning = true;
						mp_card_warning_point_alarm->insert(make_pair(card_id,it_card->second));
						break;
					case ET_CARD_NEAR_DRIVINGFACE_VEHICLE:
						break;
					case ET_CARD_NEAR_DRIVINGFACE_OVERCOUNT:
						it_card->second->m_CardHasBeenInDrivingfaceAlarm = true;
						break;
					default:
						break;
					}

					std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
					ev->status = ES_START;	
					ev->ev_type = et;

					ev->obj_type = OT_DRIVINGFACE_AREA;
					ev->obj_id = CFunctions::int2string(atoi(obj_id.c_str()));

					API_StringToTime(lost_time,ev->cur_time);
					ev->cur_value = cur_value;
					ev->limit_value = limit_value;

					ev->map_id = map_id;
					ev->area_id = area_id;
					ev->x = x;
					ev->y = y;

					ev->is_sent = false;
					it_card->second->m_event_list[et] = ev_id;
					add_event(ev);
				}
				break;
			}
		default:
			break;
		}
		nRow++;
	}

	mysql_free_result(pRes);
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_LOAD_HIS_READER), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
}
/************************************************************************/
/*    查看是否有权限，工种权限

如果没有则
1,查看掘进机是否启动中
2.判断其eare_id是否相同且和掘进机的area_id相同。   
lemon 2017/07/31*/
/*distance = GetDistance(card_point, landmark_point) *card->map_scale;
/*_point card_point(card->x, card->y, card->z);
/************************************************************************/
void CYAServerDlg::deal_card_drivingface_permission(std::shared_ptr<Card> card)
{
	WorkTypePermissionMap::iterator it_worktype = mp_worktype_permission_list.find(card->vehice_type_id);
	//查看是否在权限工种内
	if (it_worktype == mp_worktype_permission_list.end())
	{
		DrivingfaceCardMap::iterator it_drivingfaceId ;
		//查看是否是掘进机设备
		it_drivingfaceId = mp_driving_face_card_list.find(card->card_id);
		if (it_drivingfaceId != mp_driving_face_card_list.end())
		{
			return ;
		}
		for (it_drivingfaceId = mp_driving_face_card_list.begin();it_drivingfaceId != mp_driving_face_card_list.end();++it_drivingfaceId)
		{
			CardMap::iterator it_card = mp_card_list_all.find(it_drivingfaceId->first);
			if (it_card != mp_card_list_all.end())
			{
				//如果卡进入到了掘进机区域
				if (it_card->second->area_id == card->area_id)
				{
					_point p_drivingface_card(it_card->second->x,it_card->second->y,it_card->second->z);
					_point p_card (card->x,card->y,card->z);
					double dis = GetDistance(p_drivingface_card,p_card)*(it_card->second->map_scale);
					card->setDrivingfaceCulValue(dis);
					card->setDrivingfaceLimitValue(it_drivingfaceId->second->warning_threshold);

					if (dis < it_drivingfaceId->second->warning_threshold)
					{
						if (it_card->second->is_driving_face_start)
						{
							if (!card->m_CardHasBeenInDrivingfaceAlarm)
							{
								card->m_DrivingfaceAlarmFlag = it_drivingfaceId->second->drivingface_id;
								deal_alarm_card(card,mp_card_drivingface_eara_alarm,true,AF_CARD_NEAR_DRRIVINGFACE_VEHICLE);
							}
						}
						else
						{
							if (card->m_CardHasBeenInDrivingfaceAlarm)
							{
								card->m_DrivingfaceAlarmFlag = -1;
								deal_alarm_card(card,mp_card_drivingface_eara_alarm,false,AF_CARD_NEAR_DRRIVINGFACE_VEHICLE);
							}
						}
					}
					else
					{
						//首先判断是否是刚从限制距离出来。
						if (card->m_DrivingfaceAlarmFlag == it_drivingfaceId->second->drivingface_id && card->m_CardHasBeenInDrivingfaceAlarm )
						{
							card->m_DrivingfaceAlarmFlag = -1;
							deal_alarm_card(card,mp_card_drivingface_eara_alarm,false,AF_CARD_NEAR_DRRIVINGFACE_VEHICLE);
						}
					}
					break;		
				}
				else
				{
					//对于不在同一区域的情况下，比如掘进机离区域边界很近的情况  处理。。。
				}

			}
			else
			{
				return ;
			}
		}
	}

}

void CYAServerDlg::deal_card_drivingface_permission(std::shared_ptr<Card> card,int id)
{
	EVENT_TYPE et = ET_UNKNOWN;
	int limit_val = 0, cur_val = 0;

	DrivingfaceCardMap::iterator it_drivingfaceId ;
	//查看是否是掘进机设备
	it_drivingfaceId = mp_driving_face_card_list.find(card->card_id);
	if (it_drivingfaceId != mp_driving_face_card_list.end())
	{
		return ;
	}
	for (it_drivingfaceId = mp_driving_face_card_list.begin();it_drivingfaceId != mp_driving_face_card_list.end();++it_drivingfaceId)
	{
		CardMap::iterator it_card = mp_card_list_all.find(it_drivingfaceId->first);
		if (it_card != mp_card_list_all.end())
		{
			//如果卡进入到了掘进机区域
			if (it_card->second->area_id == card->area_id)
			{
				_point p_drivingface_card(it_card->second->x,it_card->second->y,it_card->second->z);
				_point p_card (card->x,card->y,card->z);
				double dis = GetDistance(p_drivingface_card,p_card)*(it_card->second->map_scale);
				card->setDrivingfaceCulValue(dis);
				card->setDrivingfaceLimitValue(it_drivingfaceId->second->warning_threshold);
				//limit_val 人员超员阈值。
				limit_val = it_drivingfaceId->second->m_overcount;

				if (dis < it_drivingfaceId->second->warning_threshold)
				{
					if (it_card->second->is_driving_face_start)
					{
						it_card->second->mp_list_over_count.insert(make_pair(card->card_id,card));

						int cv = it_card->second->mp_list_over_count.size();
						char buf[LENGTH_SQL] = { 0 };
						sprintf_s(buf,LENGTH_SQL,"[deal_card_drivingface_permission]drivingface_id:%s,card_id:%s,dis:%.3f,warning_threshold:%.3f,limit_val:%d,cur_value:%d --insert",
							it_drivingfaceId->first.c_str(),
							card->card_id.c_str(),
							dis,
							it_drivingfaceId->second->warning_threshold,
							limit_val,
							cv);
						Log::write_log(SYS_S,buf,true);
						//如果
						if (!it_card->second->m_CardHasBeenInDrivingfaceAlarm && cv >= limit_val) //later modify 
						{
							et = ET_CARD_NEAR_DRIVINGFACE_OVERCOUNT;
							cur_val = cv;
							it_card->second->m_CardHasBeenInDrivingfaceAlarm = true;
						}
						else if(it_card->second->m_CardHasBeenInDrivingfaceAlarm && cv < limit_val)
						{
							it_card->second->m_CardHasBeenInDrivingfaceAlarm = false;
							et = ET_CARD_NEAR_DRIVINGFACE_OVERCOUNT;
							cur_val = cv;
						}
					}
					else
					{
						it_card->second->mp_list_over_count.clear();
						if (it_card->second->m_CardHasBeenInDrivingfaceAlarm)
						{
							et = ET_CARD_NEAR_DRIVINGFACE_OVERCOUNT;
							cur_val = 0;
							it_card->second->m_CardHasBeenInDrivingfaceAlarm = false;
						}
					}
				}
				else
				{
					CardMap::iterator it_overcount = it_card->second->mp_list_over_count.find(card->card_id);
					if (it_overcount != it_card->second->mp_list_over_count.end())
					{
						it_card->second->mp_list_over_count.erase(it_overcount);
					}
					int cv = it_card->second->mp_list_over_count.size();
					if (it_card->second->m_CardHasBeenInDrivingfaceAlarm && cv < limit_val)
					{
						it_card->second->m_CardHasBeenInDrivingfaceAlarm = false;
						et = ET_CARD_NEAR_DRIVINGFACE_OVERCOUNT;
						cur_val = cv;
					}
				}

				//do it

				if (ET_UNKNOWN != et)
				{
					INT64 ev_id = it_card->second->m_event_list[et];
					if(ev_id > 0 ) // 
					{	
						EventMap::iterator it_ev = mp_event_list->find(ev_id);	
						if(it_ev != mp_event_list->end())
						{
							it_ev->second->limit_value = limit_val;
							it_ev->second->cur_value = cur_val;					
							it_ev->second->map_id = it_card->second->map_id;
							it_ev->second->area_id = it_card->second->area_id;
							it_ev->second->x = it_card->second->x;
							it_ev->second->y = it_card->second->y;
							it_ev->second->landmarkid = it_card->second->landmark_id;
							it_ev->second->landmarkdirect = it_card->second->landmark_direction;
							it_ev->second->landmarkdist = it_card->second->landmark_dis;
							if(it_card->second->m_CardHasBeenInDrivingfaceAlarm)
							{
								it_ev->second->is_sent = false;
							}
							else
							{
								it_ev->second->status = ES_END;
								it_ev->second->cur_time = time(NULL);
								it_ev->second->is_sent = false;
								store_data_event(it_ev->second);
								add_event(it_ev->second);

								it_card->second->m_event_list[et] = 0;
							}				
						}
					}
					else
					{

						INT64 ev_id = CFunctions::GetMicroSecond();
						std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
						ev->status = ES_START;	
						ev->ev_type = et;
						ev->obj_type = OT_DRIVINGFACE_AREA;
						ev->obj_id = CFunctions::int2string(it_drivingfaceId->second->drivingface_id);
						ev->cur_time = time(NULL);
						ev->cur_value = cur_val;
						ev->limit_value = limit_val;

						ev->map_id = it_card->second->map_id;
						ev->area_id = it_card->second->area_id;
						ev->x = it_card->second->x;
						ev->y = it_card->second->y;

						ev->landmarkid = it_card->second->landmark_id;
						ev->landmarkdirect = it_card->second->landmark_direction;
						ev->landmarkdist = it_card->second->landmark_dis;
						ev->is_sent = false;

						it_card->second->m_event_list[et] = ev_id;

						store_data_event(ev);
						add_event(ev);

					}
				}
				break;

			}
			else
			{
				//对于不在同一区域的情况下，比如掘进机离区域边界很近的情况  处理。。。
			}

		}
		else
		{
			return ;
		}
	}
}

void CYAServerDlg::deal_card_state(std::shared_ptr<Card> card /*Card* card */)
{
	card->get_state();
	card->StateBiz();

	EVENT_TYPE et = ET_UNKNOWN;
	double limit_val = 0, cur_val = 0;
	bool is_alarm = false;
	if (card->p_reader && card->p_reader->pos_state == PDT_DOWN)
	{
		// 电量

	//此卡需要推送电量低告警，并且允许在web端进行设置
	if (card->power_alarm_display)
	{
		if (card->power_state_last >= STATUS_POWER_LOWER_SERIOUS && card->power_state >= STATUS_POWER_LOWER_SERIOUS)
		{
			// 如果上次电量低，且本次电量低,继续电量低告警
			is_alarm = true;
		} 
		else if(card->power_state_last < STATUS_POWER_LOWER_SERIOUS && card->power_state >= STATUS_POWER_LOWER_SERIOUS)
		{
			// 如果上次电量正常，且本次电量低，发送电量低告警		
			is_alarm = true;
		}else if (card->power_state_last >= STATUS_POWER_LOWER_SERIOUS && card->power_state < STATUS_POWER_LOWER_SERIOUS)
		{
			//如果上次电量低，且本次电量正常，结束电量低告警
			is_alarm = false;
		}

		if (is_alarm)
		{
			// 如果推送告警，准备告警数据
			et = ET_CARD_LOW_POWER_SERIOUS;
			card->low_power_time = CFunctions::systime_to_timet(card->deal_time);
			cur_val = 0.2;
		}else{
			// 结束告警
			card->status_power = STATUS_NORMAL;	
			et = ET_CARD_LOW_POWER_SERIOUS;
			cur_val = 1;
		}
		card->power_state_last = card->status_power;

	}else{
		//因为是不推送的卡，所以不管本次的状态是否正常，都会不推送，但要结束掉之前的电量低告警
		if (card->power_state_last >= STATUS_POWER_LOWER_SERIOUS)
		{
			// 如果上次电量低，则结束电量低告警
			is_alarm = false;
			card->status_power = STATUS_NORMAL;	
			et = ET_CARD_LOW_POWER_SERIOUS;
			cur_val = 1;
			card->power_state_last = card->status_power;
		}
	}
	/*debug_print_syslog(0,"[lemon_power_e]cardId:%s,power_state_last:%d,power_state:%d,power_alarm_display:%d",
	card->card_id.c_str(),card->power_state_last,card->power_state,card->power_alarm_display);*/

	if(ET_UNKNOWN != et)
	{
		INT64 ev_id = card->m_event_list[et];
		if(ev_id > 0 )
		{			
			EventMap::iterator it_ev = mp_event_list->find(ev_id);
			if(it_ev != mp_event_list->end())
			{
				it_ev->second->cur_value = cur_val;	
				it_ev->second->map_id = card->map_id;
				it_ev->second->area_id = card->area_id;
				it_ev->second->x = card->x;
				it_ev->second->y = card->y;
				it_ev->second->landmarkid = card->landmark_id;
				it_ev->second->landmarkdirect = card->landmark_direction;
				it_ev->second->landmarkdist = card->landmark_dis;
				if(is_alarm)
				{
					it_ev->second->is_sent = false;
				}
				else
				{
					it_ev->second->status = ES_END;
					it_ev->second->cur_time = time(NULL);
					it_ev->second->is_sent = false;
					store_data_event(it_ev->second);
					add_event(it_ev->second);

					card->m_event_list[et] = 0;
				}				
			}
		}
		else
		{
			if(is_alarm){
				INT64 ev_id = CFunctions::GetMicroSecond();
				std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
				ev->status = ES_START;	
				ev->ev_type = et;
				ev->obj_type = OT_CARD;
				ev->obj_id = card->card_id;
				ev->cur_time = time(NULL);

				ev->map_id = card->map_id;
				ev->area_id = card->area_id;
				ev->x = card->x;
				ev->y = card->y;
				ev->landmarkid = card->landmark_id;
				ev->landmarkdirect = card->landmark_direction;
				ev->landmarkdist = card->landmark_dis;

				ev->is_sent = false;
				card->m_event_list[et] = ev_id;
				store_data_event(ev);
				add_event(ev);
			}
		}
	}

	}
	
	//呼救状态
	EVENT_TYPE et_help = ET_UNKNOWN;
	is_alarm = false;
	//1.如果已经有呼救告警
	//2.web取消告警。status_help && status_help_cancel 置为status_help_dealed
	//3.如果底层已经没有呼救则，取消后，不会再次进行呼救。因为status_help已经不会置为status_error。
	//4.如果底层还在呼救。这时候不管status_help是何种状态，极大的可能是error.status_help_cancel的存在都会取消。
	//并且还要保证等待线程把json传送到前端
	if(card->status_help == STATUS_ERROR && card->status_help_cancel < STATUS_AREA_FORBIDDEN){
		et_help = ET_CARD_HELP;
		limit_val = 0;
		cur_val = 1;
		is_alarm = true;
	}else{
		et_help = ET_CARD_HELP;
		limit_val = 0;
		cur_val = 1;
		is_alarm = false;
	}
	//避免没来得及传送alarm json 到web
	if (card->status_help_cancel >= STATUS_AREA_FORBIDDEN)
	{
		card->status_help_cancel >>= 1;
	}
	//debug_print_syslog(0,"[lemon_call_help]:%s,%d,%s",card->card_id.c_str(),card->status_help,is_alarm?"TRUE":"FALSE");
	if(ET_UNKNOWN != et_help)
	{
		INT64 ev_id = card->m_event_list[et_help];
		if(ev_id > 0)
		{			
			EventMap::iterator it_ev = mp_event_list->find(ev_id);
			if(it_ev != mp_event_list->end())
			{
				it_ev->second->cur_value = cur_val;	
				it_ev->second->map_id = card->map_id;
				it_ev->second->area_id = card->area_id;
				it_ev->second->x = card->x;
				it_ev->second->y = card->y;
				it_ev->second->landmarkid = card->landmark_id;
				it_ev->second->landmarkdirect = card->landmark_direction;
				it_ev->second->landmarkdist = card->landmark_dis;
				if(is_alarm)
				{
					it_ev->second->is_sent = false;
				}
				else
				{
					it_ev->second->status = ES_END;
					it_ev->second->cur_time = time(NULL);
					it_ev->second->is_sent = false;
					add_event(it_ev->second);
					store_data_event(it_ev->second);

					card->status_help = STATUS_NORMAL;
					card->m_event_list[et_help] = 0;
				}				
			}
		}
		else
		{
			if(is_alarm){
				INT64 ev_id = CFunctions::GetMicroSecond();
				std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
				ev->status = ES_START;	
				ev->ev_type = et_help;
				ev->obj_type = OT_CARD;
				ev->obj_id = card->card_id;
				ev->cur_time = time(NULL);

				ev->map_id = card->map_id;
				ev->area_id = card->area_id;
				ev->x = card->x;
				ev->y = card->y;
				ev->landmarkid = card->landmark_id;
				ev->landmarkdirect = card->landmark_direction;
				ev->landmarkdist = card->landmark_dis;

				ev->is_sent = false;
				card->m_event_list[et_help] = ev_id;
				add_event(ev);
				store_data_event(ev);

				Sleep(1);
			}
		}	
	}
	//debug_print_syslog(0,"[lemon_call_help_end]:%s,%d,%s",card->card_id.c_str(),card->status_help,is_alarm?"TRUE":"FALSE");
}
//lemon 2017/08/02
void CYAServerDlg::load_his_card_state()
{
	return ;

	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	sprintf_s(buf, "select ac.card_id, ac.alarm_type_id, ac.start_time from his_alarm_card ac \
				   where not exists(select 1 from his_alarm_card where card_id=ac.card_id and alarm_type_id=ac.alarm_type_id and start_time> ac.start_time) \
				   and ac.end_time is NULL;");
	pRes = getMysqlRes(buf);
	if(NULL == pRes)
	{
		return;
	}
	int nRow = 0;
	std::string start_time;
	string card_id = "";
	CardMap::iterator it;
	while(pRow = mysql_fetch_row(pRes)){
		if (card_id != pRow[0])
		{
			card_id = pRow[0];
			it = mp_card_list_all.find(pRow[0]);
			if(it != mp_card_list_all.end()){
				(it->second->m_event_list)[atoi(pRow[1])] = atoi(pRow[2]);
			}
			nRow++;
		}
		else
		{
			(it->second->m_event_list)[atoi(pRow[1])] = atoi(pRow[2]);
			nRow++;

		}		
	}

	mysql_free_result(pRes);
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_LOAD_HIS_STATE), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
}

EnHandleResult CYAServerDlg::OnPrepareListen( ITcpServer* pSender, SOCKET soListen )
{
	TCHAR szAddress[40];
	int iAddressLen = sizeof(szAddress) / sizeof(TCHAR);
	USHORT usPort;

	pSender->GetListenAddress(szAddress, iAddressLen, usPort);
	//::PostOnPrepareListen(szAddress, usPort);
	return HR_OK;
}

EnHandleResult CYAServerDlg::OnAccept( ITcpServer* pSender, CONNID dwConnID, SOCKET soClient )
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_269);
	BOOL bPass = TRUE;
	TCHAR szAddress[40];
	int iAddressLen = sizeof(szAddress) / sizeof(TCHAR);
	USHORT usPort;

	//TRACE(_T("CYAServerDlg::OnAccept() \r\n"));

	pSender->GetRemoteAddress(dwConnID, szAddress, iAddressLen, usPort);

	return HR_OK;
}

EnHandleResult CYAServerDlg::OnSend( ITcpServer* pSender, CONNID dwConnID, const BYTE* pData, int iLength )
{
	//::PostOnSend(dwConnID, pData, iLength);
	return HR_OK;
}
EnHandleResult CYAServerDlg::OnReceive( ITcpServer* pSender, CONNID dwConnID, const BYTE* pData, int iLength )
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_221);
	ParseData *data = BufferUtility::getInstance()->getItem();
	if(data)
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_222);
		data->handle = this;
		data->dwConnID = dwConnID;
		data->len = iLength;
		memset(data->buf, 0, LENGTH_MSG_4K);
		memcpy(data->buf, pData, iLength);
		//WT_EXECUTELONGFUNCTION 线程间跳转 WT_EXECUTEDEFAULT 执行完一个再执行另一个
		this->parse_data_server(data->buf, data->len, data->dwConnID);
		BufferUtility::getInstance()->releaseItem(data);
	}

	return HR_OK;
}

EnHandleResult CYAServerDlg::OnClose( ITcpServer* pSender, CONNID dwConnID, EnSocketOperation enOperation, int iErrorCode )
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_270);
	::PostMessage(this->GetSafeHwnd(), WM_REMOVE_SOCKET, NULL, (LPARAM)dwConnID);
	return HR_OK;
}

EnHandleResult CYAServerDlg::OnShutdown( ITcpServer* pSender )
{
	return HR_OK;
}

std::shared_ptr<_SOCK> CYAServerDlg::get_socket_by_Id( CONNID dwConnID )
{
	SocketMap::iterator _sock = mp_socket_list.begin();
	for(; _sock != mp_socket_list.end(); ++_sock){
		if(_sock->second->dwConnID == dwConnID){
			return _sock->second;
		}
	}
	return NULL;
}

afx_msg LRESULT CYAServerDlg::OnMsgRefreshIpList(WPARAM wParam, LPARAM lParam)
{
	EnterCriticalSection(&m_csRefreshList);
	m_listctrl_reader.SetRedraw(FALSE);

	m_listctrl_reader.DeleteAllItems();
	SocketMap::reverse_iterator it_sock = mp_socket_list.rbegin();
	for(; it_sock != mp_socket_list.rend(); ++it_sock){
		AddItem(it_sock->second);
		//AddItem(it_sock->second->sip, it_sock->second->reader_id, it_sock->second->state, it_sock->second->reader_type);
	}
	m_listctrl_reader.SetRedraw(TRUE);
	LeaveCriticalSection(&m_csRefreshList);
	return 0;
}

void CYAServerDlg::parse_data_locate_card_his( BYTE* DataBuffer, int& nCurPos, int reader_id, DWORD wTickCount, CString strTime, unsigned short wChr)
{
	// 按时间分组解析
	// 组长度
	WORD wframelen  = 0;
	CFunctions::getWord(DataBuffer, &wframelen, nCurPos);
	nCurPos += sizeof(WORD);
	int nframepos = nCurPos;

	// 数据保存时间 7字节，年，月，周，日，时，分，秒
	BYTE btSec = 0;
	memcpy(&btSec, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btMin = 0;
	memcpy(&btMin, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btHour = 0;
	memcpy(&btHour, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btDay = 0;
	memcpy(&btDay, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btWeek = 0;
	memcpy(&btWeek, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btMonth = 0;
	memcpy(&btMonth, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btYear = 0;
	memcpy(&btYear, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	CString strhistime;
	strhistime.Format(_T("20%.2d-%.2d-%.2d %.2d:%.2d:%.2d"), btYear%100, btMonth, btDay, btHour, btMin, btSec );				

	while(nCurPos - nframepos < wframelen){ // 一组数据
		BYTE btCardType = 0;
		memcpy(&btCardType, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);

		DWORD dwCardId = 0;
		CFunctions::getDWord(DataBuffer, &dwCardId, nCurPos);
		nCurPos += sizeof(DWORD);

		string str_card_id = CFunctions::getstrwithzero(btCardType, 3) + CFunctions::getstrwithzero(dwCardId, 10);
		std::shared_ptr<Card> pCard = std::make_shared<Card>(str_card_id, btCardType, theApp.z_offset);

		pCard->reader_id = reader_id;
		pCard->str_his_time = CFunctions::wc2c(strhistime);
		pCard->reader_tickcount = wTickCount;
		pCard->str_rec_time = CFunctions::wc2c(strTime);

		switch(btCardType)
		{
		case CT_VEHICLE:
		case CT_COALMINING_MACHINE:
		case CT_TUNNELBORING_MACHINE:
		case CT_PERSON:
			{
				//报文时间
				WORD wCardTickCount = 0;
				CFunctions::getWord(DataBuffer, &wCardTickCount, nCurPos);
				nCurPos += sizeof(WORD);

				if(pCard->time_stamp != wCardTickCount)
				{
					pCard->time_stamp_last = pCard->time_stamp;
				}
				pCard->time_stamp = wCardTickCount;

				BYTE btTypeAndPower = 0;
				memcpy(&btTypeAndPower, &DataBuffer[nCurPos], sizeof(BYTE));
				nCurPos += sizeof(BYTE);
				//报文类型
				BYTE btType = 0;
				btType = (btTypeAndPower >>4) & 0x0F;
				//电池电量
				BYTE btPower = 0;
				btPower = btTypeAndPower & 0x0F;
				pCard->ranging_type = btType;
				pCard->power_state = btPower;

				//保留
				nCurPos += sizeof(BYTE);

				//加速度
				BYTE btAcceleration = 0;
				memcpy(&btAcceleration, &DataBuffer[nCurPos], sizeof(BYTE));
				nCurPos += sizeof(BYTE);
				pCard->accelerate_state = btAcceleration;

				//定位时间戳Tsp // 字序
				LONG64 lTime1 = 0;
				BYTE btTemp = 0;
				int nRangingPos = nCurPos;
				memcpy(&btTemp, &DataBuffer[nCurPos], sizeof(BYTE));
				nCurPos += sizeof(BYTE);
				DWORD dwTemp = 0;
				CFunctions::getDWord(DataBuffer, &dwTemp, nCurPos);
				nCurPos += sizeof(DWORD);
				lTime1 = btTemp;
				lTime1 = lTime1 << 32;
				lTime1 |= dwTemp;
				pCard->flying_time = lTime1;

				double dbldist = CFunctions::getDistance(lTime1, CFunctions::TOF);
				pCard->distance = dbldist;

				BYTE btAntenna = 0;
				memcpy(&btAntenna, &DataBuffer[nCurPos], sizeof(BYTE));
				nCurPos += sizeof(BYTE);
				btAntenna = btAntenna & 0xFF;
				pCard->antenna_id = btAntenna;

				if(CHAR_LOCATEDATAHIS_TDOA == wChr ){
					// 分站时间同步序列号 
					WORD wSyncNum = 0;
					CFunctions::getWord(DataBuffer, &wSyncNum, nCurPos);
					nCurPos += sizeof(WORD);
					// 信号强度
					WORD wStrength = 0;
					CFunctions::getWord(DataBuffer, &wStrength, nCurPos);
					nCurPos += sizeof(WORD);
				}
				if(CHAR_LOCATEDATA_HIS_EXTEND == wChr)
				{
					// 信号强度
					WORD wStrength = 0;
					CFunctions::getWord(DataBuffer, &wStrength, nCurPos);
					nCurPos += sizeof(WORD);

					WORD wRxpacc = 0;
					//接受信号功率
					CFunctions::getWord(DataBuffer, &wRxpacc, nCurPos);
					nCurPos += sizeof(WORD);

					double recv_signal_power = 0.0;
					recv_signal_power = 10*log10(wStrength*pow(2,17)/pow(wRxpacc - 64,2)) - 121.74;
				}
				break;
			}
		default:
			{				
				break;
			}						
		}
		store_data_card(pCard, HIS_RAW_DATA);
	}
}

void CYAServerDlg::parse_data_locate_reader_his( BYTE * DataBuffer, int nLen, int& nCurPos, int& reader_id, int& nTick, CString& strtime, unsigned short wChr)
{
	strtime.Format(_T("%s"), COleDateTime::GetCurrentTime().Format(_T("%Y-%m-%d %H:%M:%S")));

	DWORD dwReaderID = 0;
	CFunctions::getDWord(DataBuffer, &dwReaderID, nCurPos);
	nCurPos += sizeof(DWORD);

	WORD wTickCount = 0;
	CFunctions::getWord(DataBuffer, &wTickCount, nCurPos);
	nCurPos += sizeof(WORD);
}

void CYAServerDlg::parse_data_reader_synctime(BYTE *DataBuffer, int nLen, int& nCurPos, WORD wChr)
{
	if(syncmanager.IsOutputLog() != m_log_parse_data) {
		syncmanager.SetOutputLog(m_log_parse_data);
	}

	while(nCurPos < nLen - sizeof(WORD)){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_9);
		DWORD dwReaderID = 0; // 本机分站号
		CFunctions::getDWord(DataBuffer, &dwReaderID, nCurPos);
		nCurPos += sizeof(DWORD);

		BYTE btAnt = 0; // 本机发送天线
		memcpy(&btAnt, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);

		DWORD dwUpperReaderID = 0; // 上级分站号
		CFunctions::getDWord(DataBuffer, &dwUpperReaderID, nCurPos);
		nCurPos += sizeof(DWORD);

		BYTE btUpperAnt = 0; // 上级天线
		memcpy(&btUpperAnt, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);

		WORD wSyncNum = 0; // 序列号
		CFunctions::getWord(DataBuffer, &wSyncNum, nCurPos);
		nCurPos += sizeof(WORD);

		WORD wSyncLevel = 0; // 同步等级
		CFunctions::getWord(DataBuffer, &wSyncLevel, nCurPos);
		nCurPos += sizeof(WORD);

		LONG64 lTime1 = 0, lTime2 = 0;
		BYTE btTemp = 0;
		memcpy(&btTemp, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);
		DWORD dwTemp = 0;
		CFunctions::getDWord(DataBuffer, &dwTemp, nCurPos);
		nCurPos += sizeof(DWORD);
		lTime1 = btTemp; // 本机发送时间戳
		lTime1 = lTime1 << 32;
		lTime1 |= dwTemp;

		btTemp = 0;
		dwTemp = 0;
		memcpy(&btTemp, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);
		CFunctions::getDWord(DataBuffer, &dwTemp, nCurPos);
		nCurPos += sizeof(DWORD);
		lTime2 = btTemp; // 本机接收时间戳
		lTime2 = lTime2 << 32;
		lTime2 |= dwTemp;

		DWORD dwRootReaderID = 0;	// root分站号
		BYTE btRootAnt = 0;			// root天线
		unsigned long long syncRootId = 0;
		/*if(CHAR_READER_SYNC_TIME_ROOT == wChr){
		CFunctions::getDWord(DataBuffer, &dwRootReaderID, nCurPos);
		nCurPos += sizeof(DWORD);
		memcpy(&btRootAnt, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);

		syncRootId = dwRootReaderID;
		syncRootId = (syncRootId << 8) + btRootAnt;
		}*/

		WORD wSignalStrength = 0;	// 信号强度
		WORD wRxpacc = 0;			//rxpacc值
		WORD wReserve = 0;			//预留字节
		double recv_signal_power = 0.0;

		switch (wChr)
		{
		case CHAR_READER_SYNC_TIME_ROOT:
		case CHAR_READER_SYNC_TIME_ROOT_EXTEND:
			CFunctions::getDWord(DataBuffer, &dwRootReaderID, nCurPos);
			nCurPos += sizeof(DWORD);
			memcpy(&btRootAnt, &DataBuffer[nCurPos], sizeof(BYTE));
			nCurPos += sizeof(BYTE);

			syncRootId = dwRootReaderID;
			syncRootId = (syncRootId << 8) + btRootAnt;

			if (CHAR_READER_SYNC_TIME_ROOT_EXTEND == wChr)
			{
				CFunctions::getWord(DataBuffer, &wSignalStrength, nCurPos);
				nCurPos += sizeof(WORD);

				CFunctions::getWord(DataBuffer, &wRxpacc, nCurPos);
				nCurPos += sizeof(WORD);

				recv_signal_power = 10*log10(wSignalStrength*pow(2,17)/pow(wRxpacc - 64,2)) - 121.74;

				CFunctions::getWord(DataBuffer, &wReserve, nCurPos);
				nCurPos += sizeof(WORD);
			}
			break;
		case CHAR_READER_SYNC_TIME_EXTEND:
		case CHAR_READER_SYNC_TIME:
			if (CHAR_READER_SYNC_TIME_EXTEND == wChr)
			{
				//扩展时间同步需要多解析4个字节
				CFunctions::getWord(DataBuffer, &wSignalStrength, nCurPos);
				nCurPos += sizeof(WORD);

				CFunctions::getWord(DataBuffer, &wRxpacc, nCurPos);
				nCurPos += sizeof(WORD);

				recv_signal_power = 10*log10(wSignalStrength*pow(2,17)/pow(wRxpacc - 64,2)) - 121.74;

				CFunctions::getWord(DataBuffer, &wReserve, nCurPos);
				nCurPos += sizeof(WORD);
			}
			break;
		default:
			break;
		}

#ifdef TRACE_MEMORY_SYNCTIMEMSG
		//debug_print_syslog(0, "Local station id:%d, root station id:%d, syncnum:%d, level:%d, send:%I64u, rec:%I64u", 
		//                 dwReaderID, dwRootReaderID, wSyncNum, wSyncLevel, lTime1, lTime2);

		HostServer::SyncTimeMsg msg;
		msg.LocalIdCode(dwReaderID);
		msg.LocalIdCode((msg.LocalIdCode() << 8) + btAnt);
		msg.UpperIdCode(dwUpperReaderID);
		msg.UpperIdCode((msg.UpperIdCode() << 8) + btUpperAnt);
		msg.RootIdCode(dwRootReaderID);
		msg.RootIdCode((msg.RootIdCode() << 8) + btRootAnt);
		msg.SyncNum(wSyncNum);
		msg.SyncLevel(wSyncLevel);
		msg.LocalStationSendTime(lTime1);
		msg.LocalStationReceiveTime(lTime2);

		syncmanager.analyzeSyncMsg(msg);
#endif // TRACE_MEMORY_SYNCTIMEMSG

		if(wSyncLevel == 0){
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_82);
			EnterCriticalSection(&m_csSyncTime);
			umpRootSyncNum[syncRootId] = wSyncNum;
			LeaveCriticalSection(&m_csSyncTime);
		}

		ReaderMap::iterator it = mp_reader_list.find(dwReaderID);
		if(it != mp_reader_list.end()){
			it->second->sync_level = wSyncLevel;
			it->second->sync_rootId = syncRootId;
		}

		if(m_log_parse_data){
			std::string strlog = "";
			char chlog[MAX_LOG_LENGTH] = {0};
			sprintf_s(chlog, "id1:%d, id2:%d, root:%d, sn:%d, level:%d, send:%I64u, rec:%I64u, power:%.2f",
				dwReaderID, dwUpperReaderID, dwRootReaderID, wSyncNum, wSyncLevel, lTime1, lTime2,recv_signal_power);
			strlog = chlog;
			Log::write_log(FILE_TYPE::SYNC_S, strlog, true);
		}
	}
}

int CYAServerDlg::init_antenna_sync()
{
	ReaderMap::iterator itReader = mp_reader_list.begin();
	// 初始化数组，将分站添加到列表，只有一个天线
	for(; itReader != mp_reader_list.end(); ++itReader){
		syncmanager.updateAnchor(itReader->second->reader_id, 1, 
			itReader->second->ant[0]->antenna_x * itReader->second->map_scale, 
			itReader->second->ant[0]->antenna_y * itReader->second->map_scale, 
			itReader->second->ant[0]->antenna_z * itReader->second->map_scale);
	}

	// 根据坐标计算分站间距离
	for (auto it = syncmanager._anchors.begin(); it != syncmanager._anchors.end(); it++)
	{
		for (auto it2 = syncmanager._anchors.begin(); it2 != syncmanager._anchors.end(); it2++)
		{
			if(it != it2)
			{
				double d = sqrt(pow((it->second.x - it2->second.x), 2)
					+ pow((it->second.y - it2->second.y), 2) 
					+ pow((it->second.z - it2->second.z), 2)) * 10000 / (2.99702547 * 15.65);
				syncmanager.updateDistance(it->first >>8, it->first & 0xFF, it2->first >> 8, it2->first & 0xFF,d);
			}
		}
	}
	return 0;
}

/*
*	此卡是否在主巷道内
*
*	param
*		pCard		卡对象
*
*	return
*		在主巷道返回true，否则返回false
*
*/
bool CYAServerDlg::isInMainTunel(std::shared_ptr<Card> pCard)
{
	bool bRet = false;
	int nMapId = 0;
	nMapId = pCard->map_id;

	MapInfoMap::iterator it_map = mp_map_list.find(nMapId);
	if (it_map == mp_map_list.end())
	{
		return bRet;
	}
	_point p;
	p.x = pCard->x;
	p.y = pCard->y;
	p.z = pCard->z;

	for (SectionMap::iterator it_section = it_map->second->map_section_list.begin();it_section != it_map->second->map_section_list.end();++it_section)
	{
		if (it_section->second->IsInPolygon(p))
		{
			bRet = true;
			break;
		}
	}

	return bRet;
}

int CYAServerDlg::getTunelProperty(std::shared_ptr<Card> pCard)
{
	bool bRet = false;
	int nMapId = 0;
	nMapId = pCard->map_id;

	MapInfoMap::iterator it_map = mp_map_list.find(nMapId);
	if (it_map == mp_map_list.end())
	{
		return bRet;
	}

	_point p;
	p.x = pCard->x;
	p.y = pCard->y;
	p.z = pCard->z;

	SectionMap::iterator it_section = it_map->second->map_section_list.begin();
	for (;it_section != it_map->second->map_section_list.end();++it_section)
	{
		if (it_section->second->IsInPolygon(p))
		{
			bRet = true;
			break;
		}
	}

	int nProperty = 0;
	if (it_section != it_map->second->map_section_list.end())
	{
		nProperty = it_section->second->m_nProperty;
	}

	return nProperty;
}

void CYAServerDlg::AnalysisAlgoFailedData(int interval  /*=60000*//*std::shared_ptr<Card> pCard*/)
{
	std::string strLog = "";

	//存储数据到数据库中
	DWORD cur_time = ::GetTickCount();
	if (cur_time - g_ullCurTime > interval)
	{
		SYSTEMTIME st;
		GetLocalTime(&st);
		std::string strCurTime = "";
		if (CFunctions::CheckSystemTimeValid(st))
		{
			strCurTime = CFunctions::localsystime2string(st);
		}

		//总的定位信息状态的输出
		char chLog[LENGTH_SQL] = {0};

		unsigned int counts[ALGO_LOC_TOTAL] = {0};
		for (int i = 0; i < ALGO_LOC_TOTAL;i++)
		{
			if (g_nAlgoFailedCounts[i] > 0)
			{
				char log[LENGTH_SQL] = {0};
				sprintf_s(log,LENGTH_SQL,"AlgoLocType: %d , nCounts: %d, ",i,g_nAlgoFailedCounts[i]);

				strcat_s(chLog,LENGTH_SQL,log);
			}

			counts[i] = g_nAlgoFailedCounts[i] - g_nAlgoFailedCycleCounts[i];
		}
		g_ullCurTime = ::GetTickCount();

		if (m_log_locate_data)
		{
			std::string strLog = chLog;
			Log::write_log(FILE_TYPE::ALGO_S,strLog,true);
		}
	}
}

void CYAServerDlg::ReadTdoaDistFile()
{
	ifstream in;
	in.open("D:/5.log");

	if (!in.is_open())
	{
		return;
	}

	std::shared_ptr<ReceiveDataMap> pRdm = std::make_shared<ReceiveDataMap>();
	char pch[200] = {0};
	double dMapScale = 1;

	std::shared_ptr<Card> card = std::make_shared<Card>("",0, theApp.z_offset);
	card->set_reader_path(mp_reader_path_list_tof, mp_reader_path_list_tdoa);
	card->m_nFilterType = FILTER_KALMAN;
	card->EnableFilter(FILTER_KALMAN);
	card->map_scale = dMapScale;
	card->ranging_type = LOCATEDATATYPE::LDT_TDOA;
	card->accelerate_state = 1;
	card->card_type = CT_PERSON;

	while (!in.eof())
	{
		in.getline(pch,200);
		string data = pch;
		stringstream sout;

		std::vector<std::string> metaDatas = CFunctions::split(data,",",true);
		std::shared_ptr<_coordinate> dist = std::make_shared<_coordinate>();
		for (int i=0;i<metaDatas.size();i++)
		{	
			std::string meta = metaDatas[i];

			std::vector<std::string> vtMeta = CFunctions::split(meta,":",true);
			std::vector<std::string> vtReader;

			switch(i){
			case 0:
				{
					int len = vtMeta.size() - 1;
					//分站信息
					vtReader = CFunctions::split(vtMeta[len],"-",true);
					dist->reader_id = atoi(vtReader[0].c_str());

					dist->syncRootId = 0;
					dist->antenna_id = 1;
				}
				break;
			case 1:
				dist->sync_num = atoi(vtMeta[1].c_str());
				break;
			case 2:
				break;
			case 3:
				break;
			case 4:
				//时间戳值
				sout<<vtMeta[1];
				sout>> dist->tt;
				break;
			case 5:
				break;
			case 6:
				//x
				dist->x = atof(vtMeta[1].c_str());
				break;
			case 7:
				//y
				dist->y = atof(vtMeta[1].c_str());
				break;
			case 8:
				//z
				dist->z = atof(vtMeta[1].c_str());
				break;
			case 9:
				//卡的ct号
				dist->t =  atoi(vtMeta[1].c_str());
				break;
			case 10:
				//卡号
				card->card_id = vtMeta[1];
				break;
			default:
				break;
			}
		}

		dist->acce_state = card->accelerate_state;
		dist->acce_state_last = card->accelerate_state_last;
		dist->ins_direction = card->ins_direction;
		dist->dimension = _2D;

		//card->add_dist(dist);

		if (card->m_afmData.bStatus)
		{
			AnalysisAlgoFailedData(5);
			card->m_afmData.bStatus = false;
		}

		if(card->x != card->last_x || card->y != card->last_y){
			std::string strlog = "";
			char chlog[MAX_LOG_LENGTH] = {0};
			sprintf_s(chlog, "card_id: %s, cx: %f, cy: %f, cz: %f, clx: %f, cly: %f, v: %f, ct: %d",
				card->card_id.c_str(),
				card->x, card->y, card->z, card->last_x, card->last_y, card->get_speed(), card->time_stamp_cal);
			strlog = chlog;
			Log::write_log(FILE_TYPE::DISTXX_S, strlog, true);

			card->last_x = card->x;
			card->last_y = card->y;
			card->last_z = card->z;
		}
	}
	in.close();
}

int CYAServerDlg::ReadTofDistFile()
{
	ifstream in;

	in.open("D:/new_6.log");

	if (!in.is_open())
	{
		return 1;
	}
	std::shared_ptr<ReceiveDataMap> pRdm = std::make_shared<ReceiveDataMap>();
	char pch[500] = {0};
	double dMapScale = 2;

	std::shared_ptr<Card> card = std::make_shared<Card>("0010000000156",1, theApp.z_offset);
	card->set_reader_path(mp_reader_path_list_tof, mp_reader_path_list_tdoa);
	card->m_nFilterType = FILTER_KALMAN;
	card->EnableFilter(FILTER_KALMAN);
	card->map_scale = dMapScale;
	card->ranging_type = LOCATEDATATYPE::LDT_TOF;
	card->card_type = CT_VEHICLE;

	std::shared_ptr<Reader> pReader = nullptr;
	ReaderMap::iterator it_reader = mp_reader_list.find(202);
	pReader = it_reader->second;
	card->set_reader(pReader);

	while (!in.eof())
	{
		in.getline(pch,500);
		string data = pch;
		stringstream sout;

		std::vector<std::string> metaDatas = CFunctions::split(data,",",true);
		if (metaDatas.size() == 0)
		{
			continue;
		}
		std::shared_ptr<_coordinate> dist = std::make_shared<_coordinate>();
		std::string card_id = "";
		for (int i = 2;i < metaDatas.size();i++)
		{	
			std::string meta = metaDatas[i];

			std::vector<std::string> vtMeta;
			//if(i>0){
			vtMeta = CFunctions::split(meta,":",true);
			//}
			switch(i-2){
			case 0:
				// 分站号
				dist->reader_id = atoi(vtMeta[1].c_str());
				break;
			case 1:
				// 天线号
				dist->antenna_id = atoi(vtMeta[1].c_str());
				break;
			case 2:
				// ct
				dist->t = atoi(vtMeta[1].c_str());
				break;
			case 3:
				dist->d = atof(vtMeta[1].c_str());
				break;
			case 4:
				dist->x = atof(vtMeta[1].c_str());//*dMapScale
				break;
			case 5:
				dist->y = atof(vtMeta[1].c_str());//*dMapScale
				break;
			case 6:
				dist->z = atof(vtMeta[1].c_str());//*dMapScale
				break;
			case 7:
				card_id = vtMeta[1];
				break;
			case 8:
				dist->dimension = atoi(vtMeta[1].c_str());
				break;
			case 9:
				dist->a =  atoi(vtMeta[1].c_str());
				break;
			case 10:
				//rsp =  atof(vtMeta[i].c_str());
				break;
			case 11:
				//分站时间
				//dist->cur_time =  vtMeta[i].c_str();
				break;
			case 12:
				//原始包解析时间
				//dist->a =  atoi(vtMeta[i].c_str());
				break;
			}
		}
		card->time_stamp_cal = dist->t;
		card->card_id = card_id;
		//card->add_dist(dist);

		if(m_log_locate_data)
		{
			char chlog[MAX_LOG_LENGTH] = {0};
			std::string strlog = "";

			if(card->x != card->last_x || card->y != card->last_y){
				std::string ltslog = "";
				memset(chlog,0,MAX_LOG_LENGTH*sizeof(char));
				std::string strReaderTime = "";
				std::string strAlgoTime = "";
				if (card->p_reader)
				{
					strAlgoTime = CFunctions::time_t2string(card->time_last_tof);
				}
				sprintf_s(chlog,"card_id: %s,ct: %d, cx: %.2f, cy: %.2f, cz: %.2f, clx: %.2f,fly: %.2f,cv: %f, algo_time: %s, errx: %.3f, erry: %.3f",
					card->card_id.c_str(),card->time_stamp_cal,card->x, card->y, card->z,card->last_x,card->last_y,card->get_speed(),strAlgoTime.c_str(), card->error_locate.x, card->error_locate.y);
				ltslog = chlog;
				Log::write_log(FILE_TYPE::LOCATE_TOF_S,ltslog,true);

				card->last_x = card->x;
				card->last_y = card->y;
				card->last_z = card->z;
			}
		}
	}
	in.close();

	return 0;
}

/*
* 生成当用户登陆时，返回给前端所有的模拟数据
*
* param
*		无
*
* return
*		0正常，非0失败
*
*/
int CYAServerDlg::TestGenerateAllDataJson()
{
	//所有卡的坐标以及特殊区域升井

	int i = 0;
	for (CardMap::iterator it_card = mp_card_list_all.begin();it_card != mp_card_list_all.end(); ++it_card)
	{
#if 0
		it_card->second->x = CFunctions::random(4000,4200);
		it_card->second->y = CFunctions::random(300,400);
#endif
		it_card->second->map_id = 5;
		if (it_card->second->x > 4100)
		{
			it_card->second->PosState(PDT_UP);
			it_card->second->area_id = 5;
		}else{
			it_card->second->area_id = 6;
		}

		i++;
	}

	//构造event
	for (int i=0;i<3;i++)
	{
		INT64 ev_id = CFunctions::GetMicroSecond();
		std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
		ev->status = ES_START;
		ev->ev_type = ET_CARD_PATROL_ERROR;
		ev->obj_type = OT_CARD;
		switch (i)
		{
		case 0:
			ev->obj_id = "0020000001062";
			ev->x = 4000;
			ev->y = 300;
			break;
		case 1:
			ev->obj_id = "0020000001063";
			ev->x = 4100;
			ev->y = 310;
			break;
		case 2:
			ev->obj_id = "0020000001064";
			ev->x = 4200;
			ev->y = 320;
			break;
		}
		ev->cur_time = time(NULL);
		ev->map_id = 5;
		ev->area_id = 5;

		ev->is_sent = false;
		add_event(ev);
		Sleep(1);
	}

	return 0;
}

int CYAServerDlg::TestPersonOnCardJson()
{
	map<string,OnVehicleData> real_on_card_data;

	int vehicle_size = 3;
	int start_vehicle_id = 1;
	int person_size = 5;
	int start_person_id = 1;
	for (int i = 0;i < vehicle_size;i++)
	{
		string str_card_id = CFunctions::getstrwithzero(2, 3) + CFunctions::getstrwithzero(start_vehicle_id+i, 10);
		OnVehicleData ovd;
		for(int j = 0;j < person_size;j++){
			string str_person_id = CFunctions::getstrwithzero(1, 3) + CFunctions::getstrwithzero(start_person_id+j, 10);
			ovd.counts++;
			ovd.person_cards.insert(std::make_pair(str_person_id,j%2));
		}
		real_on_card_data.insert(std::make_pair(str_card_id,ovd));
	}

	get_json_person_on_car(real_on_card_data);

	return 0;
}

void CYAServerDlg::parse_data_server( const BYTE * pData, int nLen, CONNID dwConnId )
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_92);
	EnterCriticalSection(&m_csParseDataServer);
	string tmpbuf = "";
	string ip = get_ip_by_id(dwConnId);
	formatByteArray_s(tmpbuf, ip,const_cast<BYTE*>(pData), nLen);
	//debug_print_syslog(0,"[parse_data_server],pData&%s&%d&",tmpbuf.c_str(),nLen);
	Log::write_log(FILE_TYPE::KALMAN_S,tmpbuf.c_str(),false);

	int read_length = 0;
	int pkg_len = 0;
	std::shared_ptr<BYTE> Buf(new BYTE[LENGTH_MSG_1M],[](BYTE* Buf){delete[] Buf;});
	BYTE* buf = Buf.get();

	if(buf == nullptr){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_93);
		LeaveCriticalSection(&m_csParseDataServer);
		return;
	}

	memset(buf, 0, LENGTH_MSG_1M);

	TCHAR szAddress[40];
	int iAddressLen = sizeof(szAddress) / sizeof(TCHAR);
	USHORT usPort;
	if(	_server.GetRemoteAddress(dwConnId, szAddress, iAddressLen, usPort)){
		SocketBufferMap::iterator it = mp_socket_buffer_list.find(szAddress);
		if(it != mp_socket_buffer_list.end()){ 
			// 有此socket数据
			if(nLen + it->second->wReadLen > LENGTH_MSG_1M){
				// 删除此元素
				it->second->wLen = 0;
				it->second->wReadLen = 0;
				it->second->dwConnID = dwConnId;
				mp_socket_buffer_list.erase(it);
				LeaveCriticalSection(&m_csParseDataServer);
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_94);
				return ;
			}

			if(it->second->wReadLen > 0){
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_95);
				//将缓存内的数据拷贝到buf中
				memcpy(buf, it->second->pData, it->second->wReadLen);
			}
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_96);
			//将收到的数据拷贝到buf中
			memcpy(buf + it->second->wReadLen, pData, nLen);
			//it->second->wReadLen += nLen;
			nLen += it->second->wReadLen;
		}else{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_97);
			memcpy(buf, pData, nLen);
		}

		while (read_length < nLen){
			//pkg_len是每一包数据的长度
			pkg_len = MAKEWORD(buf[read_length + 1], buf[read_length]);
			pkg_len += sizeof(WORD); // 长度
			//debug_print_syslog(0,"[parse_data_server while]pkg_len:%d,read_length:%d,nLen:%d",pkg_len,read_length,nLen);
			if(read_length + pkg_len > nLen){
				// 有不完整包，溢出，保留与下个包合并
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_271);
				break; 
			}
			//将完整包送出
			ParseData *data = BufferUtility::getInstance()->getItem();
			if(data){
				data->handle = this;
				data->dwConnID = dwConnId;
				data->len = pkg_len;
				memset(data->buf, 0, LENGTH_MSG_4K);
				//由于存在pkg_len大于LENGTH_MSG_4K的情况，导致memcpy出错的问题；
				//原因猜测可能是第三方库缓存过大再发送过来的原因
				if(pkg_len > LENGTH_MSG_4K){
					LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_272);
					if(it != mp_socket_buffer_list.end()){ 
						// 应从列表删除
						it->second->wLen = 0;
						it->second->wReadLen = 0;
						it->second->dwConnID = dwConnId;
						mp_socket_buffer_list.erase(it);
					}

					BufferUtility::getInstance()->releaseItem(data);

					LeaveCriticalSection(&m_csParseDataServer);
					return;
				}
				//如果缓存队列中有，而此时是构成了完整包，则删除缓存队列
				if(it != mp_socket_buffer_list.end()){ 
					// 应从列表删除
					it->second->wLen = 0;
					it->second->wReadLen = 0;
					it->second->dwConnID = dwConnId;
					mp_socket_buffer_list.erase(it);
					it = mp_socket_buffer_list.find(szAddress);
				}

				memcpy(data->buf, buf + read_length, pkg_len);
				//QueueUserWorkItem(_parse_package_data, (LPVOID)data, WT_EXECUTEDEFAULT);
				//send thread message
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_98);
				send_tcp_thread_message(data);
			}
			else
			{
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_273);
				//debug_print_syslog(0,"ParseData malloc is NULL");
			}
			read_length += pkg_len;
		}

		if(read_length >= nLen){ //没剩下数据, 直接解析
			if(it != mp_socket_buffer_list.end()){
				it->second->wLen = 0;
				it->second->wReadLen = 0;
				it->second->dwConnID = dwConnId;
				mp_socket_buffer_list.erase(it);
			}
		}else{ 
			// 有剩余数据，保存起来
			if(it != mp_socket_buffer_list.end()){
				try{
					if(it->second->wReadLen > 0){
						memset(&it->second->pData[it->second->wReadLen], 0, LENGTH_MSG_1M - it->second->wReadLen);
					}
				}catch(...){
					int tt = it->second->wReadLen;
				}
				try{
					memcpy(&it->second->pData[it->second->wReadLen], buf + read_length, nLen - read_length);
				}catch(...){
					int tt = it->second->wReadLen;
				}
				it->second->wReadLen += nLen - read_length;
			}else{
				std::shared_ptr<_SOCKET_BUFFER> _sockbuf = std::make_shared<_SOCKET_BUFFER>();
				if(_sockbuf){
					_sockbuf->wReadLen = 0;
					_sockbuf->dwConnID = dwConnId;
					_sockbuf->wLen = pkg_len;
					memset(_sockbuf->pData, 0, LENGTH_MSG_1M);
					memcpy(_sockbuf->pData, buf + read_length, nLen - read_length);
					_sockbuf->wReadLen += nLen - read_length;
					mp_socket_buffer_list.insert(make_pair(szAddress, _sockbuf));
				}
			}
		}
	}

	LeaveCriticalSection(&m_csParseDataServer);
}
void CYAServerDlg::iksdk_db(const std::shared_ptr<Card> card)
{
	if (PDT_UP == card->p_reader->pos_state)
	{
		time_t now = time(0);
		if (now - card->m_dbTimeInterval > 5)
		{
			EVENT_TYPE et= ET_CARD_LOW_POWER_SERIOUS;
			INT64 ev_id = card->m_event_list[et];
			int f = ev_id > 0 ? 1:0;
			std::string st = CFunctions::time_t2string(now);
			char nsql[256]={0};
			const char*sql="REPLACE INTO his_att_interface (staff_id,card_id,reader_id,staff_name,dept_name,upt_time,low_power_warn) VALUES (%d,%s,%d,'%s','%s','%s',%d);";
			sprintf_s(nsql,256,sql,card->id,card->card_id.c_str(),card->p_reader->reader_id,card->m_staffName.c_str(),
				card->m_deptName.c_str(), st.c_str(),f);
			m_qsmSQL->AddString(nsql);
			debug_print_syslog(0,"iksdk:%s==[%d]",nsql,f);
			card->m_dbTimeInterval=now;
		}
	}
}
void CYAServerDlg::deal_card_msg( std::shared_ptr<Card> card/*Card* card*/, bool is_hist /*= false*/ )
{
	//debug_print_syslog(0,"enter deal_card_msg: %s %d",__FILE__,__LINE__);
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_3);
	if(!card->is_registered)
	{
		debug_print_syslog(0, "card not registered: %s", card->card_id.c_str());
		return ;
	}
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_65);
	if(!is_hist){
		//cal_card_position_by_msg(card);
		if (card->no_need_add_dist)
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_277);
			card->cal_pos_by_cache();
			card->no_need_add_dist = false;
			card->package_is_over = false;
		}else{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_292);
			cal_card_position_by_msg(card);
		}
	}
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_2);
	//处理惯导数据校准,将所有卡的校准数据按分站归类
	/*if (LOCATEDATATYPE::LDT_TOF_INS == card->ranging_type)
	{
		
	if (card->is_deal_by_algo)
	{
	get_ins_cal_list();
	card->is_deal_by_algo = false;
	}
	}*/

	::GetLocalTime(&card->deal_time);
	if(LT_READER == theApp.locate_type){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_130);
		time_t cur_time = time(NULL);
		time_t c_time = CFunctions::systime_to_timet(card->deal_time);
		if(difftime(cur_time, c_time) <30){
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_131);
			return ;
		}
	}
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_4);

	if (card->last_x != card->x || card->last_y != card->y)
	{
		if (card->card_type != CT_PERSON)
			card->make_arg();
		
		card->last_x = card->x;
		card->last_y = card->y;
		card->m_last_time=card->m_ct_time;
		card->b_pos_change = true;
	}
	else
	{
		if (card->card_type == 0x01 && (card->status_help == STATUS_ERROR || card->status_help == STATUS_HELP_DEALED))
		{
			deal_card_state(card);
		}
		card->b_pos_change = false;
		//return ;
	}
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_6);
	if(CFunctions::TOF == card->ranging_type)
	{
		if (card->p_reader)
		{
			debug_print_syslog(0, "tof location: %s, %d, %.4f, %.4f, %d, %d,%.3f,%lld,%d",
				card->card_id.c_str(), card->time_center_stamp, card->x, card->y,
				card->b_pos_change ? 1 : 0, card->p_reader->pos_state,card->get_speed(),card->m_ct_time,card->accelerate_state);
		}else{
			//debug_print_syslog(0,"p_reader is null. card_id: %.s",card->card_id.c_str());
		}
	}

	// 掘进机
	DrivingfaceCardMap::iterator it_driving = mp_driving_face_card_list.find(card->card_id);
	if(it_driving != mp_driving_face_card_list.end())
	{
		if(m_log_raw_data)
		{
			save_raw_data_card_tof(card);
		}

		deal_card_drivingface_real(card,it_driving->second);
		return ;
	}else{
		//debug_print_syslog(0,"[It can't find %s object from drivingface_card_list ]",card->card_id.c_str());
	}
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_5);
	iksdk_db(card);
	//判断井下和区域是否超时
	if(card->b_pos_change || PDT_UP == card->p_reader->pos_state) // 坐标不变化，不走业务
	{ 
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_109);
		std::shared_ptr<NAMESPACE_POINT::card_interface> ci(card);
		//更新geohash表里的卡位置信息
		m_carmanage->update(card->getX(),card->getY(),card->card_id);
		if(card->b_pos_change && card->card_type == CT_PERSON)
		{
			//如果人卡的位置发生了变化，执行如下一人带多卡的判断
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_275);
			set_card_pos_state(card);
			m_carmanage->uwb_HandleMoreCard(ci);
			m_carmanage->determineCard(ci);
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_276);
		}

		if (CT_VEHICLE == card->card_type|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type)
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_288);
			m_carmanage->handleRule(ci);
			std::shared_ptr<RunRedLight> runredlight = m_carmanage->check_run_red_light(ci);
			if (runredlight != nullptr)
			{
				runredlight->m_vehicle_id = card->id;
				//store_data_run_red_light(card,runredlight);
			}
			deal_run_red_light_alarm(card,runredlight);
			deal_over_speed(card);
			m_carmanage->resetTrafficGroup();
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_289);
		}
		GetLandmarkInfo(card);
		//当没在猴车上时，则保存坐标。
		if (!determine_Save_Point_Or_Not(card))
		{
			//debug_print_syslog(0,"[framework normal]cardId:%s",card->card_id.c_str());
			save_card_postion(card);
		}
		
		card_enter_map(card); // 切换地图
		debug_print_syslog(0,"card before card_enter_area, card: %s, area_id: %d",card->card_id.c_str(),card->area_id);
		card_enter_area(card);//
		debug_print_syslog(0,"card after card_enter_area, card: %s, area_id: %d",card->card_id.c_str(),card->area_id);

		card_deal_other_business(card);

		deal_simulate_card(card);

		//卡升入井处理
		card_enter_mine(card);
		//卡状态处理
		deal_card_state(card);

		Calc_CoalMining_RegularCycleRate(card);
		//处理工作面司机和车卡距离计算和报警
		deal_vehicle_driver_alarm(card);
		//查看是否进入掘进机警戒区
		//这里话是不是要考虑用户配置展示数据的功能
		//lemon 2017/07/31
		//deal_card_drivingface_permission(card,true);
		//if (card->card_type == CT_VEHICLE)
		//{
		//	deal_traffic_lights(card);
		//	select_pos_output(card);
		//}
		card->isdealed = true;
		if(LT_READER != theApp.locate_type){
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_133);
			card->issent = false;
		}
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_132);
	}
	else
	{
		//在井下，而且位置没有变化，有可能是没有解析出来位置坐标，所以没办法进行人员考勤入库操作。这里直接进行判断是否考勤开始
		if (card->card_type==CT_PERSON)
		{
			debug_print_syslog(0,"[card_up_mine:%s]under the mine,the card's position is not change.%d...%d  %d  %d",card->card_id.c_str(),card->p_reader->pos_state,card->area_id,card->pos_state,card->pos_state_old);
			set_card_pos_state(card);//根据分站属性作考勤状态处理
			card_enter_mine(card);    //然后判断是否入井
		}
	}
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_4);
	//debug_print_syslog(0,"leave deal_card_msg: %s %d",__FILE__,__LINE__);
}

int CYAServerDlg::store_data_run_red_light(std::shared_ptr<Card> card,std::shared_ptr<RunRedLight> runredlight)
{
	char sql[LENGTH_SQL] = {'\0'};
	sprintf_s(
		sql, 
		LENGTH_SQL,
		"insert IGNORE into his_traffic_red_light (vehicle_id,cur_time,light_id,driver_id) values('%d','%s',%d,'%s');",
		runredlight->m_vehicle_id,
		runredlight->m_time.c_str(),
		runredlight->m_light_id,
		card->driver_id.c_str());

	execute_sql(sql);

	return 0;
}

void CYAServerDlg::deal_run_red_light_alarm(std::shared_ptr<Card> card,std::shared_ptr<RunRedLight> runredlight)
{
	bool isStart =false;
	if (runredlight!=nullptr )
	{
		isStart =true;
	}

	//告警
	INT64 ev_id = card->m_event_list[ET_RUN_RED_LIGHT];
	std::shared_ptr<YaEvent> ev;
	if (  ev_id ==0 && isStart )
	{
		ev_id = CFunctions::GetMicroSecond();
		ev = std::make_shared<YaEvent>(ev_id);
		ev->status = ES_START;
		ev->ev_type = ET_RUN_RED_LIGHT;
		ev->obj_type = OT_CARD;
		ev->obj_id = card->card_id;
		ev->map_id = card->map_id;
		ev->area_id = card->area_id;
		ev->x =card->x;
		ev->y =card->y;
		ev->limit_value = 0;
		ev->cur_value = runredlight->m_group_id;
		card->m_event_list[ET_RUN_RED_LIGHT] = ev_id;
	}
	else if (ev_id >0 && !isStart  )
	{
		EventMap::iterator it_ev = mp_event_list->find(ev_id);
		if (it_ev != mp_event_list->end())
		{
			ev = it_ev->second;
			ev->status = ES_END;
			card->m_event_list[ET_RUN_RED_LIGHT] = 0;
		}
		else
		{
			return;
		}

	}
	else
	{
		return;
	}

	ev->cur_time = time(NULL);
	ev->is_sent = false;

	store_data_event(ev);
	add_event(ev);
	if (isStart)
	{
		debug_print_syslog(0,"[event warning: the vehicle is running red lights ] vehicler_id: %d.",card->id);
	}
	else
	{
		debug_print_syslog(0,"[event warning: RUN_RED_LIGHT waring is canceled ] vehicler_id: %d.",card->id);
	}	
}

void CYAServerDlg::find_regularcyclerate_startpoint(CoalFaceStartPos &pos, std::shared_ptr<Card> card, std::shared_ptr<CoalMiningArea> area, int tagNum, std::shared_ptr<CoalMiningRegularCycle> coal)
{
	int size = card->m_vecLoc.size();
	bool bFind = false;
	for (auto it = card->m_vecLoc.rbegin(); it !=card->m_vecLoc.rend(); it++)
	{
		// 当前坐标是否在机头或机尾区域
		double distance = 0.0;
		if(1==tagNum)
		{
			if(coal->bNoTarget)// 上一次未达到机头或机尾	
			{
				coal->bNoTarget = false;
				distance = sqrt(it->x - coal->end_x) * (it->x - coal->end_x) + (it->y - coal->end_y) * (it->y - coal->end_y)*2;
			}
			else
			{
				distance = sqrt(it->x - area->x1) * (it->x - area->x1) + (it->y - area->y1) * (it->y - area->y1)*2;
			}
			
		}
		else if(2 == tagNum)
		{
			if(coal->bNoTarget)// 上一次未达到机头或机尾	
			{
				coal->bNoTarget = false;
				distance = sqrt(it->x - coal->end_x) * (it->x - coal->end_x) + (it->y - coal->end_y) * (it->y - coal->end_y)*2;
			}
			else
			{
				distance = sqrt(it->x - area->x2) * (it->x - area->x2) + (it->y - area->y2) * (it->y - area->y2)*2;
			}	
		}
	
		if ( distance < area->distance )
		{
			bFind = true;
			pos.x = it->x;
			pos.y = it->y;
			pos.rec_time = it->rec_time;
			break;
		}
	}
	if(!bFind) //没有找到出区域的点，则挑vector前面某个位置
	{
		pos.x = card->m_vecLoc[size/5].x;
		pos.y = card->m_vecLoc[size/5].y;
		pos.rec_time = card->m_vecLoc[size/5].rec_time;
	}
	string strTime = CFunctions::time_t2string(pos.rec_time);
	char chLog[MAX_LOG_LENGTH] = {0};
	std::string log = "";
	sprintf_s(chLog,"find_regularcyclerate_startpoint, card: %s, find: %d, x; %.4f, y: %.4f time: %s, bNoTarget = %d",
		card->card_id.c_str(), bFind, pos.x, pos.y, strTime.c_str(), coal->bNoTarget);
	log = chLog;
	Log::write_log(FILE_TYPE::STARTUP_RATIO,log,true);
}
/*计算采煤机的正规循环率
	
*
* param
*		card	---		车卡信息
*		tag		---		事件类型
*/

void CYAServerDlg::Calc_CoalMining_RegularCycleRate(std::shared_ptr<Card> card)
{
	//判断是否是采煤机;
	if ( CT_COALMINING_MACHINE == card->card_type )
	{
		//求到目的点的距离，和开始点的距离;
		int workface_id = m_coalWorkfaceVehicleMap[card->id];
		CoalMiningRegularCycleMap::iterator it_s = m_coalmining_regularcycle_list.find(workface_id);
		if (it_s != m_coalmining_regularcycle_list.end())
		{				
			uint64_t type=1;
			uint64_t key = type<<32|it_s->second->coalface_id;
			deal_warning_point_alarm(key,card);
			int tagNum = it_s->second->tgPointNum;
			std::shared_ptr<CoalMiningArea> area;
			CoalMiningAreaMap::iterator it_area = m_coalmining_area_list.find(it_s->second->coalface_id);
			if (it_area != m_coalmining_area_list.end())
			{
				area = it_area->second;
			}
			else
			{
				return;
			}

			//获取机头机尾位置
			double x1= area->x1;
			double x2 = area->x2;
			double y1 = area->y1;
			double y2 = area->y2;

			//记录采煤机位置
			time_t loctime = card->rec_time;
			std::string strrecTime = CFunctions::time_t2string(loctime);
			double distance = sqrt((card->x-x1)*(card->x-x1) + (card->y-y1)*(card->y - y1))*2;
			char strdistance[60]= {'\0'};
			sprintf_s(strdistance,"%s,%.4f,%.4f",strrecTime.c_str(),distance,fabs(card->getv()));
			it_s->second->pos_record = it_s->second->pos_record + strdistance;
			string time1 = CFunctions::time_t2string(loctime);
			string time2 = CFunctions::time_t2string(it_s->second->last_time);
			int time_int = loctime - it_s->second->last_time;
			int itSize = it_s->second->pos_record.size();
			debug_print_syslog(0,"regular_cycle_coalmining: card: %s, time1: %s, time2: %s, time_intervel: %d, size: %d", card->card_id.c_str(),time1.c_str(),time2.c_str(),time_int, itSize);
			//每隔60秒发送一次采煤机位置信息
			if (loctime - it_s->second->last_time >= 60 || it_s->second->pos_record.size()> 1800)
			{
				store_data_coalmining_Pos(workface_id,it_s->second->pos_record );
				it_s->second->pos_record  = "";
				it_s->second->last_time = loctime;
			}
			else
			{
				it_s->second->pos_record = it_s->second->pos_record + ";";
			}		
            // 刀数统计逻辑
			bool stateChanged = false;
			//判断是否已经开始计算刀数
			if (it_s->second->IsWorking)
			{
				double x,y;
				if (1 == it_s->second->bDirection) // 机头《-》机尾
				{
					x = x2;
					y = y2;
					tagNum = 1;
				} 
				else if(2 == it_s->second->bDirection)         // 机尾《-》机头
				{
					x = x1;
					y = y1;
					tagNum = 2;
				}
				else
				{
					char chLog[MAX_LOG_LENGTH] = {0};
					std::string log = "";
					sprintf_s(chLog,"regular_cycle_coalmining error direction1: vehicle_id:%d ",it_s->second->vehicle_id);
					log = chLog;
					Log::write_log(FILE_TYPE::STARTUP_RATIO,log,true);
				}
				//判断半刀是否完成，完成半刀则更新起始存储位置的刀数值0 - 0.5		
#if 1
				if(!it_s->second->bHalfKnife)
				{
					// 机身中心区域位置
					double center_x = (area->x1 + area->x2)/2.0;
					double center_y = (area->y1 + area->y2)/2.0;

					double half_dis = sqrt((area->x1 - area->x2)* (area->x1 - area->x2) + (area->y1 -area->y2) * (area->y1 -area->y2));
					double dis = 0.0;

					char chLoghalf[MAX_LOG_LENGTH] = {0};
					std::string loghalf = "";
					// 分机头-》机尾和机尾-》机头两种情况
					if (1 == it_s->second->bDirection) // 机头-》机尾
					{
						dis = sqrt((card->x-area->x1)*(card->x-area->x1) + (card->y-area->y1)*(card->y - area->y1))*2 ;
						sprintf_s(chLoghalf,"Calc_CoalMining_RegularCycleRate head<->tail, card: %s, half_dis: %.4f, distance: %.4f, center_x: %.4f, center_y: %.4f, x: %.4f, y: %.4f ",
							card->card_id.c_str(),half_dis,dis,center_x, center_y, card->x, card->y);
					}
					else if(2 == it_s->second->bDirection)          // 机尾-》机头
					{
						dis = sqrt((card->x-area->x2)*(card->x-area->x2) + (card->y-area->y2)*(card->y - area->y2))*2 ;
						sprintf_s(chLoghalf,"Calc_CoalMining_RegularCycleRate tail<->head, card: %s, half_dis: %.4f, distance: %.4f, center_x: %.4f, center_y: %.4f, x: %.4f, y: %.4f ",
							card->card_id.c_str(),half_dis,dis,center_x, center_y, card->x, card->y);
					}
					else
					{
						sprintf_s(chLoghalf,"regular_cycle_coalmining error direction2: vehicle_id:%d ",it_s->second->vehicle_id);
					}
					loghalf = chLoghalf;
					Log::write_log(FILE_TYPE::STARTUP_RATIO,loghalf,true);

					if(half_dis < dis)
					{
						//数据上传
						std::shared_ptr<CoalminingRegularCycleDetail> RegularCycle = std::make_shared<CoalminingRegularCycleDetail>();
						RegularCycle->vehicle_id = card->id;
						RegularCycle->dept_id = card->dept_id;
						RegularCycle->end_x =card->x;
						RegularCycle->end_y = card->y;
						RegularCycle->end_time = loctime;
						RegularCycle->start_x = it_s->second->start_x;
						RegularCycle->start_y = it_s->second->start_y;
						RegularCycle->start_time = it_s->second->start_time;
						RegularCycle->coalface_id = it_s->second->coalface_id;
						update_halfknife_coalmining_Regular_cycle(RegularCycle);
						it_s->second->bHalfKnife = true;

						//更新状态改变计算参数
						it_s->second->start_time = RegularCycle->end_time;
						it_s->second->start_x = RegularCycle->end_x;
						it_s->second->start_y = RegularCycle->end_y;					
						RegularCycle->start_time = RegularCycle->end_time;
						RegularCycle->start_x = RegularCycle->end_x;
						RegularCycle->start_y = RegularCycle->end_y;
						RegularCycle->move_direction = it_s->second->bDirection;
						store_data_coalmining_Regular_cycle(RegularCycle);
						char chLog[MAX_LOG_LENGTH] = {0};
						std::string log = "";
						sprintf_s(chLog,"Calc_CoalMining_RegularCycleRate, vehicle id: %d, center_x: %.4f,center_y:%.4f,dis:%.4f time: %s",
							RegularCycle->vehicle_id, center_x, center_y, half_dis, strrecTime.c_str());
						log = chLog;
						Log::write_log(FILE_TYPE::STARTUP_RATIO,log,true);
					}
				}
#endif
				//判断一刀是否完成
				double end_x=0.0,end_y=0.0;
				time_t endtime = loctime;
				double coalfacedis = sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2))*2;
				double dis = sqrt((card->x-x)*(card->x-x) + (card->y-y)*(card->y - y))*2 ;

				char chLognext[MAX_LOG_LENGTH] = {0};
				std::string lognext = "";
				sprintf_s(chLognext,"Calc_CoalMining_RegularCycleRate, card: %s, x: %.4f, y: %.4f, dis: %.4f, direction: %d",
					card->card_id.c_str(), card->x, card->y, dis, it_s->second->bDirection);
				lognext = chLognext;
				Log::write_log(FILE_TYPE::STARTUP_RATIO,lognext,true);

				if (dis< area->distance)
				{
					debug_print_syslog(0,"regular_cycle_coalmining: %s tagnum %d has arrived ,distance=%.4f\n", strrecTime.c_str(),it_s->second->tgPointNum,dis);
					stateChanged = true;
					end_x = card->x;
					end_y = card->y;
				}
				else if (dis < it_s->second->mindistance )
				{ 
					it_s->second->mindistance = dis;
					it_s->second->mindis_time  = loctime;
					it_s->second->end_x = card->x;
					it_s->second->end_y = card->y ;
				}
				else if (loctime - it_s->second->mindis_time > 1800  &&  it_s->second->mindistance < 0.2 * coalfacedis)
				{
					debug_print_syslog(0,"regular_cycle_coalmining: %s time is too long,tagnum %d is arrived  ,distance=%.4f\n", strrecTime.c_str(),it_s->second->tgPointNum,dis);
					//防止有障碍不能到机头或机尾的情况
					stateChanged = true;
					end_x = it_s->second->end_x;
					end_y = it_s->second->end_y;
					endtime = it_s->second->mindis_time;
				}	

				if (stateChanged)
				{
					//数据上传
					std::shared_ptr<CoalminingRegularCycleDetail> RegularCycle = std::make_shared<CoalminingRegularCycleDetail>();
					RegularCycle->vehicle_id = card->id;
					RegularCycle->coalface_id = m_coalWorkfaceVehicleMap[card->id];
					RegularCycle->dept_id = card->dept_id;
					RegularCycle->end_x =end_x;
					RegularCycle->end_y = end_y;
					RegularCycle->end_time = endtime;
					RegularCycle->start_x = it_s->second->start_x;
					RegularCycle->start_y = it_s->second->start_y;
					RegularCycle->start_time = it_s->second->start_time;
					RegularCycle->coalface_id = it_s->second->coalface_id;
					//RegularCycle->schedule_times = it_s->second->schedule_times;
					Update_data_coalmining_Regular_cycle(RegularCycle);
					//更新状态改变计算参数
					it_s->second->start_time = endtime;
					it_s->second->start_x = end_x;
					it_s->second->start_y = end_y;					
					it_s->second->tgPointNum = tagNum;//到达端点后进行目标点切换
					it_s->second->mindistance = FLT_MAX;
					it_s->second->mindis_time = loctime;	
					it_s->second->bHalfKnife = false;
					RegularCycle->start_time = endtime;
					RegularCycle->start_x = end_x;
					RegularCycle->start_y = end_y;
					if(1 == it_s->second->bDirection)
					{
						it_s->second->bDirection = 2;
						RegularCycle->move_direction = 2;
					}
					else if(2 == it_s->second->bDirection)
					{
						it_s->second->bDirection = 1;
						RegularCycle->move_direction = 1;
					}
					else
						debug_print_syslog(0,"regular_cycle_coalmining error direction3: vehicle_id:%d ",RegularCycle->vehicle_id);
					store_halfknife_coalmining_Regular_cycle(RegularCycle);
				}
			}
			else
			{			
				//采煤机是否在机头或这机尾，并改变状态

				if (sqrt((card->x-x1)*(card->x-x1) + (card->y-y1)*(card->y - y1))*2 < area->distance)
				{
					stateChanged = true;		
					it_s->second->IsWorking = true;//改变工作状态
					tagNum = 2;//开始计算正规循环率
					it_s->second->bDirection = 1; //在机头，下一刀运动方向是机头->机尾
				}
				else if (sqrt((card->x-x2)*(card->x-x2) + (card->y-y2)*(card->y - y2))*2 < area->distance)
				{
					stateChanged = true;	
					it_s->second->IsWorking = true;//改变工作状态
					tagNum = 1;//开始计算正规循环率
					it_s->second->bDirection = 2; //在机尾，下一刀运动方向是机尾->机头
				}
				if (stateChanged)
				{
					//更新状态改变计算参数
					it_s->second->start_time = card->rec_time;
					it_s->second->start_x = card->x;
					it_s->second->start_y = card->y;					
					it_s->second->tgPointNum = tagNum;//到达端点后进行目标点切换
					it_s->second->mindistance = FLT_MAX;
					it_s->second->mindis_time = loctime;
					it_s->second->bHalfKnife = false;
					std::shared_ptr<CoalminingRegularCycleDetail> RegularCycle = std::make_shared<CoalminingRegularCycleDetail>();
					RegularCycle->vehicle_id = card->id;
					RegularCycle->dept_id = card->dept_id;
					RegularCycle->start_time = card->rec_time;
					RegularCycle->start_x = card->x;
					RegularCycle->start_y = card->y;	
					RegularCycle->move_direction = it_s->second->bDirection;
					store_halfknife_coalmining_Regular_cycle(RegularCycle);
				}
			}
		}
	}
}


/*发送采煤机距离固定点距离（现在设置为机头）
	
*
* param
*		vehicle_id	---		车ID
*		dis_record		---		过去一分钟记录的位置
* 
* return
*		函数正常执行返回0，否则返回1
*/
int CYAServerDlg::store_data_coalmining_Pos(int workface_id, std::string dis_record)
{
	char sql_log[LENGTH_SQL] = {'\0'};
	time_t tCurTime = time(NULL);
	std::string strcurTime = CFunctions::time_t2string(tCurTime);
	sprintf_s(		sql_log, 	LENGTH_SQL,
		"insert IGNORE into his_draw_position (work_face_id,position_data ,write_time )values(%d,'%s','%s');",
		workface_id,
		dis_record.c_str(),
		strcurTime.c_str()
		);

	//execute_sql(sql);
	std::string error = "";
	if (sDBConnPool.ExecuteSql(sql_log,error ) < 0 )
	{
		debug_print_syslog(0,"regular_cycle: Failed to ExecuteSql:%s,Err=%s\n", sql_log, error.c_str());
	}
	return 0;
}

/*初始化综采面有关正规循环率计算的参数
	
*
* param
* 
* return
*		函数正常执行返回0，否则返回1
*/
int CYAServerDlg::init_data_coalminingface_RegularCycle()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	sprintf_s(strsql, "SELECT coalface_id, head_x , head_y, tail_x, tail_y, ht_radius,x_offset,y_offset FROM dat_coalface;");

	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}
	std::shared_ptr<CoalMiningArea> pCoalMiningArea = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))
	{
		int coalface_id =  atoi(pRow[0]);
		CoalMiningAreaMap::iterator it = m_coalmining_area_list.find(coalface_id);		
		if(it != m_coalmining_area_list.end())
		{
			pCoalMiningArea = it->second;
		}
		else
		{
			pCoalMiningArea = std::make_shared<CoalMiningArea>();
			m_coalmining_area_list.insert(make_pair(coalface_id, pCoalMiningArea));
			nRow++;
		}

		pCoalMiningArea->coalface_id = coalface_id;
		pCoalMiningArea->x1 = atof(pRow[1]);
		pCoalMiningArea->y1= atof(pRow[2]);
		pCoalMiningArea->x2 = atof(pRow[3]);
		pCoalMiningArea->y2 = atof(pRow[4]);
		pCoalMiningArea->distance = atof(pRow[5]);
		pCoalMiningArea->m_x_offset = pRow[6]==NULL?0:atof(pRow[6]);
		pCoalMiningArea->m_y_offset = pRow[7]==NULL?0:atof(pRow[7]);
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_COALFACE_AREA), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}

/*初始化采煤机有关正规循环率计算的中间参数
*
* param
* 
* return
*		函数正常执行返回0，否则返回1
*/
int CYAServerDlg::init_data_coalmining_RegularCycle()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	

	sprintf_s(strsql, "SELECT vehicle_id, coalface_id FROM dat_coalface_vehicle;");

	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}
	std::shared_ptr<CoalMiningRegularCycle> pCoalRegularCycle = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))
	{
		int vehicle_id =  atoi(pRow[0]);
		int workface_id = atoi(pRow[1]);
		CoalWorkfaceVehicleMap::iterator it_map = m_coalWorkfaceVehicleMap.find(vehicle_id);
		if(it_map == m_coalWorkfaceVehicleMap.end())
		{
			m_coalWorkfaceVehicleMap.insert(make_pair(vehicle_id,workface_id));
		}
		CoalMiningRegularCycleMap::iterator it = m_coalmining_regularcycle_list.find(workface_id);		
		if(it != m_coalmining_regularcycle_list.end())
		{
			pCoalRegularCycle = it->second;
		}
		else
		{
			pCoalRegularCycle = std::make_shared<CoalMiningRegularCycle>();
			m_coalmining_regularcycle_list.insert(make_pair(workface_id, pCoalRegularCycle));
			nRow++;
		}

		pCoalRegularCycle->vehicle_id = vehicle_id;
		pCoalRegularCycle->coalface_id = workface_id; 	
		//pCoalRegularCycle->schedule_times = atof(pRow[2]);
		pCoalRegularCycle->last_time = time_t(0);
		pCoalRegularCycle->pos_record = "";
		pCoalRegularCycle->IsWorking = false;
		pCoalRegularCycle->tgPointNum = 0;
		pCoalRegularCycle->bNoTarget = false;
		pCoalRegularCycle->bHalfKnife = false;
		pCoalRegularCycle->mindistance = FLT_MAX;
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_COALFACE_VEHICLE), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}

/*初始化采煤机有关正规循环率计算的先前参数
*
* param
* 
* return
*		函数正常执行返回0，否则返回1
*/
int CYAServerDlg::init_data_pre_coalmining_RegularCycle()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	

	sprintf_s(strsql, "SELECT work_face_id, start_time,start_x,start_y,move_direction \
					  FROM his_regular_cycle_detail\
					  where end_time is NULL and end_x is NULL;");

	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}
	std::shared_ptr<CoalMiningRegularCycle> pCoalRegularCycle = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))
	{
		int workface_id =  atoi(pRow[0]);
		time_t start_time = CFunctions::string2time_t(pRow[1]);
		time_t tCurTime = time(NULL);
		if (tCurTime - start_time > 3600 *24*3)
		{
			continue;
		}
		CoalMiningRegularCycleMap::iterator it = m_coalmining_regularcycle_list.find(workface_id);		
		if(it != m_coalmining_regularcycle_list.end())
		{
			pCoalRegularCycle = it->second;
		}
		else
		{
			continue;
		}
		pCoalRegularCycle->start_time = start_time;
		pCoalRegularCycle->last_time = time_t(0);
		pCoalRegularCycle->IsWorking = true;
		pCoalRegularCycle->bHalfKnife = true;
		pCoalRegularCycle->bDirection = atoi(pRow[4]);
		pCoalRegularCycle->start_x = atof(pRow[2]);
		pCoalRegularCycle->start_y = atof(pRow[3]);
		pCoalRegularCycle->mindis_time = time(NULL);
		pCoalRegularCycle->mindistance = FLT_MAX;
		char chLog[MAX_LOG_LENGTH] = {0};
		string strTime = CFunctions::time_t2string(start_time);
		std::string log = "";
		sprintf_s(chLog,"init_data_pre_coalmining_RegularCycle, workface id: %d, start time: %s, start_x:%.4f, start_y: %.4f,direction: %d", workface_id, strTime.c_str(), pCoalRegularCycle->start_x,pCoalRegularCycle->start_y,pCoalRegularCycle->bDirection);
		log = chLog;
		Log::write_log(FILE_TYPE::STARTUP_RATIO,log,true);
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_AREA), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}

/*初始化半刀未完成的正规循环率情况
*
* param
* 
* return
*		函数正常执行返回0，否则返回1
*/
int CYAServerDlg::init_restart_halfcoalmining_regularcycle()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	

	sprintf_s(strsql, "SELECT work_face_id, start_time,start_x,start_y,move_direction \
					  FROM his_regular_cycle_detail\
					  where end_x = 1.0 and end_time is NULL;");

	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}
	std::shared_ptr<CoalMiningRegularCycle> pCoalRegularCycle = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))
	{
		int workface_id =  atoi(pRow[0]);
		time_t start_time = CFunctions::string2time_t(pRow[1]);
		time_t tCurTime = time(NULL);
		if (tCurTime - start_time > 3600 *24*3)
		{
			continue;
		}
		CoalMiningRegularCycleMap::iterator it = m_coalmining_regularcycle_list.find(workface_id);		
		if(it != m_coalmining_regularcycle_list.end())
		{
			pCoalRegularCycle = it->second;
		}
		else
		{
			continue;
		}
		pCoalRegularCycle->start_time = start_time;
		pCoalRegularCycle->last_time = time_t(0);
		pCoalRegularCycle->IsWorking = true;
		pCoalRegularCycle->bHalfKnife = false;
		pCoalRegularCycle->bDirection = atoi(pRow[4]);
		pCoalRegularCycle->start_x = atof(pRow[2]);
		pCoalRegularCycle->start_y = atof(pRow[3]);
		pCoalRegularCycle->mindis_time = time(NULL);
		pCoalRegularCycle->mindistance = FLT_MAX;
		char chLog[MAX_LOG_LENGTH] = {0};
		string strTime = CFunctions::time_t2string(start_time);
		std::string log = "";
		sprintf_s(chLog,"init_restart_halfcoalmining_regularcycle, workface id : %d,start time: %s, start_x:%.4f, start_y: %.4f,direction; %d", workface_id,strTime.c_str(), pCoalRegularCycle->start_x,pCoalRegularCycle->start_y,pCoalRegularCycle->bDirection);
		log = chLog;
		Log::write_log(FILE_TYPE::STARTUP_RATIO,log,true);
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_AREA), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}

/*存储采煤机半刀开始的情况
*
* param
*		reguilarCycle	---		采煤机1刀的参数
* 
* return
*		函数正常执行返回0，否则返回1
*/
int CYAServerDlg::store_halfknife_coalmining_Regular_cycle(std::shared_ptr<CoalminingRegularCycleDetail> reguilarCycle )
{
	char sql_log[LENGTH_SQL] = {'\0'};
	memset(sql_log,0,MAX_LOG_LENGTH*sizeof(char));
	//获取综采面参数
	double  schedule_times =0.0;// 数据库未配置，默认取0
	get_data_coalmining_scheduletimes(reguilarCycle->coalface_id,schedule_times);
	std::string strstarttime = CFunctions::time_t2string(reguilarCycle->start_time);

	sprintf_s(		sql_log, 	LENGTH_SQL,
		"insert IGNORE into his_regular_cycle_detail (work_face_id,detail_type,start_time,detail_value,schedule_value,dept_id,start_x,start_y,end_x,end_y,move_direction) \
		values(%d,%d,'%s',%.4f,%.4f,%d,%.4f,%.4f,%.4f,%.4f,%d);",
		reguilarCycle->coalface_id,
		1,
		strstarttime.c_str(),
		0.0,
		schedule_times,
		reguilarCycle->dept_id,
		reguilarCycle->start_x,
		reguilarCycle->start_y,
		1.0,
		1.0,
		reguilarCycle->move_direction
		);
	std::string error = "";
	if (sDBConnPool.ExecuteSql(sql_log,error ) < 0 )
	{
		debug_print_syslog(0,"regular_cycle: Failed to ExecuteSql:%s,Err=%s\n", sql_log, error.c_str());
	}
	char chLog[MAX_LOG_LENGTH] = {0};
	std::string log = "";
	sprintf_s(chLog,"store_halfknife_coalmining_Regular_cycle, insert sql: %s", sql_log);
	log = chLog;
	Log::write_log(FILE_TYPE::STARTUP_RATIO,log,true);
	return 0;
}
 
/*存储采煤机1刀开始的情况
*
* param
*		reguilarCycle	---		采煤机1刀的参数
* 
* return
*		函数正常执行返回0，否则返回1
*/
int CYAServerDlg::store_data_coalmining_Regular_cycle(std::shared_ptr<CoalminingRegularCycleDetail> reguilarCycle )
{
	char sql_log[LENGTH_SQL] = {'\0'};
	memset(sql_log,0,MAX_LOG_LENGTH*sizeof(char));
	//获取综采面参数
	double  schedule_times =0.0;// 数据库未配置，默认取5
	get_data_coalmining_scheduletimes(reguilarCycle->coalface_id,schedule_times);
	std::string strstarttime = CFunctions::time_t2string(reguilarCycle->start_time);

	sprintf_s(		sql_log, 	LENGTH_SQL,
		"insert IGNORE into his_regular_cycle_detail (work_face_id,detail_type,start_time,detail_value,schedule_value,dept_id,start_x,start_y,move_direction) \
		values(%d,%d,'%s',%.4f,%.4f,%d,%.4f,%.4f,%d);",
		reguilarCycle->coalface_id,
		1,
		strstarttime.c_str(),
		0.0,
		schedule_times,
		reguilarCycle->dept_id,
		reguilarCycle->start_x,
		reguilarCycle->start_y,
		reguilarCycle->move_direction
		);
	std::string error = "";
	if (sDBConnPool.ExecuteSql(sql_log,error ) < 0 )
	{
		debug_print_syslog(0,"regular_cycle: Failed to ExecuteSql:%s,Err=%s\n", sql_log, error.c_str());
	}
	char chLog[MAX_LOG_LENGTH] = {0};
	std::string log = "";
	sprintf_s(chLog,"store_data_coalmining_Regular_cycle, insert sql: %s", sql_log);
	log = chLog;
	Log::write_log(FILE_TYPE::STARTUP_RATIO,log,true);
	return 0;
}

/* 完成半刀，更新刀数值为0.5
*
* param
*		reguilarCycle	---		采煤机0.5刀的参数
* 
* return
*		函数正常执行返回0，否则返回1
*/
int CYAServerDlg::update_halfknife_coalmining_Regular_cycle(std::shared_ptr<CoalminingRegularCycleDetail> reguilarCycle )
{
	char sql_log[LENGTH_SQL] = {'\0'};
	memset(sql_log,0,MAX_LOG_LENGTH*sizeof(char));
	std::string strstarttime = CFunctions::time_t2string(reguilarCycle->start_time);
	time_t tCurTime = time(NULL);
	time_t tStartTime = tCurTime - 3000;
	std::string strCurTime = CFunctions::time_t2string(tCurTime);
	std::string strStartTime = CFunctions::time_t2string(tStartTime);
	sprintf_s(		sql_log, 	LENGTH_SQL,
		"update  his_regular_cycle_detail set  detail_value=0.5, end_time = '%s',start_time = '%s' where work_face_id = %d and start_time = '%s';",
		strCurTime.c_str(),
		strStartTime.c_str(),
		reguilarCycle->coalface_id,
		strstarttime.c_str()
		);
	std::string error = "";
	if (sDBConnPool.ExecuteSql(sql_log,error ) < 0 )
	{
		debug_print_syslog(0,"regular_cycle: Failed to ExecuteSql:%s,Err=%s\n", sql_log, error.c_str());
	}
	char chLog[MAX_LOG_LENGTH] = {0};
	std::string log = "";
	sprintf_s(chLog,"update_halfknife_coalmining_Regular_cycle, sql: %s",sql_log);
	log = chLog;
	Log::write_log(FILE_TYPE::STARTUP_RATIO,log,true);
	return 0;
}

/*存储采煤机完成1刀的情况
*
* param
*		reguilarCycle	---		采煤机1刀的参数
* 
* return
*		函数正常执行返回0，否则返回1
*/
int CYAServerDlg::Update_data_coalmining_Regular_cycle(std::shared_ptr<CoalminingRegularCycleDetail> reguilarCycle )
{
	char sql_log[LENGTH_SQL] = {'\0'};
	memset(sql_log,0,MAX_LOG_LENGTH*sizeof(char));
	std::string strstarttime = CFunctions::time_t2string(reguilarCycle->start_time);
	std::string strendtime = CFunctions::time_t2string(reguilarCycle->end_time);
	sprintf_s(		sql_log, 	LENGTH_SQL,
		"update  his_regular_cycle_detail set end_time ='%s', detail_value=0.5,end_x=%.4f,end_y=%.4f \
		where work_face_id = %d and start_time = '%s';",
		strendtime.c_str(),
		//0.5,
		reguilarCycle->end_x,
		reguilarCycle->end_y,
		reguilarCycle->coalface_id,
		strstarttime.c_str()
		);
	std::string error = "";
	if (sDBConnPool.ExecuteSql(sql_log,error ) < 0 )
	{
		debug_print_syslog(0,"regular_cycle: Failed to ExecuteSql:%s,Err=%s\n", sql_log, error.c_str());
	}
	char chLog[MAX_LOG_LENGTH] = {0};
	std::string log = "";
	sprintf_s(chLog,"Update_data_coalmining_Regular_cycle, sql: %s",sql_log);
	log = chLog;
	Log::write_log(FILE_TYPE::STARTUP_RATIO,log,true);
	return 0;
}

/*获取采煤机的计划刀数
*
* param
* 
* return
*		函数正常执行返回0，否则返回1
*/
int CYAServerDlg::get_data_coalmining_scheduletimes(int workface_id,double& scheduletimes)
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	time_t tCurTime = time(NULL);
	std::string curDate = time_t2string_date(tCurTime);
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	

	sprintf_s(strsql, LENGTH_SQL,"SELECT 	schedule_mine_times	 FROM dat_workface_scheduling  where workface_id = %d and\
								 schedule_date ='%s';",
		workface_id,curDate.c_str());
	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}
	std::shared_ptr<CoalMiningRegularCycle> pCoalRegularCycle = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))
	{
		scheduletimes =  atoi(pRow[0]);
		break;
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_AREA), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}
/*由time_t获取日期字符串
*
* param
*    t 	---		输入time_t值
* 
* return
*		返回日期的字符串
*/
std::string CYAServerDlg::time_t2string_date(const time_t& t)
{
	struct tm *p = NULL;
	char buf[30] = {0};
	if (t == 0 || t == -1)
	{
		return "0";
	}
	p = localtime(&t);
	sprintf_s(buf,
		30,
		"%04d-%02d-%02d",
		p->tm_year + 1900,p->tm_mon + 1,p->tm_mday);

	string str = "";
	str = buf;

	return str;
}

/*处理工作面司机和车卡告警的相关信息
*
* param
*		card	---		车卡信息
* 
* return
*	
*/
void CYAServerDlg::deal_vehicle_driver_alarm(std::shared_ptr<Card> card)
{
	if ((card->card_type == CT_PERSON && (card->worktype_id == 16 ||  card->worktype_id == 40))||
		card->card_type == CT_COALMINING_MACHINE || card->card_type == CT_TUNNELBORING_MACHINE)
	{
		VehicleDriverPosMap::iterator it_p = m_vehicleDriverPosMap.find(card->id);
		if (it_p != m_vehicleDriverPosMap.end())
		{
			if (card->card_type == CT_COALMINING_MACHINE || card->card_type == CT_TUNNELBORING_MACHINE)
			{
				int dist_time;
				WorkfaceDriverAlarmMap::iterator it_a = m_WorkfaceDriverAlarmMap.find(card->id);
				if (it_a != m_WorkfaceDriverAlarmMap.end())
				{
					if (card->m_bOpen ^ it_p->second->isOn )
					{					
						it_p->second->isOn = card->m_bOpen;
						deal_vehicle_driver_changed(card);
					}
					else if (it_p->second->isOn)
					{

						dist_time= it_a->second->dist_time;
						if (card->rec_time - it_p->second->starttime > dist_time)
						{
							deal_vehicle_driver_changed(card,true);
						}
					}
				}
				else
				{
					return;
				}	

				
			}
			if (it_p->second->isOn)
			{
				if (it_p->second->PointNum == 0)
				{
					it_p->second->starttime = card->rec_time;
				}
				it_p->second->Sum_x += card->x;
				it_p->second->Sum_y += card->y;
				it_p->second->PointNum++;
			}
		}	
	}
}

/*处理工作面车和司机告警发生变化（车的开关机和到了检查告警时间）
*
* param
*		card	---		车卡信息
*		isCalc	---		true 计算车与司机之间的距离，false车的开关状态发生变化
* 
* return
*	
*/
void CYAServerDlg::deal_vehicle_driver_changed(std::shared_ptr<Card> card,bool isCalc)
{
	DeptVehicleDriverMap::iterator it_d = m_deptVehicleDriverMap.find(card->dept_id);
	if (it_d != m_deptVehicleDriverMap.end())
	{
		double mean_vx=0.;
		double mean_vy=0.;
		double distance = 0.;
		double minDistance  = FLT_MAX;
		WorkfaceDriverAlarmMap::iterator it_a = m_WorkfaceDriverAlarmMap.find(card->id);
		if (it_a != m_WorkfaceDriverAlarmMap.end())
		{
			double dist = it_a->second->dist;
			int dist_time = it_a->second->dist_time;
			if (card->card_type == CT_COALMINING_MACHINE)
			{
				std::map<int ,std::vector<int>>::iterator it_v = it_d->second->CoalMiningDriver.find(card->id);
				if ( it_v !=   it_d->second->CoalMiningDriver.end())
				{
					VehicleDriverPosMap::iterator it_vp = m_vehicleDriverPosMap.find(card->id);
					if (it_vp != m_vehicleDriverPosMap.end())
					{
						if (isCalc)
						{
							if (it_vp->second->PointNum >0)
							{
								mean_vx = it_vp->second->Sum_x/it_vp->second->PointNum;
								mean_vy = it_vp->second->Sum_y/it_vp->second->PointNum;
							}							
						}
						reset_vehicle_driver_pos(it_vp->second);
						it_vp->second->isOn = card->m_bOpen;
					}
					else
					{
						reset_vehicle_driver_pos(it_vp->second);
						return;
					}

				}
				else
				{
					return;
				}
				//获取司机列表计算司机的最小距离
				std::vector<int>& driver = it_v->second;
				for (size_t i=0;i < driver.size();i++)
				{
					VehicleDriverPosMap::iterator it_p = m_vehicleDriverPosMap.find(driver[i]);
					if (it_p != m_vehicleDriverPosMap.end())
					{
						if (isCalc)
						{
							if (calc_vehicle_driver_distance(mean_vx,mean_vy,distance,it_p->second))
							{
								if (distance < minDistance)
								{
									minDistance = distance;
								}
							}
						}
						it_p->second->isOn = card->m_bOpen;
						if (card->m_bOpen)
						{
							reset_vehicle_driver_pos(it_p->second);
						}
					}
				}
			}
			else if (card->card_type == CT_TUNNELBORING_MACHINE)
			{
				std::map<int ,std::vector<int>>::iterator it_v = it_d->second->DrivingDriver.find(card->id);
				if ( it_v !=   it_d->second->DrivingDriver.end())
				{
					VehicleDriverPosMap::iterator it_vp = m_vehicleDriverPosMap.find(card->id);
					if (it_vp != m_vehicleDriverPosMap.end())
					{
						if (isCalc)
						{
							mean_vx = it_vp->second->Sum_x/it_vp->second->PointNum;
							mean_vy = it_vp->second->Sum_y/it_vp->second->PointNum;
						}
						reset_vehicle_driver_pos(it_vp->second);
					}
					else
					{
						reset_vehicle_driver_pos(it_vp->second);
						return;
					}

					if (it_v->second.size() ==0)
					{
						return;
					}

					std::vector<int>& driver = it_v->second;
					for (size_t i=0;i < driver.size();i++)
					{
						VehicleDriverPosMap::iterator it_p = m_vehicleDriverPosMap.find(driver[i]);
						if (it_p != m_vehicleDriverPosMap.end())
						{
							if (isCalc)
							{
								if (calc_vehicle_driver_distance(mean_vx,mean_vy,distance,it_p->second))
								{
									if (distance < minDistance)
									{
										minDistance = distance;
									}
								}
							}
							it_p->second->isOn = card->m_bOpen;
							if (card->m_bOpen)
							{
								reset_vehicle_driver_pos(it_p->second);
							}
						}
					}
				}
				else
				{
					return;
				}

			}
			else
			{
				return;
			}
			//告警处理
			if (isCalc)
			{
				if (minDistance > dist)
				{
					start_end_vehicle_driver_alarm(card,true,minDistance,dist);
				}
				else
				{
					start_end_vehicle_driver_alarm(card,false);
				}
			}
			else if (!card->m_bOpen)
			{
				start_end_vehicle_driver_alarm(card,false);
			}
		}		
	}
}

/*开始或结束工作面车和司机告警
*
* param
*		card	---		车卡信息
*		isStart	---		true 开始，false结束
*		limitdis	---		告警门限（结束时默认为0）
*		realdis	---		实际距离（结束时默认为0）
* 
* return
*	
*/
void CYAServerDlg::start_end_vehicle_driver_alarm(std::shared_ptr<Card> card,bool isStart,double limitdis,double realdis)
{
	//工作面司机与车卡告警
	INT64 ev_id = card->m_event_list[ET_COALING_DRIVING_DRIVER];
	std::shared_ptr<YaEvent> ev;
	if (  ev_id ==0 && isStart )
	{
		ev_id = CFunctions::GetMicroSecond();
		ev = std::make_shared<YaEvent>(ev_id);
		ev->status = ES_START;
		ev->ev_type = ET_COALING_DRIVING_DRIVER;
		ev->obj_type = OT_CARD;
		ev->obj_id = card->card_id;
		ev->map_id = card->map_id;
		ev->area_id = card->area_id;
		ev->x =card->x;
		ev->y =card->y;
		ev->limit_value = limitdis;
		ev->cur_value = realdis;
		card->m_event_list[ET_COALING_DRIVING_DRIVER] = ev_id;
	}
	else if (ev_id >0 && !isStart  )
	{
		EventMap::iterator it_ev = mp_event_list->find(ev_id);
		if (it_ev != mp_event_list->end())
		{
			ev = it_ev->second;
			ev->status = ES_END;
			card->m_event_list[ET_COALING_DRIVING_DRIVER] = 0;
		}
		else
		{
			return;
		}
		
	}
	else
	{
		return;
	}
	
	ev->cur_time = time(NULL);
	ev->cur_value = 0;
	ev->is_sent = false;
	
	store_data_event(ev);
	add_event(ev);
	if (isStart)
	{
		debug_print_syslog(0,"[event warning: the driver is far from the vehicle ] vehicler_id: %d.",card->id);
	}
	else
	{
		debug_print_syslog(0,"[event warning: COALING_DRIVING_DRIVER waring is canceled ] vehicler_id: %d.",card->id);
	}	
}

/*计算司机和车卡的距离
*
* param
*		mean_vx	---		车的平均x坐标
*		mean_vy	---		车的平均y坐标
*		driverPos	---		司机的记录位置信息
* 
* return
*	  是否计算成功，true为成功，false失败，没有记录位置点
*/
bool CYAServerDlg::calc_vehicle_driver_distance( double mean_vx,double mean_vy,double& distance, std::shared_ptr<VehicleDriverPos> driverPos)
{
	if (driverPos->PointNum >0)
	{
		double meanx =  driverPos->Sum_x/driverPos->PointNum - mean_vx;
		double meany =  driverPos->Sum_y/driverPos->PointNum - mean_vy;
		//double meanz =  driverPos->Sum_z/driverPos->PointNum - mean_vz;
		distance = sqrt(meanx * meanx + meany * meany );
		return true;
	}
	return false;
}

/*重置记录的位置信息
*
* param
*		Pos	---		记录位置信息
* 
* return
*	  是否计算成功，true为成功，false失败，没有记录位置点
*/
void CYAServerDlg::reset_vehicle_driver_pos(std::shared_ptr<VehicleDriverPos> Pos)
{
	Pos->PointNum = 0;
	Pos->Sum_x = 0;
	Pos->Sum_y =0;
}

/*初始化工作面司机和车卡告警的相关信息
*
* param
*		card	---		车卡信息
* 
* return
*	
*/

void CYAServerDlg::Init_data_vehicle_meanpos(std::shared_ptr<Card> card)
{
	std::shared_ptr<DeptVehicleDriver> dept;
	DeptVehicleDriverMap::iterator it_d = m_deptVehicleDriverMap .find(card->dept_id);
	if (it_d != m_deptVehicleDriverMap.end())
	{
		dept = it_d->second;
	}
	else
	{
		dept = std::make_shared<DeptVehicleDriver>();
		dept->Dept_id = card->dept_id;
		m_deptVehicleDriverMap.insert(make_pair(card->dept_id,dept));
	}
	std::vector<int> driverList;
	if (card->card_type == CT_COALMINING_MACHINE )
	{		
		get_vehicle_driverlist(card->dept_id,16,driverList);		
		dept->CoalMiningDriver.clear();
		dept->CoalMiningDriver.insert(make_pair(card->id,driverList));
	}
	else if (card->card_type == CT_TUNNELBORING_MACHINE)
	{
		get_vehicle_driverlist(card->dept_id,40,driverList);
		dept->DrivingDriver.clear();
		dept->DrivingDriver.insert(make_pair(card->id,driverList));
	}
	else
	{
		return;
	}
	std::shared_ptr<VehicleDriverPos> pos	 = std::make_shared<VehicleDriverPos>();
	pos->PointNum = 0;
	pos->Sum_x = 0.;
	pos->Sum_y = 0.;
	pos->isOn = false;
	m_vehicleDriverPosMap[card->id] = pos;
	for (size_t i =0;i< driverList.size();i++)
	{
		pos	 = std::make_shared<VehicleDriverPos>();
		pos->PointNum = 0;
		pos->Sum_x = 0.;
		pos->Sum_y = 0.;
		pos->isOn = false;
		m_vehicleDriverPosMap[driverList[i]] = pos;
	}
}

void CYAServerDlg::remove_vehicle_meanpos(std::shared_ptr<Card> card)
{
	std::shared_ptr<DeptVehicleDriver> dept;
	DeptVehicleDriverMap::iterator it_d = m_deptVehicleDriverMap .find(card->dept_id);
	if (it_d == m_deptVehicleDriverMap.end())
	{
		return;
	}

	if (card->card_type == CT_COALMINING_MACHINE )
	{		
		it_d->second->CoalMiningDriver.clear();
	}
	else if (card->card_type == CT_TUNNELBORING_MACHINE)
	{
		it_d->second->DrivingDriver.clear();
	}
	else
	{
		return;
	}
	VehicleDriverPosMap::iterator it_s = m_vehicleDriverPosMap.find(card->id);
	if (it_s != m_vehicleDriverPosMap.end())
	{
		m_vehicleDriverPosMap.erase(it_s);
	}
	start_end_vehicle_driver_alarm(card,false);
}

void CYAServerDlg::remove_person_meanpos(std::shared_ptr<Card> card)
{
	std::shared_ptr<DeptVehicleDriver> dept;
	DeptVehicleDriverMap::iterator it_d = m_deptVehicleDriverMap .find(card->dept_id);
	if (it_d == m_deptVehicleDriverMap.end())
	{
		return;
	}

	if (card->worktype_id == 16 )
	{		
		if (dept->CoalMiningDriver.size()>0)
		{
			std::map<int ,std::vector<int>>::iterator it_s =  it_d->second->CoalMiningDriver.begin();
			std::vector<int>::iterator it_p = std::find(it_s->second.begin(),it_s->second.end(),card->id);
			if (it_p != it_s->second.end())
			{
				it_s->second.erase(it_p);
			}
		}
	
	}
	else if (card->card_type == 40)
	{
		if (dept->DrivingDriver.size()>0)
		{
			std::map<int ,std::vector<int>>::iterator it_s =  it_d->second->DrivingDriver.begin();
			std::vector<int>::iterator it_p = std::find(it_s->second.begin(),it_s->second.end(),card->id);
			if (it_p != it_s->second.end())
			{
				it_s->second.erase(it_p);
			}
		}
	}
	else
	{
		return;
	}
	VehicleDriverPosMap::iterator it_s = m_vehicleDriverPosMap.find(card->id);
	if (it_s != m_vehicleDriverPosMap.end())
	{
		m_vehicleDriverPosMap.erase(it_s);
	}
}

void CYAServerDlg::add_person_meanpos(std::shared_ptr<Card> card)
{
	std::shared_ptr<DeptVehicleDriver> dept;
	DeptVehicleDriverMap::iterator it_d = m_deptVehicleDriverMap .find(card->dept_id);
	if (it_d == m_deptVehicleDriverMap.end())
	{
		return;
	}

	if (card->worktype_id == 16 )
	{		
		if (dept->CoalMiningDriver.size()>0)
		{
			std::map<int ,std::vector<int>>::iterator it_s =  it_d->second->CoalMiningDriver.begin();
			std::vector<int>::iterator it_p = std::find(it_s->second.begin(),it_s->second.end(),card->id);
			if (it_p == it_s->second.end())
			{
				it_s->second.push_back(card->id);
			}
		}

	}
	else if (card->card_type == 40)
	{
		if (dept->DrivingDriver.size()>0)
		{
			std::map<int ,std::vector<int>>::iterator it_s =  it_d->second->DrivingDriver.begin();
			std::vector<int>::iterator it_p = std::find(it_s->second.begin(),it_s->second.end(),card->id);
			if (it_p != it_s->second.end())
			{
				it_s->second.push_back(card->id);
			}
		}
	}
	else
	{
		return;
	}
	
	std::shared_ptr<VehicleDriverPos> pos	 = std::make_shared<VehicleDriverPos>();
	pos->PointNum = 0;
	pos->Sum_x = 0.;
	pos->Sum_y = 0.;
	pos->isOn = false;
	m_vehicleDriverPosMap[card->id] = pos;
}
/*获取挖煤机或掘进机对应的司机列表
*
* param
*		dept_id	---		车卡信息
*		worktype_id	---		工种（16为采煤机司机，40位挖掘机司机）
*		driverList	---		司机id列表
* 
* return
*	
*/
int CYAServerDlg::get_vehicle_driverlist(int dept_id, int worktype_id, std::vector<int>& driverList)
{
	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	sprintf_s(buf, "SELECT staff_id FROM dat_staff_extend  WHERE worktype_id = %d and dept_id= %d;",
		worktype_id,dept_id);
	
	pRes = getMysqlRes(buf);
	if (NULL == pRes)
	{
		return 1;
	}
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))	
	{
		driverList.push_back(atoi(pRow[0])) ;
		nRow++;
	}
	mysql_free_result(pRes);
	return 0;
}

afx_msg LRESULT CYAServerDlg::OnRemoveSocket(WPARAM wParam, LPARAM lParam)
{
	CONNID dwConnID = (CONNID)lParam;
	remove_socket(dwConnID);
	return 0;
}

void CYAServerDlg::init_queuestring()
{
	m_qsmSQL = new QueueStrManager(SQL_EXECUTE_SENTENCE_COUNT_MAX,
		SQL_SENTENCE_LENGTH_MAX, _exec_sql);//50,7500
}

BOOL CYAServerDlg::SendData( CONNID dwConnID, WORD wCharacterWord, int wLength, BYTE* DataBuffer )
{
	BYTE SendBuffer[LENGTH_MSG_2K];
	WORD nlength = wLength + sizeof(WORD) + sizeof(WORD); //socket的数据长度 数据的长度(n) + 特征字(2) + 校验码（2）
	memset(SendBuffer, 0, LENGTH_MSG_2K);

	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);
	debug_print_syslog(0, "send_call_info: %d, %.2X, %d", dwConnID, wCharacterWord, wLength);
	BOOL ret = _server.Send(dwConnID, &SendBuffer[0], nPos);
	Sleep(5);
	if(m_log_raw_data){
		std::string strbuf = "";
		formatByteArray(strbuf, SendBuffer, nPos);
		debug_print_syslog(0, "send_call_info: %s", strbuf.c_str());
	}

	return ret;
}

void CYAServerDlg::parse_data_locate_card_his_tdoa( BYTE* DataBuffer, int nLen, int reader_id, DWORD wTickCount, CString strTime)
{
	// 按时间分组解析
	// 组长度
	int nCurPos = 0;

	// 数据保存时间 7字节，年，月，周，日，时，分，秒
	BYTE btSec = 0;
	memcpy(&btSec, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btMin = 0;
	memcpy(&btMin, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btHour = 0;
	memcpy(&btHour, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btDay = 0;
	memcpy(&btDay, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btWeek = 0;
	memcpy(&btWeek, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btMonth = 0;
	memcpy(&btMonth, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btYear = 0;
	memcpy(&btYear, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	CString strhistime;
	strhistime.Format(_T("20%.2d-%.2d-%.2d %.2d:%.2d:%.2d"), btYear%100, btMonth, btDay, btHour, btMin, btSec );				

	std::shared_ptr<BYTE> sp_bt(new BYTE[nLen],[](BYTE* bt){
		delete[] bt;
	});
	BYTE* bt = sp_bt.get();

	while(nCurPos < nLen){ // 一组数据
		// 一个数据包
		WORD wPkgLen = 0;
		CFunctions::getWord(DataBuffer, &wPkgLen, nCurPos);
		nCurPos += sizeof(WORD);

		if(bt){
			memset(bt, 0, nLen);
			memcpy(bt, &DataBuffer[nCurPos], wPkgLen);
			parse_data_locate_card_his_tdoa_package(bt, wPkgLen, reader_id, wTickCount, strTime, strhistime);
		}
		nCurPos += wPkgLen;
	}
}

void CYAServerDlg::parse_data_locate_card_his_tdoa_package( BYTE* DataBuffer, int nLen, int reader_id, DWORD wTickCount, CString strTime, CString strHistTime )
{
	// 命令字
	int nCurPos = 0;
	WORD wChr = 0;
	CFunctions::getWord(DataBuffer, &wChr, nCurPos);
	nCurPos += sizeof(WORD);

	BYTE* bt = new BYTE[LENGTH_RECORD_MAX];
	if(NULL == bt){
		return;
	}
	while(nCurPos < nLen){
		switch (wChr)
		{
		case CHAR_LOCATEDATA:
			{
				memset(bt, 0, LENGTH_RECORD_MAX);
				memcpy(bt, &DataBuffer[nCurPos], LENGTH_TOF_VEHICLE);
				parse_data_locate_card_his_tof_card(bt, LENGTH_TOF_VEHICLE, reader_id, wTickCount, strTime, strHistTime);
				nCurPos += LENGTH_TOF_VEHICLE;
				break;
			}
		case CHAR_LOCATEDATA_TDOA:
			{
				memset(bt, 0, LENGTH_RECORD_MAX);
				memcpy(bt, &DataBuffer[nCurPos], LENGTH_TDOA_VEHICLE);
				parse_data_locate_card_his_tdoa_card(bt, LENGTH_TOF_VEHICLE, reader_id, wTickCount, strTime, strHistTime);
				nCurPos += LENGTH_TDOA_VEHICLE;
				break;
			}
		case CHAR_READER_SYNC_TIME:
			{
				memset(bt, 0, LENGTH_RECORD_MAX);
				memcpy(bt, &DataBuffer[nCurPos], LENGTH_SYNC_TIME);
				parse_data_locate_card_his_sync_time(bt, LENGTH_TOF_VEHICLE, strTime, strHistTime, CHAR_READER_SYNC_TIME);
				nCurPos += LENGTH_SYNC_TIME;
				break;
			}
		case CHAR_READER_SYNC_TIME_ROOT:
			{
				memset(bt, 0, LENGTH_RECORD_MAX);
				memcpy(bt, &DataBuffer[nCurPos], LENGTH_SYNC_TIME_ROOT);
				parse_data_locate_card_his_sync_time(bt, LENGTH_TOF_VEHICLE, strTime, strHistTime, CHAR_READER_SYNC_TIME_ROOT);
				nCurPos += LENGTH_SYNC_TIME;
				break;
			}
		default:
			break;
		}
	}
	delete[] bt;
	bt = NULL;
}

void CYAServerDlg::parse_data_locate_card_his_tof_card( BYTE* DataBuffer, int nLen, int reader_id, DWORD wTickCount, CString strTime, CString strHistTime )
{
	int nCurPos = 0;
	BYTE btCardType = 0;
	memcpy(&btCardType, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	DWORD dwCardId = 0;
	CFunctions::getDWord(DataBuffer, &dwCardId, nCurPos);
	nCurPos += sizeof(DWORD);

	string str_card_id = CFunctions::getstrwithzero(btCardType, 3) + CFunctions::getstrwithzero(dwCardId, 10);

	char sql[LENGTH_SQL] = {0};
	bool b_exec = false;

	//报文时间
	WORD wCardTickCount = 0;
	CFunctions::getWord(DataBuffer, &wCardTickCount, nCurPos);
	nCurPos += sizeof(WORD);

	BYTE btTypeAndPower = 0;
	memcpy(&btTypeAndPower, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	//报文类型
	BYTE btType = 0;
	btType = (btTypeAndPower >>4) & 0x0F;
	//电池电量
	BYTE btPower = 0;
	btPower = btTypeAndPower & 0x0F;

	BYTE btCallType = 0;
	BYTE btAcceleration = 0;
	BYTE btAngularVelocity = 0;
	switch(btCardType)
	{
	case CT_VEHICLE:
	case CT_COALMINING_MACHINE:
	case CT_TUNNELBORING_MACHINE:
		//角速度值：间隔1代表3度，有正负区分
		memcpy(&btAngularVelocity, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);

		memcpy(&btAcceleration, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);
		break;
	case CT_PERSON:
		//保留	
		memcpy(&btCallType,&DataBuffer[nCurPos],sizeof(BYTE));
		nCurPos += sizeof(BYTE);
		//加速度	
		memcpy(&btAcceleration, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);
		break;
	default:
		{
			break;
		}						
	}

	//定位时间戳Tsp // 字序
	LONG64 lTime1 = 0;
	BYTE btTemp = 0;
	int nRangingPos = nCurPos;
	memcpy(&btTemp, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	DWORD dwTemp = 0;
	CFunctions::getDWord(DataBuffer, &dwTemp, nCurPos);
	nCurPos += sizeof(DWORD);
	lTime1 = btTemp;
	lTime1 = lTime1 << 32;
	lTime1 |= dwTemp;

	double dbldist = CFunctions::getDistance(lTime1, CFunctions::TOF);

	BYTE btAntenna = 0;
	memcpy(&btAntenna, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	btAntenna = btAntenna & 0xFF;

	b_exec = true;
	sprintf_s(sql, LENGTH_SQL,
		"INSERT IGNORE INTO his_raw_data(card_id, reader_id, antenna_id, reader_stamp, card_stamp, \
		fly_time, distance, ranging_type, power_state, accelerate, his_time, rec_time ) \
		VALUES(%s, %d, %d, %d, %d, %lld, %4.f, %d, %d, %d, '%s', '%s');",
		str_card_id.c_str(), reader_id, btAntenna, wTickCount, wCardTickCount, lTime1, dbldist, btType, 
		btPower,btAcceleration,	CFunctions::wc2c(strHistTime), CFunctions::wc2c(strTime));

	if (b_exec)
	{
		execute_sql(sql);
	}
}

void CYAServerDlg::parse_data_locate_card_his_tdoa_card( BYTE* DataBuffer, int nLen, int reader_id, DWORD wTickCount, CString strTime, CString strHistTime )
{
	int nCurPos = 0;
	BYTE btCardType = 0;
	memcpy(&btCardType, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	DWORD dwCardId = 0;
	CFunctions::getDWord(DataBuffer, &dwCardId, nCurPos);
	nCurPos += sizeof(DWORD);

	string str_card_id = CFunctions::getstrwithzero(btCardType, 3) + CFunctions::getstrwithzero(dwCardId, 10);

	char sql[LENGTH_SQL] = {0};
	bool b_exec = false;

	switch(btCardType)
	{
	case CT_VEHICLE:
	case CT_COALMINING_MACHINE:
	case CT_TUNNELBORING_MACHINE:
	case CT_PERSON:
		{
			//报文时间
			WORD wCardTickCount = 0;
			CFunctions::getWord(DataBuffer, &wCardTickCount, nCurPos);
			nCurPos += sizeof(WORD);

			BYTE btTypeAndPower = 0;
			memcpy(&btTypeAndPower, &DataBuffer[nCurPos], sizeof(BYTE));
			nCurPos += sizeof(BYTE);
			//报文类型
			BYTE btType = 0;
			btType = (btTypeAndPower >>4) & 0x0F;
			//电池电量
			BYTE btPower = 0;
			btPower = btTypeAndPower & 0x0F;

			//保留
			nCurPos += sizeof(BYTE);
			//加速度
			BYTE btAcceleration = 0;
			memcpy(&btAcceleration, &DataBuffer[nCurPos], sizeof(BYTE));
			nCurPos += sizeof(BYTE);

			//定位时间戳Tsp // 字序
			LONG64 lTime1 = 0;
			BYTE btTemp = 0;
			int nRangingPos = nCurPos;
			memcpy(&btTemp, &DataBuffer[nCurPos], sizeof(BYTE));
			nCurPos += sizeof(BYTE);
			DWORD dwTemp = 0;
			CFunctions::getDWord(DataBuffer, &dwTemp, nCurPos);
			nCurPos += sizeof(DWORD);
			lTime1 = btTemp;
			lTime1 = lTime1 << 32;
			lTime1 |= dwTemp;

			double dbldist = 0;

			BYTE btAntenna = 0;
			memcpy(&btAntenna, &DataBuffer[nCurPos], sizeof(BYTE));
			nCurPos += sizeof(BYTE);
			btAntenna = btAntenna & 0xFF;

			// 分站时间同步序列号
			WORD wSyncNum = 0;
			CFunctions::getWord(DataBuffer, &wSyncNum, nCurPos);
			nCurPos += sizeof(WORD);
			// 信号强度
			WORD wStrength = 0;
			CFunctions::getWord(DataBuffer, &wStrength, nCurPos);
			nCurPos += sizeof(WORD);

			double dblaccx, dblaccy, dblaccz;
			dblaccx = dblaccy = dblaccz = 0;

			b_exec = true;
			sprintf_s(sql, LENGTH_SQL,
				"INSERT IGNORE INTO his_raw_data_tdoa(card_id, reader_id, antenna_id, reader_stamp, card_stamp, \
				fly_time, distance, ranging_type, power_state, accelerate, his_time, rec_time, sync_num, strength, acc_x, acc_y, acc_z) \
				VALUES(%s, %d, %d, %d, %d, %lld, %4.f, %d, %d, %d, '%s', '%s', %d, %d, %4.f, %4.f, %4.f);",
				str_card_id.c_str(), reader_id, btAntenna, wTickCount, wCardTickCount, lTime1, dbldist, btType, 
				btPower,btAcceleration,	CFunctions::wc2c(strHistTime), CFunctions::wc2c(strTime), wSyncNum, wStrength, dblaccx, dblaccy, dblaccz);
			break;
		}
	default:
		{
			break;
		}						
	}

	if (b_exec)
	{
		execute_sql(sql);
	}
}

void CYAServerDlg::parse_data_locate_card_his_sync_time( BYTE* DataBuffer, int nLen, CString strTime, CString strHistTime, WORD wChr )
{
	char sql[LENGTH_SQL] = {0};
	bool b_exec = false;
	int nCurPos = 0;

	DWORD dwReaderID = 0; // 本机分站号
	CFunctions::getDWord(DataBuffer, &dwReaderID, nCurPos);
	nCurPos += sizeof(DWORD);

	BYTE btAnt = 0; // 本机发送天线
	memcpy(&btAnt, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	DWORD dwUpperReaderID = 0;  //root分站号
	CFunctions::getDWord(DataBuffer, &dwUpperReaderID, nCurPos);
	nCurPos += sizeof(DWORD);

	BYTE btUpperAnt = 0;		//root天线
	memcpy(&btUpperAnt, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	WORD wSyncNum = 0;			//序列号
	CFunctions::getWord(DataBuffer, &wSyncNum, nCurPos);
	nCurPos += sizeof(WORD);

	WORD wSyncLevel = 0; // 同步等级
	CFunctions::getWord(DataBuffer, &wSyncLevel, nCurPos);
	nCurPos += sizeof(WORD);

	LONG64 lTime1 = 0, lTime2 = 0;
	BYTE btTemp = 0;
	memcpy(&btTemp, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	DWORD dwTemp = 0;
	CFunctions::getDWord(DataBuffer, &dwTemp, nCurPos);
	nCurPos += sizeof(DWORD);
	lTime1 = btTemp; // 本机发送时间戳
	lTime1 = lTime1 << 32;
	lTime1 |= dwTemp;

	btTemp = 0;
	dwTemp = 0;
	memcpy(&btTemp, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	CFunctions::getDWord(DataBuffer, &dwTemp, nCurPos);
	nCurPos += sizeof(DWORD);
	lTime2 = btTemp; // 本机接收时间戳
	lTime2 = lTime2 << 32;
	lTime2 |= dwTemp;

	DWORD dwRootReaderID = 0; // root分站号
	BYTE btRootAnt = 0; // root天线

	if(CHAR_READER_SYNC_TIME_ROOT == wChr){
		CFunctions::getDWord(DataBuffer, &dwRootReaderID, nCurPos);
		nCurPos += sizeof(DWORD);

		memcpy(&btRootAnt, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);
	}

	sprintf_s(sql, LENGTH_SQL,
		"INSERT IGNORE INTO his_raw_data_sync_time(reader_id, ant_id, parent_reader_id, parent_ant_id, sync_num, sync_level,\
		send_timestamp, rec_timestamp, his_time, rec_time, root_reader_id, root_ant_id) \
		VALUES(%d, %d, %d, %d, %d, %d, %lld, %lld, '%s', '%s', %d, %d);",
		dwReaderID, btAnt, dwUpperReaderID, btUpperAnt , wSyncNum, wSyncLevel, lTime1, lTime2,
		CFunctions::wc2c(strHistTime), CFunctions::wc2c(strTime), dwRootReaderID, btRootAnt);

	execute_sql(sql);
}

void CYAServerDlg::OnEnUpdateEditReaderid()
{
	// TODO:  在此添加控件通知处理程序代码
	UpdateData(TRUE);
}

void CYAServerDlg::parse_json_data_call_card_cancel(message::ptr const& data )
{
	CString strlog;
	string user_name;
	string cardid, readerid;
	int call_time_out, reader_count, card_count, call_type_id;

	int64_t call_time;

	map<string,message::ptr> data_map = data->get_map()[JSON_ROOT_KEY_DATA]->get_map();
	// 呼叫类型，0全员，1定员
	call_type_id = data_map[JSON_KEY_CALL_CARD_CALL_TYPE]->get_int();
	user_name = data_map[JSON_KEY_CALL_CARD_USER_NAME]->get_string();
	call_time = data_map[JSON_KEY_CALL_CARD_CALL_TIME]->get_int();

	vector<message::ptr> reader_vec = data_map[JSON_KEY_CALL_CARD_STATIONS]->get_vector();
	vector<message::ptr> card_vec = data_map[JSON_KEY_CALL_CARD_CARDS]->get_vector();

	if(reader_vec.size() == 0 && card_vec.size() == 0)
	{
		return;
	}

	int reader_id, npos;
	SocketMap::iterator it_sock;
	BYTE buf[LENGTH_SEND_BUF];

	std::shared_ptr<_call_info_user> call_user;
	std::shared_ptr<_call_info_reader> call_reader;
	_call_info_card* call_card;
	//取消呼叫有两种：
	//取消全员呼叫
	//对指定卡取消呼叫
	CallInfoUserMap::iterator it_call_user = mp_user_call_info.find(user_name);
	if(it_call_user != mp_user_call_info.end())
	{
		EnterCriticalSection(&m_csCallInfo);

		// 取消全员呼叫
		if(CALL_CARD_TYPE::CCT_CALL_ALL == call_type_id)
		{
			// 删除该用户所有呼叫信息
			clear_call_card_by_user(user_name);
		}
		// 取消定员呼叫
		else
		{
			// 遍历删除指定呼叫信息
			vector<message::ptr>::const_iterator it_card = card_vec.begin();
			BYTE card_type = 0;
			CallInfoCardMap::iterator it_call_card;
			for(; it_card != card_vec.end(); ++it_card){
				string s_card_id = (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_ID]->get_string();
				card_type = (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID]->get_int();

				CallInfoReaderMap::iterator it_reader = it_call_user->second->mpReader.begin();
				for(; it_reader != it_call_user->second->mpReader.end();)
				{
					// 删除分站内的卡
					it_call_card = it_reader->second->mpCard.find(s_card_id);
					if(it_call_card != it_reader->second->mpCard.end())
					{
						it_reader->second->mpCard.erase(it_call_card);
					}

					if(it_reader->second->mpCard.size() > 0)
					{
						++it_reader;
					}
					else
					{
						// 如果分站中卡为空，删除分站
						it_reader = it_call_user->second->mpReader.erase(it_reader);
					}
				}
			}
		}

		// 没有呼叫信息，删除该用户记录
		if(0 == it_call_user->second->mpReader.size())
		{
			mp_user_call_info.erase(it_call_user);
		}

		LeaveCriticalSection(&m_csCallInfo);
	}

	//取消呼叫
	Json::Value root;
	Json::Value resp_data;
	Json::Value callinfo;
	Json::Value stations;
	Json::Value cards;

	callinfo[JSON_KEY_CALL_CARD_CALL_TYPE]   = call_type_id;
	callinfo[JSON_KEY_CALL_CARD_CALL_TIME] =(double)call_time;
	callinfo[JSON_KEY_CALL_CARD_USER_NAME] = user_name;

	//构造stations和cards
	for (vector<message::ptr>::const_iterator it_reader = reader_vec.begin();it_reader != reader_vec.end();++it_reader)
	{
		Json::Value station;
		reader_id = (*it_reader)->get_map()[JSON_KEY_CALL_CARD_STATION_ID]->get_int();
		station[JSON_KEY_CALL_CARD_STATION_ID] = reader_id;
		stations.append(station);
	}
	for (vector<message::ptr>::const_iterator it_card = card_vec.begin();it_card != card_vec.end();++it_card)
	{
		Json::Value card;

		card[JSON_KEY_CALL_CARD_CARD_ID] = (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_ID]->get_string();
		card[JSON_KEY_CALL_CARD_CARD_TYPE_ID] = (int)(*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID]->get_int();
		cards.append(card);
	}

	callinfo[JSON_KEY_CALL_CARD_STATIONS] = stations;
	callinfo[JSON_KEY_CALL_CARD_CARDS]    = cards;

	std::string ret = "";

	if(callinfo.size() > 0){
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_CALL_CARD_CANCEL_RESPONSE;
		root[JSON_ROOT_KEY_DATA] = callinfo;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION;
		ret = root.toFastString();
		send_json_data(JSON_CMD_VALUE_PUSH,ret);
	}

	strlog.Format(_T("%s%s"), _T(LOG_CANCEL_CALL_CARD), _T(LOG_SUCCESS));
	show_log(strlog);
}

void CYAServerDlg::OnAbout()
{
	// TODO: 在此添加命令处理程序代码
	CAboutDlg dlg;
	dlg.DoModal();
}

void CYAServerDlg::OnReConnect( unsigned, unsigned )
{
	is_websocket_login = false;
	is_websocket_ok = false;
}

int CYAServerDlg::init_patrol_info(std::string card_id) //int task_id)
{
	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};

	if(card_id == ""){
		sprintf_s(buf, "select pt.patrol_task_id, s.card_id, pt.staff_id, pt.start_time, pt.end_time,\
					   ppd.patrol_point_id, ppd.idx, ppd.duration_last, ppd.duration_stay_min, ppd.duration_stay_max,\
					   ppd.duration_ranging, ps.x, ps.y, ps.z, ps.map_id, ps.ranging, pt.patrol_path_id\
					   from dat_patrol_task pt, dat_patrol_path_detail ppd, dat_patrol_point ps, dat_staff_extend s\
					   where pt.patrol_path_id = ppd.patrol_path_id and ppd.patrol_point_id = ps.patrol_point_id\
					   and pt.staff_id = s.staff_id -- and pt.end_time >= curtime()\
					   and not exists(select 1 from dat_patrol_task where staff_id = pt.staff_id and start_time < pt.start_time)\
					   order by pt.patrol_task_id, ppd.idx");
	}else{
		sprintf_s(buf, "select pt.patrol_task_id, s.card_id, pt.staff_id, pt.start_time, pt.end_time,\
					   ppd.patrol_point_id, ppd.idx, ppd.duration_last, ppd.duration_stay_min, ppd.duration_stay_max,\
					   ppd.duration_ranging, ps.x, ps.y, ps.z, ps.map_id, ps.ranging, pt.patrol_path_id\
					   from dat_patrol_task pt, dat_patrol_path_detail ppd, dat_patrol_point ps, dat_staff_extend s\
					   where s.card_id = %s and pt.patrol_path_id = ppd.patrol_path_id and ppd.patrol_point_id = ps.patrol_point_id\
					   and pt.staff_id = s.staff_id -- and pt.end_time >= curtime()\
					   and not exists(select 1 from dat_patrol_task where staff_id = pt.staff_id and start_time < pt.start_time)\
					   order by pt.patrol_task_id, ppd.idx;", card_id.c_str());
	}

	pRes = getMysqlRes(buf);

	if (NULL == pRes)
	{
		return 1;
	}

	std::shared_ptr<PatrolTask> pTask = nullptr;
	std::shared_ptr<PatrolPoint> pPatrolPoint = nullptr;
	int nRow = 0;
	int tmp_task_id = 0, last_task_id = 0;
	int tmp_duration = 0;
	std::string tmp_time;
	while(pRow = mysql_fetch_row(pRes)){
		tmp_task_id = atoi(pRow[0]);
		if(tmp_task_id != last_task_id){
			last_task_id = tmp_task_id;
			nRow++;

			PatrolTaskCheckMap::iterator it_card_task = mp_card_task_list.find(pRow[1]); // 卡的任务列表
			if(it_card_task != mp_card_task_list.end()){
				pTask = it_card_task->second; // 查找到本条任务
			}else{
				pTask = std::make_shared<PatrolTask>();
				pTask->patrol_task_id = atoi(pRow[0]);
				pTask->card_id = pRow[1];
				pTask->starffer_id = pRow[2];
				pTask->patrol_path_id = atoi(pRow[16]);
				//tmp_time = pRow[3];
				API_StringToTime(pRow[3], pTask->start_time);
				API_StringToTime(pRow[4], pTask->end_time);
				mp_card_task_list.insert(make_pair(pRow[1], pTask));
			}

			tmp_duration = 0;
		}		
		tmp_duration += atoi(pRow[12]);
		PatrolPointMap::iterator it_point = pTask->mpPoint.find(atoi(pRow[5]));
		if(it_point != pTask->mpPoint.end()){
			pPatrolPoint = it_point->second;
		}else{
			pPatrolPoint = std::make_shared<PatrolPoint>();
			pPatrolPoint->idx = atoi(pRow[5]);
		}
		pPatrolPoint->patrol_point_id = atoi(pRow[6]);
		pPatrolPoint->x = atof(pRow[7]);
		pPatrolPoint->y = atof(pRow[8]);
		pPatrolPoint->z = atof(pRow[9]);
		pPatrolPoint->map_id = atoi(pRow[10]);
		pPatrolPoint->ranging = atof(pRow[11]);
		pPatrolPoint->duration_last = tmp_duration; //atoi(pRow[12]);
		pPatrolPoint->duration_stay_min = atoi(pRow[13]);
		pPatrolPoint->duration_stay_max = atoi(pRow[14]);
		pPatrolPoint->duration_ranging = atoi(pRow[15]);
	}
	mysql_free_result(pRes);
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_PATROL), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;	
}

void CYAServerDlg::deal_call_edit_patrol_task( string id, EDIT_TYPE_ID edit_type_id )
{
	CString strlog = _T("");
	switch (edit_type_id)
	{
	case ET_INSERT:
	case ET_UPDATE:
		{
			init_patrol_info(id);
			break;
		}
	case ET_DELETE:
		{
			PatrolTaskCheckMap::iterator it_task = mp_card_task_list.begin();
			for(; it_task != mp_card_task_list.end(); ++it_task){
				if(it_task->second->card_id == id){
					mp_card_task_list.erase(it_task);
					break;
				}
			}
			break;
		}
	default:
		break;
	}
	strlog.Format(_T("%s%s"), _T(LOG_EDIT_PATROL_TASK), _T(LOG_SUCCESS));
	show_log(strlog);
}

void CYAServerDlg::check_patrol()
{
	std::shared_ptr<PatrolTask> pTask = nullptr;
	std::shared_ptr<Card> pCard = nullptr;
	std::shared_ptr<PatrolPoint> pPoint, pNextPoint = nullptr;
	double cur_point_dist = 0;
	time_t tmp_time = time(NULL);
	PatrolTaskCheckMap::iterator it_card_task = mp_card_task_list.begin();
	for(; it_card_task != mp_card_task_list.end(); ++it_card_task){
		pTask = it_card_task->second;
		CardMap::iterator it_card = mp_card_list_down_person.find(pTask->card_id);
		if(it_card != mp_card_list_down_person.end()){
			pCard = it_card->second;
			PatrolPointMap::iterator it_point = pTask->mpPoint.find(pTask->cur_point_idx); //

			if(it_point != pTask->mpPoint.end()){
				pPoint = it_point->second;
				pNextPoint = (++it_point)->second;
				cur_point_dist = sqrt(pow(pCard->x - pPoint->x, 2) + pow(pCard->y - pPoint->y, 2) + pow(pCard->z - pPoint->z, 2));
				if(!pTask->is_in_cur_point){ // 未进入当前节点区域
					if(cur_point_dist < pPoint->ranging){ // 在合法范围内
						pTask->is_in_cur_point = true;
						pTask->enter_time = tmp_time;
						// 当前时间小于应到时间
						if(difftime(pTask->start_time, tmp_time) < (pPoint->duration_last - pPoint->duration_ranging) * 60){
							// 早到						
							pTask->state = PS_EARLY;
						}else if(difftime(pTask->start_time, tmp_time) <= (pPoint->duration_last + pPoint->duration_ranging ) * 60 &&  // 在合理时间范围
							difftime(pTask->end_time, tmp_time) >= (pPoint->duration_last - pPoint->duration_ranging) * 60){
								// 正常
								pTask->state = PS_NORMAL;
						}else if(difftime(pTask->start_time, tmp_time) > (pPoint->duration_last + pPoint->duration_ranging) * 60){ // 超过最晚应到时间
							// 迟到
							pTask->state = PS_LATE;
						}
					}else{ // 不再范围内，判断是否超过最晚应到时间，超过，直接按未到计算（即按照下一节点计算）
						if(difftime(pTask->start_time, tmp_time) > (pPoint->duration_last + pPoint->duration_ranging) * 60){
							pTask->state = PS_NON_ARRIVAL;
							//保存数据本节点数据
							save_patrol_data(pTask, pPoint);
							pTask->cur_point_idx++;
						}
					}					
				}else{ // 已进入当前节点区域
					if(cur_point_dist > pPoint->ranging){ // 在合法范围外，即离开合法范围
						pTask->is_in_cur_point = false;
						pTask->leave_time = tmp_time;

						pTask->duration_stay = difftime(pTask->leave_time, pTask->enter_time);
						if(pTask->duration_stay < pPoint->duration_stay_min){
							pTask->stay_state = PSS_TOO_SHORT;
						}else if(pTask->duration_stay <= pPoint->duration_stay_max){
							pTask->stay_state = PSS_NORMAL;
						}else{
							pTask->stay_state = PSS_TOO_LONG;
						}

						// 保存本节点数据
						save_patrol_data(pTask, pPoint);
						pTask->cur_point_idx++;
					}
				}				
			}
		}
	}
}

void CYAServerDlg::save_patrol_data( std::shared_ptr<PatrolTask> pTask, std::shared_ptr<PatrolPoint> pPoint )
{
	char sql[LENGTH_SQL] = {'\0'};
	char _time[STR_LEN_TIME], _time_ex[STR_LEN_TIME];
	struct tm local_time, local_time_ex;
	localtime_s(&local_time, &pTask->enter_time);
	localtime_s(&local_time_ex, &pTask->leave_time);
	strftime(_time, 30, "%Y-%m-%d %H:%M:%S", &local_time);
	strftime(_time_ex, 30, "%Y-%m-%d %H:%M:%S", &local_time_ex);

	sprintf_s(sql, LENGTH_SQL, 
		"INSERT IGNORE INTO his_patrol_data(patrol_task_id, patrol_path_id, patrol_point_id, idx, enter_time, leave_time, patrol_state_id, patrol_stay_state_id, card_id)\
		values(%d, %d, %d, %d, '%s', '%s', %d, %d, '%s');",
		pTask->patrol_task_id, pTask->patrol_path_id, pPoint->patrol_point_id, pPoint->idx, _time, _time_ex, pTask->state, pTask->stay_state, pTask->card_id.c_str());
	execute_sql(sql);

	CardMap::iterator it_card = mp_card_list_down_person.find(pTask->card_id);
	if(it_card != mp_card_list_all.end())
	{
		INT64 ev_id = it_card->second->m_event_list[ET_CARD_PATROL_ERROR];
		if(0 == ev_id) // 之前没有告警
		{
			if(pTask->state != PS_NORMAL || pTask->stay_state != PSS_NORMAL) // 现在有告警
			{
				ev_id = CFunctions::GetMicroSecond();
				std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
				ev->status = ES_START;
				ev->ev_type = ET_CARD_PATROL_ERROR;
				ev->obj_type = OT_CARD;
				ev->obj_id = it_card->first;
				ev->cur_time = time(NULL);

				ev->map_id = it_card->second->map_id;
				ev->area_id = it_card->second->area_id;
				ev->x = it_card->second->x;
				ev->y = it_card->second->y;
				ev->landmarkid = it_card->second->landmark_id;
				ev->landmarkdirect = it_card->second->landmark_direction;
				ev->landmarkdist = it_card->second->landmark_dis;

				ev->is_sent = false;

				it_card->second->m_event_list[ET_CARD_PATROL_ERROR] = ev_id;
				store_data_event(ev);
				add_event(ev);
				Sleep(1);
			}
		}
		else
		{
			EventMap::iterator it_ev = mp_event_list->find(ev_id);
			if(it_ev != mp_event_list->end()){
				if(pTask->state == PS_NORMAL && pTask->stay_state == PSS_NORMAL) // 之前有告警，当前告警结束
				{
					it_ev->second->status = ES_END;
					it_ev->second->cur_time = time(NULL);

					it_ev->second->map_id = it_card->second->map_id;
					it_ev->second->area_id = it_card->second->area_id;
					it_ev->second->x = it_card->second->x;
					it_ev->second->y = it_card->second->y;
					it_ev->second->landmarkid = it_card->second->landmark_id;
					it_ev->second->landmarkdirect = it_card->second->landmark_direction;
					it_ev->second->landmarkdist = it_card->second->landmark_dis;

					it_ev->second->is_sent = false;
					store_data_event(it_ev->second);
					add_event(it_ev->second);

					it_card->second->m_event_list[ET_CARD_PATROL_ERROR] = 0;
				}
				else // 更新告警信息
				{
					it_ev->second->status = ES_START;
					it_ev->second->cur_time = time(NULL);

					it_ev->second->map_id = it_card->second->map_id;
					it_ev->second->area_id = it_card->second->area_id;
					it_ev->second->x = it_card->second->x;
					it_ev->second->y = it_card->second->y;
					it_ev->second->landmarkid = it_card->second->landmark_id;
					it_ev->second->landmarkdirect = it_card->second->landmark_direction;
					it_ev->second->landmarkdist = it_card->second->landmark_dis;

					it_ev->second->is_sent = false;
				}	
			}
		}
	}
}

int CYAServerDlg::delete_patrol_info( std::string card_id )
{
	return 0;

	PatrolTaskCheckMap::iterator it_card_task = mp_card_task_list.find(card_id); // 卡的任务列表
	if(it_card_task != mp_card_task_list.end()){
		mp_card_task_list.erase(it_card_task);
	}
	return 0;
}

int CYAServerDlg::get_special_area_id(shared_ptr<Card> card)
{
	int specail_area_id = -1;	
	SpecilaAreaEntryMap::iterator it = mp_special_area_entry_list.begin();
	for(; it != mp_special_area_entry_list.end(); ++it)
	{
		if((card->x <= max(it->second->start_point_x, it->second->end_point_x))
			&&(card->x >= min(it->second->start_point_x, it->second->end_point_x))
			&&(card->y <= max(it->second->start_point_y, it->second->end_point_y))
			&&(card->y >= min(it->second->start_point_y, it->second->end_point_y))
			&&(card->z <= max(it->second->start_point_z, it->second->end_point_z))
			&&(card->z >= min(it->second->start_point_z, it->second->end_point_z))
			)
		{
			if (it->second->car_type!="")
			{
				std::size_t npos = it->second->car_type.find(card->vehicle_category_id);
				if (npos != std::string::npos)
				{
					specail_area_id = it->second->special_area_id;
				}
				else
				{
					specail_area_id = it->second->union_area_id;
				}
			}
			else
				specail_area_id = it->second->special_area_id;
			break;
		}
	}
	if(!m_sc.find(specail_area_id,card->id))
		specail_area_id = -1;
	return specail_area_id;
}

void CYAServerDlg::deal_card_lost_state()
{
	time_t time_current = time(NULL);
	STATUS_CARD nLost = STATUS_NORMAL;

	std::shared_ptr<Card> card = nullptr;
	double diff_rec = 0;
	// lihongzhen  2017/8/22 使用send_json_postion 目的是为了web前端动画流畅
	//int read_cache_interval = min(theApp.send_json_postion/1000, CARD_LOST_TIME_CAL);
	// zhuyf 2018/07/11 5秒之后开始清掉缓存队列
	int read_cache_interval = max(theApp.send_json_postion/1000, CARD_LOST_TIME_CAL);
	//补全区域信息
	CardMap::iterator it_staff_up = mp_card_list_up_person.begin();
	for(;it_staff_up != mp_card_list_up_person.end();)
	{
		string str = it_staff_up->second->store_data_card(HIS_AREA_LOCATION_LEAVE);
		execute_sql(str.c_str());
		mp_card_list_up_person.erase(it_staff_up++);
		debug_print_syslog(0,"[lemon mp_card_list_up_person: Area Info Complemented] %s",str.c_str());
	}

	CardMap::iterator it_staff = mp_card_list_down_person.begin();
	for (; it_staff != mp_card_list_down_person.end();)
	{
		std::shared_ptr<Card> card_staff = it_staff->second;
		it_staff++;
		diff_rec = difftime(time_current, card_staff->rec_time);
		// lihongzhen  2017/8/22 将缓存的数据读出来
		if(diff_rec > read_cache_interval && card_staff->dist_cache_size() > 0)
		{
			debug_print_syslog(0,"[zhuyf cal_pos_by_cache: diff_sec: %.3f,read_cache_interval: %d, dist_cache_size:%d.",diff_rec , read_cache_interval , card_staff->dist_cache_size());
			card_staff->cal_pos_by_cache();
			continue;
		}

		//lemon attendance incomplete
		uint64_t diff_down=time_current-card_staff->down_time;
		if(diff_down>sls_setting.att_person_thre_hour && diff_rec>CARD_ATTENDANCE_TIMEOUT)
		{
			debug_print_syslog(0,"[person_att %s]timeoff>%lld then up mine..",card_staff->card_id.c_str(),diff_down);
			// 升井
			string str_down_time = CFunctions::time_t2string(card_staff->down_time);

			card_staff->up_time = time(NULL);
			card_staff->PosState(PDT_UP);
			store_data_card(card_staff, HIS_AREA_LOCATION_LEAVE);
			card_enter_mine(card_staff, POS_DEVICE_TYPE::PDT_UP);

			char nsql[512]={ 0 };
			char *sql = "update rpt_att_staff set is_auto=%d where card_id=%s and start_time='%s';";
			sprintf_s(nsql,512,sql,1,card_staff->card_id.c_str(),str_down_time.c_str());
			m_qsmSQL->AddString(nsql);
			debug_print_syslog(0,"person_att...%s",nsql);

			card_enter_mine(it_staff->second, POS_DEVICE_TYPE::PDT_UP);	
		}

		nLost = diff_rec < CARD_LOST_TIME_OUT ? STATUS_NORMAL : STATUS_LOST;
		card = nullptr;
		if (card_staff->status_lost != nLost)
		{
			card_staff->status_lost = nLost;
			if (nLost == STATUS_LOST)
			{
				card = card_staff;
			}
		}
		if(card)
		{
			//人卡信号丢失，而且当前的状态是井上。则补全区域信息。
			card->reset();
		}
	}

	nLost = STATUS_NORMAL;
	card = nullptr;
	CardMap::iterator it_vehicle = mp_card_list_down_vehicle.begin();
	for(; it_vehicle != mp_card_list_down_vehicle.end(); )
	{
		diff_rec = difftime(time_current, it_vehicle->second->rec_time);
		if(diff_rec > read_cache_interval && it_vehicle->second->dist_cache_size() > 0)
		{
			it_vehicle->second->cal_pos_by_cache();
			++it_vehicle;
			continue;
		}
		nLost =  diff_rec < CARD_LOST_TIME_OUT ? STATUS_NORMAL :STATUS_LOST;

		card = it_vehicle->second;
		++it_vehicle;

		// 丢失数据
		if(card->status_lost != nLost)
		{
			if(STATUS_LOST == nLost)
			{
				::GetLocalTime(&card->deal_time);
				deal_alarm_card(card,mp_card_list_over_speed_vehicle,false,AF_CARD_OVER_SPEED);
				AreaMap::iterator it_area_cur = mp_area_list.find(card->area_id);
				if(it_area_cur != mp_area_list.end())
				{
					deal_alarm_card(card,it_area_cur->second->area_card_list_over_speed,false, AF_CARD_AREA_OVER_SPEED);
					int vid = card->id;
					// 处理非特殊区域的卡
					if(!it_area_cur->second->is_special()){
						// check area is special or not
						int special_area_id = get_special_area_id(card);
						if(-1 != special_area_id)
						{
							card->status_lost = nLost;
							card->idle_count = IDLE_CONFIRM_TIME; // 置为怠速，即进入盲区速度置为0

							card_leave_area(card, it_area_cur->second);
							store_data_card(card, HIS_AREA_LOCATION_LEAVE);

							// 进入特殊区域，生成一条轨迹记录
							card_enter_special_area(card, special_area_id);
							if (need_display_verification(card))// lemon 2017/08/01
							{
								send_json_data(JSON_CMD_VALUE_PUSH, get_json_special_area_process(card));
								debug_print_syslog(0, "lost state, moving: %s", get_json_special_area_process(card).c_str());
							}
							else
							{
								debug_print_syslog(0, "[need_display_no]lost state, moving: %s", get_json_special_area_process(card).c_str());
							}
							//card_enter_mine(card,POS_DEVICE_TYPE::PDT_UP);  // 信号丢失不再统计考勤
						}
						else
						{
							// 非特殊区域超过CARD_LOST_TIME_OUT秒，未接收到数据，升井处理
							if(difftime(time_current, card->rec_time) > CARD_LOST_TIME_OUT_SPECIAL_AREA)
							{
								//----------lemon smooth erase vhicle .. 
								m_carmanage->erase(card->card_id);
								//--------------------------------------
								card->status_lost = nLost;
								//card_enter_mine(card, POS_DEVICE_TYPE::PDT_UP); // 信号丢失不再统计考勤
								debug_print_syslog(0, "lost state, not enter special area: card_id: %s, area_id:%d, speed: %f, x: %f, y: %f, z: %f\n", 
									(card->card_id).c_str(), card->area_id, card->get_speed(), card->x, card->y, card->z);
							}
						}
					}	
				}

				/*if (VT_DIGGINGCOAL_MACHINE == card->vehice_type_id || VT_DRIVINGFACE_MACHINE == card->vehice_type_id)
				{
				card->status_lost = nLost;
				card_enter_mine(card, POS_DEVICE_TYPE::PDT_UP);
				}*/
			}
			else
			{
				card->status_lost = nLost;
			}			
			if(VT_DIGGINGCOAL_MACHINE == card->vehice_type_id || VT_DRIVINGFACE_MACHINE == card->vehice_type_id){
				debug_print_syslog(0,"[drivingface card lost] card_id: %s, x: %.4f, y: %.4f.",card->card_id.c_str(),card->x, card->y);
			}

			//card->resetAllBaseInfo();
			card->reset();
		}
	}
}

void CYAServerDlg::store_data_event( std::shared_ptr<YaEvent> ev )
{
	char sql[LENGTH_SQL] = {'\0'};
	char _time[STR_LEN_TIME];
	struct tm local_time;
	localtime_s(&local_time, &ev->cur_time);
	strftime(_time, STR_LEN_TIME, "%Y-%m-%d %H:%M:%S", &local_time);

	sprintf_s(sql, LENGTH_SQL, 
		"INSERT IGNORE INTO his_event_data(event_id, stat, event_type_id, obj_type_id, obj_id, \
		map_id, area_id, limit_value, cur_value, x, y, cur_time, description, landmark_id, landmark_dist,direction_mapper_id )\
		VALUES(%lld, %d, %d, %d, %s, %d, %d, %.2f, %.2f, %f, %f, '%s', '%s', %d, %d, %10.3f);",
		ev->get_id(), ev->status, ev->ev_type, ev->obj_type, ev->obj_id.c_str(), 
		ev->map_id, ev->area_id, ev->limit_value, ev->cur_value, ev->x, ev->y, _time, ev->desc.c_str(),
		ev->landmarkid, ev->landmarkdirect, ev->landmarkdist);
	execute_sql(sql);
}

void CYAServerDlg::add_event( std::shared_ptr<YaEvent> ev )
{
	EventMap::iterator it_ev = mp_event_list->find(ev->get_id());
	if(it_ev != mp_event_list->end()){
		it_ev->second->status = ev->status ;
		it_ev->second->ev_type = ev->ev_type;
		it_ev->second->obj_type = ev->obj_type;
		it_ev->second->obj_id = ev->obj_id;
		it_ev->second->cur_time = ev->cur_time;
		it_ev->second->map_id = ev->map_id;
		it_ev->second->area_id = ev->area_id;
		it_ev->second->x = ev->x;
		it_ev->second->y = ev->y;
		it_ev->second->limit_value = ev->limit_value;
		it_ev->second->cur_value = ev->cur_value;
		it_ev->second->is_sent = ev->is_sent;
	}else{
		mp_event_list->insert(make_pair(ev->get_id(), ev));
	}
}
void CYAServerDlg::get_json_all_traffic_lights(std::shared_ptr<op::TrafficLightGroup> x)
{
	Json::Value root;
	Json::Value data;
	//for(const auto x : plist)
	{
		auto vt = x->getTrafficLightInfo();
		for (const auto y : vt)
		{
			Json::Value v;
			v.append(std::get<0>(y));
			v.append(std::get<1>(y));
			v.append(std::get<2>(y));
			v.append(std::get<3>(y));
			v.append(std::get<4>(y));
			data.append(v);
			//发送给硬件
			//send_call_light(std::get<6>(y),std::get<2>(y),std::get<5>(y));
			//debug_print_syslog(0,"[TrafficLightGroup]gid:%d,lid:%d,color:%d,port:%d,ip:%s",std::get<0>(y),std::get<1>(y),std::get<2>(y),std::get<6>(y),std::get<5>(y).c_str());

			auto it_light = m_carmanage->getTrafficLight(std::get<1>(y));
			if (nullptr == it_light)
			{
				debug_print_syslog(0,"[traffic light] light_id: %d is not exist.",std::get<1>(y));
				return;
			}
			bool is_postive = it_light->m_physics_direction == 1?true:false;
			op::LIGHT_COLOUR light_color = (op::LIGHT_COLOUR)std::get<2>(y);
			LIGHT_SHAPE light_shape = get_light_sharp(light_color);
			send_call_light(it_light->m_physics_light_id,is_postive,light_shape,std::get<5>(y));
			debug_print_syslog(0,"[traffic light]group_id: %d,phy_light_id: %d,light_id: %d,color: %d,shape: %d,ip: %s",std::get<0>(y),it_light->m_physics_light_id,std::get<1>(y),light_color,light_shape,std::get<5>(y).c_str());
		}
	}

	std::string ret = "";
	if(data.size() > 0){
		root[JSON_ROOT_KEY_CMD] = "light_state";
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION_1_4;
		root[JSON_ROOT_KEY_DATA] = data;
		ret = root.toFastString();
		debug_print_syslog(0,"[light json] %s",ret.c_str());
	}
	send_json_data(JSON_CMD_VALUE_PUSH, ret);
}
std::string CYAServerDlg::get_json_all_traffic_lights()
{
	Json::Value root;
	Json::Value data;
	for(const auto x : m_carmanage->m_Map)
	{
		auto vt = x.second->getTrafficLightInfo();
		for (const auto y : vt)
		{
			Json::Value v;
			v.append(std::get<0>(y));
			v.append(std::get<1>(y));
			v.append(std::get<2>(y));
			v.append(std::get<3>(y));
			v.append(std::get<4>(y));
			data.append(v);
		}
	}

	std::string ret = "";
	if(data.size() > 0){
		root[JSON_ROOT_KEY_CMD] = "light_state";
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION;
		root[JSON_ROOT_KEY_DATA] = data;
		ret = root.toFastString();
	}
	return ret;
}

std::string CYAServerDlg::get_json_event(bool bAll /*= false*/)
{
	Json::Value root;
	Json::Value data;

	char _time[STR_LEN_TIME];
	struct tm local_time;
	char ev_id[STR_LEN_TIME];

	if(mp_event_list->empty()){return "";} 

	EventMap::iterator it_ev = mp_event_list->begin();
	for(; it_ev != mp_event_list->end();){
		/*if (ET_READER_ERROR== it_ev->second->ev_type)
		{
			it_ev++;
			continue;
		}*/
		// lihongzhen  2017/8/19 已处理呼救不再发送
		if(it_ev->second->status != ES_START && it_ev->second->status != ES_END){
			it_ev++;
			continue;
		}
		if(!it_ev->second->is_sent || bAll){
			//lemon 2017/08/01
			if(OBJECT_TYPE::OT_CARD == it_ev->second->obj_type)
			{
				CardMap::iterator it_card = mp_card_list_all.find(it_ev->second->obj_id);
				if(it_card != mp_card_list_all.end())
				{
					if (!need_display_verification(it_card->second))
					{
						++it_ev;
						continue;
					}
				}
			}
			Json::Value ev;
			sprintf_s(ev_id, "%lld", it_ev->second->get_id());
			ev[JSON_KEY_EVENT_EVENT_ID] = ev_id;
			ev[JSON_KEY_EVENT_STATUS] = it_ev->second->status;
			ev[JSON_KEY_EVENT_TYPE_ID] = it_ev->second->ev_type;
			ev[JSON_KEY_EVENT_OBJ_TYPE_ID] = it_ev->second->obj_type;
			if (it_ev->second->ev_type==ET_VEHICLE_REAR_END)
				ev[JSON_KEY_EVENT_OBJ_ID] = it_ev->second->desc;
			else
				ev[JSON_KEY_EVENT_OBJ_ID] = it_ev->second->obj_id;
			ev[JSON_KEY_EVENT_MAP_ID] = it_ev->second->map_id;
			ev[JSON_KEY_EVENT_AREA_ID] = it_ev->second->area_id;
			ev[JSON_KEY_EVENT_X] = it_ev->second->x;
			ev[JSON_KEY_EVENT_Y] = it_ev->second->y;
			ev[JSON_KEY_EVENT_LIMIT_VALUE] = it_ev->second->limit_value;

			ev[JSON_KEY_EVENT_CUR_VALUE] = it_ev->second->cur_value;
			ev[JSON_KEY_EVENT_LANDMARK_ID] = it_ev->second->landmarkid;
			ev[JSON_KEY_EVENT_LANDMARK_DIRECTION] = it_ev->second->landmarkdirect;
			ev[JSON_KEY_EVENT_LANDMARK_DISTANCE] = it_ev->second->landmarkdist;

			double t = *((int64_t*)&it_ev->second->cur_time)*ms;
			ev[JSON_KEY_EVENT_CUR_TIME] = t;

			data.append(ev);

			it_ev->second->is_sent = true;

			++it_ev;
		}
		else if(it_ev->second->is_sent)
		{
			if(it_ev->second->status == ES_END){ // 删除
				it_ev = mp_event_list->erase(it_ev);
			}else{
				++it_ev;
			}
		}
	}

	std::string ret = "";
	if(data.size() > 0){
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_EVENT;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION;
		root[JSON_ROOT_KEY_DATA] = data;
		ret = root.toFastString();
	}

	return ret;
}

std::string CYAServerDlg::get_json_new_device_state()
{
	std::string ret = "";
	Json::Value root;	
	Json::Value data;

	MapInfoMap::iterator it_map = mp_map_list.begin();

	for(; it_map != mp_map_list.end(); ++it_map){
		//通信分站列表
		ReaderMap::iterator it_ctrl_reader = mp_ctrl_reader_list.begin();
		for (it_ctrl_reader;it_ctrl_reader!=mp_ctrl_reader_list.end();++it_ctrl_reader)
		{
			if (it_ctrl_reader->second->map_id != it_map->second->map_id)
			{
				continue;
			}

			Json::Value state_dev;
			state_dev.append(it_ctrl_reader->second->reader_id);
			state_dev.append(it_ctrl_reader->second->device_type_id);
			state_dev.append(it_ctrl_reader->second->reader_state);
			//入井时间戳
			double t = *((int64_t*)&it_ctrl_reader->second->rec_time)*ms;
			state_dev.append(t);
			state_dev.append(it_map->second->map_id);
			state_dev.append(0);
			data.append(state_dev);
		}

		//红绿灯
		LightMap::iterator it_light = mp_light_list.begin();
		for (it_light;it_light!=mp_light_list.end();++it_light)
		{
			if (it_light->second->m_nMapID != it_map->second->map_id)
			{
				continue;
			}

			Json::Value state_dev;
			state_dev.append(it_light->second->m_nID);
			state_dev.append(it_light->second->device_type_id);
			state_dev.append(it_light->second->m_nShape);
			//state_dev.append(it_light->second->get_light_state());
			ReaderMap::iterator it_ctrl_reader = mp_ctrl_reader_list.find(it_light->second->m_nReaderID);
			double t = 0;
			if (it_ctrl_reader != mp_ctrl_reader_list.end())
			{
				//入井时间戳
				t = *((int64_t*)&it_ctrl_reader->second->rec_time)*ms;				
			}
			state_dev.append(t);
			state_dev.append(it_map->second->map_id);
			state_dev.append(it_light->second->m_nIsCtrl);
			data.append(state_dev);
		}
	}

	if (data.size() > 0)
	{
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_DEV_STATE;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION;
		root[JSON_ROOT_KEY_DATA] = data;
		ret = root.toFastString();
	}

	return ret;
}

void CYAServerDlg::parse_data_lights_state( BYTE* DataBuffer, int& nCurPos, int reader_id, unsigned short wChr )
{
	time_t cur_time = time(NULL);
	WORD wlen = 0; // 段长度 2 byte
	//CFunctions::getWord(DataBuffer, &wlen, nCurPos);
	//nCurPos += sizeof(WORD);
	wlen = 8;			//只针对认证，此处写死为8个


	BYTE btCmd = 0; // 控制码 1 byte 0x01 响应红绿灯设置状态 0x02 响应请求红绿灯状态
	memcpy(&btCmd, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	//BYTE btResult = 0; // 返回结果
	//memcpy(&btResult, &DataBuffer[nCurPos], sizeof(BYTE));
	//nCurPos += sizeof(BYTE);

	//// 段数据 
	//BYTE btDevType = 0; // 设备类型 1 byte 0x01灯，0x02 报警器，0x03 显示屏
	//memcpy(&btDevType, &DataBuffer[nCurPos], sizeof(BYTE));
	//nCurPos += sizeof(BYTE);

	// 设备类型 
	BYTE btDevType = 0; // 设备类型 1 byte ：0x00：读卡分站；0x01：控制分站；0x03：红绿灯；0x04：告警器；0x05：道岔；0x06：显示屏
	memcpy(&btDevType, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	if(btDevType == DEVICE_TYPE::DT_LIGHT){
		BYTE btId = 0; // 设备编号 1 byte
		memcpy(&btId, &DataBuffer[nCurPos], sizeof(BYTE));

		nCurPos += sizeof(BYTE);
		BYTE btCtrlState = 0; // 设备控制状态 1byte 0x01 自动控制，0x02 手动控制，0x03 故障
		memcpy(&btCtrlState, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);
		BYTE btColor = 0; // 颜色 1 byte 0x01 红色, 0x02 绿色
		memcpy(&btColor, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);
		BYTE btShape = 0; // 图案 1 byte 0x01 实心圆形，0x02 空心圆形，0x03 叉形，0x04 - 0x07 上下左右箭头，0xFF 警告闪烁
		memcpy(&btShape, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);

		LightMap::iterator it_light = mp_light_list.begin();
		for(; it_light != mp_light_list.end(); ++it_light){
			if(it_light->second->m_nPort == btId && it_light->second->m_nReaderID == reader_id){
				it_light->second->m_nColor = btColor;
				it_light->second->m_nShape = btShape;
				it_light->second->m_nIsCtrl = LIGHT_CTRL_STATE::CTRL_STATE_AUTO;
				it_light->second->rec_time = cur_time;
				break;
			}
		}
	}	
}

void CYAServerDlg::add_light_to_call_list( LIGHTS_SELECT_TYPE lst, LIGHT_COLOR clr, LIGHT_CTRL_STATE ctrl, int tkid, LIGHT_SHAPE ls, int light_id /*= 0*/ )
{
	if(lst == LIGHTS_SELECT_TYPE::LST_SOME_LIGHTS){
		LightCallMap::iterator it_light_call = mp_light_call_list->find(light_id);

		if(it_light_call != mp_light_call_list->end()){
			it_light_call->second->ctrl_color = clr;
			it_light_call->second->ctrl_type = ctrl;
			it_light_call->second->task_id = tkid;
			it_light_call->second->light_state = ls;
		}else{
			std::shared_ptr<LightCallInfo> pCall = std::make_shared<LightCallInfo>();
			pCall->ctrl_color = clr;
			pCall->ctrl_type = ctrl;
			pCall->light_id = light_id;
			pCall->task_id = tkid;
			pCall->light_state = ls;
			mp_light_call_list->insert(make_pair(light_id, pCall));
		}
		return ;
	}
	LightMap::iterator it_light = mp_light_list.begin();
	for(; it_light != mp_light_list.end(); ++it_light){
		if(LST_ALL_LIGHTS == lst){
			add_light_to_call_list(LIGHTS_SELECT_TYPE::LST_SOME_LIGHTS, clr, ctrl, tkid, ls, it_light->first);
		}else if(LST_ALL_UP_LIGHTS == lst && LIGHT_STREAM::UP_STREAM == it_light->second->m_nStream ){
			add_light_to_call_list(LIGHTS_SELECT_TYPE::LST_SOME_LIGHTS, clr, ctrl, tkid, ls, it_light->first);
		}else if(LST_ALL_DWON_LIGHTS == lst && LIGHT_STREAM::DOWN_STREAM == it_light->second->m_nStream){
			add_light_to_call_list(LIGHTS_SELECT_TYPE::LST_SOME_LIGHTS, clr, ctrl, tkid, ls, it_light->first);
		}
	}
}

void CYAServerDlg::send_call_light()
{
	LightCallMap::iterator it_light_call = mp_light_call_list->begin();
	for(; it_light_call != mp_light_call_list->end(); ++ it_light_call){
		send_call_light(CC_SET_LIGHTS_STATE,it_light_call->second->light_id, it_light_call->second->ctrl_type, it_light_call->second->ctrl_color,it_light_call->second->light_state);
		Sleep(2000);
	}
}

/*
 * 给红绿灯下发指令设置其颜色
 *
 * param
 *		light_id		红绿灯号
 *		color			颜色
 *		ip				红绿灯对应的ip地址
 *
 * return
 *		无
 *
*/
void CYAServerDlg::send_call_light(int light_id,int color,std::string ip)
{
	BYTE buf[LENGTH_SEND_BUF];
	SocketMap::iterator it_sock;
	BYTE btCmd = CC_SET_LIGHTS_STATE, btDevType = DEVICE_TYPE::DT_LIGHT, btShape ,control_color,ctrl_type=CTRL_STATE_AUTO;
	if (color == op::LIGHT_COLOUR::RED)
	{
		control_color = COLOR_RED;
		btShape = RED_CIRCLE_SOLID;
	}
	else if(color == op::LIGHT_COLOUR::GREEN)
	{
		control_color = COLOR_GREEN;
		btShape = GREEN_DOWN;
	}
	else
	{
		control_color = COLOR_GREEN;
		btShape = GREEN_SPARK;
	}
	int npos = 0;

	WORD wCrc;
	switch (btCmd)
	{
	case 0x01:
		{
			it_sock = mp_socket_list.find(CFunctions::c2wc(ip.c_str()));
			if(it_sock != mp_socket_list.end()){
				memset(buf, 0, LENGTH_SEND_BUF);
				npos = 0;
				memcpy(&buf[npos], &btCmd, sizeof(BYTE)); // 控制码
				npos += sizeof(BYTE);
				memcpy(&buf[npos], &btDevType, sizeof(BYTE)); // 设备类型
				npos += sizeof(BYTE);
				memcpy(&buf[npos], &light_id, sizeof(BYTE)); // 设备ID
				npos += sizeof(BYTE);
				memcpy(&buf[npos], &ctrl_type, sizeof(BYTE)); // 控制状态
				npos += sizeof(BYTE);
				memcpy(&buf[npos], &control_color, sizeof(BYTE)); // 颜色
				npos += sizeof(BYTE);
				memcpy(&buf[npos], &btShape, sizeof(BYTE)); // 图案
				npos += sizeof(BYTE);

				//CRC校验
				wCrc = CFunctions::getCRC(&buf[0], npos); // 数据长度 + 特征字
				CFunctions::memcpyWord(&buf[0], wCrc, npos);
				npos += sizeof(WORD);

				BOOL ret = SendData(it_sock->second->dwConnID,CHAR_CTRL_READER_CMD, npos, buf);
			}
		}
		break;
	case 0x02:
		{
			it_sock = mp_socket_list.find(CFunctions::c2wc(ip.c_str()));
			if(it_sock != mp_socket_list.end()){
				memset(buf, 0, LENGTH_SEND_BUF);
				npos = 0;
				memcpy(&buf[npos], &btCmd, sizeof(BYTE)); // 控制码
				npos += sizeof(BYTE);
				memcpy(&buf[npos], &btDevType, sizeof(BYTE)); // 设备类型
				npos += sizeof(BYTE);
				memcpy(&buf[npos], &light_id, sizeof(BYTE)); // 设备ID
				npos += sizeof(BYTE);
				//CRC校验
				wCrc = CFunctions::getCRC(&buf[0], npos); // 数据长度 + 特征字
				CFunctions::memcpyWord(&buf[0], wCrc, npos);
				npos += sizeof(WORD);
				SendData(it_sock->second->dwConnID,CHAR_CTRL_READER_CMD, npos, buf);
			}
		}
		break;
	default:
		break;
	}
	Sleep(LIGHT_CTRL_DELAY);
}
void CYAServerDlg::send_call_light(BYTE ctrl_cmd, int light_id, int ctrl_type, int ctrl_color,int light_shape)
{
	BYTE buf[LENGTH_SEND_BUF];

	SocketMap::iterator it_sock;
	LightMap::iterator it_light;

	int npos = 0;
	BYTE btCmd = ctrl_cmd, btDevType = DEVICE_TYPE::DT_LIGHT, btShape = light_shape;
	WORD wCrc;
	switch (ctrl_cmd)
	{
	case 0x01:
		it_light = mp_light_list.find(light_id);
		if(it_light != mp_light_list.end()){
			it_sock = mp_socket_list.find(CFunctions::c2wc(it_light->second->m_strIP.c_str()));
			if(it_sock != mp_socket_list.end()){
				memset(buf, 0, LENGTH_SEND_BUF);
				npos = 0;
				memcpy(&buf[npos], &btCmd, sizeof(BYTE)); // 控制码
				npos += sizeof(BYTE);
				memcpy(&buf[npos], &btDevType, sizeof(BYTE)); // 设备类型
				npos += sizeof(BYTE);
				memcpy(&buf[npos], &it_light->second->m_nPort, sizeof(BYTE)); // 设备ID
				npos += sizeof(BYTE);
				memcpy(&buf[npos], &ctrl_type, sizeof(BYTE)); // 控制状态
				npos += sizeof(BYTE);
				memcpy(&buf[npos], &ctrl_color, sizeof(BYTE)); // 颜色
				npos += sizeof(BYTE);
				memcpy(&buf[npos], &btShape, sizeof(BYTE)); // 图案
				npos += sizeof(BYTE);

				//CRC校验
				wCrc = CFunctions::getCRC(&buf[0], npos); // 数据长度 + 特征字
				CFunctions::memcpyWord(&buf[0], wCrc, npos);
				npos += sizeof(WORD);

				BOOL ret = SendData(it_sock->second->dwConnID,CHAR_CTRL_READER_CMD, npos, buf);
			}
		}
		break;
	case 0x02:
		it_light = mp_light_list.find(light_id);
		if(it_light != mp_light_list.end()){
			it_sock = mp_socket_list.find(CFunctions::c2wc(it_light->second->m_strIP.c_str()));
			if(it_sock != mp_socket_list.end()){
				memset(buf, 0, LENGTH_SEND_BUF);
				npos = 0;
				memcpy(&buf[npos], &btCmd, sizeof(BYTE)); // 控制码
				npos += sizeof(BYTE);
				memcpy(&buf[npos], &btDevType, sizeof(BYTE)); // 设备类型
				npos += sizeof(BYTE);
				memcpy(&buf[npos], &it_light->second->m_nPort, sizeof(BYTE)); // 设备ID
				npos += sizeof(BYTE);
				//CRC校验
				wCrc = CFunctions::getCRC(&buf[0], npos); // 数据长度 + 特征字
				CFunctions::memcpyWord(&buf[0], wCrc, npos);
				npos += sizeof(WORD);
				SendData(it_sock->second->dwConnID,CHAR_CTRL_READER_CMD, npos, buf);
			}
		}
		break;
	default:
		break;
	}
}

void CYAServerDlg::send_call_light(const int& light_id,const bool& postive,const int& color,const std::string& ip)
{
	BYTE buf[LENGTH_SEND_BUF];
	memset(buf,0,LENGTH_SEND_BUF*sizeof(BYTE));
	SocketMap::iterator it_sock = mp_socket_list.end();
	it_sock = mp_socket_list.find(CFunctions::c2wc(ip.c_str()));
	if (it_sock == mp_socket_list.end())
	{
		return;
	}

	uint8_t npos = 0;
	CFunctions::memcpyDWord(&buf[0], light_id, npos);		  // 设备id号
	npos+=sizeof(DWORD);

	BYTE deviceType = (BYTE)(DEVICE_TYPE::DT_LIGHT);
	memcpy(&buf[npos], &deviceType, sizeof(BYTE));			  // 设备类型
	npos += sizeof(BYTE);

	//红绿灯硬件支持0x00保持不变
	int postiveColor = 0x00;
	int negativeColor = 0x00;

	if (postive)
	{
		postiveColor = color;
	}else{
		negativeColor = color;
	}

	// 正面控制码
	BYTE ctrlCode = 0x01;
	memcpy(&buf[npos], &ctrlCode, sizeof(BYTE));				  
	npos += sizeof(BYTE);

	// 正面形状
	memcpy(&buf[npos], &postiveColor, sizeof(BYTE));			 
	npos += sizeof(BYTE);

	// 反面控制码
	ctrlCode = 0x02;
	memcpy(&buf[npos], &ctrlCode, sizeof(BYTE));				  
	npos += sizeof(BYTE);

	// 反面形状
	memcpy(&buf[npos], &negativeColor, sizeof(BYTE));			  
	npos += sizeof(BYTE);

	BOOL ret = SendData(it_sock->second->dwConnID,CHAR_CTRL_LIGHT_CMD, npos, buf);
	/*if (ret)
	{
		char log[MAX_LOG_LENGTH] = {0};
		sprintf_s(log,"[setup traffic light status] light_id: %d, postive_sharp: %d, negative_sharp: %d",light_id,postiveColor,negativeColor);
		Log::write_log(FILE_TYPE::PARSE_LIGHT_S,log,true);
	}*/
}

void CYAServerDlg::send_call_light(const int& light_id,const uint8_t& p_color,const uint8_t& n_color,const std::string& ip,bool b)
{
	BYTE buf[LENGTH_SEND_BUF];
	memset(buf,0,LENGTH_SEND_BUF*sizeof(BYTE));
	SocketMap::iterator it_sock = mp_socket_list.end();
	it_sock = mp_socket_list.find(CFunctions::c2wc(ip.c_str()));
	if (it_sock == mp_socket_list.end())
	{
		return;
	}

	uint8_t npos = 0;
	CFunctions::memcpyDWord(&buf[0], light_id, npos);		  // 设备id号
	npos+=sizeof(DWORD);

	BYTE deviceType = (BYTE)(DEVICE_TYPE::DT_LIGHT);
	memcpy(&buf[npos], &deviceType, sizeof(BYTE));			  // 设备类型
	npos += sizeof(BYTE);

	// 正面控制码
	BYTE ctrlCode = 0x01;
	memcpy(&buf[npos], &ctrlCode, sizeof(BYTE));				  
	npos += sizeof(BYTE);

	// 正面形状
	memcpy(&buf[npos], &p_color, sizeof(BYTE));			 
	npos += sizeof(BYTE);

	// 反面控制码
	ctrlCode = 0x02;
	memcpy(&buf[npos], &ctrlCode, sizeof(BYTE));				  
	npos += sizeof(BYTE);

	// 反面形状
	memcpy(&buf[npos], &n_color, sizeof(BYTE));			  
	npos += sizeof(BYTE);

	BOOL ret = SendData(it_sock->second->dwConnID,CHAR_CTRL_LIGHT_CMD, npos, buf);
	if (ret)
	{
		char log[MAX_LOG_LENGTH] = {0};
		sprintf_s(log,"[setup traffic light status] light_id: %d, postive_sharp: %d, negative_sharp: %d",light_id,p_color,n_color);
		Log::write_log(FILE_TYPE::PARSE_LIGHT_S,log,true);
	}
}

LIGHT_SHAPE CYAServerDlg::get_light_sharp(const op::LIGHT_COLOUR& color)
{
	LIGHT_SHAPE btShape = INIT_SHAPE;
	if (color == op::LIGHT_COLOUR::RED)
	{
		btShape = RED_CIRCLE_SOLID;
	}
	else if(color == op::LIGHT_COLOUR::GREEN)
	{
		btShape = GREEN_ALL_ON;
	}
	else if(color == op::LIGHT_COLOUR::SPARK)
	{
		btShape = GREEN_SPARK;
	}

	return btShape;
}

std::string CYAServerDlg::get_json_call_list()
{
	//呼叫
	//目前实现的方式，web端发起呼叫，通过采集和分站将呼叫信息下发到呼叫
	//卡将状态类型返回到指定某个字节表示收到了呼叫信息，卡需要保存是哪个分站将信息上传到采集的
	Json::Value root;	
	Json::Value data;
	double t = 0;
	for(CallInfoUserMap::iterator it_call_user = mp_user_call_info.begin(); it_call_user != mp_user_call_info.end(); ++it_call_user)
	{
		CallInfoReaderMap::iterator it_call_reader = it_call_user->second->mpReader.begin();
		for(; it_call_reader != it_call_user->second->mpReader.end(); ++ it_call_reader)
		{
			if (it_call_reader->first == 0)
			{
				if (it_call_reader->second->is_call_all)
				{
					for (CardMap::iterator it_card = mp_card_list_all.begin();it_card!=mp_card_list_all.end();++it_card)
					{
						//lemon 2017/08/01
						if (!need_display_verification(it_card->second))
						{
							continue;
						}
						if (it_card->second->call_type_id != 0)
						{
							Json::Value callinfo;
							Json::Value temp;
							callinfo.append(it_call_user->first);
							callinfo.append(it_card->second->card_id);
							callinfo.append(0);
							t = *((int64_t*)&it_card->second->recv_call_time)*ms;
							callinfo.append(t);
							callinfo.append(it_call_reader->second->call_level);
							callinfo.append(1);

							data.append(callinfo);
						}
					}
				}
			}else{
				CallInfoCardMap::iterator it_call_card = it_call_reader->second->mpCard.begin();
				for(; it_call_card != it_call_reader->second->mpCard.end(); ++ it_call_card)
				{
					//lemon 2017/08/01
					CardMap::iterator it_card = mp_card_list_all.find(it_call_card->second->str_card_id);
					if(it_card != mp_card_list_all.end())
					{
						if (!need_display_verification(it_card->second))
						{
							continue;
						}
					}
					Json::Value callinfo;
					Json::Value temp;
					callinfo.append(it_call_user->first);
					callinfo.append(it_call_card->second->str_card_id);
					temp = it_call_reader->first;
					callinfo.append(temp);
					t = *((int64_t*)&it_call_card->second->start_time)*ms;
					callinfo.append(t);
					callinfo.append(it_call_reader->second->call_level);
					callinfo.append(it_call_card->second->call_state);

					data.append(callinfo);
				}
			}
		}
	}

	std::string ret = "";
	if(data.size() > 0){
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_CALL_CARD_LIST;
		root[JSON_ROOT_KEY_DATA] = data;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION;
		ret = root.toFastString();
	}
	return ret;
}

bool CYAServerDlg::IsInLine( _point p1, _point p2, _point p3 )
{
	return true;
}

void CYAServerDlg::OnBnTest()
{
	int area_id = get_drivingface_area_id("0050000001121");
	area_id = get_drivingface_area_id("0050000001126");
	auto pCard = mp_card_list_all.find("0050000001193");
	init_drivingface_recently_info(pCard->second);
}

double CYAServerDlg::GetDistance(_point p1, _point p2)
{
	double distance = 0.0;
	distance = sqrt(pow(p1.x - p2.x, 2) + pow(p1.y - p2.y, 2));
	return distance;
}

//获得地标id
int CYAServerDlg::GetLandmarkID(std::shared_ptr<Card> card)
{
	int minLandmarkID = -1;
	double minDistance = 100000;
	std::shared_ptr<LandmarkInfo> pLandmarkInfo = nullptr;
	int nRow = 0;
	_point card_position (card->x, 
		card->y, 
		card->z);

	LandmarkInfoMap::iterator it = mp_landmark_list.begin();
	//遍历地标表，查找和卡位置距离最近的地标信息
	while(it != mp_landmark_list.end())
	{
		//地标和卡的定位位置在同一区域内
		if(it->second->area_id == card->area_id)
		{
			pLandmarkInfo = it->second;
			_point landmark_position (pLandmarkInfo->x, 
				pLandmarkInfo->y, 
				pLandmarkInfo->z);
			double distance = 0.0;
			distance = GetDistance(landmark_position, card_position);
			if(distance < minDistance)
			{
				minDistance = distance;
				minLandmarkID = pLandmarkInfo->landmark_id;
			}
		}
		it++;
	}
	return minLandmarkID;
}

DIRECTION_TYPE CYAServerDlg::GetDirectionType(_point card_point, _point landmark_point, int map_id)
{
	DIRECTION_TYPE direction = NODIRECTORY;
	int x_offset = 0;
	int y_offset = 0;
	int angle = 0; // x,y坐标系与地理北极的角度
	x_offset = card_point.x - landmark_point.x;
	y_offset = card_point.y - landmark_point.y;

	if(abs(x_offset) < 1)
	{
		x_offset = 0;
	}
	if(abs(y_offset) < 1)
	{
		y_offset = 0;
	}

	std::shared_ptr<MapDirectionInfo> pMapDirectoryInfo = nullptr;
	MapDirectionInfoMap::iterator it = mp_map_direction_list.find(map_id);		
	if(it == mp_map_direction_list.end())
	{
		return NODIRECTORY;
	}
	else
	{ 
		pMapDirectoryInfo = it->second;
	}

	if(0 == y_offset)
	{
		if(x_offset > 0)
		{
			angle = pMapDirectoryInfo->north_angle + 0;
		}
		if(x_offset < 0)
		{
			angle = pMapDirectoryInfo->north_angle - 180;
		}
	}
	else if(0 == x_offset)
	{
		if(y_offset < 0)
		{
			angle = pMapDirectoryInfo->north_angle - 90;
		}
		if(y_offset > 0)
		{
			angle = pMapDirectoryInfo->north_angle + 90;
		}
	}
	else if(abs(x_offset) >= abs(y_offset))
	{
		if(x_offset > 0)
		{
			angle = pMapDirectoryInfo->north_angle + 0;
		}
		if(x_offset < 0)
		{
			angle = pMapDirectoryInfo->north_angle - 180;
		}
	}
	else
	{
		if(y_offset < 0)
		{
			angle = pMapDirectoryInfo->north_angle - 90;
		}
		if(y_offset > 0)
		{
			angle = pMapDirectoryInfo->north_angle + 90;
		}
	}

	direction = (DIRECTION_TYPE)((angle % 360) / 90);
	if(angle % 360 == 0)
	{
		direction = NORTH;
	}
	if((0 == y_offset) && (0 == x_offset))
	{
		direction = NODIRECTORY;
	}

	return direction;
}

void CYAServerDlg::TestLandmarkRequirement()
{
	_point card_point;
	_point landmark_point;
	int directory_id = 0;
	int landmark_id = 0;
	LandmarkInfoMap::iterator itLandmark = mp_landmark_list.begin();

	//test 1
	card_point.x = 4727;
	card_point.y = 90;
	card_point.z = 0;
	//landmark_id = GetLandmarkID(card_point);
	itLandmark = mp_landmark_list.find(landmark_id);		
	if(itLandmark != mp_landmark_list.end())
	{
		landmark_point.x = itLandmark->second->x;
		landmark_point.y = itLandmark->second->y;
		landmark_point.z = itLandmark->second->z;
	}
	directory_id = GetDirectionType(card_point, landmark_point, 5);

	//test 2
	card_point.x = 4727;
	card_point.y = 70;
	card_point.z = 0;
	//landmark_id = GetLandmarkID(card_point);
	itLandmark = mp_landmark_list.find(landmark_id);		
	if(itLandmark != mp_landmark_list.end())
	{
		landmark_point.x = itLandmark->second->x;
		landmark_point.y = itLandmark->second->y;
		landmark_point.z = itLandmark->second->z;
	}
	directory_id = GetDirectionType(card_point, landmark_point, 5);

	return;
}

void CYAServerDlg::save_raw_data_card_tof( std::shared_ptr<Card> card )
{
	char sql[LENGTH_SQL] = {0};
	char _time[STR_LEN_TIME];
	struct tm loaddtime;
	time_t t = time(NULL);

	bool b_exec = false;

	sprintf_s(sql, LENGTH_SQL, 
		"INSERT INTO his_raw_data_card_tof(card_id, ct, ft, power_state, acc_state, reader_id, antenna_id, distance) VALUES(%s, %d, %I64u, %d, %d, %d, %d, %.3f);",  
		card->card_id.c_str(), card->time_stamp, card->flying_time, card->power_state, card->accelerate_state, card->reader_id, card->antenna_id, card->distance);

	execute_sql(sql);
}

int CYAServerDlg::init_shift()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;

	pRes = getMysqlRes("select shift_id, start_time, end_time, shift_type_id from dat_shift;");

	if( NULL == pRes)
	{
		return 2;
	}

	std::shared_ptr<BanShift> banshift = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))	{
		BanShiftMap::iterator it = mp_banshift_list.find(atoi(pRow[0]));		
		if(it != mp_banshift_list.end()){
			banshift = it->second;
		}else{
			banshift = std::make_shared<BanShift>(atoi(pRow[0]), pRow[1], pRow[2], atoi(pRow[3]));
			mp_banshift_list.insert(make_pair(banshift->shift_id, banshift));
			nRow++;
		}
		banshift->start_time = pRow[1];
		banshift->end_time = pRow[2];
	}
	mysql_free_result(pRes);
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_BANSHIFT), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}

int CYAServerDlg::GetCurShiftId( struct tm* current_time, int shift_type /* = 1*/ )
{
	char ch[64];
	strftime(ch, sizeof(ch), "%H-%M-00", current_time);
	std::string curtime = ch;

	int shift_id = 1;
	BanShiftMap::iterator it_shift = mp_banshift_list.begin();
	for(; it_shift != mp_banshift_list.end(); ++it_shift)
	{
		if(it_shift->second->shift_type_id == shift_type)
		{		
			if(it_shift->second->end_time < it_shift->second->start_time)
			{
				if(curtime >= it_shift->second->start_time || curtime < it_shift->second->end_time)
				{
					shift_id = it_shift->first;
				}
			}
			else
			{
				if(curtime >= it_shift->second->start_time && curtime < it_shift->second->end_time)
				{
					shift_id = it_shift->first;
				}
			}
		}
	}
	return shift_id;
}

void CYAServerDlg::TestCallCard()
{
	BYTE buf[LENGTH_SEND_BUF] = {0};
	memset(buf, 0, LENGTH_SEND_BUF);
	int npos = 0, card_count = 0, call_type = 1,card_type = 1, card_id = 100;
	//卡数
	card_count = 1;
	memcpy(&buf[npos], &card_count, sizeof(BYTE));
	npos += sizeof(BYTE);
	//呼叫类型
	memcpy(&buf[npos], &call_type, sizeof(BYTE));
	npos += sizeof(BYTE);

	//呼叫类型
	memcpy(&buf[npos], &call_type, sizeof(BYTE));
	npos += sizeof(BYTE);
	//卡类型
	memcpy(&buf[npos], &card_type, sizeof(BYTE));
	npos += sizeof(BYTE);
	//卡ID长度
	BYTE id_len = (BYTE)get_card_id_len(card_type);
	memcpy(&buf[npos], &id_len, sizeof(BYTE));
	npos += sizeof(BYTE);
	//卡ID
	if(id_len > 1){ // 标准卡id为4个字节，自组网卡为1个字节
		CFunctions::memcpyDWord(buf,(DWORD)card_id, npos);
	}else{
		memcpy(&buf[npos], &card_id, id_len);
	}
	npos += id_len;

	memcpy(&buf[0], &card_count, sizeof(BYTE));

	for(SocketMap::iterator it_sock= mp_socket_list.begin();it_sock!=mp_socket_list.end();++it_sock)
	{
		if(it_sock->second->findReader(101) && it_sock->second->get(101).reader_type    == DEVICE_TYPE::DT_CARD_READER)
		{
			//SendData(it_sock->second->dwConnID,CHAR_CALL, npos, buf);
			SendData(it_sock->second->dwConnID,CHAR_CALL_EXTEND, npos, buf);
			break;
		}
	}
}

void CYAServerDlg::TestParseCallCard()
{
	//{
	//    "cmd": "call_card_req",
	//    "data":{
	//	    "call_id":1,
	//		"call_time_out":5,
	//		"call_type_id": 0,
	//		"user_name": "xuying",
	//		"call_time":1501117298828,
	//		"stations": [{stationid: "0"}],
	//		"cards":[
	//		 {
	//			 "cardid":"0010000000002",
	//		     "cardtype":1
	//		 },
	//		 {
	//			 "cardid":"0010000000004",
	//			 "cardtype":1
	//		 },
	//		 {
	//			 "cardid":"0010000000005",
	//		     "cardtype":1
	//		 }
	//	     ]
	//	}
	//}	

	// 定员呼叫
	message::ptr root = object_message::create();
	static_cast<object_message*>(root.get())->get_map()[JSON_ROOT_KEY_CMD] = string_message::create(JSON_CMD_VALUE_CALL_CARD_REQUEST);

	message::ptr data = object_message::create();
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CALL_TYPE] = int_message::create(1);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CALL_TIME_OUT] = int_message::create(5);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CALL_LEVEL] = int_message::create(0);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_USER_NAME] = string_message::create("lihz");
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CALL_TIME] = int_message::create(time(NULL));

	message::ptr stations = array_message::create();
	message::ptr station = object_message::create();	
	static_cast<object_message*>(station.get())->get_map()[JSON_KEY_CALL_CARD_STATION_ID] = int_message::create(0);
	static_cast<array_message*>(stations.get())->get_vector().push_back(station);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_STATIONS] = stations;

	message::ptr cards = array_message::create();
	message::ptr card = object_message::create();
	static_cast<object_message*>(card.get())->get_map()[JSON_KEY_CALL_CARD_CARD_ID] = string_message::create("0010000000046");
	static_cast<object_message*>(card.get())->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID] = int_message::create(1);
	static_cast<array_message*>(cards.get())->get_vector().push_back(card);
	card = object_message::create();
	static_cast<object_message*>(card.get())->get_map()[JSON_KEY_CALL_CARD_CARD_ID] = string_message::create("0010000000004");
	static_cast<object_message*>(card.get())->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID] = int_message::create(1);
	static_cast<array_message*>(cards.get())->get_vector().push_back(card);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CARDS] = cards;

	static_cast<object_message*>(root.get())->get_map()[JSON_ROOT_KEY_DATA] = data;

	parse_json_data_call_card(root);

	// 全员呼叫
	root = object_message::create();
	static_cast<object_message*>(root.get())->get_map()[JSON_ROOT_KEY_CMD] = string_message::create(JSON_CMD_VALUE_CALL_CARD_REQUEST);

	data = object_message::create();
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CALL_TYPE] = int_message::create(0);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CALL_TIME_OUT] = int_message::create(5);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CALL_LEVEL] = int_message::create(0);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_USER_NAME] = string_message::create("lihz");
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CALL_TIME] = int_message::create(time(NULL));

	stations = array_message::create();
	station = object_message::create();	
	static_cast<object_message*>(station.get())->get_map()[JSON_KEY_CALL_CARD_STATION_ID] = int_message::create(0);
	static_cast<array_message*>(stations.get())->get_vector().push_back(station);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_STATIONS] = stations;

	cards = array_message::create();
	card = object_message::create();
	static_cast<object_message*>(card.get())->get_map()[JSON_KEY_CALL_CARD_CARD_ID] = string_message::create("0");
	static_cast<object_message*>(card.get())->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID] = int_message::create(1);
	static_cast<array_message*>(cards.get())->get_vector().push_back(card);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CARDS] = cards;
	static_cast<object_message*>(root.get())->get_map()[JSON_ROOT_KEY_DATA] = data;

	parse_json_data_call_card(root);

	// 取消全员呼叫
	root = object_message::create();
	static_cast<object_message*>(root.get())->get_map()[JSON_ROOT_KEY_CMD] = string_message::create(JSON_CMD_VALUE_CALL_CARD_CANCEL_REQUEST);

	data = object_message::create();
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CALL_TYPE] = int_message::create(0);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_USER_NAME] = string_message::create("lihz");
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CALL_TIME] = int_message::create(time(NULL));

	stations = array_message::create();
	station = object_message::create();	
	static_cast<object_message*>(station.get())->get_map()[JSON_KEY_CALL_CARD_STATION_ID] = int_message::create(0);
	static_cast<array_message*>(stations.get())->get_vector().push_back(station);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_STATIONS] = stations;

	cards = array_message::create();
	card = object_message::create();
	static_cast<object_message*>(card.get())->get_map()[JSON_KEY_CALL_CARD_CARD_ID] = string_message::create("0");
	static_cast<object_message*>(card.get())->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID] = int_message::create(1);
	static_cast<array_message*>(cards.get())->get_vector().push_back(card);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CARDS] = cards;
	static_cast<object_message*>(root.get())->get_map()[JSON_ROOT_KEY_DATA] = data;

	//parse_json_data_call_card_cancel(root);
	// 取消定员呼叫
	root = object_message::create();
	static_cast<object_message*>(root.get())->get_map()[JSON_ROOT_KEY_CMD] = string_message::create(JSON_CMD_VALUE_CALL_CARD_CANCEL_REQUEST);

	data = object_message::create();
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CALL_TYPE] = int_message::create(1);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_USER_NAME] = string_message::create("lihz");
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CALL_TIME] = int_message::create(time(NULL));

	stations = array_message::create();
	station = object_message::create();	
	static_cast<object_message*>(station.get())->get_map()[JSON_KEY_CALL_CARD_STATION_ID] = int_message::create(0);
	static_cast<array_message*>(stations.get())->get_vector().push_back(station);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_STATIONS] = stations;

	cards = array_message::create();
	card = object_message::create();
	static_cast<object_message*>(card.get())->get_map()[JSON_KEY_CALL_CARD_CARD_ID] = string_message::create("0010000000004");
	static_cast<object_message*>(card.get())->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID] = int_message::create(1);
	static_cast<array_message*>(cards.get())->get_vector().push_back(card);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CARDS] = cards;
	static_cast<object_message*>(root.get())->get_map()[JSON_ROOT_KEY_DATA] = data;

	parse_json_data_call_card_cancel(root);
}

void CYAServerDlg::OnLoginEx(string const& name, message::ptr const& data, bool isAck, message::list &ack_resp)
{
	int res_code = (int)data->get_map()["code"]->get_int();
	switch (res_code)
	{
	case -100: // 用户未登录
		{
			is_websocket_login_ex = false;
			break;
		}
	case 0:
		{
			if("" == data->get_map()["code"]->get_string()){ // 登录成功
				is_websocket_login_ex = true;
			}else{ // 退出登录
				is_websocket_login_ex = false;
			}
			break;
		}
	default:
		break;
	}
}

void CYAServerDlg::OnConnectedEx()
{
	is_websocket_ok = true;
	time_ws_connect_ex = ::GetTickCount();
}

void CYAServerDlg::OnClosedEx(client::close_reason const& reason)
{
	int i = -1;
	if(reason == client::close_reason_drop){
		i = (int) reason;
	}else{
		i = (int) reason;
	}
	is_websocket_login_ex = false;
	is_websocket_ok_ex = false;
}

void CYAServerDlg::OnFailedEx()
{
	is_websocket_login_ex = false;
	is_websocket_ok_ex = false;
	_io_ex->close();
}

void CYAServerDlg::ws_init_ex()
{
	is_websocket_ok_ex = false;
	is_websocket_login_ex = false;

	_io_ex->set_reconnect_attempts(0);
	using std::placeholders::_1;
	using std::placeholders::_2;
	using std::placeholders::_3;
	using std::placeholders::_4;   
	socket::ptr sock = _io_ex->socket();

	sock->on(JSON_CMD_VALUE_USER, sio::socket::event_listener_aux(std::bind(&CYAServerDlg::OnLoginEx, this, _1,_2,_3,_4)));
	sock->on(JSON_CMD_VALUE_CALL, sio::socket::event_listener_aux(std::bind(&CYAServerDlg::OnCallMessage,this,_1,_2,_3,_4)));
	//default socket opened, also we have "set_open_listener" for monitoring physical connection opened.
	_io_ex->set_socket_open_listener(std::bind(&CYAServerDlg::OnConnectedEx, this));
	//physical connection closed or drop.
	_io_ex->set_close_listener(std::bind(&CYAServerDlg::OnClosedEx,this, std::placeholders::_1));
	//physical connection fail to establish.
	_io_ex->set_fail_listener(std::bind(&CYAServerDlg::OnFailedEx,this));
}

void CYAServerDlg::ws_open_ex()
{
	// 地址相同或者备用地址为空，不走数据
	if(m_ws_url_ex == m_ws_url || 0 == m_ws_url_ex.length())
	{
		return ;
	}

	_io_ex->connect(m_ws_url_ex);

	CString strlog = _T("");

	wchar_t* p = CFunctions::c2wc(m_ws_url_ex.c_str());
	strlog.Format(_T("%s: %s"), _T(LOG_CONNECT_WEB_SERVER), p);
	if(p){
		free(p);
		p = NULL;
	}

	show_log(strlog);
}

void CYAServerDlg::ws_login_ex()
{
	USES_CONVERSION;
	CC2UTF8 conv = (char*)get_json_login().c_str();
	string szlogin = conv.c_str();
	_io_ex->socket()->emit(JSON_CMD_VALUE_USER, szlogin, [&](sio::message::list const& msglist){
		message::ptr msg_ptr = msglist[0];
		int n =(int)msg_ptr->get_map()["code"]->get_int();
		is_websocket_login_ex = (0 == n) ? true : false;
		CString strlog;
		wchar_t* p_url = CFunctions::c2wc(m_ws_url_ex.c_str());
		if(is_websocket_login_ex){
			strlog.Format(_T("%s: %s"), _T(LOG_LOGIN_WEB_SERVER), p_url);
		}else{
			p_url = CFunctions::c2wc(m_ws_url_ex.c_str());
			strlog.Format(_T("%s: %s, err: %d"), _T(LOG_LOGIN_WEB_SERVER_FAILED), p_url, n);
		}
		show_log(strlog);

		if(p_url){
			free(p_url);
			p_url = NULL;
		}
	});
}

void CYAServerDlg::ws_logout_ex()
{
	USES_CONVERSION;
	CC2UTF8 conv = (char*)get_json_logout().c_str();
	string szlogout = conv.c_str();
	_io_ex->socket()->emit(JSON_CMD_VALUE_USER, szlogout, [&](sio::message::list const& msglist){
		message::ptr msg_ptr = msglist[0];
		int n =(int)msg_ptr->get_map()["code"]->get_int();
		CString strlog;
		wchar_t* p_url = CFunctions::c2wc(m_ws_url_ex.c_str());
		if(n == 0){
			strlog.Format(_T("%s: %s"), _T(LOG_LOGOUT_WEB_SERVER), p_url);
			is_websocket_login = false;
		}else{
			p_url = CFunctions::c2wc(m_ws_url_ex.c_str());
			strlog.Format(_T("%s: %s, err: %d"), _T(LOG_LOGOUT_WEB_SERVER_FAILED), p_url, n);
		}
		show_log(strlog);

		if(p_url){
			free(p_url);
			p_url = NULL;
		}
	});
}

void CYAServerDlg::TestFitData()
{
}

int CYAServerDlg::init_leader_arrange()
{
	clear_leader_arrange();
	// 载入带班领导信息
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	sprintf_s(buf, "select la.staff_id, s.card_id, la.shift_id, s.shift_type_id, la.duty_date,\
				   sht.start_time, sht.end_time, \
				   case when start_time > end_time then CONCAT(date_add(duty_date, INTERVAL -1 DAY), ' ', start_time) else \
				   CONCAT(duty_date,' ', start_time) end as stime, CONCAT( duty_date, ' ', end_time) as etime \
				   from dat_leader_arrange la, dat_shift sht, dat_staff_extend s \
				   where la.staff_id = s.staff_id and la.shift_id = sht.shift_id \
				   and la.duty_date >= date_add(curdate(), INTERVAL -1 DAY) and la.duty_date < date_add(curdate(), INTERVAL 1 DAY);");

	MYSQL_RES *pRes = getMysqlRes(buf);
	MYSQL_ROW pRow;

	if (NULL == pRes)
	{
		return 1;
	}

	std::shared_ptr<LeaderArrange> pLeader = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))	{
		LeaderArrangeMap::iterator it = mp_leaderarrange_list.find(pRow[1]);
		if(it != mp_leaderarrange_list.end()){
			pLeader = it->second;
		}else{
			pLeader = std::make_shared<LeaderArrange>(pRow[1]);
			mp_leaderarrange_list.insert(make_pair(pRow[1], pLeader));
		}
		pLeader->staff_id = atoi(pRow[0]);
		pLeader->shift_id = atoi(pRow[2]);
		pLeader->shift_type_id = atoi(pRow[3]);
		string strTime = pRow[7];
		API_StringToTime(strTime, pLeader->starttime);
		strTime = pRow[8];
		API_StringToTime(strTime, pLeader->endtime);

		nRow++;
	}
	mysql_free_result(pRes);

	CString strlog = _T("");
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_LEADER_ARRANGE), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

std::string CYAServerDlg::get_json_leader_arrange()
{
	Json::Value root;
	Json::Value data;
	LeaderArrangeMap::iterator it_leader = mp_leaderarrange_list.begin();
	for(; it_leader != mp_leaderarrange_list.end(); ++it_leader)
	{
		CardMap::iterator it_card = mp_card_list_down_person.find(it_leader->first);
		if(it_card != mp_card_list_down_person.end())
		{
			if( it_card->second->down_time >= it_leader->second->starttime && 
				it_card->second->down_time < it_leader->second->endtime)
			{
				Json::Value card;
				card[JSON_KEY_CARD_ID] = it_card->first;
				card[JSON_KEY_CARD_TYPE_ID] = it_card->second->card_type;
				data.append(card);
			}
		}
	}

	string ret = "";
	if(!data.isNull()) // 没有带班领导推送null
	{
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_LEADER_ARRANGE;
		root[JSON_ROOT_KEY_DATA] = data;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION_1_1;
		ret = root.toFastString();
	}

	return ret;
}

void CYAServerDlg::clear_leader_arrange()
{
	LeaderArrangeMap::iterator it_leader = mp_leaderarrange_list.begin();
	for(; it_leader != mp_leaderarrange_list.end();)
	{
		it_leader = mp_leaderarrange_list.erase(it_leader);
	}
}

void CYAServerDlg::cal_card_position_by_msg(std::shared_ptr<Card> card)
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_129);
	if(CT_ADHOC == card->card_type){ // 此处不需处理，已经在解析时计算了坐标位置		
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_218);
	}else if( LT_READER == theApp.locate_type){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_111);
		card->x = card->p_reader->ant[card->antenna_id]->antenna_x;
		card->y = card->p_reader->ant[card->antenna_id]->antenna_y;
		card->z = card->p_reader->ant[card->antenna_id]->antenna_z;
		card->a = card->p_reader->ant[card->antenna_id]->antenna_angle;
		card->reader_id = card->p_reader->reader_id;
	}else{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_112);
		// 将距离加入到距离列表
		std::shared_ptr<_coordinate> dist = std::make_shared<_coordinate>();
		dist->t = card->time_stamp;
		dist->cur_time = time(NULL);

		if (card->antenna_id < 0 || card->antenna_id >2)
		{
			return;
		}
		debug_print_syslog(0,"[core dump..]%s,antenan_id:%d,p_reader_id:%d,address:%0X",card->card_id.c_str(),card->antenna_id,card->p_reader->reader_id,card->p_reader);
		dist->x = card->p_reader->ant[card->antenna_id]->antenna_x;
		dist->y = card->p_reader->ant[card->antenna_id]->antenna_y;
		dist->z = card->p_reader->ant[card->antenna_id]->antenna_z;
		dist->a = card->p_reader->ant[card->antenna_id]->antenna_angle;
		dist->reader_id = card->p_reader->reader_id;
		dist->syncRootId = card->p_reader->sync_rootId;
		dist->antenna_id = card->antenna_id;
		dist->d = card->distance;
		dist->special = card->p_reader->m_nIsSpecial;
		dist->sync_num = card->sync_num;
		dist->acce_state = card->accelerate_state;
		dist->acce_state_last = card->accelerate_state_last;
		dist->ins_direction = card->ins_direction;
		dist->rangingtype = card->ranging_type;
		dist->ins_request_check = card->ins_request_check;
		dist->dimension = card->p_reader->dimension;
		dist->strength = card->strength;
		dist->recv_signal_power = card->recv_signal_power;

		bool bUseAlgo = false;
		unsigned long long rootId = dist->syncRootId;
		unsigned short root_sync_num = 0;

		if( LOCATEDATATYPE::LDT_TDOA == card->ranging_type)
		{
			if (umpRootSyncNum.count(rootId) > 0)
			{
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_113);
				root_sync_num = umpRootSyncNum[rootId];

				if (root_sync_num - (unsigned short)dist->sync_num <= MAX_CALCLINER_NUM) // unsigned short, ignore cross period
				{
					LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_115);
					bUseAlgo = true;
				}
				else
				{
					LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_116);
					//此处需要输出计数
					ALGORITHM_FAILED(ALGO_FAILED_CONDITION_1);
					card->m_afmData.bStatus = true;
					card->m_afmData.strCardId = card->card_id;
					card->m_afmData.nCardStamp = dist->t;
					card->m_afmData.nType = ALGO_FAILED_CONDITION_1;
				}
			}
			else
			{
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_219);
			}

			if(card->p_reader->sync_level == 0){
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_119);
				bUseAlgo = true;
			}

			if(bUseAlgo){
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_120);
#ifdef TRACE_MEMORY_TAGMSG
				HostServer::TagMsg tagMsg;
				tagMsg.ReceiveTime = card->flying_time;
				tagMsg.StationIdCode = HostServer::SyncHelper::parseId((unsigned long long)card->reader_id, (unsigned long long)(card->antenna_id + 1));
				tagMsg.SyncNum = card->sync_num;
				tagMsg.SyncRootIdCode = card->p_reader->sync_rootId;
				if(card->p_reader->sync_level == 0){
					LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_121);
					dist->tt = card->flying_time;
				}else{
					LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_122);
					dist->tt = syncmanager.calTimeByLinar(tagMsg);
					if (dist->tt == 0)
					{
						dist->tt = LONGLONG_MAX;
						LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_123);
						//TRACE(_T("calc error!\r\n"));
					}
				}
#endif // TRACE_MEMORY_TAGMSG
			}else{
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_220);
			}
		}
		else if(LOCATEDATATYPE::LDT_TOF == card->ranging_type)
		{
			bUseAlgo = true;
		}else if (LOCATEDATATYPE::LDT_TOF_INS == card->ranging_type)
		{
			//如果是惯导uwb请求校准数据，则add_dist进行tof数据定位
			//否则不加入add_dist
			bUseAlgo = true;
		}else if (LOCATEDATATYPE::LDT_TDOA_INS == card->ranging_type)
		{
			//如果是惯导uwb请求校准数据，则add_dist进行tof数据定位
			//否则不加入add_dist
			//非惯导请求校准状态
			//if (NO_INS_REQUEST == card->ins_request_check)
#if 0
			{
				//发送tof后第一次收到惯导信息，触发队列内的定位数据进行计算
				std::shared_ptr<POS> pos = std::make_shared<POS>();
				//if (card->is_send_ins_check)
				{
					pos->posx = card->cur_ins_pos->posx;
					pos->posy = card->cur_ins_pos->posy;
					pos->cx = pos->posx / card->map_scale;
					pos->cy = pos->posy / card->map_scale;
					card->time_cur_algo = time(NULL);
					card->time_stamp_cal = card->time_stamp;
					card->SaveTofData(pos);
					card->need_display = true;
					card->is_algo_first_location = true;
					//TRACE(_T("after ins check, ins output data: ct: %d, x: %.3f, y: %.3f \r\n"),card->time_stamp,pos->posx,pos->posy);
					char log[100] = {0};
					sprintf_s(log,"ct: %d, x: %.3f, y: %.3f, ins_status: %d",card->time_stamp,pos->posx,pos->posy,card->ins_request_check);
					std::string strLog = log;
					Log::write_log(FILE_TYPE::SYS_S,strLog,true);
				}
			}
			bUseAlgo = false;
#endif
		}

		if(bUseAlgo)
		{
			card->is_deal_by_algo = false;
			// 井上分站的数据，不进算法
			if(PDT_DOWN ==  card->p_reader->pos_state)
			{
				if(!(dist->d < ZERO_PRECISION && CFunctions::TOF == dist->rangingtype)) // lihongzhen  2017/9/28 滤掉tof分站上报测距结果为0的情况
				{
					if (need_drivingface_algo(card))
					{
						switch(card->card_type){
						case CT_SIMULATE_CARD:
							{
								op::point p = get_drivingface_base_point(card);
								debug_print_syslog(0,"[simulation card] card_id: %s, base_x: %.3f, base_y: %.3f",card->card_id.c_str(),p.x,p.y);
								if (!p.empty())
								{
									card->calc_tunnel_boring_machine_pos(p);
								}
							}
							break;
						case CT_TUNNELBORING_MACHINE:
						case CT_COALMINING_MACHINE:
							{
								int parent_reader_id = get_parent_anchor_id(card->reader_id);
								auto it_reader = mp_reader_list.find(parent_reader_id);
								if (it_reader != mp_reader_list.end())
								{
									op::point p((*it_reader).second->reader_x,(*it_reader).second->reader_y);
									card->calc_tunnel_boring_machine_pos(p);
								}
							}	
							break;
						}		
					}
					else{
						//---------------------------lemon_smooth---------------------
						NAMESPACE_POINT::loc_info li;
						//debug_print_syslog(0,"lemon_wtf=cardid:%s=ranging_type:%d,card_type:%d,power:%d",card->card_id.c_str(),card->ranging_type,card->card_type,card->power_state);						
						li.m_loc_time = card->m_ct_time;
						li.m_card_id = atoi(card->card_id.substr(3).c_str());
						li.m_tof = card->flying_time;
						li.m_card_ct = dist->t;
						li.m_cmd_id = card->ranging_type;
						li.m_card_type = card->card_type;
						li.m_bat_level = card->power_state;
						li.m_ant_id = dist->antenna_id;
						li.m_rav = card->pGyroscopeSensor->GetValue();
						li.m_acc = dist->acce_state;
						li.m_card_sp = card->recv_signal_power;

						std::string tci = card->card_id;
						std::shared_ptr<NAMESPACE_POINT::card_interface> ci(card);
						m_carmanage->put(card->card_id,li,ci,dist->reader_id);
					}

					////---------------------------lemon_smooth---------------------
					//NAMESPACE_POINT::loc_info li;
					//debug_print_syslog(0,"lemon_wtf=cardid:%s=ranging_type:%d,card_type:%d,power:%d",card->card_id.c_str(),card->ranging_type,card->card_type,card->power_state);
					//li.m_loc_time = card->m_ct_time;
					//li.m_card_id = atoi(card->card_id.substr(3).c_str());
					//li.m_tof = card->flying_time;
					//li.m_card_ct = dist->t;
					//li.m_cmd_id = card->ranging_type;
					//li.m_card_type = card->card_type;
					//li.m_bat_level = card->power_state;
					//li.m_ant_id = dist->antenna_id;
					//li.m_rav = card->pGyroscopeSensor->GetValue();
					//li.m_acc = dist->acce_state;
					//li.m_card_sp = card->recv_signal_power;

					//std::shared_ptr<NAMESPACE_POINT::card_interface> ci(card);
					//m_carmanage->put(card->card_id,li,ci,dist->reader_id);
					//------------------------------------------------------------
					/*			char chlog[MAX_LOG_LENGTH] = {0};
					memset(chlog,0,MAX_LOG_LENGTH*sizeof(char));
					sprintf_s(chlog,"[lemon]r: %d, ant: %d, ct: %d, d: %f, x: %f, y: %f, z: %f,card_id: %s,dimension: %d,acc: %d, rsp: %.3f, gy: %.3f, acc_v: %.3f ,ct_time:%lld,fly_time:%ld,bat_power:%d,cmd_type:%d,card_type:%d",
					dist->reader_id,
					dist->antenna_id, 
					dist->t, 
					dist->d, 
					dist->x, 
					dist->y, 
					dist->z,
					card->card_id.c_str(),
					dist->dimension,
					dist->acce_state,
					card->recv_signal_power,
					card->pGyroscopeSensor->GetValue(),
					card->pAcceSensor->GetValue(),
					card->m_ct_time,
					card->flying_time,
					card->power_state,
					card->ranging_type,
					card->card_type
					);
					Log::write_log(FILE_TYPE::DIST_TOF_S,chlog,true);
					*/
					//card->add_dist(dist);
				}
			}
			else
			{
				card->b_pos_change = false; //井上分站重置状态
			}
		}
		if (card->m_afmData.bStatus)
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_124);
			AnalysisAlgoFailedData();
			card->m_afmData.bStatus = false;
		}

		if(m_log_locate_data){
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_125);
			char chlog[MAX_LOG_LENGTH] = {0};
			std::string strlog = "";

			if (card->ranging_type == LOCATEDATATYPE::LDT_TDOA)
			{
				sprintf_s(chlog, "r: %d-%d, t: %d, max_t: %d, l:%d, tt: %I64u, ft: %I64u, x1: %f, y1: %f, z1: %f, ct: %d, cardid:%s, s: %d, power: %.2f",
					dist->reader_id, dist->antenna_id + 1, dist->sync_num, root_sync_num,card->p_reader->sync_level,
					dist->tt, card->flying_time,  dist->x, dist->y, dist->z, dist->t, card->card_id.c_str(), dist->strength,dist->recv_signal_power);
				strlog = chlog;
				Log::write_log(FILE_TYPE::DIST_S, strlog, true);

				//此处和save_card_msg消息存在不一致
				if(card->x != card->last_x || card->y != card->last_y){
					LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_126);
					memset(chlog, 0, MAX_LOG_LENGTH);
					sprintf_s(chlog, "cardid:%s, ct: %d, cx: %f, cy: %f,  clx: %f, cly: %f, v: %f,as: %d",
						card->card_id.c_str(), card->time_stamp_cal, card->x, card->y, card->last_x, card->last_y, card->get_speed(), card->accelerate_state);
					strlog = chlog;
					Log::write_log(FILE_TYPE::DISTEX_S, strlog, true);

					//card->last_x = card->x;
					//card->last_y = card->y;
					//card->last_z = card->z;
				}else{		
					if(card->is_deal_by_algo){
						LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_127);
						card->last_locate_time = time(NULL);
					}
				}
			} 
			else if(card->ranging_type == LOCATEDATATYPE::LDT_TOF ||
				card->ranging_type == LOCATEDATATYPE::LDT_TOF_INS ||
				card->ranging_type == LOCATEDATATYPE::LDT_TDOA_INS)
			{
				if (card->is_deal_by_algo)
				{
					if(card->x != card->last_x || card->y != card->last_y){
						std::string ltslog = "";
						memset(chlog,0,MAX_LOG_LENGTH*sizeof(char));
						std::string strAlgoTime = "";
						if (card->p_reader)
						{
							//strReaderTime = CFunctions::time_t2string(card->p_reader->reader_time);
							strAlgoTime = CFunctions::time_t2string(card->time_last_tof);
						}
						sprintf_s(chlog,"card_id: %s,ct: %d, cx: %.2f, cy: %.2f, cz: %.2f, clx: %.2f,fly: %.2f,cv: %f, algo_time: %s, errx: %.3f, erry: %.3f",
							card->card_id.c_str(),card->time_stamp_cal,card->x, card->y, card->z,card->last_x,card->last_y,card->get_speed(),strAlgoTime.c_str(), card->error_locate.x, card->error_locate.y);
						ltslog = chlog;
						Log::write_log(FILE_TYPE::LOCATE_TOF_S,ltslog,true);

						//card->last_x = card->x;
						//card->last_y = card->y;
						//card->last_z = card->z;
					}
				}

				std::string dtslog = "";
				std::string strRecTime = "";
				std::string strRawTime = "";
				strRecTime = CFunctions::time_t2string(card->rec_time);
				strRawTime = CFunctions::timet_to_string_with_ms(card->m_ct_time);

				string tmp_Time = CFunctions::timet_to_string_with_ms(card->rec_time);
				memset(chlog,0,MAX_LOG_LENGTH*sizeof(char));
				sprintf_s(chlog,"r: %d, ant: %d, ct: %d, d: %f, x: %f, y: %f, z: %f,card_id: %s,dimension: %d,acc: %d, rsp: %.3f, gy: %.3f, acc_v: %.3f power: %.2f",
					dist->reader_id,
					dist->antenna_id, 
					dist->t, 
					dist->d, 
					dist->x, 
					dist->y, 
					dist->z,
					card->card_id.c_str(),
					dist->dimension,
					dist->acce_state,
					card->recv_signal_power,
					card->pGyroscopeSensor->GetValue(),
					card->pAcceSensor->GetValue(),
					dist->recv_signal_power
					);
				dtslog = chlog;
				Log::write_log(FILE_TYPE::DIST_TOF_S,dtslog,true);
				handle_reverse_alarm(card,dist->antenna_id,dist->t,dist->d);
			}
		}
	}
}
void CYAServerDlg::handle_reverse_alarm(std::shared_ptr<Card> card,int16_t antid,uint32_t ct,double d)
{
	auto it = mp_driving_face_card_list.find(card->card_id);
	if(it != mp_driving_face_card_list.end()){
		auto pdc=it->second;
		if (pdc->warning()){
			op::point p0(card->p_reader->ant[0]->antenna_x,card->p_reader->ant[0]->antenna_y);
			op::point p1(card->p_reader->ant[1]->antenna_x,card->p_reader->ant[1]->antenna_y);
			if (!((*pdc)[0]==p0 && (*pdc)[1]==p1)){
				pdc->set(p0,p1,card->p_reader->reader_id);
				debug_print_syslog(0,"[reverse_alarm_start]%s,bigger:%d",card->card_id.c_str(),pdc->m_tas.bigger);
			}
			debug_print_syslog(0,"[reverse_alarm_working]%s,ct:%d,antid:%d,dist:%.2f",card->card_id.c_str(),ct,antid,d);
			pdc->make_reverse_condition(antid,ct,d);
		}
	}
}
MYSQL_RES* CYAServerDlg::getMysqlRes(const char* sql)
{
	if (g_pConnPool->m_needConnect)
	{
		return NULL;
	}
	//Log::write_log(SQL_S,sql,true);
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn, g_pConnPool);

	if(pConn == NULL){
		return NULL;
	}

	int err = 0;
	MYSQL_RES *pRes = pConn->Execute(sql, err);
	switch (err)
	{
	case CR_COMMANDS_OUT_OF_SYNC:
		break;
	case CR_SERVER_GONE_ERROR:
	case CR_SERVER_LOST:
		{		
			pDbGuard.isVaild();
		}
		break;
	case CR_UNKNOWN_ERROR:
	default:
		break;
	}
	return pRes;
}

void CYAServerDlg::TestMultSql()
{
	string strsql = "CALL add_att_vehicle(0020000001025, 1025, '2017-08-06 08:35:50', '2017-08-06 08:35:50', 9, 1, 51.100);";
	m_qsmSQL->AddString(strsql.c_str());
	strsql = "CALL add_att_vehicle(0020000001025, 1025, '2017-08-06 08:35:50', '2017-08-06 18:35:51', 10, 3, 39.049);";
	m_qsmSQL->AddString(strsql.c_str());
	strsql = "call add_area_vehicle(0020000001049, 1049, 5, 5, '2017-08-06 08:35:51','2017-08-06 08:35:51');";
	m_qsmSQL->AddString(strsql.c_str());
	strsql = "call add_area_vehicle(0020000001049, 1049, 5, 5, '2017-08-06 08:35:51','2017-08-06 18:35:51');";
	m_qsmSQL->AddString(strsql.c_str());
	strsql = "INSERT IGNORE INTO his_location_vehicle(card_id, vehicle_id, cur_time, x, y, z, map_id, area_id, \
			 state,speed,mileage, landmark_id, direction_mapper_id, landmark_dist) VALUES(0020000001016, 1016, \
			 '2017-8-6 8:35:50.559', 4727.000, -16.219, 0.000, 5, 1, 0,0.000,0.0000, 9, 3, 59.3290);";
	m_qsmSQL->AddString(strsql.c_str());

	m_qsmSQL->Execute();
}

void CYAServerDlg::TestCardPosition()
{
	std::shared_ptr<Card> pCard = std::make_shared<Card>("", 0, 0);
	pCard->x = 10, pCard->y = 10;
	pCard->last_locate.x = 10, pCard->last_locate.y = 5;
	pCard->algo_calc_offset();

	double x = pCard->x_offset_after();
	double y = pCard->y_offset_after();
	TRACE(_T("offset position: %.2f, %.2f, %.2f, %.2f, %.2f, %.2f\r\n"),
		pCard->last_locate.x, pCard->last_locate.y, pCard->x, pCard->y, x, y);

	pCard->x = 10, pCard->y = 10;
	pCard->last_locate.x = 10, pCard->last_locate.y = 15;
	pCard->algo_calc_offset();

	x = pCard->x_offset_after();
	y = pCard->y_offset_after();
	TRACE(_T("offset position: %.2f, %.2f, %.2f, %.2f, %.2f, %.2f\r\n"),
		pCard->last_locate.x, pCard->last_locate.y, pCard->x, pCard->y, x, y);

	pCard->x = 5, pCard->y = 10;
	pCard->last_locate.x = 10, pCard->last_locate.y = 10;
	pCard->algo_calc_offset();

	x = pCard->x_offset_after();
	y = pCard->y_offset_after();
	TRACE(_T("offset position: %.2f, %.2f, %.2f, %.2f, %.2f, %.2f\r\n"),
		pCard->last_locate.x, pCard->last_locate.y, pCard->x, pCard->y, x, y);

	pCard->x = 15, pCard->y = 10;
	pCard->last_locate.x = 10, pCard->last_locate.y = 10;
	pCard->algo_calc_offset();

	x = pCard->x_offset_after();
	y = pCard->y_offset_after();
	TRACE(_T("offset position: %.2f, %.2f, %.2f, %.2f, %.2f, %.2f\r\n"),
		pCard->last_locate.x, pCard->last_locate.y, pCard->x, pCard->y, x, y);

	pCard->x = 10, pCard->y = 10;
	pCard->last_locate.x = 5, pCard->last_locate.y = 5;
	pCard->algo_calc_offset();

	x = pCard->x_offset_after();
	y = pCard->y_offset_after();
	TRACE(_T("offset position: %.2f, %.2f, %.2f, %.2f, %.2f, %.2f\r\n"),
		pCard->last_locate.x, pCard->last_locate.y, pCard->x, pCard->y, x, y);

	pCard->x = 10, pCard->y = 10;
	pCard->last_locate.x = 5, pCard->last_locate.y = 15;
	pCard->algo_calc_offset();

	x = pCard->x_offset_after();
	y = pCard->y_offset_after();
	TRACE(_T("offset position: %.2f, %.2f, %.2f, %.2f, %.2f, %.2f\r\n"),
		pCard->last_locate.x, pCard->last_locate.y, pCard->x, pCard->y, x, y);

	pCard->x = 10, pCard->y = 10;
	pCard->last_locate.x = 15, pCard->last_locate.y = 15;
	pCard->algo_calc_offset();

	x = pCard->x_offset_after();
	y = pCard->y_offset_after();
	TRACE(_T("offset position: %.2f, %.2f, %.2f, %.2f, %.2f, %.2f\r\n"),
		pCard->last_locate.x, pCard->last_locate.y, pCard->x, pCard->y, x, y);

	pCard->x = 10, pCard->y = 10;
	pCard->last_locate.x = 15, pCard->last_locate.y = 5;
	pCard->algo_calc_offset();

	x = pCard->x_offset_after();
	y = pCard->y_offset_after();
	TRACE(_T("offset position: %.2f, %.2f, %.2f, %.2f, %.2f, %.2f\r\n"),
		pCard->last_locate.x, pCard->last_locate.y, pCard->x, pCard->y, x, y);
}

void CYAServerDlg::TestClock()
{
	SYSTEMTIME st;
	int i = 0;
	while (i < 1000)
	{
		GetLocalTime(&st);
		Log::write_log(FILE_TYPE::SYS_S,CFunctions::systime2string(st),true);
		i++;
		//Sleep(10);
	}
}

int CYAServerDlg::init_att_area()
{
	clear_att_area();
	// 载入考勤区域信息
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	sprintf_s(buf, "select vt.vehicle_type_id, aa.area_id, ar.offset_pre, ar.offset_back \
				   from dat_att_rule_vehicle_type vt \
				   left join dat_att_rule_area aa on vt.att_rule_id = aa.att_rule_id \
				   left join dat_att_rule ar on vt.att_rule_id = ar.att_rule_id \
				   where area_id is not null;");

	MYSQL_RES *pRes = getMysqlRes(buf);
	MYSQL_ROW pRow;

	if (NULL == pRes)
	{
		return 1;
	}

	std::shared_ptr<VehicleTypeAttRule> pAttArea = nullptr;
	int nRow = 0;
	int vehicle_type_id = 0, area_id = 0, offset_pre = 0, offset_back = 0;
	while(pRow = mysql_fetch_row(pRes))	{
		vehicle_type_id = atoi(pRow[0]), area_id = atoi(pRow[1]);
		offset_pre = (pRow[2] == NULL)? 0 :atoi(pRow[2]), offset_back = (pRow[3] == NULL)? 0 : atoi(pRow[3]);
		VehicleTypeAttRuleMap::iterator it_att_area = mp_att_area_list.find(vehicle_type_id);
		if(it_att_area != mp_att_area_list.end()){
			pAttArea = it_att_area->second;
		}else{
			pAttArea = std::make_shared<VehicleTypeAttRule>(vehicle_type_id, offset_pre, offset_back);
			mp_att_area_list.insert(make_pair(vehicle_type_id, pAttArea));
		}

		pAttArea->AddArea(area_id);
		nRow++;
	}
	mysql_free_result(pRes);

	CString strlog = _T("");
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_ATT_AREA), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

void CYAServerDlg::clear_att_area()
{
	VehicleTypeAttRuleMap::iterator it_att_area = mp_att_area_list.begin();
	for(; it_att_area != mp_att_area_list.end();)
	{
		it_att_area->second->vecArea.clear();
		it_att_area = mp_att_area_list.erase(it_att_area);
	}
}

void CYAServerDlg::set_card_pos_state(std::shared_ptr<Card> card)
{
	AreaMap::iterator it_area = mp_area_list.find(card->area_id);
	if(it_area != mp_area_list.end())
	{
		if(CT_PERSON == card->card_type)
		{
			card->PosState((POS_DEVICE_TYPE::PDT_UP == card->p_reader->pos_state) ? PDT_UP :PDT_DOWN);
		}
		else if(CT_VEHICLE == card->card_type|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type)
		{
			// 根据车辆类型判断是否在考勤区域
			card->PosState(GetPosDownAndUp(card->vehice_type_id, card->area_id));
		}
	}
}

void CYAServerDlg::deal_card_drivingface_real(std::shared_ptr<Card> card,std::shared_ptr<DrivingfaceCard> drivingface_card)
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_257);

	card_enter_map(card); // 切换地图
	card_enter_mine(card);
	card_enter_area(card); //切换区域
	save_card_postion(card); //保存坐标。如果这里保存了掘进机的坐标信息。
	//his_drivingface_real就没必要保存其非法坐标了，只需保存其有效坐标即可。从his_location_vehicle表中来记录。
	//if the card has entered the area that belong to the drivingface.then start to handle drivingface logic
	//debug_print_syslog(0,"[deal_card_drivingface_real] card_id: %s, cur_area_id: %d, drivingface_card_area_id: %d.  %d",card->card_id.c_str(),card->area_id,drivingface_card->area_id,drivingface_card->drivingface_id);
	//if (card->area_id == drivingface_card->area_id)
	{
		uint64_t te = 2;
		uint64_t key = te<<32|drivingface_card->drivingface_id;
		deal_warning_point_alarm(key,card);
		deal_drivingface_alarm_all(card,drivingface_card);
		//处理掘进机的正规循环率
		op::point p(card->x,card->y);
		//debug_print_syslog(0,"[deal_card_drivingface_real] card_id: %s, x: %.3f, y: %.3f",card->card_id.c_str(),card->x,card->y);
		if (!p.empty())
		{
			deal_drivingface_services(card);
			CardMap::iterator it_card = mp_card_list_down_vehicle.find(card->card_id);
			if(it_card == mp_card_list_down_vehicle.end())
			{
				mp_card_list_down_vehicle.insert(make_pair(card->card_id, card));
			}
		}
	}

	deal_card_state(card);

	card->isdealed = true;

	if(LT_READER != theApp.locate_type){
		card->issent = false;
	}
}

POS_DEVICE_TYPE CYAServerDlg::GetPosDownAndUp(int vehicle_type_id, int area_id)
{
	POS_DEVICE_TYPE ret = POS_DEVICE_TYPE::PDT_DOWN;
	VehicleTypeAttRuleMap::iterator it_rule = mp_att_area_list.find(vehicle_type_id);
	if(it_rule != mp_att_area_list.end())
	{
		std::vector<int>::iterator it_area = 
			std::find(it_rule->second->vecArea.begin(), it_rule->second->vecArea.end(), area_id);
		if(it_area != it_rule->second->vecArea.end())
		{
			ret = POS_DEVICE_TYPE::PDT_UP;
		}
	}

	return ret;
}

/*

* 通过anchor_id去找到其挂载到哪个具体ip下的大分站id
*
* 参数
*		anchor_id		小分站id或带ip大分站下挂载的大分站
*
* 返回值
*		如果找到，返回带ip大分站id；否则返回-1；
*/
int CYAServerDlg::get_parent_anchor_id(const int& id)
{
	//查找此分站
	ReaderMap::iterator it = mp_reader_list.find(id);
	if (it == mp_reader_list.end())
	{
		//如果分站不存在
		return -1;
	}

	for (auto it_card: mp_driving_face_card_list)
	{
		if (id == it_card.second->m_big_reader_id)
		{
			return id;
		}
		else if (id == it_card.second->m_small_reader_id)
		{
			return it_card.second->m_big_reader_id;
		}
	}
	return -1;
}

int CYAServerDlg::get_parent_anchor_id(const std::string& id)
{
	auto it = mp_driving_face_card_list.find(id);
	if (it!=mp_driving_face_card_list.end())
	{
		return it->second->m_big_reader_id;
	}
	return -1;
}

uint64_t CYAServerDlg::get_drivingface_schedule_value(const uint64_t& id,const uint8_t& type)
{
	uint64_t val = 0;

	char sql[LENGTH_SQL] = {'\0'};
	string str_cur_time = CFunctions::time_t2string(time(NULL));
	sprintf_s(sql,"select workface_id,schedule_tunnelling_times from dat_workface_scheduling where schedule_date=date('%s') and workface_id=%d ;",str_cur_time.c_str(),type,id);

	MYSQL_RES *pRes = getMysqlRes(sql);
	MYSQL_ROW pRow;

	if (NULL == pRes)
	{
		return val;
	}

	uint64_t face_id = 0;
	while(pRow = mysql_fetch_row(pRes))	{
		face_id = atoi(pRow[0] == NULL ? "0":pRow[0]);
		val = atoi(pRow[1] == NULL ? "0":pRow[1]);
	}
	mysql_free_result(pRes);

	if (face_id != id)
	{
		val = 0;
	}

	return val;
}

/*
 * 分站供电告警信息：
 *		a.当分站由电池供电时,状态位为0，开启告警；
 *		b.当分站由交流电供电时，状态位为1，关闭告警；
 *
 * 参数
 *		id		分站id号
 *		status	解析分站的供电状态标志位
 *
 * 返回值
 *		无
 *
*/
void CYAServerDlg::reader_power_battery_alarm(const uint64_t& id,const uint8_t& status)
{
	auto it_reader = mp_reader_list.find(id);
	if (it_reader==mp_reader_list.end())
	{
		return;
	}

	uint8_t uStatus = status;
	if (!it_reader->second->m_bNeedPowerAlarm)
	{
		//如果分站不需要电池供电告警，而告警事件列表中存在告警信息，需要发送结束告警事件
		if (it_reader->second->m_event_list[ET_READER_POWER_BY_BATTERY]>0)
		{
			uStatus = 1;
		}
		else{
			return;
		}
	}

	switch(uStatus){
	case 1:
		{
			INT64 ev_id = it_reader->second->m_event_list[ET_READER_POWER_BY_BATTERY];
			if(ev_id > 0){
				//结束分站电池供电告警
				EventMap::iterator it_ev = mp_event_list->find(ev_id);
				if(it_ev != mp_event_list->end()){
					it_ev->second->status = ES_END;
					it_ev->second->cur_time = time(NULL);
					it_ev->second->cur_value = uStatus;
					it_ev->second->is_sent = false;
					store_data_event(it_ev->second);
					add_event(it_ev->second);
				}	
				it_reader->second->m_event_list[ET_READER_POWER_BY_BATTERY] = 0;
#ifdef _DEBUG
				std::string strlog = "";
				char chlog[MAX_LOG_LENGTH] = {0};
				sprintf_s(chlog, "[event warning: restore reader power supply] reader_id: %d.",id);
				strlog = chlog;
				Log::write_log(FILE_TYPE::DISTXX_S, strlog, true);
#endif
				debug_print_syslog(0,"[event warning: restore reader power supply] reader_id: %d.",id);
			}
		}
		break;
	case 0:
		{
			//如果告警不存在,则开始构造告警数据
			if (it_reader->second->m_event_list[ET_READER_POWER_BY_BATTERY] > 0)
			{
				return;
			}
			//开始分站电池供电告警
			INT64 ev_id = CFunctions::GetMicroSecond();
			std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
			ev->status = ES_START;
			ev->ev_type = ET_READER_POWER_BY_BATTERY;
			ev->obj_type = OT_DEVICE_READER;
			ev->obj_id = CFunctions::int2string(id);
			ev->cur_time = time(NULL);

			ev->map_id = it_reader->second->map_id;
			ev->area_id = it_reader->second->area_id;
			ev->x = it_reader->second->reader_x;
			ev->y = it_reader->second->reader_y;

			ev->limit_value = 0;
			ev->cur_value = uStatus;
			ev->is_sent = false;

			it_reader->second->m_event_list[ET_READER_POWER_BY_BATTERY] = ev_id;
			store_data_event(ev);
			add_event(ev);
			debug_print_syslog(0,"[event warning: reader power supply by battery] reader_id: %d.",id);
#ifdef _DEBUG
			std::string strlog = "";
			char chlog[MAX_LOG_LENGTH] = {0};
			sprintf_s(chlog, "[event warning: reader power supply by battery] reader_id: %d.",id);
			strlog = chlog;
			Log::write_log(FILE_TYPE::DISTXX_S, strlog, true);
#endif
			Sleep(1);
		}
		break;
	}
}

 void CYAServerDlg::deal_lamp_light_alarm()
 {
	 for (auto it_light_group : m_carmanage->m_Map)
	 {
		 for (size_t i =0; it_light_group.second->m_pTrafficLight.size();++i)
		 {

			 int ndiff = (int)difftime(time(NULL), it_light_group.second->m_pTrafficLight[i]->m_rec_time);
			 if (STATUS_DEVICE_ERROR == it_light_group.second->m_pTrafficLight[i]->light_state)
			 {
				 if (ndiff < READER_TIMEOUT)
				 {
					 deal_lamp_light_event(ET_LIGHT_ERROR,false,it_light_group.second->m_pTrafficLight[i]);
				 }
			 } 
			 else
			 {
				 if (ndiff > READER_TIMEOUT)
				 {
					 deal_lamp_light_event(ET_LIGHT_ERROR,true,it_light_group.second->m_pTrafficLight[i]);
				 }
			 }
		 }
	 }

	 ReaderMap::iterator it = m_carmanage->getPhysicsTrafficLightId(dwLightId);
	 for(; it != mp_reader_list.end(); ++ it){
		 int ndiff = (int)difftime(time(NULL), it->second->rec_time);
		 if(STATUS_DEVICE_ERROR == it->second->reader_state){ // 异常 
			 if(ndiff < READER_TIMEOUT){ // 恢复正常
				 deal_readers_event(ET_READER_ERROR,false,it->second);
			 }
		 }else{
			 //分站20秒内未接收到数据，即产生告警
			 if(ndiff >= READER_TIMEOUT){ //异常
				 deal_readers_event(ET_READER_ERROR,true,it->second);
			 }
		 }
	 }
 }

 int CYAServerDlg::init_workingface_area(int area_id /* = 0 */)
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	if(0 == area_id){
		sprintf_s(strsql, "SELECT area_id, name, map_id, area_type_id, path, \
						  over_count_person, over_count_vehicle, over_time_person, over_time_vehicle, over_speed_vehicle, is_attendance \
						  FROM dat_workingface_area as wa,dat_area as a where wa.workingface_area_id = a.area_id;");
	}else{
		sprintf_s(strsql, "SELECT area_id, name, map_id, area_type_id, path, \
						  over_count_person, over_count_vehicle, over_time_person, over_time_vehicle, over_speed_vehicle, is_attendance \
						  FROM dat_workingface_area as wa,dat_area as a \
						  where wa.workingface_area_id = a.area_id and a.area_id = %d; ", area_id);
	}
	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}
	std::shared_ptr<Area> pArea = nullptr;

	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes)){
		AreaMap::iterator it = mp_workingface_area_list.find(atoi(pRow[0]));		
		if(it != mp_workingface_area_list.end()){
			pArea = it->second;
		}else{
			pArea = std::make_shared<Area>();
			pArea->area_id = atoi(pRow[0]);
			mp_workingface_area_list.insert(make_pair(pArea->area_id, pArea));
		}
		nRow++;
		pArea->map_id = atoi(pRow[2]);
		pArea->area_name = pRow[1];
		pArea->area_type_id = atoi(pRow[3]);
		pArea->path = pRow[4]; // 多边形
		pArea->over_count_person = atoi(pRow[5]);
		pArea->over_count_vehicle = atoi(pRow[6]);
		pArea->over_time_person = atoi(pRow[7]) * 60; // 转为秒
		pArea->over_time_vehicle = atoi(pRow[8]) * 60; // 转为秒
		pArea->over_speed_vehicle = atof(pRow[9]);
		pArea->is_att = atoi(pRow[10]);
		pArea->init_border(pRow[4]);
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_WORKINGFACE_AREA), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

void CYAServerDlg::clear_card_from_list(std::shared_ptr<Card> card)
{
	//人卡清理carmanage。
	//---------lemom smooth---
	if (CT_PERSON == card->card_type)
	{
		m_carmanage->erase(card->card_id);
		std::shared_ptr<NAMESPACE_POINT::card_interface> ci(card);
		deal_alarm_card_motionless(ci,false);
		m_carmanage->erase(ci);
	}
	//------------------------
	CardMap::iterator it_card;

	MapInfoMap::iterator it_map = mp_map_list.find(card->map_id);
	if(it_map != mp_map_list.end()){
		if(CT_VEHICLE == card->card_type|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type){
			// lihongzhen  2017/8/22 车辆不从列表中清除
			CardMap::iterator it_map_card = it_map->second->map_card_list_vehicle.find(card->card_id);
			if(it_map_card != it_map->second->map_card_list_vehicle.end()){
				it_map->second->map_card_list_vehicle.erase(it_map_card);
			}
		}else if(CT_PERSON == card->card_type){
			CardMap::iterator it_map_card = it_map->second->map_card_list_person.find(card->card_id);
			if(it_map_card != it_map->second->map_card_list_person.end()){
				it_map->second->map_card_list_person.erase(it_map_card);
			}
		}
	}
	AreaMap::iterator it_area = mp_area_list.find(card->area_id);
	if(it_area != mp_area_list.end()){
		if(CT_VEHICLE == card->card_type|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type){
			// lihongzhen  2017/8/22 车辆不从列表中清除
			//进入临界区，防止多个线程同时操作map
			EnterCriticalSection(&m_csAreaList);

			CardMap::iterator it_area_card = it_area->second->area_card_list_vehicle->find(card->card_id);
			if(it_area_card != it_area->second->area_card_list_vehicle->end()){
				it_area->second->area_card_list_vehicle->erase(it_area_card);
			}

			//退出临界区
			LeaveCriticalSection(&m_csAreaList);
		}else if(CT_PERSON == card->card_type){
			CardMap::iterator it_area_card = it_area->second->area_card_list_person->find(card->card_id);
			if(it_area_card != it_area->second->area_card_list_person->end()){
				if (it_area_card->second->accelerate_state == 0)
				{
					it_area->second->area_card_list_person->erase(it_area_card);
				}
			}
		}
	}
	DeptMap::iterator it_dept = mp_dept_list.find(card->dept_id);
	if(it_dept != mp_dept_list.end()){
		if(CT_VEHICLE == card->card_type|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type){
			// lihongzhen  2017/8/22 车辆不从列表中清除
			CardMap::iterator it_dept_card = it_dept->second->dept_card_list_vehicle.find(card->card_id);
			if(it_dept_card != it_dept->second->dept_card_list_vehicle.end()){
				it_dept->second->dept_card_list_vehicle.erase(it_dept_card);
			}
		}else if(CT_PERSON == card->card_type){
			CardMap::iterator it_dept_card = it_dept->second->dept_card_list_person.find(card->card_id);
			if(it_dept_card != it_dept->second->dept_card_list_person.end()){
				debug_print_syslog(0,"[dept_person dlear_card_erase]%s,deptId:%d",card->card_id.c_str(),card->dept_id);
				it_dept->second->dept_card_list_person.erase(it_dept_card);
			}
		}
	}
	if(CT_VEHICLE == card->card_type|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type){
		// lihongzhen  2017/8/22 车辆不从列表中清除
		it_card = mp_card_list_down_vehicle.find(card->card_id);
		if(it_card != mp_card_list_down_vehicle.end()){			
			mp_card_list_down_vehicle.erase(it_card);			
		}
		it_card = mp_card_list_forbidden_vehicle->find(card->card_id);
		if(it_card != mp_card_list_forbidden_vehicle->end()){
			mp_card_list_forbidden_vehicle->erase(it_card);
		}
		it_card = mp_card_list_over_time_vehicle->find(card->card_id);
		if(it_card != mp_card_list_over_time_vehicle->end()){
			mp_card_list_over_time_vehicle->erase(it_card);
		}
		it_card = mp_card_list_area_over_time_vehicle->find(card->card_id);
		if(it_card != mp_card_list_area_over_time_vehicle->end()){
			mp_card_list_area_over_time_vehicle->erase(it_card);
		}
		it_card = mp_card_list_over_speed_vehicle->find(card->card_id);
		if(it_card != mp_card_list_over_speed_vehicle->end()){
			mp_card_list_over_speed_vehicle->erase(it_card);
		}
	}else if(CT_PERSON == card->card_type) {
		it_card = mp_card_list_down_person.find(card->card_id);
		if(it_card != mp_card_list_down_person.end()){
			mp_card_list_down_person.erase(it_card);
		}
		it_card = mp_card_list_over_time_person->find(card->card_id);
		if(it_card != mp_card_list_over_time_person->end()){
			mp_card_list_over_time_person->erase(it_card);
		}
		it_card = mp_card_list_forbidden_person->find(card->card_id);
		if(it_card != mp_card_list_forbidden_person->end()){
			mp_card_list_forbidden_person->erase(it_card);
		}
		it_card = mp_card_list_help->find(card->card_id);
		if(it_card != mp_card_list_help->end()){
			mp_card_list_help->erase(it_card);
		}
		it_card = mp_card_list_area_over_time_person->find(card->card_id);
		if(it_card != mp_card_list_area_over_time_person->end()){
			mp_card_list_area_over_time_person->erase(it_card);
		}
		it_card = mp_card_list_over_count_person->find(card->card_id);
		if (it_card != mp_card_list_over_count_person->end())
		{
			mp_card_list_over_count_person->erase(it_card);
		}
		it_card = mp_card_list_over_count_vehicle->find(card->card_id);
		if (it_card != mp_card_list_over_count_vehicle->end())
		{
			mp_card_list_over_count_vehicle->erase(it_card);
		}
		OccLevelMap::iterator it_level = mp_occlevel_list.find(card->level_id);
		if(it_level != mp_occlevel_list.end())
		{
			CardMap::iterator it_level_card = it_level->second->level_card_list_person.find(card->card_id);
			if(it_level_card != it_level->second->level_card_list_person.end())
			{
				it_level->second->level_card_list_person.erase(it_level_card);
			}
		} 
	}
	it_card = mp_card_list_all.find(card->card_id);
	if(it_card != mp_card_list_all.end())
	{
		it_card->second->reset();
		it_card->second->resetAllBaseInfo();
	}
}

void CYAServerDlg::clear_call_card_by_user(std::string user_name)
{
	// 只删除该用户的所有呼叫信息，不从呼叫列表中删除该用户记录
	CallInfoUserMap::iterator it_user_call = mp_user_call_info.find(user_name);
	if(it_user_call != mp_user_call_info.end())
	{
		CallInfoReaderMap::iterator it_call_reader = it_user_call->second->mpReader.begin();
		for( ;it_call_reader != it_user_call->second->mpReader.end();){
			it_call_reader->second->mpCard.erase(it_call_reader->second->mpCard.begin(), it_call_reader->second->mpCard.end());
			it_call_reader = it_user_call->second->mpReader.erase(it_call_reader);
		}
	}
}

//获得地标信息
void CYAServerDlg::GetLandmarkInfo(std::shared_ptr<Card> card)
{
	_point card_point(card->x, card->y, card->z);
	int landmark_id = GetLandmarkID(card);

	if(-1 == landmark_id)
	{
		return ;
	}

	card->landmark_id = landmark_id;
	_point landmark_point;
	int directory_id = NODIRECTORY;
	double distance = 0;
	LandmarkInfoMap::iterator itLandmark = mp_landmark_list.find(landmark_id);		
	if(itLandmark != mp_landmark_list.end())
	{
		landmark_point.x = itLandmark->second->x;
		landmark_point.y = itLandmark->second->y;
		landmark_point.z = itLandmark->second->z;

		directory_id = GetDirectionType(card_point, landmark_point, card->map_id);
		if(NODIRECTORY != directory_id ){
			distance = GetDistance(card_point, landmark_point) *card->map_scale;
		}
	}

	card->landmark_direction = directory_id;
	card->landmark_dis = distance;
}

void CYAServerDlg::cal_distance_of_card()
{
	MapInfoMap::iterator it_map = mp_map_list.begin();
	int firstId = 0, secondId = 0, minId = 0, maxId = 0;
	char key[20] = {0};
	double distance = 99999.0;
	for (;it_map != mp_map_list.end();++it_map)
	{
		CardMap::iterator it_card_first = it_map->second->map_card_list_vehicle.begin();
		for(; it_card_first != it_map->second->map_card_list_vehicle.end(); ++it_card_first)
		{
			firstId = atoi((it_card_first->second->card_id.substr(3, it_card_first->second->card_id.length())).c_str());
			CardMap::iterator it_card_second = it_map->second->map_card_list_vehicle.begin();
			for(; it_card_second != it_map->second->map_card_list_vehicle.end(); ++it_card_second)
			{
				if(it_card_first->first == it_card_second->first)
				{
					continue; 
				}

				secondId = atoi((it_card_second->second->card_id.substr(3, it_card_second->second->card_id.length())).c_str());
				minId = min(firstId, secondId), maxId = max(firstId, secondId);
				sprintf_s(key, "%d-%d", minId, maxId); 

				MeetingInfoMap::iterator it_meeting = mp_meetinginfo_list.find(key);

				if(it_card_first->second->bInSpecailArea || it_card_second->second->bInSpecailArea
					|| STATUS_LOST == it_card_second->second->status_lost
					|| STATUS_LOST == it_card_first->second->status_lost)
				{
					if(it_meeting != mp_meetinginfo_list.end())
					{
						// lihongzhen  2017/8/28 置为会车结束状态
						it_card_first->second->state_meeting = STATE_ACCE_MEETING_OVER;
						it_card_second->second->state_meeting = STATE_ACCE_MEETING_OVER;
						mp_meetinginfo_list.erase(it_meeting);
					}					
					continue;
				}

				distance = 99999.0;
				distance = sqrt( pow(it_card_first->second->x - it_card_second->second->x,2) + 
					pow(it_card_first->second->y - it_card_second->second->y, 2)) / it_card_first->second->map_scale;

				if(distance > VEHICLE_WIDTH * 2)
				{
					if(it_meeting != mp_meetinginfo_list.end())
					{
						// lihongzhen  2017/8/28 置为回车结束状态
						it_card_first->second->state_meeting = STATE_ACCE_MEETING_OVER;
						it_card_second->second->state_meeting = STATE_ACCE_MEETING_OVER;
						mp_meetinginfo_list.erase(it_meeting);
					}
					continue;
				}

				if(it_meeting != mp_meetinginfo_list.end())
				{
					if(it_meeting->second.distance > distance)
					{
						it_meeting->second.distance = distance;
						it_meeting->second.reduce_counter ++;
					}
				}
				else
				{
					MeetingInfo mi ;
					mi.card_id_first = it_card_first->first;
					mi.card_id_second = it_card_second->first;
					mi.distance = distance;
					mi.keyValue = key;
					mi.reduce_counter = 1;

					mp_meetinginfo_list.insert(std::make_pair(key, mi));
				}
			}
		}
	}
}

void CYAServerDlg::deal_card_dept_changed(std::shared_ptr<Card> card, int dept_id)
{
	DeptMap::iterator it_dept = mp_dept_list.find(card->dept_id);
	if(it_dept != mp_dept_list.end())
	{
		if(CT_VEHICLE == card->card_type|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type)
		{
			CardMap::iterator it_card = it_dept->second->dept_card_list_vehicle.find(card->card_id);
			if(it_card != it_dept->second->dept_card_list_vehicle.end())
			{
				it_dept->second->dept_card_list_vehicle.erase(it_card);
			}
		}
		else if( CT_PERSON == card->card_type)
		{
			CardMap::iterator it_card = it_dept->second->dept_card_list_person.find(card->card_id);
			if(it_card != it_dept->second->dept_card_list_person.end())
			{
				debug_print_syslog(0,"[dept_person dept_changed_erase chaged.]%s,deptId:%d",card->card_id.c_str(),card->dept_id);
				it_dept->second->dept_card_list_person.erase(it_card);
			}
		}
	}

	it_dept = mp_dept_list.find(dept_id);
	if(it_dept != mp_dept_list.end())
	{
		if(CT_PERSON == card->card_type)
		{
			debug_print_syslog(0,"[dept_person dept_changed_insert]%s,deptId:%d",card->card_id.c_str(),card->dept_id);
			it_dept->second->dept_card_list_person.insert(std::make_pair(card->card_id, card));
		}
		else if(CT_VEHICLE == card->card_type|| CT_COALMINING_MACHINE == card->card_type ||CT_TUNNELBORING_MACHINE == card->card_type)
		{
			it_dept->second->dept_card_list_vehicle.insert(std::make_pair(card->card_id, card));
		}
	}
}

void CYAServerDlg::reset_vehicle_meeting_state()
{
	MeetingInfoMap::iterator it_meeting = mp_meetinginfo_list.begin();
	CardMap::iterator it_card;
	for(; it_meeting != mp_meetinginfo_list.end(); ++it_meeting)
	{
		if(it_meeting->second.reduce_counter >0 && it_meeting->second.distance < VEHICLE_WIDTH){
			it_card = mp_card_list_down_vehicle.find(it_meeting->second.card_id_first);
			if(it_card != mp_card_list_down_vehicle.end())
			{
				it_card->second->state_meeting = STATE_ACCE_MEETING;
			}

			it_card = mp_card_list_down_vehicle.find(it_meeting->second.card_id_second);
			if(it_card != mp_card_list_down_vehicle.end())
			{
				it_card->second->state_meeting = STATE_ACCE_MEETING;
			}
		}
	}
}

/****************************************/
//查看是否需要使用自己的点来推动前端
/****************************************/
bool CYAServerDlg::determine_Save_Point_Or_Not(std::shared_ptr<Card> ccard)
{
	bool ret = false;
	if(ccard->m_card_ptr.expired())
	{
		ret = false;
	}
	else
	{
		std::shared_ptr<card> spc = ccard->m_card_ptr.lock();
		ret = spc->save_point();
	}
	return ret;
}
void CYAServerDlg::card_deal_other_business(std::shared_ptr<Card> card)
{
	//do monkeyCar business here.
	if (card->card_type == CT_PERSON)
	{
		if (card->m_area_changed)
		{
			debug_print_syslog(0,"[lemon the second choice area changed]cardid:%s",card->card_id.c_str());
			card->m_area_changed = false;
			Area_Map::iterator itmap = mp_area_list_->find(card->pre_area_id);
			if (itmap != mp_area_list_->end())
			{
				itmap->second->on_card_leave(card->card_id,card->area_id);
			}
			itmap = mp_area_list_->find(card->area_id);
			if (itmap != mp_area_list_->end())
			{
				itmap->second->on_card_enter(card,card->area_id);
			}
		}
		else
		{
			auto itmap = mp_area_list_->find(card->area_id);
			if (itmap != mp_area_list_->end())
			{
				itmap->second->on_card_move(card);
			}
		}
	}
}

/*
* 实现Web界面上手动拖动车辆位置的功能
* 在采集器初始化的时候和界面发送通知手动挪车的时候，清空list，从数据库表中读入已挪动位置的车辆和位置，放入list中。
* 
* add by wangsiping 2017/10/11
* 
* param
*		无
* return
*		成功返回0，失败返回1
*/
int CYAServerDlg::init_handup_vehicle()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	int nRow = 0;

	pRes = getMysqlRes("select card_id,new_x,new_y,new_area_id from dat_handup_vehicle;");

	if(NULL == pRes)
	{
		return 1;
	}

	//进入临界区，防止多个线程同时操作map
	EnterCriticalSection(&m_csHandUp);

	//清空list
	//mp_card_hand_up_list->erase(mp_card_hand_up_list->begin(), mp_card_hand_up_list->end());

	while(pRow = mysql_fetch_row(pRes))	{
		std::shared_ptr<HandUpVehicle> level = std::make_shared<HandUpVehicle>();
		level->card_id = pRow[0];
		level->point_x = atoi(pRow[1]);
		level->point_y = atoi(pRow[2]);
		level->area_id = atoi(pRow[3]);
		mp_card_hand_up_list->insert(make_pair(level->card_id, level));
		nRow++;
	}

	//退出临界区	
	LeaveCriticalSection(&m_csHandUp);	

	mysql_free_result(pRes);

	return 0;
}

/*
* 实现Web界面上手动拖动车辆位置的功能
* 判断卡坐标是否和hand up在一定半径内
* 
* add by wangsiping 2017/10/12
* 
* param
*		真实坐标X,Y,list中坐标X,Y
* return
*		在半径范围内返回0，不在半径范围内返回1
*/
int CYAServerDlg::is_in_handup_area(double real_x, double real_y, double list_x, double list_y)
{
	double destance_def = 5.0;

	double destance_x = fabs(real_x - list_x);
	double destance_y = fabs(real_y - list_y);
	double destance = sqrt((destance_x * destance_x) + (destance_y * destance_y));

	if(destance > destance_def)
	{
		return 1;
	}

	return 0;
}

/*
* 实现Web界面上手erase_handup_vehicle动拖动车辆位置的功能
* 擦除hand_up数据库中的对应记录
* 
* add by wangsiping 2017/10/12
* 
* param
*		card_id
* return
*		None
*/

void CYAServerDlg::erase_handup_vehicle(std::string card_id)
{
	char strSql[LENGTH_SQL] = {0};
	sprintf_s(strSql, "delete from dat_handup_vehicle where card_id = %s;", card_id.c_str());

	getMysqlRes(strSql);


	return;
}

/*
* 实现Web界面上手动拖动车辆位置的功能
* 更新hand_up数据库中的对应记录
* 
* add by wangsiping 2017/10/12
* 
* param
*		card_id
* return
*		成功返回0，失败返回1
*/

int CYAServerDlg::refresh_handup_list(std::string card_id)
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_290);
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	std::shared_ptr<HandUpVehicle> level = nullptr;
	int nRow = 0;

	char strSql[LENGTH_SQL] = {0};
	sprintf_s(strSql, "select card_id,new_x,new_y,new_area_id from dat_handup_vehicle where card_id = %s;", card_id.c_str());

	pRes = getMysqlRes(strSql);
	if(NULL == pRes)
	{
		return 1;
	}

	//进入临界区，防止多个线程同时操作map
	EnterCriticalSection(&m_csHandUp);

	HandUpVehicleMap::iterator it_handup = mp_card_hand_up_list->find(card_id);
	if(it_handup != mp_card_hand_up_list->end())
	{
		level = it_handup->second;
		while(pRow = mysql_fetch_row(pRes))	
		{
			level->card_id = pRow[0];
			level->point_x = atoi(pRow[1]);
			level->point_y = atoi(pRow[2]);
			level->area_id = atoi(pRow[3]);
			nRow++;
		}
	}
	else
	{
		level = std::make_shared<HandUpVehicle>();
		while(pRow = mysql_fetch_row(pRes))	
		{
			level->card_id = pRow[0];
			level->point_x = atoi(pRow[1]);
			level->point_y = atoi(pRow[2]);
			level->area_id = atoi(pRow[3]);
			nRow++;
		}
		mp_card_hand_up_list->insert(make_pair(level->card_id, level));
	}

	//退出临界区
	LeaveCriticalSection(&m_csHandUp);
	mysql_free_result(pRes);

	//手动拖车走业务,更改card相关数据
	CardMap::iterator it_card = mp_card_list_all.find(level->card_id);
	if(it_card != mp_card_list_all.end()){
		it_card->second->x = level->point_x;
		it_card->second->y = level->point_y;
		it_card->second->area_id = level->area_id;
	}

	//把新的card传入，走一下业务
	//deal_card_msg_handup(it_card->second);

	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_291);
	return 0;
}

/*
* 实现Web界面上手动拖动车辆位置的功能
* 向页面返回数据
* 
* add by wangsiping 2017/10/12
* 
* param
*		data
* return
*		成功返回0，失败返回1
*/

int CYAServerDlg::parse_json_data_hand_up(std::string card_id)
{

	Json::Value data;
	Json::Value root;
	std::string strSend = "";
	data[JSON_KEY_CARD_ID] = card_id;
	data[JSON_KEY_STATE] = 0;

	if(data.size() > 0){
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_HAND_UP_RESPONSE;
		root[JSON_ROOT_KEY_DATA] = data;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION;
		strSend = root.toFastString();
		send_json_data(JSON_CMD_VALUE_PUSH, strSend);
	}


	return 0;
}


//double CYAServerDlg::my_k_means_algo(double x1,double x2, double x3)
//{
//	std::vector<double> vec_x1;
//	std::vector<double> vec_x2;
//	std::vector<double> vec_x3;
//	do{
//		vec_x1.clear();
//		vec_x2.clear();
//		vec_x3.clear();
//		for (int i = 0; i < m_Get_AverageSpeed.size();i++)
//		{
//			int maxvec = abs(m_Get_AverageSpeed[i]-x1) > abs(m_Get_AverageSpeed[i]-x2)? (abs(m_Get_AverageSpeed[i]-x2)>abs(m_Get_AverageSpeed[i]-x3)?3:2) : (abs(m_Get_AverageSpeed[i]-x1)>abs(m_Get_AverageSpeed[i]-x3)?3:1);
//
//			switch (maxvec)
//			{
//			case 1:
//				vec_x1.push_back(m_Get_AverageSpeed[i]);
//				break;
//			case 2:
//				vec_x2.push_back(m_Get_AverageSpeed[i]);
//				break;
//			case 3:
//				vec_x3.push_back(m_Get_AverageSpeed[i]);
//				break;
//			default:
//				break;
//			}
//		}
//		double average_x1,average_x2,average_x3 ;
//		average_x3=average_x2=average_x1=0;
//		if (vec_x1.size() == 0)
//		{
//			average_x1 = x1;
//		}
//		else
//		{
//			average_x1 = accumulate_D(vec_x1)/vec_x1.size();
//		}
//		if (vec_x2.size() == 0)
//		{
//			average_x2 = x2;
//		}
//		else
//		{
//			average_x2 = accumulate_D(vec_x2)/vec_x2.size();
//		}		
//		if (vec_x3.size() == 0)
//		{
//			average_x3 = x3;
//		}
//		else
//		{
//			average_x3 = accumulate_D(vec_x3)/vec_x3.size();
//		}
//		//cout << "-------------" << vec_x1.size()<< "  " << vec_x2.size() << "  " <<vec_x3.size()<<endl;
//		if (abs(average_x1 - x1) < 0.01 && abs(average_x2-x2) < 0.01 && abs(average_x3- x3) < 0.01)
//		{
//			int which_vec = vec_x1.size()> vec_x2.size()?(vec_x1.size()>vec_x3.size() ? 1:3) : (vec_x2.size()>vec_x3.size()?2:3);
//			//cout << average_x1 << "  " << average_x2 << " " << average_x3 <<"Last..."<<endl;
//			switch (which_vec)
//			{
//			case 1:
//				return average_x1;
//				//break;
//			case 2:
//				return average_x2;
//				//break;
//			case 3:
//				return average_x3;
//				//break;
//			default:
//				break;
//			}
//		}
//		else
//		{
//			x1 = average_x1;
//			x2 = average_x2;
//			x3 = average_x3;
//			//my_k_means(average_x1,average_x2,average_x3);
//		}
//	}while (true);
//}

/*
* 实现Web界面上手动拖动车辆位置的功能
* 手动拖车走业务
* 
* add by wangsiping 2017/11/01
* 
* param
*		card
* return
*		无
*/
void CYAServerDlg::deal_card_msg_handup( std::shared_ptr<Card> card )
{
	save_card_postion(card);
	card_enter_map(card); // 切换地图
	card_enter_area(card);//
	//card_getonoff_monkeycar(card);
	card_enter_mine(card);
	deal_card_state(card);

	//deal_traffic_lights(card);
	select_pos_output(card);

	card->isdealed = true;

	debug_print_syslog(0, "exit deal_card_msg_handup.");
	return;
}



void CYAServerDlg::store_worktime_detail(std::shared_ptr<Card> card,int tag,const char* cur_time)
{
	if(!cur_time)
		return;
	bool b_exec = false;
	char sql[LENGTH_SQL] = {0};
	char _time[STR_LEN_TIME], _time_ex[STR_LEN_TIME];
	BYTE staff_type = card->m_staff_type;
	if (card->m_staff_type == CARD_FRONT_LINE_WORKERS)
	{
		//一线工人
		AreaMap::iterator it = mp_area_list.find(card->area_id);
		if (it != mp_area_list.end())
		{
			if (it->second->m_is_work_area == 1)
			{
				sprintf_s(_time,
				STR_LEN_TIME,
				"%04d-%02d-%02d %02d:%02d:%02d",card->enter_area_time.wYear,card->enter_area_time.wMonth,
				card->enter_area_time.wDay,card->enter_area_time.wHour,card->enter_area_time.wMinute,card->enter_area_time.wSecond);
				tm tm_Enter;
				tm_Enter.tm_year=card->enter_area_time.wYear;
				tm_Enter.tm_mon=card->enter_area_time.wMonth;
				tm_Enter.tm_wday=card->enter_area_time.wDay;
				tm_Enter.tm_hour=card->enter_area_time.wHour;
				tm_Enter.tm_min=card->enter_area_time.wMinute;
				tm_Enter.tm_sec=card->enter_area_time.wSecond;
				int shift_id=GetCurShiftId(&tm_Enter);
				//工作区域
				if (tag == HIS_AREA_LOCATION_ENTER)
				{
					if(card->id)
					{
						b_exec = true;
						//进入区域
						sprintf_s(sql, LENGTH_SQL, 
							"INSERT IGNORE INTO his_worktime_detail(staff_id, start_work_time,end_work_time,real_work_time,schedule_work_time,work_area_id,shift_id) \
							VALUES(%d, '%s', NULL, %.3f, %.3f, %d,%d);",  
							card->id,_time,0.0f,8.0f,card->area_id,shift_id);
					}
				}
				else if(tag == HIS_AREA_LOCATION_LEAVE)
				{
					memset(_time,0,STR_LEN_TIME);
					sprintf_s(_time,
					STR_LEN_TIME,
					"%04d-%02d-%02d %02d:%02d:%02d",
					card->deal_time.wYear,card->deal_time.wMonth,card->deal_time.wDay,
					card->deal_time.wHour,card->deal_time.wMinute,card->deal_time.wSecond);
					if(card->id && GetStartWorkTime(card->id,_time_ex))
					{
						string currentLeaveTime;
						GetCurrentLeaveAreaTime(_time_ex,cur_time,card->area_id,currentLeaveTime,card->id);
						if (currentLeaveTime != "")
						{
							b_exec = true;
							SYSTEMTIME tm1;
							sscanf(currentLeaveTime.c_str(), "%d-%d-%d %d:%d:%d",       
								&(tm1.wYear),   
								&(tm1.wMonth),   
								&(tm1.wDay),  
								&(tm1.wHour),  
								&(tm1.wMinute),  
								&(tm1.wSecond));  
							INT64 mdiff = CFunctions::TimeDiffMS(tm1,card->enter_area_time);
							double dHour = (double)mdiff / (double)(1000*60*60);
							//离开区域
							sprintf_s(sql, LENGTH_SQL, 
								"UPDATE his_worktime_detail SET end_work_time='%s',proc_tag=1,real_work_time= %.3f where staff_id=%d and start_work_time='%s';",  
								currentLeaveTime.c_str(),dHour,card->id,_time_ex);
						}
					}
					
				}
			}
		}
	}
	if(b_exec){
		execute_sql(sql);
	}
}

bool CYAServerDlg::GetStartWorkTime(int id, char* start_work_time)
{
	memset(start_work_time,0,STR_LEN_TIME);
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	std::string error = "";
	MYSQL_RES* pResRpt;
	MYSQL_ROW pRowRpt;

	sprintf_s(buf,sizeof(buf),"select start_work_time from his_worktime_detail where staff_id=%d and proc_tag=0 order by start_work_time desc limit 1",id);

	pResRpt = sDBConnPool.Query(buf,error);
	if (NULL == pResRpt)
	{
		debug_print_syslog(0,"[GetStartWorkTime : query sql failed] %s",buf);
		return false;
	}

	if (pRowRpt = mysql_fetch_row(pResRpt))
	{
		SYSTEMTIME st;
		CFunctions::string2systemtime(pRowRpt[0],st);

		sprintf_s(start_work_time,STR_LEN_TIME,"%04d-%02d-%02d %02d:%02d:%02d",st.wYear,st.wMonth,st.wDay,st.wHour,st.wMinute,st.wSecond);
		mysql_free_result(pResRpt);

		return true;
	}
	else
	{
		mysql_free_result(pResRpt);
		return false;
	}
}

void CYAServerDlg::GetCurrentLeaveAreaTime(const char* enter_time,const char* cur_time,int area_id,string &current_leave_time,int staff_id,int tag)
{
	/*int err = 0;
	char buf[LENGTH_SQL] = {0};
	std::string error = "";
	MYSQL_RES* pResRpt;
	MYSQL_ROW pRowRpt;
	sprintf_s(buf,sizeof(buf),"select end_time from rpt_att_staff where staff_id=%d and start_time<'%s' and \
								end_time > '%s' and end_time < '%s'",staff_id,enter_time,enter_time,cur_time);
	pResRpt = sDBConnPool.Query(buf,error);
	SYSTEMTIME sTimeRpt;
	SYSTEMTIME sTimeWorkTime;
	if (NULL == pResRpt)
	{
		debug_print_syslog(0,"[init_drivingface_recently_info : query sql failed] %s",buf);
		return ;
	}
	if (pRowRpt = mysql_fetch_row(pResRpt))
	{
		SYSTEMTIME st;
		CFunctions::string2systemtime(pRowRpt[0],st);
		char _time[STR_LEN_TIME] ={};
		sprintf_s(_time,STR_LEN_TIME,"%04d-%02d-%02d %02d:%02d:%02d",st.wYear,st.wMonth,st.wDay,st.wHour,st.wMinute,st.wSecond);
		current_leave_time=_time;
		mysql_free_result(pResRpt);
	}
	else
	{
		mysql_free_result(pResRpt);
		MYSQL_ROW pRow;
		MYSQL_RES* pRes;
		sprintf_s(buf, sizeof(buf),"select start_work_time from his_worktime_detail where staff_id=%d and work_area_id=%d and start_work_time>'%s' \
				   order by start_work_time asc",staff_id,area_id,enter_time);
		//pRes = getMysqlRes(buf);
		pRes = sDBConnPool.Query(buf,error);
		if (NULL == pRes)
		{
			debug_print_syslog(0,"[init_drivingface_recently_info : query sql failed] %s",buf);
			return ;
		}
		if (pRow = mysql_fetch_row(pRes))
		{
			SYSTEMTIME st;
			CFunctions::string2systemtime(pRow[0],st);
			char _time[STR_LEN_TIME] ={};
			sprintf_s(_time,STR_LEN_TIME,"%04d-%02d-%02d %02d:%02d:%02d",st.wYear,st.wMonth,st.wDay,st.wHour,st.wMinute,st.wSecond);
			current_leave_time=_time;
			mysql_free_result(pRes);
		}
		else
		{
			mysql_free_result(pRes);
			current_leave_time=cur_time;
		}
	}*/
	char buf[LENGTH_SQL] = {0};
	std::string error = "";
	MYSQL_RES* pResRpt;
	MYSQL_ROW pRowRpt;
	sprintf_s(buf,sizeof(buf),"select end_time from rpt_att_staff where staff_id=%d and start_time<'%s' and \
								end_time > '%s' and end_time < '%s'",staff_id,enter_time,enter_time,cur_time);
	pResRpt = sDBConnPool.Query(buf,error);
	SYSTEMTIME sTimeRpt;
	BOOL brpt = FALSE;
	BOOL bwork = FALSE;
	SYSTEMTIME sTimeWorkTime;
	if (NULL == pResRpt)
	{
		debug_print_syslog(0,"[init_drivingface_recently_info : query sql failed] %s",buf);
		return ;
	}
	if (pRowRpt = mysql_fetch_row(pResRpt))
	{
		SYSTEMTIME st;
		CFunctions::string2systemtime(pRowRpt[0],st);
		sTimeRpt = st;
		brpt = TRUE;
	}
	mysql_free_result(pResRpt);
	sprintf_s(buf, sizeof(buf),"select start_work_time from his_worktime_detail where staff_id=%d and work_area_id=%d and start_work_time>'%s' \
				order by start_work_time asc",staff_id,area_id,enter_time);
	//pRes = getMysqlRes(buf);
	pResRpt = sDBConnPool.Query(buf,error);
	if (NULL == pResRpt)
	{
		debug_print_syslog(0,"[init_drivingface_recently_info : query sql failed] %s",buf);
		return ;
	}
	if (pRowRpt = mysql_fetch_row(pResRpt))
	{
		SYSTEMTIME st;
		CFunctions::string2systemtime(pRowRpt[0],st);
		sTimeWorkTime = st;
		bwork = TRUE;
	}
	mysql_free_result(pResRpt);
	if (brpt && bwork)
	{
		INT64 mdiff = CFunctions::TimeDiffMS(sTimeRpt,sTimeWorkTime);
		if (mdiff > 0)
		{
			char _time[STR_LEN_TIME] ={};
			sprintf_s(_time,STR_LEN_TIME,"%04d-%02d-%02d %02d:%02d:%02d",sTimeWorkTime.wYear,sTimeWorkTime.wMonth,sTimeWorkTime.wDay,
				sTimeWorkTime.wHour,sTimeWorkTime.wMinute,sTimeWorkTime.wSecond);
			current_leave_time = _time;
		}
		else
		{
			char _time[STR_LEN_TIME] ={};
			sprintf_s(_time,STR_LEN_TIME,"%04d-%02d-%02d %02d:%02d:%02d",sTimeRpt.wYear,sTimeRpt.wMonth,sTimeRpt.wDay,
				sTimeRpt.wHour,sTimeRpt.wMinute,sTimeRpt.wSecond);
			current_leave_time = _time;
		}
	}
	else if(brpt)
	{
		char _time[STR_LEN_TIME] ={};
			sprintf_s(_time,STR_LEN_TIME,"%04d-%02d-%02d %02d:%02d:%02d",sTimeRpt.wYear,sTimeRpt.wMonth,sTimeRpt.wDay,
				sTimeRpt.wHour,sTimeRpt.wMinute,sTimeRpt.wSecond);
			current_leave_time = _time;
	}
	else if(bwork)
	{
		char _time[STR_LEN_TIME] ={};
			sprintf_s(_time,STR_LEN_TIME,"%04d-%02d-%02d %02d:%02d:%02d",sTimeWorkTime.wYear,sTimeWorkTime.wMonth,sTimeWorkTime.wDay,
				sTimeWorkTime.wHour,sTimeWorkTime.wMinute,sTimeWorkTime.wSecond);
			current_leave_time = _time;
	}
	else
	{
		current_leave_time = cur_time;
	}
}
int CYAServerDlg::Init_worktime_detail()
{
	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	sprintf_s(buf, "select d_staff.card_id,d_staff.work_line,h_work.start_work_time,h_work.work_area_id from his_worktime_detail h_work \
		inner join dat_staff_extend d_staff on h_work.staff_id=d_staff.staff_id where h_work.proc_tag=0 order by start_work_time;");
	//pRes = getMysqlRes(buf);
	std::string error = "";
	pRes = sDBConnPool.Query(buf,error);
	if (NULL == pRes)
	{
		debug_print_syslog(0,"[init_drivingface_recently_info : query sql failed] %s",buf);
		return 0;
	}
	std::shared_ptr<Card> pCard = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))	{
		CardMap::iterator it = mp_card_list_all.find(pRow[0]);
		if(it != mp_card_list_all.end()){
			pCard = it->second;
			if(atoi(pRow[1]) == 1)
			{
				SYSTEMTIME st;
				CFunctions::string2systemtime(pRow[2],st);
				pCard->enter_area_time.wYear = st.wYear;
				pCard->enter_area_time.wMonth = st.wMonth;
				pCard->enter_area_time.wDay = st.wDay;
				pCard->enter_area_time.wHour = st.wHour;
				pCard->enter_area_time.wMinute = st.wMinute;
				pCard->enter_area_time.wSecond = st.wSecond;
				pCard->area_id=atoi(pRow[3]);
			}
			else if(atoi(pRow[1]) == 2)
			{
				SYSTEMTIME st;
				CFunctions::string2systemtime(pRow[2],st);
				pCard->down_time = CFunctions::systime_to_timet(st);
				pCard->area_id=atoi(pRow[3]);
			}
		/*	SYSTEMTIME st;
			CFunctions::string2systemtime(pRow[2],st);
			pCard->down_time = CFunctions::systime_to_timet(st);
			pCard->area_id=atoi(pRow[3]);
		*/
			nRow++;
		}
	}
	mysql_free_result(pRes);

	CString strlog = _T("");
	strlog.Format(_T("%s%d%s"), _T(LOG_WORKTIME_DETAIL), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}
