### Install python-can package via pip Source: https://python-can.readthedocs.io/en/stable/index.html#/_sources/installation.rst This command installs the core `python-can` library from PyPi using pip. It's the fundamental step to get started with the library. ```Bash $ pip install python-can ``` -------------------------------- ### Install core python-can library Source: https://python-can.readthedocs.io/en/stable/index.html#/installation Installs the main `python-can` package from PyPi using the pip package manager. This is the fundamental step to get the library set up. ```Shell $ pip install python-can ``` -------------------------------- ### Install python-can with CANtact Backend Source: https://python-can.readthedocs.io/en/stable/index.html#/installation Instructions for installing the python-can library with the CANtact driver backend using pip. Includes commands for initial installation and for adding the CANtact backend to an existing python-can installation. ```bash python3 -m pip install "python-can[cantact]" ``` ```bash pip install cantact ``` -------------------------------- ### Install python-can Pre-release Version Source: https://python-can.readthedocs.io/en/stable/index.html#/development Instructions to install the latest pre-release version of the python-can library using pip, ensuring you get the most recent development features. ```bash pip install --upgrade --pre python-can ``` -------------------------------- ### Install Python-CAN Pre-release Version Source: https://python-can.readthedocs.io/en/stable/index.html#/_sources/development.rst Instructions to install the latest pre-release version of the python-can library using pip, including an upgrade and pre-release flag to get the most recent development builds. ```Shell pip install --upgrade --pre python-can ``` -------------------------------- ### Install python-can in Development Mode Source: https://python-can.readthedocs.io/en/stable/index.html#/installation Guide to installing the python-can package in editable development mode, allowing local changes or Git updates to be used without reinstallation. Requires navigating to the repository directory. ```bash # install in editable mode cd python3 -m pip install -e . ``` -------------------------------- ### Install python-can with CANtact interface dependency Source: https://python-can.readthedocs.io/en/stable/index.html#/_sources/installation.rst These commands install `python-can` with the necessary CANtact driver backend. The first command is for a fresh install, while the second can be used to add the CANtact backend to an existing `python-can` installation. ```Bash python3 -m pip install "python-can[cantact]" ``` ```Bash pip install cantact ``` -------------------------------- ### Install socketcand Binary Source: https://python-can.readthedocs.io/en/stable/index.html#/interfaces/socketcand Command to install the compiled `socketcand` binary onto the system, making it available for use. ```Shell make install ``` -------------------------------- ### Install python-can with CanViewer Backend Source: https://python-can.readthedocs.io/en/stable/index.html#/installation Instructions for installing the necessary dependencies for the python-can simple CAN viewer terminal application on Windows, specifically the windows-curses library. ```bash python -m pip install "python-can[viewer]" ``` -------------------------------- ### Python Example: Setting up Notifier and Listener Source: https://python-can.readthedocs.io/en/stable/index.html#/_sources/notifier.rst This Python example demonstrates how to set up a `can.Notifier` to distribute messages from a CAN bus to a custom `can.Listener` implementation. It shows the basic structure for receiving and processing CAN messages, highlighting the creation of the notifier and listener. ```python import can import time class MyListener(can.Listener): def on_message_received(self, msg: can.Message) -> None: print(f"Message received: {msg}") bus = can.interface.Bus(bustype='virtual', channel='vcan0', is_extended=False) listener = MyListener() notifier = can.Notifier(bus, [listener]) print("Notifier and listener set up. Waiting for messages...") time.sleep(5) notifier.stop() bus.shutdown() ``` -------------------------------- ### Install python-can with Seeed Studio support Source: https://python-can.readthedocs.io/en/stable/index.html#/interfaces/seeedstudio Installs the `python-can` library along with the `pyserial` dependency required for the Seeed Studio USB-CAN Analyzer interface using pip. ```Bash pip install python-can[seeedstudio] ``` -------------------------------- ### Build socketcand from Source on Linux Source: https://python-can.readthedocs.io/en/stable/index.html#/interfaces/socketcand Commands to install necessary build tools (`autoconf`), clone the `socketcand` repository from GitHub, and compile the source code. This prepares the `socketcand` daemon for installation. ```Shell sudo apt-get install -y autoconf git clone https://github.com/linux-can/socketcand.git cd socketcand ./autogen.sh ./configure make ``` -------------------------------- ### Install python-can with specific interface dependencies Source: https://python-can.readthedocs.io/en/stable/index.html#/installation Installs `python-can` along with additional dependencies for a specific hardware or virtual interface. For example, the `serial` extra includes the `pyserial` dependency, streamlining the setup for that interface. ```Shell $ pip install python-can[serial] ``` -------------------------------- ### Define Multiple python-can Configuration Contexts in File Source: https://python-can.readthedocs.io/en/stable/index.html#/configuration This example expands on the configuration file format, demonstrating how to define multiple named sections (e.g., `[HS]`, `[MS]`) that inherit from the `[default]` section. This allows for pre-defined configurations for different CAN bus setups, such as high-speed or medium-speed, which can be loaded by context name. ```Configuration File [default] interface = channel = bitrate = [HS] # All the values from the 'default' section are inherited channel = bitrate = [MS] # All the values from the 'default' section are inherited channel = bitrate = ``` -------------------------------- ### Install python-can with serial interface dependency Source: https://python-can.readthedocs.io/en/stable/index.html#/_sources/installation.rst This command installs `python-can` along with the `pyserial` dependency, required for using the serial interface. It simplifies the setup for serial-based CAN communication. ```Bash $ pip install python-can[serial] ``` -------------------------------- ### Install python-can with CANalyst-II support Source: https://python-can.readthedocs.io/en/stable/index.html#/interfaces/canalystii This command installs the python-can library along with the necessary dependencies for the CANalyst-II interface. The 'canalystii' extra ensures the correct backend driver is included. ```Shell pip install "python-can[canalystii]" ``` -------------------------------- ### Install python-can with CANalyst-II support Source: https://python-can.readthedocs.io/en/stable/index.html#/_sources/interfaces/canalystii.rst Provides instructions for installing the `python-can` library with the necessary dependencies for CANalyst-II device support using pip. This command ensures the `canalystii` backend driver is included. ```bash pip install "python-can[canalystii]" ``` -------------------------------- ### Vector CAN Interface Configuration File Example Source: https://python-can.readthedocs.io/en/stable/index.html#/interfaces/vector An example configuration file demonstrating how to set up the Vector interface to connect to specific CAN channels (0 and 1) for a custom application named 'python-can'. This configuration can be used by the python-can library to initialize the bus. ```Configuration [default] interface = vector channel = 0, 1 app_name = python-can ``` -------------------------------- ### Install Python Dependencies for Seeed Studio USB-CAN Analyzer Source: https://python-can.readthedocs.io/en/stable/index.html#/_sources/interfaces/seeedstudio.rst Command to install the `python-can` library with the `seeedstudio` extra, which includes `pyserial`, required for the Seeed Studio USB-CAN Analyzer interface. ```bash pip install python-can[seeedstudio] ``` -------------------------------- ### Robotell CAN-USB Interface Connection Examples Source: https://python-can.readthedocs.io/en/stable/index.html#/_sources/interfaces/robotell.rst Examples demonstrating how to specify local and remote serial ports or URLs for connecting to the Robotell CAN-USB device, including baud rate specification. ```Text /dev/ttyUSB0@115200 COM4@9600 socket://192.168.254.254:5000 rfc2217://192.168.254.254:5000 ``` -------------------------------- ### Install python-can with PCAN interface dependency Source: https://python-can.readthedocs.io/en/stable/index.html#/_sources/installation.rst This command installs the `uptime` library, which is used by the PCANBasic API to convert timestamps to epoch times. It's recommended for accurate time handling with PCAN interfaces. ```Bash pip install python-can[pcan] ``` -------------------------------- ### Vector CAN Interface Configuration File Example Source: https://python-can.readthedocs.io/en/stable/index.html#/_sources/interfaces/vector.rst Example configuration file demonstrating how to connect to CAN channels 0 and 1 using the 'vector' interface with a custom application name 'python-can'. This configuration is typically used to specify application settings for the Vector CAN interface. ```ini [default] interface = vector channel = 0, 1 app_name = python-can ``` -------------------------------- ### Install python-can in editable development mode Source: https://python-can.readthedocs.io/en/stable/index.html#/_sources/installation.rst This sequence of commands allows installing `python-can` in editable mode from a local repository. It's useful for developers who want to make local changes or pull updates without constant reinstallation. ```Bash # install in editable mode cd python3 -m pip install -e . ``` -------------------------------- ### Install python-can with gs_usb backend Source: https://python-can.readthedocs.io/en/stable/index.html#/interfaces/gs_usb Command to install the `python-can` library along with the necessary `gs_usb` interface dependencies, enabling support for Geschwister Schneider and candleLight devices. ```bash pip install "python-can[gs_usb]" ``` -------------------------------- ### Install python-can with CanViewer dependency Source: https://python-can.readthedocs.io/en/stable/index.html#/_sources/installation.rst This command installs the `windows-curses` library, which is a dependency for the `can.viewer` terminal application on Windows. It enables the graphical CAN viewer functionality. ```Bash python -m pip install "python-can[viewer]" ``` -------------------------------- ### Enable SocketCAN Interface with systemd-networkd Source: https://python-can.readthedocs.io/en/stable/index.html#/interfaces/socketcand Steps to create a configuration file for `systemd-networkd` to automatically start the `can0` socketcan interface with a specified bitrate. It also includes commands to enable and immediately start the `systemd-networkd` service. ```Shell cat >/etc/systemd/network/80-can.network <<'EOT' [Match] Name=can0 [CAN] BitRate=250K RestartSec=100ms EOT ``` ```Shell sudo systemctl enable systemd-networkd sudo systemctl start systemd-networkd ``` -------------------------------- ### PCAN-Basic Configuration Example for PCAN-USB Source: https://python-can.readthedocs.io/en/stable/index.html#/_sources/interfaces/pcan.rst An example configuration file for `python-can` demonstrating how to set up the interface for PCAN-USB devices. It specifies the interface type as 'pcan', the channel name (e.g., 'PCAN_USBBUS1'), the bus state (e.g., `can.bus.BusState.PASSIVE`), and the bitrate (e.g., 500000). ```INI [default] interface = pcan channel = PCAN_USBBUS1 state = can.bus.BusState.PASSIVE bitrate = 500000 ``` -------------------------------- ### Install python-can in Editable Mode Source: https://python-can.readthedocs.io/en/stable/index.html#/development Command to install the python-can project in editable mode, allowing developers to make changes to the source code and see them reflected without reinstallation. ```bash pip install -e . ``` -------------------------------- ### Python Example: Replaying Logged CAN Messages with MessageSync Source: https://python-can.readthedocs.io/en/stable/index.html#/file_io This Python code demonstrates how to read CAN messages from an `.asc` log file using `can.LogReader` and then replay them onto a virtual CAN bus using `can.MessageSync`. The example shows how to open both a reader and a bus, iterate through the synchronized messages, print each message, and send it over the bus. ```python import can with can.LogReader("my_logfile.asc") as reader, can.Bus(interface="virtual") as bus: for msg in can.MessageSync(messages=reader): print(msg) bus.send(msg) ``` -------------------------------- ### Python Module Setup and Imports for `can.bus` Source: https://python-can.readthedocs.io/en/stable/index.html#/_modules/can/bus Initializes the `can.bus` module, setting up logging and importing necessary components for CAN bus abstraction. ```Python """ Contains the ABC bus implementation and its documentation. """ import contextlib import logging import threading from abc import ABC, ABCMeta, abstractmethod from enum import Enum, auto from time import time from types import TracebackType from typing import ( Any, Callable, Iterator, List, Optional, Sequence, Tuple, Type, Union, cast, ) from typing_extensions import Self import can import can.typechecking from can.broadcastmanager import CyclicSendTaskABC, ThreadBasedCyclicSendTask from can.message import Message LOG = logging.getLogger(__name__) ``` -------------------------------- ### can.io.sqlite Module Imports and Logger Setup Source: https://python-can.readthedocs.io/en/stable/index.html#/_modules/can/io/sqlite Initial Python code block for the `can.io.sqlite` module, including necessary imports and logger initialization. ```Python import logging import sqlite3 import threading import time from typing import Any, Generator from can.listener import BufferedReader from can.message import Message from ..typechecking import StringPathLike from .generic import MessageReader, MessageWriter log = logging.getLogger("can.io.sqlite") ``` -------------------------------- ### SeeedBus Constructor API Documentation Source: https://python-can.readthedocs.io/en/stable/index.html#/interfaces/seeedstudio Detailed API documentation for the `SeeedBus` class constructor, outlining all available parameters, their types, descriptions, and possible values for configuring the Seeed Studio USB-CAN Analyzer. ```APIDOC SeeedBus(channel, baudrate=2000000, timeout=0.1, frame_type='STD', operation_mode='normal', bitrate=500000) Parameters: channel (str): The serial port created by the USB device when connected (e.g., '/dev/ttyUSB0'). baudrate (int, optional): Baudrate for the underlying serial port. Defaults to 2000000. timeout (float, optional): Timeout for the underlying serial port. Defaults to 0.1. frame_type (str, optional): Type of CAN frames. Defaults to 'STD'. Possible values: "STD", "EXT" operation_mode (str, optional): Operational mode of the CAN interface. Defaults to 'normal'. Possible values: "normal", "loopback", "silent", "loopback_and_silent" bitrate (int, optional): CAN bus bitrate. Defaults to 500000. Possible values: 1000000, 800000, 500000, 400000, 250000, 200000, 125000, 100000, 50000, 20000, 10000, 5000 ``` -------------------------------- ### socketcand Daemon Startup Output Example Source: https://python-can.readthedocs.io/en/stable/index.html#/interfaces/socketcand This snippet illustrates the typical verbose output displayed by the socketcand daemon upon successful startup. It confirms the activated verbose mode, the network interface in use, the listening IP address and port, and the successful binding of the socket. ```shell Verbose output activated Using network interface 'eth0' Listen adress is 10.0.16.15 Broadcast adress is 10.0.255.255 creating broadcast thread... binding socket to 10.0.16.15:29536 ``` -------------------------------- ### Python-CAN SizedRotatingLogger Example Usage Source: https://python-can.readthedocs.io/en/stable/index.html#/_modules/can/io/logger Demonstrates how to initialize `SizedRotatingLogger` with a base filename and maximum size, and integrate it with a `Notifier` to log CAN messages from a `VectorBus`. The example sets up a 5MB log file that rotates, starting its counter at 23. ```python from can import Notifier, SizedRotatingLogger from can.interfaces.vector import VectorBus bus = VectorBus(channel=[0], app_name="CANape", fd=True) logger = SizedRotatingLogger( base_filename="my_logfile.asc", max_bytes=5 * 1024 ** 2, # =5MB ) logger.rollover_count = 23 # start counter at 23 notifier = Notifier(bus=bus, listeners=[logger]) ``` -------------------------------- ### Start IXXAT CAN Controller and Clear Receive FIFO Source: https://python-can.readthedocs.io/en/stable/index.html#/_modules/can/interfaces/ixxat/canlib_vcinpl2 Starts the IXXAT CAN controller to enable message forwarding to the channel. It then clears the receive FIFO by attempting to read messages with a low timeout, discarding any initial setup messages that might be present. ```python # Start the CAN controller. Messages will be forwarded to the channel _canlib.canControlStart(self._control_handle, constants.TRUE) # For cyclic transmit list. Set when .send_periodic() is first called self._scheduler = None self._scheduler_resolution = None self.channel = channel # Usually you get back 3 messages like "CAN initialized" ecc... # Clear the FIFO by filter them out with low timeout for _ in range(rx_fifo_size): try: _canlib.canChannelReadMessage( self._channel_handle, 0, ctypes.byref(self._message) ) except (VCITimeout, VCIRxQueueEmptyError): break super().__init__(channel=channel, can_filters=None, **kwargs) ``` -------------------------------- ### Initialize Seeed Studio CAN Bus Interface Source: https://python-can.readthedocs.io/en/stable/index.html#/interfaces/seeedstudio Example of initializing a CAN bus interface using the Seeed Studio adapter, specifying the serial channel and bitrate for communication. ```Python bus = can.interface.Bus(interface='seeedstudio', channel='/dev/ttyUSB0', bitrate=500000) ``` -------------------------------- ### Retrieve Kvaser CAN Bus Statistics Source: https://python-can.readthedocs.io/en/stable/index.html#/_modules/can/interfaces/kvaser/canlib Defines the `get_stats` method for retrieving real-time bus statistics from a Kvaser CAN interface. It utilizes `canRequestBusStatistics` and `canGetBusStatistics` to populate a `BusStatistics` object. Includes setup and usage examples for testing. ```python def get_stats(self) -> structures.BusStatistics: """Retrieves the bus statistics. Use like so: .. testsetup:: kvaser from unittest.mock import Mock from can.interfaces.kvaser.structures import BusStatistics bus = Mock() bus.get_stats = Mock(side_effect=lambda: BusStatistics()) .. doctest:: kvaser >>> stats = bus.get_stats() >>> print(stats) std_data: 0, std_remote: 0, ext_data: 0, ext_remote: 0, err_frame: 0, bus_load: 0.0%, overruns: 0 :returns: bus statistics. """ canRequestBusStatistics(self._write_handle) stats = structures.BusStatistics() canGetBusStatistics( self._write_handle, ctypes.pointer(stats), ctypes.sizeof(stats) ) return stats ``` ```python from unittest.mock import Mock from can.interfaces.kvaser.structures import BusStatistics bus = Mock() bus.get_stats = Mock(side_effect=lambda: BusStatistics()) ``` ```python stats = bus.get_stats() print(stats) ``` -------------------------------- ### ETAS CAN Interface Configuration File Example Source: https://python-can.readthedocs.io/en/stable/index.html#/_sources/interfaces/etas.rst Demonstrates a basic configuration file for the ETAS CAN interface, specifying the interface type as 'etas' and a sample channel URI. This configuration is used by the underlying API to connect to a specific ETAS device and CAN channel. ```ini [default] interface = etas channel = ETAS://ETH/ES910:abcd/CAN:1 ``` -------------------------------- ### Get All Connected IXXAT Hardware IDs in Python Source: https://python-can.readthedocs.io/en/stable/index.html#/interfaces/ixxat This example shows how to use the `get_ixxat_hwids()` function from `can.interfaces.ixxat` to retrieve a simple list of unique hardware IDs for all connected IXXAT devices. This is useful for quickly identifying available IXXAT hardware without detailed configuration information. ```Python from can.interfaces.ixxat import get_ixxat_hwids for hwid in get_ixxat_hwids(): print("Found IXXAT with hardware id '%s'." % hwid) ``` -------------------------------- ### PCAN Basic API Configuration Example Source: https://python-can.readthedocs.io/en/stable/index.html#/interfaces/pcan Example configuration file for using PCAN-USB with the python-can library. It defines the interface type, channel name, bus state, and bitrate. The 'channel' parameter specifies the CAN interface name (default 'PCAN_USBBUS1'), with valid values including PCAN_ISABUSx, PCAN_DNGBUSx, PCAN_PCIBUSx, PCAN_USBBUSx, PCAN_PCCBUSx, and PCAN_LANBUSx, where 'x' is the desired channel number starting at 1. The 'state' parameter sets the bus state (default 'can.bus.BusState.ACTIVE'), and 'bitrate' defines the channel speed in bits per second (default '500000'). ```INI [default] interface = pcan channel = PCAN_USBBUS1 state = can.bus.BusState.PASSIVE bitrate = 500000 ``` -------------------------------- ### Set up a Virtual SocketCAN Interface (vcan) Source: https://python-can.readthedocs.io/en/stable/index.html#/interfaces/socketcan This snippet demonstrates how to load the vcan kernel module, create a virtual CAN network interface (vcan0), and bring it up. This is useful for testing and development without physical CAN hardware. ```bash sudo modprobe vcan # Create a vcan network interface with a specific name sudo ip link add dev vcan0 type vcan sudo ip link set vcan0 up ``` -------------------------------- ### Example can.ini configuration for neoVI interface Source: https://python-can.readthedocs.io/en/stable/index.html#/interfaces/neovi A sample configuration file (can.ini) demonstrating how to set up the default interface to neoVI and specify a channel, typically used on Windows 7 or similar environments. ```ini [default] interface = neovi channel = 1 ``` -------------------------------- ### Install python-can with neoVI extras Source: https://python-can.readthedocs.io/en/stable/index.html#/interfaces/neovi Command to install the python-can library along with the necessary dependencies for the neoVI interface using pip. This ensures that the python-ics wrapper is also installed. ```python pip install python-can[neovi] ``` -------------------------------- ### Enable and Start systemd-networkd Service Source: https://python-can.readthedocs.io/en/stable/index.html#/_sources/interfaces/socketcand.rst These Bash commands enable the `systemd-networkd` service to start automatically on boot and immediately start it if it's not already running. This ensures that the network configurations, including the socketcan interface, are applied. ```bash sudo systemctl enable systemd-networkd sudo systemctl start systemd-networkd ``` -------------------------------- ### Install Python-CAN in Editable Development Mode Source: https://python-can.readthedocs.io/en/stable/index.html#/_sources/development.rst Command to install the python-can project in editable mode. This allows developers to make changes to the source code directly within the repository and have them reflected in the installed package without reinstallation, facilitating development. ```Shell pip install -e . ``` -------------------------------- ### Upload Python-CAN Packages to PyPI using Twine Source: https://python-can.readthedocs.io/en/stable/index.html#/_sources/development.rst This command uploads the generated distribution packages (wheel and sdist) to the Python Package Index (PyPI) using `twine`. It requires `twine` to be installed and proper PyPI credentials configured. The wildcard `*` ensures both wheel and source distribution files are uploaded. ```Shell twine upload dist/python-can-X.Y.Z* ``` -------------------------------- ### API Documentation for Kvaser Bus Initialization Parameters Source: https://python-can.readthedocs.io/en/stable/index.html#/_modules/can/interfaces/kvaser/canlib Detailed API documentation for the `__init__` method of the Kvaser bus interface, outlining all supported parameters, their types, and descriptions. This includes configuration for channel, filters, bit timing, CAN FD, and various operational modes. ```APIDOC KvaserBus: __init__(channel: int, can_filters: Optional[CanFilters] = None, timing: Optional[Union[BitTiming, BitTimingFd]] = None, **kwargs) channel (int): The Channel id to create this bus with. can_filters (list, optional): See :meth:`can.BusABC.set_filters`. timing (BitTiming | BitTimingFd, optional): An instance of :class:`~can.BitTiming` or :class:`~can.BitTimingFd` to specify the bit timing parameters for the Kvaser interface. If provided, it takes precedence over the all other timing-related parameters. Note that the `f_clock` property of the `timing` instance must be 16_000_000 (16MHz) for standard CAN or 80_000_000 (80MHz) for CAN FD. bitrate (int, optional): Bitrate of channel in bit/s. accept_virtual (bool, optional): If virtual channels should be accepted. tseg1 (int, optional): Time segment 1, that is, the number of quanta from (but not including) the Sync Segment to the sampling point. If this parameter is not given, the Kvaser driver will try to choose all bit timing parameters from a set of defaults. tseg2 (int, optional): Time segment 2, that is, the number of quanta from the sampling point to the end of the bit. sjw (int, optional): The Synchronization Jump Width. Decides the maximum number of time quanta that the controller can resynchronize every bit. no_samp (int, optional): Either 1 or 3. Some CAN controllers can also sample each bit three times. In this case, the bit will be sampled three quanta in a row, with the last sample being taken in the edge between TSEG1 and TSEG2. Three samples should only be used for relatively slow baudrates. driver_mode (bool, optional): Silent or normal. single_handle (bool, optional): Use one Kvaser CANLIB bus handle for both reading and writing. This can be set if reading and/or writing is done from one thread. receive_own_messages (bool, optional): If messages transmitted should also be received back. Only works if single_handle is also False. If you want to receive messages from other applications on the same computer, set this to True or set single_handle to True. fd (bool, optional): If CAN-FD frames should be supported. fd_non_iso (bool, optional): Open the channel in Non-ISO (Bosch) FD mode. Only applies for FD buses. This changes the handling of the stuff-bit counter and the CRC. Defaults to False (ISO mode). exclusive (bool, optional): Don't allow sharing of this CANlib channel. override_exclusive (bool, optional): Open the channel even if it is opened for exclusive access already. data_bitrate (int, optional): Which bitrate to use for data phase in CAN FD. Defaults to arbitration bitrate. ``` -------------------------------- ### Example CAN Message with 1-Byte Payload Source: https://python-can.readthedocs.io/en/stable/index.html#/_sources/interfaces/serial.rst Provides an example of a CAN message containing a single-byte payload, illustrating the Arbitration ID and the payload value. ```APIDOC CAN message with 1 byte payload: CAN message: Arbitration ID: 1 Payload: 0x11 ``` -------------------------------- ### Python Async IO Example for python-can Source: https://python-can.readthedocs.io/en/stable/index.html#/asyncio This example demonstrates how to use async IO with the python-can library. It sets up a virtual CAN bus, sends messages, and processes them asynchronously using a callback function and an AsyncBufferedReader, while also logging messages to a file. It showcases both callback and coroutine patterns for message handling. ```python #!/usr/bin/env python """ This example demonstrates how to use async IO with python-can. """ import asyncio from typing import List import can from can.notifier import MessageRecipient def print_message(msg: can.Message) -> None: """Regular callback function. Can also be a coroutine.""" print(msg) async def main() -> None: """The main function that runs in the loop.""" with can.Bus( interface="virtual", channel="my_channel_0", receive_own_messages=True ) as bus: reader = can.AsyncBufferedReader() logger = can.Logger("logfile.asc") listeners: List[MessageRecipient] = [ print_message, # Callback function reader, # AsyncBufferedReader() listener logger, # Regular Listener object ] # Create Notifier with an explicit loop to use for scheduling of callbacks loop = asyncio.get_running_loop() notifier = can.Notifier(bus, listeners, loop=loop) # Start sending first message bus.send(can.Message(arbitration_id=0)) print("Bouncing 10 messages...") for _ in range(10): # Wait for next message from AsyncBufferedReader msg = await reader.get_message() # Delay response await asyncio.sleep(0.5) msg.arbitration_id += 1 bus.send(msg) # Wait for last message to arrive await reader.get_message() print("Done!") # Clean-up notifier.stop() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Python CAN Broadcast Manager Cyclic Send Example Source: https://python-can.readthedocs.io/en/stable/index.html#/bcm This Python example demonstrates various periodic message sending capabilities using the `python-can` library's broadcast manager. It includes functions for simple periodic sends, sends with a limited duration, and modifying the data of a running cyclic task. The example is designed to run with a `vcan0` interface. ```python #!/usr/bin/env python """ This example exercises the periodic sending capabilities. Expects a vcan0 interface: python3 -m examples.cyclic """ import logging import time import can logging.basicConfig(level=logging.INFO) def simple_periodic_send(bus): """ Sends a message every 20ms with no explicit timeout Sleeps for 2 seconds then stops the task. """ print("Starting to send a message every 200ms for 2s") msg = can.Message( arbitration_id=0x123, data=[1, 2, 3, 4, 5, 6], is_extended_id=False ) task = bus.send_periodic(msg, 0.20) assert isinstance(task, can.CyclicSendTaskABC) time.sleep(2) task.stop() print("stopped cyclic send") def limited_periodic_send(bus): """Send using LimitedDurationCyclicSendTaskABC.""" print("Starting to send a message every 200ms for 1s") msg = can.Message( arbitration_id=0x12345678, data=[0, 0, 0, 0, 0, 0], is_extended_id=True ) task = bus.send_periodic(msg, 0.20, 1, store_task=False) if not isinstance(task, can.LimitedDurationCyclicSendTaskABC): print("This interface doesn't seem to support LimitedDurationCyclicSendTaskABC") task.stop() return time.sleep(2) print("Cyclic send should have stopped as duration expired") # Note the (finished) task will still be tracked by the Bus # unless we pass `store_task=False` to bus.send_periodic # alternatively calling stop removes the task from the bus # task.stop() def test_periodic_send_with_modifying_data(bus): """Send using ModifiableCyclicTaskABC.""" print("Starting to send a message every 200ms. Initial data is four consecutive 1s") msg = can.Message(arbitration_id=0x0CF02200, data=[1, 1, 1, 1]) task = bus.send_periodic(msg, 0.20) if not isinstance(task, can.ModifiableCyclicTaskABC): print("This interface doesn't seem to support modification") task.stop() return time.sleep(2) print("Changing data of running task to begin with 99") msg.data[0] = 0x99 task.modify_data(msg) time.sleep(2) task.stop() print("stopped cyclic send") print("Changing data of stopped task to single ff byte") msg.data = bytearray([0xFF]) msg.dlc = 1 task.modify_data(msg) time.sleep(1) print("starting again") task.start() time.sleep(1) task.stop() print("done") # Will have to consider how to expose items like this. The socketcan # interfaces will continue to support it... but the top level api won't. # def test_dual_rate_periodic_send(): # """Send a message 10 times at 1ms intervals, then continue to send every 500ms""" # msg = can.Message(arbitration_id=0x123, data=[0, 1, 2, 3, 4, 5]) # print("Creating cyclic task to send message 10 times at 1ms, then every 500ms") # task = can.interface.MultiRateCyclicSendTask('vcan0', msg, 10, 0.001, 0.50) # time.sleep(2) # # print("Changing data[0] = 0x42") # msg.data[0] = 0x42 # task.modify_data(msg) # time.sleep(2) # # task.stop() # print("stopped cyclic send") # # time.sleep(2) # # task.start() # print("starting again") # time.sleep(2) # task.stop() # print("done") def main(): """Test different cyclic sending tasks.""" reset_msg = can.Message( arbitration_id=0x00, data=[0, 0, 0, 0, 0, 0], is_extended_id=False ) # this uses the default configuration (for example from environment variables, or a # config file) see https://python-can.readthedocs.io/en/stable/configuration.html with can.Bus() as bus: bus.send(reset_msg) simple_periodic_send(bus) bus.send(reset_msg) limited_periodic_send(bus) test_periodic_send_with_modifying_data(bus) # print("Carrying out multirate cyclic test for {} interface".format(interface)) # can.rc['interface'] = interface # test_dual_rate_periodic_send() time.sleep(2) if __name__ == "__main__": main() ``` -------------------------------- ### IXXAT Interface Basic Configuration File Example Source: https://python-can.readthedocs.io/en/stable/index.html#/_sources/interfaces/ixxat.rst This snippet shows the simplest configuration for the IXXAT interface within a python-can configuration file. It specifies the interface type as 'ixxat' and opens the first available channel (channel 0) on the first detected IXXAT device. ```text [default] interface = ixxat channel = 0 ``` -------------------------------- ### Build Python-CAN Documentation with Tox Source: https://python-can.readthedocs.io/en/stable/index.html#/_sources/development.rst Command to build the project documentation using tox. This targets the documentation build environment, generating the necessary files for the project's documentation. ```Shell pipx run tox -e docs ``` -------------------------------- ### Install socketcand Daemon Source: https://python-can.readthedocs.io/en/stable/index.html#/_sources/interfaces/socketcand.rst This Bash command installs the compiled `socketcand` daemon onto the system. It typically places the executable in a system-wide path, making it available for execution. ```bash make install ``` -------------------------------- ### Example CAN Message Filter Dictionary Source: https://python-can.readthedocs.io/en/stable/index.html#/interfaces/socketcan An example Python dictionary structure used to define a CAN message filter for the `set_filters` method, specifying a CAN ID, mask, and extended flag. ```Python [{"can_id": 0x11, "can_mask": 0x21, "extended": False}] ``` -------------------------------- ### Configure python-can Bus Instance Parameters Source: https://python-can.readthedocs.io/en/stable/index.html#/configuration This example shows how to specify the CAN interface, channel, and bitrate directly when instantiating a `can.interface.Bus` object. This method allows for fine-grained control and different configurations for multiple bus instances within the same application. ```Python import can bus = can.interface.Bus(interface='socketcan', channel='vcan0', bitrate=500000) ``` -------------------------------- ### Build python-can Project Source: https://python-can.readthedocs.io/en/stable/index.html#/development Commands to build the python-can project from source and verify the integrity of the distribution files using pipx and twine. ```bash pipx run build pipx run twine check dist/* ``` -------------------------------- ### Build python-can Documentation Source: https://python-can.readthedocs.io/en/stable/index.html#/development Command to generate the documentation for the python-can project using tox, which compiles the reStructuredText source into viewable HTML. ```bash pipx run tox -e docs ``` -------------------------------- ### Python: Registering Custom CAN I/O Handlers via Entry Points Source: https://python-can.readthedocs.io/en/stable/index.html#/notifier Shows an example of how to configure `setuptools` entry points to register a custom message reader for `python-can`. This allows external packages to extend the library's file format support by defining a `can.io.message_reader` entry point. ```python entry_points={ 'can.io.message_reader': [ '.asc = my_package.io.asc:ASCReader' ] }, ``` -------------------------------- ### Check PCANBasic API Version Compatibility Source: https://python-can.readthedocs.io/en/stable/index.html#/_modules/can/interfaces/pcan/pcan Compares the installed PCANBasic API version with a minimum required version. Logs a warning if the installed version is below the minimum, advising an upgrade. ```python def check_api_version(self): apv = self.get_api_version() if apv < MIN_PCAN_API_VERSION: log.warning( f"Minimum version of pcan api is {MIN_PCAN_API_VERSION}." f" Installed version is {apv}. Consider upgrade of pcan basic package" ) ``` -------------------------------- ### Build socketcand from Source Source: https://python-can.readthedocs.io/en/stable/index.html#/_sources/interfaces/socketcand.rst This sequence of Bash commands outlines the steps to build the `socketcand` daemon from its source code. It includes installing `autoconf` (a dependency), cloning the `socketcand` repository, navigating into the directory, and then running `autogen.sh`, `configure`, and `make` to compile the project. ```bash # autoconf is needed to build socketcand sudo apt-get install -y autoconf # clone & build sources git clone https://github.com/linux-can/socketcand.git cd socketcand ./autogen.sh ./configure make ``` -------------------------------- ### Initialize CAN Bus Interface Source: https://python-can.readthedocs.io/en/stable/index.html#/_sources/bus.rst Demonstrates how to create an instance of a CAN bus using the `can.Bus` function, specifying a particular interface like 'vector'. This sets up the bus for hardware/software interactions. ```python vector_bus = can.Bus(interface='vector', ...) ``` -------------------------------- ### Access Help for can.player Command Line Tool Source: https://python-can.readthedocs.io/en/stable/index.html#/_sources/scripts.rst Demonstrates how to display the command-line help for the `can.player` module, which is used for playing back recorded CAN bus messages. This command shows all available options and usage instructions. ```APIDOC python -m can.player -h ``` -------------------------------- ### Start CyclicSendTask Transmission Source: https://python-can.readthedocs.io/en/stable/index.html#/_modules/can/interfaces/ixxat/canlib_vcinpl2 This method initiates the transmission of a cyclic message. If the message is not yet added to the scheduler's list, it adds it; otherwise, it simply starts the transmission of the existing message. ```python def start(self): """Start transmitting message (add to list if needed).""" if self._index is None: self._index = ctypes.c_uint32() _canlib.canSchedulerAddMessage(self._scheduler, self._msg, self._index) _canlib.canSchedulerStartMessage(self._scheduler, self._index, self._count) ``` -------------------------------- ### python-can viewer Command Line Interface Reference Source: https://python-can.readthedocs.io/en/stable/index.html#/scripts This snippet displays the full help output for the `python -m can.viewer` command, serving as a complete reference for all available command-line options, their expected values, and detailed explanations of their functionality. It covers general usage, positional arguments, and various options for configuring the CAN bus and data interpretation. ```bash $ python -m can.viewer -h ldf is not supported xls is not supported xlsx is not supported yaml is not supported Usage: python -m can.viewer [-c CHANNEL] [-i {canalystii,cantact,etas,gs_usb,iscan,ixxat,kvaser,neousys,neovi,nican,nixnet,pcan,robotell,seeedstudio,serial,slcan,socketcan,socketcand,systec,udp_multicast,usb2can,vector,virtual}] [-b BITRATE] [--fd] [--data_bitrate DATA_BITRATE] [--timing ('TIMING_ARG',)] [-h] [--version] [-d ('{:,:::...:,file.txt}',)] [-f ('{:,~}',)] [-v] ('extra_args',) A simple CAN viewer terminal application written in Python positional arguments: extra_args The remaining arguments will be used for the interface and logger/player initialisation. For example, `-i vector -c 1 --app-name=MyCanApp` is the equivalent to opening the bus with `Bus('vector', channel=1, app_name='MyCanApp') options: -c, --channel CHANNEL Most backend interfaces require some sort of channel. For example with the serial interface the channel might be a rfcomm device: "/dev/rfcomm0". With the socketcan interface valid channel examples include: "can0", "vcan0". -i, --interface {canalystii,cantact,etas,gs_usb,iscan,ixxat,kvaser,neousys,neovi,nican,nixnet,pcan,robotell,seeedstudio,serial,slcan,socketcan,socketcand,systec,udp_multicast,usb2can,vector,virtual} Specify the backend CAN interface to use. If left blank, fall back to reading from configuration files. -b, --bitrate BITRATE Bitrate to use for the CAN bus. --fd Activate CAN-FD support --data_bitrate DATA_BITRATE Bitrate to use for the data phase in case of CAN-FD. --timing ('TIMING_ARG',) Configure bit rate and bit timing. For example, use `--timing f_clock=8_000_000 tseg1=5 tseg2=2 sjw=2 brp=2 nof_samples=1` for classical CAN or `--timing f_clock=80_000_000 nom_tseg1=119 nom_tseg2=40 nom_sjw=40 nom_brp=1 data_tseg1=29 data_tseg2=10 data_sjw=10 data_brp=1` for CAN FD. Check the python- can documentation to verify whether your CAN interface supports the `timing` argument. Optional arguments: -h, --help Show this help message and exit --version Show program's version number and exit -d, --decode ('{:,:::...:,file.txt}',) Specify how to convert the raw bytes into real values. The ID of the frame is given as the first argument and the format as the second. The Python struct package is used to unpack the received data where the format characters have the following meaning: < = little-endian, > = big-endian x = pad byte c = char ? = bool b = int8_t, B = uint8_t h = int16, H = uint16 l = int32_t, L = uint32_t q = int64_t, Q = uint64_t f = float (32-bits), d = double (64-bits) Fx to convert six bytes with ID 0x100 into uint8_t, uint16 and uint32_t: $ python -m can.viewer -d "100: