-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path#valves.py#
270 lines (215 loc) · 7.88 KB
/
#valves.py#
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
import time
import socket
import serial
from abc import ABC, abstractmethod
from utils import convert_com_port
class ValvesBase(ABC):
"""Base class for valve control implementing common valve logic.
Communication is abstracted through read/write methods that must be
implemented by subclasses.
"""
def __init__(self, gas_config, out_terminator="\r"):
"""Initialize the valve controller.
Args:
out_terminator (str): Command termination character [default: "\r"]
"""
self.out_terminator = out_terminator
self.gas_config = gas_config
@abstractmethod
def write(self, command: str) -> None:
"""Write a command to the valve controller.
Args:
command (str): Command to send
"""
pass
@abstractmethod
def read(self) -> str:
"""Read response from the valve controller.
Returns:
str: Response from the valve controller
"""
pass
def get_valve_position(self, valve):
"""Get the current position of a valve.
Args:
valve (str): Valve identifier (A-I)
Returns:
tuple: (valve_number, position_str)
"""
self.write(f"/{valve}CP")
current_position = self.read()
valve_no = current_position[1]
position = current_position[-2]
if position == "A":
return valve_no, "OFF"
elif position == "B":
return valve_no, "ON"
else:
return valve_no, "Unknown"
def display_valve_positions(self, valve=None):
"""Display positions of all valves or a specific valve.
Args:
valve (str, optional): Specific valve to display
"""
if valve:
valve_no, position = self.get_valve_position(valve)
print(f"Valve {valve_no} position is {position}")
else:
valves = ["A", "B", "C", "D", "E", "F", "G", "H", "I"]
for v in valves:
valve_no, position = self.get_valve_position(v)
print(f"Valve {valve_no} position is {position}")
def move_valve_to_position(self, valve, position):
"""Move a valve to the specified position.
Args:
valve (str): Valve identifier (A-I)
position (str): Target position ("ON" or "OFF")
"""
if position == "ON":
command = "CC"
elif position == "OFF":
command = "CW"
else:
print("Invalid position specified.")
return
self.write(f"/{valve}{command}")
time.sleep(0.3)
# Verify position
self.write(f"/{valve}CP")
new_position = self.read()[-2]
expected_position = "B" if position == "ON" else "A"
if new_position != expected_position:
self.write(f"/{valve}{command}")
def valve_actuation_message(self, valve, message=None):
"""Set valve actuation message mode.
Args:
valve (str): Valve identifier (A-I)
message (str, optional): Message mode ("no message", "short", "large")
"""
if message == "no message":
self.write(f"/{valve}IFM0")
elif message == "short":
self.write(f"/{valve}IFM1")
elif message == "large":
self.write(f"/{valve}IFM2")
else:
self.write(f"/{valve}IFM")
def commands_list(self, valve):
"""Get list of available commands for a valve.
Args:
valve (str): Valve identifier (A-I)
"""
self.write(f"/{valve}?")
return self.read()
def toggle_valve_position(self, valve):
"""Toggle the position of a valve.
Args:
valve (str): Valve identifier (A-I)
"""
self.write(f"/{valve}TO")
time.sleep(0.3)
return self.read()
def valve_controller_settings(self, valve):
"""Get controller settings for a valve.
Args:
valve (str): Valve identifier (A-I)
"""
self.write(f"/{valve}STAT")
return self.read()
def valve_actuation_time(self, valve):
"""Get actuation time for a valve.
Args:
valve (str): Valve identifier (A-I)
"""
self.write(f"/{valve}TM")
return self.read()
def valve_number_ports(self, valve):
"""Get number of ports for a valve.
Args:
valve (str): Valve identifier (A-I)
"""
self.write(f"/{valve}NP")
return self.read()
def feed_gas(self, gas_name: str) -> None:
"""Set valve positions to feed specified gas.
Args:
gas_name (str): Name of gas to feed (must match config file)
"""
if gas_name not in self.gas_config:
raise ValueError(f"Unknown gas: {gas_name}")
gas_settings = self.gas_config[gas_name]
if "valve_settings" not in gas_settings:
raise ValueError(f"No valve settings defined for gas: {gas_name}")
# Apply all valve settings for this gas
valve, position = gas_settings["valve_settings"]
self.move_valve_to_position(valve, position)
print(f"Feeding {gas_name}")
class SerialValves(ValvesBase):
"""Valve control over serial connection."""
def __init__(self, gas_config, port, baudrate=9600, **kwargs):
"""Initialize serial connection to valve controller.
Args:
port (str): Serial port
baudrate (int): Baud rate [default: 9600]
**kwargs: Additional arguments passed to ValvesBase
"""
super().__init__(gas_config, **kwargs)
self.ser = serial.Serial()
self.ser.baudrate = baudrate
self.ser.port = port
self.ser.timeout = 0.1
self.connect()
def connect(self):
"""Establish serial connection."""
if not self.ser.is_open:
self.ser.open()
else:
print(f"The Port is closed: {self.ser.portstr}")
def write(self, command):
"""Write command over serial connection."""
self.ser.write(f"{command}{self.out_terminator}".encode())
def read(self):
"""Read response from serial connection."""
return self.ser.readline().decode("utf-8").strip()
class EthernetValves(ValvesBase):
"""Valve control over Ethernet connection."""
def __init__(self, gas_config, host, port, **kwargs):
"""Initialize Ethernet connection to valve controller.
Args:
host (str): Host address
port (int): Port number
**kwargs: Additional arguments passed to ValvesBase
"""
super().__init__(gas_config, **kwargs)
self.host = host
self.port = port
def write(self, command):
"""Write command over Ethernet connection."""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self.host, self.port))
sock.sendall(f"{command}{self.out_terminator}".encode())
self._last_read = sock.recv(4096)
sock.close()
except Exception as e:
print(f"Failed to send command: {e}")
self._last_read = ""
def read(self):
"""Read response from Ethernet connection."""
response = self._last_read
self._last_read = ""
return response.decode().strip() if response else ""
def create_valves(io_config, gas_config):
"""Factory function to create appropriate valve controller instance.
Args:
config (dict): Configuration dictionary
Returns:
ValvesBase: Configured valve controller instance
"""
if "HOST_MOXA" not in io_config or "PORT_VALVES" not in io_config:
port = convert_com_port(io_config["COM_VALVE"])
return SerialValves(gas_config, port=port)
else:
return EthernetValves(
gas_config, host=io_config["HOST_MOXA"], port=io_config["PORT_VALVES"]
)