diff --git a/.gitignore b/.gitignore index e8507cc0..5472b01e 100644 --- a/.gitignore +++ b/.gitignore @@ -64,6 +64,7 @@ target/ # IDEs .vscode/ +.idea/ *.dbc diff --git a/canopen/emcy.py b/canopen/emcy.py index 1bbdeb75..b0447a40 100644 --- a/canopen/emcy.py +++ b/canopen/emcy.py @@ -1,5 +1,5 @@ -import struct import logging +import struct import threading import time from typing import Callable, List, Optional @@ -10,17 +10,61 @@ logger = logging.getLogger(__name__) +class EmcyError(Exception): + """EMCY exception.""" + + DESCRIPTIONS = [ + # Code Mask Description + (0x0000, 0xFF00, "Error Reset / No Error"), + (0x1000, 0xFF00, "Generic Error"), + (0x2000, 0xF000, "Current"), + (0x3000, 0xF000, "Voltage"), + (0x4000, 0xF000, "Temperature"), + (0x5000, 0xFF00, "Device Hardware"), + (0x6000, 0xF000, "Device Software"), + (0x7000, 0xFF00, "Additional Modules"), + (0x8000, 0xF000, "Monitoring"), + (0x9000, 0xFF00, "External Error"), + (0xF000, 0xFF00, "Additional Functions"), + (0xFF00, 0xFF00, "Device Specific") + ] + + def __init__(self, code: int, register: int, data: bytes, timestamp: float): + #: EMCY code + self.code = code + #: Error register + self.register = register + #: Vendor specific data + self.data = data + #: Timestamp of message + self.timestamp = timestamp + + def get_desc(self) -> str: + for code, mask, description in self.DESCRIPTIONS: + if self.code & mask == code: + return description + return "" + + def __str__(self): + text = f"Code 0x{self.code:04X}" + description = self.get_desc() + if description: + text = text + ", " + description + return text + + class EmcyConsumer: def __init__(self): #: Log of all received EMCYs for this node - self.log: List["EmcyError"] = [] + self.log: List[EmcyError] = [] #: Only active EMCYs. Will be cleared on Error Reset - self.active: List["EmcyError"] = [] + self.active: List[EmcyError] = [] self.callbacks = [] self.emcy_received = threading.Condition() def on_emcy(self, can_id, data, timestamp): + _ = can_id code, register, data = EMCY_STRUCT.unpack(data) entry = EmcyError(code, register, data, timestamp) @@ -36,7 +80,7 @@ def on_emcy(self, can_id, data, timestamp): for callback in self.callbacks: callback(entry) - def add_callback(self, callback: Callable[["EmcyError"], None]): + def add_callback(self, callback: Callable[[EmcyError], None]): """Get notified on EMCY messages from this node. :param callback: @@ -52,7 +96,7 @@ def reset(self): def wait( self, emcy_code: Optional[int] = None, timeout: float = 10 - ) -> "EmcyError": + ) -> Optional[EmcyError]: """Wait for a new EMCY to arrive. :param emcy_code: EMCY code to wait for @@ -92,46 +136,3 @@ def send(self, code: int, register: int = 0, data: bytes = b""): def reset(self, register: int = 0, data: bytes = b""): payload = EMCY_STRUCT.pack(0, register, data) self.network.send_message(self.cob_id, payload) - - -class EmcyError(Exception): - """EMCY exception.""" - - DESCRIPTIONS = [ - # Code Mask Description - (0x0000, 0xFF00, "Error Reset / No Error"), - (0x1000, 0xFF00, "Generic Error"), - (0x2000, 0xF000, "Current"), - (0x3000, 0xF000, "Voltage"), - (0x4000, 0xF000, "Temperature"), - (0x5000, 0xFF00, "Device Hardware"), - (0x6000, 0xF000, "Device Software"), - (0x7000, 0xFF00, "Additional Modules"), - (0x8000, 0xF000, "Monitoring"), - (0x9000, 0xFF00, "External Error"), - (0xF000, 0xFF00, "Additional Functions"), - (0xFF00, 0xFF00, "Device Specific") - ] - - def __init__(self, code: int, register: int, data: bytes, timestamp: float): - #: EMCY code - self.code = code - #: Error register - self.register = register - #: Vendor specific data - self.data = data - #: Timestamp of message - self.timestamp = timestamp - - def get_desc(self) -> str: - for code, mask, description in self.DESCRIPTIONS: - if self.code & mask == code: - return description - return "" - - def __str__(self): - text = f"Code 0x{self.code:04X}" - description = self.get_desc() - if description: - text = text + ", " + description - return text diff --git a/canopen/lss.py b/canopen/lss.py index 93b7d4ec..2009c91f 100644 --- a/canopen/lss.py +++ b/canopen/lss.py @@ -1,7 +1,7 @@ import logging -import time -import struct import queue +import struct +import time logger = logging.getLogger(__name__) @@ -104,21 +104,20 @@ def send_switch_mode_global(self, mode): """obsolete""" self.send_switch_state_global(mode) - def send_switch_state_selective(self, - vendorId, productCode, revisionNumber, serialNumber): + def send_switch_state_selective(self, vendor_id, product_code, revision_number, serial_number): """switch mode from WAITING_STATE to CONFIGURATION_STATE only if 128bits LSS address matches with the arguments. It sends 4 messages for each argument. Then wait the response from the slave. There will be no response if there is no matching slave - :param int vendorId: + :param int vendor_id: object index 0x1018 subindex 1 - :param int productCode: + :param int product_code: object index 0x1018 subindex 2 - :param int revisionNumber: + :param int revision_number: object index 0x1018 subindex 3 - :param int serialNumber: + :param int serial_number: object index 0x1018 subindex 4 :return: @@ -127,10 +126,10 @@ def send_switch_state_selective(self, :rtype: bool """ - self.__send_lss_address(CS_SWITCH_STATE_SELECTIVE_VENDOR_ID, vendorId) - self.__send_lss_address(CS_SWITCH_STATE_SELECTIVE_PRODUCT_CODE, productCode) - self.__send_lss_address(CS_SWITCH_STATE_SELECTIVE_REVISION_NUMBER, revisionNumber) - response = self.__send_lss_address(CS_SWITCH_STATE_SELECTIVE_SERIAL_NUMBER, serialNumber) + self.__send_lss_address(CS_SWITCH_STATE_SELECTIVE_VENDOR_ID, vendor_id) + self.__send_lss_address(CS_SWITCH_STATE_SELECTIVE_PRODUCT_CODE, product_code) + self.__send_lss_address(CS_SWITCH_STATE_SELECTIVE_REVISION_NUMBER, revision_number) + response = self.__send_lss_address(CS_SWITCH_STATE_SELECTIVE_SERIAL_NUMBER, serial_number) cs = struct.unpack_from(" None: else: self.subscribers[can_id].remove(callback) - def connect(self, *args, **kwargs) -> Network: + def connect(self, channel=None, interface=None, **kwargs) -> Network: """Connect to CAN bus using python-can. - Arguments are passed directly to :class:`can.BusABC`. Typically these - may include: + All arguments are passed directly to :class:`can.BusABC`. :param channel: Backend specific channel for the CAN interface. - :param str bustype: + :param interface: Name of the interface. See `python-can manual `__ for full list of supported interfaces. - :param int bitrate: - Bitrate in bit/s. + :param kwargs: + ``interface`` specific keyword arguments. For example: + bitrate: Bitrate in bit/s. :raises can.CanError: When connection fails. @@ -110,7 +111,7 @@ def connect(self, *args, **kwargs) -> Network: kwargs["bitrate"] = node.object_dictionary.bitrate break if self.bus is None: - self.bus = can.Bus(*args, **kwargs) + self.bus = can.Bus(channel=channel, interface=interface, **kwargs) logger.info("Connected to '%s'", self.bus.channel_info) self.notifier = can.Notifier(self.bus, self.listeners, 1) return self @@ -233,7 +234,7 @@ def send_periodic( """ return PeriodicMessageTask(can_id, data, period, self.bus, remote) - def notify(self, can_id: int, data: bytearray, timestamp: float) -> None: + def notify(self, can_id: int, data: bytes, timestamp: float) -> None: """Feed incoming message to this library. If a custom interface is used, this function must be called for each @@ -350,6 +351,7 @@ class MessageListener(Listener): """ def __init__(self, network: Network): + super().__init__() self.network = network def on_message_received(self, msg): @@ -359,7 +361,7 @@ def on_message_received(self, msg): try: self.network.notify(msg.arbitration_id, msg.data, msg.timestamp) except Exception as e: - # Exceptions in any callbaks should not affect CAN processing + # Exceptions in any callbacks should not affect CAN processing logger.error(str(e)) def stop(self) -> None: diff --git a/canopen/nmt.py b/canopen/nmt.py index 401ad15e..8184d448 100644 --- a/canopen/nmt.py +++ b/canopen/nmt.py @@ -1,6 +1,6 @@ -import threading import logging import struct +import threading import time from typing import Callable, Optional @@ -86,10 +86,7 @@ def state(self) -> str: - 'RESET' - 'RESET COMMUNICATION' """ - if self._state in NMT_STATES: - return NMT_STATES[self._state] - else: - return self._state + return NMT_STATES.get(self._state, "") @state.setter def state(self, new_state: str): @@ -180,7 +177,8 @@ def start_node_guarding(self, period: float): :param period: Period (in seconds) at which the node guarding should be advertised to the slave node. """ - if self._node_guarding_producer : self.stop_node_guarding() + if self._node_guarding_producer: + self.stop_node_guarding() self._node_guarding_producer = self.network.send_periodic(0x700 + self.id, None, period, True) def stop_node_guarding(self): @@ -227,6 +225,7 @@ def send_command(self, code: int) -> None: self.update_heartbeat() def on_write(self, index, data, **kwargs): + _ = kwargs if index == 0x1017: heartbeat_time, = struct.unpack_from(" bool: def readable(self) -> bool: return "r" in self.access_type or self.access_type == "const" - def add_value_description(self, value: int, descr: str) -> None: + def add_value_description(self, value: int, desc: str) -> None: """Associate a value with a string description. :param value: Value to describe :param desc: Description of value """ - self.value_descriptions[value] = descr + self.value_descriptions[value] = desc def add_bit_definition(self, name: str, bits: List[int]) -> None: """Associate bit(s) with a string description. @@ -461,7 +463,7 @@ def encode_desc(self, desc: str) -> int: raise ValueError( f"No value corresponds to '{desc}'. Valid values are: {valid_values}") - def decode_bits(self, value: int, bits: List[int]) -> int: + def decode_bits(self, value: int, bits: Union[str, List[int]]) -> int: try: bits = self.bit_definitions[bits] except (TypeError, KeyError): @@ -471,7 +473,7 @@ def decode_bits(self, value: int, bits: List[int]) -> int: mask |= 1 << bit return (value & mask) >> min(bits) - def encode_bits(self, original_value: int, bits: List[int], bit_value: int): + def encode_bits(self, original_value: int, bits: Union[str, List[int]], bit_value: int): try: bits = self.bit_definitions[bits] except (TypeError, KeyError): @@ -488,20 +490,20 @@ def encode_bits(self, original_value: int, bits: List[int], bit_value: int): class DeviceInformation: def __init__(self): self.allowed_baudrates = set() - self.vendor_name:Optional[str] = None - self.vendor_number:Optional[int] = None - self.product_name:Optional[str] = None - self.product_number:Optional[int] = None - self.revision_number:Optional[int] = None - self.order_code:Optional[str] = None - self.simple_boot_up_master:Optional[bool] = None - self.simple_boot_up_slave:Optional[bool] = None - self.granularity:Optional[int] = None - self.dynamic_channels_supported:Optional[bool] = None - self.group_messaging:Optional[bool] = None - self.nr_of_RXPDO:Optional[bool] = None - self.nr_of_TXPDO:Optional[bool] = None - self.LSS_supported:Optional[bool] = None + self.vendor_name: Optional[str] = None + self.vendor_number: Optional[int] = None + self.product_name: Optional[str] = None + self.product_number: Optional[int] = None + self.revision_number: Optional[int] = None + self.order_code: Optional[str] = None + self.simple_boot_up_master: Optional[bool] = None + self.simple_boot_up_slave: Optional[bool] = None + self.granularity: Optional[int] = None + self.dynamic_channels_supported: Optional[bool] = None + self.group_messaging: Optional[bool] = None + self.nr_of_RXPDO: Optional[bool] = None + self.nr_of_TXPDO: Optional[bool] = None + self.LSS_supported: Optional[bool] = None class ObjectDictionaryError(Exception): diff --git a/canopen/objectdictionary/eds.py b/canopen/objectdictionary/eds.py index cd64f604..90501239 100644 --- a/canopen/objectdictionary/eds.py +++ b/canopen/objectdictionary/eds.py @@ -2,6 +2,7 @@ import logging import re from configparser import RawConfigParser, NoOptionError, NoSectionError +from typing import Optional from canopen import objectdictionary from canopen.objectdictionary import ObjectDictionary, datatypes @@ -16,10 +17,11 @@ RECORD = 9 -def import_eds(source, node_id): +def import_eds(source, node_id: Optional[int]): eds = RawConfigParser(inline_comment_prefixes=(';',)) eds.optionxform = str opened_here = False + fp = None try: if hasattr(source, "read"): fp = source @@ -29,7 +31,7 @@ def import_eds(source, node_id): eds.read_file(fp) finally: # Only close object if opened in this fn - if opened_here: + if fp and opened_here: fp.close() od = ObjectDictionary() @@ -48,12 +50,11 @@ def import_eds(source, node_id): ]) if not eds.has_section("DeviceInfo"): - logger.warn("eds file does not have a DeviceInfo section. This section is mandatory") + logger.warning("eds file does not have a DeviceInfo section. This section is mandatory") else: for rate in [10, 20, 50, 125, 250, 500, 800, 1000]: - baudPossible = int( - eds.get("DeviceInfo", f"BaudRate_{rate}", fallback='0'), 0) - if baudPossible != 0: + baud_possible = bool(eds.get("DeviceInfo", f"BaudRate_{rate}", fallback='0')) + if baud_possible: od.device_information.allowed_baudrates.add(rate*1000) for t, eprop, odprop in [ @@ -73,20 +74,18 @@ def import_eds(source, node_id): (bool, "LSS_Supported", "LSS_supported"), ]: try: - if t in (int, bool): - setattr(od.device_information, odprop, - t(int(eds.get("DeviceInfo", eprop), 0)) - ) + if t is bool: + setattr(od.device_information, odprop, 1 if eds.get("DeviceInfo", eprop) else 0) + if t is int: + setattr(od.device_information, odprop, int(eds.get("DeviceInfo", eprop), 0)) elif t is str: - setattr(od.device_information, odprop, - eds.get("DeviceInfo", eprop) - ) + setattr(od.device_information, odprop, eds.get("DeviceInfo", eprop)) except NoOptionError: pass - if eds.has_section("DeviceComissioning"): - od.bitrate = int(eds.get("DeviceComissioning", "Baudrate")) * 1000 - od.node_id = int(eds.get("DeviceComissioning", "NodeID"), 0) + if eds.has_section("DeviceCommissioning"): + od.bitrate = int(float(eds.get("DeviceCommissioning", "Baudrate"))) * 1000 + od.node_id = int(eds.get("DeviceCommissioning", "NodeID"), 0) node_id = node_id or od.node_id for section in eds.sections(): @@ -305,7 +304,8 @@ def build_variable(eds, section, node_id, index, subindex=0): var.value = _convert_variable(node_id, var.data_type, eds.get(section, "ParameterValue")) except ValueError: pass - # Factor, Description and Unit are not standard according to the CANopen specifications, but they are implemented in the python canopen package, so we can at least try to use them + # Factor, Description and Unit are not standard according to the CANopen specifications, + # but they are implemented in the python canopen package, so we can at least try to use them if eds.has_option(section, "Factor"): try: var.factor = float(eds.get(section, "Factor")) @@ -333,11 +333,14 @@ def copy_variable(eds, section, subindex, src_var): return var -def export_dcf(od, dest=None, fileInfo={}): - return export_eds(od, dest, fileInfo, True) +def export_dcf(od, dest=None, file_info=None): + return export_eds(od, dest, file_info, True) -def export_eds(od, dest=None, file_info={}, device_commisioning=False): +def export_eds(od, dest=None, file_info=None, device_commissioning=False): + if file_info is None: + file_info = {} + def export_object(obj, eds): if isinstance(obj, objectdictionary.ODVariable): return export_variable(obj, eds) @@ -373,7 +376,7 @@ def export_variable(var, eds): eds.set(section, "DefaultValue", _revert_variable( var.data_type, var.default)) - if device_commisioning: + if device_commissioning: if getattr(var, 'value_raw', None) is not None: eds.set(section, "ParameterValue", var.value_raw) elif getattr(var, 'value', None) is not None: @@ -401,8 +404,8 @@ def export_record(var, eds): eds.set(section, "SubNumber", f"0x{len(var.subindices):X}") ot = RECORD if isinstance(var, objectdictionary.ODRecord) else ARR eds.set(section, "ObjectType", f"0x{ot:X}") - for i in var: - export_variable(var[i], eds) + for index in var: + export_variable(var[index], eds) export_array = export_record @@ -415,9 +418,9 @@ def export_record(var, eds): try: # only if eds was loaded by us - origFileInfo = od.__edsFileInfo + orig_file_info = od.__edsFileInfo except AttributeError: - origFileInfo = { + orig_file_info = { # just set some defaults "CreationDate": defmtime.strftime("%m-%d-%Y"), "CreationTime": defmtime.strftime("%I:%m%p"), @@ -426,7 +429,7 @@ def export_record(var, eds): file_info.setdefault("ModificationDate", defmtime.strftime("%m-%d-%Y")) file_info.setdefault("ModificationTime", defmtime.strftime("%I:%m%p")) - for k, v in origFileInfo.items(): + for k, v in orig_file_info.items(): file_info.setdefault(k, v) eds.add_section("FileInfo") @@ -456,60 +459,60 @@ def export_record(var, eds): elif isinstance(val, str): eds.set("DeviceInfo", eprop, val) elif isinstance(val, (int, bool)): - eds.set("DeviceInfo", eprop, int(val)) + eds.set("DeviceInfo", eprop, str(val)) # we are also adding out of spec baudrates here. for rate in od.device_information.allowed_baudrates.union( {10e3, 20e3, 50e3, 125e3, 250e3, 500e3, 800e3, 1000e3}): eds.set( "DeviceInfo", f"BaudRate_{rate//1000}", - int(rate in od.device_information.allowed_baudrates)) + str(rate in od.device_information.allowed_baudrates)) - if device_commisioning and (od.bitrate or od.node_id): - eds.add_section("DeviceComissioning") + if device_commissioning and (od.bitrate or od.node_id): + eds.add_section("DeviceCommissioning") if od.bitrate: - eds.set("DeviceComissioning", "Baudrate", int(od.bitrate / 1000)) + eds.set("DeviceCommissioning", "Baudrate", str(od.bitrate / 1000)) if od.node_id: - eds.set("DeviceComissioning", "NodeID", int(od.node_id)) + eds.set("DeviceCommissioning", "NodeID", str(od.node_id)) eds.add_section("Comments") i = 0 for line in od.comments.splitlines(): i += 1 eds.set("Comments", f"Line{i}", line) - eds.set("Comments", "Lines", i) + eds.set("Comments", "Lines", str(i)) eds.add_section("DummyUsage") for i in range(1, 8): key = f"Dummy{i:04d}" - eds.set("DummyUsage", key, 1 if (key in od) else 0) + eds.set("DummyUsage", key, "1" if (key in od) else "0") def mandatory_indices(x): return x in {0x1000, 0x1001, 0x1018} - def manufacturer_idices(x): + def manufacturer_indices(x): return x in range(0x2000, 0x6000) def optional_indices(x): return all(( x > 0x1001, not mandatory_indices(x), - not manufacturer_idices(x), + not manufacturer_indices(x), )) - supported_mantatory_indices = list(filter(mandatory_indices, od)) + supported_mandatory_indices = list(filter(mandatory_indices, od)) supported_optional_indices = list(filter(optional_indices, od)) - supported_manufacturer_indices = list(filter(manufacturer_idices, od)) + supported_manufacturer_indices = list(filter(manufacturer_indices, od)) - def add_list(section, list): + def add_list(section, list_to_add): eds.add_section(section) - eds.set(section, "SupportedObjects", len(list)) - for i in range(0, len(list)): - eds.set(section, (i + 1), f"0x{list[i]:04X}") - for index in list: + eds.set(section, "SupportedObjects", str(len(list_to_add))) + for item in range(0, len(list_to_add)): + eds.set(section, str(item + 1), f"0x{list_to_add[item]:04X}") + for index in list_to_add: export_object(od[index], eds) - add_list("MandatoryObjects", supported_mantatory_indices) + add_list("MandatoryObjects", supported_mandatory_indices) add_list("OptionalObjects", supported_optional_indices) add_list("ManufacturerObjects", supported_manufacturer_indices) diff --git a/canopen/objectdictionary/epf.py b/canopen/objectdictionary/epf.py index 46ffe59e..0e31fca8 100644 --- a/canopen/objectdictionary/epf.py +++ b/canopen/objectdictionary/epf.py @@ -1,5 +1,5 @@ -import xml.etree.ElementTree as etree import logging +from xml.etree import ElementTree from canopen import objectdictionary from canopen.objectdictionary import ObjectDictionary @@ -32,10 +32,10 @@ def import_epf(epf): :rtype: canopen.ObjectDictionary """ od = ObjectDictionary() - if etree.iselement(epf): + if ElementTree.iselement(epf): tree = epf else: - tree = etree.parse(epf).getroot() + tree = ElementTree.parse(epf).getroot() # Find and set default bitrate can_config = tree.find("Configuration/CANopen") diff --git a/canopen/pdo/__init__.py b/canopen/pdo/__init__.py index 1c951cf5..7f68acdf 100644 --- a/canopen/pdo/__init__.py +++ b/canopen/pdo/__init__.py @@ -1,8 +1,13 @@ import logging +from typing import Union, TYPE_CHECKING from canopen import node from canopen.pdo.base import PdoBase, PdoMaps +if TYPE_CHECKING: + from canopen import LocalNode, RemoteNode + + # Compatibility from canopen.pdo.base import Variable @@ -16,8 +21,8 @@ class PDO(PdoBase): :param tpdo: TPDO object holding the Transmit PDO mappings """ - def __init__(self, node, rpdo, tpdo): - super(PDO, self).__init__(node) + def __init__(self, pdo_node: Union['LocalNode', 'RemoteNode'], rpdo, tpdo): + super(PDO, self).__init__(pdo_node) self.rx = rpdo.map self.tx = tpdo.map @@ -33,11 +38,11 @@ class RPDO(PdoBase): """Receive PDO to transfer data from somewhere to the represented node. Properties 0x1400 to 0x1403 | Mapping 0x1600 to 0x1603. - :param object node: Parent node for this object. + :param object rpdo_node: Parent node for this object. """ - def __init__(self, node): - super(RPDO, self).__init__(node) + def __init__(self, rpdo_node: Union['LocalNode', 'RemoteNode']): + super(RPDO, self).__init__(rpdo_node) self.map = PdoMaps(0x1400, 0x1600, self, 0x200) logger.debug('RPDO Map as %d', len(self.map)) @@ -58,11 +63,11 @@ class TPDO(PdoBase): """Transmit PDO to broadcast data from the represented node to the network. Properties 0x1800 to 0x1803 | Mapping 0x1A00 to 0x1A03. - :param object node: Parent node for this object. + :param object tpdo_node: Parent node for this object. """ - def __init__(self, node): - super(TPDO, self).__init__(node) + def __init__(self, tpdo_node: Union['LocalNode', 'RemoteNode']): + super(TPDO, self).__init__(tpdo_node) self.map = PdoMaps(0x1800, 0x1A00, self, 0x180) logger.debug('TPDO Map as %d', len(self.map)) diff --git a/canopen/pdo/base.py b/canopen/pdo/base.py index d467cdb3..13ef24c6 100644 --- a/canopen/pdo/base.py +++ b/canopen/pdo/base.py @@ -75,6 +75,7 @@ def subscribe(self): for pdo_map in self.map.values(): pdo_map.subscribe() + # noinspection PyUnresolvedReferences,PyPackageRequirements def export(self, filename): """Export current configuration to a database file. @@ -528,7 +529,7 @@ def update(self) -> None: self._task.update(self.data) def remote_request(self) -> None: - """Send a remote request for the transmit PDO. + """Send a remote request to transmit PDO. Silently ignore if not allowed. """ if self.enabled and self.rtr_allowed: diff --git a/canopen/profiles/p402.py b/canopen/profiles/p402.py index c94e5356..510b3242 100644 --- a/canopen/profiles/p402.py +++ b/canopen/profiles/p402.py @@ -49,15 +49,15 @@ class State402: # Transition path to reach and state without a direct transition NEXTSTATE2ANY = { - ('START'): 'NOT READY TO SWITCH ON', - ('FAULT', 'NOT READY TO SWITCH ON', 'QUICK STOP ACTIVE'): 'SWITCH ON DISABLED', - ('SWITCH ON DISABLED'): 'READY TO SWITCH ON', - ('READY TO SWITCH ON'): 'SWITCHED ON', - ('SWITCHED ON'): 'OPERATION ENABLED', - ('FAULT REACTION ACTIVE'): 'FAULT', + 'START': 'NOT READY TO SWITCH ON', + ('FAULT', 'NOT READY TO SWITCH ON', 'QUICK STOP ACTIVE'): 'SWITCH ON DISABLED', + 'SWITCH ON DISABLED': 'READY TO SWITCH ON', + 'READY TO SWITCH ON': 'SWITCHED ON', + 'SWITCHED ON': 'OPERATION ENABLED', + 'FAULT REACTION ACTIVE': 'FAULT', } - # Tansition table from the DS402 State Machine + # Transition table from the DS402 State Machine TRANSITIONTABLE = { # disable_voltage --------------------------------------------------------------------- ('READY TO SWITCH ON', 'SWITCH ON DISABLED'): CW_DISABLE_VOLTAGE, # transition 7 @@ -93,7 +93,7 @@ def next_state_indirect(_from): DISABLED first, as there would have been a direct transition if the opposite was desired. - :param str target: Target state. + :param _from: current state. :return: Next target to change. :rtype: str """ @@ -214,6 +214,7 @@ def __init__(self, node_id, object_dictionary): self.tpdo_values = {} # { index: value from last received TPDO } self.tpdo_pointers = {} # { index: pdo.PdoMap instance } self.rpdo_pointers = {} # { index: pdo.PdoMap instance } + self._op_mode_support = None def setup_402_state_machine(self, read_pdos=True): """Configure the state machine by searching for a TPDO that has the StatusWord mapped. @@ -247,7 +248,7 @@ def setup_pdos(self, upload=True): def _init_tpdo_values(self): for tpdo in self.tpdo.values(): if tpdo.enabled: - tpdo.add_callback(self.on_TPDOs_update_callback) + tpdo.add_callback(self.on_tpdos_update_callback) for obj in tpdo: logger.debug('Configured TPDO: 0x%04X', obj.index) if obj.index not in self.tpdo_values: @@ -340,24 +341,25 @@ def homing(self, timeout=None, restore_op_mode=False): :return: If the homing was complete with success. :rtype: bool """ - if timeout is None: - timeout = self.TIMEOUT_HOMING_DEFAULT if restore_op_mode: previous_op_mode = self.op_mode + else: + previous_op_mode = None + if timeout is None: + timeout = self.TIMEOUT_HOMING_DEFAULT self.op_mode = 'HOMING' # The homing process will initialize at operation enabled self.state = 'OPERATION ENABLED' - homingstatus = 'UNKNOWN' + homing_status = 'UNKNOWN' self.controlword = State402.CW_OPERATION_ENABLED | Homing.CW_START # does not block # Wait for one extra cycle, to make sure the controlword was received self.check_statusword() t = time.monotonic() + timeout try: - while homingstatus not in ('TARGET REACHED', 'ATTAINED'): - homingstatus = self._homing_status() - if homingstatus in ('INTERRUPTED', 'ERROR VELOCITY IS NOT ZERO', - 'ERROR VELOCITY IS ZERO'): - raise RuntimeError(f'Unable to home. Reason: {homingstatus}') + while homing_status not in ('TARGET REACHED', 'ATTAINED'): + homing_status = self._homing_status() + if homing_status in ('INTERRUPTED', 'ERROR VELOCITY IS NOT ZERO', 'ERROR VELOCITY IS ZERO'): + raise RuntimeError(f'Unable to home. Reason: {homing_status}') if timeout and time.monotonic() > t: raise RuntimeError('Unable to home, timeout reached') logger.info('Homing mode carried out successfully.') @@ -453,7 +455,7 @@ def is_op_mode_supported(self, mode): bits = OperationMode.SUPPORTED[mode] return self._op_mode_support & bits == bits - def on_TPDOs_update_callback(self, mapobject): + def on_tpdos_update_callback(self, mapobject): """Cache updated values from a TPDO received from this node. :param mapobject: The received PDO message. @@ -500,14 +502,17 @@ def check_statusword(self, timeout=None): @property def controlword(self): """Send a state change command using PDO or SDO. - - :param int value: Controlword value to set. :raises RuntimeError: Read access to the controlword is not intended. """ raise RuntimeError('The Controlword is write-only.') @controlword.setter def controlword(self, value): + """Send a state change command using PDO or SDO. + + :param int value: Controlword value to set. + :raises RuntimeError: Read access to the controlword is not intended. + """ if 0x6040 in self.rpdo_pointers: self.rpdo_pointers[0x6040].raw = value pdo = self.rpdo_pointers[0x6040].pdo_parent diff --git a/canopen/sdo/base.py b/canopen/sdo/base.py index 0bb068b4..c626e2ae 100644 --- a/canopen/sdo/base.py +++ b/canopen/sdo/base.py @@ -1,13 +1,16 @@ from __future__ import annotations import binascii -from typing import Iterator, Optional, Union +from typing import Iterator, Optional, Union, cast, TYPE_CHECKING from collections.abc import Mapping from canopen import objectdictionary from canopen import variable from canopen.utils import pretty_index +if TYPE_CHECKING: + from canopen.sdo import SdoClient, SdoServer + class CrcXmodem: """Mimics CrcXmodem from crccheck.""" @@ -50,12 +53,16 @@ def __getitem__( self, index: Union[str, int] ) -> Union[SdoVariable, SdoArray, SdoRecord]: entry = self.od[index] + if TYPE_CHECKING: + sdo_node = cast(Union[SdoClient, SdoServer], self) + else: + sdo_node = self if isinstance(entry, objectdictionary.ODVariable): - return SdoVariable(self, entry) + return SdoVariable(sdo_node, entry) elif isinstance(entry, objectdictionary.ODArray): - return SdoArray(self, entry) + return SdoArray(sdo_node, entry) elif isinstance(entry, objectdictionary.ODRecord): - return SdoRecord(self, entry) + return SdoRecord(sdo_node, entry) def __iter__(self) -> Iterator[int]: return iter(self.od) @@ -94,7 +101,7 @@ def download( class SdoRecord(Mapping): - def __init__(self, sdo_node: SdoBase, od: objectdictionary.ODRecord): + def __init__(self, sdo_node: Union[SdoClient, SdoServer], od: objectdictionary.ODRecord): self.sdo_node = sdo_node self.od = od @@ -116,7 +123,7 @@ def __contains__(self, subindex: Union[int, str]) -> bool: class SdoArray(Mapping): - def __init__(self, sdo_node: SdoBase, od: objectdictionary.ODArray): + def __init__(self, sdo_node: Union[SdoClient, SdoServer], od: objectdictionary.ODArray): self.sdo_node = sdo_node self.od = od @@ -139,7 +146,7 @@ def __contains__(self, subindex: int) -> bool: class SdoVariable(variable.Variable): """Access object dictionary variable values using SDO protocol.""" - def __init__(self, sdo_node: SdoBase, od: objectdictionary.ODVariable): + def __init__(self, sdo_node: Union[SdoServer, SdoClient], od: objectdictionary.ODVariable): self.sdo_node = sdo_node variable.Variable.__init__(self, od) diff --git a/canopen/sdo/client.py b/canopen/sdo/client.py index e4c50aa8..abb07750 100644 --- a/canopen/sdo/client.py +++ b/canopen/sdo/client.py @@ -1,15 +1,14 @@ -import struct -import logging import io -import time +import logging import queue +import time -from canopen.network import CanError from canopen import objectdictionary +from canopen.network import CanError from canopen.sdo.base import SdoBase -from canopen.utils import pretty_index from canopen.sdo.constants import * from canopen.sdo.exceptions import * +from canopen.utils import pretty_index logger = logging.getLogger(__name__) @@ -42,6 +41,7 @@ def __init__(self, rx_cobid, tx_cobid, od): self.responses = queue.Queue() def on_response(self, can_id, data, timestamp): + _ = can_id, timestamp self.responses.put(bytes(data)) def send_request(self, request): @@ -198,6 +198,7 @@ def open(self, index, subindex=0, mode="rb", encoding="ascii", :returns: A file like object. """ + buffered_stream = None buffer_size = buffering if buffering > 1 else io.DEFAULT_BUFFER_SIZE if "r" in mode: if block_transfer: diff --git a/canopen/sdo/server.py b/canopen/sdo/server.py index e2a16e61..f3c47167 100644 --- a/canopen/sdo/server.py +++ b/canopen/sdo/server.py @@ -1,22 +1,26 @@ import logging +from typing import TYPE_CHECKING from canopen.sdo.base import SdoBase from canopen.sdo.constants import * from canopen.sdo.exceptions import * +if TYPE_CHECKING: + from canopen import LocalNode + logger = logging.getLogger(__name__) class SdoServer(SdoBase): """Creates an SDO server.""" - def __init__(self, rx_cobid, tx_cobid, node): + def __init__(self, rx_cobid, tx_cobid, node: 'LocalNode'): """ :param int rx_cobid: COB-ID that the server receives on (usually 0x600 + node ID) :param int tx_cobid: COB-ID that the server responds with (usually 0x580 + node ID) - :param canopen.LocalNode od: + :param canopen.LocalNode node: Node object owning the server """ SdoBase.__init__(self, rx_cobid, tx_cobid, node.object_dictionary) @@ -28,6 +32,7 @@ def __init__(self, rx_cobid, tx_cobid, node): self.last_received_error = 0x00000000 def on_request(self, can_id, data, timestamp): + _ = can_id, timestamp command, = struct.unpack_from("B", data, 0) ccs = command & 0xE0 @@ -50,7 +55,7 @@ def on_request(self, can_id, data, timestamp): self.abort(0x05040001) except SdoAbortedError as exc: self.abort(exc.code) - except KeyError as exc: + except KeyError: self.abort(0x06020000) except Exception as exc: self.abort() @@ -118,6 +123,7 @@ def request_aborted(self, data): logger.info("Received request aborted for 0x%04X:%02X with code 0x%X", index, subindex, code) def block_download(self, data): + _ = data # We currently don't support BLOCK DOWNLOAD logger.error("Block download is not supported") self.abort(0x05040001) @@ -211,6 +217,8 @@ def download( Sub-index of object to write. :param data: Data to be written. + :param force_segment: + Not used in SDOServer :raises canopen.SdoAbortedError: When node responds with an error. diff --git a/canopen/variable.py b/canopen/variable.py index 3ec67c79..1be2bd6c 100644 --- a/canopen/variable.py +++ b/canopen/variable.py @@ -24,9 +24,10 @@ def __init__(self, od: objectdictionary.ODVariable): self.subindex = od.subindex def __repr__(self) -> str: - subindex = self.subindex if isinstance(self.od.parent, - (objectdictionary.ODRecord, objectdictionary.ODArray) - ) else None + if isinstance(self.od.parent, (objectdictionary.ODRecord, objectdictionary.ODArray)): + subindex = self.subindex + else: + subindex = None return f"<{type(self).__qualname__} {self.name!r} at {pretty_index(self.index, subindex)}>" def get_data(self) -> bytes: @@ -148,8 +149,9 @@ def write( """Alternative way of writing using a function instead of attributes. May be useful for asynchronous writing. - - :param str fmt: + :param value: + The value to write + :param fmt: How to write the value - 'raw' - 'phys' @@ -168,6 +170,7 @@ class Bits(Mapping): def __init__(self, variable: Variable): self.variable = variable self.read() + self.raw = None @staticmethod def _get_bits(key): diff --git a/doc/integration.rst b/doc/integration.rst index 6e677ce8..17589c16 100644 --- a/doc/integration.rst +++ b/doc/integration.rst @@ -66,3 +66,4 @@ Here is an example:: # Should be done in a thread but here we notify the network for # demonstration purposes only network.notify(0x701, bytearray([0x05]), time.time()) + diff --git a/examples/simple_ds402_node.py b/examples/simple_ds402_node.py index 5847923d..c6ed988b 100644 --- a/examples/simple_ds402_node.py +++ b/examples/simple_ds402_node.py @@ -5,11 +5,11 @@ import time -try: +# Start with creating a network representing one CAN bus +network = canopen.Network() - # Start with creating a network representing one CAN bus - network = canopen.Network() +try: # Connect to the CAN bus network.connect(bustype='kvaser', channel=0, bitrate=1000000) @@ -23,7 +23,7 @@ # Reset network node.nmt.state = 'RESET COMMUNICATION' - #node.nmt.state = 'RESET' + # node.nmt.state = 'RESET' node.nmt.wait_for_bootup(15) print(f'node state 1) = {node.nmt.state}') @@ -77,8 +77,7 @@ # Save new PDO configuration to node node.tpdo.save() - # publish the a value to the control word (in this case reset the fault at the motors) - + # publish a value to the control word (in this case reset the fault at the motors) node.rpdo.read() node.rpdo[1]['Controlword'].raw = 0x80 node.rpdo[1].transmit() @@ -115,15 +114,12 @@ raise Exception('Timeout when trying to change state') time.sleep(0.001) - print(f'Node Status {node.powerstate_402.state}') + print(f'Node Status {node.state}') # ----------------------------------------------------------------------------------------- node.nmt.start_node_guarding(0.01) while True: - try: - network.check() - except Exception: - break + network.check() # Read a value from TxPDO1 node.tpdo[1].wait_for_reception() @@ -141,8 +137,8 @@ pass except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() - fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] - print(exc_type, fname, exc_tb.tb_lineno) + file_name = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] + print(exc_type, file_name, exc_tb.tb_lineno) traceback.print_exc() finally: # Disconnect from CAN bus @@ -155,4 +151,3 @@ node.nmt.stop_node_guarding() network.sync.stop() network.disconnect() - diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..8a39b470 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +python-can +setuptools \ No newline at end of file diff --git a/test/sample.eds b/test/sample.eds index 16d0c31a..a5e9e4ee 100644 --- a/test/sample.eds +++ b/test/sample.eds @@ -29,7 +29,7 @@ NrOfRXPDO=4 NrOfTXPDO=4 LSS_Supported=0 -[DeviceComissioning] +[DeviceCommissioning] NodeID=2 NodeName=Some name Baudrate=500 diff --git a/test/test_eds.py b/test/test_eds.py index 88654a0f..05fa74ae 100644 --- a/test/test_eds.py +++ b/test/test_eds.py @@ -157,20 +157,18 @@ def test_dummy_variable(self): def test_dummy_variable_undefined(self): with self.assertRaises(KeyError): - var_undef = self.od['Dummy0001'] + _ = self.od['Dummy0001'] def test_reading_factor(self): var = self.od['EDS file extensions']['FactorAndDescription'] self.assertEqual(var.factor, 0.1) self.assertEqual(var.description, "This is the a test description") - self.assertEqual(var.unit,'mV') + self.assertEqual(var.unit, 'mV') var2 = self.od['EDS file extensions']['Error Factor and No Description'] self.assertEqual(var2.description, '') self.assertEqual(var2.factor, 1) self.assertEqual(var2.unit, '') - - def test_comments(self): self.assertEqual(self.od.comments, """ diff --git a/test/test_emcy.py b/test/test_emcy.py index 34c3ca29..118801c2 100644 --- a/test/test_emcy.py +++ b/test/test_emcy.py @@ -48,6 +48,7 @@ class MockNetwork(object): data = None def send_message(self, can_id, data): + _ = can_id self.data = data diff --git a/test/test_local.py b/test/test_local.py index dd6efe1a..f7123ccf 100644 --- a/test/test_local.py +++ b/test/test_local.py @@ -1,8 +1,8 @@ import os +import time import unittest + import canopen -import logging -import time # logging.basicConfig(level=logging.DEBUG) @@ -17,11 +17,11 @@ class TestSDO(unittest.TestCase): @classmethod def setUpClass(cls): cls.network1 = canopen.Network() - cls.network1.connect("test", bustype="virtual") + cls.network1.connect("test", interface="virtual") cls.remote_node = cls.network1.add_node(2, EDS_PATH) cls.network2 = canopen.Network() - cls.network2.connect("test", bustype="virtual") + cls.network2.connect("test", interface="virtual") cls.local_node = cls.network2.create_node(2, EDS_PATH) cls.remote_node2 = cls.network1.add_node(3, EDS_PATH) @@ -180,11 +180,11 @@ class TestNMT(unittest.TestCase): @classmethod def setUpClass(cls): cls.network1 = canopen.Network() - cls.network1.connect("test", bustype="virtual") + cls.network1.connect("test", interface="virtual") cls.remote_node = cls.network1.add_node(2, EDS_PATH) cls.network2 = canopen.Network() - cls.network2.connect("test", bustype="virtual") + cls.network2.connect("test", interface="virtual") cls.local_node = cls.network2.create_node(2, EDS_PATH) cls.remote_node2 = cls.network1.add_node(3, EDS_PATH) @@ -214,7 +214,7 @@ def test_start_two_remote_nodes(self): def test_stop_two_remote_nodes_using_broadcast(self): # This is a NMT broadcast "Stop remote node" # ie. set the node in STOPPED state - self.network1.send_message(0, [2, 0]) + self.network1.send_message(0, bytes([2, 0])) # Line below is just so that we are sure the slaves have received the command # before we do the check @@ -234,6 +234,7 @@ def test_heartbeat(self): self.local_node.nmt.stop_heartbeat() + class TestPDO(unittest.TestCase): """ Test PDO slave. @@ -242,11 +243,11 @@ class TestPDO(unittest.TestCase): @classmethod def setUpClass(cls): cls.network1 = canopen.Network() - cls.network1.connect("test", bustype="virtual") + cls.network1.connect("test", interface="virtual") cls.remote_node = cls.network1.add_node(2, EDS_PATH) cls.network2 = canopen.Network() - cls.network2.connect("test", bustype="virtual") + cls.network2.connect("test", interface="virtual") cls.local_node = cls.network2.create_node(2, EDS_PATH) @classmethod diff --git a/test/test_network.py b/test/test_network.py index 095648ad..fa9a1c28 100644 --- a/test/test_network.py +++ b/test/test_network.py @@ -1,10 +1,11 @@ -import time import os +import time import unittest -import canopen import can +import canopen + EDS_PATH = os.path.join(os.path.dirname(__file__), 'sample.eds') @@ -32,11 +33,11 @@ def test_notify(self): self.assertListEqual(self.network.scanner.nodes, [2]) def test_send(self): - bus = can.interface.Bus(bustype="virtual", channel=1) - self.network.connect(bustype="virtual", channel=1) + bus = can.interface.Bus(interface="virtual", channel=1) + self.network.connect(interface="virtual", channel=1) # Send standard ID - self.network.send_message(0x123, [1, 2, 3, 4, 5, 6, 7, 8]) + self.network.send_message(0x123, bytes([1, 2, 3, 4, 5, 6, 7, 8])) msg = bus.recv(1) self.assertIsNotNone(msg) self.assertEqual(msg.arbitration_id, 0x123) @@ -44,7 +45,7 @@ def test_send(self): self.assertSequenceEqual(msg.data, [1, 2, 3, 4, 5, 6, 7, 8]) # Send extended ID - self.network.send_message(0x12345, []) + self.network.send_message(0x12345, bytes()) msg = bus.recv(1) self.assertIsNotNone(msg) self.assertEqual(msg.arbitration_id, 0x12345) @@ -54,10 +55,10 @@ def test_send(self): self.network.disconnect() def test_send_perodic(self): - bus = can.interface.Bus(bustype="virtual", channel=1) - self.network.connect(bustype="virtual", channel=1) + bus = can.interface.Bus(interface="virtual", channel=1) + self.network.connect(interface="virtual", channel=1) - task = self.network.send_periodic(0x123, [1, 2, 3], 0.01) + task = self.network.send_periodic(0x123, bytes([1, 2, 3]), 0.01) time.sleep(0.1) # FIXME: This test is a little fragile, as the number of elements # depends on the timing of the machine. @@ -67,7 +68,7 @@ def test_send_perodic(self): self.assertIsNotNone(msg) self.assertSequenceEqual(msg.data, [1, 2, 3]) # Update data - task.update([4, 5, 6]) + task.update(bytes([4, 5, 6])) time.sleep(0.02) while msg is not None and msg.data == b'\x01\x02\x03': msg = bus.recv(0) diff --git a/test/test_od.py b/test/test_od.py index 9c25bfcb..31f90c32 100644 --- a/test/test_od.py +++ b/test/test_od.py @@ -151,6 +151,7 @@ def test_get_item_dot(self): self.assertEqual(test_od["Test Array.Test Variable"], member1) self.assertEqual(test_od["Test Array.Test Variable 2"], member2) + class TestArray(unittest.TestCase): def test_subindexes(self): diff --git a/test/test_pdo.py b/test/test_pdo.py index 32963cf3..ea34fc93 100644 --- a/test/test_pdo.py +++ b/test/test_pdo.py @@ -9,32 +9,32 @@ class TestPDO(unittest.TestCase): def test_bit_mapping(self): node = canopen.Node(1, EDS_PATH) - map = node.pdo.tx[1] - map.add_variable('INTEGER16 value') # 0x2001 - map.add_variable('UNSIGNED8 value', length=4) # 0x2002 - map.add_variable('INTEGER8 value', length=4) # 0x2003 - map.add_variable('INTEGER32 value') # 0x2004 - map.add_variable('BOOLEAN value', length=1) # 0x2005 - map.add_variable('BOOLEAN value 2', length=1) # 0x2006 + test_map = node.pdo.tx[1] + test_map.add_variable('INTEGER16 value') # 0x2001 + test_map.add_variable('UNSIGNED8 value', length=4) # 0x2002 + test_map.add_variable('INTEGER8 value', length=4) # 0x2003 + test_map.add_variable('INTEGER32 value') # 0x2004 + test_map.add_variable('BOOLEAN value', length=1) # 0x2005 + test_map.add_variable('BOOLEAN value 2', length=1) # 0x2006 # Write some values - map['INTEGER16 value'].raw = -3 - map['UNSIGNED8 value'].raw = 0xf - map['INTEGER8 value'].raw = -2 - map['INTEGER32 value'].raw = 0x01020304 - map['BOOLEAN value'].raw = False - map['BOOLEAN value 2'].raw = True + test_map['INTEGER16 value'].raw = -3 + test_map['UNSIGNED8 value'].raw = 0xf + test_map['INTEGER8 value'].raw = -2 + test_map['INTEGER32 value'].raw = 0x01020304 + test_map['BOOLEAN value'].raw = False + test_map['BOOLEAN value 2'].raw = True # Check expected data - self.assertEqual(map.data, b'\xfd\xff\xef\x04\x03\x02\x01\x02') + self.assertEqual(test_map.data, b'\xfd\xff\xef\x04\x03\x02\x01\x02') # Read values from data - self.assertEqual(map['INTEGER16 value'].raw, -3) - self.assertEqual(map['UNSIGNED8 value'].raw, 0xf) - self.assertEqual(map['INTEGER8 value'].raw, -2) - self.assertEqual(map['INTEGER32 value'].raw, 0x01020304) - self.assertEqual(map['BOOLEAN value'].raw, False) - self.assertEqual(map['BOOLEAN value 2'].raw, True) + self.assertEqual(test_map['INTEGER16 value'].raw, -3) + self.assertEqual(test_map['UNSIGNED8 value'].raw, 0xf) + self.assertEqual(test_map['INTEGER8 value'].raw, -2) + self.assertEqual(test_map['INTEGER32 value'].raw, 0x01020304) + self.assertEqual(test_map['BOOLEAN value'].raw, False) + self.assertEqual(test_map['BOOLEAN value 2'].raw, True) self.assertEqual(node.tpdo[1]['INTEGER16 value'].raw, -3) self.assertEqual(node.tpdo[1]['UNSIGNED8 value'].raw, 0xf) diff --git a/test/test_sdo.py b/test/test_sdo.py index 31759c22..281bf8fe 100644 --- a/test/test_sdo.py +++ b/test/test_sdo.py @@ -110,8 +110,7 @@ def test_block_download(self): (RX, b'\xa1\x00\x00\x00\x00\x00\x00\x00') ] data = b'A really really long string...' - with self.network[2].sdo['Writable string'].open( - 'wb', size=len(data), block_transfer=True) as fp: + with self.network[2].sdo['Writable string'].open('wb', size=len(data), block_transfer=True) as fp: fp.write(data) def test_block_upload(self): diff --git a/test/test_sync.py b/test/test_sync.py index 0321ceb6..8fcd1b2a 100644 --- a/test/test_sync.py +++ b/test/test_sync.py @@ -1,13 +1,15 @@ import unittest + import canopen +from canopen.sync import SyncProducer class TestSync(unittest.TestCase): def test_sync_producer(self): network = canopen.Network() - network.connect(bustype="virtual", receive_own_messages=True) - producer = canopen.sync.SyncProducer(network) + network.connect(interface="virtual", receive_own_messages=True) + producer = SyncProducer(network) producer.transmit() msg = network.bus.recv(1) network.disconnect() @@ -16,8 +18,8 @@ def test_sync_producer(self): def test_sync_producer_counter(self): network = canopen.Network() - network.connect(bustype="virtual", receive_own_messages=True) - producer = canopen.sync.SyncProducer(network) + network.connect(interface="virtual", receive_own_messages=True) + producer = SyncProducer(network) producer.transmit(2) msg = network.bus.recv(1) network.disconnect() @@ -25,5 +27,6 @@ def test_sync_producer_counter(self): self.assertEqual(msg.dlc, 1) self.assertEqual(msg.data, b"\x02") + if __name__ == "__main__": unittest.main() diff --git a/test/test_time.py b/test/test_time.py index d8d12e53..6da3c414 100644 --- a/test/test_time.py +++ b/test/test_time.py @@ -1,13 +1,15 @@ import unittest + import canopen +from canopen.timestamp import TimeProducer class TestTime(unittest.TestCase): def test_time_producer(self): network = canopen.Network() - network.connect(bustype="virtual", receive_own_messages=True) - producer = canopen.timestamp.TimeProducer(network) + network.connect(interface="virtual", receive_own_messages=True) + producer = TimeProducer(network) producer.transmit(1486236238) msg = network.bus.recv(1) network.disconnect()