SocketCAN

SocketCAN is a set of open source CAN drivers and a networking stack contributed by Volkswagen Research to the Linux kernel. SocketCAN was formerly known as Low Level CAN Framework (LLCF).

Typical CAN communication layers. With SocketCAN (left) or conventional (right).

Traditional CAN drivers for Linux are based on the model of character devices. Typically they only allow sending to and receiving from the CAN controller. Conventional implementations of this class of device driver only allow a single process to access the device, which means that all other processes are blocked in the meantime. In addition, these drivers typically all differ slightly in the interface presented to the application, stifling portability. The SocketCAN concept on the other hand uses the model of network devices, which allows multiple applications to access one CAN device simultaneously. Also, a single application is able to access multiple CAN networks in parallel.

The SocketCAN concept extends the Berkeley sockets API in Linux by introducing a new protocol family, PF_CAN, that coexists with other protocol families, such as PF_INET for the Internet Protocol. The communication with the CAN bus is therefore done analogously to the use of the Internet Protocol via sockets. Fundamental components of SocketCAN are the network device drivers for different CAN controllers and the implementation of the CAN protocol family. The protocol family, PF_CAN, provides the structures to enable different protocols on the bus: Raw sockets for direct CAN communication and transport protocols for point-to-point connections. Moreover the broadcast manager which is part of the CAN protocol family provides functions e.g. for sending CAN messages periodically or realize complex message filters. Since Linux kernel Version 5.10 the protocol family also includes an ISO-TP implementation, CAN_ISOTP.[1]

Patches for CAN were added in the 2.6.25 Linux kernel. Meanwhile some controller drivers were added and work is going on to add drivers for a variety of controllers.

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.[2] An open source library python-can provides SocketCAN support for Python 2 and Python 3[3][circular reference].

Installing a CAN device requires loading the can_dev module and configuring the IP link to specify the CAN bus bitrate, for example:

$ modprobe can_dev
$ modprobe can
$ modprobe can_raw
$ sudo ip link set can0 type can bitrate 500000
$ sudo ip link set up can0

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 vcan
$ sudo ip link add dev vcan0 type vcan
$ sudo ip link set up vcan0
$ ip link show vcan0
3: vcan0: <NOARP,UP,LOWER_UP> 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.[4]

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include <net/if.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>

#include <linux/can.h>
#include <linux/can/raw.h>

int
main(void)
{
	int s;
	int nbytes;
	struct sockaddr_can addr;
	struct can_frame frame;
	struct ifreq ifr;

	const char *ifname = "vcan0";

	if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) == -1) {
		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)) == -1) {
		perror("Error in socket bind");
		return -2;
	}

	frame.can_id  = 0x123;
	frame.can_dlc = 2;
	frame.data[0] = 0x11;
	frame.data[1] = 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[5] package.

user@server:~/can-utils $ ./candump vcan0
  vcan0  123  [2] 11 22

References

  1. ^ "hartkopp/can-isotp". May 14, 2021 – via GitHub.
  2. ^ "Issue 10141: SocketCan support - Python tracker". bugs.python.org.
  3. ^ SocketCAN
  4. ^ Viewable online from Linux Kernel Documentation or in linux/Documentation/networking/can.txt in most recent source trees
  5. ^ can-utils https://github.com/linux-can/can-utils/

Read other articles:

Song Hinh District Huyện Sông HinhDistrictNegara VietnamWilayahPusat Pesisir SelatanProvinsiPhu YenPusatHai RiengLuas • Total342 sq mi (885 km2)Populasi (2003) • Total38.102Zona waktuUTC+7 (UTC + 7) Sông Hinh merupakan sebuah distrik rural (huyện) di provinsi Phu Yen, wilayah Pusat Pesisir Selatan, Vietnam. Nama ini sama dengan nama sungai yang melintasi distrik ini, Sungai Hinh. Pada tahun 2003, distrik ini memiliki populasi sebesar 380,...

 

Artikel ini sebatang kara, artinya tidak ada artikel lain yang memiliki pranala balik ke halaman ini.Bantulah menambah pranala ke artikel ini dari artikel yang berhubungan atau coba peralatan pencari pranala.Tag ini diberikan pada Februari 2023. Uji protein metode Bradford dikembangkan oleh Marion M. Bradford pada tahun 1976.[1] Uji ini digunakan untuk menentukan konsentrasi protein dalam larutan menggunakan prosedur spektroskopi yang cepat dan akurat.[2].Reaksi bergantung pad...

 

