message_queue.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  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. //20230412
  180. //_Mqtt_ZR = std::make_unique<CMqtt>(this);
  181. //_Mqtt_ZR->start();
  182. //_can=std::make_unique<SocketCan>(this);
  183. //_can->Start(_canip,_canport,_hostport);
  184. std::this_thread::yield();
  185. // OnNotifyReq(0);
  186. }
  187. /*
  188. void CMessageQueue::WriteCanMessage(std::unordered_map<int32_t, cannet_frame>& node,bool islidar)
  189. {
  190. if(!bDataChannelCreated) return;
  191. // std::lock_guard<std::mutex> l(_canLock);
  192. RemoNet::CCCanMesage Req;
  193. Req.set_islidar(islidar);
  194. for(auto& p:node)
  195. {
  196. int32_t lidar=p.second.canid;
  197. auto m=Req.add_message();
  198. m->set_head(p.second.dlc);
  199. m->set_canid(lidar);
  200. m->set_data(p.second.data,8);
  201. }
  202. MessageHead Head;
  203. CIOBuffer pBuffer;
  204. Head.Command = RemoNet::CC_CAN;
  205. Head.Length = Req.ByteSizeLong();
  206. Head.Serialize(pBuffer.Buffer);
  207. auto ptr = pBuffer.Buffer + MessageHead::Size();
  208. Req.SerializeToArray(ptr, Head.Length);
  209. pBuffer.Length = MessageHead::Size() + Head.Length;
  210. _peerArray[0]->SendData(&pBuffer);
  211. }
  212. bool CMessageQueue::IsCarId(int32_t value)
  213. {
  214. return std::find(_carArray.begin(),_carArray.end(),value)!=_carArray.end();
  215. }
  216. */
  217. void CMessageQueue::EnQueue(CIOBuffer* pBuffer)
  218. {
  219. bool bNullBuffer=false;
  220. std::unique_lock <std::mutex> lck(_lock);
  221. if(Head==nullptr)
  222. {
  223. Head=Tail=pBuffer;
  224. bNullBuffer=true;
  225. }
  226. else{
  227. Tail->NextBuf=pBuffer;
  228. Tail=Tail->NextBuf;
  229. }
  230. pBuffer->NextBuf=nullptr;
  231. if(bNullBuffer)
  232. {
  233. //_cv.notify_one();
  234. //20231023
  235. _cv.notify_all();
  236. }
  237. }
  238. void CMessageQueue::Process()
  239. {
  240. CIOBuffer * ptr=nullptr;
  241. {
  242. std::unique_lock <std::mutex> lck(_lock);
  243. /*
  244. while(Head==nullptr)
  245. {
  246. _cv.wait(lck);
  247. }
  248. */
  249. while(Head==nullptr&&_cv.wait_for(lck,std::chrono::seconds(1))==std::cv_status::timeout)
  250. {
  251. CheckSignal();
  252. //std::cout<<".";
  253. //std::cout.flush();
  254. }
  255. }
  256. while(Head!=nullptr)
  257. {
  258. ptr=Head;
  259. Head=Head->NextBuf;
  260. if(ptr!=nullptr)
  261. {
  262. Message* message=reinterpret_cast<Message *>(ptr->Buffer);
  263. switch (message->cmd)
  264. {
  265. case MessageType::ReqVideo:
  266. OnNotifyReq((int32_t)message->param_l);
  267. break;
  268. case MessageType::RepVideo:
  269. OnNotifyRep((int32_t)message->param_l);
  270. break;
  271. case MessageType::Connected:
  272. OnNotifyConnected((bool)message->param_l);
  273. break;
  274. case MessageType::Leave:
  275. OnNotifyLeave();
  276. break;
  277. case MessageType::AsyncMessage:
  278. OnNotifyMessage();
  279. break;
  280. case MessageType::StopSensor:
  281. OnNotifyStopSensor();
  282. break;
  283. case MessageType::Ping:
  284. OnNotifyPing(message->param_l);
  285. break;
  286. }
  287. ptr->Release();
  288. }
  289. }
  290. }
  291. void CMessageQueue::SetTick(long long tick)
  292. {
  293. _curTick=tick;
  294. }
  295. void CMessageQueue::OnNotifyConnected(bool bRet)
  296. {
  297. if(bRet)
  298. {
  299. _client->WriteAddRobot(_serial,_name,static_cast<int32_t>(EgoType::Car));
  300. _updatethread.start(_client.get());
  301. //cs->Analog(0,0,0,0,0);
  302. }
  303. else
  304. {
  305. if(_peerId!=-1)
  306. {
  307. OnVideoLeave(_peerId,EgoType::User);
  308. _peerId=-1;
  309. }
  310. _updatethread.stop();
  311. }
  312. }
  313. int day_diffient(int year_start, int month_start, int day_start,char *Dst)
  314. {
  315. //2024-03-11
  316. int year_end = strtol(Dst,NULL,10);
  317. char Temp = '-',*p = NULL,*p1 = NULL;
  318. p = strchr(Dst,Temp);
  319. int month_end = strtol(p + 1,NULL,10);
  320. p1 = strchr(p + 1,Temp);
  321. int day_end = strtol(p1 + 1,NULL,10);
  322. int y2, m2, d2;
  323. int y1, m1, d1;
  324. m1 = (month_start + 9) % 12;
  325. y1 = year_start - m1/10;
  326. d1 = 365*y1 + y1/4 - y1/100 + y1/400 + (m1*306 + 5)/10 + (day_start - 1);
  327. m2 = (month_end + 9) % 12;
  328. y2 = year_end - m2/10;
  329. d2 = 365*y2 + y2/4 - y2/100 + y2/400 + (m2*306 + 5)/10 + (day_end - 1);
  330. return (d1 - d2);
  331. }
  332. void delete_days(const char *path)
  333. {
  334. DIR *dir;
  335. struct dirent *entry;
  336. struct stat statbuf;
  337. time_t rawtime;
  338. struct tm* info;
  339. time(&rawtime);
  340. info = localtime(&rawtime);
  341. uint8_t secret[64] = { 0 };
  342. sprintf((char*)secret, "%d-%.2d-%.2d.log", info->tm_year + 1900, info->tm_mon + 1, info->tm_mday);
  343. printf("%s\r\n",secret);
  344. dir = opendir(path);
  345. if (dir == NULL)
  346. {
  347. printf("无法打开目录\n");
  348. return;
  349. }
  350. while ((entry = readdir(dir)) != NULL)
  351. {
  352. if(entry->d_name[0]=='.')
  353. continue;
  354. //printf("%s\n",entry->d_name);
  355. if(day_diffient(info->tm_year + 1900, info->tm_mon + 1, info->tm_mday,entry->d_name) > 15)
  356. {
  357. char Dst[128];
  358. memset(Dst,0,128);
  359. sprintf(Dst,"rm -rf /home/nvidia/20240226ZGJ-PORT/EgoZJ/EgoSystem/build/log/%s",entry->d_name);
  360. system(Dst);
  361. }
  362. }
  363. closedir(dir);
  364. }
  365. void CMessageQueue::SerichFile(char *filename)
  366. {
  367. DIR *directory_pointer;
  368. struct dirent *entry;
  369. int exist = 0;
  370. char Dst[128];
  371. memset(Dst,0,128);
  372. sprintf(Dst,"/home/nvidia/20240226ZGJ-PORT/EgoZJ/EgoSystem/build/log/%s",filename);
  373. if((directory_pointer=opendir("/home/nvidia/20240226ZGJ-PORT/EgoZJ/EgoSystem/build/log/")) == NULL)
  374. printf("Error open\n");
  375. else
  376. {
  377. while((entry=readdir(directory_pointer)) != NULL)
  378. {
  379. if(entry->d_name[0]=='.') continue;
  380. printf("%s\n",entry->d_name);
  381. if(!strcmp(entry->d_name,filename))
  382. {
  383. File_fd = fopen(Dst, "a");
  384. exist = 1;
  385. break;
  386. }
  387. }
  388. }
  389. if(!exist)
  390. File_fd = fopen(Dst, "w+");
  391. closedir(directory_pointer);
  392. }
  393. void CMessageQueue::OnNotifyReq(int32_t index)
  394. {
  395. // std::cout<<__FUNCTION__<<","<<__LINE__<<std::endl;
  396. if(_peerId==-1) return;
  397. if(index==0)
  398. {
  399. mrsWebrtcCreateFactory(true);
  400. _curTick=0;
  401. bStopedCar=false;
  402. _Rtk->Start();
  403. if(_Version)//AD10
  404. {
  405. _CanBusVehicle->Start();
  406. _CanBusRadar->Start();
  407. }
  408. else
  409. {
  410. _PcanBusVehicle->Start();
  411. _RadarIp->Start();
  412. }
  413. _Mqtt_ZR->Start();
  414. _Mqtt_SE->Start();
  415. File_fd = NULL;
  416. struct statfs diskInfo;
  417. statfs("/dev/mmcblk0p1", &diskInfo);
  418. unsigned long long freeDisk = diskInfo.f_bfree * diskInfo.f_bsize;
  419. time_t rawtime;
  420. struct tm* info;
  421. time(&rawtime);
  422. info = localtime(&rawtime);
  423. uint8_t secret[64] = { 0 };
  424. sprintf((char*)secret, "%d-%.2d-%.2d.log", info->tm_year + 1900, info->tm_mon + 1, info->tm_mday);
  425. if((freeDisk >> 30) < 15)
  426. {
  427. system("rm -rf /home/nvidia/20240226ZGJ-PORT/EgoZJ/EgoSystem/build/log");
  428. system("mkdir /home/nvidia/20240226ZGJ-PORT/EgoZJ/EgoSystem/build/log/");
  429. }
  430. else
  431. delete_days("/home/nvidia/20240226ZGJ-PORT/EgoZJ/EgoSystem/build/log");
  432. SerichFile((char *)secret);
  433. }
  434. _peerArray[index]=std::make_unique<CPeerConnection>(static_cast<ChannelType>(index),_client.get());
  435. _client->WriteVideoRep(_peerId, RemoNet::VideoDesc::OK, index);
  436. }
  437. void CMessageQueue::OnNotifyRep(int32_t index)
  438. {
  439. _peerArray[index]=std::make_unique<CPeerConnection>(static_cast<ChannelType>(index), _client.get());
  440. InitPeerConnection(_peerId,index);
  441. _peerArray[index]->CreateOffer();
  442. }
  443. void CMessageQueue::InitPeerConnection(int32_t peer,int32_t index)
  444. {
  445. _peerArray[index]->Initialize(peer,index,_UdpMinPort,_UdpMaxPort);
  446. _peerArray[index]->AddDataChannel(true, false);
  447. _peerArray[index]->AddLocalVideoTrack(static_cast<RenderPosition>(index),_cameraArray[index].index);
  448. if(index==RenderPosition::BACK)
  449. {
  450. void * front=_peerArray[RenderPosition::FRONT]->GetCurrentCtx();
  451. while(front==nullptr)
  452. {
  453. std::cout<<"front==nullptr"<<std::endl;
  454. std::this_thread::sleep_for(std::chrono::microseconds(50));
  455. front=_peerArray[RenderPosition::FRONT]->GetCurrentCtx();
  456. }
  457. void * back=_peerArray[RenderPosition::BACK]->GetCurrentCtx();
  458. while (back==nullptr)
  459. {
  460. std::cout<<"back==nullptr"<<std::endl;
  461. std::this_thread::sleep_for(std::chrono::microseconds(50));
  462. back=_peerArray[RenderPosition::BACK]->GetCurrentCtx();
  463. }
  464. _peerArray[RenderPosition::FRONT]->SetOtherCtx(back);
  465. _peerArray[RenderPosition::BACK]->SetOtherCtx(front);
  466. }
  467. /*
  468. if((index+1)==RenderPosition::ALL)
  469. {
  470. void * front=_peerArray[RenderPosition::FRONT]->GetCurrentCtx();
  471. while(front==nullptr)
  472. {
  473. std::cout<<"front==nullptr"<<std::endl;
  474. std::this_thread::sleep_for(std::chrono::microseconds(50));
  475. front=_peerArray[RenderPosition::FRONT]->GetCurrentCtx();
  476. }
  477. void * back=_peerArray[RenderPosition::BACK]->GetCurrentCtx();
  478. while (back==nullptr)
  479. {
  480. std::cout<<"back==nullptr"<<std::endl;
  481. std::this_thread::sleep_for(std::chrono::microseconds(50));
  482. back=_peerArray[RenderPosition::BACK]->GetCurrentCtx();
  483. }
  484. _peerArray[RenderPosition::FRONT]->SetOtherCtx(back);
  485. _peerArray[RenderPosition::BACK]->SetOtherCtx(front);
  486. void * left=_peerArray[RenderPosition::LEFT]->GetCurrentCtx();
  487. while(left==nullptr)
  488. {
  489. std::cout<<"left==nullptr"<<std::endl;
  490. std::this_thread::sleep_for(std::chrono::microseconds(50));
  491. front=_peerArray[RenderPosition::LEFT]->GetCurrentCtx();
  492. }
  493. void * right=_peerArray[RenderPosition::RIGHT]->GetCurrentCtx();
  494. while (right==nullptr)
  495. {
  496. std::cout<<"right==nullptr"<<std::endl;
  497. std::this_thread::sleep_for(std::chrono::microseconds(50));
  498. back=_peerArray[RenderPosition::RIGHT]->GetCurrentCtx();
  499. }
  500. _peerArray[RenderPosition::LEFT]->SetOtherCtx(right);
  501. _peerArray[RenderPosition::RIGHT]->SetOtherCtx(left);
  502. }
  503. */
  504. /*
  505. if((index+1)==RenderPosition::ALL)
  506. {
  507. void * front=_peerArray[RenderPosition::FRONT]->GetCurrentCtx();
  508. void * back=_peerArray[RenderPosition::BACK]->GetCurrentCtx();
  509. void * left=_peerArray[RenderPosition::LEFT]->GetCurrentCtx();
  510. void * right=_peerArray[RenderPosition::RIGHT]->GetCurrentCtx();
  511. void * dash=_peerArray[RenderPosition::DASHBOARD]->GetCurrentCtx();
  512. _peerArray[RenderPosition::FRONT]->SetOtherCtx(back);
  513. _peerArray[RenderPosition::BACK]->SetOtherCtx(front);
  514. _peerArray[RenderPosition::LEFT]->SetOtherCtx(left);
  515. _peerArray[RenderPosition::RIGHT]->SetOtherCtx(right);
  516. _peerArray[RenderPosition::DASHBOARD]->SetOtherCtx(dash);
  517. }
  518. */
  519. if(index==RenderPosition::FRONT)
  520. _peerArray[index]->AddLocalAudioTrack();
  521. }
  522. void CMessageQueue::OnAdd(bool bRet)
  523. {
  524. }
  525. void CMessageQueue::OnConnected(bool bRet)
  526. {
  527. CIOBuffer * pBuffer=CIOBuffer::Alloc();
  528. Message* message=reinterpret_cast<Message *>(pBuffer->Buffer);
  529. message->cmd=MessageType::Connected;
  530. message->param_l=bRet;
  531. EnQueue(pBuffer);
  532. }
  533. void CMessageQueue::OnVideoLeave(int32_t peer,EgoType type)
  534. {
  535. {
  536. CIOBuffer * pBuffer=CIOBuffer::Alloc();
  537. Message* message=reinterpret_cast<Message *>(pBuffer->Buffer);
  538. message->cmd=MessageType::StopSensor;
  539. EnQueue(pBuffer);
  540. }
  541. {
  542. CIOBuffer * pBuffer=CIOBuffer::Alloc();
  543. Message* message=reinterpret_cast<Message *>(pBuffer->Buffer);
  544. message->cmd=MessageType::Leave;
  545. EnQueue(pBuffer);
  546. }
  547. }
  548. #ifdef WIN32
  549. void CMessageQueue::OnVideoRep(int32_t index,RemoNet::VideoDesc desc)
  550. {
  551. if (desc == RemoNet::VideoDesc::OK)
  552. {
  553. assert(_peerId!=-1);
  554. CIOBuffer * pBuffer=CIOBuffer::Alloc();
  555. Message* message=reinterpret_cast<Message *>(pBuffer->Buffer);
  556. message->cmd=MessageType::ReqVideo;
  557. message->param_l=index;
  558. EnQueue(pBuffer);
  559. }
  560. }
  561. #else
  562. void CMessageQueue::OnVideoReq(int32_t video,int32_t peer)
  563. {
  564. // std::cout<<__FUNCTION__<<","<<__LINE__<<std::endl;
  565. _peerId=peer;
  566. CIOBuffer * pBuffer=CIOBuffer::Alloc();
  567. Message* message=reinterpret_cast<Message *>(pBuffer->Buffer);
  568. message->cmd=MessageType::ReqVideo;
  569. message->param_l=video;
  570. EnQueue(pBuffer);
  571. }
  572. #endif
  573. void CMessageQueue::OnNotifyLeave()
  574. {
  575. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  576. for (size_t i = 0; i < _peerArray.size(); i++)
  577. {
  578. if(_peerArray[i]!=nullptr)
  579. {
  580. _peerArray[i]->Close();
  581. _peerArray[i].reset();
  582. }
  583. /* code */
  584. }
  585. _peerId=-1;
  586. }
  587. void CMessageQueue::OnNotifyStopSensor()
  588. {
  589. _curTick=0;
  590. if(_Version)//AD10
  591. {
  592. std::cout<<"_CanBusVehicle Stop"<<std::endl;
  593. _CanBusVehicle->Stop();
  594. std::cout<<"_CanBusRadar Stop"<<std::endl;
  595. _CanBusRadar->Stop();
  596. }
  597. else
  598. {
  599. std::cout<<"_PcanBusVehicle Stop"<<std::endl;
  600. _PcanBusVehicle->Stop();
  601. std::cout<<"_RadarIp Stop"<<std::endl;
  602. _RadarIp->Stop();
  603. }
  604. std::cout << "RTK Stop" << std::endl;
  605. _Rtk->Stop();
  606. std::cout<<"mqtt Stop"<<std::endl;
  607. _Mqtt_ZR->Stop();
  608. std::cout<<"data mqtt Stop"<<std::endl;
  609. _Mqtt_SE->Stop();
  610. if(!File_fd)
  611. {
  612. fclose(File_fd);
  613. File_fd = NULL;
  614. }
  615. RemoNet::StopAck Rep;
  616. CIOBuffer Buffer;
  617. MessageHead Head;
  618. Head.Command = RemoNet::CC_StopACK;
  619. Head.Length = Rep.ByteSizeLong();
  620. Head.Serialize(Buffer.Buffer);
  621. auto ptr = Buffer.Buffer + MessageHead::Size();
  622. Rep.SerializeToArray(ptr, Head.Length);
  623. Buffer.Length = Head.Length + MessageHead::Size();
  624. _peerArray[RenderPosition::FRONT]->SendData(Buffer);
  625. }
  626. void CMessageQueue::OnVideoOffer(int32_t index,const char* type, const char* sdp)
  627. {
  628. // std::cout<<__FUNCTION__<<","<<__LINE__<<std::endl;
  629. InitPeerConnection(_peerId,index);
  630. _peerArray[index]->SetRemoteDescription(type,sdp);
  631. _peerArray[index]->CreateAnswer();
  632. }
  633. void CMessageQueue::OnVideoAnswer(int32_t index, const char* type, const char* sdp)
  634. {
  635. // std::cout<<__FUNCTION__<<","<<__LINE__<<std::endl;
  636. _peerArray[index]->SetRemoteDescription(type,sdp);
  637. }
  638. void CMessageQueue::OnVideoCandidate(int32_t index,const char* candidate,
  639. int32_t sdp_mline_index,
  640. const char* sdp_mid)
  641. {
  642. _peerArray[index]->AddIceCandidate(candidate,sdp_mline_index,sdp_mid);
  643. }
  644. /*
  645. void CMessageQueue::SwitchCamera(bool front)
  646. {
  647. _peerArray[RenderPosition::FRONT_BACK]->SwitchCapture(front);
  648. }
  649. */
  650. void CMessageQueue::OnMessageFrameNotify(ChannelType type,int16_t cmd,int16_t length,const void * data)
  651. {
  652. // std::cout<<"cmd:" <<std::hex<<cmd<<std::endl;
  653. if(cmd==RemoNet::CC_Text)
  654. {
  655. RemoNet::TestTextReq Req;
  656. Req.ParseFromArray(data,length);
  657. std::cout<<Req.text()<<std::endl;
  658. CIOBuffer * pBuffer=CIOBuffer::Alloc();
  659. Message* message=reinterpret_cast<Message *>(pBuffer->Buffer);
  660. message->cmd=MessageType::AsyncMessage;
  661. EnQueue(pBuffer);
  662. }
  663. else if(cmd==RemoNet::CC_Switch)
  664. {
  665. RemoNet::CCSwitch Req;
  666. Req.ParseFromArray(data,length);
  667. bool front=Req.front();
  668. _peerArray[RenderPosition::FRONT]->SwitchCapture(front);
  669. }
  670. else if(cmd==RemoNet::CC_Ping)
  671. {
  672. RemoNet::CCPing Req;
  673. Req.ParseFromArray(data,length);
  674. CIOBuffer * pBuffer=CIOBuffer::Alloc();
  675. Message* message=reinterpret_cast<Message *>(pBuffer->Buffer);
  676. message->cmd=MessageType::Ping;
  677. message->param_l=Req.tick();
  678. EnQueue(pBuffer);
  679. }
  680. else if(cmd==RemoNet::CC_SensorStop)
  681. {
  682. CIOBuffer * pBuffer=CIOBuffer::Alloc();
  683. Message* message=reinterpret_cast<Message *>(pBuffer->Buffer);
  684. message->cmd=MessageType::StopSensor;
  685. EnQueue(pBuffer);
  686. }
  687. else if (cmd == RemoNet::CC_CANMSG)
  688. {
  689. _source = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
  690. _curTick = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
  691. RemoNet::CCCanMsg Req;
  692. Req.ParseFromArray(data, length);
  693. cannet_frame* frames = (cannet_frame*)alloca(sizeof(cannet_frame) * Req.frams_size());
  694. for (int32_t i = 0; i < Req.frams_size(); i++)
  695. {
  696. auto& frame = Req.frams(i);
  697. frames[i].canid = frame.canid();
  698. frames[i].dlc = frame.dlc();
  699. memcpy(frames[i].data, frame.data().data(), frame.dlc());
  700. }
  701. //_robot->Get()->OnMessage(frames, Req.frams_size());
  702. if(_Version)//AD10
  703. _CanBusVehicle->Get()->OnMessage(frames, Req.frams_size());
  704. else
  705. _PcanBusVehicle->Get()->OnMessage(frames, Req.frams_size());
  706. }
  707. }
  708. void CMessageQueue::StopCar()
  709. {
  710. std::cout<<"Stop Car"<<std::endl;
  711. if(_Version)//AD10
  712. _CanBusVehicle->Get()->Emergency();
  713. else
  714. _PcanBusVehicle->Get()->Emergency();
  715. }
  716. void CMessageQueue::OnNotifyMessage()
  717. {
  718. RemoNet::TestTextReq Req;
  719. Req.set_text("ewqewqewqe");
  720. CIOBuffer Buffer;
  721. MessageHead Head;
  722. Head.Command = RemoNet::CC_Text;
  723. Head.Length = Req.ByteSizeLong();
  724. Head.Serialize(Buffer.Buffer);
  725. auto ptr = Buffer.Buffer + MessageHead::Size();
  726. Req.SerializeToArray(ptr, Head.Length);
  727. Buffer.Length = Head.Length + MessageHead::Size();
  728. _peerArray[RenderPosition::FRONT]->SendData(Buffer);
  729. }
  730. void CMessageQueue::OnNotifyPing(int64_t value)
  731. {
  732. RemoNet::CCPing Rep;
  733. Rep.set_tick(value);
  734. CIOBuffer Buffer;
  735. MessageHead Head;
  736. Head.Command = RemoNet::CC_Ping;
  737. Head.Length = Rep.ByteSizeLong();
  738. Head.Serialize(Buffer.Buffer);
  739. auto ptr = Buffer.Buffer + MessageHead::Size();
  740. Rep.SerializeToArray(ptr, Head.Length);
  741. Buffer.Length = Head.Length + MessageHead::Size();
  742. //std::cout << "ping" << std::endl;
  743. if( _peerArray[RenderPosition::FRONT]!=nullptr && _peerArray[RenderPosition::FRONT]->bReadyChannel)
  744. _peerArray[RenderPosition::FRONT]->SendData(Buffer);
  745. }
  746. /*
  747. void CMessageQueue::StartCar()
  748. {
  749. _can->SetStartWrite(true);
  750. }
  751. */
  752. void CMessageQueue::CheckSignal()
  753. {
  754. if(!bStopedCar)
  755. {
  756. long long tick=std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
  757. if(_curTick!=0&&tick-_curTick > 3)
  758. {
  759. StopCar();
  760. bStopedCar=true;
  761. std::cout<<"_curTick!=0&&tick-_curTick > 3" << std::endl;
  762. _curStopTick = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
  763. btimeStopedCar = true;
  764. _curTick = 0;
  765. }
  766. }
  767. }
  768. void CMessageQueue::WriteIMUData(ImuData* data)
  769. {
  770. MessageHead Head;
  771. CIOBuffer Buffer;
  772. RemoNet::IMuMessage Req;
  773. Req.set_rx(data->ry);
  774. Req.set_ry(data->rx);
  775. // Req.set_rz(data->rz);
  776. Head.Command=RemoNet::CC_IMU;
  777. Head.Length=Req.ByteSizeLong();
  778. Head.Serialize(Buffer.Buffer);
  779. auto ptr = Buffer.Buffer + MessageHead::Size();
  780. Req.SerializeToArray(ptr, Head.Length);
  781. Buffer.Length = Head.Length + MessageHead::Size();
  782. if( _peerArray[ChannelType::CHANNEL_IMU]!=nullptr)
  783. _peerArray[ChannelType::CHANNEL_IMU]->SendData(Buffer);
  784. }
  785. void CMessageQueue::WritePacket(ChannelType type, CIOBuffer & pBuffer)
  786. {
  787. if( _peerArray[type]!=nullptr)
  788. _peerArray[type]->SendData(pBuffer);
  789. }
  790. void CMessageQueue::WriteRadarData(RadarData& data)
  791. {
  792. MessageHead Head;
  793. CIOBuffer Buffer;
  794. RemoNet::CCRadarMessage Req;
  795. Req.set_radar0(data.r0);
  796. Req.set_radar1(data.r1);
  797. Req.set_radar2(data.r2);
  798. Req.set_radar3(data.r3);
  799. Req.set_radar4(data.r4);
  800. Req.set_radar5(data.r5);
  801. Req.set_radar6(data.r6);
  802. Req.set_radar7(data.r7);
  803. //Head.Command=RemoNet::CC_IMU;
  804. Head.Command = RemoNet::CC_Radar;
  805. Head.Length=Req.ByteSizeLong();
  806. Head.Serialize(Buffer.Buffer);
  807. auto ptr = Buffer.Buffer + MessageHead::Size();
  808. Req.SerializeToArray(ptr, Head.Length);
  809. Buffer.Length = Head.Length + MessageHead::Size();
  810. if( _peerArray[ChannelType::CHANNEL_RADAR]!=nullptr)
  811. _peerArray[ChannelType::CHANNEL_RADAR]->SendData(Buffer);
  812. }
  813. void CMessageQueue::WriteRobotStatus(int32_t ,int32_t )
  814. {
  815. }
  816. #ifdef LIDAR_SENSOR
  817. void CMessageQueue::WriteLidarPoint(const PointCloudMsg<PointXYZI>& msg,ChannelType side)
  818. {
  819. RemoNet::LidarPoint pt;
  820. pt.set_is_left(side==ChannelType::CHANNEL_LEFT_LIDAR);
  821. pt.set_frame_id(msg.frame_id);
  822. pt.set_height(msg.height);
  823. pt.set_width(msg.width);
  824. pt.set_is_dense(msg.is_dense);
  825. pt.set_seq(msg.seq);
  826. pt.set_timestamp(msg.timestamp);
  827. for(int i=0;i<msg.point_cloud_ptr->size();i++)
  828. {
  829. pt.add_data((*msg.point_cloud_ptr)[i].x);
  830. pt.add_data((*msg.point_cloud_ptr)[i].y);
  831. pt.add_data((*msg.point_cloud_ptr)[i].z);
  832. pt.add_data((*msg.point_cloud_ptr)[i].intensity);
  833. }
  834. MessageHead Head;
  835. CIOBuffer Buffer;
  836. Head.Command=RemoNet::CC_LIDARDATA;
  837. Head.Length=pt.ByteSizeLong();
  838. Head.Serialize(Buffer.Buffer);
  839. auto ptr = Buffer.Buffer + MessageHead::Size();
  840. pt.SerializeToArray(ptr, Head.Length);
  841. Buffer.Length = Head.Length + MessageHead::Size();
  842. if( _peerArray[side]!=nullptr)
  843. _peerArray[side]->SendData(&Buffer);
  844. }
  845. #endif
  846. void CMessageQueue::SwitchCamera(bool front)
  847. {
  848. _peerArray[RenderPosition::FRONT]->SwitchCapture(front);
  849. _peerArray[RenderPosition::BACK]->SwitchCapture(front);
  850. }
  851. void CMessageQueue::SendZGJStatus(int status)
  852. {
  853. _Rtk->Get()->Send_ZGJ_status(status);
  854. }
  855. void CMessageQueue::SendVehicleStatus(int16_t Direction,int16_t Hand_Throttle,int16_t Foot_Throttle,int16_t Brake)
  856. {
  857. //CDataMqttSensor::sendMessage()
  858. if (CDataMqttSensor::_run)
  859. {
  860. time_t rawtime;
  861. struct tm* info;
  862. time(&rawtime);
  863. info = localtime(&rawtime);
  864. char secret[64] = { 0 };
  865. 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);
  866. printf("%s\r\n",secret);
  867. char WriteLocalDat[128];
  868. memset(WriteLocalDat,0,128);
  869. 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,
  870. Direction,Hand_Throttle,Foot_Throttle,Brake);
  871. fwrite(WriteLocalDat, strlen(WriteLocalDat) , 1, File_fd);
  872. Json::Value root;
  873. Json::Value Source;
  874. Json::FastWriter writer;
  875. std::string SendTime;
  876. Source["1"] = SendTime.assign(secret,strlen(secret));//发送时间
  877. Source["2"] = Direction;//方向值
  878. Source["3"] = Hand_Throttle;//手油门值
  879. Source["4"] = Foot_Throttle;//脚油门值
  880. Source["5"] = Brake;//刹车值
  881. Json::StyledWriter sw;
  882. //std::cout << sw.write(Source) << std::endl << std::endl;
  883. if (!DataMqtt_SendDate)
  884. {
  885. DataMqtt_curTick = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
  886. DataMqtt_SendDate = true;
  887. }
  888. else
  889. {
  890. long long tick = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
  891. if (DataMqtt_curTick != 0 && tick - DataMqtt_curTick > 10000)
  892. {
  893. if (CDataMqttSensor::_run && (CDataMqttSensor::m_mqttClient != NULL))
  894. CDataMqttSensor::sendMessage((char*)sw.write(Source).c_str(), 0, (char*)"bg/log");
  895. DataMqtt_SendDate = false;
  896. }
  897. }
  898. }
  899. }