message_queue.cpp 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
  1. #include <atomic>
  2. #include <string>
  3. #include "../common/comm.h"
  4. #include "api.h"
  5. #include "../common/iobuffer.h"
  6. #include "../common/sensor_socket.h"
  7. #include "../common/peer_connection.h"
  8. #include "VideoRenderer.h"
  9. #include "../thirdparty/jsoncpp/include/json/json.h"
  10. #include "protocol.pb.h"
  11. #include "imu_sensor.h"
  12. #include "Rtk.h"
  13. #include "message_queue.h"
  14. #include <fstream>
  15. #include <iostream>
  16. #include <cstring>
  17. #include "hmacsha256.h"
  18. #include <linux/usbdevice_fs.h>
  19. #include <sys/ioctl.h>
  20. #include <sys/statfs.h>
  21. #include <stdlib.h>
  22. #include <unistd.h>
  23. #include <sys/vfs.h>
  24. #include <dirent.h>
  25. #include <sys/stat.h>
  26. CMessageQueue::CMessageQueue():Head(nullptr),Tail(nullptr)
  27. {
  28. _peerId=-1;
  29. btimeStopedCar = false;
  30. File_fd = NULL;
  31. _Version = 1;
  32. }
  33. CMessageQueue::~CMessageQueue()
  34. {
  35. }
  36. void renableUSB(const char* file)
  37. {
  38. printf("Resetting USB device %s\n", file);
  39. int fd = open(file, O_WRONLY);
  40. if (fd < 0) {
  41. char text[256];
  42. perror(text);
  43. printf("Error opening output file %s", text);
  44. return;
  45. }
  46. int rc = ioctl(fd, USBDEVFS_RESET, 0);
  47. if (rc < 0) {
  48. perror("Error in ioctl");
  49. return;
  50. }
  51. printf("Reset successful\n");
  52. close(fd);
  53. }
  54. void CMessageQueue::Create()
  55. {
  56. Json::Value root;
  57. Json::Reader jsonReader;
  58. std::ifstream ifile("./config.json");
  59. std::string serverip;
  60. int32_t _hostPort;
  61. int32_t _remotePort;
  62. _curTick=0;
  63. bStopedCar=false;
  64. if(jsonReader.parse(ifile,root))
  65. {
  66. std::cout<<"enter config json"<<std::endl;
  67. _serial=root["serial"].asString();
  68. int32_t _Rtkport=root["rtk_port"].asInt();
  69. int32_t _Rtkhost=root["rtk_host"].asInt();
  70. std::string _Rtkip=root["rtk_ip"].asString();
  71. std::cout<<"Rtk ip:"<< _Rtkip <<std::endl;
  72. _Rtk = std::make_unique<SensorSocket<CRtkSensor>>(this, _Rtkip, _Rtkport, _Rtkhost);
  73. //_Rtk->Start();
  74. _Version = root["Version"].asInt();
  75. if(_Version)//AD10
  76. {
  77. std::string can_port_radar = root["can_bus_radar"].asString();
  78. _CanBusRadar = std::make_unique<SensorCanBus<CCanRadarSensor>>(this, can_port_radar);
  79. //_CanBusRadar->Start();
  80. }
  81. else
  82. {
  83. //_RadarIp
  84. int32_t _radarport=root["radar_port"].asInt();
  85. int32_t _radarhost=root["radar_host"].asInt();
  86. std::string _radarip=root["radar_ip"].asString();
  87. std::cout<<"radar ip:"<<_radarip<<std::endl;
  88. _RadarIp = std::make_unique<SensorSocket<CRadarSensor>>(this,_radarip,_radarport,_radarhost);
  89. //_RadarIp->Start();
  90. }
  91. if(_Version)//AD10
  92. {
  93. std::string can_port = root["can_bus_vehicle"].asString();
  94. _CanBusVehicle = std::make_unique<SensorCanBus<CCanBusSensor>>(this, can_port);
  95. //_CanBusVehicle->Start();
  96. }
  97. else
  98. {
  99. _PcanBusVehicle = std::make_unique<SensorPeakCan<CPcanSensor>>(this);
  100. //_PcanBusVehicle->Start();
  101. }
  102. _UdpMinPort=root["udp_min_port"].asInt();
  103. _UdpMaxPort=root["udp_max_port"].asInt();
  104. //20230417
  105. //const char* serverUrl = "tcp://localhost:1883"; //服务器地址
  106. //const char* userName = ""; //用户名
  107. //const char* password = ""; //密码
  108. std::string serverUrl = root["MqttserverUrl"].asString();
  109. std::string userName = root["Esn"].asString();
  110. std::string password = root["EsnPass"].asString();
  111. std::string clientId = ""; //客户端标识符
  112. bool _Hm256 = false;
  113. unsigned char Source[128];
  114. time_t rawtime;
  115. struct tm* info;
  116. char buffer[80];
  117. time(&rawtime);
  118. info = localtime(&rawtime);
  119. uint8_t secret[32] = { 0 };
  120. //如UTC 时间2018/7/24 17:56:20 则应表示为2018072417。
  121. /*sprintf((char*)secret, "%d%.2d%.2d%.2d", info->tm_year + 1900, info->tm_mon + 1, info->tm_mday,
  122. info->tm_hour);*/
  123. sprintf((char*)secret, "%d%.2d%.2d", info->tm_year + 1900, info->tm_mon + 1, info->tm_mday);
  124. memset(Source, 0, 128);
  125. sprintf((char*)Source, "%s_0_0_%s", userName.c_str(), secret);
  126. clientId.clear();
  127. clientId.append((const char*)Source);
  128. if (password.length() && _Hm256)
  129. {
  130. uint8_t outdata[128] = { 0 };
  131. uint8_t md[SHA256_DIGESTLEN] = { 0 };
  132. int len1 = strlen((char*)secret);
  133. int len2 = strlen((char*)password.c_str());
  134. HMAC_SHA256_CTX hmac;
  135. hmac_sha256_init(&hmac, secret, len1);
  136. hmac_sha256_update(&hmac, (const uint8_t*)password.c_str(), len2);
  137. hmac_sha256_final(&hmac, md);
  138. memcpy(outdata, md, SHA256_DIGESTLEN);
  139. password.clear();
  140. password.append((const char*)outdata);
  141. }
  142. _Mqtt_ZR = std::make_unique<SensorMQTT<CMqttSensor>>(this, serverUrl, userName, password, clientId);
  143. std::string DataServerUrl = root["DataServerUrl"].asString();
  144. std::string DatauserName = root["DataEsn"].asString();
  145. std::string Datapassword = root["DataEsnPass"].asString();
  146. std::string DataclientId = root["DataClientId"].asString();
  147. _Mqtt_SE = std::make_unique<SensorMQTT<CDataMqttSensor>>(this, DataServerUrl, DatauserName, Datapassword, DataclientId);
  148. //_Mqtt_SE->Start();
  149. //std::string _usb_1 = root["usb_3"].asString();
  150. //renableUSB("/dev/bus/usb/002/002");
  151. //renableUSB("/dev/bus/usb/001/003");
  152. //renableUSB(_usb_2.c_str());
  153. //renableUSB(_usb_1.c_str());
  154. serverip=root["ip"].asString();
  155. _hostPort=root["TcpHostPort"].asInt();
  156. _remotePort=root["TcpRemotePort"].asInt();
  157. _name=root["name"].asString();
  158. const Json::Value arrayObj=root["camerainfo"];
  159. int32_t count=arrayObj.size();
  160. for(int32_t i=0;i<count;i++)
  161. {
  162. LocalCameraInfo info;
  163. const Json::Value& value=arrayObj[i];
  164. info.index=value["index"].asInt();
  165. info.label=value["label"].asString();
  166. _cameraArray.push_back(info);
  167. }
  168. for(int i=0;i<_cameraArray.size();i++)
  169. {
  170. _peerArray.push_back({nullptr});
  171. }
  172. }
  173. else{
  174. std::string error=jsonReader.getFormattedErrorMessages();
  175. std::cout<<error<<std::endl;
  176. }
  177. _client=std::make_unique<SocketClient>(this);
  178. _client->Start(serverip.c_str(),_remotePort,_hostPort);
  179. std::this_thread::yield();
  180. }
  181. void CMessageQueue::EnQueue(CIOBuffer* pBuffer)
  182. {
  183. bool bNullBuffer=false;
  184. std::unique_lock <std::mutex> lck(_lock);
  185. if(Head==nullptr)
  186. {
  187. Head=Tail=pBuffer;
  188. bNullBuffer=true;
  189. }
  190. else{
  191. Tail->NextBuf=pBuffer;
  192. Tail=Tail->NextBuf;
  193. }
  194. pBuffer->NextBuf=nullptr;
  195. if(bNullBuffer)
  196. {
  197. //_cv.notify_one();
  198. //20231023
  199. _cv.notify_all();
  200. }
  201. }
  202. void CMessageQueue::Process()
  203. {
  204. // printf("-----process-----\n");
  205. CIOBuffer * ptr=nullptr;
  206. {
  207. std::unique_lock <std::mutex> lck(_lock);
  208. /*
  209. while(Head==nullptr)
  210. {
  211. _cv.wait(lck);
  212. }
  213. */
  214. while(Head==nullptr&&_cv.wait_for(lck,std::chrono::seconds(1))==std::cv_status::timeout)
  215. {
  216. CheckSignal();
  217. //std::cout<<".";
  218. //std::cout.flush();
  219. }
  220. }
  221. while(Head!=nullptr)
  222. {
  223. // printf("head-------\n");
  224. ptr=Head;
  225. Head=Head->NextBuf;
  226. if(ptr!=nullptr)
  227. {
  228. Message* message=reinterpret_cast<Message *>(ptr->Buffer);
  229. switch (message->cmd)
  230. {
  231. case MessageType::ReqVideo:
  232. // printf("ReqVideo\n");
  233. // printf("ReqVideo message param_l : %d\n", message->param_l);
  234. OnNotifyReq((int32_t)message->param_l);
  235. break;
  236. case MessageType::RepVideo:
  237. // printf("RepVideo\n");
  238. // printf("RepVideo message param_l : %d\n", message->param_l);
  239. OnNotifyRep((int32_t)message->param_l);
  240. break;
  241. case MessageType::Connected:
  242. // printf("Connected\n");
  243. // printf("Connected message param_l : %d\n", message->param_l);
  244. OnNotifyConnected((bool)message->param_l);
  245. break;
  246. case MessageType::Leave:
  247. // printf("Leave\n");
  248. OnNotifyLeave();
  249. break;
  250. case MessageType::AsyncMessage:
  251. // printf("AsyncMessage\n");
  252. OnNotifyMessage();
  253. break;
  254. case MessageType::StopSensor:
  255. // printf("StopSensor\n");
  256. OnNotifyStopSensor();
  257. break;
  258. case MessageType::Ping:
  259. // printf("Ping \n");
  260. OnNotifyPing(message->param_l);
  261. break;
  262. }
  263. ptr->Release();
  264. }
  265. // printf("8888888-------------head-------\n");
  266. }
  267. }
  268. void CMessageQueue::SetTick(long long tick)
  269. {
  270. _curTick=tick;
  271. }
  272. void CMessageQueue::OnNotifyConnected(bool bRet)
  273. {
  274. if(bRet)
  275. {
  276. std::cout << _serial << " " << _name << std::endl;
  277. _client->WriteAddRobot(_serial,_name,static_cast<int32_t>(EgoType::Car));
  278. _updatethread.start(_client.get());
  279. //cs->Analog(0,0,0,0,0);
  280. }
  281. else
  282. {
  283. if(_peerId!=-1)
  284. {
  285. OnVideoLeave(_peerId,EgoType::User);
  286. _peerId=-1;
  287. }
  288. _updatethread.stop();
  289. }
  290. }
  291. int day_diffient(int year_start, int month_start, int day_start,char *Dst)
  292. {
  293. //2024-03-11
  294. int year_end = strtol(Dst,NULL,10);
  295. char Temp = '-',*p = NULL,*p1 = NULL;
  296. p = strchr(Dst,Temp);
  297. int month_end = strtol(p + 1,NULL,10);
  298. p1 = strchr(p + 1,Temp);
  299. int day_end = strtol(p1 + 1,NULL,10);
  300. int y2, m2, d2;
  301. int y1, m1, d1;
  302. m1 = (month_start + 9) % 12;
  303. y1 = year_start - m1/10;
  304. d1 = 365*y1 + y1/4 - y1/100 + y1/400 + (m1*306 + 5)/10 + (day_start - 1);
  305. m2 = (month_end + 9) % 12;
  306. y2 = year_end - m2/10;
  307. d2 = 365*y2 + y2/4 - y2/100 + y2/400 + (m2*306 + 5)/10 + (day_end - 1);
  308. return (d1 - d2);
  309. }
  310. void delete_days(const char *path)
  311. {
  312. DIR *dir;
  313. struct dirent *entry;
  314. struct stat statbuf;
  315. time_t rawtime;
  316. struct tm* info;
  317. time(&rawtime);
  318. info = localtime(&rawtime);
  319. uint8_t secret[64] = { 0 };
  320. sprintf((char*)secret, "%d-%.2d-%.2d.log", info->tm_year + 1900, info->tm_mon + 1, info->tm_mday);
  321. printf("%s\r\n",secret);
  322. dir = opendir(path);
  323. if (dir == NULL)
  324. {
  325. printf("无法打开目录\n");
  326. return;
  327. }
  328. while ((entry = readdir(dir)) != NULL)
  329. {
  330. if(entry->d_name[0]=='.')
  331. continue;
  332. //printf("%s\n",entry->d_name);
  333. if(day_diffient(info->tm_year + 1900, info->tm_mon + 1, info->tm_mday,entry->d_name) > 15)
  334. {
  335. char Dst[128];
  336. memset(Dst,0,128);
  337. sprintf(Dst,"rm -rf /home/nvidia/devdata/ZJ_PRO/EgoSystem/build/log/%s",entry->d_name);
  338. system(Dst);
  339. }
  340. }
  341. closedir(dir);
  342. }
  343. void CMessageQueue::SerichFile(char *filename)
  344. {
  345. DIR *directory_pointer;
  346. struct dirent *entry;
  347. int exist = 0;
  348. char Dst[128];
  349. memset(Dst,0,128);
  350. sprintf(Dst,"/home/nvidia/devdata/ZJ_PRO/EgoSystem/build/log/%s",filename);
  351. if((directory_pointer=opendir("/home/nvidia/devdata/ZJ_PRO/EgoSystem/build/log/")) == NULL)
  352. printf("Error open\n");
  353. else
  354. {
  355. while((entry=readdir(directory_pointer)) != NULL)
  356. {
  357. if(entry->d_name[0]=='.') continue;
  358. printf("%s\n",entry->d_name);
  359. if(!strcmp(entry->d_name,filename))
  360. {
  361. File_fd = fopen(Dst, "a");
  362. exist = 1;
  363. break;
  364. }
  365. }
  366. }
  367. if(!exist)
  368. File_fd = fopen(Dst, "w+");
  369. closedir(directory_pointer);
  370. }
  371. void CMessageQueue::OnNotifyReq(int32_t index)
  372. {
  373. // std::cout<<__FUNCTION__<<","<<__LINE__<<std::endl;
  374. if(_peerId==-1) return;
  375. if(index==0)
  376. {
  377. mrsWebrtcCreateFactory(true);
  378. _curTick=0;
  379. bStopedCar=false;
  380. _Rtk->Start();
  381. if(_Version)//AD10
  382. {
  383. _CanBusVehicle->Start();
  384. _CanBusRadar->Start();
  385. }
  386. else
  387. {
  388. _PcanBusVehicle->Start();
  389. _RadarIp->Start();
  390. }
  391. _Mqtt_ZR->Start();
  392. _Mqtt_SE->Start();
  393. File_fd = NULL;
  394. struct statfs diskInfo;
  395. statfs("/dev/mmcblk0p1", &diskInfo);
  396. unsigned long long freeDisk = diskInfo.f_bfree * diskInfo.f_bsize;
  397. time_t rawtime;
  398. struct tm* info;
  399. time(&rawtime);
  400. info = localtime(&rawtime);
  401. uint8_t secret[64] = { 0 };
  402. sprintf((char*)secret, "%d-%.2d-%.2d.log", info->tm_year + 1900, info->tm_mon + 1, info->tm_mday);
  403. if((freeDisk >> 30) < 15)
  404. {
  405. system("rm -rf /home/nvidia/devdata/ZJ_PRO/EgoSystem/build/log");
  406. system("mkdir /home/nvidia/devdata/ZJ_PRO/EgoSystem/build/log/");
  407. }
  408. else
  409. delete_days("/home/nvidia/devdata/ZJ_PRO/EgoSystem/build/log");
  410. SerichFile((char *)secret);
  411. }
  412. _peerArray[index]=std::make_unique<CPeerConnection>(static_cast<ChannelType>(index),_client.get());
  413. _client->WriteVideoRep(_peerId, RemoNet::VideoDesc::OK, index);
  414. }
  415. void CMessageQueue::OnNotifyRep(int32_t index)
  416. {
  417. _peerArray[index]=std::make_unique<CPeerConnection>(static_cast<ChannelType>(index), _client.get());
  418. InitPeerConnection(_peerId,index);
  419. _peerArray[index]->CreateOffer();
  420. }
  421. void CMessageQueue::InitPeerConnection(int32_t peer,int32_t index)
  422. {
  423. _peerArray[index]->Initialize(peer,index,_UdpMinPort,_UdpMaxPort);
  424. _peerArray[index]->AddDataChannel(true, false);
  425. _peerArray[index]->AddLocalVideoTrack(static_cast<RenderPosition>(index),_cameraArray[index].index);
  426. if(index==RenderPosition::BACK)
  427. {
  428. void * front=_peerArray[RenderPosition::FRONT]->GetCurrentCtx();
  429. while(front==nullptr)
  430. {
  431. std::cout<<"front==nullptr"<<std::endl;
  432. std::this_thread::sleep_for(std::chrono::microseconds(50));
  433. front=_peerArray[RenderPosition::FRONT]->GetCurrentCtx();
  434. }
  435. void * back=_peerArray[RenderPosition::BACK]->GetCurrentCtx();
  436. while (back==nullptr)
  437. {
  438. std::cout<<"back==nullptr"<<std::endl;
  439. std::this_thread::sleep_for(std::chrono::microseconds(50));
  440. back=_peerArray[RenderPosition::BACK]->GetCurrentCtx();
  441. }
  442. _peerArray[RenderPosition::FRONT]->SetOtherCtx(back);
  443. _peerArray[RenderPosition::BACK]->SetOtherCtx(front);
  444. }
  445. /*
  446. if((index+1)==RenderPosition::ALL)
  447. {
  448. void * front=_peerArray[RenderPosition::FRONT]->GetCurrentCtx();
  449. while(front==nullptr)
  450. {
  451. std::cout<<"front==nullptr"<<std::endl;
  452. std::this_thread::sleep_for(std::chrono::microseconds(50));
  453. front=_peerArray[RenderPosition::FRONT]->GetCurrentCtx();
  454. }
  455. void * back=_peerArray[RenderPosition::BACK]->GetCurrentCtx();
  456. while (back==nullptr)
  457. {
  458. std::cout<<"back==nullptr"<<std::endl;
  459. std::this_thread::sleep_for(std::chrono::microseconds(50));
  460. back=_peerArray[RenderPosition::BACK]->GetCurrentCtx();
  461. }
  462. _peerArray[RenderPosition::FRONT]->SetOtherCtx(back);
  463. _peerArray[RenderPosition::BACK]->SetOtherCtx(front);
  464. void * left=_peerArray[RenderPosition::LEFT]->GetCurrentCtx();
  465. while(left==nullptr)
  466. {
  467. std::cout<<"left==nullptr"<<std::endl;
  468. std::this_thread::sleep_for(std::chrono::microseconds(50));
  469. front=_peerArray[RenderPosition::LEFT]->GetCurrentCtx();
  470. }
  471. void * right=_peerArray[RenderPosition::RIGHT]->GetCurrentCtx();
  472. while (right==nullptr)
  473. {
  474. std::cout<<"right==nullptr"<<std::endl;
  475. std::this_thread::sleep_for(std::chrono::microseconds(50));
  476. back=_peerArray[RenderPosition::RIGHT]->GetCurrentCtx();
  477. }
  478. _peerArray[RenderPosition::LEFT]->SetOtherCtx(right);
  479. _peerArray[RenderPosition::RIGHT]->SetOtherCtx(left);
  480. }
  481. */
  482. /*
  483. if((index+1)==RenderPosition::ALL)
  484. {
  485. void * front=_peerArray[RenderPosition::FRONT]->GetCurrentCtx();
  486. void * back=_peerArray[RenderPosition::BACK]->GetCurrentCtx();
  487. void * left=_peerArray[RenderPosition::LEFT]->GetCurrentCtx();
  488. void * right=_peerArray[RenderPosition::RIGHT]->GetCurrentCtx();
  489. void * dash=_peerArray[RenderPosition::DASHBOARD]->GetCurrentCtx();
  490. _peerArray[RenderPosition::FRONT]->SetOtherCtx(back);
  491. _peerArray[RenderPosition::BACK]->SetOtherCtx(front);
  492. _peerArray[RenderPosition::LEFT]->SetOtherCtx(left);
  493. _peerArray[RenderPosition::RIGHT]->SetOtherCtx(right);
  494. _peerArray[RenderPosition::DASHBOARD]->SetOtherCtx(dash);
  495. }
  496. */
  497. if(index==RenderPosition::FRONT)
  498. _peerArray[index]->AddLocalAudioTrack();
  499. }
  500. void CMessageQueue::OnAdd(bool bRet)
  501. {
  502. }
  503. void CMessageQueue::OnConnected(bool bRet)
  504. {
  505. CIOBuffer * pBuffer=CIOBuffer::Alloc();
  506. Message* message=reinterpret_cast<Message *>(pBuffer->Buffer);
  507. message->cmd=MessageType::Connected;
  508. message->param_l=bRet;
  509. EnQueue(pBuffer);
  510. }
  511. void CMessageQueue::OnVideoLeave(int32_t peer,EgoType type)
  512. {
  513. {
  514. CIOBuffer * pBuffer=CIOBuffer::Alloc();
  515. Message* message=reinterpret_cast<Message *>(pBuffer->Buffer);
  516. message->cmd=MessageType::StopSensor;
  517. EnQueue(pBuffer);
  518. }
  519. {
  520. CIOBuffer * pBuffer=CIOBuffer::Alloc();
  521. Message* message=reinterpret_cast<Message *>(pBuffer->Buffer);
  522. message->cmd=MessageType::Leave;
  523. EnQueue(pBuffer);
  524. }
  525. }
  526. #ifdef WIN32
  527. void CMessageQueue::OnVideoRep(int32_t index,RemoNet::VideoDesc desc)
  528. {
  529. if (desc == RemoNet::VideoDesc::OK)
  530. {
  531. assert(_peerId!=-1);
  532. CIOBuffer * pBuffer=CIOBuffer::Alloc();
  533. Message* message=reinterpret_cast<Message *>(pBuffer->Buffer);
  534. message->cmd=MessageType::ReqVideo;
  535. message->param_l=index;
  536. EnQueue(pBuffer);
  537. }
  538. }
  539. #else
  540. void CMessageQueue::OnVideoReq(int32_t video,int32_t peer)
  541. {
  542. // std::cout<<__FUNCTION__<<","<<__LINE__<<std::endl;
  543. _peerId=peer;
  544. CIOBuffer * pBuffer=CIOBuffer::Alloc();
  545. Message* message=reinterpret_cast<Message *>(pBuffer->Buffer);
  546. message->cmd=MessageType::ReqVideo;
  547. message->param_l=video;
  548. EnQueue(pBuffer);
  549. }
  550. #endif
  551. void CMessageQueue::OnNotifyLeave()
  552. {
  553. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  554. for (size_t i = 0; i < _peerArray.size(); i++)
  555. {
  556. if(_peerArray[i]!=nullptr)
  557. {
  558. _peerArray[i]->Close();
  559. _peerArray[i].reset();
  560. }
  561. /* code */
  562. }
  563. _peerId=-1;
  564. }
  565. void CMessageQueue::OnNotifyStopSensor()
  566. {
  567. _curTick=0;
  568. if(_Version)//AD10
  569. {
  570. std::cout<<"_CanBusVehicle Stop"<<std::endl;
  571. _CanBusVehicle->Stop();
  572. std::cout<<"_CanBusRadar Stop"<<std::endl;
  573. _CanBusRadar->Stop();
  574. }
  575. else
  576. {
  577. std::cout<<"_PcanBusVehicle Stop"<<std::endl;
  578. _PcanBusVehicle->Stop();
  579. std::cout<<"_RadarIp Stop"<<std::endl;
  580. _RadarIp->Stop();
  581. }
  582. std::cout << "RTK Stop" << std::endl;
  583. _Rtk->Stop();
  584. std::cout<<"mqtt Stop"<<std::endl;
  585. _Mqtt_ZR->Stop();
  586. std::cout<<"data mqtt Stop"<<std::endl;
  587. _Mqtt_SE->Stop();
  588. if(!File_fd)
  589. {
  590. fclose(File_fd);
  591. File_fd = NULL;
  592. }
  593. RemoNet::StopAck Rep;
  594. CIOBuffer Buffer;
  595. MessageHead Head;
  596. Head.Command = RemoNet::CC_StopACK;
  597. Head.Length = Rep.ByteSizeLong();
  598. Head.Serialize(Buffer.Buffer);
  599. auto ptr = Buffer.Buffer + MessageHead::Size();
  600. Rep.SerializeToArray(ptr, Head.Length);
  601. Buffer.Length = Head.Length + MessageHead::Size();
  602. _peerArray[RenderPosition::FRONT]->SendData(Buffer);
  603. }
  604. void CMessageQueue::OnVideoOffer(int32_t index,const char* type, const char* sdp)
  605. {
  606. // std::cout<<__FUNCTION__<<","<<__LINE__<<std::endl;
  607. printf ("onvideo offer9999999999999999999999999999999999999999999999999999999999999999999999999999\n");
  608. InitPeerConnection(_peerId,index);
  609. _peerArray[index]->SetRemoteDescription(type,sdp);
  610. _peerArray[index]->CreateAnswer();
  611. }
  612. void CMessageQueue::OnVideoAnswer(int32_t index, const char* type, const char* sdp)
  613. {
  614. // std::cout<<__FUNCTION__<<","<<__LINE__<<std::endl;
  615. _peerArray[index]->SetRemoteDescription(type,sdp);
  616. }
  617. void CMessageQueue::OnVideoCandidate(int32_t index,const char* candidate,
  618. int32_t sdp_mline_index,
  619. const char* sdp_mid)
  620. {
  621. _peerArray[index]->AddIceCandidate(candidate,sdp_mline_index,sdp_mid);
  622. }
  623. /*
  624. void CMessageQueue::SwitchCamera(bool front)
  625. {
  626. _peerArray[RenderPosition::FRONT_BACK]->SwitchCapture(front);
  627. }
  628. */
  629. void CMessageQueue::OnMessageFrameNotify(ChannelType type,int16_t cmd,int16_t length,const void * data)
  630. {
  631. // std::cout<<"cmd:" <<std::hex<<cmd<<std::endl;
  632. if(cmd==RemoNet::CC_Text)
  633. {
  634. RemoNet::TestTextReq Req;
  635. Req.ParseFromArray(data,length);
  636. std::cout<<Req.text()<<std::endl;
  637. CIOBuffer * pBuffer=CIOBuffer::Alloc();
  638. Message* message=reinterpret_cast<Message *>(pBuffer->Buffer);
  639. message->cmd=MessageType::AsyncMessage;
  640. EnQueue(pBuffer);
  641. }
  642. else if(cmd==RemoNet::CC_Switch)
  643. {
  644. RemoNet::CCSwitch Req;
  645. Req.ParseFromArray(data,length);
  646. bool front=Req.front();
  647. _peerArray[RenderPosition::FRONT]->SwitchCapture(front);
  648. }
  649. else if(cmd==RemoNet::CC_Ping)
  650. {
  651. RemoNet::CCPing Req;
  652. Req.ParseFromArray(data,length);
  653. CIOBuffer * pBuffer=CIOBuffer::Alloc();
  654. Message* message=reinterpret_cast<Message *>(pBuffer->Buffer);
  655. message->cmd=MessageType::Ping;
  656. message->param_l=Req.tick();
  657. EnQueue(pBuffer);
  658. }
  659. else if(cmd==RemoNet::CC_SensorStop)
  660. {
  661. CIOBuffer * pBuffer=CIOBuffer::Alloc();
  662. Message* message=reinterpret_cast<Message *>(pBuffer->Buffer);
  663. message->cmd=MessageType::StopSensor;
  664. EnQueue(pBuffer);
  665. }
  666. else if (cmd == RemoNet::CC_CANMSG)
  667. {
  668. _source = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
  669. _curTick = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
  670. RemoNet::CCCanMsg Req;
  671. Req.ParseFromArray(data, length);
  672. cannet_frame* frames = (cannet_frame*)alloca(sizeof(cannet_frame) * Req.frams_size());
  673. for (int32_t i = 0; i < Req.frams_size(); i++)
  674. {
  675. auto& frame = Req.frams(i);
  676. frames[i].canid = frame.canid();
  677. frames[i].dlc = frame.dlc();
  678. memcpy(frames[i].data, frame.data().data(), frame.dlc());
  679. }
  680. //_robot->Get()->OnMessage(frames, Req.frams_size());
  681. if(_Version)//AD10
  682. _CanBusVehicle->Get()->OnMessage(frames, Req.frams_size());
  683. else
  684. _PcanBusVehicle->Get()->OnMessage(frames, Req.frams_size());
  685. }
  686. }
  687. void CMessageQueue::StopCar()
  688. {
  689. std::cout<<"Stop Car"<<std::endl;
  690. if(_Version)//AD10
  691. _CanBusVehicle->Get()->Emergency();
  692. else
  693. _PcanBusVehicle->Get()->Emergency();
  694. }
  695. void CMessageQueue::OnNotifyMessage()
  696. {
  697. RemoNet::TestTextReq Req;
  698. Req.set_text("ewqewqewqe");
  699. CIOBuffer Buffer;
  700. MessageHead Head;
  701. Head.Command = RemoNet::CC_Text;
  702. Head.Length = Req.ByteSizeLong();
  703. Head.Serialize(Buffer.Buffer);
  704. auto ptr = Buffer.Buffer + MessageHead::Size();
  705. Req.SerializeToArray(ptr, Head.Length);
  706. Buffer.Length = Head.Length + MessageHead::Size();
  707. _peerArray[RenderPosition::FRONT]->SendData(Buffer);
  708. }
  709. void CMessageQueue::OnNotifyPing(int64_t value)
  710. {
  711. RemoNet::CCPing Rep;
  712. Rep.set_tick(value);
  713. CIOBuffer Buffer;
  714. MessageHead Head;
  715. Head.Command = RemoNet::CC_Ping;
  716. Head.Length = Rep.ByteSizeLong();
  717. Head.Serialize(Buffer.Buffer);
  718. auto ptr = Buffer.Buffer + MessageHead::Size();
  719. Rep.SerializeToArray(ptr, Head.Length);
  720. Buffer.Length = Head.Length + MessageHead::Size();
  721. //std::cout << "ping" << std::endl;
  722. if( _peerArray[RenderPosition::FRONT]!=nullptr && _peerArray[RenderPosition::FRONT]->bReadyChannel)
  723. _peerArray[RenderPosition::FRONT]->SendData(Buffer);
  724. }
  725. /*
  726. void CMessageQueue::StartCar()
  727. {
  728. _can->SetStartWrite(true);
  729. }
  730. */
  731. void CMessageQueue::CheckSignal()
  732. {
  733. if(!bStopedCar)
  734. {
  735. long long tick=std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
  736. if(_curTick!=0&&tick-_curTick > 3)
  737. {
  738. StopCar();
  739. bStopedCar=true;
  740. std::cout<<"_curTick!=0&&tick-_curTick > 3" << std::endl;
  741. _curStopTick = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
  742. btimeStopedCar = true;
  743. _curTick = 0;
  744. }
  745. }
  746. }
  747. void CMessageQueue::WriteIMUData(ImuData* data)
  748. {
  749. MessageHead Head;
  750. CIOBuffer Buffer;
  751. RemoNet::IMuMessage Req;
  752. Req.set_rx(data->ry);
  753. Req.set_ry(data->rx);
  754. // Req.set_rz(data->rz);
  755. Head.Command=RemoNet::CC_IMU;
  756. Head.Length=Req.ByteSizeLong();
  757. Head.Serialize(Buffer.Buffer);
  758. auto ptr = Buffer.Buffer + MessageHead::Size();
  759. Req.SerializeToArray(ptr, Head.Length);
  760. Buffer.Length = Head.Length + MessageHead::Size();
  761. if( _peerArray[ChannelType::CHANNEL_IMU]!=nullptr)
  762. _peerArray[ChannelType::CHANNEL_IMU]->SendData(Buffer);
  763. }
  764. void CMessageQueue::WritePacket(ChannelType type, CIOBuffer & pBuffer)
  765. {
  766. if( _peerArray[type]!=nullptr)
  767. _peerArray[type]->SendData(pBuffer);
  768. }
  769. void CMessageQueue::WriteRadarData(RadarData& data)
  770. {
  771. MessageHead Head;
  772. CIOBuffer Buffer;
  773. RemoNet::CCRadarMessage Req;
  774. Req.set_radar0(data.r0);
  775. Req.set_radar1(data.r1);
  776. Req.set_radar2(data.r2);
  777. Req.set_radar3(data.r3);
  778. Req.set_radar4(data.r4);
  779. Req.set_radar5(data.r5);
  780. Req.set_radar6(data.r6);
  781. Req.set_radar7(data.r7);
  782. //Head.Command=RemoNet::CC_IMU;
  783. Head.Command = RemoNet::CC_Radar;
  784. Head.Length=Req.ByteSizeLong();
  785. Head.Serialize(Buffer.Buffer);
  786. auto ptr = Buffer.Buffer + MessageHead::Size();
  787. Req.SerializeToArray(ptr, Head.Length);
  788. Buffer.Length = Head.Length + MessageHead::Size();
  789. if( _peerArray[ChannelType::CHANNEL_RADAR]!=nullptr)
  790. _peerArray[ChannelType::CHANNEL_RADAR]->SendData(Buffer);
  791. }
  792. void CMessageQueue::WriteRobotStatus(int32_t ,int32_t )
  793. {
  794. }
  795. #ifdef LIDAR_SENSOR
  796. void CMessageQueue::WriteLidarPoint(const PointCloudMsg<PointXYZI>& msg,ChannelType side)
  797. {
  798. RemoNet::LidarPoint pt;
  799. pt.set_is_left(side==ChannelType::CHANNEL_LEFT_LIDAR);
  800. pt.set_frame_id(msg.frame_id);
  801. pt.set_height(msg.height);
  802. pt.set_width(msg.width);
  803. pt.set_is_dense(msg.is_dense);
  804. pt.set_seq(msg.seq);
  805. pt.set_timestamp(msg.timestamp);
  806. for(int i=0;i<msg.point_cloud_ptr->size();i++)
  807. {
  808. pt.add_data((*msg.point_cloud_ptr)[i].x);
  809. pt.add_data((*msg.point_cloud_ptr)[i].y);
  810. pt.add_data((*msg.point_cloud_ptr)[i].z);
  811. pt.add_data((*msg.point_cloud_ptr)[i].intensity);
  812. }
  813. MessageHead Head;
  814. CIOBuffer Buffer;
  815. Head.Command=RemoNet::CC_LIDARDATA;
  816. Head.Length=pt.ByteSizeLong();
  817. Head.Serialize(Buffer.Buffer);
  818. auto ptr = Buffer.Buffer + MessageHead::Size();
  819. pt.SerializeToArray(ptr, Head.Length);
  820. Buffer.Length = Head.Length + MessageHead::Size();
  821. if( _peerArray[side]!=nullptr)
  822. _peerArray[side]->SendData(&Buffer);
  823. }
  824. #endif
  825. void CMessageQueue::SwitchCamera(bool front)
  826. {
  827. _peerArray[RenderPosition::FRONT]->SwitchCapture(front);
  828. _peerArray[RenderPosition::BACK]->SwitchCapture(front);
  829. }
  830. void CMessageQueue::SendZGJStatus(int status)
  831. {
  832. _Rtk->Get()->Send_ZGJ_status(status);
  833. }
  834. void CMessageQueue::SendVehicleStatus(int16_t Direction,int16_t Hand_Throttle,int16_t Foot_Throttle,int16_t Brake)
  835. {
  836. //CDataMqttSensor::sendMessage()
  837. if (CDataMqttSensor::_run)
  838. {
  839. time_t rawtime;
  840. struct tm* info;
  841. time(&rawtime);
  842. info = localtime(&rawtime);
  843. char secret[64] = { 0 };
  844. sprintf((char*)secret, "%d-%.2d-%.2d %.2d:%.2d:%.2d", info->tm_year + 1900, info->tm_mon + 1, info->tm_mday,info->tm_hour,info->tm_min,info->tm_sec);
  845. printf("%s\r\n",secret);
  846. char WriteLocalDat[128];
  847. memset(WriteLocalDat,0,128);
  848. sprintf(WriteLocalDat, "%d-%.2d-%.2d %.2d:%.2d:%.2d 方向值:%d 手油门值:%d 脚油门值:%d 刹车值:%d\n", info->tm_year + 1900, info->tm_mon + 1, info->tm_mday,info->tm_hour,info->tm_min,info->tm_sec,
  849. Direction,Hand_Throttle,Foot_Throttle,Brake);
  850. fwrite(WriteLocalDat, strlen(WriteLocalDat) , 1, File_fd);
  851. Json::Value root;
  852. Json::Value Source;
  853. Json::FastWriter writer;
  854. std::string SendTime;
  855. Source["1"] = SendTime.assign(secret,strlen(secret));//发送时间
  856. Source["2"] = Direction;//方向值
  857. Source["3"] = Hand_Throttle;//手油门值
  858. Source["4"] = Foot_Throttle;//脚油门值
  859. Source["5"] = Brake;//刹车值
  860. Json::StyledWriter sw;
  861. //std::cout << sw.write(Source) << std::endl << std::endl;
  862. if (!DataMqtt_SendDate)
  863. {
  864. DataMqtt_curTick = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
  865. DataMqtt_SendDate = true;
  866. }
  867. else
  868. {
  869. long long tick = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
  870. if (DataMqtt_curTick != 0 && tick - DataMqtt_curTick > 10000)
  871. {
  872. if (CDataMqttSensor::_run && (CDataMqttSensor::m_mqttClient != NULL))
  873. CDataMqttSensor::sendMessage((char*)sw.write(Source).c_str(), 0, (char*)"bg/log");
  874. DataMqtt_SendDate = false;
  875. }
  876. }
  877. }
  878. }