Repository navigation
Expand file tree
/
Copy pathServer.py
More file actions
535 lines (400 loc) · 16 KB
/
Copy pathServer.py
File metadata and controls
535 lines (400 loc) · 16 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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
######################################################################################################
# @author Mehrdad Zarei <mzarei@umk.pl>
# @date 2021.07.18
# @version 0
#
# @brief Server to get information from wavelength meter and DigiLock to send them to the clients
#
######################################################################################################
import json
import threading
import socket
import sys
import time
from datetime import datetime
from wlmConst import *
import wavelength_meter
import DigiLock
HEADER = 64
PORT = int(sys.argv[2])
SERVER = str(sys.argv[1])
# SERVER = socket.gethostbyname(socket.gethostname()) # for private server
ADDR = (SERVER, PORT)
FORMAT = "utf-8"
DISCONNECT_MESSAGE = "!DISCONNECT"
time_out = 60.0
wlm_state = True
# only one connection can connect to digi, others should be refused
digi_ip = "192.168.0.175"
digi_port = 60001
digi_update = False
digi_state = True
transfer_lock = 0 # 0 don't lock, 1 lock
digi_con = 0 # 0 not connected, 1 connected, 2 connecting
digi_err = 2 # 1 no error, 0 error, 2 hold on it is locking
ptp_lvl = 0.04
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
wlm = wavelength_meter.WavelengthMeter(dllpath = str(sys.argv[3]), WlmVer = int(sys.argv[4]))
digi = DigiLock.digiClient()
def my_send(conn, msg):
total_sent = 0
MSGLEN = len(msg)
send_length = str(MSGLEN).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
# print(send_length)
# waiting for reply
while True:
try:
msg_recv = conn.recv(1)
except Exception:
msg_recv = '0'
if msg_recv == '':
return -1
try:
if int(msg_recv) == 1:
break
elif int(msg_recv) == 0:
return 0
except Exception:
break
# send msg len
while total_sent < HEADER:
sent = conn.send(send_length[total_sent:])
if sent == 0:
return -1
total_sent += sent
# waiting for reply
while True:
try:
msg_recv = conn.recv(1)
except Exception:
msg_recv = '0'
if msg_recv == '':
return -1
try:
if int(msg_recv) == 1:
break
elif int(msg_recv) == 0:
return 0
except Exception:
break
# send msg
total_sent = 0
while total_sent < MSGLEN:
sent = conn.send(msg[total_sent:])
if sent == 0:
return -1
total_sent = total_sent + sent
# waiting for reply
while True:
try:
msg_recv = conn.recv(1)
except Exception:
msg_recv = '0'
if msg_recv == '':
return -1
try:
if int(msg_recv) == 1:
break
elif int(msg_recv) == 0:
return 0
except Exception:
break
return 1
def my_recv(conn):
chunks = []
bytes_recd = 0
try:
conn.send(bytes("1".encode(FORMAT)))
except Exception:
return '0'
# recv msg len
while bytes_recd < HEADER:
chunk = conn.recv(min(HEADER - bytes_recd, HEADER))
if chunk == '':
return '-1'
chunks.append(chunk.decode(FORMAT))
bytes_recd += len(chunk)
msg_len = ''.join(chunks)
# print(msg_len)
try:
MSGLEN = int(msg_len)
conn.send(bytes("1".encode(FORMAT)))
except :
conn.send(bytes("0".encode(FORMAT)))
return '0'
# print(MSGLEN)
chunks = []
bytes_recd = 0
# recv msg
while bytes_recd < MSGLEN:
chunk = conn.recv(min(MSGLEN - bytes_recd, 1024))
if chunk == '':
return '-1'
chunks.append(chunk.decode(FORMAT))
bytes_recd += len(chunk)
conn.send(bytes("1".encode(FORMAT)))
return ''.join(chunks)
def handle_digi():
global digi_ip, digi_port, digi_update, digi_state, transfer_lock, digi_con, digi_err, ptp_lvl
t1 = time.time()
while True:
# for the first time
if digi_con == 2:
digi_con = digi.connect(ip = digi_ip, port = digi_port)
print(digi_con)
if digi_con == 1:
first_lock = 0
upd_t = 2 # update every 2 s
t1 = time.time() # start timing
if digi_con == 1:
# refresh digilock connection every 100 s to avoid freezing
if (time.time() - t1) > 99:
digi.__del__()
time.sleep(1)
digi_con = digi.connect(ip = digi_ip, port = digi_port)
t1 = time.time() # restart timing
if transfer_lock == 1:
if first_lock == 0:
digi.set_peakTpeak(ptp = ptp_lvl)
digi_con = digi.setting()
if digi_con == 0:
continue
digi_err = 2 # don't do anything before locking which may takes long time
digi_con, err = digi.checking()
if digi_con == 0:
continue
# check digi_con maybe it is changed by operator
if err == 0 and digi_con == 1: # try one more time
digi_con, err = digi.checking()
if digi_con == 0:
continue
if err == 1 and digi_con == 1:
digi_con, err = digi.lock()
if digi_con == 0:
continue
if err == 0 and digi_con == 1: # try one more time
digi_con, err = digi.lock()
if digi_con == 0:
continue
digi_err = err
if digi_err == 0:
transfer_lock = 0
continue
first_lock = 1
digi.set_peakTpeak(ptp = ptp_lvl)
digi_err = 2 # don't do anything before returning from check_lock which may takes long time
digi_con, digi_err, upd_t = digi.check_lock()
if digi_con == 0:
continue
if digi_err == 0:
digi_update = True
time.sleep(1) # wait to send data
transfer_lock = 0
continue
else:
if first_lock == 1: # unlock if it was lock
digi_con = digi.unlock()
if digi_con == 0:
continue
first_lock = 0
time.sleep(upd_t)
# digi.__del__()
def handle_client(event, conn, addr):
now = datetime.now()
print(f"[NEW CONNECTION] {addr} connected at {now}")
conn.settimeout(time_out)
global wlm_state, digi_ip, digi_port, digi_update, digi_state, transfer_lock, digi_con, digi_err, ptp_lvl
connected = True
ch = 1
wlm_ch = 1
keep_ch = 0
prec = 5
switch_mode = -1
exp_mode = False
exp_up = -1
exp_down = -1
while connected:
try:
msg = my_recv(conn)
if msg == '0':
continue
elif msg == '-1':
connected = False
continue
# print(msg)
obj_send = {}
try:
obj_recv = json.loads(msg)
except :
obj_recv = {}
if "STATUS" in obj_recv and obj_recv["STATUS"] == DISCONNECT_MESSAGE:
connected = False
continue
if "WLM_RUN" in obj_recv and obj_recv["WLM_RUN"] == 1:
if wlm_state:
wlm_state = False
wlm.run(action = 'show') # show or hide
wlm.measurement(cCtrlStartMeasurement) # state : cCtrlStopAll, cCtrlStartMeasurement
if "RELOCKING" in obj_recv:
keep_ch = obj_recv["RELOCKING"]
# keep software on the same channel
if keep_ch == 0:
wlm_ch = wlm.getSwitcherChannel()
elif keep_ch == 2:
keep_ch = 0
if "CH" in obj_recv:
ch = obj_recv["CH"]
if ch < 1 or ch > 8:
ch = 1
else:
ch = wlm_ch
wlmSwitch_mode = wlm.getSwitcherMode()
# take changes from wavemeter
if wlmSwitch_mode != switch_mode:
switch_mode = wlmSwitch_mode
# apply changes from operator
elif "SWITCH_MODE" in obj_recv and obj_recv["SWITCH_MODE"] != switch_mode:
# 0 for single mode and 1 for switch mode
wlm.setSwitcherMode(obj_recv["SWITCH_MODE"])
switch_mode = obj_recv["SWITCH_MODE"]
if obj_recv["SWITCH_MODE"] == 1:
wlm.setSwitcherSignalStates(ch, 1, 0)
obj_send["SWITCH_MODE"] = switch_mode
wlm.setSwitcherChannel(ch)
wlmExp_auto = wlm.getExposureMode(ch)
# take changes from wavemeter
if wlmExp_auto != exp_mode:
exp_mode = wlmExp_auto
# apply changes from operator
elif "EXP_AUTO" in obj_recv and obj_recv["EXP_AUTO"] == 1:
wlm.setExposureMode(ch, True)
exp_mode = True
elif "EXP_AUTO" in obj_recv and obj_recv["EXP_AUTO"] == 0:
wlm.setExposureMode(ch, False)
exp_mode = False
if not exp_mode:
wlmExp_up = wlm.getExposure(ch, 1)
# take changes from wavemeter
if wlmExp_up != exp_up:
exp_up = wlmExp_up
# apply changes from operator
elif "EXP_UP" in obj_recv:
# mode 1 for interferometer
wlm.setExposure(ch, 1, obj_recv["EXP_UP"])
wlmExp_down = wlm.getExposure(ch, 2)
# take changes from wavemeter
if wlmExp_down != exp_down:
exp_down = wlmExp_down
# apply changes from operator
elif "EXP_DOWN" in obj_recv:
# mode 2 for wide interferometer
wlm.setExposure(ch, 2, obj_recv["EXP_DOWN"])
exp_up = wlm.getExposure(ch, 1)
exp_down = wlm.getExposure(ch, 2)
if (exp_up > 1000 or exp_down > 1000) and exp_mode:
wlm.setExposureMode(ch, False)
exp_mode = False
wlm.setExposure(ch, 1, 2)
exp_up = 2
wlm.setExposure(ch, 2, 2)
exp_down = 2
# change the numbers to str during transfer with json
obj_send["EXP_AUTO"] = 1 if exp_mode else 0
obj_send["EXP_UP"] = str(exp_up)
obj_send["EXP_DOWN"] = str(exp_down)
if "PREC" in obj_recv:
prec = obj_recv["PREC"]
if "WAVEL" in obj_recv and obj_recv["WAVEL"] == 1:
# to keep laset digit if it is 0, we should use format
# if your digits are variable use this
wavelength = f'{wlm.getWavelength(ch):.{prec}f}'
# wavelength = '{:.5f}'.format(round(wlm.getWavelength(ch), 6))
obj_send["WAVEL"] = wavelength
else:
obj_send["WAVEL"] = "None"
if "FREQ" in obj_recv and obj_recv["FREQ"] == 1:
# if your digits are variable use this
freq = f'{wlm.getFrequency(ch):.{prec}f}'
# freq = '{:.5f}'.format(round(wlm.getFrequency(ch), 6))
obj_send["FREQ"] = freq
else:
obj_send["FREQ"] = "None"
if "SPEC" in obj_recv and obj_recv["SPEC"] == 1:
spectrum_list = []
ratio, spectrum_list = wlm.spectrum(ch)
ratio = round(ratio, 4)
obj_send["RATIO"] = str(ratio)
obj_send["SPEC"] = spectrum_list
else:
obj_send["RATIO"] = "None"
# back to the same channel
if keep_ch == 0:
wlm.setSwitcherChannel(wlm_ch)
if "DIGI_RUN" in obj_recv and obj_recv["DIGI_RUN"] == 1:
lock = False
if not digi_update:
if "TRANSFER_LOCK" in obj_recv and transfer_lock == 0:
transfer_lock = obj_recv["TRANSFER_LOCK"]
digi_err = 2
if "TRANSFER_LOCK" in obj_recv and obj_recv["TRANSFER_LOCK"] == 0:
lock = True
if "PTP_LVL" in obj_recv:
ptp_lvl = obj_recv["PTP_LVL"]
if digi_state:
digi_state = False
if "DIGI_IP" in obj_recv:
digi_ip = obj_recv["DIGI_IP"]
if "DIGI_PORT" in obj_recv:
digi_port = obj_recv["DIGI_PORT"]
# assigning after ip, port
digi_con = 2 # connecting
digi_err = 2 # hold on
obj_send["DIGI_RUN"] = digi_con
if lock:
obj_send["TRANSFER_LOCK"] = 0 # if coming tranfer lock is 0 send back 0
else:
obj_send["TRANSFER_LOCK"] = digi_err
digi_update = False # change state after sending values
if digi_con == 0:
digi_state = True
obj_send["SEND"] = " "
data = json.dumps(obj_send)
message = data.encode(FORMAT)
err = my_send(conn, message)
if err == 0:
continue
elif err == -1:
connected = False
continue
except Exception as e:
now = datetime.now()
print(f"[ERROR] connection {addr} is closing with error at {now} for {e}")
conn.close()
return
# check for stop
if event.is_set():
break
now = datetime.now()
print(f"[CLOSING] connection {addr} is closing at {now}")
conn.close()
def start():
server.listen()
print(f"[LISTENING] Server is listening on ({SERVER}:{PORT})")
# start thread for DigiLock
#digi_thread = threading.Thread(target=handle_digi, args=())
#digi_thread.start()
while True:
conn, addr = server.accept()
# create the event
event = threading.Event()
thread = threading.Thread(target=handle_client, args=(event, conn, addr))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 2}") # there are already 2 connections (main and digi)
# event.set()
# # wait for the new thread to finish
# thread.join()
now = datetime.now()
print(f"[STARTING] server is starting at {now}")
start()