nvcan.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  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. mivlog->warn("read incomplete message");
  169. continue;
  170. }
  171. bRecv = true;
  172. nrecvcount++;
  173. // qDebug("receive msg.");
  174. mMutex.lock();
  175. basecan_msg msg;
  176. msg.id = frame.can_id&0x1fffffff;
  177. if((frame.can_id&0x80000000)!= 0)msg.isExtern = true;
  178. else msg.isExtern = false;
  179. if((frame.can_id&0x40000000)!= 0)msg.isRemote = true;
  180. else msg.isRemote = false;
  181. msg.nLen = frame.len;
  182. nsecondrecvcount++;
  183. if((frame.len<9)&&(frame.len>0))memcpy(msg.data,frame.data,frame.len);
  184. if(mMsgRecvBuf[i].size()<BUF_SIZE)
  185. {
  186. mMsgRecvBuf[i].push_back(msg);
  187. }
  188. mMutex.unlock();
  189. }
  190. }
  191. qint64 nsecondnow = QDateTime::currentSecsSinceEpoch();
  192. if(nlastsecond != nsecondnow)
  193. {
  194. nlastsecond = nsecondnow;
  195. std::cout<<"second recv count:"<<nsecondrecvcount<<std::endl;
  196. nsecondrecvcount = 0;
  197. }
  198. if((QDateTime::currentMSecsSinceEpoch() - nLastRecv)> 1000)
  199. {
  200. if(nRecvState == 0)
  201. {
  202. nRecvState = -1;
  203. mfault->SetFaultState(0,1,"More than 1 second not receive data.");
  204. }
  205. }
  206. else
  207. {
  208. if(nRecvState == -1)
  209. {
  210. nRecvState = 0;
  211. mfault->SetFaultState(0,0,"CAN OK.");
  212. }
  213. }
  214. if(bRecv)continue;
  215. mWaitMutex.lock();
  216. mwc.wait(&mWaitMutex,1);
  217. mWaitMutex.unlock();
  218. #ifdef TEST_PROG
  219. // qDebug("send time : %lld",QDateTime::currentMSecsSinceEpoch());
  220. #endif
  221. struct canfd_frame framesend[2500];
  222. #ifdef SEND_STAT
  223. qint64 sendsettime[2500];
  224. #endif
  225. for(int nch =0;nch<currmax;nch++)
  226. {
  227. int nsend = 0;
  228. mMutex.lock();
  229. int nbufsize = mMsgSendBuf[nch].size();
  230. if(nbufsize>2500)nbufsize = 2500;
  231. for(i=0;i<nbufsize;i++)
  232. {
  233. if(i>=2500)break;
  234. memcpy(framesend[i].data,mMsgSendBuf[nch].at(i).data,8);
  235. framesend[i].can_id = mMsgSendBuf[nch].at(i).id;
  236. if(mMsgSendBuf[nch].at(i).isExtern)
  237. {
  238. framesend[i].can_id = framesend[i].can_id|0x80000000;
  239. }
  240. else
  241. {
  242. framesend[i].can_id = framesend[i].can_id&0x7ff;
  243. }
  244. if(mMsgSendBuf[nch].at(i).isRemote)
  245. {
  246. framesend[i].can_id= framesend[i].can_id|0x40000000;
  247. }
  248. framesend[i].len = mMsgSendBuf[nch].at(i).nLen;
  249. #ifdef SEND_STAT
  250. sendsettime[i] = mMsgSendBuf[nch].at(i).mSetTime;
  251. #endif
  252. nsend++;
  253. }
  254. mMsgSendBuf[nch].clear();
  255. mMutex.unlock();
  256. if(nsend > 0)
  257. {
  258. for(i=0;i<nsend;i++)
  259. {
  260. mMutexRW.lock();
  261. if (write(mps[nch], &framesend[i],16) != 16) {
  262. mMutexRW.unlock();
  263. mivlog->error("write error 1");
  264. // perror("write error 1.");
  265. nretry++;
  266. secondretrycount++;
  267. if(nretry > 5)
  268. {
  269. // std::cout<<"retry fail,retry:"<<nretry<<std::endl;
  270. }
  271. else
  272. {
  273. }
  274. if(nretry < 5)
  275. {
  276. i--;
  277. }
  278. else
  279. {
  280. nretry = 0;
  281. // std::cout<<"retry more than 100. drop this message."<<std::endl;
  282. }
  283. std::this_thread::sleep_for(std::chrono::microseconds(100));
  284. // std::cout<<"retry send."<<std::endl;
  285. continue;
  286. }
  287. else
  288. {
  289. mMutexRW.unlock();
  290. #ifdef SEND_STAT
  291. qint64 nnowms = QDateTime::currentMSecsSinceEpoch();
  292. qint64 nlat = nnowms - sendsettime[i];
  293. xvectorlat.push_back(nlat);
  294. nretry = 0;
  295. nsecondsend++;
  296. #endif
  297. }
  298. }
  299. }
  300. qint64 nnowsecond = QDateTime::currentSecsSinceEpoch();
  301. if( nnowsecond != nLastSecond)
  302. {
  303. nLastSecond = nnowsecond;
  304. std::cout<<" second send count: "<<nsecondsend<<std::endl;
  305. nsecondsend = 0;
  306. #ifdef SEND_STAT
  307. int j;
  308. int nsendcount = xvectorlat.size();
  309. if(nsendcount > 0)
  310. {
  311. qint64 xlatmax = 0;
  312. qint64 xlatavg = 0;
  313. for(j=0;j<nsendcount;j++)
  314. {
  315. if(xvectorlat[j]> xlatmax)xlatmax = xvectorlat[j];
  316. xlatavg = xlatavg + xvectorlat[j];
  317. }
  318. xlatavg = xlatavg/nsendcount;
  319. std::cout<<" max latency: "<<xlatmax<<" avg latency: "<<xlatavg
  320. <<" second retry count:"<<secondretrycount<<std::endl;
  321. xvectorlat.clear();
  322. }
  323. #endif
  324. secondretrycount = 0;
  325. }
  326. }
  327. }
  328. for (i=0; i<currmax; i++)
  329. {
  330. close(s[i]);
  331. }
  332. qDebug("nvcan thread close.");
  333. mbRunning = false;
  334. }
  335. void nvcan::threadsend()
  336. {
  337. return;
  338. int currmax = 1;
  339. int s[MAXSOCK];
  340. int i;
  341. struct sockaddr_can addr;
  342. struct ifreq ifr;
  343. for(i=0;i<currmax;i++)
  344. {
  345. s[i] = socket(PF_CAN, SOCK_RAW, CAN_RAW);
  346. if (s[i] < 0) {
  347. return;
  348. }
  349. addr.can_family = AF_CAN;
  350. memset(&ifr.ifr_name, 0, sizeof(ifr.ifr_name));
  351. strncpy(ifr.ifr_name, CANNAME[i].data(), 5);
  352. if (ioctl(s[i], SIOCGIFINDEX, &ifr) < 0) {
  353. return;
  354. }
  355. addr.can_ifindex = ifr.ifr_ifindex;
  356. if (bind(s[i], (struct sockaddr *)&addr, sizeof(addr)) < 0) {
  357. return;
  358. }
  359. }
  360. std::cout<<"threadsend open can success."<<std::endl;
  361. mps = &s[0];
  362. // int currmax = 1;
  363. // int i;
  364. while(mbCANOpen == false)
  365. {
  366. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  367. }
  368. qint64 nLastSecond = 0;
  369. int nsecondsend = 0;
  370. int nretry = 0;
  371. #ifdef SEND_STAT
  372. std::vector<qint64> xvectorlat;
  373. #endif
  374. int secondretrycount = 0;
  375. while(mbSendRun)
  376. {
  377. mWaitMutex.lock();
  378. mwc.wait(&mWaitMutex,100);
  379. mWaitMutex.unlock();
  380. #ifdef TEST_PROG
  381. // qDebug("send time : %lld",QDateTime::currentMSecsSinceEpoch());
  382. #endif
  383. struct canfd_frame framesend[2500];
  384. #ifdef SEND_STAT
  385. qint64 sendsettime[2500];
  386. #endif
  387. for(int nch =0;nch<currmax;nch++)
  388. {
  389. int nsend = 0;
  390. mMutex.lock();
  391. int nbufsize = mMsgSendBuf[nch].size();
  392. if(nbufsize>2500)nbufsize = 2500;
  393. for(i=0;i<nbufsize;i++)
  394. {
  395. if(i>=2500)break;
  396. memcpy(framesend[i].data,mMsgSendBuf[nch].at(i).data,8);
  397. framesend[i].can_id = mMsgSendBuf[nch].at(i).id;
  398. if(mMsgSendBuf[nch].at(i).isExtern)
  399. {
  400. framesend[i].can_id = framesend[i].can_id|0x80000000;
  401. }
  402. else
  403. {
  404. framesend[i].can_id = framesend[i].can_id&0x7ff;
  405. }
  406. if(mMsgSendBuf[nch].at(i).isRemote)
  407. {
  408. framesend[i].can_id= framesend[i].can_id|0x40000000;
  409. }
  410. framesend[i].len = mMsgSendBuf[nch].at(i).nLen;
  411. #ifdef SEND_STAT
  412. sendsettime[i] = mMsgSendBuf[nch].at(i).mSetTime;
  413. #endif
  414. nsend++;
  415. }
  416. mMsgSendBuf[nch].clear();
  417. mMutex.unlock();
  418. if(nsend > 0)
  419. {
  420. for(i=0;i<nsend;i++)
  421. {
  422. mMutexRW.lock();
  423. if (write(mps[nch], &framesend[i],16) != 16) {
  424. mMutexRW.unlock();
  425. mivlog->error("write error 1");
  426. // perror("write error 1.");
  427. nretry++;
  428. secondretrycount++;
  429. if(nretry > 30)
  430. {
  431. // std::cout<<"retry fail,retry:"<<nretry<<std::endl;
  432. }
  433. else
  434. {
  435. }
  436. if(nretry < 100)
  437. {
  438. i--;
  439. }
  440. else
  441. {
  442. nretry = 0;
  443. // std::cout<<"retry more than 100. drop this message."<<std::endl;
  444. }
  445. std::this_thread::sleep_for(std::chrono::microseconds(100));
  446. // std::cout<<"retry send."<<std::endl;
  447. continue;
  448. }
  449. else
  450. {
  451. mMutexRW.unlock();
  452. #ifdef SEND_STAT
  453. qint64 nnowms = QDateTime::currentMSecsSinceEpoch();
  454. qint64 nlat = nnowms - sendsettime[i];
  455. xvectorlat.push_back(nlat);
  456. nretry = 0;
  457. nsecondsend++;
  458. #endif
  459. }
  460. }
  461. }
  462. qint64 nnowsecond = QDateTime::currentSecsSinceEpoch();
  463. if( nnowsecond != nLastSecond)
  464. {
  465. nLastSecond = nnowsecond;
  466. std::cout<<" second send count: "<<nsecondsend<<std::endl;
  467. nsecondsend = 0;
  468. #ifdef SEND_STAT
  469. int j;
  470. int nsendcount = xvectorlat.size();
  471. if(nsendcount > 0)
  472. {
  473. qint64 xlatmax = 0;
  474. qint64 xlatavg = 0;
  475. for(j=0;j<nsendcount;j++)
  476. {
  477. if(xvectorlat[j]> xlatmax)xlatmax = xvectorlat[j];
  478. xlatavg = xlatavg + xvectorlat[j];
  479. }
  480. xlatavg = xlatavg/nsendcount;
  481. std::cout<<" max latency: "<<xlatmax<<" avg latency: "<<xlatavg
  482. <<" second retry count:"<<secondretrycount<<std::endl;
  483. xvectorlat.clear();
  484. }
  485. #endif
  486. secondretrycount = 0;
  487. }
  488. }
  489. }
  490. std::cout<<"nvcan::threadsend exit."<<std::endl;
  491. }
  492. void nvcan::startdev()
  493. {
  494. start();
  495. }
  496. void nvcan::stopdev()
  497. {
  498. requestInterruption();
  499. QTime xTime;
  500. xTime.start();
  501. while(xTime.elapsed()<100)
  502. {
  503. if(mbRunning == false)
  504. {
  505. mfault->SetFaultState(1, 0, "can closed");
  506. mivlog->error("can is closed at %d",xTime.elapsed());
  507. qDebug("can is closed.");
  508. break;
  509. }
  510. }
  511. }
  512. int nvcan::GetMessage(const int nch,basecan_msg *pMsg, const int nCap)
  513. {
  514. if((nch>1)||(nch < 0))return -1;
  515. if(mMsgRecvBuf[nch].size() == 0)return 0;
  516. int nRtn;
  517. nRtn = nCap;
  518. mMutex.lock();
  519. if(nRtn > mMsgRecvBuf[nch].size())nRtn = mMsgRecvBuf[nch].size();
  520. int i;
  521. for(i=0;i<nRtn;i++)
  522. {
  523. memcpy(&pMsg[i],&(mMsgRecvBuf[nch].at(i)),sizeof(basecan_msg));
  524. }
  525. std::vector<basecan_msg>::iterator iter;
  526. iter = mMsgRecvBuf[nch].begin();
  527. for(i=0;i<nRtn;i++)
  528. {
  529. iter = mMsgRecvBuf[nch].erase(iter);
  530. }
  531. mMutex.unlock();
  532. return nRtn;
  533. }
  534. int nvcan::SetMessage(const int nch, basecan_msg *pMsg)
  535. {
  536. if((nch>1)||(nch < 0))return -1;
  537. mMutex.lock();
  538. if(mMsgSendBuf[nch].size() > BUF_SIZE)
  539. {
  540. std::cout<<"buffer full."<<std::endl;
  541. mMutex.unlock();
  542. return -2;
  543. }
  544. if(mMsgRecvBuf[nch].size() > 100)
  545. {
  546. std::cout<<"buffer data more 100"<<std::endl;
  547. }
  548. mMsgSendBuf[nch].push_back(*pMsg);
  549. mMutex.unlock();
  550. return 0;
  551. }
  552. void nvcan::CmdSend()
  553. {
  554. mwc.wakeAll();
  555. }
  556. void nvcan::onMsg(bool bCAN, int nR, const char *strres)
  557. {
  558. mivlog->verbose("msg is %s ",strres);
  559. }