Skip to content

Commit dd0312d

Browse files
Replace to_byte operations with pack and unpack for Python 2.x
1 parent 1e3fb04 commit dd0312d

2 files changed

Lines changed: 17 additions & 9 deletions

File tree

can/interfaces/serial/serial_can.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
"""
99

1010
import logging
11+
import struct
1112

1213
logger = logging.getLogger('can.serial')
1314

@@ -77,9 +78,16 @@ def send(self, msg, timeout=None):
7778
"""
7879
if isinstance(msg.timestamp, float):
7980
msg.timestamp = int(msg.timestamp)
80-
timestamp = msg.timestamp.to_bytes(4, byteorder='little')
81-
a_id = msg.arbitration_id.to_bytes(4, byteorder='little')
82-
dlc = msg.dlc.to_bytes(1, byteorder='little')
81+
try:
82+
timestamp = struct.pack('<I', msg.timestamp)
83+
except Exception:
84+
raise ValueError('Timestamp is out of range')
85+
try:
86+
a_id = struct.pack('<I', msg.arbitration_id)
87+
except Exception:
88+
raise ValueError('Arbitration Id is out of range')
89+
# dlc = msg.dlc.to_bytes(1, byteorder='little')
90+
dlc = struct.pack('<B', msg.dlc)
8391
byte_msg = bytes([0xAA]) + timestamp + dlc + a_id + msg.data + \
8492
bytes([0xBB])
8593
self.ser.write(byte_msg)
@@ -110,11 +118,11 @@ def recv(self, timeout=None):
110118

111119
if len(rx_byte) and ord(rx_byte) == 0xAA:
112120
s = bytearray(self.ser.read(4))
113-
timestamp = int.from_bytes(s, byteorder='little', signed=False)
121+
timestamp = (struct.unpack('<I', s))[0]
114122
dlc = ord(self.ser.read())
115123

116124
s = bytearray(self.ser.read(4))
117-
arb_id = int.from_bytes(s, byteorder='little', signed=False)
125+
arb_id = (struct.unpack('<I', s))[0]
118126

119127
data = self.ser.read(dlc)
120128

test/serial_test.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -125,10 +125,10 @@ def test_rx_tx_max_timestamp(self):
125125

126126
def test_rx_tx_max_timestamp_error(self):
127127
"""
128-
Tests for an exception with an out of bound timestamp (max + 1)
128+
Tests for an exception with an out of range timestamp (max + 1)
129129
"""
130130
msg = can.Message(timestamp=0xFFFFFFFF+1)
131-
self.assertRaises(OverflowError, self.bus.send, msg)
131+
self.assertRaises(ValueError, self.bus.send, msg)
132132

133133
def test_rx_tx_min_timestamp(self):
134134
"""
@@ -141,10 +141,10 @@ def test_rx_tx_min_timestamp(self):
141141

142142
def test_rx_tx_min_timestamp_error(self):
143143
"""
144-
Tests for an exception with an out of bound timestamp (min - 1)
144+
Tests for an exception with an out of range timestamp (min - 1)
145145
"""
146146
msg = can.Message(timestamp=-1)
147-
self.assertRaises(OverflowError, self.bus.send, msg)
147+
self.assertRaises(ValueError, self.bus.send, msg)
148148

149149

150150
if __name__ == '__main__':

0 commit comments

Comments
 (0)