diff --git a/pyads/connection.py b/pyads/connection.py index bfe4a550..0e8da110 100644 --- a/pyads/connection.py +++ b/pyads/connection.py @@ -50,6 +50,7 @@ ads_type_to_ctype, PLCSimpleDataType, PLCDataType, + STRING_BUFFER, ) from .filetimes import filetime_to_dt from .pyads_ex import ( @@ -445,7 +446,7 @@ def get_all_symbols(self) -> List[AdsSymbol]: symbol_size_msg = self.read( ADSIGRP_SYM_UPLOADINFO2, ADSIOFFS_DEVDATA_ADSSTATE, - PLCTYPE_STRING, + PLCTYPE_STRING * STRING_BUFFER, return_ctypes=True, ) sym_count = struct.unpack("I", symbol_size_msg[0:4])[0] diff --git a/pyads/pyads_ex.py b/pyads/pyads_ex.py index c53d1380..aae756db 100644 --- a/pyads/pyads_ex.py +++ b/pyads/pyads_ex.py @@ -269,7 +269,8 @@ def get_value_from_ctype_data(read_data: Optional[Any], plc_type: Type) -> Any: return read_data.value.decode("utf-8") if type_is_wstring(plc_type): - return read_data.value # ctypes automatically decoded the string for us + # `read_data.value` also exists, but could be wrong - explicitly decode instead: + return bytes(read_data).decode("utf-16-le").rstrip("\x00") if type(plc_type).__name__ == "PyCArrayType": return list(read_data) @@ -857,9 +858,13 @@ def adsSyncReadReqEx2( if error_code: raise ADSError(error_code) - # If we're reading a value of predetermined size (anything but wstring, regular - # strings also contain size), validate that the correct number of bytes were read - if check_length and bytes_read.value != data_length.value: + # If we're reading a value of predetermined size (anything but strings, which can be shorted + # because of null-termination), validate that the correct number of bytes were read + if ( + check_length + and not (type_is_string(data_type) or type_is_wstring(data_type)) + and bytes_read.value != data_length.value + ): raise RuntimeError( "Insufficient data (expected {0} bytes, {1} were read).".format( data_length.value, bytes_read.value diff --git a/tests/test_connection_class.py b/tests/test_connection_class.py index 710eabab..9d1a8557 100644 --- a/tests/test_connection_class.py +++ b/tests/test_connection_class.py @@ -231,11 +231,9 @@ def test_read_string(self): # Assert that the server received the correct command self.assert_command_id(requests[0], constants.ADSCOMMAND_READ) - # The string buffer is 1024 bytes long, this will be filled with \x0F - # and null terminated with \x00 by our test server. The \x00 will get - # chopped off during parsing to python string type - expected_result = "\x0F" * 1023 - self.assertEqual(result, expected_result) + # We are reading only a single character, which the test-server defaults at 0 + expected_result = "\x00" + self.assertEqual(expected_result, result) def test_write_uint(self): value = 100 @@ -1451,7 +1449,7 @@ def test_read_wstring(self): var = PLCVariable( "wstr", expected1.encode("utf-16-le") + b"\x00\x00", - constants.ADST_WSTRING, "WSTRING" + constants.ADST_WSTRING, "WSTRING(80)" ) self.handler.add_variable(var)