BusUnitLogic.cpp 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568
  1. // BusUnitLogic.cpp : 定义 DLL 应用程序的导出函数。
  2. //
  3. #include <time.h>
  4. #include <unistd.h>
  5. #include <sys/types.h>
  6. #include <sys/wait.h>
  7. #include <cstring>
  8. #include <fcntl.h>
  9. #include <wordexp.h>
  10. #include <filesystem>
  11. #include "common_api.h"
  12. #include "LocalConfig.h"
  13. #include "LogicDriver.h"
  14. #include "BusUnitLogic.h"
  15. #include "PacketAnalizer.h"
  16. #include "LogicClient.h"
  17. #include "DriverConfigManager.h"
  18. #define BusUnitGuidStr "{181F92D6-A546-4ACF-8EF1-2CCAA9EA974E}"
  19. // 这是导出变量的一个示例
  20. BUSUNITLOGIC_API int nBusUnitLogic=0;
  21. // 这是导出函数的一个示例。
  22. BUSUNITLOGIC_API int fnBusUnitLogic(void)
  23. {
  24. return 42;
  25. }
  26. static string CurrentDateTime2()
  27. {
  28. std::time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
  29. char buf[100] = { 0 };
  30. std::strftime(buf, sizeof(buf), " %Y-%m-%d_%H%M%S ", std::localtime(&now));
  31. return buf;
  32. }
  33. /// <summary>
  34. /// 创建带Console显示的进程
  35. /// </summary>
  36. /// <param name="pfullFilePath">进程启动命令行</param>
  37. /// <param name="pfullWorkPath">工作路径</param>
  38. /// <param name="pinfo">返回进程Info</param>
  39. /// <param name="ShowWindow">是否显示Console</param>
  40. /// <returns></returns>
  41. bool CreateTheProcess_Console_Config(const char* pfullFilePath, const char* pfullWorkPath,
  42. LinuxProcessInfo& pinfo, bool ShowWindow)
  43. {
  44. // 解析命令行参数
  45. wordexp_t result;
  46. if (wordexp(pfullFilePath, &result, WRDE_NOCMD | WRDE_UNDEF) != 0) {
  47. return false; // 参数解析失败
  48. }
  49. pid_t pid = fork();
  50. if (pid < 0) {
  51. wordfree(&result);
  52. return false; // fork 失败
  53. }
  54. // 子进程
  55. if (pid == 0) {
  56. // 设置工作目录
  57. if (pfullWorkPath && chdir(pfullWorkPath) != 0) {
  58. _exit(EXIT_FAILURE);
  59. }
  60. // 隐藏控制台输出
  61. if (!ShowWindow) {
  62. int nullfd = open("/dev/null", O_RDWR);
  63. if (nullfd != -1) {
  64. dup2(nullfd, STDIN_FILENO);
  65. dup2(nullfd, STDOUT_FILENO);
  66. dup2(nullfd, STDERR_FILENO);
  67. close(nullfd);
  68. }
  69. }
  70. // 执行程序
  71. execvp(result.we_wordv[0], result.we_wordv);
  72. _exit(EXIT_FAILURE); // execvp 失败才会执行到这里
  73. }
  74. // 父进程
  75. else {
  76. wordfree(&result);
  77. pinfo.process_id = pid; // 存储子进程 PID
  78. return true;
  79. }
  80. }
  81. // 这是已导出类的构造函数。
  82. // 有关类定义的信息,请参阅 BusUnitLogic.h
  83. BusUnitLogic::BusUnitLogic()
  84. {
  85. m_DevList = new DeviceDescriptList();
  86. m_pCcosDevList = new DeviceDescriptList();
  87. m_pCcosDevList->SetKey("CcosDeviceList");
  88. m_pbusID = new BaseJsonDataObject<string>();
  89. m_pbusID->SetKey("BusId");
  90. (*m_pbusID) = (const char*)getLocalEbusId();
  91. m_pMachineID = new BaseJsonDataObject<string>();
  92. m_pMachineID->SetKey("MachineId");
  93. (*m_pMachineID) = (const char*)getLocalMachineId();
  94. m_pProcID = new BaseJsonDataObject<UINT64>();
  95. m_pProcID->SetKey("ProcId");
  96. (*m_pProcID) = (UINT64)getpid();
  97. m_pGrpcPort = new BaseJsonDataObject<int>();
  98. m_pGrpcPort->SetKey("GrpcPort");
  99. (*m_pGrpcPort) = 9000;
  100. m_pState = new BaseJsonDataObject<int>();
  101. m_pState->SetKey("Status");
  102. (*m_pState) = 0;
  103. m_pExitFlag = new BaseJsonDataObject<int>();
  104. m_pExitFlag->SetKey("ExitFlag");
  105. (*m_pExitFlag) = 0;
  106. m_pEnableEthBus = new BaseJsonDataObject<int>();
  107. m_pEnableEthBus->SetKey("EnableEthBus");
  108. (*m_pEnableEthBus) = 0;//default is disconnect
  109. m_pEthBusRouterIp = new BaseJsonDataObject<string>();
  110. m_pEthBusRouterIp->SetKey("EthBusRouterIp");
  111. (*m_pEthBusRouterIp) = (const char*)"";
  112. m_pForTest = new BaseJsonDataObject<bool>();
  113. m_pForTest->SetKey("ForTestFlag");
  114. (*m_pForTest) = 0;//default is 0
  115. m_pFullDriverList = new DriverDescriptList();
  116. m_pFullDriverList->SetKey("FullDriverList");
  117. m_pConfigDriverList = new DriverDescriptList();
  118. m_pConfigDriverList->SetKey("ConfigDriverList");
  119. m_pProcessInfo = new map<string, vector<TargetDriverInfo>>();
  120. m_bConfigRemoveDriver = false;
  121. m_DriverConfigMange = new DriverConfigManager();
  122. m_Actions.add("AddDeviceDescrpt", "");
  123. m_Actions.add("DelDeviceDescrpt", "");
  124. m_Actions.add("ExitDriverProc", "");
  125. m_Actions.add("SetDeviceStatus", "");
  126. m_Actions.add("SetEthBusSwitch", "");
  127. m_Actions.add("SetEthBusRouterIp", "");
  128. m_Actions.add("ForTest", "");
  129. m_Actions.add("ConfigLoadDriver", "");
  130. m_Actions.add("LoadAllConfigDriver", "");
  131. m_Actions.add("ConfigRemoveDriver", "");
  132. m_Actions.add("SubscribeTopic", ""); //DPC 订阅事件
  133. m_Actions.add("Unsubscribe", ""); //取消订阅
  134. m_Actions.add("GetAllConfigList","");
  135. m_Actions.add("AddDriverConfig", "");
  136. m_Actions.add("DelDriverConfig", "");
  137. m_Actions.add("GetDriverConfigRes", "");
  138. m_Actions.add("SetDriverConfigRes", "");
  139. m_Actions.add("CheckAndKillLiveDriver", "");
  140. }
  141. BusUnitLogic::~BusUnitLogic()
  142. {
  143. delete m_DevList;
  144. delete m_pCcosDevList;
  145. delete m_pbusID;
  146. delete m_pMachineID;
  147. delete m_pProcID;
  148. delete m_pGrpcPort;
  149. delete m_pState;
  150. delete m_pExitFlag;
  151. delete m_pEnableEthBus;
  152. delete m_pEthBusRouterIp;
  153. delete m_pForTest;
  154. delete m_pFullDriverList;
  155. delete m_pConfigDriverList;
  156. delete m_pProcessInfo;
  157. }
  158. /// <summary>
  159. /// 获取Bus单元逻辑设备的GUID类型
  160. /// </summary>
  161. /// <param name="DevType">返回值</param>
  162. /// <returns></returns>
  163. bool SYSTEM_CALL BusUnitLogic::GetDeviceType(GUID &DevType)
  164. {
  165. return string_2_guid(BusUnitGuidStr, DevType);
  166. }
  167. /// <summary>
  168. /// 测试数据更新验证,如果值相同,则生成通知
  169. /// </summary>
  170. /// <param name="Flag">判定条件值</param>
  171. /// <returns></returns>
  172. int DATA_ACTION BusUnitLogic::ForTest(bool Flag)
  173. {
  174. RET_STATUS ret = RET_SUCCEED;
  175. if ((*m_pForTest) != Flag)
  176. {
  177. (*m_pForTest) = Flag;
  178. ResDataObject NotifyData;
  179. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_UPDATE, m_pForTest->GetKey(), m_pForTest->GetVal());
  180. ret = CmdFromLogicDev(&NotifyData);
  181. //PublishAction(&NotifyData, (m_strEBusRoot + "/Notify").c_str(), m_pMqttConntion);
  182. }
  183. return ret;
  184. }
  185. //get device resource
  186. /// <summary>
  187. /// 返回Bus单元逻辑设备的资源描述,这里新增了订阅Action
  188. /// </summary>
  189. /// <param name="pDeviceResource">返回值</param>
  190. /// <returns></returns>
  191. RET_STATUS SYSTEM_CALL BusUnitLogic::GetDeviceResource(ResDataObject PARAM_OUT *pDeviceResource)
  192. {
  193. bool ret = true;
  194. //make device type
  195. ret &= pDeviceResource->add("ClientType", DPC_UnitClient);
  196. ret &= pDeviceResource->add("DeviceType", BusUnitGuidStr);
  197. //make attributes
  198. ResDataObject AttrVal;
  199. AttrVal.add(m_pMachineID->GetKey(), m_pMachineID->GetVal());
  200. AttrVal.add(m_pbusID->GetKey(), m_pbusID->GetVal());
  201. AttrVal.add(m_pProcID->GetKey(), m_pProcID->GetVal());
  202. AttrVal.add(m_pGrpcPort->GetKey(), m_pGrpcPort->GetVal());
  203. AttrVal.add(m_pState->GetKey(), m_pState->GetVal());
  204. AttrVal.add(m_pExitFlag->GetKey(), m_pExitFlag->GetVal());
  205. AttrVal.add(m_pEnableEthBus->GetKey(), m_pEnableEthBus->GetVal());
  206. AttrVal.add(m_pEthBusRouterIp->GetKey(), m_pEthBusRouterIp->GetVal());
  207. AttrVal.add(m_pForTest->GetKey(), m_pForTest->GetVal());
  208. ResDataObject arraylist;
  209. m_DevList->GetResDataObject(arraylist);
  210. AttrVal.add(m_DevList->GetKey(), arraylist);
  211. //full driver list
  212. arraylist.clear();
  213. m_pFullDriverList->GetResDataObject(arraylist);
  214. AttrVal.add(m_pFullDriverList->GetKey(), arraylist);
  215. //ccos 设备列表
  216. arraylist.clear();
  217. m_pCcosDevList->GetResDataObject(arraylist);
  218. AttrVal.add(m_pCcosDevList->GetKey(), arraylist);
  219. //config driver list
  220. arraylist.clear();
  221. m_pConfigDriverList->GetResDataObject(arraylist);
  222. AttrVal.add(m_pConfigDriverList->GetKey(), arraylist);
  223. ret &= pDeviceResource->add("Attribute", AttrVal);
  224. //Actions
  225. ResDataObject ActionVal;
  226. if (ret)
  227. {
  228. pDeviceResource->add("Action", m_Actions);
  229. return RET_SUCCEED;
  230. }
  231. return RET_FAILED;
  232. }
  233. int ProcessCcosProcConfig(string devType, string devVendor, string devProduct, string devSerilID, int& ccosProcBasePort, bool install);
  234. //ResourceCommand Request In and Response Out
  235. RET_STATUS SYSTEM_CALL BusUnitLogic::Request(ResDataObject PARAM_IN *pRequest, ResDataObject PARAM_OUT *pResponse)
  236. {
  237. ResDataObject res;
  238. RET_STATUS ret = RET_NOSUPPORT;
  239. //1. analize request
  240. PACKET_CMD cmd = PacketAnalizer::GetPacketCmd(pRequest);
  241. //cmd:get,set,add,del,exe,
  242. //ignore open/close
  243. //Action和Attr应该做成一个MAP,经过MAP访问这些资源,不应该是switch case
  244. //为了快速做一版,先保留switch case!!!
  245. string keystr = PacketAnalizer::GetPacketKey(pRequest);
  246. ACTION_SYNC_MODE syncmode = PacketAnalizer::GetPacketSyncMode(pRequest);
  247. PacketAnalizer::MakeResponseByReq(*pResponse, *pRequest, ret);
  248. //mLog::FINFO("BusUnit Request cmd [{$}] key [{$}]", (int)cmd, keystr);
  249. switch (cmd){
  250. case PACKET_CMD_EXE:
  251. {
  252. if (keystr == "AddDeviceDescrpt")
  253. {
  254. bool result = true;
  255. ResDataObject obj1,obj2,obj3,obj4,obj5,obj6;
  256. result &= PacketAnalizer::GetParam(pRequest, 0, obj1);
  257. result &= PacketAnalizer::GetParam(pRequest, 1, obj2);
  258. result &= PacketAnalizer::GetParam(pRequest, 2, obj3);
  259. result &= PacketAnalizer::GetParam(pRequest, 3, obj4);
  260. result &= PacketAnalizer::GetParam(pRequest, 4, obj5);
  261. result &= PacketAnalizer::GetParam(pRequest, 5, obj6);
  262. if (result)
  263. {
  264. //2. call api
  265. ret = (RET_STATUS)AddDeviceDescrpt((const char *)obj1, (const char *)obj2, (const char *)obj3, (UINT64)obj4, (UINT64)obj5, (bool)obj6);
  266. }
  267. else
  268. {
  269. //put log here
  270. }
  271. }
  272. else if (keystr == "LoadAllConfigDriver")
  273. {
  274. ResDataObject resConfig;
  275. ret = (RET_STATUS)LoadAllConfigDriver(true, &resConfig);
  276. pResponse->update("CONTEXT", resConfig);
  277. }
  278. else if (keystr == "ConfigLoadDriver")
  279. {
  280. //1. 获取参数
  281. ResDataObject obj;
  282. if (PacketAnalizer::GetParam(pRequest, 0, obj))
  283. {
  284. ResDataObject value,resConfig;
  285. ResDataObject resCcosProcConf;
  286. if (!PacketAnalizer::GetParam(pRequest, 1, value))
  287. {
  288. value = "0";
  289. }
  290. //2. call api
  291. char szFixDrv[MAX_PATH];
  292. memset(szFixDrv, 0, MAX_PATH);
  293. ret = (RET_STATUS)ConfigLoadDriver((const char *)obj, szFixDrv,MAX_PATH, value, resConfig, resCcosProcConf);
  294. //3. 打包
  295. res.add("P0", szFixDrv);
  296. res.add("ConfigRes", resConfig);
  297. res.add("CcosProc", resCcosProcConf);
  298. pResponse->update("CONTEXT", res);
  299. }
  300. }
  301. else if (keystr == "ConfigRemoveDriver")
  302. {
  303. //1. 获取参数
  304. ResDataObject obj;
  305. if (PacketAnalizer::GetParam(pRequest, 0, obj))
  306. {
  307. //2. call api
  308. bool bfind = false;
  309. ResDataObject DriverBusId;
  310. ResDataObject obj2,resReq,resRes;
  311. if (PacketAnalizer::GetParam(pRequest, 1, obj2))
  312. {
  313. ResDataObject fileList;
  314. //如果有P1,则是子系统自己发的,CCOS路径
  315. if (GetSpecificDriverConfigFiles(fileList, false))
  316. {
  317. for (size_t i = 0; i < fileList.size(); i++)
  318. {
  319. ResDataObject BusId;
  320. //get ebus driver path
  321. if (GetDriverEbusId(fileList.GetKey(i), BusId, DriverBusId))
  322. {
  323. //for test
  324. //mLog::FINFO("file[{$}] File:{$}\n Buspath:{$}\n", i, fileList.GetKey(i), (const char*)DriverBusId);
  325. ///DevCareRayRF/Detector/driver/CareRay/1800RF/1234/{18CAB88A-C61C-4BB2-AC28-184FDD4FD160}
  326. // CCOS/DEVICE/Detecor/CareRay/1800RF
  327. vector<string> items;
  328. SplitDevicePath(DriverBusId, items);
  329. string ccosPath = "CCOS/DEVICE/";
  330. if (items.size() >= 6)
  331. ccosPath = ccosPath + items[1] + "/" + items[3] + "/" + items[4] + "/" + items[5];
  332. //mLog::FINFO("file[{$}] File:{$} CcosPath:{$}\n", i, fileList.GetKey(i), ccosPath);
  333. if ( ccosPath == (const char*)obj)
  334. {
  335. bfind = true;
  336. //mLog::FINFO("Remove Driver {$} ", ccosPath);
  337. int basePort = 0;
  338. if (items.size() >= 6)
  339. ProcessCcosProcConfig(items[1], items[3], items[4], items[5], basePort, false);
  340. res.add("P0", DriverBusId);
  341. ResDataObject resConfig;
  342. resConfig.add(ccosPath.c_str(), "");
  343. res.add("ConfigRes", resConfig);
  344. res.add("CcosProc", "");
  345. pResponse->update("CONTEXT", res);
  346. break;
  347. }
  348. }
  349. }
  350. }
  351. if (bfind)
  352. {
  353. while (1)
  354. {
  355. //mLog::FINFO("Try Notify Channel to ConfigRemoveDriver {$}", (const char*)DriverBusId);
  356. string cltName = "RemoveDriver" + to_string(rand());
  357. LogicClient startupClient(cltName, "", "TEMP", false);
  358. //std::function<void(LogicClient*, const char*, int)>;
  359. //HANDLE hOk = CreateEvent(NULL, FALSE, FALSE, "");
  360. if (startupClient.Open("/ccosChannel", ACTION, "", 2000, nullptr) == RET_SUCCEED)
  361. {
  362. //mLog::FINFO("Channel opened . try action. remove [{$}]", (const char*)DriverBusId);
  363. resReq.add("P0", (const char*)DriverBusId);
  364. startupClient.Action("ConfigRemoveDriver", resReq, resRes, 2000, "ccosChannel");
  365. //mLog::FINFO("Channel Action ret ={$}. with resp {$}", (int)ret, resRes.encode());
  366. //PacketAnalizer::UpdatePacketContext((*pResponse), resRes);
  367. startupClient.Close();
  368. ret = RET_SUCCEED;
  369. break;
  370. }
  371. else
  372. {
  373. //mLog::FERROR("Open Channel failed. for {$} try again...", (const char*)DriverBusId);
  374. }
  375. }
  376. }
  377. }
  378. else
  379. {
  380. //mLog::FINFO("Real ConfigRemoveDriver {$}", (const char*)obj);
  381. ret = (RET_STATUS)ConfigRemoveDriver((const char *)obj);
  382. }
  383. //3. 打包
  384. }
  385. }
  386. else if (keystr == "DelDeviceDescrpt")
  387. {
  388. //1. 获取参数
  389. ResDataObject obj;
  390. if (PacketAnalizer::GetParam(pRequest, 0, obj))
  391. {
  392. //2. call api
  393. ret = (RET_STATUS)DelDeviceDescrpt((const char *)obj);
  394. //3. 打包
  395. }
  396. }
  397. else if (keystr == "ExitDriverProc")
  398. {
  399. ret = (RET_STATUS)ExitDriverProc();
  400. }
  401. else if (keystr == "CheckAndKillLiveDriver")
  402. {
  403. //1. 获取参数
  404. ResDataObject obj;
  405. if (PacketAnalizer::GetParam(pRequest, 0, obj))
  406. {
  407. if (CheckAndKillLiveDriver((const char*)obj, false))
  408. ret = RET_SUCCEED;
  409. else
  410. ret = RET_FAILED;
  411. }
  412. }
  413. else if (keystr == "SetDeviceStatus")
  414. {
  415. //1. 获取参数
  416. ResDataObject obj;
  417. if (PacketAnalizer::GetParam(pRequest, 0, obj))
  418. {
  419. //2. call api
  420. ret = (RET_STATUS)SetDeviceStatus((int)obj);
  421. //3. 打包
  422. }
  423. }
  424. else if (keystr == "SetEthBusSwitch")
  425. {
  426. //1. 获取参数
  427. ResDataObject obj;
  428. if (PacketAnalizer::GetParam(pRequest, 0, obj))
  429. {
  430. //2. call api
  431. ret = (RET_STATUS)SetEthBusSwitch((int)obj);
  432. //3. 打包
  433. }
  434. }
  435. else if (keystr == "SetEthBusRouterIp")
  436. {
  437. //1. 获取参数
  438. ResDataObject obj;
  439. if (PacketAnalizer::GetParam(pRequest, 0, obj))
  440. {
  441. //2. call api
  442. ret = (RET_STATUS)SetEthBusRouterIp((const char*)obj);
  443. //3. 打包
  444. }
  445. }
  446. else if (keystr == "Get")
  447. {
  448. //1. 获取参数
  449. ResDataObject Res;
  450. ResDataObject obj;
  451. if (PacketAnalizer::GetParam(pRequest, 0, obj))
  452. {
  453. //2. call api
  454. ret = (RET_STATUS)Get((const char*)obj,Res);
  455. //3. 打包
  456. if (ret == RET_SUCCEED)
  457. {
  458. PacketAnalizer::UpdatePacketContext((*pResponse), Res);
  459. }
  460. }
  461. }
  462. else if (keystr == "ForTest")
  463. {
  464. ResDataObject Res;
  465. ResDataObject obj;
  466. if (PacketAnalizer::GetParam(pRequest, 0, obj))
  467. {
  468. //2. call api
  469. ret = (RET_STATUS)ForTest((bool)obj);
  470. }
  471. }
  472. else if (keystr == "SubscribeTopic") {
  473. // 收到 应用或者其他模块的 订阅消息
  474. // 往MQTT broker 里订阅
  475. }
  476. else if (keystr == "GetAllConfigList")
  477. {
  478. //int (ResDataObject& resAll);
  479. //RET_STATUS (const char* pszDevPath, ResDataObject& resNewDevPath);
  480. //RET_STATUS (const char* pszDevPath);
  481. //int (const char* pszDevPath, ResDataObject& resConfig);
  482. //int (const char* pszDevPath, ResDataObject* resConfig);
  483. ResDataObject resAll;
  484. m_DriverConfigMange->GetAllConfigList(resAll);
  485. ret = RET_SUCCEED;
  486. res.update("P0", resAll);
  487. pResponse->update("CONTEXT", res);
  488. }
  489. else if (keystr == "AddDriverConfig")
  490. {
  491. //1. 获取参数
  492. ResDataObject obj;
  493. if (PacketAnalizer::GetParam(pRequest, 0, obj))
  494. {
  495. //2. call api
  496. ResDataObject real;
  497. ret = m_DriverConfigMange->AddDriverConfig((const char*)obj, real);
  498. //3. 打包
  499. res.update("P0", real);
  500. pResponse->update("CONTEXT", res);
  501. }
  502. }
  503. else if (keystr == "DelDriverConfig")
  504. {
  505. //1. 获取参数
  506. ResDataObject obj;
  507. if (PacketAnalizer::GetParam(pRequest, 0, obj))
  508. {
  509. //2. call api
  510. ret = m_DriverConfigMange->DelDriverConfig((const char*)obj);
  511. }
  512. }
  513. else if (keystr == "GetDriverConfigRes")
  514. {
  515. //1. 获取参数
  516. ResDataObject obj;
  517. if (PacketAnalizer::GetParam(pRequest, 0, obj))
  518. {
  519. //2. call api
  520. ResDataObject resConfig;
  521. ret = m_DriverConfigMange->GetDriverConfigRes((const char*)obj, resConfig);
  522. //3. 打包
  523. res.update("P0", resConfig);
  524. pResponse->update("CONTEXT", res);
  525. }
  526. }
  527. else if (keystr == "SetDriverConfigRes")
  528. {
  529. ResDataObject obj, resConfig;
  530. if (PacketAnalizer::GetParam(pRequest, 0, obj))
  531. {
  532. if (PacketAnalizer::GetParam(pRequest, 1, resConfig))
  533. {
  534. //2. call api
  535. ret = m_DriverConfigMange->SetDriverConfigRes((const char*)obj, &resConfig) ;
  536. //3. 打包
  537. //res.update("P0", resConfig);
  538. //pResponse->update("CONTEXT", res);
  539. }
  540. }
  541. }
  542. }
  543. break;
  544. default:
  545. //对当前设备来讲,其他都是浮云
  546. break;
  547. }
  548. //return status
  549. PacketAnalizer::MakeRetCode(ret, pResponse);
  550. return ret;
  551. }
  552. RET_STATUS BusUnitLogic::ProcessRequest(ResDataObject* pCmd, PACKET_CMD cmd)
  553. {
  554. ResDataObject resRes, resResponse;
  555. ResDataObject resTopic;
  556. PacketAnalizer::GetContextTopic(pCmd, resTopic);
  557. if (cmd == PACKET_CMD_OPEN )
  558. {
  559. GetDeviceResource(&resRes);
  560. PacketAnalizer::MakeOpenResponse(*pCmd, resResponse, resRes);
  561. PacketAnalizer::UpdateDeviceNotifyResponse(resResponse, getLocalMachineId(), getLocalEbusId(), (UINT64)getpid(), (UINT64)m_pMqttConntion);
  562. std::cout << "TID [" << GetCurrentThreadId() << "] BusUnitLogic:: PACKET_CMD_OPEN [" << (const char*)resTopic << "] " << "msg body" << resResponse.encode() << endl; //
  563. PacketAnalizer::UpdatePacketTopic(&resResponse, (const char*)resTopic, m_strClientID.c_str());
  564. PublishAction(&resResponse, (const char*)resTopic, m_pMqttConntion);
  565. //m_pPacketSendingQue->InQueue(resResponse);
  566. return RET_SUCCEED;
  567. }
  568. if (cmd == PACKET_CMD_CLOSE)
  569. {
  570. //CLOSE 客户端主动断开
  571. }
  572. RET_STATUS ret = Request(pCmd, &resResponse);
  573. //PacketAnalizer::GetPacketRetCode(&resResponse, ret);
  574. std::cout << "BusUnitLogic::ProcessRequest get resp" << resResponse.encode() << endl;
  575. std::cout << "BusUnitLogic::ProcessRequest return by [" << (const char*)resTopic << "] resp" << resResponse.encode() << endl;
  576. PacketAnalizer::UpdatePacketTopic(&resResponse, (const char*)resTopic, m_strClientID.c_str());
  577. PublishAction(&resResponse, (const char*)resTopic, m_pMqttConntion);
  578. //m_pPacketSendingQue->InQueue(resResponse);
  579. return ret;
  580. }
  581. //notify to lower layer
  582. RET_STATUS SYSTEM_CALL BusUnitLogic::CmdToLogicDev(ResDataObject PARAM_IN *pCmd)
  583. {
  584. assert(0);//not happening
  585. return RET_FAILED;
  586. }
  587. //errors,warnings
  588. void BusUnitLogic::SetErrorInfo(int errCode, char *pErrInfo)
  589. {
  590. }
  591. void BusUnitLogic::SetWarningInfo(int warningCode, char *pWarningInfo)
  592. {
  593. }
  594. bool SYSTEM_CALL BusUnitLogic::CheckBusIdsExistance(const char *pszBusId)
  595. {
  596. //ResDataObject ConfigDrvList;
  597. //GetDriverConfigFiles(ConfigDrvList);
  598. //map<string, string> HitCheck;
  599. ////check static first
  600. //for (size_t i = 0; i < ConfigDrvList.size(); i++)
  601. //{
  602. // ResDataObject BusId;
  603. // ResDataObject DriverBusId;
  604. // if (GetDriverEbusId(ConfigDrvList.GetKey(i), BusId, DriverBusId))
  605. // {
  606. // map<string, string>::iterator iter = HitCheck.find((const char*)BusId);
  607. // if (iter != HitCheck.end())
  608. // {
  609. // //exist one
  610. // //mLog::Warn("Same BusId:%s on both Driver\nDrvA:%s\nDrvB:%s", (const char*)BusId, ConfigDrvList.GetKey(i), iter->second.c_str());
  611. // }
  612. // HitCheck[(const char*)BusId] = ConfigDrvList.GetKey(i);
  613. // if (pszBusId)
  614. // {
  615. // iter = HitCheck.find(pszBusId);
  616. // if (iter != HitCheck.end())
  617. // {
  618. // //exist one
  619. // //mLog::Warn("Same BusId:%s on Driver\nDrv:%s\nRequest BusId:%s", (const char*)BusId, ConfigDrvList.GetKey(i), pszBusId);
  620. // }
  621. // }
  622. // }
  623. //}
  624. if (pszBusId)
  625. {
  626. //check live second
  627. map<string, vector<TargetDriverInfo>>::iterator iter = m_pProcessInfo->begin();
  628. while (iter != m_pProcessInfo->end())
  629. {
  630. if (iter->first == pszBusId)
  631. {
  632. //mLog::Warn("Same BusId:{$} Already on the run...", pszBusId);
  633. return false;
  634. }
  635. ++iter;
  636. }
  637. }
  638. return true;
  639. }
  640. bool SYSTEM_CALL BusUnitLogic::LoadAllConfigDrivers()
  641. {
  642. bool ret = true;
  643. //get list of fulldrvlist
  644. ResDataObject FullDrvList;
  645. GetFullDriverConfigFiles(FullDrvList);
  646. //get list of configdrvlist
  647. ResDataObject ConfigDrvList;
  648. GetDriverConfigFiles(ConfigDrvList);
  649. if (CheckBusIdsExistance(0) == false)
  650. {
  651. return false;
  652. }
  653. //add second
  654. for (size_t i = 0; i < FullDrvList.size(); i++)
  655. {
  656. ResDataObject BusId;
  657. ResDataObject DriverBusId;
  658. //get ebus driver path
  659. if (GetDriverEbusId(FullDrvList.GetKey(i), BusId, DriverBusId))
  660. {
  661. ret &= m_pFullDriverList->AddDriver(DriverBusId);
  662. if (ret == false)
  663. {
  664. //mLog::FERROR("AddDriver of FullDrv:{$} Failed.", FullDrvList.GetKey(i));
  665. }
  666. }
  667. else
  668. {
  669. //mLog::FERROR("GetDriverEbusId configfile:{$} Failed.", FullDrvList.GetKey(i));
  670. }
  671. }
  672. for (size_t i = 0; i < ConfigDrvList.size(); i++)
  673. {
  674. ResDataObject BusId;
  675. ResDataObject DriverBusId;
  676. if (GetDriverEbusId(ConfigDrvList.GetKey(i), BusId, DriverBusId))
  677. {
  678. ret &= m_pConfigDriverList->AddDriver(DriverBusId);
  679. if (ret == false)
  680. {
  681. //mLog::FERROR("AddDriver of ConfigDrv:{$} Failed.", ConfigDrvList.GetKey(i));
  682. }
  683. }
  684. else
  685. {
  686. //mLog::FERROR("GetDriverEbusId configfile:{$} Failed.", ConfigDrvList.GetKey(i));
  687. }
  688. }
  689. return ret;
  690. }
  691. std::string GetCurTime64ToString() {
  692. time_t now;
  693. struct tm t1;
  694. time(&now); // 获取当前UTC时间
  695. localtime_r(&now, &t1); // 转换为本地时间(线程安全)
  696. return FormatstdString("%04d%02d%02d%02d%02d%02d",
  697. t1.tm_year + 1900,
  698. t1.tm_mon + 1,
  699. t1.tm_mday,
  700. t1.tm_hour,
  701. t1.tm_min,
  702. t1.tm_sec);
  703. }
  704. int DATA_ACTION BusUnitLogic::MakeDriverNotify(const char *pszDriverpath, bool Add)
  705. {
  706. RET_STATUS ret = RET_SUCCEED;
  707. //exiting...
  708. if ((*m_pExitFlag) != 0)
  709. {
  710. return RET_INVALID;
  711. }
  712. ResDataObject NotifyData;
  713. ResDataObject theContext;
  714. theContext.add(pszDriverpath, "");
  715. if (Add)
  716. {
  717. if (m_pConfigDriverList->AddDriver(pszDriverpath))
  718. {
  719. //printf("AddDriver %s ok\n", pszDriverpath);
  720. //mLog::FINFO("AddDriver {$} ok\n", pszDriverpath);
  721. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_ADD, m_pConfigDriverList->GetKey(), theContext);
  722. CmdFromLogicDev(&NotifyData);
  723. //PublishAction(&NotifyData, (m_strEBusRoot + "/Notify").c_str(), m_pMqttConntion);
  724. }
  725. else
  726. {
  727. //printf("AddDriver %s failed\n", pszDriverpath);
  728. //mLog::FERROR("AddDriver {$} failed\n", pszDriverpath);
  729. ret = RET_FAILED;
  730. }
  731. }
  732. else
  733. {
  734. if (m_pConfigDriverList->DelDriver(pszDriverpath))
  735. {
  736. //printf("DelDriver %s ok\n", pszDriverpath);
  737. //mLog::FINFO("DelDriver {$} ok\n", pszDriverpath);
  738. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_DEL, m_pConfigDriverList->GetKey(), theContext);
  739. CmdFromLogicDev(&NotifyData);
  740. //PublishAction(&NotifyData, (m_strEBusRoot + "/Notify").c_str(), m_pMqttConntion);
  741. }
  742. else
  743. {
  744. //printf("DelDriver %s failed\n", pszDriverpath);
  745. //mLog::FERROR("DelDriver {$} failed\n", pszDriverpath);
  746. ret = RET_FAILED;
  747. }
  748. }
  749. return ret;
  750. }
  751. int GetGrpcPort()
  752. {
  753. int port = 9000;
  754. //Detector_ecomdemo_demo_1234.json
  755. if (GetConfigMode() == CCOS_PROC_CHANNEL)
  756. return port;
  757. string devType = GetMajorID();
  758. string major,type;
  759. size_t pos = devType.find_first_of('_');
  760. if (pos != string::npos)
  761. {
  762. major = devType.substr(0, pos);
  763. type = devType.substr(pos + 1);
  764. if (major.length() > 0 && type.length() > 0)
  765. {
  766. try
  767. {
  768. ResDataObject resSrvConf;
  769. string ccosDir = GetProcessDirectory();
  770. ccosDir += "\\srvconf.json";
  771. resSrvConf.loadFile(ccosDir.c_str());
  772. if (resSrvConf.GetKeyCount("PortMap") > 0)
  773. {
  774. for (int x = 0; x < resSrvConf["PortMap"].size(); x++)
  775. {
  776. if ((string)resSrvConf["PortMap"][x]["Type"] == major)
  777. {
  778. int y = 0, idx;
  779. int ccosProcBasePort = (int)resSrvConf["PortMap"][x]["RPCPort"];
  780. for (; y < resSrvConf["PortMap"][x]["ProcMap"].size(); y++)
  781. {
  782. idx = (int)resSrvConf["PortMap"][x]["ProcMap"][y]["Index"];
  783. if ((string)resSrvConf["PortMap"][x]["ProcMap"][y]["Name"] == type)
  784. {
  785. //got it
  786. if (idx == -1)
  787. idx = 0;
  788. //mLog::FINFO("Got config for {$} port index {$} at srvconf.json",devType, idx);
  789. return ccosProcBasePort + 2 * idx;
  790. }
  791. }
  792. return ccosProcBasePort;
  793. }
  794. }
  795. }
  796. }
  797. catch (...)
  798. {
  799. }
  800. }
  801. }
  802. //mLog::FWARN("No found portmap for {$}", devType);
  803. return port;
  804. }
  805. int ProcessCcosProcConfig(string devType, string devVendor, string devProduct, string devSerilID, int &ccosProcBasePort, bool install)
  806. {
  807. string ccosDir = GetProcessDirectory();
  808. ccosDir += "\\srvconf.json";
  809. //mLog::FINFO("Try scan {$} for ccosproc portmap configration by {$}:{$}:{$} for {$}", ccosDir, devType, devVendor, devProduct, install?"install":"uninstall");
  810. ResDataObject resConf;
  811. try
  812. {
  813. resConf.loadFile(ccosDir.c_str());
  814. bool bFind = false;
  815. string findName = devVendor + "_" + devProduct + "_" + devSerilID;
  816. if (resConf.GetKeyCount("PortMap") > 0)
  817. {
  818. for (int x = 0; x < resConf["PortMap"].size(); x++)
  819. {
  820. if ((string)resConf["PortMap"][x]["Type"] == devType)
  821. {
  822. int y = 0, idx;
  823. int maxPort = 0;
  824. ccosProcBasePort = (int)resConf["PortMap"][x]["HTTPPort"];
  825. for (; y < resConf["PortMap"][x]["ProcMap"].size(); y++)
  826. {
  827. idx = (int)resConf["PortMap"][x]["ProcMap"][y]["Index"];
  828. if (idx > maxPort)
  829. maxPort = idx;
  830. if ((string)resConf["PortMap"][x]["ProcMap"][y]["Name"] == findName||
  831. (string)resConf["PortMap"][x]["ProcMap"][y]["Name"] == "Default")
  832. {
  833. bFind = true;
  834. //got it
  835. //mLog::FINFO("Got config port index {$} at srvconf.json", idx);
  836. break;
  837. }
  838. }
  839. if (install && !bFind)
  840. {
  841. //需要添加
  842. ResDataObject newconf;
  843. newconf.add("Name", findName.c_str());
  844. newconf.add("Index", maxPort + 1 );
  845. resConf["PortMap"][x]["ProcMap"].add("", newconf);
  846. //mLog::FINFO("Not found at srvconf for {$} add conf {$}", findName, newconf.encode());
  847. resConf.SaveFile(ccosDir.c_str());
  848. return maxPort + 1;
  849. }
  850. else if (install && bFind)
  851. {
  852. //已经有这个配置了,直接返回即可
  853. if (idx == -1)
  854. {
  855. maxPort = 0;
  856. resConf["PortMap"][x]["ProcMap"].eraseOneOf("", 0);
  857. ResDataObject newconf;
  858. newconf.add("Name", findName.c_str());
  859. newconf.add("Index", maxPort );
  860. resConf["PortMap"][x]["ProcMap"].add("", newconf);
  861. //mLog::FINFO("Not found at srvconf for {$} add conf {$}", findName, newconf.encode());
  862. resConf.SaveFile(ccosDir.c_str());
  863. return maxPort;
  864. }
  865. //mLog::FINFO("found port=[{$}] at srvconf for {$} add conf ",maxPort, findName);
  866. return maxPort ;
  867. }
  868. else if(!install && bFind)
  869. {
  870. //需要卸载
  871. resConf["PortMap"][x]["ProcMap"].eraseOneOf("", y);
  872. if (resConf["PortMap"][x]["ProcMap"].size() <= 0)
  873. {
  874. ResDataObject defut;
  875. defut.add("Name", "Default");
  876. defut.add("Index", "-1");
  877. resConf["PortMap"][x]["ProcMap"].add("", defut);
  878. }
  879. //mLog::FINFO("uninstall found index={$} at srvconf for {$} ", y, findName);
  880. resConf.SaveFile(ccosDir.c_str());
  881. return y;
  882. }
  883. else
  884. {
  885. //mLog::FINFO("?? install=[{$}] found={$} index={$} at srvconf for {$} ", install, bFind, findName);
  886. }
  887. }
  888. }
  889. }
  890. }
  891. catch (...)
  892. {
  893. }
  894. //mLog::FINFO("INSTALL Driver had no right port");
  895. return -1;
  896. }
  897. void TrimeSDKPath(string& sdkPath)
  898. {
  899. if (sdkPath.length() > 0)
  900. {
  901. if (sdkPath[0] == '\\' || sdkPath[0] == '/')
  902. sdkPath = sdkPath.substr(1);
  903. if (sdkPath.length() > 0)
  904. {
  905. if (sdkPath[sdkPath.length() - 1] == '\\' || sdkPath[sdkPath.length() - 1] == '/')
  906. {
  907. sdkPath = sdkPath.substr(0, sdkPath.length() - 1);
  908. }
  909. }
  910. }
  911. }
  912. string GetSDKPath(const char* pszDriverPath, int &nServerIdx)
  913. {
  914. string sdkPath;
  915. nServerIdx = -1;
  916. try
  917. {
  918. ResDataObject resCtx;
  919. resCtx.loadFile(pszDriverPath);
  920. if (resCtx.GetKeyCount("CONFIGURATION") <= 0)
  921. return "";
  922. if (resCtx["CONFIGURATION"].GetKeyCount("SDKPath") <= 0)
  923. {
  924. return "";
  925. }
  926. sdkPath = (const char*)resCtx["CONFIGURATION"]["SDKPath"];
  927. TrimeSDKPath(sdkPath);
  928. if (resCtx["CONFIGURATION"].GetKeyCount("ServerID") > 0)
  929. {
  930. nServerIdx = (int)resCtx["CONFIGURATION"]["ServerID"];
  931. }
  932. }
  933. catch (...)
  934. {
  935. }
  936. return sdkPath;
  937. }
  938. int CheckDuplicateSDK(const char* pszDriverPath)
  939. {
  940. int nCount = 0;
  941. ResDataObject resCtx;
  942. try
  943. {
  944. resCtx.loadFile(pszDriverPath);
  945. if (resCtx.GetKeyCount("CONFIGURATION") <= 0)
  946. {
  947. //mLog::FWARN("Driver {$} content no CONFIGURATION", pszDriverPath);
  948. return 0;
  949. }
  950. ResDataObject conf = resCtx["CONFIGURATION"];
  951. string sdkPath;
  952. if (conf.GetKeyCount("SDKPath") <= 0)
  953. {
  954. //mLog::FDEBUG("Driver {$} content no SDKPath", pszDriverPath);
  955. return 0;
  956. }
  957. sdkPath = (const char*)conf["SDKPath"];
  958. TrimeSDKPath(sdkPath);
  959. ResDataObject fileList;
  960. GetSpecificDriverConfigFiles(fileList, false);
  961. int idx[100], max = -1;
  962. //mLog::FINFO("Include Driver {$} Has {$} Devices", pszDriverPath, fileList.size());
  963. for (int x = 0; x < fileList.size(); x++)
  964. {
  965. int nSrvIdx = -1;
  966. string dvrSDKPath = GetSDKPath(fileList.GetKey(x), nSrvIdx);
  967. //get ebus driver path
  968. idx[x] = -1;
  969. if (dvrSDKPath.length() > 0)
  970. {
  971. if (dvrSDKPath.substr(0, sdkPath.length()) == sdkPath)
  972. {
  973. //mLog::FINFO("Got Same SDK path of Driver {$} at Devices{$} of ServerIdx=[{$}]", pszDriverPath, fileList.GetKey(x), nSrvIdx);
  974. idx[x] = nSrvIdx;
  975. if (nSrvIdx > max)
  976. max = nSrvIdx;
  977. nCount++;
  978. }
  979. }
  980. }
  981. //没有洞
  982. if (nCount == max + 2)
  983. {
  984. //mLog::FINFO("Driver {$} SDK Installed Sorted of mine index=[{$}]", pszDriverPath, nCount);
  985. resCtx["CONFIGURATION"].update("ServerID", nCount - 1);
  986. resCtx.SaveFile(pszDriverPath);
  987. return nCount - 1;
  988. }
  989. //
  990. sort(idx, idx + fileList.size() - 1);
  991. //肯定有-1, ImageSave/Demo设备/子系统等等
  992. for (int x = 1; x < fileList.size(); x++)
  993. {
  994. if (idx[x] >= 0)
  995. {
  996. if ((idx[x] - idx[x - 1]) > 1)
  997. {
  998. //mLog::FINFO("Driver {$} SDK Installed unSorted ; Got mine index=[{$}]", pszDriverPath, idx[x - 1] + 1);
  999. //这里有洞,取洞的下一个值
  1000. resCtx["CONFIGURATION"].update("ServerID", idx[x - 1] + 1);
  1001. resCtx.SaveFile(pszDriverPath);
  1002. return idx[x-1] + 1;
  1003. }
  1004. }
  1005. }
  1006. //mLog::FINFO("Driver {$} SDK Installed Sorted 2 of mine index=[{$}]", pszDriverPath, nCount);
  1007. resCtx["CONFIGURATION"].update("ServerID", nCount - 1);
  1008. resCtx.SaveFile(pszDriverPath);
  1009. return nCount - 1;
  1010. }
  1011. catch (...)
  1012. {
  1013. //mLog::FWARN("Driver {$} Configruation read content error", pszDriverPath);
  1014. return 0;
  1015. }
  1016. }
  1017. int DATA_ACTION BusUnitLogic::ConfigLoadDriver(const char *pszDriverpath, char *pszFixDriverpath, DWORD FixDrvLen, ResDataObject resValue, ResDataObject& resConfig, ResDataObject& resCcosProcConf)
  1018. {
  1019. int ret = RET_SUCCEED;
  1020. bool X64Driver = true;
  1021. ResDataObject fileList;
  1022. //find driver from fulldrvlist
  1023. //for test
  1024. //mLog::FINFO("Enter ConfigLoadDriver:{$}\n", pszDriverpath);
  1025. LogicDriver* pDPC = (LogicDriver*)GetDrvDPC();
  1026. if (pDPC == 0)
  1027. {
  1028. //mLog::FINFO("GetDrvDPC failed");
  1029. return RET_FAILED;
  1030. }
  1031. m_bConfigRemoveDriver = true;
  1032. pDPC->Thread_Lock(2000);
  1033. //mLog::FINFO("DPC lock ok");
  1034. //find x64
  1035. if (GetSpecificDriverConfigFiles(fileList, true))
  1036. {
  1037. //check x64FLAG
  1038. //assert(0);//NOT FINISHED YET
  1039. //exist x64
  1040. for (size_t i = 0; i < fileList.size(); i++)
  1041. {
  1042. ResDataObject BusId;
  1043. ResDataObject DriverBusId;
  1044. //get ebus driver path
  1045. if (GetDriverEbusId(fileList.GetKey(i), BusId, DriverBusId))
  1046. {
  1047. //for test
  1048. //mLog::FINFO("file[{$}] File:{$}\n Buspath:{$}\n",i, fileList.GetKey(i), (const char *)DriverBusId);
  1049. ///DevCareRayRF/Detector/driver/CareRay/1800RF/1234/{18CAB88A-C61C-4BB2-AC28-184FDD4FD160}
  1050. // CCOS/DEVICE/Detecor/CareRay/1800RF
  1051. vector<string> items;
  1052. SplitDevicePath(DriverBusId, items);
  1053. string ccosPath = "CCOS/DEVICE/";
  1054. if (items.size() >= 5)
  1055. ccosPath = ccosPath + items[1] + "/" + items[3] + "/" + items[4];
  1056. //mLog::FINFO("file[{$}] File:{$} CcosPath:{$}\n", i, fileList.GetKey(i), ccosPath);
  1057. if (DriverBusId == pszDriverpath || ccosPath == pszDriverpath)
  1058. {
  1059. string FullFilePath = fileList.GetKey(i);
  1060. //copy configuration
  1061. //make new title
  1062. string TargetFileTitle = GetFileTitle(FullFilePath);
  1063. string TimePos = GetCurTime64ToString();
  1064. string NewTargetFileTitle = FormatstdString("\\%s_%s.xml", TargetFileTitle.c_str(), TimePos.c_str());
  1065. //make full filepath
  1066. //ResDataObject DriverConfigPath = GetDriverConfigPath();
  1067. string DriverConfigPath = GetProcessDirectory(); //GetFileDirectory(FullFilePath);//...\FullConfig
  1068. //DriverConfigPath = GetFileDirectory(DriverConfigPath);//...procDir
  1069. DriverConfigPath += "\\DriverConfig";
  1070. string FullNewTargetFilePath = DriverConfigPath.c_str();
  1071. FullNewTargetFilePath += NewTargetFileTitle;
  1072. //for test
  1073. //mLog::FINFO("Got Match:{$}\nCopy: Org:{$}\nDes:{$}\n", FullFilePath.c_str(), fileList.GetKey(i), FullNewTargetFilePath.c_str());
  1074. if (std::filesystem::copy_file(
  1075. fileList.GetKey(i), // 源文件路径
  1076. FullNewTargetFilePath.c_str(), // 目标文件路径
  1077. std::filesystem::copy_options::overwrite_existing))// 覆盖已存在文件
  1078. {
  1079. TargetDriverInfo DrvInfo;
  1080. if (GetDriverEbusId(FullNewTargetFilePath.c_str(), DrvInfo.m_RootBusId, DrvInfo.m_DriverBusId, true) == false)
  1081. {
  1082. return RET_FAILED;
  1083. }
  1084. items.clear();
  1085. SplitDevicePath((const char*)DrvInfo.m_DriverBusId, items);
  1086. //这个时候item还在
  1087. //刷新端口
  1088. int newPort = -1;
  1089. int basePort = 9001;
  1090. if (items.size() >= 6)
  1091. newPort = ProcessCcosProcConfig(items[1], items[3], items[4], items[5], basePort, true);
  1092. if (ccosPath == pszDriverpath)
  1093. {
  1094. ///DevPSGRF/Generator/Dr/PSGRF/HF/05274E0D/{18FDF176-DECE-445F-A52C-A14BDD3AC2C1}
  1095. vector<string> idItems;
  1096. SplitDevicePath((const char*)DrvInfo.m_DriverBusId, idItems);
  1097. if (idItems.size() > 5)
  1098. {
  1099. ccosPath += "/";
  1100. ccosPath += idItems[5];
  1101. }
  1102. //mLog::FINFO("Got new devPath {$} transfer to ccos path {$}", (const char*)DrvInfo.m_DriverBusId, ccosPath);
  1103. //resNewDevPath = ccosPath.c_str();
  1104. }
  1105. //got match
  1106. if (CheckBusIdsExistance(DrvInfo.m_RootBusId) == false)
  1107. {
  1108. //exist bus id
  1109. UnloadDriver(DrvInfo.m_RootBusId);
  1110. }
  1111. //reload
  1112. //检查重复的SDK目录
  1113. CheckDuplicateSDK(FullNewTargetFilePath.c_str());
  1114. if ((int)resValue != 2)
  1115. {
  1116. resConfig.clear();
  1117. if ((int)resValue == 1)
  1118. {
  1119. ret = LoadAllConfigDriver(true, &resConfig);
  1120. }
  1121. else
  1122. {
  1123. ret = LoadAllConfigDriver(true);
  1124. usleep(6000000);//must sleep 6s
  1125. }
  1126. }
  1127. else
  1128. {
  1129. //mLog::FINFO("Notify Channel to startup the new driver proc.");
  1130. //等于2的时候,不启进程,让Channel 启动进程
  1131. //std::function<void(LogicClient*, const char*, int)>;
  1132. //HANDLE hOk = CreateEvent(NULL, FALSE, FALSE, "");
  1133. while (1)
  1134. {
  1135. //mLog::FINFO("Try Notify Channel to LoadAllConfigDriver ");
  1136. LogicClient startupClient("LoadConfigDriver_" + to_string(rand()), "", "TEMP", false);
  1137. if (startupClient.Open("/ccosChannel", ACTION, "", 2000, nullptr) == RET_SUCCEED)
  1138. {
  1139. //mLog::FINFO("Channel opened . try action.");
  1140. ResDataObject resReq,resRes;
  1141. int ret = startupClient.Action("LoadAllConfigDriver", resReq, resRes, 2000, "ccosChannel");
  1142. //mLog::FINFO("Channel Action ret ={$}. with resp {$}", ret, resRes.encode());
  1143. startupClient.Close();
  1144. break;
  1145. }
  1146. else
  1147. {
  1148. //mLog::FERROR("Open Channel failed for {$} try again.", ccosPath);
  1149. }
  1150. }
  1151. resConfig.clear();
  1152. resConfig.update(ccosPath.c_str(), basePort + newPort * 2);
  1153. basePort;
  1154. }
  1155. if (ret >= RET_SUCCEED) {
  1156. snprintf(pszFixDriverpath, FixDrvLen, "%s", DrvInfo.m_DriverBusId.encode());
  1157. }
  1158. //mLog::FINFO("LoadAllConfigDriver return:{$}\n", ret);
  1159. m_bConfigRemoveDriver = false;
  1160. pDPC->Thread_UnLock();
  1161. //mLog::FINFO("DPC Unlock ok");
  1162. return ret;
  1163. }
  1164. else
  1165. {
  1166. //mLog::FERROR("CopyFile failed\n");
  1167. }
  1168. }
  1169. }
  1170. else
  1171. {
  1172. //mLog::FERROR("GetDriverEbusId failed\n");
  1173. }
  1174. }
  1175. }
  1176. else
  1177. {
  1178. //mLog::FERROR("GetSpecificDriverConfigFiles failed\n");
  1179. }
  1180. pDPC->Thread_UnLock();
  1181. //mLog::FINFO("DPC Unlock ok");
  1182. m_bConfigRemoveDriver = false;
  1183. return RET_SUCCEED;
  1184. }
  1185. bool SYSTEM_CALL BusUnitLogic::CheckAndKillLiveDriver(const char *pszDriverpath, bool bRemoveDriver)
  1186. {
  1187. //printf("Try Del Driver:%s\n", pszDriverpath);
  1188. //mLog::FINFO("Try Del Driver:{$}\n", pszDriverpath);
  1189. map<string, vector<TargetDriverInfo>>::iterator iter = m_pProcessInfo->begin();
  1190. while (iter != m_pProcessInfo->end())
  1191. {
  1192. for (size_t DriverIdx = 0; DriverIdx < iter->second.size(); DriverIdx++)
  1193. {
  1194. string DrvBusId = (const char*)(iter->second)[DriverIdx].m_DriverBusId;
  1195. //mLog::FINFO("Test Match:{$}\n", DrvBusId.c_str());
  1196. if (DrvBusId == pszDriverpath)
  1197. {
  1198. //mLog::FINFO("Got Match:{$}\n", DrvBusId.c_str());
  1199. //got one
  1200. pid_t targetPid = iter->second[DriverIdx].m_info.process_id;
  1201. if (kill(targetPid, 0) == 0)
  1202. {
  1203. //process exist
  1204. //mLog::FINFO("Target Process Exist");
  1205. string strBusIdCopy = DrvBusId;
  1206. LogicClient chClient1("CheckAndKillLiveDriver_temp","driver", "", false);
  1207. chClient1.SetRouter(CCOS_PACKET_ROUTE_LOCAL);
  1208. DrvBusId = "/";
  1209. DrvBusId += iter->first.c_str();
  1210. ////mLog::FINFO("DrvBusId :{$}\n", DrvBusId.c_str());
  1211. //mLog::FINFO("open :{$}\n", strBusIdCopy.c_str());
  1212. int nRet = -1;
  1213. if (chClient1.Open(strBusIdCopy.c_str(), ALL_ACCESS, "", ONE_ACTION_TIMEOUT) >= RET_SUCCEED)
  1214. {
  1215. //if (strBusIdCopy.find("Detector"))//disconnect before Del
  1216. //{
  1217. // bool bret = false;
  1218. // ACTION_SYNC_MODE syncmode = chClient1.GetRequestSyncMode();
  1219. // //mLog::FINFO("RequestSyncMode is {$}\n",syncmode);
  1220. // if (syncmode != ACTION_SYNC)
  1221. // {
  1222. // bret = chClient1.SetRequestSyncMode(ACTION_SYNC);
  1223. // //mLog::FINFO("SetRequestSyncMode to sync\n");
  1224. // }
  1225. // ResDataObject req, resp;
  1226. // int nRet = chClient1.Action("DisConnect", req, resp, ONE_ACTION_TIMEOUT);
  1227. // if (nRet >= RET_SUCCEED)
  1228. // {
  1229. // //mLog::FINFO("Succeed Action: DisConnect\n");
  1230. // Sleep(2000);//wait detector finish the disconnect.UI send cmd wait 3s
  1231. // }
  1232. // else
  1233. // {
  1234. // //mLog::FINFO("Failed Action: DisConnect ret = {$}\n", nRet);
  1235. // }
  1236. // if (bret)
  1237. // {
  1238. // chClient1.SetRequestSyncMode(syncmode);
  1239. // //mLog::FINFO("SetRequestSyncMode back\n");
  1240. // }
  1241. //}
  1242. ResDataObject req;
  1243. nRet = chClient1.Action_Req("ExitDriverProc", req, ONE_ACTION_TIMEOUT);
  1244. if (nRet >= RET_SUCCEED)
  1245. {
  1246. chClient1.Close();
  1247. // 等待进程退出
  1248. int waitCount = 0;
  1249. const int maxWait = ONE_ACTION_TIMEOUT / 100; // 转换为100ms单位
  1250. while (waitCount < maxWait) {
  1251. if (kill(targetPid, 0) != 0 && errno == ESRCH) {
  1252. break; // 进程已退出
  1253. }
  1254. usleep(100 * 1000); // 100ms
  1255. waitCount++;
  1256. }
  1257. // 超时后强制终止
  1258. if (kill(targetPid, 0) == 0) {
  1259. kill(targetPid, SIGKILL);
  1260. }
  1261. if (bRemoveDriver)
  1262. {
  1263. const char* configPath = (const char*)(iter->second)[DriverIdx].m_CcosProcInfo["DriverConfigPath"];
  1264. if (unlink(configPath) == 0)
  1265. {
  1266. iter->second.erase(iter->second.begin() + DriverIdx);
  1267. if (iter->second.empty()) {
  1268. iter = m_pProcessInfo->erase(iter);
  1269. }
  1270. else {
  1271. ++iter;
  1272. }
  1273. return true;
  1274. }
  1275. else
  1276. {
  1277. int err = errno;
  1278. // 记录错误信息
  1279. }
  1280. }
  1281. else
  1282. {
  1283. if (iter->second.empty()) {
  1284. iter = m_pProcessInfo->erase(iter);
  1285. }
  1286. else {
  1287. ++iter;
  1288. }
  1289. return true;
  1290. }
  1291. }
  1292. else
  1293. {
  1294. //printf("Failed Action:ExitDriverProc -> %s...\n", strBusIdCopy.c_str());
  1295. ////mLog::FERROR("Failed Action: ExitDriverProc -> %s ...\n", strBusIdCopy.c_str());
  1296. //mLog::FINFO("Failed Action: ExitDriverProc ret {$}-> {$} ...\n",nRet, strBusIdCopy.c_str());
  1297. chClient1.Close();
  1298. }
  1299. //if (chClient1.Action(pszAction, req, res, Timeout) < RET_SUCCEED)
  1300. //{
  1301. // printf("Failed Action:%s ...\n",pszAction);
  1302. // //mLog::FERROR("Failed Action: {$} ...\n", pszAction);
  1303. // chClient1.Close();
  1304. //}
  1305. //else
  1306. //{
  1307. // printf("Succeed Action:%s ...\n", pszAction);
  1308. // //mLog::FINFO("Succeed Action: {$} ...\n", pszAction);
  1309. // return true;
  1310. //}
  1311. //chClient1.Close();
  1312. }
  1313. else
  1314. {
  1315. //printf("Open local %s Failed\n", DrvBusId.c_str());
  1316. //mLog::FINFO("Open local {$} Failed ret {$}\n", strBusIdCopy.c_str(),nRet);
  1317. }
  1318. }
  1319. else
  1320. {
  1321. //mLog::FINFO("Target Process Not Exist");
  1322. //mLog::FINFO("Try Delete Driver File:{$}\n", (const char*)(iter->second)[DriverIdx].m_CcosProcInfo["DriverConfigPath"]);
  1323. if (bRemoveDriver)
  1324. {
  1325. const char* configPath = (const char*)(iter->second)[DriverIdx].m_CcosProcInfo["DriverConfigPath"];
  1326. if (unlink(configPath) == 0)
  1327. {
  1328. iter->second.erase(iter->second.begin() + DriverIdx);
  1329. if (iter->second.empty()) {
  1330. iter = m_pProcessInfo->erase(iter);
  1331. }
  1332. else {
  1333. ++iter;
  1334. }
  1335. return true;
  1336. }
  1337. }
  1338. else
  1339. {
  1340. //mLog::FINFO("Do nothing");
  1341. return true;
  1342. }
  1343. }
  1344. return false;
  1345. }
  1346. }
  1347. ++iter;
  1348. }
  1349. return true;
  1350. }
  1351. int DATA_ACTION BusUnitLogic::ConfigRemoveDriver(const char *pszDriverpath)
  1352. {
  1353. int ret = RET_SUCCEED;
  1354. //mLog::FINFO("Enter ConfigRemoveDriver:{$}\n", pszDriverpath);
  1355. //find driver from configdrvlist
  1356. if (m_pConfigDriverList->IsDriverExist(pszDriverpath) == false)
  1357. {
  1358. //not exist then return succeed.
  1359. //mLog::FINFO("Target Driver Not Exist {$}",pszDriverpath);
  1360. return RET_FAILED;
  1361. }
  1362. LogicDriver* pDPC = (LogicDriver*)GetDrvDPC();
  1363. if (pDPC == 0)
  1364. {
  1365. //mLog::FINFO("GetDrvDPC failed");
  1366. return RET_FAILED;
  1367. }
  1368. m_bConfigRemoveDriver = true;
  1369. pDPC->Thread_Lock(3000);
  1370. //mLog::FINFO("DPC lock ok");
  1371. try{
  1372. //check Live status
  1373. if (CheckAndKillLiveDriver(pszDriverpath))
  1374. {
  1375. ret = MakeDriverNotify(pszDriverpath, false);
  1376. //reload
  1377. ret = LoadAllConfigDriver(true);
  1378. usleep(6000000);//must sleep 6s
  1379. //mLog::FINFO("sleep over");
  1380. }
  1381. else
  1382. {
  1383. ret = RET_FAILED;
  1384. }
  1385. }
  1386. catch (...)
  1387. {
  1388. ret = RET_FAILED;
  1389. //mLog::FINFO("crash");
  1390. }
  1391. pDPC->Thread_UnLock();
  1392. //mLog::FINFO("DPC Unlock ok");
  1393. m_bConfigRemoveDriver = false;
  1394. //mLog::FINFO("ConfigRemoveDriver over");
  1395. return ret;
  1396. }
  1397. //Data Access
  1398. int DATA_ACTION BusUnitLogic::AddDeviceDescrpt(const char PARAM_IN *pDevPath, const char PARAM_IN *pTargetType, const char PARAM_IN *pMachineId, UINT64 ProcId, UINT64 Addr, bool forceAdd)
  1399. {
  1400. DeviceDescript dd;
  1401. //mLog::FINFO("Begin with DevPath={$} TargetType={$} MachineID={$} ProcID={$} Addr={$} ForceAd={$}", pDevPath, pTargetType, pMachineId, ProcId, Addr, forceAdd);
  1402. //exiting...
  1403. if ((*m_pExitFlag) != 0)
  1404. {
  1405. //mLog::FINFO("End with ExitFlag {$}", (int)(*m_pExitFlag));
  1406. return RET_INVALID;
  1407. }
  1408. dd.SetKey(pDevPath);
  1409. dd.m_TargetType = pTargetType;
  1410. dd.m_ProcId = ProcId;
  1411. dd.m_Address = Addr;
  1412. dd.m_MachineId = pMachineId;
  1413. ResDataObject NotifyData;
  1414. ResDataObject theContext;
  1415. dd.GetResDataObject(theContext);
  1416. if(pDevPath[0] == '/')
  1417. {
  1418. //mLog::FINFO("Ebus Path {$}", pDevPath);
  1419. if (m_DevList->AddDriver(dd))
  1420. {
  1421. //mLog::FINFO("AddDriver ok {$}", pDevPath);
  1422. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_ADD, m_DevList->GetKey(), theContext);
  1423. }
  1424. else
  1425. {
  1426. //mLog::FERROR("AddDriver Failed {$}", pDevPath);
  1427. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_ONLINE, m_DevList->GetKey(), theContext);
  1428. }
  1429. //PublishAction(&NotifyData, (m_strEBusRoot + "/Notify").c_str(), m_pMqttConntion);
  1430. }
  1431. else {
  1432. //ccos 的Key
  1433. //mLog::FINFO("CCOS Path {$}", pDevPath);
  1434. if (m_pCcosDevList->AddDriver(dd))
  1435. {
  1436. //mLog::FINFO("AddDriver ok {$}", pDevPath);
  1437. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_ADD, m_pCcosDevList->GetKey(), theContext);
  1438. }
  1439. else
  1440. {
  1441. //mLog::FERROR("AddDriver Failed {$}", pDevPath);
  1442. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_ONLINE, m_pCcosDevList->GetKey(), theContext);
  1443. }
  1444. //PublishAction(&NotifyData, (m_strEBusRoot + "/Notify").c_str(), m_pMqttConntion);
  1445. }
  1446. CmdFromLogicDev(&NotifyData);
  1447. return RET_SUCCEED;
  1448. }
  1449. int DATA_ACTION BusUnitLogic::Get(const char PARAM_IN *pKey,ResDataObject &Res)
  1450. {
  1451. string Key = pKey;
  1452. if (Key == m_DevList->GetKey())
  1453. {
  1454. ResDataObject arraylist;
  1455. m_DevList->GetResDataObject(arraylist);
  1456. Res.add(m_DevList->GetKey(), arraylist);
  1457. return RET_SUCCEED;
  1458. }
  1459. return RET_FAILED;
  1460. }
  1461. int DATA_ACTION BusUnitLogic::DelDeviceDescrpt(const char PARAM_IN *pDevPath)
  1462. {
  1463. if(pDevPath[0] == '/')
  1464. {
  1465. if (m_DevList->DelVal(pDevPath))
  1466. {
  1467. //3. Notify
  1468. ResDataObject NotifyData;
  1469. ResDataObject theContext;
  1470. theContext.add("DevicePath", pDevPath);
  1471. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_DEL, m_DevList->GetKey(), theContext);
  1472. CmdFromLogicDev(&NotifyData);
  1473. //PublishAction(&NotifyData, (m_strEBusRoot + "/Notify").c_str(), m_pMqttConntion);
  1474. }
  1475. }
  1476. else
  1477. {
  1478. if (m_pCcosDevList->DelVal(pDevPath))
  1479. {
  1480. //3. Notify
  1481. ResDataObject NotifyData;
  1482. ResDataObject theContext;
  1483. theContext.add("DevicePath", pDevPath);
  1484. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_DEL, m_pCcosDevList->GetKey(), theContext);
  1485. CmdFromLogicDev(&NotifyData);
  1486. //PublishAction(&NotifyData, (m_strEBusRoot + "/Notify").c_str(), m_pMqttConntion);
  1487. }
  1488. }
  1489. return RET_SUCCEED;
  1490. }
  1491. int DATA_ACTION BusUnitLogic::SetDeviceStatus(int Status)
  1492. {
  1493. RET_STATUS ret = RET_SUCCEED;
  1494. if ((*m_pState) != Status)
  1495. {
  1496. ResDataObject NotifyData;
  1497. (*m_pState) = Status;
  1498. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_UPDATE, m_pState->GetKey(), m_pState->GetVal());
  1499. ret = CmdFromLogicDev(&NotifyData);
  1500. //string notfiyTopic = m_strEBusRoot + "/Notify";
  1501. //PublishAction(&NotifyData, notfiyTopic.c_str() , m_pMqttConntion);
  1502. }
  1503. return ret;
  1504. }
  1505. int DATA_ACTION BusUnitLogic::SetEthBusSwitch(int Switch)
  1506. {
  1507. RET_STATUS ret = RET_SUCCEED;
  1508. if ((*m_pEnableEthBus) != Switch)
  1509. {
  1510. ResDataObject NotifyData;
  1511. (*m_pEnableEthBus) = Switch;
  1512. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_UPDATE, m_pEnableEthBus->GetKey(), m_pEnableEthBus->GetVal());
  1513. ret = CmdFromLogicDev(&NotifyData);
  1514. //PublishAction(&NotifyData, (m_strEBusRoot + "/Notify").c_str(), m_pMqttConntion);
  1515. }
  1516. return ret;
  1517. }
  1518. int DATA_ACTION BusUnitLogic::SetEthBusRouterIp(const char PARAM_IN *pRouterIp)
  1519. {
  1520. RET_STATUS ret = RET_SUCCEED;
  1521. std::string Param = pRouterIp;
  1522. std::string RouterIp = (*m_pEthBusRouterIp);
  1523. if (RouterIp != Param)
  1524. {
  1525. ResDataObject NotifyData;
  1526. (*m_pEthBusRouterIp) = Param;
  1527. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_UPDATE, m_pEthBusRouterIp->GetKey(), m_pEthBusRouterIp->GetVal());
  1528. ret = CmdFromLogicDev(&NotifyData);
  1529. //PublishAction(&NotifyData, (m_strEBusRoot + "/Notify").c_str(), m_pMqttConntion);
  1530. }
  1531. return ret;
  1532. }
  1533. int DATA_ACTION BusUnitLogic::ExitDriverProc()
  1534. {
  1535. RET_STATUS ret = RET_SUCCEED;
  1536. if ((*m_pExitFlag) == 0)
  1537. {
  1538. ResDataObject NotifyData;
  1539. SetExitFlag(1);
  1540. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_UPDATE, m_pExitFlag->GetKey(), m_pExitFlag->GetVal());
  1541. ret = CmdFromLogicDev(&NotifyData);
  1542. //PublishAction(&NotifyData, (m_strEBusRoot + "/Notify").c_str(), m_pMqttConntion);
  1543. }
  1544. return ret;
  1545. }
  1546. int SYSTEM_CALL BusUnitLogic::GetExitFlag()
  1547. {
  1548. return (*m_pExitFlag);
  1549. }
  1550. int SYSTEM_CALL BusUnitLogic::SetExitFlag(int ExitFlag)
  1551. {
  1552. (*m_pExitFlag) = ExitFlag;
  1553. return 1;
  1554. }
  1555. int SYSTEM_CALL BusUnitLogic::GetbusId(ResDataObject &obj)
  1556. {
  1557. obj = m_pbusID->GetVal();
  1558. return RET_SUCCEED;
  1559. }
  1560. int SYSTEM_CALL BusUnitLogic::GetMachineId(ResDataObject &obj)
  1561. {
  1562. obj = m_pMachineID->GetVal();
  1563. return RET_SUCCEED;
  1564. }
  1565. int SYSTEM_CALL BusUnitLogic::GetProcId(UINT64 &obj)
  1566. {
  1567. obj = (*m_pProcID);
  1568. return RET_SUCCEED;
  1569. }
  1570. int SYSTEM_CALL BusUnitLogic::SetbusId(ResDataObject &obj)
  1571. {
  1572. (*m_pbusID) = (const char *)obj;
  1573. return RET_SUCCEED;
  1574. }
  1575. int SYSTEM_CALL BusUnitLogic::SetMachineId(ResDataObject &obj)
  1576. {
  1577. (*m_pMachineID) = (const char *)obj;
  1578. return RET_SUCCEED;
  1579. }
  1580. int SYSTEM_CALL BusUnitLogic::SetProcId(UINT64 obj)
  1581. {
  1582. (*m_pProcID) = (UINT64)obj;
  1583. return RET_SUCCEED;
  1584. }
  1585. DWORD SYSTEM_CALL BusUnitLogic::GetDeviceCount()
  1586. {
  1587. return (DWORD)m_DevList->m_DeviceList.size();
  1588. }
  1589. bool SYSTEM_CALL BusUnitLogic::GetDeviceDescript(DWORD Idx, ResDataObject &DevPath, ResDataObject &DevType, ResDataObject &MachineId, UINT64 &ProcId, UINT64 &Addr)
  1590. {
  1591. if (m_DevList->m_DeviceList.size() > Idx)
  1592. {
  1593. DevPath = m_DevList->m_DeviceList[Idx].GetKey();
  1594. DevType = m_DevList->m_DeviceList[Idx].m_TargetType.GetVal();
  1595. MachineId = m_DevList->m_DeviceList[Idx].m_MachineId.GetVal();
  1596. ProcId = m_DevList->m_DeviceList[Idx].m_ProcId;
  1597. Addr = m_DevList->m_DeviceList[Idx].m_Address;
  1598. return true;
  1599. }
  1600. return false;
  1601. }
  1602. int SYSTEM_CALL BusUnitLogic::GetDeviceStatus()
  1603. {
  1604. return (*m_pState);
  1605. }
  1606. int SYSTEM_CALL BusUnitLogic::GetEthBusSwitch()
  1607. {
  1608. return (*m_pEnableEthBus);
  1609. }
  1610. int SYSTEM_CALL BusUnitLogic::GetEthBusRouterIp(ResDataObject &obj)
  1611. {
  1612. obj = (*m_pEthBusRouterIp).GetVal();
  1613. return 1;
  1614. }
  1615. /// <summary>
  1616. /// 检查所有驱动进程,如果进程Crash了,需要根据配置重新拉起来
  1617. /// </summary>
  1618. /// <returns></returns>
  1619. void SYSTEM_CALL BusUnitLogic::CheckAllLiveDriver()
  1620. {
  1621. map<string, vector<TargetDriverInfo>>::iterator iter = m_pProcessInfo->begin();
  1622. while (iter != m_pProcessInfo->end())
  1623. {
  1624. if (m_bConfigRemoveDriver)
  1625. {
  1626. //Sleep(2000);
  1627. //mLog::FINFO("ConfigDriver working");
  1628. return;
  1629. }
  1630. //for (size_t DriverIdx = 0; DriverIdx < iter->second.size(); DriverIdx++)
  1631. {
  1632. string DrvBusId = "/";
  1633. DrvBusId += (const char*)iter->first.c_str();
  1634. {
  1635. //got one
  1636. pid_t targetPid = iter->second[0].m_info.process_id;
  1637. if (kill(targetPid, 0) == 0)
  1638. {
  1639. //process exist
  1640. LogicClient chClient1("CheckAllLiveDriver_temp","driver","",false);
  1641. chClient1.SetRouter(CCOS_PACKET_ROUTE_LOCAL);
  1642. if (chClient1.Open(DrvBusId.c_str(), ALL_ACCESS, "", ONE_ACTION_TIMEOUT) >= RET_SUCCEED)
  1643. {
  1644. chClient1.Close();
  1645. }
  1646. else
  1647. {
  1648. //printf("Open local %s Failed while check Live\n", DrvBusId.c_str());
  1649. //mLog::FERROR("Open local {$} Failed while check Live\n", DrvBusId.c_str());
  1650. }
  1651. }
  1652. else
  1653. {
  1654. if (m_bConfigRemoveDriver)
  1655. {
  1656. //mLog::FINFO("ConfigDriver working 2");
  1657. return;
  1658. }
  1659. //target process crashed
  1660. //printf("Autoload Flag:%d \n BusId:%s\n", (bool)(iter->second)[0].m_CcosProcInfo["AutoLoad"], iter->first.c_str());
  1661. //do reload
  1662. if ((bool)(iter->second)[0].m_CcosProcInfo["AutoLoad"])
  1663. {
  1664. memset(&(iter->second)[0].m_info, 0, sizeof(LinuxProcessInfo));
  1665. if (CreateTheProcess_Console_Config((iter->second)[0].m_CcosProcInfo["DriverPath"],
  1666. (iter->second)[0].m_CcosProcInfo["WorkPath"],
  1667. (iter->second)[0].m_info,
  1668. (iter->second)[0].m_CcosProcInfo["ShowWindow"]) == FALSE)
  1669. {
  1670. //printf("Reload Failed.Can't Create Process for config:%s\n",
  1671. // (const char*)(iter->second)[0].m_CcosProcInfo["DriverConfigPath"]);
  1672. //mLog::FERROR("Reload Failed.Can't Create Process for config:{$}", (const char*)(iter->second)[0].m_CcosProcInfo["DriverConfigPath"]);
  1673. }
  1674. else
  1675. {
  1676. //printf("Reload Succeed.Create Process for config:%s Succeed\n",
  1677. // (const char*)(iter->second)[0].m_CcosProcInfo["DriverConfigPath"]);
  1678. //mLog::FINFO("Reload Succeed.Create Process for config:{$} Succeed", (const char*)(iter->second)[0].m_CcosProcInfo["DriverConfigPath"]);
  1679. usleep(6000000);//wait
  1680. }
  1681. }
  1682. else
  1683. {
  1684. //kick iter;
  1685. //printf("Kick crashed process. BusId:%s\n", iter->first.c_str());
  1686. //mLog::FINFO("Kick crashed process. BusId:{$}\n", iter->first.c_str());
  1687. DelDeviceDescrpt(DrvBusId.c_str());
  1688. iter = m_pProcessInfo->erase(iter);
  1689. continue;
  1690. }
  1691. }
  1692. }
  1693. }
  1694. ++iter;
  1695. }
  1696. return;
  1697. }
  1698. int SYSTEM_CALL BusUnitLogic::LoadAllConfigDriver(bool ForReload, ResDataObject* pResource)
  1699. {
  1700. RET_STATUS ret = RET_SUCCEED;
  1701. //this is for dpc call
  1702. bool FullDriverList = false;
  1703. ResDataObject fileList;
  1704. //find driver from fulldrvlist
  1705. if (CheckBusIdsExistance(0) == false)
  1706. {
  1707. //mLog::FERROR("CheckBusIdsExistance(0) == false");
  1708. return RET_FAILED;
  1709. }
  1710. LogicDriver* pDPC = (LogicDriver*)GetDrvDPC();
  1711. if (pDPC == 0)
  1712. {
  1713. //mLog::FERROR("pDPC == 0");
  1714. return RET_FAILED;
  1715. }
  1716. //mLog::FINFO("GetDrvDPC ok");
  1717. //pDPC->Thread_Lock();
  1718. ////mLog::FINFO("DPC lock ok");
  1719. try{
  1720. //find x64
  1721. if (GetSpecificDriverConfigFiles(fileList, FullDriverList))
  1722. {
  1723. //mLog::FINFO("GetSpecificDriverConfigFiles ok");
  1724. map<string,int> ConflictBusIds;
  1725. map<string, string> BusIdMap;//BusId <-> Dir
  1726. map<string, vector<TargetDriverInfo>> LoadDriverMap;
  1727. //exist x64
  1728. for (size_t i = 0; i < fileList.size(); i++)
  1729. {
  1730. TargetDriverInfo DrvInfo;
  1731. if (GetDriverEbusId(fileList.GetKey(i), DrvInfo.m_RootBusId, DrvInfo.m_DriverBusId))
  1732. {
  1733. //get ebus driver path
  1734. if (GetDriverProcInfo(fileList.GetKey(i), DrvInfo.m_CcosProcInfo))
  1735. {
  1736. map<string,string>::iterator BusIdsIter = BusIdMap.find((const char*)DrvInfo.m_RootBusId);
  1737. if (BusIdsIter != BusIdMap.end())
  1738. {
  1739. //same busId Exist
  1740. if (BusIdsIter->second == (const char*)fileList[i])
  1741. {
  1742. //same dir,ok
  1743. }
  1744. else
  1745. {
  1746. //different dir,ng
  1747. ConflictBusIds[BusIdsIter->first] = 1;
  1748. }
  1749. }
  1750. else
  1751. {
  1752. //no BusId exist
  1753. BusIdMap[(const char*)DrvInfo.m_RootBusId] = (const char*)fileList[i];
  1754. }
  1755. LoadDriverMap[(const char *)DrvInfo.m_RootBusId].push_back(DrvInfo);
  1756. }
  1757. else
  1758. {
  1759. //mLog::FINFO("GetDriverProcInfo failed {$} ", fileList.GetKey(i));
  1760. }
  1761. }
  1762. else
  1763. {
  1764. //mLog::FINFO("GetDriverEbusId failed {$} ", fileList.GetKey(i));
  1765. }
  1766. }
  1767. map<string, vector<TargetDriverInfo>>::iterator DelIter;
  1768. //kick same busids drivers
  1769. map<string, int>::iterator ConflictIter = ConflictBusIds.begin();
  1770. while (ConflictIter != ConflictBusIds.end())
  1771. {
  1772. DelIter = LoadDriverMap.find(ConflictIter->first);
  1773. if (DelIter != LoadDriverMap.end())
  1774. {
  1775. //mLog::FERROR("busid:{$} conflict", DelIter->first.c_str());
  1776. for (size_t DriverIdx = 0; DriverIdx < DelIter->second.size(); DriverIdx++)
  1777. {
  1778. const char *pszConfigFilepath = DelIter->second[DriverIdx].m_CcosProcInfo["DriverConfigPath"];//config file path
  1779. //mLog::FERROR("busid:{$} conflict.Ignore ConfigFile:{$}", DelIter->first.c_str(),pszConfigFilepath);
  1780. }
  1781. LoadDriverMap.erase(DelIter);
  1782. }
  1783. ++ConflictIter;
  1784. }
  1785. ConflictBusIds.clear();
  1786. //mLog::FINFO("LoadDriverMap size {$} ", LoadDriverMap.size());
  1787. //kick condition like (same busid but not same procType)
  1788. DelIter = LoadDriverMap.begin();
  1789. while (DelIter != LoadDriverMap.end())
  1790. {
  1791. if (DelIter->second.size() > 1)
  1792. {
  1793. bool ConflictProc = false;
  1794. //more than one driver exist
  1795. for (size_t DriverIdx = 0; DriverIdx < DelIter->second.size() - 1; DriverIdx++)
  1796. {
  1797. if (ConflictProc)
  1798. {
  1799. break;
  1800. }
  1801. //compare each others driverproc
  1802. string DriverProc = "";
  1803. ResDataObject DriverProcessPath;
  1804. GetDriverProcessPath(DelIter->second[DriverIdx].m_CcosProcInfo["DriverConfigPath"], DriverProcessPath);
  1805. DriverProc = (const char*)DriverProcessPath;
  1806. for (size_t CompareIdx = DriverIdx + 1; CompareIdx < DelIter->second.size(); CompareIdx++)
  1807. {
  1808. if (ConflictProc)
  1809. {
  1810. break;
  1811. }
  1812. string CompareProc = "";
  1813. ResDataObject CompareProcessPath;
  1814. GetDriverProcessPath(DelIter->second[CompareIdx].m_CcosProcInfo["DriverConfigPath"], CompareProcessPath);
  1815. CompareProc = (const char*)CompareProcessPath;
  1816. if (CompareProc != DriverProc)
  1817. {
  1818. ConflictBusIds[DelIter->first] = 1;
  1819. ConflictProc = true;
  1820. }
  1821. }
  1822. }
  1823. }
  1824. ++DelIter;
  1825. }
  1826. //kick again
  1827. ConflictIter = ConflictBusIds.begin();
  1828. while (ConflictIter != ConflictBusIds.end())
  1829. {
  1830. DelIter = LoadDriverMap.find(ConflictIter->first);
  1831. if (DelIter != LoadDriverMap.end())
  1832. {
  1833. //mLog::FERROR("busid:{$} processType conflict", DelIter->first.c_str());
  1834. for (size_t DriverIdx = 0; DriverIdx < DelIter->second.size(); DriverIdx++)
  1835. {
  1836. const char* pszConfigFilepath = DelIter->second[DriverIdx].m_CcosProcInfo["DriverConfigPath"];//config file path
  1837. //mLog::FERROR("busid:{$} processType conflict.Ignore ConfigFile:{$}", DelIter->first.c_str(), pszConfigFilepath);
  1838. }
  1839. LoadDriverMap.erase(DelIter);
  1840. }
  1841. ++ConflictIter;
  1842. }
  1843. map<string, vector<TargetDriverInfo>>::iterator iter = LoadDriverMap.begin();
  1844. while (iter != LoadDriverMap.end())
  1845. {
  1846. if (ForReload)
  1847. {
  1848. if (CheckBusIdsExistance(iter->first.c_str()) == false)
  1849. {
  1850. //target exist
  1851. ++iter;
  1852. continue;
  1853. }
  1854. }
  1855. //make full process path
  1856. bool FirstIn = true;
  1857. string ConfigFile;
  1858. string FullDriverPath = "";
  1859. for (size_t DriverIdx = 0; DriverIdx < iter->second.size(); DriverIdx++)
  1860. {
  1861. //make driverpath
  1862. if (FirstIn)
  1863. {
  1864. ResDataObject DriverProcessPath;
  1865. GetDriverProcessPath(iter->second[DriverIdx].m_CcosProcInfo["DriverConfigPath"], DriverProcessPath);
  1866. FullDriverPath = (const char *)DriverProcessPath;
  1867. FirstIn = false;
  1868. }
  1869. ConfigFile = (const char *)iter->second[DriverIdx].m_CcosProcInfo["DriverConfigPath"];
  1870. //get config file title
  1871. string ConfigFileName = GetFileName(ConfigFile);
  1872. FullDriverPath += " " + ConfigFileName;
  1873. }
  1874. //rest all of same busid
  1875. for (size_t DriverIdx = 0; DriverIdx < iter->second.size(); DriverIdx++)
  1876. {
  1877. iter->second[DriverIdx].m_CcosProcInfo["DriverPath"] = FullDriverPath.c_str();//[fullpath of exe] [config1.xml config2.xml ...]
  1878. }
  1879. //create process
  1880. if (CreateTheProcess_Console_Config(iter->second[0].m_CcosProcInfo["DriverPath"],
  1881. iter->second[0].m_CcosProcInfo["WorkPath"],
  1882. iter->second[0].m_info,
  1883. iter->second[0].m_CcosProcInfo["ShowWindow"]) == FALSE)
  1884. {
  1885. //mLog::FERROR("Can't Create Process:{$}", FullDriverPath.c_str());
  1886. }
  1887. else
  1888. {
  1889. //mLog::FINFO("Create Process:{$} ok", FullDriverPath.c_str());
  1890. for (size_t DriverIdx = 0; DriverIdx < iter->second.size(); DriverIdx++)
  1891. {
  1892. (*m_pProcessInfo)[(const char*)iter->second[DriverIdx].m_RootBusId].push_back(iter->second[DriverIdx]);
  1893. MakeDriverNotify((const char *)iter->second[DriverIdx].m_DriverBusId, true);
  1894. }
  1895. }
  1896. ++iter;
  1897. }
  1898. }
  1899. else
  1900. {
  1901. //mLog::FERROR("GetSpecificDriverConfigFiles failed");
  1902. }
  1903. }
  1904. catch (...)
  1905. {
  1906. //mLog::FERROR("crash");
  1907. ret = RET_FAILED;
  1908. }
  1909. //pDPC->Thread_UnLock();
  1910. ////mLog::FINFO("DPC Unlock ok");
  1911. return ret;
  1912. }
  1913. void SYSTEM_CALL BusUnitLogic::UnloadDriver(const char *pszBusId)
  1914. {
  1915. //mLog::FINFO("Enter UnloadDriver:{$}", pszBusId);
  1916. map<string, vector<TargetDriverInfo>>::iterator iter = m_pProcessInfo->find(pszBusId);
  1917. if (iter != m_pProcessInfo->end())
  1918. {
  1919. //found target busid.
  1920. //notify target quit first
  1921. string DrvBusId = "/";
  1922. DrvBusId += (const char*)iter->first.c_str();
  1923. {
  1924. //got one
  1925. pid_t targetPid = iter->second[0].m_info.process_id;
  1926. if (kill(targetPid, 0) == 0)
  1927. {
  1928. //process exist
  1929. LogicClient chClient1("UnloadDriver_temp","driver", "", false);
  1930. chClient1.SetRouter(CCOS_PACKET_ROUTE_LOCAL);
  1931. if (chClient1.Open(DrvBusId.c_str(), ALL_ACCESS, "", ONE_ACTION_TIMEOUT) >= RET_SUCCEED)
  1932. {
  1933. ResDataObject req;
  1934. if (chClient1.Action_Req("ExitDriverProc", req, ONE_ACTION_TIMEOUT) >= RET_SUCCEED)
  1935. {
  1936. //printf("Succeed Action:ExitDriverProc %s ...\n", DrvBusId.c_str());
  1937. //mLog::FINFO("Succeed Action: ExitDriverProc {$} ...\n", DrvBusId.c_str());
  1938. chClient1.Close();
  1939. }
  1940. else
  1941. {
  1942. //printf("Failed Action:ExitDriverProc -> %s...\n", DrvBusId.c_str());
  1943. //mLog::FERROR("Failed Action: ExitDriverProc -> {$} ...\n", DrvBusId.c_str());
  1944. chClient1.Close();
  1945. }
  1946. }
  1947. else
  1948. {
  1949. //printf("Open local %s Failed\n", DrvBusId.c_str());
  1950. //mLog::FERROR("Open local {$} Failed\n", DrvBusId.c_str());
  1951. }
  1952. }
  1953. }
  1954. int waitCount = 0;
  1955. const int maxWait = (ONE_ACTION_TIMEOUT - 1000) / 100; // 转换为100ms单位
  1956. while (waitCount < maxWait) {
  1957. if (kill(iter->second[0].m_info.process_id, 0) != 0 && errno == ESRCH) {
  1958. break; // 进程已退出
  1959. }
  1960. usleep(100 * 1000); // 100ms
  1961. waitCount++;
  1962. }
  1963. // 超时后强制终止
  1964. if (kill(iter->second[0].m_info.process_id, 0) == 0) {
  1965. kill(iter->second[0].m_info.process_id, SIGKILL);
  1966. }
  1967. //make notify
  1968. for (size_t DriverIdx = 0; DriverIdx < iter->second.size(); DriverIdx++)
  1969. {
  1970. MakeDriverNotify((const char *)iter->second[DriverIdx].m_DriverBusId, false);
  1971. }
  1972. //kick busid
  1973. m_pProcessInfo->erase(iter);
  1974. }
  1975. //mLog::FINFO("Exit UnloadDriver:{$}", pszBusId);
  1976. return;
  1977. }
  1978. void SYSTEM_CALL BusUnitLogic::UnloadAllRegistedDrivers()
  1979. {
  1980. map<string, vector<TargetDriverInfo>>::iterator iter = m_pProcessInfo->begin();
  1981. while (iter != m_pProcessInfo->end())
  1982. {
  1983. string DrvBusId = "/";
  1984. DrvBusId += (const char*)iter->first.c_str();
  1985. {
  1986. //got one
  1987. pid_t targetPid = iter->second[0].m_info.process_id;
  1988. if (kill(targetPid, 0) == 0)
  1989. {
  1990. //process exist
  1991. LogicClient chClient1("UnloadAllRegistedDrivers_temp","driver", "", false);
  1992. chClient1.SetRouter(CCOS_PACKET_ROUTE_LOCAL);
  1993. if (chClient1.Open(DrvBusId.c_str(), ALL_ACCESS,"", ONE_ACTION_TIMEOUT) >= RET_SUCCEED)
  1994. {
  1995. ResDataObject req;
  1996. if (chClient1.Action_Req("ExitDriverProc", req, ONE_ACTION_TIMEOUT) >= RET_SUCCEED)
  1997. {
  1998. //printf("Succeed Action:ExitDriverProc %s ...\n", DrvBusId.c_str());
  1999. //mLog::FINFO("Succeed Action: ExitDriverProc {$} ...\n", DrvBusId.c_str());
  2000. chClient1.Close();
  2001. }
  2002. else
  2003. {
  2004. //printf("Failed Action:ExitDriverProc -> %s...\n", DrvBusId.c_str());
  2005. //mLog::FERROR("Failed Action: ExitDriverProc -> {$} ...\n", DrvBusId.c_str());
  2006. chClient1.Close();
  2007. }
  2008. }
  2009. else
  2010. {
  2011. //printf("Open local %s Failed\n", DrvBusId.c_str());
  2012. //mLog::FERROR("Open local {$} Failed\n", DrvBusId.c_str());
  2013. }
  2014. }
  2015. }
  2016. ++iter;
  2017. }
  2018. DWORD Idx = 0;
  2019. if (m_pProcessInfo->size() > 64)
  2020. {
  2021. //printf("\n\n\n\nthe process number out of 64\n\n\n\n");
  2022. //mLog::FERROR("the process number out of 64");
  2023. map<string, vector<TargetDriverInfo>>::iterator iter = m_pProcessInfo->begin();
  2024. while (iter != m_pProcessInfo->end())
  2025. {
  2026. pid_t pid = iter->second[0].m_info.process_id;
  2027. // 如果进程仍然存在,强制终止
  2028. if (kill(pid, 0) == 0) {
  2029. kill(pid, SIGKILL);
  2030. }
  2031. ++iter;
  2032. }
  2033. }
  2034. else
  2035. {
  2036. // 创建进程ID列表
  2037. std::vector<pid_t> pids;
  2038. pids.reserve(m_pProcessInfo->size());
  2039. // 收集所有需要等待的进程ID
  2040. for (auto& [key, drivers] : *m_pProcessInfo) {
  2041. if (!drivers.empty()) {
  2042. pids.push_back(drivers[0].m_info.process_id);
  2043. }
  2044. }
  2045. // 使用 poll 实现多进程等待
  2046. bool allExited = false;
  2047. int timeout = ONE_ACTION_TIMEOUT - 1000; // 毫秒
  2048. auto startTime = std::chrono::steady_clock::now();
  2049. while (!allExited && timeout > 0) {
  2050. allExited = true;
  2051. for (auto pid : pids) {
  2052. // 检查进程状态
  2053. if (kill(pid, 0) == 0 || errno != ESRCH) {
  2054. allExited = false;
  2055. break;
  2056. }
  2057. }
  2058. if (!allExited) {
  2059. // 等待100ms
  2060. usleep(100 * 1000);
  2061. // 更新剩余时间
  2062. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  2063. std::chrono::steady_clock::now() - startTime);
  2064. timeout -= elapsed.count();
  2065. }
  2066. }
  2067. // 如果超时仍有进程未退出
  2068. if (!allExited) {
  2069. for (auto& [key, drivers] : *m_pProcessInfo) {
  2070. if (!drivers.empty()) {
  2071. pid_t pid = drivers[0].m_info.process_id;
  2072. if (kill(pid, 0) == 0 || errno != ESRCH) {
  2073. // 强制终止进程
  2074. kill(pid, SIGKILL);
  2075. }
  2076. }
  2077. }
  2078. }
  2079. }
  2080. return;
  2081. }
  2082. void BusUnitLogic::OnSetClientID()
  2083. {
  2084. m_strClientID = m_strClientID + "_bus_device";
  2085. //取得端口号
  2086. (*m_pGrpcPort) = GetGrpcPort();
  2087. }
  2088. void BusUnitLogic::SubscribeSelf()
  2089. {
  2090. //assert(m_strEBusRoot.length() > 0);
  2091. LogicDevice::SubscribeSelf();
  2092. SubscribeActions();
  2093. ResDataObject NotifyData;
  2094. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_UPDATE, m_pGrpcPort->GetKey(), m_pGrpcPort->GetVal());
  2095. CmdFromLogicDev(&NotifyData);
  2096. }