CanFD 2.0.2__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.2
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.2"
7
+ version = "2.0.3"
8
8
  authors = [
9
9
  { name="codenocold", email="codenocold@gmail.com" },
10
10
  ]
@@ -1,6 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import queue
4
+ import struct
4
5
  import threading
5
6
  import time
6
7
  from dataclasses import dataclass
@@ -46,6 +47,10 @@ dlc_to_len_map = {
46
47
  15: 64,
47
48
  }
48
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
+
49
54
 
50
55
  class WorkMode(IntEnum):
51
56
  NORMAL = 0
@@ -81,8 +86,12 @@ class CanFrame:
81
86
  data: bytes = b""
82
87
 
83
88
  def __post_init__(self) -> None:
84
- CANFD_VALID_LENGTHS = (0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 20, 24, 32, 48, 64)
85
- if self.len in CANFD_VALID_LENGTHS:
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
+ ):
86
95
  return
87
96
  max_len = 64 if self.fd else 8
88
97
  if self.len > max_len:
@@ -90,8 +99,10 @@ class CanFrame:
90
99
  object.__setattr__(self, "len", max_len)
91
100
  object.__setattr__(self, "data", padded_data)
92
101
  return
93
- padded_len = next(length for length in CANFD_VALID_LENGTHS if length > self.len)
94
- padded_data = self.data + bytes([0] * (padded_len - self.len))
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)
95
106
  object.__setattr__(self, "len", padded_len)
96
107
  object.__setattr__(self, "data", padded_data)
97
108
 
@@ -163,21 +174,16 @@ def _valid_frame(frame: CanFrame) -> bool:
163
174
  def cobs_encode(data: bytes) -> tuple[bool, bytes | None]:
164
175
  if not isinstance(data, bytes):
165
176
  return False, None
166
- out = bytearray([0])
167
- code_index, code = 0, 1
168
- for byte in data:
169
- if byte == 0:
170
- out[code_index] = code
171
- code_index, code = len(out), 1
172
- out.append(0)
173
- else:
174
- out.append(byte)
175
- code += 1
176
- if code == 0xFF:
177
- out[code_index] = code
178
- code_index, code = len(out), 1
179
- out.append(0)
180
- 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)
181
187
  return True, bytes(out)
182
188
 
183
189
 
@@ -208,25 +214,20 @@ def pack_frame(frame: CanFrame) -> tuple[bool, bytes | None]:
208
214
  | (0x20 if frame.ext else 0)
209
215
  | (0x10 if frame.rtr else 0)
210
216
  )
211
- return True, (
212
- bytes((3, flags))
213
- + frame.ts.to_bytes(2, "little")
214
- + frame.id.to_bytes(4, "little")
215
- + frame.data
216
- )
217
+ return True, _FRAME_HEADER_STRUCT.pack(3, flags, frame.ts, frame.id) + frame.data
217
218
 
218
219
 
219
220
  def unpack_frame(payload: bytes) -> tuple[bool, CanFrame | None]:
220
221
  if not isinstance(payload, bytes) or len(payload) < 8 or payload[0] != 3:
221
222
  return False, None
222
- flags = payload[1]
223
+ _, flags, ts, can_id = _FRAME_HEADER_STRUCT.unpack_from(payload, 0)
223
224
  frame = CanFrame(
224
- int.from_bytes(payload[2:4], "little"),
225
+ ts,
225
226
  bool(flags & 0x20),
226
227
  bool(flags & 0x10),
227
228
  bool(flags & 0x80),
228
229
  bool(flags & 0x40),
229
- int.from_bytes(payload[4:8], "little"),
230
+ can_id,
230
231
  dlc_to_len_map[flags & 0x0F],
231
232
  payload[8:],
232
233
  )
@@ -251,9 +252,11 @@ class CanFD:
251
252
  RSP_STATE_ERROR = 0xEE
252
253
 
253
254
  def __init__(self) -> None:
254
- self._ser = None
255
+ self._ser: serial.Serial | None = None
255
256
  self._running = False
256
- 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()
257
260
  self._tx_queue: queue.Queue[bytes] = queue.Queue()
258
261
  self._frames: queue.Queue[CanFrame] = queue.Queue()
259
262
  self._statuses: queue.Queue[BusStatus] = queue.Queue()
@@ -271,6 +274,14 @@ class CanFD:
271
274
  )
272
275
  }
273
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
+
274
285
  def scan(self) -> list[str]:
275
286
  ports = []
276
287
  for port in serial.tools.list_ports.comports():
@@ -279,37 +290,45 @@ class CanFD:
279
290
  return ports
280
291
 
281
292
  def open(self, serial_number: str) -> bool:
282
- if self._running:
293
+ if self._running or not isinstance(serial_number, str) or not serial_number:
283
294
  return False
284
295
 
285
296
  # scan port
286
297
  ports = []
287
298
  for port in serial.tools.list_ports.comports():
288
299
  if port.serial_number and serial_number in port.serial_number:
289
- ports.append(port.name)
300
+ ports.append(getattr(port, "device", None) or port.name)
290
301
  if len(ports) == 0:
291
302
  return False
292
303
 
293
- # open serial port
304
+ # open serial port with blocking timeout for event-driven wakeup
294
305
  try:
295
- 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)
296
307
  except Exception: # noqa: BLE001
297
308
  return False
298
309
 
