Skip to content
Merged
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
2 changes: 1 addition & 1 deletion .pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ fail-on=
enable=
attribute-defined-outside-init,
fixme,
missing-docstring,
protected-access,
too-few-public-methods,
useless-suppression
Expand All @@ -89,7 +90,6 @@ disable=
duplicate-code,
invalid-name,
logging-too-many-args,
missing-docstring,
use-symbolic-message-instead,
format # handled by black

Expand Down
1 change: 1 addition & 0 deletions examples/common/async_tornado_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ def on_done(f):


def _print(value):
""" Internal print. """
if hasattr(value, "bits"):
result = value.bits
elif hasattr(value, "registers"):
Expand Down
1 change: 1 addition & 0 deletions examples/common/async_tornado_client_serial.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ def on_done(f):


def _print(value):
""" Internal print """
if hasattr(value, "bits"):
result = value.bits
elif hasattr(value, "registers"):
Expand Down
1 change: 1 addition & 0 deletions examples/contrib/thread_safe_datastore.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ def __init__(self):
self.writer = False # is there a current writer

def __is_pending_writer(self):
""" Internal is pending writer. """
return (self.writer # if there is a current writer
or (self.queue # or if there is a waiting writer
and (self.queue[0] != self.read_condition)))
Expand Down
8 changes: 1 addition & 7 deletions pymodbus/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"""

import logging as __logging
from logging import NullHandler as __null
import pymodbus.version as __version
__version__ = __version.version.short()
__author__ = 'Galen Collins'
Expand All @@ -19,11 +20,4 @@
#---------------------------------------------------------------------------#
# Block unhandled logging
#---------------------------------------------------------------------------#
try:
from logging import NullHandler as __null
except ImportError:
class __null(__logging.Handler): # pylint: disable=invalid-name
def emit(self, record):
pass

__logging.getLogger(__name__).addHandler(__null())
6 changes: 6 additions & 0 deletions pymodbus/client/asynchronous/async_io/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,7 @@ def _create_protocol(self):
return protocol

async def _connect(self):
""" Internal connect. """
_logger.debug('Connecting.')
try:
transport, protocol = await self.loop.create_connection(
Expand Down Expand Up @@ -311,6 +312,7 @@ def protocol_lost_connection(self, protocol):


async def _reconnect(self):
""" Internal reconnect. """
txt = f"Waiting {self.delay_ms} ms before next connection attempt."
_logger.debug(txt)
await asyncio.sleep(self.delay_ms / 1000)
Expand Down Expand Up @@ -528,6 +530,7 @@ def _create_protocol(self, host=None, port=0):


async def _connect(self):
""" Internal connect. """
_logger.debug('Connecting.')
try:
endpoint = await self.loop.create_datagram_endpoint(
Expand Down Expand Up @@ -571,6 +574,7 @@ def protocol_lost_connection(self, protocol):
'callback called while not connected.')

async def _reconnect(self):
""" Internal reconnect. """
txt = f"Waiting {self.delay_ms} ms before next connection attempt."
_logger.debug(txt)
await asyncio.sleep(self.delay_ms / 1000)
Expand Down Expand Up @@ -705,12 +709,14 @@ def stop(self):
self.protocol.transport.close()

def _create_protocol(self):
""" Internal create protocol. """
protocol = self.protocol_class(framer=self.framer)
protocol.factory = self
return protocol

@property
def _connected(self):
""" Internal connected. """
return self._connected_event.is_set()

async def connect(self):
Expand Down
4 changes: 4 additions & 0 deletions pymodbus/client/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ def trace(self, writeable):
self._debugfd = writeable

def _dump(self, data):
""" Internal dump. """
fd = self._debugfd if self._debugfd else sys.stdout
try:
fd.write(hexlify_packets(data))
Expand Down Expand Up @@ -218,6 +219,7 @@ def close(self):
self.socket = None

def _check_read_buffer(self):
""" Internal check read buffer. """
time_ = time.time()
end = time_ + self.timeout
data = None
Expand Down Expand Up @@ -656,6 +658,7 @@ def close(self):
self.socket = None

def _in_waiting(self):
""" Internal _in_waiting. """
in_waiting = ("in_waiting" if hasattr(
self.socket, "in_waiting") else "inWaiting")

Expand Down Expand Up @@ -699,6 +702,7 @@ def _send(self, request):
return 0

def _wait_for_data(self):
""" Internal wait for data. """
size = 0
more_data = False
if self.timeout is not None and self.timeout:
Expand Down
1 change: 1 addition & 0 deletions pymodbus/client/sync_diag.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ def _recv(self, size):
raise ConnectionException from exc

def _log_delayed_response(self, result_len, size, delay):
""" Internal log delayed response. """
if not size and result_len > 0:
_logger.info(self.timelimit_read_msg, delay, result_len)
elif ((not result_len) or (size and result_len < size)) and delay >= self.timeout:
Expand Down
1 change: 1 addition & 0 deletions pymodbus/datastore/database/sql_datastore.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ def _build_set(self, type, offset, values, prefix=''): # pylint: disable=no-self
return result

def _check(self, type, offset, values): #NOSONAR pylint: disable=unused-argument,redefined-builtin
""" Internal check. """
result = self._get(type, offset, count=1)
return False if len(result) > 0 else True # pylint: disable=simplifiable-if-expression

Expand Down
1 change: 1 addition & 0 deletions pymodbus/datastore/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,7 @@ def getValues(self, address, count=1):
return [self.values[i] for i in range(address, address + count)]

def _process_values(self, values):
""" Internal process values. """
def _process_as_dict(values):
for idx, val in iter(values.items()):
if isinstance(val, (list, tuple)):
Expand Down
2 changes: 2 additions & 0 deletions pymodbus/mei_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@


class _OutOfSpaceException(Exception):
""" Internal out of space exception. """
# This exception exists here as a simple, local way to manage response
# length control for the only MODBUS command which requires it under
# standard, non-error conditions. It and the structures associated with
Expand Down Expand Up @@ -133,6 +134,7 @@ def __init__(self, read_code=None, information=None, **kwargs):
self.space_left = None

def _encode_object(self, object_id, data):
""" Internal encode object. """
self.space_left -= (2 + len(data))
if self.space_left <= 0:
raise _OutOfSpaceException(object_id)
Expand Down
1 change: 1 addition & 0 deletions pymodbus/repl/client/completer.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ def arg_completions(self, words, word_before_cursor): # pylint: disable=unused-a
return cmd if cmd else None

def _get_completions(self, word, word_before_cursor):
""" Internal get completions. """
if self.ignore_case:
word_before_cursor = word_before_cursor.lower()
return self.word_matches(word, word_before_cursor)
Expand Down
6 changes: 6 additions & 0 deletions pymodbus/repl/client/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,15 @@ def __init__(self, name, signature, doc, unit=False):
self.args.update(**DEFAULT_KWARGS)

def _create_help(self):
""" Internal create help. """
doc = filter(lambda d: d, self.doc)
cmd_help = list(filter(
lambda x: not x.startswith(":param") and not x.startswith(
":return"), doc))
return " ".join(cmd_help).strip()

def _create_arg_help(self):
""" Internal create arg help. """
param_dict = {}
params = list(filter(lambda d: d.strip().startswith(":param"),
self.doc))
Expand Down Expand Up @@ -137,6 +139,7 @@ def __str__(self):


def _get_requests(members):
""" Internal get requests. """
commands = list(filter(lambda x: (x[0] not in EXCLUDE
and x[0] not in CLIENT_METHODS
and callable(x[1])),
Expand All @@ -151,6 +154,7 @@ def _get_requests(members):


def _get_client_methods(members):
""" Internal get client methods. """
commands = list(filter(lambda x: (x[0] not in EXCLUDE
and x[0] in CLIENT_METHODS),
members))
Expand All @@ -164,6 +168,7 @@ def _get_client_methods(members):


def _get_client_properties(members):
""" Internal get client properties. """
global CLIENT_ATTRIBUTES # pylint: disable=global-variable-not-assigned
commands = list(filter(lambda x: not callable(x[1]), members))
commands = {
Expand Down Expand Up @@ -260,6 +265,7 @@ def raw(self):
self.print_result()

def _process_dict(self, use_dict):
""" Internal process dict. """
new_dict = OrderedDict()
for k, v in use_dict.items():
if isinstance(v, bytes):
Expand Down
2 changes: 2 additions & 0 deletions pymodbus/repl/client/mclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ class ExtendedRequestSupport: # pylint: disable=(too-many-public-methods

@staticmethod
def _process_exception(resp, **kwargs):
""" Internal process exception. """
if not (unit := kwargs.get("unit")):
err = {
"message": "Broadcast message, ignoring errors!!!"
Expand Down Expand Up @@ -357,6 +358,7 @@ def get_com_event_log(self, **kwargs):
return ExtendedRequestSupport._process_exception(resp)

def _execute_diagnostic_request(self, request):
""" Internal execute diagnostic request. """
resp = self.execute(request) # pylint: disable=no-member
if not resp.isError():
return {
Expand Down
5 changes: 5 additions & 0 deletions pymodbus/server/async_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ def __init__(self, owner):
self.handler_task = None # coroutine to be run on asyncio loop

def _log_exception(self):
""" Internal log exception. """
if isinstance(self, ModbusConnectedRequestHandler):
txt = f"Handler for stream [{self.client_address[:2]}] has been canceled"
_logger.error(txt)
Expand Down Expand Up @@ -746,13 +747,16 @@ async def start(self):


def _protocol_factory(self):
""" Internal protocol factory. """
return self.handler(self)

async def _delayed_connect(self):
""" Internal delayed connect. """
await asyncio.sleep(self.reconnect_delay)
await self._connect()

async def _connect(self):
""" Internal connect. """
if self.reconnecting_task is not None:
self.reconnecting_task = None
try:
Expand Down Expand Up @@ -786,6 +790,7 @@ def on_connection_lost(self):
self._check_reconnect()

def _check_reconnect(self):
""" Internal check reconnect. """
txt = f"checking autoreconnect {self.auto_reconnect} {self.reconnecting_task}"
_logger.debug(txt)
if self.auto_reconnect and (self.reconnecting_task is None):
Expand Down
1 change: 1 addition & 0 deletions pymodbus/server/asynchronous.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,7 @@ def _send(self, message, addr):
# Starting Factories
# --------------------------------------------------------------------------- #
def _is_main_thread():
""" Internal is main thread. """
if threading.current_thread() != threading.main_thread():
_logger.debug("Running in spawned thread")
return False
Expand Down
1 change: 1 addition & 0 deletions pymodbus/server/reactive/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ def manipulator_config(self, value):
self._manipulator_config.update(**value)

def _add_routes(self):
""" Internal add routes. """
self._web_app.add_routes([
web.post('/', self._response_manipulator)])

Expand Down
5 changes: 5 additions & 0 deletions pymodbus/transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ def __init__(self, client, **kwargs):
self._set_adu_size()

def _set_adu_size(self):
""" Internal set adu size. """
# base ADU size of modbus frame in bytes
if isinstance(self.client.framer, ModbusSocketFramer):
self.base_adu_size = 7 # tid(2), pid(2), length(2), uid(1)
Expand All @@ -82,6 +83,7 @@ def _set_adu_size(self):
self.base_adu_size = -1

def _calculate_response_length(self, expected_pdu_size):
""" Internal calculate response length. """
if self.base_adu_size == -1:
return None
return self.base_adu_size + expected_pdu_size
Expand Down Expand Up @@ -226,6 +228,7 @@ def execute(self, request): #NOSONAR pylint: disable=too-complex

def _retry_transaction(self, retries, reason,
packet, response_length, full=False):
""" Internal retry transaction. """
txt = f"Retry on {reason} response - {retries}"
_logger.debug(txt)
_logger.debug("Changing transaction state from "
Expand Down Expand Up @@ -296,9 +299,11 @@ def _transact(self, packet, response_length, # pylint: disable=too-complex
return result, last_exception

def _send(self, packet, retrying=False): #NOSONAR pylint: disable=unused-argument
""" Internal send. """
return self.client.framer.sendPacket(packet)

def _recv(self, expected_response_length, full): #NOSONAR pylint: disable=too-complex
""" Internal receive. """
total = None
if not full:
exception_length = self._calculate_exception_length()
Expand Down
1 change: 1 addition & 0 deletions test/test_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from pymodbus.pdu import ModbusResponse, ModbusRequest

def _raise_exception(_):
""" Raise exception. """
raise ModbusException('something')

class SimpleFactoryTest(unittest.TestCase):
Expand Down