Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
5 changes: 2 additions & 3 deletions canopen/objectdictionary/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -500,11 +500,10 @@ def encode_phys(self, value: Union[int, bool, float, str, bytes]) -> int:
def decode_desc(self, value: int) -> str:
if not self.value_descriptions:
raise ObjectDictionaryError("No value descriptions exist")
elif value not in self.value_descriptions:
elif (desc := self.value_descriptions.get(value)) is None:
raise ObjectDictionaryError(
f"No value description exists for {value}")
else:
return self.value_descriptions[value]
return desc

def encode_desc(self, desc: str) -> int:
if not self.value_descriptions:
Expand Down
24 changes: 19 additions & 5 deletions canopen/variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,11 @@ def raw(self) -> Union[int, bool, float, str, bytes]:
"""
value = self.od.decode_raw(self.data)
text = f"Value of {self.name!r} ({pretty_index(self.index, self.subindex)}) is {value!r}"
if value in self.od.value_descriptions:
text += f" ({self.od.value_descriptions[value]})"
if (
isinstance(value, int)
and (desc := self.od.value_descriptions.get(value)) is not None
):
text += f" ({desc})"
logger.debug(text)
return value

Expand Down Expand Up @@ -108,8 +111,14 @@ def phys(self, value: Union[int, bool, float, str, bytes]):

@property
def desc(self) -> str:
"""Converts to and from a description of the value as a string."""
value = self.od.decode_desc(self.raw)
"""Convert to and from a description of the value as a string.

:raises TypeError: If the received raw data was anything but an integer value.
"""
raw_int = self.raw
if not isinstance(raw_int, int):
raise TypeError("Description of values only supported for integer objects")
value = self.od.decode_desc(raw_int)
logger.debug("Description is '%s'", value)
return value

Expand Down Expand Up @@ -146,7 +155,9 @@ def read(self, fmt: str = "raw") -> Union[int, bool, float, str, bytes]:
raise ValueError(f"Invalid format '{fmt}'")

def write(
self, value: Union[int, bool, float, str, bytes], fmt: str = "raw"
self,
value: Union[int, bool, float, str, bytes],
fmt: str = "raw",
) -> None:
"""Alternative way of writing using a function instead of attributes.

Expand All @@ -157,12 +168,15 @@ def write(
- 'raw'
- 'phys'
- 'desc'
:raises TypeError: If the "desc" format was specified with anything but a string value.
"""
if fmt == "raw":
self.raw = value
elif fmt == "phys":
self.phys = value
elif fmt == "desc":
if not isinstance(value, str):
raise TypeError("fmt=desc requires a string value")
self.desc = value


Expand Down
Loading