12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048 |
- #include "CustMngrAuthFSM.h"
- #include "CustMngrAuth_UserErrorCode.h"
- #include "SpHelper.h"
- #include "fileutil.h"
- #include <fstream>
- #include <map>
- #include <memory>
- #include <thread>
- #include <chrono>
- #include <string>
- #include <ctime>
- #include <cstring>
- using std::string;
- const int UPDATE_INTERNAL = 10 * 60 * 1000; //query data from branch server internal, 10min
- const int CONNECT_INTERNAL = 10 * 60 * 1000; //connect branch server internal, 10min
- const int FINGER_NUM = 8; //suuport max register finger num
- const int COLLECT_TIMES = 3; //press finger times
- #define IMAGE_NUM 3
- #define RUNINFOFILE "CustMngrAuth.ini"
- #define RUNINFOFILE_BAK "CustMngrAuth_bak.ini"
- class CCustMngrAuthEntity;
- #pragma region event response
- void CCustMngrAuthFSM::s0_on_entry()
- {
- LOG_FUNCTION();
- FSMEvent* pEvt = new FSMEvent(USER_EVT_INIT);
- PostEventFIFO(pEvt);
- }
- void CCustMngrAuthFSM::s0_on_exit()
- {
- LOG_FUNCTION();
- }
- unsigned int CCustMngrAuthFSM::s0_on_event(FSMEvent* pEvt)
- {
- LOG_FUNCTION();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("s0 evt %d", pEvt->iEvt);
- switch (pEvt->iEvt)
- {
- case USER_EVT_INIT:
- {
- InitTask* task = new InitTask(this);
- GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- pEvt->SetHandled();
- return 0;
- }
- break;
- default:
- break;
- }
- return 0;
- }
- void CCustMngrAuthFSM::s1_on_entry()
- {
- LOG_FUNCTION();
- }
- void CCustMngrAuthFSM::s1_on_exit()
- {
- LOG_FUNCTION();
- }
- unsigned int CCustMngrAuthFSM::s1_on_event(FSMEvent* pEvt)
- {
- LOG_FUNCTION();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("s1 evt %d", pEvt->iEvt);
- switch (pEvt->iEvt)
- {
- case USER_EVT_INIT_FINISHED:
- pEvt->SetHandled();
- return pEvt->param1;
- default:
- break;
- }
- return 0;
- }
- void CCustMngrAuthFSM::s2_on_entry()
- {
- LOG_FUNCTION();
- }
- void CCustMngrAuthFSM::s2_on_exit()
- {
- LOG_FUNCTION();
- }
- unsigned int CCustMngrAuthFSM::s2_on_event(FSMEvent* pEvt)
- {
- LOG_FUNCTION();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("s2 evt(%d)", pEvt->iEvt);
- switch (pEvt->iEvt)
- {
- case USER_EVT_AUTHORIZE_START:
- {
- pEvt->SetHandled();
- AuthorizeStartEvent* authorEvt = dynamic_cast<AuthorizeStartEvent*>(pEvt);
- if (authorEvt->ctx->Req.TimeLimit <= 0)
- {
- AuthorizeFinishedEvent* e = new AuthorizeFinishedEvent();
- e->ctx = authorEvt->ctx;
- e->param1 = Error_Param;
- this->PostEventFIFO(e);
- break;
- }
- //time here should be less than the web
- m_TimeLimit = (authorEvt->ctx->Req.TimeLimit - 3) * 1000;
- m_bCancelAuthorize = false;
- MatchFingerPrintTask* matchTask = new MatchFingerPrintTask(this);
- matchTask->ctx = authorEvt->ctx;
- GetEntityBase()->GetFunction()->PostThreadPoolTask(matchTask);
- }
- break;
- case USER_EVT_QUERYAUTHORINFO:
- {
- pEvt->SetHandled();
- QueryAuthorInfoEvent* queryEvt = dynamic_cast<QueryAuthorInfoEvent*>(pEvt);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER)("time = %d", queryEvt->ctx->Req.TimeLimit);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER)("wayOfKey = %d", queryEvt->ctx->Req.WayofKey);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER)("wayOfFinger = %d", queryEvt->ctx->Req.WayofFinger);
- if (queryEvt->ctx->Req.TimeLimit <= 0)
- {
- LOG_TRACE("ERROR: receive timelimit lessequal than zero. ctx->Answer(error_Param)");
- QueryAuthorInfoFinishedEvent* e = new QueryAuthorInfoFinishedEvent();
- e->ctx = queryEvt->ctx;
- e->param1 = Error_Param;
- this->PostEventFIFO(e);
- break;
- }
- m_TimeLimit = (queryEvt->ctx->Req.TimeLimit - 2) * 1000;
- ErrorCodeEnum eErr;
- m_bCancelAuthorize = false;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER)("WayOfKey = %d, WayOfFinger = %d", queryEvt->ctx->Req.WayofKey, queryEvt->ctx->Req.WayofFinger);
- if (queryEvt->ctx->Req.WayofKey == 1)
- {
- //打开USB
- }
- if (queryEvt->ctx->Req.WayofFinger == 1)
- {
- //起指纹匹配线程
- MatchFingerPrintTaskEx* mTask = new MatchFingerPrintTaskEx(this);
- mTask->ctx = queryEvt->ctx;
- GetEntityBase()->GetFunction()->PostThreadPoolTask(mTask);
- }
- }
- break;
- case USER_EVT_COLLECTFINGERPRINT_START:
- {
- pEvt->SetHandled();
- CollectFingerPrintStartEvent* collectEvt = dynamic_cast<CollectFingerPrintStartEvent*>(pEvt);
- CollectFingerPrintTask* collectTask = new CollectFingerPrintTask(this);
- collectTask->ctx = collectEvt->ctx;
- GetEntityBase()->GetFunction()->PostThreadPoolTask(collectTask);
- }
- break;
- case USER_EVT_COLLECTFINGERPRINTEX_START:
- {
- pEvt->SetHandled();
- CollectFingerPrintExStartEvent* collectEvt = dynamic_cast<CollectFingerPrintExStartEvent*>(pEvt);
- CollectFingerPrintExTask* collectExTask = new CollectFingerPrintExTask(this);
- collectExTask->ctx = collectEvt->ctx;
- GetEntityBase()->GetFunction()->PostThreadPoolTask(collectExTask);
- }
- break;
- case USER_EVT_COLLECTFINGERPRINTINFO:
- {
- pEvt->SetHandled();
- CollectFingerPrintInfoEvent* collectEvt = dynamic_cast<CollectFingerPrintInfoEvent*>(pEvt);
- CollectFingerPrintInfoTask* collectExTask = new CollectFingerPrintInfoTask(this);
- collectExTask->ctx = collectEvt->ctx;
- GetEntityBase()->GetFunction()->PostThreadPoolTask(collectExTask);
- }
- break;
- case USER_EVT_GENERATE_TEMPLATE:
- {
- pEvt->SetHandled();
- GenerateTemplateEvent* gtEvt = dynamic_cast<GenerateTemplateEvent*>(pEvt);
- GenerateTemplateTask* gtTask = new GenerateTemplateTask(this);
- gtTask->ctx = gtEvt->ctx;
- GetEntityBase()->GetFunction()->PostThreadPoolTask(gtTask);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Generate Template task posted");
- }
- break;
- case USER_EVT_SAVEFINGERPRINT_START:
- {
- pEvt->SetHandled();
- SaveFingerPrintStartEvent* saveEvtfpe = dynamic_cast<SaveFingerPrintStartEvent*>(pEvt);
- SaveFingerPrintTask* saveTask = new SaveFingerPrintTask(this);
- saveTask->ctx = saveEvtfpe->ctx;
- GetEntityBase()->GetFunction()->PostThreadPoolTask(saveTask);
- }
- break;
- case USER_EVT_CHECKUKEY:
- {
- pEvt->SetHandled();
- //SwitchUSB(true);
- }
- break;
- default:
- break;
- }
- return 0;
- }
- void CCustMngrAuthFSM::s3_on_entry()
- {
- LOG_FUNCTION();
- ScheduleTimer(1, m_TimeLimit);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("set timer when match, %dms", m_TimeLimit);
- }
- void CCustMngrAuthFSM::s3_on_exit()
- {
- LOG_FUNCTION();
- CancelTimer(1);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("exit match event, timer canceled");
- }
- unsigned int CCustMngrAuthFSM::s3_on_event(FSMEvent* pEvt)
- {
- LOG_FUNCTION();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("s3 evt %d, %d", pEvt->iEvt, pEvt->param1);
- switch (pEvt->iEvt)
- {
- case USER_EVT_HOLDON:
- {
- pEvt->SetHandled();
- CancelTimer(1);
- HoldOnEvent* holdEvt = dynamic_cast<HoldOnEvent*>(pEvt);
- if (holdEvt->ctx == NULL)
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("HoldOnEvent->ctx is NULL");
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER)("HoldOn with MoreTime: %d second", holdEvt->ctx->Req.MoreTime);
- int moreTime = holdEvt->ctx->Req.MoreTime * 1000;
- ScheduleTimer(1, (moreTime > 0) ? moreTime : m_TimeLimit);
- }
- break;
- case EVT_TIMER:
- {
- pEvt->SetHandled();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Hit Timer");
- m_bAuthorizeTimeout = true;
- m_bCancelAuthorize = true;
- CancelAuthorize();
- }
- break;
- case USER_EVT_AUTHORIZE_FINISHED:
- {
- pEvt->SetHandled();
- AuthorizeFinishedEvent* authorEvt = dynamic_cast<AuthorizeFinishedEvent*>(pEvt);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Checking m_authCtx and answer ctx");
- if (authorEvt->param1 == 0)
- {
- if (m_authCtx.eAuthByWhich == AuthByUkey)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("m_authCtx.eAuthByWhich == AuthByUkey");
- if (m_pFingerPrint != NULL && !m_pFingerPrint->QuerySessionClosed())
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Invoke cancel match.");
- m_pFingerPrint->CancelMatch();
- }
- authorEvt->ctx->Ans.WayofAuth = AuthByUkey;
- authorEvt->ctx->Ans.UkeyID = m_authCtx.UkeyID;
- authorEvt->ctx->Answer(Error_Succeed);
- }
- else if (m_authCtx.eAuthByWhich == AuthByFngPrnt)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("m_authCtx.eAuthByWhich == AuthByFngPrnt");
- authorEvt->ctx->Ans.WayofAuth = AuthByFngPrnt;
- authorEvt->ctx->Ans.CustomerID = m_authCtx.CustomerID;
- authorEvt->ctx->Answer(Error_Succeed);
- }
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("authorize finished with param1 as %d", authorEvt->param1);
- authorEvt->ctx->Answer((ErrorCodeEnum)authorEvt->param1);
- }
- if (m_pFingerPrint != NULL && !m_pFingerPrint->QuerySessionClosed())
- {
- //m_bCancelAuthorize = true; //已结束授权,无用?
- m_pFingerPrint->GetFunction()->CloseSession();
- m_pFingerPrint = NULL;
- }
- m_authCtx.eAuthByWhich = AuthByNone;
- m_authCtx.CustomerID = "";
- m_authCtx.UkeyID = "";
- m_ctx = NULL;
- }
- break;
- case USER_EVT_QUERYAUTHORINFO_FINISHED:
- {
- pEvt->SetHandled();
- QueryAuthorInfoFinishedEvent* qafEvt = dynamic_cast<QueryAuthorInfoFinishedEvent*>(pEvt);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Checking m_authCtx and answer qaInfoCtx");
- if (qafEvt->param1 == 0)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER)("authorize finished with param1 as 0"); //Error_Succeed
- if (m_authCtx.eAuthByWhich == AuthByUkey)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("m_authCtx.eAuthByWhich == AuthByUkey");
- if (m_pFingerPrint != NULL && !m_pFingerPrint->QuerySessionClosed())
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Invoke cancel collect.");
- m_pFingerPrint->CancelRegister();
- }
- qafEvt->ctx->Ans.WayofAuth = AuthByUkey;
- qafEvt->ctx->Ans.UkeyID = m_authCtx.UkeyID;
- qafEvt->ctx->Answer(Error_Succeed);
- }
- else if (m_authCtx.eAuthByWhich == AuthByFngPrnt)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("m_authCtx.eAuthByWhich == AuthByFngPrnt");
- qafEvt->ctx->Ans.WayofAuth = AuthByFngPrnt;
- qafEvt->ctx->Ans.Feature = m_authCtx.Feature;
- qafEvt->ctx->Ans.FingerImg = m_authCtx.FingerImg;
- qafEvt->ctx->Answer(Error_Succeed);
- }
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("authorize finished with param1 as %d", qafEvt->param1);
- qafEvt->ctx->Answer((ErrorCodeEnum)qafEvt->param1, qafEvt->param2);
- }
- if (m_pFingerPrint != NULL && !m_pFingerPrint->QuerySessionClosed())
- {
- m_bCancelAuthorize = true;
- m_pFingerPrint->GetFunction()->CloseSession();
- m_pFingerPrint = NULL;
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("M_pFingerPrint disconnected.");
- }
- m_authCtx.eAuthByWhich = AuthByNone;
- m_authCtx.CustomerID = "";
- m_authCtx.UkeyID = "";
- m_authCtx.Feature = "";
- memset(&m_authCtx.FingerImg, 0, sizeof(m_authCtx.FingerImg));
- qaInfoCtx = NULL;
- }
- break;
- case USER_EVT_AUTHORIZE_CANCEL:
- {
- pEvt->SetHandled();
- m_bCancelAuthorize = true;
- CancelAuthorize();
- }
- break;
- case USER_EVT_QUERYAUTHORINFO_CANCEL:
- {
- pEvt->SetHandled();
- m_bCancelAuthorize = true;
- CancelCollect();
- }
- break;
- default:
- break;
- }
- return 0;
- }
- void CCustMngrAuthFSM::s4_on_entry()
- {
- LOG_FUNCTION();
- }
- void CCustMngrAuthFSM::s4_on_exit()
- {
- LOG_FUNCTION();
- }
- unsigned int CCustMngrAuthFSM::s4_on_event(FSMEvent* pEvt)
- {
- LOG_FUNCTION();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("s4 evt %d, %d", pEvt->iEvt, pEvt->param1);
- switch (pEvt->iEvt)
- {
- case USER_EVT_COLLECTFINGERPRINT_FINISHED:
- pEvt->SetHandled();
- break;
- case USER_EVT_COLLECTFINGERPRINTEX_FINISHED:
- pEvt->SetHandled();
- break;
- case USER_EVT_COLLECTFINGERPRINTINFO_FINISHED:
- pEvt->SetHandled();
- break;
- case USER_EVT_GENERATE_TEMPLATE_FINISHED:
- pEvt->SetHandled();
- break;
- case USER_EVT_COLLECTFINGERPRINT_CANCEL:
- {
- pEvt->SetHandled();
- if (m_pFingerPrint != NULL && !m_pFingerPrint->QuerySessionClosed())
- m_pFingerPrint->CancelRegister();
- }
- break;
- case USER_EVT_SAVEFINGERPRINT_FINISHED:
- pEvt->SetHandled();
- break;
- case USER_EVT_CHECKUKEY_FINISHED:
- {
- pEvt->SetHandled();
- }
- break;
- default:
- break;
- }
- return 0;
- }
- void CCustMngrAuthFSM::s5_on_entry()
- {
- LOG_FUNCTION();
- }
- void CCustMngrAuthFSM::s5_on_exit()
- {
- LOG_FUNCTION();
- }
- unsigned int CCustMngrAuthFSM::s5_on_event(FSMEvent* pEvt)
- {
- LOG_FUNCTION();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("s5 evt %d, %d", pEvt->iEvt, pEvt->param1);
- return 0;
- }
- #pragma endregion
- #pragma region invoked function
- ErrorCodeEnum CCustMngrAuthFSM::WaitForUkey(ErrorCodeEnum eErr)
- {
- int status = (eErr == Error_NoTarget) ? 4 : 3;//4: no data in local, 3:enitty exception
- BroadcastGetFinger(status);
- while (1)
- {
- SLEEP(300);
- if (m_bCancelAuthorize)
- {
- m_bCancelAuthorize = false;
- if (m_bAuthorizeTimeout)
- {
- m_bAuthorizeTimeout = false;
- return Error_TimeOut;
- }
- else
- return Error_Cancel;
- }
- }
- }
- void CCustMngrAuthFSM::CancelAuthorize()
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Invoke m_pFingerPrint->CancelMatch()");
- if (m_pFingerPrint != NULL && !m_pFingerPrint->QuerySessionClosed())
- m_pFingerPrint->CancelMatch();
- }
- void CCustMngrAuthFSM::CancelCollect()
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Invoke m_pFingerPrint->CancelRegister()");
- if (m_pFingerPrint != NULL && !m_pFingerPrint->QuerySessionClosed())
- m_pFingerPrint->CancelRegister();
- }
- ErrorCodeEnum CCustMngrAuthFSM::SwitchUSB(bool bOpen)
- {
- LOG_FUNCTION();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("connecting DeviceControl");
- ErrorCodeEnum errCode;
- m_pDeviceControl = new DeviceControlService_ClientBase(GetEntityBase());
- if (m_pDeviceControl != NULL)
- {
- errCode = m_pDeviceControl->Connect();
- if (errCode != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("m_pDeviceControl connect failed with errCode(%s)", SpStrError(errCode));
- m_pDeviceControl->SafeDelete();
- }else {
- if (bOpen)
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Open USB");
- else
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Close USB");
- DeviceControlService_USB_Req usbReq;
- DeviceControlService_USB_Ans usbAns;
- usbReq.open = bOpen;//open or close usb
- errCode = m_pDeviceControl->USB(usbReq, usbAns, 2000);
- if (errCode != Error_Succeed)
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Open/Close usb failed.");
- else
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Open/Close usb success.");
- m_pDeviceControl->GetFunction()->CloseSession();
- }
- m_pDeviceControl = NULL;
- return errCode;
- }
- else {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("DeviceControl is null.");
- return Error_Unexpect;
- }
- }
- #pragma endregion
- #pragma region entity init
- ErrorCodeEnum CCustMngrAuthFSM::OnInit()
- {
- LOG_FUNCTION();
- CSystemStaticInfo staticInfo;
- m_pEntity->GetFunction()->GetSystemStaticInfo(staticInfo);
- m_TerminalID = staticInfo.strTerminalID;
- m_csMachineType = staticInfo.strMachineType;
- m_authCtx.eAuthByWhich = AuthByNone;
- m_FingerSection = "FingerInfo";
- return Error_Succeed;
- }
- int CCustMngrAuthFSM::Initial()
- {
- ErrorCodeEnum errCode = OpenRunInfoFile();
- if (errCode != Error_Succeed)
- return 1;
- return 0;
- }
- ErrorCodeEnum CCustMngrAuthFSM::OpenRunInfoFile()
- {
- ErrorCodeEnum errCode;
- errCode = GetEntityBase()->GetFunction()->GetPath("RunInfo", m_RunInfoPath);
- if (errCode != Error_Succeed)
- {
- LogError(Severity_High, Error_DevLoadFileFailed
- , LOG_ERR_CUSTMNGRAUTH_GET_RUNINFO_PATH_FAILED_Init
- , "get runinfo path failed while init");
- errCode = Error_Unexpect;
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("runinfo path: %s", m_RunInfoPath.GetData());
-
- return errCode;
- }
- #pragma endregion
- #pragma region entity exit
- ErrorCodeEnum CCustMngrAuthFSM::OnExit()
- {
- LOG_FUNCTION();
- FSMImpl<CCustMngrAuthFSM>::OnExit();
- return Error_Succeed;
- }
- #pragma endregion
- #pragma region update feature process
- void CCustMngrAuthFSM::FeatureUpdate()
- {
- LOG_FUNCTION();
- InitBeforeUpdateData();
- int waitInternal = UPDATE_INTERNAL;
- while (true)
- {
- do
- {
- int connectFailedTimes = 0;
- m_pConnection = new FeatureUpdateConn(m_pEntity, this);
- if (m_pConnection->ConnectFromCentralSetting() && m_pConnection->IsConnectionOK())
- {
- connectFailedTimes = 0;
- waitInternal = UPDATE_INTERNAL;
- ErrorCodeEnum errCode;
- CSmartPointer<IConfigInfo> spConfig;
- CAutoArray<CSimpleStringA> transArray;
- RunInfoParams runInfoParam;
- memset(&runInfoParam, 0, sizeof(runInfoParam));
- errCode = InitBeforeQueryData(runInfoParam, spConfig);
- if (errCode != Error_Succeed)
- break;
-
- errCode = ReceiveDataFromServer(transArray, runInfoParam);
- if (errCode != Error_Succeed)
- break;
- errCode = BackupBeforeWriteData(runInfoParam, spConfig);
- if (errCode != Error_Succeed)
- break;
- errCode = WriteData(runInfoParam, transArray, spConfig);
- if (errCode != Error_Succeed)
- break;
- }else {
- connectFailedTimes++;
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("connect branchserver failed for %d times, try again in %d ms."
- , connectFailedTimes, CONNECT_INTERNAL);
- if (connectFailedTimes >= 60)
- {
- //30min give a warn
- LogWarn(Severity_Middle, Error_Unexpect
- , LOG_ERR_CUSTMNGRAUTH_FEATUPDATE_CONNECT_FAILED
- , "Connect branch server failed.");
- connectFailedTimes = 0;
- }
- waitInternal = CONNECT_INTERNAL;
- }
- } while (false);
- if (m_pConnection)
- {
- m_pConnection->Close();
- m_pConnection->DecRefCount();
- m_pConnection = NULL;
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Feature-update processed, wait until next");
- //wait for next query
- if (WaitForSingleObject(hStopUpdate, waitInternal) == WAIT_OBJECT_0)
- break;
- }
- }
- /// <summary>
- /// Init memory data
- /// </summary>
- void CCustMngrAuthFSM::InitBeforeUpdateData()
- {
- bool bHasData = false;
- bool bReadResult = ReadDataIntoMemory(bHasData);
- if (bReadResult && bHasData)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Read feature data into memory success.");
- }
- else if (bReadResult && !bHasData) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Has no data in local file.");
- }
- else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Read feature data into memory failed, wait next read.");
- }
- }
- /// <summary>
- /// read fingerprint feature data into memory from local file
- /// </summary>
- /// <param name="bHasData">output param</param>
- /// <returns></returns>
- bool CCustMngrAuthFSM::ReadDataIntoMemory(bool& bHasData)
- {
- LOG_FUNCTION();
- CSimpleStringA runInfoFile(true);
- runInfoFile = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR RUNINFOFILE
- , m_RunInfoPath.GetData());
- std::ifstream inFile(runInfoFile.GetData());
- string line;
- int customerNum = 0;
- ULLINT startReadFile = RVCGetTickCount();
- ULLINT endReadFile = RVCGetTickCount();
- while (getline(inFile, line))
- {
- if (line.length() <= 0)
- continue;
- string tempLine = ClearStringSpaceHeadTail(line);
- if (!tempLine.compare("[UpdateTime]") || string::npos != tempLine.find("UpdateTime")
- || !tempLine.compare("[LatestTime]") || string::npos != tempLine.find("LatestTime")
- || !tempLine.compare("[FingerInfo]") || !tempLine.compare("[FaceInfo]")
- || string::npos != tempLine.find("FaceInfo1") || string::npos != tempLine.find("FaceInfo2"))
- {
- continue;
- }
- string::size_type pos = tempLine.find("=");
- if (pos != 16)
- continue;
- string keys = tempLine.substr(0, pos);
- string values = tempLine.substr(pos + 1);
- Json::Reader reader;
- Json::Value root;
- if (reader.parse((const char*)values.c_str(), root))
- {
- customerNum++;
- FeatureData* fd = new FeatureData();
- fd->FingerIDArray.Init(FINGER_NUM);
- fd->FingerIDLenArray.Init(FINGER_NUM);
- char index[20];
- for (int i = 0; i < FINGER_NUM; ++i)
- {
- memset(index, 0, sizeof(index));
- #ifdef RVC_OS_WIN
- _snprintf_s(index, 10, "FingerID%d", i + 1);
- #else
- snprintf(index, 10, "FingerID%d", i + 1);
- #endif // RVC_OS_WIN
- fd->FingerIDArray[i] = root.isMember(index) ? CSimpleStringA(root[index].asCString()) : "";
- fd->FingerIDLenArray[i] = root.isMember(index) ? fd->FingerIDArray[i].GetLength() : 0;
- }
- m_featureData[CSimpleStringA(keys.c_str())] = fd;
- }
- else {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("Error: parse jsonFingerInfo failed.");
- LogWarn(Severity_Middle, Error_Unexpect
- , LOG_ERR_CUSTMNGRAUTH_AUTHORIZATION_READFEAT_FAILED
- , "Read fingerprint feature json failed.");
- return false;
- }
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Total CustomerNum:%d in local file.", customerNum);
- endReadFile = RVCGetTickCount();
- ULLINT duration = endReadFile - startReadFile;
- LogWarn(Severity_Middle, Error_Debug
- , LOG_ERR_CUSTMNGRAUTH_READ_INTO_MEMORY_TIME
- , GenerateAlarmJson("CustMngrAuth", duration).GetData());
- bHasData = true;
- return true;
- }
- CSimpleString CCustMngrAuthFSM::GenerateAlarmJson(CSimpleString entityName, int cost)
- {
- return CSimpleString::Format("[{\"name\":\"%s\",\"cost\":%d}]"
- , entityName.GetData(), cost);
- }
- string CCustMngrAuthFSM::ClearStringSpaceHeadTail(string& line)
- {
- if (line.empty())
- return line;
- line.erase(0, line.find_first_not_of(" "));
- line.erase(line.find_last_not_of(" ") + 1);
- return line;
- }
- /// <summary>
- /// init runinfo pointer and some time parameters
- /// </summary>
- /// <param name="runInfoParam">out param</param>
- /// <param name="spConfig">out param</param>
- /// <returns></returns>
- ErrorCodeEnum CCustMngrAuthFSM::InitBeforeQueryData(RunInfoParams& runInfoParam, CSmartPointer<IConfigInfo>& spConfig)
- {
- ErrorCodeEnum errCode = Error_Succeed;
- EnterCriticalSection(&m_cs);//临时锁一下运行时,防止在写入
- errCode = LoadRunConfig(spConfig);
- if (Error_Succeed != errCode)
- {
- LeaveCriticalSection(&m_cs);
- return errCode;
- }
- InitTimeParams(runInfoParam, spConfig);
- LeaveCriticalSection(&m_cs);
- return errCode;
- }
- ErrorCodeEnum CCustMngrAuthFSM::LoadRunConfig(CSmartPointer<IConfigInfo>& spConfig)
- {
- ErrorCodeEnum errCode = Error_Succeed;
- errCode = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfig);
- if (errCode != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Open runcfg file failed before query data.");
- LogError(Severity_High, Error_Unexpect
- , LOG_ERR_CUSTMNGRAUTH_OPEN_RUNINFO_FAILED_UPDATE
- , "open runcfg failed before query data.");
- }
- return errCode;
- }
- void CCustMngrAuthFSM::InitTimeParams(RunInfoParams& runInfoParam, CSmartPointer<IConfigInfo>& spConfig)
- {
- ErrorCodeEnum errCode = Error_Succeed;
- runInfoParam.LatestTime = "";
- runInfoParam.UpdateTime = "";
- CSimpleStringA latestTime(""), updateTime("");
- spConfig->ReadConfigValue("LatestTime", "LatestTime", latestTime);
- spConfig->ReadConfigValue("UpdateTime", "UpdateTime", updateTime);
- //query current time
- CSimpleStringA newTime = GetCurrentDate();
- runInfoParam.UpdateTime = newTime;
- runInfoParam.LatestTime = latestTime;
- //当前日期大于文件中日期时,需要做全量更新
- if (updateTime.GetLength() <= 0
- || (updateTime.GetLength() > 0 && CompareTime(newTime, updateTime) > 0)
- || latestTime.GetLength() <= 0)
- {
- runInfoParam.IsFirstTimeQueryData = true;
- }
- }
- CSimpleStringA CCustMngrAuthFSM::GetCurrentDate()
- {
- time_t curTime = time(NULL);
- tm* p = localtime(&curTime);
- char cTime[100] = { 0 };
- #ifdef RVC_OS_WIN
- _snprintf_s(cTime, 100, "%d%02d%02d", p->tm_year + 1900, p->tm_mon + 1, p->tm_mday);
- #else
- snprintf(cTime, 100, "%d%02d%02d", p->tm_year + 1900, p->tm_mon + 1, p->tm_mday);
- #endif // RVC_OS_WIN
- CSimpleStringA curDate(cTime);
- return curDate;
- }
- ///**TODO(Gifur@9/23/2022): param */
- int CCustMngrAuthFSM::CompareTime(CSimpleStringA time1, CSimpleStringA time2)
- {
- if (time1.GetLength() > 0 && time2.GetLength() > 0)
- {
- int year1 = atoi((const char*)time1.SubString(0, 4));
- int month1 = atoi((const char*)time1.SubString(4, 2));
- int day1 = atoi((const char*)time1.SubString(6, 2));
- int year2 = atoi((const char*)time2.SubString(0, 4));
- int month2 = atoi((const char*)time2.SubString(4, 2));
- int day2 = atoi((const char*)time2.SubString(6, 2));
- int temp1 = year1 * 10000 + month1 * 100 + day1;
- int temp2 = year2 * 10000 + month2 * 100 + day2;
- if (temp1 > temp2)
- return 1;
- else if (temp1 < temp2)
- return -1;
- else
- return 0;
- }
- return 0;
- }
- /// <summary>
- /// receive fingerprint feature from branch server
- /// </summary>
- /// <param name="dataArray">out param</param>
- /// <param name="runInfoParam">in param</param>
- /// <returns></returns>
- ErrorCodeEnum CCustMngrAuthFSM::ReceiveDataFromServer(CAutoArray<CSimpleStringA>& dataArray, RunInfoParams runInfoParam)
- {
- LOG_FUNCTION();
- char currAgent[16];
- char branchID[16];
- memset(currAgent, 0, sizeof(currAgent));
- memset(branchID, 0, sizeof(currAgent));
- bool bResumeTrans = true;
- ErrorCodeEnum errCode = Error_Unexpect;
- while (bResumeTrans)
- {
- if (runInfoParam.IsFirstTimeQueryData)
- m_pConnection->SendFeatReq(currAgent, branchID);
- else
- m_pConnection->SendFeatReq(currAgent, branchID, runInfoParam.LatestTime.GetData());
-
- ResetEvent(m_pConnection->m_hPkgAnswer);
-
- DWORD dw = WaitForSingleObject(m_pConnection->m_hPkgAnswer, 20000); //10->20 20200430@liuwentao
- switch (dw)
- {
- case WAIT_FAILED:
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("WAIT_FAILED!");
- break;
- case WAIT_TIMEOUT:
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("WAIT_TIMEOUT");
- case WAIT_OBJECT_0:
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("WAIT_OBJECT_0");
- break;
- }
- ResetEvent(m_pConnection->m_hPkgAnswer);
- if (m_pConnection->m_reply == NULL)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("m_reply still null after m_hPkgAnswer handled");
- break;
- }
- if (m_pConnection->m_GetErrMsg)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("get error message, check dbg log");
- break;
- }
- if (m_pConnection->m_reply->ResultCode == 2)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("remote server uninitialized yet, unable to excute query");
- break;
- }
- else {
- if (m_pConnection->m_reply->ResultCode == 0)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("All package downloaded from branch server.");
- bResumeTrans = false;
- errCode = Error_Succeed;
- }
- memcpy(currAgent, m_pConnection->m_reply->CurrentAgent, 16);
- memcpy(branchID, m_pConnection->m_reply->BranchID, 16);
- CSimpleStringA jbuf(m_pConnection->m_reply->Data, m_pConnection->m_jsonLen);
- dataArray.Append(&jbuf, 0, 1);
- }
- }
- if (bResumeTrans)
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("some errors happened, check the related log");
- if (dataArray.GetCount() <= 0)
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("query no data from branchServer.");
- return errCode;
- }
- /// <summary>
- /// backup runinfo file, in case some error occurs when process data
- /// </summary>
- /// <param name="runInfoParam">input/output param</param>
- /// <param name="spConfig">input param</param>
- /// <returns></returns>
- ErrorCodeEnum CCustMngrAuthFSM::BackupBeforeWriteData(RunInfoParams& runInfoParam, CSmartPointer<IConfigInfo>& spConfig)
- {
- LOG_FUNCTION();
- ErrorCodeEnum errCode = Error_Succeed;
- runInfoParam.SrcFile = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR RUNINFOFILE
- , m_RunInfoPath.GetData());
- runInfoParam.BackupFile = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "runcfg" SPLIT_SLASH_STR RUNINFOFILE_BAK
- , m_RunInfoPath.GetData());
- EnterCriticalSection(&m_cs);
- if (!BackupFile(runInfoParam.SrcFile, runInfoParam.BackupFile))
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Backup runinfo file failed.");
- if (runInfoParam.IsFirstTimeQueryData)
- {
- //首次更新,需清除数据,全量写入,并更新时间
- ofstream fileOut((const char*)runInfoParam.SrcFile, ios::trunc);
- fileOut.close();
- }
- errCode = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfig);
- if (errCode != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("error: open runcfg failed with errCode(%s)", SpStrError(errCode));
- BackupFile(runInfoParam.BackupFile, runInfoParam.SrcFile);// if backup fail, recover
- LeaveCriticalSection(&m_cs);
- }
- spConfig->WriteConfigValue("UpdateTime", "UpdateTime", runInfoParam.UpdateTime.GetData());
- if (runInfoParam.IsFirstTimeQueryData)
- {
- spConfig->WriteConfigValue("LatestTime", "LatestTime", "");
- }
- return errCode;
- }
- bool CCustMngrAuthFSM::BackupFile(CSimpleStringA srcFile, CSimpleStringA dstFile)
- {
- if (!ExistsFile(srcFile.GetData()))
- return true;
- int result = fileutil_copy_file(dstFile.GetData(), srcFile.GetData());
- return (result == 0) ? true : false;
- }
- /// <summary>
- /// write data into local file and memory
- /// </summary>
- /// <param name="runInfoParam">input/output param</param>
- /// <param name="dataArray">input param</param>
- /// <param name="spConfig">input param</param>
- /// <returns></returns>
- ErrorCodeEnum CCustMngrAuthFSM::WriteData(RunInfoParams& runInfoParam
- , CAutoArray<CSimpleStringA> dataArray
- , CSmartPointer<IConfigInfo>& spConfig)
- {
- ErrorCodeEnum errCode = Error_Unexpect;
- TempFeatureData tmpFeatureData;
- tmpFeatureData.MaxUpdateTime = runInfoParam.LatestTime;
- bool bExitLoop = false;
- for (int transTime = 0; transTime < dataArray.GetCount(); ++transTime)
- {
- Json::Value root;
- Json::Reader reader;
- //only 3-4 data, cause the limit of transfer amount
- CSimpleStringA transBuffer = dataArray[transTime];
- if (reader.parse(transBuffer.GetData(), root))
- {
- for (int i = 0; i < (int)root.size(); ++i)
- {
- JsonParams jsonParam;
- jsonParam.Root = root;
- jsonParam.Index = i;
- errCode = ProcessFeatureData(jsonParam, tmpFeatureData, runInfoParam, spConfig);
- if (Error_Succeed != errCode)
- {
- bExitLoop = true;
- break;
- }
- }
- if (bExitLoop)
- break;
- }else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("fail to parse transArray[%d]!", transTime);
- LeaveCriticalSection(&m_cs);
- bExitLoop = true;
- break;
- }
- }
- if (bExitLoop)
- return Error_Unexpect;
- if (tmpFeatureData.MaxUpdateTime.GetLength() > 0)
- {
- spConfig->WriteConfigValue("LatestTime", "LatestTime"
- , tmpFeatureData.MaxUpdateTime.GetData());
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("updateNum=%d", tmpFeatureData.tmpFeatureMap.size());
- UpdateDataIntoMemory(tmpFeatureData.tmpFeatureMap, runInfoParam.IsFirstTimeQueryData);
- LeaveCriticalSection(&m_cs);
- return Error_Succeed;
- }
- /// <summary>
- /// process feature data
- /// </summary>
- /// <param name="jsonParam"></param>
- /// <param name="tmpFeatureData"></param>
- /// <param name="runinfoParam"></param>
- /// <param name="spConfig"></param>
- /// <returns></returns>
- ErrorCodeEnum CCustMngrAuthFSM::ProcessFeatureData(JsonParams& jsonParam, TempFeatureData& tmpFeatureData
- , RunInfoParams runinfoParam, CSmartPointer<IConfigInfo>& spConfig)
- {
- ErrorCodeEnum errCode = Error_Succeed;
- FeatureData* fd = new FeatureData();
- fd->FingerIDArray.Init(FINGER_NUM);
- fd->FingerIDLenArray.Init(FINGER_NUM);
- char FingerID[20];//runinfo file is named "FingerID"
- char fingerId[20];//branchserver is named "fingerId" , history bug
- for (int fingerIndex = 0; fingerIndex < FINGER_NUM; ++fingerIndex)
- {
- ZeroMemory(FingerID, sizeof(FingerID));
- ZeroMemory(fingerId, sizeof(fingerId));
- #ifdef RVC_OS_WIN
- _snprintf_s(FingerID, 10, "FingerID%d", fingerIndex + 1);
- _snprintf_s(fingerId, 10, "fingerId%d", fingerIndex + 1);
- #else
- snprintf(FingerID, 10, "FingerID%d", fingerIndex + 1);
- snprintf(fingerId, 10, "fingerId%d", fingerIndex + 1);
- #endif // RVC_OS_WIN
- jsonParam.FingerInfo[FingerID] = jsonParam.Root[jsonParam.Index][fingerId].asCString();
- fd->FingerIDArray[fingerIndex] = CSimpleStringA(jsonParam.Root[jsonParam.Index][fingerId].asCString());
- fd->FingerIDLenArray[fingerIndex] = fd->FingerIDArray[fingerIndex].GetLength();
- }
- CSimpleStringA customerID = CSimpleStringA(jsonParam.Root[jsonParam.Index]["customerID"].asCString());
- if (tmpFeatureData.tmpFeatureMap.find(customerID) == tmpFeatureData.tmpFeatureMap.end())
- {
- // if not exist , insert directly
- tmpFeatureData.tmpFeatureMap[customerID] = fd;
- }else {
- auto tempFD = tmpFeatureData.tmpFeatureMap[customerID];
- tmpFeatureData.tmpFeatureMap[customerID] = fd;
- if (tempFD)
- {
- delete tempFD;
- tempFD = NULL;
- }
- }
- CSimpleStringA tempMaxUpdateTime = CSimpleStringA(jsonParam.Root[jsonParam.Index]["updateTime"].asCString());
- tmpFeatureData.MaxUpdateTime = GetMaxTime(tmpFeatureData.MaxUpdateTime, tempMaxUpdateTime);
- int fingerDataState = jsonParam.Root[jsonParam.Index]["state"].asCString()[0] - '0';
- if (fingerDataState == 0)
- {
- Json::FastWriter writer;
- CSimpleStringA jsonFingerStr(writer.write(jsonParam.FingerInfo).c_str());
- int jlen = jsonFingerStr.GetLength() - 1;
- char* jstr = new char[jlen + 1];
- memcpy(jstr, jsonFingerStr.GetData(), jlen);
- jstr[jlen] = '\0'; //in case no \n in the end
- errCode = spConfig->WriteConfigValue(m_FingerSection.GetData(), customerID.GetData(), jstr);
- delete[] jstr;
- if (errCode != Error_Succeed)
- {
- BackupFile(runinfoParam.BackupFile, runinfoParam.SrcFile);
- LeaveCriticalSection(&m_cs);
- errCode = Error_Unexpect;
- }
- }else if (fingerDataState == 2)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("state(2): customer %s is currently unavailable.", customerID.GetData());
- spConfig->WriteConfigValue((const char*)m_FingerSection, customerID.GetData(), "");
- }else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("unexpected customer(%s)'s state is either 0 or 2", customerID.GetData());
- }
- return errCode;
- }
- CSimpleStringA CCustMngrAuthFSM::GetMaxTime(CSimpleStringA maxTime, CSimpleStringA tempTime)
- {
- if (tempTime.GetLength() <= 0)
- return maxTime;
- if (maxTime.GetLength() <= 0)
- {
- maxTime = tempTime;
- }
- else {
- int compareResult = CompareUpdateTime((const char*)maxTime, (const char*)tempTime);
- if (compareResult == 0)
- {
- maxTime = tempTime;
- }
- }
- return maxTime;
- }
- int CCustMngrAuthFSM::CompareUpdateTime(const char* time1, const char* time2)
- {
- int year1, month1, day1, hour1, minute1, second1;
- int year2, month2, day2, hour2, minute2, second2;
- sscanf(time1, "%d-%d-%d %d:%d:%d", &year1, &month1, &day1, &hour1, &minute1, &second1);
- sscanf(time2, "%d-%d-%d %d:%d:%d", &year2, &month2, &day2, &hour2, &minute2, &second2);
- int tm1 = year1 * 10000 + month1 * 100 + day1;
- int tm2 = year2 * 10000 + month2 * 100 + day2;
- if (tm1 != tm2)
- return (tm1 > tm2) ? 1 : 0;
- tm1 = hour1 * 3600 + minute1 * 60 + second1;
- tm2 = hour2 * 3600 + minute2 * 60 + second2;
- if (tm1 != tm2)
- return (tm1 > tm2) ? 1 : 0;
- return 2;
- }
- /// <summary>
- /// write data into memory when update fingerprint feature
- /// </summary>
- /// <param name="tempFeature"></param>
- /// <param name="bIsFirstTimeQueryData"></param>
- void CCustMngrAuthFSM::UpdateDataIntoMemory(map<CSimpleStringA, FeatureData*> tempFeature, bool bIsFirstTimeQueryData)
- {
- if (!bIsFirstTimeQueryData)
- {
- for (auto it = tempFeature.begin(); it != tempFeature.end(); ++it) {
- if (m_featureData.find(it->first) == m_featureData.end()) {//if not exist,insert immediately
- m_featureData[it->first] = it->second;
- }
- else {//if exist already, release memory first, then insert
- auto tempFD = m_featureData[it->first];
- m_featureData[it->first] = it->second;
- if (tempFD != NULL) { delete tempFD; tempFD = NULL; }
- }
- }
- }else {
- for (auto iter = m_featureData.begin(); iter != m_featureData.end();) {
- auto fd = iter->second;
- if (fd) { delete fd; fd = NULL; m_featureData.erase(iter++); }
- }
- m_featureData.insert(tempFeature.begin(), tempFeature.end());
- }
- }
- #pragma endregion
- #pragma region Registe process
- ErrorCodeEnum CCustMngrAuthFSM::CollectFingerPrint(SpReqAnsContext<CustMngrAuthService_CollectFingerPrint_Req, CustMngrAuthService_CollectFingerPrint_Ans>::Pointer ctx, DWORD& dwUserErrCode)
- {
- LOG_FUNCTION();
- LogWarn(Severity_Low, Error_Unexpect, LOG_ERR_CUSTMNGRAUTH_INVOKE_GETIMAGE, "web invoke CollectFingerPrint");
- ErrorCodeEnum errCode = ConnectFingerPrintEntity();
- if (errCode != Error_Succeed)
- return errCode;
- errCode = CollectProcess(ctx, dwUserErrCode);
- if (errCode == Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Register FingerPrint successfully.");
- return Error_Succeed;
- }
- else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Register FingerPrint failed! %s", SpStrError(errCode));
- return errCode;
- }
- }
- ErrorCodeEnum CCustMngrAuthFSM::CollectFingerPrintInfo(SpReqAnsContext<CustMngrAuthService_CollectFingerPrintInfo_Req, CustMngrAuthService_CollectFingerPrintInfo_Ans>::Pointer ctx, DWORD& dwUserErrCode)
- {
- LOG_FUNCTION();
- if (ctx == NULL || !(ctx->Req.FingerId > 0 && ctx->Req.FingerId < 10))
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("CollectFingerPrintInfo, Invalid inParam, FingerId:%d", ctx->Req.FingerId);
- return Error_Param;
- }
- CSimpleStringA tmpParam = CSimpleStringA::Format("web invoke CollectFingerPrintInfo with inParam FingerId:%d", ctx->Req.FingerId);
- LogWarn(Severity_Low, Error_Unexpect, LOG_ERR_CUSTMNGRAUTH_INVOKE_CollectFingerPrintInfo, "web invoke CollectFingerPrintInfo");
- ErrorCodeEnum errCode = ConnectFingerPrintEntity();
- if (errCode != Error_Succeed)
- return errCode;
- CSimpleStringA depPath(true);
- m_pEntity->GetFunction()->GetPath("Dep", depPath);
- FingerPrintService_GetFingerPrint_Req GetFingerReq;
- FingerPrintService_GetFingerPrint_Ans GetFingerAns;
- GetFingerReq.times = ctx->Req.FingerId;
- if (m_pFingerPrint == NULL || m_pFingerPrint->QuerySessionClosed())
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("m_pFingerPrint is NULL or connection closed.");
- return Error_Hardware;
- }
- errCode = m_pFingerPrint->GetFingerPrint(GetFingerReq, GetFingerAns, 30000, dwUserErrCode);
- if (errCode == Error_NotInit)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("FingerPrintEntity not ready or failed.");
- return Error_DevNotAvailable;
- }
- if (errCode == Error_Succeed)
- {
- switch (GetFingerAns.reserved1[0])
- {
- case 1:
- errCode = Error_Succeed;
- break;
- case 2:
- errCode = Error_TimeOut;
- break;
- case 3:
- errCode = Error_Cancel;
- break;
- default:
- errCode = Error_Unexpect;
- break;
- }
- if (errCode == Error_Succeed)
- {
- ctx->Ans.feature = GetFingerAns.feature;
- CBlob data;
- CSimpleStringA imgFullPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", depPath.GetData(), GetFingerAns.imageName.GetData());
- ErrorCodeEnum imgErrCode = GetImgBlob(data, imgFullPath);
- if (imgErrCode != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Failed to load image(%s)", imgFullPath.GetData());
- return Error_Unexpect;
- }
- ctx->Ans.fingerImg = data;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("CollectFingerPrintInfo return success.");
- }
- }
- else
- errCode = Error_Unexpect;
- return errCode;
- }
- ErrorCodeEnum CCustMngrAuthFSM::GenerateTemplate(SpReqAnsContext<CustMngrAuthService_GenerateTemplate_Req, CustMngrAuthService_GenerateTemplate_Ans>::Pointer ctx, DWORD& dwUserErrCode)
- {
- LOG_FUNCTION();
- LogWarn(Severity_Low, Error_Unexpect, LOG_ERR_CUSTMNGRAUTH_INVOKE_GenerateTemplate, "web invoke GenerateTemplate");
- int fingerNum = ctx->Req.FingerIDList.GetCount();
- if (fingerNum != IMAGE_NUM)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GenerateTemplate, Invalid inParam, fingerNum:%d", fingerNum);
- return Error_Param;
- }
- ErrorCodeEnum errCode;
- m_pFingerPrint = new FingerPrintService_ClientBase(m_pEntity);
- errCode = m_pFingerPrint->Connect();
- if (errCode != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("ERROR: connect to fingerprint entity failed while GenerateTemplate: %s", SpStrError(errCode));
- m_pFingerPrint->SafeDelete();
- m_pFingerPrint = NULL;
- return Error_DevNotAvailable; //TODO::give one other errCode
- }
- CSimpleStringA depPath(true);
- m_pEntity->GetFunction()->GetPath("Dep", depPath);
- FingerPrintService_GenerateTemplate_Req generateReq;
- FingerPrintService_GenerateTemplate_Ans generateAns;
- generateReq.FingerIDList.Init(IMAGE_NUM);
- for (int i = 0; i < generateReq.FingerIDList.GetCount(); ++i)
- {
- generateReq.FingerIDList[i] = ctx->Req.FingerIDList[i];
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("fingerIDList = %d", generateReq.FingerIDList[i]);
- }
- if (m_pFingerPrint == NULL || m_pFingerPrint->QuerySessionClosed())
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("m_pFingerPrint is NULL or connection closed.");
- return Error_DevNotAvailable;
- }
- errCode = m_pFingerPrint->GenerateTemplate(generateReq, generateAns, 20000, dwUserErrCode);
- if (errCode == Error_NotInit)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("FingerPrintEntity not ready or failed.");
- return Error_DevNotAvailable;
- }
- if (errCode == Error_Succeed)
- {
- ctx->Ans.templateFeature = generateAns.templateFeature;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("GenerateTemplate return success.");
- }
- else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("Invoke GenerateTemplate returned %d", errCode);
- errCode = Error_Unexpect;
- }
- return errCode;
- }
- ErrorCodeEnum CCustMngrAuthFSM::CollectFingerPrintEx(SpReqAnsContext<CustMngrAuthService_CollectFingerPrintEx_Req, CustMngrAuthService_CollectFingerPrintEx_Ans>::Pointer ctx, DWORD& dwUserErrCode)
- {
- LOG_FUNCTION();
- LogWarn(Severity_Low, Error_Unexpect, LOG_ERR_CUSTMNGRAUTH_INVOKE_GETIMAGEEx, "web invoke CollectFingerPrintEx");
- ErrorCodeEnum errCode = ConnectFingerPrintEntity();
- if (errCode != Error_Succeed)
- return errCode;
- errCode = CollectProcessEx(ctx, dwUserErrCode);
- if (errCode == Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Register FingerPrint successfully.");
- return Error_Succeed;
- }
- else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Register FingerPrint failed: %s !", SpStrError(errCode));
- return errCode;
- }
- }
- ErrorCodeEnum CCustMngrAuthFSM::CollectProcess(SpReqAnsContext<CustMngrAuthService_CollectFingerPrint_Req, CustMngrAuthService_CollectFingerPrint_Ans>::Pointer& ctx, DWORD& dwUserErrCode)
- {
- ErrorCodeEnum errCode = Error_Succeed;
- vector<CSimpleStringA> imgPaths;
- CSimpleStringA depPath(true);
- m_pEntity->GetFunction()->GetPath("Dep", depPath);
- ctx->Ans.FingerImgs.Init(COLLECT_TIMES);
- for (int i = 0; i < COLLECT_TIMES; ++i)
- {
- if (i) SLEEP(2000);
- if (m_pFingerPrint == NULL || m_pFingerPrint->QuerySessionClosed())
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("m_pFingerPrint is NULL or connection closed.");
- return Error_NoTarget;
- }
- BroadcastPressFinger(i + 1, true);//press finger
- FingerPrintService_GetImageAndFeature_Req collecetReq;
- FingerPrintService_GetImageAndFeature_Ans collecetAns;
- collecetReq.times = i + 1;//the num from 1 start , 1/2/3
- errCode = m_pFingerPrint->GetImageAndFeature(collecetReq, collecetAns, 16000, dwUserErrCode);//fingerprint entity loop duration is 15s
- if (errCode == Error_Succeed)
- {
- BroadcastPressFinger(i + 1, false);//lift finger
- CBlob data;
- CSimpleStringA imgFullPath(true);
- imgFullPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s"
- , depPath.GetData(), collecetAns.imageName.GetData());
- errCode = GetImgBlob(data, imgFullPath);
- imgPaths.push_back(imgFullPath);
- if (errCode != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_USER)("Failed to load finger image, %s", imgFullPath.GetData());
- errCode = Error_Unexpect;
- break;
- }
- switch (i)
- {
- case 0:
- ctx->Ans.FingerImg1 = data;
- break;
- case 1:
- ctx->Ans.FingerImg2 = data;
- break;
- case 2:
- ctx->Ans.FingerImg3 = data;
- break;
- }
- ctx->Ans.FingerImgs[i] = data;
- if (i == (COLLECT_TIMES - 1)) {
- ctx->Ans.feature = collecetAns.feature;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("feature = %s", ctx->Ans.feature.GetData());
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("invoke GetImageAndFeature failed in %dth time, errCode(%s)", i + 1, SpStrError(errCode));
- break;
- }
- }
- for (size_t i = 0; i < imgPaths.size(); ++i)
- {
- if (ExistsFileA(imgPaths[i]))
- RemoveFileA(imgPaths[i]);
- }
- return errCode;
- }
- ErrorCodeEnum CCustMngrAuthFSM::CollectProcessEx(SpReqAnsContext<CustMngrAuthService_CollectFingerPrintEx_Req, CustMngrAuthService_CollectFingerPrintEx_Ans>::Pointer& ctx, DWORD& dwUserErrCode)
- {
- ErrorCodeEnum errCode = Error_Succeed;
- CSimpleStringA depPath(true);
- m_pEntity->GetFunction()->GetPath("Dep", depPath);
- ctx->Ans.FingerImgs.Init(COLLECT_TIMES);
- FingerPrintService_GetImageAndFeatureEx_Req collectExReq;
- FingerPrintService_GetImageAndFeatureEx_Ans collectExAns;
- collectExReq.times = ctx->Req.FingerId;
- if (m_pFingerPrint == NULL || m_pFingerPrint->QuerySessionClosed())
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("m_pFingerPrint is NULL or connection closed.");
- return Error_NoTarget;
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Start %dth scan fingerprint", collectExReq.times);
- errCode = m_pFingerPrint->GetImageAndFeatureEx(collectExReq, collectExAns, 30000, dwUserErrCode);//fingerprint entity loop duration is 15s
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("reserverd1[0] = %d", collectExAns.reserved1[0]);
- if (errCode == Error_NotExist) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("cannot find finger img in dep!");
- return Error_NotExist;
- }
- if (errCode == Error_Succeed && collectExAns.reserved1[0] == 3) {
- return Error_Cancel;
- }
- if (errCode == Error_Succeed && collectExAns.reserved1[0] == 2) {
- return Error_TimeOut;
- }
- CBlob data;
- CSimpleStringA imgFullPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s"
- , depPath.GetData(), collectExAns.imageName.GetData());
- ErrorCodeEnum imgErrCode = GetImgBlob(data, imgFullPath);
- if (imgErrCode != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("Failed to load image(%s)", imgFullPath.GetData());
- return Error_NotExist;
- }
- CSimpleStringA imageName(true);
- CSimpleStringA imgPrefix = "finger";
- CSimpleStringA imgSuffix = ".bmp";
- switch (ctx->Req.FingerId)
- {
- case 1:
- ctx->Ans.FingerImg1 = data;
- break;
- case 2:
- ctx->Ans.FingerImg2 = data;
- break;
- case 3:
- ctx->Ans.FingerImg3 = data;
- for (size_t i = 0; i < 10; ++i)
- {
- imageName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s%d%s", depPath.GetData(), imgPrefix.GetData(), i, imgSuffix.GetData());
- if (ExistsFileA(imageName))
- RemoveFileA(imageName);
- }
- imageName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s%s", depPath.GetData(), imgPrefix.GetData(), imgSuffix.GetData());
- if (ExistsFileA(imageName))
- RemoveFileA(imageName);
- break;
- default:
- break;
- }
- if (errCode == Error_Succeed && collectExAns.reserved1[0] == 1) {
- if (ctx->Req.FingerId == COLLECT_TIMES)
- ctx->Ans.feature = collectExAns.feature;
- }
- else if(errCode == Error_NotInit){
- errCode = Error_DevNotAvailable;
- }else {
- errCode = Error_Unexpect;
- }
- if (errCode == Error_Succeed) {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Register FingerPrint successfully.");
- }
- else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("Register FingerPrint failed! %s", SpStrError(errCode));
- }
- return errCode;
- }
- void CCustMngrAuthFSM::BroadcastPressFinger(int times, bool bPressFinger)
- {
- if (bPressFinger)
- {
- PressFinger pfEvt;//
- pfEvt.FingerNo = 1;//maybe no use,control by @zhuyi
- pfEvt.Times = times;
- SpSendBroadcast(m_pEntity->GetFunction(), SP_MSG_OF(PressFinger)
- , SP_MSG_SIG_OF(PressFinger), pfEvt);
- }
- else {
- LiftFinger lfEvt;
- lfEvt.FingerNo = 1;
- lfEvt.Times = times;
- SpSendBroadcast(m_pEntity->GetFunction(), SP_MSG_OF(LiftFinger)
- , SP_MSG_SIG_OF(LiftFinger), lfEvt);
- }
- }
- ErrorCodeEnum CCustMngrAuthFSM::GetImgBlob(CBlob& data, CSimpleStringA imgPath)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("image full path: %s", imgPath.GetData());
- FILE* fp = fopen(imgPath, "rb");
- if (fp)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("fopen succeed.");
- fseek(fp, 0, SEEK_END);
- long flen = ftell(fp);
- fseek(fp, 0, SEEK_SET);
- data.Alloc(flen);
- fread(data.m_pData, 1, flen, fp);
- fclose(fp);
- return Error_Succeed;
- }
- else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("fopen %s failed!", imgPath.GetData());
- return Error_IO;
- }
- }
- #pragma endregion
- #pragma region Save fingerprint process
- ErrorCodeEnum CCustMngrAuthFSM::SaveFingerPrint(SpReqAnsContext<CustMngrAuthService_SaveFingerPrint_Req, CustMngrAuthService_SaveFingerPrint_Ans>::Pointer ctx)
- {
- LOG_FUNCTION();
- EnterCriticalSection(&m_cs);
- CSmartPointer<IConfigInfo> spConfig;
- Json::FastWriter writer;
- ErrorCodeEnum errCode;
- errCode = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfig);
- if (errCode != Error_Succeed) {
- LogError(Severity_High, Error_DevLoadFileFailed
- , LOG_ERR_CUSTMNGRAUTH_OPEN_RUNINFO_FAILED_SAVEFINGERPRINT
- , "open runinfo file failed while save data to local.");
- LeaveCriticalSection(&m_cs);
- return Error_Unexpect;
- }
- if (ctx->Req.FPFeatureList == nullptr)
- return Error_Param;
- int fingerIDNum = ctx->Req.FingerIdList.GetCount();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("FingerIDNum=%d", fingerIDNum);
- FeatureData* fd = new FeatureData();
- fd->FingerIDArray.Init(fingerIDNum);
- fd->FingerIDLenArray.Init(fingerIDNum);
- char fingerID[20];
- Json::Value fingerInfo;
- for (int i = 0; i < fingerIDNum; ++i)
- {
- memset(fingerID, 0, sizeof(fingerID));
- #ifdef RVC_OS_WIN
- _snprintf_s(fingerID, 10, "FingerID%d", ctx->Req.FingerIdList[i]);
- #else
- snprintf(fingerID, 10, "FingerID%d", ctx->Req.FingerIdList[i]);
- #endif // RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("writing %s", fingerID);
- fingerInfo[fingerID] = ctx->Req.FPFeatureList[i].GetData();
- fd->FingerIDArray[i] = ctx->Req.FPFeatureList[i];
- fd->FingerIDLenArray[i] = fd->FingerIDArray[i].GetLength();
- }
- if (m_featureData.find(ctx->Req.CustomerID) == m_featureData.end())
- {
- //not exist, insert directly
- m_featureData[ctx->Req.CustomerID] = fd;
- }
- else {
- auto tempFD = m_featureData[ctx->Req.CustomerID];
- m_featureData[ctx->Req.CustomerID] = fd;
- if (tempFD) { delete tempFD; tempFD = NULL; }
- }
- errCode = spConfig->WriteConfigValue(m_FingerSection.GetData()
- , ctx->Req.CustomerID.GetData()
- , writer.write(fingerInfo).c_str());
- if (errCode != Error_Succeed)
- {
- LogError(Severity_High, Error_DevLoadFileFailed
- , LOG_ERR_CUSTMNGRAUTH_REGISTER_WRITE_RUNINFO_FAILED
- , "write data into runinfo failed when commit.");
- LeaveCriticalSection(&m_cs);
- return Error_Unexpect;
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("write data into runinfo success when commit.");
- LeaveCriticalSection(&m_cs);
- return errCode;
- }
- #pragma endregion
- #pragma region authorize process
- ErrorCodeEnum CCustMngrAuthFSM::MatchFingerPrint(SpReqAnsContext<CustMngrAuthService_StartAuthorize_Req, CustMngrAuthService_StartAuthorize_Ans>::Pointer ctx, bool& bStopAuthorize)
- {
- LOG_FUNCTION();
- LogWarn(Severity_Low, Error_Unexpect, LOG_ERR_CUSTMNGRAUTH_INVOKE_MATCH, "web invoke MatchFingerPrint");
- ErrorCodeEnum errCode = ConnectFingerPrintEntity();
- if (errCode != Error_Succeed)
- return errCode;
- MatchParams* matchParam = new MatchParams();
- matchParam->sTotalNumOfTemplate = 0;
- errCode = PrepareDataBeforeMatch(matchParam);
- if (errCode != Error_Succeed)
- return errCode;
- errCode = MatchProcess(matchParam, bStopAuthorize);
- return errCode;
- }
- ErrorCodeEnum CCustMngrAuthFSM::ConnectFingerPrintEntity()
- {
- ErrorCodeEnum errCode = Error_Succeed;
- m_pFingerPrint = new FingerPrintService_ClientBase(m_pEntity);
- errCode = m_pFingerPrint->Connect();
- if (errCode != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("ERROR: connect to fingerprint entity failed! %s", SpStrError(errCode));
- m_pFingerPrint->SafeDelete();
- errCode = Error_NoTarget; //TODO::give one other errCode
- }
- return errCode;
- }
- ErrorCodeEnum CCustMngrAuthFSM::PrepareDataBeforeMatch(MatchParams* matchParam)
- {
- EnterCriticalSection(&m_cs);
- CAutoArray<CSimpleStringA> tempFeatureArray;
- CAutoArray<int> tempFeatureLenArray;
- int totalCustomerID = m_featureData.size();
- int totalTemplate = totalCustomerID * FINGER_NUM;
- tempFeatureArray.Init(totalTemplate);
- tempFeatureLenArray.Init(totalTemplate);
- if (totalCustomerID <= 0)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("No FingerPrint data in local file or read local file failed.");
- LeaveCriticalSection(&m_cs);
- if (matchParam != NULL)
- delete matchParam;
- return Error_NoTarget;
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("begin copy feature to reqParams");
- for (auto it = m_featureData.begin(); it != m_featureData.end(); ++it)
- {
- TemplateInfo ti;
- memset(&ti, 0, sizeof(ti));
- ti.CustomerID = it->first;
- ti.TemplateNum = 0;
- for (int index = 0; index < FINGER_NUM; ++index)
- {
- if (index >= it->second->FingerIDArray.GetCount()) //旧版本可能只有2个
- break;
- if (it->second->FingerIDArray[index].GetLength() <= 0)
- continue;
- tempFeatureArray[matchParam->sTotalNumOfTemplate] = it->second->FingerIDArray[index];
- tempFeatureLenArray[matchParam->sTotalNumOfTemplate] = it->second->FingerIDLenArray[index];
- ti.TemplateNum = ti.TemplateNum + 1;
- ++matchParam->sTotalNumOfTemplate;
- }
- if (ti.TemplateNum > 0)
- matchParam->sFingerCount.push_back(ti);
- }
- LeaveCriticalSection(&m_cs);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("num of template not empty:%d", matchParam->sTotalNumOfTemplate);
- matchParam->sMatchReq.templateNum = matchParam->sTotalNumOfTemplate;
- matchParam->sMatchReq.templates.Init(matchParam->sTotalNumOfTemplate);
- matchParam->sMatchReq.templateLen.Init(matchParam->sTotalNumOfTemplate);
- for (int i = 0; i < matchParam->sTotalNumOfTemplate; ++i)
- {
- matchParam->sMatchReq.templates[i] = tempFeatureArray[i];
- matchParam->sMatchReq.templateLen[i] = tempFeatureLenArray[i];
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("end copy feature to reqParams");
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("templateNum: %d", matchParam->sMatchReq.templateNum);
- return Error_Succeed;
- }
- ErrorCodeEnum CCustMngrAuthFSM::MatchProcess(MatchParams* matchParam, bool& bStopAuthorize)
- {
- ErrorCodeEnum errCode = Error_Succeed;
- while (true)
- {
- if (m_pFingerPrint == NULL || m_pFingerPrint->QuerySessionClosed())
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("m_pFingerPrint is NULL or connection closed.");
- return Error_Unexpect;
- }
- //fingerprint entity may not return immediately
- SLEEP(100);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("begin next invoke match.");
- errCode = m_pFingerPrint->Match(matchParam->sMatchReq, matchParam->sMatchAns, 20000);
- if (m_bCancelAuthorize || errCode == Error_Cancel)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("cancel authorize task.");
- bStopAuthorize = true;
- m_bCancelAuthorize = false;
- if (m_bAuthorizeTimeout)
- {
- m_bAuthorizeTimeout = false;
- return Error_TimeOut;
- }
- return Error_Cancel;
- }
- else if (errCode == Error_Unexpect || errCode == Error_TimeOut)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("invoke match error with errCode(%s)", SpStrError(errCode));
- BroadcastGetFinger(2);
- }
- else if (errCode == Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("invoke match success, start analyze result.");
- errCode = AnalyzeMatchResult(matchParam, bStopAuthorize);
- if (errCode == Error_Succeed)
- return Error_Succeed; //continue if other errCode
- }
- else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("invole match error(%s), stop authorize", SpStrError(errCode));
- return Error_Unexpect;
- }
- }
- }
- void CCustMngrAuthFSM::BroadcastGetFinger(int status)
- {
- GetFinger evt;
- evt.Status = status;
- SpSendBroadcast(GetEntityBase()->GetFunction()
- , SP_MSG_OF(GetFinger), SP_MSG_SIG_OF(GetFinger)
- , evt);
- }
- ErrorCodeEnum CCustMngrAuthFSM::AnalyzeMatchResult(MatchParams* matchParam, bool& bStopAuthorize)
- {
- int resTemplateNum = matchParam->sMatchAns.result.GetCount();
- if (resTemplateNum != matchParam->sTotalNumOfTemplate)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("result templateNum(%d) is not equale to the Req's(%d)."
- , resTemplateNum, matchParam->sTotalNumOfTemplate);
- return Error_Unexpect;
- }
- std::vector<TemplateInfo>tmpFingerCountInfo(matchParam->sFingerCount);
- int matchIndex = -1; //matched CustomerID's index in array
- int matchCount = 0; //num of matched
- int fingerCountIndex = 0; //index of fingerCountInfo
- int FINGER_NUM = tmpFingerCountInfo[fingerCountIndex].TemplateNum;
- for (int i = 0; i < resTemplateNum; i += FINGER_NUM)
- {
- int oneCustMatchResult = 0;
- FINGER_NUM = tmpFingerCountInfo[fingerCountIndex].TemplateNum;
- for (int j = 0; j < FINGER_NUM; ++j)
- {
- oneCustMatchResult += matchParam->sMatchAns.result[i + j];
- }
- if (oneCustMatchResult > 0) //one customer has more than one match, just as one
- {
- matchCount++;
- matchIndex = fingerCountIndex;
- }
- if (matchCount > 1) //more than one customer's finger matched
- break;
- fingerCountIndex++;
- }
- int matchResult = matchCount;//0:no match; 1:just one match; 2: muti match
- switch (matchResult)
- {
- case 0:
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("MatchResult: 0| no match");
- BroadcastGetFinger(0);
- }
- break;
- case 1:
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("MatchResult: 1| one and only one match, authorize done.");
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Match Finger(CustomerID=%s)", (const char*)tmpFingerCountInfo[matchIndex].CustomerID);
- m_authCtx.eAuthByWhich = AuthByFngPrnt;
- m_authCtx.CustomerID = tmpFingerCountInfo[matchIndex].CustomerID;
- bStopAuthorize = true;
- return Error_Succeed;
- }
- break;
- case 2:
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("MatchResult: 2 | two and more matches. be alerted");
- BroadcastGetFinger(1);
- }
- break;
- default:break;
- }
- return Error_Unexpect;
- }
- ErrorCodeEnum CCustMngrAuthFSM::MatchFingerPrintEx(SpReqAnsContext<CustMngrAuthService_QueryAuthorInfo_Req, CustMngrAuthService_QueryAuthorInfo_Ans>::Pointer ctx, bool& bStopAuthorize, DWORD& dwUserErrCode)
- {
- LOG_FUNCTION();
- LogWarn(Severity_Low, Error_Unexpect, LOG_ERR_CUSTMNGRAUTH_INVOKE_MATCHEx, "web invoke MatchFingerPrintEx");
- ErrorCodeEnum errCode;
- m_pFingerPrint = new FingerPrintService_ClientBase(m_pEntity);
- errCode = m_pFingerPrint->Connect();
- if (errCode != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("ERROR: connect to fingerprint entity failed while match %s", SpStrError(errCode));
- m_pFingerPrint->SafeDelete();
- m_pFingerPrint = NULL;
- return Error_Hardware; //TODO::give one other errCode
- }
- CSimpleStringA depPath(true);
- m_pEntity->GetFunction()->GetPath("Dep", depPath);
- FingerPrintService_GetFingerPrint_Req GetFingerReq;
- FingerPrintService_GetFingerPrint_Ans GetFingerAns;
- GetFingerReq.times = 10;
- if (m_pFingerPrint == NULL || m_pFingerPrint->QuerySessionClosed())
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("m_pFingerPrint is NULL or connection closed.");
- return Error_Hardware;
- }
- errCode = m_pFingerPrint->GetFingerPrint(GetFingerReq, GetFingerAns, 30000, dwUserErrCode);
- if (errCode == Error_NotInit)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER)("FingerPrintEntity not ready or failed.");
- return Error_Hardware;
- }
- bStopAuthorize = true;
- if (m_bCancelAuthorize || GetFingerAns.reserved1[0] == 3) {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("GetFingerPrint is canceled while match.");
- m_bCancelAuthorize = false;
- if (m_bAuthorizeTimeout) {
- m_bAuthorizeTimeout = false;
- return Error_TimeOut;
- }
- return Error_Cancel;
- }
- if (errCode == Error_Succeed)
- {
- switch (GetFingerAns.reserved1[0])
- {
- case 1:
- errCode = Error_Succeed;
- break;
- case 2:
- errCode = Error_TimeOut;
- break;
- case 3:
- errCode = Error_Cancel;
- break;
- default:
- errCode = Error_Unexpect;
- break;
- }
- if (errCode == Error_Succeed)
- {
- m_authCtx.eAuthByWhich = AuthByFngPrnt;
- ctx->Ans.Feature = GetFingerAns.feature;
- CBlob data;
- CSimpleStringA imgFullPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", depPath.GetData(), GetFingerAns.imageName.GetData());
- ErrorCodeEnum imgErrCode = GetImgBlob(data, imgFullPath);
- if (imgErrCode != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Failed to load image(%s)", imgFullPath.GetData());
- return Error_Unexpect;
- }
- ctx->Ans.FingerImg = data;
- m_authCtx.Feature = ctx->Ans.Feature;
- m_authCtx.FingerImg = ctx->Ans.FingerImg;
- }
- }
- else
- errCode = Error_Unexpect;
- DeleteBmp(BmpImage);
- return errCode;
- }
- void CCustMngrAuthFSM::DeleteBmp(int type)
- {
- if ((type & BmpImage) == BmpImage)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("to delete fingerprint images...");
- CSimpleStringA imageName;
- DeleteFileIfExisted("finger.bmp");
- for (int i = 1; i <= 10; ++i) {
- imageName = CSimpleString::Format("finger%d.bmp", i);
- DeleteFileIfExisted(imageName.GetData());
- }
- }
- if ((type & TestImage) == TestImage)
- {
- DeleteFileIfExisted("testFinger.bmp");
- }
- }
- ErrorCodeEnum CCustMngrAuthFSM::DeleteFileIfExisted(const char* fileName)
- {
- if (strlen(fileName) == 0 || strchr(fileName, (int)'*') != NULL)
- {
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("Invalid or empty filename(%s)", fileName);
- return Error_Param;
- }
- CSimpleStringA strPath, strObjPath;
- ErrorCodeEnum errCode = m_pEntity->GetFunction()->GetPath("Dep", strPath);
- strObjPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s"
- , strPath.GetData(), fileName);
- if (ExistsFileA(strObjPath))
- {
- if (RemoveFileA(strObjPath))
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("DeleteFile(%s) success.", strObjPath.GetData());
- return Error_Succeed;
- }
- else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("DeleteFile(%s) failed LastError(%s).", strObjPath.GetData(), GetLastError());
- return Error_Unexpect;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("file %s not exist.", fileName);
- return Error_Succeed;
- }
- }
- #pragma endregion
|