Skip to content

Commit 10312b8

Browse files
lumagizariiii9003
authored andcommitted
Fix decoding error in Kvaser constructor for non-ASCII product name (#1613)
* Implement test to trigger ASCII decoding error in Kvaser bus constructor * Change handling of invalid chars in Kvaser device name Previously, illegal characters triggered an exception. With the new behavior, illegal characters will be replaced with a placeholder value. * Rename variables in test
1 parent 008ae61 commit 10312b8

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

can/interfaces/kvaser/canlib.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -722,7 +722,8 @@ def get_channel_info(channel):
722722
ctypes.sizeof(number),
723723
)
724724

725-
return f"{name.value.decode('ascii')}, S/N {serial.value} (#{number.value + 1})"
725+
name_decoded = name.value.decode("ascii", errors="replace")
726+
return f"{name_decoded}, S/N {serial.value} (#{number.value + 1})"
726727

727728

728729
init_kvaser_library()

test/test_kvaser.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"""
44
"""
55

6+
import ctypes
67
import time
78
import unittest
89
from unittest.mock import Mock
@@ -48,6 +49,26 @@ def test_bus_creation(self):
4849
self.assertTrue(canlib.canOpenChannel.called)
4950
self.assertTrue(canlib.canBusOn.called)
5051

52+
def test_bus_creation_illegal_channel_name(self):
53+
# Test if the bus constructor is able to deal with non-ASCII characters
54+
def canGetChannelDataMock(
55+
channel: ctypes.c_int,
56+
param: ctypes.c_int,
57+
buf: ctypes.c_void_p,
58+
bufsize: ctypes.c_size_t,
59+
):
60+
if param == constants.canCHANNELDATA_DEVDESCR_ASCII:
61+
buf_char_ptr = ctypes.cast(buf, ctypes.POINTER(ctypes.c_char))
62+
for i, char in enumerate(b"hello\x7a\xcb"):
63+
buf_char_ptr[i] = char
64+
65+
canlib.canGetChannelData = canGetChannelDataMock
66+
bus = can.Bus(channel=0, interface="kvaser")
67+
68+
self.assertTrue(bus.channel_info.startswith("hello"))
69+
70+
bus.shutdown()
71+
5172
def test_bus_shutdown(self):
5273
self.bus.shutdown()
5374
self.assertTrue(canlib.canBusOff.called)

0 commit comments

Comments
 (0)