sensor_socket.h 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184
  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. int flag;
  80. #ifndef WIN32
  81. bool _startRead;
  82. bool _startWrite;
  83. #endif
  84. };
  85. template<typename T>
  86. #ifdef _MAINDLG
  87. SensorSocket<T>::SensorSocket(CThreadWindow* q, std::string can_ip, int32_t can_port, int32_t host_port)
  88. #else
  89. SensorSocket<T>::SensorSocket(CMessageQueue* q, std::string can_ip, int32_t can_port, int32_t host_port)
  90. #endif
  91. {
  92. _sensorNotify=std::make_unique<T>(q);
  93. _canip=can_ip;
  94. _canport=can_port;
  95. _hostport=host_port;
  96. #ifndef WIN32
  97. _startWrite=_startRead=true;
  98. #endif
  99. }
  100. template<typename T>
  101. bool SensorSocket<T>::Start(const char * ip)
  102. {
  103. #ifdef WIN32
  104. WSAData data;
  105. WSAStartup(MAKEWORD(2, 2), &data);
  106. #endif
  107. std::cout<<"SensorSocket<T>::Start"<<std::endl;
  108. _sensorNotify->SetSensorSocket(this);
  109. _fd = socket(AF_INET, SOCK_DGRAM, 0);
  110. sockaddr_in sin;
  111. sin.sin_family = AF_INET;
  112. sin.sin_port = htons(_hostport);
  113. #ifdef WIN32
  114. sin.sin_addr.s_addr = inet_addr(ip);
  115. #else
  116. sin.sin_addr.s_addr = htonl(INADDR_ANY);
  117. #endif
  118. if (::bind(_fd, (sockaddr*)&sin, sizeof(sin)) == -1)
  119. return false;
  120. /*
  121. flag = fcntl(_fd, F_GETFL, 0);
  122. if (flag < 0)
  123. {
  124. printf("fcntl failed.\n");
  125. }
  126. flag |= O_NONBLOCK;
  127. if (fcntl(_fd, F_SETFL, flag) < 0)
  128. {
  129. printf("fcntl failed.\n");
  130. }*/
  131. _canaddr.sin_family=AF_INET;
  132. _canaddr.sin_addr.s_addr=inet_addr(_canip.c_str());
  133. _canaddr.sin_port=htons(_canport);
  134. _sensorNotify->Start();
  135. _thread = std::thread(&SensorSocket::Run, this);
  136. return true;
  137. }
  138. template<typename T>
  139. void SensorSocket<T>::Read(CIOBuffer* pBuffer)
  140. {
  141. sockaddr_in from;
  142. socklen_t fromlen=sizeof(sockaddr_in);
  143. int32_t ret = recvfrom(_fd,(char *)pBuffer->Buffer, CIOBuffer::IO_BUFFER_SIZE,0,(sockaddr*)&from,&fromlen);
  144. if (ret <= 0)
  145. {
  146. return;
  147. }
  148. pBuffer->Length=ret;
  149. }
  150. template<typename T>
  151. void SensorSocket<T>::Run()
  152. {
  153. _run = true;
  154. struct pollfd fds[1];
  155. fds[0].fd = _fd;
  156. fds[0].events = POLLIN;
  157. while (_run)
  158. {
  159. if(poll(&fds[0], 1, 1000) > 0)
  160. {
  161. if (fds[0].revents & POLLIN)
  162. {
  163. CIOBuffer pBuffer;
  164. sockaddr_in from;
  165. socklen_t fromlen=sizeof(sockaddr_in);
  166. int32_t ret = recvfrom(_fd,(char *)pBuffer.Buffer, CIOBuffer::IO_BUFFER_SIZE,0,(sockaddr*)&from,&fromlen);
  167. if (ret <= 0||!_run)
  168. {
  169. continue;
  170. }
  171. _sensorNotify->Notify(pBuffer.Buffer,ret);
  172. }
  173. }
  174. }
  175. std::cout<<"SensorSocket<T>::Run Finished"<<std::endl;
  176. }
  177. template<typename T>
  178. void SensorSocket<T>::Write(CIOBuffer * pBuffer)
  179. {
  180. #ifndef WIN32
  181. if(_startWrite==false) return;
  182. #endif
  183. socklen_t len=sizeof(_canaddr);
  184. int ret=::sendto(_fd,(char *)pBuffer->Buffer,pBuffer->Length,0,(const sockaddr *)&_canaddr,len);
  185. {
  186. // std::cout<<"ret = "<<ret<<" size ="<<pBuffer->Length<<std::endl;
  187. }
  188. }
  189. template<typename T>
  190. void SensorSocket<T>::Stop()
  191. {
  192. if(!_run) return;
  193. _sensorNotify->Stop();
  194. _run = false;
  195. #ifdef WIN32
  196. closesocket(_fd);
  197. #else
  198. close(_fd);
  199. #endif
  200. std::cout<<"SensorSocket<T>::Stop"<<std::endl;
  201. _thread.join();
  202. }
  203. #ifndef WIN32
  204. template<typename T>
  205. void SensorSocket<T>::SetStartRead(bool b)
  206. {
  207. _startRead=b;
  208. }
  209. template<typename T>
  210. void SensorSocket<T>::SetStartWrite(bool b)
  211. {
  212. _startWrite=b;
  213. }
  214. #endif
  215. template<typename T>
  216. T* SensorSocket<T>::Get()
  217. {
  218. return _sensorNotify.get();
  219. }
  220. template<typename T>
  221. class SensorTCP
  222. {
  223. public:
  224. #ifdef _MAINDLG
  225. SensorTCP(CThreadWindow* q, std::string can_ip, int32_t can_port, int32_t host_port);
  226. #else
  227. SensorTCP(CMessageQueue * q,std::string can_ip,int32_t can_port,int32_t host_port);
  228. #endif
  229. bool Start(const char* ip=nullptr);
  230. void Run();
  231. void Stop();
  232. void Write(CIOBuffer * pBuffer);
  233. T* Get();
  234. #ifndef WIN32
  235. void SetStartRead(bool b);
  236. void SetStartWrite(bool b);
  237. #endif
  238. private:
  239. socket_t _fd;
  240. std::thread _thread;
  241. bool _run;
  242. std::string _canip;
  243. int32_t _canport;
  244. int32_t _hostport;
  245. std::mutex _lock;
  246. std::unordered_map<int32_t, cannet_frame> _message;
  247. std::unique_ptr<T> _sensorNotify;
  248. sockaddr_in _canaddr;
  249. int flag;
  250. #ifndef WIN32
  251. bool _startRead;
  252. bool _startWrite;
  253. #endif
  254. };
  255. template<typename T>
  256. #ifdef _MAINDLG
  257. SensorTCP<T>::SensorTCP(CThreadWindow* q, std::string can_ip, int32_t can_port, int32_t host_port)
  258. #else
  259. SensorTCP<T>::SensorTCP(CMessageQueue* q, std::string can_ip, int32_t can_port, int32_t host_port)
  260. #endif
  261. {
  262. _sensorNotify=std::make_unique<T>(q);
  263. _canip=can_ip;
  264. _canport=can_port;
  265. _hostport=host_port;
  266. _run = false;
  267. #ifndef WIN32
  268. _startWrite=_startRead=true;
  269. #endif
  270. }
  271. template<typename T>
  272. bool SensorTCP<T>::Start(const char * ip)
  273. {
  274. #ifdef WIN32
  275. WSAData data;
  276. WSAStartup(MAKEWORD(2, 2), &data);
  277. #endif
  278. std::cout<<"SensorSocket<T>::Start"<<_canip<<","<<_canport<<std::endl;
  279. //_sensorNotify->SetSensorSocket(this);
  280. _fd = socket(AF_INET, SOCK_STREAM, 0);
  281. sockaddr_in sin;
  282. sin.sin_family = AF_INET;
  283. sin.sin_port = htons(_canport);
  284. #ifdef WIN32
  285. sin.sin_addr.s_addr = inet_addr(ip);
  286. #else
  287. sin.sin_addr.s_addr =inet_addr(_canip.c_str());// htonl(INADDR_ANY);
  288. #endif
  289. while (::connect(_fd, (sockaddr*)&sin, sizeof(sin)) == -1)
  290. {
  291. std::cout<< "connect "<<_canip<<" failed"<<std::endl;
  292. std::this_thread::sleep_for(std::chrono::milliseconds(2000));
  293. }
  294. flag = fcntl(_fd, F_GETFL, 0);
  295. if (flag < 0)
  296. {
  297. printf("fcntl failed.\n");
  298. }
  299. flag |= O_NONBLOCK;
  300. if (fcntl(_fd, F_SETFL, flag) < 0)
  301. {
  302. printf("fcntl failed.\n");
  303. }
  304. if(_run == false)
  305. _thread = std::thread(&SensorTCP::Run, this);
  306. _sensorNotify->Start();
  307. return true;
  308. }
  309. template<typename T>
  310. void SensorTCP<T>::Run()
  311. {
  312. _run = true;
  313. struct pollfd fds[1];
  314. fds[0].fd = _fd;
  315. fds[0].events = POLLIN;
  316. // long long k = 0;
  317. //long long tick = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
  318. while (_run)
  319. {
  320. #ifdef WEBRTC_LINUX
  321. // _sensorNotify->PreProcess();
  322. if(poll(&fds[0], 1, 1000) > 0)
  323. {
  324. if (fds[0].revents & POLLIN)
  325. {
  326. #endif
  327. CIOBuffer pBuffer;
  328. sockaddr_in from;
  329. socklen_t fromlen=sizeof(sockaddr_in);
  330. int32_t ret = recv(_fd,(char *)pBuffer.Buffer, CIOBuffer::IO_BUFFER_SIZE,0);
  331. if (ret <= 0||!_run)
  332. {
  333. close(_fd);
  334. this->Start();
  335. }
  336. //_sensorNotify->Notify(pBuffer.Buffer,ret);
  337. #ifdef WEBRTC_LINUX
  338. }
  339. }
  340. #endif
  341. }
  342. std::cout<<"SensorSocket<T>::Run Finished"<<std::endl;
  343. }
  344. template<typename T>
  345. void SensorTCP<T>::Write(CIOBuffer * pBuffer)
  346. {
  347. #ifndef WIN32
  348. if(_startWrite==false) return;
  349. #endif
  350. socklen_t len=sizeof(_canaddr);
  351. int ret=::send(_fd,(char *)pBuffer->Buffer,pBuffer->Length,0);
  352. if(ret<=0)
  353. {
  354. std::cout<<"ret = "<<ret<<" size ="<<pBuffer->Length<<std::endl;
  355. }
  356. }
  357. template<typename T>
  358. void SensorTCP<T>::Stop()
  359. {
  360. if(!_run) return;
  361. _sensorNotify->Stop();
  362. _run = false;
  363. #ifdef WIN32
  364. closesocket(_fd);
  365. #else
  366. close(_fd);
  367. #endif
  368. std::cout<<"SensorSocket<T>::Stop"<<std::endl;
  369. _thread.join();
  370. std::cout<<"SensorSocket<T>::Stop finished"<<std::endl;
  371. }
  372. #ifndef WIN32
  373. template<typename T>
  374. void SensorTCP<T>::SetStartRead(bool b)
  375. {
  376. _startRead=b;
  377. }
  378. template<typename T>
  379. void SensorTCP<T>::SetStartWrite(bool b)
  380. {
  381. _startWrite=b;
  382. }
  383. #endif
  384. template<typename T>
  385. T* SensorTCP<T>::Get()
  386. {
  387. return _sensorNotify.get();
  388. }
  389. #include "../thirdparty/Mqtt/include/MQTTAsync.h"
  390. #include <string.h>
  391. //20230414 MQTT
  392. template<typename T>
  393. class SensorMQTT
  394. {
  395. public:
  396. SensorMQTT(CMessageQueue* q, std::string Server_Address, std::string Esn, std::string Password, std::string Clientid);
  397. bool Start();
  398. //void Run();
  399. void Stop();
  400. void Write(CIOBuffer* pBuffer, const char* pubTopic);
  401. T* Get();
  402. private:
  403. MQTTAsync mqttClient;
  404. //std::thread _thread;
  405. std::string _Server_Address;
  406. std::string _Esn;
  407. std::string _Password;
  408. std::string _ClientID;
  409. //std::mutex _lock;
  410. //std::unordered_map<int32_t, cannet_frame> _message;
  411. std::unique_ptr<T> _sensorNotify;
  412. };
  413. template<typename T>
  414. SensorMQTT<T>::SensorMQTT(CMessageQueue* q, std::string Server_Address, std::string Esn, std::string Password, std::string Clientid)
  415. {
  416. _sensorNotify = std::make_unique<T>(q);
  417. _Server_Address = Server_Address;
  418. _Esn = Esn;
  419. _Password = Password;
  420. _ClientID = Clientid;
  421. }
  422. template<typename T>
  423. bool SensorMQTT<T>::Start()
  424. {
  425. std::cout << "SensorMQTT<T>::Start" << _Server_Address << "," << _Esn << "," << _Password << "," << _ClientID <<std::endl;
  426. int rc = 0;
  427. MQTTAsync_create(&mqttClient, _Server_Address.c_str(), _ClientID.c_str(), MQTTCLIENT_PERSISTENCE_NONE, NULL);
  428. _sensorNotify->SetSensorMQTT(mqttClient, _Esn);
  429. MQTTAsync_setCallbacks(mqttClient, NULL, _sensorNotify->Disconnect, _sensorNotify->RecevieMessage, NULL); //�������ӶϿ��ͽ������ݻص�
  430. MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer; //��ʼ���ṹ��
  431. conn_opts.cleansession = 1;
  432. conn_opts.username = _Esn.c_str();
  433. conn_opts.password = _Password.c_str();
  434. conn_opts.onFailure = _sensorNotify->onConnectFailure; //����ʧ�ܻص�
  435. conn_opts.context = mqttClient;
  436. conn_opts.automaticReconnect = true; //�����Ͽ��Զ�����
  437. conn_opts.minRetryInterval = 5; //��С�������ʱ��(��)��ÿ��ʧ���������ʱ�䶼��ӱ�
  438. conn_opts.maxRetryInterval = 365 * 24 * 60 * 60; //����������ʱ��(��)
  439. MQTTAsync_setConnected(mqttClient, (char *)conn_opts.username , _sensorNotify->onConnectCallCBack); //�������ӳɹ��ص�,�����ǵ�һ�����ӳɹ����������ɹ�������ô˻ص�
  440. if ((rc = MQTTAsync_connect(mqttClient, &conn_opts)) != MQTTASYNC_SUCCESS) //��������
  441. {
  442. std::cout << "MQTTAsync_connect() fail, error code: " << rc << std::endl;
  443. }
  444. //_thread = std::thread(&SensorMQTT::Run, this);
  445. //_sensorNotify->Start();
  446. return true;
  447. }
  448. template<typename T>
  449. void SensorMQTT<T>::Stop()
  450. {
  451. _sensorNotify->Stop(_Esn.c_str());
  452. std::cout << "SensorMQTT<T>::Stop" << std::endl;
  453. }
  454. template<typename T>
  455. T* SensorMQTT<T>::Get()
  456. {
  457. return _sensorNotify.get();
  458. }
  459. template<typename T>
  460. void SensorMQTT<T>::Write(CIOBuffer* pBuffer, const char* pubTopic)
  461. {
  462. _sensorNotify->sendMessage((char *)pBuffer->Buffer,1,pubTopic);
  463. }
  464. #include <PCANBasic.h>
  465. #include <assert.h>
  466. //20230414 PEAKCAN
  467. template<typename T>
  468. class SensorPeakCan
  469. {
  470. public:
  471. SensorPeakCan(CMessageQueue* q);
  472. bool Start();
  473. void Run();
  474. void Stop();
  475. void Write(TPCANMsg* dataMessage);
  476. T* Get();
  477. private:
  478. TPCANStatus result;
  479. TPCANHandle _handle = PCAN_NONEBUS;
  480. bool _isFD;
  481. bool _run;
  482. std::thread _thread;
  483. std::unique_ptr<T> _sensorNotify;
  484. };
  485. template<typename T>
  486. SensorPeakCan<T>::SensorPeakCan(CMessageQueue* q)
  487. {
  488. _sensorNotify = std::make_unique<T>(q);
  489. }
  490. template<typename T>
  491. bool SensorPeakCan<T>::Start()
  492. {
  493. std::cout << "SensorPeakCan<T>::Start" << std::endl;
  494. _sensorNotify->SetSensorSocket(this);
  495. int iBuffer;
  496. TPCANHandle _HandlesArray[16];
  497. char strMsg[256];
  498. _HandlesArray[0] = PCAN_USBBUS1;
  499. _HandlesArray[1] = PCAN_USBBUS2;
  500. _HandlesArray[2] = PCAN_USBBUS3;
  501. _HandlesArray[3] = PCAN_USBBUS4;
  502. _HandlesArray[4] = PCAN_USBBUS5;
  503. _HandlesArray[5] = PCAN_USBBUS6;
  504. _HandlesArray[6] = PCAN_USBBUS7;
  505. _HandlesArray[7] = PCAN_USBBUS8;
  506. _HandlesArray[8] = PCAN_USBBUS9;
  507. _HandlesArray[9] = PCAN_USBBUS10;
  508. _HandlesArray[10] = PCAN_USBBUS11;
  509. _HandlesArray[11] = PCAN_USBBUS12;
  510. _HandlesArray[12] = PCAN_USBBUS13;
  511. _HandlesArray[13] = PCAN_USBBUS14;
  512. _HandlesArray[14] = PCAN_USBBUS15;
  513. _HandlesArray[15] = PCAN_USBBUS16;
  514. for (int i = 0; i < (sizeof(_HandlesArray) / sizeof(TPCANHandle)); i++)
  515. {
  516. result = CAN_GetValue(_HandlesArray[i], PCAN_CHANNEL_CONDITION, &iBuffer, sizeof(iBuffer));
  517. if (((result) == PCAN_ERROR_OK) && ((iBuffer & PCAN_CHANNEL_AVAILABLE) == PCAN_CHANNEL_AVAILABLE))
  518. {
  519. result = CAN_GetValue((TPCANHandle)_HandlesArray[i], PCAN_CHANNEL_FEATURES, (void*)&iBuffer, sizeof(iBuffer));
  520. _isFD = (result == PCAN_ERROR_OK) && (iBuffer & FEATURE_FD_CAPABLE);
  521. _handle = _HandlesArray[i];
  522. break;
  523. }
  524. }
  525. if (_handle != PCAN_NONEBUS)
  526. {
  527. result = ::CAN_Initialize(_handle, PCAN_BAUD_250K);
  528. if (result == PCAN_ERROR_OK)
  529. {
  530. result = CAN_SetValue(_handle, PCAN_BUSOFF_AUTORESET | PCAN_PARAMETER_ON, (void*)&iBuffer, sizeof(iBuffer));
  531. }
  532. else
  533. return false;
  534. _run = true;
  535. _sensorNotify->Start();
  536. _thread = std::thread(&SensorPeakCan::Run, this);
  537. }
  538. return true;
  539. }
  540. template<typename T>
  541. void SensorPeakCan<T>::Stop()
  542. {
  543. if (!_run) return;
  544. _sensorNotify->Stop();
  545. _run = false;
  546. _thread.join();
  547. CAN_Uninitialize(_handle);
  548. std::cout << "SensorPeakCan<T>::Stop" << std::endl;
  549. }
  550. template<typename T>
  551. T* SensorPeakCan<T>::Get()
  552. {
  553. return _sensorNotify.get();
  554. }
  555. template<typename T>
  556. void SensorPeakCan<T>::Write(TPCANMsg *dataMessage)
  557. {
  558. /*dataMessage.ID = 0x601;
  559. dataMessage.MSGTYPE = PCAN_MESSAGE_STANDARD;
  560. dataMessage.LEN = 0x03;
  561. memset(dataMessage.DATA,0x00,8);
  562. dataMessage.DATA[0] = 0xB1;
  563. dataMessage.DATA[1] = 0x10;
  564. dataMessage.DATA[2] = 0xFF;*/
  565. int fd;
  566. if(CAN_GetValue(_handle, PCAN_RECEIVE_EVENT, &fd, sizeof(fd)) == PCAN_ERROR_OK)
  567. {
  568. result = CAN_Write(_handle, dataMessage);
  569. if(result == PCAN_ERROR_OK)
  570. std::cout << std::hex << dataMessage->ID << std::endl;
  571. else
  572. std::cout << std::hex << result << std::endl;
  573. }
  574. }
  575. template<typename T>
  576. void SensorPeakCan<T>::Run()
  577. {
  578. int fd;
  579. TPCANMsg CANMsg;
  580. TPCANTimestamp CANTimeStamp;
  581. TPCANStatus stsResult = CAN_GetValue(_handle, PCAN_RECEIVE_EVENT, &fd, sizeof(fd));
  582. if (stsResult != PCAN_ERROR_OK)
  583. std::cout << "CAN_GetValue Error" << "\n";
  584. while (_run)
  585. {
  586. /*
  587. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  588. TPCANStatus ret = PCAN_ERROR_OK;
  589. do{
  590. result = CAN_Read(_handle, &CANMsg, &CANTimeStamp);
  591. if (result != PCAN_ERROR_QRCVEMPTY)
  592. _sensorNotify->Notify(&CANMsg, CANMsg.LEN);
  593. memset(&CANMsg, 0, sizeof(CANMsg));
  594. memset(&CANTimeStamp, 0, sizeof(CANTimeStamp));
  595. }
  596. while(result & PCAN_ERROR_QRCVEMPTY);
  597. */
  598. struct timeval timeout = {0,0};
  599. timeout.tv_usec = 20000; // 20ms
  600. fd_set fds;
  601. FD_ZERO(&fds);
  602. FD_SET(fd, &fds);
  603. int err = select(fd + 1, &fds, NULL, NULL, &timeout);
  604. if (err != -1 && FD_ISSET(fd, &fds))
  605. {
  606. result = CAN_Read(_handle, &CANMsg, &CANTimeStamp);
  607. if (result != PCAN_ERROR_QRCVEMPTY)
  608. {
  609. _sensorNotify->Notify(&CANMsg, CANMsg.LEN);
  610. memset(&CANMsg, 0, sizeof(CANMsg));
  611. memset(&CANTimeStamp, 0, sizeof(CANTimeStamp));
  612. }
  613. }
  614. }
  615. }
  616. #include <unistd.h>
  617. #include <net/if.h>
  618. #include <sys/ioctl.h>
  619. #include <sys/socket.h>
  620. #include <linux/can.h>
  621. #include <linux/can/raw.h>
  622. //20231128 CANBUS
  623. template<typename T>
  624. class SensorCanBus
  625. {
  626. public:
  627. SensorCanBus(CMessageQueue* q,std::string CanName);
  628. bool Start();
  629. void Run();
  630. void Stop();
  631. void Write(can_frame *date);
  632. T* Get();
  633. int sockfd;
  634. private:
  635. bool _run;
  636. struct ifreq ifr;
  637. struct sockaddr_can can_addr;
  638. int ret;
  639. int nbytes;
  640. struct can_frame Reciveframe;
  641. std::string _CanName;
  642. std::thread _thread;
  643. std::unique_ptr<T> _sensorNotify;
  644. };
  645. template<typename T>
  646. SensorCanBus<T>::SensorCanBus(CMessageQueue* q,std::string CanName)
  647. {
  648. _sensorNotify = std::make_unique<T>(q);
  649. _CanName = CanName;
  650. sockfd = -1;
  651. memset(&ifr,0,sizeof(ifr));
  652. memset(&can_addr,0,sizeof(can_addr));
  653. memset(&Reciveframe,0,sizeof(Reciveframe));
  654. _run = false;
  655. }
  656. template<typename T>
  657. bool SensorCanBus<T>::Start()
  658. {
  659. std::cout << "SensorCanBus<T>::Start" << std::endl;
  660. _sensorNotify->SetCanBusSensor(this);
  661. sockfd = socket(PF_CAN, SOCK_RAW, CAN_RAW);
  662. if(sockfd < 0)
  663. {
  664. std::cout << "SensorCanBus Socket Error" << std::endl;
  665. }
  666. memcpy(ifr.ifr_name,_CanName.c_str(),_CanName.length());
  667. //std::cout << ifr.ifr_name << std::endl;
  668. ioctl(sockfd, SIOCGIFINDEX, &ifr);
  669. can_addr.can_family = AF_CAN;
  670. can_addr.can_ifindex = ifr.ifr_ifindex;
  671. ret = bind(sockfd, (struct sockaddr *)&can_addr, sizeof(can_addr));
  672. if (ret < 0)
  673. {
  674. std::cout << "SensorCanBus Bind Error" << std::endl;
  675. close(sockfd);
  676. return false;
  677. }
  678. int loopback = 0;
  679. setsockopt(sockfd, SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback, sizeof(loopback));
  680. int ro = 1;
  681. setsockopt(sockfd, SOL_CAN_RAW, CAN_RAW_RECV_OWN_MSGS, &ro, sizeof(ro));
  682. int flag = fcntl(sockfd, F_GETFL, 0);
  683. if (flag < 0)
  684. {
  685. std::cout << "fcntl F_GETFL fail" << std::endl;
  686. }
  687. if (fcntl(sockfd, F_SETFL, flag | O_NONBLOCK) < 0)
  688. {
  689. std::cout << "fcntl F_SETFL fail" << std::endl;
  690. }
  691. _run = true;
  692. _sensorNotify->Start();
  693. _thread = std::thread(&SensorCanBus::Run, this);
  694. return true;
  695. }
  696. template<typename T>
  697. void SensorCanBus<T>::Stop()
  698. {
  699. if (!_run) return;
  700. _sensorNotify->Stop();
  701. _run = false;
  702. _thread.join();
  703. close(sockfd);
  704. std::cout << "SensorCanBus<T>::Stop" << std::endl;
  705. }
  706. template<typename T>
  707. T* SensorCanBus<T>::Get()
  708. {
  709. return _sensorNotify.get();
  710. }
  711. template<typename T>
  712. void SensorCanBus<T>::Write(can_frame *date)
  713. {
  714. ret = write(sockfd, date, sizeof(can_frame));
  715. if(sizeof(can_frame) != ret)
  716. {
  717. printf("SensorCanBus write error:%d\r\n",ret);
  718. }
  719. }
  720. template<typename T>
  721. void SensorCanBus<T>::Run()
  722. {
  723. //struct pollfd fds[1];
  724. //fds[0].fd = sockfd;
  725. //fds[0].events = POLLIN;
  726. while (_run)
  727. {
  728. fd_set fds;
  729. struct timeval timeout = {0,0};
  730. timeout.tv_usec = 20000;
  731. FD_ZERO(&fds);
  732. FD_SET(sockfd, &fds);
  733. int err = select(sockfd + 1, &fds, NULL, NULL, &timeout);
  734. if (err != -1 && FD_ISSET(sockfd, &fds))
  735. {
  736. nbytes = read(sockfd, &Reciveframe, sizeof(Reciveframe));
  737. if(nbytes > 0)
  738. {
  739. _sensorNotify->Notify(&Reciveframe);
  740. //printf("CAN frame:\nID = %x\nDLC = %x\nDATA = %s\n", Reciveframe.can_id,Reciveframe.can_dlc, Reciveframe.data);
  741. }
  742. }
  743. }
  744. }
  745. #include <termios.h>
  746. //20231204 RS485
  747. template<typename T>
  748. class SensorSerial
  749. {
  750. public:
  751. SensorSerial(CMessageQueue* q,std::string CanName,uint32_t speed);
  752. bool Start();
  753. void Run();
  754. void Stop();
  755. void Write(uint8_t * pBuffer,uint8_t Length);
  756. T* Get();
  757. int Serialfd;
  758. private:
  759. bool _run;
  760. int nbytes;
  761. std::string _CanName;
  762. uint32_t _speed;
  763. std::thread _thread;
  764. std::unique_ptr<T> _sensorNotify;
  765. };
  766. template<typename T>
  767. SensorSerial<T>::SensorSerial(CMessageQueue* q,std::string CanName,uint32_t speed)
  768. {
  769. _sensorNotify = std::make_unique<T>(q);
  770. _run = false;
  771. _CanName = CanName;
  772. _speed = speed;
  773. Serialfd = -1;
  774. }
  775. template<typename T>
  776. bool SensorSerial<T>::Start()
  777. {
  778. std::cout << "SensorSerial<T>::Start" << std::endl;
  779. _sensorNotify->SetSerialSensor(this);
  780. Serialfd = open((const char *)_CanName.c_str(), O_RDWR | O_NOCTTY | O_NDELAY);
  781. if (-1 == Serialfd)
  782. {
  783. printf("Can't Open Serial Port\r\n");
  784. return false;
  785. }
  786. if(fcntl(Serialfd, F_SETFL, O_NONBLOCK) < 0)
  787. {
  788. printf("Unable set to NONBLOCK \r\n");
  789. return false;
  790. }
  791. struct termios Opt;
  792. tcgetattr(Serialfd, &Opt);
  793. int speed_arr[] = { B38400, B19200, B9600, B4800, B2400, B1200, B300, \
  794. B38400, B19200, B9600, B4800, B2400, B1200, B300, };
  795. int name_arr[] = { 38400, 19200, 9600, 4800, 2400, 1200, 300, 38400, \
  796. 19200, 9600, 4800, 2400, 1200, 300, };
  797. for (int i=0; i<sizeof(speed_arr)/sizeof(int); i++)
  798. {
  799. if (_speed == name_arr[i])
  800. {
  801. cfsetispeed(&Opt, speed_arr[i]);
  802. cfsetospeed(&Opt, speed_arr[i]);
  803. break;
  804. }
  805. }
  806. Opt.c_cflag &= ~CSIZE;
  807. Opt.c_cflag |= CS8;
  808. Opt.c_cflag &= ~PARENB; // Clear parity enable
  809. Opt.c_cflag &= ~CSTOPB;
  810. Opt.c_iflag &= ~(IXON | IXOFF | IXANY);
  811. Opt.c_oflag &= ~OPOST;
  812. Opt.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
  813. Opt.c_cc[VMIN] = 0;
  814. Opt.c_cc[VTIME] = 0;
  815. tcflush (Serialfd, TCIFLUSH);
  816. if(tcsetattr(Serialfd, TCSANOW, &Opt))
  817. printf("Serial succuss!\r\n");
  818. _run = true;
  819. _sensorNotify->Start();
  820. _thread = std::thread(&SensorSerial::Run, this);
  821. return true;
  822. }
  823. template<typename T>
  824. T* SensorSerial<T>::Get()
  825. {
  826. return _sensorNotify.get();
  827. }
  828. template<typename T>
  829. void SensorSerial<T>::Write(uint8_t * pBuffer,uint8_t Length)
  830. {
  831. int ret = write(Serialfd,(const char *)pBuffer,Length);
  832. }
  833. template<typename T>
  834. void SensorSerial<T>::Run()
  835. {
  836. uint8_t pBuffer[128];
  837. while (_run)
  838. {
  839. struct timeval timeout = {0,0};
  840. timeout.tv_usec = 20000;
  841. fd_set fds;
  842. FD_ZERO(&fds);
  843. FD_SET(Serialfd, &fds);
  844. int err = select(Serialfd + 1, &fds, NULL, NULL, &timeout);
  845. if (err != -1 && FD_ISSET(Serialfd, &fds))
  846. {
  847. memset(pBuffer,0,128);
  848. nbytes = read(Serialfd,pBuffer,128);
  849. if(nbytes > 0)
  850. {
  851. _sensorNotify->Notify(pBuffer,nbytes);
  852. }
  853. }
  854. }
  855. }
  856. template<typename T>
  857. void SensorSerial<T>::Stop()
  858. {
  859. if (!_run) return;
  860. _sensorNotify->Stop();
  861. _run = false;
  862. _thread.join();
  863. close(Serialfd);
  864. std::cout << "SensorSerial<T>::Stop" << std::endl;
  865. }
  866. #include "modbus/modbus.h"
  867. //20231205 modbus tcp or rtu
  868. template<typename T>
  869. class SensorModbusTcp
  870. {
  871. public:
  872. SensorModbusTcp(CMessageQueue* q,std::string ip,uint32_t port,uint32_t slaveID[16],uint32_t type);//0.tcp.1rtu
  873. bool Start();
  874. void Stop();
  875. void Write(uint8_t * pBuffer,uint8_t Length);
  876. void read_input_registers(uint16_t addr,uint16_t nb);//0x04
  877. void read_registers(uint16_t addr,uint16_t nb);//0x03
  878. T* Get();
  879. modbus_t *_modbusclient;
  880. uint32_t mode_type;
  881. private:
  882. bool _run;
  883. int nbytes;
  884. std::string _ServerIp;
  885. uint32_t _ServerPort;
  886. uint32_t _SlaveID[16];
  887. std::unique_ptr<T> _sensorNotify;
  888. };
  889. template<typename T>
  890. SensorModbusTcp<T>::SensorModbusTcp(CMessageQueue* q,std::string ip,uint32_t port,uint32_t slaveID[16],uint32_t type)
  891. {
  892. _sensorNotify = std::make_unique<T>(q);
  893. _run = false;
  894. _ServerIp = ip;
  895. _ServerPort = port;
  896. //_SlaveID = slaveID;
  897. memset(_SlaveID,0,16);
  898. memcpy(_SlaveID,slaveID,16);
  899. _modbusclient = nullptr;
  900. mode_type = type;
  901. }
  902. template<typename T>
  903. T* SensorModbusTcp<T>::Get()
  904. {
  905. return _sensorNotify.get();
  906. }
  907. template<typename T>
  908. void SensorModbusTcp<T>::Write(uint8_t * pBuffer,uint8_t Length)
  909. {
  910. }
  911. template<typename T>
  912. void SensorModbusTcp<T>::read_input_registers(uint16_t addr,uint16_t nb)//0x04
  913. {
  914. uint16_t Receive[128];
  915. memset(Receive,0,128);
  916. modbus_set_slave(_modbusclient, _SlaveID[0]);
  917. int ret_id1 = modbus_read_input_registers(_modbusclient,addr,nb,Receive);
  918. modbus_set_slave(_modbusclient, _SlaveID[1]);
  919. int ret_id2 = modbus_read_input_registers(_modbusclient,addr,nb,Receive + ret_id1);
  920. /*
  921. int ret = ret_id1 + ret_id2;
  922. uint8_t HexData[256];
  923. memset(HexData,0,256);
  924. for(int i = 0 ; i < ret ; i+=2)
  925. {
  926. HexData[i + 1] = (Receive[i] & 0x00ff);
  927. HexData[i] = ((Receive[i] & 0xff00) >> 8);
  928. }
  929. */
  930. _sensorNotify->Notify(Receive);
  931. }
  932. template<typename T>
  933. void SensorModbusTcp<T>::read_registers(uint16_t addr,uint16_t nb)//0x03
  934. {
  935. uint16_t Receive[128],Buff[128];
  936. memset(Receive,0,128);
  937. memset(Buff,0,128);
  938. modbus_set_slave(_modbusclient, _SlaveID[0]);
  939. modbus_read_registers(_modbusclient,addr,nb,Receive);
  940. Buff[0] = Receive[1];
  941. modbus_set_slave(_modbusclient, _SlaveID[1]);
  942. modbus_read_registers(_modbusclient,addr,nb,Receive);
  943. Buff[1] = Receive[1];
  944. /*
  945. int ret = ret_id1 + ret_id2;
  946. uint8_t HexData[256];
  947. memset(HexData,0,256);
  948. for(int i = 0 ; i < ret ; i+=2)
  949. {
  950. HexData[i + 1] = (Receive[i] & 0x00ff);
  951. HexData[i] = ((Receive[i] & 0xff00) >> 8);
  952. }
  953. */
  954. _sensorNotify->Notify(Buff);
  955. }
  956. template<typename T>
  957. bool SensorModbusTcp<T>::Start()
  958. {
  959. std::cout << "SensorModbusTcp<T>::Start" << std::endl;
  960. _sensorNotify->SetModbusTcpSensor(this);
  961. if(!mode_type)
  962. _modbusclient = modbus_new_tcp(_ServerIp.c_str(), _ServerPort);
  963. else
  964. _modbusclient = modbus_new_rtu(_ServerIp.c_str(), _ServerPort,'N',8,1);//modbus_new_rtu("/dev/ttySP1", 115200, 'N', 8, 1);
  965. if(_modbusclient)
  966. {
  967. modbus_set_debug(_modbusclient,1);
  968. if (!modbus_connect(_modbusclient))
  969. {
  970. std::cout << "connect Slave ok" << std::endl;
  971. //modbus_set_response_timeout(mb, 1, 200000);
  972. _run = true;
  973. _sensorNotify->Start();
  974. return true;
  975. }
  976. else
  977. {
  978. modbus_free(_modbusclient);
  979. _modbusclient = nullptr;
  980. return false;
  981. }
  982. }
  983. else
  984. return false;
  985. }
  986. template<typename T>
  987. void SensorModbusTcp<T>::Stop()
  988. {
  989. if (!_run) return;
  990. _sensorNotify->Stop();
  991. _run = false;
  992. if(_modbusclient)
  993. {
  994. modbus_close(_modbusclient);
  995. modbus_free(_modbusclient);
  996. }
  997. _modbusclient = nullptr;
  998. std::cout << "SensorModbusTcp<T>::Stop" << std::endl;
  999. }