BusUnitLogic.cpp 64 KB

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