svinota / pyroute2

Python Netlink and PF_ROUTE library — network configuration and monitoring
https://pyroute2.org/
Other
960 stars 248 forks source link

Introduce netlink/rtnl CAN support #1109

Closed johnernberg closed 1 year ago

johnernberg commented 1 year ago

Adds handling of all the attributes related to CAN.

I was not able to figure out how create an interface similar to the iproute package, so the interface is a bit more low level in that instead of adding bitrate with "bitrate=" one has to package a can_bittiming dict with {"bitrate": }.

The attribute CAN_CLOCK is a struct of one member in the ABI, but it doesn't seem that fields support one-member structs.

A couple of the attributes haven't been tested because I do not have any dongles that support them. E.g. the TDC options.

Fixes #1023

svinota commented 1 year ago

Thanks a lot!

yegorich commented 1 year ago

@johnernberg could you please provide an example with setting a CAN bitrate? I've found the following code but, aside from bringing can0 interface up and down, nothing changes:

from time import sleep
from pyroute2 import IPRoute

with IPRoute() as ip_route:
    can0 = ip_route.link_lookup(ifname='can0')[0]
    link = ip_route.link('get', index=can0)
    if 'state' in link[0] and link[0]['state'] == 'up':
        ip_route.link('set', index=can0, state='down')
        sleep(1)

    ip_route.link('set', index=can0, type='can', bitrate=100000)
    ip_route.link('set', index=can0, state='up')
yegorich commented 1 year ago

Some info about my system. It's Debian Bookworm (Linux 6.1.0). CAN hardware is an SLCAN device.

The following command is working as expected:

ip link set can0 type can bitrate 100000

johnernberg commented 1 year ago

@yegorich As explained in the commit message this is a little bit more low level than the iproute command line.

What iproute tools call type is here called 'kind' because that is what netlink uses internally. And the bitrate must be provided using the can_bittiming structure which has a bitrate field.

Try:

ip_route.link('set', index=can0, kind='can', can_bittiming={'bitrate': 100000 })
yegorich commented 1 year ago

@johnernberg it works like a charm. Thank you very much. I'll try to submit a PR with such an example.

@svinota where should I place this example code? examples/iproute?