// CanModelDPC.cpp : 定义 DLL 应用程序的导出函数。 // #include "stdafx.h" #include "CanModelDPC.h" #include "DevTree.h" #include "CanModelDevice.h" #include "common_api.h" #include #include #include "localConfig.h" #include "ModuleConfig.h" #include #include #include CANMODELDPC_C_API DriverDPC* GetDriverDPC() { return (DriverDPC*)(new CanModelDPC()); } CANMODELDPC_C_API void ReleaseDriverDPC(DriverDPC *p) { CanModelDPC *org = (CanModelDPC*)p; delete org; } typedef nsDEV::IODriver* (*GetDriverMgrAPI)(); typedef VirtualDevice* (*CreateVirtuaDeviceAPI)(); typedef void (*FreeVirtualDeviceAPI)(VirtualDevice*); Log4CPP::Logger* //mLog::gLogger = nullptr; HANDLE g_hExit = INVALID_HANDLE_VALUE; CanModelDPC::CanModelDPC(void) { m_pWorkpath = new std::string(); m_MainHostDevice = nullptr; //m_pMidObject = 0; //m_pMidObject.reset(new eDEV::Mediator()); if (//mLog::gLogger == nullptr) { string strLogPath = GetProcessDirectory() + R"(\Conf\Log4CPP.Config.xml)"; string LogHost = ((string)getLogRootpath()).c_str(); Log4CPP::ThreadContext::Map::Set(ECOM::Utility::Hash("LogFileName"), "Platform"); //Log4CPP::GlobalContext::Map::Set("LogHost", LogHost.c_str()); Log4CPP::ThreadContext::Map::Set(ECOM::Utility::Hash("LogHost"), LogHost.c_str() + 1); auto rc = Log4CPP::LogManager::LoadConfigFile(strLogPath.c_str()); //mLog::gLogger = Log4CPP::LogManager::GetLogger("Platform"); //mLog::FINFO("Code Build datetime [{$} {$}]", __DATE__, __TIME__); } g_hExit = CreateEvent(NULL, TRUE, FALSE, NULL); } CanModelDPC::~CanModelDPC(void) { delete m_pWorkpath; SetEvent(g_hExit); } bool CanModelDPC::LoadVirtualDevice(const char* pDevicePath, bool isImgDevice, bool bAddToList, string devPath, string devSrvPath) { string devDeriverPath = GetProcessDirectory() + "\\VirtualDevices\\" + pDevicePath; string FilePath = GetFileDirectory(devDeriverPath); AddEnvPath(FilePath.c_str()); auto hModle = LoadLibrary(devDeriverPath.c_str()); //m_arrImgeFunc = nullptr; if (hModle) { VirtualDevice* pDevice = nullptr; //mLog::FINFO("Load Driver ok.. {$}", devDeriverPath); CreateVirtuaDeviceAPI callfunc = (CreateVirtuaDeviceAPI)GetProcAddress(hModle, "CreateVirtualDevice"); if (callfunc) { pDevice = callfunc(); if (pDevice) { int nIndex = -1; if (isImgDevice) { if (bAddToList) { //"ImageProcessIndex": // "DescKey":"ImageProcessIndex", // "Value" : "2" /*ResDataObject resPri; if (RET_SUCCEED == pDevice->DevGet("", "ImageProcessIndex", resPri)) { string strPri = (const char*)resPri; if (strPri.length() > 0) { resPri = ""; int nPri = atoi(strPri.c_str()); for (int x = 0; x < m_arrImgeProcessDevices.size(); x++) { if (m_arrImgeProcessDevices[x]->DevGet("", "ImageProcessIndex", resPri) == RET_SUCCEED) { strPri = (const char*)resPri; if (atoi(strPri.c_str()) < nPri) { nIndex = x; continue; } else break; } } } }*/ ImageProcessAPI func = (ImageProcessAPI)GetProcAddress(hModle, "DeviceImgProcess"); if (nIndex >= 0) { //mLog::FINFO("Inesrt {$} at [{$}] ImageProcess Array", pDevice->GetCcosRootPath(), nIndex); m_arrImgeProcessDevices.insert(m_arrImgeProcessDevices.begin()+nIndex, pDevice); m_arrImgeFunc.insert(m_arrImgeFunc.begin()+nIndex, func); } else { //mLog::FINFO("Append {$} ImageProcess Array at [{$}] ", pDevice->GetCcosRootPath(), m_arrImgeFunc.size()); m_arrImgeProcessDevices.push_back(pDevice); m_arrImgeFunc.push_back(func); } } m_hImgeDeviceHandle = hModle; } else { if (bAddToList) { m_arrMessageProcessDevices.push_back( pDevice); m_hMessageDeviceHandle = hModle; } } if (!bAddToList) { //mLog::FINFO("Only Init Module from Template "); FreeVirtualDeviceAPI freeFunc = (FreeVirtualDeviceAPI)GetProcAddress(hModle, "ReleaseVirtualDevice"); if (freeFunc && pDevice) { //创建对象,只是模型文件操作 //mLog::FINFO(" SetDeviceInfo {$} devSrvPath: {$} ",devPath, devSrvPath); pDevice->SetDeviceInfo(devPath, devSrvPath); //mLog::FINFO("First Install Test and check Module Begin "); pDevice->SetClientRootID("", devSrvPath.c_str()); //mLog::FINFO("Test and check Module End "); freeFunc(pDevice); } } //m_NewDevManager.reset(pDriver); //succeed return true; } else { DWORD errNo = GetLastError(); //mLog::FERROR("lib:{$} no Object returned.ErrNo:{$}\n", devDeriverPath, errNo); } } else { DWORD errNo = GetLastError(); //mLog::FERROR("lib:{$} no CreateIODriver entry.ErrNo:{$}\n", devDeriverPath, errNo); } } else { DWORD errNo = GetLastError(); //mLog::FERROR("Load lib:{$} failed.ErrNo:{$}\n", devDeriverPath, errNo); } return false; } const int MAX_IMG_THREAD = 4; //using imgFuncThreadParams = std::tuple; using imgFuncThreadParams = std::tuple; imgFuncThreadParams g_paramImgThread[MAX_IMG_THREAD]; HANDLE g_hImgThread[MAX_IMG_THREAD]; HANDLE g_hIdleEvent[MAX_IMG_THREAD+1]; HANDLE g_hDataReaded[MAX_IMG_THREAD]; HANDLE g_hDataReadyEvent[MAX_IMG_THREAD+1]; DWORD WINAPI ImgeProcessThread(LPVOID pPara); bool CanModelDPC::InitDeviceMgr(const char *pDriverpath) { m_Module = LoadLibrary(pDriverpath); if (m_Module) { //mLog::FINFO("Load Driver ok.. {$}", pDriverpath); GetDriverMgrAPI callfunc = (GetDriverMgrAPI)GetProcAddress(m_Module, "CreateIODriver"); if (callfunc) { auto pDriver = reinterpret_cast (callfunc()); if (pDriver) { m_NewDevManager.reset(pDriver); //succeed SECURITY_ATTRIBUTES sa = { 0 }; sa.bInheritHandle = TRUE; sa.nLength = sizeof(SECURITY_ATTRIBUTES); DWORD threadID; for (int x = 0; x < MAX_IMG_THREAD; x++) { g_hDataReadyEvent[x] = CreateEvent(NULL, FALSE, FALSE, NULL); g_hIdleEvent[x] = CreateEvent(NULL, FALSE, TRUE, NULL); g_hDataReaded[x] = CreateEvent(NULL, FALSE, FALSE, NULL); g_hImgThread[x] = CreateThread(&sa, 0, ImgeProcessThread, (void*)x, 0, &threadID); //mLog::FINFO("Create ImageProcessThread ID={$}", threadID); } g_hDataReadyEvent[MAX_IMG_THREAD] = g_hExit; g_hIdleEvent[MAX_IMG_THREAD] = g_hExit; ///初始化 图像处理线程需要的数据 return true; } else { DWORD errNo = GetLastError(); //mLog::FERROR("lib:{$} no Object returned.ErrNo:{$}\n", pDriverpath, errNo); } } else { DWORD errNo = GetLastError(); //mLog::FERROR("lib:{$} no CreateIODriver entry.ErrNo:{$}\n", pDriverpath, errNo); } } else { DWORD errNo = GetLastError(); //mLog::FERROR("Load lib:{$} failed.ErrNo:{$}\n", pDriverpath, errNo); } return false; } static void TrimeSDKPath(string& sdkPath) { if (sdkPath.length() > 0) { if (sdkPath[0] == '\\' || sdkPath[0] == '/') sdkPath = sdkPath.substr(1); if (sdkPath.length() > 0) { if (sdkPath[sdkPath.length() - 1] == '\\' || sdkPath[sdkPath.length() - 1] == '/') { sdkPath = sdkPath.substr(0, sdkPath.length() - 1); } } } } namespace fs = std::filesystem; void copy_directory(const fs::path& src, const fs::path& dst) { if (!fs::exists(dst)) { fs::create_directory(dst); } for (auto& dir_entry : fs::recursive_directory_iterator(src)) { const auto& path = dir_entry.path(); auto relative_path = path.lexically_relative(src); fs::path dest_path = dst / relative_path; if (fs::is_directory(path)) { fs::create_directories(dest_path); } else if (fs::is_regular_file(path)) { fs::copy(path, dest_path, fs::copy_options::update_existing); } else { std::cerr << "Unhandled path: " << path << std::endl; } } } bool CanModelDPC::DriverEntry(ResDataObject &Configuration) { const char *pDriverpath = Configuration["oemdriver"]; if (pDriverpath == 0 || strlen(pDriverpath) == 0) { //mLog::FERROR("context of oemdriver is empty"); return false; } m_resHardwareInfo.update("MajorID", (const char*)Configuration["MajorID"]); m_resHardwareInfo.update("MinorID", (const char*)Configuration["MinorID"]); m_resHardwareInfo.update("VendorID", (const char*)Configuration["VendorID"]); m_resHardwareInfo.update("ProductID", (const char*)Configuration["ProductID"]); m_resHardwareInfo.update("SerialID", (const char*)Configuration["SerialID"]); string sdkPath,realSdkPath; m_nServerIdx = -1; if (Configuration.GetKeyCount("ServerID") > 0) { //有ServerID配置 m_nServerIdx = (int)Configuration["ServerID"]; if (m_nServerIdx > 0) { //mLog::FINFO("Need clone SDK path from 0"); if (Configuration.GetKeyCount("SDKPath") > 0) { sdkPath = (const char*)Configuration["SDKPath"]; realSdkPath = sdkPath; TrimeSDKPath(realSdkPath); realSdkPath = GetProcessDirectory() + "\\" + realSdkPath; string newSdkPath = realSdkPath + to_string(m_nServerIdx); //mLog::FINFO("Try Copy Directory from {$} to {$}", realSdkPath, newSdkPath); try { copy_directory(realSdkPath, newSdkPath); } catch (...) { //mLog::FWARN("Copy Directory from {$} to {$} Error maybe exists.", realSdkPath, newSdkPath); } if (sdkPath.length() > 0) { if (sdkPath[sdkPath.length() - 1] == '\\' ) { sdkPath = sdkPath.substr(0, sdkPath.length() - 1) + to_string(m_nServerIdx) + "\\"; } else if (sdkPath[sdkPath.length() - 1] == '/') { sdkPath = sdkPath.substr(0, sdkPath.length() - 1) + to_string(m_nServerIdx) + "/"; } else { sdkPath = sdkPath + to_string(m_nServerIdx); } Configuration.update("SDKPath", sdkPath.c_str()); } } } } if (InitDeviceMgr(pDriverpath) == false) { //mLog::FERROR("CreateIODriver Failed.{$}",pDriverpath); return false; } bool ret = ModuleDriver::DriverEntry(Configuration); string moduleConfig = GetModuleConfigrateFilePath(m_resHardwareInfo); string filepath; try { ResDataObject moduleConf; moduleConf.loadFile(moduleConfig.c_str()); filepath = moduleConfig; //mLog::FINFO("Load Configration from Mudle Config [{$}]", moduleConfig); } catch (...) { //mLog::FERROR("Failed to Load Configration from Driver Config [{$}]", moduleConfig); filepath = GetDriverConfigFilePath(); //mLog::FERROR("Try Load Configration from Driver Config [{$}]", moduleConfig); } //这里修改SDKPath和ServerID if (m_nServerIdx > 0 && sdkPath.length() > 0) { //mLog::FINFO("Change SDKPath and ServerID {$}", m_nServerIdx); ResDataObject resCtx; try { resCtx.loadFile(filepath.c_str()); if (resCtx.GetKeyCount("CONFIGURATION") > 0) { if (resCtx["CONFIGURATION"].GetKeyCount("SDKPath") > 0 ) { resCtx["CONFIGURATION"]["SDKPath"].update("Value", sdkPath.c_str()); } else { ResDataObject resObj; resObj.add("Value", sdkPath.c_str()); resCtx["CONFIGURATION"].add("SDKPath", resObj); } if (resCtx["CONFIGURATION"].GetKeyCount("ServerID") > 0) { resCtx["CONFIGURATION"]["ServerID"].update("Value", m_nServerIdx); } else { ResDataObject resObj; resObj.add("Value", m_nServerIdx); resCtx["CONFIGURATION"].add("ServerID", resObj); } if (resCtx["CONFIGURATION"].GetKeyCount("ComServerID") > 0) { resCtx["CONFIGURATION"]["ComServerID"].update("Value", m_nServerIdx); } resCtx.SaveFile(filepath.c_str()); } } catch (...) { //mLog::FERROR("Read config file error {$}", filepath); } } if (ret) { //这里检查模型对象的配置项是否存在,如果是走模型配置,在安装的时候,会自动创建一份修改后的配置文件 //这里可以直接检查到 //mLog::FINFO("m_NewDevManager->DriverEntry {$}", filepath); ret = m_NewDevManager->DriverEntry(filepath); //mLog::FINFO("m_NewDevManager->Prepare "); m_NewDevManager->Prepare(); } else { //mLog::FERROR("LogicDriver::DriverEntry Failed.{$}", filepath.c_str()); } return ret; } DWORD SYSTEM_CALL CanModelDPC::OnNotify(HANDLE evtList[], DWORD count) { DWORD dwResult = WaitForMultipleObjects(count, evtList, FALSE, 2500); if ((dwResult >= WAIT_OBJECT_0) && (dwResult < WAIT_OBJECT_0 + count - 1)) { //mLog::FINFO("OnNotify Platform"); return dwResult - WAIT_OBJECT_0; } else { if (NULL != m_NewDevManager) { if (!m_NewDevManager->isConnected()) { //mLog::FWARN("CONNECTED is false"); if (*m_pConnectionStatus) { //mLog::FWARN("Notify disCONNECTED "); LogicDriver::DisConnect(); } if (!*m_pConnectionStatus) { //mLog::FINFO("Try CONNECT"); if (m_NewDevManager->Connect()) { //mLog::FINFO("try CONNECTED is ok"); LogicDriver::Connect(); //mLog::FINFO("Notify CONNECTED is ok"); } else { //mLog::FWARN("Notify disCONNECTED "); LogicDriver::DisConnect(); //mLog::FWARN("Try CONNECT failed. "); } } } else { if (!*m_pConnectionStatus) { //mLog::FINFO("Auto CONNECTED is ok"); LogicDriver::Connect(); //mLog::FINFO("Notify CONNECTED is ok"); } } //此处从程序启动后会一直打印,重复调用work函数 ////mLog::FINFO("ImageSaveDev->work()"); //((ImageSaveDev*)m_pImgSaveDev)->Work(); } } return 1; } RET_STATUS CanModelDPC::OnAction(const char* pszActionName, const char* pszParams, ResDataObject& resResponse) { RET_STATUS ret = ModuleDriver::OnAction(pszActionName, pszParams, resResponse); if (ret != RET_NOSUPPORT) { //成功或者失败, return ret; } string action = pszActionName; if (action == "InstallVirutalDevice") { //安装虚拟设备 /// "ABS": { // "InstalHost":"Detector", // "ImgeProcessDevice" : "ABS\\ABSX64.dll" // }, // "DAP": { // "MessageProcessDevice": "DAP\\DAPX64.dll" // } // //找到配置项,检查文件 //ResDataObject resTest,resdll; //resdll.add("ImgeProcessDevice", "ABS\\ABSX64.dll"); //resTest.add("ABS", resdll); ResDataObject resConf; string fileName = GetDriverConfigFilePath(); //mLog::FINFO("Try Load xml Config file {$} ", fileName); resConf.loadFile(fileName.c_str()); //string test = resTest.encode(); if (resConf.GetKeyCount("CONFIGURATION") <= 0) { //mLog::FERROR("config file {$} content error", fileName); ret = RET_FAILED; return ret; } //resConf = resConf["CONFIGURATION"]; ResDataObject resVirtual; resVirtual.decode(pszParams); bool changed = false; string strServDevPath; for (int vdIdx = 0; vdIdx < resVirtual.size(); vdIdx++) { bool got = false; string vdModuleName; //DTS/ABS/... if (strcmp(resVirtual.GetKey(vdIdx), "RespTopic") == 0) continue; if (resVirtual[vdIdx].GetKeyCount("ServDevPath") > 0) strServDevPath = (const char*)resVirtual[vdIdx]["ServDevPath"]; else strServDevPath = ""; for (int cfIdx = 0; cfIdx < resVirtual[vdIdx].size(); cfIdx++) { string va = (const char*)resVirtual[vdIdx][cfIdx]; if (va.length() > 4 && va.substr(va.length() - 4, 4) == ".dll") { string type = resVirtual[vdIdx].GetKey(cfIdx); vdModuleName = va; int idx = resConf["CONFIGURATION"].GetFirstOf(type.c_str()); while (idx != -1) { string confV = resConf["CONFIGURATION"][idx]; if (confV == va) { got = true; break; } idx = resConf["CONFIGURATION"].GetNextOf(type.c_str(), idx); } if (!got) { resConf["CONFIGURATION"].add(type.c_str(), va.c_str()); changed = true; break; } } } if (resVirtual[vdIdx].GetKeyCount("ServDevPath") > 0) { } if (got || changed) { //新装 string newdev = "CCOS/DEVICE/" + string(resVirtual.GetKey(vdIdx)); string devPath = newdev; devPath += "/" + string((const char*)m_resHardwareInfo["VendorID"]);// , (const char*)Configuration["VendorID"]); devPath += "/" + string((const char*)m_resHardwareInfo["ProductID"]);//, (const char*)Configuration["ProductID"]); devPath += "/" + string((const char*)m_resHardwareInfo["SerialID"]);//, (const char*)Configuration["SerialID"]); //mLog::FINFO("New Virtual Device Path {$}", devPath); resResponse.add(strServDevPath.c_str(), ""); if (strServDevPath.length() <= 0) strServDevPath = devPath; if (!got) { //mLog::FINFO("New install VD {$]", strServDevPath); //之前没有配置,则需要测试,并设置 LoadVirtualDevice(vdModuleName.c_str(), false, false, devPath, strServDevPath); } else { //mLog::FINFO("VD had installed aready {$]", strServDevPath); for(int x=0;xGetCcosRootPath() == strServDevPath) { // //mLog::FINFO("VD {$} had installed aready type ImageProcessDevices with idx {$]", strServDevPath, x); resResponse.update(strServDevPath.c_str(), "ON"); } for (int x = 0; x < m_arrMessageProcessDevices.size(); x++) if (m_arrMessageProcessDevices[x]->GetCcosRootPath() == strServDevPath) { // //mLog::FINFO("VD {$} had installed aready type MessageProcessDevices with idx {$]", strServDevPath, x); resResponse.update(strServDevPath.c_str(), "ON"); } if(strlen(resResponse[strServDevPath.c_str()]) == 0) resResponse.update(strServDevPath.c_str(), "OFF"); } } } if (changed) { //ResDataObject save; //save.add("CONFIGURATION", resConf); resConf.SaveFile(fileName.c_str()); } ret = RET_SUCCEED; //resResponse = "Install ok."; } else if (action == "restart") { resResponse = "reStart ok."; ret = RET_SUCCEED; exit(1); } return ret; } bool CanModelDPC::GetDeviceType(GUID &DevType) { string DriverType = m_NewDevManager->GetGUID(); if (DriverType.size() == 0) { //mLog::FERROR("GetDeviceType Failed"); return false; } //if (m_pNewDevManager->GetDriverType(DriverType) == false) //{ // return false; //} return string_2_guid(DriverType.c_str(), DevType); } string DEVICE_ID = ""; string TOPIC_PREFIX = ""; bool SYSTEM_CALL CanModelDPC::Driver_Probe(ResDataObject& PARAM_OUT HardwareInfo) { //string DriverInfo = m_NewDevManager->DriverProbe(); //mLog::FINFO("Driver : DriverInfo {$}", m_resHardwareInfo.encode()); //if (m_pNewDevManager->Driver_Probe(DriverInfo)) { ResDataObject Config = m_resHardwareInfo; HardwareInfo = m_resHardwareInfo; //if (Config.decode(DriverInfo.c_str())) { //HardwareInfo.add("MajorID", (const char*)Config["MajorID"]); //HardwareInfo.add("MinorID", (const char*)Config["MinorID"]); //HardwareInfo.add("VendorID", (const char*)Config["VendorID"]); //HardwareInfo.add("ProductID", (const char*)Config["ProductID"]); //HardwareInfo.add("SerialID", (const char*)Config["SerialID"]); ostringstream os,os2; os << (const char*)Config["VendorID"] << "_" << (const char*)Config["ProductID"] << "_" << (const char*)Config["SerialID"]; DEVICE_ID = os.str(); os2 << "" << (const char*)Config["MajorID"] ;//<< "/" << (const char*)Config["VendorID"] << "/" << (const char*)Config["ProductID"]; os2 << "/" << (const char*)Config["SerialID"] << "/"; TOPIC_PREFIX = os2.str(); return true; } //else //{ // //mLog::FERROR("Driver_Probe Failed"); //} } return false; } RET_STATUS CanModelDPC::GetDeviceResource(ResDataObject *pDeviceResource) { RET_STATUS ret = RET_FAILED; ResDataObject BaseLayerConfig; if ((*m_config).GetPropties().size() > 0) { ModuleDriver::GetDeviceResource(pDeviceResource); //mLog::FINFO("ModuleDriver : GetDeviceResource {$}", pDeviceResource->encode()); //BaseLayerConfig = *pDeviceResource; } string ResInfo;// = m_NewDevManager->GetResource(); //mLog::FINFO("IO Driver : GetDeviceResource {$}", ResInfo); //if (m_pNewDevManager->GetDriverResource(ResInfo)) { //low layerInfo ResDataObject LowLayerConfig; if ((*m_config).GetPropties().size() <= 0) { ResInfo = m_NewDevManager->GetResource(); if (LowLayerConfig.decode(ResInfo.c_str()) == false) { //mLog::FERROR("GetDriverResource Failed"); return ret; } ResDataObject BaseLayerConfig; ret = LogicDriver::GetDeviceResource(&BaseLayerConfig); if (ret < RET_SUCCEED) { return ret; } } //base LogicDriverinfo if (BaseLayerConfig.size() <= 0) { ret = LogicDriver::GetDeviceResource(&BaseLayerConfig); //mLog::FINFO("LogicDriver : GetDeviceResource {$}", BaseLayerConfig.encode()); if (ret < RET_SUCCEED) { return ret; } } if (LowLayerConfig.GetFirstOf("Attribute") >= 0) { //loop Low Layer Attribute for (size_t i = 0; i < LowLayerConfig["Attribute"].size(); i++) { const char *pKey = LowLayerConfig["Attribute"].GetKey(i); if (pKey) { int BaseIdx = BaseLayerConfig["Attribute"].GetFirstOf(pKey); if (BaseIdx >= 0) { //exist then overwrite BaseLayerConfig["Attribute"][BaseIdx] = LowLayerConfig["Attribute"][i]; } else { //not exist then add BaseLayerConfig["Attribute"].add(pKey, LowLayerConfig["Attribute"][i]); } } } } if (LowLayerConfig.GetFirstOf("Action") >= 0) { //loop Low Layer Action for (size_t i = 0; i < LowLayerConfig["Action"].size(); i++) { const char *pKey = LowLayerConfig["Action"].GetKey(i); if (pKey) { int BaseIdx = BaseLayerConfig["Action"].GetFirstOf(pKey); if (BaseIdx >= 0) { //exist then overwrite BaseLayerConfig["Action"][BaseIdx] = LowLayerConfig["Action"][i]; } else { //not exist then add BaseLayerConfig["Action"].add(pKey, LowLayerConfig["Action"][i]); } } } } (*pDeviceResource) = BaseLayerConfig; //mLog::FINFO("GetDeviceResource Result {$}", BaseLayerConfig.encode()); return RET_SUCCEED; } return ret; } /* void CanModelDPC::SubscribeSelf() { //这里订阅topic }*/ bool CanModelDPC::Device_Probe(ResDataObject &HardwareInfo) { //string DeviceInfo = m_NewDevManager->DeviceProbe(); //mLog::FINFO("Driver : Device_Probe {$}", m_resHardwareInfo.encode()); //if (m_pNewDevManager->Device_Probe(DeviceInfo)) { //ResDataObject Config; //if (Config.decode(DeviceInfo.c_str())) { //HardwareInfo.add("MajorID", (const char*)Config["MajorID"]); //HardwareInfo.add("MinorID", (const char*)Config["MinorID"]); //HardwareInfo.add("VendorID", (const char*)Config["VendorID"]); //HardwareInfo.add("ProductID", (const char*)Config["ProductID"]); //HardwareInfo.add("SerialID", (const char*)Config["SerialID"]); HardwareInfo = m_resHardwareInfo; return true; } //else //{ // //mLog::FERROR("Device_Probe Failed"); //} } return false; } bool CanModelDPC::SetDeviceWorkPath(const char *pWorkPath) { return true; } bool CanModelDPC::SetDriverWorkPath(const char *pWorkPath) { (*m_pWorkpath) = pWorkPath; //要把读取单一硬件属性的过程放到此处 return true; } bool CanModelDPC::Connect() { bool bret = m_NewDevManager->Connect(); if (bret) { LogicDriver::Connect();//make sure it's connected //mLog::FINFO("Connect Succeed"); return true; } else { //mLog::FERROR("Connect Failed"); } return false; } bool SYSTEM_CALL CanModelDPC::GetConnectionStatus() { return m_NewDevManager->isConnected(); } void CanModelDPC::DisConnect() { m_NewDevManager->Disconnect(); LogicDriver::DisConnect();//make sure it's Disconnected //mLog::FINFO("DisConnect Succeed"); } bool SYSTEM_CALL CanModelDPC::OnHeartBeat() { return m_NewDevManager->OnHeartBeat(); } DWORD WINAPI ImgeProcessThread(LPVOID pPara) { int nIndex = (int)pPara; imgFuncThreadParams* pParam = g_paramImgThread + nIndex; HANDLE hWait[2]; hWait[0] = g_hDataReadyEvent[nIndex]; hWait[1] = g_hExit; while (true) { DWORD dwWait = WaitForMultipleObjects(2, hWait, FALSE, 1000); if (dwWait == WAIT_OBJECT_0) { //有图像 int nNum = std::get<0>(*pParam); ImageProcessAPI* func = std::get<1>(*pParam); LogicDevice** pDev = std::get<8>(*pParam); string Head = std::get<3>(*pParam); string context = std::get<4>(*pParam); SetEvent(g_hDataReaded[nIndex]); if (func != nullptr) { //string temp = std::get<3>(*pParam); for (int x = 0; x < nNum; x++) { if (func[x] == nullptr) { //mLog::FERROR("Thread[{$}] ImageProcessFunc is null with devpath= {$}", nIndex, pDev[x]->GetCcosRootPath()); continue; } //mLog::FINFO("Thread[{$}] start ImageProcess {$} from {$} with devpath= {$}", nIndex, Head, std::get<7>(*pParam)->GetCcosRootPath(), pDev[x]->GetCcosRootPath()); func[x](std::get<2>(*pParam), Head, (char*)context.c_str(), std::get<5>(*pParam), std::get<6>(*pParam),std::get<7>(*pParam), pDev[x]); //mLog::FINFO("Thread[{$}] ImageProcessFunc Over with devpath= {$}", nIndex, pDev[x]->GetCcosRootPath()); } } else { //mLog::FERROR("Thread[{$}] ImageProcessFunc arrpoint is null ", nIndex); } SetEvent(g_hIdleEvent[nIndex]); } else if(dwWait == WAIT_OBJECT_0 + 1) { //mLog::FINFO("ImageThread {$} Got exit", nIndex); } } //delete pParam; //std::get<1>(*pParam) = Type; //std::get<2>(*pParam) = (char*)imageHead.c_str(); //std::get<3>(*pParam) = (char*)resContext.encode(); //std::get<4>(*pParam) = pFrameBuff; //std::get<5>(*pParam) = FrameSize; //std::get<6>(*pParam) = pDeviceFrom; //std::get<7>(*pParam) = m_arrImgeProcessDevices[x]; return 0; } /// /// /// /// /// /// /// /// /// int CanModelDPC::ImageRrocess(int Type, string& imageHead, ResDataObject& resContext, char* pFrameBuff, DWORD FrameSize, CanModelDevice* pDeviceFrom) { //mLog::FINFO("Begin"); //std::vector threads; if (m_arrImgeFunc.size() <= 0) return 0; char* context = (char*)resContext.encode(); char* header = (char*)imageHead.c_str(); HANDLE thread = INVALID_HANDLE_VALUE; //for (int x = 0; x < m_arrImgeFunc.size(); x++) { DWORD dwWait = WaitForMultipleObjects(MAX_IMG_THREAD + 1, g_hIdleEvent, FALSE, INFINITE); //mLog::FINFO("Wait for ImageProcessThrad Idle return {$}", dwWait); if (dwWait != WAIT_TIMEOUT && dwWait >= WAIT_OBJECT_0 && dwWait < WAIT_OBJECT_0 + MAX_IMG_THREAD) { imgFuncThreadParams* pParam = g_paramImgThread + (dwWait - WAIT_OBJECT_0); std::get<0>(*pParam) = m_arrImgeFunc.size(); std::get<1>(*pParam) = m_arrImgeFunc.data(); std::get<2>(*pParam) = Type; std::get<3>(*pParam) = header; std::get<4>(*pParam) = context; std::get<5>(*pParam) = pFrameBuff; std::get<6>(*pParam) = FrameSize; std::get<7>(*pParam) = pDeviceFrom; std::get<8>(*pParam) = (LogicDevice**)m_arrImgeProcessDevices.data(); //mLog::FINFO("Notify ImageProcessThread [{$}] work ", dwWait - WAIT_OBJECT_0); SetEvent(g_hDataReadyEvent[dwWait - WAIT_OBJECT_0]); //等待线程 读取完数据 ,就可以下一个 //mLog::FINFO("Start Wait {$} Thread to Read Data.", m_arrImgeFunc.size()); DWORD dwRet = WaitForSingleObject(g_hDataReaded[dwWait - WAIT_OBJECT_0], 4000); if (dwRet == WAIT_OBJECT_0) //mLog::FINFO("Over Succeded with ret {$}", dwRet); else //mLog::FERROR("Over Timeout with ret {$}", dwRet); } else { //mLog::FERROR("No Process this Iamge with ret {$}", dwWait); } } //if (m_arrImgeFunc != nullptr) // return m_arrImgeFunc(Type, imageHead, (char*)resContext.encode(), pFrameBuff, FrameSize, pDeviceFrom, m_arrImgeProcessDevices); return m_arrImgeFunc.size(); } /// /// /// /// /// /// int CanModelDPC::NotifyMessageProcess(ResDataObject& resNotify, CanModelDevice* pDeviceFrom) { //mLog::FINFO("Begin"); ResDataObject resResp; RET_STATUS ret = RET_FAILED; //if (m_arrMessageProcessDevices != nullptr) for(int x=0;x< m_arrMessageProcessDevices.size();x++) { ret = m_arrMessageProcessDevices[x]->Request(&resNotify, &resResp); } //if (m_arrImgeProcessDevices != nullptr) for(int x=0;x< m_arrImgeProcessDevices.size();x++) { ret = m_arrImgeProcessDevices[x]->Request(&resNotify, &resResp); } //mLog::FINFO("End"); return ret ; } void InitLogicDevice(LogicDevice* p, string guidname) { } PVOID CanModelDPC::LoadLogicDevices() { std::cout << "**************** CanModelDPC :: LoadLogicDevices" << std::endl; //mLog::FINFO( "Load Logic Devices"); int nDeviceNumber = 1; string filepath = GetDriverConfigFilePath(); ResDataObject Config; string imgLogicDevice, noImgLogicDevice; std::cout << "**************** CanModelDPC Load Config " << filepath << std::endl; if (Config.loadFile(filepath.c_str())) { int nHaveDeviceNumber = (int)Config["CONFIGURATION"].GetKeyCount("DeviceNumber"); if (nHaveDeviceNumber > 0) { nDeviceNumber = Config["CONFIGURATION"]["DeviceNumber"]; //mLog::FINFO("Have {$} Devices", nDeviceNumber); } else { //mLog::FWARN("Have no DeviceNumber Attribute"); } int nHaveImgLogicDevice = (int)Config["CONFIGURATION"].GetKeyCount("ImgeProcessDevice"); if (nHaveImgLogicDevice > 0) { int first = Config["CONFIGURATION"].GetFirstOf("ImgeProcessDevice"); while (first != -1) { imgLogicDevice = (const char*)Config["CONFIGURATION"][first]; if (imgLogicDevice.length() > 0) { //图像处理逻辑设备 LoadVirtualDevice(imgLogicDevice.c_str(), true); } first = Config["CONFIGURATION"].GetNextOf("ImgeProcessDevice", first); } } int nHaveNoneImgLogicDevice = (int)Config["CONFIGURATION"].GetKeyCount("MessageProcessDevice"); if (nHaveNoneImgLogicDevice > 0) { int first = Config["CONFIGURATION"].GetFirstOf("MessageProcessDevice"); while (first != -1) { imgLogicDevice = (const char*)Config["CONFIGURATION"][first]; if (imgLogicDevice.length() > 0) { //图像处理逻辑设备 LoadVirtualDevice(imgLogicDevice.c_str(), false); } first = Config["CONFIGURATION"].GetNextOf("MessageProcessDevice", first); } //noImgLogicDevice = (const char*)Config["CONFIGURATION"]["MessageProcessDevice"]; } } else { //mLog::FERROR("Load config file failed {$}",filepath.c_str()); } DevTree *pTree = (DevTree *)GetDeviceTree(); //imgLogicDevice "VirtualDevice/ABS/ABSX64.dll" //m_arrImgeProcessDevices = nullptr; //if (imgLogicDevice.length() > 0) //{ // //图像处理逻辑设备 // LoadVirtualDevice(imgLogicDevice.c_str(), true); //} //noImgLogicDevice "VirtualDevice/AGD/AGDX64.dll" //m_arrMessageProcessDevices = nullptr; //if (noImgLogicDevice.length() > 0) //{ // //非图像处理设备 // LoadVirtualDevice(noImgLogicDevice.c_str()); //} for (int i = 0; i < nDeviceNumber; i++) { CanModelDevice *p = new CanModelDevice(); std::cout << " ****************CanModelDPC Try new Device " << i << " of " << nDeviceNumber << std::endl; auto pIoDevice = m_NewDevManager->CreateDevice(i); if (pIoDevice) { GUID guid2; string guidname; //((LogicDevice*)pChild)->GetDeviceType(guid); //bool bget = pIoDevice->GetDeviceType(guid2); guidname = pIoDevice->GetGUID(); //guid_2_string(guid2, guidname); ResDataObject subpath; subpath = (guidname).c_str(); ResDataObject probe,conn_usless; Device_Probe(probe); //此时知道宿主设备是谁,如果Generator/Detector // string hostName; bool isMain = false; if (probe.GetKeyCount("MajorID") > 0) { //找到宿主 hostName = "CCOS/DEVICE/" + string((const char* )probe["MajorID"]); } string fullpath = MakeDevicePath(probe, conn_usless, subpath); string ccospath = MakeCcosPath(probe, conn_usless, subpath, false); if (hostName.length() > 0) { if (ccospath.substr(0, hostName.length()) == hostName) { //宿主设备 isMain = true; //mLog::FINFO("Got MainHost {$} of {$}", hostName, ccospath); } } if (isMain && m_MainHostDevice == nullptr) { m_MainHostDevice = p; //mLog::FINFO("Add ImageProcess Deivce : {$} ", m_arrImgeProcessDevices.size()); //嵌入式设备加载 for (int x = 0; x < m_arrImgeProcessDevices.size(); x++) { GUID guid2; string guidname; m_arrImgeProcessDevices[x]->GetDeviceType(guid2); guid_2_string(guid2, guidname); ResDataObject subpath; subpath = (guidname).c_str(); ResDataObject probe, conn_usless; Device_Probe(probe); string fullpatht = MakeDevicePath(probe, conn_usless, subpath); string ccospatht = MakeCcosPath(probe, conn_usless, subpath, false); m_arrImgeProcessDevices[x]->SetClientRootID(fullpatht.c_str(), ccospatht.c_str()); m_arrImgeProcessDevices[x]->CompleteInit(); pTree->Add((PVOID)(m_arrImgeProcessDevices[x]), TYPE_DEVICE); //mLog::FINFO("Try add ccos child {$} ", ccospatht); m_MainHostDevice->AddCcosChildren(m_arrImgeProcessDevices[x], ccospatht.c_str()); } //mLog::FINFO("Add MessageProcess Deivce : {$} ", m_arrImgeProcessDevices.size()); //if (m_arrMessageProcessDevices != nullptr) for (int x = 0; x < m_arrMessageProcessDevices.size(); x++) { GUID guid2; string guidname; m_arrMessageProcessDevices[x]->GetDeviceType(guid2); guid_2_string(guid2, guidname); ResDataObject subpath; subpath = (guidname).c_str(); ResDataObject probe, conn_usless; Device_Probe(probe); string fullpatht = MakeDevicePath(probe, conn_usless, subpath); string ccospatht = MakeCcosPath(probe, conn_usless, subpath, false); m_arrMessageProcessDevices[x]->SetClientRootID(fullpatht.c_str(), ccospatht.c_str()); m_arrMessageProcessDevices[x]->CompleteInit(); pTree->Add((PVOID)(m_arrMessageProcessDevices[x]), TYPE_DEVICE); //mLog::FINFO("Try add ccos child {$} ", ccospatht); m_MainHostDevice->AddCcosChildren(m_arrMessageProcessDevices[x], ccospatht.c_str()); } } //pDevice->SetEbusRoot(fullpath.c_str()); p->SetClientRootID(fullpath.c_str(), ccospath.c_str()); //mLog::FINFO(" SetClientRootID ", ccospath); //p->SetClientRootID(); //mLog::FINFO("Get IoDevice Succeed"); p->SetDrvDPC(this); HANDLE DisconnectEvt = GetPassiveDisConnectEvtHandle(); //p->ConnectMQTTServer(); p->Init(std::move(pIoDevice), DisconnectEvt); //p->SubscribeAction(); //mLog::FINFO("Create IoDevice Succeed"); } else { //mLog::FERROR("Create IoDevice Failed"); delete p; return NULL; } //*/ ResDataObject resPri; string strPri; for (int x = 1; x < m_arrImgeProcessDevices.size(); x++) { for (int y = 0; y < x; y++) { unsigned int xPri, yPri; xPri = yPri = -1; if (m_arrImgeProcessDevices[x]->DevGet("", "ImageProcessIndex", resPri) == RET_SUCCEED) { strPri = (const char*)resPri; if (strPri.length() > 0) xPri = atoi(strPri.c_str()); //mLog::FINFO("Vd {$} ImageProcessIdex=[{$}]", m_arrImgeProcessDevices[x]->GetCcosRootPath(), strPri); } if (m_arrImgeProcessDevices[y]->DevGet("", "ImageProcessIndex", resPri) == RET_SUCCEED) { strPri = (const char*)resPri; if (strPri.length() > 0) xPri = atoi(strPri.c_str()); //mLog::FINFO("Vd {$} ImageProcessIdex=[{$}]", m_arrImgeProcessDevices[y]->GetCcosRootPath(), strPri); } if (xPri < yPri) { auto* pTemp = m_arrImgeProcessDevices[x]; auto fTemp = m_arrImgeFunc[x]; m_arrImgeProcessDevices[x] = m_arrImgeProcessDevices[y]; m_arrImgeProcessDevices[y] = pTemp; m_arrImgeFunc[x] = m_arrImgeFunc[y]; m_arrImgeFunc[y] = fTemp; //mLog::FINFO("Exchange Vd [{$}] <=> [{$}]", x, y); } } } //*/ LogicDevice *pret = (LogicDevice *)p; pTree->Add((PVOID)pret, TYPE_DEVICE); LogicDevice::AddEbusChildren(p, ""); } return (PVOID)pTree; } void CanModelDPC::UnloadLogicDevices() { //mLog::FINFO( "UnLoad Logic Devices"); DevTree *pTree = (DevTree *)GetDeviceTree(); size_t Size = pTree->size(); for (size_t i = 0; i < Size; i++) { DevTreeNode node = (*pTree)[i]; if (node.m_NodeType == TYPE_DEVICE) { CanModelDevice *pdev = (CanModelDevice*)node.m_pObject; delete pdev; } else { //tree dev //do not copy this!!!! //UnloadLogicDevices(node.m_pObject); } } pTree->clear(); //mLog::FINFO( "UnLoad Over"); } RET_STATUS DATA_ACTION CanModelDPC::GetDeviceConfig(ResDataObject PARAM_OUT* pDeviceConfig) { if ((*m_config).GetPropties().size() > 0) { //mLog::FERROR("GetDeviceConfig has module config do not return anything."); return RET_FAILED; } //mLog::FINFO( "GetDeviceConfig start"); std::string strDeviceConfig; if (m_NewDevManager->GetDeviceConfig(strDeviceConfig)) { pDeviceConfig->decode(strDeviceConfig.c_str()); //mLog::FINFO( "GetDeviceConfig ok {$}", strDeviceConfig); } else { //mLog::FERROR( "GetDeviceConfig failed"); return RET_FAILED; } //mLog::FINFO( "GetDeviceConfig Over"); return RET_SUCCEED; } RET_STATUS DATA_ACTION CanModelDPC::SetDeviceConfig(ResDataObject PARAM_IN* DeviceConfig) { if ((*m_config).GetPropties().size() > 0) { return RET_FAILED; } //mLog::FINFO( "SetDeviceConfig start"); std::string strDeviceConfig = DeviceConfig->encode(); if (m_NewDevManager->SetDeviceConfig(strDeviceConfig)) { } else { return RET_FAILED; } //mLog::FINFO( "SetDeviceConfig Over"); return RET_SUCCEED; }