LogicClient.cpp 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041
  1. //#include "SysIF.h"
  2. #include "LocalConfig.h"
  3. #include "LogicClient.h"
  4. #include "common_api.h"
  5. #include "PacketAnalizer.h"
  6. #include "LogLocalHelper.h"
  7. #include "Log4CPP.h"
  8. #define ATTRIBUTE ("Attribute")
  9. #include <iostream>
  10. #include<chrono>
  11. #ifndef _CRT_SECURE_NO_WARNINGS
  12. #define _CRT_SECURE_NO_WARNINGS
  13. #endif
  14. //Log4CPP::Logger* gLogger = nullptr;
  15. string LogHost = "";
  16. // Linux下获取进程ID
  17. inline DWORD GetCurrentProcessId() {
  18. return getpid();
  19. }
  20. inline string CurrentDateTime2()
  21. {
  22. std::time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
  23. char buf[100] = { 0 };
  24. std::strftime(buf, sizeof(buf), " %Y-%m-%d %H:%M:%S ", std::localtime(&now));
  25. return buf;
  26. }
  27. inline std::string CurrentDateTime()
  28. {
  29. // 获取当前时间点
  30. auto now = std::chrono::system_clock::now();
  31. // 将时间长度转换为微秒数
  32. auto now_us = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch());
  33. // 再转成tm格式
  34. auto now_time_t = std::chrono::system_clock::to_time_t(now);
  35. auto now_tm = std::localtime(&now_time_t);
  36. // 可以直接输出到标准输出
  37. // std::cout << std::put_time(now_tm, "%Y-%m-%d %H:%M:%S.") << std::setfill('0') << std::setw(6) << now_us.count() % 1000000 << std::endl;
  38. // 格式化字符,年月日时分秒
  39. std::string now_time_str;
  40. char buf[64];
  41. std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", now_tm);
  42. now_time_str += buf;
  43. // 格式化微秒
  44. //snprintf(buf, sizeof(buf), ".%06lld ", now_us.count() % 1000000);
  45. snprintf(buf, sizeof(buf), ".%06ld ", now_us.count() % 1000000);
  46. now_time_str += buf;
  47. //printf("%s\n", now_time_str.c_str());
  48. return now_time_str;
  49. }
  50. LogicClient::LogicClient(string szClientName, string szTransaction, string szType, bool bNeedNotify)
  51. {
  52. m_ReqIdx = 0;
  53. pLogicDeivce = NULL;
  54. m_SyncMode = ACTION_SYNC;
  55. m_FileFlags = 0;
  56. m_ClosedFlag = true;
  57. m_OwnerThreadId = 0;
  58. m_pActionName = new string();
  59. m_pFilePath = new string();
  60. m_pLastMsgInfo = new string();
  61. m_pPacketWaitQue = new MsgQueue<ResDataObject>();
  62. m_pPacketReceivedQue = new MsgQueue<ResDataObject>();
  63. m_pPacketNotifyQue = new MsgQueue<ResDataObject>();
  64. m_NotifyEvent = LinuxEvent::CreateEvent(LinuxEvent::MANUAL_RESET, false);
  65. m_ResponseEvent = LinuxEvent::CreateEvent(LinuxEvent::AUTO_RESET, false);
  66. m_bNeedNotify = bNeedNotify;
  67. //m_pSysIF = new ClientSysIF();
  68. m_pMqttConn = nullptr;
  69. m_strClientName = szClientName;
  70. if (m_strClientName.length() <= 0) {
  71. string stream;
  72. stream = "LogicClient_" + to_string( GetCurrentProcessId()) + "_" + string( (const char*)getLocalEbusId()) + "_" +to_string( GetCurrentThreadId());
  73. m_strClientName = stream;
  74. stream.clear();
  75. string stream2;
  76. stream2 = CCOS_CLIENT_ROOT_TOPIC + string( "/Resp_") + to_string( GetCurrentProcessId()) + "_" + string( (const char*)getLocalEbusId()) + "_" + to_string( GetCurrentThreadId());
  77. m_strDefaultTopic = stream2;
  78. }
  79. else
  80. {
  81. stringstream stream;
  82. stream << "LogicClient_" << szClientName << "_" << (const char*)getLocalEbusId() << "_" << GetCurrentProcessId();
  83. m_strClientName = stream.str();
  84. stream.clear();
  85. stringstream stream2;
  86. stream2 << CCOS_CLIENT_ROOT_TOPIC << (szType.length()<=0?"":"/") << (szType.length()<=0?"":szType) << "/" << szClientName << "/Resp_" << (const char*)getLocalEbusId() << "_" << GetCurrentProcessId();
  87. m_strDefaultTopic = stream2.str();
  88. }
  89. m_strCurTransaction = szTransaction;
  90. m_pFileHandle = new CcosDevFileHandle();
  91. m_ClientLock = (HANDLE)new CcosLock();
  92. m_Router = CCOS_PACKET_ROUTE_ANY;
  93. m_hDeviceOpenOK = LinuxEvent::CreateEvent(LinuxEvent::MANUAL_RESET, false);// CreateEvent(NULL, FALSE, FALSE, NULL);
  94. m_hDeviceCloseOK = LinuxEvent::CreateEvent(LinuxEvent::AUTO_RESET, false);
  95. m_hReOpen = LinuxEvent::CreateEvent(LinuxEvent::AUTO_RESET, false);
  96. m_pPacketArrivedCallbackFunc = nullptr;
  97. m_openCallbackFunc = nullptr;
  98. SetName(m_strClientName.c_str());
  99. }
  100. LogicClient::~LogicClient(void)
  101. {
  102. FWARN("Free LogicClient Object [{$}]", m_strClientName);
  103. cout << "Free LogicClient Object == " << m_strClientName << endl;
  104. if (IsClosed() == false) {
  105. Close();
  106. }
  107. if (m_Base_Thread != 0) {
  108. StopThread(3000); // 再次尝试停止线程
  109. }
  110. //delete m_pSysIF;
  111. CloseConnection(m_pMqttConn);
  112. //m_pSysIF = NULL;
  113. m_pMqttConn = nullptr;
  114. delete m_pActionName;
  115. m_pActionName = NULL;
  116. delete m_pFilePath;
  117. m_pFilePath = NULL;
  118. delete m_pLastMsgInfo;
  119. m_pLastMsgInfo = NULL;
  120. delete m_pPacketWaitQue;
  121. m_pPacketWaitQue = NULL;
  122. delete m_pPacketReceivedQue;
  123. m_pPacketReceivedQue = NULL;
  124. delete m_pPacketNotifyQue;
  125. m_pPacketNotifyQue = NULL;
  126. delete m_pFileHandle;
  127. m_pFileHandle = NULL;
  128. delete (CcosLock*)m_ClientLock;
  129. m_ClientLock = NULL;
  130. }
  131. bool LogicClient::GetFileHandle(CcosDevFileHandle &Handle)
  132. {
  133. if (IsClosed() == false)
  134. {
  135. Lock();
  136. Handle = (*m_pFileHandle);
  137. UnLock();
  138. return true;
  139. }
  140. //make client handle
  141. Handle[CCOS_PACK_HANDLE_LANG] = "en-US";//NOT FINISHED YET
  142. Handle[CCOS_PACK_HANDLE_ROUTE] = m_Router;//route
  143. Handle[CCOS_PACK_HANDLE_FLAGS] = 0;//
  144. Handle[CCOS_PACKET_HANDLE_KEY] = 0;//
  145. //target
  146. Handle.GetTarget(false)[CCOS_PACK_TARGET_ADDR] = (UINT64)0;
  147. Handle.GetTarget(false)[CCOS_PACK_TARGET_PROCID] = (UINT64)0;
  148. Handle.GetTarget(false)[CCOS_PACK_TARGET_BUSID] = "";
  149. Handle.GetTarget(false)[CCOS_PACK_TARGET_MACHINEID] = "";
  150. //local
  151. Handle.GetTarget()[CCOS_PACK_TARGET_ADDR] = (UINT64)(PVOID*)m_pMqttConn;
  152. Handle.GetTarget()[CCOS_PACK_TARGET_PROCID] = (UINT64)GetCurrentProcessId();
  153. Handle.GetTarget()[CCOS_PACK_TARGET_BUSID] = (const char*)getLocalEbusId();
  154. Handle.GetTarget()[CCOS_PACK_TARGET_MACHINEID] = (const char*)getLocalMachineId();
  155. return false;
  156. }
  157. bool LogicClient::SetRouter(CCOS_PACKET_ROUTE Route)
  158. {
  159. if (IsClosed())
  160. {
  161. m_Router = Route;
  162. return true;
  163. }
  164. return false;
  165. }
  166. bool LogicClient::Lock(DWORD timeout)
  167. {
  168. if (m_ClientLock == NULL)
  169. {
  170. FERROR("{$} @ Trans {$} Lock handle is null", m_strClientName, m_strCurTransaction);
  171. return false;
  172. }
  173. bool LockRet = (((CcosLock*)m_ClientLock)->Thread_Lock(timeout) == WAIT_OBJECT_0);
  174. std::cout << m_strClientName << " [LLKK] "<< (UINT64)this << " Try Lock Result " << LockRet << " With timeout " << timeout << endl;
  175. if (!LockRet)
  176. std::cout << m_strClientName << " [LLKK] " << (UINT64)this << " Lock Failed" << endl;
  177. return LockRet;
  178. }
  179. void LogicClient::UnLock()
  180. {
  181. if (m_ClientLock == NULL)
  182. {
  183. FERROR("{$} @ Trans {$} UnLock handle is null", m_strClientName, m_strCurTransaction);
  184. return ;
  185. }
  186. std::cout << m_strClientName << " [LLKK] " << (UINT64)this << "Try to Unlock " << endl;
  187. ((CcosLock*)m_ClientLock)->Thread_UnLock();
  188. std::cout << m_strClientName << " [LLKK] " << (UINT64)this << " Unlock " << endl;
  189. }
  190. bool LogicClient::InitClient(const char *pPath, int flags)
  191. {
  192. std::cout <<"Enter InitClient:pPath:"<< pPath << endl;
  193. ResDataObject rMsg;
  194. m_strDevicePath = pPath;
  195. m_OwnerThreadId = 0;
  196. (*m_pLastMsgInfo) = "";
  197. std::cout << "Start ClearQueue_Internal()" << endl;
  198. ClearQueue_Internal();
  199. FWARN("m_DeviceResource.clear() [{$}]", m_strDevicePath);
  200. m_DeviceResource.clear();
  201. //m_pFileHandle->m_Lang.SetVal("en-US");//NOT FINISHED YET
  202. //m_pFileHandle->m_Route = m_Router;//route
  203. //m_pFileHandle->m_Flags = flags;
  204. //m_pFileHandle->m_HandleId = 0;
  205. (*m_pFileHandle)[CCOS_PACK_HANDLE_LANG] = "en-US";//NOT FINISHED YET
  206. (*m_pFileHandle)[CCOS_PACK_HANDLE_ROUTE] = m_Router;//route
  207. (*m_pFileHandle)[CCOS_PACK_HANDLE_FLAGS] = flags;
  208. (*m_pFileHandle)[CCOS_PACKET_HANDLE_KEY] = (UINT64)0;//
  209. //target
  210. m_pFileHandle->GetTarget(false)[CCOS_PACK_TARGET_MACHINEID] = "";
  211. m_pFileHandle->GetTarget(false)[CCOS_PACK_TARGET_BUSID] = "";
  212. m_pFileHandle->GetTarget(false)[CCOS_PACK_TARGET_PROCID] = (UINT64)0;
  213. m_pFileHandle->GetTarget(false)[CCOS_PACK_TARGET_ADDR] = (UINT64)0;
  214. //m_pFileHandle->m_Dev.m_Addr = (UINT64)0;
  215. //m_pFileHandle->m_Dev.m_ProcID = (UINT64)0;
  216. //m_pFileHandle->m_Dev.m_busID = "";
  217. //m_pFileHandle->m_Dev.m_MachineID = "";
  218. //local
  219. m_pFileHandle->GetTarget()[CCOS_PACK_TARGET_MACHINEID] = (const char*)getLocalMachineId();
  220. m_pFileHandle->GetTarget()[CCOS_PACK_TARGET_BUSID] = (const char*)getLocalEbusId();
  221. m_pFileHandle->GetTarget()[CCOS_PACK_TARGET_PROCID] = (UINT64)GetCurrentProcessId();
  222. m_pFileHandle->GetTarget()[CCOS_PACK_TARGET_ADDR] = (UINT64)(PVOID*)m_pMqttConn;
  223. //m_pFileHandle->m_Owner.m_Addr = (UINT64)(PVOID*)m_pSysIF;
  224. //m_pFileHandle->m_Owner.m_ProcID = (UINT64)GetCurrentProcessId();
  225. //m_pFileHandle->m_Owner.m_busID = (const char*)getLocalEbusId();
  226. //m_pFileHandle->m_Owner.m_MachineID = (const char*)getLocalMachineId();
  227. m_FileFlags = flags;
  228. if (m_strDevicePath.length() <= 0)
  229. {
  230. //允许透传消息
  231. m_SyncMode = ACTION_SYNC;
  232. }
  233. if (pPath)
  234. {
  235. string busId;
  236. std::cout << "Start getBusIdFromFilePath()" << endl;
  237. if (getBusIdFromFilePath(pPath, busId) == false)
  238. {
  239. (*m_pFilePath) = "";
  240. //return false;
  241. }
  242. //m_pFileHandle->m_Dev.m_busID = busId;
  243. m_pFileHandle->GetTarget(false)[CCOS_PACK_TARGET_BUSID] = busId.c_str();
  244. (*m_pFilePath) = pPath;
  245. }
  246. string strLogPath = GetProcessDirectory() + R"(/Conf/log_config.xml)";
  247. string LogHost = (string)getRootpath();
  248. std::string moduleName = "LogicClient";
  249. bool ret = initLogModule(
  250. LogHost, // 主机名(用于日志路径中的{host}占位符)
  251. moduleName, // 唯一模块名
  252. strLogPath, // 配置文件路径
  253. true // 是否输出到控制台(可选)
  254. );
  255. if (!ret) {
  256. std::cerr << "Log init failed!" << std::endl;
  257. }
  258. // 绑定当前动态库的模块名(调用自身实现的接口)
  259. ClientSetLocalModuleName(moduleName);
  260. FINFO("Code Build datetime [{$} {$}] LogHost:{$}", __DATE__, __TIME__, LogHost);
  261. FWARN("\n{$}=============== LogicClient log begin : version:1.0.0.0 ===================\n", m_strClientName);
  262. return true;
  263. }
  264. bool LogicClient::GetFilePath(ResDataObject &path)
  265. {
  266. if (IsClosed() == false)
  267. {
  268. path = (*m_pFilePath).c_str();
  269. return true;
  270. }
  271. return false;
  272. }
  273. RET_STATUS LogicClient::ProcessActionResponse(ResDataObject &packet, ResDataObject &OutputParam)
  274. {
  275. RET_STATUS ret = RET_FAILED;
  276. if (PacketAnalizer::GetPacketRetCode(&packet, ret))
  277. {
  278. //get error or warning Msg here
  279. string errInfo;
  280. PacketAnalizer::GetPacketMsgInfo(&packet, errInfo);
  281. if (errInfo.size() > 0)
  282. {
  283. string actionname = PacketAnalizer::GetPacketKey(&packet);
  284. (*m_pLastMsgInfo) = actionname + ":" + errInfo;
  285. }
  286. if (ret >= RET_SUCCEED)
  287. {
  288. if (PacketAnalizer::GetPacketContext(&packet, OutputParam))
  289. {
  290. //succeed
  291. //printf("Thread:%d,Action OK\n", GetCurrentThreadId());
  292. return ret;
  293. }
  294. }
  295. if (ret == RET_INVALID)
  296. {
  297. //DisconnectCDI();
  298. }
  299. }
  300. return ret;
  301. }
  302. RET_STATUS LogicClient::ProcessResource(ResDataObject &packet)
  303. {
  304. ResDataObject resParam;
  305. RET_STATUS ret = RET_FAILED;
  306. //got match response
  307. if (PacketAnalizer::GetPacketRetCode(&packet, ret))
  308. {
  309. //get error or warning Msg here
  310. PacketAnalizer::GetPacketMsgInfo(&packet, (*m_pLastMsgInfo));
  311. if (ret >= RET_SUCCEED)
  312. {
  313. //whole device resource
  314. if (PacketAnalizer::GetPacketContext(&packet, m_DeviceResource))
  315. {
  316. FDEBUG("Update Device {$} Resource [{$}]", m_strDevicePath, m_DeviceResource.encode());
  317. return ret;
  318. }
  319. }
  320. }
  321. FERROR("Device Open Result Error", packet.encode());
  322. //put some log here
  323. FINFO("m_DeviceResource.clear() [{$}] after Device Open Result Error", m_strDevicePath);
  324. m_DeviceResource.clear();
  325. return RET_FAILED;
  326. }
  327. RET_STATUS LogicClient::ProcessClose(ResDataObject &packet)
  328. {
  329. //we have disconnect here
  330. PacketAnalizer::GetPacketMsgInfo(&packet, (*m_pLastMsgInfo));
  331. //make the object status as CLOSED
  332. //DisconnectCDI();
  333. //clear the info
  334. //m_pPacketReceivedQue->Lock();
  335. m_pPacketWaitQue->Clear();
  336. m_pPacketReceivedQue->Clear();
  337. //m_DeviceResource.clear();
  338. //m_pPacketReceivedQue->UnLock();
  339. //m_pPacketNotifyQue->Lock();
  340. m_pPacketNotifyQue->Clear();
  341. //m_pPacketNotifyQue->UnLock();
  342. return RET_INVALID;
  343. }
  344. RET_STATUS LogicClient::ProcessOpenResponse(ResDataObject &packet)
  345. {
  346. ResDataObject resParam;
  347. RET_STATUS ret = RET_FAILED;
  348. //got match response
  349. if (PacketAnalizer::GetPacketRetCode(&packet, ret))
  350. {
  351. //get error or warning Msg here
  352. PacketAnalizer::GetPacketMsgInfo(&packet, (*m_pLastMsgInfo));
  353. if (ret >= RET_SUCCEED)
  354. {
  355. if (PacketAnalizer::GetPacketHandle(&packet, resParam))
  356. {
  357. if (m_pFileHandle == NULL)
  358. return RET_FAILED;
  359. //got file handle
  360. if (m_pFileHandle->SetResDataObject(resParam))
  361. {
  362. //succeed here
  363. //Get Device Resource
  364. if (ProcessResource(packet) >= RET_SUCCEED)
  365. {
  366. string res = packet.encode();
  367. FDEBUG("OpenResponse ok {$}", res.substr(0, 16384));
  368. //FDEBUG("OpenResponse ok\n");
  369. if (m_bNeedNotify && m_ClosedFlag) {
  370. const char* realPath = NULL;
  371. if (m_strDevicePath[0] == '/')
  372. realPath = ((char*)m_strDevicePath.c_str()) + 1; //去掉首字符"/"
  373. else
  374. realPath = m_strDevicePath.c_str();
  375. string notifyTopic = realPath;
  376. notifyTopic += "/Notify/#";
  377. SubscribeTopic(m_pMqttConn, notifyTopic.c_str());
  378. // 等待订阅完成:轮询检查SUBACK是否收到,确保Notify订阅真正生效
  379. const DWORD notifyTimeoutMs = 5000;
  380. FINFO("[LogicClient::ProcessOpenResponse] {$} - Waiting for Notify subscription to complete (timeout: {$}ms)", m_strClientName, notifyTimeoutMs);
  381. if (!WaitForSubscriptionComplete(m_pMqttConn, notifyTimeoutMs)) {
  382. FERROR("[LogicClient::ProcessOpenResponse] {$} - Notify subscription did not complete within timeout", m_strClientName);
  383. }
  384. // SUBACK收到后,等待Broker完成内部路由表更新
  385. // 延时可通过环境变量MQTT_BROKER_ROUTING_DELAY_MS配置,默认200ms
  386. WaitForBrokerRouting(m_strClientName.c_str());
  387. }
  388. if (m_openCallbackFunc != nullptr)
  389. m_openCallbackFunc(this, m_strDevicePath.c_str(), 1);
  390. m_OwnerThreadId = (DWORD)GetCurrentThreadId();
  391. std::cout << "TID [" << m_OwnerThreadId << "] LogicClient::ProcessOpenResponse OpenResponse ok." << m_strClientName << endl;
  392. FDEBUG("LogicClient::ProcessOpenResponse {$} OpenResponse ok. {$}", m_OwnerThreadId, m_strClientName);
  393. m_hDeviceOpenOK->SetEvent();
  394. SetThreadOnTheRun(true); //线程可以正常运转
  395. m_ClosedFlag = false;
  396. return ret;
  397. }
  398. }
  399. }
  400. }
  401. }
  402. FERROR("Thread:{$} ,OpenResponse ng ",GetCurrentThreadId());
  403. //printf("Thread:%d,OpenResponse ng\n", GetCurrentThreadId());
  404. //put some log here
  405. return RET_FAILED;
  406. }
  407. RET_STATUS LogicClient::CloseDevice()
  408. {
  409. RET_STATUS ret = RET_FAILED;
  410. const char* realPath = NULL;
  411. if (m_strDevicePath[0] == '/')
  412. realPath = ((char*)m_strDevicePath.c_str()) + 1; //去掉首字符"/"
  413. else
  414. realPath = m_strDevicePath.c_str();
  415. FDEBUG("{$} CloseDevice {$} and use default topic {$}", m_strClientName, realPath, m_strDefaultTopic);
  416. if (Lock(1000) == false)
  417. {
  418. FERROR("CloseDev Lock Timeout for Dev: {$} ", m_strClientName);
  419. //GPRINTA_ERROR("OpenDev Lock Timeout for Dev:%s", pPath);
  420. return RET_TIMEOUT;
  421. }
  422. if (m_ClosedFlag)
  423. {
  424. UnSubscribe(m_pMqttConn, m_strDefaultTopic.c_str());
  425. if (m_bNeedNotify) {
  426. string notifyTopic = realPath;
  427. notifyTopic += "/Notify/#";
  428. UnSubscribe(m_pMqttConn, notifyTopic.c_str());
  429. }
  430. }
  431. UnLock();
  432. m_hDeviceOpenOK->ResetEvent();
  433. m_hDeviceCloseOK->SetEvent();
  434. //标志
  435. //m_ClosedFlag = true;
  436. ////make close req
  437. ResDataObject req;
  438. PacketAnalizer::MakeCloseRequest(req, (*m_pFileHandle));
  439. if ((m_FileFlags & CCOS_FILE_FLAGS::ABSCRACT_ONLINE) == CCOS_FILE_FLAGS::ABSCRACT_ONLINE)
  440. {
  441. if (m_strWS.length() > 0)
  442. {
  443. //需要显式 上设备上线
  444. ResDataObject resContext;
  445. resContext.add("Offline", m_strWS.c_str());
  446. PacketAnalizer::UpdatePacketContext(req, resContext);
  447. PublishAction(&req, m_pFilePath->c_str(), m_pMqttConn);
  448. }
  449. }
  450. ////send it
  451. ////ret = pLogicDeivce->CmdFromLogicDev(&req);
  452. ////UnLock();
  453. //DWORD dwret = WaitForSingleObject(m_hCloseOK, 1000);
  454. //if (dwret != WAIT_OBJECT_0)
  455. //{
  456. // //printf("Thread:%d,Send Close OK\n", GetCurrentThreadId());
  457. //}
  458. //else
  459. //{
  460. // printf("Thread:%d,Send Close Failed\n", GetCurrentThreadId());
  461. //}
  462. return ret;
  463. }
  464. RET_STATUS LogicClient::OpenDevice(bool bAsync)
  465. {
  466. std::cout << "[LogicClient::OpenDevice-Info] IN" << std::endl;
  467. if (m_strDevicePath.empty())
  468. {
  469. m_OwnerThreadId = (DWORD)GetCurrentThreadId();
  470. std::cout << "TID [" << m_OwnerThreadId << "] LogicClient::ProcessOpenResponse OpenResponse ok." << m_strClientName << std::endl;
  471. m_hDeviceOpenOK->SetEvent();
  472. SetThreadOnTheRun(true);
  473. m_ClosedFlag = false;
  474. return RET_SUCCEED;
  475. }
  476. const char* realPath = (m_strDevicePath[0] == '/') ? (m_strDevicePath.c_str() + 1) : m_strDevicePath.c_str();
  477. if (!Lock(1000))
  478. {
  479. return RET_TIMEOUT;
  480. }
  481. if (m_ClosedFlag)
  482. {
  483. FINFO("[LogicClient::OpenDevice-Info] {$} - Subscribing to default MQTT topic: {$}", m_strClientName, m_strDefaultTopic);
  484. SubscribeTopic(m_pMqttConn, m_strDefaultTopic.c_str());
  485. // 等待订阅完成:轮询检查SUBACK是否收到,而不是使用固定延时
  486. // 这样可以确保订阅真正生效后才发送消息,避免时序问题导致消息丢失
  487. const DWORD timeoutMs = 5000; // 5秒超时
  488. FINFO("[LogicClient::OpenDevice-Info] {$} - Waiting for subscription to complete (timeout: {$}ms)", m_strClientName, timeoutMs);
  489. if (!WaitForSubscriptionComplete(m_pMqttConn, timeoutMs)) {
  490. FERROR("[LogicClient::OpenDevice-Error] {$} - Subscription did not complete within timeout", m_strClientName);
  491. // 即使超时也继续,但记录错误
  492. }
  493. // SUBACK收到后,等待Broker完成内部路由表更新
  494. // 延时可通过环境变量MQTT_BROKER_ROUTING_DELAY_MS配置,默认200ms
  495. WaitForBrokerRouting(m_strClientName.c_str());
  496. }
  497. // 输出调试信息
  498. std::cout << "[LogicClient::OpenDevice-Debug] " << m_strClientName << " - OpenDevice (Path: " << realPath
  499. << ", Default Topic: " << m_strDefaultTopic
  500. << ", Async Mode: " << (bAsync ? "Enabled" : "Disabled")
  501. << (m_ClosedFlag ? "" : ", MQTT Topic: No Re-Subscription Required") << std::endl;
  502. // 构建并发送请求
  503. ResDataObject req;
  504. DWORD reqidx = PacketAnalizer::MakeOpenRequest(req, (*m_pFileHandle), realPath);
  505. PacketAnalizer::UpdateOpenRequest(req, getLocalMachineId(), getLocalEbusId(), GetCurrentProcessId(), (UINT64)m_pMqttConn);
  506. PacketAnalizer::UpdateContextTopic(&req, m_strDefaultTopic.c_str());
  507. PacketAnalizer::UpdatePacketTopic(&req, realPath, m_strClientName.c_str());
  508. // 处理在线标志
  509. if ((m_FileFlags & CCOS_FILE_FLAGS::ABSCRACT_ONLINE) == CCOS_FILE_FLAGS::ABSCRACT_ONLINE && !m_strWS.empty())
  510. {
  511. ResDataObject resContext;
  512. PacketAnalizer::GetPacketContext(&req, resContext);
  513. resContext.add("Online", m_strWS.c_str());
  514. PacketAnalizer::UpdatePacketContext(req, resContext);
  515. }
  516. // 发布请求
  517. int publishResult = PublishAction(&req, realPath, m_pMqttConn);
  518. UnLock();
  519. if (publishResult < 0)
  520. {
  521. return RET_FAILED;
  522. }
  523. if (!bAsync)
  524. {
  525. auto waitAndCheck = [&]() -> bool {
  526. std::cout << "try Wait for Open ok." << m_strClientName << std::endl;
  527. if (m_hDeviceOpenOK->Wait(4000))
  528. {
  529. std::cout << "Open ok. done" << m_strClientName << std::endl;
  530. if (m_openCallbackFunc) m_openCallbackFunc(this, realPath, 1);
  531. return true;
  532. }
  533. return false;
  534. };
  535. if (waitAndCheck())
  536. {
  537. return RET_SUCCEED;
  538. }
  539. }
  540. else
  541. {
  542. return RET_FAILED;
  543. }
  544. return RET_SUCCEED;
  545. }
  546. bool LogicClient::OnStartThread()
  547. {
  548. auto ret_ptr = std::make_shared<RET_STATUS>(RET_FAILED);
  549. std::string realPath;
  550. std::cout << "OnStartThreadL:m_strDevicePath: " << m_strDevicePath << std::endl;
  551. if (!m_strDevicePath.empty() && m_strDevicePath[0] == '/')
  552. realPath = m_strDevicePath.substr(1); // string直接截取,安全无指针问题
  553. else
  554. realPath = m_strDevicePath; // 直接赋值string,值拷贝安全
  555. //if (Lock(10000) == false)
  556. //{
  557. // //GPRINTA_ERROR("OpenDev Lock Timeout for Dev[flag:%d]:%s", flags, pPath);
  558. // return false;
  559. //}
  560. //GPRINTA_DEBUG("Thread:%d,Open Entry", GetCurrentThreadId());
  561. //make connection to CDI
  562. //ConnectCDI();
  563. ResDataObject req, res, resParam;
  564. //make open req
  565. //HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
  566. // 新增调试输出
  567. if (m_pMqttConn) {
  568. std::cout << "m_pMqttConn Memory address: " << m_pMqttConn << std::endl;
  569. // 解包元组内容并输出
  570. void* mqttClient = std::get<0>(*m_pMqttConn);
  571. mqtt_topic_list* topicList = std::get<1>(*m_pMqttConn);
  572. void* msgHook = std::get<2>(*m_pMqttConn);
  573. std::string clientId = std::get<3>(*m_pMqttConn);
  574. ccos_mqtt_callback callback = std::get<4>(*m_pMqttConn);
  575. pthread_t threadId = std::get<5>(*m_pMqttConn);
  576. CcosLock* connLock = std::get<6>(*m_pMqttConn);
  577. mqtt_msg_list* msgList = std::get<7>(*m_pMqttConn);
  578. sem_t* semaphore = std::get<8>(*m_pMqttConn);
  579. std::cout << "MQTT Client Handle: " << mqttClient << std::endl;
  580. std::cout << "MQTT Topic List: " << topicList << std::endl;
  581. std::cout << "Message Hook ID: " << msgHook << std::endl;
  582. std::cout << "Client ID: " << (!clientId.empty() ? clientId : "null") << std::endl;
  583. std::cout << "Thread ID: " << threadId << std::endl;
  584. std::cout << "Connection Lock: " << connLock << std::endl;
  585. std::cout << "Message List: " << msgList << std::endl;
  586. std::cout << "Semaphore Handle: " << semaphore << std::endl;
  587. }
  588. else {
  589. std::cout << "m_pMqttConn is nullptr" << std::endl;
  590. }
  591. //HANDLE hOpened = CreateEvent(NULL, FALSE, FALSE, NULL);
  592. if (m_pMqttConn == nullptr)
  593. {
  594. FINFO("LogicClient::Open {$} try open path:[{$}]", m_strClientName, realPath );
  595. std::cout << CurrentDateTime() << " LogicClient::Open [" << m_strClientName << "] try open path: " << realPath << endl << endl;
  596. m_pMqttConn = NewConnection(m_strClientName.c_str(), [ret_ptr, realPath, this](ResDataObject* rsp, const char* topic, void* conn_void) {
  597. //m_pMqttConn = CreateConnection
  598. std::cout << "OnStartThread::NewConnnect callback in "<< std::endl;
  599. if (m_pMqttConn == NULL)
  600. return;
  601. //回调函数不再加锁,要确保每一步都是ok的
  602. /*
  603. if (Lock(1000) == false)
  604. {
  605. FERROR("callback Lock Timeout for Dev: {$} ", m_strClientName);
  606. //GPRINTA_ERROR("OpenDev Lock Timeout for Dev:%s", pPath);
  607. return ;
  608. }*/
  609. ccos_mqtt_connection* conn = (ccos_mqtt_connection*)conn_void;
  610. if (PacketAnalizer::GetPacketType(rsp) == PACKET_TYPE_RES)
  611. {
  612. //check cmd
  613. string path = realPath;
  614. if ((PacketAnalizer::GetPacketCmd(rsp) == PACKET_CMD_OPEN) &&
  615. (PacketAnalizer::GetPacketKey(rsp).substr(0, path.length()) == path || PacketAnalizer::GetPacketKey(rsp) == realPath))
  616. {
  617. FINFO("{$} LogicClient::Open {$} OK ", m_strClientName, realPath);
  618. std::cout << "\n\n-----------" << CurrentDateTime() << "LogicClient::Open OK [" << m_strClientName << "] try open path:" << realPath << endl << endl;
  619. if (Lock(2000))
  620. {
  621. *ret_ptr = ProcessOpenResponse(*rsp);
  622. UnLock();
  623. }
  624. else
  625. {
  626. FERROR("{$} Process Open Result with Lock Client failed ", m_strClientName);
  627. }
  628. }
  629. else
  630. {
  631. FINFO("Unkown Packet: cmd {$} packet key: {$}", (int)PacketAnalizer::GetPacketCmd(rsp), PacketAnalizer::GetPacketKey(rsp) );
  632. std::cout << m_strClientName << CurrentDateTime() << "Try Conn callback get unkown packet pointer [" << (UINT64)this << endl;
  633. std::cout << "Unkown Packet: cmd [" << PacketAnalizer::GetPacketCmd(rsp) << "] packet key: " << PacketAnalizer::GetPacketKey(rsp) << "" << endl;
  634. if (m_pPacketArrivedCallbackFunc != nullptr)
  635. {
  636. m_pPacketArrivedCallbackFunc(rsp, topic, conn);
  637. }
  638. else
  639. {
  640. //m_pPacketReceivedQue->Lock();
  641. m_pPacketReceivedQue->InQueue(*rsp);
  642. //SetEvent(m_NotifyEvent);//notify to user
  643. m_ResponseEvent->SetEvent();
  644. //m_pPacketReceivedQue->UnLock();
  645. }
  646. }
  647. }
  648. else
  649. {
  650. //got other one
  651. //printf("Thread:%d,in open.got other packet\n", GetCurrentThreadId());
  652. //GPRINTA_DEBUG("in open.got other packet\n\n");
  653. //check priority one => CLOSE
  654. if (PacketAnalizer::GetPacketCmd((ResDataObject*)rsp) == PACKET_CMD_CLOSE)
  655. {
  656. std::cout << CurrentDateTime() << m_strClientName << "Got Close Paket ..." << endl;
  657. //we have disconnect here
  658. //GPRINTA_DEBUG("in open.got Close packet\n\n");
  659. *ret_ptr = ProcessClose(*rsp);
  660. }
  661. else {
  662. std::cout << "*****-----***** " << CurrentDateTime() << m_strClientName << " Received msg " << rsp->encode() << endl;
  663. if (m_pPacketArrivedCallbackFunc != nullptr)
  664. m_pPacketArrivedCallbackFunc(rsp, topic, conn);
  665. else
  666. {
  667. if (PacketAnalizer::GetPacketType(rsp) == PACKET_TYPE_NOTIFY )
  668. {
  669. PACKET_CMD cmd = PACKET_CMD_NONE;
  670. PACKET_TYPE rType;
  671. string key;
  672. rType = PacketAnalizer::GetPacketType(rsp);
  673. cmd = PacketAnalizer::GetPacketCmd(rsp);
  674. if (rType == PACKET_TYPE_NOTIFY /*&& m_pActionName->size() <= 0*/ && cmd == PACKET_CMD_UPDATE)
  675. {
  676. //只有在非Action期间,更新,如果有遗漏,再说 2024.9.2
  677. cmd = PacketAnalizer::GetPacketCmd(rsp);
  678. key = PacketAnalizer::GetPacketKey(rsp);
  679. //2.notify
  680. UpdateDeviceResource(cmd, *rsp);
  681. }
  682. else
  683. {
  684. FWARN("{$} Got unexpected.. Packet {$}", m_strClientName, rsp->encode());
  685. }
  686. //m_pPacketNotifyQue->Lock();
  687. m_pPacketNotifyQue->InQueue(*rsp);
  688. //SetEvent(m_NotifyEvent);//notify to user
  689. //m_pPacketNotifyQue->UnLock();
  690. m_NotifyEvent->SetEvent();
  691. }
  692. else
  693. PacketArrived(rsp);
  694. }
  695. }
  696. }
  697. //UnLock();
  698. });
  699. }
  700. if (m_pMqttConn == nullptr) {
  701. FERROR("LogicClient {$} Connect Mqtt client failed with open device : {$}", m_strClientName, realPath);
  702. std::cout << "XXXXXX XXXXXX [" << m_strClientName << "] LogicClient Connect Mqtt client failed with open device [" << realPath << "]" << endl;
  703. //UnLock();
  704. if (m_openCallbackFunc != nullptr)
  705. m_openCallbackFunc(this, realPath.c_str(), 0);
  706. return false;
  707. }
  708. //ret = RET_SUCCEED;
  709. //SubscribeTopic(m_pMqttConn, m_strDefaultTopic.c_str());
  710. //PacketAnalizer::UpdateOpenRequest(req, getLocalMachineId(), getLocalEbusId(), GetCurrentProcessId(), (UINT64)m_pMqttConn);
  711. //PacketAnalizer::UpdateContextTopic(&req, m_strDefaultTopic.c_str());
  712. //PacketAnalizer::UpdatePacketTopic(&req, realPath, m_strClientName.c_str());
  713. //PublishAction(&req, realPath, m_pMqttConn);
  714. ////UnLock();
  715. //DWORD dwret = WaitForSingleObject(m_hOpenOK, 4000);
  716. //if (dwret == WAIT_OBJECT_0)
  717. //{
  718. // if (m_openCallbackFunc != nullptr)
  719. // m_openCallbackFunc(this, realPath, 1);
  720. // return true;
  721. //}
  722. if (OpenDevice() == RET_SUCCEED)
  723. return true;
  724. FINFO("LogicClient {$} Open Device {$} failed ", m_strClientName, realPath);
  725. if (IsClosed()) {
  726. std::cout << CurrentDateTime()<< " XXXXXX XXXXXX [Thread Exiting] LogicClient Open Device failed" << endl;
  727. }
  728. else {
  729. std::cout << "XXXXXX XXXXXX [" << m_strClientName << "]LogicClient Open Device [" << realPath << "] failed " << endl;
  730. }
  731. if (m_openCallbackFunc != nullptr)
  732. m_openCallbackFunc(this, realPath.c_str(), 0);
  733. CloseConnection(m_pMqttConn);
  734. m_pMqttConn = nullptr;
  735. return false;
  736. }
  737. bool LogicClient::OnEndThread()
  738. {
  739. std::cout << "Thread End..." << endl;
  740. FINFO("End Client Thread");
  741. //CloseDevice();
  742. //ResDataObject req;
  743. ////make close req
  744. //PacketAnalizer::MakeCloseRequest(req, (*m_pFileHandle));
  745. ////send it
  746. ////ret = pLogicDeivce->CmdFromLogicDev(&req);
  747. //PublishAction(&req, m_pFilePath->c_str(), m_pMqttConn);
  748. ////UnLock();
  749. //DWORD dwret = WaitForSingleObject(m_hCloseOK, 1000);
  750. //if (dwret != WAIT_OBJECT_0)
  751. //{
  752. // //printf("Thread:%d,Send Close OK\n", GetCurrentThreadId());
  753. //
  754. //}
  755. //else
  756. //{
  757. // printf("Thread:%d,Send Close Failed\n", GetCurrentThreadId());
  758. //}
  759. //std::cout << CurrentDateTime() << "[" << m_strClientName << "] try Close Mqtt " << endl;
  760. //CloseConnection(m_pMqttConn);
  761. m_pMqttConn = nullptr;
  762. return true;
  763. }
  764. bool LogicClient::Exec(void)
  765. {
  766. //ResDataObject req;
  767. //if (ReadCmd(req))
  768. //{
  769. // return true;
  770. //}
  771. std::vector<std::shared_ptr<LinuxEvent>> hWait = {
  772. m_ExitFlag,
  773. m_hReOpen,
  774. };
  775. DWORD dwRet = LinuxEvent::WaitForMultipleEvents(hWait, 10);//WaitForSingleObject(m_ExitFlag, 100);
  776. if (dwRet == WAIT_OBJECT_0)
  777. {
  778. std::cout << m_strClientName << " MQTT Prepare Exit " << endl;
  779. return false;
  780. }
  781. else if (dwRet == WAIT_OBJECT_0 + 1)
  782. {
  783. FDEBUG(" {$} try Real ReOpen", m_strClientName);
  784. //CloseDevice();
  785. m_hDeviceOpenOK->ResetEvent();
  786. OpenDevice(false);
  787. FDEBUG(" {$} try ReOpen over", m_strClientName);
  788. }
  789. usleep(1000);
  790. return true;
  791. }
  792. int LogicClient::ReOpenDevice()
  793. {
  794. FINFO(" {$} set to ReOpen",m_strClientName );
  795. m_hDeviceOpenOK->ResetEvent();
  796. m_hReOpen->SetEvent();
  797. return RET_SUCCEED;
  798. }
  799. int LogicClient::Open(const char *pPath, int flags, const char* pszWS, DWORD timeout, logic_client_open_callback calback)
  800. {
  801. std::cout << CurrentDateTime() << " LogicClient::Open[" << m_strClientName << "] try Open " << pPath << endl;
  802. if (Lock(timeout) == false)
  803. {
  804. std::cout << "FERROR::OpenDev Lock Timeout for Dev[flag: " << flags << " ]: " << pPath << endl;
  805. FERROR("OpenDev Lock Timeout for Dev[flag: {$} ]: {$} ", flags, pPath);
  806. //GPRINTA_ERROR("OpenDev Lock Timeout for Dev[flag:%d]:%s", flags, pPath);
  807. return RET_TIMEOUT;
  808. }
  809. m_strWS = pszWS;
  810. if (InitClient(pPath, flags) == false)
  811. {
  812. UnLock();
  813. std::cout << "FERROR::InitClient Failed for Dev [flag: " << flags << " ]: " << pPath << endl;
  814. FERROR("InitClient Failed for Dev [flag: {$} ]: {$} ", flags, pPath);
  815. //GPRINTA_ERROR("InitClient Failed for Dev[flag:%d]:%s", flags, pPath);
  816. return RET_FAILED;
  817. }
  818. std::cout <<"IsClosed" << endl;
  819. if (IsClosed() == false)
  820. {
  821. std::cout << "LogicClient::Open " << m_strClientName << " try is Already Opend: " << m_strDevicePath << endl;
  822. FINFO("LogicClient::Open {$} try is Already Opend: ", m_strClientName, m_strDevicePath);
  823. std::cout << CurrentDateTime() << " LogicClient::Open [" << m_strClientName << "] try is Already Opend: " << m_strDevicePath << endl;
  824. if (Close() == RET_PENDING)
  825. {
  826. UnLock();
  827. std::cout << "OpenDev Close Method is onGoing.. for Dev [flag: " << flags << " ]: " << pPath << endl;
  828. FERROR("OpenDev Close Method is onGoing.. for Dev [flag: {$} ]: {$} ", flags, pPath);
  829. //GPRINTA_ERROR("OpenDev Close Method is onGoing.. for Dev[flag:%d]:%s", flags, pPath);
  830. return RET_PENDING;
  831. }
  832. }
  833. m_openCallbackFunc = calback;
  834. std::cout << "UnLock" << endl;
  835. UnLock();
  836. std::cout << "StartThread" << endl;
  837. StartThread(false, true);
  838. if (calback == nullptr)
  839. {
  840. if (WaitTheThreadOnTheRun(timeout))
  841. return RET_SUCCEED;
  842. std::cout << "WaitTheThreadOnTheRun Timeout " << timeout << " for Open " << pPath << endl;
  843. FERROR("WaitTheThreadOnTheRun Timeout {$} for Open {$}", timeout, pPath);
  844. //GPRINTA_ERROR("WaitTheThreadOnTheRun Timeout %i for Open %s", timeout, pPath);
  845. return RET_FAILED;
  846. }
  847. return RET_SUCCEED;
  848. }
  849. int LogicClient::Close()
  850. {
  851. RET_STATUS ret = RET_SUCCEED;
  852. FINFO(" LogicClient::Close {$} try Close path:",m_strClientName , m_strDevicePath);
  853. std::cout << CurrentDateTime() << " LogicClient::Close [" << m_strClientName << "] try Close path: " << m_strDevicePath << endl;
  854. if (Lock(1000) == false)
  855. {
  856. FINFO("close wait timeout");
  857. std::cout << "close wait timeout " << endl;
  858. //return RET_PENDING;
  859. }
  860. if (IsClosed() == false)
  861. {
  862. StopThread(3000);
  863. CloseConnection(m_pMqttConn);
  864. }
  865. //printf("Thread:%d,Close Entry\n", GetCurrentThreadId());
  866. UnLock();
  867. FINFO(" LogicClient::Close {$} CloseConnection : {$}", m_strClientName, m_strDevicePath);
  868. std::cout << CurrentDateTime() << " LogicClient::Close [" << m_strClientName << "] CloseConnection : " << m_strDevicePath << endl;
  869. //Disconnect
  870. //DisconnectCDI();
  871. //底层MQTT连接并不关闭,除非显式关闭,或者对象被释放
  872. m_hDeviceOpenOK->ResetEvent();
  873. m_pMqttConn = nullptr;
  874. m_ClosedFlag = true;
  875. FINFO(" LogicClient::Close {$} Close Over.:", m_strClientName, m_strDevicePath);
  876. std::cout << CurrentDateTime() << " LogicClient::Close [" << m_strClientName << "] Close Over.: " << m_strDevicePath << endl;
  877. return ret;
  878. }
  879. const char *LogicClient::GetLastErrorInfo()
  880. {
  881. return m_pLastMsgInfo->c_str();
  882. }
  883. bool LogicClient::IsClosed()
  884. {
  885. return m_ClosedFlag;
  886. }
  887. //bool LogicClient::IsOpenOK()
  888. //{
  889. // if (m_ClosedFlag)
  890. // return false;
  891. // DWORD dwRet = WaitForSingleObject(m_hDeviceOpenOK, 0);
  892. // if (dwRet == WAIT_OBJECT_0)
  893. // {
  894. // return true;
  895. // }
  896. // else
  897. // {
  898. // return false;
  899. // }
  900. //}
  901. /*
  902. bool LogicClient::IsAllReqFinished()
  903. {
  904. ClientSysIF *p = (ClientSysIF*)m_pSysIF;
  905. bool ret = false;
  906. ret = p->IsAllRequestFinished();
  907. return (ret);
  908. }
  909. bool LogicClient::SetRequestSyncMode(ACTION_SYNC_MODE Sync)
  910. {
  911. if (IsAllReqFinished())
  912. {
  913. m_SyncMode = Sync;
  914. return true;
  915. }
  916. return false;
  917. }
  918. ACTION_SYNC_MODE LogicClient::GetRequestSyncMode()
  919. {
  920. return m_SyncMode;
  921. }*/
  922. RET_STATUS LogicClient::UpdateDeviceResource(DWORD timeout)
  923. {
  924. RET_STATUS ret = RET_FAILED;
  925. Lock();
  926. ResDataObject req, res;
  927. try {
  928. ret = (RET_STATUS)Action("UpdateDeviceResource", req, res, timeout);
  929. if (ret >= RET_SUCCEED)
  930. {
  931. FINFO("m_DeviceResource.clear() [{$}]", m_strDevicePath);
  932. //update
  933. m_DeviceResource.clear();
  934. m_DeviceResource = res;
  935. FINFO("m_DeviceResource clear [{$}] .set [{$}]", m_strDevicePath, res.encode());
  936. }
  937. }
  938. catch (...)
  939. {
  940. ret = RET_FAILED;
  941. }
  942. UnLock();
  943. return ret;
  944. }
  945. bool LogicClient::HasAction(const char* pszAction)
  946. {
  947. if (string(pszAction) == "UpdateDeviceResource")
  948. return true;
  949. int actid = m_DeviceResource.GetFirstOf("Action");
  950. if (actid < 0)
  951. {
  952. FINFO("Device [{$}] has no Action Items for Action [{$}] in [{$}]", m_strDevicePath, pszAction, m_DeviceResource.encode());
  953. return false;
  954. }
  955. ResDataObject actions = m_DeviceResource[actid];
  956. if (actions.GetFirstOf(pszAction) >= 0)
  957. return true;
  958. FINFO("Device [{$}] Action no Items for Action [{$}] in [{$}]", m_strDevicePath, pszAction, actions.encode());
  959. return false;
  960. }
  961. bool LogicClient::HasProperty(const char* pszProperty)
  962. {
  963. int atrid = m_DeviceResource.GetFirstOf("Attribute");
  964. if (atrid < 0)
  965. return false;
  966. ResDataObject actions = m_DeviceResource[atrid];
  967. if (actions.GetFirstOf(pszProperty) >= 0)
  968. return true;
  969. return false;
  970. }
  971. bool LogicClient::GetProperty(const char* pszProperty, ResDataObject& resRet)
  972. {
  973. int atrid = m_DeviceResource.GetFirstOf("Attribute");
  974. if (atrid < 0)
  975. return false;
  976. ResDataObject propertys = m_DeviceResource[atrid];
  977. if (propertys.GetFirstOf(pszProperty) >= 0)
  978. {
  979. resRet = propertys[pszProperty];
  980. return true;
  981. }
  982. return false;
  983. }
  984. RET_STATUS LogicClient::GetDeviceType(GUID &DevType)
  985. {
  986. RET_STATUS ret = RET_FAILED;
  987. Lock();
  988. try {
  989. if (IsClosed() == false)
  990. {
  991. if (string_2_guid((const char *)m_DeviceResource["DeviceType"], DevType))
  992. {
  993. ret = RET_SUCCEED;
  994. }
  995. }
  996. }
  997. catch (...)
  998. {
  999. ret = RET_FAILED;
  1000. }
  1001. UnLock();
  1002. return ret;
  1003. }
  1004. RET_STATUS LogicClient::GetDeviceResource(ResDataObject PARAM_OUT *pDeviceResource)
  1005. {
  1006. RET_STATUS ret = RET_FAILED;
  1007. bool blocked = Lock();
  1008. try {
  1009. if (IsClosed() == false)
  1010. {
  1011. (*pDeviceResource) = m_DeviceResource;
  1012. string res = m_DeviceResource.encode();
  1013. FINFO("GetDeviceResource ok. {$}", res.substr(0, 16384));
  1014. ret = RET_SUCCEED;
  1015. UnLock();
  1016. return ret;
  1017. }
  1018. }
  1019. catch (...)
  1020. {
  1021. ret = RET_FAILED;
  1022. }
  1023. UnLock();
  1024. FINFO("{$} GetDeviceResource failed with closedflag [{$}]",m_strClientName, m_ClosedFlag?1:0);
  1025. return ret;
  1026. }
  1027. void LogicClient::PacketArrived(ResDataObject *pResponse)
  1028. {
  1029. //two kind packet.
  1030. //1.response
  1031. //1.1 open response
  1032. //1.2 close response
  1033. //no Locks!!!!!!
  1034. //assert(0);
  1035. //check priority one => CLOSE
  1036. //if (PacketAnalizer::GetPacketCmd(pResponse) == PACKET_CMD_CLOSE)
  1037. //{
  1038. // //we have disconnect here
  1039. // printf("Thread:%d,Got Close Notify.Passive Close\n", GetCurrentThreadId());
  1040. // ProcessClose(*pResponse);
  1041. // SetEvent(m_NotifyEvent);//notify to user
  1042. // SetEvent(m_ResponseEvent);//notify to user
  1043. // return;
  1044. //}
  1045. //1.3 update response
  1046. //1.4 action response
  1047. //1.5 data ??
  1048. //2.notify
  1049. //2.1 data notify
  1050. //m_pPacketReceivedQue->Lock();
  1051. m_pPacketReceivedQue->InQueue(*pResponse);
  1052. //for test
  1053. //GPRINTA_DEBUG("Client:%d,Thread %d:Got Packet--JG:%s",this, GetCurrentThreadId(), pResponse->encode());
  1054. if (m_ReqIdx != 0)
  1055. {
  1056. if (m_ReqIdx == PacketAnalizer::GetPacketIdx(pResponse))
  1057. {
  1058. if (PacketAnalizer::GetPacketType(pResponse) == PACKET_TYPE_RES)
  1059. {
  1060. //check cmd
  1061. if ((PacketAnalizer::GetPacketCmd(pResponse) == PACKET_CMD_EXE) &&
  1062. (PacketAnalizer::GetPacketKey(pResponse) == (*m_pActionName)))
  1063. {
  1064. //got match response
  1065. //for test
  1066. //GPRINTA_DEBUG("Client:%d,Got Response--JG",this);
  1067. m_ResponseEvent->SetEvent();
  1068. //m_pPacketReceivedQue->UnLock();
  1069. return;
  1070. }
  1071. }
  1072. FERROR(" {$} Action Resp Error {$}", m_strClientName, pResponse->encode());
  1073. std::cout << "[" << m_strClientName << "] Action Resp Error " << pResponse->encode() << endl;
  1074. }
  1075. else
  1076. {
  1077. FDEBUG(" {$} When Actioned.. Get Notify {$} ", m_strClientName, pResponse->encode());
  1078. std::cout << "[" << m_strClientName << "] When Actioned.. Get Notify " << pResponse->encode() << endl;
  1079. }
  1080. }
  1081. else {
  1082. FDEBUG(" {$} Get Notify {$}", m_strClientName, pResponse->encode());
  1083. std::cout << "[" << m_strClientName << "] Get Notify " << pResponse->encode() << endl;
  1084. }
  1085. m_ResponseEvent->SetEvent();//notify to user
  1086. //m_pPacketReceivedQue->UnLock();
  1087. }
  1088. int LogicClient::Action_Trans(ResDataObject* pOrgReq, DWORD timeout)
  1089. {
  1090. RET_STATUS ret = RET_FAILED;
  1091. //ResDataObject req;
  1092. if (Lock(timeout) == false)
  1093. {
  1094. return RET_TIMEOUT;
  1095. }
  1096. //printf("Thread:%d,Action Entry\n", GetCurrentThreadId());
  1097. if (m_ClosedFlag)
  1098. {
  1099. UnLock();
  1100. return ret;
  1101. }
  1102. if (IsThreadSafe() == false)
  1103. {
  1104. UnLock();
  1105. return RET_THREAD_INVALID;
  1106. }
  1107. //must be in SYNC mode
  1108. if (m_SyncMode != ACTION_SYNC)
  1109. {
  1110. UnLock();
  1111. return ret;
  1112. }
  1113. //make packet request
  1114. //m_ReqIdx = PacketAnalizer::MakeActionRequest(req, (*m_pFileHandle), pActionName, ReqParams, m_SyncMode);
  1115. //(*m_pActionName) = pActionName;
  1116. FDEBUG(" {$} at {$} Action_Trans Req: {$} ", m_strClientName, m_pFilePath->c_str(), pOrgReq->encode());
  1117. PacketAnalizer::UpdateContextTopic(pOrgReq, m_strDefaultTopic.c_str());
  1118. string actionName = PacketAnalizer::GetPacketKey(pOrgReq);
  1119. PacketAnalizer::UpdatePacketTransaction(*pOrgReq, m_strCurTransaction);
  1120. //send packet
  1121. //ret = pLogicDeivce->CmdFromLogicDev(&req);
  1122. int nret = PublishAction(pOrgReq, PacketAnalizer::GetActionTopic(m_pFilePath->c_str(), actionName.c_str()).c_str(), m_pMqttConn);
  1123. if (nret > 0)
  1124. {
  1125. ret = RET_SUCCEED;
  1126. }
  1127. else
  1128. {
  1129. m_ReqIdx = 0;
  1130. (*m_pActionName) = "";
  1131. }
  1132. UnLock();
  1133. return ret;
  1134. }
  1135. int LogicClient::Action_Req(const char *pActionName, ResDataObject &ReqParams, DWORD timeout, const char* pszDevicePath)
  1136. {
  1137. RET_STATUS ret = RET_FAILED;
  1138. ResDataObject req;
  1139. if (Lock(timeout) == false)
  1140. {
  1141. FERROR("try Lock failed for :Action[{$}]", pActionName);
  1142. return RET_TIMEOUT;
  1143. }
  1144. //printf("Thread:%d,Action Entry\n", GetCurrentThreadId());
  1145. if (m_ClosedFlag)
  1146. {
  1147. FERROR("Clinet {$} aready closed. :Action[{$}]", m_strClientName, pActionName);
  1148. UnLock();
  1149. return ret;
  1150. }
  1151. if (IsThreadSafe() == false)
  1152. {
  1153. FERROR("IsThreadSafe() == false ThreadName {$}. :Action[{$}]", m_strName, pActionName);
  1154. UnLock();
  1155. return RET_THREAD_INVALID;
  1156. }
  1157. if (pszDevicePath == nullptr && !HasAction(pActionName))
  1158. {
  1159. FERROR("pszDevicePath == nullptr && !HasAction(pActionName) ThreadName {$}. :Action[{$}] with devPath[{$}]", m_strName, pActionName, pszDevicePath);
  1160. return RET_SUCCEED;
  1161. }
  1162. //must be in SYNC mode
  1163. if (m_SyncMode != ACTION_SYNC)
  1164. {
  1165. FERROR("m_SyncMode != ACTION_SYNC {$} for :Action[{$}]", m_strClientName, pActionName);
  1166. UnLock();
  1167. return ret;
  1168. }
  1169. if (m_ReqIdx != 0)
  1170. {
  1171. FERROR(" {$} try call more than once Action_Req.Ignore first ActionReq Idx[{$}]:Action[{$}]", m_strClientName, m_ReqIdx, m_pActionName->c_str());
  1172. //GPRINTA_ERROR("try call more than once Action_Req.Ignore first ActionReq Idx[%u]:Action[%s] ",m_ReqIdx,m_pActionName->c_str());
  1173. m_ReqIdx = 0;
  1174. (*m_pActionName) = "";
  1175. }
  1176. FDEBUG(" {$} at {$} Action_Req {$} Req: {$} ", m_strClientName, m_pFilePath->c_str() , pActionName, ReqParams.encode());
  1177. //make packet request
  1178. m_ReqIdx = PacketAnalizer::MakeActionRequest(req, (*m_pFileHandle), pActionName, ReqParams, m_SyncMode);
  1179. (*m_pActionName) = pActionName;
  1180. PacketAnalizer::UpdateContextTopic(&req, m_strDefaultTopic.c_str());
  1181. PacketAnalizer::UpdatePacketTransaction(req, m_strCurTransaction);
  1182. //send packet
  1183. //ret = pLogicDeivce->CmdFromLogicDev(&req);
  1184. int nret = PublishAction(&req, PacketAnalizer::GetActionTopic(pszDevicePath == nullptr ? m_pFilePath->c_str() : pszDevicePath, pActionName).c_str(), m_pMqttConn);
  1185. if (nret > 0)
  1186. {
  1187. ret = RET_SUCCEED;
  1188. }
  1189. else
  1190. {
  1191. m_ReqIdx = 0;
  1192. (*m_pActionName) = "";
  1193. }
  1194. UnLock();
  1195. return ret;
  1196. }
  1197. int LogicClient::Action_Res(const char *pActionName, ResDataObject &ResParams, DWORD timeout)
  1198. {
  1199. RET_STATUS ret = RET_FAILED;
  1200. ResDataObject res;
  1201. if (Lock(timeout) == false)
  1202. {
  1203. return RET_TIMEOUT;
  1204. }
  1205. if (m_ClosedFlag)
  1206. {
  1207. //for test
  1208. //GPRINTA_DEBUG("Client:%d,Action_Res Closed ReqIdx:%d,Name:%s",this, m_ReqIdx, (*m_pActionName).c_str());
  1209. m_ReqIdx = 0;
  1210. (*m_pActionName) = "";
  1211. UnLock();
  1212. return RET_INVALID;
  1213. }
  1214. if (IsThreadSafe() == false)
  1215. {
  1216. //for test
  1217. //GPRINTA_DEBUG("Client:%d,Action_Res ThreadUnSafe ReqIdx:%d,Name:%s",this, m_ReqIdx, (*m_pActionName).c_str());
  1218. m_ReqIdx = 0;
  1219. (*m_pActionName) = "";
  1220. UnLock();
  1221. return RET_THREAD_INVALID;
  1222. }
  1223. //must be in SYNC mode
  1224. if (m_SyncMode != ACTION_SYNC)
  1225. {
  1226. //for test
  1227. //GPRINTA_DEBUG("Client:%d,Action_Res No Sync ReqIdx:%d,Name:%s",this, m_ReqIdx, (*m_pActionName).c_str());
  1228. m_ReqIdx = 0;
  1229. (*m_pActionName) = "";
  1230. UnLock();
  1231. return ret;
  1232. }
  1233. if (m_ReqIdx == 0)
  1234. {
  1235. //for test
  1236. //GPRINTA_DEBUG("Client:%d,Action_Res ReqIdx == 0 ReqIdx:%d,Name:%s",this, m_ReqIdx, (*m_pActionName).c_str());
  1237. (*m_pActionName) = "";
  1238. UnLock();
  1239. return ret;
  1240. }
  1241. //ReqIdx must not zero
  1242. while (m_pPacketReceivedQue->WaitForInQue(timeout) == WAIT_OBJECT_0)
  1243. {
  1244. //got response
  1245. if (m_pPacketReceivedQue->DeQueue(res))
  1246. {
  1247. //update notify evt
  1248. IsDataArrived();
  1249. if ((m_ReqIdx == PacketAnalizer::GetPacketIdx(&res)) &&
  1250. (PacketAnalizer::GetPacketType(&res) == PACKET_TYPE_RES))
  1251. {
  1252. //check cmd
  1253. if ((PacketAnalizer::GetPacketCmd(&res) != PACKET_CMD_EXE) ||
  1254. (PacketAnalizer::GetPacketKey(&res) != pActionName))
  1255. {
  1256. //wrong packet
  1257. continue;
  1258. }
  1259. //got match response
  1260. ret = ProcessActionResponse(res, ResParams);
  1261. //for test
  1262. //GPRINTA_DEBUG("Client:%d,Action_Res Finished ReqIdx:%d,Name:%s",this, m_ReqIdx, (*m_pActionName).c_str());
  1263. m_ReqIdx = 0;
  1264. (*m_pActionName) = "";
  1265. UnLock();
  1266. return ret;
  1267. }
  1268. else
  1269. {
  1270. //got other one
  1271. //check priority one => CLOSE
  1272. if (PacketAnalizer::GetPacketCmd(&res) == PACKET_CMD_CLOSE)
  1273. {
  1274. //we have disconnect here
  1275. ret = ProcessClose(res);
  1276. //for test
  1277. //GPRINTA_DEBUG("Client:%d,Action_Res Got Closed ReqIdx:%d,Name:%s",this, m_ReqIdx, (*m_pActionName).c_str());
  1278. m_ReqIdx = 0;
  1279. (*m_pActionName) = "";
  1280. UnLock();
  1281. return ret;
  1282. }
  1283. FERROR("{$} got device[{$}] what packet {$}",m_strClientName, m_strDevicePath, res.encode());
  1284. m_pPacketWaitQue->InQueue(res);
  1285. IsDataArrived();
  1286. }
  1287. }
  1288. }
  1289. ret = RET_TIMEOUT;
  1290. //for test
  1291. //GPRINTA_DEBUG("Client:%d,Action_Res Got Timeout ReqIdx:%d,Name:%s",this, m_ReqIdx, (*m_pActionName).c_str());
  1292. //m_ReqIdx = 0;
  1293. //(*m_pActionName) = "";
  1294. UnLock();
  1295. return ret;
  1296. }
  1297. std::shared_ptr<LinuxEvent> LogicClient::GetResponseHandle()
  1298. {
  1299. return m_ResponseEvent;
  1300. }
  1301. void LogicClient::SubScribeTopic(const char* pszTopic, bool bSubscribe)
  1302. {
  1303. if (bSubscribe)
  1304. SubscribeTopic(m_pMqttConn, pszTopic);
  1305. else
  1306. UnSubscribe(m_pMqttConn, pszTopic);
  1307. }
  1308. int LogicClient::Action(const char *pActionName, ResDataObject &ReqParams, ResDataObject &ResParams, DWORD timeout, const char* pszDevicePath)
  1309. {
  1310. RET_STATUS ret = RET_FAILED;
  1311. ResDataObject req, res;
  1312. if (Lock(timeout) == false)
  1313. {
  1314. std::cout << "[ERROR] " << m_strClientName << " try Action " << pActionName << " LockTimeout" << std::endl;
  1315. FERROR("{$} try Action {$} LockTimeout", m_strClientName, pActionName);
  1316. return RET_TIMEOUT;
  1317. }
  1318. //printf("Thread:%d,Action Entry\n", GetCurrentThreadId());
  1319. std::cout << "[DEBUG] Thread:" << GetCurrentThreadId() << ", Action Entry - " << pActionName << std::endl;
  1320. if (m_ClosedFlag)
  1321. {
  1322. FERROR("{$} try Action {$} Aready Closed", m_strClientName, pActionName);
  1323. std::cout << "[ERROR] " << m_strClientName << " try Action " << pActionName << " Already Closed" << std::endl;
  1324. UnLock();
  1325. return ret;
  1326. }
  1327. if (IsThreadSafe() == false)
  1328. {
  1329. FERROR("{$} try Action {$} IsThreadSafe false", m_strClientName, pActionName);
  1330. std::cout << "[ERROR] " << m_strClientName << " try Action " << pActionName << " IsThreadSafe false" << std::endl;
  1331. UnLock();
  1332. return RET_THREAD_INVALID;
  1333. }
  1334. if (pszDevicePath == nullptr && !HasAction(pActionName))
  1335. {
  1336. std::cout << "[ERROR] " << m_strClientName << " try Action " << pActionName
  1337. << " with pszDevicePath == nullptr && !HasAction(pActionName)" << std::endl;
  1338. FERROR("{$} try Action {$} with pszDevicePath == nullptr && !HasAction(pActionName)", m_strClientName, pActionName);
  1339. UnLock();
  1340. return RET_SUCCEED;
  1341. }
  1342. std::cout << "[DEBUG] " << m_strClientName << " at "
  1343. << (pszDevicePath == nullptr ? m_pFilePath->c_str() : pszDevicePath)
  1344. << " Action " << pActionName << " Req: " << ReqParams.encode() << std::endl;
  1345. FDEBUG(" {$} at {$} Action {$} Req: {$} ", m_strClientName, pszDevicePath == nullptr ? m_pFilePath->c_str() : pszDevicePath, pActionName, ReqParams.encode());
  1346. //make packet request
  1347. DWORD reqidx = PacketAnalizer::MakeActionRequest(req, (*m_pFileHandle), pActionName, ReqParams, m_SyncMode);
  1348. PacketAnalizer::UpdateContextTopic(&req, m_strDefaultTopic.c_str());
  1349. PacketAnalizer::UpdatePacketTransaction(req, m_strCurTransaction);
  1350. UnLock();
  1351. //send packet int ActionAndResp(ccos_mqtt_connection* hConnection,const char* pAction, ResDataObject* pContext, const char* pszTopic, ResDataObject& resObj, DWORD dwWaitTime )
  1352. //ret = pLogicDeivce->CmdFromLog icDev(&req);
  1353. int nret = ActionAndRespWithConnDefalt(m_pMqttConn, pActionName,req, &ReqParams,
  1354. PacketAnalizer::GetActionTopic(pszDevicePath==nullptr?m_pFilePath->c_str():pszDevicePath,pActionName).c_str(),
  1355. res, timeout);
  1356. if (nret > 0)
  1357. {
  1358. ret = RET_SUCCEED;
  1359. DWORD retId = PacketAnalizer::GetPacketIdx(&res);
  1360. PACKET_TYPE tpRes = PacketAnalizer::GetPacketType(&res);
  1361. if ((reqidx == retId) &&
  1362. (tpRes == PACKET_TYPE_RES))
  1363. {
  1364. //check cmd
  1365. if ((PacketAnalizer::GetPacketCmd(&res) == PACKET_CMD_EXE))
  1366. {
  1367. ret = ProcessActionResponse(res, ResParams);
  1368. //UnLock();
  1369. return ret;
  1370. }
  1371. }
  1372. else
  1373. {
  1374. FINFO("{$} What Resp ? [{$}]", m_strClientName, PacketAnalizer::GetPacketKey(&res));
  1375. std::cout << "[INFO] " << m_strClientName << " What Resp ? [" << PacketAnalizer::GetPacketKey(&res) << "]" << std::endl;
  1376. }
  1377. }
  1378. FERROR("Failed={$} : {$} at {$} Action {$} Req: {$} ", (int)ret, m_strClientName, pszDevicePath == nullptr ? m_pFilePath->c_str() : pszDevicePath, pActionName, ReqParams.encode());
  1379. //else
  1380. //{
  1381. // ReOpenDevice();
  1382. //}
  1383. return ret;
  1384. }
  1385. bool LogicClient::IsThreadSafe()
  1386. {
  1387. return true;
  1388. //return (m_OwnerThreadId == GetCurrentThreadId());
  1389. }
  1390. std::shared_ptr<LinuxEvent> LogicClient::GetNotifyHandle()
  1391. {
  1392. return m_NotifyEvent;
  1393. }
  1394. void LogicClient::ClearQueue_Internal()
  1395. {
  1396. //m_pPacketReceivedQue->Lock();
  1397. m_pPacketReceivedQue->Clear();
  1398. m_pPacketWaitQue->Clear();
  1399. m_NotifyEvent->ResetEvent();
  1400. //m_pPacketReceivedQue->UnLock();
  1401. }
  1402. bool LogicClient::DeQueuePacket_Internal(ResDataObject &Packet)
  1403. {
  1404. bool ret = false;
  1405. //m_pPacketReceivedQue->Lock();
  1406. //wait que first
  1407. if (m_pPacketWaitQue->DeQueue(Packet))
  1408. {
  1409. ret = true;
  1410. }
  1411. else if (m_pPacketReceivedQue->DeQueue(Packet))
  1412. {
  1413. ret = true;
  1414. }
  1415. else
  1416. {
  1417. ret = false;
  1418. }
  1419. //set event
  1420. if (m_pPacketWaitQue->size() > 0 || m_pPacketReceivedQue->size() > 0)
  1421. {
  1422. m_NotifyEvent->SetEvent();
  1423. }
  1424. else
  1425. {
  1426. m_NotifyEvent->ResetEvent();
  1427. }
  1428. //m_pPacketReceivedQue->UnLock();
  1429. return ret;
  1430. }
  1431. void LogicClient::CleanupQueue()
  1432. {
  1433. if (Lock(1000) == false)
  1434. {
  1435. //printf("Can't Lock Que for cleanup\n");
  1436. return;
  1437. }
  1438. ClearQueue_Internal();
  1439. UnLock();
  1440. }
  1441. bool LogicClient::IsDataArrived()
  1442. {
  1443. bool ret = false;
  1444. //the packet queue must be encapsulated
  1445. //m_pPacketReceivedQue->Lock();
  1446. if (m_pPacketWaitQue->size() > 0 || m_pPacketReceivedQue->size() > 0)
  1447. {
  1448. FDEBUG("{$} have packet to process ..m_pPacketWaitQue {$} .m_pPacketReceivedQue {$}.", m_strClientName, m_pPacketWaitQue->size(), m_pPacketReceivedQue->size());
  1449. ret = true;
  1450. m_ResponseEvent->SetEvent();
  1451. }
  1452. else
  1453. {
  1454. m_ResponseEvent->ResetEvent();
  1455. }
  1456. //m_pPacketReceivedQue->UnLock();
  1457. //m_pPacketNotifyQue->Lock();
  1458. if (m_pPacketNotifyQue->size() > 0 )
  1459. {
  1460. FDEBUG("{$} have notify to process ..m_pPacketNotifyQue {$} .", m_strClientName, m_pPacketNotifyQue->size());
  1461. ret = true;
  1462. m_NotifyEvent->SetEvent();
  1463. }
  1464. else
  1465. {
  1466. m_NotifyEvent->ResetEvent();
  1467. }
  1468. //m_pPacketNotifyQue->UnLock();
  1469. return ret;
  1470. }
  1471. /*
  1472. * PACKET_CMD CommonLogicClient::ReadCmd(ResDataObject &CmdObject)
  1473. {
  1474. PACKET_CMD ret = PACKET_CMD_NONE;
  1475. while (IsDataArrived())
  1476. {
  1477. ret = LogicClient::ReadCmd(CmdObject);
  1478. if (ret != PACKET_CMD_NONE)
  1479. {
  1480. return ret;
  1481. }
  1482. }
  1483. return ret;
  1484. }
  1485. */
  1486. /// <summary>
  1487. /// 子类CommonLogicClient ReadCMD判断 需要检查逻辑,进行兼容性修改
  1488. /// </summary>
  1489. /// <param name="CmdObject"></param>
  1490. /// <returns></returns>
  1491. PACKET_CMD LogicClient::ReadCmd(ResDataObject &CmdObject)
  1492. {
  1493. PACKET_CMD cmd = PACKET_CMD_NONE;
  1494. //check connection
  1495. if (IsClosed() == true)
  1496. {
  1497. cmd = PACKET_CMD_CLOSE;
  1498. ClearQueue_Internal();
  1499. return cmd;
  1500. }
  1501. if(IsThreadSafe() == false)
  1502. {
  1503. ClearQueue_Internal();
  1504. return cmd;
  1505. }
  1506. if (Lock(100) == false)
  1507. {
  1508. std::cout << "LogicClient::ReadCmd " << m_strClientName << "] Lock timeout Receved Que has [" << m_pPacketReceivedQue->size() << "] Object" << endl;
  1509. return cmd;
  1510. }
  1511. //read receive que second
  1512. RET_STATUS ret = RET_NOSUPPORT;
  1513. PACKET_TYPE rType;
  1514. ResDataObject rMsg;
  1515. string key;
  1516. //read wait que first
  1517. while (DeQueuePacket_Internal(rMsg))
  1518. {
  1519. rType = PacketAnalizer::GetPacketType(&rMsg);
  1520. cmd = PacketAnalizer::GetPacketCmd(&rMsg);
  1521. key = PacketAnalizer::GetPacketKey(&rMsg);
  1522. std::cout << "ReadCmd [" << m_strClientName << "] Type: " << rType << "cmd: " << cmd << " Key: " << key << endl;
  1523. FINFO("{$} ReadCmd Type: {$} cmd: {$} Key: {$} ", m_strClientName, (int)rType, (int)cmd, key);
  1524. if (cmd > PACKET_CMD_NONE && cmd < PACKET_CMD_MAX)
  1525. {
  1526. if (rType == PACKET_TYPE_RES)
  1527. {
  1528. //1.response
  1529. CmdObject = rMsg;
  1530. //[open] need care
  1531. if (cmd == PACKET_CMD_OPEN)
  1532. {
  1533. ret = ProcessOpenResponse(rMsg);
  1534. if (ret >= RET_SUCCEED)
  1535. {
  1536. UnLock();
  1537. return cmd;
  1538. }
  1539. }
  1540. }
  1541. else if (rType == PACKET_TYPE_NOTIFY)
  1542. {
  1543. //2.notify
  1544. UpdateDeviceResource(cmd, rMsg);
  1545. CmdObject = rMsg;
  1546. UnLock();
  1547. return cmd;
  1548. }
  1549. else
  1550. {
  1551. //ignore it
  1552. cmd = PACKET_CMD_NONE;
  1553. }
  1554. }
  1555. rMsg.clear();
  1556. }
  1557. UnLock();
  1558. return cmd;
  1559. }
  1560. PACKET_CMD LogicClient::ReadNotify(ResDataObject& CmdObject)
  1561. {
  1562. CmdObject.clear();
  1563. //m_pPacketNotifyQue->Lock();
  1564. if (m_pPacketNotifyQue->DeQueue(CmdObject))
  1565. {
  1566. //m_pPacketNotifyQue->UnLock();
  1567. return PacketAnalizer::GetPacketCmd(&CmdObject);
  1568. }
  1569. m_NotifyEvent->ResetEvent();
  1570. if(m_pPacketReceivedQue->DeQueue(CmdObject))
  1571. {
  1572. return PacketAnalizer::GetPacketCmd(&CmdObject);
  1573. }
  1574. m_ResponseEvent->ResetEvent();
  1575. //m_pPacketNotifyQue->UnLock();
  1576. return PACKET_CMD_NONE;
  1577. }
  1578. RET_STATUS SYSTEM_CALL LogicClient::WaitForState(const char* state, DWORD timeout)
  1579. {
  1580. PACKET_CMD cmd;
  1581. ResDataObject data;
  1582. ResDataObject context;
  1583. string strKey, value;
  1584. DWORD firstTick = GetTickCount();
  1585. std::shared_ptr<LinuxEvent> notifyhandle = GetNotifyHandle();
  1586. while (true)
  1587. {
  1588. while (IsDataArrived())
  1589. {
  1590. data.clear();
  1591. cmd = ReadCmd(data);
  1592. strKey = PacketAnalizer::GetPacketKey(&data);
  1593. PacketAnalizer::GetPacketContext(&data, context);
  1594. value = (const char *)context;
  1595. if (strKey == "CurrentState")
  1596. {
  1597. if (value == string(state))
  1598. return RET_SUCCEED;
  1599. }
  1600. else if (strKey == string(state))
  1601. {
  1602. return RET_SUCCEED;
  1603. }
  1604. }
  1605. if ((GetTickCount() - firstTick) < timeout)
  1606. {
  1607. if (notifyhandle->Wait(timeout))
  1608. {
  1609. continue;
  1610. }
  1611. }
  1612. break;
  1613. }
  1614. return RET_FAILED;
  1615. }
  1616. RET_STATUS LogicClient::UpdateDeviceResource(int cmdType,ResDataObject &packet)
  1617. {
  1618. RET_STATUS ret = RET_SUCCEED;
  1619. Lock();
  1620. try {
  1621. string strKey = PacketAnalizer::GetPacketKey(&packet);
  1622. ResDataObject ResContext;
  1623. PacketAnalizer::GetPacketContext(&packet, ResContext);
  1624. if (cmdType == PACKET_CMD_UPDATE)
  1625. {
  1626. if (m_DeviceResource[ATTRIBUTE].GetFirstOf(strKey.c_str()) >= 0)
  1627. {
  1628. m_DeviceResource[ATTRIBUTE].update(strKey.c_str(), ResContext);
  1629. }
  1630. }
  1631. else if (cmdType == PACKET_CMD_ADD)
  1632. {
  1633. if (strKey=="ErrorList")
  1634. {
  1635. /*pLogicDeivce->*/GetDeviceResource(&m_DeviceResource);
  1636. }
  1637. else if (m_DeviceResource[ATTRIBUTE].GetFirstOf(strKey.c_str()) < 0)
  1638. {
  1639. m_DeviceResource[ATTRIBUTE].add(strKey.c_str(), ResContext);
  1640. }
  1641. else if (m_DeviceResource[ATTRIBUTE].GetFirstOf(strKey.c_str()) >= 0 &&
  1642. (string)ResContext != "" &&m_DeviceResource[ATTRIBUTE][strKey.c_str()].GetFirstOf(((string)ResContext).c_str()) < 0)
  1643. {
  1644. m_DeviceResource[ATTRIBUTE][strKey.c_str()].add(((string)ResContext).c_str(), "");
  1645. }
  1646. }
  1647. else if (cmdType == PACKET_CMD_DEL)
  1648. {
  1649. if (strKey == "ErrorList")
  1650. {
  1651. /*pLogicDeivce->*/GetDeviceResource(&m_DeviceResource);
  1652. }
  1653. else if (m_DeviceResource[ATTRIBUTE].GetFirstOf(strKey.c_str()) >= 0 )
  1654. {
  1655. if ((string)ResContext != "" && m_DeviceResource[ATTRIBUTE][strKey.c_str()].GetFirstOf(((string)ResContext).c_str()) >= 0)
  1656. {
  1657. m_DeviceResource[ATTRIBUTE][strKey.c_str()].eraseOneOf(((string)ResContext).c_str(), m_DeviceResource[ATTRIBUTE][strKey.c_str()].GetFirstOf(((string)ResContext).c_str()));
  1658. }
  1659. else
  1660. {
  1661. m_DeviceResource[ATTRIBUTE].eraseOneOf(strKey.c_str(), m_DeviceResource[ATTRIBUTE].GetFirstOf(strKey.c_str()));
  1662. }
  1663. }
  1664. }
  1665. }
  1666. catch (...)
  1667. {
  1668. ret = RET_FAILED;
  1669. }
  1670. UnLock();
  1671. return ret;
  1672. }