internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: pymodbus-dev/pymodbus

Issue:
NameError: global name 'TimeoutError' is not defined
<!--
Please use the Pymodbus gitter channel at https://gitter.im/pymodbus_dev/Lobby or Stack Overflow(tag [pymodbus](https://stackoverflow.com/questions/tagged/pymodbus) for
support questions.

Before opening a new issue, make sure you do the following:
    * check that your issue isn't already filed: https://github.com/riptideio/pymodbus/issues
    * prepare a short, runnable example that reproduce the issue with the latest development version of Pymodbus
-->

### Versions

* Python: 2.7.13
* OS: GNU/Linux
* Pymodbus: 1.4.0

### Description

Pymodbus 1.4.0 raises a `NameError` when using Python 2 because `TimeoutError` was added in Python 3.3.

### Code and Logs

```python
  File "/usr/local/lib/python2.7/dist-packages/pymodbus/client/common.py", line 109, in read_holding_registers
    return self.execute(request)
  File "/usr/local/lib/python2.7/dist-packages/pymodbus/client/sync.py", line 85, in execute
    return self.transaction.execute(request)
  File "/usr/local/lib/python2.7/dist-packages/pymodbus/transaction.py", line 130, in execute
    result = self._recv(expected_response_length or 1024)
  File "/usr/local/lib/python2.7/dist-packages/pymodbus/transaction.py", line 189, in _recv
    except (TimeoutError, SerialException):
NameError: global name 'TimeoutError' is not defined

```



Discussion:

Resolving patch:
diff --git a/pymodbus/transaction.py b/pymodbus/transaction.py
--- a/pymodbus/transaction.py
+++ b/pymodbus/transaction.py
@@ -14,6 +14,12 @@
 from pymodbus.utilities  import checkLRC, computeLRC
 from pymodbus.compat import iterkeys, imap, byte2int
 
+# Python 2 compatibility.
+try:
+    TimeoutError
+except NameError:
+    TimeoutError = socket.timeout
+
 #---------------------------------------------------------------------------#
 # Logging
 #---------------------------------------------------------------------------#
@@ -186,7 +192,7 @@ def _recv(self, expected_response_length):
                             # If no response being recived there
                             # is no point in conitnuing
                             break
-                    except (TimeoutError, SerialException):
+                    except (TimeoutError, socket.timeout, SerialException):
                         break
                 else:
                     break


Test patch:
Repository: pymodbus-dev/pymodbus

