LogicDevice.cpp 108 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498
  1. // LogicDevice.cpp : 定义 DLL 应用程序的导出函数。
  2. //
  3. #include <cstring>
  4. #include <iostream>
  5. #include <chrono>
  6. #include "LogicDevice.h"
  7. #include <stddef.h> // 用于 offsetof
  8. #include "PacketAnalizer.h"
  9. #include "MessageInfo.h"
  10. #include "common_api.h"
  11. #include "LocalConfig.h"
  12. #include "Base64.h"
  13. #include "SystemLogger.hpp"
  14. #include "mqttclient.h"
  15. #include "LinuxEvent.h"
  16. //Log4CPP::Logger* ////mLog::gLogger = nullptr;
  17. void msgarrivd(void* client, message_data_t* message);
  18. std::string CurrentDateTime();
  19. //-------------Logic Device SysIF--------------------------
  20. LogicDeviceSysIF::LogicDeviceSysIF(void)
  21. {
  22. }
  23. LogicDeviceSysIF::~LogicDeviceSysIF(void)
  24. {
  25. }
  26. //init
  27. void LogicDeviceSysIF::SetLogicDevice(LogicDevice *p)
  28. {
  29. m_pLogicDev = p;
  30. //p->SetSysLogicDevice(this);
  31. };
  32. LogicDevice* LogicDeviceSysIF::GetLogicDevice()
  33. {
  34. return m_pLogicDev;
  35. }
  36. //Command In and Out
  37. //notify from lower layer
  38. RET_STATUS HW_ACTION LogicDeviceSysIF::CmdFromLogicDev(ResDataObject PARAM_IN *pCmd)
  39. {
  40. return RET_FAILED;
  41. };
  42. //notify to lower layer
  43. RET_STATUS SYSTEM_CALL LogicDeviceSysIF::CmdToLogicDev(ResDataObject PARAM_IN *pCmd)
  44. {
  45. if (m_pLogicDev)
  46. {
  47. return m_pLogicDev->CmdToLogicDev(pCmd);
  48. }
  49. return RET_NOSUPPORT;
  50. };
  51. const std::string SERVER_ADDRESS("127.0.0.1");
  52. /*
  53. string DEVICE_ID; //AS CLIENT_ID
  54. //const std::string CLIENT_ID("paho_cpp_async_subcribe");
  55. //const std::string TOPIC("hello");
  56. mqtt::async_client* m_pMqttClient = NULL; //MQTT 对象
  57. const int QOS = 1;
  58. const int N_RETRY_ATTEMPTS = 5;*/
  59. using namespace std;
  60. LogicDevice* g_pDPCDeviceObject = NULL;
  61. string LogHost = "";
  62. //string DEVICE_ID;
  63. //-------------Data Logic Device--------------------------
  64. LogicDevice::LogicDevice(void)
  65. {
  66. m_EvtNotify = LinuxEvent::CreateEvent(LinuxEvent::AUTO_RESET, false);
  67. uuid_t uuid;
  68. char uuid_str[37];
  69. uuid_generate_random(uuid);
  70. uuid_unparse(uuid, uuid_str);
  71. m_pDevInstance = new char[40];
  72. strncpy(m_pDevInstance, uuid_str, 40);
  73. m_pResErrorList = new ResDataObject();
  74. sem_init(&m_SemphRequest, 0, 0);
  75. sem_init(&m_SemphPublish, 0, 0);
  76. m_pDrvDPC = NULL;
  77. g_pDPCDeviceObject = this;
  78. m_pMqttConntion = nullptr;
  79. //m_strServer = "tcp://localhost:1883";
  80. m_strServer = SERVER_ADDRESS;// "192.168.2.225";
  81. m_strServerPort = "1883";
  82. m_bMqttUseSSL = false;
  83. m_strMqttUser = "";
  84. m_strMqttPassword = "";
  85. m_strEBusRoot = "";
  86. m_strCCOSDevicePath = "";
  87. m_pParent = nullptr;
  88. m_topicFilter = nullptr;
  89. m_pPacketReceivedQue = new MsgQueue<ResDataObject>();
  90. m_pPacketSendingQue = new MsgQueue<ResDataObject>();
  91. int x = 0;
  92. for ( x = 0; x < sizeof(szPad); x++)
  93. szPad[x] = 'A' + x % 26;
  94. szPad[x-1] = 0;
  95. memset(szPad2, 0, sizeof(szPad2));
  96. m_dwLastPacket = GetTickCount();
  97. }
  98. LogicDevice::~LogicDevice(void)
  99. {
  100. delete []m_pDevInstance;
  101. delete m_pResErrorList;
  102. sem_destroy(&m_SemphRequest);
  103. sem_destroy(&m_SemphPublish);
  104. //m_EvtNotify = NULL;
  105. delete m_pPacketReceivedQue;
  106. delete m_pPacketSendingQue;
  107. }
  108. void LogicDevice::SetClientRootID(const char* pszEBusRoot, const char* pszCCOSRoot) {
  109. if (m_strClientID.length() > 0)
  110. {
  111. ////mLog::FINFO("Aready set RootID EBUS: [{$}] CCOS : [{$}] result m_strClientID [{$}]", pszEBusRoot, pszCCOSRoot, m_strClientID);
  112. return;
  113. }
  114. ////mLog::FINFO("Set RootID EBUS: [{$}] CCOS : [{$}]", pszEBusRoot, pszCCOSRoot);
  115. if (pszEBusRoot[0] == '/') {
  116. m_strEBusRoot = pszEBusRoot + 1;
  117. }
  118. else {
  119. m_strEBusRoot = pszEBusRoot;
  120. }
  121. char szKeys[256];
  122. strcpy(szKeys, pszEBusRoot);
  123. char* pt = szKeys;
  124. while (*pt != 0)
  125. {
  126. if (*pt == '/' || *pt == '{' || *pt == '}'|| *pt == '-')
  127. *pt = '_';
  128. pt++;
  129. }
  130. m_strClientID = CCOS_CLIENT_ID_PREFIX;
  131. if (szKeys[0] == '_')
  132. m_strClientID += (szKeys + 1);
  133. else
  134. m_strClientID += szKeys;
  135. if (pszCCOSRoot != nullptr)
  136. {
  137. std::cout << "LogicDevice::SetClientRootID [ Set CCOS path is" << pszCCOSRoot << "]" << std::endl;
  138. ////mLog::FINFO("Set CCOS path: {$}", pszCCOSRoot);
  139. m_strCCOSDevicePath = pszCCOSRoot;
  140. int nPos = m_strCCOSDevicePath.find('/');
  141. if (nPos != string::npos)
  142. {
  143. //CCOS/
  144. nPos = m_strCCOSDevicePath.find('/', nPos + 1);
  145. //CCOS/DEVICE/
  146. if (nPos != string::npos)
  147. {
  148. m_strCCOSRoot = m_strCCOSDevicePath.substr(0, nPos);
  149. //CCOS/DEVICE/Generator
  150. nPos = m_strCCOSDevicePath.find('/', nPos + 1);
  151. if (nPos != string::npos)
  152. {
  153. m_strAbstractPath = m_strCCOSDevicePath.substr(0, nPos);
  154. }
  155. }
  156. }
  157. ////mLog::FINFO("Set CCOS path: CCOSROOT {$} AbstractPath {$} ", m_strCCOSRoot, m_strAbstractPath);
  158. }
  159. ////mLog::FINFO("Set MQTT ClientName {$} @CCOSRoot {$}", m_strClientID, m_strCCOSDevicePath);
  160. SetName(m_strClientID.c_str());
  161. OnSetClientID();
  162. }
  163. void LogicDevice::OnSetClientID() {
  164. }
  165. void LogicDevice::SubscribeSelf() {
  166. size_t topicCount = 0;
  167. if (m_strEBusRoot.length() > 0) topicCount++;
  168. if (m_strCCOSDevicePath.length() > 0) topicCount++;
  169. if (m_strAbstractPath.length() > 0) {
  170. topicCount++;
  171. if (m_strDevicePath.length() > 0) topicCount++;
  172. }
  173. if (m_strCCOSRoot.length() > 0) topicCount++;
  174. topicCount += 7 * 3;
  175. m_subscribedTopics.reserve(topicCount);
  176. if (m_strDevicePath.length() > 0 && m_strDevicePath[0] != '/') {
  177. m_strDevicePath = "/" + m_strDevicePath;
  178. }
  179. ////mLog::FINFO("{$} try Subscribe {$} use conn {$} ", m_strClientID, m_strEBusRoot, (UINT64)m_pMqttConntion);
  180. std::cout << "----***** " << m_strClientID << " [" << m_strEBusRoot << "] use conn" << (UINT64)m_pMqttConntion << endl;
  181. if (m_strEBusRoot.length() > 0) {
  182. m_subscribedTopics.push_back(m_strEBusRoot);
  183. SubscribeTopic(m_pMqttConntion, m_subscribedTopics.back().c_str());
  184. }
  185. if (m_strCCOSDevicePath.length() > 0)
  186. {
  187. ////mLog::FINFO("CCOSDevice [{$}] ", m_strCCOSDevicePath + m_strDevicePath);
  188. std::string fullTopic = m_strCCOSDevicePath + m_strDevicePath;
  189. m_subscribedTopics.push_back(fullTopic);
  190. SubscribeTopic(m_pMqttConntion, m_subscribedTopics.back().c_str());
  191. //订阅
  192. }
  193. ////mLog::FINFO("AbstractPath [{$}] ", m_strAbstractPath);
  194. if (m_strAbstractPath.length() > 0)
  195. {
  196. m_subscribedTopics.push_back(m_strAbstractPath);
  197. SubscribeTopic(m_pMqttConntion, m_subscribedTopics.back().c_str());
  198. if (m_strDevicePath.length() > 0)
  199. {
  200. std::string fullAbstractTopic = m_strAbstractPath + m_strDevicePath;
  201. m_subscribedTopics.push_back(fullAbstractTopic);
  202. SubscribeTopic(m_pMqttConntion, m_subscribedTopics.back().c_str());
  203. }
  204. }
  205. ////mLog::FINFO("CCOSRoot [{$}] ", m_strCCOSRoot);
  206. if (m_strCCOSRoot.length() > 0)
  207. {
  208. m_subscribedTopics.push_back(m_strCCOSRoot);
  209. SubscribeTopic(m_pMqttConntion, m_subscribedTopics.back().c_str());
  210. //订阅
  211. }
  212. SubscribeActions();
  213. }
  214. void LogicDevice::SubScribeTopic(const char* pszTopic, bool bSubscribe)
  215. {
  216. if (bSubscribe)
  217. {
  218. m_subscribedTopics.push_back(pszTopic);
  219. SubscribeTopic(m_pMqttConntion, m_subscribedTopics.back().c_str());
  220. }
  221. else
  222. UnSubscribe(m_pMqttConntion, pszTopic);
  223. }
  224. void LogicDevice::NotifyDrvThread()
  225. {
  226. m_EvtNotify->SetEvent();
  227. }
  228. std::shared_ptr<LinuxEvent> LogicDevice::GetEvtHandle()
  229. {
  230. return m_EvtNotify;
  231. }
  232. //1. init part
  233. //void LogicDevice::SetSysLogicDevice(LogicDeviceSysIF *pLogic)
  234. //{
  235. // m_pSysLogic = pLogic;
  236. //}
  237. //void LogicDevice::SetLogHandle(Logger PARAM_IN *pLogger)
  238. //{
  239. // m_pLogger = pLogger;
  240. //}
  241. //
  242. //Logger *LogicDevice::GetLogHandle()
  243. //{
  244. // return m_pLogger;
  245. //}
  246. void LogicDevice::SetDrvDPC(DriverDPC *pDPC)
  247. {
  248. m_pDrvDPC = pDPC;
  249. }
  250. DriverDPC *LogicDevice::GetDrvDPC()
  251. {
  252. return m_pDrvDPC;
  253. }
  254. RET_STATUS LogicDevice::AddEbusChildren(LogicDevice* pChild, const char* szEbusDevPath)
  255. {
  256. if (szEbusDevPath == nullptr)
  257. return RET_FAILED;
  258. for (auto dev : m_subDevices) {
  259. if (dev->GetRootPath() == szEbusDevPath)
  260. return RET_SUCCEED;
  261. }
  262. m_subDevices.push_back(pChild);
  263. return RET_SUCCEED;
  264. }
  265. RET_STATUS LogicDevice::AddCcosChildren(LogicDevice* pChild, const char* szCcosDevPath)
  266. {
  267. if (szCcosDevPath == nullptr)
  268. return RET_FAILED;
  269. for (auto dev : m_subCcosDevices) {
  270. if (dev->GetCcosRootPath() == szCcosDevPath)
  271. return RET_SUCCEED;
  272. }
  273. m_subCcosDevices.push_back(pChild);
  274. return RET_SUCCEED;
  275. }
  276. LogicDevice* LogicDevice::GetEbusChild(const char* szEbusDevPath)
  277. {
  278. for (auto dev : m_subDevices) {
  279. if (dev->GetRootPath() == szEbusDevPath)
  280. return dev;
  281. }
  282. return nullptr;
  283. }
  284. LogicDevice* LogicDevice::GetCcosChild(const char* szCcosDevPath)
  285. {
  286. for (auto dev : m_subCcosDevices) {
  287. if (dev->GetCcosRootPath() == szCcosDevPath)
  288. return dev;
  289. }
  290. return nullptr;
  291. }
  292. void SYSTEM_CALL LogicDevice::CompleteInit()
  293. {
  294. //if (//mLog::gLogger == nullptr)
  295. //{
  296. // string strLogPath = GetProcessDirectory() + R"(\Conf\Log4CPP.Config.xml)";
  297. // LogHost = ((string)getLogRootpath()).c_str();
  298. // if (LogHost.length() <= 1)
  299. // {
  300. // char szName[256];
  301. // sprintf(szName, "/LogicDevice_%08d", GetCurrentProcessId());
  302. // LogHost = szName;
  303. // }
  304. // Log4CPP::ThreadContext::Map::Set(ECOM::Utility::Hash("LogFileName"), "LogicDevice");
  305. // //Log4CPP::GlobalContext::Map::Set("LogHost", LogHost.c_str());
  306. // Log4CPP::ThreadContext::Map::Set(ECOM::Utility::Hash("LogHost"), LogHost.c_str() + 1);
  307. // auto rc = Log4CPP::LogManager::LoadConfigFile(strLogPath.c_str());
  308. // ////mLog::gLogger = Log4CPP::LogManager::GetLogger("LogicDevice");
  309. // ////mLog::FINFO("Code Build datetime [{$} {$}]", __DATE__, __TIME__);
  310. //}
  311. //else
  312. //{
  313. // string strRoot = ((string)getLogRootpath()).c_str();
  314. // if (strRoot.length() > 1 && strRoot != LogHost)
  315. // {
  316. // string strLogPath = GetProcessDirectory() + R"(\Conf\Log4CPP.Config.xml)";
  317. // LogHost = strRoot;
  318. // Log4CPP::ThreadContext::Map::Set(ECOM::Utility::Hash("LogFileName"), "LogicDevice");
  319. // //Log4CPP::GlobalContext::Map::Set("LogHost", LogHost.c_str());
  320. // Log4CPP::ThreadContext::Map::Set(ECOM::Utility::Hash("LogHost"), LogHost.c_str() + 1);
  321. // auto rc = Log4CPP::LogManager::LoadConfigFile(strLogPath.c_str());
  322. // ////mLog::gLogger = Log4CPP::LogManager::GetLogger("LogicDevice");
  323. // }
  324. //}
  325. //string version;
  326. //if (GetVersion(version, hMyModule))
  327. // ////mLog::FINFO("\n===============log begin : version:{$} ===================\n", version.c_str());
  328. //else
  329. ////mLog::FINFO("\n===============log begin : version:1.0.0.0 ===================\n");
  330. ////mLog::FINFO("{$}Connect MQTT Server {$}:{$}", m_strServer, m_strServerPort, m_strClientID);
  331. if (m_strClientID.length() <= 0)
  332. {
  333. ////mLog::FWARN("No Client name ......" );
  334. std::cout << "No Client name ......." << endl;
  335. return;
  336. }
  337. std::cout << "CompleteInit->NewConnection ......." << endl;
  338. m_pMqttConntion = NewConnection(m_strServer.c_str(), m_strServerPort.c_str(), m_strMqttUser.c_str(), m_strMqttPassword.c_str(), m_strClientID.c_str(),
  339. [this](ResDataObject* req, const char* topic, void* conn) {
  340. //这里只处理当前层次设备的请求,下一层的直接靠URI来路由
  341. //首先根据topic判断是请求我的,还是我请求的,请求我的topic 是 以 ROOT开头的URI
  342. // 发送给我的,如果需要应答,则需要调用Request返回Resp,否则直接调用,不返回应答
  343. // 消息处理如果耗时较长,则需要开线程来处理
  344. if (strncmp(topic, m_strEBusRoot.c_str(), m_strEBusRoot.length()) == 0 ||
  345. strncmp(topic, m_strCCOSDevicePath.c_str(), m_strCCOSDevicePath.length()) == 0)
  346. {
  347. //主题以ebus或者ccos开头,给我发的消息,进行处理
  348. ProcessSubscribeRequest(req);
  349. }
  350. else
  351. {
  352. //我主动订阅的外部模块的消息
  353. ProcessSubscribeMsg(req);
  354. }
  355. //CmdToLogicDev(req);
  356. });
  357. if (m_pMqttConntion != nullptr)
  358. {
  359. StartThread(); //启动Request线程
  360. SubscribeSelf();
  361. //DWORD dwThreadID = 0;
  362. //CreateThread(0, 0, Thread_Publish_Thread, this, 0, &dwThreadID);
  363. //////mLog::FINFO("[{$}] Publish Thread id [{$}]", m_strClientID, dwThreadID);
  364. }
  365. }
  366. RET_STATUS LogicDevice::ProcessSubscribeRequest(ResDataObject* req) {
  367. PACKET_TYPE type = PacketAnalizer::GetPacketType(req);
  368. PACKET_CMD cmd = PacketAnalizer::GetPacketCmd(req);
  369. switch (type) {
  370. case PACKET_TYPE_REQ:
  371. PacketAnalizer::GetPacketTransaction(req, m_strCurTransaction);
  372. ProcessRequest(req, cmd);//请求
  373. break;
  374. case PACKET_TYPE_RES:
  375. ProcessResponse(req, cmd);//应答
  376. break;
  377. case PACKET_TYPE_NOTIFY:
  378. ProcessNotify(req, cmd);
  379. //通知
  380. break;
  381. }
  382. return RET_FAILED;
  383. }
  384. RET_STATUS LogicDevice::ProcessSubscribeMsg(ResDataObject* pCmd)
  385. {
  386. ProcessSubscribeRequest(pCmd);
  387. return RET_SUCCEED;
  388. }
  389. RET_STATUS LogicDevice::ProcessRequest(ResDataObject* pCmd, PACKET_CMD cmd)
  390. {
  391. //Open命令
  392. if (cmd == PACKET_CMD_OPEN) {
  393. /* {
  394. "IDX": "40",
  395. "TYPE" : "0",
  396. "CMD" : "0",
  397. "HANDLE" :
  398. {
  399. "ROUTE": "1",
  400. "FLAGS" : "63",
  401. "LANG" : "en-US",
  402. "HANDLEID" : "0",
  403. "OWNERID" :
  404. {
  405. "EBUSID": "ImageSave",
  406. "MACHINEID" : "DESKTOP-FVD53H8",
  407. "PROCID" : "35408",
  408. "ADDR" : "2631366957696"
  409. },
  410. "DEVID":
  411. {
  412. "EBUSID": "ccosChannel",
  413. "MACHINEID" : "",
  414. "PROCID" : "0",
  415. "ADDR" : "0"
  416. }
  417. },
  418. "KEY": "\/ccosChannel"
  419. ResDataObject resRes, resResponse;
  420. ResDataObject resTopic;
  421. PacketAnalizer::GetContextTopic(pCmd, resTopic);
  422. if (cmd == PACKET_CMD_OPEN )
  423. {
  424. //std::cout << "publis " << (const char*)resTopic << "msg body" << resResponse.encode() << endl;
  425. PublishAction(&resResponse, (const char*)resTopic, m_pMqttConntion);
  426. return RET_SUCCEED;
  427. }
  428. if (cmd == PACKET_CMD_CLOSE)
  429. {
  430. //CLOSE 客户端主动断开
  431. }
  432. } */
  433. PacketArrived(pCmd);
  434. return RET_SUCCEED;
  435. }
  436. else if (cmd == PACKET_CMD_CLOSE)
  437. {
  438. ResDataObject resp;
  439. InnerOpenClose(*pCmd, resp, false);
  440. }
  441. else {
  442. PacketArrived(pCmd);
  443. }
  444. return RET_SUCCEED;
  445. }
  446. RET_STATUS LogicDevice::ProcessResponse(ResDataObject* pCmd, PACKET_CMD cmd)
  447. {
  448. return RET_SUCCEED;
  449. }
  450. RET_STATUS LogicDevice::ProcessNotify(ResDataObject* pCmd, PACKET_CMD cmd)
  451. {
  452. PacketArrived(pCmd);
  453. return RET_SUCCEED;
  454. }
  455. void LogicDevice::PacketArrived(ResDataObject* pRequest)
  456. {
  457. //m_pPacketReceivedQue->Lock();
  458. ////mLog::FINFO("PacketArrived msg [id: {$} ]: cmd {$} key: [{$}]", m_strClientID, (int)PacketAnalizer::GetPacketCmd(pRequest), PacketAnalizer::GetPacketKey(pRequest));
  459. //if (Thread_Lock(5000) != WAIT_OBJECT_0)
  460. //{
  461. // ////mLog::FERROR("PacketArrived Lock Timeout for msg [id: {$} ]: cmd {$} key: ", m_strClientID, (int)PacketAnalizer::GetPacketCmd(pRequest), PacketAnalizer::GetPacketKey(pRequest));
  462. // //GPRINTA_ERROR("OpenDev Lock Timeout for Dev[flag:%d]:%s", flags, pPath);
  463. // return ;
  464. //}
  465. m_pPacketReceivedQue->InQueue(*pRequest);
  466. ////mLog::FINFO("PacketArrived msg INTO QUEUE [id: {$} ]: cmd {$} key: [{$}]", m_strClientID, (int)PacketAnalizer::GetPacketCmd(pRequest), PacketAnalizer::GetPacketKey(pRequest));
  467. //SetEvent(m_EvtNotify);//notify to user
  468. long nLast = 0;
  469. int released = sem_post(&m_SemphRequest); // 释放信号量,通知等待的线程
  470. if (released <= 0)
  471. {
  472. ////mLog::FERROR("PacketArrived ReleaseSemaphore failed {$} ", GetLastError());
  473. }
  474. //Thread_UnLock();
  475. //m_pPacketReceivedQue->UnLock();
  476. }
  477. bool LogicDevice::OnStartThread()
  478. {
  479. return true;
  480. }
  481. bool LogicDevice::OnEndThread()
  482. {
  483. return true;
  484. }
  485. //单一发送线程,暂时未用
  486. DWORD LogicDevice::Thread_Publish_Thread(void* pPara)
  487. {
  488. INT ret = 0;
  489. int waitevent = 0;
  490. LogicDevice* handle = (LogicDevice*)pPara;
  491. //prev work usleep(30000);
  492. ////mLog::FINFO("Thread Start [{$}]", handle->m_strClientID);
  493. while (!handle->m_ExitFlag->Wait(1))
  494. {
  495. //do work
  496. ResDataObject resSend;
  497. DWORD wait = handle->m_pPacketSendingQue->WaitForInQue(100);
  498. if (wait != WAIT_OBJECT_0)
  499. continue;
  500. bool bHasPacket = handle->m_pPacketSendingQue->DeQueue(resSend);
  501. if (bHasPacket)
  502. {
  503. PACKET_CMD cmd = PacketAnalizer::GetPacketCmd(&resSend);
  504. PACKET_TYPE type = PacketAnalizer::GetPacketType(&resSend);
  505. ////mLog::FINFO(" [{$}] Publish key [{$}] type [{$}] cmd [{$}] ", handle->m_strClientID, PacketAnalizer::GetPacketKey(&resSend), (int)type, (int)cmd);
  506. if (PACKET_CMD_NONE == cmd)
  507. {
  508. ////mLog::FDEBUG(" [{$}] Publish what packet {$} ", handle->m_strClientID, resSend.encode());
  509. }
  510. if (type == PACKET_TYPE_NOTIFY)
  511. {
  512. CcosDevFileHandle* pHandle = new CcosDevFileHandle;
  513. PacketAnalizer::UpdateNotifyHandle(resSend, *pHandle);
  514. ////mLog::FINFO("Notify Transaction: {$}", handle->m_strCurTransaction);
  515. PacketAnalizer::UpdatePacketTransaction(resSend, handle->m_strCurTransaction);
  516. PacketAnalizer::UpdateDeviceNotifyResponse(resSend, getLocalMachineId(), getLocalEbusId(), (UINT64)pthread_self(), (UINT64)handle->m_pMqttConntion);
  517. ////mLog::FDEBUG("Notify: {$}", resSend.encode());
  518. //printf("--> %s \n", pCmd->encode());
  519. PublishAction(&resSend, (handle->m_strEBusRoot + "/Notify").c_str(), handle->m_pMqttConntion);
  520. PublishAction(&resSend, (handle->m_strCCOSRoot + "/Notify/" + PacketAnalizer::GetPacketKey(&resSend)).c_str(), handle->m_pMqttConntion);
  521. delete pHandle;
  522. }
  523. else
  524. {
  525. ResDataObject resTopic;
  526. PacketAnalizer::GetPacketTopic(&resSend, resTopic);
  527. //PacketAnalizer::GetPacketTopicGetPacketTopic
  528. //PacketAnalizer::UpdatePacketTopic(&resResponse, resTopic);
  529. ////mLog::FINFO(" [{$}] Publish [{$}] type [{$}] cmd [{$}] to [{$}]", handle->m_strClientID, PacketAnalizer::GetPacketKey(&resSend), (int)type, (int)cmd, (const char*)resTopic);
  530. PublishAction(&resSend, (const char*)resTopic, handle->m_pMqttConntion);
  531. }
  532. }
  533. }
  534. return 0;
  535. }
  536. RET_STATUS LogicDevice::DevOpen(const char* pszDevUri, const char* pszGroup, ResDataObject& resRespons)
  537. {
  538. cout << "LogicDevice::DevOpen - Entering. pszDevUri: " << (pszDevUri ? pszDevUri : "nullptr")
  539. << ", pszGroup: " << (pszGroup ? pszGroup : "nullptr") << endl;
  540. ResDataObject req, reqParam;
  541. reqParam = pszGroup;
  542. cout << "LogicDevice::DevOpen - Creating OPEN request. Command: PACKET_CMD_OPEN" << endl;
  543. PacketAnalizer::MakeRequest(req, pszDevUri, PACKET_CMD_OPEN, &reqParam);
  544. RET_STATUS ret = InnerOpenClose(req, resRespons, true);
  545. cout << "LogicDevice::DevOpen - InnerOpenClose returned: " << ret << endl;
  546. return ret;
  547. }
  548. RET_STATUS LogicDevice::DevClose(const char* pszDevUri, const char* pszGroup, ResDataObject& resRespons)
  549. {
  550. cout << "LogicDevice::DevClose - Entering. pszDevUri: " << (pszDevUri ? pszDevUri : "nullptr")
  551. << ", pszGroup: " << (pszGroup ? pszGroup : "nullptr") << endl;
  552. ResDataObject req, reqParam;
  553. reqParam = pszGroup;
  554. cout << "LogicDevice::DevClose - Creating CLOSE request. Command: PACKET_CMD_CLOSE" << endl;
  555. PacketAnalizer::MakeRequest(req, pszDevUri, PACKET_CMD_CLOSE, &reqParam);
  556. RET_STATUS ret = InnerOpenClose(req, resRespons, false);
  557. cout << "LogicDevice::DevClose - InnerOpenClose returned: " << ret << endl;
  558. return ret;
  559. }
  560. /// <summary>
  561. /// Get device property
  562. /// </summary>
  563. RET_STATUS LogicDevice::DevGet(const char* pszDevUri, const char* pszProperty, ResDataObject& resRespons)
  564. {
  565. cout << "LogicDevice::DevGet - Entering. pszDevUri: " << (pszDevUri ? pszDevUri : "nullptr")
  566. << ", pszProperty: " << (pszProperty ? pszProperty : "nullptr") << endl;
  567. ResDataObject req, reqParam;
  568. cout << "LogicDevice::DevGet - Creating GET request. Command: PACKET_CMD_GET, Property: " << (pszProperty ? pszProperty : "nullptr") << endl;
  569. PacketAnalizer::MakeRequest(req, pszProperty, PACKET_CMD_GET, &reqParam);
  570. RET_STATUS ret = Request(&req, &resRespons);
  571. cout << "LogicDevice::DevGet - Request returned: " << ret << endl;
  572. return ret;
  573. }
  574. /// <summary>
  575. /// Set device property
  576. /// </summary>
  577. RET_STATUS LogicDevice::DevSet(const char* pszDevUri, const char* pszProperty, const char* pszValueSet, ResDataObject& resRespons)
  578. {
  579. cout << "LogicDevice::DevSet - Entering. pszDevUri: " << (pszDevUri ? pszDevUri : "nullptr")
  580. << ", pszProperty: " << (pszProperty ? pszProperty : "nullptr")
  581. << ", pszValueSet: " << (pszValueSet ? pszValueSet : "nullptr") << endl;
  582. ResDataObject req, reqParam;
  583. if (pszValueSet != nullptr && pszValueSet[0] != 0) {
  584. if (pszValueSet[0] == '{') {
  585. cout << "LogicDevice::DevSet - Decoding JSON value for property" << endl;
  586. reqParam.decode(pszValueSet);
  587. }
  588. else {
  589. cout << "LogicDevice::DevSet - Using raw value for property" << endl;
  590. reqParam = pszValueSet;
  591. }
  592. }
  593. else {
  594. cout << "LogicDevice::DevSet - No value provided for property" << endl;
  595. }
  596. cout << "LogicDevice::DevSet - Creating SET request. Command: PACKET_CMD_SET, Property: " << (pszProperty ? pszProperty : "nullptr") << endl;
  597. PacketAnalizer::MakeRequest(req, pszProperty, PACKET_CMD_SET, &reqParam);
  598. RET_STATUS ret = Request(&req, &resRespons);
  599. cout << "LogicDevice::DevSet - Request returned: " << ret << endl;
  600. return ret;
  601. }
  602. /// <summary>
  603. /// Update device property
  604. /// </summary>
  605. RET_STATUS LogicDevice::DevUpdate(const char* pszDevUri, const char* pszProperty, const char* pszValueUpdate, ResDataObject& resRespons)
  606. {
  607. cout << "LogicDevice::DevUpdate - Entering. pszDevUri: " << (pszDevUri ? pszDevUri : "nullptr")
  608. << ", pszProperty: " << (pszProperty ? pszProperty : "nullptr")
  609. << ", pszValueUpdate: " << (pszValueUpdate ? pszValueUpdate : "nullptr") << endl;
  610. ResDataObject req, reqParam;
  611. if (pszValueUpdate != nullptr && pszValueUpdate[0] != 0) {
  612. if (pszValueUpdate[0] == '{') {
  613. cout << "LogicDevice::DevUpdate - Decoding JSON value for update" << endl;
  614. reqParam.decode(pszValueUpdate);
  615. }
  616. else {
  617. cout << "LogicDevice::DevUpdate - Using raw value for update" << endl;
  618. reqParam = pszValueUpdate;
  619. }
  620. }
  621. else {
  622. cout << "LogicDevice::DevUpdate - No update value provided" << endl;
  623. }
  624. cout << "LogicDevice::DevUpdate - Creating UPDATE request. Command: PACKET_CMD_UPDATE, Property: " << (pszProperty ? pszProperty : "nullptr") << endl;
  625. PacketAnalizer::MakeRequest(req, pszProperty, PACKET_CMD_UPDATE, &reqParam);
  626. RET_STATUS ret = Request(&req, &resRespons);
  627. cout << "LogicDevice::DevUpdate - Request returned: " << ret << endl;
  628. return ret;
  629. }
  630. /// <summary>
  631. /// Add device property
  632. /// </summary>
  633. RET_STATUS LogicDevice::DevAdd(const char* pszDevUri, const char* pszProperty, const char* pszValueAdd, ResDataObject& resRespons)
  634. {
  635. cout << "LogicDevice::DevAdd - Entering. pszDevUri: " << (pszDevUri ? pszDevUri : "nullptr")
  636. << ", pszProperty: " << (pszProperty ? pszProperty : "nullptr")
  637. << ", pszValueAdd: " << (pszValueAdd ? pszValueAdd : "nullptr") << endl;
  638. ResDataObject req, reqParam;
  639. if (pszValueAdd != nullptr && pszValueAdd[0] != 0) {
  640. if (pszValueAdd[0] == '{') {
  641. cout << "LogicDevice::DevAdd - Decoding JSON value for addition" << endl;
  642. reqParam.decode(pszValueAdd);
  643. }
  644. else {
  645. cout << "LogicDevice::DevAdd - Using raw value for addition" << endl;
  646. reqParam = pszValueAdd;
  647. }
  648. }
  649. else {
  650. cout << "LogicDevice::DevAdd - No value provided for addition" << endl;
  651. }
  652. cout << "LogicDevice::DevAdd - Creating ADD request. Command: PACKET_CMD_ADD, Property: " << (pszProperty ? pszProperty : "nullptr") << endl;
  653. PacketAnalizer::MakeRequest(req, pszProperty, PACKET_CMD_ADD, &reqParam);
  654. RET_STATUS ret = Request(&req, &resRespons);
  655. cout << "LogicDevice::DevAdd - Request returned: " << ret << endl;
  656. return ret;
  657. }
  658. /// <summary>
  659. /// Delete device property
  660. /// </summary>
  661. RET_STATUS LogicDevice::DevDel(const char* pszDevUri, const char* pszProperty, const char* pszValueDel, ResDataObject& resRespons)
  662. {
  663. cout << "LogicDevice::DevDel - Entering. pszDevUri: " << (pszDevUri ? pszDevUri : "nullptr")
  664. << ", pszProperty: " << (pszProperty ? pszProperty : "nullptr")
  665. << ", pszValueDel: " << (pszValueDel ? pszValueDel : "nullptr") << endl;
  666. ResDataObject req, reqParam;
  667. if (pszValueDel != nullptr && pszValueDel[0] != 0) {
  668. if (pszValueDel[0] == '{') {
  669. cout << "LogicDevice::DevDel - Decoding JSON value for deletion" << endl;
  670. reqParam.decode(pszValueDel);
  671. }
  672. else {
  673. cout << "LogicDevice::DevDel - Using raw value for deletion" << endl;
  674. reqParam = pszValueDel;
  675. }
  676. }
  677. else {
  678. cout << "LogicDevice::DevDel - No value provided for deletion" << endl;
  679. }
  680. cout << "LogicDevice::DevDel - Creating DEL request. Command: PACKET_CMD_DEL, Property: " << (pszProperty ? pszProperty : "nullptr") << endl;
  681. PacketAnalizer::MakeRequest(req, pszProperty, PACKET_CMD_DEL, &reqParam);
  682. RET_STATUS ret = Request(&req, &resRespons);
  683. cout << "LogicDevice::DevDel - Request returned: " << ret << endl;
  684. return ret;
  685. }
  686. /// <summary>
  687. /// Execute device action
  688. /// </summary>
  689. RET_STATUS LogicDevice::DevAction(const char* pszDevUri, const char* pszActionName, const char* pszParams, ResDataObject& resRespons)
  690. {
  691. cout << "LogicDevice::DevAction - Entering. pszDevUri: " << (pszDevUri ? pszDevUri : "nullptr")
  692. << ", pszActionName: " << (pszActionName ? pszActionName : "nullptr")
  693. << ", pszParams: " << (pszParams ? pszParams : "nullptr") << endl;
  694. ResDataObject req, reqParam;
  695. if (pszParams != nullptr && pszParams[0] != 0) {
  696. if (pszParams[0] == '{') {
  697. cout << "LogicDevice::DevAction - Decoding JSON parameters for action" << endl;
  698. reqParam.decode(pszParams);
  699. }
  700. else {
  701. cout << "LogicDevice::DevAction - Using raw parameters for action" << endl;
  702. reqParam = pszParams;
  703. }
  704. }
  705. else {
  706. cout << "LogicDevice::DevAction - No parameters provided for action" << endl;
  707. }
  708. cout << "LogicDevice::DevAction - Creating EXE request. Command: PACKET_CMD_EXE, Action: " << (pszActionName ? pszActionName : "nullptr") << endl;
  709. PacketAnalizer::MakeRequest(req, pszActionName, PACKET_CMD_EXE, &reqParam);
  710. ResDataObject resResult;
  711. RET_STATUS ret = Request(&req, &resResult);
  712. cout << "LogicDevice::DevAction - Request returned: " << ret << endl;
  713. PacketAnalizer::GetPacketContext(&resResult, resRespons);
  714. cout << "LogicDevice::DevAction - Extracted packet context to response" << endl;
  715. return ret;
  716. }
  717. /// <summary>
  718. /// Send message to device
  719. /// </summary>
  720. RET_STATUS LogicDevice::DevMessage(const char* pszDevUri, const char* pszTopic, const char* pszMessageValue, ResDataObject& resRespons)
  721. {
  722. cout << "LogicDevice::DevMessage - Entering. pszDevUri: " << (pszDevUri ? pszDevUri : "nullptr")
  723. << ", pszTopic: " << (pszTopic ? pszTopic : "nullptr")
  724. << ", pszMessageValue: " << (pszMessageValue ? pszMessageValue : "nullptr") << endl;
  725. ResDataObject req, reqParam;
  726. if (pszMessageValue != nullptr && pszMessageValue[0] != 0) {
  727. if (pszMessageValue[0] == '{') {
  728. cout << "LogicDevice::DevMessage - Decoding JSON message value" << endl;
  729. reqParam.decode(pszMessageValue);
  730. }
  731. else {
  732. cout << "LogicDevice::DevMessage - Using raw message value" << endl;
  733. reqParam = pszMessageValue;
  734. }
  735. }
  736. else {
  737. cout << "LogicDevice::DevMessage - No message value provided" << endl;
  738. }
  739. cout << "LogicDevice::DevMessage - Creating MSG request. Command: PACKET_CMD_MSG, Topic: " << (pszTopic ? pszTopic : "nullptr") << endl;
  740. PacketAnalizer::MakeRequest(req, pszTopic, PACKET_CMD_MSG, &reqParam);
  741. RET_STATUS ret = Request(&req, &resRespons);
  742. cout << "LogicDevice::DevMessage - Request returned: " << ret << endl;
  743. return ret;
  744. }
  745. RET_STATUS LogicDevice::InnerOpenClose(ResDataObject& req, ResDataObject& resp, bool openOrClose)
  746. {
  747. if (openOrClose)
  748. {
  749. ResDataObject resContext;
  750. GetDeviceResource(&resp);
  751. LogicDevice::GetDeviceResource(&resp);
  752. PacketAnalizer::GetPacketTransaction(&req, m_strCurTransaction);
  753. if (PacketAnalizer::GetPacketContext(&req, resContext))
  754. {
  755. //如果有上线参数
  756. if (resContext.GetFirstOf("Online") >= 0)
  757. {
  758. ////mLog::FINFO("Got Online Request {$}", resContext.encode());
  759. int idx = resContext.GetFirstOf("Online");
  760. //如果有上线参数
  761. if (idx >= 0)
  762. {
  763. do
  764. {
  765. string wsName = resContext[idx].encode();
  766. ////mLog::FINFO("SubscribeGroupActions [{$}] ", wsName);
  767. SubscribeGroupActions(wsName, true);
  768. idx = resContext.GetNextOf("Online", idx);
  769. } while (idx >= 0);
  770. }
  771. resp.update("Online", m_rsOnlineGroup);
  772. }
  773. }
  774. }
  775. else
  776. {
  777. ResDataObject context;
  778. if (PacketAnalizer::GetPacketContext(&req, context))
  779. {
  780. int idx = context.GetFirstOf("Offline");
  781. //如果有上线参数
  782. if (idx >= 0)
  783. {
  784. do
  785. {
  786. string wsName = context[idx].encode();
  787. SubscribeGroupActions(wsName, false);
  788. idx = context.GetNextOf("Offline", idx);
  789. } while (idx >= 0);
  790. }
  791. resp.update("Online", m_rsOnlineGroup);
  792. }
  793. }
  794. return RET_SUCCEED;
  795. }
  796. bool LogicDevice::Exec(void)
  797. {
  798. struct timespec ts;
  799. clock_gettime(CLOCK_REALTIME, &ts);
  800. ts.tv_sec += 3;
  801. // 等待退出信号(3秒超时)
  802. DWORD dwRet = 0;
  803. dwRet = m_ExitFlag->Wait(3);
  804. if (dwRet == WAIT_OBJECT_0)
  805. {
  806. return false;
  807. }
  808. // 等待请求信号(3秒超时)
  809. int ret = sem_timedwait(&m_SemphRequest, &ts);
  810. if (ret == 0) {
  811. ////mLog::FDEBUG("[{$}] Got Packet Event ", m_strClientID);
  812. ResDataObject req;
  813. bool got = true;
  814. do {
  815. got = m_pPacketReceivedQue->DeQueue(req);
  816. if (got) {
  817. m_dwLastPacket = GetTickCount();
  818. PACKET_CMD cmd = PacketAnalizer::GetPacketCmd(&req);
  819. std::string keystr = PacketAnalizer::GetPacketKey(&req);
  820. ////mLog::FINFO(" {$} Got Request key {$} transaction {$}",
  821. // m_strClientID, keystr, m_strCurTransaction);
  822. if (cmd == PACKET_CMD_OPEN) {
  823. ResDataObject resRes, resResponse;
  824. InnerOpenClose(req, resRes, true);
  825. PacketAnalizer::MakeOpenResponse(req, resResponse, resRes);
  826. resResponse.update("Online", m_rsOnlineGroup);
  827. PacketAnalizer::UpdatePacketTransaction(resResponse, m_strCurTransaction);
  828. ResDataObject resTopic;
  829. PacketAnalizer::GetContextTopic(&req, resTopic);
  830. PacketAnalizer::UpdatePacketTopic(&resResponse, resTopic, m_strClientID.c_str());
  831. if (keystr.substr(0, 4) == "CCOS") {
  832. PacketAnalizer::UpdatePacketKey(&resResponse, m_strCCOSDevicePath.c_str());
  833. }
  834. else {
  835. PacketAnalizer::UpdateDeviceNotifyResponse(resResponse,
  836. getLocalMachineId(),
  837. getLocalEbusId(),
  838. (uint64_t)getpid(),
  839. (uint64_t)m_pMqttConntion);
  840. }
  841. PublishAction(&resResponse, (const char*)resTopic, m_pMqttConntion);
  842. // 发送连接状态通知
  843. ResDataObject NotifyData;
  844. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_UPDATE,
  845. "ConnectionStatus", "1");
  846. PacketAnalizer::UpdatePacketTransaction(NotifyData, m_strCurTransaction);
  847. CmdFromLogicDev(&NotifyData);
  848. }
  849. else {
  850. PacketAnalizer::GetPacketTransaction(&req, m_strCurTransaction);
  851. ResDataObject resPacket;
  852. RET_STATUS retStatus = RET_FAILED;
  853. if (cmd == PACKET_CMD_EXE && keystr == "UpdateDeviceResource") {
  854. ResDataObject devRes;
  855. if ((retStatus = GetDeviceResource(&devRes)) == RET_SUCCEED) {
  856. LogicDevice::GetDeviceResource(&devRes);
  857. PacketAnalizer::UpdatePacketContext(resPacket, devRes);
  858. }
  859. }
  860. else {
  861. retStatus = Request(&req, &resPacket);
  862. }
  863. PacketAnalizer::MakeRetCode(retStatus, &resPacket);
  864. PacketAnalizer::CloneTransaction(&req, &resPacket);
  865. ResDataObject resTopic;
  866. PacketAnalizer::GetContextTopic(&req, resTopic);
  867. PacketAnalizer::UpdatePacketTopic(&resPacket, resTopic, m_strClientID.c_str());
  868. PublishAction(&resPacket, (const char*)resTopic, m_pMqttConntion);
  869. }
  870. }
  871. } while (got);
  872. // 检查心跳(10分钟无数据发送心跳)
  873. if (GetTickCount() - m_dwLastPacket > 600000) {
  874. m_dwLastPacket = GetTickCount();
  875. ResDataObject heartBeat;
  876. PacketAnalizer::MakeNotify(heartBeat, PACKET_CMD_ONLINE,
  877. "HeartBeat", m_strClientID.c_str());
  878. PublishAction(&heartBeat, "CCOS/DEVICE/HeartBeat", m_pMqttConntion);
  879. }
  880. return true;
  881. }
  882. // 检查心跳(即使没有请求)
  883. if (GetTickCount() - m_dwLastPacket > 600000) {
  884. m_dwLastPacket = GetTickCount();
  885. ResDataObject heartBeat;
  886. PacketAnalizer::MakeNotify(heartBeat, PACKET_CMD_ONLINE,
  887. "HeartBeat", m_strClientID.c_str());
  888. PublishAction(&heartBeat, "CCOS/DEVICE/HeartBeat", m_pMqttConntion);
  889. }
  890. return true;
  891. }
  892. void SYSTEM_CALL LogicDevice::CompleteUnInit()
  893. {
  894. StopThread();
  895. }
  896. int LogicDevice::GetDevice_Thread_Priority()
  897. {
  898. return THREAD_PRIORITY_NONE;
  899. }
  900. RET_STATUS LogicDevice::GetDeviceResource(ResDataObject PARAM_OUT *pDeviceResource)
  901. {
  902. //pDeviceResource->update("ClientType", DPC_UnitClient);
  903. GUID guid;
  904. string name;
  905. GetDeviceType(guid);
  906. guid_2_string(guid, name);
  907. pDeviceResource->update("DeviceType", name.c_str());
  908. //Get Unit Type (Unit GUID)
  909. if (pDeviceResource->GetFirstOf("LogicDevInstance")<0)
  910. {
  911. pDeviceResource->add("LogicDevInstance", m_pDevInstance);
  912. }
  913. ////
  914. size_t idx = (*pDeviceResource)["Attribute"].size();
  915. if (idx > 0)
  916. {
  917. int erroridx = (*pDeviceResource)["Attribute"].GetFirstOf("ErrorList");
  918. if (erroridx < 0)
  919. {
  920. (*pDeviceResource)["Attribute"].add("ErrorList", *m_pResErrorList);
  921. }
  922. else
  923. {
  924. (*pDeviceResource)["Attribute"]["ErrorList"] = *m_pResErrorList;
  925. }
  926. }
  927. else
  928. {
  929. ResDataObject Attribute;
  930. Attribute.add("ErrorList", *m_pResErrorList);
  931. pDeviceResource->add("Attribute", Attribute);
  932. }
  933. // (*pDeviceResource)["Action"].size();
  934. if (pDeviceResource->GetFirstOf("Action") < 0)
  935. {
  936. pDeviceResource->add("Action", m_Actions);
  937. }
  938. return RET_SUCCEED;
  939. }
  940. //notify from lower layer
  941. RET_STATUS LogicDevice::CmdFromLogicDev(ResDataObject *pCmd)
  942. {
  943. PACKET_CMD cmd = PacketAnalizer::GetPacketCmd(pCmd);
  944. PACKET_TYPE type = PacketAnalizer::GetPacketType(pCmd);
  945. if (type == PACKET_TYPE_NOTIFY)
  946. {
  947. CcosDevFileHandle* pHandle = new CcosDevFileHandle;
  948. PacketAnalizer::UpdateNotifyHandle(*pCmd, *pHandle);
  949. ////mLog::FDEBUG("Notify Transaction: {$}", m_strCurTransaction);
  950. PacketAnalizer::UpdatePacketTransaction(*pCmd, m_strCurTransaction);
  951. ;
  952. //if (m_strEBusRoot.length() <= 0)
  953. //{
  954. // //////mLog::FWARN("EBusRoot is null");
  955. //}
  956. PacketAnalizer::UpdateDeviceNotifyResponse(
  957. *pCmd,
  958. getLocalMachineId(),
  959. getLocalEbusId(),
  960. static_cast<uint64_t>(getpid()), // Linux 上获取进程 ID
  961. reinterpret_cast<uint64_t>(m_pMqttConntion) // 假设 m_pMqttConntion 在 Linux 上是指针类型
  962. );
  963. ////mLog::FDEBUG("[{$}] Notify: {$}", m_strClientID, pCmd->encode());
  964. //printf("--> %s \n", pCmd->encode());
  965. PacketAnalizer::UpdatePacketTopic(pCmd, (m_strEBusRoot + "/Notify").c_str(), m_strClientID.c_str());
  966. PublishAction(pCmd, (m_strEBusRoot + "/Notify").c_str(), m_pMqttConntion);
  967. string strNotifyPath = "/Notify/" + PacketAnalizer::GetPacketKey(pCmd);
  968. PacketAnalizer::UpdatePacketTopic(pCmd, (m_strCCOSRoot + strNotifyPath).c_str(), m_strClientID.c_str());
  969. PublishAction(pCmd, (m_strCCOSDevicePath + strNotifyPath).c_str(), m_pMqttConntion);
  970. if (m_strAbstractPath.length() > 0)
  971. {
  972. PublishAction(pCmd, (m_strAbstractPath + strNotifyPath).c_str(), m_pMqttConntion);
  973. string realPath,devPath;
  974. devPath = m_strAbstractPath.substr(((string)"CCOS/DEVICE").length());
  975. for (int x = 0; x < m_rsOnlineGroup.size(); x++)
  976. {
  977. if ((int)m_rsOnlineGroup[x] == 1)
  978. {
  979. realPath = "CCOS/" +(string)m_rsOnlineGroup.GetKey(x) + devPath + strNotifyPath;
  980. PublishAction(pCmd, realPath.c_str(), m_pMqttConntion);
  981. }
  982. }
  983. } //m_pPacketSendingQue->InQueue(*pCmd);
  984. delete pHandle;
  985. }
  986. return RET_SUCCEED;
  987. /*
  988. if (pCmd && m_pSysLogic)
  989. {
  990. return m_pSysLogic->CmdFromLogicDev(pCmd);
  991. }
  992. //put log here
  993. return RET_FAILED;*/
  994. }
  995. std::wstring mb2wc_a(const char* mbstr)
  996. {
  997. std::wstring strVal;
  998. // 获取输入字符串的长度
  999. size_t mbstr_len = strlen(mbstr);
  1000. // 计算转换后宽字符字符串的长度
  1001. size_t size = mbstr_len + 1; // 需要多一个字符来存储结尾的 '\0'
  1002. wchar_t* wcstr = new wchar_t[size];
  1003. if (wcstr)
  1004. {
  1005. memset(wcstr, 0, size * sizeof(wchar_t));
  1006. // mbsrtowcs 返回转换后的字符数
  1007. size_t ret = mbsrtowcs(wcstr, &mbstr, size, nullptr);
  1008. if (ret != (size_t)-1) // mbsrtowcs 返回 (size_t)-1 表示错误
  1009. {
  1010. strVal = wcstr;
  1011. }
  1012. delete[] wcstr;
  1013. }
  1014. return strVal;
  1015. }
  1016. RET_STATUS HW_ACTION LogicDevice::AddErrorMessageUnicode(const char* DevInstance, const char* Code, int &Level, const wchar_t* ResInfo, const wchar_t* Description, int nMessageType)
  1017. {
  1018. string ResBase64, DesBase64;
  1019. wstring wResUTF = ResInfo;
  1020. wstring wDesUTF = Description;
  1021. CBase64::Encode((const unsigned char *)wResUTF.c_str(), (unsigned long)wResUTF.size() * sizeof(wchar_t), ResBase64);
  1022. CBase64::Encode((const unsigned char *)wDesUTF.c_str(), (unsigned long)wDesUTF.size() * sizeof(wchar_t), DesBase64);
  1023. return AddErrorMessage(DevInstance, Code, Level, ResBase64.c_str(), DesBase64.c_str(), nMessageType);
  1024. }
  1025. RET_STATUS HW_ACTION LogicDevice::AddErrorMessage(const char* DevInstance, const char* Code, int &Level, const char* ResInfo, const char* Description, int nMessageType, const char* pAppId)
  1026. {
  1027. string ResBase64,DesBase64;
  1028. wstring wResUTF = mb2wc_a(ResInfo);
  1029. wstring wDesUTF = mb2wc_a(Description);
  1030. CBase64::Encode((const unsigned char *)wResUTF.c_str(), (unsigned long)wResUTF.size() * sizeof(wchar_t), ResBase64);
  1031. CBase64::Encode((const unsigned char *)wDesUTF.c_str(), (unsigned long)wDesUTF.size() * sizeof(wchar_t), DesBase64);
  1032. return AddErrorMessageBase(DevInstance, Code, Level, ResBase64.c_str(), DesBase64.c_str(), nMessageType, pAppId);
  1033. }
  1034. RET_STATUS LogicDevice::AddErrorMessageBase(const char* DevInstance, const char* Code, int &Level, const char* ResInfo, const char* Description, int nMessageType, const char* pAppId)
  1035. {
  1036. //int ret = 1;
  1037. if (Code == 0 || (string)ResInfo == "")
  1038. {
  1039. ////mLog::FERROR("Code or ResInfo is empty");
  1040. return RET_FAILED;
  1041. }
  1042. MessageInfo info;
  1043. info.CodeID = Code;
  1044. info.Type = nMessageType;
  1045. info.Level = Level;
  1046. info.Resouceinfo = ResInfo;
  1047. info.Description = Description;
  1048. string strDevInstanceCode = DevInstance;
  1049. strDevInstanceCode += Code;
  1050. for (size_t i = 0; i < m_pResErrorList->size(); i++)
  1051. {
  1052. string strInstancekey = m_pResErrorList->GetKey(i);
  1053. if (strInstancekey == strDevInstanceCode)
  1054. {
  1055. //for (size_t j = 0; j < (*m_pResErrorList)[DevInstance].size(); j++)
  1056. //{
  1057. // string strCodekey = (*m_pResErrorList)[DevInstance].GetKey(j);
  1058. // string strtype = (*m_pResErrorList)[DevInstance][strCodekey.c_str()]["Type"];
  1059. // if (strCodekey == (string)Code && atoi(strtype.c_str()) == nMessageType)
  1060. // {
  1061. //ret = 0;
  1062. ////mLog::FWARN("Same Code:%s with MessageType:%d already Exist", Code,nMessageType);
  1063. return RET_SUCCEED;
  1064. // }
  1065. //}
  1066. //ret = 2;
  1067. //break;
  1068. }
  1069. }
  1070. //if (ret==1)
  1071. {
  1072. ResDataObject NotifyData, ResNotify, ErrorInfo/*, tempInfo*/;
  1073. //info.GetResDataObject(tempInfo);
  1074. //ErrorInfo.update(Code, tempInfo);
  1075. info.GetResDataObject(ErrorInfo);
  1076. struct timeval tv;
  1077. struct tm* tm_info;
  1078. char TimeTag[30];
  1079. // 获取当前时间
  1080. gettimeofday(&tv, NULL);
  1081. // 转换为本地时间
  1082. tm_info = localtime(&tv.tv_sec);
  1083. // 格式化时间为字符串
  1084. snprintf(TimeTag, sizeof(TimeTag), "%04d-%02d-%02d %02d:%02d:%02d.%03ld",
  1085. tm_info->tm_year + 1900, tm_info->tm_mon + 1, tm_info->tm_mday,
  1086. tm_info->tm_hour, tm_info->tm_min, tm_info->tm_sec, tv.tv_usec / 1000);
  1087. ErrorInfo.add("CreationTime", TimeTag);
  1088. ErrorInfo.add("AppId", pAppId);
  1089. ErrorInfo.add("InstanceId", DevInstance);
  1090. if (nMessageType == ERRORTYPE)//只有错误会增加到错误列表中,警告通知上层即可
  1091. {
  1092. m_pResErrorList->update(strDevInstanceCode.c_str(), ErrorInfo);
  1093. }
  1094. ResNotify.update(strDevInstanceCode.c_str(), ErrorInfo);
  1095. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_ADD, "ErrorList", ResNotify);
  1096. ////mLog::FWARN( "preposterror ErrorType:{$} {$}", nMessageType,NotifyData.encode());
  1097. CmdFromLogicDev(&NotifyData);
  1098. //PublishAction(&NotifyData, (m_strEBusRoot + "/Notify").c_str(), m_pMqttConntion);
  1099. }
  1100. //else if (ret == 2)
  1101. //{
  1102. // ResDataObject NotifyData, ResNotify, ErrorInfo, tempInfo;
  1103. // info.GetResDataObject(tempInfo);
  1104. // ErrorInfo.update(Code, tempInfo);
  1105. // if (nMessageType == ERRORTYPE)//只有错误会增加到错误列表中,警告通知上层即可
  1106. // {
  1107. // (*m_pResErrorList)[DevInstance].update(Code, tempInfo);
  1108. // }
  1109. // ResNotify.update(DevInstance, ErrorInfo);
  1110. // PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_ADD, "ErrorList", ResNotify);
  1111. // RES_////mLog::FDEBUG(NotifyData, "preposterror RET:%d,ErrorType:%u", ret, nMessageType);
  1112. // CmdFromLogicDev(&NotifyData);
  1113. //}
  1114. //put log here
  1115. return RET_SUCCEED;
  1116. }
  1117. RET_STATUS LogicDevice::AddErrorMessage(const char* Code, int &Level, const char* ResInfo, int nMessageType, const char* pAppId)
  1118. {
  1119. AddErrorMessage(m_pDevInstance, Code, Level, ResInfo, "",nMessageType, pAppId);
  1120. //put log here
  1121. return RET_FAILED;
  1122. }
  1123. RET_STATUS LogicDevice::DelErrorMessage(const char* DevInstance, const char* Code, int &Level, const char* ResInfo, const char* Description, int nMessageType)
  1124. {
  1125. int index = -1;
  1126. bool m_bClearAll = false;
  1127. //trim empty code string
  1128. string CodeStr = Code;
  1129. if (CodeStr.size() == 0 || CodeStr == "0" || CodeStr == "")
  1130. {
  1131. CodeStr = "";
  1132. Code = CodeStr.c_str();
  1133. m_bClearAll = true;
  1134. }
  1135. //if ((string)Code == "0" || (string)Code == "")
  1136. //{
  1137. // m_bClearAll = true;
  1138. //}
  1139. string strDevInstanceCode = DevInstance;
  1140. strDevInstanceCode += Code;
  1141. if (m_bClearAll)
  1142. {
  1143. m_pResErrorList->clear();
  1144. }
  1145. else
  1146. {
  1147. MessageInfo info;
  1148. info.CodeID = Code;
  1149. info.Type = nMessageType;
  1150. info.Level = Level;
  1151. info.Resouceinfo = ResInfo;
  1152. info.Description = Description;
  1153. for (size_t i = 0; i < m_pResErrorList->size(); i++)
  1154. {
  1155. string strInstancekey = m_pResErrorList->GetKey(i);
  1156. if (strInstancekey == strDevInstanceCode)
  1157. {
  1158. //for (size_t j = 0; j < (*m_pResErrorList)[DevInstance].size(); j++)
  1159. //{
  1160. // string strCodekey = (*m_pResErrorList)[DevInstance].GetKey(j);
  1161. // string strtype = (*m_pResErrorList)[DevInstance][strCodekey.c_str()]["Type"];
  1162. // if (strCodekey == (string)Code && atoi(strtype.c_str()) == nMessageType)
  1163. // {
  1164. // index = (INT)j;
  1165. // break;
  1166. // }
  1167. //}
  1168. index = (int)i;
  1169. break;
  1170. }
  1171. }
  1172. }
  1173. MessageInfo info;
  1174. info.CodeID = Code;
  1175. info.Type = nMessageType;
  1176. info.Level = Level;
  1177. info.Resouceinfo = ResInfo;
  1178. info.Description = Description;
  1179. ResDataObject NotifyData, ResNotify, ErrorInfo/*, tempInfo*/;
  1180. //info.GetResDataObject(tempInfo);
  1181. //ErrorInfo.add(Code, tempInfo);
  1182. info.GetResDataObject(ErrorInfo);
  1183. ErrorInfo.add("InstanceId", DevInstance);
  1184. bool result = false;
  1185. if (index>=0)
  1186. {
  1187. //result = (*m_pResErrorList)[DevInstance].eraseOneOf(Code, index);
  1188. result = (*m_pResErrorList).eraseAllOf(strDevInstanceCode.c_str());
  1189. }
  1190. if (index >= 0 || m_bClearAll || nMessageType == WARNTYPE)
  1191. {
  1192. ResNotify.add(strDevInstanceCode.c_str(), ErrorInfo);
  1193. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_DEL, "ErrorList", ResNotify);
  1194. ////mLog::FWARN( "pre Del error ErrorCode:{$} {$}", Code ,NotifyData.encode());
  1195. CmdFromLogicDev(&NotifyData);
  1196. //PublishAction(&NotifyData, (m_strEBusRoot + "/Notify").c_str(), m_pMqttConntion);
  1197. }
  1198. return RET_SUCCEED;
  1199. }
  1200. RET_STATUS LogicDevice::DelErrorMessage(const char* Code, int &Level, const char* ResInfo, int nMessageType)
  1201. {
  1202. DelErrorMessage(m_pDevInstance, Code, Level, ResInfo, "", nMessageType);
  1203. //put log here
  1204. return RET_FAILED;
  1205. }
  1206. RET_STATUS LogicDevice::EvtProcedure()
  1207. {
  1208. return RET_FAILED;
  1209. }
  1210. bool LogicDevice::CheckFeatureLicense(const char *pszFeatureId)
  1211. {
  1212. ////mLog::FERROR("NOT FINISHED YET");
  1213. return false;
  1214. }
  1215. RET_STATUS LogicDevice::IoSystemLog(int Level, const char* pCode, const char* pContext, size_t ContextSize, const char* pAppId)
  1216. {
  1217. std::string strResult = "";
  1218. //组Context包
  1219. //if (m_pLogger)
  1220. {
  1221. wstring wContect = mb2wc_a(pContext);
  1222. CBase64::Encode((const unsigned char*)wContect.c_str(), (unsigned long)wContect.size() * sizeof(wchar_t), strResult);
  1223. }
  1224. //Thread_Lock();
  1225. //if (NULL != fmt)
  1226. //{
  1227. // va_list marker = NULL;
  1228. // va_start(marker, fmt);
  1229. // size_t nLength = _vscprintf(fmt, marker) + 1;
  1230. // std::vector<char> vBuffer(nLength, '\0');
  1231. // int nWritten = vsnprintf_s(&vBuffer[0], vBuffer.size(), nLength, fmt, marker);
  1232. // if (nWritten > 0)
  1233. // {
  1234. // strResult = &vBuffer[0];
  1235. // }
  1236. // va_end(marker);
  1237. //}
  1238. //Thread_UnLock();
  1239. ResDataObject SysLogNode;
  1240. string guidstr;
  1241. GUID DeviceGuid;
  1242. //组Log包
  1243. if (GetDeviceType(DeviceGuid))
  1244. {
  1245. guid_2_string(DeviceGuid, guidstr);
  1246. SysLogNode.add("Module", guidstr.c_str());
  1247. SysLogNode.add("AppId", pAppId);
  1248. SysLogNode.add("ThreadId", GetCurrentThreadId());
  1249. if (pCode)
  1250. {
  1251. SysLogNode.add("BusinessKey", pCode);
  1252. }
  1253. else
  1254. {
  1255. SysLogNode.add("BusinessKey", "");
  1256. }
  1257. SysLogNode.add("IP", (const char*)getLocalIpAddress());
  1258. struct timeval tv;
  1259. struct tm* tm_info;
  1260. char TimeTag[30];
  1261. // 获取当前时间
  1262. gettimeofday(&tv, NULL);
  1263. // 转换为本地时间
  1264. tm_info = localtime(&tv.tv_sec);
  1265. // 格式化时间为字符串
  1266. snprintf(TimeTag, sizeof(TimeTag), "%04d-%02d-%02d %02d:%02d:%02d.%03ld",
  1267. tm_info->tm_year + 1900, tm_info->tm_mon + 1, tm_info->tm_mday,
  1268. tm_info->tm_hour, tm_info->tm_min, tm_info->tm_sec, tv.tv_usec / 1000);
  1269. SysLogNode.add("CreationTime", TimeTag);
  1270. string strLevel = SysLogLevel2str(Level);
  1271. SysLogNode.add("Level", strLevel.c_str());
  1272. SysLogNode.add("HostName", (const char*)getLocalMachineId());
  1273. SysLogNode.add("ProcessName", (const char*)GetModuleTitle());
  1274. SysLogNode.add("FreeText", strResult.c_str());
  1275. SysLogNode.add("Context", pCode);
  1276. ResDataObject NotifyData;
  1277. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_MSG, "Syslog", SysLogNode);
  1278. CmdFromLogicDev(&NotifyData);
  1279. //PublishAction(&NotifyData, (m_strEBusRoot + "/Notify").c_str(), m_pMqttConntion);
  1280. }
  1281. else
  1282. {
  1283. ////mLog::FWARN("no Guid??");
  1284. return RET_FAILED;
  1285. }
  1286. //打印LOG
  1287. switch (Level)
  1288. {
  1289. case Syslog_Debug:
  1290. //RES_PRINTA_DEBUG(m_pLogger, SysLogNode, "SysLog");
  1291. ////mLog::FDEBUG("SysLog {$} ", SysLogNode.encode());
  1292. break;
  1293. case Syslog_Information:
  1294. ///RES_PRINTA_INFO(m_pLogger, SysLogNode, "SysLog");
  1295. ////mLog::FINFO("SysLog {$} ", SysLogNode.encode());
  1296. break;
  1297. case Syslog_Warning:
  1298. //RES_PRINTA_WARN(m_pLogger, SysLogNode, "SysLog");
  1299. ////mLog::Warn("SysLog {$} ", SysLogNode.encode());
  1300. break;
  1301. case Syslog_Error:
  1302. //RES_PRINTA_ERROR(m_pLogger, SysLogNode, "SysLog");
  1303. ////mLog::FERROR("SysLog {$} ", SysLogNode.encode());
  1304. break;
  1305. case Syslog_Fatal:
  1306. //RES_PRINTA_FATAL(m_pLogger, SysLogNode, "SysLog");
  1307. ////mLog::FINFO("SysLog {$} ", SysLogNode.encode());
  1308. break;
  1309. default:
  1310. ////mLog::FINFO("SysLog {$} " ,SysLogNode.encode() );
  1311. break;
  1312. }
  1313. return RET_SUCCEED;
  1314. }
  1315. RET_STATUS LogicDevice::SystemLog(SYSLOGLEVEL Level,const char *pCode, const char* fmt, ...)
  1316. {
  1317. std::string strResult = "";
  1318. //组Context包
  1319. //if (m_pLogger)
  1320. //{
  1321. // m_pLogger->Thread_Lock();
  1322. // if (NULL != fmt)
  1323. // {
  1324. // va_list marker = NULL;
  1325. // va_start(marker, fmt);
  1326. // size_t nLength = _vscprintf(fmt, marker) + 1;
  1327. // std::vector<char> vBuffer(nLength, '\0');
  1328. // int nWritten = vsnprintf_s(&vBuffer[0], vBuffer.size(), nLength, fmt, marker);
  1329. // if (nWritten > 0)
  1330. // {
  1331. // strResult = &vBuffer[0];
  1332. // }
  1333. // va_end(marker);
  1334. // }
  1335. // m_pLogger->Thread_UnLock();
  1336. //}
  1337. //else
  1338. {
  1339. Thread_Lock();
  1340. if (fmt != NULL) {
  1341. va_list marker;
  1342. va_start(marker, fmt);
  1343. // 获取格式化字符串所需的大小(不包括终止符)
  1344. int nLength = vsnprintf(NULL, 0, fmt, marker);
  1345. if (nLength >= 0) {
  1346. std::vector<char> vBuffer(nLength + 1, '\0'); // +1 为终止符
  1347. vsnprintf(&vBuffer[0], vBuffer.size(), fmt, marker);
  1348. strResult = &vBuffer[0]; // 将缓冲区内容赋值给结果字符串
  1349. }
  1350. va_end(marker);
  1351. }
  1352. Thread_UnLock();
  1353. }
  1354. ResDataObject SysLogNode;
  1355. string guidstr;
  1356. GUID DeviceGuid;
  1357. //组Log包
  1358. if (GetDeviceType(DeviceGuid))
  1359. {
  1360. guid_2_string(DeviceGuid, guidstr);
  1361. SysLogNode.add("Module", guidstr.c_str());
  1362. SysLogNode.add("AppId", "");
  1363. SysLogNode.add("ThreadId", GetCurrentThreadId());
  1364. if (pCode)
  1365. {
  1366. SysLogNode.add("BusinessKey", pCode);
  1367. }
  1368. else
  1369. {
  1370. SysLogNode.add("BusinessKey", "");
  1371. }
  1372. SysLogNode.add("IP", (const char *)getLocalIpAddress());
  1373. struct timeval tv;
  1374. struct tm* tm_info;
  1375. char TimeTag[30];
  1376. // 获取当前时间
  1377. gettimeofday(&tv, NULL);
  1378. // 转换为本地时间
  1379. tm_info = localtime(&tv.tv_sec);
  1380. // 格式化时间为字符串
  1381. snprintf(TimeTag, sizeof(TimeTag), "%04d-%02d-%02d %02d:%02d:%02d.%03ld",
  1382. tm_info->tm_year + 1900, tm_info->tm_mon + 1, tm_info->tm_mday,
  1383. tm_info->tm_hour, tm_info->tm_min, tm_info->tm_sec, tv.tv_usec / 1000);
  1384. SysLogNode.add("CreationTime", TimeTag);
  1385. SysLogNode.add("Level", Level);
  1386. SysLogNode.add("HostName", (const char *)getLocalMachineId());
  1387. SysLogNode.add("ProcessName", (const char *)GetModuleTitle());
  1388. SysLogNode.add("FreeText", strResult.c_str());
  1389. ResDataObject NotifyData;
  1390. PacketAnalizer::MakeNotify(NotifyData, PACKET_CMD_MSG, "Syslog", SysLogNode);
  1391. CmdFromLogicDev(&NotifyData);
  1392. //PublishAction(&NotifyData, (m_strEBusRoot + "/Notify").c_str(), m_pMqttConntion);
  1393. if(m_pParent != nullptr)
  1394. NotifyParent(&NotifyData, "/Notify");
  1395. }
  1396. else
  1397. {
  1398. ////mLog::FERROR("no Guid??");
  1399. return RET_FAILED;
  1400. }
  1401. //打印LOG
  1402. switch (Level)
  1403. {
  1404. case Syslog_Debug:
  1405. //RES_PRINTA_DEBUG(m_pLogger, SysLogNode, "SysLog");
  1406. ////mLog::FDEBUG("SysLog {$}", SysLogNode.encode());
  1407. break;
  1408. case Syslog_Information:
  1409. //RES_PRINTA_INFO(m_pLogger, SysLogNode, "SysLog");
  1410. ////mLog::FINFO("SysLog {$}", SysLogNode.encode());
  1411. break;
  1412. case Syslog_Warning:
  1413. //RES_PRINTA_WARN(m_pLogger, SysLogNode, "SysLog");
  1414. ////mLog::Warn("SysLog {$}", SysLogNode.encode());
  1415. break;
  1416. case Syslog_Error:
  1417. //RES_PRINTA_ERROR(m_pLogger, SysLogNode, "SysLog");
  1418. ////mLog::FERROR("SysLog {$}", SysLogNode.encode());
  1419. break;
  1420. case Syslog_Fatal:
  1421. //RES_PRINTA_FATAL(m_pLogger, SysLogNode, "SysLog");
  1422. ////mLog::FINFO("SysLog {$}", SysLogNode.encode());
  1423. break;
  1424. default:
  1425. ////mLog::FINFO( "SysLog {$}", SysLogNode.encode());
  1426. break;
  1427. }
  1428. return RET_SUCCEED;
  1429. }
  1430. /////////////////////////////////////////////////////////////////////////////
  1431. ccos_mqtt_connection* LogicDevice::CreateConnection(const char* pszClientID, ccos_mqtt_callback onmsg)
  1432. {
  1433. return nullptr;
  1434. }
  1435. std::string CurrentDateTime()
  1436. {
  1437. auto now = std::chrono::system_clock::now();
  1438. auto now_us = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch());
  1439. auto now_time_t = std::chrono::system_clock::to_time_t(now);
  1440. std::tm now_tm{};
  1441. localtime_r(&now_time_t, &now_tm); // 线程安全版本
  1442. char buf[64];
  1443. std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &now_tm);
  1444. std::string now_time_str = buf;
  1445. // 格式化微秒部分并追加
  1446. snprintf(buf, sizeof(buf), ".%06lld", static_cast<long long>(now_us.count() % 1000000));
  1447. now_time_str += buf;
  1448. return now_time_str;
  1449. }
  1450. static string CurrentDateTime2()
  1451. {
  1452. std::time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
  1453. char buf[100] = { 0 };
  1454. std::strftime(buf, sizeof(buf), " %Y-%m-%d %H:%M:%S ", std::localtime(&now));
  1455. return buf;
  1456. }
  1457. bool LogicDevice::GetActions(ResDataObject& resAction)
  1458. {
  1459. for (int x = 0; x < m_Actions.size(); x++)
  1460. {
  1461. resAction.update(m_Actions.GetKey(x), "");
  1462. }
  1463. return true;
  1464. }
  1465. void LogicDevice::NotifyParent(ResDataObject* NotifyData, const char* pszTopic, ccos_mqtt_connection* hConnection)
  1466. {
  1467. if (m_pParent != nullptr)
  1468. {
  1469. if (hConnection == nullptr)
  1470. {
  1471. hConnection = m_pParent->m_pMqttConntion;
  1472. }
  1473. PublishAction(NotifyData, (m_pParent->GetRootPath() + pszTopic).c_str(), hConnection);
  1474. }
  1475. }
  1476. const mqtt_qos_t MQTT_QOS = QOS2;
  1477. /// <summary>
  1478. /// 工作位设备组 上线或者下线,设备路径为 CCOS/Table/Detector
  1479. /// CCOS/Demo/Detector
  1480. /// </summary>
  1481. /// <param name="bOnline"></param>
  1482. void LogicDevice::SubscribeGroupActions(string wsName, int bOnline)
  1483. {
  1484. if (m_rsOnlineGroup.GetFirstOf(wsName.c_str()) >= 0)
  1485. {
  1486. int lastOnline = (int)m_rsOnlineGroup[wsName.c_str()];
  1487. if (bOnline == lastOnline)
  1488. {
  1489. ////mLog::FWARN("Group Abstract is already ? Online {$}", bOnline);
  1490. return;
  1491. }
  1492. }
  1493. if ( m_strAbstractPath.length() > 0)
  1494. {
  1495. std::string pszAction, gpPath;
  1496. int ret = 0;
  1497. int num = m_Actions.size();
  1498. ////mLog::FINFO("Group Device onLine or offLine {$}", bOnline);
  1499. gpPath = m_strAbstractPath;
  1500. gpPath.replace(0, string("CCOS/DEVICE").length(), "CCOS/" + wsName);
  1501. pszAction = gpPath + m_strDevicePath;
  1502. pszAction += "/Action/+";
  1503. SubScribeTopic(pszAction.c_str(), bOnline == 1);
  1504. if (bOnline)
  1505. {
  1506. ////mLog::FINFO("{$} Subscribe Device Group Action {$} ", m_strClientID, pszAction);
  1507. }
  1508. else
  1509. {
  1510. ////mLog::FINFO("{$} UnSubscribe Device Group Action {$} ", m_strClientID, pszAction);
  1511. }
  1512. //for (size_t i = 0; i < num; i++)
  1513. //{
  1514. // pszAction = gpPath + m_strDevicePath;
  1515. // pszAction += "/Action/";
  1516. // pszAction += (m_Actions.GetKey(i));
  1517. // SubScribeTopic(pszAction.c_str(), bOnline == 1);
  1518. // if (bOnline)
  1519. // {
  1520. // ////mLog::FINFO("{$} Subscribe Device Group Action {$} ", m_strClientID, pszAction);
  1521. // }
  1522. // else
  1523. // {
  1524. // ////mLog::FINFO("{$} UnSubscribe Device Group Action {$} ", m_strClientID, pszAction);
  1525. // }
  1526. //}
  1527. m_rsOnlineGroup.update(wsName.c_str(), bOnline);
  1528. }
  1529. else
  1530. {
  1531. ////mLog::FWARN("try Online but AbstractPath is none {$}", m_strClientID);
  1532. }
  1533. }
  1534. void SubscribeModule(ccos_mqtt_connection* pconn, string devuribBase)
  1535. {
  1536. string pszAction = devuribBase ;
  1537. pszAction += "/Get/+";
  1538. m_subscribedTopics.push_back(pszAction);
  1539. SubscribeTopic(pconn, m_subscribedTopics.back().c_str());
  1540. pszAction = devuribBase;
  1541. pszAction += "/Update/+";
  1542. m_subscribedTopics.push_back(pszAction);
  1543. SubscribeTopic(pconn, m_subscribedTopics.back().c_str());
  1544. pszAction = devuribBase;
  1545. pszAction += "/Set/+";
  1546. m_subscribedTopics.push_back(pszAction);
  1547. SubscribeTopic(pconn, m_subscribedTopics.back().c_str());
  1548. pszAction = devuribBase;
  1549. pszAction += "/Add/+";
  1550. m_subscribedTopics.push_back(pszAction);
  1551. SubscribeTopic(pconn, m_subscribedTopics.back().c_str());
  1552. pszAction = devuribBase;
  1553. pszAction += "/Del/+";
  1554. m_subscribedTopics.push_back(pszAction);
  1555. SubscribeTopic(pconn, m_subscribedTopics.back().c_str());
  1556. pszAction = devuribBase;
  1557. pszAction += "/Action/+";
  1558. m_subscribedTopics.push_back(pszAction);
  1559. SubscribeTopic(pconn, m_subscribedTopics.back().c_str());
  1560. pszAction = devuribBase;
  1561. pszAction += "/Message/+";
  1562. m_subscribedTopics.push_back(pszAction);
  1563. SubscribeTopic(pconn, m_subscribedTopics.back().c_str());
  1564. }
  1565. void LogicDevice::SubscribeActions()
  1566. {
  1567. ////mLog::FINFO("Begain");
  1568. if (nullptr == m_pMqttConntion)
  1569. return;
  1570. int num = m_Actions.size();
  1571. mqtt_client* pMqttClient = (mqtt_client*)std::get<MQTT_CLT_ID>(*m_pMqttConntion);
  1572. mqtt_topic_list* pTopicList = std::get<MQTT_TIPIC_LIST_ID>(*m_pMqttConntion);
  1573. {
  1574. ResDataObject res,resAction;
  1575. GetDeviceResource(&res);
  1576. std::cout << "LogicDevice::SubscribeActions GetDeviceResource" << res.encode() << endl;
  1577. resAction = res["Action"];
  1578. ////mLog::FINFO("Actions from deviceresource [{$}]", resAction.size());
  1579. for (int x = 0; x < resAction.size(); x++)
  1580. {
  1581. string action = (string)resAction.GetKey(x);
  1582. if (action.length() > 0)
  1583. {
  1584. ////mLog::FINFO("Action from DeviceResource [{$}]", action);
  1585. m_Actions.update(action.c_str(), "");
  1586. }
  1587. }
  1588. num = m_Actions.size();
  1589. }
  1590. std::string pszAction;
  1591. int ret = 0;
  1592. SubscribeModule(m_pMqttConntion, m_strEBusRoot.c_str());
  1593. ////mLog::FINFO("{$} Subscribe EBus Action {$} return {$} topic num {$}", m_strClientID, pszAction, ret, pTopicList->size());
  1594. if (m_strEBusRoot != m_strCCOSDevicePath)
  1595. {
  1596. pszAction = m_strCCOSDevicePath + m_strDevicePath;
  1597. SubscribeModule(m_pMqttConntion, pszAction.c_str());
  1598. ////mLog::FINFO("{$} Subscribe CCOS Action {$} return {$} topic num {$}", m_strClientID, pszAction, ret, pTopicList->size());
  1599. }
  1600. if (m_strAbstractPath.length() > 0)
  1601. {
  1602. pszAction = m_strAbstractPath + m_strDevicePath;
  1603. SubscribeModule(m_pMqttConntion, pszAction.c_str());
  1604. ////mLog::FINFO("{$} Subscribe Abstract Action {$} return {$} topic num {$}", m_strClientID, pszAction, ret, pTopicList->size());
  1605. }
  1606. //for (size_t i = 0; i < num; i++)
  1607. //{
  1608. // //订阅ebus的路径
  1609. // pszAction = m_strEBusRoot;
  1610. // pszAction += "/Action/";
  1611. // pszAction += (m_Actions.GetKey(i));
  1612. // SubscribeTopic(m_pMqttConntion, pszAction.c_str());
  1613. // ////mLog::FINFO("{$} Subscribe Action {$} return {$} topic num {$}", m_strClientID, pszAction, ret, pTopicList->size());
  1614. //
  1615. // //订阅CCOS设备路径
  1616. // if (m_strEBusRoot != m_strCCOSDevicePath)
  1617. // {
  1618. // pszAction = m_strCCOSDevicePath + m_strDevicePath;
  1619. // pszAction += "/Action/";
  1620. // pszAction += (m_Actions.GetKey(i));
  1621. // SubscribeTopic(m_pMqttConntion, pszAction.c_str());
  1622. // ////mLog::FINFO("{$} Subscribe Action {$} return {$} topic num {$}", m_strClientID, pszAction, ret, pTopicList->size());
  1623. // }
  1624. // //抽象设备路径要一直存在
  1625. // //订阅抽象设备路径
  1626. // if ( m_strAbstractPath.length() > 0)
  1627. // {
  1628. // pszAction = m_strAbstractPath + m_strDevicePath;
  1629. // pszAction += "/Action/";
  1630. // pszAction += (m_Actions.GetKey(i));
  1631. // SubscribeTopic(m_pMqttConntion, pszAction.c_str());
  1632. // ////mLog::FINFO("{$} Subscribe Action {$} return {$} topic num {$}", m_strClientID, pszAction, ret, pTopicList->size());
  1633. // }
  1634. //}
  1635. //pszAction = m_strEBusRoot;
  1636. //pszAction += "/Action/UpdateDeviceResource";
  1637. ////std::cout << "=====*******====== 【" << m_strClientID << "】 Subscribe Action " << pszAction << endl;
  1638. //pTopicList->push_back(pszAction);
  1639. //mqtt_subscribe(pMqttClient, pszAction.c_str(), MQTT_QOS, msgarrivd);
  1640. //////mLog::FINFO("{$} Subscribe Action {$} return {$} topic num {$}", m_strClientID, pszAction, ret, pTopicList->size());
  1641. //*/
  1642. }
  1643. /*
  1644. void connlost(void* context, char* cause)
  1645. {
  1646. //连接中断
  1647. ccos_mqtt_connection* connection = (ccos_mqtt_connection*)context;
  1648. std::cout << "Connection Lost .....[" << std::get<CLINET_ID_ID>(*connection) <<"] why?" << endl;
  1649. printf("\nConnection lost\n");
  1650. printf(" cause: %s\n", cause);
  1651. std::cout << CurrentDateTime() << "MQTT Server Connection lost...." << endl;
  1652. }
  1653. void disconnected(void* context, MQTTProperties* props, enum MQTTReasonCodes rc)
  1654. {
  1655. ccos_mqtt_connection* connection = (ccos_mqtt_connection*)context;
  1656. std::cout << "Connection disconnected .....[" << std::get<CLINET_ID_ID>(*connection) << "] why?" << endl;
  1657. }
  1658. */
  1659. //发送成功
  1660. //void delivered(void* context, MQTTAsync_token dt)
  1661. //{
  1662. // printf("Message with token value %d delivery confirmed\n", dt);
  1663. // //deliveredtoken = dt;
  1664. //}
  1665. //void connlost(void* context, char* cause)
  1666. //{
  1667. // //printf("Connection 0X%08X Lost ...... ???? %s \n",, cause);
  1668. // //std::cout << "Connection Context [" << (UINT64)context << "] conn lost " << (cause==nullptr?"": cause) << endl;
  1669. //
  1670. // //连接中断
  1671. // ccos_mqtt_connection* connection = (ccos_mqtt_connection*)context;
  1672. // mqtt_client* client = (mqtt_client*)std::get<MQTT_CLT_ID>(*connection);
  1673. // std::cout << CurrentDateTime() << "Connection Lost 2 .....[" << std::get<CLINET_ID_ID>(*connection) << "] why? " << (cause == nullptr ? "" : cause) << endl;
  1674. // return;
  1675. //
  1676. // MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
  1677. // int rc;
  1678. //
  1679. // printf("Reconnecting\n");
  1680. // conn_opts.keepAliveInterval = 20;
  1681. // conn_opts.cleansession = 1;
  1682. // if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
  1683. // {
  1684. // printf("Failed to start connect, return code %d\n", rc);
  1685. // //finished = 1;
  1686. // }
  1687. //}
  1688. //重连成功
  1689. //void onReconnected(void* context, char* cause)
  1690. //{
  1691. // //printf("onReconnected 0X%08X Lost ...... ???? %s \n", (UINT64)context, cause);
  1692. // //std::cout << "onReconnected [" << (UINT64)context << "] conn " << (cause == nullptr ? "" : cause) << endl;
  1693. //
  1694. // ccos_mqtt_connection* connection = (ccos_mqtt_connection*)context;
  1695. // mqtt_client* client = (mqtt_client*)std::get<MQTT_CLT_ID>(*connection);
  1696. // MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
  1697. // mqtt_topic_list* pTopicList = std::get<MQTT_TIPIC_LIST_ID>(*connection);
  1698. // const char* client_id = std::get<CLINET_ID_ID>(*connection);
  1699. // int rc;
  1700. //
  1701. // //printf(" %s \n", std::get<CLINET_ID_ID>(*connection));
  1702. // std::cout << "[" << client_id << "] Successful reconnection Use context [" << (UINT64)context << "]" << endl;
  1703. // //cout << "Connected ok.. by TID [" << GetCurrentThreadId() << "]" << endl;
  1704. // // 重新订阅,暂不重新订阅,看看
  1705. //
  1706. // ///*
  1707. // //printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n"
  1708. // // "Press Q<Enter> to quit\n\n", TOPIC, CLIENTID, QOS);
  1709. // //opts.onSuccess = onSubscribe;
  1710. // //opts.onFailure = onSubscribeFailure;
  1711. // //opts.context = client;
  1712. // auto it = pTopicList->begin();
  1713. // while(it != pTopicList->end())
  1714. // {
  1715. // rc = MQTTAsync_subscribe(client, (*it).c_str(), 1, &opts);
  1716. // printf("-------- [%s] re subscribe %s, return code %d\n", client_id, (*it).c_str(), rc);
  1717. // it++;
  1718. // }
  1719. // //*/
  1720. //
  1721. //}
  1722. //
  1723. ////MQTT 连接主动断开连接失败
  1724. //void onDisconnectFailure(void* context, MQTTAsync_failureData* response)
  1725. //{
  1726. // printf("Disconnect failed, rc %d\n", response->code);
  1727. // //disc_finished = 1;
  1728. //}
  1729. //
  1730. ////MQTT 连接主动断开连接成功
  1731. //void onDisconnect(void* context, MQTTAsync_successData* response)
  1732. //{
  1733. // //printf("Successful disconnection\n");
  1734. // //disc_finished = 1;
  1735. //}
  1736. //
  1737. //void onSubscribe(void* context, MQTTAsync_successData* response)
  1738. //{
  1739. // printf("Subscribe succeeded\n");
  1740. // //subscribed = 1;
  1741. //}
  1742. //
  1743. //void onSubscribeFailure(void* context, MQTTAsync_failureData* response)
  1744. //{
  1745. // printf("Subscribe failed, rc %d\n", response->code);
  1746. // //finished = 1;
  1747. //}
  1748. //
  1749. //
  1750. //void onConnectFailure(void* context, MQTTAsync_failureData* response)
  1751. //{
  1752. // printf("Connect failed, rc %d\n", response->code);
  1753. // //finished = 1;
  1754. //}
  1755. //void onConnect(void* context, MQTTAsync_successData* response)
  1756. //{
  1757. //
  1758. // ccos_mqtt_connection* connection = (ccos_mqtt_connection*)context;
  1759. // mqtt_client* client = (mqtt_client*)std::get<MQTT_CLT_ID>(*connection);
  1760. //
  1761. // std::cout << "[" << std::get<CLINET_ID_ID>(*connection) << "] onConnect Context [" << (UINT64)context << "] " << endl;
  1762. //
  1763. // MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
  1764. // int rc;
  1765. //
  1766. // //printf("[%s] connect MQTT Successful connection\n", std::get< CLINET_ID_ID>(*connection));
  1767. // HANDLE hConnected = std::get< CONNECTED_HANDLE_ID>(*connection);
  1768. // if (hConnected != NULL)
  1769. // SetEvent(hConnected);
  1770. //
  1771. // /*
  1772. // printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n"
  1773. // "Press Q<Enter> to quit\n\n", TOPIC, CLIENTID, QOS);
  1774. // opts.onSuccess = onSubscribe;
  1775. // opts.onFailure = onSubscribeFailure;
  1776. // opts.context = client;
  1777. // if ((rc = MQTTAsync_subscribe(client, TOPIC, QOS, &opts)) != MQTTASYNC_SUCCESS)
  1778. // {
  1779. // printf("Failed to start subscribe, return code %d\n", rc);
  1780. // finished = 1;
  1781. // }*/
  1782. //}
  1783. //往指定主题发送Action包,携带参数,并指定答复的Topic,异步模式处理Resp,需要在对应连接的回调中处理
  1784. int PublishActionWithoutLock(string &message, const char* pszTopic, mqtt_client* pMqttClient, std::string client_id, mqtt_qos_t qos = MQTT_QOS);
  1785. void resubscribe_topic(void* client, void* reconnect_date)
  1786. {
  1787. mqtt_client* pClient = (mqtt_client*)client;
  1788. ccos_mqtt_connection* connection = (ccos_mqtt_connection*)pClient->mqtt_conn_context;
  1789. mqtt_topic_list* pTopicList = std::get<MQTT_TIPIC_LIST_ID>(*connection);
  1790. string client_id = std::get<CLINET_ID_ID>(*connection);
  1791. ////mLog::FWARN("Connection Reconneted ok. {$}, topic num :{$}", client_id, pTopicList->size());
  1792. CcosLock* pLock = std::get<CONN_SEND_LOCK_ID>(*connection);
  1793. pLock->Thread_Lock();
  1794. for_each(pTopicList->begin(),pTopicList->end(), [&pClient] (string str)-> void {
  1795. ////mLog::FWARN("Resubscribe {$}", str);
  1796. mqtt_subscribe(pClient, str.c_str(), MQTT_QOS, msgarrivd);
  1797. });
  1798. pLock->Thread_UnLock();
  1799. }
  1800. //MQTT消息抵达
  1801. //int msgarrvd(void* context, char* topicName, int topicLen, MQTTAsync_message* message)
  1802. void msgarrivd(void* client, message_data_t* message)
  1803. {
  1804. if (client == nullptr)
  1805. {
  1806. //printf("************************ somthing happend...");
  1807. return;
  1808. }
  1809. //消息抵达
  1810. ResDataObject req;
  1811. string topic = strlen( message->topic_name) > sizeof(message->topic_name)-1 ? string(message->topic_name, sizeof(message->topic_name) - 1) : message->topic_name; //topicName; //msg->get_topic().c_str();
  1812. mqtt_client* pClient = (mqtt_client*)client;
  1813. ccos_mqtt_connection* connection = (ccos_mqtt_connection*)pClient->mqtt_conn_context;
  1814. if (!connection) return;
  1815. CcosLock* pLock = std::get<CONN_SEND_LOCK_ID>(*connection);
  1816. if (pLock == nullptr)
  1817. return;
  1818. pLock->Thread_Lock();
  1819. //再次取Lock,如果发现是空了,什么都不干
  1820. CcosLock* pLockTemp = std::get<CONN_SEND_LOCK_ID>(*connection);
  1821. if (pLockTemp == nullptr)
  1822. {
  1823. pLock->Thread_UnLock();
  1824. return;
  1825. }
  1826. string client_id = std::get<CLINET_ID_ID>(*connection);
  1827. void* pc = std::get<MQTT_CLT_ID>(*connection);
  1828. if (pc == nullptr)
  1829. {
  1830. //printf("mqtt is closed now..\n");
  1831. pLock->Thread_UnLock();
  1832. return;
  1833. }
  1834. std::cout << CurrentDateTime() << "msgarrivd:: TID [" << GetCurrentThreadId() << "] " << client_id << " Get Msg from " << topic << /*" msg Body " << payload <<*/ endl;
  1835. //std::cout << " msg Body " << payload << endl;
  1836. if ((topic.length() >= MQTT_TOPIC_LEN_MAX && message->message->payloadlen > 16380) || message->message->payloadlen > 512*1024)
  1837. {
  1838. //std::string payloads((const char*)message->message->payload, 128);
  1839. ////mLog::FWARN("TID {$} : {$} Get Bad Msg Len[{$}] from {$}", GetCurrentThreadId(), client_id, message->message->payloadlen, topic.substr(0, 255));
  1840. pLock->Thread_UnLock();
  1841. return;
  1842. }
  1843. if((int)message->message->payloadlen > 16380)
  1844. std::cout << CurrentDateTime() << "msgarrivd:: TID [" << GetCurrentThreadId() << "] " << client_id << " Get big Msg from " << topic << " msg Len " << message->message->payloadlen << /*" msg Body " << payload <<*/ endl;
  1845. ////mLog::FWARN("TID {$} : {$} Get big Msg from {$} msg Len {$}", GetCurrentThreadId(), client_id, topic, message->message->payloadlen);
  1846. ////mLog::FDEBUG("TID {$} : {$} Get Msg from {$} msg Body {$}", GetCurrentThreadId(), client_id, topic, payload.substr(0, 1024));
  1847. const char* pclient_id = client_id.c_str();
  1848. try
  1849. {
  1850. std::string strPayload((const char*)message->message->payload, message->message->payloadlen);
  1851. req.decode(strPayload.c_str());
  1852. }
  1853. catch (...)
  1854. {
  1855. pLock->Thread_UnLock();
  1856. ////mLog::FWARN("Decode Exception.. {$}", payload);
  1857. return;
  1858. }
  1859. //取消息钩子
  1860. void* pHook = std::get<MSG_HOOK_ID>(*connection);
  1861. if (pHook != nullptr) {
  1862. ccos_mqtt_msg_filter* filter = (ccos_mqtt_msg_filter*)(pHook);
  1863. ccos_mqtt_msg_filter_func func = std::get<FILTER_FUNC_ID>(*filter);
  1864. //std::get<FILTER_FUNC_ID>(*filter) = nullptr;
  1865. std::cout << CurrentDateTime() << "msgarrivd:: TID [" << GetCurrentThreadId() << "] " << client_id << " Got Hook Process " << topic << endl;
  1866. ////mLog::FDEBUG("TID {$} : {$} Got Hook Process {$} ", GetCurrentThreadId(), client_id, topic);
  1867. //消息钩子函数存在
  1868. ResDataObject *pRequests = std::get<FILTER_RES_OBJ_ID>(*filter);
  1869. for(int x=0;x<pRequests->size();x++) {
  1870. //ccos_mqtt_msg_filter_func func = *(ccos_mqtt_msg_filter_func*)pfiterFunc;
  1871. std::cout << CurrentDateTime() << "msgarrivd:: TID [" << GetCurrentThreadId() << "] " << client_id << " Hook Process Function " << topic << endl;
  1872. ////mLog::FDEBUG("TID {$} : {$} Hook Process Function {$} ", GetCurrentThreadId(), client_id, topic);
  1873. string keyAction = pRequests->GetKey(x);
  1874. ResDataObject resObj = (*pRequests)[x];
  1875. std::shared_ptr<LinuxEvent> hEvent = std::get<FILTER_HANDLE_ID>(*filter);
  1876. if (PacketAnalizer::GetPacketType(&req) == PACKET_TYPE_RES && keyAction == PacketAnalizer::GetPacketKey(&req)) {
  1877. //勾住了,是该钩子的消息,则通知
  1878. //std::get<FILTER_FUNC_ID>(*filter) = nullptr;
  1879. std::cout << CurrentDateTime() << "msgarrivd:: TID [" << GetCurrentThreadId() << "] " << client_id << " Got Hook Function Hooked.. " << topic << endl;
  1880. hEvent = LinuxEvent::OpenEvent(string(resObj).c_str());
  1881. if (hEvent==nullptr)
  1882. {
  1883. hEvent = std::get<FILTER_HANDLE_ID>(*filter);
  1884. }
  1885. ////mLog::FINFO("TID {$} : {$} Got Hook Function Hooked.. {$} Notify Event [{$}] Handle [{$}]", GetCurrentThreadId(), client_id, topic, string(resObj), hEvent);
  1886. //PacketAnalizer::GetPacketContext(&req, *resObj);
  1887. ResDataObject* pResponse = std::get<FILTER_RESPONS_OBJ_ID>(*filter);
  1888. pResponse->add(keyAction.c_str(), req);
  1889. if (!hEvent) {
  1890. std::cerr << "Failed to open shared event" << std::endl;
  1891. }
  1892. else {
  1893. hEvent->SetEvent();
  1894. }
  1895. //CloseHandle(hEvent);
  1896. pRequests->eraseOneOf(keyAction.c_str(), 0);
  1897. pLock->Thread_UnLock();
  1898. //MQTTAsync_freeMessage(&message);
  1899. //MQTTAsync_free(topicName);
  1900. return ;
  1901. }
  1902. }
  1903. }
  1904. std::cout << CurrentDateTime() << "msgarrivd:: TID [" << GetCurrentThreadId() << "] " << client_id << " Go on Process " << topic << endl;
  1905. pLock->Thread_UnLock();
  1906. ccos_mqtt_callback onmsg = std::get<USER_MSG_CAKBCK_ID>(*connection);
  1907. if (onmsg != nullptr)
  1908. (onmsg)(&req, topic.c_str(), connection);
  1909. else
  1910. {
  1911. ////mLog::FWARN("TID {$} : {$} USER_MSG_CAKBCK_ID is null {$} ", GetCurrentThreadId(), std::get<CLINET_ID_ID>(*connection), topic);
  1912. cout << "**** ----- **** USER_MSG_CAKBCK_ID is null" << std::get<CLINET_ID_ID>(*connection) << " When processing " << topic << endl;
  1913. }
  1914. //MQTTAsync_freeMessage(&message);
  1915. //MQTTAsync_free(topicName);
  1916. return ;
  1917. }
  1918. void* MqttSendThreadFunc(void* pPara)
  1919. {
  1920. ccos_mqtt_connection* connection = (ccos_mqtt_connection*)pPara;
  1921. CcosLock* pLock = std::get<CONN_SEND_LOCK_ID>(*connection);
  1922. mqtt_msg_list* pList = std::get<MSG_LIST_ID>(*connection);
  1923. mqtt_client* pConn = (mqtt_client*)std::get<MQTT_CLT_ID>(*connection);
  1924. std::string client_id = std::get<CLINET_ID_ID>(*connection);
  1925. sem_t* hSemaphore = std::get<SEMAPHORE_HANDLE_ID>(*connection);
  1926. // 线程启动日志
  1927. std::cout << "[" << client_id << "] The MQTT sending thread is started" << std::endl;
  1928. while (std::get<THREAD_RUNNING_ID>(*connection)) {
  1929. struct timespec ts;
  1930. clock_gettime(CLOCK_REALTIME, &ts);
  1931. ts.tv_sec += 1;
  1932. // 等待信号量前的日志
  1933. //std::cout << "[" << client_id << "] Wait for the message semaphore..." << std::endl;
  1934. if (sem_timedwait(hSemaphore, &ts) == 0) {
  1935. std::cout << "[" << client_id << "] Received the message semaphore and ready to process the message" << std::endl;
  1936. pLock->Thread_Lock();
  1937. std::cout << "[" << client_id << "] Successfully obtained the sending lock" << std::endl;
  1938. if (pList->empty()) {
  1939. std::cout << "[" << client_id << "] The message list is empty, release the lock." << std::endl;
  1940. pLock->Thread_UnLock();
  1941. continue;
  1942. }
  1943. ResDataObject* pMsg = pList->front();
  1944. pList->pop_front();
  1945. std::cout << "[" << client_id << "] Get a message from the message list, the number of remaining messages: " << pList->size() << std::endl;
  1946. for (int x = 0; x < pMsg->size(); x++) {
  1947. const char* pTopic = pMsg->GetKey(x);
  1948. std::string message = (std::string)(*pMsg)[pTopic];
  1949. std::cout << "[" << client_id << "] Prepare to publish messages to the topic: " << pTopic
  1950. << ", Message length: " << message.length() << "Byte" << std::endl;
  1951. mqtt_message_t msg;
  1952. memset(&msg, 0, sizeof(msg));
  1953. msg.payload = (void*)message.c_str();
  1954. msg.payloadlen = message.length();
  1955. msg.qos = QOS1;
  1956. // 发布消息
  1957. int publishResult = mqtt_publish(pConn, pTopic, &msg);
  1958. if (publishResult == 0) {
  1959. std::cout << "[" << client_id << "] Message published successfully to the topic: " << pTopic << std::endl;
  1960. }
  1961. else {
  1962. std::cout << "[" << client_id << "] Message publishing failed to the topic: " << pTopic
  1963. << ", Error code: " << publishResult << std::endl;
  1964. }
  1965. }
  1966. delete pMsg;
  1967. std::cout << "[" << client_id << "] The message processing is completed, and the message object has been released." << std::endl;
  1968. pLock->Thread_UnLock();
  1969. std::cout << "[" << client_id << "] Release the sending lock" << std::endl;
  1970. }
  1971. else if (errno == ETIMEDOUT) {
  1972. //std::cout << "[" << client_id << "] The semaphore wait timed out, continue waiting." << std::endl;
  1973. }
  1974. else {
  1975. // 其他错误情况
  1976. std::cout << "[" << client_id << "] Semaphore wait error, error code: " << errno << std::endl;
  1977. }
  1978. }
  1979. return NULL;
  1980. }
  1981. // 安全遍历MQTT消息处理程序的宏
  1982. #define mqtt_list_for_each_entry_safe(pos, n, head, member) \
  1983. for (pos = container_of((head)->next, typeof(*pos), member), \
  1984. n = container_of(pos->member.next, typeof(*pos), member); \
  1985. &pos->member != (head); \
  1986. pos = n, n = container_of(n->member.next, typeof(*n), member))
  1987. // 通过成员指针获取包含结构的指针
  1988. #define container_of(ptr, type, member) ({ \
  1989. const typeof(((type*)0)->member)* __mptr = (ptr); \
  1990. (type*)((char*)__mptr - offsetof(type, member)); })
  1991. // 重连回调函数 - 实现自动重订阅
  1992. static void reconnect_handler(void* client, void* reconnect_data) {
  1993. mqtt_client_t* c = (mqtt_client_t*)client;
  1994. message_handlers_t* pos, * n;
  1995. ccos_mqtt_connection* connection = (ccos_mqtt_connection*)c->mqtt_conn_context;
  1996. // 遍历所有已订阅的主题并重新订阅
  1997. CcosLock* pLock = std::get<CONN_SEND_LOCK_ID>(*connection);
  1998. pLock->Thread_Lock();
  1999. mqtt_list_for_each_entry_safe(pos, n, &c->mqtt_msg_handler_list, list) {
  2000. mqtt_subscribe(c, pos->topic_filter, pos->qos, pos->handler);
  2001. }
  2002. pLock->Thread_UnLock();
  2003. }
  2004. mqtt_client_t* InnerConnect(ccos_mqtt_connection* connection) {
  2005. std::cout << "[MQTT] Acquiring MQTT client instance..." << std::endl;
  2006. mqtt_client_t* pMqttClient = mqtt_lease();
  2007. if (!pMqttClient) {
  2008. std::cerr << "[ERROR] Failed to acquire MQTT client instance" << std::endl;
  2009. return nullptr;
  2010. }
  2011. std::cout << "[SUCCESS] MQTT client acquired: " << pMqttClient << std::endl;
  2012. // 确保 connection 指针有效(避免后续访问悬空指针)
  2013. if (!connection) {
  2014. std::cerr << "[ERROR] Invalid connection context (nullptr)" << std::endl;
  2015. mqtt_release(pMqttClient); // 释放客户端
  2016. return nullptr;
  2017. }
  2018. std::get<MQTT_CLT_ID>(*connection) = pMqttClient;
  2019. pMqttClient->mqtt_conn_context = connection;
  2020. std::string pszClientID = std::get<CLINET_ID_ID>(*connection);
  2021. std::cout << "[CONFIG] Setting connection parameters:"
  2022. << "\n\tClient ID: " << (!pszClientID.empty() ? pszClientID : "null")
  2023. << "\n\tHost: " << SERVER_ADDRESS
  2024. << "\n\tPort: 1883"
  2025. << std::endl;
  2026. // 设置MQTT连接参数
  2027. std::string host_str = SERVER_ADDRESS;
  2028. char* host_buf = new char[host_str.size() + 1];
  2029. strncpy(host_buf, host_str.c_str(), host_str.size() + 1);
  2030. mqtt_set_host(pMqttClient, host_buf);
  2031. char port_buf[6] = "1883";
  2032. uint8_t clean_session = 1;
  2033. uint16_t keep_alive = 50;
  2034. mqtt_set_port(pMqttClient, port_buf);
  2035. mqtt_set_user_name(pMqttClient, const_cast<char*>("zskkcc"));
  2036. mqtt_set_password(pMqttClient, const_cast<char*>("zskk1234"));
  2037. mqtt_set_client_id(pMqttClient, (char*)pszClientID.c_str());
  2038. mqtt_set_clean_session(pMqttClient, 0);
  2039. mqtt_set_keep_alive_interval(pMqttClient, keep_alive);
  2040. mqtt_set_cmd_timeout(pMqttClient, 5000);
  2041. mqtt_set_write_buf_size(pMqttClient, 4096+1);
  2042. mqtt_set_read_buf_size(pMqttClient, 4096+1);
  2043. // 设置重连回调(替代mqtt_set_resubscribe_handler)
  2044. //mqtt_subscribe();
  2045. mqtt_set_reconnect_handler(pMqttClient, reconnect_handler);
  2046. int rc = 0;
  2047. uint64_t start_time = GetTickCount();
  2048. const uint64_t timeout_ms = 10000; // 10秒超时
  2049. int attempt_count = 0;
  2050. std::cout << "[CONNECT] Initiating connection (timeout: " << timeout_ms << "ms)..." << std::endl;
  2051. try {
  2052. while (true) {
  2053. attempt_count++;
  2054. std::cout << "[ATTEMPT #" << attempt_count << "] Trying MQTT connect..." << std::endl;
  2055. rc = mqtt_connect(pMqttClient);
  2056. if (rc != MQTT_SUCCESS_ERROR) {
  2057. uint64_t elapsed = GetTickCount() - start_time;
  2058. std::cerr << "[ERROR] Connection failed (code: " << rc << "), Elapsed: " << elapsed << "ms" << std::endl;
  2059. if (elapsed > timeout_ms) {
  2060. // 超时处理
  2061. std::cerr << "[FATAL] Connection timeout after " << timeout_ms << "ms" << std::endl;
  2062. delete[] host_buf;
  2063. mqtt_release(pMqttClient);
  2064. return nullptr;
  2065. }
  2066. // 计算剩余时间
  2067. uint64_t remaining = timeout_ms - elapsed;
  2068. uint64_t wait_time = (remaining > 2000) ? 2000 : remaining;
  2069. std::cout << "[RETRY] Waiting " << wait_time << "ms before next attempt..." << std::endl;
  2070. usleep(wait_time * 1000);
  2071. }
  2072. else {
  2073. uint64_t total_time = GetTickCount() - start_time;
  2074. std::cout << "[SUCCESS] Connected in " << total_time << "ms after " << attempt_count << " attempts" << std::endl;
  2075. break;
  2076. }
  2077. }
  2078. }
  2079. catch (const std::exception& e) {
  2080. std::cerr << "[ERROR] " << e.what() << std::endl;
  2081. delete[] host_buf;
  2082. mqtt_release(pMqttClient);
  2083. return nullptr;
  2084. }
  2085. return pMqttClient;
  2086. }
  2087. ccos_mqtt_connection* LogicDevice::NewConnection(const char* pszServer,const char* pszServerPort, const char* pszUserName, const char* pszPassword, const char* pszClientID, ccos_mqtt_callback onmsg)
  2088. {
  2089. ////mLog::FINFO("TID {$} : {$} NewConnection {$}:{$} user: {$} password {$} ", GetCurrentThreadId(), pszClientID, pszServer, pszServerPort, pszUserName, pszPassword);
  2090. std::cout << "TID " << GetCurrentThreadId()
  2091. << " : " << pszClientID
  2092. << " NewConnection " << pszServer
  2093. << ":" << pszServerPort
  2094. << " user: " << pszUserName
  2095. << " password " << pszPassword
  2096. << std::endl;
  2097. //连接MQTT broker
  2098. DWORD dwTick = GetTickCount();
  2099. ccos_mqtt_connection* connection = new ccos_mqtt_connection;
  2100. // 初始化元组字段
  2101. std::get<MQTT_TIPIC_LIST_ID>(*connection) = new mqtt_topic_list;
  2102. std::get<CLINET_ID_ID>(*connection) = pszClientID;
  2103. std::get<USER_MSG_CAKBCK_ID>(*connection) = onmsg;
  2104. CcosLock* pLock = new CcosLock();
  2105. std::get<CONN_SEND_LOCK_ID>(*connection) = pLock;
  2106. pLock->Thread_Lock();
  2107. ccos_mqtt_msg_filter* pfilter = new ccos_mqtt_msg_filter;
  2108. std::get<FILTER_FUNC_ID>(*pfilter) = nullptr;
  2109. std::get<FILTER_RES_OBJ_ID>(*pfilter) = new ResDataObject;
  2110. std::get<FILTER_RESPONS_OBJ_ID>(*pfilter) = new ResDataObject;
  2111. std::get<MSG_HOOK_ID>(*connection) = pfilter;
  2112. std::cout << "ALLOCATE Connection [" << (UINT64) connection << "] filter [" << (UINT64)pfilter << "] .. for " << pszClientID << endl;
  2113. mqtt_client* pMqttClient = InnerConnect(connection);
  2114. if (pMqttClient == nullptr)
  2115. {
  2116. pLock->Thread_UnLock();
  2117. delete connection;
  2118. delete pfilter;
  2119. return nullptr;
  2120. }
  2121. std::get<MQTT_CLT_ID>(*connection) = pMqttClient;
  2122. //pMqttClient->mqtt_conn_context = connection;
  2123. //设置MQTT连接参数
  2124. //mqtt_set_port(pMqttClient, (char*)pszServerPort);
  2125. //mqtt_set_host(pMqttClient, (char*)pszServer);
  2126. //sprintf(szClentName, "%s_%d_%d", server ? "MQTT_TEST_SERVER" : "TEST_CLIENT", GetCurrentProcessId(), xc);
  2127. //mqtt_set_client_id(pMqttClient, (char*)pszClientID);
  2128. //mqtt_set_user_name(pMqttClient, (char*)pszUserName);
  2129. //mqtt_set_password(pMqttClient, (char*)pszPassword);
  2130. //mqtt_set_clean_session(pMqttClient, 1);
  2131. //mqtt_set_version(pMqttClient, 5);
  2132. //mqtt_set_resubscribe_handler(pMqttClient, resubscribe_topic);
  2133. //mqtt_set_write_buf_size(pMqttClient, 8192);
  2134. //mqtt_set_read_buf_size(pMqttClient, 8192);
  2135. //mqtt_set_write_buf_size(pMqttClient, MQTT_DEFAULT_BUF_SIZE);
  2136. //mqtt_set_read_buf_size(pMqttClient, MQTT_DEFAULT_BUF_SIZE);
  2137. //if (pszUserName != nullptr && strlen(pszUserName) > 0)
  2138. // conn_opts.username = pszUserName;
  2139. //if (pszPassword != nullptr && strlen(pszPassword) > 0)
  2140. // conn_opts.password = pszPassword;
  2141. //设置回调函数
  2142. /*
  2143. int rc = 0;
  2144. dwTick = GetTickCount();
  2145. while (true)
  2146. {
  2147. int rc = mqtt_connect(pMqttClient);
  2148. if (rc != MQTT_SUCCESS_ERROR)
  2149. {
  2150. //默认10s内尝试
  2151. if (GetTickCount() - dwTick > 10000)
  2152. {
  2153. ////mLog::FINFO(" TID {$} {$} Failed 1 to connect to the MQTT server... {$} return : ", GetCurrentThreadId(), pszClientID, rc);
  2154. pLock->Thread_UnLock();
  2155. delete connection;
  2156. delete pfilter;
  2157. return nullptr;
  2158. }
  2159. else
  2160. {
  2161. ////mLog::FINFO(" TID {$} {$} Failed 1 to connect to the MQTT server Try again 2s later...... {$} return : ", GetCurrentThreadId(), pszClientID, rc);
  2162. //std::cout << CurrentDateTime() << " TID [" << GetCurrentThreadId() << "] Failed 1 to connect to the MQTT server Try again 2s later...【" << pszClientID << "】error : " << rc << endl;
  2163. Sleep(2000);
  2164. }
  2165. }
  2166. else
  2167. {
  2168. break;
  2169. }
  2170. }
  2171. */
  2172. std::get<MSG_LIST_ID>(*connection) = new mqtt_msg_list;
  2173. // 创建POSIX信号量
  2174. sem_t* semaphore = new sem_t;
  2175. sem_init(semaphore, 0, 0);
  2176. std::get<SEMAPHORE_HANDLE_ID>(*connection) = semaphore;
  2177. // 创建发送线程
  2178. pthread_t threadId;
  2179. if (pthread_create(&threadId, NULL, MqttSendThreadFunc, connection) != 0) {
  2180. std::cerr << "Failed to create MQTT send thread" << std::endl;
  2181. // 错误处理...
  2182. sem_destroy(semaphore);
  2183. delete semaphore;
  2184. pLock->Thread_UnLock();
  2185. delete connection;
  2186. return nullptr;
  2187. }
  2188. std::get<CONNECTED_HANDLE_ID>(*connection) = threadId;
  2189. std::get<THREAD_RUNNING_ID>(*connection) = true;
  2190. std::cout << "MqttSendThreadFunc thread id [" << threadId << "]" << std::endl;
  2191. pLock->Thread_UnLock();
  2192. uint64_t dwWaitTick = GetTickCount() - dwTick;
  2193. std::cout << "MQTT " << pszClientID << " try ConnMqtt Succeeded. Use Time: "
  2194. << dwWaitTick << " ms" << std::endl;
  2195. return connection;
  2196. }
  2197. //创建额外连接,需要提供回调函数
  2198. LOGICDEVICE_API ccos_mqtt_connection* NewConnection(const char* pszClientID, ccos_mqtt_callback onmsg, DWORD dwOpenTimeout, bool async)
  2199. {
  2200. DWORD dwTick = GetTickCount();
  2201. ////mLog::FINFO("TID {$} : {$} NewConnection2 {$}:{$} ", GetCurrentThreadId(), pszClientID, SERVER_ADDRESS, 1883);
  2202. //mqtt_client* pMqttClient = nullptr;
  2203. //pMqttClient = mqtt_lease();
  2204. ccos_mqtt_connection* connection = new ccos_mqtt_connection;
  2205. //HANDLE hConneted = CreateEvent(NULL, FALSE, FALSE, NULL);
  2206. //std::get<MQTT_CLT_ID>(*connection) = pMqttClient;
  2207. mqtt_topic_list* pTopicList = new std::list<string>;
  2208. std::get<MQTT_TIPIC_LIST_ID>(*connection) = pTopicList;
  2209. CcosLock* pLock = new CcosLock();
  2210. std::get<CONN_SEND_LOCK_ID>(*connection) = pLock;
  2211. pLock->Thread_Lock();
  2212. ccos_mqtt_msg_filter* pfilter = new ccos_mqtt_msg_filter;
  2213. std::get<FILTER_FUNC_ID>(*pfilter) = nullptr;
  2214. std::get<MSG_HOOK_ID>(*connection) = pfilter;
  2215. std::get<FILTER_RES_OBJ_ID>(*pfilter) = new ResDataObject;
  2216. std::get<FILTER_RESPONS_OBJ_ID>(*pfilter) = new ResDataObject;
  2217. std::cout << "ALLOCATE Connection 2 [" << (UINT64)connection << "] filter [" << (UINT64)pfilter << "] ..for " << pszClientID << endl;
  2218. std::get<CLINET_ID_ID>(*connection) = pszClientID;
  2219. std::get< USER_MSG_CAKBCK_ID>(*connection) = onmsg;
  2220. mqtt_client* pMqttClient = InnerConnect(connection);
  2221. if (pMqttClient == nullptr)
  2222. {
  2223. pLock->Thread_UnLock();
  2224. delete connection;
  2225. delete pfilter;
  2226. return nullptr;
  2227. }
  2228. std::get<MQTT_CLT_ID>(*connection) = pMqttClient;
  2229. //pMqttClient->mqtt_conn_context = connection;
  2230. //设置回调函数
  2231. //设置MQTT连接参数
  2232. //mqtt_set_resubscribe_handler(pMqttClient, resubscribe_topic);
  2233. /*
  2234. //连接Broker
  2235. int rc = 0;
  2236. dwTick = GetTickCount();
  2237. while (true)
  2238. {
  2239. rc = mqtt_connect(pMqttClient);
  2240. if (rc != MQTT_SUCCESS_ERROR)
  2241. {
  2242. if (GetTickCount() - dwTick > dwOpenTimeout)
  2243. {
  2244. ////mLog::FINFO(" TID {$} {$} Failed 2 to connect to the MQTT server... {$} return : ", GetCurrentThreadId(), pszClientID, rc);
  2245. pLock->Thread_UnLock();
  2246. delete connection;
  2247. delete pfilter;
  2248. return nullptr;
  2249. }
  2250. else
  2251. {
  2252. ////mLog::FINFO(" TID {$} {$} Failed 2 to connect to the MQTT server Try again 20ms later...... {$} return : ", GetCurrentThreadId(), pszClientID, rc);
  2253. //std::cout << CurrentDateTime() << " TID [" << GetCurrentThreadId() << "] Failed to connect to the MQTT server Try again 2s later..." << pszClientID << endl;
  2254. Sleep(20);
  2255. }
  2256. }
  2257. else
  2258. {
  2259. break;
  2260. }
  2261. }*/
  2262. DWORD dwWaitTick = GetTickCount() - dwTick;
  2263. ////mLog::FWARN("MQTT {$} try ConnMqtt Succecced Use Time ****** {$} ms*** wait: {$} ms*** TID ", pszClientID, GetTickCount() - dwTick, dwWaitTick, GetCurrentThreadId());
  2264. std::get<MSG_LIST_ID>(*connection) = new mqtt_msg_list;
  2265. // 创建POSIX信号量
  2266. sem_t* semaphore = new sem_t;
  2267. sem_init(semaphore, 0, 0);
  2268. std::get<SEMAPHORE_HANDLE_ID>(*connection) = semaphore;
  2269. // 创建发送线程
  2270. pthread_t threadId;
  2271. if (pthread_create(&threadId, NULL, MqttSendThreadFunc, connection) != 0) {
  2272. std::cerr << "Failed to create MQTT send thread" << std::endl;
  2273. // 错误处理...
  2274. sem_destroy(semaphore);
  2275. delete semaphore;
  2276. pLock->Thread_UnLock();
  2277. delete connection;
  2278. return nullptr;
  2279. }
  2280. std::get<CONNECTED_HANDLE_ID>(*connection) = threadId;
  2281. std::get<THREAD_RUNNING_ID>(*connection) = true;
  2282. std::cout << "MqttSendThreadFunc thread id [" << threadId << "]" << std::endl;
  2283. pLock->Thread_UnLock();
  2284. std::cout << "MQTT " << pszClientID << " try ConnMqtt Succeeded. Use Time: "
  2285. << dwWaitTick << " ms" << std::endl;
  2286. return connection;
  2287. }
  2288. //重置连接
  2289. LOGICDEVICE_API void ResetConnection(ccos_mqtt_connection* hConnection)
  2290. {
  2291. if (hConnection == nullptr)
  2292. {
  2293. return;
  2294. }
  2295. ////mLog::FWARN(" Reset Mqtt Connection..", std::get<CLINET_ID_ID>(*hConnection));
  2296. std::cout << CurrentDateTime() << std::get<CLINET_ID_ID>(*hConnection) << " Close Mqtt Connection.." << endl;
  2297. mqtt_client* pconn = (mqtt_client*)std::get<MQTT_CLT_ID>(*hConnection);
  2298. if (pconn != nullptr) {
  2299. CcosLock* pLock = std::get<CONN_SEND_LOCK_ID>(*hConnection);
  2300. pLock->Thread_Lock();
  2301. //mqtt_do_reconnect(pconn);
  2302. mqtt_disconnect(pconn);
  2303. /*mqtt_set_resubscribe_handler(pconn, resubscribe_topic);
  2304. mqtt_connect(pconn);*/
  2305. mqtt_release(pconn);
  2306. pconn = InnerConnect(hConnection);
  2307. int rc = MQTT_SUCCESS_ERROR;// mqtt_connect(pconn);
  2308. if (pconn != nullptr)
  2309. {
  2310. //std::get<MQTT_CLT_ID>(*hConnection) = pconn;
  2311. //resubscribe_topic(pconn, pconn->mqtt_conn_context);
  2312. //////mLog::FWARN("mqtt_connect ret {$} do mqtt resubscribe {$}", rc, std::get<CLINET_ID_ID>(*hConnection));
  2313. }
  2314. pLock->Thread_UnLock();
  2315. }
  2316. }
  2317. //关闭并释放连接
  2318. LOGICDEVICE_API void CloseConnection(ccos_mqtt_connection* hConnection)
  2319. {
  2320. if (!hConnection) return;
  2321. auto clientId = std::get<CLINET_ID_ID>(*hConnection);
  2322. std::cout << CurrentDateTime() << clientId << " Close Mqtt Connection.." << endl;
  2323. std::get<THREAD_RUNNING_ID>(*hConnection) = false;
  2324. sem_t* semaphore = std::get<SEMAPHORE_HANDLE_ID>(*hConnection);
  2325. if (semaphore) {
  2326. sem_post(semaphore); // 发送信号量唤醒线程
  2327. }
  2328. pthread_t sendThread = std::get<CONNECTED_HANDLE_ID>(*hConnection);
  2329. if (sendThread != 0) {
  2330. // 等待线程退出,超时时间设为1秒
  2331. struct timespec timeout;
  2332. clock_gettime(CLOCK_REALTIME, &timeout);
  2333. timeout.tv_sec += 1;
  2334. int joinResult = pthread_timedjoin_np(sendThread, nullptr, &timeout);
  2335. if (joinResult != 0) {
  2336. std::cerr << CurrentDateTime() << " " << clientId
  2337. << " Warning: Send thread did not exit in time, force cancel" << std::endl;
  2338. pthread_cancel(sendThread); // 超时后强制终止(最后的备选方案)
  2339. pthread_join(sendThread, nullptr);
  2340. }
  2341. std::get<CONNECTED_HANDLE_ID>(*hConnection) = 0; // 重置线程ID
  2342. }
  2343. CcosLock* pLock = std::get<CONN_SEND_LOCK_ID>(*hConnection);
  2344. if (nullptr != pLock)
  2345. pLock->Thread_Lock();
  2346. else
  2347. return;
  2348. mqtt_client* pMqttClient = static_cast<mqtt_client*>(std::get<MQTT_CLT_ID>(*hConnection));
  2349. if (pMqttClient) {
  2350. mqtt_disconnect(pMqttClient); // 断开连接
  2351. mqtt_release(pMqttClient); // 释放客户端实例
  2352. pMqttClient = NULL;
  2353. std::get<MQTT_CLT_ID>(*hConnection) = nullptr;
  2354. }
  2355. ccos_mqtt_msg_filter* pFilter = static_cast<ccos_mqtt_msg_filter*>(std::get<MSG_HOOK_ID>(*hConnection));
  2356. if (pFilter) {
  2357. std::cout << "Free Connection filter [" << (UINT64)pFilter << "] .." << std::endl;
  2358. // 释放filter内部的资源对象
  2359. delete std::get<FILTER_RES_OBJ_ID>(*pFilter);
  2360. delete std::get<FILTER_RESPONS_OBJ_ID>(*pFilter);
  2361. delete pFilter;
  2362. std::get<MSG_HOOK_ID>(*hConnection) = nullptr;
  2363. }
  2364. mqtt_msg_list* pMsgList = std::get<MSG_LIST_ID>(*hConnection);
  2365. if (pMsgList) {
  2366. // 清理剩余未发送的消息
  2367. while (!pMsgList->empty()) {
  2368. ResDataObject* pMsg = pMsgList->front();
  2369. pMsgList->pop_front();
  2370. delete pMsg; // 释放消息对象
  2371. }
  2372. delete pMsgList;
  2373. std::get<MSG_LIST_ID>(*hConnection) = nullptr;
  2374. }
  2375. if (semaphore) {
  2376. sem_destroy(semaphore); // 销毁信号量
  2377. delete semaphore;
  2378. std::get<SEMAPHORE_HANDLE_ID>(*hConnection) = nullptr;
  2379. }
  2380. mqtt_topic_list* pTopicList = std::get<MQTT_TIPIC_LIST_ID>(*hConnection);
  2381. if (pTopicList) {
  2382. pTopicList->clear(); // 清空列表
  2383. delete pTopicList;
  2384. std::get<MQTT_TIPIC_LIST_ID>(*hConnection) = nullptr;
  2385. }
  2386. if (pLock) {
  2387. pLock->Thread_UnLock(); // 确保锁被释放
  2388. delete pLock;
  2389. std::get<CONN_SEND_LOCK_ID>(*hConnection) = nullptr;
  2390. }
  2391. delete hConnection;
  2392. std::cout << CurrentDateTime() << clientId << " Close Mqtt Connection over.." << endl;
  2393. }
  2394. //主动订阅主题
  2395. LOGICDEVICE_API int SubscribeTopic(ccos_mqtt_connection* hConnection, const char* pszTopic, bool isShare)
  2396. {
  2397. if (hConnection == nullptr)
  2398. {
  2399. return 0;
  2400. }
  2401. mqtt_client* pMqttClient = (mqtt_client*)std::get<MQTT_CLT_ID>(*hConnection);
  2402. mqtt_topic_list* pTopicList = std::get<MQTT_TIPIC_LIST_ID>(*hConnection);
  2403. CcosLock* pLock = std::get<CONN_SEND_LOCK_ID>(*hConnection);
  2404. pLock->Thread_Lock();
  2405. pTopicList->push_back(std::string(pszTopic));
  2406. //pMqttClient->subscribe(pszTopic, 1, opts);
  2407. int rc = MQTT_SUCCESS_ERROR;
  2408. DWORD dwTick = GetTickCount();
  2409. int nTryTimes = 0;
  2410. do
  2411. {
  2412. if (pTopicList->size() < 1)
  2413. {
  2414. const char* topicToSubscribe = pTopicList->back().c_str();
  2415. int ret = mqtt_subscribe(pMqttClient, topicToSubscribe, MQTT_QOS, msgarrivd);
  2416. //int ret = mqtt_subscribe(pMqttClient, pszTopic, MQTT_QOS, msgarrivd);
  2417. ////mLog::FWARN("mqtt {$} Subscribe First {$} return {$} topic num {$}", std::get<CLINET_ID_ID>(*hConnection), pszTopic, ret, pTopicList->size());
  2418. std::cout << "mqtt [" << std::get<CLINET_ID_ID>(*hConnection) << " ]Subscribe First " << pszTopic << endl;
  2419. }
  2420. else
  2421. {
  2422. const char* topicToSubscribe = pTopicList->back().c_str();
  2423. int ret = mqtt_subscribe(pMqttClient, topicToSubscribe, MQTT_QOS, msgarrivd);
  2424. //int ret = mqtt_subscribe(pMqttClient, pszTopic, MQTT_QOS, msgarrivd);
  2425. ////mLog::FWARN("mqtt {$} Subscribe ReUse {$} topic num {$}", std::get<CLINET_ID_ID>(*hConnection), pszTopic, ret, pTopicList->size());
  2426. std::cout << "mqtt [" << std::get<CLINET_ID_ID>(*hConnection) << " ]Subscribe ReUse " << pszTopic << endl;
  2427. }
  2428. if (rc != MQTT_SUCCESS_ERROR)
  2429. {
  2430. ////mLog::FWARN("try do mqtt reconnect ..");
  2431. //mqtt_do_reconnect(pMqttClient);
  2432. mqtt_disconnect(pMqttClient);
  2433. //mqtt_set_resubscribe_handler(pMqttClient, resubscribe_topic);
  2434. mqtt_release(pMqttClient);
  2435. pMqttClient = InnerConnect(hConnection);
  2436. int rc = MQTT_SUCCESS_ERROR;// mqtt_connect(pconn);
  2437. if (pMqttClient != nullptr)
  2438. {
  2439. //std::get<MQTT_CLT_ID>(*hConnection) = pMqttClient;
  2440. //resubscribe_topic(pMqttClient, pMqttClient->mqtt_conn_context);
  2441. //////mLog::FWARN("mqtt_connect ret {$} do mqtt resubscribe {$}", rc, std::get<CLINET_ID_ID>(*hConnection));
  2442. }
  2443. usleep(2000 * 1000);
  2444. }
  2445. } while (rc != MQTT_SUCCESS_ERROR && GetTickCount() - dwTick < 100);
  2446. pLock->Thread_UnLock();
  2447. return 0;
  2448. }
  2449. //主题订阅取消
  2450. LOGICDEVICE_API int UnSubscribe(ccos_mqtt_connection* hConnection, const char* pszTopic)
  2451. {
  2452. if (hConnection == nullptr)
  2453. {
  2454. return 0;
  2455. }
  2456. mqtt_client* pMqttClient = (mqtt_client*)std::get<MQTT_CLT_ID>(*hConnection);
  2457. //if (!pMqttClient->is_connected()) {
  2458. // //////mLog::FERROR( " MQTT connection lost at subscribe %s ", topic);
  2459. // return 0;
  2460. //}
  2461. //MQTTSubscribe_options opts = MQTTSubscribe_options_initializer;
  2462. //auto ret = pMqttClient->unsubscribe(pszTopic);
  2463. mqtt_topic_list* pTopicList = std::get<MQTT_TIPIC_LIST_ID>(*hConnection);
  2464. CcosLock* pLock = std::get<CONN_SEND_LOCK_ID>(*hConnection);
  2465. pLock->Thread_Lock();
  2466. //MQTTAsync_responseOptions resp;
  2467. pTopicList->remove(pszTopic);
  2468. int rc = MQTT_SUCCESS_ERROR;
  2469. DWORD dwTick = GetTickCount();
  2470. int nTryTimes = 0;
  2471. do
  2472. {
  2473. int ret = mqtt_unsubscribe(pMqttClient, pszTopic);
  2474. ////mLog::FWARN("mqtt {$} Unsubscribe {$} return {$}", std::get<CLINET_ID_ID>(*hConnection), pszTopic, ret);
  2475. } while (rc != MQTT_SUCCESS_ERROR && GetTickCount() - dwTick < 100);
  2476. pLock->Thread_UnLock();
  2477. return 2;
  2478. }
  2479. //往指定主题发送CCOS协议包整包,使用临时创建连接,仅发送,不接收
  2480. LOGICDEVICE_API int PublishMsg(ResDataObject* pCmd, const char* pszTopic, const char* pszSenderName, DWORD dwTimeout)
  2481. {
  2482. char pszClientID[256];
  2483. snprintf(pszClientID, sizeof(pszClientID), "TEMP_%s_%d_0X%08lX",
  2484. (pszSenderName == nullptr) ? "ANONYMOUS" : pszSenderName,
  2485. getpid(), GetCurrentThreadId());
  2486. ccos_mqtt_connection* connObj = NewConnection(pszClientID, [](ResDataObject*, const char*, void* conn) {
  2487. });
  2488. mqtt_client* pConn = (mqtt_client*)std::get<MQTT_CLT_ID>(*connObj);
  2489. PacketAnalizer::UpdatePacketTopic(pCmd, pszTopic, pszClientID);
  2490. //MQTTAsync_responseOptions resp = MQTTAsync_responseOptions_initializer;
  2491. string pLoad = pCmd->encode();
  2492. int rc = PublishActionWithoutLock(pLoad, pszTopic, pConn, pszSenderName);
  2493. std::cout << "CLT [" << pszClientID << "] at " << CurrentDateTime() << " Publish to [" << pszTopic << "] result " << rc << endl;
  2494. ////mLog::FDEBUG("CLT {$} Publish to {$} send result {$}", pszClientID, pszTopic, rc);
  2495. CloseConnection(connObj);
  2496. return rc;
  2497. }
  2498. //往指定主题发送CCOS协议包整包,使用已创建的连接发送
  2499. LOGICDEVICE_API int PublishAction(ResDataObject* pAction, const char* pszTopic, ccos_mqtt_connection* hConnection, DWORD dwTimeout)
  2500. {
  2501. if (hConnection == nullptr)
  2502. {
  2503. ////mLog::FDEBUG("Who ????? Publish to {$} Action Body: {$}", pszTopic, pAction->encode());
  2504. std::cout << CurrentDateTime() << "Who ????? " << "Publish to [" << pszTopic << "] Action Body: "<< pAction->encode() << endl; //<< pAction->encode()
  2505. return 0;
  2506. }
  2507. std::cout << CurrentDateTime() << std::get<CLINET_ID_ID>(*hConnection) << " Publish Action to ["<< pszTopic << "] Action Body: " << endl; //<< pAction->encode()
  2508. string topic = pszTopic;
  2509. if (topic.length() <= 0)
  2510. {
  2511. ////mLog::FWARN("ignore empty topic packet {$}", pAction->encode());
  2512. return 2;
  2513. }
  2514. mqtt_client* pMqttClient = (mqtt_client*)std::get<MQTT_CLT_ID>(*hConnection);
  2515. //if (!pMqttClient->is_connected()) {
  2516. // //////mLog::FERROR( " MQTT connection lost at subscribe %s ", topic);
  2517. // return 0;
  2518. //}
  2519. std::string client_id = std::get<CLINET_ID_ID>(*hConnection);
  2520. CcosLock* pLock = std::get<CONN_SEND_LOCK_ID>(*hConnection);
  2521. pLock->Thread_Lock();
  2522. ////mLog::FDEBUG("{$} Publish Action to {$} Action Body: {$}", std::get<CLINET_ID_ID>(*hConnection), pszTopic, pAction->encode());
  2523. //string org_publisher = PacketAnalizer::GetPacketPublisher(pAction);
  2524. //if(org_publisher.length() <= 0)
  2525. PacketAnalizer::UpdatePacketTopic(pAction, pszTopic, client_id.c_str() );
  2526. ResDataObject* pPacket = new ResDataObject();
  2527. mqtt_msg_list* pList = std::get<MSG_LIST_ID>(*hConnection);
  2528. pPacket->add(pszTopic, pAction->encode());
  2529. ////mLog::FDEBUG(" {$} Try push packet to Send list: {$}", client_id, pPacket->encode());
  2530. pList->push_back(pPacket);
  2531. sem_post(std::get<SEMAPHORE_HANDLE_ID>(*hConnection));
  2532. std::cout << "try publish " << pAction->encode() << endl;
  2533. //pMqttClient->publish(pszTopic, pAction->encode());
  2534. /*
  2535. //pConn->publish(pszTopic, pCmd->encode());
  2536. std::cout << "try publish " << pAction->encode() << endl;
  2537. const char* pLoad = pAction->encode();
  2538. int len = strlen(pLoad);
  2539. //MQTTAsync_responseOptions resp;
  2540. //MQTTAsync_responseOptions resp = MQTTAsync_responseOptions_initializer;
  2541. mqtt_message_t msg;
  2542. memset(&msg, 0, sizeof(msg));
  2543. msg.payload = (void*)pLoad;
  2544. msg.qos = MQTT_QOS;
  2545. msg.payloadlen = len;
  2546. int rc = MQTT_SUCCESS_ERROR;
  2547. DWORD dwTick = GetTickCount();
  2548. int nTryTimes = 0;
  2549. do
  2550. {
  2551. rc = mqtt_publish(pMqttClient, pszTopic, &msg);
  2552. nTryTimes++;
  2553. if (rc != MQTT_SUCCESS_ERROR)
  2554. {
  2555. ////mLog::FINFO("try mqtt_publish ret {$} do mqtt reconnect .. {$}",rc, client_id);
  2556. //mqtt_do_reconnect(pMqttClient);
  2557. mqtt_disconnect(pMqttClient);
  2558. rc = mqtt_connect(pMqttClient);
  2559. if (rc == MQTT_SUCCESS_ERROR)
  2560. {
  2561. resubscribe_topic(pMqttClient, pMqttClient->mqtt_conn_context);
  2562. ////mLog::FINFO("mqtt_connect ret {$} do mqtt resubscribe {$}", rc, client_id);
  2563. }
  2564. Sleep(2);
  2565. }
  2566. } while (rc != MQTT_SUCCESS_ERROR && GetTickCount() - dwTick < dwTimeout);
  2567. //std::cout << "CLT [" << pszClientID << "] at " << CurrentDateTime() << " Publish to [" << pszTopic << "] result " << rc << endl;
  2568. ////mLog::FINFO("CLT {$} PublishAction to {$} send Times {$} result {$}", client_id, pszTopic, nTryTimes, rc);
  2569. //int rc = MQTTAsync_send(pMqttClient, pszTopic, len, pLoad, 0, 0, &resp);
  2570. //std::cout << "CLT [" << client_id << "] at " << CurrentDateTime() << " Use mqtt_client " << (UINT64)pMqttClient << " Publish to [" << pszTopic << "] Send result " << rc << endl;
  2571. if (rc < 0)
  2572. {
  2573. ////mLog::FERROR("{$} PublishAction failed {$} body: {$}", client_id, pszTopic, rc, pLoad);
  2574. //std::cout << " ErrorCode " << rc << " Send Msg : " << pLoad << endl;
  2575. pLock->Thread_UnLock();
  2576. return rc;
  2577. }*/
  2578. //MQTTResponse resp = MQTTClient_publish5(pMqttClient, pszTopic, strlen(pLoad), pLoad, 0, 0, NULL, NULL);
  2579. //std::cout << "CLT [" << client_id << "] at " << CurrentDateTime() << " Publish to [" << pszTopic << "] result " << resp.reasonCode << endl;
  2580. ////mLog::FDEBUG("CLT {$} PublishAction to {$} Send List has {$} packets ", client_id, pszTopic, pList->size());
  2581. pLock->Thread_UnLock();
  2582. return 2;
  2583. }
  2584. //往指定主题发送Action包,携带参数,并指定答复的Topic,异步模式处理Resp,需要在对应连接的回调中处理
  2585. int PublishActionWithoutLock(string& message, const char* pszTopic, mqtt_client* pMqttClient, std::string client_id, mqtt_qos_t qos)
  2586. {
  2587. const int dwTimeout = 500;
  2588. if (pMqttClient == nullptr)
  2589. {
  2590. ////mLog::FERROR("Who ????? Publish 2 to {$} Action {$} Body: {$}", pszTopic, message);
  2591. return 0;
  2592. }
  2593. ////mLog::FDEBUG("{$} Publish with qos[{$}] Action 2 to {$} Body: {$} ", client_id, (int)qos, pszTopic, message);
  2594. const char* pLoad = message.c_str();
  2595. int len = message.length();
  2596. mqtt_message_t msg;
  2597. memset(&msg, 0, sizeof(msg));
  2598. msg.payload = (void*)pLoad;
  2599. msg.payloadlen = len;
  2600. msg.qos = qos;
  2601. int rc = MQTT_SUCCESS_ERROR;
  2602. DWORD dwTick = GetTickCount();
  2603. int nTryTimes = 0;
  2604. do
  2605. {
  2606. rc = mqtt_publish(pMqttClient, pszTopic, &msg);
  2607. nTryTimes++;
  2608. if (rc != MQTT_SUCCESS_ERROR)
  2609. {
  2610. ////mLog::FWARN("try mqtt_publish ret {$} do mqtt reconnect .. {$}", rc, client_id);
  2611. usleep(10000 * 1000);
  2612. //mqtt_do_reconnect(pMqttClient);
  2613. ccos_mqtt_connection* hConnection = (ccos_mqtt_connection*)pMqttClient->mqtt_conn_context;
  2614. mqtt_disconnect(pMqttClient);
  2615. /*mqtt_set_resubscribe_handler(pMqttClient, resubscribe_topic);
  2616. mqtt_connect(pMqttClient);*/
  2617. mqtt_release(pMqttClient);
  2618. pMqttClient = InnerConnect(hConnection);
  2619. //int rc = MQTT_SUCCESS_ERROR;// mqtt_connect(pconn);
  2620. if (pMqttClient != nullptr)
  2621. {
  2622. //std::get<MQTT_CLT_ID>(*hConnection) = pMqttClient;
  2623. //resubscribe_topic(pMqttClient, hConnection);
  2624. //////mLog::FWARN("mqtt_connect ret {$} do mqtt resubscribe {$}", rc, std::get<CLINET_ID_ID>(*hConnection));
  2625. }
  2626. }
  2627. } while (rc != MQTT_SUCCESS_ERROR && (nTryTimes <= 2 || GetTickCount() - dwTick < dwTimeout));
  2628. if(nTryTimes > 1)
  2629. ////mLog::FWARN("CLT {$} PublishAction to {$} send Times {$} result {$}", client_id, pszTopic, nTryTimes, rc);
  2630. ////mLog::FDEBUG("CLT {$} PublishAction to {$} send Times {$} result {$}", client_id, pszTopic, nTryTimes, rc);
  2631. if (rc < 0)
  2632. {
  2633. ////mLog::FERROR("{$} PublishAction {$} failed {$} body: {$}", client_id, pszTopic, rc, pLoad);
  2634. return rc;
  2635. }
  2636. return 2;
  2637. }
  2638. /*
  2639. /// <summary>
  2640. /// 往指定主题发送Action包,携带参数,并指定答复的Topic,同步等待resp,
  2641. /// 超时没收到应答返回失败,
  2642. /// 复用链接时须小心,该函数会接管回调函数,结束后恢复
  2643. /// </summary>
  2644. /// <param name="pAction">要发送的命令Action名</param>
  2645. /// <param name="pContext">命令携带的参数</param>
  2646. /// <param name="pszTopic">要发送的目标topic</param>
  2647. /// <param name="pszRespTopic">本次请求的应答接收Topic</param>
  2648. /// <param name="resObj">应答返回的参数结果</param>
  2649. /// <param name="dwWaitTime">等待超时时间</param>
  2650. /// <param name="hConnection">复用的MQTT链接句柄</param>
  2651. /// <param name="onmsg">复用的链接的消息处理函数</param>
  2652. /// <returns>成功返回2,其他返回错误码</returns>
  2653. LOGICDEVICE_API int ActionAndRespWithConnection(ccos_mqtt_connection* hConnection, const char* pAction, ResDataObject& req, ResDataObject* pContext, const char* pszTopic, const char* pszRespTopic,
  2654. ResDataObject& resObj, DWORD dwWaitTime)
  2655. {
  2656. std::cout << CurrentDateTime() << std::get<CLINET_ID_ID>(*hConnection) << "\nAction2 : " << pAction << " to " << pszTopic << endl;// << "\n Action Body: " << " Context " << pContext->encode() << endl << endl; //<< req.encode()
  2657. if (pszRespTopic != nullptr)
  2658. PacketAnalizer::UpdateContextTopic(pContext, pszRespTopic);
  2659. if (hConnection == nullptr)
  2660. {
  2661. return 0;
  2662. }
  2663. mqtt_client* pMqttClient = (mqtt_client*)std::get<MQTT_CLT_ID>(*hConnection);
  2664. //if (!pMqttClient->is_connected()) {
  2665. // //////mLog::FERROR( " MQTT connection lost at subscribe %s ", topic);
  2666. // return 0;
  2667. //}
  2668. HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
  2669. //SubscribeTopic()
  2670. auto action_func = [&resObj, pszRespTopic, pMqttClient, hConnection, hEvent](void* context, char* topicName, int topicLen, MQTTClient_message* message) {
  2671. string topic = topicName;//msg->get_topic().c_str();
  2672. if (strcmp(pszRespTopic, topic.c_str()) == 0) {
  2673. std::cout << CurrentDateTime() << std::get<CLINET_ID_ID>(*hConnection) << " get Right Resp by " << topic << endl;
  2674. //应答到了,处理
  2675. ResDataObject req;
  2676. req.decode((const char*)message->payload);
  2677. PacketAnalizer::GetPacketContext(&req, resObj);
  2678. SetEvent(hEvent);
  2679. //处理结束 将函数指针换回去
  2680. void* oldFuncPointer = std::get<MQTT_MSG_ARRIVED_ID>(*hConnection);
  2681. //pMqttClient->set_message_callback(*(mqtt::async_client::message_handler*)oldFuncPointer);
  2682. MQTTAsync_setCallbacks(pMqttClient, hConnection, connlost, msgarrvd, NULL);
  2683. }
  2684. else
  2685. {
  2686. //MQTTClient_messageArrived *orgfunc = (MQTTClient_messageArrived*)std::get<MQTT_MSG_ARRIVED_ID>(*hConnection);
  2687. (msgarrvd)(context, topicName, topicLen, message);
  2688. }
  2689. };
  2690. //接管回调
  2691. // pMqttClient->set_message_callback(action_func);
  2692. MQTTClient_setCallbacks(pMqttClient, hConnection, connlost, (MQTTClient_messageArrived*)&action_func, delivered);
  2693. //pMqttClient->subscribe(pszRespTopic, 1);
  2694. MQTTSubscribe_options opts = MQTTSubscribe_options_initializer;
  2695. MQTTProperties prop = MQTTProperties_initializer;
  2696. std::cout << "mqtt 【" << std::get<CLINET_ID_ID>(*hConnection) << " 】Subscribe " << pszTopic << endl;
  2697. //pMqttClient->subscribe(pszTopic, 1, opts);
  2698. MQTTClient_subscribe5(pMqttClient, pszTopic, 1, NULL, NULL);
  2699. PacketAnalizer::UpdatePacketTopic(&req, pszTopic, std::get<CLINET_ID_ID>(*hConnection));
  2700. //pMqttClient->publish(pszTopic, req.encode());
  2701. MQTTClient_message pubmsg = MQTTClient_message_initializer;
  2702. MQTTClient_message* m = NULL;
  2703. MQTTClient_deliveryToken dt;
  2704. MQTTProperty property;
  2705. property.identifier = MQTTPROPERTY_CODE_USER_PROPERTY;
  2706. property.value.data.data = "test user property";
  2707. property.value.data.len = (int)strlen(property.value.data.data);
  2708. property.value.value.data = "test user property value";
  2709. property.value.value.len = (int)strlen(property.value.value.data);
  2710. MQTTProperties properties = MQTTProperties_initializer;
  2711. MQTTProperties_add(&properties, &property);
  2712. //pConn->publish(pszTopic, pCmd->encode());
  2713. const char* pLoad = req.encode();
  2714. MQTTResponse resp = MQTTClient_publish5(pMqttClient, pszTopic, strlen(pLoad), pLoad, 0, 0, &properties, &dt);
  2715. std::cout << "CLT [" << std::get<CLINET_ID_ID>(*hConnection) << "] at " << CurrentDateTime() << " Publish x to [" << pszTopic << "] result " << resp.reasonCode << endl;
  2716. DWORD ret = WaitForSingleObject(hEvent, dwWaitTime);
  2717. if (ret == WAIT_OBJECT_0) {
  2718. //等到应答了
  2719. return 2;
  2720. }
  2721. return 0;
  2722. }
  2723. */
  2724. /// <summary>
  2725. /// 往指定主题发送Action包,携带参数,复用Resp的Topic,同步等待resp,超时没收到应答返回失败,
  2726. /// </summary>
  2727. /// <param name="hConnection"></param>
  2728. /// <param name="pAction"></param>
  2729. /// <param name="pContext"></param>
  2730. /// <param name="pszTopic"></param>
  2731. /// <param name="resObj"></param>
  2732. /// <param name="hEvent"></param>
  2733. /// <param name="dwWaitTime"></param>
  2734. /// <returns></returns>
  2735. LOGICDEVICE_API int ActionAndRespWithConnDefalt(ccos_mqtt_connection* hConnection, const char* pAction, ResDataObject& req, ResDataObject* pContext,
  2736. const char* pszTopic, ResDataObject& resObj, DWORD dwWaitTime)
  2737. {
  2738. usleep(1000 * 1000);
  2739. std::cout << CurrentDateTime() << std::get<CLINET_ID_ID>(*hConnection) << "\nAction : " << pAction << " to " << pszTopic << "\n Action Body: " << " Context " << pContext->encode() << endl << endl; //<< req.encode()
  2740. if (hConnection == nullptr)
  2741. {
  2742. return 0;
  2743. }
  2744. DWORD dwTick = GetTickCount();
  2745. mqtt_client* pMqttClient = (mqtt_client*)std::get<MQTT_CLT_ID>(*hConnection);
  2746. std::shared_ptr<LinuxEvent> hEvent = LinuxEvent::CreateEvent(LinuxEvent::AUTO_RESET, false);
  2747. ResDataObject resContext;
  2748. string strResObject;
  2749. char* pszPad = 0;
  2750. char* pszPad2 = 0;
  2751. auto func = [pAction, hConnection, &pszPad, &resObj, &pszPad2, dwTick, dwWaitTime](ResDataObject* rsp) -> bool {
  2752. ////mLog::FINFO("{$} try check action resp {$} compared with {$}", std::get<CLINET_ID_ID>(*hConnection), pAction, PacketAnalizer::GetPacketKey(rsp));
  2753. std::cout << CurrentDateTime() << std::get<CLINET_ID_ID>(*hConnection) << " try check action resp [" << pAction << "] compared with " << PacketAnalizer::GetPacketKey(rsp).c_str() << endl;
  2754. if (PacketAnalizer::GetPacketType(rsp) == PACKET_TYPE_RES &&
  2755. strcmp(pAction, PacketAnalizer::GetPacketKey(rsp).c_str()) == 0)
  2756. {
  2757. if (GetTickCount() - dwTick < dwWaitTime)
  2758. {
  2759. ////mLog::FDEBUG("ActionAndRespWithConnDefalt Packet Content {$} content {$}", PacketAnalizer::GetPacketKey(rsp), rsp->encode());
  2760. resObj = *rsp;
  2761. return true;
  2762. }
  2763. else
  2764. {
  2765. ////mLog::FWARN("ActionAndRespWithConnDefalt Packet Content {$} Timeout content {$}", PacketAnalizer::GetPacketKey(rsp), rsp->encode());
  2766. return false;
  2767. }
  2768. std::cout << " : " << PacketAnalizer::GetPacketKey(rsp) << " content " << rsp->encode() << endl;
  2769. }
  2770. ////mLog::FDEBUG("ActionAndRespWithConnDefalt what ? {$} content {$}", PacketAnalizer::GetPacketKey(rsp), rsp->encode());
  2771. std::cout << "ActionAndRespWithConnDefalt what ? " << PacketAnalizer::GetPacketKey(rsp) << endl;
  2772. return false;
  2773. };
  2774. CcosLock* pLock = std::get<CONN_SEND_LOCK_ID>(*hConnection);
  2775. pLock->Thread_Lock();
  2776. ////mLog::FDEBUG("{$} ActionAndRespWithConnDefalt {$} to Topic {$} body {$} ", std::get<CLINET_ID_ID>(*hConnection), pAction, pszTopic, pContext->encode());
  2777. ccos_mqtt_msg_filter* pfilter = (ccos_mqtt_msg_filter*)std::get<MSG_HOOK_ID>(*hConnection);
  2778. ResDataObject *resActions = std::get<FILTER_RES_OBJ_ID>(*pfilter);
  2779. resActions->add(pAction, pszTopic);
  2780. std::get<FILTER_HANDLE_ID>(*pfilter) = hEvent;
  2781. std::get<FILTER_FUNC_ID>(*pfilter) = func;
  2782. std::string client_id = std::get<CLINET_ID_ID>(*hConnection);
  2783. PacketAnalizer::UpdatePacketTopic(&req, pszTopic, std::get<CLINET_ID_ID>(*hConnection).c_str());
  2784. const char* pLoad = req.encode();
  2785. ResDataObject* pPacket = new ResDataObject();
  2786. mqtt_msg_list* pList = std::get<MSG_LIST_ID>(*hConnection);
  2787. pPacket->add(pszTopic, pLoad);
  2788. ////mLog::FDEBUG(" {$} Try push packet to Send list: {$}", client_id, pPacket->encode());
  2789. pList->push_back(pPacket);
  2790. sem_post(std::get<SEMAPHORE_HANDLE_ID>(*hConnection));
  2791. /*
  2792. mqtt_message_t msg;
  2793. memset(&msg, 0, sizeof(msg));
  2794. msg.payload = (void*)pLoad;
  2795. msg.qos = MQTT_QOS;
  2796. msg.payloadlen = strlen(pLoad);
  2797. //int rc = mqtt_publish(pMqttClient, pszTopic, &msg);
  2798. int rc = MQTT_SUCCESS_ERROR;
  2799. dwTick = GetTickCount();
  2800. int nTryTimes = 0;
  2801. do
  2802. {
  2803. rc = mqtt_publish(pMqttClient, pszTopic, &msg);
  2804. nTryTimes++;
  2805. if (rc != MQTT_SUCCESS_ERROR)
  2806. {
  2807. ////mLog::FINFO("try mqtt_publish ret {$} do mqtt reconnect 3.. {$}", rc, client_id);
  2808. //mqtt_do_reconnect(pMqttClient);
  2809. mqtt_disconnect(pMqttClient);
  2810. rc = mqtt_connect(pMqttClient);
  2811. if (rc == MQTT_SUCCESS_ERROR)
  2812. {
  2813. resubscribe_topic(pMqttClient, pMqttClient->mqtt_conn_context);
  2814. ////mLog::FINFO("mqtt_connect ret {$} do mqtt resubscribe {$}", rc, client_id);
  2815. }
  2816. Sleep(2);
  2817. }
  2818. } while (rc != MQTT_SUCCESS_ERROR && GetTickCount() - dwTick < 3);
  2819. if (nTryTimes >= 1)
  2820. ////mLog::FINFO("CLT {$} Publish to {$} send Times {$} result {$}", std::get<CLINET_ID_ID>(*hConnection), pszTopic, nTryTimes, rc);
  2821. */
  2822. pLock->Thread_UnLock();
  2823. dwTick = GetTickCount() - dwTick;
  2824. //////mLog::FINFO("CLT {$} Publish to {$} Use TID {$} Use Time {$} result {$} ", std::get<CLINET_ID_ID>(*hConnection), pszTopic, GetCurrentThreadId(), dwTick, rc);
  2825. std::cout << "CLT [" << std::get<CLINET_ID_ID>(*hConnection) << "] at " << CurrentDateTime() << " Publish to [" << pszTopic << "] Use TID [" << GetCurrentThreadId() << "] Use Time[" << dwTick << "]ms" << endl;
  2826. dwTick = GetTickCount();
  2827. DWORD ret = hEvent->Wait(dwWaitTime);
  2828. if (ret) {
  2829. //等到应答了
  2830. dwTick = GetTickCount() - dwTick;
  2831. pLock->Thread_Lock();
  2832. ResDataObject* pResp = std::get<FILTER_RESPONS_OBJ_ID>(*pfilter);
  2833. for (int x = 0; x < pResp->size(); x++)
  2834. {
  2835. ResDataObject r = (*pResp)[x];
  2836. if (string(pAction) == string(pResp->GetKey(x)) && PacketAnalizer::GetPacketIdx(&req) == PacketAnalizer::GetPacketIdx(&r))
  2837. {
  2838. resObj = r;
  2839. pResp->eraseOneOf(pAction, x);
  2840. break;
  2841. }
  2842. }
  2843. pLock->Thread_UnLock();
  2844. std::cout << "CLT [" << std::get<CLINET_ID_ID>(*hConnection) << "] at " << CurrentDateTime() << "try [" << pszTopic << "] getresp ok Use Time[" << dwTick << "]ms" << endl;
  2845. ////mLog::FDEBUG("CLT {$} try {$} getresp ok Use Time {$}", std::get<CLINET_ID_ID>(*hConnection), pszTopic, dwTick);
  2846. //std::get<FILTER_RES_OBJ_ID>(*pfilter) = nullptr;
  2847. return 2;
  2848. }
  2849. //std::get<FILTER_FUNC_ID>(*pfilter) = nullptr;
  2850. //resObj.decode(strResObject.c_str());
  2851. ////mLog::FERROR("CLT {$} try {$} getresp timeout ", std::get<CLINET_ID_ID>(*hConnection), pszTopic );
  2852. std::cout << "CLT [" << std::get<CLINET_ID_ID>(*hConnection) << "] at " << CurrentDateTime() << "try [" << pszTopic << "] " << endl;
  2853. //std::get<FILTER_RES_OBJ_ID>(*pfilter) = nullptr;
  2854. return 0;
  2855. }
  2856. /// <summary>
  2857. /// 新建MQTT连接发送Ation并等待应答
  2858. /// </summary>
  2859. /// <param name="pAction"></param>
  2860. /// <param name="pContext"></param>
  2861. /// <param name="pszTopic"></param>
  2862. /// <param name="pszRespTopic"></param>
  2863. /// <param name="resObj"></param>
  2864. /// <param name="dwWaitTime"></param>
  2865. /// <param name="pszSenderName"></param>
  2866. /// <returns></returns>
  2867. LOGICDEVICE_API int ActionAndResp(const char* pAction, ResDataObject* pContext, const char* pszTopic, const char* pszRespTopic, ResDataObject& resObj,
  2868. DWORD dwWaitTime, const char* pszSenderName)
  2869. {
  2870. ResDataObject req;
  2871. if (pszRespTopic != nullptr)
  2872. PacketAnalizer::UpdateContextTopic(pContext, pszRespTopic);
  2873. //临时创建连接并发送和接收应答
  2874. char pszClientID[256];
  2875. snprintf(pszClientID, sizeof(pszClientID), "TEMP_%s_%d_0X%08lX",
  2876. (pszSenderName == nullptr) ? "ANONYMOUS" : pszSenderName,
  2877. getpid(), GetCurrentThreadId());
  2878. sem_t sem;
  2879. if (sem_init(&sem, 0, 0) != 0) {
  2880. return 0; // 如果初始化失败,返回0
  2881. }
  2882. std::cout << " ActionAndResp->NewConnection " << endl;
  2883. ccos_mqtt_connection* connObj = NewConnection(pszClientID, [&resObj, &sem](ResDataObject* req, const char* topic, void* conn) {
  2884. //应答到了,处理
  2885. PacketAnalizer::GetPacketContext(req, resObj);
  2886. sem_post(&sem);
  2887. });
  2888. ////发布消息,并等待应答
  2889. PublishAction(&req, pszTopic, connObj);
  2890. // 等待应答或超时
  2891. struct timespec ts;
  2892. clock_gettime(CLOCK_REALTIME, &ts);
  2893. ts.tv_sec += dwWaitTime / 1000; // 转换为秒
  2894. ts.tv_nsec += (dwWaitTime % 1000) * 1000000; // 转换为纳秒
  2895. // 等待信号量或者超时
  2896. int ret = 0;
  2897. while (ret == 0) {
  2898. ret = sem_timedwait(&sem, &ts); // 超时或者接收到信号量
  2899. if (ret == -1 && errno == ETIMEDOUT) {
  2900. // 超时
  2901. sem_destroy(&sem);
  2902. CloseConnection(connObj);
  2903. return 0; // 超时返回0
  2904. }
  2905. }
  2906. // 等到应答了
  2907. sem_destroy(&sem); // 销毁信号量
  2908. CloseConnection(connObj);
  2909. return 2; // 返回2表示应答成功
  2910. }