CanFD 2.0.0__tar.gz → 2.0.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: canfd
3
- Version: 2.0.0
3
+ Version: 2.0.3
4
4
  Summary: USB-CANFD adapter library
5
5
  Author-email: codenocold <codenocold@gmail.com>
6
6
  Project-URL: Homepage, https://item.taobao.com/item.htm?id=610739408298&pisk=gk1ibhvShOJs2NZpp6O_UqNW8L2L1COXmihvDIK4LH-I6id9MB7ePElZgAJqL9b5mhUbCCBHmMSHbibb5E-V0ixABJFR5NOXguK0w7Q_KdFldGcwbBz2PEkaJd8WeRtwguE8wv3eCldVDhKkTWkePH8wuh84-p86zI8wQFzHYEYS3cSV0yxe5U8q3jJZYv8XYx8wgf-UTUTq0EkZgybeAER20iJa-wlW80K5Q1CUvc3ZsyTX16YMI373FjlcPbpw4sKEgu5HSQtP7Hcqg3xvIkQhWlc5JC1lqUITTfjlP6sH8gP0xIsC3i8cY7iv1TI1NpbQUX7BsH9P3p4a_wAMjLYpKqM9stS1id6ilz_e_M6WVdyQAefOwKxWKDrNJwxwEtjTAj-OEwSHe6nKwIsC3i8cYcjPQvkySdlX8rCEhx9wRexJG15mT3zKtXa3-Y3DQeTyJy4nh9vwReGT-yD5Md8B5-C..&spm=a21xtw.29178619.0.0
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "canfd"
7
- version = "2.0.0"
7
+ version = "2.0.3"
8
8
  authors = [
9
9
  { name="codenocold", email="codenocold@gmail.com" },
10
10
  ]
@@ -1,7 +1,9 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import queue
4
+ import struct
4
5
  import threading
6
+ import time
5
7
  from dataclasses import dataclass
6
8
  from enum import IntEnum
7
9
 
@@ -45,6 +47,10 @@ dlc_to_len_map = {
45
47
  15: 64,
46
48
  }
47
49
 
50
+ _CANFD_VALID_LENGTHS = (0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 20, 24, 32, 48, 64)
51
+ _FRAME_HEADER_STRUCT = struct.Struct("<BBHI")
52
+ _ENABLE_CMD_STRUCT = struct.Struct("<BBHBBBHBBB")
53
+
48
54
 
49
55
  class WorkMode(IntEnum):
50
56
  NORMAL = 0
@@ -80,7 +86,25 @@ class CanFrame:
80
86
  data: bytes = b""
81
87
 
82
88
  def __post_init__(self) -> None:
83
- pass
89
+ if (
90
+ not isinstance(self.len, int)
91
+ or not isinstance(self.data, bytes)
92
+ or self.len in _CANFD_VALID_LENGTHS
93
+ or self.len < 0
94
+ ):
95
+ return
96
+ max_len = 64 if self.fd else 8
97
+ if self.len > max_len:
98
+ padded_data = self.data[:max_len]
99
+ object.__setattr__(self, "len", max_len)
100
+ object.__setattr__(self, "data", padded_data)
101
+ return
102
+ padded_len = next(
103
+ length for length in _CANFD_VALID_LENGTHS if length > self.len
104
+ )
105
+ padded_data = self.data + b"\x00" * (padded_len - self.len)
106
+ object.__setattr__(self, "len", padded_len)
107
+ object.__setattr__(self, "data", padded_data)
84
108
 
85
109
 
86
110
  @dataclass(frozen=True, slots=True)
@@ -150,21 +174,16 @@ def _valid_frame(frame: CanFrame) -> bool:
150
174
  def cobs_encode(data: bytes) -> tuple[bool, bytes | None]:
151
175
  if not isinstance(data, bytes):
152
176
  return False, None
