Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ target/

# IDEs
.vscode/
.idea/

*.dbc

Expand Down
97 changes: 49 additions & 48 deletions canopen/emcy.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import struct
import logging
import struct
import threading
import time
from typing import Callable, List, Optional
Expand All @@ -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)

Expand All @@ -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:
Expand All @@ -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
Expand Down Expand Up @@ -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
62 changes: 32 additions & 30 deletions canopen/lss.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import logging
import time
import struct
import queue
import struct
import time

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -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):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change is strictly speaking a change in interface. It will break if someone use named arguments to call this function.

"""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:
Expand All @@ -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("<B", response)[0]
if cs == CS_SWITCH_STATE_SELECTIVE_RESPONSE:
Expand Down Expand Up @@ -203,19 +202,21 @@ def store_configuration(self):
self.__send_configure(CS_STORE_CONFIGURATION)

def send_identify_remote_slave(self,
vendorId, productCode,
revisionNumberLow, revisionNumberHigh,
serialNumberLow, serialNumberHigh):

vendor_id,
product_code,
revision_number_low,
revision_number_high,
serial_number_low,
serial_number_high):
"""This command sends the range of LSS address to find the slave nodes
in the specified range

:param int vendorId:
:param int productCode:
:param int revisionNumberLow:
:param int revisionNumberHigh:
:param int serialNumberLow:
:param int serialNumberHigh:
:param int vendor_id:
:param int product_code:
:param int revision_number_low:
:param int revision_number_high:
:param int serial_number_low:
:param int serial_number_high:

:return:
True if any slave responds.
Expand All @@ -225,12 +226,12 @@ def send_identify_remote_slave(self,

# TODO it should handle the multiple respones from slaves

self.__send_lss_address(CS_IDENTIFY_REMOTE_SLAVE_VENDOR_ID, vendorId)
self.__send_lss_address(CS_IDENTIFY_REMOTE_SLAVE_PRODUCT_CODE, productCode)
self.__send_lss_address(CS_IDENTIFY_REMOTE_SLAVE_REVISION_NUMBER_LOW, revisionNumberLow)
self.__send_lss_address(CS_IDENTIFY_REMOTE_SLAVE_REVISION_NUMBER_HIGH, revisionNumberHigh)
self.__send_lss_address(CS_IDENTIFY_REMOTE_SLAVE_SERIAL_NUMBER_LOW, serialNumberLow)
self.__send_lss_address(CS_IDENTIFY_REMOTE_SLAVE_SERIAL_NUMBER_HIGH, serialNumberHigh)
self.__send_lss_address(CS_IDENTIFY_REMOTE_SLAVE_VENDOR_ID, vendor_id)
self.__send_lss_address(CS_IDENTIFY_REMOTE_SLAVE_PRODUCT_CODE, product_code)
self.__send_lss_address(CS_IDENTIFY_REMOTE_SLAVE_REVISION_NUMBER_LOW, revision_number_low)
self.__send_lss_address(CS_IDENTIFY_REMOTE_SLAVE_REVISION_NUMBER_HIGH, revision_number_high)
self.__send_lss_address(CS_IDENTIFY_REMOTE_SLAVE_SERIAL_NUMBER_LOW, serial_number_low)
self.__send_lss_address(CS_IDENTIFY_REMOTE_SLAVE_SERIAL_NUMBER_HIGH, serial_number_high)

def send_identify_non_configured_remote_slave(self):
# TODO it should handle the multiple respones from slaves
Expand Down Expand Up @@ -261,7 +262,7 @@ def fast_scan(self):
lss_bit_check -= 1

if not self.__send_fast_scan_message(lss_id[lss_sub], lss_bit_check, lss_sub, lss_next):
lss_id[lss_sub] |= 1<<lss_bit_check
lss_id[lss_sub] |= 1 << lss_bit_check

time.sleep(0.01)

Expand Down Expand Up @@ -289,7 +290,7 @@ def __send_fast_scan_message(self, id_number, bit_checker, lss_sub, lss_next):

cs = struct.unpack_from("<B", recv_msg)[0]
if cs == CS_IDENTIFY_SLAVE:
return True
return True

return False

Expand Down Expand Up @@ -391,6 +392,7 @@ def __send_command(self, message):
return response

def on_message_received(self, can_id, data, timestamp):
_ = can_id, timestamp

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was a nifty way of consuming unused arguments!

self.responses.put(bytes(data))


Expand Down
24 changes: 13 additions & 11 deletions canopen/network.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from __future__ import annotations

from collections.abc import MutableMapping
import logging
import threading
from collections.abc import MutableMapping
from typing import Callable, Dict, Iterator, List, Optional, Union

try:
Expand All @@ -13,6 +13,7 @@
# Do not fail if python-can is not installed
can = None
CanError = Exception

class Listener:
""" Dummy listener """

Expand All @@ -26,7 +27,7 @@ class Listener:

logger = logging.getLogger(__name__)

Callback = Callable[[int, bytearray, float], None]
Callback = Callable[[int, bytes, float], None]


class Network(MutableMapping):
Expand Down Expand Up @@ -84,20 +85,20 @@ def unsubscribe(self, can_id, callback=None) -> 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 <https://python-can.readthedocs.io/en/stable/configuration.html#interface-names>`__
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.
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -350,6 +351,7 @@ class MessageListener(Listener):
"""

def __init__(self, network: Network):
super().__init__()
self.network = network

def on_message_received(self, msg):
Expand All @@ -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:
Expand Down
11 changes: 5 additions & 6 deletions canopen/nmt.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import threading
import logging
import struct
import threading
import time
from typing import Callable, Optional

Expand Down Expand Up @@ -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, "")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this replacement the same as the former code? What about:

return NMT_STATES.get(self._state, self._state)


@state.setter
def state(self, new_state: str):
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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("<H", data)
if heartbeat_time == 0:
Expand Down
Loading