Socket CAN - Usage

Usage

The application first sets up its access to the CAN interface by initialising a socket (much like in TCP/IP communications), then binding that socket to an interface (or all interfaces, if the application so desires). Once bound, the socket can then be used like a UDP socket via read, write, etc...

Python added support for SocketCan in version 3.3.

There is also a virtual can driver for testing purposes which can be loaded and created in Linux with the commands below.

$ modprobe can $ modprobe can_raw $ modprobe can_bcm $ modprobe vcan $ sudo ip link add dev vcan0 type vcan $ sudo ip link set up vcan0 $ ip link show vcan0 3: vcan0: mtu 16 qdisc noqueue state UNKNOWN link/can

The following code snippet is a working example of the SocketCAN API, that sends a packet using the raw interface. It is based on the notes documented in the Linux Kernel.

#include #include #include #include #include #include #include #include #include #include int main(void) { int s; int nbytes; struct sockaddr_can addr; struct can_frame frame; struct ifreq ifr; char *ifname = "vcan0"; if((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) { perror("Error while opening socket"); return -1; } strcpy(ifr.ifr_name, ifname); ioctl(s, SIOCGIFINDEX, &ifr); addr.can_family = AF_CAN; addr.can_ifindex = ifr.ifr_ifindex; printf("%s at index %d\n", ifname, ifr.ifr_ifindex); if(bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("Error in socket bind"); return -2; } frame.can_id = 0x123; frame.can_dlc = 2; frame.data = 0x11; frame.data = 0x22; nbytes = write(s, &frame, sizeof(struct can_frame)); printf("Wrote %d bytes\n", nbytes); return 0; }

The packet can be analyzed on the vcan0 interface using the candump utility which is part of the SocketCAN can-utils package.

can-utils $ ./candump vcan0 vcan0 123 11 22

Read more about this topic:  Socket CAN

Famous quotes containing the word usage:

    ...Often the accurate answer to a usage question begins, “It depends.” And what it depends on most often is where you are, who you are, who your listeners or readers are, and what your purpose in speaking or writing is.
    Kenneth G. Wilson (b. 1923)

    Pythagoras, Locke, Socrates—but pages
    Might be filled up, as vainly as before,
    With the sad usage of all sorts of sages,
    Who in his life-time, each was deemed a bore!
    The loftiest minds outrun their tardy ages.
    George Gordon Noel Byron (1788–1824)

    Girls who put out are tramps. Girls who don’t are ladies. This is, however, a rather archaic usage of the word. Should one of you boys happen upon a girl who doesn’t put out, do not jump to the conclusion that you have found a lady. What you have probably found is a lesbian.
    Fran Lebowitz (b. 1951)