Skip to content

Commit 7a8e3b1

Browse files
felixdivomergify-bot
authored and
mergify-bot
committed
Specific Exceptions: Adapting pcan interface
Part of #1046. Also partly cleans up the docstrings in `basic.py` and uses some subtests in `test_pcan.py` (the parameter `name` was else unused in most parameterized tests).
1 parent 9080c47 commit 7a8e3b1

File tree

3 files changed

+130
-133
lines changed

3 files changed

+130
-133
lines changed

can/interfaces/pcan/basic.py

Lines changed: 20 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,12 @@
88
#
99
# ------------------------------------------------------------------
1010
# Author : Keneth Wagner
11-
# Last change: 14.01.2021 Wagner
12-
#
13-
# Language: Python 2.7, 3.7
1411
# ------------------------------------------------------------------
1512
#
1613
# Copyright (C) 1999-2021 PEAK-System Technik GmbH, Darmstadt
1714
# more Info at http://www.peak-system.com
18-
#
1915

2016
# Module Imports
21-
#
2217
from ctypes import *
2318
from ctypes.util import find_library
2419
from string import *
@@ -601,8 +596,7 @@ def Initialize(
601596
Interrupt=c_ushort(0),
602597
):
603598

604-
"""
605-
Initializes a PCAN Channel
599+
"""Initializes a PCAN Channel
606600
607601
Parameters:
608602
Channel : A TPCANHandle representing a PCAN Channel
@@ -627,8 +621,7 @@ def Initialize(
627621
#
628622
def InitializeFD(self, Channel, BitrateFD):
629623

630-
"""
631-
Initializes a FD capable PCAN Channel
624+
"""Initializes a FD capable PCAN Channel
632625
633626
Parameters:
634627
Channel : The handle of a FD capable PCAN Channel
@@ -659,8 +652,7 @@ def InitializeFD(self, Channel, BitrateFD):
659652
#
660653
def Uninitialize(self, Channel):
661654

662-
"""
663-
Uninitializes one or all PCAN Channels initialized by CAN_Initialize
655+
"""Uninitializes one or all PCAN Channels initialized by CAN_Initialize
664656
665657
Remarks:
666658
Giving the TPCANHandle value "PCAN_NONEBUS", uninitialize all initialized channels
@@ -682,8 +674,7 @@ def Uninitialize(self, Channel):
682674
#
683675
def Reset(self, Channel):
684676

685-
"""
686-
Resets the receive and transmit queues of the PCAN Channel
677+
"""Resets the receive and transmit queues of the PCAN Channel
687678
688679
Remarks:
689680
A reset of the CAN controller is not performed
@@ -705,8 +696,7 @@ def Reset(self, Channel):
705696
#
706697
def GetStatus(self, Channel):
707698

708-
"""
709-
Gets the current status of a PCAN Channel
699+
"""Gets the current status of a PCAN Channel
710700
711701
Parameters:
712702
Channel : A TPCANHandle representing a PCAN Channel
@@ -725,8 +715,7 @@ def GetStatus(self, Channel):
725715
#
726716
def Read(self, Channel):
727717

728-
"""
729-
Reads a CAN message from the receive queue of a PCAN Channel
718+
"""Reads a CAN message from the receive queue of a PCAN Channel
730719
731720
Remarks:
732721
The return value of this method is a 3-touple, where
@@ -740,7 +729,7 @@ def Read(self, Channel):
740729
Channel : A TPCANHandle representing a PCAN Channel
741730
742731
Returns:
743-
A touple with three values
732+
A tuple with three values
744733
"""
745734
try:
746735
msg = TPCANMsg()
@@ -755,8 +744,7 @@ def Read(self, Channel):
755744
#
756745
def ReadFD(self, Channel):
757746

758-
"""
759-
Reads a CAN message from the receive queue of a FD capable PCAN Channel
747+
"""Reads a CAN message from the receive queue of a FD capable PCAN Channel
760748
761749
Remarks:
762750
The return value of this method is a 3-touple, where
@@ -770,7 +758,7 @@ def ReadFD(self, Channel):
770758
Channel : The handle of a FD capable PCAN Channel
771759
772760
Returns:
773-
A touple with three values
761+
A tuple with three values
774762
"""
775763
try:
776764
msg = TPCANMsgFD()
@@ -785,8 +773,7 @@ def ReadFD(self, Channel):
785773
#
786774
def Write(self, Channel, MessageBuffer):
787775

788-
"""
789-
Transmits a CAN message
776+
"""Transmits a CAN message
790777
791778
Parameters:
792779
Channel : A TPCANHandle representing a PCAN Channel
@@ -806,8 +793,7 @@ def Write(self, Channel, MessageBuffer):
806793
#
807794
def WriteFD(self, Channel, MessageBuffer):
808795

809-
"""
810-
Transmits a CAN message over a FD capable PCAN Channel
796+
"""Transmits a CAN message over a FD capable PCAN Channel
811797
812798
Parameters:
813799
Channel : The handle of a FD capable PCAN Channel
@@ -827,8 +813,7 @@ def WriteFD(self, Channel, MessageBuffer):
827813
#
828814
def FilterMessages(self, Channel, FromID, ToID, Mode):
829815

830-
"""
831-
Configures the reception filter
816+
"""Configures the reception filter
832817
833818
Remarks:
834819
The message filter will be expanded with every call to this function.
@@ -855,8 +840,7 @@ def FilterMessages(self, Channel, FromID, ToID, Mode):
855840
#
856841
def GetValue(self, Channel, Parameter):
857842

858-
"""
859-
Retrieves a PCAN Channel value
843+
"""Retrieves a PCAN Channel value
860844
861845
Remarks:
862846
Parameters can be present or not according with the kind
@@ -872,7 +856,7 @@ def GetValue(self, Channel, Parameter):
872856
Parameter : The TPCANParameter parameter to get
873857
874858
Returns:
875-
A touple with 2 values
859+
A tuple with 2 values
876860
"""
877861
try:
878862
if (
@@ -912,9 +896,8 @@ def GetValue(self, Channel, Parameter):
912896
#
913897
def SetValue(self, Channel, Parameter, Buffer):
914898

915-
"""
916-
Returns a descriptive text of a given TPCANStatus error
917-
code, in any desired language
899+
"""Returns a descriptive text of a given TPCANStatus error
900+
code, in any desired language
918901
919902
Remarks:
920903
Parameters can be present or not according with the kind
@@ -951,8 +934,7 @@ def SetValue(self, Channel, Parameter, Buffer):
951934

952935
def GetErrorText(self, Error, Language=0):
953936

954-
"""
955-
Configures or sets a PCAN Channel value
937+
"""Configures or sets a PCAN Channel value
956938
957939
Remarks:
958940
@@ -969,7 +951,7 @@ def GetErrorText(self, Error, Language=0):
969951
Language : Indicates a 'Primary language ID' (Default is Neutral(0))
970952
971953
Returns:
972-
A touple with 2 values
954+
A tuple with 2 values
973955
"""
974956
try:
975957
mybuffer = create_string_buffer(256)
@@ -981,8 +963,7 @@ def GetErrorText(self, Error, Language=0):
981963

982964
def LookUpChannel(self, Parameters):
983965

984-
"""
985-
Finds a PCAN-Basic channel that matches with the given parameters
966+
"""Finds a PCAN-Basic channel that matches with the given parameters
986967
987968
Remarks:
988969
@@ -995,7 +976,7 @@ def LookUpChannel(self, Parameters):
995976
to be matched within a PCAN-Basic channel
996977
997978
Returns:
998-
A touple with 2 values
979+
A tuple with 2 values
999980
"""
1000981
try:
1001982
mybuffer = TPCANHandle(0)

can/interfaces/pcan/pcan.py

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,18 @@
22
Enable basic CAN over a PCAN USB device.
33
"""
44

5+
from .basic import * # Do this first since the wildcard imports a lot
6+
57
import logging
68
import time
79
from datetime import datetime
810

911
from typing import Optional
10-
from can import CanError, Message, BusABC
11-
from can.bus import BusState
12-
from can.util import len2dlc, dlc2len
13-
from .basic import *
12+
13+
from ...message import Message
14+
from ...bus import BusABC, BusState
15+
from ...util import len2dlc, dlc2len
16+
from ...exceptions import CanError, CanOperationError, CanInitializationError
1417

1518

1619
# Set up logging
@@ -251,7 +254,7 @@ def __init__(
251254
ioport = 0x02A0
252255
interrupt = 11
253256

254-
if type(channel) != int:
257+
if not isinstance(channel, int):
255258
channel = pcan_channel_names[channel]
256259

257260
self.m_objPCANBasic = PCANBasic()
@@ -260,7 +263,7 @@ def __init__(
260263
if state is BusState.ACTIVE or state is BusState.PASSIVE:
261264
self.state = state
262265
else:
263-
raise ArgumentError("BusState must be Active or Passive")
266+
raise ValueError("BusState must be Active or Passive")
264267

265268
if self.fd:
266269
f_clock_val = kwargs.get("f_clock", None)
@@ -286,15 +289,15 @@ def __init__(
286289
)
287290

288291
if result != PCAN_ERROR_OK:
289-
raise PcanError(self._get_formatted_error(result))
292+
raise PcanCanInitializationError(self._get_formatted_error(result))
290293

291294
result = self.m_objPCANBasic.SetValue(
292295
self.m_PcanHandle, PCAN_ALLOW_ERROR_FRAMES, PCAN_PARAMETER_ON
293296
)
294297

295298
if result != PCAN_ERROR_OK:
296299
if platform.system() != "Darwin":
297-
raise PcanError(self._get_formatted_error(result))
300+
raise PcanCanInitializationError(self._get_formatted_error(result))
298301
else:
299302
# TODO Remove Filter when MACCan actually supports it:
300303
# https://github.com/mac-can/PCBUSB-Library/
@@ -308,7 +311,7 @@ def __init__(
308311
self.m_PcanHandle, PCAN_RECEIVE_EVENT, self._recv_event
309312
)
310313
if result != PCAN_ERROR_OK:
311-
raise PcanError(self._get_formatted_error(result))
314+
raise PcanCanInitializationError(self._get_formatted_error(result))
312315

313316
super().__init__(channel=channel, state=state, bitrate=bitrate, *args, **kwargs)
314317

@@ -407,7 +410,7 @@ def set_device_number(self, device_number):
407410
)
408411
!= PCAN_ERROR_OK
409412
):
410-
raise ValueError
413+
raise ValueError()
411414
except ValueError:
412415
log.error("Invalid value '%s' for device number.", device_number)
413416
return False
@@ -445,7 +448,7 @@ def _recv_internal(self, timeout):
445448
log.warning(self._get_formatted_error(result[0]))
446449
return None, False
447450
elif result[0] != PCAN_ERROR_OK:
448-
raise PcanError(self._get_formatted_error(result[0]))
451+
raise PcanCanOperationError(self._get_formatted_error(result[0]))
449452

450453
theMsg = result[1]
451454
itsTimeStamp = result[2]
@@ -554,7 +557,7 @@ def send(self, msg, timeout=None):
554557
result = self.m_objPCANBasic.Write(self.m_PcanHandle, CANMsg)
555558

556559
if result != PCAN_ERROR_OK:
557-
raise PcanError("Failed to send: " + self._get_formatted_error(result))
560+
raise PcanCanOperationError("Failed to send: " + self._get_formatted_error(result))
558561

559562
def flash(self, flash):
560563
"""
@@ -655,6 +658,12 @@ def status_string(self) -> Optional[str]:
655658

656659

657660
class PcanError(CanError):
658-
"""
659-
A generic error on a PCAN bus.
660-
"""
661+
"""A generic error on a PCAN bus."""
662+
663+
664+
class PcanCanOperationError(CanOperationError, PcanError):
665+
"""Like :class:`can.exceptions.CanOperationError`, but specific to Pcan."""
666+
667+
668+
class PcanCanInitializationError(CanInitializationError, PcanError):
669+
"""Like :class:`can.exceptions.CanInitializationError`, but specific to Pcan."""

0 commit comments

Comments
 (0)