153
- out = bytearray([0])
154
- code_index, code = 0, 1
155
- for byte in data:
156
- if byte == 0:
157
- out[code_index] = code
158
- code_index, code = len(out), 1
159
- out.append(0)
160
- else:
161
- out.append(byte)
162
- code += 1
163
- if code == 0xFF:
164
- out[code_index] = code
165
- code_index, code = len(out), 1
166
- out.append(0)
167
- out[code_index] = code
177
+ if not data:
178
+ return True, b"\x01"
179
+ out = bytearray()
180
+ for chunk in data.split(b"\x00"):
181
+ while len(chunk) >= 254:
182
+ out.append(0xFF)
183
+ out.extend(chunk[:254])
184
+ chunk = chunk[254:]
185
+ out.append(len(chunk) + 1)
186
+ out.extend(chunk)
168
187
  return True, bytes(out)
169
188
 
170
189
 
@@ -195,25 +214,20 @@ def pack_frame(frame: CanFrame) -> tuple[bool, bytes | None]:
195
214
  | (0x20 if frame.ext else 0)
196
215
  | (0x10 if frame.rtr else 0)
197
216
  )
198
- return True, (
199
- bytes((3, flags))
200
- + frame.ts.to_bytes(2, "little")
201
- + frame.id.to_bytes(4, "little")
202
- + frame.data
203
- )
217
+ return True, _FRAME_HEADER_STRUCT.pack(3, flags, frame.ts, frame.id) + frame.data
204
218
 
205
219
 
206
220
  def unpack_frame(payload: bytes) -> tuple[bool, CanFrame | None]:
207
221
  if not isinstance(payload, bytes) or len(payload) < 8 or payload[0] != 3:
208
222
  return False, None
209
- flags = payload[1]
223
+ _, flags, ts, can_id = _FRAME_HEADER_STRUCT.unpack_from(payload, 0)
210
224
  frame = CanFrame(
211
- int.from_bytes(payload[2:4], "little"),
225
+ ts,
212
226
  bool(flags & 0x20),
213
227
  bool(flags & 0x10),
214
228
  bool(flags & 0x80),
215
229
  bool(flags & 0x40),
216
- int.from_bytes(payload[4:8], "little"),
230
+ can_id,
217
231
  dlc_to_len_map[flags & 0x0F],
218
232
  payload[8:],
219
233
  )
@@ -238,9 +252,11 @@ class CanFD:
238
252
  RSP_STATE_ERROR = 0xEE
239
253
 
240
254
  def __init__(self) -> None:
241
- self._ser = None
255
+ self._ser: serial.Serial | None = None
242
256
  self._running = False
243
- self._thread: threading.Thread | None = None
257
+ self._tx_thread: threading.Thread | None = None
258
+ self._rx_thread: threading.Thread | None = None
259
+ self._cmd_lock = threading.Lock()
244
260
  self._tx_queue: queue.Queue[bytes] = queue.Queue()
245
261
  self._frames: queue.Queue[CanFrame] = queue.Queue()
246
262
  self._statuses: queue.Queue[BusStatus] = queue.Queue()
@@ -258,6 +274,14 @@ class CanFD:
258
274
  )
259
275
  }
260
276
 
277
+ def __enter__(self) -> CanFD:
278
+ return self
279
+
280
+ def __exit__(self, exc_type: object, exc_val: object, exc_tb: object) -> None:
281
+ if self._running:
282
+ self.disable()
283
+ self.close()
284
+
261
285
  def scan(self) -> list[str]:
262
286
  ports = []
263
287
  for port in serial.tools.list_ports.comports():
@@ -266,37 +290,45 @@ class CanFD:
266
290
  return ports
267
291
 
268
292
  def open(self, serial_number: str) -> bool:
269
- if self._running:
293
+ if self._running or not isinstance(serial_number, str) or not serial_number:
270
294
  return False
271
295
 
272
296
  # scan port
273
297
  ports = []
274
298
  for port in serial.tools.list_ports.comports():
275
299
  if port.serial_number and serial_number in port.serial_number:
276
- ports.append(port.name)
300
+ ports.append(getattr(port, "device", None) or port.name)
277
301
  if len(ports) == 0:
278
302
  return False
279
303
 
