Page 1 of 1

How to detect unplugged PCAN-USB?

Posted: Mon 13. Jan 2020, 11:36
by Cluni
Hi,

I'm trying to use a PCAN-USB using SocketCAN in cpp under linux. Therefore I'm using a non-blocking read. Now I have the problem that I can't detect, if the PCAN-USB itself is unplugged out of the USB-Port. The read returns a -1 -- doesn't matter if the adapter is unplugged or if there only is a timeout. Is there a possibility to differ between these two situations?

Best regards,
Bernd

Re: How to detect unplugged PCAN-USB?

Posted: Mon 13. Jan 2020, 12:40
by M.Heidemann
Hi,

If you take a look at the source code for candump (Which you can find online by searching "candump.c"), you can see how this is handled in SocketCan (Starting from line 647):

Code: Select all

				for (i=0; i<currmax; i++) {  /* check all CAN RAW sockets */

			if (FD_ISSET(s[i], &rdfs)) {

				int idx;

				/* these settings may be modified by recvmsg() */
				iov.iov_len = sizeof(frame);
				msg.msg_namelen = sizeof(addr);
				msg.msg_controllen = sizeof(ctrlmsg);  
				msg.msg_flags = 0;

				nbytes = recvmsg(s[i], &msg, 0);
				idx = idx2dindex(addr.can_ifindex, s[i]);

				if (nbytes < 0) {
					if ((errno == ENETDOWN) && !down_causes_exit) {
						fprintf(stderr, "%s: interface down\n", devname[idx]);
						continue;
					}
					perror("read");
					return 1;
				}


You can take this as a starting point to implement your own solution.

Also take a look at the examples given in the documentation for SocketCan:

https://www.kernel.org/doc/Documentatio ... ng/can.txt

Best Regards

Marvin

Re: How to detect unplugged PCAN-USB?

Posted: Mon 13. Jan 2020, 14:49
by Cluni
Hello Marvin,

thank you very much!

Code: Select all

if ((errno == ENETDOWN)...

was the right hint!

I already took a look at the file "candump.h" before, but unfortunately I had an other (older?) version of this file. There wasn't any use of errno...

Now it works like it should! Thanks a lot!

Best regards
Bernd