123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710 |
- // DiosChannel.cpp : 定义控制台应用程序的入口点。
- //
- #include "stdafx.h"
- #include <Windows.h>
- #include <conio.h>
- #include <ctype.h>
- #include "cdi.h"
- #include "BusUnitClient.h"
- #include "LogicClient.h"
- #include "LocalConfig.h"
- #include "PacketAnalizer.h"
- #include "ConsoleThread.h"
- #include "AutoDmp.h"
- //#include "Vga_Demo.h"
- #include <chrono>
- #include "common_api.h"
- #include <set>
- inline std::string CurrentDateTime()
- {
- // 获取当前时间点
- auto now = std::chrono::system_clock::now();
- // 将时间长度转换为微秒数
- auto now_us = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch());
- // 再转成tm格式
- auto now_time_t = std::chrono::system_clock::to_time_t(now);
- auto now_tm = std::localtime(&now_time_t);
- // 可以直接输出到标准输出
- // std::cout << std::put_time(now_tm, "%Y-%m-%d %H:%M:%S.") << std::setfill('0') << std::setw(6) << now_us.count() % 1000000 << std::endl;
- // 格式化字符,年月日时分秒
- std::string now_time_str;
- char buf[64];
- std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", now_tm);
- now_time_str += buf;
- // 格式化微秒
- snprintf(buf, sizeof(buf), ".%06lld ", now_us.count() % 1000000);
- now_time_str += buf;
- //printf("%s\n", now_time_str.c_str());
- return now_time_str;
- }
- AutoDmp atdmp;
- //CommonLogicClient WheelClient;
- #define MAX_THREAD_TEST (1)
- DWORD ConsoleThreadCount = MAX_THREAD_TEST;
- ConsoleThread g_ConsoleThread[MAX_THREAD_TEST];
- //UI_Thread g_UIThread;
- //Vga_Demo g_VgaDemoThread;
- bool StartConsoleThreads(bool start)
- {
- bool ret = true;
- //return ret;//
- for (DWORD i = 0; i < ConsoleThreadCount; i++)
- {
- if (start)
- {
- g_ConsoleThread[i].SetName("ConsoleThread");
- ret &= (g_ConsoleThread[i]).StartThread();
- printf("start console Thread:%d!\n", i);
- }
- else
- {
- (g_ConsoleThread[i]).StopThread(100);
- }
- }
- return ret;
- }
- bool WINAPI ConsoleHandler(DWORD msgType)
- {
- if ((msgType == CTRL_CLOSE_EVENT) ||
- (msgType == CTRL_SHUTDOWN_EVENT))
- {
- printf("Close console window!\n");
- StartConsoleThreads(false);
- GetCommandDispathIF()->WaitExit(500, true);
- /* Note: The system gives you very limited time to exit in this condition */
- return true;
- }
- /*
- Other messages:
- CTRL_BREAK_EVENT Ctrl-Break pressed
- CTRL_LOGOFF_EVENT User log off
- CTRL_SHUTDOWN_EVENT System shutdown
- */
- return false;
- }
- std::set<string> g_arrWhiteDirectory;
- string procdir;
- void KeepParent(string dir)
- {
- if (dir == procdir)
- return;
- g_arrWhiteDirectory.insert(dir);
- string parent = GetFileDirectory(dir);
- if (parent == procdir || parent.length() <= 0)
- return;
- KeepParent(parent);
- }
- void CheckWhiteDir(ResDataObject & driverConf, string& driverPath, string& sdkPath)
- {
- if (driverConf.GetFirstOf("oemdriver") > 0)
- {
- driverPath = (const char*)driverConf["oemdriver"];
- driverPath = ReplaceSubString(driverPath, string("%ROOT%"), procdir);
- if (driverConf.GetFirstOf("SDKPath") > 0)
- {
- sdkPath = (const char*)driverConf["SDKPath"];
- if (sdkPath.length() > 0)
- {
- if (sdkPath[0] != '\\')
- sdkPath = procdir + "\\" + sdkPath;
- else
- sdkPath = procdir + sdkPath;
- if (sdkPath[sdkPath.length() - 1] == '\\')
- sdkPath.erase(sdkPath.length() - 1, 1);
- }
- }
- }
- else if (driverConf.GetFirstOf("driver") > 0)
- {
- //普通驱动
- driverPath = (const char*)driverConf["driver"];
- driverPath = ReplaceSubString(driverPath, string("%ROOT%"), procdir);
- }
- driverPath = GetFileDirectory(driverPath);
- g_arrWhiteDirectory.insert(driverPath);
- KeepParent(driverPath);
- cout<< endl << "Keep Driver White Path " << driverPath << endl;
- if (sdkPath.length() > 0)
- {
- bool isSub = false;
- string sdkPpath;
- sdkPpath = GetFileDirectory(sdkPath);
- if (sdkPpath.length() >= driverPath.length())
- {
- //if (sdkPath.substr(0, driverPath.length()) == driverPath)
- if(sdkPpath == driverPath)
- {
- //sdk目录在driver子目录
- isSub = true;
- }
- }
- if (!isSub)
- {
- g_arrWhiteDirectory.insert(sdkPath);
- KeepParent(sdkPath);
- cout << "Keep Driver S D K Path " << sdkPath << endl;
- }
- else
- {
- cout << "With Driver S D K Path " << sdkPath << endl;
- }
- }
- }
- /// <summary>
- /// 清理已安装Driver驱动目录,保留白名单驱动
- /// </summary>
- /// <param name="whitelist"></param>
- void CleanDriver(ResDataObject* whitelist)
- {
- procdir = GetProcessDirectory();
- ResDataObject fileList;
- GetSpecificDriverConfigFiles(fileList, false);
- for (int x = 0; x < fileList.size(); x++)
- {
- string filename = fileList.GetKey(x);
- bool bFind = false;
- //std::cout << "CleanDriver " << fileList.GetKey(x) << " white list " << whitelist->encode() << endl;
- for (int y = 0; y < whitelist->size(); y++)
- {
- string key = (*whitelist)[y];
- if (filename.find(key) != string::npos)
- {
- bFind = true;
- //
- }
- }
- ResDataObject driverConfFile;
- ResDataObject driverConf;
- string driverPath,sdkPath;
- if (driverConfFile.loadFile(filename.c_str()))
- {
- if (driverConfFile.GetFirstOf("CONFIGURATION") < 0)
- continue;
- driverConf = driverConfFile["CONFIGURATION"];
-
- }
- if (!bFind)
- {
- DeleteFile(filename.c_str());
- }
- else
- {
- CheckWhiteDir(driverConf, driverPath, sdkPath);
- }
- }
- }
- /// <summary>
- /// 校验驱动,不在列表的需要移除配置
- /// </summary>
- /// <param name="fileList">驱动配置文件列表in/out paht:bool </param>
- /// <param name="driverList">要保留的驱动目录out</param>
- /// <param name="oneDriver">当前要检查的驱动信息 in</param>
- /// <param name="driverType">驱动类型如Detector/SynBox等</param>
- /// <returns></returns>
- bool CheckInDriver(ResDataObject& fileList, ResDataObject& driverList, ResDataObject& oneDriver, const char* driverType)
- {
- string procdir = GetProcessDirectory();
- for (int x = 0; x < fileList.size(); x++)
- {
- ResDataObject driverConfFile;
- if (driverConfFile.loadFile(fileList.GetKey(x)))
- {
- ResDataObject driverConf;
- if (driverConfFile.GetFirstOf("CONFIGURATION") < 0)
- continue;
- driverConf = driverConfFile["CONFIGURATION"];
- if (driverConf.GetFirstOf("MajorID") < 0)
- continue;
- string MajorID = (const char*)driverConf["MajorID"];
- if (strcmp(driverType, MajorID.c_str()) != 0)
- {
- continue;
- }
- if (driverConf.GetFirstOf("VendorID") >= 0 && oneDriver.GetFirstOf("VendorID") >= 0)
- {
- if (driverConf.GetFirstOf("ProductID") >= 0 && oneDriver.GetFirstOf("ProductID") >= 0)
- {
- if (strcmp(driverConf["ProductID"], oneDriver["ProductID"]) == 0 &&
- strcmp(driverConf["VendorID"], oneDriver["VendorID"]) == 0)
- {
- //匹配了
- if (driverConf.GetFirstOf("oemdriver") > 0)
- {
- string sdkPath, driverPath = driverConf["oemdriver"];
- driverPath = ReplaceSubString(driverPath, string("%ROOT%"), procdir);
- FILE* f = fopen(driverPath.c_str(), "r");
- if (f != NULL)
- {
- fileList[x] = true;
- fclose(f);
- if (oneDriver.GetFirstOf("Install") >= 0)
- {
- const char* install = oneDriver["Install"];
- if (strcmp(install, "true") == 0)
- {
- string dstPath = ReplaceSubString(fileList.GetKey(x), string("FullConfig"), string("DriverConfig"));
- //拷贝安装驱动到DriverConfig,暂时不预装
- //CopyFile(fileList.GetKey(x), dstPath.c_str(), FALSE);
- //std::cout << "Install Driver: " << dstPath << endl;
- }
- }
- //记录驱动保留目录
- //存在多个设备共享驱动情况
- //只要有一个需要安装,驱动不能删除
- driverPath = GetFileDirectory(driverPath);
- driverList.update(driverPath.c_str(), true);
- CheckWhiteDir(driverConf, driverPath, sdkPath);
- return true;
- }
- }
- }
- }
- }
- }
- }
- return false;
- }
- // 删除文件(第二个参数bDelete表示是否删除至回收站,默认删除到回收站)
- bool RecycleFileOrFolder(string strPath, bool bDelete = true)
- {
- strPath += '\0';
- SHFILEOPSTRUCT shDelFile;
- memset(&shDelFile, 0, sizeof(SHFILEOPSTRUCT));
- shDelFile.fFlags |= FOF_SILENT; // 不显示进度
- shDelFile.fFlags |= FOF_NOERRORUI; // 不报告错误信息
- shDelFile.fFlags |= FOF_NOCONFIRMATION; // 直接删除,不进行确认
- // 设置SHFILEOPSTRUCT的参数为删除做准备
- shDelFile.wFunc = FO_DELETE; // 执行的操作
- shDelFile.pFrom = strPath.c_str(); // 操作的对象,也就是目录(注意:以“\0\0”结尾)
- shDelFile.pTo = NULL; // 必须设置为NULL
- if (bDelete) //根据传递的bDelete参数确定是否删除到回收站
- {
- shDelFile.fFlags &= ~FOF_ALLOWUNDO; //直接删除,不进入回收站
- }
- else
- {
- shDelFile.fFlags |= FOF_ALLOWUNDO; //删除到回收站
- }
- BOOL bres = SHFileOperation(&shDelFile); //删除
- return !bres;
- }
- /// <summary>
- /// 移除驱动,配置文件和驱动目录
- /// </summary>
- /// <param name="pszDriverConf">要移除的驱动文件路径</param>
- /// <param name="resRetainDriverList">要保留的驱动目录列表</param>
- void DeleteDriver(const char* pszDriverConf, ResDataObject& resRetainDriverList)
- {
- string procdir = GetProcessDirectory();
- ResDataObject driverConfFile;
- if (driverConfFile.loadFile(pszDriverConf))
- {
- ResDataObject driverConf;
- if (driverConfFile.GetFirstOf("CONFIGURATION") >= 0)
- {
- driverConf = driverConfFile["CONFIGURATION"];
- if (driverConf.GetFirstOf("oemdriver") > 0)
- {
- string driverPath = driverConf["oemdriver"];
- driverPath = ReplaceSubString(driverPath, string("%ROOT%"), procdir);
- driverPath = GetFileDirectory(driverPath);
- if (resRetainDriverList.GetFirstOf(driverPath.c_str()) < 0)
- {
- RecycleFileOrFolder(driverPath.c_str());
- std::cout << "Remove Driver Module: " << driverPath << endl;
- }
- }
- }
- }
- DeleteFile(pszDriverConf);
- std::cout << "Delete Driver Config: " << pszDriverConf << endl;
- }
- /// <summary>
- /// 校验驱动配置
- /// </summary>
- /// <param name="pszFileName">驱动配置文件名,不含路径,文件必须在设备目录里</param>
- void DefineDriver(const char* pszFileName)
- {
- string procdir = GetProcessDirectory();
- ResDataObject resDriver;
- string driverFile = procdir + "\\" + pszFileName;
- g_arrWhiteDirectory.clear();
- if (resDriver.loadFile(driverFile.c_str()))
- {
- string canInsstall = procdir + "\\DriverDefine\\DriverDefine.json";
- CopyFile(driverFile.c_str(), canInsstall.c_str(), FALSE);
- //先清理已安装驱动
- ResDataObject whitelist;
- if (resDriver.GetFirstOf("WhiteList") >= 0)
- {
- whitelist = resDriver["WhiteList"];
- CleanDriver(&whitelist);
- }
- if (resDriver.GetFirstOf("Drivers") >= 0)
- {
- //获取所有配置
- ResDataObject fileList, driverList;
- GetSpecificDriverConfigFiles(fileList, true);
- for (int fn = 0; fn < fileList.size(); fn++)
- {
- fileList[fn] = false;
- }
- //校验每个驱动
- ResDataObject ResDrivers = resDriver["Drivers"];
- for (int x = 0; x < ResDrivers.size(); x++)
- {
- //Detector/Generator/...
- ResDataObject resDrConf = ResDrivers[x];
- for (int y = 0; y < resDrConf.size(); y++)
- {
- ResDataObject oneDriver = resDrConf[y];
- CheckInDriver(fileList, driverList, oneDriver, ResDrivers.GetKey(x));
- }
- }
- //移除没有驱动程序的驱动配置
- //移除未在驱动配置列表的驱动
- //白名单驱动要保留
- for (int afn = 0; afn < fileList.size(); afn++)
- {
- if ((bool)fileList[afn] == false)
- {
- bool isWhite = false;
- string driverFile = fileList.GetKey(afn);
- for (int wn = 0; wn < whitelist.size(); wn++)
- {
- if (driverFile.find((const char*)whitelist[wn]) != string::npos)
- {
- isWhite = true;
- break;
- }
- }
- if (!isWhite)
- DeleteDriver(driverFile.c_str(), driverList);
- }
- }
- }
- }
- std::vector<string> dirList;
- FindSubFiles(procdir + "\\OEMDrivers", dirList, true, "*", true, 3, 2);
- FindSubFiles(procdir + "\\ServiceDrivers", dirList, true, "*", true, 2, 2);
- FindSubFiles(procdir + "\\SystemDrivers", dirList, true, "*", true, 2, 2);
-
- cout << endl << "After Define Left Driver Dirs." << endl;
- for (string td : dirList)
- {
- cout << td << endl;
- string tmp = td.substr(td.length() - 4);
- //size_t pos = td.find_last_of("conf");
- if (tmp == "conf" )
- {
- g_arrWhiteDirectory.insert(td);
- cout << "Keeped." << endl;
- }
- else
- {
- if (tmp == "Conf")
- {
- g_arrWhiteDirectory.insert(td);
- cout << "Keeped." << endl;
- }
- else
- {
- if (g_arrWhiteDirectory.find(td) != g_arrWhiteDirectory.end())
- {
- //
- cout << "Keeped." << endl;
- }
- else
- {
- cout << "Removed. Useless Dir" << endl;
- RecycleFileOrFolder(td);
- }
- }
- }
-
- }
- cout << endl <<endl << "After Define Left Driver Diretory " << endl;
- for (string dir : g_arrWhiteDirectory)
- {
- cout << dir << endl;
- }
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- bool status = true;
- printf("Main Thread:%d\n", GetCurrentThreadId());
- int nTotal = 0;
- int nMsgCount = 0;
- char szName[20][256];
- int count[10] = {0,0,0,0,0,0,0,0,0,0};
- if (argc > 1)
- {
- if (strcmp(argv[1], "test") == 0)
- {
- int nConnNum = 1;
- if (argc > 2)
- nConnNum = atoi(argv[2]);
- if (nConnNum > 20)
- {
- nConnNum = 20;
- }
- dios_mqtt_connection** pConns = new dios_mqtt_connection * [nConnNum];
- for (int x = 0; x < nConnNum; x++)
- {
- sprintf(szName[x], "TEST_MQTT_Server_%d", x);
- pConns[x] = NewConnection(szName[x], [szName,x,&count, &nTotal, &nMsgCount](ResDataObject* rsp, const char* topic, void* conn_void) {
- dios_mqtt_connection* conn = (dios_mqtt_connection*)conn_void;
- std::cout << "Server [" << szName[x] << "] " << CurrentDateTime() << "Get Msg from " << topic << " Msg Body " << rsp->encode() << endl;
- string tickSend = PacketAnalizer::GetPacketKey(rsp);
- DWORD dwTick = GetTickCount() - atoi(tickSend.c_str());
- nTotal += dwTick;
- nMsgCount++;
- if (dwTick < 3)
- {
- count[0]++;
- }
- else if (dwTick < 5)
- {
- count[1]++;
- }
- else if (dwTick < 10)
- {
- count[2]++;
- }
- else if (dwTick < 15)
- {
- count[3]++;
- }
- else if (dwTick < 20)
- {
- count[4]++;
- }
- else
- {
- count[5]++;
- //std::cout << "Receive Packet Use Time [" << dwTick << "]ms " << endl;
- }
- if (PacketAnalizer::GetPacketType(rsp) == PACKET_TYPE_RES)
- {
- //check cmd
- if ((PacketAnalizer::GetPacketCmd(rsp) == PACKET_CMD_OPEN) /*&& (PacketAnalizer::GetPacketKey(rsp) == realPath)*/)
- {
- //std::cout << "\n\n-----------" << CurrentDateTime() << "LogicClient::Open OK [" << m_strClientName << "] try open path:" << realPath << endl << endl;
- //ret = ProcessOpenResponse(*rsp);
- //if (m_bNeedNotify) {
- string notifyTopic = "DIOS/Tetst/";
- notifyTopic += "/Notify/#";
- SubscribeTopic(conn, notifyTopic.c_str());
- //}
- }
- else
- {
- std::cout << szName[x] << CurrentDateTime() << "Try Conn callback get unkown packet pointer [" << (UINT64)conn << endl;
- std::cout << "Unkown Packet: cmd [" << PacketAnalizer::GetPacketCmd(rsp) << "] packet key: " << PacketAnalizer::GetPacketKey(rsp) << "" << endl;
- //if (m_pPacketArrivedCallbackFunc != nullptr)
- //{
- // m_pPacketArrivedCallbackFunc(rsp, topic, conn);
- //}
- //else
- //{
- // m_pPacketReceivedQue->Lock();
- // m_pPacketReceivedQue->InQueue(*rsp);
- // //SetEvent(m_NotifyEvent);//notify to user
- // SetEvent(m_ResponseEvent);
- // m_pPacketReceivedQue->UnLock();
- //}
- }
- }
- else
- {
- }
- });
- char szTopic[256];
- //sprintf(szTopic, "DIOS/TEST/Notify/%d/%d/TestV", GetCurrentProcessId(), m_nIndex);
- sprintf(szTopic, "DIOS/TEST/Notify/+/%d/#", x);
- SubscribeTopic(pConns[x], szTopic);
- SubscribeTopic(pConns[x], "DIOS/TEST/Action/#", true);
- }
- std::cout << "Waiting quit..." << endl;
- while (1)
- {
- char cmd = getchar();
- if (cmd == 'q')
- break;
- else if (cmd == 'p')
- {
- std::cout << "Time < 3 : " << count[0] << endl;
- std::cout << "Time < 5 : " << count[1] << endl;
- std::cout << "Time < 10 : " << count[2] << endl;
- std::cout << "Time < 15 : " << count[3] << endl;
- std::cout << "Time < 20 : " << count[4] << endl;
- std::cout << "Time > 20 : " << count[5] << endl;
- memset(count, 0, sizeof(count));
- std::cout << "TotalTime " << nTotal << " ms , msg count : " << nMsgCount << "Average : " << nTotal*1.0/nMsgCount << endl;
- nTotal = nMsgCount = 0;
- }
- else if (cmd == 'x')
- {
- for (int x = 0; x < nConnNum; x++)
- {
- ResetConnection(pConns[x]);
- }
- }
- Sleep(10);
- }
- for (int x = 0; x < nConnNum; x++)
- {
- CloseConnection(pConns[x]);
- }
- delete[] pConns;
- std::cout << "Hello World!\n";
- return 0;
- }
- else
- {
- std::cout << "Starting Process Driver Define....." << endl;
- DefineDriver(argv[1]);
- std::cout << "Driver Define Done." << endl;
- return 0;
- }
- }
- setLogRootpath(((string)getChannelRootpath()).c_str());
- if (GetCommandDispathIF()->InitAs(DIOS_PROC_CHANNEL, (UINT64)GetCurrentProcessId()))
- {
- if (SetConsoleCtrlHandler((PHANDLER_ROUTINE)ConsoleHandler, true))
- {
- {
- LogicClient buClient("channel_temp", "", "", false);
- if (buClient.Open((const char*)getRootpath(), ALL_ACCESS) == RET_SUCCEED)
- {
- //buClient.ExitDriverProc();
- buClient.Close();
- /*DWORD count = buClient.GetDeviceCount();
- for (DWORD i = 0; i < count; i++)
- {
- UINT64 ProcId, Addr;
- ResDataObject DevType,devpath, MachineId;
- buClient.GetDeviceDescript(i, devpath, DevType, MachineId, ProcId, Addr);
- printf("path:%s\nProc:%I64u\nAddr:%I64u\n", (const char*)devpath, ProcId, Addr);
- LogicClient DevClient("channel_exe_temp","channel");
- if (DevClient.Open((const char*)devpath, ALL_ACCESS) >= RET_SUCCEED)
- {
- DevClient.Close();
- printf("Open Succeed\n");
- }
- else
- {
- printf("Open Failed\n");
- }
- }*/
- status = true;
- }
- else
- {
- status = false;
- }
- }
- //start work
- if (status)
- {
- if (StartConsoleThreads(true))
- {
- printf("Done Init Channel.going to sleep...\n");
- while (1){
- if (GetCommandDispathIF()->WaitExit(500) == true)
- {
- StartConsoleThreads(false);
- //ShareMemory_ServerStop();
- return 1;
- }
- }
- }
- }
- printf("Can't Start Console Thread.Exit in 3sec\n");
- Sleep(3000);
- }
- }
- //ShareMemory_ServerStop();
- return 0;
- }
|