280
- # open serial port
304
+ # open serial port with blocking timeout for event-driven wakeup
281
305
  try:
282
- self._ser = serial.Serial(ports[0], 115200, timeout=0, write_timeout=0)
306
+ self._ser = serial.Serial(ports[0], 115200, timeout=0.05, write_timeout=0.2)
283
307
  except Exception: # noqa: BLE001
284
308
  return False
285
309
 
286
310
  # wait a short moment to ensure the serial port is ready
287
311
  time.sleep(0.1)
288
312
 
289
- # clear TX queue and reset serial buffers
313
+ # clear all queues and reset serial buffers
290
314
  self._tx_queue.queue.clear()
315
+ self._frames.queue.clear()
316
+ self._statuses.queue.clear()
317
+ for resp_queue in self._responses.values():
318
+ resp_queue.queue.clear()
291
319
  self._ser.reset_input_buffer()
292
320
  self._ser.reset_output_buffer()
293
321
 
294
- # start the communication thread
322
+ # start the TX and RX communication threads
295
323
  self._running = True
296
- self._thread = threading.Thread(
297
- target=self._run, name="canfd-thread", daemon=True
324
+ self._tx_thread = threading.Thread(
325
+ target=self._tx_run, name="canfd-tx-thread", daemon=True
326
+ )
327
+ self._rx_thread = threading.Thread(
328
+ target=self._rx_run, name="canfd-rx-thread", daemon=True
298
329
  )
299
- self._thread.start()
330
+ self._tx_thread.start()
331
+ self._rx_thread.start()
300
332
  return True
301
333
 
302
334
  def is_open(self) -> bool:
@@ -304,10 +336,25 @@ class CanFD:
304
336
 
305
337
  def close(self) -> bool:
306
338
  self._running = False
307
- thread = self._thread
308
- if thread and thread is not threading.current_thread():
309
- thread.join(timeout=1.0)
310
- return thread is None or not thread.is_alive()
339
+
340
+ tx_thread = self._tx_thread
341
+ if tx_thread and tx_thread.is_alive():
342
+ # 放入空字节信号,微秒级立即唤醒阻塞在 get() 上的发送线程
343
+ self._tx_queue.put(b"")
344
+ if tx_thread and tx_thread is not threading.current_thread():
345
+ tx_thread.join(timeout=1.0)
346
+
347
+ rx_thread = self._rx_thread
348
+ if rx_thread and rx_thread is not threading.current_thread():
349
+ rx_thread.join(timeout=1.0)
350
+
351
+ tx_stopped = tx_thread is None or not tx_thread.is_alive()
352
+ rx_stopped = rx_thread is None or not rx_thread.is_alive()
353
+ if tx_stopped:
354
+ self._tx_thread = None
355
+ if rx_stopped:
356
+ self._rx_thread = None
357
+ return tx_stopped and rx_stopped
311
358
 
312
359
  def enable(
313
360
  self,
@@ -327,12 +374,17 @@ class CanFD:
327
374
  | (0x40 if termination else 0)
328
375
  | (0x80 if fd_bosch else 0)
329
376
  )
330
- payload = (
331
- bytes((self.CMD_ENABLE, flags))
332
- + timing.can_prescaler.to_bytes(2, "little")
333
- + bytes((timing.can_seg1, timing.can_seg2, timing.can_sjw))
334
- + timing.data_prescaler.to_bytes(2, "little")
335
- + bytes((timing.data_seg1, timing.data_seg2, timing.data_sjw))
377
+ payload = _ENABLE_CMD_STRUCT.pack(
378
+ self.CMD_ENABLE,
379
+ flags,
380
+ timing.can_prescaler,
381
+ timing.can_seg1,
382
+ timing.can_seg2,
383
+ timing.can_sjw,
384
+ timing.data_prescaler,
385
+ timing.data_seg1,
386
+ timing.data_seg2,
387
+ timing.data_sjw,
336
388
  )
337
389
  return self._command(payload)[0]
338
390
 
@@ -407,43 +459,78 @@ class CanFD:
407
459
  def dfu_end(self) -> bool:
408
460
  return self._command(bytes((self.CMD_DFU_END,)))[0]
409
461
 
410
- def _run(self) -> None:
411
- pack_buffer = bytearray()
462
+ def _tx_run(self) -> None:
463
+ tx_buffer = bytearray()
412
464
  while self._running:
413
- # 发送队列中的数据
414
465
  try:
415
- while not self._tx_queue.empty():
416
- data = self._tx_queue.get_nowait()
417
- if self._ser and self._ser.is_open:
418
- self._ser.write(data)
466
+ # 阻塞等待第一包数据:无数据时释放 GIL (0 CPU),入队瞬间立即唤醒
467
+ first_pkg = self._tx_queue.get(timeout=0.05)
468
+ except queue.Empty:
469
+ continue
470
+
471
+ if not self._running or not first_pkg:
472
+ break
473
+
474
+ tx_buffer.clear()
475
+ tx_buffer.extend(first_pkg)
476
+ # 顺便把队列里同一时刻积压的其他包合并发送,减少系统调用
477
+ while not self._tx_queue.empty():
478
+ try:
479
+ tx_buffer.extend(self._tx_queue.get_nowait())
480
+ except queue.Empty:
481
+ break
482
+
483
+ try:
484
+ if self._ser and self._ser.is_open:
485
+ self._ser.write(tx_buffer)
419
486
  except serial.SerialException:
487
+ self._running = False
420
488
  break
421
489
 
422
- # 读取底层接收缓冲区
490
+ def _rx_run(self) -> None:
491
+ pack_buffer = bytearray()
492
+ while self._running:
423
493
  try:
424
- if self._ser and self._ser.is_open and self._ser.in_waiting > 0:
425
- chunk = self._ser.read(self._ser.in_waiting)
426
- # 将读取到的串口数据追加到包缓冲区
494
+ if self._ser and self._ser.is_open:
495
+ # 1. 阻塞等待首字节:无数据时释放 GIL,数据到达瞬间微秒级唤醒
496
+ chunk = self._ser.read(1)
497
+ if not chunk:
498
+ continue
499
+
500
+ # 2. 首字节到达后,立即把缓冲区里剩余的字节一次性读空
501
+ n = self._ser.in_waiting
502
+ if n > 0:
503
+ chunk += self._ser.read(n)
504
+
505
+ # 3. 批量切分并完成 COBS 解包与分发
427
506
  pack_buffer.extend(chunk)
428
- while b"\0" in pack_buffer:
429
- idx = pack_buffer.find(b"\0")
430
- raw = bytes(pack_buffer[:idx])
431
- del pack_buffer[: idx + 1]
432
- if not raw:
433
- continue
434
- ret, pack = cobs_decode(raw)
435
- if ret:
436
- self._dispatch(pack)
507
+ if b"\0" in chunk:
508
+ parts = pack_buffer.split(b"\0")
509
+ pack_buffer = parts.pop()
510
+ for raw in parts:
511
+ if raw:
512
+ ret, pack = cobs_decode(raw)
513
+ if ret:
514
+ self._dispatch(pack)
437
515
  except serial.SerialException:
516
+ self._running = False
438
517
  break
439
518
 
440
- # safe cleanup before thread exits
519
+ # 退出清理:先唤醒并等待发送线程安全退出,再关闭串口
520
+ self._running = False
521
+ tx_thread = self._tx_thread
522
+ if tx_thread and tx_thread.is_alive():
523
+ self._tx_queue.put(b"")
524
+ if tx_thread and tx_thread is not threading.current_thread():
525
+ tx_thread.join(timeout=0.5)
441
526
  if self._ser and self._ser.is_open:
442
- self._ser.close()
527
+ try:
528
+ self._ser.close()
529
+ except Exception: # noqa: BLE001
530
+ pass
443
531
  self._ser = None
444
- self._running = False
445
532
 
446
- def _dispatch(self, payload: bytes | None):
533
+ def _dispatch(self, payload: bytes | None) -> None:
447
534
  if not payload:
448
535
  return
449
536
  command = payload[0]
@@ -458,34 +545,48 @@ class CanFD:
458
545
  if not ret:
459
546
  return
460
547
  self._statuses.put(status)
461
- self._responses[command].put(payload)
548
+ resp_queue = self._responses[command]
549
+ while not resp_queue.empty():
550
+ try:
551
+ resp_queue.get_nowait()
552
+ except queue.Empty:
553
+ break
554
+ resp_queue.put(payload)
462
555
 
463
556
  elif command in self._responses:
464
- self._responses[command].put(payload)
557
+ resp_queue = self._responses[command]
558
+ while not resp_queue.empty():
559
+ try:
560
+ resp_queue.get_nowait()
561
+ except queue.Empty:
562
+ break
563
+ resp_queue.put(payload)
465
564
 
466
565
  def _command(
467
566
  self, payload: bytes, timeout: float = 0.2
468
567
  ) -> tuple[bool, bytes | None]:
469
568
  command = payload[0]
470
-
471
- # Clear any existing responses for this command
472
569
  responses = self._responses[command]
473
- while not responses.empty():
474
- try:
475
- responses.get_nowait()
476
- except queue.Empty:
477
- break
478
570
 
479
- # transmit the command using COBS encoding
480
571
  ret, encoded = cobs_encode(payload)
481
572
  if not ret:
482
573
  return False, None
483
- self._tx_queue.put(encoded + b"\0")
484
574
 
485
- try:
486
- response = responses.get(timeout=timeout)
487
- except queue.Empty:
488
- return False, None
575
+ with self._cmd_lock:
576
+ # Clear any existing responses for this command
577
+ while not responses.empty():
578
+ try:
579
+ responses.get_nowait()
580
+ except queue.Empty:
581
+ break
582
+
583
+ # transmit the command using COBS encoding
584
+ self._tx_queue.put(encoded + b"\0")
585
+
586
+ try:
587
+ response = responses.get(timeout=timeout)
588
+ except queue.Empty:
589
+ return False, None
489
590
 
490
591
  if command in (
491
592
  self.CMD_ENABLE,
@@ -494,7 +595,7 @@ class CanFD:
494
595
  self.CMD_DFU_START,
495
596
  self.CMD_DFU_DATA,
496
597
  self.CMD_DFU_END,
497
- ) and (len(response) != 2 or response[1] != 0xAA):
598
+ ) and (len(response) != 2 or response[1] != self.RSP_STATE_OK):
498
599
  return False, None
499
600
  if not response or response[0] != command:
500
601
  return False, None
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: canfd
3
- Version: 2.0.0
3
+ Version: 2.0.3
4
4
  Summary: USB-CANFD adapter library
5
5
  Author-email: codenocold <codenocold@gmail.com>
6
6
  Project-URL: Homepage, https://item.taobao.com/item.htm?id=610739408298&pisk=gk1ibhvShOJs2NZpp6O_UqNW8L2L1COXmihvDIK4LH-I6id9MB7ePElZgAJqL9b5mhUbCCBHmMSHbibb5E-V0ixABJFR5NOXguK0w7Q_KdFldGcwbBz2PEkaJd8WeRtwguE8wv3eCldVDhKkTWkePH8wuh84-p86zI8wQFzHYEYS3cSV0yxe5U8q3jJZYv8XYx8wgf-UTUTq0EkZgybeAER20iJa-wlW80K5Q1CUvc3ZsyTX16YMI373FjlcPbpw4sKEgu5HSQtP7Hcqg3xvIkQhWlc5JC1lqUITTfjlP6sH8gP0xIsC3i8cY7iv1TI1NpbQUX7BsH9P3p4a_wAMjLYpKqM9stS1id6ilz_e_M6WVdyQAefOwKxWKDrNJwxwEtjTAj-OEwSHe6nKwIsC3i8cYcjPQvkySdlX8rCEhx9wRexJG15mT3zKtXa3-Y3DQeTyJy4nh9vwReGT-yD5Md8B5-C..&spm=a21xtw.29178619.0.0
File without changes
File without changes
File without changes
File without changes