-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.py
More file actions
166 lines (139 loc) · 6.23 KB
/
Copy pathmain.py
File metadata and controls
166 lines (139 loc) · 6.23 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import sys
import logging
from core.modbus_client import ModbusClient
logging.basicConfig(level=logging.ERROR, format='%(levelname)s: %(message)s')
def run_cli():
def get_connection():
ip = input("Enter IP (default 127.0.0.1): ") or "127.0.0.1"
port = int(input("Enter Port (default 502): ") or "502")
unit = int(input("Enter Unit ID (default 1): ") or "1")
return ModbusClient(ip, port, unit)
def menu():
print("\n=== ModbusLens CLI ===")
print("1. Read Coils")
print("2. Read Discrete Inputs")
print("3. Read Holding Registers")
print("4. Read Input Registers")
print("5. Write Coil")
print("6. Write Register")
print("7. Write Multiple Coils")
print("8. Write Multiple Registers")
print("9. Exit")
def main_cli():
modbus = get_connection()
print("\nConnecting...")
if not modbus.connect():
print("[ERROR] Connection failed. Check IP/Port and try again.")
return
print("[OK] Connected")
try:
while True:
menu()
choice = input("Select option: ").strip()
try:
if choice == "1":
addr = int(input("Address: "))
count = int(input("Count: "))
data = modbus.read_coils(addr, count)
if data is None:
print("[ERROR] Failed to read coils")
else:
print(f"[OK] Result: {data}")
elif choice == "2":
addr = int(input("Address: "))
count = int(input("Count: "))
data = modbus.read_discrete_inputs(addr, count)
if data is None:
print("[ERROR] Failed to read discrete inputs")
else:
print(f"[OK] Result: {data}")
elif choice == "3":
addr = int(input("Address: "))
count = int(input("Count: "))
data = modbus.read_registers(addr, count)
if data is None:
print("[ERROR] Failed to read registers")
else:
print(f"[OK] Result: {data}")
elif choice == "4":
addr = int(input("Address: "))
count = int(input("Count: "))
data = modbus.read_input_registers(addr, count)
if data is None:
print("[ERROR] Failed to read input registers")
else:
print(f"[OK] Result: {data}")
elif choice == "5":
addr = int(input("Address: "))
val = int(input("Value (0/1): "))
success = modbus.write_coil(addr, bool(val))
print("[OK] Success" if success else "[ERROR] Failed")
elif choice == "6":
addr = int(input("Address: "))
val = int(input("Value: "))
success = modbus.write_register(addr, val)
print("[OK] Success" if success else "[ERROR] Failed")
elif choice == "7":
addr = int(input("Start Address: "))
values = input("Values (comma separated 0/1): ")
values = [bool(int(v.strip())) for v in values.split(",")]
success = modbus.write_coils(addr, values)
print("[OK] Success" if success else "[ERROR] Failed")
elif choice == "8":
addr = int(input("Start Address: "))
values = input("Values (comma separated integers): ")
values = [int(v.strip()) for v in values.split(",")]
success = modbus.write_registers(addr, values)
print("[OK] Success" if success else "[ERROR] Failed")
elif choice == "9":
print("Exiting...")
break
else:
print("[ERROR] Invalid choice")
except ValueError as e:
print(f"[ERROR] Input error: Please enter valid numbers. ({e})")
except Exception as e:
print(f"[ERROR] Error: {e}")
finally:
modbus.disconnect()
print("Disconnected")
main_cli()
def run_gui():
try:
from gui.main_window import main as gui_main
gui_main()
except ImportError as e:
print(f"GUI dependencies not available: {e}")
print("Make sure PySide6 is installed: pip install PySide6")
print("Install with: pip install PySide6")
sys.exit(1)
except SystemExit:
# GUI main() calls sys.exit(), so this is expected
pass
except Exception as e:
print(f"GUI failed to start: {e}")
print("\nTroubleshooting:")
print("- Make sure you're running on a system with graphical display")
print("- If in an IDE, try running from command line")
print("- For headless environments, use the CLI version: python main.py")
sys.exit(1)
def main():
if len(sys.argv) > 1 and sys.argv[1] == "--gui":
run_gui()
elif len(sys.argv) > 1 and sys.argv[1] in ["--help", "-h"]:
print("ModbusLens - Modbus Client/Server")
print("Usage:")
print(" python main.py # Run CLI version")
print(" python main.py --gui # Run GUI version")
print(" python main.py --help # Show this help")
elif len(sys.argv) > 1:
print(f"Unknown argument: {sys.argv[1]}")
print("ModbusLens - Modbus Client/Server")
print("Usage:")
print(" python main.py # Run CLI version")
print(" python main.py --gui # Run GUI version")
print(" python main.py --help # Show this help")
else:
run_cli()
if __name__ == "__main__":
main()