Skip to content

Commit

Permalink
Fixed string detection during notification callback
Browse files Browse the repository at this point in the history
  • Loading branch information
RobertoRoos committed Sep 13, 2024
1 parent c4a4e9a commit 0682e6c
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
9 changes: 6 additions & 3 deletions pyads/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,9 @@
adsSyncDelDeviceNotificationReqEx,
adsSyncSetTimeoutEx,
ADSError,
get_value_from_ctype_data,
type_is_wstring,
type_is_string,
)
from .structs import (
AmsAddr,
Expand Down Expand Up @@ -1019,9 +1022,9 @@ def parse_notification(
addressof(contents) + SAdsNotificationHeader.data.offset
)
value: Any
if plc_datatype == PLCTYPE_STRING:
# read only until null-termination character
value = bytearray(data).split(b"\0", 1)[0].decode("utf-8")
if type_is_string(plc_datatype) or type_is_wstring(plc_datatype):
# Re-use string parsing from pyads_ex: (but doesn't work for other types)
value = get_value_from_ctype_data(data, plc_datatype)

elif plc_datatype is not None and issubclass(plc_datatype, Structure):
value = plc_datatype()
Expand Down
6 changes: 5 additions & 1 deletion pyads/pyads_ex.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,11 @@ def get_value_from_ctype_data(read_data: Optional[Any], plc_type: Type) -> Any:
return None

if type_is_string(plc_type):
return read_data.value.decode("utf-8")
if hasattr(read_data, "value"):
return read_data.value.decode("utf-8")
return bytes(read_data).decode("utf-8").rstrip("\x00")
# `read_data.value` does not always exist, and without it all the null
# terminators needs to be removed after decoding

if type_is_wstring(plc_type):
# `read_data.value` also exists, but could be wrong - explicitly decode instead:
Expand Down

0 comments on commit 0682e6c

Please sign in to comment.