299
310
  # wait a short moment to ensure the serial port is ready
300
311
  time.sleep(0.1)
301
312
 
302
- # clear TX queue and reset serial buffers
313
+ # clear all queues and reset serial buffers
303
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()
304
319
  self._ser.reset_input_buffer()
305
320
  self._ser.reset_output_buffer()
306
321
 
307
- # start the communication thread
322
+ # start the TX and RX communication threads
308
323
  self._running = True
309
- self._thread = threading.Thread(
310
- 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
311
326
  )
312
- self._thread.start()
327
+ self._rx_thread = threading.Thread(
328
+ target=self._rx_run, name="canfd-rx-thread", daemon=True
329
+ )
330
+ self._tx_thread.start()
331
+ self._rx_thread.start()
313
332
  return True
314
333
 
315
334
  def is_open(self) -> bool:
@@ -317,10 +336,25 @@ class CanFD:
317
336
 
318
337
  def close(self) -> bool:
319
338
  self._running = False
320
- thread = self._thread
321
- if thread and thread is not threading.current_thread():
322
- thread.join(timeout=1.0)
323
- 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
324
358
 
325
359
  def enable(
326
360
  self,
@@ -340,12 +374,17 @@ class CanFD:
340
374
  | (0x40 if termination else 0)
341
375
  | (0x80 if fd_bosch else 0)
342
376
  )
343
- payload = (
344
- bytes((self.CMD_ENABLE, flags))
345
- + timing.can_prescaler.to_bytes(2, "little")
346
- + bytes((timing.can_seg1, timing.can_seg2, timing.can_sjw))
347
- + timing.data_prescaler.to_bytes(2, "little")
348
- + 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,
349
388
  )
350
389
  return self._command(payload)[0]
351
390
 
@@ -420,43 +459,78 @@ class CanFD:
420
459
  def dfu_end(self) -> bool:
421
460
  return self._command(bytes((self.CMD_DFU_END,)))[0]
422
461
 
423
- def _run(self) -> None:
424
- pack_buffer = bytearray()
462
+ def _tx_run(self) -> None:
463
+ tx_buffer = bytearray()
425
464
  while self._running:
426
- # 发送队列中的数据
427
465
  try:
428
- while not self._tx_queue.empty():
429
- data = self._tx_queue.get_nowait()
430
- if self._ser and self._ser.is_open:
431
- 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)
432
486
  except serial.SerialException:
487
+ self._running = False
433
488
  break
434
489
 
435
- # 读取底层接收缓冲区
490
+ def _rx_run(self) -> None:
491
+ pack_buffer = bytearray()
492
+ while self._running:
436
493
  try:
437
- if self._ser and self._ser.is_open and self._ser.in_waiting > 0:
438
- chunk = self._ser.read(self._ser.in_waiting)
439
- # 将读取到的串口数据追加到包缓冲区
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 解包与分发
440
506
  pack_buffer.extend(chunk)
441
- while b"\0" in pack_buffer:
442
- idx = pack_buffer.find(b"\0")
443
- raw = bytes(pack_buffer[:idx])
444
- del pack_buffer[: idx + 1]
445
- if not raw:
446
- continue
447
- ret, pack = cobs_decode(raw)
448
- if ret:
449
- 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)
450
515
  except serial.SerialException:
516
+ self._running = False
451
517
  break
452
518
 
453
- # 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)
454
526
  if self._ser and self._ser.is_open:
455
- self._ser.close()
527
+ try:
528
+ self._ser.close()
529
+ except Exception: # noqa: BLE001
530
+ pass
456
531
  self._ser = None
457
- self._running = False
458
532
 
459
- def _dispatch(self, payload: bytes | None):
533
+ def _dispatch(self, payload: bytes | None) -> None:
460
534
  if not payload:
461
535
  return
462
536
  command = payload[0]
@@ -471,34 +545,48 @@ class CanFD:
471
545
  if not ret:
472
546
  return
473
547
  self._statuses.put(status)
474
- 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)
475
555
 
476
556
  elif command in self._responses:
477
- 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)
478
564
 
479
565
  def _command(
480
566
  self, payload: bytes, timeout: float = 0.2
481
567
  ) -> tuple[bool, bytes | None]:
482
568
  command = payload[0]
483
-
484
- # Clear any existing responses for this command
485
569
  responses = self._responses[command]
486
- while not responses.empty():
487
- try:
488
- responses.get_nowait()
489
- except queue.Empty:
490
- break
491
570
 
492
- # transmit the command using COBS encoding
493
571
  ret, encoded = cobs_encode(payload)
494
572
  if not ret:
495
573
  return False, None
496
- self._tx_queue.put(encoded + b"\0")
497
574
 
498
- try:
499
- response = responses.get(timeout=timeout)
500
- except queue.Empty:
501
- 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
502
590
 
503
591
  if command in (
504
592
  self.CMD_ENABLE,
@@ -507,7 +595,7 @@ class CanFD:
507
595
  self.CMD_DFU_START,
508
596
  self.CMD_DFU_DATA,
509
597
  self.CMD_DFU_END,
510
- ) and (len(response) != 2 or response[1] != 0xAA):
598
+ ) and (len(response) != 2 or response[1] != self.RSP_STATE_OK):
511
599
  return False, None
512
600
  if not response or response[0] != command:
513
601
  return False, None
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: canfd
3
- Version: 2.0.2
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