Reputation: 797
I have a pymodbus server running and I'd like to know if a client is connected to it that it is serving. Is there any way to do that? I can't see an obvious way.
I'm using the synchronous server:
pymodbus.server.sync.ModbusTcpServer
Upvotes: 3
Views: 1574
Reputation: 1
I'm not sure how to have a server publish its state in a publisher/subscriber pattern, but one way to ascertain whether a server is running is to poll it with a client. As was mentioned in the comments, setting up a logger from the logging module can also be useful.
The AsyncModbusTcpClient
class has a connected
attribute which is a bool value you can check. A True
value indicates that the server is running.
Here I've wrapped the client in a class to demonstrate that you can add any logic you care to to the boolean check.
from pymodbus.client import AsyncModbusTcpClient
class PymodbusAsyncClient():
def __init__(self, host, port=502):
self.host = host
self.port = port
self.client = AsyncModbusTcpClient(self.host, port=self.port)
async def connect(self) -> None:
await self.client.connect()
if self.client.connected:
print(f"Connected to Modbus server at {self.host}:{self.port}")
return True
return False`
# Server logging
logging.basicConfig(
filename="path/to/logfile/pymodbus_server.log",
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=logging.INFO,
)
# Run server
await StartAsyncTcpServer(context, identity=identity, address=("localhost", 502))
logging output:
2024-05-30 17:18:21,394 - pymodbus.logging - INFO - Server listening.
2024-05-30 17:18:30,370 - root -INFO - Connected to Modbus server at localhost:502`
Upvotes: 0