-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhyperion.py
More file actions
1958 lines (1455 loc) · 71.5 KB
/
hyperion.py
File metadata and controls
1958 lines (1455 loc) · 71.5 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
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
# The MIT License (MIT)
#
# Copyright (c) 2018 Luna Innovations, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Module for interfacing to a Hyperion Instrument manufactured by Micron Optics, Inc.
Version 2.0.0.0
This version is a breaking change and is not backwards compatible with version 1.x. It is
written for Python version 3.5 or above.
The changes make the entire module much more pythonic than the previous version, and should result
in more streamlined and readable code.
There are now streaming classes that simplify the process of setting up streaming of
peaks, sensors, or spectra. (HCommTCPSensorStreamer, HCommTCPPeaksStreamer, HCommTCPSpectrumStreamer). These
classes enable concurrency for streaming using the python built in asyncio library. Examples are provided to
show to implement these.
The AsyncHyperion class implements all functions as coroutines, enabling easy insertion into applications that
require concurrency for all functions.
"""
import asyncio
import socket
from struct import pack, unpack
from collections import namedtuple
import numpy as np
from datetime import datetime
from functools import partial
import logging
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
COMMAND_PORT = 51971
STREAM_PEAKS_PORT = 51972
STREAM_SPECTRA_PORT = 51973
STREAM_SENSORS_PORT = 51974
SUCCESS = 0
_LIBRARY_VERSION = '2.0.0.1'
HyperionResponse = namedtuple('HyperionResponse', 'message content')
HyperionResponse.__doc__ += "A namedtuple object that encapsulates responses returned from a Hyperion Instrument"
HyperionResponse.message.__doc__ = "A human readable string returned for most commands."
HyperionResponse.content.__doc__ = "The binary data returned from the instrument, as a bytearray"
HPeakOffsets = namedtuple('HPeakOffsets', 'boundaries delays')
HPeakOffsets.__doc__ += "A namedtuple object that contains the boundaries and delays associated with distance" \
" compensation"
HPeakOffsets.boundaries.__doc__ = "A list of region boundary edges"
HPeakOffsets.delays.__doc__ = "A list of delays in ns that are applied to region below the respective boundary edge"
NetworkSettings = namedtuple('NetworkSettings', 'address netmask gateway')
SPEED_OF_LIGHT = 2.9979e8
class HCommTCPClient(object):
"""A class that implements the hyperion communication protocol over TCP, using asynchronous IO
"""
READ_HEADER_LENGTH = 8
WRITE_HEADER_LENGTH = 8
RECV_BUFFER_SIZE = 4096
def __init__(self, address : str, port, loop):
"""Sets up a new HCommTCPClient for connection to a Hyperion instrument.
:param str address: IPV4 Address of the hyperion instrument
:param int port: The port to connect. Different ports have different functionality. The default works for all commands.
:param loop: The execution loop that is used to schedule tasks.
"""
self.address = address
self.port = port
self.reader = None
self.writer = None
self.loop = loop
self.read_buffer = bytearray()
async def connect(self):
"""
Open an asyncio connection to the instrument.
:return:
"""
self.reader, self.writer = await asyncio.open_connection(self.address, self.port, loop = self.loop)
async def read_data(self, data_length):
"""Asynchronously read a fixed number of bytes from the TCP connection.
:param data_length:
:return: data_length number of bytes in a bytearray
:rtype: bytearray
"""
data = self.read_buffer
while len(data) < data_length:
data = data + await self.reader.read(self.RECV_BUFFER_SIZE)
data_out = data[:data_length]
self.read_buffer = data[data_length:]
return data_out
async def read_response(self):
"""Asynchronously reads a hyperion formatted response from the instrument
:return: The response as a HyperionResponse namedTuple.
:rtype: HyperionResponse
"""
read_header = await self.read_data(self.READ_HEADER_LENGTH)
(status, response_type, message_length, content_length) = unpack('BBHI', read_header)
if message_length > 0:
message = await self.read_data(message_length)
else:
message = b''
if status != SUCCESS:
self.read_buffer = bytearray()
loop = asyncio.get_event_loop()
loop.call_exception_handler({'message':message.decode()})
#raise (HyperionError(message))
content = await self.read_data(content_length)
return HyperionResponse(message=message.decode(encoding='ascii'), content=content)
def write_command(self, command, argument = '', request_options = 0):
"""Writes a formatted command packet to the hyperion instrument
:param str command: The command to be sent. Must start with "#".
:param str argument: The argument string. More than one arguments are included in a single space-delimited string.
:param request_options: byte flags that determine the type of data returned by the instrument.
"""
header_out = pack('BBHI', request_options, 0, len(command), len(argument))
self.writer.write(header_out)
self.writer.write(command.encode(encoding='ascii'))
self.writer.write(argument.encode(encoding='ascii'))
async def execute_command(self, command, argument='', request_options = 0):
"""Asynchronously writes a formatted command packet to the hyperion instrument and returns the response.
:param str command: The command to be sent. Must start with "#".
:param str argument: The argument string. More than one arguments are included in a single space-delimited string.
:param request_options: byte flags that determine the type of data returned by the instrument.
:return: The response as a HyperionResponse namedTuple
:rtype: HyperionResponse
"""
if self.writer is None:
await self.connect()
self.write_command(command, argument, request_options)
response = await self.read_response()
self.last_response = response
return response
@classmethod
def hyperion_command(cls, address, command, argument='', request_options=0):
"""
A self contained synchronous wrapper for sending single commands to the hyperion and receiving a response.
:param address: The instrument ipV4 address.
:type address: str
:param command: The command to be sent. Must start with "#".
:type command: str
:param argument: The argument string. If more than one, arguments are included in a single space-delimited string.
:type argument: str
:param request_options: Byte flags that determine the type of data returned by the instrument.
:type request_options: int
:return: The response as a HyperionResponse namedTuple
:rtype: HyperionResponse
"""
exec_loop = asyncio.get_event_loop()
h1 = HCommTCPClient(address, COMMAND_PORT, exec_loop)
error_report = {'status':False}
def exception_handler(loop, context):
error_report['status'] = True
error_report['message'] = context['message']
exec_loop.set_exception_handler(exception_handler)
exec_loop.run_until_complete(h1.execute_command(command, argument, request_options))
h1.writer.close()
if error_report['status']:
raise HyperionError(error_report['message'])
return h1.last_response
class HCommTCPStreamer(HCommTCPClient):
"""
Abstract base class for the different streaming data sources on the Hyperion (peaks, spectra, sensors)
"""
def __init__(self, address:str, port: int, loop, queue : asyncio.Queue, data_parser = None, fast_streaming = False):
"""
Set up a new streaming client.
:param address: The instrument ipV4 address
:type address: str
:param port: TCP port that is used for streaming.
:type port: int
:param loop: The event loop that will be used for scheduling tasks.
:type loop: asyncio.loop
:param queue: asyncio.Queue queue: A queue that can be used for transferring streamed data within the thead.
:type queue: asyncio.Queue
:param data_parser: Callable that takes in the binary content from the stream and returns a data dict that can
be consumed.
"""
super().__init__(address, port=port, loop=loop)
logger.debug('Streaming initiated on: {0}:{1}'.format(address,port))
self.data_queue = queue
self.stream_active = False
self._data_parser = data_parser or (lambda data_in: {'data': data_in})
self._last_content_length = None
self._fast_streaming = fast_streaming
self._stream_counter = 0
async def get_data(self, content_length = None):
"""
Asynchronously retrieve streaming data, and output the parsed data dictionary.
:param content_length: If not none, then this will avoid the added call to retrieve the read header, and will
retrieve both the header and the content in a single call.
:type content_length: int
:return: parse data
:rtype: dict
"""
if content_length:
content = await self.read_data(self.READ_HEADER_LENGTH + content_length)
content = content[self.READ_HEADER_LENGTH:]
else:
read_header = await self.read_data(self.READ_HEADER_LENGTH)
(status, response_type, message_length, content_length) = unpack('BBHI', read_header)
content = await self.read_data(content_length)
if self._fast_streaming:
logger.debug('First data retrieved from stream')
self._last_content_length = content_length
return self._data_parser(content)
async def stream_data(self):
"""
This is a producer loop that initiates the connection and Streams sensor data to the data queue to be consumed
elsewhere.
:return: None
"""
await self.connect()
logger.debug('Stream connected')
self.stream_active = True
while self.stream_active:
data_out = await self.get_data(self._last_content_length)
await self.data_queue.put(data_out)
self._stream_counter += 1
#put a final empty data set in the queue
logger.info("Stream no longer active.")
logger.info("Sending end of stream.")
logger.debug("Stream counter: {0}".format(self._stream_counter))
await self.data_queue.put({'data':None})
await self.data_queue.join()
self.writer.close()
def stop_streaming(self):
"""
Stops the endless loop within the stream_data method.
:return: None
"""
logger.info("Stopping Stream")
self.stream_active = False
class HCommTCPSensorStreamer(HCommTCPStreamer):
"""
A Class that can stream sensor data from a hyperion instrument.
"""
def __init__(self, address: str, loop, queue: asyncio.Queue):
"""Sets up a new streaming client for sensor data from a hyperion instrument
:param str address: The instrument ipV4 address
:param loop: The event loop that will be used for scheduling tasks.
:param asyncio.Queue queue: A queue that can be used for transferring streamed data within the main thread.
"""
super().__init__(address,
port=STREAM_SENSORS_PORT,
loop=loop,
queue = queue,
data_parser = HACQSensorData.data_parser,
fast_streaming=True)
class HCommTCPPeaksStreamer(HCommTCPStreamer):
"""
A Class that can stream peaks data from a hyperion instrument.
"""
def __init__(self, address: str, loop, queue: asyncio.Queue):
"""Sets up a new streaming client for sensor data from a hyperion instrument
:param str address: The instrument ipV4 address
:param loop: The event loop that will be used for scheduling tasks.
:param asyncio.Queue queue: A queue that can be used for transferring streamed data within the main thread.
"""
super().__init__(address,
port=STREAM_PEAKS_PORT,
loop=loop,
queue = queue,
data_parser = HACQPeaksData.data_parser,
fast_streaming=False)
class HCommTCPSpectrumStreamer(HCommTCPStreamer):
"""
A Class that can stream spectrum data from a hyperion instrument.
"""
def __init__(self, address: str, loop, queue: asyncio.Queue, powercal=None):
"""Sets up a new streaming client for sensor data from a hyperion instrument
:param str address: The instrument ipV4 address
:param loop: The event loop that will be used for scheduling tasks.
:param asyncio.Queue queue: A queue that can be used for transferring streamed data within the main thread.
"""
#This one line saves many
data_parser = partial(HACQSpectrumData.data_parser, powercal=powercal)
super().__init__(address,
port=STREAM_SPECTRA_PORT,
loop=loop,
queue = queue,
data_parser = data_parser,
fast_streaming=True)
class HACQSensorData(object):
"""Class that encapsulates sensor data streamed from hyperion
"""
SensorHeader = namedtuple('SensorHeader',
['header_length',
'status',
'buffer_percentage',
'reserved',
'serial_number',
'timestamp_int',
'timestamp_frac'])
def __init__(self, streaming_data):
header_length = 24
self.header = HACQSensorData.SensorHeader(*unpack('HBBIQII', streaming_data[:header_length]))
self.data = np.frombuffer(streaming_data[self.header.header_length:], dtype=np.float)
@classmethod
def data_parser(cls, streaming_data):
"""
Parser that takes in data from the stream and outputs formatted data in a dictionary
:param streaming_data: bytearray of content from Hyperion instrument
:type streaming_data: bytearray
:return: Data dictionary with 'timestamp' and 'data' keys.
:rtype: dict
"""
sensor_data = cls(streaming_data)
timestamp = sensor_data.header.timestamp_frac * 1e-9 + sensor_data.header.timestamp_int
return {'timestamp': timestamp, 'data':sensor_data}
class HACQPeaksData(object):
PeaksHeader = namedtuple('PeaksHeader',
['length',
'version',
'reserved',
'serial_number',
'timestamp_int',
'timestamp_frac'])
def __init__(self, raw_data):
header_length = 24
self.header = HACQPeaksData.PeaksHeader(*unpack('HHIQII', raw_data[:header_length]))
self.serial_number = self.header.serial_number
# header.length is the total length including the peak counts array
self._peak_counts = np.frombuffer(raw_data[header_length:self.header.length], dtype=np.int16)
self.channel_boundaries = np.cumsum(self._peak_counts)
self.data = np.frombuffer(raw_data[self.header.length:], dtype=np.float)
channel_start = 0
self.channel_slices = []
for channel_end in self.channel_boundaries:
self.channel_slices.append(self.data[channel_start:channel_end])
channel_start = channel_end
def __getitem__(self, item):
if item in range(1, len(self.channel_boundaries) + 1):
return self.channel_slices[item - 1]
raise HyperionError('Invalid channel number')
@classmethod
def data_parser(cls, raw_data):
peaks_data = cls(raw_data)
timestamp = peaks_data.header.timestamp_frac * 1e-9 + peaks_data.header.timestamp_int
return {'timestamp': timestamp, 'data':peaks_data}
class HACQSpectrumData(object):
SpectrumHeader = namedtuple('SpectrumHeader',
['length',
'version',
'reserved',
'serial_number',
'timestamp_int',
'timestamp_frac',
'start_wavelength',
'wavelength_increment',
'num_points',
'num_channels',
'active_channel_bits'])
def __init__(self, raw_data, powercal = None):
header_length = 48
self.header = HACQSpectrumData.SpectrumHeader(*unpack('HHIQIIddIHH', raw_data[:header_length]))
self.data = np.frombuffer(raw_data[header_length:], dtype=np.uint16).reshape((self.header.num_channels,
self.header.num_points))
self.channel_map = np.zeros(self.header.num_channels, dtype = int)
map_index = 0
for channel_index in range(16):
if (self.header.active_channel_bits >> channel_index) & 1:
self.channel_map[map_index] = channel_index
map_index += 1
if powercal:
self.data = self._raw_spectrum_to_db(powercal)
self._spectra = dict()
list(map(lambda x,y: self._spectra.update({x + 1:y}), self.channel_map, self.data))
self.spectra_header = {
'start_wavelength' : self.header.start_wavelength,
'wavelength_increment': self.header.wavelength_increment,
'num_points': self.header.num_points
}
def __getitem__(self, item):
try:
return self._spectra[item]
except KeyError:
raise HyperionError('No data for requested channel. Make sure requested channel is in the set of full'
' spectrum channel numbers. See Hyperion.active_full_spectrum_channel_numbers')
@property
def wavelengths(self):
return (self.spectra_header['start_wavelength'] +
np.arange(self.spectra_header['num_points'])*self.spectra_header['wavelength_increment'])
def _raw_spectrum_to_db(self, powercal):
offsets = powercal.offsets[self.channel_map]
scales = powercal.inverse_scales[self.channel_map]
data_db = (self.data.T * scales + offsets).T
return data_db
@classmethod
def data_parser(cls, raw_data, powercal=None):
spectra_data = cls(raw_data, powercal)
timestamp = spectra_data.header.timestamp_frac * 1e-9 + spectra_data.header.timestamp_int
return {'timestamp': timestamp, 'data':spectra_data}
class HPeakDetectionSettings(object):
"""Class that encapsulates the settings that describe peak detection for a
hyperion channel.
"""
def __init__(self, setting_id=0, name='', description='',
boxcar_length=0, diff_filter_length=0,
lockout=0, ntv_period=0, threshold=0, mode='Peak'):
"""
:param setting_id: The numerical index of the setting.
:type setting_id: int
:param name: The name of the setting.
:type name: str
:param description: A longer description of the use for this setting
:type description: str
:param boxcar_length: The length of the boxcar filter, in units of pm
:type boxcar_length: int
:param diff_filter_length: The length of the difference filter, in units of pm
:type diff_filter_length: int
:param lockout: The spectral length, in pm, of the lockout period
:type lockout: int
:param ntv_period: The length, in pm, of the noise threshold voltage period.
:type ntv_period: int
:param threshold: The normalized threshold for detecting peaks/valleys
:type threshold: int
:param mode: This is either 'Peak' or 'Valley'
:type mode: str
"""
self.setting_id = setting_id
self.name = name
self.description = description
self.boxcar_length = boxcar_length
self.diff_filter_length = diff_filter_length
self.lockout = lockout
self.ntv_period = ntv_period
self.threshold = threshold
self.mode = mode
@classmethod
def from_binary_data(cls, detection_settings_data):
"""
:param detection_settings_data: Byte array of detection settings in binary format as returned from instrument
:type detection_settings_data: bytearray
:return: If there is only one detection setting in the binary data, then it is returned as a single object.
Otherwise, returns all of the detection settings in detection_settings_data, parsed as HPeakDetectionSettings
objects and returned as a dict with the keys being the setting_id
:rtype: HPeakDetectionSettings or dict of HPeakDetectionSettings
"""
detection_settings = {}
while len(detection_settings_data):
(setting_id, name_length) = unpack('BB', detection_settings_data[:2])
detection_settings_data = detection_settings_data[2:]
name = detection_settings_data[: name_length].decode()
detection_settings_data = detection_settings_data[name_length:]
description_length = detection_settings_data[0]
detection_settings_data = detection_settings_data[1:]
description = detection_settings_data[: description_length].decode()
(boxcar_length, diff_filter_length, lockout,
ntv_period, threshold, mode) = \
unpack('HHHHiB', detection_settings_data[description_length:(description_length + 13)])
# In case more than one preset is contained in detectionSettingsData
detection_settings_data = detection_settings_data[(description_length + 13):]
if (mode == 0):
mode = 'Valley'
else:
mode = 'Peak'
detection_settings[setting_id] = (cls(setting_id, name, description, boxcar_length, diff_filter_length,
lockout, ntv_period, threshold, mode))
if len(detection_settings) == 1:
return detection_settings[setting_id]
else:
return detection_settings
def pack(self):
if self.mode == 'Peak':
mode_number = 1
else:
mode_number = 0
pack_string = "{0} '{1}' '{2}' {3} {4} {5} {6} {7} {8}".format(
self.setting_id, self.name, self.description, self.boxcar_length,
self.diff_filter_length, self.lockout, self.ntv_period,
self.threshold, mode_number)
return pack_string
class HyperionError(Exception):
"""Exception class for encapsulating error information from Hyperion.
"""
# changed to reflect the error codes
def __init__(self, message):
self.string = message
def __str__(self):
return repr(self.string)
class Hyperion(object):
PowerCal = namedtuple('PowerCal', 'offsets scales inverse_scales')
def __init__(self, address: str):
self._address = address
self._power_cal = None
def _execute_command(self, command: str, argument: str = ''):
return HCommTCPClient.hyperion_command(self._address, command, argument)
@property
def power_cal(self):
"""
Gets the offset and scale to be used to convert the fixed point spectrum data into dBm units.
:return: The offset and scale for each channel.
:rtype: Hyperion.PowerCal
"""
if self._power_cal is None:
cal_info = np.frombuffer(self._execute_command('#GetPowerCalibrationInfo').content, dtype=np.int32)
offsets = cal_info[::2]
scales = cal_info[1::2]
inverse_scales = 1.0/scales
self._power_cal = Hyperion.PowerCal(offsets, scales, inverse_scales)
return self._power_cal
@property
def serial_number(self):
"""
The instrument serial number.
:type: str
"""
return self._execute_command('#GetSerialNumber').content.decode()
@property
def library_version(self):
"""
The version of this API library.
:type: str
"""
return _LIBRARY_VERSION
@property
def firmware_version(self):
"""
The version of firmware on the instrument.
:type: str
"""
return self._execute_command('#GetFirmwareVersion').content.decode()
@property
def fpga_version(self):
"""
The version of FPGA code on the instrument.
:type: str
"""
return self._execute_command('#GetFPGAVersion').content.decode()
@property
def instrument_name(self):
"""
The user programmable name of the instrument (settable).
:type: str
"""
return self._execute_command('#GetInstrumentName').content.decode()
@instrument_name.setter
def instrument_name(self, name: str):
self._execute_command('#SetInstrumentName', name)
@property
def is_ready(self):
"""
True if the instrument is ready for operation, false otherwise.
:type: bool
"""
return unpack('B', self._execute_command('#isready').content)[0] > 0
@property
def channel_count(self):
"""
The number of channels on the instrument
:type: int
"""
return unpack('I', self._execute_command('#GetDutChannelCount').content)[0]
@property
def max_peak_count_per_channel(self):
"""
The maximum number of peaks that can be returned on any channel.
:type: int
"""
return unpack('I', self._execute_command('#GetMaximumPeakCountPerDutChannel').content)[0]
@property
def available_detection_settings(self):
"""
A dictionary of all detection settings presets that are present on the instrument, with keys equal to the
setting_id.
:type: list of HPeakDetectionSettings
"""
detection_settings_data = self._execute_command('#GetAvailableDetectionSettings').content
return HPeakDetectionSettings.from_binary_data(detection_settings_data)
@property
def channel_detection_setting_ids(self):
"""
A list of the detection setting ids that are currently active on each channel.
:type: List of int
"""
id_list = []
ids = self._execute_command('#GetAllChannelDetectionSettingIds').content
for id in ids:
id_list.append(int(id))
return id_list
@property
def active_full_spectrum_channel_numbers(self):
"""
An array of the channels for which full spectrum data is acquired. (settable)
:type: numpy.ndarray of int
"""
return np.frombuffer(self._execute_command('#getActiveFullSpectrumDutChannelNumbers').content, dtype=np.int32)
@active_full_spectrum_channel_numbers.setter
def active_full_spectrum_channel_numbers(self, channel_numbers):
channel_string = ''
for channel in channel_numbers:
channel_string += '{0} '.format(channel)
self._execute_command('#setActiveFullSpectrumDutChannelNumbers', channel_string)
@property
def available_laser_scan_speeds(self):
"""
An array of the available laser scan speeds that are settable on the instrument
:type: numpy.ndarray of int
"""
return np.frombuffer(self._execute_command('#GetAvailableLaserScanSpeeds').content, dtype=np.int32)
@property
def laser_scan_speed(self):
"""
The current laser scan speed of the instrument. (settable)
:type: int
"""
return unpack('I', self._execute_command('#GetLaserScanSpeed').content)[0]
@laser_scan_speed.setter
def laser_scan_speed(self, scan_speed: int):
self._execute_command('#SetLaserScanSpeed', '{0}'.format(scan_speed))
@property
def active_network_settings(self):
"""
The network address, netmask, and gateway that are currently active on the instrument.
:type: NetworkSettings namedtuple
"""
net_addresses = self._execute_command('#GetActiveNetworkSettings').content
address = socket.inet_ntoa(net_addresses[:4])
mask = socket.inet_ntoa(net_addresses[4:8])
gateway = socket.inet_ntoa(net_addresses[8:12])
return NetworkSettings(address, mask, gateway)
@property
def static_network_settings(self):
"""
The network address, netmask, and gateway that are active when the instrument is in static mode. (settable)
:type: NetworkSettings namedtuple
"""
net_addresses = self._execute_command('#GetStaticNetworkSettings').content
address = socket.inet_ntoa(net_addresses[:4])
mask = socket.inet_ntoa(net_addresses[4:8])
gateway = socket.inet_ntoa(net_addresses[8:12])
return NetworkSettings(address, mask, gateway)
@static_network_settings.setter
def static_network_settings(self, network_settings: NetworkSettings):
current_settings = self.static_network_settings
ip_mode = self.network_ip_mode
argument = '{0} {1} {2}'.format(network_settings.address,
network_settings.netmask,
network_settings.gateway)
self._execute_command('#SetStaticNetworkSettings', argument)
if ip_mode == 'STATIC' and current_settings.address != network_settings.address:
self._address = network_settings.address
@property
def network_ip_mode(self):
"""
The network ip configuration mode, can be dhcp or dynamic for DHCP mode, or static for static mode. (settable)
:type: str
"""
return self._execute_command('#GetNetworkIpMode').content.decode()
@network_ip_mode.setter
def network_ip_mode(self, mode):
update_ip = False
if mode in ['Static', 'static', 'STATIC']:
if self.network_ip_mode in ['dynamic', 'Dynamic', 'DHCP', 'dhcp']:
update_ip = True
new_ip = self.static_network_settings.address
command = '#EnableStaticIpMode'
elif mode in ['dynamic', 'Dynamic', 'DHCP', 'dhcp']:
command = '#EnableDynamicIpMode'
else:
raise HyperionError('Hyperion Error: Unknown Network IP Mode requested')
self._execute_command(command)
if update_ip:
self._address = new_ip
@property
def instrument_utc_date_time(self):
"""
The UTC time on the instrument. If set, this will be overwritten by NTP or PTP if enabled.
:type: datetime.datetime
"""
date_data = self._execute_command('#GetInstrumentUtcDateTime').content
return datetime(*unpack('HHHHHH', date_data))
@instrument_utc_date_time.setter
def instrument_utc_date_time(self, date_time: datetime):
self._execute_command('#SetInstrumentUtcDateTime', date_time.strftime('%Y %m %d %H %M %S'))
@property
def ntp_enabled(self):
"""
Boolean value indicating the enabled state of the Network Time Protocol for automatic time synchronization.
(settable)
:type: bool
"""
return unpack('I', self._execute_command('#GetNtpEnabled').content)[0] > 0
@ntp_enabled.setter
def ntp_enabled(self, enabled: bool):
if enabled:
argument = '1'
else:
argument = '0'
self._execute_command('#SetNtpEnabled', argument)
@property
def ntp_server(self):
"""
String containing the IP address of the NTP server. (settable)
:type: str
"""
return self._execute_command('#GetNtpServer').content.decode()
@ntp_server.setter
def ntp_server(self, server_address):
self._execute_command('#SetNtpServer', server_address)
@property
def ptp_enabled(self):
"""
Boolean value indicating the enabled state of the precision time protocol. Note that this cannot be enabled
at the same time as NTP. (settable)
:type: bool
"""
return unpack('I', self._execute_command('#GetPtpEnabled').content)[0] > 0
@ptp_enabled.setter
def ptp_enabled(self, enabled: bool):
if enabled:
argument = '1'
else:
argument = '0'
self._execute_command('#SetPtpEnabled', argument)