-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathT4_Maser_Comms.py
More file actions
430 lines (387 loc) · 13.2 KB
/
Copy pathT4_Maser_Comms.py
File metadata and controls
430 lines (387 loc) · 13.2 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
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
# -*- coding: utf-8 -*-
# =============================================================================
# %% Heading Info
# %%% Author Info
# Author: William W. Wallace
# Author Phone: +1-(304) 456-2216
# Author Email: wwallace@nrao.edu
# %%% Versioning
# Date of Creation: 2025-05-29
# Date of last Edit: 2025-06-05
# Purpose Of Script: to communicate with an i3000 T4 maser and return the
# resonce. In addition to decode the response from a MONIT command
# Update Log:
# %%%% v1.0.0
# Ready for distrobution
# %%%% V1.0.1
# Values with LSB gain of NaN are not installed in this maser model.
# Removing them from creating a dict entry
# in addition adding an option to return detailed or channel_values only in
# the dict.
# %% Command Line Entry Format
# T4_Maser_Comms.py 10.16.98.16 14000 "MONIT;\r\n" --retries 5 --timeout 2 --backoff 2 -C
#
# %% Module Imports
# =============================================================================
import argparse
import logging
import socket
import sys
import tkinter as tk
import numpy as np
from typing import Optional
from tkinter import messagebox
# %% Function & Class Definitions
def configure_logging(verbose: bool) -> None:
"""Configure logging based on verbosity level"""
level = logging.DEBUG if verbose else logging.INFO
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(message)s',
level=level
)
def show_error_dialog(title, message):
root = tk.Tk()
root.withdraw() # Hide the main window
messagebox.showerror(title, message)
root.destroy()
def validate_message(message: str) -> None:
"""Validate message content and length"""
if not isinstance(message, str):
raise ValueError("Message must be a string")
if not message.strip():
raise ValueError("Message cannot be empty or whitespace")
if len(message.encode('utf-8')) > 256:
raise ValueError("Message exceeds 256 byte limit")
def udp_communicate(
host: str,
port: int,
message: str,
retries: int = 3,
timeout: float = 5.0,
backoff_factor: float = 1.5
) -> Optional[str]:
"""
Communicate with UDP host with exponential backoff
Args:
host: Target host IP or hostname
port: Target port number
message: Message to send
retries: Number of retry attempts
timeout: Initial timeout in seconds
backoff_factor: Multiplier for timeout between retries
Returns:
Received response or None if all attempts fail
"""
validate_message(message)
buffersize = 256
current_timeout = timeout
with socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM) as sock:
for attempt in range(1, retries + 1):
try:
# seems one must bind the port to local port as well
sock.bind(('', port))
sock.settimeout(current_timeout)
sock.sendto(message.encode('utf-8'), (host, port))
# sock.sendto(message.encode(), (host, port))
logging.info(
f"Attempt {attempt}/{retries} sent to {host}:{port}")
response, addr = sock.recvfrom(buffersize)
logging.debug(f"Received {len(response)} bytes from {addr}")
sock.close()
# print(response.decode('utf-8'))
return response
except socket.timeout:
logging.warning(
f"Timeout after {current_timeout}s (attempt {attempt})")
current_timeout *= backoff_factor
sock.close()
except (socket.error, UnicodeDecodeError) as e:
logging.error(f"Communication error: {str(e)}")
sock.close()
break
logging.error(f"Failed after {retries} attempts")
return None
def decodeMONIT(input_str: str, channelValOnly: bool) -> Optional[dict]:
"""Take the received string from MONIT command and decodit it."""
# Tuples utilized in calculations from T4 Maser Operation Manual
# See page 47 of said manual
t4_channel_names = (
"U batt.A [V]",
"I batt. A [A]",
"U batt.B [V]",
"I batt. B [A]",
"Set. H [V]",
"Meas. H [V]",
"I purifier [A]",
"I dissociator [A]",
"H light [V]",
"IT heater [V]",
"IB heater [V]",
"IS heater [V]",
"UTC heater [V]",
"ES heater [V]",
"EB heater [V]",
"I heater [V]",
"T heater [V]",
"Boxes temp. [°C]",
"I Boxes [A]",
"Amb. Temp. [°C]",
"C field [V]",
"U varactor [V]",
"U HT ext. [Kv]",
"I HT ext. [uA]",
"U HT int. [kV]",
"I HT int. [uA]",
"Sto. press. [V]",
"Sto. heater [V]",
"Pir. heater [V]",
"UOCXO 100 MHz [V]",
"U 405 kHz [V]",
"U ocxo [V]",
"+24Vdc [V]",
"+15Vdc [V]",
"-15Vdc [V]",
"+5Vdc [V]",
"-5Vdc [V]",
"+8Vdc [V]",
"+18Vdc [V]",
"LOCK 100 MHz status",
"Lock status"
)
# t4_ADC_fs_counts = (
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 4096,
# 256,
# 256,
# 256,
# 256,
# 256,
# 256,
# 256,
# 256,
# 1
# )
t4_LSB_Gains = (
0.02441,
0.001221,
0.02441,
0.001221,
0.003662,
0.001221,
0.001221,
0.001221,
0.001221,
0.004883,
0.004883,
0.004883,
0.004883,
0.004883,
0.004883,
0.004883,
0.004883,
0.02441,
0.001221,
0.01221,
float('nan'),
0.002441,
0.001221,
0.1221,
0.001221,
0.1221,
0.004883,
0.006104,
0.006104,
0.002441,
0.003662,
0.002441,
0.09766,
0.07813,
-0.07813,
0.03906,
float('nan'),
0.03906,
float('nan'),
0.03906,
1
)
# Extract hex data after '$'
if input_str[0] == 'b' and len(input_str) == 118:
cleaned_str = input_str[2:-2] # Remove b' and trailing \r\n
elif input_str[0] == '$' and len(input_str) == 116:
cleaned_str = input_str[0:-2] # Remove \r\n
else:
cleaned_str = input_str[0:-2] # Remove\r\n
start_index = cleaned_str.find('$') + 1
hex_data = cleaned_str[start_index:].replace('\\r\\n', '')
# clean another trailing carriage return
hex_data = hex_data.replace('\\r\\', '')
decoded_dict = {}
try:
if len(hex_data) == 113:
# Process channels 0-31 (12 bits = 3 hex characters each)
for channel in range(32):
start = channel * 3
code = hex_data[start:start+3]
binWd = 4*3
decimalVal = int(code, 16)
binspec = '{fill}{align}{width}{type}'.format(
fill='0', align='>', width=binWd, type='b')
binaryVal = format(decimalVal, binspec)
channelVal = (
decimalVal * t4_LSB_Gains[channel]
)
if np.isnan(channelVal):
pass
elif channelValOnly:
decoded_dict[t4_channel_names[channel]] = channelVal
else:
decoded_dict[t4_channel_names[channel]] = {
'Original_Hex_Code': code,
'Binary_Value': binaryVal,
'Decimal_Value': decimalVal,
'Channel_Value': channelVal
}
# Process channels 32-39 (8 bits = 2 hex characters each)
for idx, channel in enumerate(range(32, 40)):
start = 96 + (idx * 2)
code = hex_data[start:start+2]
binWd = 4*2
decimalVal = int(code, 16)
binspec = '{fill}{align}{width}{type}'.format(
fill='0', align='>', width=binWd, type='b')
binaryVal = format(decimalVal, binspec)
channelVal = (
decimalVal * t4_LSB_Gains[channel]
)
if np.isnan(channelVal):
pass
elif channelValOnly:
decoded_dict[t4_channel_names[channel]] = channelVal
else:
decoded_dict[t4_channel_names[channel]] = {
'Original_Hex_Code': code,
'Binary_Value': binaryVal,
'Decimal_Value': decimalVal,
'Channel_Value': channelVal
}
# Process channel 40 (1 bit from first hex character's MSB)
if len(hex_data) == 113:
code = hex_data[112]
# bit = str((int(code, 16) >> 3) & 0b1)
channel = 40
binWd = 4*1
decimalVal = int(code, 16)
binspec = '{fill}{align}{width}{type}'.format(
fill='0', align='>', width=binWd, type='b')
binaryVal = format(decimalVal, binspec)
channelVal = (
decimalVal * t4_LSB_Gains[channel]
)
if channelValOnly:
decoded_dict[t4_channel_names[channel]] = channelVal
else:
decoded_dict[t4_channel_names[channel]] = {
'Original_Hex_Code': code,
'Binary_Value': binaryVal,
'Decimal_Value': decimalVal,
'Channel_Value': channelVal
}
# print(decoded_dict)
return decoded_dict
else:
raise ValueError("The truncated string returned from the MONIT " +
"Command is of the wrong length. It should be " +
"equal to 113. The current len(hex_data) " +
"is equal " +
"to " + str(len(hex_data)) + ".")
except ValueError as e:
show_error_dialog("Input Error", str(e))
logging.error(f"Validation error: {str(e)}")
sys.exit(1)
def main() -> Optional[str]:
"""Command-line interface entry point."""
parser = argparse.ArgumentParser(
description="UDP Client with Retry Logic",
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument("host", help="Target host IP address")
parser.add_argument("port", type=int, help="Target port number")
parser.add_argument("message", help="Message to send")
parser.add_argument("-r", "--retries", type=int, default=3,
help="Number of retry attempts")
parser.add_argument("-t", "--timeout", type=float, default=5.0,
help="Initial timeout in seconds")
parser.add_argument("-b", "--backoff", type=float, default=1.5,
help="Timeout multiplier between attempts")
parser.add_argument("-v", "--verbose", action="store_true",
help="Enable debug logging")
parser.add_argument("-C", "--channelValOnly", action="store_true",
help="Only store the calculated channel " +
"value in the returned dictionary.")
args = parser.parse_args()
configure_logging(args.verbose)
try:
response = udp_communicate(
args.host,
args.port,
args.message,
args.retries,
args.timeout,
args.backoff
)
# easy test case
# =============================================================================
# response = udp_communicate(
# '10.16.98.16',
# 14000,
# 'MONIT;\r\n',
# 5,
# 2,
# 2
# )
# =============================================================================
# Now lets make it human readable
channelVal_dict = decodeMONIT(response.decode('utf-8'),
args.channelValOnly)
return channelVal_dict
except ValueError as e:
logging.error(f"Validation error: {str(e)}")
sys.exit(1)
if response:
print(f"Server response: {response}")
return channelVal_dict
sys.exit(0)
else:
sys.exit(2)
if __name__ == "__main__":
main()