sensor_socket.h 19 KB

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