Issue:
`client.async` sneaking in dependencies
In importing `client.async.asyncio`, `client.async.__init__` triggers `from pymodbus.client.async.deprecated.async` ([source](https://github.com/riptideio/pymodbus/blob/master/pymodbus/client/async/__init__.py)), which then imports twisted. Twisted is a fairly heavy dependency and is not needed to use asyncio.


Discussion:

Resolving patch:
diff --git a/pymodbus/client/async/__init__.py b/pymodbus/client/async/__init__.py
--- a/pymodbus/client/async/__init__.py
+++ b/pymodbus/client/async/__init__.py
@@ -31,4 +31,14 @@
     # For asyncio the actual client is returned and event loop is asyncio loop
 
 """
-from pymodbus.client.async.deprecated.async import *
+from pymodbus.compat import is_installed
+
+installed = is_installed('twisted')
+if installed:
+    # Import deprecated async client only if twisted is installed #338
+    from pymodbus.client.async.deprecated.async import *
+else:
+    import logging
+    logger = logging.getLogger(__name__)
+    logger.warning("Not Importing deprecated clients. "
+                   "Dependency Twisted is not Installed")
diff --git a/pymodbus/client/async/deprecated/__init__.py b/pymodbus/client/async/deprecated/__init__.py
--- a/pymodbus/client/async/deprecated/__init__.py
+++ b/pymodbus/client/async/deprecated/__init__.py
@@ -43,5 +43,5 @@
 """
 
 
-def deprecated(name): # pragma: no cover
+def deprecated(name):  # pragma: no cover
     warnings.warn(WARNING.format(name), DeprecationWarning)
diff --git a/pymodbus/compat.py b/pymodbus/compat.py
--- a/pymodbus/compat.py
+++ b/pymodbus/compat.py
@@ -58,6 +58,16 @@
     implements_to_string = lambda x: x
 
     byte2int = lambda b: b
+    if PYTHON_VERSION >= (3, 4):
+        def is_installed(module):
+            import importlib.util
+            found = importlib.util.find_spec(module)
+            return found
+    else:
+        def is_installed(module):
+            import importlib
+            found = importlib.find_loader(module)
+            return found
 # --------------------------------------------------------------------------- #
 # python > 2.5 compatability layer
 # --------------------------------------------------------------------------- #
@@ -76,3 +86,11 @@ def implements_to_string(klass):
         klass.__unicode__ = klass.__str__
         klass.__str__ = lambda x: x.__unicode__().encode('utf-8')
         return klass
+
+    def is_installed(module):
+        import imp
+        try:
+            imp.find_module(module)
+            return True
+        except ImportError:
+            return False
\ No newline at end of file


Test patch:
Repository: pymodbus-dev/pymodbus

Issue:
Pymodbus 2.2.0rc2 failing to read registers/coils
<!--
Please use the Pymodbus gitter channel at https://gitter.im/pymodbus_dev/Lobby or Stack Overflow(tag [pymodbus](https://stackoverflow.com/questions/tagged/pymodbus) for
support questions.

Before opening a new issue, make sure you do the following:
    * check that your issue isn't already filed: https://github.com/riptideio/pymodbus/issues
    * prepare a short, runnable example that reproduce the issue with the latest development version of Pymodbus
-->

### Versions

* Python: 2.7.12
* OS: OSX
* Pymodbus: 2.2.0rc2
* Modbus Hardware (if used):  NA

### Pymodbus Specific
* Server: tcp/rtu/ascii - sync/async --> all
* Client: tcp/rtu/ascii - sync/async  --> all

### Description
Basic operations on TCP to read coils/registers failing with `[Input/Output] No Response received from the remote unit/Unable to decode response`.
 The same code works just fine in earlier versions of pymodbus (2.2.0rc1 and below)
### Code and Logs

```python
 # code and logs here.

```



Discussion:

Resolving patch:
diff --git a/doc/conf.py b/doc/conf.py
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -45,7 +45,9 @@
 # Add any Sphinx extension module names here, as strings. They can be
 # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
 # ones.
-extensions = ['sphinx.ext.autodoc', 'm2r', 'recommonmark']
+
+#extensions = ['sphinx.ext.autodoc', 'm2r', 'recommonmark']
+extensions = ['sphinx.ext.autodoc', 'm2r']
 
 # Add any paths that contain templates here, relative to this directory.
 templates_path = ['_templates']
@@ -53,9 +55,9 @@
 # The suffix(es) of source filenames.
 # You can specify multiple suffix as a list of string:
 #
-source_parsers = {
-    '.md': CommonMarkParser,
-}
+#source_parsers = {
+#    '.md': CommonMarkParser,
+#}
 
 source_suffix = ['.rst', '.md']
 # source_suffix = '.rst'


Test patch:
Repository: pymodbus-dev/pymodbus

Issue:
Use pycryptodome instead of pycrypto.
<!--
Please use the Pymodbus gitter channel at https://gitter.im/pymodbus_dev/Lobby or Stack Overflow(tag [pymodbus](https://stackoverflow.com/questions/tagged/pymodbus) for
support questions.

Before opening a new issue, make sure you do the following:
    * check that your issue isn't already filed: https://github.com/riptideio/pymodbus/issues
    * prepare a short, runnable example that reproduce the issue with the latest development version of Pymodbus
-->

### Versions

* Python: 2.7.12
* OS: Ubuntu 18.04
* Pymodbus: 2.1.0 [twisted]
* Modbus Hardware (if used): 

### Pymodbus Specific
* Server: tcp - async

### Description

I am trying to use Mod bus server on TCP protocol, but when I installed pymodbus and I saw it's installed pycrypto, which is deprecated and dead software. 

I already have installed pycryptodome in my application, which is a conflict with pycrypto, 
we can't have both pycrypto and pycryptodome at the same time,

Can we have pymodbus[twisted] release which can use pycryptodome instead of pycrypto?


Discussion:
I am not sure of the amount of effort this might need, I would be glad to accept a PR if you can give a try with pycryptodome and can assure nothing breaks.
AFAICT twisted doesn't use PyCrypto? The most recent mention I can find in their repo is https://github.com/twisted/twisted/pull/953
Added pull request with changes in the setup file, which will allow installing Cryptodome instead Crypto.

Pull request #409 

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -85,7 +85,6 @@
         'twisted': [
             'twisted >= 12.2.0',
             'pyasn1 >= 0.1.4',
-            'pycrypto >= 2.6'
         ],
         'tornado': [
             'tornado >= 4.5.3'


Test patch:
Repository: pymodbus-dev/pymodbus

Issue:
Pymodbus 2.2.0rc2 failing to read registers/coils
<!--
Please use the Pymodbus gitter channel at https://gitter.im/pymodbus_dev/Lobby or Stack Overflow(tag [pymodbus](https://stackoverflow.com/questions/tagged/pymodbus) for
support questions.

Before opening a new issue, make sure you do the following:
    * check that your issue isn't already filed: https://github.com/riptideio/pymodbus/issues
    * prepare a short, runnable example that reproduce the issue with the latest development version of Pymodbus
-->

### Versions

* Python: 2.7.12
* OS: OSX
* Pymodbus: 2.2.0rc2
* Modbus Hardware (if used):  NA

### Pymodbus Specific
* Server: tcp/rtu/ascii - sync/async --> all
* Client: tcp/rtu/ascii - sync/async  --> all

### Description
Basic operations on TCP to read coils/registers failing with `[Input/Output] No Response received from the remote unit/Unable to decode response`.
 The same code works just fine in earlier versions of pymodbus (2.2.0rc1 and below)
### Code and Logs

```python
 # code and logs here.

```



Discussion:
Fixed with v2.2.0rc3

Resolving patch:
diff --git a/doc/conf.py b/doc/conf.py
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -45,7 +45,9 @@
 # Add any Sphinx extension module names here, as strings. They can be
 # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
 # ones.
-extensions = ['sphinx.ext.autodoc', 'm2r', 'recommonmark']
+
+#extensions = ['sphinx.ext.autodoc', 'm2r', 'recommonmark']
+extensions = ['sphinx.ext.autodoc', 'm2r']
 
 # Add any paths that contain templates here, relative to this directory.
 templates_path = ['_templates']
@@ -53,9 +55,9 @@
 # The suffix(es) of source filenames.
 # You can specify multiple suffix as a list of string:
 #
-source_parsers = {
-    '.md': CommonMarkParser,
-}
+#source_parsers = {
+#    '.md': CommonMarkParser,
+#}
 
 source_suffix = ['.rst', '.md']
 # source_suffix = '.rst'


Test patch:
Repository: pymodbus-dev/pymodbus

Issue:
Python modbus Unit decode
https://github.com/riptideio/pymodbus/blob/fbdc470ae3e138c50e3659ec4ec8ebf39df58936/pymodbus/client/asynchronous/twisted/__init__.py#L101

Always be 0 because all framers not return 'uid' but 'unit'

Create pythonpackage.yml
<!--  Please raise your PR's against the `dev` branch instead of `master` -->

Another typo length lenght
Apart the typos carried by my PR #480, I just noticed another one in pymodbus/framer/socket_framer.py (dev branch):
```
return dict(tid=tid, pid=pid, lenght=length, unit=uid, fcode=fcode)
```
Read RTU Holding Register through Serial Forwarder/TCP.
I have Energy Meter connected through RTU and able to get holding registers data through simple RTU Code. 
Now i want to make Convert this RTU to TCP through Forwarder. I want to send data to TCP which forwards the command to RTU and fetches data for me.

I have implement the Forwarder code just dont know how to fetch the holding register of RTU through it.

**Code for Simple RTU Read**

> import pymodbus
> from pymodbus.pdu import ModbusRequest
> from pymodbus.client.sync import ModbusSerialClient as ModbusClient 
> #initialize a serial RTU client instance
> from pymodbus.transaction import ModbusRtuFramer
> 
> #count= the number of registers to read
> #unit= the slave unit this request is targeting
> #address= the starting address to read from
> 
> client = ModbusClient(method = 'rtu', port='/dev/ttyUSB0', baudrate= 9600)
> 
> #Connect to the serial modbus server
>  connection = client.connect()
>  print(connection)
> 
> #Starting add, num of reg to read, slave unit.
> read  = client.read_holding_registers(address = 0x01,count =2, unit=1)
> data = read.registers
> 
> print(data)
> 
> #Closes the underlying socket connection
> client.close()


Discussion:

Resolving patch:
diff --git a/pymodbus/version.py b/pymodbus/version.py
--- a/pymodbus/version.py
+++ b/pymodbus/version.py
@@ -41,9 +41,7 @@ def __str__(self):
         return '[%s, version %s]' % (self.package, self.short())
 
 
-version = Version('pymodbus', 2, 4, 0, 'rc2')
-
-
+version = Version('pymodbus', 2, 4, 0)
 
 version.__name__ = 'pymodbus'  # fix epydoc error
 
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -84,14 +84,14 @@
                       'sphinx_rtd_theme',
                       'humanfriendly'],
         'twisted': [
-            'twisted >= 12.2.0',
+            'twisted >= 20.3.0',
             'pyasn1 >= 0.1.4',
         ],
         'tornado': [
-            'tornado >= 4.5.3'
+            'tornado == 4.5.3'
         ],
         'repl': [
-            'click>=6.7',
+            'click>=7.0',
             'prompt-toolkit==2.0.4',
             'pygments==2.2.0'
         ]


Test patch:
Repository: pymodbus-dev/pymodbus

Issue:
AttributeError: module 'asyncio' has no attribute 'exceptions'
```
Traceback (most recent call last):
  File "/home//.local/bin/pymodbus.server", line 6, in <module>
    from pymodbus.repl.server.main import server
  File "/home//.local/lib/python3.7/site-packages/pymodbus/repl/server/main.py", line 16, in <module>
    CANCELLED_ERROR = asyncio.exceptions.CancelledError
AttributeError: module 'asyncio' has no attribute 'exceptions'
```

in the code 

```
if IS_PYTHON3 and PYTHON_VERSION > (3, 7):
    CANCELLED_ERROR = asyncio.exceptions.CancelledError
else:
    CANCELLED_ERROR = asyncio.CancelledError

```
python 3.7 at least 3.7.3 doesn't have `asyncio.exceptions`
Maybe it was supposed to be >= 3.8.



Discussion:
This should've been `if IS_PYTHON3 and PYTHON_VERSION >= (3, 8):`.

Resolving patch:
diff --git a/pymodbus/repl/server/main.py b/pymodbus/repl/server/main.py
--- a/pymodbus/repl/server/main.py
+++ b/pymodbus/repl/server/main.py
@@ -3,7 +3,6 @@
 Copyright (c) 2020 by RiptideIO
 All rights reserved.
 """
-import sys
 import logging
 import asyncio
 import json
@@ -17,10 +16,7 @@
 from pymodbus.server.reactive.default_config import DEFUALT_CONFIG
 from pymodbus.repl.server.cli import run_repl
 
-if sys.version_info > (3, 7):
-    CANCELLED_ERROR = asyncio.exceptions.CancelledError
-else:
-    CANCELLED_ERROR = asyncio.CancelledError  # pylint: disable=invalid-name
+CANCELLED_ERROR = asyncio.exceptions.CancelledError
 
 
 @click.group("ReactiveModbusServer")


Test patch:
Repository: pymodbus-dev/pymodbus

Issue:
mask_write_register command processes partial responses
### Versions
* Python: 3.10.0
* OS: Win 10
* Pymodbus: 3.0.0.dev3 (also 2.5.3)
* Modbus Hardware (if used): Custom

### Pymodbus Specific
* Client: rtu - sync/async

### Description

The mask_write_register command processes partial responses resulting in error:

_Modbus Error: [Input/Output] No Response received from the remote unit/Unable to decode response_

The issue is traced back to the _class MaskWriteRegisterResponse_ which does not include the _get_response_pdu_size_ method.   As a result, the client does not wait for the full response and only the initial data in the receive buffer is processed.  A race condition results with unpredictable failures.     

Adding the following method to the class resolves the problem.

### Code and Logs

```python
def get_response_pdu_size(self):
    """
    Func_code (1 byte) + Starting Address (2 byte) + And_mask (2 Bytes) + OrMask (2 Bytes)
    :return:
    """
    return 1 + 2 + 2 + 2

```



Discussion:
@mickstevens1 thanks for reporting, would you mind raising a PR with your fix please?

Resolving patch:
diff --git a/pymodbus/register_write_message.py b/pymodbus/register_write_message.py
--- a/pymodbus/register_write_message.py
+++ b/pymodbus/register_write_message.py
@@ -109,6 +109,14 @@ def decode(self, data):
         """
         self.address, self.value = struct.unpack(">HH", data)
 
+    def get_response_pdu_size(self):  # pylint: disable=no-self-use
+        """Get response pdu size.
+
+        Func_code (1 byte) + Starting Address (2 byte) + And_mask (2 Bytes) + OrMask (2 Bytes)
+        :return:
+        """
+        return 1 + 2 + 2 + 2
+
     def __str__(self):
         """Return a string representation of the instance.
 


Test patch:
Repository: pymodbus-dev/pymodbus

Issue:
callback_server.py example error
<!--
Please use the Pymodbus gitter channel at https://gitter.im/pymodbus_dev/Lobby or Stack Overflow(tag [pymodbus](https://stackoverflow.com/questions/tagged/pymodbus) for
support questions.

Before opening a new issue, make sure you do the following:
    * check that your issue isn't already filed: https://github.com/riptideio/pymodbus/issues
    * prepare a short, runnable example that reproduce the issue with the latest development version of Pymodbus
-->

### Versions

* Python: 3.7
* OS: Ubuntu 20
* Pymodbus: 2.5.0
* Modbus Hardware (if used): 

### Pymodbus Specific
* Server: rtu - sync
* Client: rtu - sync

### Description

When I adapt the "callback_server.py" example, I make the queue client modify the datastore, but my client doesn't see the changes.
after some work, it's due to the use of Process creation for the queue listener that makes changes in it's own scope.

### Correction
change the queue Process listener creation :
```python
    p = Process(target=device_writer, args=(queue,))
    p.start()
```
by a Thread queue listenrer makes changes could be seen by my client because of modification made in the same server scope:
```python
from threading import Thread
...
     t = Thread(target = device_writer, args=(queue,))
    t.start()
```



Discussion:
This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.
This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.
This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.
This issue was closed because it has been stalled for 5 days with no activity.

Resolving patch:
diff --git a/examples/common/callback_server.py b/examples/common/callback_server.py
--- a/examples/common/callback_server.py
+++ b/examples/common/callback_server.py
@@ -7,7 +7,8 @@
 a device-mapping file.
 """
 import logging
-from multiprocessing import Queue, Process
+from multiprocessing import Queue
+from threading import Thread
 
 # --------------------------------------------------------------------------- #
 # import the modbus libraries we need
@@ -138,8 +139,8 @@ def run_callback_server():
     # ----------------------------------------------------------------------- #
     # run the server you want
     # ----------------------------------------------------------------------- #
-    proc = Process(target=device_writer, args=(queue,))
-    proc.start()
+    thread = Thread(target=device_writer, args=(queue,))
+    thread.start()
     StartTcpServer(context, identity=identity, address=("localhost", 5020))
 
 


Test patch:
Repository: pymodbus-dev/pymodbus

Issue:
AttributeError: 'NoneType' object has no attribute 'cancel' in pymodbus.server.asyncio
### Versions

* Python: 3.7
* OS: MacOS 10.15.1
* Pymodbus: 2.3.0

### Pymodbus Specific
* Server: tcp - asyncio

### Description

Launching a local asyncio server with verbose logging, connecting to it, and then disconnecting.

### Code and Logs

```python
import asyncio
from pymodbus.server.asyncio import StartTcpServer
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext

import logging

if __name__ == '__main__':
    logging.basicConfig()
    logging.getLogger().setLevel(logging.DEBUG)

    context = ModbusServerContext(slaves=ModbusSlaveContext(), single=True)
    asyncio.run(StartTcpServer(context, address=("localhost", 5020), defer_start=False))
```

Then connecting to the tcp socket and immediately disconnecting : 

```
DEBUG:pymodbus.server.asyncio:Datastore unable to fulfill request: 'NoneType' object has no attribute 'cancel'; Traceback (most recent call last):
  File ".../venv/lib/python3.7/site-packages/pymodbus/server/asyncio.py", line 82, in connection_lost
    self.handler_task.cancel()
AttributeError: 'NoneType' object has no attribute 'cancel'
```


Discussion:
Use `address=("0.0.0.0", 5020)` instead of `('localhost', 5020)`. That should solve this issue. 
Sorry for the delayed response.
This is a useful workaround, but don't you think the underlying issue deserves a fix ? `"localhost"` is a perfectly valid host. If you don't have the bandwidth to fix the issue now, maybe you can just leave it opened ?
I agree , that's is the reason why I have put the label as `enhancement`
This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.
This is still an issue.

Resolving patch:
diff --git a/pymodbus/server/async_io.py b/pymodbus/server/async_io.py
--- a/pymodbus/server/async_io.py
+++ b/pymodbus/server/async_io.py
@@ -115,7 +115,8 @@ def connection_lost(self, call_exc):
         socket itself will result in this call.
         """
         try:
-            self.handler_task.cancel()
+            if self.handler_task:
+                self.handler_task.cancel()
             if call_exc is None:
                 self._log_exception()
             elif hasattr(self, "client_address"):  # TCP connection


Test patch: