grpcclient.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. #include "grpcclient.h"
  2. grpcclient * ggrpcclient;
  3. void ListenData(const char * strdata,const unsigned int nSize,const unsigned int index,const QDateTime * dt,const char * strmemname)
  4. {
  5. ggrpcclient->UpdateData(strdata,nSize,strmemname);
  6. }
  7. void ListenPicData(const char * strdata,const unsigned int nSize,const unsigned int index,const QDateTime * dt,const char * strmemname)
  8. {
  9. ggrpcclient->UpdatePicData(strdata,nSize,strmemname);
  10. }
  11. grpcclient::grpcclient(std::string stryamlpath)
  12. {
  13. ggrpcclient = this;
  14. dec_yaml(stryamlpath.data());
  15. mstrpicmsgname[0] = "picfront";
  16. mstrpicmsgname[1] = "picrear";
  17. mstrpicmsgname[2] = "picleft";
  18. mstrpicmsgname[3] = "picright";
  19. unsigned int i;
  20. for(i=0;i<mvectormsgunit.size();i++)
  21. {
  22. mvectormsgunit[i].mpa = iv::modulecomm::RegisterRecv(mvectormsgunit[i].mstrmsgname,ListenData);
  23. }
  24. for(i=0;i<mvectorctrlmsgunit.size();i++)
  25. {
  26. mvectorctrlmsgunit[i].mpa = iv::modulecomm::RegisterSend(mvectorctrlmsgunit[i].mstrmsgname,mvectorctrlmsgunit[i].mnBufferSize,
  27. mvectorctrlmsgunit[i].mnBufferCount);
  28. }
  29. for(i=0;i<NUM_CAM;i++)
  30. {
  31. mpaPic[i] = iv::modulecomm::RegisterRecv(mstrpicmsgname[i].data(),ListenPicData);
  32. }
  33. for(i=0;i<NUM_CAM;i++)
  34. {
  35. unsigned int j;
  36. for(j=0;j<NUM_THREAD_PERCAM;j++)
  37. {
  38. mpThread[i*NUM_THREAD_PERCAM + j] = new std::thread(&grpcclient::threadpicupload,this,i);
  39. }
  40. }
  41. for(i=0;i<NUM_CAM;i++)
  42. {
  43. mpicbuf[i].mnSkipBase = mnskip;
  44. }
  45. }
  46. grpcclient::~grpcclient()
  47. {
  48. std::cout<<" enter ~grpcclient"<<std::endl;
  49. mbPicUpload = false;
  50. requestInterruption();
  51. while(this->isFinished() == false)
  52. {
  53. }
  54. std::cout<<"now join grpcclient thread"<<std::endl;
  55. unsigned int i;
  56. for(i=0;i<NUM_CAM;i++)
  57. {
  58. unsigned int j;
  59. for(j=0;j<NUM_THREAD_PERCAM;j++)
  60. {
  61. mpThread[i*NUM_THREAD_PERCAM + j]->join();
  62. }
  63. }
  64. for(i=0;i<mvectorctrlmsgunit.size();i++)
  65. {
  66. iv::modulecomm::Unregister(mvectorctrlmsgunit[i].mpa);
  67. }
  68. for(i=0;i<mvectormsgunit.size();i++)
  69. {
  70. iv::modulecomm::Unregister(mvectormsgunit[i].mpa);
  71. }
  72. std::cout<<"complete ~grpcclient"<<std::endl;
  73. }
  74. void grpcclient::run()
  75. {
  76. int nsize = mvectormsgunit.size();
  77. int i;
  78. int ninterval = atoi(gstruploadinterval.data());
  79. if(ninterval<=0)ninterval = 100;
  80. QTime xTime;
  81. xTime.start();
  82. int nlastsend = xTime.elapsed();
  83. std::string target_str = gstrserverip+":";
  84. target_str = target_str + gstrserverport ;//std::to_string()
  85. auto cargs = grpc::ChannelArguments();
  86. cargs.SetMaxReceiveMessageSize(1024 * 1024 * 1024); // 1 GB
  87. cargs.SetMaxSendMessageSize(1024 * 1024 * 1024);
  88. std::shared_ptr<Channel> channel = grpc::CreateCustomChannel(
  89. target_str, grpc::InsecureChannelCredentials(),cargs);
  90. std::unique_ptr<iv::UploadThread::Stub> stub_ = iv::UploadThread::NewStub(channel);
  91. iv::UploadRequestThread request;
  92. int nid = 0;
  93. // Container for the data we expect from the server.
  94. iv::UploadReplyThread reply;
  95. gpr_timespec timespec;
  96. timespec.tv_sec = 30;//设置阻塞时间为2秒
  97. timespec.tv_nsec = 0;
  98. timespec.clock_type = GPR_TIMESPAN;
  99. // ClientContext context;
  100. std::vector<qint64> xvectorlatency;
  101. while(!QThread::isInterruptionRequested())
  102. {
  103. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  104. if((xTime.elapsed()-nlastsend)<ninterval)
  105. {
  106. continue;
  107. }
  108. bool bImportant = false;
  109. int nkeeptime = 0;
  110. iv::cloud::cloudmsg xmsg;
  111. xmsg.set_xtime(QDateTime::currentMSecsSinceEpoch());
  112. gMutexMsg.lock();
  113. for(i=0;i<nsize;i++)
  114. {
  115. if(mvectormsgunit[i].mbRefresh)
  116. {
  117. mvectormsgunit[i].mbRefresh = false;
  118. if(mvectormsgunit[i].mbImportant)
  119. {
  120. bImportant = true;
  121. }
  122. if(mvectormsgunit[i].mnkeeptime > nkeeptime)
  123. {
  124. nkeeptime = mvectormsgunit[i].mnkeeptime;
  125. }
  126. iv::cloud::cloudunit xcloudunit;
  127. xcloudunit.set_msgname(mvectormsgunit[i].mstrmsgname);
  128. xcloudunit.set_data(mvectormsgunit[i].mpstrmsgdata.get(),mvectormsgunit[i].mndatasize);
  129. iv::cloud::cloudunit * pcu = xmsg.add_xclouddata();
  130. pcu->CopyFrom(xcloudunit);
  131. }
  132. }
  133. gMutexMsg.unlock();
  134. int nbytesize = xmsg.ByteSize();
  135. char * strbuf = new char[nbytesize];
  136. std::shared_ptr<char> pstrbuf;
  137. pstrbuf.reset(strbuf);
  138. if(xmsg.SerializeToArray(strbuf,nbytesize))
  139. {
  140. ClientContext context ;
  141. context.set_deadline(timespec);
  142. qint64 time1 = QDateTime::currentMSecsSinceEpoch();
  143. request.set_id(nid);
  144. request.set_ntime(time1);
  145. request.set_strquerymd5(gstrqueryMD5);
  146. request.set_strctrlmd5(gstrctrlMD5);
  147. request.set_strvin(gstrVIN);
  148. request.set_xdata(strbuf,nbytesize);
  149. request.set_kepptime(nkeeptime);
  150. request.set_bimportant(bImportant);
  151. request.set_nsendtime(QDateTime::currentMSecsSinceEpoch());
  152. request.set_nlatency(CalcLateny(xvectorlatency));
  153. nid++;
  154. nlastsend = xTime.elapsed();
  155. // The actual RPC.
  156. Status status = stub_->uploaddata(&context, request, &reply);
  157. if (status.ok()) {
  158. std::cout<<" data size is "<<nbytesize<<std::endl;
  159. std::cout<<nid<<" upload successfully"<<std::endl;
  160. xvectorlatency.push_back((QDateTime::currentMSecsSinceEpoch() - reply.nreqsendtime()));
  161. while(xvectorlatency.size()>10)xvectorlatency.erase(xvectorlatency.begin());
  162. if(reply.nres() == 1)
  163. {
  164. iv::cloud::cloudmsg xmsg;
  165. if(xmsg.ParseFromArray(reply.xdata().data(),reply.xdata().size()))
  166. {
  167. sharectrlmsg(&xmsg);
  168. }
  169. }
  170. } else {
  171. std::cout << status.error_code() << ": " << status.error_message()
  172. << std::endl;
  173. std::cout<<"RPC failed"<<std::endl;
  174. if(status.error_code() == 4)
  175. {
  176. std::cout<<" RPC Exceed Time, Create New stub_"<<std::endl;
  177. channel = grpc::CreateCustomChannel(
  178. target_str, grpc::InsecureChannelCredentials(),cargs);
  179. stub_ = iv::UploadThread::NewStub(channel);
  180. }
  181. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  182. }
  183. }
  184. }
  185. std::cout<<" grpcclient:run complete."<<std::endl;
  186. }
  187. void grpcclient::dec_yaml(const char * stryamlpath)
  188. {
  189. YAML::Node config;
  190. try
  191. {
  192. config = YAML::LoadFile(stryamlpath);
  193. }
  194. catch(YAML::BadFile e)
  195. {
  196. qDebug("load error.");
  197. return;
  198. }
  199. std::vector<std::string> vecmodulename;
  200. if(config["server"])
  201. {
  202. gstrserverip = config["server"].as<std::string>();
  203. }
  204. if(config["port"])
  205. {
  206. gstrserverport = config["port"].as<std::string>();
  207. }
  208. if(config["uploadinterval"])
  209. {
  210. gstruploadinterval = config["uploadinterval"].as<std::string>();
  211. }
  212. if(config["skip"])
  213. {
  214. std::string strskip = config["skip"].as<std::string>();
  215. mnskip = atoi(strskip.data());
  216. if(mnskip<1)mnskip = 1;
  217. }
  218. if(config["VIN"])
  219. {
  220. gstrVIN = config["VIN"].as<std::string>();
  221. }
  222. if(config["queryMD5"])
  223. {
  224. gstrqueryMD5 = config["queryMD5"].as<std::string>();
  225. }
  226. else
  227. {
  228. return;
  229. }
  230. if(config["ctrlMD5"])
  231. {
  232. gstrctrlMD5 = config["ctrlMD5"].as<std::string>();
  233. }
  234. std::string strmsgname;
  235. if(config["uploadmessage"])
  236. {
  237. for(YAML::const_iterator it= config["uploadmessage"].begin(); it != config["uploadmessage"].end();++it)
  238. {
  239. std::string strtitle = it->first.as<std::string>();
  240. std::cout<<strtitle<<std::endl;
  241. if(config["uploadmessage"][strtitle]["msgname"]&&config["uploadmessage"][strtitle]["buffersize"]&&config["uploadmessage"][strtitle]["buffercount"])
  242. {
  243. iv::msgunit xmu;
  244. strmsgname = config["uploadmessage"][strtitle]["msgname"].as<std::string>();
  245. strncpy(xmu.mstrmsgname,strmsgname.data(),255);
  246. xmu.mnBufferSize = config["uploadmessage"][strtitle]["buffersize"].as<int>();
  247. xmu.mnBufferCount = config["uploadmessage"][strtitle]["buffercount"].as<int>();
  248. if(config["uploadmessage"][strtitle]["bimportant"])
  249. {
  250. std::string strimportant = config["uploadmessage"][strtitle]["bimportant"].as<std::string>();
  251. if(strimportant == "true")
  252. {
  253. xmu.mbImportant = true;
  254. }
  255. }
  256. if(config["uploadmessage"][strtitle]["keeptime"])
  257. {
  258. std::string strkeep = config["uploadmessage"][strtitle]["keeptime"].as<std::string>();
  259. xmu.mnkeeptime = atoi(strkeep.data());
  260. }
  261. mvectormsgunit.push_back(xmu);
  262. }
  263. }
  264. }
  265. else
  266. {
  267. }
  268. if(!config["ctrlMD5"])
  269. {
  270. return;
  271. }
  272. if(config["ctrlmessage"])
  273. {
  274. std::string strnodename = "ctrlmessage";
  275. for(YAML::const_iterator it= config[strnodename].begin(); it != config[strnodename].end();++it)
  276. {
  277. std::string strtitle = it->first.as<std::string>();
  278. std::cout<<strtitle<<std::endl;
  279. if(config[strnodename][strtitle]["msgname"]&&config[strnodename][strtitle]["buffersize"]&&config[strnodename][strtitle]["buffercount"])
  280. {
  281. iv::msgunit xmu;
  282. strmsgname = config[strnodename][strtitle]["msgname"].as<std::string>();
  283. strncpy(xmu.mstrmsgname,strmsgname.data(),255);
  284. xmu.mnBufferSize = config[strnodename][strtitle]["buffersize"].as<int>();
  285. xmu.mnBufferCount = config[strnodename][strtitle]["buffercount"].as<int>();
  286. mvectorctrlmsgunit.push_back(xmu);
  287. }
  288. }
  289. }
  290. else
  291. {
  292. }
  293. return;
  294. }
  295. void grpcclient::sharectrlmsg(iv::cloud::cloudmsg * pxmsg)
  296. {
  297. int i;
  298. int nsize = pxmsg->xclouddata_size();
  299. for(i=0;i<nsize;i++)
  300. {
  301. int j;
  302. int nquerysize = mvectorctrlmsgunit.size();
  303. for(j=0;j<nquerysize;j++)
  304. {
  305. if(strncmp(pxmsg->xclouddata(i).msgname().data(), mvectorctrlmsgunit[j].mstrmsgname,255) == 0)
  306. {
  307. // qDebug("size is %d ",pxmsg->xclouddata(i).data().size());
  308. iv::modulecomm::ModuleSendMsg(mvectorctrlmsgunit[j].mpa,pxmsg->xclouddata(i).data().data(),pxmsg->xclouddata(i).data().size());
  309. break;
  310. }
  311. }
  312. }
  313. }
  314. void grpcclient::UpdateData(const char *strdata, const unsigned int nSize, const char *strmemname)
  315. {
  316. int nsize = mvectormsgunit.size();
  317. int i;
  318. for(i=0;i<nsize;i++)
  319. {
  320. if(strncmp(strmemname,mvectormsgunit[i].mstrmsgname,255) == 0)
  321. {
  322. gMutexMsg.lock();
  323. char * strtem = new char[nSize];
  324. memcpy(strtem,strdata,nSize);
  325. mvectormsgunit[i].mpstrmsgdata.reset(strtem);
  326. mvectormsgunit[i].mndatasize = nSize;
  327. mvectormsgunit[i].mbRefresh = true;
  328. gMutexMsg.unlock();
  329. break;
  330. }
  331. }
  332. }
  333. void grpcclient::UpdatePicData(const char *strdata, const unsigned int nSize, const char *strmemname)
  334. {
  335. int npos = -1;
  336. unsigned int i;
  337. for(i=0;i<NUM_CAM;i++)
  338. {
  339. if(strncmp(strmemname,mstrpicmsgname[i].data(),255) == 0)
  340. {
  341. npos = i;
  342. break;
  343. }
  344. }
  345. if(npos<0)
  346. {
  347. std::cout<<"grpcclient::UpdatePicData not found pic. msg name is "<<strmemname<<std::endl;
  348. return;
  349. }
  350. if(npos>= NUM_CAM)
  351. {
  352. std::cout<<"Camera count is "<<NUM_CAM<<" NOW camear is "<<npos<<std::endl;
  353. return;
  354. }
  355. mpicbuf[npos].mMutex.lock();
  356. mpicbuf[npos].mnMsgTime = QDateTime::currentMSecsSinceEpoch();
  357. mpicbuf[npos].mbRefresh = true;
  358. mpicbuf[npos].mpstrmsgdata = std::shared_ptr<char>(new char[nSize]);
  359. mpicbuf[npos].mDataSize = nSize;
  360. memcpy(mpicbuf[npos].mpstrmsgdata.get(),strdata,nSize);
  361. mpicbuf[npos].mMutex.unlock();
  362. mpicbuf[npos].mwc.wakeAll();
  363. }
  364. void grpcclient::threadpicupload(int nCamPos)
  365. {
  366. std::cout<<"thread cam "<<nCamPos<<"run"<<std::endl;
  367. int nsize = mvectormsgunit.size();
  368. int i;
  369. int ninterval = atoi(gstruploadinterval.data());
  370. if(ninterval<=0)ninterval = 100;
  371. QTime xTime;
  372. xTime.start();
  373. int nlastsend = xTime.elapsed();
  374. std::string target_str = gstrserverip+":";
  375. target_str = target_str + gstrserverport ;//std::to_string()
  376. auto cargs = grpc::ChannelArguments();
  377. cargs.SetMaxReceiveMessageSize(1024 * 1024 * 1024); // 1 GB
  378. cargs.SetMaxSendMessageSize(1024 * 1024 * 1024);
  379. std::shared_ptr<Channel> channel = grpc::CreateCustomChannel(
  380. target_str, grpc::InsecureChannelCredentials(),cargs);
  381. std::unique_ptr<iv::UploadThread::Stub> stub_ = iv::UploadThread::NewStub(channel);
  382. iv::PicUpRequestThread request;
  383. int nid = 0;
  384. // Container for the data we expect from the server.
  385. iv::PicUpReplyThread reply;
  386. gpr_timespec timespec;
  387. timespec.tv_sec = 30;//设置阻塞时间为2秒
  388. timespec.tv_nsec = 0;
  389. timespec.clock_type = GPR_TIMESPAN;
  390. // ClientContext context;
  391. while(mbPicUpload)
  392. {
  393. std::shared_ptr<char> pstr_ptr;
  394. if((nCamPos<0)||(nCamPos >= NUM_CAM))
  395. {
  396. std::cout<<"Cam Pos Error. "<<"Pos: "<<nCamPos<<" TOTAL:"<<NUM_CAM<<std::endl;
  397. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  398. continue;
  399. }
  400. bool bUpdate = false;
  401. qint64 nMsgTime = 0;
  402. int nSize = 0;
  403. qint64 npiclatency;
  404. int nSkipBase = 1;
  405. int nCount;
  406. mpicbuf[nCamPos].mWaitMutex.lock();
  407. mpicbuf[nCamPos].mwc.wait(&mpicbuf[nCamPos].mWaitMutex,100);
  408. mpicbuf[nCamPos].mWaitMutex.unlock();
  409. mpicbuf[nCamPos].mMutex.lock();
  410. bUpdate = mpicbuf[nCamPos].mbRefresh;
  411. if(bUpdate == true)
  412. {
  413. nMsgTime = mpicbuf[nCamPos].mnMsgTime;
  414. mpicbuf[nCamPos].mbRefresh = false;
  415. pstr_ptr = mpicbuf[nCamPos].mpstrmsgdata;
  416. nSize = mpicbuf[nCamPos].mDataSize;
  417. npiclatency = CalcLateny(mpicbuf[nCamPos].mvectorlatency);
  418. nSkipBase = mpicbuf[nCamPos].mnSkipBase;
  419. nCount = mpicbuf[nCamPos].mnCount;
  420. mpicbuf[nCamPos].mnCount++;
  421. // if(npiclatency > 500)
  422. // {
  423. // if(mpicbuf[nCamPos].mnSkipBase<30)mpicbuf[nCamPos].mnSkipBase++;
  424. // }
  425. // else
  426. // {
  427. // if(npiclatency<300)
  428. // if(mpicbuf[nCamPos].mnSkipBase > mpicbuf[nCamPos].mnDefSkipBase)mpicbuf[nCamPos].mnSkipBase--;
  429. // }
  430. std::cout<<"upload "<<nMsgTime<<" latency: "<<npiclatency<<" skip param: "<<nSkipBase<<std::endl;
  431. }
  432. mpicbuf[nCamPos].mMutex.unlock();
  433. if(bUpdate == false)
  434. {
  435. // std::this_thread::sleep_for(std::chrono::milliseconds(10));
  436. continue;
  437. }
  438. if(nCount%nSkipBase != 0)
  439. {
  440. continue;
  441. }
  442. ClientContext context ;
  443. context.set_deadline(timespec);
  444. qint64 time1 = QDateTime::currentMSecsSinceEpoch();
  445. request.set_npictime(nMsgTime);
  446. request.set_ncampos(nCamPos);
  447. request.set_strvin(gstrVIN);
  448. request.set_xdata(pstr_ptr.get(),nSize);
  449. request.set_nlatency(npiclatency);
  450. nid++;
  451. nlastsend = xTime.elapsed();
  452. // The actual RPC.
  453. Status status = stub_->uploadpic(&context, request, &reply);
  454. if (status.ok()) {
  455. qint64 nlaten = QDateTime::currentMSecsSinceEpoch() - time1;
  456. mpicbuf[nCamPos].mMutex.lock();
  457. mpicbuf[nCamPos].mvectorlatency.push_back(nlaten);
  458. while(mpicbuf[nCamPos].mvectorlatency.size()>10)mpicbuf[nCamPos].mvectorlatency.erase(mpicbuf[nCamPos].mvectorlatency.begin());
  459. mpicbuf[nCamPos].mMutex.unlock();
  460. if(reply.nres() == 1)
  461. {
  462. // iv::cloud::cloudmsg xmsg;
  463. // if(xmsg.ParseFromArray(reply.xdata().data(),reply.xdata().size()))
  464. // {
  465. // sharectrlmsg(&xmsg);
  466. // }
  467. }
  468. } else {
  469. std::cout << status.error_code() << ": " << status.error_message()
  470. << std::endl;
  471. std::cout<<"RPC failed"<<std::endl;
  472. if(status.error_code() == 4)
  473. {
  474. std::cout<<nCamPos<<" RPC Exceed Time, Create New stub_"<<std::endl;
  475. channel = grpc::CreateCustomChannel(
  476. target_str, grpc::InsecureChannelCredentials(),cargs);
  477. stub_ = iv::UploadThread::NewStub(channel);
  478. }
  479. std::this_thread::sleep_for(std::chrono::milliseconds(900));
  480. }
  481. }
  482. std::cout<<"threadpicupload cam pos: "<<nCamPos<<" exit."<<std::endl;
  483. }
  484. qint64 grpcclient::CalcLateny(std::vector<qint64> &xvectorlatency)
  485. {
  486. if(xvectorlatency.size() == 0)return 1000;
  487. unsigned int i;
  488. qint64 nLatencyTotal = 0;
  489. for(i=0;i<xvectorlatency.size();i++)
  490. {
  491. nLatencyTotal = nLatencyTotal + xvectorlatency[i];
  492. }
  493. qint64 nLatencyAvg = nLatencyTotal/xvectorlatency.size();
  494. return nLatencyAvg;
  495. }