العلاقات السويسرية الفانواتية سويسرا فانواتو   سويسرا   فانواتو تعديل مصدري - تعديل   العلاقات السويسرية الفانواتية هي العلاقات الثنائية التي تجمع بين سويسرا وفانواتو.[1][2][3][4][5] مقارنة بين البلدين هذه مقارنة عامة ومرجعية للدولتين: وجه الم...

Pertempuran BuchaBagian dari serangan Kyiv dalam Invasi Rusia ke Ukraina 2022Tanggal27 Februari – 12 Maret 2022 (Tahap pertama)29–31 Maret 2022 (Tahap kedua)LokasiBucha, Oblast Kyiv, UkrainaHasil Tahap pertama: Pasukan Rusia menduduki kota pada 12 Maret 2022.[1][2] Tahap kedua: Penarikan mundur pasukan Rusia pada 31 Maret 2022[3] dan kota dikuasai kembali oleh pasukan Ukraina.[4][5]Pihak terlibat  Rusia  UkrainaTokoh dan pemimpin Gennady B...

 

  لمعانٍ أخرى، طالع نشر (توضيح). نشرصنف فرعي من نشاط — اتصالات يمتهنه ناشر التاريخ publishing industry in China (en) — publishing history (en) تعديل - تعديل مصدري - تعديل ويكي بيانات طباعة الصحف في كابول، أفغانستان استمع إلى هذه المقالة (2 دقائق)noicon هذا الملف الصوتي أُنشئ من نسخة هذه المقالة المؤ�...

 

Volkswagen Beetle adalah simbol rekonstruksi Jerman Barat. Yang ada di gambar ini merupakan mobil ke-1.000.000. Wirtschaftswunder (Jerman: [ˈvɪʁt.ʃaftsˌvʊndɐ] ⓘ, keajaiban ekonomi), juga dikenal sebagai Keajaiban di Sungai Rhine, adalah istilah yang menjelaskan rekonstruksi dan perkembangan ekonomi Jerman Barat dan Austria yang begitu cepat setelah Perang Dunia II.[1][2] Istilah ini digunakan pertama kali oleh The Times tahun 1950.[butuh rujukan] Hal i...

МифологияРитуально-мифологическийкомплекс Система ценностей Сакральное Миф Мономиф Теория основного мифа Ритуал Обряд Праздник Жречество Мифологическое сознание Магическое мышление Низшая мифология Модель мира Цикличность Сотворение мира Мировое яйцо Мифическое �...

 

Le Maine parmi les anciennes provinces de France. Le Maine est une région historique et une ancienne province située dans l'Ouest de la France. Entouré par des régions plus affirmées comme la Bretagne, la Normandie ou encore l'Anjou, le Maine occupe une zone de transition, à cheval sur le Massif armoricain et le Bassin parisien. À ce titre, le Maine est une sorte de carrefour des paysages : sa frange occidentale évoque la Bretagne, l'Est est rempli de collines comme le paysage de...

 

Сельское поселение России (МО 2-го уровня)Новотитаровское сельское поселение Флаг[d] Герб 45°14′09″ с. ш. 38°58′16″ в. д.HGЯO Страна  Россия Субъект РФ Краснодарский край Район Динской Включает 4 населённых пункта Адм. центр Новотитаровская Глава сельского пос�...

For the village in Iran, see Barmah, Iran. Town in Victoria, AustraliaBarmahVictoriaMurray River crossing at BarmahBarmahCoordinates36°01′03″S 144°57′55″E / 36.01750°S 144.96528°E / -36.01750; 144.96528Population282 (2016 census)[1]Postcode(s)3639Location 265 km (165 mi) N of Melbourne 63 km (39 mi) NW of Shepparton 34 km (21 mi) SW of Echuca 27 km (17 mi) W of Nathalia 16 km (10 mi) W of Picola...

 

Geographic feature of Niger This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Geography of Niger – news · newspapers · books · scholar · JSTOR (April 2013) (Learn how and when to remove this message) Geography of NigerContinentAfricaRegionWestern AfricaCoordinates16°00′N 08°00′E / 16.000�...

 

Compact car This article is about the compact car produced since 2008. For the subcompact car produced between 2001 and 2008, see Suzuki Ignis. Motor vehicle Chevrolet Cruze2017 Chevrolet Cruze LT sedanOverviewManufacturerGeneral MotorsAlso calledDaewoo Lacetti Premiere (2008–2011)Holden Cruze (2009–2016)Holden Astra Sedan (2016–2019)Production2008–2023[1]Body and chassisClassCompact car (C)LayoutFront-engine, front-wheel driveChronologyPredecessorDaewoo/Chevrolet Lacetti...

