nvcan.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. #include "nvcan.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <stdint.h>
  5. #include <unistd.h>
  6. #include <string.h>
  7. #include <signal.h>
  8. #include <ctype.h>
  9. #include <libgen.h>
  10. #include <time.h>
  11. #include <errno.h>
  12. #include <sys/time.h>
  13. #include <sys/types.h>
  14. #include <sys/socket.h>
  15. #include <sys/ioctl.h>
  16. #include <sys/uio.h>
  17. #include <net/if.h>
  18. #include <linux/can.h>
  19. #include <linux/can/raw.h>
  20. #include <QDateTime>
  21. #include <iostream>
  22. #include <thread>
  23. /* for hardware timestamps - since Linux 2.6.30 */
  24. #ifndef SO_TIMESTAMPING
  25. #define SO_TIMESTAMPING 37
  26. #endif
  27. /* from #include <linux/net_tstamp.h> - since Linux 2.6.30 */
  28. #define SOF_TIMESTAMPING_SOFTWARE (1<<4)
  29. #define SOF_TIMESTAMPING_RX_SOFTWARE (1<<3)
  30. #define SOF_TIMESTAMPING_RAW_HARDWARE (1<<6)
  31. #define MAXSOCK 16 /* max. number of CAN interfaces given on the cmdline */
  32. #define MAXIFNAMES 30 /* size of receive name index to omit ioctls */
  33. #define MAXCOL 6 /* number of different colors for colorized output */
  34. #define ANYDEV "any" /* name of interface to receive from any CAN interface */
  35. #define ANL "\r\n" /* newline in ASC mode */
  36. #define SILENT_INI 42 /* detect user setting on commandline */
  37. #define SILENT_OFF 0 /* no silent mode */
  38. #define SILENT_ANI 1 /* silent mode with animation */
  39. #define SILENT_ON 2 /* silent mode (completely silent) */
  40. #include <QTime>
  41. #define BUF_SIZE 1000
  42. std::string CANNAME[] = {"can0","can1"};
  43. nvcan::nvcan(const char * strcanname)
  44. {
  45. // qDebug("nvcan");
  46. // connect(this,SIGNAL(SIG_CANOPENSTATE(bool,int,const char*)),this,SLOT(onMsg(bool,int,const char*)));
  47. CANNAME[0] = strcanname;
  48. mfault = new iv::Ivfault("can_socket");
  49. mivlog = new iv::Ivlog("can_socket");
  50. mfault->SetFaultState(0,0,"Prepare Initialize.");
  51. mpsendthread = new std::thread(&nvcan::threadsend,this);
  52. }
  53. void nvcan::ExecRecv(int s)
  54. {
  55. }
  56. void nvcan::run()
  57. {
  58. int currmax = 1;
  59. fd_set rdfs;
  60. int s[MAXSOCK];
  61. int ret;
  62. struct sockaddr_can addr;
  63. char ctrlmsg[CMSG_SPACE(sizeof(struct timeval) + 3*sizeof(struct timespec) + sizeof(__u32))];
  64. struct iovec iov;
  65. struct msghdr msg;
  66. struct canfd_frame frame;
  67. int nbytes, i, maxdlen;
  68. struct ifreq ifr;
  69. struct timeval tv, last_tv;
  70. struct timeval timeout_config = { 0, 0 }, *timeout_current = 0;
  71. mfault->SetFaultState(0,0,"Initializing.");
  72. for(i=0;i<currmax;i++)
  73. {
  74. s[i] = socket(PF_CAN, SOCK_RAW, CAN_RAW);
  75. if (s[i] < 0) {
  76. mfault->SetFaultState(2,1,"Create Socket Error.");
  77. emit SIG_CANOPENSTATE(false,-1,"Create Socket Error");
  78. return;
  79. }
  80. addr.can_family = AF_CAN;
  81. memset(&ifr.ifr_name, 0, sizeof(ifr.ifr_name));
  82. strncpy(ifr.ifr_name, CANNAME[i].data(), 5);
  83. if (ioctl(s[i], SIOCGIFINDEX, &ifr) < 0) {
  84. mfault->SetFaultState(2,2,"SIOCGIFINDEX.");
  85. emit SIG_CANOPENSTATE(false,-2,"SIOCGIFINDEX");
  86. return;
  87. }
  88. addr.can_ifindex = ifr.ifr_ifindex;
  89. if (bind(s[i], (struct sockaddr *)&addr, sizeof(addr)) < 0) {
  90. mfault->SetFaultState(2,3,"bind error.");
  91. emit SIG_CANOPENSTATE(false,-3,"bind error");
  92. return;
  93. }
  94. }
  95. mps = &s[0];
  96. mbCANOpen = true;
  97. mivlog->verbose("open can succesfully.");
  98. mfault->SetFaultState(0,0,"CAN OK.");
  99. emit SIG_CANOPENSTATE(true,0,"open can card successfully");
  100. std::cout<<"can open succesfully."<<std::endl;
  101. iov.iov_base = &frame;
  102. msg.msg_name = &addr;
  103. msg.msg_iov = &iov;
  104. msg.msg_iovlen = 1;
  105. msg.msg_control = &ctrlmsg;
  106. qint64 nLastRecv = QDateTime::currentMSecsSinceEpoch();
  107. int nRecvState = 0; // 0 Have Data 1 No Data;
  108. mbRunning = true;
  109. int nrecvcount = 0;
  110. qint64 nlastsecond = 0;
  111. int nsecondrecvcount = 0;
  112. qint64 nLastSecond = 0;
  113. int nsecondsend = 0;
  114. int nretry = 0;
  115. #ifdef SEND_STAT
  116. std::vector<qint64> xvectorlat;
  117. #endif
  118. int secondretrycount = 0;
  119. while((!QThread::isInterruptionRequested())&&(mbCANOpen))
  120. {
  121. FD_ZERO(&rdfs);
  122. for (i=0; i<currmax; i++)
  123. FD_SET(s[i], &rdfs);
  124. if (timeout_current)
  125. *timeout_current = timeout_config;
  126. timeout_config.tv_sec= 0;
  127. timeout_config.tv_usec = 0;;
  128. timeout_current = &timeout_config;
  129. ret = select(s[currmax-1]+1, &rdfs, NULL, NULL, timeout_current);
  130. if (ret < 0) {
  131. emit SIG_CANOPENSTATE(false,-4,"select error");
  132. mfault->SetFaultState(2,4,"select error.");
  133. std::cout<<"select error."<<std::endl;
  134. mbCANOpen = false;
  135. continue;
  136. }
  137. // std::cout<<"time: "<<QDateTime::currentMSecsSinceEpoch()<<" ret : "<<ret<<std::endl;
  138. bool bRecv = false;
  139. for (i=0; i<currmax; i++) { /* check all CAN RAW sockets */
  140. if (FD_ISSET(s[i], &rdfs)) {
  141. nLastRecv = QDateTime::currentMSecsSinceEpoch();
  142. /* these settings may be modified by recvmsg() */
  143. iov.iov_len = sizeof(frame);
  144. msg.msg_namelen = sizeof(addr);
  145. msg.msg_controllen = sizeof(ctrlmsg);
  146. msg.msg_flags = 0;
  147. mMutexRW.lock();
  148. nbytes = recvmsg(s[i], &msg, 0);
  149. mMutexRW.unlock();
  150. if (nbytes < 0) {
  151. // if ((errno == ENETDOWN) && !down_causes_exit) {
  152. if ((errno == ENETDOWN)) {
  153. mivlog->error("%s interface down", CANNAME[i].data());
  154. mfault->SetFaultState(1, 0, "interface down");
  155. emit SIG_CANOPENSTATE(false,-5,"can card down");
  156. fprintf(stderr, "%s: interface down\n", CANNAME[i].data());
  157. return;
  158. }
  159. continue;
  160. // perror("read");
  161. // return 1;
  162. }
  163. if ((size_t)nbytes == CAN_MTU)
  164. maxdlen = CAN_MAX_DLEN;
  165. else if ((size_t)nbytes == CANFD_MTU)
  166. maxdlen = CANFD_MAX_DLEN;
  167. else {
  168. std::cout<<"read incomplate message."<<std::endl;
  169. mivlog->warn("read incomplete message");
  170. continue;
  171. }
  172. bRecv = true;
  173. nrecvcount++;
  174. // qDebug("receive msg.");
  175. mMutex.lock();
  176. basecan_msg msg;
  177. msg.id = frame.can_id&0x1fffffff;
  178. if((frame.can_id&0x80000000)!= 0)msg.isExtern = true;
  179. else msg.isExtern = false;
  180. if((frame.can_id&0x40000000)!= 0)msg.isRemote = true;
  181. else msg.isRemote = false;
  182. msg.nLen = frame.len;
  183. nsecondrecvcount++;
  184. if((frame.len<9)&&(frame.len>0))memcpy(msg.data,frame.data,frame.len);
  185. if(mMsgRecvBuf[i].size()<BUF_SIZE)
  186. {
  187. mMsgRecvBuf[i].push_back(msg);
  188. }
  189. mMutex.unlock();
  190. }
  191. }
  192. qint64 nsecondnow = QDateTime::currentSecsSinceEpoch();
  193. if(nlastsecond != nsecondnow)
  194. {
  195. nlastsecond = nsecondnow;
  196. std::cout<<"second recv count:"<<nsecondrecvcount<<std::endl;
  197. nsecondrecvcount = 0;
  198. }
  199. if((QDateTime::currentMSecsSinceEpoch() - nLastRecv)> 1000)
  200. {
  201. if(nRecvState == 0)
  202. {
  203. nRecvState = -1;
  204. mfault->SetFaultState(0,1,"More than 1 second not receive data.");
  205. }
  206. }
  207. else
  208. {
  209. if(nRecvState == -1)
  210. {
  211. nRecvState = 0;
  212. mfault->SetFaultState(0,0,"CAN OK.");
  213. }
  214. }
  215. if(bRecv)continue;
  216. mWaitMutex.lock();
  217. mwc.wait(&mWaitMutex,1);
  218. mWaitMutex.unlock();
  219. #ifdef TEST_PROG
  220. // qDebug("send time : %lld",QDateTime::currentMSecsSinceEpoch());
  221. #endif
  222. struct canfd_frame framesend[2500];
  223. #ifdef SEND_STAT
  224. qint64 sendsettime[2500];
  225. #endif
  226. for(int nch =0;nch<currmax;nch++)
  227. {
  228. int nsend = 0;
  229. mMutex.lock();
  230. int nbufsize = mMsgSendBuf[nch].size();
  231. if(nbufsize>2500)nbufsize = 2500;
  232. for(i=0;i<nbufsize;i++)
  233. {
  234. if(i>=2500)break;
  235. memcpy(framesend[i].data,mMsgSendBuf[nch].at(i).data,8);
  236. framesend[i].can_id = mMsgSendBuf[nch].at(i).id;
  237. if(mMsgSendBuf[nch].at(i).isExtern)
  238. {
  239. framesend[i].can_id = framesend[i].can_id|0x80000000;
  240. }
  241. else
  242. {
  243. framesend[i].can_id = framesend[i].can_id&0x7ff;
  244. }
  245. if(mMsgSendBuf[nch].at(i).isRemote)
  246. {
  247. framesend[i].can_id= framesend[i].can_id|0x40000000;
  248. }
  249. framesend[i].len = mMsgSendBuf[nch].at(i).nLen;
  250. #ifdef SEND_STAT
  251. sendsettime[i] = mMsgSendBuf[nch].at(i).mSetTime;
  252. #endif
  253. nsend++;
  254. }
  255. mMsgSendBuf[nch].clear();
  256. mMutex.unlock();
  257. if(nsend > 0)
  258. {
  259. for(i=0;i<nsend;i++)
  260. {
  261. mMutexRW.lock();
  262. if (write(mps[nch], &framesend[i],16) != 16) {
  263. mMutexRW.unlock();
  264. mivlog->error("write error 1");
  265. // perror("write error 1.");
  266. nretry++;
  267. secondretrycount++;
  268. if(nretry > 5)
  269. {
  270. // std::cout<<"retry fail,retry:"<<nretry<<std::endl;
  271. }
  272. else
  273. {
  274. }
  275. if(nretry < 5)
  276. {
  277. i--;
  278. }
  279. else
  280. {
  281. nretry = 0;
  282. // std::cout<<"retry more than 100. drop this message."<<std::endl;
  283. }
  284. std::this_thread::sleep_for(std::chrono::microseconds(100));
  285. // std::cout<<"retry send."<<std::endl;
  286. continue;
  287. }
  288. else
  289. {
  290. mMutexRW.unlock();
  291. #ifdef SEND_STAT
  292. qint64 nnowms = QDateTime::currentMSecsSinceEpoch();
  293. qint64 nlat = nnowms - sendsettime[i];
  294. xvectorlat.push_back(nlat);
  295. nretry = 0;
  296. nsecondsend++;
  297. #endif
  298. }
  299. }
  300. }
  301. qint64 nnowsecond = QDateTime::currentSecsSinceEpoch();
  302. if( nnowsecond != nLastSecond)
  303. {
  304. nLastSecond = nnowsecond;
  305. std::cout<<" second send count: "<<nsecondsend<<std::endl;
  306. nsecondsend = 0;
  307. #ifdef SEND_STAT
  308. int j;
  309. int nsendcount = xvectorlat.size();
  310. if(nsendcount > 0)
  311. {
  312. qint64 xlatmax = 0;
  313. qint64 xlatavg = 0;
  314. for(j=0;j<nsendcount;j++)
  315. {
  316. if(xvectorlat[j]> xlatmax)xlatmax = xvectorlat[j];
  317. xlatavg = xlatavg + xvectorlat[j];
  318. }
  319. xlatavg = xlatavg/nsendcount;
  320. std::cout<<" max latency: "<<xlatmax<<" avg latency: "<<xlatavg
  321. <<" second retry count:"<<secondretrycount<<std::endl;
  322. xvectorlat.clear();
  323. }
  324. #endif
  325. secondretrycount = 0;
  326. }
  327. }
  328. }
  329. for (i=0; i<currmax; i++)
  330. {
  331. close(s[i]);
  332. }
  333. qDebug("nvcan thread close.");
  334. mbRunning = false;
  335. }
  336. void nvcan::threadsend()
  337. {
  338. return;
  339. int currmax = 1;
  340. int s[MAXSOCK];
  341. int i;
  342. struct sockaddr_can addr;
  343. struct ifreq ifr;
  344. for(i=0;i<currmax;i++)
  345. {
  346. s[i] = socket(PF_CAN, SOCK_RAW, CAN_RAW);
  347. if (s[i] < 0) {
  348. return;
  349. }
  350. addr.can_family = AF_CAN;
  351. memset(&ifr.ifr_name, 0, sizeof(ifr.ifr_name));
  352. strncpy(ifr.ifr_name, CANNAME[i].data(), 5);
  353. if (ioctl(s[i], SIOCGIFINDEX, &ifr) < 0) {
  354. return;
  355. }
  356. addr.can_ifindex = ifr.ifr_ifindex;
  357. if (bind(s[i], (struct sockaddr *)&addr, sizeof(addr)) < 0) {
  358. return;
  359. }
  360. }
  361. std::cout<<"threadsend open can success."<<std::endl;
  362. mps = &s[0];
  363. // int currmax = 1;
  364. // int i;
  365. while(mbCANOpen == false)
  366. {
  367. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  368. }
  369. qint64 nLastSecond = 0;
  370. int nsecondsend = 0;
  371. int nretry = 0;
  372. #ifdef SEND_STAT
  373. std::vector<qint64> xvectorlat;
  374. #endif
  375. int secondretrycount = 0;
  376. while(mbSendRun)
  377. {
  378. mWaitMutex.lock();
  379. mwc.wait(&mWaitMutex,100);
  380. mWaitMutex.unlock();
  381. #ifdef TEST_PROG
  382. // qDebug("send time : %lld",QDateTime::currentMSecsSinceEpoch());
  383. #endif
  384. struct canfd_frame framesend[2500];
  385. #ifdef SEND_STAT
  386. qint64 sendsettime[2500];
  387. #endif
  388. for(int nch =0;nch<currmax;nch++)
  389. {
  390. int nsend = 0;
  391. mMutex.lock();
  392. int nbufsize = mMsgSendBuf[nch].size();
  393. if(nbufsize>2500)nbufsize = 2500;
  394. for(i=0;i<nbufsize;i++)
  395. {
  396. if(i>=2500)break;
  397. memcpy(framesend[i].data,mMsgSendBuf[nch].at(i).data,8);
  398. framesend[i].can_id = mMsgSendBuf[nch].at(i).id;
  399. if(mMsgSendBuf[nch].at(i).isExtern)
  400. {
  401. framesend[i].can_id = framesend[i].can_id|0x80000000;
  402. }
  403. else
  404. {
  405. framesend[i].can_id = framesend[i].can_id&0x7ff;
  406. }
  407. if(mMsgSendBuf[nch].at(i).isRemote)
  408. {
  409. framesend[i].can_id= framesend[i].can_id|0x40000000;
  410. }
  411. framesend[i].len = mMsgSendBuf[nch].at(i).nLen;
  412. #ifdef SEND_STAT
  413. sendsettime[i] = mMsgSendBuf[nch].at(i).mSetTime;
  414. #endif
  415. nsend++;
  416. }
  417. mMsgSendBuf[nch].clear();
  418. mMutex.unlock();
  419. if(nsend > 0)
  420. {
  421. for(i=0;i<nsend;i++)
  422. {
  423. mMutexRW.lock();
  424. if (write(mps[nch], &framesend[i],16) != 16) {
  425. mMutexRW.unlock();
  426. mivlog->error("write error 1");
  427. // perror("write error 1.");
  428. nretry++;
  429. secondretrycount++;
  430. if(nretry > 30)
  431. {
  432. // std::cout<<"retry fail,retry:"<<nretry<<std::endl;
  433. }
  434. else
  435. {
  436. }
  437. if(nretry < 100)
  438. {
  439. i--;
  440. }
  441. else
  442. {
  443. nretry = 0;
  444. // std::cout<<"retry more than 100. drop this message."<<std::endl;
  445. }
  446. std::this_thread::sleep_for(std::chrono::microseconds(100));
  447. // std::cout<<"retry send."<<std::endl;
  448. continue;
  449. }
  450. else
  451. {
  452. mMutexRW.unlock();
  453. #ifdef SEND_STAT
  454. qint64 nnowms = QDateTime::currentMSecsSinceEpoch();
  455. qint64 nlat = nnowms - sendsettime[i];
  456. xvectorlat.push_back(nlat);
  457. nretry = 0;
  458. nsecondsend++;
  459. #endif
  460. }
  461. }
  462. }
  463. qint64 nnowsecond = QDateTime::currentSecsSinceEpoch();
  464. if( nnowsecond != nLastSecond)
  465. {
  466. nLastSecond = nnowsecond;
  467. std::cout<<" second send count: "<<nsecondsend<<std::endl;
  468. nsecondsend = 0;
  469. #ifdef SEND_STAT
  470. int j;
  471. int nsendcount = xvectorlat.size();
  472. if(nsendcount > 0)
  473. {
  474. qint64 xlatmax = 0;
  475. qint64 xlatavg = 0;
  476. for(j=0;j<nsendcount;j++)
  477. {
  478. if(xvectorlat[j]> xlatmax)xlatmax = xvectorlat[j];
  479. xlatavg = xlatavg + xvectorlat[j];
  480. }
  481. xlatavg = xlatavg/nsendcount;
  482. std::cout<<" max latency: "<<xlatmax<<" avg latency: "<<xlatavg
  483. <<" second retry count:"<<secondretrycount<<std::endl;
  484. xvectorlat.clear();
  485. }
  486. #endif
  487. secondretrycount = 0;
  488. }
  489. }
  490. }
  491. std::cout<<"nvcan::threadsend exit."<<std::endl;
  492. }
  493. void nvcan::startdev()
  494. {
  495. start();
  496. }
  497. void nvcan::stopdev()
  498. {
  499. requestInterruption();
  500. QTime xTime;
  501. xTime.start();
  502. while(xTime.elapsed()<100)
  503. {
  504. if(mbRunning == false)
  505. {
  506. mfault->SetFaultState(1, 0, "can closed");
  507. mivlog->error("can is closed at %d",xTime.elapsed());
  508. qDebug("can is closed.");
  509. break;
  510. }
  511. }
  512. }
  513. int nvcan::GetMessage(const int nch,basecan_msg *pMsg, const int nCap)
  514. {
  515. if((nch>1)||(nch < 0))return -1;
  516. if(mMsgRecvBuf[nch].size() == 0)return 0;
  517. int nRtn;
  518. nRtn = nCap;
  519. mMutex.lock();
  520. if(nRtn > mMsgRecvBuf[nch].size())nRtn = mMsgRecvBuf[nch].size();
  521. int i;
  522. for(i=0;i<nRtn;i++)
  523. {
  524. memcpy(&pMsg[i],&(mMsgRecvBuf[nch].at(i)),sizeof(basecan_msg));
  525. }
  526. std::vector<basecan_msg>::iterator iter;
  527. iter = mMsgRecvBuf[nch].begin();
  528. for(i=0;i<nRtn;i++)
  529. {
  530. iter = mMsgRecvBuf[nch].erase(iter);
  531. }
  532. mMutex.unlock();
  533. return nRtn;
  534. }
  535. int nvcan::SetMessage(const int nch, basecan_msg *pMsg)
  536. {
  537. if((nch>1)||(nch < 0))return -1;
  538. mMutex.lock();
  539. if(mMsgSendBuf[nch].size() > BUF_SIZE)
  540. {
  541. std::cout<<"buffer full."<<std::endl;
  542. mMutex.unlock();
  543. return -2;
  544. }
  545. if(mMsgRecvBuf[nch].size() > 100)
  546. {
  547. std::cout<<"buffer data more 100"<<std::endl;
  548. }
  549. mMsgSendBuf[nch].push_back(*pMsg);
  550. mMutex.unlock();
  551. return 0;
  552. }
  553. void nvcan::CmdSend()
  554. {
  555. mwc.wakeAll();
  556. }
  557. void nvcan::onMsg(bool bCAN, int nR, const char *strres)
  558. {
  559. mivlog->verbose("msg is %s ",strres);
  560. }