sensor_socket.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  1. #pragma once
  2. #ifdef WIN32
  3. #ifndef WIN32_LEAN_AND_MEAN
  4. #define WIN32_LEAN_AND_MEAN
  5. #endif
  6. #include <WS2tcpip.h>
  7. #include <WinSock2.h>
  8. #define socketerrno WSAGetLastError()
  9. #define SOCKET_EAGAIN_EINPROGRESS WSAEINPROGRESS
  10. #define SOCKET_EWOULDBLOCK WSAEWOULDBLOCK
  11. #ifndef _SSIZE_T_DEFINED
  12. typedef int ssize_t;
  13. #define _SSIZE_T_DEFINED
  14. #endif
  15. #ifndef _SOCKET_T_DEFINED
  16. typedef SOCKET socket_t;
  17. #define _SOCKET_T_DEFINED
  18. #endif
  19. #else
  20. #include <unistd.h>
  21. #include <arpa/inet.h>
  22. #include <sys/types.h>
  23. #include <sys/socket.h>
  24. #include <netinet/in.h>
  25. #include <netinet/tcp.h>
  26. #include <fcntl.h>
  27. #include <poll.h>
  28. #define socketerrno errno
  29. #define SOCKET_EAGAIN_EINPROGRESS EAGAIN
  30. #define SOCKET_EWOULDBLOCK EWOULDBLOCK
  31. #define INVALID_SOCKET -1
  32. #define SOCKET_ERROR -1
  33. #ifndef _SOCKET_T_DEFINED
  34. typedef int socket_t;
  35. #define _SOCKET_T_DEFINED
  36. #endif
  37. #endif
  38. #include <thread>
  39. #include <mutex>
  40. #include <iostream>
  41. #include <unordered_map>
  42. #include "../common/comm.h"
  43. #ifdef _MAINDLG
  44. class CThreadWindow;
  45. #else
  46. class CMessageQueue;
  47. #endif
  48. class CIOBuffer;
  49. template<typename T>
  50. class SensorSocket
  51. {
  52. public:
  53. #ifdef _MAINDLG
  54. SensorSocket(CThreadWindow* q, std::string can_ip, int32_t can_port, int32_t host_port);
  55. #else
  56. SensorSocket(CMessageQueue * q,std::string can_ip,int32_t can_port,int32_t host_port);
  57. #endif
  58. bool Start(const char* ip=nullptr);
  59. void Run();
  60. void Stop();
  61. void Write(CIOBuffer * pBuffer);
  62. void Read(CIOBuffer* pBuffer);
  63. T* Get();
  64. #ifndef WIN32
  65. void SetStartRead(bool b);
  66. void SetStartWrite(bool b);
  67. #endif
  68. private:
  69. socket_t _fd;
  70. std::thread _thread;
  71. bool _run;
  72. std::string _canip;
  73. int32_t _canport;
  74. int32_t _hostport;
  75. std::mutex _lock;
  76. std::unordered_map<int32_t, cannet_frame> _message;
  77. std::unique_ptr<T> _sensorNotify;
  78. sockaddr_in _canaddr;
  79. #ifndef WIN32
  80. bool _startRead;
  81. bool _startWrite;
  82. #endif
  83. };
  84. template<typename T>
  85. #ifdef _MAINDLG
  86. SensorSocket<T>::SensorSocket(CThreadWindow* q, std::string can_ip, int32_t can_port, int32_t host_port)
  87. #else
  88. SensorSocket<T>::SensorSocket(CMessageQueue* q, std::string can_ip, int32_t can_port, int32_t host_port)
  89. #endif
  90. {
  91. _sensorNotify=std::make_unique<T>(q);
  92. _canip=can_ip;
  93. _canport=can_port;
  94. _hostport=host_port;
  95. #ifndef WIN32
  96. _startWrite=_startRead=true;
  97. #endif
  98. }
  99. template<typename T>
  100. bool SensorSocket<T>::Start(const char * ip)
  101. {
  102. #ifdef WIN32
  103. WSAData data;
  104. WSAStartup(MAKEWORD(2, 2), &data);
  105. #endif
  106. std::cout<<"SensorSocket<T>::Start"<<std::endl;
  107. _sensorNotify->SetSensorSocket(this);
  108. _fd = socket(AF_INET, SOCK_DGRAM, 0);
  109. sockaddr_in sin;
  110. sin.sin_family = AF_INET;
  111. sin.sin_port = htons(_hostport);
  112. #ifdef WIN32
  113. sin.sin_addr.s_addr = inet_addr(ip);
  114. #else
  115. sin.sin_addr.s_addr = htonl(INADDR_ANY);
  116. #endif
  117. if (::bind(_fd, (sockaddr*)&sin, sizeof(sin)) == -1)
  118. return false;
  119. _canaddr.sin_family=AF_INET;
  120. _canaddr.sin_addr.s_addr=inet_addr(_canip.c_str());
  121. _canaddr.sin_port=htons(_canport);
  122. _sensorNotify->Start();
  123. _thread = std::thread(&SensorSocket::Run, this);
  124. return true;
  125. }
  126. template<typename T>
  127. void SensorSocket<T>::Read(CIOBuffer* pBuffer)
  128. {
  129. sockaddr_in from;
  130. socklen_t fromlen=sizeof(sockaddr_in);
  131. int32_t ret = recvfrom(_fd,(char *)pBuffer->Buffer, CIOBuffer::IO_BUFFER_SIZE,0,(sockaddr*)&from,&fromlen);
  132. if (ret <= 0)
  133. {
  134. return;
  135. }
  136. pBuffer->Length=ret;
  137. }
  138. template<typename T>
  139. void SensorSocket<T>::Run()
  140. {
  141. _run = true;
  142. struct pollfd fds[1];
  143. fds[0].fd = _fd;
  144. fds[0].events = POLLIN;
  145. while (_run)
  146. {
  147. if(poll(&fds[0], 1, 1000) > 0)
  148. {
  149. if (fds[0].revents & POLLIN)
  150. {
  151. CIOBuffer pBuffer;
  152. sockaddr_in from;
  153. socklen_t fromlen=sizeof(sockaddr_in);
  154. int32_t ret = recvfrom(_fd,(char *)pBuffer.Buffer, CIOBuffer::IO_BUFFER_SIZE,0,(sockaddr*)&from,&fromlen);
  155. if (ret <= 0||!_run)
  156. {
  157. continue;
  158. }
  159. // std::cout << pBuffer.Buffer << std::endl;
  160. _sensorNotify->Notify(pBuffer.Buffer,ret);
  161. }
  162. }
  163. }
  164. std::cout<<"SensorSocket<T>::Run Finished"<<std::endl;
  165. }
  166. template<typename T>
  167. void SensorSocket<T>::Write(CIOBuffer * pBuffer)
  168. {
  169. #ifndef WIN32
  170. if(_startWrite==false) return;
  171. #endif
  172. socklen_t len=sizeof(_canaddr);
  173. int ret=::sendto(_fd,(char *)pBuffer->Buffer,pBuffer->Length,0,(const sockaddr *)&_canaddr,len);
  174. {
  175. // std::cout<<"ret = "<<ret<<" size ="<<pBuffer->Length<<std::endl;
  176. }
  177. }
  178. template<typename T>
  179. void SensorSocket<T>::Stop()
  180. {
  181. if(!_run) return;
  182. _sensorNotify->Stop();
  183. _run = false;
  184. #ifdef WIN32
  185. closesocket(_fd);
  186. #else
  187. close(_fd);
  188. #endif
  189. std::cout<<"SensorSocket<T>::Stop"<<std::endl;
  190. _thread.join();
  191. }
  192. #ifndef WIN32
  193. template<typename T>
  194. void SensorSocket<T>::SetStartRead(bool b)
  195. {
  196. _startRead=b;
  197. }
  198. template<typename T>
  199. void SensorSocket<T>::SetStartWrite(bool b)
  200. {
  201. _startWrite=b;
  202. }
  203. #endif
  204. template<typename T>
  205. T* SensorSocket<T>::Get()
  206. {
  207. return _sensorNotify.get();
  208. }
  209. template<typename T>
  210. class SensorTCP
  211. {
  212. public:
  213. #ifdef _MAINDLG
  214. SensorTCP(CThreadWindow* q, std::string can_ip, int32_t can_port, int32_t host_port);
  215. #else
  216. SensorTCP(CMessageQueue * q,std::string can_ip,int32_t can_port,int32_t host_port);
  217. #endif
  218. bool Start(const char* ip=nullptr);
  219. void Run();
  220. void Stop();
  221. void Write(CIOBuffer * pBuffer);
  222. T* Get();
  223. #ifndef WIN32
  224. void SetStartRead(bool b);
  225. void SetStartWrite(bool b);
  226. #endif
  227. private:
  228. socket_t _fd;
  229. std::thread _thread;
  230. bool _run;
  231. std::string _canip;
  232. int32_t _canport;
  233. int32_t _hostport;
  234. std::mutex _lock;
  235. std::unordered_map<int32_t, cannet_frame> _message;
  236. std::unique_ptr<T> _sensorNotify;
  237. sockaddr_in _canaddr;
  238. #ifndef WIN32
  239. bool _startRead;
  240. bool _startWrite;
  241. #endif
  242. };
  243. template<typename T>
  244. #ifdef _MAINDLG
  245. SensorTCP<T>::SensorTCP(CThreadWindow* q, std::string can_ip, int32_t can_port, int32_t host_port)
  246. #else
  247. SensorTCP<T>::SensorTCP(CMessageQueue* q, std::string can_ip, int32_t can_port, int32_t host_port)
  248. #endif
  249. {
  250. _sensorNotify=std::make_unique<T>(q);
  251. _canip=can_ip;
  252. _canport=can_port;
  253. _hostport=host_port;
  254. _run = false;
  255. #ifndef WIN32
  256. _startWrite=_startRead=true;
  257. #endif
  258. }
  259. template<typename T>
  260. bool SensorTCP<T>::Start(const char * ip)
  261. {
  262. #ifdef WIN32
  263. WSAData data;
  264. WSAStartup(MAKEWORD(2, 2), &data);
  265. #endif
  266. std::cout<<"SensorSocket<T>::Start"<<_canip<<","<<_canport<<std::endl;
  267. //_sensorNotify->SetSensorSocket(this);
  268. _fd = socket(AF_INET, SOCK_STREAM, 0);
  269. sockaddr_in sin;
  270. sin.sin_family = AF_INET;
  271. sin.sin_port = htons(_canport);
  272. #ifdef WIN32
  273. sin.sin_addr.s_addr = inet_addr(ip);
  274. #else
  275. sin.sin_addr.s_addr =inet_addr(_canip.c_str());// htonl(INADDR_ANY);
  276. #endif
  277. while (::connect(_fd, (sockaddr*)&sin, sizeof(sin)) == -1)
  278. {
  279. std::cout<< "connect "<<_canip<<" failed"<<std::endl;
  280. std::this_thread::sleep_for(std::chrono::milliseconds(2000));
  281. }
  282. if(_run == false)
  283. _thread = std::thread(&SensorTCP::Run, this);
  284. _sensorNotify->Start();
  285. return true;
  286. }
  287. template<typename T>
  288. void SensorTCP<T>::Run()
  289. {
  290. _run = true;
  291. struct pollfd fds[1];
  292. fds[0].fd = _fd;
  293. fds[0].events = POLLIN;
  294. // long long k = 0;
  295. //long long tick = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
  296. while (_run)
  297. {
  298. #ifdef WEBRTC_LINUX
  299. // _sensorNotify->PreProcess();
  300. if(poll(&fds[0], 1, 1000) > 0)
  301. {
  302. if (fds[0].revents & POLLIN)
  303. {
  304. #endif
  305. CIOBuffer pBuffer;
  306. sockaddr_in from;
  307. socklen_t fromlen=sizeof(sockaddr_in);
  308. int32_t ret = recv(_fd,(char *)pBuffer.Buffer, CIOBuffer::IO_BUFFER_SIZE,0);
  309. if (ret <= 0||!_run)
  310. {
  311. close(_fd);
  312. this->Start();
  313. }
  314. //_sensorNotify->Notify(pBuffer.Buffer,ret);
  315. #ifdef WEBRTC_LINUX
  316. }
  317. }
  318. #endif
  319. }
  320. std::cout<<"SensorSocket<T>::Run Finished"<<std::endl;
  321. }
  322. template<typename T>
  323. void SensorTCP<T>::Write(CIOBuffer * pBuffer)
  324. {
  325. #ifndef WIN32
  326. if(_startWrite==false) return;
  327. #endif
  328. socklen_t len=sizeof(_canaddr);
  329. int ret=::send(_fd,(char *)pBuffer->Buffer,pBuffer->Length,0);
  330. if(ret<=0)
  331. {
  332. std::cout<<"ret = "<<ret<<" size ="<<pBuffer->Length<<std::endl;
  333. }
  334. }
  335. template<typename T>
  336. void SensorTCP<T>::Stop()
  337. {
  338. if(!_run) return;
  339. _sensorNotify->Stop();
  340. _run = false;
  341. #ifdef WIN32
  342. closesocket(_fd);
  343. #else
  344. close(_fd);
  345. #endif
  346. std::cout<<"SensorSocket<T>::Stop"<<std::endl;
  347. _thread.join();
  348. std::cout<<"SensorSocket<T>::Stop finished"<<std::endl;
  349. }
  350. #ifndef WIN32
  351. template<typename T>
  352. void SensorTCP<T>::SetStartRead(bool b)
  353. {
  354. _startRead=b;
  355. }
  356. template<typename T>
  357. void SensorTCP<T>::SetStartWrite(bool b)
  358. {
  359. _startWrite=b;
  360. }
  361. #endif
  362. template<typename T>
  363. T* SensorTCP<T>::Get()
  364. {
  365. return _sensorNotify.get();
  366. }
  367. #include "../thirdparty/Mqtt/include/MQTTAsync.h"
  368. #include <string.h>
  369. //20230414 中软
  370. template<typename T>
  371. class SensorMQTT
  372. {
  373. public:
  374. SensorMQTT(CMessageQueue* q, std::string Server_Address, std::string Esn, std::string Password, std::string Clientid);
  375. bool Start();
  376. //void Run();
  377. void Stop();
  378. void Write(CIOBuffer* pBuffer, const char* pubTopic);
  379. T* Get();
  380. private:
  381. MQTTAsync mqttClient;
  382. //std::thread _thread;
  383. std::string _Server_Address;
  384. std::string _Esn;
  385. std::string _Password;
  386. std::string _ClientID;
  387. //std::mutex _lock;
  388. //std::unordered_map<int32_t, cannet_frame> _message;
  389. std::unique_ptr<T> _sensorNotify;
  390. };
  391. template<typename T>
  392. SensorMQTT<T>::SensorMQTT(CMessageQueue* q, std::string Server_Address, std::string Esn, std::string Password, std::string Clientid)
  393. {
  394. _sensorNotify = std::make_unique<T>(q);
  395. _Server_Address = Server_Address;
  396. _Esn = Esn;
  397. _Password = Password;
  398. _ClientID = Clientid;
  399. }
  400. template<typename T>
  401. bool SensorMQTT<T>::Start()
  402. {
  403. std::cout << "SensorMQTT<T>::Start" << _Server_Address << "," << _Esn << "," << _Password << "," << _ClientID <<std::endl;
  404. int rc = 0;
  405. MQTTAsync_create(&mqttClient, _Server_Address.c_str(), _ClientID.c_str(), MQTTCLIENT_PERSISTENCE_NONE, NULL);
  406. _sensorNotify->SetSensorMQTT(mqttClient, _Esn);
  407. MQTTAsync_setCallbacks(mqttClient, NULL, _sensorNotify->Disconnect, _sensorNotify->RecevieMessage, NULL); //�������ӶϿ��ͽ������ݻص�
  408. MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer; //��ʼ���ṹ��
  409. conn_opts.cleansession = 1;
  410. conn_opts.username = _Esn.c_str();
  411. conn_opts.password = _Password.c_str();
  412. conn_opts.onFailure = _sensorNotify->onConnectFailure; //����ʧ�ܻص�
  413. conn_opts.context = mqttClient;
  414. conn_opts.automaticReconnect = true; //�����Ͽ��Զ�����
  415. conn_opts.minRetryInterval = 5; //��С�������ʱ��(��)��ÿ��ʧ���������ʱ�䶼��ӱ�
  416. conn_opts.maxRetryInterval = 365 * 24 * 60 * 60; //����������ʱ��(��)
  417. MQTTAsync_setConnected(mqttClient, (char *)conn_opts.username , _sensorNotify->onConnectCallCBack); //�������ӳɹ��ص�,�����ǵ�һ�����ӳɹ����������ɹ�������ô˻ص�
  418. if ((rc = MQTTAsync_connect(mqttClient, &conn_opts)) != MQTTASYNC_SUCCESS) //��������
  419. {
  420. std::cout << "MQTTAsync_connect() fail, error code: " << rc << std::endl;
  421. }
  422. //_thread = std::thread(&SensorMQTT::Run, this);
  423. //_sensorNotify->Start();
  424. return true;
  425. }
  426. template<typename T>
  427. void SensorMQTT<T>::Stop()
  428. {
  429. _sensorNotify->Stop(_Esn.c_str());
  430. std::cout << "SensorMQTT<T>::Stop" << std::endl;
  431. }
  432. template<typename T>
  433. T* SensorMQTT<T>::Get()
  434. {
  435. return _sensorNotify.get();
  436. }
  437. template<typename T>
  438. void SensorMQTT<T>::Write(CIOBuffer* pBuffer, const char* pubTopic)
  439. {
  440. _sensorNotify->sendMessage((char *)pBuffer->Buffer,1,pubTopic);
  441. }
  442. #include <unistd.h>
  443. #include <net/if.h>
  444. #include <sys/ioctl.h>
  445. #include <sys/socket.h>
  446. #include <linux/can.h>
  447. #include <linux/can/raw.h>
  448. #include <linux/can/error.h>
  449. //20231128 CANBUS
  450. template<typename T>
  451. class SensorCanBus
  452. {
  453. public:
  454. SensorCanBus(CMessageQueue* q,std::string CanName);
  455. bool Start();
  456. void Run();
  457. void Stop();
  458. void Write(can_frame *date);
  459. T* Get();
  460. int sockfd;
  461. private:
  462. bool _run;
  463. struct ifreq ifr;
  464. struct sockaddr_can can_addr;
  465. int ret;
  466. int nbytes;
  467. struct can_frame Reciveframe;
  468. std::string _CanName;
  469. std::thread _thread;
  470. std::unique_ptr<T> _sensorNotify;
  471. };
  472. template<typename T>
  473. SensorCanBus<T>::SensorCanBus(CMessageQueue* q,std::string CanName)
  474. {
  475. _sensorNotify = std::make_unique<T>(q);
  476. _CanName = CanName;
  477. sockfd = -1;
  478. memset(&ifr,0,sizeof(ifr));
  479. memset(&can_addr,0,sizeof(can_addr));
  480. memset(&Reciveframe,0,sizeof(Reciveframe));
  481. _run = false;
  482. }
  483. template<typename T>
  484. bool SensorCanBus<T>::Start()
  485. {
  486. std::cout << "SensorCanBus<T>::Start" << std::endl;
  487. _sensorNotify->SetCanBusSensor(this);
  488. sockfd = socket(PF_CAN, SOCK_RAW, CAN_RAW);
  489. if(sockfd < 0)
  490. {
  491. std::cout << "SensorCanBus Socket Error" << std::endl;
  492. }
  493. memcpy(ifr.ifr_name,_CanName.c_str(),_CanName.length());
  494. //std::cout << ifr.ifr_name << std::endl;
  495. ioctl(sockfd, SIOCGIFINDEX, &ifr);
  496. can_addr.can_family = AF_CAN;
  497. can_addr.can_ifindex = ifr.ifr_ifindex;
  498. ret = bind(sockfd, (struct sockaddr *)&can_addr, sizeof(can_addr));
  499. if (ret < 0)
  500. {
  501. std::cout << "SensorCanBus Bind Error" << std::endl;
  502. close(sockfd);
  503. return false;
  504. }
  505. int loopback = 0;
  506. setsockopt(sockfd, SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback, sizeof(loopback));
  507. int ro = 1;
  508. setsockopt(sockfd, SOL_CAN_RAW, CAN_RAW_RECV_OWN_MSGS, &ro, sizeof(ro));
  509. /*
  510. can_err_mask_t err_mask = (CAN_ERR_TX_TIMEOUT | CAN_ERR_BUSOFF);
  511. setsockopt(sockfd, SOL_CAN_RAW, CAN_RAW_ERR_FILTER, &err_mask, sizeof(err_mask));
  512. */
  513. int flag = fcntl(sockfd, F_GETFL, 0);
  514. if (flag < 0)
  515. {
  516. std::cout << "fcntl F_GETFL fail" << std::endl;
  517. }
  518. if (fcntl(sockfd, F_SETFL, flag | O_NONBLOCK) < 0)
  519. {
  520. std::cout << "fcntl F_SETFL fail" << std::endl;
  521. }
  522. _run = true;
  523. _sensorNotify->Start();
  524. _thread = std::thread(&SensorCanBus::Run, this);
  525. return true;
  526. }
  527. template<typename T>
  528. void SensorCanBus<T>::Stop()
  529. {
  530. if (!_run) return;
  531. _sensorNotify->Stop();
  532. _run = false;
  533. _thread.join();
  534. close(sockfd);
  535. std::cout << "SensorCanBus<T>::Stop" << std::endl;
  536. }
  537. template<typename T>
  538. T* SensorCanBus<T>::Get()
  539. {
  540. return _sensorNotify.get();
  541. }
  542. template<typename T>
  543. void SensorCanBus<T>::Write(can_frame *date)
  544. {
  545. ret = write(sockfd, date, sizeof(can_frame));
  546. printf("写给底盘",date);
  547. if(sizeof(can_frame) != ret)
  548. {
  549. perror("write");
  550. //printf("\r\n");
  551. }
  552. }
  553. template<typename T>
  554. void SensorCanBus<T>::Run()
  555. {
  556. //struct pollfd fds[1];
  557. //fds[0].fd = sockfd;
  558. //fds[0].events = POLLIN;
  559. while (_run)
  560. {
  561. fd_set fds;
  562. struct timeval timeout = {0,0};
  563. timeout.tv_usec = 20000;
  564. FD_ZERO(&fds);
  565. FD_SET(sockfd, &fds);
  566. int err = select(sockfd + 1, &fds, NULL, NULL, &timeout);
  567. if (err != -1 && FD_ISSET(sockfd, &fds))
  568. {
  569. nbytes = read(sockfd, &Reciveframe, sizeof(Reciveframe));
  570. if(nbytes > 0)
  571. {
  572. _sensorNotify->Notify(&Reciveframe);
  573. //printf("CAN frame:\nID = %x\nDLC = %x\nDATA = %s\n", Reciveframe.can_id,Reciveframe.can_dlc, Reciveframe.data);
  574. }
  575. }
  576. }
  577. }
  578. #include <PCANBasic.h>
  579. #include <assert.h>
  580. //20230414 PEAKCAN
  581. template<typename T>
  582. class SensorPeakCan
  583. {
  584. public:
  585. SensorPeakCan(CMessageQueue* q);
  586. bool Start();
  587. void Run();
  588. void Stop();
  589. void Write(TPCANMsg* dataMessage);
  590. T* Get();
  591. private:
  592. TPCANStatus result;
  593. TPCANHandle _handle = PCAN_NONEBUS;
  594. bool _isFD;
  595. bool _run;
  596. std::thread _thread;
  597. std::unique_ptr<T> _sensorNotify;
  598. };
  599. template<typename T>
  600. SensorPeakCan<T>::SensorPeakCan(CMessageQueue* q)
  601. {
  602. _sensorNotify = std::make_unique<T>(q);
  603. }
  604. template<typename T>
  605. bool SensorPeakCan<T>::Start()
  606. {
  607. std::cout << "SensorPeakCan<T>::Start" << std::endl;
  608. _sensorNotify->SetSensorSocket(this);
  609. int iBuffer;
  610. TPCANHandle _HandlesArray[16];
  611. char strMsg[256];
  612. _HandlesArray[0] = PCAN_USBBUS1;
  613. _HandlesArray[1] = PCAN_USBBUS2;
  614. _HandlesArray[2] = PCAN_USBBUS3;
  615. _HandlesArray[3] = PCAN_USBBUS4;
  616. _HandlesArray[4] = PCAN_USBBUS5;
  617. _HandlesArray[5] = PCAN_USBBUS6;
  618. _HandlesArray[6] = PCAN_USBBUS7;
  619. _HandlesArray[7] = PCAN_USBBUS8;
  620. _HandlesArray[8] = PCAN_USBBUS9;
  621. _HandlesArray[9] = PCAN_USBBUS10;
  622. _HandlesArray[10] = PCAN_USBBUS11;
  623. _HandlesArray[11] = PCAN_USBBUS12;
  624. _HandlesArray[12] = PCAN_USBBUS13;
  625. _HandlesArray[13] = PCAN_USBBUS14;
  626. _HandlesArray[14] = PCAN_USBBUS15;
  627. _HandlesArray[15] = PCAN_USBBUS16;
  628. for (int i = 0; i < (sizeof(_HandlesArray) / sizeof(TPCANHandle)); i++)
  629. {
  630. result = CAN_GetValue(_HandlesArray[i], PCAN_CHANNEL_CONDITION, &iBuffer, sizeof(iBuffer));
  631. if (((result) == PCAN_ERROR_OK) && ((iBuffer & PCAN_CHANNEL_AVAILABLE) == PCAN_CHANNEL_AVAILABLE))
  632. {
  633. result = CAN_GetValue((TPCANHandle)_HandlesArray[i], PCAN_CHANNEL_FEATURES, (void*)&iBuffer, sizeof(iBuffer));
  634. _isFD = (result == PCAN_ERROR_OK) && (iBuffer & FEATURE_FD_CAPABLE);
  635. _handle = _HandlesArray[i];
  636. break;
  637. }
  638. }
  639. if (_handle != PCAN_NONEBUS)
  640. {
  641. result = ::CAN_Initialize(_handle, PCAN_BAUD_250K);
  642. if (result == PCAN_ERROR_OK)
  643. {
  644. result = CAN_SetValue(_handle, PCAN_BUSOFF_AUTORESET | PCAN_PARAMETER_ON, (void*)&iBuffer, sizeof(iBuffer));
  645. }
  646. else
  647. return false;
  648. _run = true;
  649. _sensorNotify->Start();
  650. _thread = std::thread(&SensorPeakCan::Run, this);
  651. }
  652. return true;
  653. }
  654. template<typename T>
  655. void SensorPeakCan<T>::Stop()
  656. {
  657. if (!_run) return;
  658. _sensorNotify->Stop();
  659. _run = false;
  660. _thread.join();
  661. CAN_Uninitialize(_handle);
  662. std::cout << "SensorPeakCan<T>::Stop" << std::endl;
  663. }
  664. template<typename T>
  665. T* SensorPeakCan<T>::Get()
  666. {
  667. return _sensorNotify.get();
  668. }
  669. template<typename T>
  670. void SensorPeakCan<T>::Write(TPCANMsg *dataMessage)
  671. {
  672. /*dataMessage.ID = 0x601;
  673. dataMessage.MSGTYPE = PCAN_MESSAGE_STANDARD;
  674. dataMessage.LEN = 0x03;
  675. memset(dataMessage.DATA,0x00,8);
  676. dataMessage.DATA[0] = 0xB1;
  677. dataMessage.DATA[1] = 0x10;
  678. dataMessage.DATA[2] = 0xFF;*/
  679. int fd;
  680. if(CAN_GetValue(_handle, PCAN_RECEIVE_EVENT, &fd, sizeof(fd)) == PCAN_ERROR_OK)
  681. {
  682. result = CAN_Write(_handle, dataMessage);
  683. /*
  684. if(result == PCAN_ERROR_OK)
  685. std::cout << std::hex << dataMessage->ID << std::endl;
  686. else
  687. std::cout << std::hex << result << std::endl;
  688. */
  689. if(result != PCAN_ERROR_OK)
  690. CAN_Reset(_handle);
  691. }
  692. }
  693. template<typename T>
  694. void SensorPeakCan<T>::Run()
  695. {
  696. int fd;
  697. TPCANMsg CANMsg;
  698. TPCANTimestamp CANTimeStamp;
  699. TPCANStatus stsResult = CAN_GetValue(_handle, PCAN_RECEIVE_EVENT, &fd, sizeof(fd));
  700. if (stsResult != PCAN_ERROR_OK)
  701. std::cout << "CAN_GetValue Error" << "\n";
  702. while (_run)
  703. {
  704. /*
  705. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  706. TPCANStatus ret = PCAN_ERROR_OK;
  707. do{
  708. result = CAN_Read(_handle, &CANMsg, &CANTimeStamp);
  709. if (result != PCAN_ERROR_QRCVEMPTY)
  710. _sensorNotify->Notify(&CANMsg, CANMsg.LEN);
  711. memset(&CANMsg, 0, sizeof(CANMsg));
  712. memset(&CANTimeStamp, 0, sizeof(CANTimeStamp));
  713. }
  714. while(result & PCAN_ERROR_QRCVEMPTY);
  715. */
  716. struct timeval timeout = {0,0};
  717. timeout.tv_usec = 20000; // 20ms
  718. fd_set fds;
  719. FD_ZERO(&fds);
  720. FD_SET(fd, &fds);
  721. int err = select(fd + 1, &fds, NULL, NULL, &timeout);
  722. if (err != -1 && FD_ISSET(fd, &fds))
  723. {
  724. result = CAN_Read(_handle, &CANMsg, &CANTimeStamp);
  725. if (result != PCAN_ERROR_QRCVEMPTY)
  726. {
  727. _sensorNotify->Notify(&CANMsg, CANMsg.LEN);
  728. memset(&CANMsg, 0, sizeof(CANMsg));
  729. memset(&CANTimeStamp, 0, sizeof(CANTimeStamp));
  730. }
  731. }
  732. }
  733. }