ملخص معلومات الملف الوصف هذه صورة لشخصية: صالح القلاب المصدر (https://pydrojava.org/%D8%B5%D8%A7%D9%84%D8%AD-%D8%A7%D9%84%D9%82%D9%84%D8%A7%D8%A8-%D8%A7%D9%84%D8%B9%D8%B1%D8%A8-%D9%85%D8%B9-%D8%AD%D9%82%D9%88%D9%82-%D8%A7%D9%84%D9%83%D8%B1%D8%AF-%D9%88%D8%A7%D9%84%D9%85%D8%B4%D9%83/) التاريخ المنتج هذا الملف لا يمتلك معلومات معلومات المنتج، وربما تنقصه بعض المعلومات الأ�...

 

Election for the governorship of the U.S. state of Minnesota 1930 Minnesota gubernatorial election ← 1928 November 4, 1930 1932 →   Nominee Floyd B. Olson Ray P. Chase Party Farmer–Labor Republican Popular vote 473,154 289,528 Percentage 59.34% 36.31% County resultsOlson:      40-50%      50-60%      60-70%      70-80%Chase:      40-50%...

 

Football clubShodmon HisorFull nameShodmon GhissarGround Hisor, TajikistanLeagueTajik League201110th Shodmon Hisor (Persian: دسته فوتبال شادمان, Dastai Futboli Shodmon) is a Tajikistan association football club from Hisor. History Domestic history Season League Tajik Cup Top goalscorer Manager Div. Pos. Pl. W D L GS GA P Name League 1992 1st 7th 20 8 4 8 18 16 20 1993 1st 7th 30 14 7 9 54 33 35 1994 1st 5th 30 14 11 5 64 25 39 Runner-Up 1995 1st 9th 28 11 5 12 38 44 38 1996 1s...

由於受到破坏,依據方針,本条目页已獲半保護。 請参閱保护方针及保护日志以获取更多信息。如果您不能修改此条目页,您可以请求修改、在讨论页提出修改提议、申请解除保护、登录或创建账号。 此條目可参照英語維基百科相應條目来扩充。 (2021年1月5日)若您熟悉来源语言和主题,请协助参考外语维基百科扩充条目。请勿直接提交机械翻译,也不要翻译不可靠、低品�...

 

Study of physical, chemical, and biological processes in the ocean For the scientific journal, see Oceanography (journal) and Ocean Science (journal). Thermohaline circulation Oceanography (from Ancient Greek ὠκεανός (ōkeanós) 'ocean', and γραφή (graphḗ) 'writing'), also known as oceanology, sea science, ocean science, and marine science, is the scientific study of the oceans. It is an Earth science, which covers a wide range of topics, including e...

 

2011 video game 2011 video gameThe Witcher 2: Assassins of KingsDeveloper(s)CD Projekt RedPublisher(s)CD ProjektDirector(s)Adam Badowski[3]Producer(s)Jędrzej MrózDesigner(s)Mateusz KanikMaciej SzcześnikProgrammer(s)Tomasz WójcikWriter(s)Sebastian StępieńKonrad TomaszkiewiczMarcin BlachaComposer(s)Adam SkorupaKrzysztof WierzynkiewiczMarcin PrzybyłowiczSeriesThe WitcherEngineREDenginePlatform(s)Microsoft WindowsXbox 360[4]OS X[5]Linux[6]Release 17 May 2011...

Deviations from local realism Part of a series of articles aboutQuantum mechanics i ℏ d d t | Ψ ⟩ = H ^ | Ψ ⟩ {\displaystyle i\hbar {\frac {d}{dt}}|\Psi \rangle ={\hat {H}}|\Psi \rangle } Schrödinger equation Introduction Glossary History Background Classical mechanics Old quantum theory Bra–ket notation Hamiltonian Interference Fundamentals Complementarity Decoherence Entanglement Energy level Measurement Nonlocality Quantum number State Superposi...

 

Disambiguazione – Se stai cercando altri significati, vedi Hardware (disambigua). Vista dei componenti di un PC raffreddato a liquido L'hardware (abbreviato HW, dall'inglese hard «duro, pesante»,[1] e ware «merci, prodotti», su imitazione del termine software) è l'insieme di tutte le parti tangibili elettroniche, elettriche, meccaniche, magnetiche, ottiche che consentono il funzionamento di un computer. Più in generale il termine si riferisce a qualsiasi componente fisico...