BusUnitLogic.cpp 65 KB

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