2121log_tx = log .getChild ("tx" )
2222log_rx = log .getChild ("rx" )
2323
24- try :
25- import fcntl
26- except ImportError :
27- log .error ("fcntl not available on this platform" )
28-
29-
3024try :
3125 from socket import CMSG_SPACE
3226
4438 LimitedDurationCyclicSendTaskABC ,
4539)
4640from can .typechecking import CanFilters
47- from can .interfaces .socketcan . constants import * # CAN_RAW, CAN_*_FLAG
41+ from can .interfaces .socketcan import constants
4842from can .interfaces .socketcan .utils import pack_filters , find_available_interfaces
4943
5044
@@ -177,9 +171,9 @@ def build_can_frame(msg: Message) -> bytes:
177171 can_id = _compose_arbitration_id (msg )
178172 flags = 0
179173 if msg .bitrate_switch :
180- flags |= CANFD_BRS
174+ flags |= constants . CANFD_BRS
181175 if msg .error_state_indicator :
182- flags |= CANFD_ESI
176+ flags |= constants . CANFD_ESI
183177 max_len = 64 if msg .is_fd else 8
184178 data = bytes (msg .data ).ljust (max_len , b"\x00 " )
185179 return CAN_FRAME_HEADER_STRUCT .pack (can_id , msg .dlc , flags ) + data
@@ -211,7 +205,7 @@ def build_bcm_header(
211205
212206
213207def build_bcm_tx_delete_header (can_id : int , flags : int ) -> bytes :
214- opcode = CAN_BCM_TX_DELETE
208+ opcode = constants . CAN_BCM_TX_DELETE
215209 return build_bcm_header (opcode , flags , 0 , 0 , 0 , 0 , 0 , can_id , 1 )
216210
217211
@@ -223,13 +217,13 @@ def build_bcm_transmit_header(
223217 msg_flags : int ,
224218 nframes : int = 1 ,
225219) -> bytes :
226- opcode = CAN_BCM_TX_SETUP
220+ opcode = constants . CAN_BCM_TX_SETUP
227221
228- flags = msg_flags | SETTIMER | STARTTIMER
222+ flags = msg_flags | constants . SETTIMER | constants . STARTTIMER
229223
230224 if initial_period > 0 :
231225 # Note `TX_COUNTEVT` creates the message TX_EXPIRED when count expires
232- flags |= TX_COUNTEVT
226+ flags |= constants . TX_COUNTEVT
233227
234228 def split_time (value : float ) -> Tuple [int , int ]:
235229 """Given seconds as a float, return whole seconds and microseconds"""
@@ -254,20 +248,22 @@ def split_time(value: float) -> Tuple[int, int]:
254248
255249
256250def build_bcm_update_header (can_id : int , msg_flags : int , nframes : int = 1 ) -> bytes :
257- return build_bcm_header (CAN_BCM_TX_SETUP , msg_flags , 0 , 0 , 0 , 0 , 0 , can_id , nframes )
251+ return build_bcm_header (
252+ constants .CAN_BCM_TX_SETUP , msg_flags , 0 , 0 , 0 , 0 , 0 , can_id , nframes
253+ )
258254
259255
260256def dissect_can_frame (frame : bytes ) -> Tuple [int , int , int , bytes ]:
261257 can_id , can_dlc , flags = CAN_FRAME_HEADER_STRUCT .unpack_from (frame )
262- if len (frame ) != CANFD_MTU :
258+ if len (frame ) != constants . CANFD_MTU :
263259 # Flags not valid in non-FD frames
264260 flags = 0
265261 return can_id , can_dlc , flags , frame [8 : 8 + can_dlc ]
266262
267263
268264def create_bcm_socket (channel : str ) -> socket .socket :
269265 """create a broadcast manager socket and connect to the given interface"""
270- s = socket .socket (PF_CAN , socket .SOCK_DGRAM , CAN_BCM )
266+ s = socket .socket (constants . PF_CAN , socket .SOCK_DGRAM , constants . CAN_BCM )
271267 s .connect ((channel ,))
272268 return s
273269
@@ -297,13 +293,13 @@ def _compose_arbitration_id(message: Message) -> int:
297293 can_id = message .arbitration_id
298294 if message .is_extended_id :
299295 log .debug ("sending an extended id type message" )
300- can_id |= CAN_EFF_FLAG
296+ can_id |= constants . CAN_EFF_FLAG
301297 if message .is_remote_frame :
302298 log .debug ("requesting a remote frame" )
303- can_id |= CAN_RTR_FLAG
299+ can_id |= constants . CAN_RTR_FLAG
304300 if message .is_error_frame :
305301 log .debug ("sending error frame" )
306- can_id |= CAN_ERR_FLAG
302+ can_id |= constants . CAN_ERR_FLAG
307303 return can_id
308304
309305
@@ -354,7 +350,7 @@ def _tx_setup(
354350 ) -> None :
355351 # Create a low level packed frame to pass to the kernel
356352 body = bytearray ()
357- self .flags = CAN_FD_FRAME if messages [0 ].is_fd else 0
353+ self .flags = constants . CAN_FD_FRAME if messages [0 ].is_fd else 0
358354
359355 if self .duration :
360356 count = int (self .duration / self .period )
@@ -380,7 +376,7 @@ def _check_bcm_task(self) -> None:
380376 # Do a TX_READ on a task ID, and check if we get EINVAL. If so,
381377 # then we are referring to a CAN message with an existing ID
382378 check_header = build_bcm_header (
383- opcode = CAN_BCM_TX_READ ,
379+ opcode = constants . CAN_BCM_TX_READ ,
384380 flags = 0 ,
385381 count = 0 ,
386382 ival1_seconds = 0 ,
@@ -391,7 +387,7 @@ def _check_bcm_task(self) -> None:
391387 nframes = 0 ,
392388 )
393389 log .debug (
394- f "Reading properties of (cyclic) transmission task id={ self .task_id } " ,
390+ "Reading properties of (cyclic) transmission task id=%d" , self .task_id
395391 )
396392 try :
397393 self .bcm_socket .send (check_header )
@@ -495,7 +491,7 @@ def create_socket() -> socket.socket:
495491 """Creates a raw CAN socket. The socket will
496492 be returned unbound to any interface.
497493 """
498- sock = socket .socket (PF_CAN , socket .SOCK_RAW , CAN_RAW )
494+ sock = socket .socket (constants . PF_CAN , socket .SOCK_RAW , constants . CAN_RAW )
499495
500496 log .info ("Created a socket" )
501497
@@ -534,7 +530,7 @@ def capture_message(
534530 # Fetching the Arb ID, DLC and Data
535531 try :
536532 cf , ancillary_data , msg_flags , addr = sock .recvmsg (
537- CANFD_MTU , RECEIVED_ANCILLARY_BUFFER_SIZE
533+ constants . CANFD_MTU , RECEIVED_ANCILLARY_BUFFER_SIZE
538534 )
539535 if get_channel :
540536 channel = addr [0 ] if isinstance (addr , tuple ) else addr
@@ -549,7 +545,7 @@ def capture_message(
549545 assert len (ancillary_data ) == 1 , "only requested a single extra field"
550546 cmsg_level , cmsg_type , cmsg_data = ancillary_data [0 ]
551547 assert (
552- cmsg_level == socket .SOL_SOCKET and cmsg_type == SO_TIMESTAMPNS
548+ cmsg_level == socket .SOL_SOCKET and cmsg_type == constants . SO_TIMESTAMPNS
553549 ), "received control message type that was not requested"
554550 # see https://man7.org/linux/man-pages/man3/timespec.3.html -> struct timespec for details
555551 seconds , nanoseconds = RECEIVED_TIMESTAMP_STRUCT .unpack_from (cmsg_data )
@@ -564,12 +560,12 @@ def capture_message(
564560 # #define CAN_EFF_FLAG 0x80000000U /* EFF/SFF is set in the MSB */
565561 # #define CAN_RTR_FLAG 0x40000000U /* remote transmission request */
566562 # #define CAN_ERR_FLAG 0x20000000U /* error frame */
567- is_extended_frame_format = bool (can_id & CAN_EFF_FLAG )
568- is_remote_transmission_request = bool (can_id & CAN_RTR_FLAG )
569- is_error_frame = bool (can_id & CAN_ERR_FLAG )
570- is_fd = len (cf ) == CANFD_MTU
571- bitrate_switch = bool (flags & CANFD_BRS )
572- error_state_indicator = bool (flags & CANFD_ESI )
563+ is_extended_frame_format = bool (can_id & constants . CAN_EFF_FLAG )
564+ is_remote_transmission_request = bool (can_id & constants . CAN_RTR_FLAG )
565+ is_error_frame = bool (can_id & constants . CAN_ERR_FLAG )
566+ is_fd = len (cf ) == constants . CANFD_MTU
567+ bitrate_switch = bool (flags & constants . CANFD_BRS )
568+ error_state_indicator = bool (flags & constants . CANFD_ESI )
573569
574570 # Section 4.7.1: MSG_DONTROUTE: set when the received frame was created on the local host.
575571 is_rx = not bool (msg_flags & socket .MSG_DONTROUTE )
@@ -625,8 +621,8 @@ def __init__(
625621 ) -> None :
626622 """Creates a new socketcan bus.
627623
628- If setting some socket options fails, an error will be printed but no exception will be thrown.
629- This includes enabling:
624+ If setting some socket options fails, an error will be printed
625+ but no exception will be thrown. This includes enabling:
630626
631627 - that own messages should be received,
632628 - CAN-FD frames and
@@ -656,7 +652,7 @@ def __init__(
656652 """
657653 self .socket = create_socket ()
658654 self .channel = channel
659- self .channel_info = "socketcan channel '%s'" % channel
655+ self .channel_info = f "socketcan channel '{ channel } '"
660656 self ._bcm_sockets : Dict [str , socket .socket ] = {}
661657 self ._is_filtered = False
662658 self ._task_id = 0
@@ -665,39 +661,47 @@ def __init__(
665661 # set the local_loopback parameter
666662 try :
667663 self .socket .setsockopt (
668- SOL_CAN_RAW , CAN_RAW_LOOPBACK , 1 if local_loopback else 0
664+ constants .SOL_CAN_RAW ,
665+ constants .CAN_RAW_LOOPBACK ,
666+ 1 if local_loopback else 0 ,
669667 )
670668 except OSError as error :
671669 log .error ("Could not set local loopback flag(%s)" , error )
672670
673671 # set the receive_own_messages parameter
674672 try :
675673 self .socket .setsockopt (
676- SOL_CAN_RAW , CAN_RAW_RECV_OWN_MSGS , 1 if receive_own_messages else 0
674+ constants .SOL_CAN_RAW ,
675+ constants .CAN_RAW_RECV_OWN_MSGS ,
676+ 1 if receive_own_messages else 0 ,
677677 )
678678 except OSError as error :
679679 log .error ("Could not receive own messages (%s)" , error )
680680
681681 # enable CAN-FD frames if desired
682682 if fd :
683683 try :
684- self .socket .setsockopt (SOL_CAN_RAW , CAN_RAW_FD_FRAMES , 1 )
684+ self .socket .setsockopt (
685+ constants .SOL_CAN_RAW , constants .CAN_RAW_FD_FRAMES , 1
686+ )
685687 except OSError as error :
686688 log .error ("Could not enable CAN-FD frames (%s)" , error )
687689
688690 if not ignore_rx_error_frames :
689691 # enable error frames
690692 try :
691- self .socket .setsockopt (SOL_CAN_RAW , CAN_RAW_ERR_FILTER , 0x1FFFFFFF )
693+ self .socket .setsockopt (
694+ constants .SOL_CAN_RAW , constants .CAN_RAW_ERR_FILTER , 0x1FFFFFFF
695+ )
692696 except OSError as error :
693697 log .error ("Could not enable error frames (%s)" , error )
694698
695699 # enable nanosecond resolution timestamping
696700 # we can always do this since
697- # 1) is is guaranteed to be at least as precise as without
701+ # 1) it is guaranteed to be at least as precise as without
698702 # 2) it is available since Linux 2.6.22, and CAN support was only added afterward
699703 # so this is always supported by the kernel
700- self .socket .setsockopt (socket .SOL_SOCKET , SO_TIMESTAMPNS , 1 )
704+ self .socket .setsockopt (socket .SOL_SOCKET , constants . SO_TIMESTAMPNS , 1 )
701705
702706 bind_socket (self .socket , channel )
703707 kwargs .update (
@@ -830,7 +834,9 @@ def _send_periodic_internal(
830834 general the message will be sent at the given rate until at
831835 least *duration* seconds.
832836 """
833- msgs = LimitedDurationCyclicSendTaskABC ._check_and_convert_messages (msgs )
837+ msgs = LimitedDurationCyclicSendTaskABC ._check_and_convert_messages ( # pylint: disable=protected-access
838+ msgs
839+ )
834840
835841 msgs_channel = str (msgs [0 ].channel ) if msgs [0 ].channel else None
836842 bcm_socket = self ._get_bcm_socket (msgs_channel or self .channel )
@@ -850,7 +856,9 @@ def _get_bcm_socket(self, channel: str) -> socket.socket:
850856
851857 def _apply_filters (self , filters : Optional [can .typechecking .CanFilters ]) -> None :
852858 try :
853- self .socket .setsockopt (SOL_CAN_RAW , CAN_RAW_FILTER , pack_filters (filters ))
859+ self .socket .setsockopt (
860+ constants .SOL_CAN_RAW , constants .CAN_RAW_FILTER , pack_filters (filters )
861+ )
854862 except OSError as error :
855863 # fall back to "software filtering" (= not in kernel)
856864 self ._is_filtered = False
@@ -899,8 +907,6 @@ def sender(event: threading.Event) -> None:
899907 sender_socket .send (build_can_frame (msg ))
900908 print ("Sender sent a message." )
901909
902- import threading
903-
904910 e = threading .Event ()
905911 threading .Thread (target = receiver , args = (e ,)).start ()
906912 threading .Thread (target = sender , args = (e ,)).start ()
0 commit comments