Skip to content

Runtime Error when init AsyncModbusTcpClient outside of an running event loop #2102

@PJ-Schulz

Description

@PJ-Schulz

Versions

  • Python: 3.11.7
  • OS: 22.04 (wsl)
  • Pymodbus: 3.6.6
  • Modbus Hardware (if used):

Pymodbus Specific

  • Client: tcp - async

Description

Hello, I found something which works in pymodbus 3.6.4 but not in 3.6.5, 3.6.6.

Previously in version 3.6.4 I could create the client outside of an async function started with asyncio. With the newer versions this is no longer possible. If the client is now created outside, a RuntimeError: no running event loop is raised.

The constructor itself is synchronous. I am surprised that I first have to create an asyncio event loop and then call the constructor.

I think the change came in this PR: #2046

Code and Logs

import asyncio
import pymodbus
from pymodbus.client import AsyncModbusTcpClient

pymodbus.pymodbus_apply_logging_config("DEBUG")

client = AsyncModbusTcpClient("127.0.0.1", 5020)

async def test_connection():
    await client.connect()
    await client.read_holding_registers(100, 10)

asyncio.run(test_connection())
Traceback (most recent call last):
  File "/home/philipp/repos/iiot-app-http-modbus-adapter/foobar.py", line 8, in <module>
    client = AsyncModbusTcpClient("127.0.0.1", 5020)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/philipp/repos/iiot-app-http-modbus-adapter/.venv/lib/python3.11/site-packages/pymodbus/client/tcp.py", line 72, in __init__
    ModbusBaseClient.__init__(
  File "/home/philipp/repos/iiot-app-http-modbus-adapter/.venv/lib/python3.11/site-packages/pymodbus/client/base.py", line 64, in __init__
    ModbusProtocol.__init__(
  File "/home/philipp/repos/iiot-app-http-modbus-adapter/.venv/lib/python3.11/site-packages/pymodbus/transport/transport.py", line 152, in __init__
    self.loop: asyncio.AbstractEventLoop = asyncio.get_running_loop()
                                           ^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: no running event loop

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions