CDI.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554
  1. // CDI.cpp : 定义 DLL 应用程序的导出函数。
  2. //
  3. #include "CDI.h"
  4. #include "DrvTree.h"
  5. #include "common_api.h"
  6. #include "LocalConfig.h"
  7. //#include "ebus.h"
  8. #include "DriverManager.h"
  9. //#include "DevBusManager.h"
  10. #include "DeviceBus.h"
  11. #include "PacketAnalizer.h"
  12. #include "PacketCommon.h"
  13. //#include "ClientManager.h"
  14. #include "HandleManager.h"
  15. #include "BusUnitClient.h"
  16. #include "ProcThreadManager.h"
  17. //#include "ShareMemory_IF.h"
  18. #include "Crc64.h"
  19. //#include "ShareMemory_Server.h"
  20. //#include "ShareMemory_Client.h"
  21. //#include "CcosConsoleScript.h"
  22. //#include "APlatformDcs.h"
  23. #include "ModuleClient.h"
  24. #include <iostream>
  25. #include <unistd.h>
  26. #include <limits.h>
  27. #include <sys/types.h>
  28. #include <sys/wait.h>
  29. #include <sys/time.h>
  30. #include <sys/file.h>
  31. #include <cstring>
  32. #include <pthread.h>
  33. #include <fcntl.h>
  34. #include <cctype>
  35. #include <algorithm>
  36. #include "debug.h"
  37. #include "LogLocalHelper.h"
  38. #include "Log4CPP.h"
  39. //globle names
  40. CDI g_CDI;
  41. CDI::CDI()
  42. {
  43. m_MasterProcId = 0;
  44. m_ExitHandle = LinuxEvent::CreateEvent(LinuxEvent::MANUAL_RESET,false);
  45. m_prootClient = NULL;
  46. //m_DCSMap = NULL;
  47. return;
  48. }
  49. CDI::~CDI()
  50. {
  51. if (m_prootClient)
  52. {
  53. delete ((BusUnitClient*)m_prootClient);
  54. m_prootClient = NULL;
  55. }
  56. return;
  57. }
  58. /*
  59. INT CDI::LoadAllDCS()
  60. {
  61. //find all *.DCS
  62. m_DCSMap = new map<HMODULE,CcosConsoleScript*>();
  63. string basedll = string(DCSBASE) + string(".dcs.dll");
  64. string procdir = GetProcessDirectory();
  65. vector<string> filelist;
  66. FindSubFiles(procdir, filelist, true, "*.dcs.dll");
  67. for (size_t i = 0; i < filelist.size(); i++)
  68. {
  69. std::string::size_type pos = 0;
  70. //skip me first.DCSBASE.DCS
  71. if ((pos = filelist[i].find(basedll, pos)) != std::string::npos)
  72. {
  73. continue;
  74. }
  75. HMODULE dllhandle = LoadLibrary(filelist[i].c_str());
  76. if (dllhandle)
  77. {
  78. LOADDCS loadfunc = (LOADDCS)GetProcAddress(dllhandle, "LoadDCS");
  79. UNLOADDCS unloadfunc = (UNLOADDCS)GetProcAddress(dllhandle, "UnLoadDCS");
  80. if (loadfunc && unloadfunc)
  81. {
  82. CcosConsoleScript *pDCS = loadfunc();
  83. if (pDCS)
  84. {
  85. (*((map<HMODULE, CcosConsoleScript*> *)m_DCSMap))[dllhandle] = pDCS;
  86. }
  87. else
  88. {
  89. printf("LoadDCS failed.file:%s", filelist[i].c_str());
  90. DebugPrint("LoadDCS failed.file:%s", filelist[i].c_str());
  91. }
  92. }
  93. else
  94. {
  95. printf("no LoadDCS/UnLoadDCS function in dllfile:%s", filelist[i].c_str());
  96. DebugPrint("no LoadDCS/UnLoadDCS function in dllfile:%s", filelist[i].c_str());
  97. }
  98. }
  99. else
  100. {
  101. printf("\n\nError at load Dcs file.ErrorCode:%d\n\nDcsFile:%s\n\n",GetLastError(), filelist[i].c_str());
  102. DebugPrint("\n\nError at load Dcs file.ErrorCode:%d\n\nDcsFile:%s\n\n", GetLastError(), filelist[i].c_str());
  103. }
  104. //CcosConsoleScript *pDCS = new APlatformDcs();
  105. //if (pDCS)
  106. //{
  107. // //map it
  108. // (*((vector<CcosConsoleScript*> *)m_DCSMap)).push_back(pDCS);
  109. //}
  110. }
  111. return 0;
  112. }
  113. INT CDI::UnLoadAllDCS()
  114. {
  115. if (m_DCSMap)
  116. {
  117. map<HMODULE, CcosConsoleScript*>::iterator iter = (*((map<HMODULE, CcosConsoleScript*> *)m_DCSMap)).begin();
  118. while (iter != (*((map<HMODULE, CcosConsoleScript*> *)m_DCSMap)).end())
  119. {
  120. UNLOADDCS unloadfunc = (UNLOADDCS)GetProcAddress(iter->first, "UnLoadDCS");
  121. if (unloadfunc)
  122. {
  123. unloadfunc(iter->second);
  124. }
  125. ++iter;
  126. }
  127. (*((map<HMODULE, CcosConsoleScript*> *)m_DCSMap)).clear();
  128. delete (map<HMODULE, CcosConsoleScript*> *)m_DCSMap;
  129. m_DCSMap = NULL;
  130. }
  131. return 0;
  132. }
  133. */
  134. INT CDI::CommandInput(const char *pszCmd)
  135. {
  136. return 0;
  137. /*
  138. bool hit = false;
  139. if (m_DCSMap)
  140. {
  141. if (pszCmd && strlen(pszCmd) > 0)
  142. {
  143. string exp = pszCmd;
  144. //makeLowerStr(exp);
  145. ResDataObject Req = CcosConsoleScript::SeperateCommand(pszCmd);
  146. if (Req.size() > 0)
  147. {
  148. map<HMODULE, CcosConsoleScript*>::iterator iter = (*((map<HMODULE, CcosConsoleScript*> *)m_DCSMap)).begin();
  149. while (iter != (*((map<HMODULE, CcosConsoleScript*> *)m_DCSMap)).end())
  150. {
  151. if (exp == "help")
  152. {
  153. iter->second->Help();
  154. hit = true;
  155. ++iter;
  156. continue;
  157. }
  158. else
  159. {
  160. if (iter->second->Command(Req) == DCS_NOT_SUPPORT)
  161. {
  162. ++iter;
  163. continue;
  164. }
  165. hit = true;
  166. }
  167. break;
  168. ++iter;
  169. }
  170. //for (size_t i = 0; i < (*((vector<CcosConsoleScript*> *)m_DCSMap)).size(); i++)
  171. //{
  172. // if (exp == "help")
  173. // {
  174. // (*((vector<CcosConsoleScript*> *)m_DCSMap))[i]->Help();
  175. // hit = true;
  176. // continue;
  177. // }
  178. // else
  179. // {
  180. // if ((*((vector<CcosConsoleScript*> *)m_DCSMap))[i]->Command(Req) == DCS_NOT_SUPPORT)
  181. // {
  182. // continue;
  183. // }
  184. // hit = true;
  185. // }
  186. // break;
  187. //}
  188. if (hit == false)
  189. {
  190. printf("%s is not right command.plz use help for more info\n", (const char *)Req[0]);
  191. }
  192. return 1;
  193. }
  194. }
  195. }
  196. return 0;*/
  197. }
  198. void CDI::StartMqttServer()
  199. {
  200. return;
  201. char exePath[PATH_MAX];
  202. ssize_t len = readlink("/proc/self/exe", exePath, sizeof(exePath) - 1);
  203. if (len == -1) {
  204. std::cerr << "Failed to get executable path" << std::endl;
  205. return;
  206. }
  207. exePath[len] = '\0';
  208. std::string mqtt_path = exePath;
  209. size_t pos = mqtt_path.find_last_of('/');
  210. if (pos == std::string::npos) {
  211. std::cerr << "Invalid executable path" << std::endl;
  212. return;
  213. }
  214. mqtt_path.erase(pos + 1); // 保留末尾的 '/'
  215. std::string work_dir = mqtt_path + "emqx";
  216. mqtt_path += "emqx/bin/emqx";
  217. std::cout << "Try Start Mqtt Server First.. " << mqtt_path << std::endl;
  218. pid_t pid = fork();
  219. if (pid == 0) { // 子进程
  220. // 重定向标准输出/错误到/dev/null(相当于隐藏输出)
  221. int null_fd = open("/dev/null", O_WRONLY);
  222. dup2(null_fd, STDOUT_FILENO);
  223. dup2(null_fd, STDERR_FILENO);
  224. close(null_fd);
  225. // 准备参数
  226. char* args[] = {
  227. const_cast<char*>("emqx"),
  228. const_cast<char*>("start"),
  229. nullptr
  230. };
  231. // 切换工作目录并执行
  232. chdir(work_dir.c_str());
  233. execv(mqtt_path.c_str(), args);
  234. // 如果execv失败
  235. std::cerr << "execv failed: " << strerror(errno) << std::endl;
  236. _exit(1);
  237. }
  238. else if (pid > 0) { // 父进程
  239. // 非阻塞等待子进程退出
  240. waitpid(pid, nullptr, WNOHANG);
  241. std::cout << "Mqtt server started in background (PID: " << pid << ")" << std::endl;
  242. }
  243. else {
  244. std::cerr << "fork failed: " << strerror(errno) << std::endl;
  245. }
  246. /*
  247. if (!CreateProcess(NULL, // No module name (use command line)
  248. (LPSTR)mqtt_path.c_str(), // Command line
  249. NULL, // Process handle not inheritable
  250. NULL, // Thread handle not inheritable
  251. FALSE, // Set handle inheritance to FALSE
  252. CREATE_NEW_CONSOLE, // No creation flags
  253. NULL, // Use parent's environment block
  254. szFileName,
  255. //pfullWorkPath, // Use parent's starting directory
  256. &si, // Pointer to STARTUPINFO structure
  257. &pinfo) // Pointer to PROCESS_INFORMATION structure
  258. )
  259. {
  260. printf("CreateProcess failed (%d).\n", GetLastError());
  261. printf("Command path :%s\n", mqtt_path);
  262. }*/
  263. }
  264. void* CDI::InitShareMemory(void* pPara)
  265. {
  266. CDI* pCdi = (CDI*)pPara;
  267. //FINFO("Begin");
  268. //CCOS_PROC_TYPE Master = GetConfigMode();
  269. //DWORD dwTick = GetTickCount();
  270. //if (Master == CCOS_PROC_CHANNEL)
  271. //{
  272. // //channel
  273. // if (ShareMemory_ServerStart() == false || ShareMemory_ClientStart() == false)
  274. // {
  275. // FERROR("Can't Start Console Thread.sharememory server start failed.Exit in 3sec");
  276. // sleep(3);
  277. // return 0;
  278. // }
  279. // FINFO( "-*-*-*-* Channel ShareMemory Use Time {$} ms", GetTickCount() - dwTick );
  280. // dwTick = GetTickCount();
  281. //}
  282. //else if (Master == CCOS_PROC_MASTER)
  283. //{
  284. // //main proc
  285. // if (ShareMemory_ClientStart() == false)
  286. // {
  287. // FERROR("Can't Start Console Thread.sharememory client start failed.Exit in 3sec");
  288. // sleep(3);
  289. // return 0;
  290. // }
  291. // std::cout << "-*-*-*-* ShareMemory_ClientStart Use Time" << GetTickCount() - dwTick << " ms" << endl;
  292. // dwTick = GetTickCount();
  293. //}
  294. ////share memory init
  295. //DWORD BigBlockSize, BigBlockCount, SmallBlockSize, SmallBlockCount;
  296. //if (GetShareMemSettings(BigBlockSize, BigBlockCount, SmallBlockSize, SmallBlockCount) == false)
  297. //{
  298. // FERROR("Can't GetShareMemSettings");
  299. // return false;
  300. //}
  301. //if (Init_Circle_SM_IF(BigBlockSize, BigBlockCount, SmallBlockSize, SmallBlockCount) < 0)
  302. //{
  303. // FERROR("Can't Init_Circle_SM_IF");
  304. // return false;
  305. //}
  306. //dwTick = GetTickCount();
  307. return 0;
  308. }
  309. /// <summary>
  310. /// 返回当前所有设备
  311. /// </summary>
  312. /// <param name="pDevices"></param>
  313. /// <param name="nDevNums"></param>
  314. /// <returns></returns>
  315. const char* CDI::GetAllDevice(void** pDevices, int& nDevNums)
  316. {
  317. return g_DrvManager.GetAllDevice(pDevices, nDevNums);
  318. }
  319. bool CDI::InitAs(CCOS_PROC_TYPE Master, UINT64 MasterProcId)
  320. {
  321. //NOT FINISHED YET
  322. //no Slave status
  323. pthread_t hShareMemoryHandle;
  324. ModuleClient hstClient("CDI_NOTIFY", "", "", false);
  325. string devPathNull = "";
  326. string mjrID = GetDeviceID();
  327. mjrID = mjrID.substr(0, mjrID.find_first_of('/'));
  328. if (mjrID.length() <= 0)
  329. mjrID = "Channel";
  330. string topic = "CCOS/HOST/" + mjrID + "/Status/Startup";
  331. DWORD dwTick = GetTickCount();
  332. if (Master == CCOS_PROC_CHANNEL)
  333. {
  334. string strLogPath = GetProcessDirectory() + R"(/Conf/log_config.xml)";
  335. string LogHost = ((string)getLogRootpath()).c_str();
  336. std::string moduleName = "Platform";
  337. bool ret = initLogModule(
  338. LogHost, // 主机名(用于日志路径中的{host}占位符)
  339. moduleName, // 唯一模块名
  340. strLogPath, // 配置文件路径
  341. true // 是否输出到控制台(可选)
  342. );
  343. if (!ret) {
  344. std::cerr << "Log init failed!" << std::endl;
  345. return false;
  346. }
  347. // 绑定当前动态库的模块名(调用自身实现的接口)
  348. CDI_setLocalModuleName(moduleName);
  349. cout << endl << "LogHost = " << LogHost << endl << endl;
  350. FINFO("Code Build datetime [{$} {$}]", __DATE__, __TIME__);
  351. // Linux下使用文件锁实现单实例检测
  352. int lock_fd = open("/tmp/Channel.lock", O_CREAT | O_RDWR, 0666);
  353. if (lock_fd == -1) {
  354. perror("open lock file failed");
  355. return false;
  356. }
  357. if (flock(lock_fd, LOCK_EX | LOCK_NB) == -1) {
  358. if (errno == EWOULDBLOCK) {
  359. printf("Can't Start Console Thread.already exist.Exit in 3sec\n");
  360. close(lock_fd);
  361. sleep(3);
  362. return false;
  363. }
  364. }
  365. //启动MQTTserver 允许多次启动
  366. FINFO("StartMqttServer");
  367. StartMqttServer();
  368. FINFO("StartMqttServer Use Time {$} ", GetTickCount() - dwTick);
  369. dwTick = GetTickCount();
  370. }
  371. else if (Master == CCOS_PROC_MASTER)
  372. {
  373. string strLogPath = GetProcessDirectory() + R"(/Conf/log_config.xml)";
  374. string LogHost = (string)getRootpath();
  375. std::string moduleName = "Platform";
  376. bool ret = initLogModule(
  377. LogHost, // 主机名(用于日志路径中的{host}占位符)
  378. moduleName, // 唯一模块名
  379. strLogPath, // 配置文件路径
  380. true // 是否输出到控制台(可选)
  381. );
  382. if (!ret) {
  383. std::cerr << "Log init failed!" << std::endl;
  384. return false;
  385. }
  386. // 绑定当前动态库的模块名(调用自身实现的接口)
  387. CDI_setLocalModuleName(moduleName);
  388. // 记录日志 - 使用模块特定的宏
  389. cout << endl << "LogHost = " << LogHost << endl << endl;
  390. FINFO("Code Build datetime [{$} {$}]", __DATE__, __TIME__);
  391. if (LogHost.length() <= 1)
  392. {
  393. char szName[256];
  394. sprintf(szName, "/LogicDevice_%08d", getpid());
  395. LogHost = szName;
  396. }
  397. setLogRootpath(LogHost.c_str());
  398. // FINFO("Code Build datetime [{$} {$}]", __DATE__, __TIME__);
  399. std::cout << "Code Build datetime [" << __DATE__ << " " << __TIME__ << "]\n";
  400. //}
  401. //get full proc path
  402. string keyStr,targetStr;
  403. targetStr = "";
  404. string dir = GetProcessDirectory();
  405. transform(dir.begin(), dir.end(), dir.begin(),
  406. [](unsigned char c) { return tolower(c); });
  407. size_t pos = 0;
  408. while ((pos = dir.find('\\', pos)) != string::npos) {
  409. dir.replace(pos, 1, "/");
  410. }
  411. //make md5
  412. unsigned char digest[35];
  413. memset(digest, 0, 35);
  414. }
  415. hstClient.Open(devPathNull.c_str(), ALL_ACCESS);
  416. std::cout << "hstClient.Notify" << "\n";
  417. hstClient.Notify(topic.c_str(), GetDeviceID().c_str(), "Startup", "Status", "Init started");
  418. SetConfigMode(Master);
  419. //std::cout << "Start backgroud InitShareMemory " << "\n";
  420. //{
  421. // pthread_attr_t attr;
  422. // pthread_attr_init(&attr);
  423. // pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  424. // // 创建线程
  425. // if (pthread_create(&hShareMemoryHandle, &attr,
  426. // InitShareMemory, this) != 0) {
  427. // perror("pthread_create failed");
  428. // return false;
  429. // }
  430. // pthread_attr_destroy(&attr);
  431. //}
  432. FINFO("CDI ");
  433. //Master & Channel
  434. hstClient.Notify(topic.c_str(), GetDeviceID().c_str(), "Startup", "Status", "Load Root Driver");
  435. int nGrpcPort = 9000;
  436. if (Master == CCOS_PROC_MASTER || Master == CCOS_PROC_CHANNEL)
  437. {
  438. FINFO("CDI InitAs RPROC_TYPE {$}", (int) Master);
  439. std::cout << "CDI InitAs RPROC_TYPE " << Master << std::endl;
  440. //load root driver
  441. FINFO("g_DrvManager.LoadRootDrv ");
  442. if (g_DrvManager.LoadRootDrv() == false)
  443. {
  444. //log here
  445. //
  446. std::cout << "Failed to load root drv." <<std::endl;
  447. FINFO("Failed to load root drv.");
  448. UnLoadAll();
  449. return false;
  450. }
  451. ResDataObject rootRes;
  452. LogicDevice* pDev[10];
  453. int nNum = 0;
  454. g_DrvManager.GetAllDevice((void**)pDev, nNum);
  455. std::cout << "Now Add Deivce Num is " << nNum << std::endl;
  456. FINFO("Now Add Deivce Num is {$}", nNum);
  457. for (int x = 0; x < nNum; x++)
  458. {
  459. string path = pDev[x]->GetCcosRootPath();
  460. FINFO("[{$}] Dev is {$}", x, path);
  461. std::cout << "[" << x << "] Dev is " << path << std::endl;
  462. // CCOS/HOST/
  463. if (path.length() > 10 && path.substr(0, 10) == "CCOS/HOST/")
  464. {
  465. pDev[x]->GetDeviceResource(&rootRes);
  466. std::cout << "Dev " << path << " resource is " << rootRes.encode() << std::endl;
  467. FINFO("Dev {$} resource is {$}", path, rootRes.encode());
  468. nGrpcPort = rootRes["Attribute"]["GrpcPort"];
  469. FINFO("This Driver GRPC Port is {$}", nGrpcPort);
  470. std::cout << "This Driver GRPC Port is " << nGrpcPort << std::endl;
  471. }
  472. }
  473. std::cout << "g_DrvManager.LoadRootDrv over."<< std::endl;
  474. FINFO("g_DrvManager.LoadRootDrv over.");
  475. }
  476. else {
  477. std::cout << "CDI InitAs RPROC_TYPE " << Master << std::endl;
  478. FINFO("CDI InitAs RPROC_TYPE {$}", (int)Master);
  479. }
  480. std::cout << "CDI -*-*-*-* g_DrvManager.LoadRootDrv() Use Time " << GetTickCount() - dwTick<<" ms" << std::endl;
  481. FINFO("CDI -*-*-*-* g_DrvManager.LoadRootDrv() Use Time {$} ms", GetTickCount() - dwTick);
  482. dwTick = GetTickCount();
  483. //make sure root exist
  484. //LoadAllDCS();
  485. //load bus driver
  486. hstClient.Notify(topic.c_str(), GetDeviceID().c_str(), "Startup", "Status", "Load Bus Driver");
  487. FINFO("CDI::InitAs LoadBusDrv ");
  488. if (LoadBusDrv() == false)
  489. {
  490. //log here
  491. //
  492. std::cout << "Failed to load bus drv."<< std::endl;
  493. FINFO("Failed to load bus drv.");
  494. UnLoadAll();
  495. return false;
  496. }
  497. std::cout << "LoadBusDrv use time " << GetTickCount() - dwTick << std::endl;
  498. FINFO("LoadBusDrv use time {$}", GetTickCount() - dwTick);
  499. dwTick = GetTickCount();
  500. FINFO("CDI InitAs g_DrvTree.StartThread");
  501. //start monitoring root driver,and update drvtree
  502. if (g_DrvTree.StartThread() == false)
  503. {
  504. //log here
  505. std::cout << "Failed to start drv tree thread." << std::endl;
  506. FINFO("Failed to start drv tree thread.");
  507. UnLoadAll();
  508. return false;
  509. }
  510. std::cout << "CDI g_DrvTree.StartThread Use Time " << GetTickCount() - dwTick << std::endl;
  511. FINFO("CDI g_DrvTree.StartThread Use Time {$} ms", GetTickCount() - dwTick);
  512. dwTick = GetTickCount();
  513. /*
  514. if (Master == CCOS_PROC_CLIENT)
  515. {
  516. //ccos client
  517. assert(0);//NOT FINISHED YET
  518. }
  519. else */
  520. static int idx_test = 0;
  521. if (Master == CCOS_PROC_CHANNEL)
  522. {
  523. //ccos channel
  524. FINFO("CDI InitAs g_DrvManager.UpdateRootDrvStatus");
  525. if (g_DrvManager.UpdateRootDrvStatus(1))
  526. {
  527. FINFO("CDI g_DrvManager.UpdateRootDrvStatus Use Time {$} ms", GetTickCount() - dwTick);
  528. dwTick = GetTickCount();
  529. FINFO("CDI InitBusUnit");
  530. if (InitBusUnit())
  531. {
  532. FINFO("CDI InitBusUnit Use Time {$} ms ", GetTickCount() - dwTick );
  533. dwTick = GetTickCount();
  534. //等待共享内存线程结束
  535. //struct timespec ts;
  536. //clock_gettime(CLOCK_REALTIME, &ts);
  537. //ts.tv_sec += 2; // 2秒超时
  538. //// 使用pthread_timedjoin_np实现超时等待
  539. //if (pthread_timedjoin_np(hShareMemoryHandle, nullptr, &ts) != 0) {
  540. // fprintf(stderr, "InitShareMemory thread timeout\n");
  541. //}
  542. FINFO("CDI WaitForSingleObject hShareMemoryHandle over.");
  543. return true;
  544. }
  545. UnLoadAll();
  546. }
  547. return false;
  548. }
  549. else if (Master == CCOS_PROC_MASTER)
  550. {
  551. //load all drivers in pocket
  552. //ResDataObject filelist;
  553. //if (GetDriverConfigFiles(filelist))
  554. //{
  555. // for (size_t i = 0; i < filelist.size(); i++)
  556. // {
  557. // //1.load drv
  558. // if (g_DrvManager.LoadDriver(filelist.GetKey(i)) == false)
  559. // {
  560. // //log here
  561. // printf("Failed Load Drver:%s\n", filelist.GetKey(i));
  562. // }
  563. // //printf("Load %s succeed\n", filelist.GetKey(i));
  564. // }
  565. //}
  566. size_t idx = 0;
  567. const char *pszConfigDriverpath = GetDriverConfigFilepath(idx);
  568. std::cout << "CDI InitAs g_DrvManager.LoadDriver(pszConfigDriverpath) " << idx << std::endl;
  569. FINFO("CDI InitAs g_DrvManager.LoadDriver(pszConfigDriverpath) {$}", idx);
  570. while (pszConfigDriverpath)
  571. {
  572. FINFO("CDI InitAs g_DrvManager.LoadDriver: {$}", pszConfigDriverpath);
  573. std::cout << "CDI InitAs g_DrvManager.LoadDriver:" << pszConfigDriverpath << std::endl;
  574. string msg = "Load Main Driver ";
  575. msg += pszConfigDriverpath;
  576. hstClient.Notify(topic.c_str(), GetDeviceID().c_str(), "Startup", "Status",msg.c_str() );
  577. if (g_DrvManager.LoadDriver(pszConfigDriverpath) == false)
  578. {
  579. //log here
  580. FINFO("Failed Load Drver:{$}", pszConfigDriverpath);
  581. }
  582. else
  583. {
  584. std::cout << "Load " << pszConfigDriverpath<< "succeed" << std::endl;
  585. FINFO("Load {$} succeed", pszConfigDriverpath);
  586. }
  587. FINFO("CDI g_DrvManager.LoadDriver Use Time {$} ms", GetTickCount() - dwTick );
  588. dwTick = GetTickCount();
  589. pszConfigDriverpath = GetDriverConfigFilepath(++idx);
  590. }
  591. std::cout << "CDI UpdateRootDrvStatus" <<std::endl;
  592. FINFO("CDI UpdateRootDrvStatus");
  593. if (g_DrvManager.UpdateRootDrvStatus(1))
  594. {
  595. FINFO("CDI g_DrvManager.UpdateRootDrvStatus Use Time {$} ms", GetTickCount() - dwTick);
  596. dwTick = GetTickCount();
  597. FINFO("CDI InitBusUnit");
  598. std::cout << "CDI InitBusUnit" << std::endl;
  599. if (InitBusUnit())
  600. {
  601. FINFO("CDI InitBusUnit Use Time {$} ms", GetTickCount() - dwTick);
  602. dwTick = GetTickCount();
  603. ////等待共享内存线程结束
  604. //struct timespec ts;
  605. //clock_gettime(CLOCK_REALTIME, &ts);
  606. //ts.tv_sec += 2; // 2秒超时
  607. //// 使用pthread_timedjoin_np实现超时等待
  608. //if (pthread_timedjoin_np(hShareMemoryHandle, nullptr, &ts) != 0) {
  609. // fprintf(stderr, "InitShareMemory thread timeout\n");
  610. //}
  611. //std::cout << "CDI WaitForSingleObject(hShareMemoryHandle over" << std::endl;
  612. FINFO("CDI WaitForSingleObject(hShareMemoryHandle over");
  613. idx_test++;
  614. std::cout << "CDI g_DrvManager.DynDriverInitLoadAll "<< idx_test << std::endl;
  615. FINFO("CDI g_DrvManager.DynDriverInitLoadAll {$}", idx_test);
  616. g_DrvManager.DynDriverInitLoadAll();
  617. hstClient.Notify(topic.c_str(), GetDeviceID().c_str(), "Startup", "Status", "Start OK");
  618. topic = "CCOS/HOST/" + mjrID + "/Status/Running";
  619. string runMsg = "{\"GrpcPort\":" + to_string(nGrpcPort) + "}";
  620. hstClient.Notify(topic.c_str(), (string("CCOS/DRIVER/")+ GetDeviceID()).c_str(), "Running", "Status", runMsg.c_str());
  621. FINFO("CDI DynDriverInitLoadAll over. Started ok.");
  622. std::cout << "CDI DynDriverInitLoadAll over. Started ok." << std::endl;
  623. return true;
  624. }
  625. else
  626. {
  627. FINFO("Failed to init bus unit.");
  628. }
  629. }
  630. std::cout << "CDI UnLoadAll" << std::endl;
  631. FINFO("CDI UnLoadAll");
  632. UnLoadAll();
  633. return false;
  634. }
  635. /*else if (Master == CCOS_PROC_SLAVE)
  636. {
  637. //slave
  638. assert(0);//NOT FINISHED YET
  639. }*/
  640. std::cout << "-*-*-*-* Shoud not Execute, execpet somting failed..... Use Time" << GetTickCount() - dwTick << " ms" << endl;
  641. dwTick = GetTickCount();
  642. if (InitBusUnit())
  643. {
  644. std::cout << "-*-*-*-* InitBusUnit again Use Time" << GetTickCount() - dwTick << " ms" << endl;
  645. dwTick = GetTickCount();
  646. //等待共享内存线程结束
  647. //struct timespec ts;
  648. //clock_gettime(CLOCK_REALTIME, &ts);
  649. //ts.tv_sec += 2; // 2秒超时
  650. //// 使用pthread_timedjoin_np实现超时等待
  651. //if (pthread_timedjoin_np(hShareMemoryHandle, nullptr, &ts) != 0) {
  652. // fprintf(stderr, "InitShareMemory thread timeout\n");
  653. //}
  654. idx_test++;
  655. std::cout << "- *-*-*-* ========= g_DrvManager.DynDriverInitLoadAll 2 " << idx_test << endl;
  656. g_DrvManager.DynDriverInitLoadAll();
  657. return true;
  658. }
  659. UnLoadAll();
  660. return false;
  661. }
  662. /*
  663. bool CDI::ReceivedFromLocalBus(ResDataObject &packet)
  664. {
  665. bool ret = true;
  666. RES_FINFO(packet, "Packet from Local Bus");
  667. //correct it's direction
  668. try {
  669. PacketAnalizer::UpdatePacketRoute(packet, CCOS_PACKET_ROUTE_LOCAL);
  670. //do the normal dispatch
  671. ret = ReceivedFromBus(packet);
  672. }
  673. catch (...)
  674. {
  675. ret = false;
  676. }
  677. return ret;
  678. }
  679. bool CDI::ReceivedFromEthBus(ResDataObject &packet)
  680. {
  681. bool ret = true;
  682. RES_FINFO(packet, "Packet from Eth Bus");
  683. //correct it's direction
  684. try {
  685. PacketAnalizer::UpdatePacketRoute(packet, CCOS_PACKET_ROUTE_ETH);
  686. //do the normal dispatch
  687. ret = ReceivedFromBus(packet);
  688. }
  689. catch (...)
  690. {
  691. ret = false;
  692. }
  693. return ret;
  694. }
  695. */
  696. bool CDI::SendCcosPacket(ResDataObject& packet)
  697. {
  698. CCOS_PACKET_ROUTE Route;
  699. if (!PacketAnalizer::GetPacketRoute(&packet, Route))
  700. return false;
  701. bool sendtoLocalMachine = false;
  702. bool sendBlockData = false;
  703. //packet cmd
  704. PACKET_CMD cmd = PacketAnalizer::GetPacketCmd(&packet);
  705. if (cmd == PACKET_CMD_DATA)
  706. {
  707. sendBlockData = true;
  708. }
  709. string DesBusId;
  710. if (!PacketAnalizer::GetDestinationBusId(packet, DesBusId))
  711. {
  712. return false;
  713. }
  714. //Precaculate direction
  715. if (Route == CCOS_PACKET_ROUTE_ANY)
  716. {
  717. //choose one
  718. Route = GetBusIdDirection(DesBusId);
  719. }
  720. //caculate again
  721. if (Route == CCOS_PACKET_ROUTE_LOCAL)
  722. {
  723. //target in this machine
  724. sendtoLocalMachine = true;
  725. }
  726. else if (Route == CCOS_PACKET_ROUTE_ETH)
  727. {
  728. //target is not in this machine
  729. }
  730. else if (Route == CCOS_PACKET_ROUTE_ANY)
  731. {
  732. //if still any direction,then try local and try eth
  733. //local first
  734. if (DoSendPacket(packet, true, sendBlockData, DesBusId) == CMD_ECHO_OK)
  735. {
  736. return CMD_ECHO_OK;
  737. }
  738. //try eth
  739. return DoSendPacket(packet, false, sendBlockData, DesBusId);
  740. }
  741. else
  742. {
  743. //ignore
  744. return CMD_ECHO_IGNORE;
  745. }
  746. //do send
  747. return DoSendPacket(packet, sendtoLocalMachine, sendBlockData, DesBusId);
  748. }
  749. //1.command comes from client
  750. //2.dispatch command comes from device
  751. bool CDI::ReceivedFromBus(ResDataObject &packet)
  752. {
  753. bool ret = true;
  754. /*
  755. //check destination & dispatch
  756. CMD_ECHO DispatchRet = DispatchPacket(packet);
  757. if (DispatchRet == CMD_ECHO_OK)
  758. {
  759. //log here
  760. FINFO("Trasform Succeed");
  761. return true;
  762. }
  763. else if (DispatchRet == CMD_ECHO_IGNORE)
  764. {
  765. FINFO("Ignore Packet");
  766. return false;
  767. }
  768. else if (DispatchRet == CMD_ECHO_NG)//this proc
  769. {
  770. //dispatch to the process
  771. FINFO("Dispatch to Local");
  772. DispatchRet = DispatchToLocal(packet);
  773. if (DispatchRet == CMD_ECHO_OK)
  774. {
  775. FINFO("Dispatch to Local Succeed");
  776. return true;
  777. }
  778. else if (DispatchRet == CMD_ECHO_NG)//device access failed
  779. {
  780. //request in
  781. //make failed Res and send it
  782. FERROR("Dispatch to Local Failed.no access right");
  783. Ex_ResponseRemoteClientReq(packet, RET_FAILED, "no access right");
  784. return true;//保持连线
  785. }
  786. else if (DispatchRet == CMD_ECHO_NOTARGET)
  787. {
  788. //deal later
  789. FERROR("Dispatch to Local Failed.no target exist");
  790. }
  791. else
  792. {
  793. //ignore
  794. FERROR("Dispatch to Local Failed.no idea....");
  795. }
  796. }
  797. if (DispatchRet == CMD_ECHO_NOTARGET)
  798. {
  799. PACKET_TYPE type = PacketAnalizer::GetPacketType(&packet);
  800. PACKET_CMD cmd = PacketAnalizer::GetPacketCmd(&packet);
  801. //failed send packet
  802. switch (type)
  803. {
  804. case PACKET_TYPE_REQ:
  805. //make INVALID Res and send it
  806. if (cmd != PACKET_CMD_CLOSE)
  807. {
  808. FERROR("Response to Owner.no device exist....");
  809. Ex_ResponseRemoteClientReq(packet, RET_INVALID, "no device exist");
  810. }
  811. break;
  812. case PACKET_TYPE_RES:
  813. case PACKET_TYPE_NOTIFY:
  814. //make Close Notify and send it
  815. FERROR("Request Close to Device.no Owner exist...");
  816. Ex_RequestRemoteClientClose(packet);
  817. break;
  818. default:
  819. //log here??
  820. FERROR("Packet error.WTF happenning???");
  821. return false;
  822. break;
  823. }
  824. return false;
  825. }
  826. else
  827. {
  828. //junky packet
  829. FERROR("Packet error junky packet.");
  830. }
  831. */
  832. return false;
  833. }
  834. /*
  835. //broardcast
  836. bool CDI::ReceivedDeviceNotify(ResDataObject &packet)
  837. {
  838. vector<CcosDevFileHandle> OwnerList;
  839. if (g_HandleManager.GetNotifyOwners(packet, OwnerList))
  840. {
  841. //NOT FINISHED YET
  842. //need to seperate this proc owner,local proc owner,eth owner
  843. for (DWORD i = 0; i < OwnerList.size(); i++)
  844. {
  845. //make notify
  846. ResDataObject notify;
  847. notify = packet;
  848. //add
  849. PacketAnalizer::UpdateNotifyHandle(notify, OwnerList[i]);
  850. //printf("Driver Thread:%d,Send Notify\n", GetCurrentThreadId());
  851. RES_FINFO(notify,"Notify to Owners:\n");
  852. ReceivedFromDevice(notify);
  853. }
  854. return true;
  855. }
  856. else
  857. {
  858. //printf("Driver Thread:%d,Failed to Notify.no packet owner exist\n", GetCurrentThreadId());
  859. }
  860. return false;
  861. }*/
  862. //notify & response.
  863. bool CDI::ReceivedFromDevice(ResDataObject &packet)
  864. {
  865. /*
  866. PACKET_TYPE type = PacketAnalizer::GetPacketType(&packet);
  867. switch (type)
  868. {
  869. case PACKET_TYPE_RES:
  870. case PACKET_TYPE_NOTIFY:
  871. break;
  872. default:
  873. //log here??
  874. printf("Driver Thread:%d,ReceivedFromDevice.wrong packet type\n", GetCurrentThreadId());
  875. FINFO("ReceivedFromDevice.wrong packet type");
  876. return false;
  877. break;
  878. }
  879. bool ret = true;
  880. //check destination & dispatch
  881. CMD_ECHO DispatchRet = DispatchPacket(packet);
  882. if (DispatchRet == CMD_ECHO_OK)
  883. {
  884. //log here
  885. FINFO("Done Dispatch");
  886. return true;
  887. }
  888. else if (DispatchRet == CMD_ECHO_NG)//this proc
  889. {
  890. //this proc
  891. FINFO("Local Dispatch");
  892. //dispatch to the process
  893. DispatchRet = DispatchToLocal(packet);
  894. if (DispatchRet == CMD_ECHO_OK)
  895. {
  896. return true;
  897. }
  898. //no client exist
  899. FINFO("no client exist in Local");
  900. Ex_ResponseDeviceRes(packet);
  901. }
  902. else if (DispatchRet == CMD_ECHO_NOTARGET)
  903. {
  904. //failed send packet to target
  905. FINFO("no client exist in Local");
  906. Ex_ResponseDeviceRes(packet);
  907. }
  908. else
  909. {
  910. //junky packet
  911. }
  912. */
  913. return false;
  914. }
  915. /*
  916. //request
  917. bool CDI::ReceivedFromClient(ResDataObject &packet)
  918. {
  919. assert(0); //没有从客户端交互的了
  920. return true;
  921. PACKET_TYPE type = PacketAnalizer::GetPacketType(&packet);
  922. switch (type)
  923. {
  924. case PACKET_TYPE_REQ:
  925. break;
  926. default:
  927. //log here??
  928. return false;
  929. break;
  930. }
  931. bool ret = true;
  932. UINT64 ProcId;
  933. UINT64 Addr;
  934. if (PacketAnalizer::GetPacketHandleProcId(&packet, ProcId, false) == true &&
  935. PacketAnalizer::GetPacketHandleAddr(&packet, Addr, false) == true)
  936. {
  937. if (g_ClientManager.FindClient(Addr) == false)
  938. {
  939. //log here
  940. //no client registed
  941. return false;
  942. }
  943. //check destination & dispatch
  944. CMD_ECHO DispatchRet = DispatchPacket(packet);
  945. if (DispatchRet == CMD_ECHO_OK)
  946. {
  947. //log here
  948. return true;
  949. }
  950. else if (DispatchRet == CMD_ECHO_NG)//this proc
  951. {
  952. //target is this proc
  953. //dispatch to the process
  954. DispatchRet = To_Local_RequestProcedure(packet);
  955. if (DispatchRet == CMD_ECHO_OK)
  956. {
  957. return true;
  958. }
  959. else if (DispatchRet == CMD_ECHO_NG)//access right NG
  960. {
  961. //权限不够
  962. Ex_ResponseClientReq(packet,RET_FAILED,"no access right");
  963. return true;//保持连线
  964. }
  965. //其他情况,全部返回失败,由客户端自行断开
  966. }
  967. else if (DispatchRet == CMD_ECHO_NOTARGET)
  968. {
  969. //failed send out packet
  970. //the target must be at outside of the process
  971. //just return false
  972. }
  973. else
  974. {
  975. //junky packet
  976. }
  977. }
  978. return false;
  979. }
  980. */
  981. /*
  982. bool CDI::RegistClient(UINT64 Address)
  983. {
  984. return g_ClientManager.RegistClient(Address);
  985. }
  986. bool CDI::UnRegistClient(UINT64 Address)
  987. {
  988. return g_ClientManager.UnRegistClient(Address);
  989. }*/
  990. bool CDI::Registhandle(void* Handle)
  991. {
  992. CcosDevFileHandle *pHandle = (CcosDevFileHandle *)Handle;
  993. bool ret = g_HandleManager.Registhandle(*pHandle);
  994. FINFO("RegistHandle.Id:{$},Result:{$}", (UINT64)(*pHandle)[CCOS_PACKET_HANDLE_KEY], ret);
  995. return ret;
  996. }
  997. bool CDI::UnRegistHandle(UINT64 CrcCode)
  998. {
  999. FINFO("UnRegistHandle Entry.Id:{$}", CrcCode);
  1000. bool ret = g_HandleManager.UnRegistHandle(CrcCode);
  1001. FINFO("UnRegistHandle.Id:{$},Result:{$}", CrcCode, ret);
  1002. return ret;
  1003. }
  1004. void CDI::UnLoadAll()
  1005. {
  1006. //printf("--------Exit System Entry--------\n");
  1007. Thread_Lock();
  1008. //printf("UnLoadAllDCS\n");
  1009. //UnLoadAllDCS();
  1010. FINFO("UnLoadAllDrivers");
  1011. //printf("UnLoadAllDrivers\n");
  1012. g_DrvManager.UnloadDrivers();
  1013. FINFO("UnLoadRootDriver");
  1014. //printf("UnloadRootDriver\n");
  1015. g_DrvManager.UnloadRootDriver();
  1016. FINFO("StopDriverTree");
  1017. if (g_DrvTree.StopThread(100) == false)
  1018. {
  1019. FINFO("StopDriverTree Used Terminate!!!!!!!!!!!!!!!");
  1020. //printf("StopDriverTree Used Terminate!!!!!!!!!!!!!!!\n");
  1021. }
  1022. //FINFO("HandleManager.Clear");
  1023. //g_HandleManager.Clear();
  1024. //HandleManager没必要卸载,因为它保存的是本地设备的句柄,而本地设备在卸载后,
  1025. //会有统一的Close Notify发给Owner.
  1026. FINFO("StopBusManager");
  1027. //printf("StopBusManager\n");
  1028. if (UnloadBusDrv() == false)
  1029. {
  1030. FINFO("StopBusManagerThread Used Terminate!!!!!!!!!!!!!!!");
  1031. //printf("StopBusManagerThread Used Terminate!!!!!!!!!!!!!!!\n");
  1032. }
  1033. /*
  1034. FINFO("UnRegistAllClient");
  1035. printf("UnRegistAllClient\n");
  1036. g_ClientManager.UnRegistAll();*/
  1037. FINFO("Exit LogSystem");
  1038. //printf("ExitLoggerModule\n");
  1039. //ExitLoggerModule();
  1040. Thread_UnLock();
  1041. //printf("SetEventExit\n");
  1042. m_ExitHandle->SetEvent();
  1043. //printf("Clear Sharememory\n");
  1044. //Exit_Circle_SM_IF();
  1045. //printf("--------Exit System Exit--------\n");
  1046. }
  1047. //bool CDI::RegistThread(PVOID pCcosThread)
  1048. //{
  1049. // return true;
  1050. // //return g_PTManager.RegistThread(pCcosThread);
  1051. //}
  1052. //
  1053. //void CDI::UnRegistThread(DWORD Tid)
  1054. //{
  1055. // return;
  1056. // //BusUnRegistThread(Tid);//buss
  1057. // //CleanupForThread(Tid);//locks
  1058. // //g_PTManager.UnRegistThread(Tid);
  1059. //}
  1060. //bool CDI::GetThreadsLogger(DWORD Tid, PVOID &pLogger)
  1061. //{
  1062. // pLogger = g_PTManager.GetThreadLogger(Tid);
  1063. //
  1064. // return (pLogger != NULL);
  1065. //}
  1066. bool CDI::InitBusUnit()
  1067. {
  1068. if (m_prootClient == NULL)
  1069. {
  1070. m_prootClient = new BusUnitClient("CDI_BusUnit_rootClient");
  1071. //for test
  1072. CcosDevFileHandle Handle;
  1073. ((BusUnitClient*)m_prootClient)->GetFileHandle(Handle);
  1074. FINFO("RootClient init Address:{$}", (UINT64)Handle.GetTarget()[CCOS_PACK_TARGET_ADDR]);
  1075. //printf("RootClient init Address:%I64u\n", (UINT64)Handle.GetTarget()[CCOS_PACK_TARGET_ADDR]);
  1076. if (((BusUnitClient*)m_prootClient)->Open((const char*)getRootpath(), ALL_ACCESS) >= RET_SUCCEED)
  1077. {
  1078. //for test
  1079. FINFO("RootClient Open Succeed");
  1080. //printf("RootClient Open Succeed\n");
  1081. return true;
  1082. }
  1083. //for test
  1084. FINFO("RootClient Open Failed");
  1085. //printf("RootClient Open Failed\n");
  1086. delete ((BusUnitClient*)m_prootClient);
  1087. m_prootClient = NULL;
  1088. }
  1089. return false;
  1090. }
  1091. bool CDI::WaitExit(DWORD timeout,bool Exit)
  1092. {
  1093. if (Exit)
  1094. {
  1095. ((BusUnitClient*)m_prootClient)->Close();
  1096. //do the Exit Job
  1097. //printf("UnLoadAll On Purpose\n");
  1098. FINFO("UnLoadAll On Purpose ");
  1099. UnLoadAll();
  1100. //printf("UnLoadAll Finished\n");
  1101. usleep(100000);
  1102. return true;
  1103. }
  1104. std::shared_ptr<LinuxEvent> hand = ((BusUnitClient*)m_prootClient)->GetNotifyHandle();
  1105. DWORD wait = hand->Wait(timeout);
  1106. if (wait == WAIT_OBJECT_0)
  1107. {
  1108. //printf("WaitExit:Got Root Notify\n");
  1109. //update status
  1110. ResDataObject packet;
  1111. try {
  1112. //printf("Thread:%d,DrvTree Thread Loop\n", GetCurrentThreadId());
  1113. if (((BusUnitClient*)m_prootClient)->IsClosed() == true)
  1114. {
  1115. //printf("WaitExit:Try Open Root \n");
  1116. FINFO("client handle is closed.Try Open Root");
  1117. //try once
  1118. if (((BusUnitClient*)m_prootClient)->Open((const char*)getRootpath(), ALL_ACCESS) == false)
  1119. {
  1120. //printf("Thread:%d,Open Failed\n", GetCurrentThreadId());
  1121. FERROR("Thread:{$},Open root : {$} Failed.unloadall...\n", GetCurrentThreadId(), (const char*)getRootpath());
  1122. UnLoadAll();
  1123. return true;
  1124. }
  1125. //printf("WaitExit:Try Open Root Succeed\n");
  1126. }
  1127. //below is opened status
  1128. PACKET_CMD cmd;
  1129. do {
  1130. cmd = ((BusUnitClient*)m_prootClient)->ReadCmd(packet);
  1131. if (cmd == PACKET_CMD_UPDATE)
  1132. {
  1133. //printf("Got Root Update\n");
  1134. string key = PacketAnalizer::GetPacketKey(&packet);
  1135. if (key == "ExitFlag")
  1136. {
  1137. if (((BusUnitClient*)m_prootClient)->GetExitFlag())
  1138. {
  1139. ((BusUnitClient*)m_prootClient)->Close();
  1140. //do the Exit Job
  1141. //printf("Entering Exit Job\n");
  1142. FINFO("ExitFlag is Set.Entering Exit Job\n");
  1143. UnLoadAll();
  1144. return true;
  1145. }
  1146. }
  1147. //ignore others
  1148. }
  1149. else
  1150. {
  1151. //ignore others
  1152. //printf("Thread:%d,DrvTree Thread Ignore\n", GetCurrentThreadId(), cmd);
  1153. }
  1154. } while (cmd != PACKET_CMD_NONE);
  1155. }
  1156. catch (...)
  1157. {
  1158. //printf("Thread:%d,Exeption in DrvTree Thread\n", GetCurrentThreadId());
  1159. }
  1160. return false;
  1161. }
  1162. //timeout no quit
  1163. return false;
  1164. }
  1165. void CDI::Ex_RequestRemoteClientClose(ResDataObject &Res)
  1166. {
  1167. try {
  1168. ResDataObject Req;
  1169. //send close notify
  1170. if (PacketAnalizer::MakeCloseRequestByRes(Res, Req))
  1171. {
  1172. DispatchPacket(Req);
  1173. }
  1174. }
  1175. catch (...)
  1176. {
  1177. }
  1178. }
  1179. void CDI::Ex_ResponseRemoteClientReq(ResDataObject &Req, RET_STATUS status, const char *pInfo)
  1180. {
  1181. try {
  1182. ResDataObject Res;
  1183. if (PacketAnalizer::MakeResponseByReq(Res, Req, status, pInfo))
  1184. {
  1185. DispatchPacket(Res);
  1186. }
  1187. //send close notify
  1188. }
  1189. catch (...)
  1190. {
  1191. }
  1192. }
  1193. void CDI::Ex_ResponseClientReq(ResDataObject &Req, RET_STATUS status, const char *pInfo)
  1194. {
  1195. try {
  1196. ResDataObject Res;
  1197. PacketAnalizer::MakeResponseByReq(Res, Req, status, pInfo);
  1198. CMD_ECHO ret = CMD_ECHO_OK;//To_Local_ResponseProcedure(Res);
  1199. if (ret == CMD_ECHO_OK)
  1200. {
  1201. //log here
  1202. }
  1203. }
  1204. catch (...)
  1205. {
  1206. }
  1207. }
  1208. void CDI::Ex_ResponseDeviceRes(ResDataObject &Res)
  1209. {
  1210. try {
  1211. //清除句柄
  1212. UINT64 Crc = 0;
  1213. PacketAnalizer::GetPacketHandleCrc(&Res, Crc);
  1214. g_HandleManager.UnRegistHandle(Crc);
  1215. }
  1216. catch (...)
  1217. {
  1218. }
  1219. }
  1220. void CDI::Ex_ResponseEbus(ResDataObject &packet)
  1221. {
  1222. //Req
  1223. //Res
  1224. }
  1225. /*
  1226. CMD_ECHO CDI::DispatchToLocal(ResDataObject &packet)
  1227. {
  1228. //match to this proc
  1229. //request:dispatch to device
  1230. //response:dispatch to client
  1231. //notify:dispatch to client
  1232. CMD_ECHO echo = CMD_ECHO_IGNORE;
  1233. //check req or res
  1234. PACKET_TYPE type = PacketAnalizer::GetPacketType(&packet);
  1235. switch (type)
  1236. {
  1237. case PACKET_TYPE_REQ:
  1238. echo = (To_Local_RequestProcedure(packet));
  1239. break;
  1240. case PACKET_TYPE_RES:
  1241. assert(0); //从eBus上不再会收到res,因为不会发req了,client的收发转到MQTT了
  1242. //echo = To_Local_ResponseProcedure(packet);
  1243. break;
  1244. case PACKET_TYPE_NOTIFY:
  1245. assert(0); //从eBus上不再会收到notify,notify的收发转到MQTT了
  1246. //echo = To_Local_NotifyProcedure(packet);
  1247. break;
  1248. default:
  1249. //log here??
  1250. break;
  1251. }
  1252. return echo;
  1253. }*/
  1254. /*
  1255. bool CDI::AddDPC(PVOID pMDPC, PVOID pDPC, ResDataObject &DrvConfig)
  1256. {
  1257. return g_DrvManager.LoadDPC((MultiDPC*)pMDPC, (DriverDPC*)pDPC, DrvConfig);
  1258. }
  1259. bool CDI::DelDPC(PVOID pMDPC, PVOID pDPC)
  1260. {
  1261. return g_DrvManager.UnLoadDPC((MultiDPC*)pMDPC, (DriverDPC*)pDPC);
  1262. }
  1263. */
  1264. CDI_C_API CDI *GetCommandDispathIF()
  1265. {
  1266. return &g_CDI;
  1267. }
  1268. /*
  1269. CDI_C_API bool InitClientEnv()
  1270. {
  1271. if (GetCommandDispathIF()->InitAs(CCOS_PROC_CLIENT, (UINT64)GetCurrentProcessId()))
  1272. {
  1273. return true;
  1274. }
  1275. return false;
  1276. }
  1277. CDI_C_API bool DestroyClientEnv()
  1278. {
  1279. GetCommandDispathIF()->UnLoadAll();
  1280. return true;
  1281. }
  1282. */
  1283. CDI_C_API CDInterface* GetCDI()
  1284. {
  1285. return &g_CDI;
  1286. }