Last active
November 24, 2023 08:53
-
-
Save KevinRohn/0ea7c5456a8a3ffc2fa857854823f971 to your computer and use it in GitHub Desktop.
Quick and Dirty modbus Python request
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pymodbus.client import ModbusTcpClient | |
import time | |
host = '192.168.20.203' # Replace with the IP address of your Modbus server | |
port = 502 # Replace with the port number of your Modbus server | |
start_address = 250 # Replace with the starting address of the register you want to read | |
count = 10 # Number of registers to read | |
slaves = [1] # List of Slave IDs of the Modbus servers | |
client = ModbusTcpClient(host, port) | |
try: | |
if client.connect(): | |
print("Connected to Modbus Server") | |
total_elapsed_time = 0.0 # Total elapsed time for all requests | |
num_requests = 0 # Number of requests made | |
while True: | |
for slave in slaves: | |
start_time = time.time() | |
response = client.read_input_registers(start_address, count, slave) | |
elapsed_time = (time.time() - start_time) * 1000 # Calculate the elapsed time in milliseconds | |
total_elapsed_time += elapsed_time | |
num_requests += 1 | |
average_elapsed_time = total_elapsed_time / num_requests # Calculate the average elapsed time | |
if response.isError(): | |
print(f"Error reading registers for slave {slave}") | |
else: | |
print(f"Slave {slave} Response: {response.registers} | Took {elapsed_time:.2f} ms") | |
print(f"Average elapsed time over {num_requests} requests: {average_elapsed_time:.2f} ms") | |
time.sleep(0.000001) # Sleep for 100 microseconds before reading the registers again for the next slave | |
else: | |
print("Unable to connect to Modbus Server") | |
except KeyboardInterrupt: | |
print("Application is closing") | |
finally: | |
client.close() | |
print("Modbus Client Disconnected") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment