Repository navigation
Expand file tree
/
Copy pathmodbus_client.py
More file actions
84 lines (76 loc) · 3.1 KB
/
Copy pathmodbus_client.py
File metadata and controls
84 lines (76 loc) · 3.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import argparse
from pymodbus.client import ModbusTcpClient
def read_coil(ip, port, address):
try:
client = ModbusTcpClient(ip, port=int(port))
client.connect()
response = client.read_coils(int(address), count=10)
client.close()
if response.isError():
print("Error:", response)
else:
for index, value in enumerate(response.bits):
print(f"{index}: {value}")
except Exception as e:
print("Error:", e)
def write_coil(ip, port, address, value):
try:
client = ModbusTcpClient(ip, port=int(port))
client.connect()
response = client.write_coil(int(address), bool(int(value)))
client.close()
if response.isError():
print("Error:", response)
else:
print(f"Coil (value {value}) write successful to address {address}")
except Exception as e:
print("Error:", e)
def read_register(ip, port, address):
try:
client = ModbusTcpClient(ip, port=int(port))
client.connect()
response = client.read_holding_registers(int(address), count=10)
client.close()
if response.isError():
print("Error:", response)
else:
for index, value in enumerate(response.registers):
print(f"{index}: {value}")
except Exception as e:
print("Error:", e)
def write_register(ip, port, address, value):
try:
client = ModbusTcpClient(ip, port=int(port))
client.connect()
response = client.write_register(int(address), int(value))
client.close()
if response.isError():
print("Error:", response)
else:
print(f"Register (value {value}) write successful to address {address}")
except Exception as e:
print("Error:", e)
def main():
parser = argparse.ArgumentParser(description="Modbus TCP CLI Tool")
parser.add_argument("command", choices=["read_coil", "write_coil", "read_register", "write_register"], help="Modbus command to run")
parser.add_argument("--ip", required=True, help="Modbus server IP")
parser.add_argument("--port", required=True, help="Modbus server port")
parser.add_argument("--address", required=True, help="Register/Coil address")
parser.add_argument("--value", help="Value to write (only for write commands)")
args = parser.parse_args()
if args.command == "read_coil":
read_coil(args.ip, args.port, args.address)
elif args.command == "write_coil":
if args.value is None:
print("Error: --value is required for write_coil")
else:
write_coil(args.ip, args.port, args.address, args.value)
elif args.command == "read_register":
read_register(args.ip, args.port, args.address)
elif args.command == "write_register":
if args.value is None:
print("Error: --value is required for write_register")
else:
write_register(args.ip, args.port, args.address, args.value)
if __name__ == "__main__":
main()