BusUnitLogic.cpp 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589
  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. static 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. std::cout << "[BusUnitLogic::AddDeviceDescrpt] Entering method. Parameters - DevPath: " << (pDevPath ? pDevPath : "null")
  1402. << ", TargetType: " << (pTargetType ? pTargetType : "null")
  1403. << ", MachineId: " << (pMachineId ? pMachineId : "null")
  1404. << ", ProcId: " << ProcId << ", Addr: " << Addr
  1405. << ", ForceAdd: " << (forceAdd ? "true" : "false") << std::endl;
  1406. DeviceDescript dd;
  1407. //mLog::FINFO("Begin with DevPath={$} TargetType={$} MachineID={$} ProcID={$} Addr={$} ForceAd={$}", pDevPath, pTargetType, pMachineId, ProcId, Addr, forceAdd);
  1408. //exiting...
  1409. if ((*m_pExitFlag) != 0)
  1410. {
  1411. std::cout << "[BusUnitLogic::AddDeviceDescrpt] Exit flag is non-zero (" << (int)(*m_pExitFlag)
  1412. << "), aborting operation. Returning RET_INVALID" << std::endl;
  1413. //mLog::FINFO("End with ExitFlag {$}", (int)(*m_pExitFlag));
  1414. return RET_INVALID;
  1415. }
  1416. dd.SetKey(pDevPath);
  1417. dd.m_TargetType = pTargetType;
  1418. dd.m_ProcId = ProcId;
  1419. dd.m_Address = Addr;
  1420. dd.m_MachineId = pMachineId;
  1421. std::cout << "[BusUnitLogic::AddDeviceDescrpt] Device descriptor initialized - TargetType: " << (pTargetType ? pTargetType : "null")
  1422. << ", ProcId: " << ProcId << ", Address: " << Addr
  1423. << ", MachineId: " << (pMachineId ? pMachineId : "null") << std::endl;
  1424. ResDataObject NotifyData;
  1425. ResDataObject theContext;
  1426. dd.GetResDataObject(theContext);
  1427. std::cout << "[BusUnitLogic::AddDeviceDescrpt] Generated context data from device descriptor" << std::endl;
  1428. if(pDevPath[0] == '/')
  1429. {
  1430. //mLog::FINFO("Ebus Path {$}", pDevPath);
  1431. std::cout << "[BusUnitLogic::AddDeviceDescrpt] Detected Ebus path: " << pDevPath << std::endl;
  1432. if (m_DevList->AddDriver(dd))
  1433. {
  1434. //mLog::FINFO("AddDriver ok {$}", pDevPath);
  1435. std::cout << "[BusUnitLogic::AddDeviceDescrpt] Successfully added driver to DevList for path: " << pDevPath << std::endl;
  1436. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_ADD, m_DevList->GetKey(), theContext);
  1437. }
  1438. else
  1439. {
  1440. //mLog::FERROR("AddDriver Failed {$}", pDevPath);
  1441. std::cout << "[BusUnitLogic::AddDeviceDescrpt] Failed to add driver to DevList for path: " << pDevPath << std::endl;
  1442. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_ONLINE, m_DevList->GetKey(), theContext);
  1443. }
  1444. //PublishAction(&NotifyData, (m_strEBusRoot + "/Notify").c_str(), m_pMqttConntion);
  1445. }
  1446. else {
  1447. //ccos 的Key
  1448. //mLog::FINFO("CCOS Path {$}", pDevPath);
  1449. std::cout << "[BusUnitLogic::AddDeviceDescrpt] Detected CCOS path: " << (pDevPath ? pDevPath : "null") << std::endl;
  1450. if (m_pCcosDevList->AddDriver(dd))
  1451. {
  1452. std::cout << "[BusUnitLogic::AddDeviceDescrpt] Successfully added driver to CcosDevList for path: " << (pDevPath ? pDevPath : "null") << std::endl;
  1453. //mLog::FINFO("AddDriver ok {$}", pDevPath);
  1454. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_ADD, m_pCcosDevList->GetKey(), theContext);
  1455. }
  1456. else
  1457. {
  1458. //mLog::FERROR("AddDriver Failed {$}", pDevPath);
  1459. std::cout << "[BusUnitLogic::AddDeviceDescrpt] Failed to add driver to CcosDevList for path: " << (pDevPath ? pDevPath : "null") << std::endl;
  1460. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_ONLINE, m_pCcosDevList->GetKey(), theContext);
  1461. }
  1462. //PublishAction(&NotifyData, (m_strEBusRoot + "/Notify").c_str(), m_pMqttConntion);
  1463. }
  1464. std::cout << "[BusUnitLogic::AddDeviceDescrpt] Calling CmdFromLogicDev with generated NotifyData" << std::endl;
  1465. CmdFromLogicDev(&NotifyData);
  1466. std::cout << "[BusUnitLogic::AddDeviceDescrpt] Exiting method successfully. Returning RET_SUCCEED" << std::endl;
  1467. return RET_SUCCEED;
  1468. }
  1469. int DATA_ACTION BusUnitLogic::Get(const char PARAM_IN *pKey,ResDataObject &Res)
  1470. {
  1471. string Key = pKey;
  1472. if (Key == m_DevList->GetKey())
  1473. {
  1474. ResDataObject arraylist;
  1475. m_DevList->GetResDataObject(arraylist);
  1476. Res.add(m_DevList->GetKey(), arraylist);
  1477. return RET_SUCCEED;
  1478. }
  1479. return RET_FAILED;
  1480. }
  1481. int DATA_ACTION BusUnitLogic::DelDeviceDescrpt(const char PARAM_IN *pDevPath)
  1482. {
  1483. if(pDevPath[0] == '/')
  1484. {
  1485. if (m_DevList->DelVal(pDevPath))
  1486. {
  1487. //3. Notify
  1488. ResDataObject NotifyData;
  1489. ResDataObject theContext;
  1490. theContext.add("DevicePath", pDevPath);
  1491. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_DEL, m_DevList->GetKey(), theContext);
  1492. CmdFromLogicDev(&NotifyData);
  1493. //PublishAction(&NotifyData, (m_strEBusRoot + "/Notify").c_str(), m_pMqttConntion);
  1494. }
  1495. }
  1496. else
  1497. {
  1498. if (m_pCcosDevList->DelVal(pDevPath))
  1499. {
  1500. //3. Notify
  1501. ResDataObject NotifyData;
  1502. ResDataObject theContext;
  1503. theContext.add("DevicePath", pDevPath);
  1504. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_DEL, m_pCcosDevList->GetKey(), theContext);
  1505. CmdFromLogicDev(&NotifyData);
  1506. //PublishAction(&NotifyData, (m_strEBusRoot + "/Notify").c_str(), m_pMqttConntion);
  1507. }
  1508. }
  1509. return RET_SUCCEED;
  1510. }
  1511. int DATA_ACTION BusUnitLogic::SetDeviceStatus(int Status)
  1512. {
  1513. RET_STATUS ret = RET_SUCCEED;
  1514. if ((*m_pState) != Status)
  1515. {
  1516. ResDataObject NotifyData;
  1517. (*m_pState) = Status;
  1518. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_UPDATE, m_pState->GetKey(), m_pState->GetVal());
  1519. ret = CmdFromLogicDev(&NotifyData);
  1520. //string notfiyTopic = m_strEBusRoot + "/Notify";
  1521. //PublishAction(&NotifyData, notfiyTopic.c_str() , m_pMqttConntion);
  1522. }
  1523. return ret;
  1524. }
  1525. int DATA_ACTION BusUnitLogic::SetEthBusSwitch(int Switch)
  1526. {
  1527. RET_STATUS ret = RET_SUCCEED;
  1528. if ((*m_pEnableEthBus) != Switch)
  1529. {
  1530. ResDataObject NotifyData;
  1531. (*m_pEnableEthBus) = Switch;
  1532. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_UPDATE, m_pEnableEthBus->GetKey(), m_pEnableEthBus->GetVal());
  1533. ret = CmdFromLogicDev(&NotifyData);
  1534. //PublishAction(&NotifyData, (m_strEBusRoot + "/Notify").c_str(), m_pMqttConntion);
  1535. }
  1536. return ret;
  1537. }
  1538. int DATA_ACTION BusUnitLogic::SetEthBusRouterIp(const char PARAM_IN *pRouterIp)
  1539. {
  1540. RET_STATUS ret = RET_SUCCEED;
  1541. std::string Param = pRouterIp;
  1542. std::string RouterIp = (*m_pEthBusRouterIp);
  1543. if (RouterIp != Param)
  1544. {
  1545. ResDataObject NotifyData;
  1546. (*m_pEthBusRouterIp) = Param;
  1547. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_UPDATE, m_pEthBusRouterIp->GetKey(), m_pEthBusRouterIp->GetVal());
  1548. ret = CmdFromLogicDev(&NotifyData);
  1549. //PublishAction(&NotifyData, (m_strEBusRoot + "/Notify").c_str(), m_pMqttConntion);
  1550. }
  1551. return ret;
  1552. }
  1553. int DATA_ACTION BusUnitLogic::ExitDriverProc()
  1554. {
  1555. RET_STATUS ret = RET_SUCCEED;
  1556. if ((*m_pExitFlag) == 0)
  1557. {
  1558. ResDataObject NotifyData;
  1559. SetExitFlag(1);
  1560. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_UPDATE, m_pExitFlag->GetKey(), m_pExitFlag->GetVal());
  1561. ret = CmdFromLogicDev(&NotifyData);
  1562. //PublishAction(&NotifyData, (m_strEBusRoot + "/Notify").c_str(), m_pMqttConntion);
  1563. }
  1564. return ret;
  1565. }
  1566. int SYSTEM_CALL BusUnitLogic::GetExitFlag()
  1567. {
  1568. return (*m_pExitFlag);
  1569. }
  1570. int SYSTEM_CALL BusUnitLogic::SetExitFlag(int ExitFlag)
  1571. {
  1572. (*m_pExitFlag) = ExitFlag;
  1573. return 1;
  1574. }
  1575. int SYSTEM_CALL BusUnitLogic::GetbusId(ResDataObject &obj)
  1576. {
  1577. obj = m_pbusID->GetVal();
  1578. return RET_SUCCEED;
  1579. }
  1580. int SYSTEM_CALL BusUnitLogic::GetMachineId(ResDataObject &obj)
  1581. {
  1582. obj = m_pMachineID->GetVal();
  1583. return RET_SUCCEED;
  1584. }
  1585. int SYSTEM_CALL BusUnitLogic::GetProcId(UINT64 &obj)
  1586. {
  1587. obj = (*m_pProcID);
  1588. return RET_SUCCEED;
  1589. }
  1590. int SYSTEM_CALL BusUnitLogic::SetbusId(ResDataObject &obj)
  1591. {
  1592. (*m_pbusID) = (const char *)obj;
  1593. return RET_SUCCEED;
  1594. }
  1595. int SYSTEM_CALL BusUnitLogic::SetMachineId(ResDataObject &obj)
  1596. {
  1597. (*m_pMachineID) = (const char *)obj;
  1598. return RET_SUCCEED;
  1599. }
  1600. int SYSTEM_CALL BusUnitLogic::SetProcId(UINT64 obj)
  1601. {
  1602. (*m_pProcID) = (UINT64)obj;
  1603. return RET_SUCCEED;
  1604. }
  1605. DWORD SYSTEM_CALL BusUnitLogic::GetDeviceCount()
  1606. {
  1607. return (DWORD)m_DevList->m_DeviceList.size();
  1608. }
  1609. bool SYSTEM_CALL BusUnitLogic::GetDeviceDescript(DWORD Idx, ResDataObject &DevPath, ResDataObject &DevType, ResDataObject &MachineId, UINT64 &ProcId, UINT64 &Addr)
  1610. {
  1611. if (m_DevList->m_DeviceList.size() > Idx)
  1612. {
  1613. DevPath = m_DevList->m_DeviceList[Idx].GetKey();
  1614. DevType = m_DevList->m_DeviceList[Idx].m_TargetType.GetVal();
  1615. MachineId = m_DevList->m_DeviceList[Idx].m_MachineId.GetVal();
  1616. ProcId = m_DevList->m_DeviceList[Idx].m_ProcId;
  1617. Addr = m_DevList->m_DeviceList[Idx].m_Address;
  1618. return true;
  1619. }
  1620. return false;
  1621. }
  1622. int SYSTEM_CALL BusUnitLogic::GetDeviceStatus()
  1623. {
  1624. return (*m_pState);
  1625. }
  1626. int SYSTEM_CALL BusUnitLogic::GetEthBusSwitch()
  1627. {
  1628. return (*m_pEnableEthBus);
  1629. }
  1630. int SYSTEM_CALL BusUnitLogic::GetEthBusRouterIp(ResDataObject &obj)
  1631. {
  1632. obj = (*m_pEthBusRouterIp).GetVal();
  1633. return 1;
  1634. }
  1635. /// <summary>
  1636. /// 检查所有驱动进程,如果进程Crash了,需要根据配置重新拉起来
  1637. /// </summary>
  1638. /// <returns></returns>
  1639. void SYSTEM_CALL BusUnitLogic::CheckAllLiveDriver()
  1640. {
  1641. map<string, vector<TargetDriverInfo>>::iterator iter = m_pProcessInfo->begin();
  1642. while (iter != m_pProcessInfo->end())
  1643. {
  1644. if (m_bConfigRemoveDriver)
  1645. {
  1646. //Sleep(2000);
  1647. //mLog::FINFO("ConfigDriver working");
  1648. return;
  1649. }
  1650. //for (size_t DriverIdx = 0; DriverIdx < iter->second.size(); DriverIdx++)
  1651. {
  1652. string DrvBusId = "/";
  1653. DrvBusId += (const char*)iter->first.c_str();
  1654. {
  1655. //got one
  1656. pid_t targetPid = iter->second[0].m_info.process_id;
  1657. if (kill(targetPid, 0) == 0)
  1658. {
  1659. //process exist
  1660. LogicClient chClient1("CheckAllLiveDriver_temp","driver","",false);
  1661. chClient1.SetRouter(CCOS_PACKET_ROUTE_LOCAL);
  1662. if (chClient1.Open(DrvBusId.c_str(), ALL_ACCESS, "", ONE_ACTION_TIMEOUT) >= RET_SUCCEED)
  1663. {
  1664. chClient1.Close();
  1665. }
  1666. else
  1667. {
  1668. //printf("Open local %s Failed while check Live\n", DrvBusId.c_str());
  1669. //mLog::FERROR("Open local {$} Failed while check Live\n", DrvBusId.c_str());
  1670. }
  1671. }
  1672. else
  1673. {
  1674. if (m_bConfigRemoveDriver)
  1675. {
  1676. //mLog::FINFO("ConfigDriver working 2");
  1677. return;
  1678. }
  1679. //target process crashed
  1680. //printf("Autoload Flag:%d \n BusId:%s\n", (bool)(iter->second)[0].m_CcosProcInfo["AutoLoad"], iter->first.c_str());
  1681. //do reload
  1682. if ((bool)(iter->second)[0].m_CcosProcInfo["AutoLoad"])
  1683. {
  1684. memset(&(iter->second)[0].m_info, 0, sizeof(LinuxProcessInfo));
  1685. if (CreateTheProcess_Console_Config((iter->second)[0].m_CcosProcInfo["DriverPath"],
  1686. (iter->second)[0].m_CcosProcInfo["WorkPath"],
  1687. (iter->second)[0].m_info,
  1688. (iter->second)[0].m_CcosProcInfo["ShowWindow"]) == FALSE)
  1689. {
  1690. //printf("Reload Failed.Can't Create Process for config:%s\n",
  1691. // (const char*)(iter->second)[0].m_CcosProcInfo["DriverConfigPath"]);
  1692. //mLog::FERROR("Reload Failed.Can't Create Process for config:{$}", (const char*)(iter->second)[0].m_CcosProcInfo["DriverConfigPath"]);
  1693. }
  1694. else
  1695. {
  1696. //printf("Reload Succeed.Create Process for config:%s Succeed\n",
  1697. // (const char*)(iter->second)[0].m_CcosProcInfo["DriverConfigPath"]);
  1698. //mLog::FINFO("Reload Succeed.Create Process for config:{$} Succeed", (const char*)(iter->second)[0].m_CcosProcInfo["DriverConfigPath"]);
  1699. usleep(6000000);//wait
  1700. }
  1701. }
  1702. else
  1703. {
  1704. //kick iter;
  1705. //printf("Kick crashed process. BusId:%s\n", iter->first.c_str());
  1706. //mLog::FINFO("Kick crashed process. BusId:{$}\n", iter->first.c_str());
  1707. DelDeviceDescrpt(DrvBusId.c_str());
  1708. iter = m_pProcessInfo->erase(iter);
  1709. continue;
  1710. }
  1711. }
  1712. }
  1713. }
  1714. ++iter;
  1715. }
  1716. return;
  1717. }
  1718. int SYSTEM_CALL BusUnitLogic::LoadAllConfigDriver(bool ForReload, ResDataObject* pResource)
  1719. {
  1720. RET_STATUS ret = RET_SUCCEED;
  1721. //this is for dpc call
  1722. bool FullDriverList = false;
  1723. ResDataObject fileList;
  1724. //find driver from fulldrvlist
  1725. if (CheckBusIdsExistance(0) == false)
  1726. {
  1727. //mLog::FERROR("CheckBusIdsExistance(0) == false");
  1728. return RET_FAILED;
  1729. }
  1730. LogicDriver* pDPC = (LogicDriver*)GetDrvDPC();
  1731. if (pDPC == 0)
  1732. {
  1733. //mLog::FERROR("pDPC == 0");
  1734. return RET_FAILED;
  1735. }
  1736. //mLog::FINFO("GetDrvDPC ok");
  1737. //pDPC->Thread_Lock();
  1738. ////mLog::FINFO("DPC lock ok");
  1739. try{
  1740. //find x64
  1741. if (GetSpecificDriverConfigFiles(fileList, FullDriverList))
  1742. {
  1743. //mLog::FINFO("GetSpecificDriverConfigFiles ok");
  1744. map<string,int> ConflictBusIds;
  1745. map<string, string> BusIdMap;//BusId <-> Dir
  1746. map<string, vector<TargetDriverInfo>> LoadDriverMap;
  1747. //exist x64
  1748. for (size_t i = 0; i < fileList.size(); i++)
  1749. {
  1750. TargetDriverInfo DrvInfo;
  1751. if (GetDriverEbusId(fileList.GetKey(i), DrvInfo.m_RootBusId, DrvInfo.m_DriverBusId))
  1752. {
  1753. //get ebus driver path
  1754. if (GetDriverProcInfo(fileList.GetKey(i), DrvInfo.m_CcosProcInfo))
  1755. {
  1756. map<string,string>::iterator BusIdsIter = BusIdMap.find((const char*)DrvInfo.m_RootBusId);
  1757. if (BusIdsIter != BusIdMap.end())
  1758. {
  1759. //same busId Exist
  1760. if (BusIdsIter->second == (const char*)fileList[i])
  1761. {
  1762. //same dir,ok
  1763. }
  1764. else
  1765. {
  1766. //different dir,ng
  1767. ConflictBusIds[BusIdsIter->first] = 1;
  1768. }
  1769. }
  1770. else
  1771. {
  1772. //no BusId exist
  1773. BusIdMap[(const char*)DrvInfo.m_RootBusId] = (const char*)fileList[i];
  1774. }
  1775. LoadDriverMap[(const char *)DrvInfo.m_RootBusId].push_back(DrvInfo);
  1776. }
  1777. else
  1778. {
  1779. //mLog::FINFO("GetDriverProcInfo failed {$} ", fileList.GetKey(i));
  1780. }
  1781. }
  1782. else
  1783. {
  1784. //mLog::FINFO("GetDriverEbusId failed {$} ", fileList.GetKey(i));
  1785. }
  1786. }
  1787. map<string, vector<TargetDriverInfo>>::iterator DelIter;
  1788. //kick same busids drivers
  1789. map<string, int>::iterator ConflictIter = ConflictBusIds.begin();
  1790. while (ConflictIter != ConflictBusIds.end())
  1791. {
  1792. DelIter = LoadDriverMap.find(ConflictIter->first);
  1793. if (DelIter != LoadDriverMap.end())
  1794. {
  1795. //mLog::FERROR("busid:{$} conflict", DelIter->first.c_str());
  1796. for (size_t DriverIdx = 0; DriverIdx < DelIter->second.size(); DriverIdx++)
  1797. {
  1798. const char *pszConfigFilepath = DelIter->second[DriverIdx].m_CcosProcInfo["DriverConfigPath"];//config file path
  1799. //mLog::FERROR("busid:{$} conflict.Ignore ConfigFile:{$}", DelIter->first.c_str(),pszConfigFilepath);
  1800. }
  1801. LoadDriverMap.erase(DelIter);
  1802. }
  1803. ++ConflictIter;
  1804. }
  1805. ConflictBusIds.clear();
  1806. //mLog::FINFO("LoadDriverMap size {$} ", LoadDriverMap.size());
  1807. //kick condition like (same busid but not same procType)
  1808. DelIter = LoadDriverMap.begin();
  1809. while (DelIter != LoadDriverMap.end())
  1810. {
  1811. if (DelIter->second.size() > 1)
  1812. {
  1813. bool ConflictProc = false;
  1814. //more than one driver exist
  1815. for (size_t DriverIdx = 0; DriverIdx < DelIter->second.size() - 1; DriverIdx++)
  1816. {
  1817. if (ConflictProc)
  1818. {
  1819. break;
  1820. }
  1821. //compare each others driverproc
  1822. string DriverProc = "";
  1823. ResDataObject DriverProcessPath;
  1824. GetDriverProcessPath(DelIter->second[DriverIdx].m_CcosProcInfo["DriverConfigPath"], DriverProcessPath);
  1825. DriverProc = (const char*)DriverProcessPath;
  1826. for (size_t CompareIdx = DriverIdx + 1; CompareIdx < DelIter->second.size(); CompareIdx++)
  1827. {
  1828. if (ConflictProc)
  1829. {
  1830. break;
  1831. }
  1832. string CompareProc = "";
  1833. ResDataObject CompareProcessPath;
  1834. GetDriverProcessPath(DelIter->second[CompareIdx].m_CcosProcInfo["DriverConfigPath"], CompareProcessPath);
  1835. CompareProc = (const char*)CompareProcessPath;
  1836. if (CompareProc != DriverProc)
  1837. {
  1838. ConflictBusIds[DelIter->first] = 1;
  1839. ConflictProc = true;
  1840. }
  1841. }
  1842. }
  1843. }
  1844. ++DelIter;
  1845. }
  1846. //kick again
  1847. ConflictIter = ConflictBusIds.begin();
  1848. while (ConflictIter != ConflictBusIds.end())
  1849. {
  1850. DelIter = LoadDriverMap.find(ConflictIter->first);
  1851. if (DelIter != LoadDriverMap.end())
  1852. {
  1853. //mLog::FERROR("busid:{$} processType conflict", DelIter->first.c_str());
  1854. for (size_t DriverIdx = 0; DriverIdx < DelIter->second.size(); DriverIdx++)
  1855. {
  1856. const char* pszConfigFilepath = DelIter->second[DriverIdx].m_CcosProcInfo["DriverConfigPath"];//config file path
  1857. //mLog::FERROR("busid:{$} processType conflict.Ignore ConfigFile:{$}", DelIter->first.c_str(), pszConfigFilepath);
  1858. }
  1859. LoadDriverMap.erase(DelIter);
  1860. }
  1861. ++ConflictIter;
  1862. }
  1863. map<string, vector<TargetDriverInfo>>::iterator iter = LoadDriverMap.begin();
  1864. while (iter != LoadDriverMap.end())
  1865. {
  1866. if (ForReload)
  1867. {
  1868. if (CheckBusIdsExistance(iter->first.c_str()) == false)
  1869. {
  1870. //target exist
  1871. ++iter;
  1872. continue;
  1873. }
  1874. }
  1875. //make full process path
  1876. bool FirstIn = true;
  1877. string ConfigFile;
  1878. string FullDriverPath = "";
  1879. for (size_t DriverIdx = 0; DriverIdx < iter->second.size(); DriverIdx++)
  1880. {
  1881. //make driverpath
  1882. if (FirstIn)
  1883. {
  1884. ResDataObject DriverProcessPath;
  1885. GetDriverProcessPath(iter->second[DriverIdx].m_CcosProcInfo["DriverConfigPath"], DriverProcessPath);
  1886. FullDriverPath = (const char *)DriverProcessPath;
  1887. FirstIn = false;
  1888. }
  1889. ConfigFile = (const char *)iter->second[DriverIdx].m_CcosProcInfo["DriverConfigPath"];
  1890. //get config file title
  1891. string ConfigFileName = GetFileName(ConfigFile);
  1892. FullDriverPath += " " + ConfigFileName;
  1893. }
  1894. //rest all of same busid
  1895. for (size_t DriverIdx = 0; DriverIdx < iter->second.size(); DriverIdx++)
  1896. {
  1897. iter->second[DriverIdx].m_CcosProcInfo["DriverPath"] = FullDriverPath.c_str();//[fullpath of exe] [config1.xml config2.xml ...]
  1898. }
  1899. //create process
  1900. if (CreateTheProcess_Console_Config(iter->second[0].m_CcosProcInfo["DriverPath"],
  1901. iter->second[0].m_CcosProcInfo["WorkPath"],
  1902. iter->second[0].m_info,
  1903. iter->second[0].m_CcosProcInfo["ShowWindow"]) == FALSE)
  1904. {
  1905. //mLog::FERROR("Can't Create Process:{$}", FullDriverPath.c_str());
  1906. }
  1907. else
  1908. {
  1909. //mLog::FINFO("Create Process:{$} ok", FullDriverPath.c_str());
  1910. for (size_t DriverIdx = 0; DriverIdx < iter->second.size(); DriverIdx++)
  1911. {
  1912. (*m_pProcessInfo)[(const char*)iter->second[DriverIdx].m_RootBusId].push_back(iter->second[DriverIdx]);
  1913. MakeDriverNotify((const char *)iter->second[DriverIdx].m_DriverBusId, true);
  1914. }
  1915. }
  1916. ++iter;
  1917. }
  1918. }
  1919. else
  1920. {
  1921. //mLog::FERROR("GetSpecificDriverConfigFiles failed");
  1922. }
  1923. }
  1924. catch (...)
  1925. {
  1926. //mLog::FERROR("crash");
  1927. ret = RET_FAILED;
  1928. }
  1929. //pDPC->Thread_UnLock();
  1930. ////mLog::FINFO("DPC Unlock ok");
  1931. return ret;
  1932. }
  1933. void SYSTEM_CALL BusUnitLogic::UnloadDriver(const char *pszBusId)
  1934. {
  1935. //mLog::FINFO("Enter UnloadDriver:{$}", pszBusId);
  1936. map<string, vector<TargetDriverInfo>>::iterator iter = m_pProcessInfo->find(pszBusId);
  1937. if (iter != m_pProcessInfo->end())
  1938. {
  1939. //found target busid.
  1940. //notify target quit first
  1941. string DrvBusId = "/";
  1942. DrvBusId += (const char*)iter->first.c_str();
  1943. {
  1944. //got one
  1945. pid_t targetPid = iter->second[0].m_info.process_id;
  1946. if (kill(targetPid, 0) == 0)
  1947. {
  1948. //process exist
  1949. LogicClient chClient1("UnloadDriver_temp","driver", "", false);
  1950. chClient1.SetRouter(CCOS_PACKET_ROUTE_LOCAL);
  1951. if (chClient1.Open(DrvBusId.c_str(), ALL_ACCESS, "", ONE_ACTION_TIMEOUT) >= RET_SUCCEED)
  1952. {
  1953. ResDataObject req;
  1954. if (chClient1.Action_Req("ExitDriverProc", req, ONE_ACTION_TIMEOUT) >= RET_SUCCEED)
  1955. {
  1956. //printf("Succeed Action:ExitDriverProc %s ...\n", DrvBusId.c_str());
  1957. //mLog::FINFO("Succeed Action: ExitDriverProc {$} ...\n", DrvBusId.c_str());
  1958. chClient1.Close();
  1959. }
  1960. else
  1961. {
  1962. //printf("Failed Action:ExitDriverProc -> %s...\n", DrvBusId.c_str());
  1963. //mLog::FERROR("Failed Action: ExitDriverProc -> {$} ...\n", DrvBusId.c_str());
  1964. chClient1.Close();
  1965. }
  1966. }
  1967. else
  1968. {
  1969. //printf("Open local %s Failed\n", DrvBusId.c_str());
  1970. //mLog::FERROR("Open local {$} Failed\n", DrvBusId.c_str());
  1971. }
  1972. }
  1973. }
  1974. int waitCount = 0;
  1975. const int maxWait = (ONE_ACTION_TIMEOUT - 1000) / 100; // 转换为100ms单位
  1976. while (waitCount < maxWait) {
  1977. if (kill(iter->second[0].m_info.process_id, 0) != 0 && errno == ESRCH) {
  1978. break; // 进程已退出
  1979. }
  1980. usleep(100 * 1000); // 100ms
  1981. waitCount++;
  1982. }
  1983. // 超时后强制终止
  1984. if (kill(iter->second[0].m_info.process_id, 0) == 0) {
  1985. kill(iter->second[0].m_info.process_id, SIGKILL);
  1986. }
  1987. //make notify
  1988. for (size_t DriverIdx = 0; DriverIdx < iter->second.size(); DriverIdx++)
  1989. {
  1990. MakeDriverNotify((const char *)iter->second[DriverIdx].m_DriverBusId, false);
  1991. }
  1992. //kick busid
  1993. m_pProcessInfo->erase(iter);
  1994. }
  1995. //mLog::FINFO("Exit UnloadDriver:{$}", pszBusId);
  1996. return;
  1997. }
  1998. void SYSTEM_CALL BusUnitLogic::UnloadAllRegistedDrivers()
  1999. {
  2000. map<string, vector<TargetDriverInfo>>::iterator iter = m_pProcessInfo->begin();
  2001. while (iter != m_pProcessInfo->end())
  2002. {
  2003. string DrvBusId = "/";
  2004. DrvBusId += (const char*)iter->first.c_str();
  2005. {
  2006. //got one
  2007. pid_t targetPid = iter->second[0].m_info.process_id;
  2008. if (kill(targetPid, 0) == 0)
  2009. {
  2010. //process exist
  2011. LogicClient chClient1("UnloadAllRegistedDrivers_temp","driver", "", false);
  2012. chClient1.SetRouter(CCOS_PACKET_ROUTE_LOCAL);
  2013. if (chClient1.Open(DrvBusId.c_str(), ALL_ACCESS,"", ONE_ACTION_TIMEOUT) >= RET_SUCCEED)
  2014. {
  2015. ResDataObject req;
  2016. if (chClient1.Action_Req("ExitDriverProc", req, ONE_ACTION_TIMEOUT) >= RET_SUCCEED)
  2017. {
  2018. //printf("Succeed Action:ExitDriverProc %s ...\n", DrvBusId.c_str());
  2019. //mLog::FINFO("Succeed Action: ExitDriverProc {$} ...\n", DrvBusId.c_str());
  2020. chClient1.Close();
  2021. }
  2022. else
  2023. {
  2024. //printf("Failed Action:ExitDriverProc -> %s...\n", DrvBusId.c_str());
  2025. //mLog::FERROR("Failed Action: ExitDriverProc -> {$} ...\n", DrvBusId.c_str());
  2026. chClient1.Close();
  2027. }
  2028. }
  2029. else
  2030. {
  2031. //printf("Open local %s Failed\n", DrvBusId.c_str());
  2032. //mLog::FERROR("Open local {$} Failed\n", DrvBusId.c_str());
  2033. }
  2034. }
  2035. }
  2036. ++iter;
  2037. }
  2038. DWORD Idx = 0;
  2039. if (m_pProcessInfo->size() > 64)
  2040. {
  2041. //printf("\n\n\n\nthe process number out of 64\n\n\n\n");
  2042. //mLog::FERROR("the process number out of 64");
  2043. map<string, vector<TargetDriverInfo>>::iterator iter = m_pProcessInfo->begin();
  2044. while (iter != m_pProcessInfo->end())
  2045. {
  2046. pid_t pid = iter->second[0].m_info.process_id;
  2047. // 如果进程仍然存在,强制终止
  2048. if (kill(pid, 0) == 0) {
  2049. kill(pid, SIGKILL);
  2050. }
  2051. ++iter;
  2052. }
  2053. }
  2054. else
  2055. {
  2056. // 创建进程ID列表
  2057. std::vector<pid_t> pids;
  2058. pids.reserve(m_pProcessInfo->size());
  2059. // 收集所有需要等待的进程ID
  2060. for (auto& [key, drivers] : *m_pProcessInfo) {
  2061. if (!drivers.empty()) {
  2062. pids.push_back(drivers[0].m_info.process_id);
  2063. }
  2064. }
  2065. // 使用 poll 实现多进程等待
  2066. bool allExited = false;
  2067. int timeout = ONE_ACTION_TIMEOUT - 1000; // 毫秒
  2068. auto startTime = std::chrono::steady_clock::now();
  2069. while (!allExited && timeout > 0) {
  2070. allExited = true;
  2071. for (auto pid : pids) {
  2072. // 检查进程状态
  2073. if (kill(pid, 0) == 0 || errno != ESRCH) {
  2074. allExited = false;
  2075. break;
  2076. }
  2077. }
  2078. if (!allExited) {
  2079. // 等待100ms
  2080. usleep(100 * 1000);
  2081. // 更新剩余时间
  2082. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  2083. std::chrono::steady_clock::now() - startTime);
  2084. timeout -= elapsed.count();
  2085. }
  2086. }
  2087. // 如果超时仍有进程未退出
  2088. if (!allExited) {
  2089. for (auto& [key, drivers] : *m_pProcessInfo) {
  2090. if (!drivers.empty()) {
  2091. pid_t pid = drivers[0].m_info.process_id;
  2092. if (kill(pid, 0) == 0 || errno != ESRCH) {
  2093. // 强制终止进程
  2094. kill(pid, SIGKILL);
  2095. }
  2096. }
  2097. }
  2098. }
  2099. }
  2100. return;
  2101. }
  2102. void BusUnitLogic::OnSetClientID()
  2103. {
  2104. m_strClientID = m_strClientID + "_bus_device";
  2105. //取得端口号
  2106. (*m_pGrpcPort) = GetGrpcPort();
  2107. }
  2108. void BusUnitLogic::SubscribeSelf()
  2109. {
  2110. //assert(m_strEBusRoot.length() > 0);
  2111. LogicDevice::SubscribeSelf();
  2112. SubscribeActions();
  2113. ResDataObject NotifyData;
  2114. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_UPDATE, m_pGrpcPort->GetKey(), m_pGrpcPort->GetVal());
  2115. CmdFromLogicDev(&NotifyData);
  2116. }