diff --git a/modbus_tk/modbus.py b/modbus_tk/modbus.py index f858e60..3fd5945 100644 --- a/modbus_tk/modbus.py +++ b/modbus_tk/modbus.py @@ -84,6 +84,7 @@ def __init__(self, timeout_in_sec, hooks=None): """Constructor: can define a timeout""" self._timeout = timeout_in_sec self._verbose = False + self._print_in_hex = False self._is_opened = False def __del__(self): @@ -93,6 +94,10 @@ def __del__(self): def set_verbose(self, verbose): """print some more log prints for debug purpose""" self._verbose = verbose + + def print_telegrams_in_hex(self, print_in_hex): + """print telegrams in hex format""" + self._print_in_hex = print_in_hex def open(self): """open the communication with the slave""" @@ -352,7 +357,7 @@ def execute( if retval is not None: request = retval if self._verbose: - LOGGER.debug(get_log_buffer("-> ", request)) + LOGGER.debug(get_log_buffer("-> ", request, self._print_in_hex)) self._send(request) call_hooks("modbus.Master.after_send", (self, )) @@ -364,7 +369,7 @@ def execute( if retval is not None: response = retval if self._verbose: - LOGGER.debug(get_log_buffer("<- ", response)) + LOGGER.debug(get_log_buffer("<- ", response, self._print_in_hex)) # extract the pdu part of the response response_pdu = query.parse_response(response) @@ -1077,7 +1082,7 @@ def _handle(self, request): """handle a received sentence""" if self._verbose: - LOGGER.debug(get_log_buffer("-->", request)) + LOGGER.debug(get_log_buffer("-->", request, self._print_in_hex)) # gets a query for analyzing the request query = self._make_query() @@ -1092,5 +1097,5 @@ def _handle(self, request): response = retval if response and self._verbose: - LOGGER.debug(get_log_buffer("<--", response)) + LOGGER.debug(get_log_buffer("<--", response, self._print_in_hex)) return response diff --git a/modbus_tk/utils.py b/modbus_tk/utils.py index 3d6be34..5d8c769 100644 --- a/modbus_tk/utils.py +++ b/modbus_tk/utils.py @@ -61,11 +61,14 @@ def flush_socket(socks, lim=0): raise Exception("flush_socket: maximum number of iterations reached") -def get_log_buffer(prefix, buff): +def get_log_buffer(prefix, buff, print_in_hex = False): """Format binary data into a string for debug purpose""" log = prefix for i in buff: - log += str(ord(i) if PY2 else i) + "-" + if print_in_hex == True: + log += format(i, '02x') + "-" + else: + log += str(ord(i) if PY2 else i) + "-" return log[:-1]