forked from JMoVS/JUMP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMeasurementHardware.py
1653 lines (1416 loc) · 82.9 KB
/
MeasurementHardware.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
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""This is a module to implement the hardware side of the commands to send through the GPIB interface to the Measuremnt
hardware devices. It responds to predefined methods and returns correctly calculated values back to the
MeasurementDeviceController"""
__copyright__ = "Copyright 2015 - 2017, Justin Scholz"
__author__ = "Justin Scholz"
import time, datetime
from abc import ABCMeta, abstractmethod, abstractproperty
from importlib import import_module
import UserInput
import visa
from pyvisa.resources.gpib import GPIBInstrument # We want to set our dev individually so code completion works
from pyvisa.resources.messagebased import MessageBasedResource
def importer(device_class, idn_name_to_import, idn_alias_to_import):
"""
Imports device serials and names gracefully so you don't have to have serial files for devices you don't own. It
receives the expected
:param device_class: the name of the serial file as string
:param idn_name_to_import: the name of the device-name in the serial file as string
:param idn_alias_to_import: the name of the device-alias in the serial file as string
:return: idn_alias_to_import, idn_alias_to_import
"""
try:
import_name = "Device_Serials." + device_class
dev_information = import_module(import_name)
idn_name_to_import = getattr(dev_information, idn_name_to_import)
idn_alias_to_import = getattr(dev_information, idn_alias_to_import)
except ImportError:
idn_name_to_import = ["Device Serial file not present"]
idn_alias_to_import = "Device Serial file not present"
return idn_name_to_import, idn_alias_to_import
class MeasurementDeviceController:
"""The purpose of the MeasurementDeviceController is to abstract the hardware away from the measurement logic. It
shouldn't matter whether it is an Alpha Analyzer or something else. Therefore this module will create objects
for the respective hardware python class and send commands there.
MeasurementDeviceController objects adhere to standard methods to be controlled by other objects to provide
an abstract way of accessing the hardware
"""
def __init__(self, resource_manager: visa.ResourceManager):
"""init method should ready a list of devices with their accompanying *IDN? information. These answers will be
stored in the idn_list[] variable"""
self.dev_resource_manager = resource_manager
self.recognized_devs = []
self.mes_device = None
""":type :MeasurementDevice"""
self.select_device()
self.initialize_device()
self.name = self.mes_device.idn_alias
return
def _create_list_of_connected_devs(self):
list_of_resources = self.dev_resource_manager.list_resources_info(query='?*::INSTR')
self.idn_list = []
for instrument in list_of_resources:
instrument_instance = self.dev_resource_manager.open_resource(instrument)
""":type :MessageBasedResource"""
# set the communication time out so it doesn't wait 2.5 seconds per device! This value is in milliseconds
instrument_instance.timeout = 50
try:
self.idn_list.append((instrument, instrument_instance.query('*IDN?')))
except visa.VisaIOError:
try:
# Agilent/HP3458A doesn't adhere to standards. That's why we need to do this here
instrument_instance.write("END ALWAYS")
self.idn_list.append((instrument, instrument_instance.query('ID?')))
except visa.VisaIOError:
pass
instrument_instance.close()
self.idn_list.append((None,"NIMaxScreenshots"))
def initialize_device(self):
"""method to initialize the device to be ready for measurement"""
self.mes_device.initialize_instrument()
return
def check_controlable_for_compatibility(self, controlable_to_be_changed, list_of_values_of_controlable: []):
"""Checks the actual_controlable list with the hardware and returns a modified actual_controlable list if necessary
:param list_of_values_of_measurable: []
:return: hardware_possible_values_for_measurable
"""
hardware_possible_values_for_measurable = []
for controlable_value in list_of_values_of_controlable:
actual_controlable = self.mes_device.set_controlable(controlable_to_be_changed, controlable_value)
hardware_possible_values_for_measurable.append(actual_controlable)
return hardware_possible_values_for_measurable
def measure_measurable(self, measurable_to_measure):
"""
:param measurable_to_measure: The specific measurable the device should measure. In case of an ALPHA for
example, it's irrelevant as it will only ever measure frequency response right now. But a temperature
controller has different sensors so we may want to check sensor A or sensor B
:return: [[descriptor_for_results],[list_of_results_according_to_descriptor_of_results]
descriptor_for_results: a list containing descriptors what measured_1 and measured_2 are (eg R and X)
measured_freq: one may send one frequency to the device, but the measurementDevice may choose to measure a
different one. Here we state (if possible and returned) the actual one
"""
return self.mes_device.measure_measurable(measurable_to_measure)
def set_controlable(self, dev_controlable_dict: dict):
result_dict = self.mes_device.set_controlable(dev_controlable_dict)
return result_dict
@property
def controlables(self):
return self.mes_device.controlables
@property
def measurables(self):
return self.mes_device.measurables
def _detect_devices(self):
self._create_list_of_connected_devs()
mes_dev_choos_helper = MeasurementDeviceChooser()
for item in self.idn_list:
self.recognized_devs = mes_dev_choos_helper.detect_devices(item[0], item[1])
def select_device(self):
self.recognized_devs.clear()
self._detect_devices()
mes_dev_choos_helper = MeasurementDeviceChooser()
failed = False
if len(self.recognized_devs) == 0:
failed = True
elif len(self.recognized_devs) == 1:
print("Recognized the following measurement device. Do you want to select this?")
print(self.recognized_devs[0][1])
question = {"question_title": "1 device detected",
"question_text": "The device " + self.recognized_devs[0][2] + " was detected. Select?",
"default_answer": True, "optiontype": "yes_no"}
answer = UserInput.ask_user_for_input(question)["answer"]
if answer:
mes_dev_choos_helper.select_device(self.recognized_devs[0], self.dev_resource_manager)
self.mes_device = mes_dev_choos_helper.mes_device
else:
failed = True
elif len(self.recognized_devs) > 1:
valid_options = []
for index, instrument in enumerate(self.recognized_devs):
valid_options.append(instrument[2])
question = {"question_title": "Detected devices",
"question_text": "{0} measurement devices were found. "
"Which one do you want to use?".format(len(self.recognized_devs)),
"default_answer": 0,
"optiontype": "multi_choice",
"valid_options": valid_options}
answer = UserInput.ask_user_for_input(question)["answer"]
mes_dev_choos_helper.select_device(self.recognized_devs[answer], self.dev_resource_manager)
self.mes_device = mes_dev_choos_helper.mes_device
if failed:
UserInput.post_status("no measurement devices recognized")
UserInput.post_status("The hardware is reporting to be:")
iterator = 0
for dev in self.idn_list:
# We have to remove the last 2 characters or else it won't display (last characters are \x00\r)
UserInput.post_status("#{0}: {1}: {2}".format(iterator, dev[0], (dev[1][:-2])))
iterator += 1
UserInput.confirm_warning("Please retry detecting devices and make sure all "
"hardware connectors are plugged in tightly.")
self.select_device()
################################################
class MeasurementDevice(metaclass=ABCMeta):
"""This can be considered as the general layout of all the hardware device classes. These methods will always be present but may
return False if they are not implemented
:type mes_device : MeasurementDevice
"""
# We need this so device detection of multiple devices works
# This will later be set to the user chosen device idn
idn_name = "Something should be here"
def __init__(self):
self.recognized_devs = []
self.mes_device = None
self.visa_instrument = None
self.res_man = None
"""":type : visa.ResourceManager"""
self.measurables = []
self.controlables = []
self.idn_alias = None
@abstractmethod
def initialize_instrument(self):
return
@abstractmethod
def detect_devices(self, instrument: visa.Resource, name_of_dev: str):
return
@abstractmethod
def select_device(self, recognized_dev: [], resource_manager: visa.ResourceManager):
return
@abstractmethod
def measure_measurable(self, measurable_to_measure):
"""
:return:
"""
return
@abstractmethod
def set_controlable(self, controlables_dict: {}):
return controlables_dict
def set_visa_dev(self, instrument: visa.Resource, resource_manager: visa.ResourceManager):
self.visa_instrument = resource_manager.open_resource(instrument)
return
class ALPHA(MeasurementDevice):
"""The class for the hardware command implementation of the Alpha Analyzer """
idn_name_Alpha, idn_alias_Alpha = importer("ALPHA", "idn_name_Alpha", "idn_alias_Alpha")
measurables = ["RX"]
controlables = ["expected_freq"]
def select_device(self, should_be_selected_dev: [], resource_manager: visa.ResourceManager):
for Alpha_ID in self.idn_name_Alpha:
if Alpha_ID in should_be_selected_dev[1]:
self.mes_device = ALPHA()
self.mes_device.visa_instrument = None
""":type :MessageBasedResource"""
self.mes_device.idn_name = Alpha_ID
self.mes_device.idn_alias = self.idn_alias_Alpha
self.mes_device.set_visa_dev(should_be_selected_dev[0], resource_manager)
self.mes_device.controlables = ALPHA.controlables
self.mes_device.measurables = ALPHA.measurables
super().select_device(should_be_selected_dev, resource_manager)
def detect_devices(self, instrument: visa.Resource, name_of_dev: str):
for name in self.idn_name_Alpha:
if name in name_of_dev:
self.recognized_devs.append((instrument, name, self.idn_alias_Alpha))
super().detect_devices(instrument, name_of_dev)
def initialize_instrument(self):
"""This will initialize the visa dev and if necessary, ask the user about his choosing if there are options.
"""
self.visa_instrument.write("*RST") # soft reset
successful = False
while not successful:
try:
successful = self._command_status_parsing(self.visa_instrument.query("*IDN?"))[0] # we may have to wait
# a little
except visa.VisaIOError:
time.sleep(0.1)
time.sleep(1)
result = self.visa_instrument.query("MODE=IMP") # Impedance measurement mode
if not ALPHA._command_status_parsing(result)[0]:
print(result[1])
print("You should probably start over.")
result = self.visa_instrument.query("ZLLCOR=1") # Enable low loss correction
if not ALPHA._command_status_parsing(result)[0]:
print(result[1])
print("Failed to set low loss correction.")
self._set_measurement_mode() # We want to know whether it's 2,3 or 4 point measurement mode
self._set_driven_shield() # Driven shields?
self._calibrate_alpha() # Calibration?
self._connection_check() # Connection check necessary/wanted?
self._activate_short_load() # activate short load?
self._activate_reference_measurement() # Activate reference measurement?
successful_execution = False
while not successful_execution:
question = {"question_title": "Excitation voltage",
"question_text": "Please enter an excitation voltage between 0 and 3 V. Maximum accuracy is 0.1 V.",
"default_answer": 1.0,
"optiontype": "free_choice",
"valid_options_lower_limit": 0.0,
"valid_options_upper_limit": 3.0,
"valid_options_steplength": 1e1}
answer = UserInput.ask_user_for_input(question)["answer"]
successful_execution = self._set_ac_excitation_voltage(answer)
self._set_minimum_measurement_time() # Set default minimum measurement time (0.5s)
def measure_measurable(self, measurable_to_measure):
"""
:param measurable_to_measure: not used in ALPHA, we always measure frequency right now
:return: result. In case of ALPHA: {"R": measured_R, "X": measured_X,
"freq": measured_freq,"successful": successful_measurement, "message": message}
"""
# Start the measurement!
self.visa_instrument.write("MST")
# None means here that we wait indefinitely!! (23 day measurements for the win!! ;-) )
self.visa_instrument.wait_for_srq(None)
# get the measurement data
response = self.visa_instrument.query("ZRE?")
successful_execution, message = ALPHA._command_status_parsing(response)
if not successful_execution:
print(message)
print("Couldn't measure the frequency.")
# TODO: THis could probably be changed to just use .query_asci_values to not have to parse manually
successful_measurement, message, measured_R, measured_X, measured_freq = self._parse_results(response)
if not successful_measurement:
print(message)
# we shouldn't save incorrect measurement data # TODO: Should we really be that hard?!
measured_R = None
measured_X = None
measured_freq = None
result = {"R": measured_R, "X": measured_X, "freq": measured_freq, "successful_alpha": successful_measurement,
"message_alpha": message, "time_alpha": time.strftime("%d.%m.%Y %H:%M:%S")}
return result
def set_controlable(self, controlable_dict: {}):
"""
:param controlable_dict: {"expected_freq": 1.3}, a dictionary containing the identifier and the new value
:return: controlable_dict with the actual value
"""
self.visa_instrument.write("GFR=" + str(controlable_dict["expected_freq"]))
response = self.visa_instrument.query("GFR?")
successful_execution, message = ALPHA._command_status_parsing(response)
freq = 0
if not successful_execution:
UserInput.post_status(message)
UserInput.post_status("Couldn't get accurate frequency.")
else:
# this is ugly code and probably, all of the ALPHA should change to query_asci_values...
gfr, freq = message.split(sep="=")
freq = float(freq)
return {"expected_freq": freq}
def _set_measurement_mode(self):
"""Asks the user which measurement mode he prefers and sets it accordingly
"""
self.measurement_mode = int
question = {"question_title": "Measurement Mode",
"question_text": "Please choose which measurement mode to use", "default_answer": 2,
"optiontype": "multi_choice", "valid_options": ["2-point", "3-point", "4-point"]}
self.measurement_mode = 2 + UserInput.ask_user_for_input(question)["answer"]
# The ALPHA accepts 2, 3 or 4 as value, the standard return is 0,1 or 2 so we have to add 2
response = self.visa_instrument.query("FRS=" + str(self.measurement_mode)) # Actually set the measurement mode
successful_execution, message = ALPHA._command_status_parsing(response)
if not successful_execution:
UserInput.post_status(message)
UserInput.post_status("We failed to set the measurement mode. Something is wrong. "
"Is the ZG4 or POT/GAL connected properly?")
def _set_driven_shield(self):
""" Ask the user for preference and set driven shield yes/no
"""
self.driven_shield = (int, int)
question = {"question_title": "Driven shields",
"question_text": "Do you want to use driven shields?", "default_answer": 0,
"optiontype": "multi_choice",
"valid_options": ["no", "yes: Drive V high shield", "yes: Drive V low shield",
"yes: Drive both shields"]}
answer = UserInput.ask_user_for_input(question)["answer"]
if answer == 0:
self.driven_shield = (0, 0)
elif answer == 1:
self.driven_shield = (1, 0)
elif answer == 2:
self.driven_shield = (0, 1)
elif answer == 3:
self.driven_shield = (1, 1)
response = self.visa_instrument.query("DRS=" + str(self.driven_shield[0]) + " " + str(self.driven_shield[1]))
successful_execution, message = ALPHA._command_status_parsing(response)
if not successful_execution:
UserInput.post_status(message)
UserInput.post_status("Driven shield mode couldn't be set!")
def _calibrate_alpha(self):
""" This method asks about the ALPHA specific calibration preferences (no, fast, full or short_load)
"""
self.was_calibrated = int # 0 = no, 1 = fast calibration, 2 = full calibration, 3 = short load calibration
question = {"question_title": "Calibration",
"question_text": "Calibrate this black Alpha box?",
"default_answer": 0,
"optiontype": "multi_choice",
"valid_options": ["no calibration", "fast calibration (recommended)",
"full calibration (approximately 30-60 minutes)",
"Perform low impedance short-load calibration"]}
answer = UserInput.ask_user_for_input(question)["answer"]
if answer == 0: # no calibration (default)
self.was_calibrated = 1
UserInput.post_status("No calibration was done.")
elif answer == 1: # fast calibration
# Due to the infamous ALPHA bug, we set the measurement mode to 2-point first:
response = self.visa_instrument.query("FRS=2")
successful_execution, message = ALPHA._command_status_parsing(response)
if not successful_execution:
UserInput.post_status(message)
UserInput.post_status("Couldn't set measurement mode to 2-point for calibration. Please start over.")
# Now calibrate
response = self.visa_instrument.query("ZRUNCAL=REF_INIT")
successful_execution, message = ALPHA._command_status_parsing(
response) # TODO: Check behaviour here with the query
if not successful_execution:
UserInput.post_status(message)
UserInput.post_status("Couldn't initialize the Calibration. Please restart the program.")
UserInput.confirm_warning("Please disconnect all cables that could cause an impedance!")
self.visa_instrument.write("ZRUNCAL=REF") # this command should be checked for with a srq:
UserInput.post_status("Please wait a moment. Started at: " + time.strftime("%c"))
self.visa_instrument.wait_for_srq(None)
response = self.visa_instrument.read()
successful_execution, message = ALPHA._command_status_parsing(response)
if not successful_execution:
UserInput.post_status(message)
UserInput.post_status("Couldn't perform fast calibration.")
else:
self.was_calibrated = 2
UserInput.post_status("Calibration succeeded")
response = self.visa_instrument.query("FRS=" + str(self.measurement_mode))
successful_execution, message = ALPHA._command_status_parsing(response)
if not successful_execution:
UserInput.post_status(message)
UserInput.post_status("We failed to set the measurement mode. Something is wrong. "
"Is the ZG4 or POT/GAL connected properly?")
elif answer == 2: # full calibration
# Due to the infamous ALPHA bug, we set the measurement mode to 2-point first:
response = self.visa_instrument.query("FRS=2")
successful_execution, message = ALPHA._command_status_parsing(response)
if not successful_execution:
UserInput.post_status(message)
UserInput.post_status("Couldn't set measurement mode to 2-point for calibration. Please start over.")
# Now calibrate
response = self.visa_instrument.query("ZRUNCAL=ALL_INIT")
successful_execution, message = ALPHA._command_status_parsing(
response) # TODO: Check behaviour here with the query
if not successful_execution:
UserInput.post_status(message)
UserInput.post_status("Couldn't initialize the Calibration. Please restart the program.")
UserInput.confirm_warning("Please disconnect all cables that could cause an impedance!")
self.visa_instrument.write("ZRUNCAL=ALL")
UserInput.post_status("This can take up to an hour. No status update will be shown. Please be patient!")
UserInput.post_status("Calibration started at: " + time.strftime("%c"))
self.visa_instrument.wait_for_srq(None)
response = self.visa_instrument.read()
successful_execution, message = ALPHA._command_status_parsing(response)
if not successful_execution:
UserInput.post_status(message)
UserInput.post_status("Couldn't perform Calibration. Please start over")
else:
self.was_calibrated = 3
UserInput.post_status("Calibration succeeded")
response = self.visa_instrument.query("FRS=" + str(self.measurement_mode))
successful_execution, message = ALPHA._command_status_parsing(response)
if not successful_execution:
UserInput.post_status(message)
UserInput.post_status("We failed to set the measurement mode. Something is wrong. "
"Is the ZG4 or POT/GAL connected properly?")
elif answer == 3: # short load calibration
response = self.visa_instrument.query("ZRUNCAL=SL_INIT")
successful_execution, message = ALPHA._command_status_parsing(response)
if not successful_execution:
UserInput.post_status(message)
UserInput.post_status("Couldn't initialize low impedance short load calibration. "
"Try restarting the program and the ALPHA!")
UserInput.confirm_warning("Please connect the short calibration standard.")
self.visa_instrument.write("ZRUNCAL=SL_SHORT") # again, srq method
UserInput.post_status("Calibrating short load. Started at: " + time.strftime("%c"))
self.visa_instrument.wait_for_srq()
response = self.visa_instrument.read()
successful_execution, message = ALPHA._command_status_parsing(response)
if not successful_execution:
UserInput.post_status(message)
UserInput.post_status(
"Could not calibrate short load. Look at error message above and consider a restart.")
UserInput.confirm_warning("Please connect the 100" + u"\u03A9" + " load calibration standard.")
self.visa_instrument.write("ZRUNCAL=SL_100")
UserInput.post_status("Performing 100" + u"\u03A9" + " calibration. Started at: " + time.strftime("%c"))
self.visa_instrument.wait_for_srq()
response = self.visa_instrument.read()
successful_execution, message = ALPHA._command_status_parsing(response)
if not successful_execution:
UserInput.post_status(message)
UserInput.post_status("Error during 100" + u"\u03A9" + " calibration. Consider starting over.")
else:
self.was_calibrated = 4
UserInput.post_status("Calibration succeeded")
def _connection_check(self):
""" A connection check might be (depending on connected gear and previously run calibrations) necessary
"""
response = self.visa_instrument.query("ZCON_TO_CHECK?")
self.connections_checked = False
successful_execution, message = ALPHA._command_status_parsing(response)
response = response[:-2]
if not successful_execution:
UserInput.post_status(message)
UserInput.post_status("Refer to the error message and the ALPHA display, we only wanted to check a status!")
else: # well, it succeeded telling us its needs of connection checks
if response == "ZCON_TO_CHECK=0": # '0' means that it doesn't require a check
if self.was_calibrated == 1: # if it was not calibrated, this test was never run, but also isn't
# required. Purly optional nature.
question = {"question_title": "Connection check",
"question_text": "Connection check wasn't performed but is optional. Do you want to check the connections?",
"default_answer": True,
"optiontype": "yes_no"}
answer = UserInput.ask_user_for_input(question)["answer"]
if answer:
UserInput.confirm_warning("Make sure all cables are connected properly!")
self.visa_instrument.write("ZRUNCAL=CONCHECK") # CONCHECK is considered a calibration task
# and therefore should be handled via srq
UserInput.post_status(
"Running connection test, pls hold tight. Started at: " + time.strftime("%c"))
self.visa_instrument.wait_for_srq()
response = self.visa_instrument.read()
successful_execution, message = ALPHA._command_status_parsing(response)
if not successful_execution:
UserInput.post_status(message)
UserInput.post_status("Connection test failed. You can give it another try if you want to.")
self._connection_check()
else:
self.connections_checked = True
UserInput.post_status("Connections tested successfully!")
else:
self.connections_checked = True # ALPHA does connection check during calibration
elif response == "ZCON_TO_CHECK=1":
UserInput.post_status("The ALPHA is requiring a connection check.")
UserInput.confirm_warning("Please connect all cables.")
self.visa_instrument.write("ZRUNCAL=CONCHECK") # CONCHECK is considered a calibration task
# and therefore should be handled via srq
UserInput.post_status("Running connection test, pls hold tight. Started at: " + time.strftime("%c"))
self.visa_instrument.wait_for_srq()
response = self.visa_instrument.read()
successful_execution, message = ALPHA._command_status_parsing(response)
if not successful_execution:
UserInput.post_status(message)
UserInput.post_status("Connection test failed. You can give it another try if you want to.")
self._connection_check()
else:
self.connections_checked = True
else:
UserInput.post_status(message)
UserInput.post_status(
"Couldn't get the status of the concheck. Something is wrong. A least the ALPHA didn't "
"respond properly to the ZCON_TO_CHECK? command.")
self._connection_check() # TODO: Think concheck through and see whether it is implemented correctly
def _activate_short_load(self):
""" A method to ask whether user wants to use short_load or not
"""
question = {"question_title": "Short Load calibration",
"question_text": "Do you want to use short-load calibration?", "default_answer": False,
"optiontype": "yes_no"}
answer = UserInput.ask_user_for_input(question)["answer"]
if answer: # user wanted to use short load calibration
response = self.visa_instrument.query("ZSLCAL=1")
self.short_load_activated = True
successful_execution, message = ALPHA._command_status_parsing(response)
if not successful_execution:
UserInput.post_status(message)
UserInput.post_status("Couldn't activate short load calibration.")
elif not answer: # default: off
response = self.visa_instrument.query("ZSLCAL=0")
self.short_load_activated = False
successful_execution, message = ALPHA._command_status_parsing(response)
if not successful_execution:
UserInput.post_status(message)
UserInput.post_status("Couldn't set short load calibration to off.")
def _activate_reference_measurement(self):
""" A method to ask the user whether he wants to use a reference measurement and set it accordingly
"""
question = {"question_title": "Reference measurement.",
"question_text": "Enable reference measurement (recommended)?", "default_answer": True,
"optiontype": "yes_no"}
answer = UserInput.ask_user_for_input(question)["answer"]
if answer: # user wanted to
# use short load calibration
response = self.visa_instrument.query("ZREFMODE=-3")
self.reference_measurement_activated = True
successful_execution, message = ALPHA._command_status_parsing(response)
if not successful_execution:
UserInput.post_status(message)
UserInput.post_status("Couldn't set reference measureent to on (-3).")
elif not answer:
response = self.visa_instrument.query("ZREFMODE=0")
self.reference_measurement_activated = False
successful_execution, message = ALPHA._command_status_parsing(response)
if not successful_execution:
UserInput.post_status(message)
UserInput.post_status("Failed to deactivate reference measurement!")
def _set_ac_excitation_voltage(self, voltage: float):
""" AC excitation voltage can be set per measurement point.
:param voltage: AFAIK a value with one digit after the dot valuable
:return: Bool: whether it was successful or not
"""
response = self.visa_instrument.query("ACV=" + str(voltage)) # Set default excitation voltage
successful_execution, message = ALPHA._command_status_parsing(response)
successful = bool # to return whether this method was successfull or not
if successful_execution:
self.excitation_voltage = voltage
return successful_execution
def _set_minimum_measurement_time(self, seconds=0.5):
""" Sets the minimum measurement time.
:param seconds: the value for the minimum measurement time
:return: Bool: Whether it was successful in setting it or not.
"""
response = self.visa_instrument.query("MTM=" + str(seconds))
successful_execution, message = ALPHA._command_status_parsing(response)
if not successful_execution:
UserInput.post_status(message)
elif successful_execution:
self.minimum_measurement_time = seconds
return successful_execution
@staticmethod
def _command_status_parsing(response: str):
"""
:param response: pass the result of a read to see whether the command executed fine!
:return: successful: when the result is "OK" or something else, it returns True; message: A message
describing the error code according to the Manual
"""
response = response[:-2]
message = response # if it is not overriden later, the message is supposed to be the result
if response == "OK":
successful = True
elif response == "CA":
successful = False
message = "Cannot execute this command during active calibration."
elif response == "CR":
successful = False
message = "A measurement was started which requires a test interface calibration which does not exist. \n " \
"The ALPHA will: \n Recalibrate interface, *type* Sno=*Interface* *Serial Number* *Calibration" \
" type* \n whereas *Calibration type* specifies the required calibration. Perform " \
"calibration as described in 2005 ALPHA manual calibration chapter."
elif response == "CN":
successful = False
message = "The received command is unavailable while the CE output of a POT/GAL interface *is* connected."
elif response == "EC":
successful = False
message = "System connection test required. You should try to calibrate the device."
elif response == "ER":
successful = False
message = "General command error. Depends on the issued command."
elif response == "HR":
successful = False
message = "The reference calibration for the IMP_HV150 us invalid. You should try to calibrate again"
elif response == "II":
successful = False
message = "The command is not supported by the actual connected test interface."
elif response == "IM":
successful = False
message = "Whoever programmed this thingy didn't make sure that you only want to measure things " \
"that are supported in the mode you are in!"
elif response == "IP":
successful = False
message = "Somehow we messed up the command parameter, I'm sorry. Try running this with a debugger."
elif response == "MR":
successful = False
message = "You can't run this command while a measurement/calibration is being done!"
elif response == "NA":
successful = False
message = "DC bias is not activated. One should get the programmer to *use DCE=1* to activate it!"
elif response == "NC":
successful = False
message = "The received command is unavailable while the CE output of a POT/GAL " \
"interface is *not* connected."
elif response == "NI":
successful = False
message = "somehow a calibration was started without running init first. Fire the programmer!"
elif response == "NO":
successful = False
message = "A calibration was started without initialization. Refer to ZRUNCAL command for details and " \
"give your programmer a cup of coffee. He probably needs it."
elif response == "RE":
successful = False
message = "One of the parameters tried were out of range of the possible measurement parameters. " \
"It's the coder's fault again!"
elif response == "UC":
successful = False
message = "Probably a typo. The ALPHA at least couln't make sense of the command's name!"
else:
successful = True
return successful, message
@staticmethod
def _parse_results(message: str):
"""
:rtype: successful_execution, message, measured_R, measured_X, measured_freq
"""
measured_R, measured_X, measured_freq, result_status, reference_measurement_enabled = message.split()
# we don't use reference_measurement_enabled, as we set this ourselves and now about its state
measured_R = measured_R[+4:]
measured_R = float(measured_R)
measured_X = float(measured_X)
measured_freq = float(measured_freq)
result_status = int(result_status)
successful = bool
if result_status == 0:
successful = False
message = "Invalid (result buffer empty)."
elif result_status == 1:
successful = False
message = "Measurement still in progress!!"
elif result_status == 2:
successful = True
message = "Measurement was successful"
elif result_status == 3:
successful = True
message = "Voltage V1 for sample measurement out of range"
elif result_status == 4:
successful = True
message = "Current for sample measurement out of range."
elif result_status == 5:
successful = True
message = "Voltage V1 for reference measurement out of range."
return successful, message, measured_R, measured_X, measured_freq
class Temp_336(MeasurementDevice):
idn_name_336, idn_alias_336 = importer("Temp_336", "idn_name_336", "idn_alias_336")
setpoint = 300
pid = None
heateroutput = None
heaterrange = 1
control_sensor = ""
sample_sensor = ""
measurables = ["Sensor A", "Sensor B", "Sensor C", "Sensor D"]
controlables = ["Setpoint", "PID", "HeaterOutput", "HeaterRange"]
def select_device(self, should_be_selected_dev: [], resource_manager: visa.ResourceManager):
if should_be_selected_dev[1] in self.idn_name_336:
for idns_336 in self.idn_name_336:
if idns_336 in should_be_selected_dev[1]:
self.mes_device = Temp_336()
self.mes_device.measurables = Temp_336.measurables
self.mes_device.controlables = Temp_336.controlables
self.mes_device.visa_instrument = None
""":type :MessageBasedResource"""
self.mes_device.idn_name = idns_336
self.mes_device.idn_alias = self.idn_alias_336
self.mes_device.set_visa_dev(should_be_selected_dev[0], resource_manager)
super().select_device(should_be_selected_dev, resource_manager)
def detect_devices(self, instrument: visa.Resource, name_of_dev: str):
for name in self.idn_name_336:
if name in name_of_dev:
self.recognized_devs.append((instrument, name, Temp_336.idn_alias_336))
super().detect_devices(instrument, name_of_dev)
def initialize_instrument(self):
self.visa_instrument.write("ramp 1,0,0")
def set_controlable(self, controlable_dict: {}):
"""
:param controlable_dict: {Setpoint: 200, PID: {"startTemp": 0, "P": 50, "I": 20, "D": 0, "HR": 3}}
"""
setpoint_needs_update = False
pids_need_update = False
heater_output_needs_update = False
heater_range_needs_update = False
if "Setpoint" in controlable_dict:
self.setpoint = controlable_dict["Setpoint"]
setpoint_needs_update = True
if "PID" in controlable_dict:
self.pid = controlable_dict["PID"]
pids_need_update = True
if "HO" in controlable_dict:
self.heateroutput = controlable_dict["HO"]
heater_output_needs_update = True
if "HR" in controlable_dict:
self.heaterrange = controlable_dict["HR"]
heater_range_needs_update = True
if heater_output_needs_update:
# When the output changes, we need to update everything as we don't know pre-existing values
# Update PIDs for new output
self.visa_instrument.write("PID" + str(self.heateroutput) + "," + str(self.pid["P"]) + "," +
str(self.pid["I"]) + "," + str(self.pid["D"]))
# Update heater range for the output chosen
self.visa_instrument.write("RANGE " + str(self.heateroutput) + "," + str(self.heaterrange))
# Update setpoint for chosen output
self.visa_instrument.write("SETP " + str(self.heateroutput) + "," + str(self.setpoint))
else:
if heater_range_needs_update:
# Update heater range for the output chosen
self.visa_instrument.write("RANGE " + str(self.heateroutput) + "," + str(self.heaterrange))
if pids_need_update:
# Update PIDs for new output
self.visa_instrument.write("PID" + str(self.heateroutput) + "," + str(self.pid["P"]) + "," +
str(self.pid["I"]) + "," + str(self.pid["D"]))
if setpoint_needs_update:
# update setpoint for chosen output
self.visa_instrument.write("SETP " + str(self.heateroutput) + "," + str(self.setpoint))
return controlable_dict
def measure_measurable(self, measurable_to_measure):
value = None
if measurable_to_measure == "Sensor A":
value = self.visa_instrument.query_ascii_values("KRDG? a")
elif measurable_to_measure == "Sensor B":
value = self.visa_instrument.query_ascii_values("KRDG? b")
elif measurable_to_measure == "Sensor C":
value = self.visa_instrument.query_ascii_values("KRDG? c")
elif measurable_to_measure == "Sensor D":
value = self.visa_instrument.query_ascii_values("KRDG? d")
result = {"K": value[0], "time_temp": time.strftime("%d.%m.%Y %H:%M:%S")}
return result
class Quatro(MeasurementDevice):
"""The class for the hardware command implementation of the Quatro hardware device"""
idn_name_Quatro, idn_alias_Quatro = importer("Quatro", "idn_name_Quatro", "idn_alias_Quatro")
measurables = ["Sample temperature"]
controlables = ["Setpoint", "PowerOffNow"]
def measure_measurable(self, measurable_to_measure):
"""We only have one measurable - that being the sample temperature - therefore, we don't ever need to handle
which measurable is passed into this method specifically
:param measurable_to_measure: The measurable that is to be measured
:return:
"""
dev_string = self.visa_instrument.query("QPVCT?")
temp_in_celsius = self._parse_quatro_temperature(dev_string)
temp_in_kelvin = temp_in_celsius + 273.15
result = {"K": temp_in_kelvin, "time_temp": time.strftime("%d.%m.%Y %H:%M:%S")}
return result
def set_controlable(self, controlable_dict: {}):
# must return a controlable dict with refreshed values of what was set
"""
:param controlable_dict: The dictionary containing the controlable(s)
"""
result = {"Nothing done": True}
if "Setpoint" in controlable_dict:
# The Quatro uses Celsius as unit, we therefore need to convert back and forth
kelvin_setpoint = controlable_dict["Setpoint"]
celsius_setpoint = kelvin_setpoint - 273.15
self.visa_instrument.write("QSPT=" + str(celsius_setpoint))
result = {"Setpoint": kelvin_setpoint}
elif "PowerOffNow" in controlable_dict:
# We should power off both the Gas Heater and the Dewar Heater
self.visa_instrument.write("QSHD=0")
self.visa_instrument.write("QSHG=0")
result = {"Heater_off": True}
return result
def select_device(self, should_be_selected_dev: [], resource_manager: visa.ResourceManager):
if should_be_selected_dev[1] in self.idn_name_Quatro:
for Quatro_ID in self.idn_name_Quatro:
if Quatro_ID in should_be_selected_dev[1]:
self.mes_device = Quatro()
self.mes_device.visa_instrument = None
""":type :MessageBasedResource""" # in case of GPIB ones
self.mes_device.idn_name = Quatro_ID
self.mes_device.idn_alias = self.idn_alias_Quatro
self.mes_device.set_visa_dev(should_be_selected_dev[0], resource_manager)
self.mes_device.measurables = Quatro.measurables
self.mes_device.controlables = Quatro.controlables
super().select_device(should_be_selected_dev, resource_manager)
def detect_devices(self, instrument: visa.Resource, name_of_dev: str):
for name in self.idn_name_Quatro:
if name in name_of_dev:
self.recognized_devs.append((instrument, name, Quatro.idn_alias_Quatro))
super().detect_devices(instrument, name_of_dev)
def initialize_instrument(self):
UserInput.post_status("We had nothing to initialize at the Quat(t)ro! ¯\_(ツ)_/¯ ")
def _parse_quatro_temperature(self, dev_string: str):
"""This method takes the string that the Quatro returns (eg 'PVCT=24.40\x00\r') and then returns the float
of the temperature
:param dev_string: the resulting string of <<query("QPVCT?")>>
:return: float of the temperature in celsius
"""
# we need to cut off the end characters so that we get "PVCT=24.40"
dev_string = dev_string[:-2]
# now split at the "=" sign and choose the second item of the resulting list
temp_in_celsius_str = dev_string.split("=")[1]
# convert it to float so we can calculate with it
temp_in_celsius = float(temp_in_celsius_str)
return temp_in_celsius
class Agilent4980A(MeasurementDevice):
"""The class for the hardware command implementation of a Generic device """
idn_name_Agilent4980A, idn_alias_Agilent4980A = importer("Agilent4980A", "idn_name_Agilent4980A",
"idn_alias_Agilent4980A")
measurables = ["CpD", "CpQ", "CpG", "CpRp", "CsD", "CsQ", "CsRs", "LpQ", "LpD", "LpRp", "LsD", "LsQ", "LsRs",
"RX", "ZTd", "ZTr", "GB", "YTd", "YTr"]
controlables = ["expected_freq"]
def measure_measurable(self, measurable_to_measure: str):
"""
:param measurable_to_measure: The measurable that is to be measured
:return:
"""
self.visa_instrument.write(":FUNC:IMP " + measurable_to_measure)
# we have to first set all the dev triggers correctly:
self.visa_instrument.assert_trigger()
result = {}
did_get_results = False
while not did_get_results:
try:
raw_results = self.visa_instrument.query("FETC?")
result = self._parse_raw_results(raw_results, measurable_to_measure)
# If we run into that strange fetc bug, we just fecth again after a short waiting time
if "buggy_hardware" in result:
time.sleep(0.01)
raw_results = self.visa_instrument.query("FETC?")
result = self._parse_raw_results(raw_results, measurable_to_measure)
did_get_results = True
except visa.VisaIOError:
# Sleep a little after the usual time out to wait for whether it will have measurement data then
time.sleep(0.1)
return result
def _parse_raw_results(self, raw_result: str, measurable_to_measure: str):
"""^Parses the raw result from the agilent into a dictionary
:param raw_result: the raw string. Either being doubled or normal one, eg either
"-2.184032447E-12,+1.007183946E-02,+0-2.184032447E-12,+1.007183946E-02,+0\n"
or simply "
"-2.184032447E-12,+1.007183946E-02,+0\n"
"""
# This happens if you call FETC? in an unlucky time and you get double length. I don't trust the values there
if len(raw_result) == 73: